diff --git a/packages/uni-core/src/service/plugin/on.ts b/packages/uni-core/src/service/plugin/on.ts index 16e4f16e192ab72a77aa8ec8bf693e316fe8d049..2c205f7e85c01552e255e5f7279e2713a77cb406 100644 --- a/packages/uni-core/src/service/plugin/on.ts +++ b/packages/uni-core/src/service/plugin/on.ts @@ -1,9 +1,11 @@ import { ComponentPublicInstance } from '@vue/runtime-core' import { getCurrentPage, invokeHook } from './page' +import { onWebInvokeAppService } from '@dcloudio/uni-platform' export function initOn() { UniServiceJSBridge.on('onAppEnterForeground', onAppEnterForeground) UniServiceJSBridge.on('onAppEnterBackground', onAppEnterBackground) + UniServiceJSBridge.on('onWebInvokeAppService', onWebInvokeAppService) } function onAppEnterForeground() { diff --git a/packages/uni-h5/dist/uni-h5.cjs.js b/packages/uni-h5/dist/uni-h5.cjs.js index 06c4b59c5d52a1990957b5503198175066e05729..257779f698ed3852a04b688c3250ccae49689950 100644 --- a/packages/uni-h5/dist/uni-h5.cjs.js +++ b/packages/uni-h5/dist/uni-h5.cjs.js @@ -350,5922 +350,5953 @@ function invokeHook(vm, name, args) { const hooks = vm.$[name]; return hooks && uniShared.invokeArrayFns(hooks, args); } -function errorHandler(err, instance, info) { - if (!instance) { - throw err; - } - const app = getApp(); - if (!app || !app.$vm) { - throw err; - } - { - invokeHook(app.$vm, "onError", err); - } -} -function initApp$1(app) { - const appConfig = app._context.config; - if (shared.isFunction(app._component.onError)) { - appConfig.errorHandler = errorHandler; - } - const globalProperties = appConfig.globalProperties; - { - globalProperties.$set = set; - globalProperties.$applyOptions = applyOptions; - } -} -const pageMetaKey = PolySymbol(process.env.NODE_ENV !== "production" ? "UniPageMeta" : "upm"); -function usePageMeta() { - return vue.inject(pageMetaKey); -} -function providePageMeta(id) { - const pageMeta = initPageMeta(id); - vue.provide(pageMetaKey, pageMeta); - return pageMeta; -} -function usePageRoute() { - if (__UNI_FEATURE_PAGES__) { - return vueRouter.useRoute(); - } - const url = location.href; - const searchPos = url.indexOf("?"); - const hashPos = url.indexOf("#", searchPos > -1 ? searchPos : 0); - let query = {}; - if (searchPos > -1) { - query = uniShared.parseQuery(url.slice(searchPos + 1, hashPos > -1 ? hashPos : url.length)); - } - const {meta} = __uniRoutes[0]; - return { - meta, - query, - path: "/" + meta.route - }; +const SCHEME_RE = /^([a-z-]+:)?\/\//i; +const DATA_RE = /^data:.*,.*/; +const baseUrl = __IMPORT_META_ENV_BASE_URL__; +function addBase(filePath) { + return baseUrl + filePath; } -function initPageMeta(id) { - if (__UNI_FEATURE_PAGES__) { - return vue.reactive(normalizePageMeta(JSON.parse(JSON.stringify(mergePageMeta(id, vueRouter.useRoute().meta))))); +function getRealPath(filePath) { + if (__uniConfig.router.base === "./") { + filePath = filePath.replace(/^\.\/static\//, "/static/"); } - return vue.reactive(normalizePageMeta(JSON.parse(JSON.stringify(mergePageMeta(id, __uniRoutes[0].meta))))); -} -const PAGE_META_KEYS = [ - "navigationBar", - "refreshOptions" -]; -function mergePageMeta(id, pageMeta) { - const res = shared.extend({id}, __uniConfig.globalStyle, pageMeta); - PAGE_META_KEYS.forEach((name) => { - res[name] = shared.extend({}, __uniConfig.globalStyle[name], pageMeta[name]); - }); - return res; -} -function normalizePageMeta(pageMeta) { - if (__UNI_FEATURE_PULL_DOWN_REFRESH__) { - const {enablePullDownRefresh, navigationBar} = pageMeta; - if (enablePullDownRefresh) { - const refreshOptions = shared.extend({ - support: true, - color: "#2BD009", - style: "circle", - height: 70, - range: 150, - offset: 0 - }, pageMeta.refreshOptions); - let offset = rpx2px(refreshOptions.offset); - const {type} = navigationBar; - if (type !== "transparent" && type !== "none") { - offset += uniShared.NAVBAR_HEIGHT + 0; - } - refreshOptions.offset = offset; - refreshOptions.height = rpx2px(refreshOptions.height); - refreshOptions.range = rpx2px(refreshOptions.range); - pageMeta.refreshOptions = refreshOptions; + if (filePath.indexOf("/") === 0) { + if (filePath.indexOf("//") === 0) { + filePath = "https:" + filePath; + } else { + return addBase(filePath.substr(1)); } } - if (__UNI_FEATURE_NAVIGATIONBAR__) { - const {navigationBar} = pageMeta; - const {titleSize, titleColor, backgroundColor} = navigationBar; - navigationBar.type = navigationBar.type || "default"; - navigationBar.backButton = pageMeta.isQuit ? false : true; - navigationBar.titleSize = titleSize || "16px"; - navigationBar.titleColor = titleColor || "#fff"; - navigationBar.backgroundColor = backgroundColor || "#F7F7F7"; - } - return pageMeta; -} -function getStateId() { - { - return 1; - } -} -PolySymbol(process.env.NODE_ENV !== "production" ? "layout" : "l"); -let tabBar; -function useTabBar() { - if (!tabBar) { - tabBar = __uniConfig.tabBar && vue.reactive(__uniConfig.tabBar); + if (SCHEME_RE.test(filePath) || DATA_RE.test(filePath) || filePath.indexOf("blob:") === 0) { + return filePath; } - return tabBar; -} -const HTTP_METHODS = [ - "GET", - "OPTIONS", - "HEAD", - "POST", - "PUT", - "DELETE", - "TRACE", - "CONNECT" -]; -function elemInArray(str, arr) { - if (!str || arr.indexOf(str) === -1) { - return arr[0]; + const pages = getCurrentPages(); + if (pages.length) { + return addBase(getRealRoute(pages[pages.length - 1].$page.route, filePath).substr(1)); } - return str; -} -function validateProtocolFail(name, msg) { - console.warn(`${name}: ${msg}`); + return filePath; } -function validateProtocol(name, data, protocol, onFail) { - if (!onFail) { - onFail = validateProtocolFail; - } - for (const key in protocol) { - const errMsg = validateProp(key, data[key], protocol[key], !shared.hasOwn(data, key)); - if (shared.isString(errMsg)) { - onFail(name, errMsg); +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); } - } -} -function validateProtocols(name, args, protocol, onFail) { - if (!protocol) { - return; - } - if (!shared.isArray(protocol)) { - return validateProtocol(name, args[0] || Object.create(null), protocol, onFail); - } - const len = protocol.length; - const argsLen = args.length; - for (let i = 0; i < len; i++) { - const opts = protocol[i]; - const data = Object.create(null); - if (argsLen > i) { - data[opts.name] = args[i]; + }, + methods: { + _toggleListeners(type, id, watch) { + if (watch && !id) { + return; + } + if (!shared.isFunction(this._handleSubscribe)) { + return; + } + UniViewJSBridge[type](this.$page.id + "-" + this.$options.name.replace(/VUni([A-Z])/, "$1").toLowerCase() + "-" + id, this._handleSubscribe); + }, + _getContextInfo() { + const id = `context-${this._uid}`; + if (!this._contextId) { + this._toggleListeners("subscribe", id); + this._contextId = id; + } + return { + name: this.$options.name.replace(/VUni([A-Z])/, "$1").toLowerCase(), + id, + page: this.$page.id + }; } - validateProtocol(name, data, {[opts.name]: opts}, onFail); - } -} -function validateProp(name, value, prop, isAbsent) { - if (!shared.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 = shared.isArray(type) ? type : [type]; - const expectedTypes = []; - for (let i = 0; i < types.length && !isValid; i++) { - const {valid, expectedType} = assertType(value, types[i]); - expectedTypes.push(expectedType || ""); - isValid = valid; - } - if (!isValid) { - return getInvalidTypeMessage(name, value, expectedTypes); +}; +function throttle(fn, wait) { + let last = 0; + let timeout; + let waitCallback; + const newFn = function(...arg) { + const now = Date.now(); + clearTimeout(timeout); + waitCallback = () => { + waitCallback = null; + last = now; + fn.apply(this, arg); + }; + if (now - last < wait) { + timeout = setTimeout(waitCallback, wait - (now - last)); + return; } - } - if (validator) { - return validator(value); - } -} -const isSimpleType = /* @__PURE__ */ shared.makeMap("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; - } - } else if (expectedType === "Object") { - valid = shared.isObject(value); - } else if (expectedType === "Array") { - valid = shared.isArray(value); - } else { - { - valid = value instanceof type; - } - } - return { - valid, - expectedType + waitCallback(); }; -} -function getInvalidTypeMessage(name, value, expectedTypes) { - let message = `Invalid args: type check failed for args "${name}". Expected ${expectedTypes.map(shared.capitalize).join(", ")}`; - const expectedType = expectedTypes[0]; - const receivedType = shared.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); - } + newFn.cancel = function() { + clearTimeout(timeout); + waitCallback = null; }; -} -let invokeCallbackId = 1; -const invokeCallbacks = {}; -function addInvokeCallback(id, name, callback, keepAlive = false) { - invokeCallbacks[id] = { - name, - keepAlive, - callback + newFn.flush = function() { + clearTimeout(timeout); + waitCallback && waitCallback(); }; - return id; + return newFn; } -function invokeCallback(id, res, extras) { - if (typeof id === "number") { - const opts = invokeCallbacks[id]; - if (opts) { - if (!opts.keepAlive) { - delete invokeCallbacks[id]; +const _sfc_main$2 = { + 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); } - return opts.callback(res, extras); } - } - return res; -} -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 (shared.isFunction(fn)) { - apiCallbacks[name] = tryCatch(fn); - delete args[name]; + }, + 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; } } - return apiCallbacks; +}; +const _hoisted_1$1 = {class: "uni-audio-default"}; +const _hoisted_2$1 = {class: "uni-audio-right"}; +const _hoisted_3$1 = {class: "uni-audio-time"}; +const _hoisted_4$1 = {class: "uni-audio-info"}; +const _hoisted_5 = {class: "uni-audio-name"}; +const _hoisted_6 = {class: "uni-audio-author"}; +function _sfc_render$2(_ctx, _cache, $props, $setup, $data, $options) { + return vue.openBlock(), vue.createBlock("uni-audio", vue.mergeProps({ + id: $props.id, + controls: !!$props.controls + }, _ctx.$attrs), [ + vue.createVNode("audio", { + ref: "audio", + loop: $props.loop, + style: {"display": "none"} + }, null, 8, ["loop"]), + vue.createVNode("div", _hoisted_1$1, [ + vue.createVNode("div", { + style: "background-image: url(" + _ctx.$getRealPath($props.poster) + ");", + class: "uni-audio-left" + }, [ + vue.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), + vue.createVNode("div", _hoisted_2$1, [ + vue.createVNode("div", _hoisted_3$1, vue.toDisplayString($data.currentTime), 1), + vue.createVNode("div", _hoisted_4$1, [ + vue.createVNode("div", _hoisted_5, vue.toDisplayString($props.name), 1), + vue.createVNode("div", _hoisted_6, vue.toDisplayString($props.author), 1) + ]) + ]) + ]) + ], 16, ["id", "controls"]); } -function normalizeErrMsg(errMsg, name) { - if (!errMsg || errMsg.indexOf(":fail") === -1) { - return name + ":ok"; +_sfc_main$2.render = _sfc_render$2; +function converPx(value) { + if (/^-?\d+[ur]px$/i.test(value)) { + return value.replace(/(^-?\d+)[ur]px$/i, (text, num) => { + return `${uni.upx2px(parseFloat(num))}px`; + }); + } else if (/^-?[\d\.]+$/.test(value)) { + return `${value}px`; } - return name + errMsg.substring(errMsg.indexOf(":fail")); + return value || ""; } -function createAsyncApiCallback(name, args = {}, {beforeAll, beforeSuccess} = {}) { - if (!shared.isPlainObject(args)) { - args = {}; - } - const {success, fail, complete} = getApiCallbacks(args); - const hasSuccess = shared.isFunction(success); - const hasFail = shared.isFunction(fail); - const hasComplete = shared.isFunction(complete); - const callbackId = invokeCallbackId++; - addInvokeCallback(callbackId, name, (res) => { - res = res || {}; - res.errMsg = normalizeErrMsg(res.errMsg, name); - shared.isFunction(beforeAll) && beforeAll(res); - if (res.errMsg === name + ":ok") { - shared.isFunction(beforeSuccess) && beforeSuccess(res); - hasSuccess && success(res); - } else { - hasFail && fail(res); +function converType(type) { + return type.replace(/[A-Z]/g, (text) => { + return `-${text.toLowerCase()}`; + }).replace("webkit", "-webkit"); +} +function getStyle(action) { + const animateTypes1 = [ + "matrix", + "matrix3d", + "scale", + "scale3d", + "rotate3d", + "skew", + "translate", + "translate3d" + ]; + const animateTypes2 = [ + "scaleX", + "scaleY", + "scaleZ", + "rotate", + "rotateX", + "rotateY", + "rotateZ", + "skewX", + "skewY", + "translateX", + "translateY", + "translateZ" + ]; + const animateTypes3 = ["opacity", "background-color"]; + const animateTypes4 = ["width", "height", "left", "right", "top", "bottom"]; + const animates = action.animates; + const option = action.option; + const transition = option.transition; + const style = {}; + const transform = []; + animates.forEach((animate) => { + let type = animate.type; + let args = [...animate.args]; + if (animateTypes1.concat(animateTypes2).includes(type)) { + if (type.startsWith("rotate") || type.startsWith("skew")) { + args = args.map((value) => parseFloat(value) + "deg"); + } else if (type.startsWith("translate")) { + args = args.map(converPx); + } + if (animateTypes2.indexOf(type) >= 0) { + args.length = 1; + } + transform.push(`${type}(${args.join(",")})`); + } else if (animateTypes3.concat(animateTypes4).includes(args[0])) { + type = args[0]; + const value = args[1]; + style[type] = animateTypes4.includes(type) ? converPx(value) : value; } - hasComplete && complete(res); }); - return callbackId; + style.transform = style.webkitTransform = transform.join(" "); + style.transition = style.webkitTransition = Object.keys(style).map((type) => `${converType(type)} ${transition.duration}ms ${transition.timingFunction} ${transition.delay}ms`).join(","); + style.transformOrigin = style.webkitTransformOrigin = option.transformOrigin; + return style; } -const callbacks = [API_SUCCESS, API_FAIL, API_COMPLETE]; -function hasCallback(args) { - if (shared.isPlainObject(args) && callbacks.find((cb) => shared.isFunction(args[cb]))) { - return true; +function startAnimation(context) { + const animation2 = context.animation; + if (!animation2 || !animation2.actions || !animation2.actions.length) { + return; } - return false; -} -function handlePromise(promise) { - if (__UNI_FEATURE_PROMISE__) { - return promise.then((data) => { - return [null, data]; - }).catch((err) => [err]); + let index2 = 0; + const actions = animation2.actions; + const length = animation2.actions.length; + function animate() { + const action = actions[index2]; + const transition = action.option.transition; + const style = getStyle(action); + Object.keys(style).forEach((key) => { + context.$el.style[key] = style[key]; + }); + index2 += 1; + if (index2 < length) { + setTimeout(animate, transition.duration + transition.delay); + } } - return promise; + setTimeout(() => { + animate(); + }, 0); } -function promisify(fn) { - return (args = {}) => { - if (hasCallback(args)) { - return fn(args); +var animation = { + props: ["animation"], + watch: { + animation: { + deep: true, + handler() { + startAnimation(this); + } } - return handlePromise(new Promise((resolve, reject) => { - fn(shared.extend(args, {success: resolve, fail: reject})); - })); + }, + mounted() { + startAnimation(this); + } +}; +const defineBuiltInComponent = (options) => { + const {props: props2, mixins} = options; + if (!props2 || !props2.animation) { + (mixins || (options.mixins = [])).push(animation); + } + return defineSystemComponent(options); +}; +const defineSystemComponent = (options) => { + options.compatConfig = { + MODE: 3 }; -} -function formatApiArgs(args, options) { - const params = args[0]; - if (!options || !shared.isPlainObject(options.formatArgs) && shared.isPlainObject(params)) { - return; + return vue.defineComponent(options); +}; +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 formatArgs = options.formatArgs; - const keys = Object.keys(formatArgs); - for (let i = 0; i < keys.length; i++) { - const name = keys[i]; - const formatterOrDefaultValue = formatArgs[name]; - if (shared.isFunction(formatterOrDefaultValue)) { - const errMsg = formatterOrDefaultValue(args[0][name], params); - if (shared.isString(errMsg)) { - return errMsg; - } - } else { - if (!shared.hasOwn(params, name)) { - params[name] = formatterOrDefaultValue; - } - } +}; +function useHover(props2) { + const hovering = vue.ref(false); + let hoverTouch = false; + let hoverStartTimer; + let hoverStayTimer; + function hoverReset() { + requestAnimationFrame(() => { + clearTimeout(hoverStayTimer); + hoverStayTimer = setTimeout(() => { + hovering.value = false; + }, parseInt(props2.hoverStayTime)); + }); } -} -function invokeSuccess(id, name, res) { - return invokeCallback(id, shared.extend(res || {}, {errMsg: name + ":ok"})); -} -function invokeFail(id, name, err) { - return invokeCallback(id, {errMsg: name + ":fail" + (err ? " " + err : "")}); -} -function beforeInvokeApi(name, args, protocol, options) { - if (process.env.NODE_ENV !== "production") { - validateProtocols(name, args, protocol); + 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)); } - if (options && options.beforeInvoke) { - const errMsg2 = options.beforeInvoke(args); - if (shared.isString(errMsg2)) { - return errMsg2; + function onTouchend() { + hoverTouch = false; + if (hovering.value) { + hoverReset(); } } - const errMsg = formatApiArgs(args, options); - if (errMsg) { - return errMsg; + function onTouchcancel() { + hoverTouch = false; + hovering.value = false; + clearTimeout(hoverStartTimer); } -} -function wrapperTaskApi(name, fn, protocol, options) { - return (args) => { - const id = createAsyncApiCallback(name, args, options); - const errMsg = beforeInvokeApi(name, [args], protocol, options); - if (errMsg) { - return invokeFail(id, name, errMsg); + return { + hovering, + binding: { + onTouchstartPassive, + onTouchend, + onTouchcancel } - return fn(args, { - resolve: (res) => invokeSuccess(id, name, res), - reject: (err) => invokeFail(id, name, err) - }); }; } -function wrapperSyncApi(name, fn, protocol, options) { - return (...args) => { - const errMsg = beforeInvokeApi(name, args, protocol, options); - if (errMsg) { - throw new Error(errMsg); +function useBooleanAttr(props2, keys) { + if (shared.isString(keys)) { + keys = [keys]; + } + return keys.reduce((res, key) => { + if (props2[key]) { + res[key] = true; } - return fn.apply(null, args); - }; -} -function wrapperAsyncApi(name, fn, protocol, options) { - return wrapperTaskApi(name, fn, protocol, options); + return res; + }, Object.create(null)); } -function defineTaskApi(name, fn, protocol, options) { - return promisify(wrapperTaskApi(name, fn, process.env.NODE_ENV !== "production" ? protocol : void 0, options)); +function withWebEvent(fn) { + return fn.__wwe = true, fn; } -function defineSyncApi(name, fn, protocol, options) { - return wrapperSyncApi(name, fn, process.env.NODE_ENV !== "production" ? protocol : void 0, options); +function useCustomEvent(ref, emit2) { + return (name, evt, detail) => { + if (ref.value) { + emit2(name, normalizeCustomEvent(name, evt, ref.value, detail || {})); + } + }; } -function defineAsyncApi(name, fn, protocol, options) { - return promisify(wrapperAsyncApi(name, fn, process.env.NODE_ENV !== "production" ? protocol : void 0, options)); +function useNativeEvent(emit2) { + return (name, evt) => { + emit2(name, createNativeEvent(evt)); + }; } -const SCHEME_RE = /^([a-z-]+:)?\/\//i; -const DATA_RE = /^data:.*,.*/; -const baseUrl = __IMPORT_META_ENV_BASE_URL__; -function addBase(filePath) { - return baseUrl + filePath; +function normalizeCustomEvent(name, domEvt, el, detail) { + const target = uniShared.normalizeTarget(el); + return { + type: detail.type || name, + timeStamp: domEvt.timeStamp || 0, + target, + currentTarget: target, + detail + }; } -function getRealPath(filePath) { - if (__uniConfig.router.base === "./") { - filePath = filePath.replace(/^\.\/static\//, "/static/"); +const uniFormKey = PolySymbol(process.env.NODE_ENV !== "production" ? "uniForm" : "uf"); +var index$x = /* @__PURE__ */ defineBuiltInComponent({ + name: "Form", + setup(_props, { + slots, + emit: emit2 + }) { + provideForm(emit2); + return () => vue.createVNode("uni-form", null, [vue.createVNode("span", null, [slots.default && slots.default()])]); } - if (filePath.indexOf("/") === 0) { - if (filePath.indexOf("//") === 0) { - filePath = "https:" + filePath; - } else { - return addBase(filePath.substr(1)); +}); +function provideForm(emit2) { + const fields2 = []; + vue.provide(uniFormKey, { + addField(field) { + fields2.push(field); + }, + removeField(field) { + fields2.splice(fields2.indexOf(field), 1); + }, + submit() { + emit2("submit", { + detail: { + value: fields2.reduce((res, field) => { + if (field.submit) { + const [name, value] = field.submit(); + name && (res[name] = value); + } + return res; + }, Object.create(null)) + } + }); + }, + reset() { + fields2.forEach((field) => field.reset && field.reset()); + emit2("reset"); } - } - 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; + }); + return fields2; } -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); - } - }, - methods: { - _toggleListeners(type, id, watch) { - if (watch && !id) { - return; +const uniLabelKey = PolySymbol(process.env.NODE_ENV !== "production" ? "uniLabel" : "ul"); +const props$u = { + for: { + type: String, + default: "" + } +}; +var index$w = /* @__PURE__ */ defineBuiltInComponent({ + name: "Label", + props: props$u, + setup(props2, { + slots + }) { + const pageId = useCurrentPageId(); + const handlers = useProvideLabel(); + const pointer = vue.computed(() => props2.for || slots.default && slots.default.length); + const _onClick = withWebEvent(($event) => { + const EventTarget = $event.target; + let stopPropagation = /^uni-(checkbox|radio|switch)-/.test(EventTarget.className); + if (!stopPropagation) { + stopPropagation = /^uni-(checkbox|radio|switch|button)$|^(svg|path)$/i.test(EventTarget.tagName); } - if (!shared.isFunction(this._handleSubscribe)) { + if (stopPropagation) { return; } - UniViewJSBridge[type](this.$page.id + "-" + this.$options.name.replace(/VUni([A-Z])/, "$1").toLowerCase() + "-" + id, this._handleSubscribe); - }, - _getContextInfo() { - const id = `context-${this._uid}`; - if (!this._contextId) { - this._toggleListeners("subscribe", id); - this._contextId = id; + if (props2.for) { + UniViewJSBridge.emit("uni-label-click-" + pageId + "-" + props2.for, $event, true); + } else { + handlers[0]($event, true); } - return { - name: this.$options.name.replace(/VUni([A-Z])/, "$1").toLowerCase(), - id, - page: this.$page.id - }; - } + }); + return () => vue.createVNode("uni-label", { + "class": { + "uni-label-pointer": pointer + }, + "onClick": _onClick + }, [slots.default && slots.default()], 10, ["onClick"]); } -}; -function throttle(fn, wait) { - let last = 0; - let timeout; - let waitCallback; - const newFn = function(...arg) { - const now = Date.now(); - clearTimeout(timeout); - waitCallback = () => { - waitCallback = null; - last = now; - fn.apply(this, arg); - }; - if (now - last < wait) { - timeout = setTimeout(waitCallback, wait - (now - last)); - return; +}); +function useProvideLabel() { + const handlers = []; + vue.provide(uniLabelKey, { + addHandler(handler) { + handlers.push(handler); + }, + removeHandler(handler) { + handlers.splice(handlers.indexOf(handler), 1); } - waitCallback(); - }; - newFn.cancel = function() { - clearTimeout(timeout); - waitCallback = null; - }; - newFn.flush = function() { - clearTimeout(timeout); - waitCallback && waitCallback(); - }; - return newFn; + }); + return handlers; } -const _sfc_main$2 = { - name: "Audio", - mixins: [subscriber], +var index$v = /* @__PURE__ */ defineBuiltInComponent({ + name: "Button", props: { id: { type: String, default: "" }, - src: { + hoverClass: { type: String, - default: "" + default: "button-hover" }, - loop: { - type: [Boolean, String], + hoverStartTime: { + type: [Number, String], + default: 20 + }, + hoverStayTime: { + type: [Number, String], + default: 70 + }, + hoverStopPropagation: { + type: Boolean, default: false }, - controls: { + disabled: { type: [Boolean, String], default: false }, - poster: { + formType: { type: String, default: "" }, - name: { + openType: { 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); - } + loading: { + type: [Boolean, String], + default: false } }, - 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; + setup(props2, { + slots + }) { + const rootRef = vue.ref(null); + const uniForm = vue.inject(uniFormKey, false); + const { + hovering, + binding + } = useHover(props2); + useI18n(); + const onClick = withWebEvent((e2, isLabelClick) => { + if (props2.disabled) { + return e2.stopImmediatePropagation(); } - }, - trigger() { - if (this.playing) { - this.$refs.audio.pause(); - } else { - this.$refs.audio.play(); + if (isLabelClick) { + rootRef.value.click(); } - }, - 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; + const formType = props2.formType; + if (formType) { + if (!uniForm) { + return; + } + if (formType === "submit") { + uniForm.submit(); + } else if (formType === "reset") { + uniForm.reset(); + } + return; } - return str; + }); + const uniLabel = vue.inject(uniLabelKey, false); + if (uniLabel) { + uniLabel.addHandler(onClick); } + return () => { + const hoverClass = props2.hoverClass; + const booleanAttrs = useBooleanAttr(props2, "disabled"); + const loadingAttrs = useBooleanAttr(props2, "loading"); + const hasHoverClass = hoverClass && hoverClass !== "none"; + return vue.createVNode("uni-button", vue.mergeProps({ + "ref": rootRef, + "onClick": onClick, + "class": hasHoverClass && hovering.value ? hoverClass : "" + }, hasHoverClass && binding, booleanAttrs, loadingAttrs), [slots.default && slots.default()], 16, ["onClick"]); + }; } -}; -const _hoisted_1$1 = {class: "uni-audio-default"}; -const _hoisted_2$1 = {class: "uni-audio-right"}; -const _hoisted_3$1 = {class: "uni-audio-time"}; -const _hoisted_4$1 = {class: "uni-audio-info"}; -const _hoisted_5 = {class: "uni-audio-name"}; -const _hoisted_6 = {class: "uni-audio-author"}; -function _sfc_render$2(_ctx, _cache, $props, $setup, $data, $options) { - return vue.openBlock(), vue.createBlock("uni-audio", vue.mergeProps({ - id: $props.id, - controls: !!$props.controls - }, _ctx.$attrs), [ - vue.createVNode("audio", { - ref: "audio", - loop: $props.loop, - style: {"display": "none"} - }, null, 8, ["loop"]), - vue.createVNode("div", _hoisted_1$1, [ - vue.createVNode("div", { - style: "background-image: url(" + _ctx.$getRealPath($props.poster) + ");", - class: "uni-audio-left" - }, [ - vue.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), - vue.createVNode("div", _hoisted_2$1, [ - vue.createVNode("div", _hoisted_3$1, vue.toDisplayString($data.currentTime), 1), - vue.createVNode("div", _hoisted_4$1, [ - vue.createVNode("div", _hoisted_5, vue.toDisplayString($props.name), 1), - vue.createVNode("div", _hoisted_6, vue.toDisplayString($props.author), 1) - ]) - ]) - ]) - ], 16, ["id", "controls"]); +}); +var ResizeSensor = /* @__PURE__ */ defineBuiltInComponent({ + name: "ResizeSensor", + props: { + initial: { + type: Boolean, + default: false + } + }, + emits: ["resize"], + setup(props2, { + emit: emit2 + }) { + const rootRef = vue.ref(null); + const reset = useResizeSensorReset(rootRef); + const update = useResizeSensorUpdate(rootRef, emit2, reset); + return () => vue.createVNode("uni-resize-sensor", { + "ref": rootRef, + "onAnimationstartOnce": update + }, [vue.createVNode("div", { + "onScroll": update + }, [vue.createVNode("div", null, null)], 40, ["onScroll"]), vue.createVNode("div", { + "onScroll": update + }, [vue.createVNode("div", null, null)], 40, ["onScroll"])], 40, ["onAnimationstartOnce"]); + } +}); +function useResizeSensorUpdate(rootRef, emit2, reset) { + const size = vue.reactive({ + width: -1, + height: -1 + }); + vue.watch(() => shared.extend({}, size), (value) => emit2("resize", value)); + return () => { + const { + width, + height + } = rootRef.value.getBoundingClientRect(); + size.width = width; + size.height = height; + reset(); + }; } -_sfc_main$2.render = _sfc_render$2; -function converPx(value) { - if (/^-?\d+[ur]px$/i.test(value)) { - return value.replace(/(^-?\d+)[ur]px$/i, (text, num) => { - return `${uni.upx2px(parseFloat(num))}px`; - }); - } else if (/^-?[\d\.]+$/.test(value)) { - return `${value}px`; +function useResizeSensorReset(rootRef) { + return () => { + const { + firstElementChild, + lastElementChild + } = rootRef.value; + firstElementChild.scrollLeft = 1e5; + firstElementChild.scrollTop = 1e5; + lastElementChild.scrollLeft = 1e5; + lastElementChild.scrollTop = 1e5; + }; +} +const pixelRatio = 1; +function wrapper(canvas) { + canvas.width = canvas.offsetWidth * pixelRatio; + canvas.height = canvas.offsetHeight * pixelRatio; + canvas.getContext("2d").__hidpi__ = true; +} +let isHidpi = false; +function initHidpi() { + if (isHidpi) { + return; } - return value || ""; + isHidpi = true; + const proto = CanvasRenderingContext2D.prototype; + proto.drawImageByCanvas = function(_super) { + return function(canvas, srcx, srcy, srcw, srch, desx, desy, desw, desh, isScale) { + if (!this.__hidpi__) { + return _super.apply(this, arguments); + } + srcx *= pixelRatio; + srcy *= pixelRatio; + srcw *= pixelRatio; + srch *= pixelRatio; + desx *= pixelRatio; + desy *= pixelRatio; + desw = isScale ? desw * pixelRatio : desw; + desh = isScale ? desh * pixelRatio : desh; + _super.call(this, canvas, srcx, srcy, srcw, srch, desx, desy, desw, desh); + }; + }(proto.drawImage); } -function converType(type) { - return type.replace(/[A-Z]/g, (text) => { - return `-${text.toLowerCase()}`; - }).replace("webkit", "-webkit"); +const initHidpiOnce = /* @__PURE__ */ uniShared.once(initHidpi); +function $getRealPath(src) { + return src ? getRealPath(src) : src; } -function getStyle(action) { - const animateTypes1 = [ - "matrix", - "matrix3d", - "scale", - "scale3d", - "rotate3d", - "skew", - "translate", - "translate3d" - ]; - const animateTypes2 = [ - "scaleX", - "scaleY", - "scaleZ", - "rotate", - "rotateX", - "rotateY", - "rotateZ", - "skewX", - "skewY", - "translateX", - "translateY", - "translateZ" - ]; - const animateTypes3 = ["opacity", "background-color"]; - const animateTypes4 = ["width", "height", "left", "right", "top", "bottom"]; - const animates = action.animates; - const option = action.option; - const transition = option.transition; - const style = {}; - const transform = []; - animates.forEach((animate) => { - let type = animate.type; - let args = [...animate.args]; - if (animateTypes1.concat(animateTypes2).includes(type)) { - if (type.startsWith("rotate") || type.startsWith("skew")) { - args = args.map((value) => parseFloat(value) + "deg"); - } else if (type.startsWith("translate")) { - args = args.map(converPx); - } - if (animateTypes2.indexOf(type) >= 0) { - args.length = 1; - } - transform.push(`${type}(${args.join(",")})`); - } else if (animateTypes3.concat(animateTypes4).includes(args[0])) { - type = args[0]; - const value = args[1]; - style[type] = animateTypes4.includes(type) ? converPx(value) : value; - } +function resolveColor(color) { + color = color.slice(0); + color[3] = color[3] / 255; + return "rgba(" + color.join(",") + ")"; +} +function processTouches(target, touches) { + const eventTarget = target; + return Array.from(touches).map((touch) => { + let boundingClientRect = eventTarget.getBoundingClientRect(); + return { + identifier: touch.identifier, + x: touch.clientX - boundingClientRect.left, + y: touch.clientY - boundingClientRect.top + }; }); - style.transform = style.webkitTransform = transform.join(" "); - style.transition = style.webkitTransition = Object.keys(style).map((type) => `${converType(type)} ${transition.duration}ms ${transition.timingFunction} ${transition.delay}ms`).join(","); - style.transformOrigin = style.webkitTransformOrigin = option.transformOrigin; - return style; } -function startAnimation(context) { - const animation2 = context.animation; - if (!animation2 || !animation2.actions || !animation2.actions.length) { - return; - } - let index2 = 0; - const actions = animation2.actions; - const length = animation2.actions.length; - function animate() { - const action = actions[index2]; - const transition = action.option.transition; - const style = getStyle(action); - Object.keys(style).forEach((key) => { - context.$el.style[key] = style[key]; - }); - index2 += 1; - if (index2 < length) { - setTimeout(animate, transition.duration + transition.delay); - } +let tempCanvas; +function getTempCanvas(width = 0, height = 0) { + if (!tempCanvas) { + tempCanvas = document.createElement("canvas"); } - setTimeout(() => { - animate(); - }, 0); + tempCanvas.width = width; + tempCanvas.height = height; + return tempCanvas; } -var animation = { - props: ["animation"], - watch: { - animation: { - deep: true, - handler() { - startAnimation(this); - } - } +const props$t = { + canvasId: { + type: String, + default: "" }, - mounted() { - startAnimation(this); - } -}; -const defineBuiltInComponent = (options) => { - const {props: props2, mixins} = options; - if (!props2 || !props2.animation) { - (mixins || (options.mixins = [])).push(animation); + disableScroll: { + type: [Boolean, String], + default: false } - return defineSystemComponent(options); }; -const defineSystemComponent = (options) => { - options.compatConfig = { +var index$u = /* @__PURE__ */ defineBuiltInComponent({ + inheritAttrs: false, + name: "Canvas", + compatConfig: { MODE: 3 - }; - return vue.defineComponent(options); -}; -const hoverProps = { - hoverClass: { - type: String, - default: "none" - }, - hoverStopPropagation: { - type: Boolean, - default: false }, - hoverStartTime: { - type: [Number, String], - default: 50 + props: props$t, + computed: { + id() { + return this.canvasId; + } }, - hoverStayTime: { - type: [Number, String], - default: 400 + setup(props2, { + emit: emit2, + slots + }) { + initHidpiOnce(); + const canvas = vue.ref(null); + const sensor = vue.ref(null); + const actionsWaiting = vue.ref(false); + const trigger = useNativeEvent(emit2); + const { + $attrs, + $excludeAttrs, + $listeners + } = useAttrs({ + excludeListeners: true + }); + const { + _listeners + } = useListeners(props2, $listeners, trigger); + const { + _handleSubscribe, + _resize + } = useMethods(canvas, actionsWaiting); + useSubscribe(_handleSubscribe, useContextInfo(props2.canvasId), true); + return () => { + const { + canvasId, + disableScroll + } = props2; + return vue.createVNode("uni-canvas", vue.mergeProps({ + "canvas-id": canvasId, + "disable-scroll": disableScroll + }, $attrs.value, $excludeAttrs.value, _listeners.value), [vue.createVNode("canvas", { + "ref": canvas, + "class": "uni-canvas-canvas", + "width": "300", + "height": "150" + }, null, 512), vue.createVNode("div", { + "style": "position: absolute;top: 0;left: 0;width: 100%;height: 100%;overflow: hidden;" + }, [slots.default && slots.default()]), vue.createVNode(ResizeSensor, { + "ref": sensor, + "onResize": _resize + }, null, 8, ["onResize"])], 16, ["canvas-id", "disable-scroll"]); + }; } -}; -function useHover(props2) { - const hovering = vue.ref(false); - let hoverTouch = false; - let hoverStartTimer; - let hoverStayTimer; - function hoverReset() { - requestAnimationFrame(() => { - clearTimeout(hoverStayTimer); - hoverStayTimer = setTimeout(() => { - hovering.value = false; - }, parseInt(props2.hoverStayTime)); +}); +function useListeners(props2, Listeners, trigger) { + const _listeners = vue.computed(() => { + let events = ["onTouchstart", "onTouchmove", "onTouchend"]; + let _$listeners = Listeners.value; + let $listeners = shared.extend({}, (() => { + let obj = {}; + for (const key in _$listeners) { + if (Object.prototype.hasOwnProperty.call(_$listeners, key)) { + const event = _$listeners[key]; + obj[key] = event; + } + } + return obj; + })()); + events.forEach((event) => { + let existing = $listeners[event]; + let eventHandler = []; + if (existing) { + eventHandler.push(withWebEvent(($event) => { + trigger(event.replace("on", "").toLocaleLowerCase(), shared.extend({}, (() => { + let obj = {}; + for (const key in $event) { + obj[key] = $event[key]; + } + return obj; + })(), { + touches: processTouches($event.currentTarget, $event.touches), + changedTouches: processTouches($event.currentTarget, $event.changedTouches) + })); + })); + } + if (props2.disableScroll && event === "onTouchmove") { + eventHandler.push(onEventPrevent); + } + $listeners[event] = eventHandler; }); + return $listeners; + }); + return { + _listeners + }; +} +function useMethods(canvasRef, actionsWaiting) { + let _actionsDefer = []; + let _images = {}; + function _resize() { + var canvas = canvasRef.value; + if (canvas.width > 0 && canvas.height > 0) { + var context = canvas.getContext("2d"); + var imageData = context.getImageData(0, 0, canvas.width, canvas.height); + wrapper(canvas); + context.putImageData(imageData, 0, 0); + } else { + wrapper(canvas); + } } - function onTouchstartPassive(evt) { - if (evt._hoverPropagationStopped) { + function actionsChanged({ + actions, + reserve, + callbackId + }) { + if (!actions) { return; } - if (!props2.hoverClass || props2.hoverClass === "none" || props2.disabled) { + if (actionsWaiting.value) { + _actionsDefer.push([actions, reserve, callbackId]); return; } - if (evt.touches.length > 1) { - return; - } - if (props2.hoverStopPropagation) { - evt._hoverPropagationStopped = true; + var canvas = canvasRef.value; + 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); } - hoverTouch = true; - hoverStartTimer = setTimeout(() => { - hovering.value = true; - if (!hoverTouch) { - hoverReset(); + 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 = checkImageLoaded(data[1], actions.slice(index2 + 1), callbackId, function(image) { + if (image) { + c2d[method1] = c2d.createPattern(image, data[2]); + } + }); + if (!loaded) { + break; + } + continue; + } + c2d[method1] = color; + } else if (method1 === "globalAlpha") { + c2d[method1] = Number(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") { + const font = c2d.__font__ || c2d.font; + c2d.__font__ = c2d.font = 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 if (method1 === "font") { + c2d.__font__ = c2d.font = 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); + _images = _images || {}; + if (checkImageLoaded(url, actions.slice(index2 + 1), callbackId, function(image) { + if (image) { + c2d.drawImage.apply(c2d, [image].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); + } } - }, parseInt(props2.hoverStartTime)); - } - function onTouchend() { - hoverTouch = false; - if (hovering.value) { - hoverReset(); + } + if (!actionsWaiting.value && callbackId) { + UniViewJSBridge.publishHandler("onCanvasMethodCallback", { + callbackId, + data: { + errMsg: "drawCanvas:ok" + } + }, getCurrentPageId()); } } - function onTouchcancel() { - hoverTouch = false; - hovering.value = false; - clearTimeout(hoverStartTimer); + function preloadImage(actions) { + actions.forEach(function(action) { + var method = action.method; + var data = action.data; + var src = ""; + if (method === "drawImage") { + src = data[0]; + src = $getRealPath(src); + data[0] = src; + } else if (method === "setFillStyle" && data[0] === "pattern") { + src = data[1]; + src = $getRealPath(src); + data[1] = src; + } + if (src && !_images[src]) { + loadImage(); + } + function loadImage() { + const image = _images[src] = new Image(); + image.onload = function() { + image.ready = true; + }; + getSameOriginUrl(src).then((src2) => { + image.src = src2; + }).catch(() => { + image.src = src; + }); + } + }); } - return { - hovering, - binding: { - onTouchstartPassive, - onTouchend, - onTouchcancel + function checkImageLoaded(src, actions, callbackId, fn) { + var image = _images[src]; + if (image.ready) { + fn(image); + return true; + } else { + _actionsDefer.unshift([actions, true]); + actionsWaiting.value = true; + image.onload = function() { + image.ready = true; + fn(image); + actionsWaiting.value = false; + var actions2 = _actionsDefer.slice(0); + _actionsDefer = []; + for (var action = actions2.shift(); action; ) { + actionsChanged({ + actions: action[0], + reserve: action[1], + callbackId + }); + action = actions2.shift(); + } + }; + return false; } - }; -} -function useBooleanAttr(props2, keys) { - if (shared.isString(keys)) { - keys = [keys]; } - return keys.reduce((res, key) => { - if (props2[key]) { - res[key] = true; + function getImageData({ + x = 0, + y = 0, + width, + height, + destWidth, + destHeight, + hidpi = true, + dataType: dataType2, + quality = 1, + type = "png", + callbackId + }) { + const canvas = canvasRef.value; + let data; + const maxWidth = canvas.offsetWidth - x; + width = width ? Math.min(width, maxWidth) : maxWidth; + const maxHeight = canvas.offsetHeight - y; + height = height ? Math.min(height, maxHeight) : maxHeight; + 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; } - return res; - }, Object.create(null)); -} -function withWebEvent(fn) { - return fn.__wwe = true, fn; -} -function useCustomEvent(ref, emit2) { - return (name, evt, detail) => { - if (ref.value) { - emit2(name, normalizeCustomEvent(name, evt, ref.value, detail || {})); + const newCanvas = getTempCanvas(destWidth, destHeight); + const context = newCanvas.getContext("2d"); + if (type === "jpeg" || type === "jpg") { + type = "jpeg"; + context.fillStyle = "#fff"; + context.fillRect(0, 0, destWidth, destHeight); } + context.__hidpi__ = true; + context.drawImageByCanvas(canvas, x, y, width, height, 0, 0, destWidth, destHeight, false); + let result; + try { + let compressed; + if (dataType2 === "base64") { + data = newCanvas.toDataURL(`image/${type}`, quality); + } else { + const imgData = context.getImageData(0, 0, destWidth, destHeight); + if (false) + ; + else { + data = Array.prototype.slice.call(imgData.data); + } + } + result = { + errMsg: "canvasGetImageData:ok", + data, + compressed, + width: destWidth, + height: destHeight + }; + } catch (error) { + result = { + errMsg: `canvasGetImageData:fail ${error}` + }; + } + newCanvas.height = newCanvas.width = 0; + context.__hidpi__ = false; + if (!callbackId) { + return result; + } else { + UniViewJSBridge.publishHandler("onCanvasMethodCallback", { + callbackId, + data: result + }, getCurrentPageId()); + } + } + function putImageData({ + data, + x, + y, + width, + height, + compressed, + callbackId + }) { + try { + if (!height) { + height = Math.round(data.length / 4 / width); + } + const canvas = getTempCanvas(width, height); + const context = canvas.getContext("2d"); + if (false) + ; + context.putImageData(new ImageData(new Uint8ClampedArray(data), width, height), 0, 0); + canvasRef.value.getContext("2d").drawImage(canvas, x, y, width, height); + canvas.height = canvas.width = 0; + } catch (error) { + UniViewJSBridge.publishHandler("onCanvasMethodCallback", { + callbackId, + data: { + errMsg: "canvasPutImageData:fail" + } + }, getCurrentPageId()); + return; + } + UniViewJSBridge.publishHandler("onCanvasMethodCallback", { + callbackId, + data: { + errMsg: "canvasPutImageData:ok" + } + }, getCurrentPageId()); + } + function toTempFilePath({ + x = 0, + y = 0, + width, + height, + destWidth, + destHeight, + fileType, + quality, + dirname, + callbackId + }) { + const res = getImageData({ + x, + y, + width, + height, + destWidth, + destHeight, + hidpi: false, + dataType: "base64", + type: fileType, + quality + }); + if (!res.data || !res.data.length) { + UniViewJSBridge.publishHandler("onCanvasMethodCallback", { + callbackId, + data: { + errMsg: res.errMsg.replace("canvasPutImageData", "toTempFilePath") + } + }, getCurrentPageId()); + return; + } + saveImage(res.data, dirname, (error, tempFilePath) => { + let errMsg = `toTempFilePath:${error ? "fail" : "ok"}`; + if (error) { + errMsg += ` ${error.message}`; + } + UniViewJSBridge.publishHandler("onCanvasMethodCallback", { + callbackId, + data: { + errMsg, + tempFilePath + } + }, getCurrentPageId()); + }); + } + const methods = { + actionsChanged, + getImageData, + putImageData, + toTempFilePath }; + function _handleSubscribe(type, data = {}) { + let method = methods[type]; + if (type.indexOf("_") !== 0 && typeof method === "function") { + method(data); + } + } + return shared.extend(methods, { + _resize, + _handleSubscribe + }); } -function useNativeEvent(emit2) { - return (name, evt) => { - emit2(name, createNativeEvent(evt)); - }; -} -function normalizeCustomEvent(name, domEvt, el, detail) { - const target = uniShared.normalizeTarget(el); - return { - type: detail.type || name, - timeStamp: domEvt.timeStamp || 0, - target, - currentTarget: target, - detail - }; -} -const uniFormKey = PolySymbol(process.env.NODE_ENV !== "production" ? "uniForm" : "uf"); -var index$x = /* @__PURE__ */ defineBuiltInComponent({ - name: "Form", - setup(_props, { - slots, - emit: emit2 +const uniCheckGroupKey = PolySymbol(process.env.NODE_ENV !== "production" ? "uniCheckGroup" : "ucg"); +const props$s = { + name: { + type: String, + default: "" + } +}; +var index$t = /* @__PURE__ */ defineBuiltInComponent({ + name: "CheckboxGroup", + props: props$s, + emits: ["change"], + setup(props2, { + emit: emit2, + slots }) { - provideForm(emit2); - return () => vue.createVNode("uni-form", null, [vue.createVNode("span", null, [slots.default && slots.default()])]); + const rootRef = vue.ref(null); + const trigger = useCustomEvent(rootRef, emit2); + useProvideCheckGroup(props2, trigger); + return () => { + return vue.createVNode("uni-checkbox-group", { + "ref": rootRef + }, [slots.default && slots.default()], 512); + }; } }); -function provideForm(emit2) { +function useProvideCheckGroup(props2, trigger) { const fields2 = []; - vue.provide(uniFormKey, { + const getFieldsValue = () => fields2.reduce((res, field) => { + if (field.value.checkboxChecked) { + res.push(field.value.value); + } + return res; + }, new Array()); + vue.provide(uniCheckGroupKey, { addField(field) { fields2.push(field); }, removeField(field) { fields2.splice(fields2.indexOf(field), 1); }, - submit() { - emit2("submit", { - detail: { - value: fields2.reduce((res, field) => { - if (field.submit) { - const [name, value] = field.submit(); - name && (res[name] = value); - } - return res; - }, Object.create(null)) - } + checkboxChange($event) { + trigger("change", $event, { + value: getFieldsValue() }); - }, - reset() { - fields2.forEach((field) => field.reset && field.reset()); - emit2("reset"); } }); - return fields2; + const uniForm = vue.inject(uniFormKey, false); + if (uniForm) { + uniForm.addField({ + submit: () => { + let data = ["", null]; + if (props2.name !== "") { + data[0] = props2.name; + data[1] = getFieldsValue(); + } + return data; + } + }); + } + return getFieldsValue; } -const uniLabelKey = PolySymbol(process.env.NODE_ENV !== "production" ? "uniLabel" : "ul"); -const props$u = { - for: { +const props$r = { + 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: "" } }; -var index$w = /* @__PURE__ */ defineBuiltInComponent({ - name: "Label", - props: props$u, +var index$s = /* @__PURE__ */ defineBuiltInComponent({ + name: "Checkbox", + props: props$r, setup(props2, { slots }) { - const pageId = useCurrentPageId(); - const handlers = useProvideLabel(); - const pointer = vue.computed(() => props2.for || slots.default && slots.default.length); - const _onClick = withWebEvent(($event) => { - const EventTarget = $event.target; - let stopPropagation = /^uni-(checkbox|radio|switch)-/.test(EventTarget.className); - if (!stopPropagation) { - stopPropagation = /^uni-(checkbox|radio|switch|button)$|^(svg|path)$/i.test(EventTarget.tagName); - } - if (stopPropagation) { - return; - } - if (props2.for) { - UniViewJSBridge.emit("uni-label-click-" + pageId + "-" + props2.for, $event, true); - } else { - handlers[0]($event, true); - } + const checkboxChecked = vue.ref(props2.checked); + const checkboxValue = vue.ref(props2.value); + vue.watch([() => props2.checked, () => props2.value], ([newChecked, newModelValue]) => { + checkboxChecked.value = newChecked; + checkboxValue.value = newModelValue; }); - return () => vue.createVNode("uni-label", { - "class": { - "uni-label-pointer": pointer - }, - "onClick": _onClick - }, [slots.default && slots.default()], 10, ["onClick"]); - } -}); -function useProvideLabel() { - const handlers = []; - vue.provide(uniLabelKey, { - addHandler(handler) { - handlers.push(handler); - }, - removeHandler(handler) { - handlers.splice(handlers.indexOf(handler), 1); - } - }); - return handlers; -} -var index$v = /* @__PURE__ */ defineBuiltInComponent({ - 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: "" - }, - loading: { - type: [Boolean, String], - default: false - } - }, - setup(props2, { - slots - }) { - const rootRef = vue.ref(null); - const uniForm = vue.inject(uniFormKey, false); + const reset = () => { + checkboxChecked.value = false; + }; const { - hovering, - binding - } = useHover(props2); - useI18n(); - const onClick = withWebEvent((e2, isLabelClick) => { + uniCheckGroup, + uniLabel + } = useCheckboxInject(checkboxChecked, checkboxValue, reset); + const _onClick = ($event) => { if (props2.disabled) { - return e2.stopImmediatePropagation(); - } - if (isLabelClick) { - rootRef.value.click(); - } - const formType = props2.formType; - if (formType) { - if (!uniForm) { - return; - } - if (formType === "submit") { - uniForm.submit(); - } else if (formType === "reset") { - uniForm.reset(); - } return; } - }); - const uniLabel = vue.inject(uniLabelKey, false); - if (uniLabel) { - uniLabel.addHandler(onClick); + checkboxChecked.value = !checkboxChecked.value; + uniCheckGroup && uniCheckGroup.checkboxChange($event); + }; + if (!!uniLabel) { + uniLabel.addHandler(_onClick); } return () => { - const hoverClass = props2.hoverClass; - const booleanAttrs = useBooleanAttr(props2, "disabled"); - const loadingAttrs = useBooleanAttr(props2, "loading"); - const hasHoverClass = hoverClass && hoverClass !== "none"; - return vue.createVNode("uni-button", vue.mergeProps({ - "ref": rootRef, - "onClick": onClick, - "class": hasHoverClass && hovering.value ? hoverClass : "" - }, hasHoverClass && binding, booleanAttrs, loadingAttrs), [slots.default && slots.default()], 16, ["onClick"]); + const { + booleanAttrs + } = useBooleanAttr(props2, "disabled"); + return vue.createVNode("uni-checkbox", vue.mergeProps(booleanAttrs, { + "onClick": _onClick + }), [vue.createVNode("div", { + "class": "uni-checkbox-wrapper" + }, [vue.createVNode("div", { + "class": ["uni-checkbox-input", { + "uni-checkbox-input-disabled": props2.disabled + }] + }, [checkboxChecked.value ? createSvgIconVNode(ICON_PATH_SUCCESS_NO_CIRCLE, props2.color, 22) : ""], 2), slots.default && slots.default()])], 16, ["onClick"]); }; } }); -var ResizeSensor = /* @__PURE__ */ defineBuiltInComponent({ - name: "ResizeSensor", - props: { - initial: { - type: Boolean, - default: false - } - }, - emits: ["resize"], - setup(props2, { - emit: emit2 - }) { - const rootRef = vue.ref(null); - const reset = useResizeSensorReset(rootRef); - const update = useResizeSensorUpdate(rootRef, emit2, reset); - return () => vue.createVNode("uni-resize-sensor", { - "ref": rootRef, - "onAnimationstartOnce": update - }, [vue.createVNode("div", { - "onScroll": update - }, [vue.createVNode("div", null, null)], 40, ["onScroll"]), vue.createVNode("div", { - "onScroll": update - }, [vue.createVNode("div", null, null)], 40, ["onScroll"])], 40, ["onAnimationstartOnce"]); - } -}); -function useResizeSensorUpdate(rootRef, emit2, reset) { - const size = vue.reactive({ - width: -1, - height: -1 - }); - vue.watch(() => shared.extend({}, size), (value) => emit2("resize", value)); - return () => { - const { - width, - height - } = rootRef.value.getBoundingClientRect(); - size.width = width; - size.height = height; - reset(); +function useCheckboxInject(checkboxChecked, checkboxValue, reset) { + const field = vue.computed(() => ({ + checkboxChecked: Boolean(checkboxChecked.value), + value: checkboxValue.value + })); + const formField = { + reset }; -} -function useResizeSensorReset(rootRef) { - return () => { - const { - firstElementChild, - lastElementChild - } = rootRef.value; - firstElementChild.scrollLeft = 1e5; - firstElementChild.scrollTop = 1e5; - lastElementChild.scrollLeft = 1e5; - lastElementChild.scrollTop = 1e5; + const uniCheckGroup = vue.inject(uniCheckGroupKey, false); + if (!!uniCheckGroup) { + uniCheckGroup.addField(field); + } + const uniForm = vue.inject(uniFormKey, false); + if (!!uniForm) { + uniForm.addField(formField); + } + const uniLabel = vue.inject(uniLabelKey, false); + return { + uniCheckGroup, + uniForm, + uniLabel }; } -const pixelRatio = 1; -function wrapper(canvas) { - canvas.width = canvas.offsetWidth * pixelRatio; - canvas.height = canvas.offsetHeight * pixelRatio; - canvas.getContext("2d").__hidpi__ = true; +let resetTimer; +function iosHideKeyboard() { } -let isHidpi = false; -function initHidpi() { - if (isHidpi) { - return; +const props$q = { + cursorSpacing: { + type: [Number, String], + default: 0 + }, + showConfirmBar: { + type: [Boolean, String], + default: "auto" + }, + adjustPosition: { + type: [Boolean, String], + default: true + }, + autoBlur: { + type: [Boolean, String], + default: false } - isHidpi = true; - const proto = CanvasRenderingContext2D.prototype; - proto.drawImageByCanvas = function(_super) { - return function(canvas, srcx, srcy, srcw, srch, desx, desy, desw, desh, isScale) { - if (!this.__hidpi__) { - return _super.apply(this, arguments); +}; +const emit$1 = ["keyboardheightchange"]; +function useKeyboard$1(props2, elRef, trigger) { + function initKeyboard(el) { + el.addEventListener("focus", () => { + clearTimeout(resetTimer); + document.addEventListener("click", iosHideKeyboard, false); + }); + const onKeyboardHide = () => { + document.removeEventListener("click", iosHideKeyboard, false); + if (String(navigator.vendor).indexOf("Apple") === 0) { + document.documentElement.scrollTo(document.documentElement.scrollLeft, document.documentElement.scrollTop); } - srcx *= pixelRatio; - srcy *= pixelRatio; - srcw *= pixelRatio; - srch *= pixelRatio; - desx *= pixelRatio; - desy *= pixelRatio; - desw = isScale ? desw * pixelRatio : desw; - desh = isScale ? desh * pixelRatio : desh; - _super.call(this, canvas, srcx, srcy, srcw, srch, desx, desy, desw, desh); }; - }(proto.drawImage); + el.addEventListener("blur", () => { + onKeyboardHide(); + }); + } + vue.watch(() => elRef.value, (el) => initKeyboard(el)); } -const initHidpiOnce = /* @__PURE__ */ uniShared.once(initHidpi); -function $getRealPath(src) { - return src ? getRealPath(src) : src; +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 chars; + var match; + var stack = []; + var last = html; + stack.last = function() { + return this[this.length - 1]; + }; + while (html) { + chars = 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); + chars = false; + } + } else if (html.indexOf("]*>"), function(all, text2) { + text2 = text2.replace(/|/g, "$1$2"); + if (handler.chars) { + handler.chars(text2); + } + return ""; + }); + parseEndTag("", stack.last()); + } + if (html == last) { + throw "Parse Error: " + html; + } + last = html; + } + parseEndTag(); + function parseStartTag(tag, tagName, rest, unary) { + tagName = tagName.toLowerCase(); + if (block[tagName]) { + while (stack.last() && inline[stack.last()]) { + parseEndTag("", stack.last()); + } + } + if (closeSelf[tagName] && stack.last() == tagName) { + parseEndTag("", tagName); + } + unary = empty[tagName] || !!unary; + if (!unary) { + stack.push(tagName); + } + if (handler.start) { + var attrs = []; + rest.replace(attr, function(match2, name) { + var value = arguments[2] ? arguments[2] : arguments[3] ? arguments[3] : arguments[4] ? arguments[4] : fillAttrs[name] ? name : ""; + attrs.push({ + name, + value, + escaped: value.replace(/(^|[^\\])"/g, '$1\\"') + }); + }); + if (handler.start) { + handler.start(tagName, attrs, 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; + } + } + } + if (pos >= 0) { + for (var i = stack.length - 1; i >= pos; i--) { + if (handler.end) { + handler.end(stack[i]); + } + } + stack.length = pos; + } + } } -function resolveColor(color) { - color = color.slice(0); - color[3] = color[3] / 255; - return "rgba(" + color.join(",") + ")"; +function makeMap(str) { + var obj = {}; + var items = str.split(","); + for (var i = 0; i < items.length; i++) { + obj[items[i]] = true; + } + return obj; } -function processTouches(target, touches) { - const eventTarget = target; - return Array.from(touches).map((touch) => { - let boundingClientRect = eventTarget.getBoundingClientRect(); - return { - identifier: touch.identifier, - x: touch.clientX - boundingClientRect.left, - y: touch.clientY - boundingClientRect.top - }; +function useQuill(props2, rootRef, trigger) { + vue.watch(() => props2.readOnly, (value) => { }); + vue.watch(() => props2.placeholder, (value) => { + }); + const id = useContextInfo(); + useSubscribe((type, data) => { + const {options, callbackId} = data; + let res; + let errMsg; + { + errMsg = "not ready"; + } + if (callbackId) { + UniViewJSBridge.publishHandler("onEditorMethodCallback", { + callbackId, + data: shared.extend({}, res, { + errMsg: `${type}:${errMsg ? "fail " + errMsg : "ok"}` + }) + }); + } + }, id, true); } -let tempCanvas; -function getTempCanvas(width = 0, height = 0) { - if (!tempCanvas) { - tempCanvas = document.createElement("canvas"); - } - tempCanvas.width = width; - tempCanvas.height = height; - return tempCanvas; -} -const props$t = { - canvasId: { +const props$p = /* @__PURE__ */ shared.extend({}, props$q, { + id: { type: String, default: "" }, - disableScroll: { + readOnly: { type: [Boolean, String], default: false - } -}; -var index$u = /* @__PURE__ */ defineBuiltInComponent({ - inheritAttrs: false, - name: "Canvas", - compatConfig: { - MODE: 3 }, - props: props$t, - computed: { - id() { - return this.canvasId; - } + placeholder: { + type: String, + default: "" + }, + showImgSize: { + type: [Boolean, String], + default: false + }, + showImgToolbar: { + type: [Boolean, String], + default: false }, + showImgResize: { + type: [Boolean, String], + default: false + } +}); +var index$r = /* @__PURE__ */ defineBuiltInComponent({ + name: "Editor", + props: props$p, + emit: ["ready", "focus", "blur", "input", "statuschange", ...emit$1], setup(props2, { - emit: emit2, - slots + emit: emit2 }) { - initHidpiOnce(); - const canvas = vue.ref(null); - const sensor = vue.ref(null); - const actionsWaiting = vue.ref(false); - const trigger = useNativeEvent(emit2); - const { - $attrs, - $excludeAttrs, - $listeners - } = useAttrs({ - excludeListeners: true - }); - const { - _listeners - } = useListeners(props2, $listeners, trigger); - const { - _handleSubscribe, - _resize - } = useMethods(canvas, actionsWaiting); - useSubscribe(_handleSubscribe, useContextInfo(props2.canvasId), true); + const rootRef = vue.ref(null); + useQuill(props2); + useKeyboard$1(props2, rootRef); return () => { - const { - canvasId, - disableScroll - } = props2; - return vue.createVNode("uni-canvas", vue.mergeProps({ - "canvas-id": canvasId, - "disable-scroll": disableScroll - }, $attrs.value, $excludeAttrs.value, _listeners.value), [vue.createVNode("canvas", { - "ref": canvas, - "class": "uni-canvas-canvas", - "width": "300", - "height": "150" - }, null, 512), vue.createVNode("div", { - "style": "position: absolute;top: 0;left: 0;width: 100%;height: 100%;overflow: hidden;" - }, [slots.default && slots.default()]), vue.createVNode(ResizeSensor, { - "ref": sensor, - "onResize": _resize - }, null, 8, ["onResize"])], 16, ["canvas-id", "disable-scroll"]); + return vue.createVNode("uni-editor", { + "ref": rootRef, + "id": props2.id, + "class": "ql-container" + }, null, 8, ["id"]); }; } }); -function useListeners(props2, Listeners, trigger) { - const _listeners = vue.computed(() => { - let events = ["onTouchstart", "onTouchmove", "onTouchend"]; - let _$listeners = Listeners.value; - let $listeners = shared.extend({}, (() => { - let obj = {}; - for (const key in _$listeners) { - if (Object.prototype.hasOwnProperty.call(_$listeners, key)) { - const event = _$listeners[key]; - obj[key] = event; - } - } - return obj; - })()); - events.forEach((event) => { - let existing = $listeners[event]; - let eventHandler = []; - if (existing) { - eventHandler.push(withWebEvent(($event) => { - trigger(event.replace("on", "").toLocaleLowerCase(), shared.extend({}, (() => { - let obj = {}; - for (const key in $event) { - obj[key] = $event[key]; - } - return obj; - })(), { - touches: processTouches($event.currentTarget, $event.touches), - changedTouches: processTouches($event.currentTarget, $event.changedTouches) - })); - })); - } - if (props2.disableScroll && event === "onTouchmove") { - eventHandler.push(onEventPrevent); - } - $listeners[event] = eventHandler; - }); - return $listeners; - }); - return { - _listeners - }; -} -function useMethods(canvasRef, actionsWaiting) { - let _actionsDefer = []; - let _images = {}; - function _resize() { - var canvas = canvasRef.value; - if (canvas.width > 0 && canvas.height > 0) { - var context = canvas.getContext("2d"); - var imageData = context.getImageData(0, 0, canvas.width, canvas.height); - wrapper(canvas); - context.putImageData(imageData, 0, 0); - } else { - wrapper(canvas); +const INFO_COLOR = "#10aeff"; +const WARN_COLOR = "#f76260"; +const GREY_COLOR = "#b2b2b2"; +const CANCEL_COLOR = "#f43530"; +const ICONS = { + success: { + d: ICON_PATH_SUCCESS, + c: uniShared.PRIMARY_COLOR + }, + success_no_circle: { + d: ICON_PATH_SUCCESS_NO_CIRCLE, + c: uniShared.PRIMARY_COLOR + }, + 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: uniShared.PRIMARY_COLOR + }, + search: { + d: ICON_PATH_SEARCH, + c: GREY_COLOR + }, + clear: { + d: ICON_PATH_CLEAR, + c: GREY_COLOR + } +}; +var index$q = /* @__PURE__ */ defineBuiltInComponent({ + name: "Icon", + props: { + type: { + type: String, + required: true, + default: "" + }, + size: { + type: [String, Number], + default: 23 + }, + color: { + type: String, + default: "" } + }, + setup(props2) { + const path = vue.computed(() => ICONS[props2.type]); + return () => { + const { + value + } = path; + return vue.createVNode("uni-icon", null, [value && value.d && createSvgIconVNode(value.d, props2.color || value.c, rpx2px(props2.size))]); + }; } - function actionsChanged({ - actions, - reserve, - callbackId +}); +const props$o = { + src: { + type: String, + default: "" + }, + mode: { + type: String, + default: "scaleToFill" + }, + lazyLoad: { + type: [Boolean, String], + default: false + }, + draggable: { + type: Boolean, + default: true + } +}; +const FIX_MODES = { + widthFix: ["width", "height"], + heightFix: ["height", "width"] +}; +const IMAGE_MODES = { + aspectFit: ["center center", "contain"], + aspectFill: ["center center", "cover"], + widthFix: [, "100% 100%"], + heightFix: [, "100% 100%"], + top: ["center top"], + bottom: ["center bottom"], + center: ["center center"], + left: ["left center"], + right: ["right center"], + "top left": ["left top"], + "top right": ["right top"], + "bottom left": ["left bottom"], + "bottom right": ["right bottom"] +}; +var index$p = /* @__PURE__ */ defineBuiltInComponent({ + name: "Image", + props: props$o, + setup(props2, { + emit: emit2 }) { - if (!actions) { - return; + const rootRef = vue.ref(null); + const state = useImageState(rootRef, props2); + const trigger = useCustomEvent(rootRef, emit2); + const { + fixSize + } = useImageSize(rootRef, props2, state); + useImageLoader(state, { + trigger, + fixSize + }); + return () => { + const { + mode: mode2 + } = props2; + const { + imgSrc, + modeStyle + } = state; + return vue.createVNode("uni-image", { + "ref": rootRef + }, [vue.createVNode("div", { + "style": modeStyle + }, null, 4), imgSrc ? vue.createVNode("img", { + "src": imgSrc, + "draggable": props2.draggable + }, null, 8, ["src", "draggable"]) : vue.createVNode("img", null, null), FIX_MODES[mode2] ? vue.createVNode(ResizeSensor, { + "onResize": fixSize + }, null, 8, ["onResize"]) : vue.createVNode("span", null, null)], 512); + }; + } +}); +function useImageState(rootRef, props2) { + const imgSrc = vue.ref(""); + const modeStyleRef = vue.computed(() => { + let size = "auto"; + let position = ""; + const opts = IMAGE_MODES[props2.mode]; + if (!opts) { + position = "0% 0%"; + size = "100% 100%"; + } else { + opts[0] && (position = opts[0]); + opts[1] && (size = opts[1]); } - if (actionsWaiting.value) { - _actionsDefer.push([actions, reserve, callbackId]); + const srcVal = imgSrc.value; + return `background-image:${srcVal ? 'url("' + srcVal + '")' : "none"};background-position:${position};background-size:${size};background-repeat:no-repeat;`; + }); + const state = vue.reactive({ + rootEl: rootRef, + src: vue.computed(() => props2.src ? getRealPath(props2.src) : ""), + origWidth: 0, + origHeight: 0, + origStyle: { + width: "", + height: "" + }, + modeStyle: modeStyleRef, + imgSrc + }); + return state; +} +function useImageLoader(state, { + trigger, + fixSize +}) { + let img; + const setState = (width = 0, height = 0, imgSrc = "") => { + state.origWidth = width; + state.origHeight = height; + state.imgSrc = imgSrc; + }; + const loadImage = (src) => { + if (!src) { + resetImage(); + setState(); return; } - var canvas = canvasRef.value; - 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); - } - 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 = checkImageLoaded(data[1], actions.slice(index2 + 1), callbackId, function(image) { - if (image) { - c2d[method1] = c2d.createPattern(image, data[2]); - } - }); - if (!loaded) { - break; - } - continue; - } - c2d[method1] = color; - } else if (method1 === "globalAlpha") { - c2d[method1] = Number(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") { - const font = c2d.__font__ || c2d.font; - c2d.__font__ = c2d.font = 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 if (method1 === "font") { - c2d.__font__ = c2d.font = 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); - _images = _images || {}; - if (checkImageLoaded(url, actions.slice(index2 + 1), callbackId, function(image) { - if (image) { - c2d.drawImage.apply(c2d, [image].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 (!actionsWaiting.value && callbackId) { - UniViewJSBridge.publishHandler("onCanvasMethodCallback", { - callbackId, - data: { - errMsg: "drawCanvas:ok" - } - }, getCurrentPageId()); - } - } - function preloadImage(actions) { - actions.forEach(function(action) { - var method = action.method; - var data = action.data; - var src = ""; - if (method === "drawImage") { - src = data[0]; - src = $getRealPath(src); - data[0] = src; - } else if (method === "setFillStyle" && data[0] === "pattern") { - src = data[1]; - src = $getRealPath(src); - data[1] = src; - } - if (src && !_images[src]) { - loadImage(); - } - function loadImage() { - const image = _images[src] = new Image(); - image.onload = function() { - image.ready = true; - }; - getSameOriginUrl(src).then((src2) => { - image.src = src2; - }).catch(() => { - image.src = src; - }); - } - }); - } - function checkImageLoaded(src, actions, callbackId, fn) { - var image = _images[src]; - if (image.ready) { - fn(image); - return true; - } else { - _actionsDefer.unshift([actions, true]); - actionsWaiting.value = true; - image.onload = function() { - image.ready = true; - fn(image); - actionsWaiting.value = false; - var actions2 = _actionsDefer.slice(0); - _actionsDefer = []; - for (var action = actions2.shift(); action; ) { - actionsChanged({ - actions: action[0], - reserve: action[1], - callbackId - }); - action = actions2.shift(); - } - }; - return false; - } - } - function getImageData({ - x = 0, - y = 0, - width, - height, - destWidth, - destHeight, - hidpi = true, - dataType: dataType2, - quality = 1, - type = "png", - callbackId - }) { - const canvas = canvasRef.value; - let data; - const maxWidth = canvas.offsetWidth - x; - width = width ? Math.min(width, maxWidth) : maxWidth; - const maxHeight = canvas.offsetHeight - y; - height = height ? Math.min(height, maxHeight) : maxHeight; - 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"); - if (type === "jpeg" || type === "jpg") { - type = "jpeg"; - context.fillStyle = "#fff"; - context.fillRect(0, 0, destWidth, destHeight); - } - context.__hidpi__ = true; - context.drawImageByCanvas(canvas, x, y, width, height, 0, 0, destWidth, destHeight, false); - let result; - try { - let compressed; - if (dataType2 === "base64") { - data = newCanvas.toDataURL(`image/${type}`, quality); - } else { - const imgData = context.getImageData(0, 0, destWidth, destHeight); - if (false) - ; - else { - data = Array.prototype.slice.call(imgData.data); - } - } - result = { - errMsg: "canvasGetImageData:ok", - data, - compressed, - width: destWidth, - height: destHeight - }; - } catch (error) { - result = { - errMsg: `canvasGetImageData:fail ${error}` - }; + if (!img) { + img = new Image(); } - newCanvas.height = newCanvas.width = 0; - context.__hidpi__ = false; - if (!callbackId) { - return result; - } else { - UniViewJSBridge.publishHandler("onCanvasMethodCallback", { - callbackId, - data: result - }, getCurrentPageId()); + img.onload = (evt) => { + const { + width, + height + } = img; + setState(width, height, src); + fixSize(); + resetImage(); + trigger("load", evt, { + width, + height + }); + }; + img.onerror = (evt) => { + setState(); + resetImage(); + trigger("error", evt, { + errMsg: `GET ${state.src} 404 (Not Found)` + }); + }; + img.src = src; + }; + const resetImage = () => { + if (img) { + img.onload = null; + img.onerror = null; + img = null; } - } - function putImageData({ - data, - x, - y, - width, - height, - compressed, - callbackId - }) { - try { - if (!height) { - height = Math.round(data.length / 4 / width); - } - const canvas = getTempCanvas(width, height); - const context = canvas.getContext("2d"); - if (false) - ; - context.putImageData(new ImageData(new Uint8ClampedArray(data), width, height), 0, 0); - canvasRef.value.getContext("2d").drawImage(canvas, x, y, width, height); - canvas.height = canvas.width = 0; - } catch (error) { - UniViewJSBridge.publishHandler("onCanvasMethodCallback", { - callbackId, - data: { - errMsg: "canvasPutImageData:fail" - } - }, getCurrentPageId()); + }; + vue.watch(() => state.src, (value) => loadImage(value)); +} +function fixNumber(num) { + return num; +} +function useImageSize(rootRef, props2, state) { + const fixSize = () => { + const { + mode: mode2 + } = props2; + const names = FIX_MODES[mode2]; + if (!names) { return; } - UniViewJSBridge.publishHandler("onCanvasMethodCallback", { - callbackId, - data: { - errMsg: "canvasPutImageData:ok" - } - }, getCurrentPageId()); - } - function toTempFilePath({ - x = 0, - y = 0, - width, - height, - destWidth, - destHeight, - fileType, - quality, - dirname, - callbackId - }) { - const res = getImageData({ - x, - y, - width, - height, - destWidth, - destHeight, - hidpi: false, - dataType: "base64", - type: fileType, - quality - }); - if (!res.data || !res.data.length) { - UniViewJSBridge.publishHandler("onCanvasMethodCallback", { - callbackId, - data: { - errMsg: res.errMsg.replace("canvasPutImageData", "toTempFilePath") - } - }, getCurrentPageId()); + const { + origWidth, + origHeight + } = state; + const ratio = origWidth && origHeight ? origWidth / origHeight : 0; + if (!ratio) { return; } - saveImage(res.data, dirname, (error, tempFilePath) => { - let errMsg = `toTempFilePath:${error ? "fail" : "ok"}`; - if (error) { - errMsg += ` ${error.message}`; - } - UniViewJSBridge.publishHandler("onCanvasMethodCallback", { - callbackId, - data: { - errMsg, - tempFilePath - } - }, getCurrentPageId()); - }); - } - const methods = { - actionsChanged, - getImageData, - putImageData, - toTempFilePath + const rootEl = rootRef.value; + const rect = rootEl.getBoundingClientRect(); + const value = rect[names[0]]; + if (value) { + rootEl.style[names[1]] = fixNumber(value / ratio) + "px"; + } }; - function _handleSubscribe(type, data = {}) { - let method = methods[type]; - if (type.indexOf("_") !== 0 && typeof method === "function") { - method(data); + const resetSize = () => { + const { + style + } = rootRef.value; + const { + origStyle: { + width, + height + } + } = state; + style.width = width; + style.height = height; + }; + vue.watch(() => props2.mode, (value, oldValue) => { + if (FIX_MODES[oldValue]) { + resetSize(); + } + if (FIX_MODES[value]) { + fixSize(); } - } - return shared.extend(methods, { - _resize, - _handleSubscribe }); + return { + fixSize, + resetSize + }; } -const uniCheckGroupKey = PolySymbol(process.env.NODE_ENV !== "production" ? "uniCheckGroup" : "ucg"); -const props$s = { - name: { - type: String, - default: "" - } -}; -var index$t = /* @__PURE__ */ defineBuiltInComponent({ - name: "CheckboxGroup", - props: props$s, - emits: ["change"], - setup(props2, { - emit: emit2, - slots - }) { - const rootRef = vue.ref(null); - const trigger = useCustomEvent(rootRef, emit2); - useProvideCheckGroup(props2, trigger); - return () => { - return vue.createVNode("uni-checkbox-group", { - "ref": rootRef - }, [slots.default && slots.default()], 512); - }; +uniShared.passive(true); +function useUserAction() { + const state = vue.reactive({ + userAction: false + }); + return { + state + }; +} +function useScopedAttrs() { + const state = vue.reactive({ + attrs: {} + }); + return { + state + }; +} +function useFormField(nameKey, value) { + const uniForm = vue.inject(uniFormKey, false); + if (!uniForm) { + return; } -}); -function useProvideCheckGroup(props2, trigger) { - const fields2 = []; - const getFieldsValue = () => fields2.reduce((res, field) => { - if (field.value.checkboxChecked) { - res.push(field.value.value); - } - return res; - }, new Array()); - vue.provide(uniCheckGroupKey, { - addField(field) { - fields2.push(field); - }, - removeField(field) { - fields2.splice(fields2.indexOf(field), 1); + const instance = vue.getCurrentInstance(); + const ctx = { + submit() { + const proxy = instance.proxy; + return [ + proxy[nameKey], + typeof value === "string" ? proxy[value] : value.value + ]; }, - checkboxChange($event) { - trigger("change", $event, { - value: getFieldsValue() - }); + reset() { + if (typeof value === "string") { + instance.proxy[value] = ""; + } else { + value.value = ""; + } + } + }; + uniForm.addField(ctx); +} +const pageIds = []; +const UniViewJSBridgeSubscribe = function() { + const pageId = getCurrentPageId(); + if (pageIds.includes(pageId)) + return; + pageIds.push(pageId); + UniViewJSBridge.subscribe(pageId + ".getSelectedTextRange", function({pageId: pageId2, callbackId}) { + const activeElement = document.activeElement; + if (!activeElement) + return; + const tagName = activeElement.tagName.toLowerCase(); + const tagNames = ["input", "textarea"]; + const data = {}; + if (tagNames.includes(tagName)) { + data.start = activeElement.selectionStart; + data.end = activeElement.selectionEnd; } + UniViewJSBridge.publishHandler("onGetSelectedTextRange", { + callbackId, + data + }, pageId2); }); - const uniForm = vue.inject(uniFormKey, false); - if (uniForm) { - uniForm.addField({ - submit: () => { - let data = ["", null]; - if (props2.name !== "") { - data[0] = props2.name; - data[1] = getFieldsValue(); - } - return data; - } - }); - } - return getFieldsValue; +}; +function getValueString(value) { + return value === null ? "" : String(value); } -const props$r = { - checked: { - type: [Boolean, String], - default: false - }, - id: { +const props$n = /* @__PURE__ */ shared.extend({}, { + name: { type: String, default: "" }, + modelValue: { + type: [String, Number], + default: "" + }, + value: { + type: [String, Number], + default: "" + }, disabled: { type: [Boolean, String], default: false }, - color: { - type: String, - default: "#007aff" + autoFocus: { + type: [Boolean, String], + default: false }, - value: { - type: String, - default: "" - } -}; -var index$s = /* @__PURE__ */ defineBuiltInComponent({ - name: "Checkbox", - props: props$r, - setup(props2, { - slots - }) { - const checkboxChecked = vue.ref(props2.checked); - const checkboxValue = vue.ref(props2.value); - vue.watch([() => props2.checked, () => props2.value], ([newChecked, newModelValue]) => { - checkboxChecked.value = newChecked; - checkboxValue.value = newModelValue; - }); - const reset = () => { - checkboxChecked.value = false; - }; - const { - uniCheckGroup, - uniLabel - } = useCheckboxInject(checkboxChecked, checkboxValue, reset); - const _onClick = ($event) => { - if (props2.disabled) { - return; - } - checkboxChecked.value = !checkboxChecked.value; - uniCheckGroup && uniCheckGroup.checkboxChange($event); - }; - if (!!uniLabel) { - uniLabel.addHandler(_onClick); - } - return () => { - const { - booleanAttrs - } = useBooleanAttr(props2, "disabled"); - return vue.createVNode("uni-checkbox", vue.mergeProps(booleanAttrs, { - "onClick": _onClick - }), [vue.createVNode("div", { - "class": "uni-checkbox-wrapper" - }, [vue.createVNode("div", { - "class": ["uni-checkbox-input", { - "uni-checkbox-input-disabled": props2.disabled - }] - }, [checkboxChecked.value ? createSvgIconVNode(ICON_PATH_SUCCESS_NO_CIRCLE, props2.color, 22) : ""], 2), slots.default && slots.default()])], 16, ["onClick"]); - }; - } -}); -function useCheckboxInject(checkboxChecked, checkboxValue, reset) { - const field = vue.computed(() => ({ - checkboxChecked: Boolean(checkboxChecked.value), - value: checkboxValue.value - })); - const formField = { - reset - }; - const uniCheckGroup = vue.inject(uniCheckGroupKey, false); - if (!!uniCheckGroup) { - uniCheckGroup.addField(field); - } - const uniForm = vue.inject(uniFormKey, false); - if (!!uniForm) { - uniForm.addField(formField); - } - const uniLabel = vue.inject(uniLabelKey, false); - return { - uniCheckGroup, - uniForm, - uniLabel - }; -} -let resetTimer; -function iosHideKeyboard() { -} -const props$q = { - cursorSpacing: { + focus: { + type: [Boolean, String], + default: false + }, + cursor: { type: [Number, String], - default: 0 + default: -1 }, - showConfirmBar: { - type: [Boolean, String], - default: "auto" + selectionStart: { + type: [Number, String], + default: -1 }, - adjustPosition: { - type: [Boolean, String], - default: true + selectionEnd: { + type: [Number, String], + default: -1 }, - autoBlur: { + type: { + type: String, + default: "text" + }, + password: { type: [Boolean, String], default: false + }, + placeholder: { + type: String, + default: "" + }, + placeholderStyle: { + type: String, + default: "" + }, + placeholderClass: { + type: String, + default: "" + }, + maxlength: { + type: [Number, String], + default: 140 + }, + confirmType: { + type: String, + default: "done" } -}; -const emit$1 = ["keyboardheightchange"]; -function useKeyboard$1(props2, elRef, trigger) { - function initKeyboard(el) { - el.addEventListener("focus", () => { - clearTimeout(resetTimer); - document.addEventListener("click", iosHideKeyboard, false); - }); - const onKeyboardHide = () => { - document.removeEventListener("click", iosHideKeyboard, false); - if (String(navigator.vendor).indexOf("Apple") === 0) { - document.documentElement.scrollTo(document.documentElement.scrollLeft, document.documentElement.scrollTop); - } - }; - el.addEventListener("blur", () => { - onKeyboardHide(); - }); - } - vue.watch(() => elRef.value, (el) => initKeyboard(el)); +}, props$q); +const emit = [ + "input", + "focus", + "blur", + "update:value", + "update:modelValue", + "update:focus", + ...emit$1 +]; +function useBase(props2, rootRef, emit2) { + const fieldRef = vue.ref(null); + const trigger = useCustomEvent(rootRef, emit2); + const selectionStart = vue.computed(() => { + const selectionStart2 = Number(props2.selectionStart); + return isNaN(selectionStart2) ? -1 : selectionStart2; + }); + const selectionEnd = vue.computed(() => { + const selectionEnd2 = Number(props2.selectionEnd); + return isNaN(selectionEnd2) ? -1 : selectionEnd2; + }); + const cursor = vue.computed(() => { + const cursor2 = Number(props2.cursor); + return isNaN(cursor2) ? -1 : cursor2; + }); + const maxlength = vue.computed(() => { + var maxlength2 = Number(props2.maxlength); + return isNaN(maxlength2) ? 140 : maxlength2; + }); + const value = getValueString(props2.modelValue) || getValueString(props2.value); + const state = vue.reactive({ + value, + valueOrigin: value, + maxlength, + focus: props2.focus, + composing: false, + selectionStart, + selectionEnd, + cursor + }); + vue.watch(() => state.focus, (val) => emit2("update:focus", val)); + vue.watch(() => state.maxlength, (val) => state.value = state.value.slice(0, val)); + return { + fieldRef, + state, + trigger + }; } -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 chars; - var match; - var stack = []; - var last = html; - stack.last = function() { - return this[this.length - 1]; +function useValueSync(props2, state, emit2, trigger) { + const valueChangeFn = uniShared.debounce((val) => { + state.value = getValueString(val); + }, 100); + vue.watch(() => props2.modelValue, valueChangeFn); + vue.watch(() => props2.value, valueChangeFn); + const triggerInputFn = throttle((event, detail) => { + emit2("update:modelValue", detail.value); + emit2("update:value", detail.value); + trigger("input", event, detail); + }, 100); + const triggerInput = (event, detail, force) => { + valueChangeFn.cancel(); + triggerInputFn(event, detail); + if (force) { + triggerInputFn.flush(); + } }; - while (html) { - chars = 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); - chars = false; - } - } else if (html.indexOf("]*>"), function(all, text2) { - text2 = text2.replace(/|/g, "$1$2"); - if (handler.chars) { - handler.chars(text2); - } - return ""; - }); - parseEndTag("", stack.last()); + return { + trigger, + triggerInput + }; +} +function useAutoFocus(props2, fieldRef) { + useUserAction(); + const needFocus = vue.computed(() => props2.autoFocus || props2.focus); + function focus() { + if (!needFocus.value) { + return; } - if (html == last) { - throw "Parse Error: " + html; + const field = fieldRef.value; + if (!field || false) { + setTimeout(focus, 100); + return; + } + { + field.focus(); } - last = html; } - parseEndTag(); - function parseStartTag(tag, tagName, rest, unary) { - tagName = tagName.toLowerCase(); - if (block[tagName]) { - while (stack.last() && inline[stack.last()]) { - parseEndTag("", stack.last()); - } + function blur() { + const field = fieldRef.value; + if (field) { + field.blur(); } - if (closeSelf[tagName] && stack.last() == tagName) { - parseEndTag("", tagName); + } + vue.watch(() => props2.focus, (value) => { + if (value) { + focus(); + } else { + blur(); } - unary = empty[tagName] || !!unary; - if (!unary) { - stack.push(tagName); + }); +} +function useEvent(fieldRef, state, trigger, triggerInput, beforeInput) { + function checkSelection() { + const field = fieldRef.value; + if (field && state.focus && state.selectionStart > -1 && state.selectionEnd > -1) { + field.selectionStart = state.selectionStart; + field.selectionEnd = state.selectionEnd; } - if (handler.start) { - var attrs = []; - rest.replace(attr, function(match2, name) { - var value = arguments[2] ? arguments[2] : arguments[3] ? arguments[3] : arguments[4] ? arguments[4] : fillAttrs[name] ? name : ""; - attrs.push({ - name, - value, - escaped: value.replace(/(^|[^\\])"/g, '$1\\"') - }); + } + function checkCursor() { + const field = fieldRef.value; + if (field && state.focus && state.selectionStart < 0 && state.selectionEnd < 0 && state.cursor > -1) { + field.selectionEnd = field.selectionStart = state.cursor; + } + } + function initField() { + const field = fieldRef.value; + const onFocus = function(event) { + state.focus = true; + trigger("focus", event, { + value: state.value }); - if (handler.start) { - handler.start(tagName, attrs, unary); + checkSelection(); + checkCursor(); + }; + const onInput = function(event, force) { + event.stopPropagation(); + if (typeof beforeInput === "function" && beforeInput(event, state) === false) { + return; } - } - } - function parseEndTag(tag, tagName) { - if (!tagName) { - var pos = 0; - } else { - for (var pos = stack.length - 1; pos >= 0; pos--) { - if (stack[pos] == tagName) { - break; - } + state.value = field.value; + if (!state.composing) { + triggerInput(event, { + value: field.value, + cursor: field.selectionEnd + }, force); } - } - if (pos >= 0) { - for (var i = stack.length - 1; i >= pos; i--) { - if (handler.end) { - handler.end(stack[i]); - } + }; + const onBlur = function(event) { + if (state.composing) { + state.composing = false; + onInput(event, true); } - stack.length = pos; - } - } -} -function makeMap(str) { - var obj = {}; - var items = str.split(","); - for (var i = 0; i < items.length; i++) { - obj[items[i]] = true; + state.focus = false; + trigger("blur", event, { + value: state.value, + cursor: event.target.selectionEnd + }); + }; + field.addEventListener("change", (event) => event.stopPropagation()); + field.addEventListener("focus", onFocus); + field.addEventListener("blur", onBlur); + field.addEventListener("input", onInput); + field.addEventListener("compositionstart", (event) => { + event.stopPropagation(); + state.composing = true; + }); + field.addEventListener("compositionend", (event) => { + event.stopPropagation(); + if (state.composing) { + state.composing = false; + onInput(event); + } + }); } - return obj; + vue.watch([() => state.selectionStart, () => state.selectionEnd], checkSelection); + vue.watch(() => state.cursor, checkCursor); + vue.watch(() => fieldRef.value, initField); } -function useQuill(props2, rootRef, trigger) { - vue.watch(() => props2.readOnly, (value) => { - }); - vue.watch(() => props2.placeholder, (value) => { - }); - const id = useContextInfo(); - useSubscribe((type, data) => { - const {options, callbackId} = data; - let res; - let errMsg; - { - errMsg = "not ready"; - } - if (callbackId) { - UniViewJSBridge.publishHandler("onEditorMethodCallback", { - callbackId, - data: shared.extend({}, res, { - errMsg: `${type}:${errMsg ? "fail " + errMsg : "ok"}` - }) - }); - } - }, id, true); +function useField(props2, rootRef, emit2, beforeInput) { + UniViewJSBridgeSubscribe(); + const {fieldRef, state, trigger} = useBase(props2, rootRef, emit2); + const {triggerInput} = useValueSync(props2, state, emit2, trigger); + useAutoFocus(props2, fieldRef); + useKeyboard$1(props2, fieldRef); + const {state: scopedAttrsState} = useScopedAttrs(); + useFormField("name", state); + useEvent(fieldRef, state, trigger, triggerInput, beforeInput); + const fixDisabledColor = false; + return { + fieldRef, + state, + scopedAttrsState, + fixDisabledColor, + trigger + }; } -const props$p = /* @__PURE__ */ shared.extend({}, props$q, { - id: { - type: String, - default: "" - }, - readOnly: { - type: [Boolean, String], - default: false - }, - placeholder: { +const props$m = /* @__PURE__ */ shared.extend({}, props$n, { + placeholderClass: { type: String, - default: "" - }, - showImgSize: { - type: [Boolean, String], - default: false - }, - showImgToolbar: { - type: [Boolean, String], - default: false - }, - showImgResize: { - type: [Boolean, String], - default: false + default: "input-placeholder" } }); -var index$r = /* @__PURE__ */ defineBuiltInComponent({ - name: "Editor", - props: props$p, - emit: ["ready", "focus", "blur", "input", "statuschange", ...emit$1], +var Input = /* @__PURE__ */ defineBuiltInComponent({ + name: "Input", + props: props$m, + emits: ["confirm", ...emit], setup(props2, { emit: emit2 }) { + const INPUT_TYPES = ["text", "number", "idcard", "digit", "password"]; + const type = vue.computed(() => { + let type2 = ""; + switch (props2.type) { + case "text": + if (props2.confirmType === "search") { + type2 = "search"; + } + break; + case "idcard": + type2 = "text"; + break; + case "digit": + type2 = "number"; + break; + default: + type2 = ~INPUT_TYPES.includes(props2.type) ? props2.type : "text"; + break; + } + return props2.password ? "password" : type2; + }); + const valid = vue.ref(true); const rootRef = vue.ref(null); - useQuill(props2); - useKeyboard$1(props2, rootRef); - return () => { - return vue.createVNode("uni-editor", { - "ref": rootRef, - "id": props2.id, - "class": "ql-container" - }, null, 8, ["id"]); - }; - } -}); -const INFO_COLOR = "#10aeff"; -const WARN_COLOR = "#f76260"; -const GREY_COLOR = "#b2b2b2"; -const CANCEL_COLOR = "#f43530"; -const ICONS = { - success: { - d: ICON_PATH_SUCCESS, - c: uniShared.PRIMARY_COLOR - }, - success_no_circle: { - d: ICON_PATH_SUCCESS_NO_CIRCLE, - c: uniShared.PRIMARY_COLOR - }, - 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: uniShared.PRIMARY_COLOR - }, - search: { - d: ICON_PATH_SEARCH, - c: GREY_COLOR - }, - clear: { - d: ICON_PATH_CLEAR, - c: GREY_COLOR - } -}; -var index$q = /* @__PURE__ */ defineBuiltInComponent({ - name: "Icon", - props: { - type: { - type: String, - required: true, - default: "" - }, - size: { - type: [String, Number], - default: 23 - }, - color: { - type: String, - default: "" + const { + fieldRef, + state, + scopedAttrsState, + fixDisabledColor, + trigger + } = useField(props2, rootRef, emit2, (event, state2) => { + const input = event.target; + if (NUMBER_TYPES.includes(props2.type)) { + valid.value = input.validity && input.validity.valid; + } + if (type.value === "number") { + const maxlength = state2.maxlength; + if (maxlength > 0 && input.value.length > maxlength) { + input.value = input.value.slice(0, maxlength); + state2.value = input.value; + return false; + } + } + }); + const NUMBER_TYPES = ["number", "digit"]; + const step = vue.computed(() => NUMBER_TYPES.includes(props2.type) ? "0.000000000000000001" : ""); + function onKeyUpEnter(event) { + if (event.key !== "Enter") { + return; + } + event.stopPropagation(); + trigger("confirm", event, { + value: event.target.value + }); } - }, - setup(props2) { - const path = vue.computed(() => ICONS[props2.type]); return () => { - const { - value - } = path; - return vue.createVNode("uni-icon", null, [value && value.d && createSvgIconVNode(value.d, props2.color || value.c, rpx2px(props2.size))]); + let inputNode = props2.disabled && fixDisabledColor ? vue.createVNode("input", { + "ref": fieldRef, + "value": state.value, + "tabindex": "-1", + "readonly": !!props2.disabled, + "type": type.value, + "maxlength": state.maxlength, + "step": step.value, + "class": "uni-input-input", + "onFocus": (event) => event.target.blur() + }, null, 40, ["value", "readonly", "type", "maxlength", "step", "onFocus"]) : vue.createVNode("input", { + "ref": fieldRef, + "value": state.value, + "disabled": !!props2.disabled, + "type": type.value, + "maxlength": state.maxlength, + "step": step.value, + "enterkeyhint": props2.confirmType, + "class": "uni-input-input", + "autocomplete": "off", + "onKeyup": onKeyUpEnter + }, null, 40, ["value", "disabled", "type", "maxlength", "step", "enterkeyhint", "onKeyup"]); + return vue.createVNode("uni-input", { + "ref": rootRef + }, [vue.createVNode("div", { + "class": "uni-input-wrapper" + }, [vue.withDirectives(vue.createVNode("div", vue.mergeProps(scopedAttrsState.attrs, { + "style": props2.placeholderStyle, + "class": ["uni-input-placeholder", props2.placeholderClass] + }), [props2.placeholder], 16), [[vue.vShow, !(state.value.length || !valid.value)]]), props2.confirmType === "search" ? vue.createVNode("form", { + "action": "", + "onSubmit": (event) => event.preventDefault(), + "class": "uni-input-form" + }, [inputNode], 40, ["onSubmit"]) : inputNode])], 512); }; } }); -const props$o = { - src: { - type: String, - default: "" - }, - mode: { - type: String, - default: "scaleToFill" - }, - lazyLoad: { - type: [Boolean, String], - default: false - }, - draggable: { +function entries(obj) { + return Object.keys(obj).map((key) => [key, obj[key]]); +} +const DEFAULT_EXCLUDE_KEYS = ["class", "style"]; +const LISTENER_PREFIX = /^on[A-Z]+/; +const useAttrs = (params = {}) => { + const {excludeListeners = false, excludeKeys = []} = params; + const instance = vue.getCurrentInstance(); + const attrs = vue.shallowRef({}); + const listeners = vue.shallowRef({}); + const excludeAttrs = vue.shallowRef({}); + const allExcludeKeys = excludeKeys.concat(DEFAULT_EXCLUDE_KEYS); + instance.attrs = vue.reactive(instance.attrs); + vue.watchEffect(() => { + const res = entries(instance.attrs).reduce((acc, [key, val]) => { + if (allExcludeKeys.includes(key)) { + acc.exclude[key] = val; + } else if (LISTENER_PREFIX.test(key)) { + if (!excludeListeners) { + acc.attrs[key] = val; + } + acc.listeners[key] = val; + } else { + acc.attrs[key] = val; + } + return acc; + }, { + exclude: {}, + attrs: {}, + listeners: {} + }); + attrs.value = res.attrs; + listeners.value = res.listeners; + excludeAttrs.value = res.exclude; + }); + return {$attrs: attrs, $listeners: listeners, $excludeAttrs: excludeAttrs}; +}; +function initScrollBounce() { +} +function disableScrollBounce({disable}) { +} +function flatVNode(nodes) { + const array = []; + if (Array.isArray(nodes)) { + nodes.forEach((vnode) => { + if (vue.isVNode(vnode)) { + if (vnode.type === vue.Fragment) { + array.push(...flatVNode(vnode.children)); + } else { + array.push(vnode); + } + } else if (Array.isArray(vnode)) { + array.push(...flatVNode(vnode)); + } + }); + } + return array; +} +const props$l = { + scaleArea: { type: Boolean, - default: true + default: false } }; -const FIX_MODES = { - widthFix: ["width", "height"], - heightFix: ["height", "width"] -}; -const IMAGE_MODES = { - aspectFit: ["center center", "contain"], - aspectFill: ["center center", "cover"], - widthFix: [, "100% 100%"], - heightFix: [, "100% 100%"], - top: ["center top"], - bottom: ["center bottom"], - center: ["center center"], - left: ["left center"], - right: ["right center"], - "top left": ["left top"], - "top right": ["right top"], - "bottom left": ["left bottom"], - "bottom right": ["right bottom"] -}; -var index$p = /* @__PURE__ */ defineBuiltInComponent({ - name: "Image", - props: props$o, +var index$o = /* @__PURE__ */ defineBuiltInComponent({ + inheritAttrs: false, + name: "MovableArea", + props: props$l, setup(props2, { - emit: emit2 + slots }) { const rootRef = vue.ref(null); - const state = useImageState(rootRef, props2); - const trigger = useCustomEvent(rootRef, emit2); + const _isMounted = vue.ref(false); + let { + setContexts, + events: movableAreaEvents + } = useMovableAreaState(props2, rootRef); const { - fixSize - } = useImageSize(rootRef, props2, state); - useImageLoader(state, { - trigger, - fixSize + $listeners, + $attrs, + $excludeAttrs + } = useAttrs(); + const _listeners = $listeners.value; + let events = ["onTouchstart", "onTouchmove", "onTouchend"]; + events.forEach((event) => { + let existing = _listeners[event]; + let ours = movableAreaEvents[`_${event}`]; + _listeners[event] = existing ? [].concat(existing, ours) : ours; }); + let movableViewItems = []; + const originMovableViewContexts = []; + function updateMovableViewContexts() { + const contexts = []; + for (let index2 = 0; index2 < movableViewItems.length; index2++) { + const movableViewItem = movableViewItems[index2]; + const movableViewContext = originMovableViewContexts.find((context) => movableViewItem.el === context.rootRef.value); + if (movableViewContext) { + contexts.push(vue.markRaw(movableViewContext)); + } + } + setContexts(contexts); + } + const addMovableViewContext = (movableViewContext) => { + originMovableViewContexts.push(movableViewContext); + updateMovableViewContexts(); + }; + const removeMovableViewContext = (movableViewContext) => { + const index2 = originMovableViewContexts.indexOf(movableViewContext); + if (index2 >= 0) { + originMovableViewContexts.splice(index2, 1); + updateMovableViewContexts(); + } + }; + vue.provide("_isMounted", _isMounted); + vue.provide("movableAreaRootRef", rootRef); + vue.provide("addMovableViewContext", addMovableViewContext); + vue.provide("removeMovableViewContext", removeMovableViewContext); return () => { - const { - mode: mode2 - } = props2; - const { - imgSrc, - modeStyle - } = state; - return vue.createVNode("uni-image", { + const defaultSlots = slots.default && slots.default(); + movableViewItems = flatVNode(defaultSlots); + return vue.createVNode("uni-movable-area", vue.mergeProps({ "ref": rootRef - }, [vue.createVNode("div", { - "style": modeStyle - }, null, 4), imgSrc ? vue.createVNode("img", { - "src": imgSrc, - "draggable": props2.draggable - }, null, 8, ["src", "draggable"]) : vue.createVNode("img", null, null), FIX_MODES[mode2] ? vue.createVNode(ResizeSensor, { - "onResize": fixSize - }, null, 8, ["onResize"]) : vue.createVNode("span", null, null)], 512); + }, $attrs.value, $excludeAttrs.value, _listeners), [vue.createVNode(ResizeSensor, { + "onReize": movableAreaEvents._resize + }, null, 8, ["onReize"]), movableViewItems], 16); }; } -}); -function useImageState(rootRef, props2) { - const imgSrc = vue.ref(""); - const modeStyleRef = vue.computed(() => { - let size = "auto"; - let position = ""; - const opts = IMAGE_MODES[props2.mode]; - if (!opts) { - position = "0% 0%"; - size = "100% 100%"; - } else { - opts[0] && (position = opts[0]); - opts[1] && (size = opts[1]); +}); +function calc(e2) { + return Math.sqrt(e2.x * e2.x + e2.y * e2.y); +} +function useMovableAreaState(props2, rootRef) { + const width = vue.ref(0); + const height = vue.ref(0); + const gapV = vue.reactive({ + x: null, + y: null + }); + const pinchStartLen = vue.ref(null); + let _scaleMovableView = null; + let movableViewContexts = []; + function _updateScale(e2) { + if (e2 && e2 !== 1) { + if (props2.scaleArea) { + movableViewContexts.forEach(function(item) { + item._setScale(e2); + }); + } else { + if (_scaleMovableView) { + _scaleMovableView._setScale(e2); + } + } + } + } + function _find(target, items = movableViewContexts) { + let root = rootRef.value; + function get(node) { + for (let i = 0; i < items.length; i++) { + const item = items[i]; + if (node === item.rootRef.value) { + return item; + } + } + if (node === root || node === document.body || node === document) { + return null; + } + return get(node.parentNode); + } + return get(target); + } + const _onTouchstart = withWebEvent((t2) => { + let i = t2.touches; + if (i) { + if (i.length > 1) { + let r = { + x: i[1].pageX - i[0].pageX, + y: i[1].pageY - i[0].pageY + }; + pinchStartLen.value = calc(r); + gapV.x = r.x; + gapV.y = r.y; + if (!props2.scaleArea) { + let touch0 = _find(i[0].target); + let touch1 = _find(i[1].target); + _scaleMovableView = touch0 && touch0 === touch1 ? touch0 : null; + } + } } - const srcVal = imgSrc.value; - return `background-image:${srcVal ? 'url("' + srcVal + '")' : "none"};background-position:${position};background-size:${size};background-repeat:no-repeat;`; - }); - const state = vue.reactive({ - rootEl: rootRef, - src: vue.computed(() => props2.src ? getRealPath(props2.src) : ""), - origWidth: 0, - origHeight: 0, - origStyle: { - width: "", - height: "" - }, - modeStyle: modeStyleRef, - imgSrc }); - return state; -} -function useImageLoader(state, { - trigger, - fixSize -}) { - let img; - const setState = (width = 0, height = 0, imgSrc = "") => { - state.origWidth = width; - state.origHeight = height; - state.imgSrc = imgSrc; - }; - const loadImage = (src) => { - if (!src) { - resetImage(); - setState(); - return; + const _onTouchmove = withWebEvent((t2) => { + let n = t2.touches; + if (n) { + if (n.length > 1) { + t2.preventDefault(); + let i = { + x: n[1].pageX - n[0].pageX, + y: n[1].pageY - n[0].pageY + }; + if (gapV.x !== null && pinchStartLen.value && pinchStartLen.value > 0) { + let r = calc(i) / pinchStartLen.value; + _updateScale(r); + } + gapV.x = i.x; + gapV.y = i.y; + } } - if (!img) { - img = new Image(); + }); + const _onTouchend = withWebEvent((e2) => { + let t2 = e2.touches; + if (!(t2 && t2.length)) { + if (e2.changedTouches) { + gapV.x = 0; + gapV.y = 0; + pinchStartLen.value = null; + if (props2.scaleArea) { + movableViewContexts.forEach(function(item) { + item._endScale(); + }); + } else { + if (_scaleMovableView) { + _scaleMovableView._endScale(); + } + } + } } - img.onload = (evt) => { - const { - width, - height - } = img; - setState(width, height, src); - fixSize(); - resetImage(); - trigger("load", evt, { - width, - height - }); - }; - img.onerror = (evt) => { - setState(); - resetImage(); - trigger("error", evt, { - errMsg: `GET ${state.src} 404 (Not Found)` - }); - }; - img.src = src; - }; - const resetImage = () => { - if (img) { - img.onload = null; - img.onerror = null; - img = null; + }); + function _resize() { + _getWH(); + movableViewContexts.forEach(function(item, index2) { + item.setParent(); + }); + } + function _getWH() { + let style = window.getComputedStyle(rootRef.value); + let rect = rootRef.value.getBoundingClientRect(); + width.value = rect.width - ["Left", "Right"].reduce(function(all, item) { + const LEFT = "border" + item + "Width"; + const RIGHT = "padding" + item; + return all + parseFloat(style[LEFT]) + parseFloat(style[RIGHT]); + }, 0); + height.value = rect.height - ["Top", "Bottom"].reduce(function(all, item) { + const TOP = "border" + item + "Width"; + const BOTTOM = "padding" + item; + return all + parseFloat(style[TOP]) + parseFloat(style[BOTTOM]); + }, 0); + } + vue.provide("movableAreaWidth", width); + vue.provide("movableAreaHeight", height); + return { + setContexts(contexts) { + movableViewContexts = contexts; + }, + events: { + _onTouchstart, + _onTouchmove, + _onTouchend, + _resize } }; - vue.watch(() => state.src, (value) => loadImage(value)); -} -function fixNumber(num) { - return num; } -function useImageSize(rootRef, props2, state) { - const fixSize = () => { - const { - mode: mode2 - } = props2; - const names = FIX_MODES[mode2]; - if (!names) { - return; - } - const { - origWidth, - origHeight - } = state; - const ratio = origWidth && origHeight ? origWidth / origHeight : 0; - if (!ratio) { - return; - } - const rootEl = rootRef.value; - const rect = rootEl.getBoundingClientRect(); - const value = rect[names[0]]; - if (value) { - rootEl.style[names[1]] = fixNumber(value / ratio) + "px"; +const addListenerToElement = function(element, type, callback, capture) { + element.addEventListener(type, ($event) => { + if (typeof callback === "function") { + if (callback($event) === false) { + if (typeof $event.cancelable !== "undefined" ? $event.cancelable : true) { + $event.preventDefault(); + } + $event.stopPropagation(); + } } - }; - const resetSize = () => { - const { - style - } = rootRef.value; - const { - origStyle: { - width, - height + }, { + passive: false + }); +}; +function useTouchtrack(element, method, useCancel) { + let x0 = 0; + let y0 = 0; + let x1 = 0; + let y1 = 0; + const fn = function($event, state, x, y) { + if (method({ + target: $event.target, + currentTarget: $event.currentTarget, + preventDefault: $event.preventDefault.bind($event), + stopPropagation: $event.stopPropagation.bind($event), + touches: $event.touches, + changedTouches: $event.changedTouches, + detail: { + state, + x, + y, + dx: x - x0, + dy: y - y0, + ddx: x - x1, + ddy: y - y1, + timeStamp: $event.timeStamp } - } = state; - style.width = width; - style.height = height; + }) === false) { + return false; + } }; - vue.watch(() => props2.mode, (value, oldValue) => { - if (FIX_MODES[oldValue]) { - resetSize(); + let $eventOld = null; + let hasTouchStart; + let hasMouseDown; + addListenerToElement(element, "touchstart", function($event) { + hasTouchStart = true; + if ($event.touches.length === 1 && !$eventOld) { + $eventOld = $event; + x0 = x1 = $event.touches[0].pageX; + y0 = y1 = $event.touches[0].pageY; + return fn($event, "start", x0, y0); } - if (FIX_MODES[value]) { - fixSize(); + }); + addListenerToElement(element, "mousedown", function($event) { + hasMouseDown = true; + if (!hasTouchStart && !$eventOld) { + $eventOld = $event; + x0 = x1 = $event.pageX; + y0 = y1 = $event.pageY; + return fn($event, "start", x0, y0); } }); - return { - fixSize, - resetSize - }; -} -uniShared.passive(true); -function useUserAction() { - const state = vue.reactive({ - userAction: false + addListenerToElement(element, "touchmove", function($event) { + if ($event.touches.length === 1 && $eventOld) { + const res = fn($event, "move", $event.touches[0].pageX, $event.touches[0].pageY); + x1 = $event.touches[0].pageX; + y1 = $event.touches[0].pageY; + return res; + } }); - return { - state + const mouseMoveEventListener = function($event) { + if (!hasTouchStart && hasMouseDown && $eventOld) { + const res = fn($event, "move", $event.pageX, $event.pageY); + x1 = $event.pageX; + y1 = $event.pageY; + return res; + } }; -} -function useScopedAttrs() { - const state = vue.reactive({ - attrs: {} + document.addEventListener("mousemove", mouseMoveEventListener); + addListenerToElement(element, "touchend", function($event) { + if ($event.touches.length === 0 && $eventOld) { + hasTouchStart = false; + $eventOld = null; + return fn($event, "end", $event.changedTouches[0].pageX, $event.changedTouches[0].pageY); + } }); - return { - state - }; -} -function useFormField(nameKey, value) { - const uniForm = vue.inject(uniFormKey, false); - if (!uniForm) { - return; - } - const instance = vue.getCurrentInstance(); - const ctx = { - submit() { - const proxy = instance.proxy; - return [ - proxy[nameKey], - typeof value === "string" ? proxy[value] : value.value - ]; - }, - reset() { - if (typeof value === "string") { - instance.proxy[value] = ""; - } else { - value.value = ""; - } + const mouseUpEventListener = function($event) { + hasMouseDown = false; + if (!hasTouchStart && $eventOld) { + $eventOld = null; + return fn($event, "end", $event.pageX, $event.pageY); } }; - uniForm.addField(ctx); -} -const pageIds = []; -const UniViewJSBridgeSubscribe = function() { - const pageId = getCurrentPageId(); - if (pageIds.includes(pageId)) - return; - pageIds.push(pageId); - UniViewJSBridge.subscribe(pageId + ".getSelectedTextRange", function({pageId: pageId2, callbackId}) { - const activeElement = document.activeElement; - if (!activeElement) - return; - const tagName = activeElement.tagName.toLowerCase(); - const tagNames = ["input", "textarea"]; - const data = {}; - if (tagNames.includes(tagName)) { - data.start = activeElement.selectionStart; - data.end = activeElement.selectionEnd; + document.addEventListener("mouseup", mouseUpEventListener); + addListenerToElement(element, "touchcancel", function($event) { + if ($eventOld) { + hasTouchStart = false; + const $eventTemp = $eventOld; + $eventOld = null; + return fn($event, useCancel ? "cancel" : "end", $eventTemp.touches[0].pageX, $eventTemp.touches[0].pageY); } - UniViewJSBridge.publishHandler("onGetSelectedTextRange", { - callbackId, - data - }, pageId2); }); -}; -function getValueString(value) { - return value === null ? "" : String(value); } -const props$n = /* @__PURE__ */ shared.extend({}, { - name: { - type: String, - default: "" - }, - modelValue: { - type: [String, Number], - default: "" - }, - value: { - type: [String, Number], - default: "" - }, - disabled: { - type: [Boolean, String], - default: false - }, - autoFocus: { - type: [Boolean, String], - default: false - }, - focus: { - type: [Boolean, String], - default: false - }, - cursor: { - type: [Number, String], - default: -1 - }, - selectionStart: { - type: [Number, String], - default: -1 - }, - selectionEnd: { - type: [Number, String], - default: -1 - }, - type: { - type: String, - default: "text" - }, - password: { - type: [Boolean, String], - default: false - }, - placeholder: { - type: String, - default: "" - }, - placeholderStyle: { - type: String, - default: "" - }, - placeholderClass: { - type: String, - default: "" - }, - maxlength: { - type: [Number, String], - default: 140 - }, - confirmType: { - type: String, - default: "done" +function e(e2, t2, n) { + return e2 > t2 - n && e2 < t2 + n; +} +function t$1(t2, n) { + return e(t2, 0, n); +} +function Friction$1(e2, t2) { + this._m = e2; + this._f = 1e3 * t2; + this._startTime = 0; + this._v = 0; +} +Friction$1.prototype.setV = function(x, y) { + var n = Math.pow(Math.pow(x, 2) + Math.pow(y, 2), 0.5); + this._x_v = x; + this._y_v = y; + this._x_a = -this._f * this._x_v / n; + this._y_a = -this._f * this._y_v / n; + this._t = Math.abs(x / this._x_a) || Math.abs(y / this._y_a); + this._lastDt = null; + this._startTime = new Date().getTime(); +}; +Friction$1.prototype.setS = function(x, y) { + this._x_s = x; + this._y_s = y; +}; +Friction$1.prototype.s = function(t2) { + if (t2 === void 0) { + t2 = (new Date().getTime() - this._startTime) / 1e3; + } + if (t2 > this._t) { + t2 = this._t; + this._lastDt = t2; + } + var x = this._x_v * t2 + 0.5 * this._x_a * Math.pow(t2, 2) + this._x_s; + var y = this._y_v * t2 + 0.5 * this._y_a * Math.pow(t2, 2) + this._y_s; + if (this._x_a > 0 && x < this._endPositionX || this._x_a < 0 && x > this._endPositionX) { + x = this._endPositionX; + } + if (this._y_a > 0 && y < this._endPositionY || this._y_a < 0 && y > this._endPositionY) { + y = this._endPositionY; } -}, props$q); -const emit = [ - "input", - "focus", - "blur", - "update:value", - "update:modelValue", - "update:focus", - ...emit$1 -]; -function useBase(props2, rootRef, emit2) { - const fieldRef = vue.ref(null); - const trigger = useCustomEvent(rootRef, emit2); - const selectionStart = vue.computed(() => { - const selectionStart2 = Number(props2.selectionStart); - return isNaN(selectionStart2) ? -1 : selectionStart2; - }); - const selectionEnd = vue.computed(() => { - const selectionEnd2 = Number(props2.selectionEnd); - return isNaN(selectionEnd2) ? -1 : selectionEnd2; - }); - const cursor = vue.computed(() => { - const cursor2 = Number(props2.cursor); - return isNaN(cursor2) ? -1 : cursor2; - }); - const maxlength = vue.computed(() => { - var maxlength2 = Number(props2.maxlength); - return isNaN(maxlength2) ? 140 : maxlength2; - }); - const value = getValueString(props2.modelValue) || getValueString(props2.value); - const state = vue.reactive({ - value, - valueOrigin: value, - maxlength, - focus: props2.focus, - composing: false, - selectionStart, - selectionEnd, - cursor - }); - vue.watch(() => state.focus, (val) => emit2("update:focus", val)); - vue.watch(() => state.maxlength, (val) => state.value = state.value.slice(0, val)); return { - fieldRef, - state, - trigger + x, + y }; -} -function useValueSync(props2, state, emit2, trigger) { - const valueChangeFn = uniShared.debounce((val) => { - state.value = getValueString(val); - }, 100); - vue.watch(() => props2.modelValue, valueChangeFn); - vue.watch(() => props2.value, valueChangeFn); - const triggerInputFn = throttle((event, detail) => { - emit2("update:modelValue", detail.value); - emit2("update:value", detail.value); - trigger("input", event, detail); - }, 100); - const triggerInput = (event, detail, force) => { - valueChangeFn.cancel(); - triggerInputFn(event, detail); - if (force) { - triggerInputFn.flush(); - } +}; +Friction$1.prototype.ds = function(t2) { + if (t2 === void 0) { + t2 = (new Date().getTime() - this._startTime) / 1e3; + } + if (t2 > this._t) { + t2 = this._t; + } + return { + dx: this._x_v + this._x_a * t2, + dy: this._y_v + this._y_a * t2 }; +}; +Friction$1.prototype.delta = function() { return { - trigger, - triggerInput + x: -1.5 * Math.pow(this._x_v, 2) / this._x_a || 0, + y: -1.5 * Math.pow(this._y_v, 2) / this._y_a || 0 }; +}; +Friction$1.prototype.dt = function() { + return -this._x_v / this._x_a; +}; +Friction$1.prototype.done = function() { + var t2 = e(this.s().x, this._endPositionX) || e(this.s().y, this._endPositionY) || this._lastDt === this._t; + this._lastDt = null; + return t2; +}; +Friction$1.prototype.setEnd = function(x, y) { + this._endPositionX = x; + this._endPositionY = y; +}; +Friction$1.prototype.reconfigure = function(m, f2) { + this._m = m; + this._f = 1e3 * f2; +}; +function Spring$1(m, k, c) { + this._m = m; + this._k = k; + this._c = c; + this._solution = null; + this._endPosition = 0; + this._startTime = 0; } -function useAutoFocus(props2, fieldRef) { - useUserAction(); - const needFocus = vue.computed(() => props2.autoFocus || props2.focus); - function focus() { - if (!needFocus.value) { - return; - } - const field = fieldRef.value; - if (!field || false) { - setTimeout(focus, 100); - return; - } - { - field.focus(); - } - } - function blur() { - const field = fieldRef.value; - if (field) { - field.blur(); - } - } - vue.watch(() => props2.focus, (value) => { - if (value) { - focus(); - } else { - blur(); - } - }); -} -function useEvent(fieldRef, state, trigger, triggerInput, beforeInput) { - function checkSelection() { - const field = fieldRef.value; - if (field && state.focus && state.selectionStart > -1 && state.selectionEnd > -1) { - field.selectionStart = state.selectionStart; - field.selectionEnd = state.selectionEnd; - } - } - function checkCursor() { - const field = fieldRef.value; - if (field && state.focus && state.selectionStart < 0 && state.selectionEnd < 0 && state.cursor > -1) { - field.selectionEnd = field.selectionStart = state.cursor; - } - } - function initField() { - const field = fieldRef.value; - const onFocus = function(event) { - state.focus = true; - trigger("focus", event, { - value: state.value - }); - checkSelection(); - checkCursor(); - }; - const onInput = function(event, force) { - event.stopPropagation(); - if (typeof beforeInput === "function" && beforeInput(event, state) === false) { - return; - } - state.value = field.value; - if (!state.composing) { - triggerInput(event, { - value: field.value, - cursor: field.selectionEnd - }, force); +Spring$1.prototype._solve = function(e2, t2) { + var n = this._c; + var i = this._m; + var r = this._k; + var o2 = n * n - 4 * i * r; + if (o2 === 0) { + const a2 = -n / (2 * i); + const s = e2; + const l = t2 / (a2 * e2); + return { + x: function(e3) { + return (s + l * e3) * Math.pow(Math.E, a2 * e3); + }, + dx: function(e3) { + var t3 = Math.pow(Math.E, a2 * e3); + return a2 * (s + l * e3) * t3 + l * t3; } }; - const onBlur = function(event) { - if (state.composing) { - state.composing = false; - onInput(event, true); + } + if (o2 > 0) { + const c = (-n - Math.sqrt(o2)) / (2 * i); + const u = (-n + Math.sqrt(o2)) / (2 * i); + const d = (t2 - c * e2) / (u - c); + const h = e2 - d; + return { + x: function(e3) { + var t3; + var n2; + if (e3 === this._t) { + t3 = this._powER1T; + n2 = this._powER2T; + } + this._t = e3; + if (!t3) { + t3 = this._powER1T = Math.pow(Math.E, c * e3); + } + if (!n2) { + n2 = this._powER2T = Math.pow(Math.E, u * e3); + } + return h * t3 + d * n2; + }, + dx: function(e3) { + var t3; + var n2; + if (e3 === this._t) { + t3 = this._powER1T; + n2 = this._powER2T; + } + this._t = e3; + if (!t3) { + t3 = this._powER1T = Math.pow(Math.E, c * e3); + } + if (!n2) { + n2 = this._powER2T = Math.pow(Math.E, u * e3); + } + return h * c * t3 + d * u * n2; } - state.focus = false; - trigger("blur", event, { - value: state.value, - cursor: event.target.selectionEnd - }); }; - field.addEventListener("change", (event) => event.stopPropagation()); - field.addEventListener("focus", onFocus); - field.addEventListener("blur", onBlur); - field.addEventListener("input", onInput); - field.addEventListener("compositionstart", (event) => { - event.stopPropagation(); - state.composing = true; - }); - field.addEventListener("compositionend", (event) => { - event.stopPropagation(); - if (state.composing) { - state.composing = false; - onInput(event); - } - }); } - vue.watch([() => state.selectionStart, () => state.selectionEnd], checkSelection); - vue.watch(() => state.cursor, checkCursor); - vue.watch(() => fieldRef.value, initField); -} -function useField(props2, rootRef, emit2, beforeInput) { - UniViewJSBridgeSubscribe(); - const {fieldRef, state, trigger} = useBase(props2, rootRef, emit2); - const {triggerInput} = useValueSync(props2, state, emit2, trigger); - useAutoFocus(props2, fieldRef); - useKeyboard$1(props2, fieldRef); - const {state: scopedAttrsState} = useScopedAttrs(); - useFormField("name", state); - useEvent(fieldRef, state, trigger, triggerInput, beforeInput); - const fixDisabledColor = false; + var p2 = Math.sqrt(4 * i * r - n * n) / (2 * i); + var f2 = -n / 2 * i; + var v2 = e2; + var g2 = (t2 - f2 * e2) / p2; return { - fieldRef, - state, - scopedAttrsState, - fixDisabledColor, - trigger + x: function(e3) { + return Math.pow(Math.E, f2 * e3) * (v2 * Math.cos(p2 * e3) + g2 * Math.sin(p2 * e3)); + }, + dx: function(e3) { + var t3 = Math.pow(Math.E, f2 * e3); + var n2 = Math.cos(p2 * e3); + var i2 = Math.sin(p2 * e3); + return t3 * (g2 * p2 * n2 - v2 * p2 * i2) + f2 * t3 * (g2 * i2 + v2 * n2); + } }; -} -const props$m = /* @__PURE__ */ shared.extend({}, props$n, { - placeholderClass: { - type: String, - default: "input-placeholder" +}; +Spring$1.prototype.x = function(e2) { + if (e2 === void 0) { + e2 = (new Date().getTime() - this._startTime) / 1e3; + } + return this._solution ? this._endPosition + this._solution.x(e2) : 0; +}; +Spring$1.prototype.dx = function(e2) { + if (e2 === void 0) { + e2 = (new Date().getTime() - this._startTime) / 1e3; + } + return this._solution ? this._solution.dx(e2) : 0; +}; +Spring$1.prototype.setEnd = function(e2, n, i) { + if (!i) { + i = new Date().getTime(); } -}); -var Input = /* @__PURE__ */ defineBuiltInComponent({ - name: "Input", - props: props$m, - emits: ["confirm", ...emit], - setup(props2, { - emit: emit2 - }) { - const INPUT_TYPES = ["text", "number", "idcard", "digit", "password"]; - const type = vue.computed(() => { - let type2 = ""; - switch (props2.type) { - case "text": - if (props2.confirmType === "search") { - type2 = "search"; - } - break; - case "idcard": - type2 = "text"; - break; - case "digit": - type2 = "number"; - break; - default: - type2 = ~INPUT_TYPES.includes(props2.type) ? props2.type : "text"; - break; - } - return props2.password ? "password" : type2; - }); - const valid = vue.ref(true); - const rootRef = vue.ref(null); - const { - fieldRef, - state, - scopedAttrsState, - fixDisabledColor, - trigger - } = useField(props2, rootRef, emit2, (event, state2) => { - const input = event.target; - if (NUMBER_TYPES.includes(props2.type)) { - valid.value = input.validity && input.validity.valid; + if (e2 !== this._endPosition || !t$1(n, 0.1)) { + n = n || 0; + var r = this._endPosition; + if (this._solution) { + if (t$1(n, 0.1)) { + n = this._solution.dx((i - this._startTime) / 1e3); } - if (type.value === "number") { - const maxlength = state2.maxlength; - if (maxlength > 0 && input.value.length > maxlength) { - input.value = input.value.slice(0, maxlength); - state2.value = input.value; - return false; - } + r = this._solution.x((i - this._startTime) / 1e3); + if (t$1(n, 0.1)) { + n = 0; } - }); - const NUMBER_TYPES = ["number", "digit"]; - const step = vue.computed(() => NUMBER_TYPES.includes(props2.type) ? "0.000000000000000001" : ""); - function onKeyUpEnter(event) { - if (event.key !== "Enter") { - return; + if (t$1(r, 0.1)) { + r = 0; } - event.stopPropagation(); - trigger("confirm", event, { - value: event.target.value - }); + r += this._endPosition; + } + if (!(this._solution && t$1(r - e2, 0.1) && t$1(n, 0.1))) { + this._endPosition = e2; + this._solution = this._solve(r - this._endPosition, n); + this._startTime = i; } - return () => { - let inputNode = props2.disabled && fixDisabledColor ? vue.createVNode("input", { - "ref": fieldRef, - "value": state.value, - "tabindex": "-1", - "readonly": !!props2.disabled, - "type": type.value, - "maxlength": state.maxlength, - "step": step.value, - "class": "uni-input-input", - "onFocus": (event) => event.target.blur() - }, null, 40, ["value", "readonly", "type", "maxlength", "step", "onFocus"]) : vue.createVNode("input", { - "ref": fieldRef, - "value": state.value, - "disabled": !!props2.disabled, - "type": type.value, - "maxlength": state.maxlength, - "step": step.value, - "enterkeyhint": props2.confirmType, - "class": "uni-input-input", - "autocomplete": "off", - "onKeyup": onKeyUpEnter - }, null, 40, ["value", "disabled", "type", "maxlength", "step", "enterkeyhint", "onKeyup"]); - return vue.createVNode("uni-input", { - "ref": rootRef - }, [vue.createVNode("div", { - "class": "uni-input-wrapper" - }, [vue.withDirectives(vue.createVNode("div", vue.mergeProps(scopedAttrsState.attrs, { - "style": props2.placeholderStyle, - "class": ["uni-input-placeholder", props2.placeholderClass] - }), [props2.placeholder], 16), [[vue.vShow, !(state.value.length || !valid.value)]]), props2.confirmType === "search" ? vue.createVNode("form", { - "action": "", - "onSubmit": (event) => event.preventDefault(), - "class": "uni-input-form" - }, [inputNode], 40, ["onSubmit"]) : inputNode])], 512); - }; } -}); -function entries(obj) { - return Object.keys(obj).map((key) => [key, obj[key]]); -} -const DEFAULT_EXCLUDE_KEYS = ["class", "style"]; -const LISTENER_PREFIX = /^on[A-Z]+/; -const useAttrs = (params = {}) => { - const {excludeListeners = false, excludeKeys = []} = params; - const instance = vue.getCurrentInstance(); - const attrs = vue.shallowRef({}); - const listeners = vue.shallowRef({}); - const excludeAttrs = vue.shallowRef({}); - const allExcludeKeys = excludeKeys.concat(DEFAULT_EXCLUDE_KEYS); - instance.attrs = vue.reactive(instance.attrs); - vue.watchEffect(() => { - const res = entries(instance.attrs).reduce((acc, [key, val]) => { - if (allExcludeKeys.includes(key)) { - acc.exclude[key] = val; - } else if (LISTENER_PREFIX.test(key)) { - if (!excludeListeners) { - acc.attrs[key] = val; - } - acc.listeners[key] = val; - } else { - acc.attrs[key] = val; - } - return acc; - }, { - exclude: {}, - attrs: {}, - listeners: {} - }); - attrs.value = res.attrs; - listeners.value = res.listeners; - excludeAttrs.value = res.exclude; - }); - return {$attrs: attrs, $listeners: listeners, $excludeAttrs: excludeAttrs}; }; -function initScrollBounce() { -} -function disableScrollBounce({disable}) { -} -function flatVNode(nodes) { - const array = []; - if (Array.isArray(nodes)) { - nodes.forEach((vnode) => { - if (vue.isVNode(vnode)) { - if (vnode.type === vue.Fragment) { - array.push(...flatVNode(vnode.children)); - } else { - array.push(vnode); - } - } else if (Array.isArray(vnode)) { - array.push(...flatVNode(vnode)); - } - }); +Spring$1.prototype.snap = function(e2) { + this._startTime = new Date().getTime(); + this._endPosition = e2; + this._solution = { + x: function() { + return 0; + }, + dx: function() { + return 0; + } + }; +}; +Spring$1.prototype.done = function(n) { + if (!n) { + n = new Date().getTime(); } - return array; + return e(this.x(), this._endPosition, 0.1) && t$1(this.dx(), 0.1); +}; +Spring$1.prototype.reconfigure = function(m, t2, c) { + this._m = m; + this._k = t2; + this._c = c; + if (!this.done()) { + this._solution = this._solve(this.x() - this._endPosition, this.dx()); + this._startTime = new Date().getTime(); + } +}; +Spring$1.prototype.springConstant = function() { + return this._k; +}; +Spring$1.prototype.damping = function() { + return this._c; +}; +Spring$1.prototype.configuration = function() { + function e2(e3, t3) { + e3.reconfigure(1, t3, e3.damping()); + } + function t2(e3, t3) { + e3.reconfigure(1, e3.springConstant(), t3); + } + return [ + { + label: "Spring Constant", + read: this.springConstant.bind(this), + write: e2.bind(this, this), + min: 100, + max: 1e3 + }, + { + label: "Damping", + read: this.damping.bind(this), + write: t2.bind(this, this), + min: 1, + max: 500 + } + ]; +}; +function STD(e2, t2, n) { + this._springX = new Spring$1(e2, t2, n); + this._springY = new Spring$1(e2, t2, n); + this._springScale = new Spring$1(e2, t2, n); + this._startTime = 0; } -const props$l = { - scaleArea: { - type: Boolean, +STD.prototype.setEnd = function(e2, t2, n, i) { + var r = new Date().getTime(); + this._springX.setEnd(e2, i, r); + this._springY.setEnd(t2, i, r); + this._springScale.setEnd(n, i, r); + this._startTime = r; +}; +STD.prototype.x = function() { + var e2 = (new Date().getTime() - this._startTime) / 1e3; + return { + x: this._springX.x(e2), + y: this._springY.x(e2), + scale: this._springScale.x(e2) + }; +}; +STD.prototype.done = function() { + var e2 = new Date().getTime(); + return this._springX.done(e2) && this._springY.done(e2) && this._springScale.done(e2); +}; +STD.prototype.reconfigure = function(e2, t2, n) { + this._springX.reconfigure(e2, t2, n); + this._springY.reconfigure(e2, t2, n); + this._springScale.reconfigure(e2, t2, n); +}; +const props$k = { + direction: { + type: String, + default: "none" + }, + inertia: { + type: [Boolean, String], + default: false + }, + outOfBounds: { + type: [Boolean, String], + default: false + }, + x: { + type: [Number, String], + default: 0 + }, + y: { + type: [Number, String], + default: 0 + }, + damping: { + type: [Number, String], + default: 20 + }, + friction: { + type: [Number, String], + default: 2 + }, + disabled: { + type: [Boolean, String], + default: false + }, + scale: { + type: [Boolean, String], default: false + }, + scaleMin: { + type: [Number, String], + default: 0.5 + }, + scaleMax: { + type: [Number, String], + default: 10 + }, + scaleValue: { + type: [Number, String], + default: 1 + }, + animation: { + type: [Boolean, String], + default: true } }; -var index$o = /* @__PURE__ */ defineBuiltInComponent({ - inheritAttrs: false, - name: "MovableArea", - props: props$l, +var index$n = /* @__PURE__ */ defineBuiltInComponent({ + name: "MovableView", + props: props$k, + emits: ["change", "scale"], setup(props2, { - slots + slots, + emit: emit2 }) { const rootRef = vue.ref(null); - const _isMounted = vue.ref(false); - let { - setContexts, - events: movableAreaEvents - } = useMovableAreaState(props2, rootRef); + const trigger = useCustomEvent(rootRef, emit2); const { - $listeners, - $attrs, - $excludeAttrs - } = useAttrs(); - const _listeners = $listeners.value; - let events = ["onTouchstart", "onTouchmove", "onTouchend"]; - events.forEach((event) => { - let existing = _listeners[event]; - let ours = movableAreaEvents[`_${event}`]; - _listeners[event] = existing ? [].concat(existing, ours) : ours; - }); - let movableViewItems = []; - const originMovableViewContexts = []; - function updateMovableViewContexts() { - const contexts = []; - for (let index2 = 0; index2 < movableViewItems.length; index2++) { - const movableViewItem = movableViewItems[index2]; - const movableViewContext = originMovableViewContexts.find((context) => movableViewItem.el === context.rootRef.value); - if (movableViewContext) { - contexts.push(vue.markRaw(movableViewContext)); - } - } - setContexts(contexts); - } - const addMovableViewContext = (movableViewContext) => { - originMovableViewContexts.push(movableViewContext); - updateMovableViewContexts(); - }; - const removeMovableViewContext = (movableViewContext) => { - const index2 = originMovableViewContexts.indexOf(movableViewContext); - if (index2 >= 0) { - originMovableViewContexts.splice(index2, 1); - updateMovableViewContexts(); - } - }; - vue.provide("_isMounted", _isMounted); - vue.provide("movableAreaRootRef", rootRef); - vue.provide("addMovableViewContext", addMovableViewContext); - vue.provide("removeMovableViewContext", removeMovableViewContext); + setParent + } = useMovableViewState(props2, trigger, rootRef); return () => { - const defaultSlots = slots.default && slots.default(); - movableViewItems = flatVNode(defaultSlots); - return vue.createVNode("uni-movable-area", vue.mergeProps({ + return vue.createVNode("uni-movable-view", { "ref": rootRef - }, $attrs.value, $excludeAttrs.value, _listeners), [vue.createVNode(ResizeSensor, { - "onReize": movableAreaEvents._resize - }, null, 8, ["onReize"]), movableViewItems], 16); + }, [vue.createVNode(ResizeSensor, { + "onResize": setParent + }, null, 8, ["onResize"]), slots.default && slots.default()], 512); }; } }); -function calc(e2) { - return Math.sqrt(e2.x * e2.x + e2.y * e2.y); +let requesting = false; +function _requestAnimationFrame(e2) { + if (!requesting) { + requesting = true; + requestAnimationFrame(function() { + e2(); + requesting = false; + }); + } } -function useMovableAreaState(props2, rootRef) { - const width = vue.ref(0); - const height = vue.ref(0); - const gapV = vue.reactive({ - x: null, - y: null - }); - const pinchStartLen = vue.ref(null); - let _scaleMovableView = null; - let movableViewContexts = []; - function _updateScale(e2) { - if (e2 && e2 !== 1) { - if (props2.scaleArea) { - movableViewContexts.forEach(function(item) { - item._setScale(e2); - }); - } else { - if (_scaleMovableView) { - _scaleMovableView._setScale(e2); - } - } - } +function p(t2, n) { + if (t2 === n) { + return 0; } - function _find(target, items = movableViewContexts) { - let root = rootRef.value; - function get(node) { - for (let i = 0; i < items.length; i++) { - const item = items[i]; - if (node === item.rootRef.value) { - return item; - } - } - if (node === root || node === document.body || node === document) { - return null; - } - return get(node.parentNode); - } - return get(target); + let i = t2.offsetLeft; + return t2.offsetParent ? i += p(t2.offsetParent, n) : 0; +} +function f(t2, n) { + if (t2 === n) { + return 0; } - const _onTouchstart = withWebEvent((t2) => { - let i = t2.touches; - if (i) { - if (i.length > 1) { - let r = { - x: i[1].pageX - i[0].pageX, - y: i[1].pageY - i[0].pageY - }; - pinchStartLen.value = calc(r); - gapV.x = r.x; - gapV.y = r.y; - if (!props2.scaleArea) { - let touch0 = _find(i[0].target); - let touch1 = _find(i[1].target); - _scaleMovableView = touch0 && touch0 === touch1 ? touch0 : null; - } - } + let i = t2.offsetTop; + return t2.offsetParent ? i += f(t2.offsetParent, n) : 0; +} +function v(a2, b) { + return +((1e3 * a2 - 1e3 * b) / 1e3).toFixed(1); +} +function g(friction, execute, endCallback) { + let record = { + id: 0, + cancelled: false + }; + let cancel = function(record2) { + if (record2 && record2.id) { + cancelAnimationFrame(record2.id); } - }); - const _onTouchmove = withWebEvent((t2) => { - let n = t2.touches; - if (n) { - if (n.length > 1) { - t2.preventDefault(); - let i = { - x: n[1].pageX - n[0].pageX, - y: n[1].pageY - n[0].pageY - }; - if (gapV.x !== null && pinchStartLen.value && pinchStartLen.value > 0) { - let r = calc(i) / pinchStartLen.value; - _updateScale(r); - } - gapV.x = i.x; - gapV.y = i.y; - } + if (record2) { + record2.cancelled = true; } - }); - const _onTouchend = withWebEvent((e2) => { - let t2 = e2.touches; - if (!(t2 && t2.length)) { - if (e2.changedTouches) { - gapV.x = 0; - gapV.y = 0; - pinchStartLen.value = null; - if (props2.scaleArea) { - movableViewContexts.forEach(function(item) { - item._endScale(); - }); - } else { - if (_scaleMovableView) { - _scaleMovableView._endScale(); - } + }; + function fn(record2, friction2, execute2, endCallback2) { + if (!record2 || !record2.cancelled) { + execute2(friction2); + let isDone = friction2.done(); + if (!isDone) { + if (!record2.cancelled) { + record2.id = requestAnimationFrame(fn.bind(null, record2, friction2, execute2, endCallback2)); } } + if (isDone && endCallback2) { + endCallback2(friction2); + } } - }); - function _resize() { - _getWH(); - movableViewContexts.forEach(function(item, index2) { - item.setParent(); - }); - } - function _getWH() { - let style = window.getComputedStyle(rootRef.value); - let rect = rootRef.value.getBoundingClientRect(); - width.value = rect.width - ["Left", "Right"].reduce(function(all, item) { - const LEFT = "border" + item + "Width"; - const RIGHT = "padding" + item; - return all + parseFloat(style[LEFT]) + parseFloat(style[RIGHT]); - }, 0); - height.value = rect.height - ["Top", "Bottom"].reduce(function(all, item) { - const TOP = "border" + item + "Width"; - const BOTTOM = "padding" + item; - return all + parseFloat(style[TOP]) + parseFloat(style[BOTTOM]); - }, 0); } - vue.provide("movableAreaWidth", width); - vue.provide("movableAreaHeight", height); + fn(record, friction, execute, endCallback); return { - setContexts(contexts) { - movableViewContexts = contexts; - }, - events: { - _onTouchstart, - _onTouchmove, - _onTouchend, - _resize - } + cancel: cancel.bind(null, record), + model: friction }; } -const addListenerToElement = function(element, type, callback, capture) { - element.addEventListener(type, ($event) => { - if (typeof callback === "function") { - if (callback($event) === false) { - if (typeof $event.cancelable !== "undefined" ? $event.cancelable : true) { - $event.preventDefault(); - } - $event.stopPropagation(); - } - } - }, { - passive: false +function _getPx(val) { + if (/\d+[ur]px$/i.test(val)) { + return uni.upx2px(parseFloat(val)); + } + return Number(val) || 0; +} +function useMovableViewState(props2, trigger, rootRef) { + const movableAreaWidth = vue.inject("movableAreaWidth", vue.ref(0)); + const movableAreaHeight = vue.inject("movableAreaHeight", vue.ref(0)); + const _isMounted = vue.inject("_isMounted", vue.ref(false)); + const movableAreaRootRef = vue.inject("movableAreaRootRef"); + vue.inject("addMovableViewContext", () => { }); -}; -function useTouchtrack(element, method, useCancel) { - let x0 = 0; - let y0 = 0; - let x1 = 0; - let y1 = 0; - const fn = function($event, state, x, y) { - if (method({ - target: $event.target, - currentTarget: $event.currentTarget, - preventDefault: $event.preventDefault.bind($event), - stopPropagation: $event.stopPropagation.bind($event), - touches: $event.touches, - changedTouches: $event.changedTouches, - detail: { - state, - x, - y, - dx: x - x0, - dy: y - y0, - ddx: x - x1, - ddy: y - y1, - timeStamp: $event.timeStamp - } - }) === false) { - return false; - } + vue.inject("removeMovableViewContext", () => { + }); + const xSync = vue.ref(_getPx(props2.x)); + const ySync = vue.ref(_getPx(props2.y)); + const scaleValueSync = vue.ref(Number(props2.scaleValue) || 1); + const width = vue.ref(0); + const height = vue.ref(0); + const minX = vue.ref(0); + const minY = vue.ref(0); + const maxX = vue.ref(0); + const maxY = vue.ref(0); + let _SFA = null; + const _offset = { + x: 0, + y: 0 }; - let $eventOld = null; - let hasTouchStart; - let hasMouseDown; - addListenerToElement(element, "touchstart", function($event) { - hasTouchStart = true; - if ($event.touches.length === 1 && !$eventOld) { - $eventOld = $event; - x0 = x1 = $event.touches[0].pageX; - y0 = y1 = $event.touches[0].pageY; - return fn($event, "start", x0, y0); - } + const _scaleOffset = { + x: 0, + y: 0 + }; + let _scale = 1; + let _translateX = 0; + let _translateY = 0; + const dampingNumber = vue.computed(() => { + let val = Number(props2.damping); + return isNaN(val) ? 20 : val; }); - addListenerToElement(element, "mousedown", function($event) { - hasMouseDown = true; - if (!hasTouchStart && !$eventOld) { - $eventOld = $event; - x0 = x1 = $event.pageX; - y0 = y1 = $event.pageY; - return fn($event, "start", x0, y0); - } + const frictionNumber = vue.computed(() => { + let val = Number(props2.friction); + return isNaN(val) || val <= 0 ? 2 : val; }); - addListenerToElement(element, "touchmove", function($event) { - if ($event.touches.length === 1 && $eventOld) { - const res = fn($event, "move", $event.touches[0].pageX, $event.touches[0].pageY); - x1 = $event.touches[0].pageX; - y1 = $event.touches[0].pageY; - return res; - } + const scaleMinNumber = vue.computed(() => { + let val = Number(props2.scaleMin); + return isNaN(val) ? 0.5 : val; }); - const mouseMoveEventListener = function($event) { - if (!hasTouchStart && hasMouseDown && $eventOld) { - const res = fn($event, "move", $event.pageX, $event.pageY); - x1 = $event.pageX; - y1 = $event.pageY; - return res; - } - }; - document.addEventListener("mousemove", mouseMoveEventListener); - addListenerToElement(element, "touchend", function($event) { - if ($event.touches.length === 0 && $eventOld) { - hasTouchStart = false; - $eventOld = null; - return fn($event, "end", $event.changedTouches[0].pageX, $event.changedTouches[0].pageY); - } + const scaleMaxNumber = vue.computed(() => { + let val = Number(props2.scaleMax); + return isNaN(val) ? 10 : val; }); - const mouseUpEventListener = function($event) { - hasMouseDown = false; - if (!hasTouchStart && $eventOld) { - $eventOld = null; - return fn($event, "end", $event.pageX, $event.pageY); - } - }; - document.addEventListener("mouseup", mouseUpEventListener); - addListenerToElement(element, "touchcancel", function($event) { - if ($eventOld) { - hasTouchStart = false; - const $eventTemp = $eventOld; - $eventOld = null; - return fn($event, useCancel ? "cancel" : "end", $eventTemp.touches[0].pageX, $eventTemp.touches[0].pageY); - } + const xMove = vue.computed(() => props2.direction === "all" || props2.direction === "horizontal"); + const yMove = vue.computed(() => props2.direction === "all" || props2.direction === "vertical"); + const _STD = new STD(1, 9 * Math.pow(dampingNumber.value, 2) / 40, dampingNumber.value); + new Friction$1(1, frictionNumber.value); + vue.watch(() => props2.x, (val) => { + xSync.value = _getPx(val); }); -} -function e(e2, t2, n) { - return e2 > t2 - n && e2 < t2 + n; -} -function t$1(t2, n) { - return e(t2, 0, n); -} -function Friction$1(e2, t2) { - this._m = e2; - this._f = 1e3 * t2; - this._startTime = 0; - this._v = 0; -} -Friction$1.prototype.setV = function(x, y) { - var n = Math.pow(Math.pow(x, 2) + Math.pow(y, 2), 0.5); - this._x_v = x; - this._y_v = y; - this._x_a = -this._f * this._x_v / n; - this._y_a = -this._f * this._y_v / n; - this._t = Math.abs(x / this._x_a) || Math.abs(y / this._y_a); - this._lastDt = null; - this._startTime = new Date().getTime(); -}; -Friction$1.prototype.setS = function(x, y) { - this._x_s = x; - this._y_s = y; -}; -Friction$1.prototype.s = function(t2) { - if (t2 === void 0) { - t2 = (new Date().getTime() - this._startTime) / 1e3; - } - if (t2 > this._t) { - t2 = this._t; - this._lastDt = t2; + vue.watch(() => props2.y, (val) => { + ySync.value = _getPx(val); + }); + vue.watch(xSync, (val) => { + _setX(val); + }); + vue.watch(ySync, (val) => { + _setY(val); + }); + vue.watch(() => props2.scaleValue, (val) => { + scaleValueSync.value = Number(val) || 0; + }); + vue.watch(scaleValueSync, (val) => { + _setScaleValue(val); + }); + vue.watch(scaleMinNumber, () => { + _setScaleMinOrMax(); + }); + vue.watch(scaleMaxNumber, () => { + _setScaleMinOrMax(); + }); + function FAandSFACancel() { + if (_SFA) { + _SFA.cancel(); + } } - var x = this._x_v * t2 + 0.5 * this._x_a * Math.pow(t2, 2) + this._x_s; - var y = this._y_v * t2 + 0.5 * this._y_a * Math.pow(t2, 2) + this._y_s; - if (this._x_a > 0 && x < this._endPositionX || this._x_a < 0 && x > this._endPositionX) { - x = this._endPositionX; + function _setX(val) { + if (xMove.value) { + if (val + _scaleOffset.x === _translateX) { + return _translateX; + } else { + if (_SFA) { + _SFA.cancel(); + } + _animationTo(val + _scaleOffset.x, ySync.value + _scaleOffset.y, _scale); + } + } + return val; } - if (this._y_a > 0 && y < this._endPositionY || this._y_a < 0 && y > this._endPositionY) { - y = this._endPositionY; + function _setY(val) { + if (yMove.value) { + if (val + _scaleOffset.y === _translateY) { + return _translateY; + } else { + if (_SFA) { + _SFA.cancel(); + } + _animationTo(xSync.value + _scaleOffset.x, val + _scaleOffset.y, _scale); + } + } + return val; } - return { - x, - y - }; -}; -Friction$1.prototype.ds = function(t2) { - if (t2 === void 0) { - t2 = (new Date().getTime() - this._startTime) / 1e3; + function _setScaleMinOrMax() { + if (!props2.scale) { + return false; + } + _updateScale(_scale, true); } - if (t2 > this._t) { - t2 = this._t; + function _setScaleValue(scale) { + if (!props2.scale) { + return false; + } + scale = _adjustScale(scale); + _updateScale(scale, true); + return scale; } - return { - dx: this._x_v + this._x_a * t2, - dy: this._y_v + this._y_a * t2 - }; -}; -Friction$1.prototype.delta = function() { - return { - x: -1.5 * Math.pow(this._x_v, 2) / this._x_a || 0, - y: -1.5 * Math.pow(this._y_v, 2) / this._y_a || 0 - }; -}; -Friction$1.prototype.dt = function() { - return -this._x_v / this._x_a; -}; -Friction$1.prototype.done = function() { - var t2 = e(this.s().x, this._endPositionX) || e(this.s().y, this._endPositionY) || this._lastDt === this._t; - this._lastDt = null; - return t2; -}; -Friction$1.prototype.setEnd = function(x, y) { - this._endPositionX = x; - this._endPositionY = y; -}; -Friction$1.prototype.reconfigure = function(m, f2) { - this._m = m; - this._f = 1e3 * f2; -}; -function Spring$1(m, k, c) { - this._m = m; - this._k = k; - this._c = c; - this._solution = null; - this._endPosition = 0; - this._startTime = 0; -} -Spring$1.prototype._solve = function(e2, t2) { - var n = this._c; - var i = this._m; - var r = this._k; - var o2 = n * n - 4 * i * r; - if (o2 === 0) { - const a2 = -n / (2 * i); - const s = e2; - const l = t2 / (a2 * e2); - return { - x: function(e3) { - return (s + l * e3) * Math.pow(Math.E, a2 * e3); - }, - dx: function(e3) { - var t3 = Math.pow(Math.E, a2 * e3); - return a2 * (s + l * e3) * t3 + l * t3; + function _getLimitXY(x, y) { + let outOfBounds = false; + if (x > maxX.value) { + x = maxX.value; + outOfBounds = true; + } else { + if (x < minX.value) { + x = minX.value; + outOfBounds = true; } - }; - } - if (o2 > 0) { - const c = (-n - Math.sqrt(o2)) / (2 * i); - const u = (-n + Math.sqrt(o2)) / (2 * i); - const d = (t2 - c * e2) / (u - c); - const h = e2 - d; - return { - x: function(e3) { - var t3; - var n2; - if (e3 === this._t) { - t3 = this._powER1T; - n2 = this._powER2T; - } - this._t = e3; - if (!t3) { - t3 = this._powER1T = Math.pow(Math.E, c * e3); - } - if (!n2) { - n2 = this._powER2T = Math.pow(Math.E, u * e3); - } - return h * t3 + d * n2; - }, - dx: function(e3) { - var t3; - var n2; - if (e3 === this._t) { - t3 = this._powER1T; - n2 = this._powER2T; - } - this._t = e3; - if (!t3) { - t3 = this._powER1T = Math.pow(Math.E, c * e3); - } - if (!n2) { - n2 = this._powER2T = Math.pow(Math.E, u * e3); - } - return h * c * t3 + d * u * n2; + } + if (y > maxY.value) { + y = maxY.value; + outOfBounds = true; + } else { + if (y < minY.value) { + y = minY.value; + outOfBounds = true; } + } + return { + x, + y, + outOfBounds }; } - var p2 = Math.sqrt(4 * i * r - n * n) / (2 * i); - var f2 = -n / 2 * i; - var v2 = e2; - var g2 = (t2 - f2 * e2) / p2; - return { - x: function(e3) { - return Math.pow(Math.E, f2 * e3) * (v2 * Math.cos(p2 * e3) + g2 * Math.sin(p2 * e3)); - }, - dx: function(e3) { - var t3 = Math.pow(Math.E, f2 * e3); - var n2 = Math.cos(p2 * e3); - var i2 = Math.sin(p2 * e3); - return t3 * (g2 * p2 * n2 - v2 * p2 * i2) + f2 * t3 * (g2 * i2 + v2 * n2); - } - }; -}; -Spring$1.prototype.x = function(e2) { - if (e2 === void 0) { - e2 = (new Date().getTime() - this._startTime) / 1e3; + function _updateOffset() { + _offset.x = p(rootRef.value, movableAreaRootRef.value); + _offset.y = f(rootRef.value, movableAreaRootRef.value); } - return this._solution ? this._endPosition + this._solution.x(e2) : 0; -}; -Spring$1.prototype.dx = function(e2) { - if (e2 === void 0) { - e2 = (new Date().getTime() - this._startTime) / 1e3; + function _updateWH(scale) { + scale = scale || _scale; + scale = _adjustScale(scale); + let rect = rootRef.value.getBoundingClientRect(); + height.value = rect.height / _scale; + width.value = rect.width / _scale; + let _height = height.value * scale; + let _width = width.value * scale; + _scaleOffset.x = (_width - width.value) / 2; + _scaleOffset.y = (_height - height.value) / 2; } - return this._solution ? this._solution.dx(e2) : 0; -}; -Spring$1.prototype.setEnd = function(e2, n, i) { - if (!i) { - i = new Date().getTime(); + function _updateBoundary() { + let x = 0 - _offset.x + _scaleOffset.x; + let _width = movableAreaWidth.value - width.value - _offset.x - _scaleOffset.x; + minX.value = Math.min(x, _width); + maxX.value = Math.max(x, _width); + let y = 0 - _offset.y + _scaleOffset.y; + let _height = movableAreaHeight.value - height.value - _offset.y - _scaleOffset.y; + minY.value = Math.min(y, _height); + maxY.value = Math.max(y, _height); } - if (e2 !== this._endPosition || !t$1(n, 0.1)) { - n = n || 0; - var r = this._endPosition; - if (this._solution) { - if (t$1(n, 0.1)) { - n = this._solution.dx((i - this._startTime) / 1e3); - } - r = this._solution.x((i - this._startTime) / 1e3); - if (t$1(n, 0.1)) { - n = 0; + function _updateScale(scale, animat) { + if (props2.scale) { + scale = _adjustScale(scale); + _updateWH(scale); + _updateBoundary(); + const limitXY = _getLimitXY(_translateX, _translateY); + const x = limitXY.x; + const y = limitXY.y; + if (animat) { + _animationTo(x, y, scale, "", true, true); + } else { + _requestAnimationFrame(function() { + _setTransform(x, y, scale, "", true, true); + }); } - if (t$1(r, 0.1)) { - r = 0; + } + } + function _adjustScale(scale) { + scale = Math.max(0.5, scaleMinNumber.value, scale); + scale = Math.min(10, scaleMaxNumber.value, scale); + return scale; + } + function _animationTo(x, y, scale, source, r, o2) { + FAandSFACancel(); + if (!xMove.value) { + x = _translateX; + } + if (!yMove.value) { + y = _translateY; + } + if (!props2.scale) { + scale = _scale; + } + let limitXY = _getLimitXY(x, y); + x = limitXY.x; + y = limitXY.y; + if (!props2.animation) { + _setTransform(x, y, scale, source, r, o2); + return; + } + _STD._springX._solution = null; + _STD._springY._solution = null; + _STD._springScale._solution = null; + _STD._springX._endPosition = _translateX; + _STD._springY._endPosition = _translateY; + _STD._springScale._endPosition = _scale; + _STD.setEnd(x, y, scale, 1); + _SFA = g(_STD, function() { + let data = _STD.x(); + let x2 = data.x; + let y2 = data.y; + let scale2 = data.scale; + _setTransform(x2, y2, scale2, source, r, o2); + }, function() { + _SFA.cancel(); + }); + } + function _setTransform(x, y, scale, source = "", r, o2) { + if (!(x !== null && x.toString() !== "NaN" && typeof x === "number")) { + x = _translateX || 0; + } + if (!(y !== null && y.toString() !== "NaN" && typeof y === "number")) { + y = _translateY || 0; + } + x = Number(x.toFixed(1)); + y = Number(y.toFixed(1)); + scale = Number(scale.toFixed(1)); + if (!(_translateX === x && _translateY === y)) { + if (!r) { + trigger("change", {}, { + x: v(x, _scaleOffset.x), + y: v(y, _scaleOffset.y), + source + }); } - r += this._endPosition; } - if (!(this._solution && t$1(r - e2, 0.1) && t$1(n, 0.1))) { - this._endPosition = e2; - this._solution = this._solve(r - this._endPosition, n); - this._startTime = i; + if (!props2.scale) { + scale = _scale; } - } -}; -Spring$1.prototype.snap = function(e2) { - this._startTime = new Date().getTime(); - this._endPosition = e2; - this._solution = { - x: function() { - return 0; - }, - dx: function() { - return 0; + scale = _adjustScale(scale); + scale = +scale.toFixed(3); + if (o2 && scale !== _scale) { + trigger("scale", {}, { + x, + y, + scale + }); } - }; -}; -Spring$1.prototype.done = function(n) { - if (!n) { - n = new Date().getTime(); - } - return e(this.x(), this._endPosition, 0.1) && t$1(this.dx(), 0.1); -}; -Spring$1.prototype.reconfigure = function(m, t2, c) { - this._m = m; - this._k = t2; - this._c = c; - if (!this.done()) { - this._solution = this._solve(this.x() - this._endPosition, this.dx()); - this._startTime = new Date().getTime(); - } -}; -Spring$1.prototype.springConstant = function() { - return this._k; -}; -Spring$1.prototype.damping = function() { - return this._c; -}; -Spring$1.prototype.configuration = function() { - function e2(e3, t3) { - e3.reconfigure(1, t3, e3.damping()); - } - function t2(e3, t3) { - e3.reconfigure(1, e3.springConstant(), t3); + let transform = "translateX(" + x + "px) translateY(" + y + "px) translateZ(0px) scale(" + scale + ")"; + rootRef.value.style.transform = transform; + rootRef.value.style.webkitTransform = transform; + _translateX = x; + _translateY = y; + _scale = scale; } - return [ - { - label: "Spring Constant", - read: this.springConstant.bind(this), - write: e2.bind(this, this), - min: 100, - max: 1e3 - }, - { - label: "Damping", - read: this.damping.bind(this), - write: t2.bind(this, this), - min: 1, - max: 500 + function setParent() { + if (!_isMounted.value) { + return; } - ]; -}; -function STD(e2, t2, n) { - this._springX = new Spring$1(e2, t2, n); - this._springY = new Spring$1(e2, t2, n); - this._springScale = new Spring$1(e2, t2, n); - this._startTime = 0; -} -STD.prototype.setEnd = function(e2, t2, n, i) { - var r = new Date().getTime(); - this._springX.setEnd(e2, i, r); - this._springY.setEnd(t2, i, r); - this._springScale.setEnd(n, i, r); - this._startTime = r; -}; -STD.prototype.x = function() { - var e2 = (new Date().getTime() - this._startTime) / 1e3; + FAandSFACancel(); + let scale = props2.scale ? scaleValueSync.value : 1; + _updateOffset(); + _updateWH(scale); + _updateBoundary(); + _translateX = xSync.value + _scaleOffset.x; + _translateY = ySync.value + _scaleOffset.y; + let limitXY = _getLimitXY(_translateX, _translateY); + let x = limitXY.x; + let y = limitXY.y; + _setTransform(x, y, scale, "", true); + } return { - x: this._springX.x(e2), - y: this._springY.x(e2), - scale: this._springScale.x(e2) + setParent }; -}; -STD.prototype.done = function() { - var e2 = new Date().getTime(); - return this._springX.done(e2) && this._springY.done(e2) && this._springScale.done(e2); -}; -STD.prototype.reconfigure = function(e2, t2, n) { - this._springX.reconfigure(e2, t2, n); - this._springY.reconfigure(e2, t2, n); - this._springScale.reconfigure(e2, t2, n); -}; -const props$k = { - direction: { +} +const OPEN_TYPES = ["navigate", "redirect", "switchTab", "reLaunch", "navigateBack"]; +const props$j = { + hoverClass: { type: String, - default: "none" + default: "navigator-hover" }, - inertia: { - type: [Boolean, String], - default: false + url: { + type: String, + default: "" }, - outOfBounds: { - type: [Boolean, String], - default: false + openType: { + type: String, + default: "navigate", + validator(value) { + return Boolean(~OPEN_TYPES.indexOf(value)); + } }, - x: { - type: [Number, String], - default: 0 + delta: { + type: Number, + default: 1 }, - y: { + hoverStartTime: { type: [Number, String], - default: 0 + default: 50 }, - damping: { + hoverStayTime: { type: [Number, String], - default: 20 + default: 600 }, - friction: { - type: [Number, String], - default: 2 + exists: { + type: String, + default: "" }, - disabled: { - type: [Boolean, String], + hoverStopPropagation: { + type: Boolean, default: false + } +}; +var index$m = /* @__PURE__ */ defineBuiltInComponent({ + name: "Navigator", + compatConfig: { + MODE: 3 }, - scale: { - type: [Boolean, String], - default: false + props: props$j, + setup(props2, { + slots + }) { + const { + hovering, + binding + } = useHover(props2); + function onClick($event) { + if (props2.openType !== "navigateBack" && !props2.url) { + console.error(" should have url attribute when using navigateTo, redirectTo, reLaunch or switchTab"); + return; + } + switch (props2.openType) { + case "navigate": + uni.navigateTo({ + url: props2.url + }); + break; + case "redirect": + uni.redirectTo({ + url: props2.url, + exists: props2.exists + }); + break; + case "switchTab": + uni.switchTab({ + url: props2.url + }); + break; + case "reLaunch": + uni.reLaunch({ + url: props2.url + }); + break; + case "navigateBack": + uni.navigateBack({ + delta: props2.delta + }); + break; + } + } + return () => { + const { + hoverClass + } = props2; + const hasHoverClass = props2.hoverClass && props2.hoverClass !== "none"; + return vue.createVNode("uni-navigator", vue.mergeProps({ + "class": hasHoverClass && hovering.value ? hoverClass : "" + }, hasHoverClass && binding, { + "onClick": onClick + }), [slots.default && slots.default()], 16, ["onClick"]); + }; + } +}); +const props$i = { + value: { + type: Array, + default() { + return []; + }, + validator: function(val) { + return Array.isArray(val) && val.filter((val2) => typeof val2 === "number").length === val.length; + } }, - scaleMin: { - type: [Number, String], - default: 0.5 + indicatorStyle: { + type: String, + default: "" }, - scaleMax: { - type: [Number, String], - default: 10 + indicatorClass: { + type: String, + default: "" }, - scaleValue: { - type: [Number, String], - default: 1 + maskStyle: { + type: String, + default: "" }, - animation: { - type: [Boolean, String], - default: true + maskClass: { + type: String, + default: "" } }; -var index$n = /* @__PURE__ */ defineBuiltInComponent({ - name: "MovableView", - props: props$k, - emits: ["change", "scale"], +function useState$2(props2) { + const value = vue.reactive([...props2.value]); + const state = vue.reactive({ + value, + height: 34 + }); + vue.watch(() => props2.value, (val, oldVal) => { + { + state.value.length = val.length; + val.forEach((val2, index2) => { + if (val2 !== state.value[index2]) { + state.value.splice(index2, 1, val2); + } + }); + } + }); + return state; +} +var PickerView = /* @__PURE__ */ defineBuiltInComponent({ + name: "PickerView", + props: props$i, + emits: ["change", "pickstart", "pickend", "update:value"], setup(props2, { slots, emit: emit2 }) { const rootRef = vue.ref(null); const trigger = useCustomEvent(rootRef, emit2); - const { - setParent - } = useMovableViewState(props2, trigger, rootRef); + const state = useState$2(props2); + const resizeSensorRef = vue.ref(null); + let columnVNodes = []; + function getItemIndex(vnode) { + return columnVNodes.indexOf(vnode); + } + const getPickerViewColumn = function(columnInstance) { + const ref = vue.computed({ + get() { + const index2 = getItemIndex(columnInstance.vnode); + return state.value[index2] || 0; + }, + set(current) { + const index2 = getItemIndex(columnInstance.vnode); + const oldCurrent = state.value[index2]; + if (oldCurrent !== current) { + state.value.splice(index2, 1, current); + const value = state.value.map((val) => val); + emit2("update:value", value); + trigger("change", {}, { + value + }); + } + } + }); + return ref; + }; + vue.provide("getPickerViewColumn", getPickerViewColumn); + vue.provide("pickerViewProps", props2); + vue.provide("pickerViewState", state); return () => { - return vue.createVNode("uni-movable-view", { + const defaultSlots = slots.default && slots.default(); + columnVNodes = flatVNode(defaultSlots); + return vue.createVNode("uni-picker-view", { "ref": rootRef }, [vue.createVNode(ResizeSensor, { - "onResize": setParent - }, null, 8, ["onResize"]), slots.default && slots.default()], 512); + "ref": resizeSensorRef, + "onResize": ({ + height + }) => state.height = height + }, null, 8, ["onResize"]), vue.createVNode("div", { + "class": "uni-picker-view-wrapper" + }, [defaultSlots])], 512); + }; + } +}); +class Friction { + constructor(drag) { + this._drag = drag; + this._dragLog = Math.log(drag); + this._x = 0; + this._v = 0; + this._startTime = 0; + } + set(x, v2) { + this._x = x; + this._v = v2; + this._startTime = new Date().getTime(); + } + setVelocityByEnd(e2) { + this._v = (e2 - this._x) * this._dragLog / (Math.pow(this._drag, 100) - 1); + } + x(e2) { + if (e2 === void 0) { + e2 = (new Date().getTime() - this._startTime) / 1e3; + } + const t2 = e2 === this._dt && this._powDragDt ? this._powDragDt : this._powDragDt = Math.pow(this._drag, e2); + this._dt = e2; + return this._x + this._v * t2 / this._dragLog - this._v / this._dragLog; + } + dx(e2) { + if (e2 === void 0) { + e2 = (new Date().getTime() - this._startTime) / 1e3; + } + const t2 = e2 === this._dt && this._powDragDt ? this._powDragDt : this._powDragDt = Math.pow(this._drag, e2); + this._dt = e2; + return this._v * t2; + } + done() { + return Math.abs(this.dx()) < 3; + } + reconfigure(e2) { + const t2 = this.x(); + const n = this.dx(); + this._drag = e2; + this._dragLog = Math.log(e2); + this.set(t2, n); + } + configuration() { + const e2 = this; + return [ + { + label: "Friction", + read: function() { + return e2._drag; + }, + write: function(t2) { + e2.reconfigure(t2); + }, + min: 1e-3, + max: 0.1, + step: 1e-3 + } + ]; + } +} +function o(e2, t2, n) { + return e2 > t2 - n && e2 < t2 + n; +} +function a(e2, t2) { + return o(e2, 0, t2); +} +class Spring { + constructor(m, k, c) { + this._m = m; + this._k = k; + this._c = c; + this._solution = null; + this._endPosition = 0; + this._startTime = 0; + } + _solve(e2, t2) { + const n = this._c; + const i = this._m; + const r = this._k; + const o2 = n * n - 4 * i * r; + if (o2 === 0) { + const a3 = -n / (2 * i); + const s2 = e2; + const l2 = t2 / (a3 * e2); + return { + x: function(e22) { + return (s2 + l2 * e22) * Math.pow(Math.E, a3 * e22); + }, + dx: function(e22) { + const t22 = Math.pow(Math.E, a3 * e22); + return a3 * (s2 + l2 * e22) * t22 + l2 * t22; + } + }; + } + if (o2 > 0) { + const c = (-n - Math.sqrt(o2)) / (2 * i); + const u = (-n + Math.sqrt(o2)) / (2 * i); + const l2 = (t2 - c * e2) / (u - c); + const s2 = e2 - l2; + return { + x: function(e22) { + let t22; + let n2; + if (e22 === this._t) { + t22 = this._powER1T; + n2 = this._powER2T; + } + this._t = e22; + if (!t22) { + t22 = this._powER1T = Math.pow(Math.E, c * e22); + } + if (!n2) { + n2 = this._powER2T = Math.pow(Math.E, u * e22); + } + return s2 * t22 + l2 * n2; + }, + dx: function(e22) { + let t22; + let n2; + if (e22 === this._t) { + t22 = this._powER1T; + n2 = this._powER2T; + } + this._t = e22; + if (!t22) { + t22 = this._powER1T = Math.pow(Math.E, c * e22); + } + if (!n2) { + n2 = this._powER2T = Math.pow(Math.E, u * e22); + } + return s2 * c * t22 + l2 * u * n2; + } + }; + } + const d = Math.sqrt(4 * i * r - n * n) / (2 * i); + const a2 = -n / 2 * i; + const s = e2; + const l = (t2 - a2 * e2) / d; + return { + x: function(e22) { + return Math.pow(Math.E, a2 * e22) * (s * Math.cos(d * e22) + l * Math.sin(d * e22)); + }, + dx: function(e22) { + const t22 = Math.pow(Math.E, a2 * e22); + const n2 = Math.cos(d * e22); + const i2 = Math.sin(d * e22); + return t22 * (l * d * n2 - s * d * i2) + a2 * t22 * (l * i2 + s * n2); + } }; } -}); -let requesting = false; -function _requestAnimationFrame(e2) { - if (!requesting) { - requesting = true; - requestAnimationFrame(function() { - e2(); - requesting = false; - }); - } -} -function p(t2, n) { - if (t2 === n) { - return 0; - } - let i = t2.offsetLeft; - return t2.offsetParent ? i += p(t2.offsetParent, n) : 0; -} -function f(t2, n) { - if (t2 === n) { - return 0; + x(e2) { + if (e2 === void 0) { + e2 = (new Date().getTime() - this._startTime) / 1e3; + } + return this._solution ? this._endPosition + this._solution.x(e2) : 0; } - let i = t2.offsetTop; - return t2.offsetParent ? i += f(t2.offsetParent, n) : 0; -} -function v(a2, b) { - return +((1e3 * a2 - 1e3 * b) / 1e3).toFixed(1); -} -function g(friction, execute, endCallback) { - let record = { - id: 0, - cancelled: false - }; - let cancel = function(record2) { - if (record2 && record2.id) { - cancelAnimationFrame(record2.id); + dx(e2) { + if (e2 === void 0) { + e2 = (new Date().getTime() - this._startTime) / 1e3; } - if (record2) { - record2.cancelled = true; + return this._solution ? this._solution.dx(e2) : 0; + } + setEnd(e2, t2, n) { + if (!n) { + n = new Date().getTime(); } - }; - function fn(record2, friction2, execute2, endCallback2) { - if (!record2 || !record2.cancelled) { - execute2(friction2); - let isDone = friction2.done(); - if (!isDone) { - if (!record2.cancelled) { - record2.id = requestAnimationFrame(fn.bind(null, record2, friction2, execute2, endCallback2)); + if (e2 !== this._endPosition || !a(t2, 0.4)) { + t2 = t2 || 0; + let i = this._endPosition; + if (this._solution) { + if (a(t2, 0.4)) { + t2 = this._solution.dx((n - this._startTime) / 1e3); + } + i = this._solution.x((n - this._startTime) / 1e3); + if (a(t2, 0.4)) { + t2 = 0; } + if (a(i, 0.4)) { + i = 0; + } + i += this._endPosition; } - if (isDone && endCallback2) { - endCallback2(friction2); + if (!(this._solution && a(i - e2, 0.4) && a(t2, 0.4))) { + this._endPosition = e2; + this._solution = this._solve(i - this._endPosition, t2); + this._startTime = n; } } } - fn(record, friction, execute, endCallback); - return { - cancel: cancel.bind(null, record), - model: friction - }; -} -function _getPx(val) { - if (/\d+[ur]px$/i.test(val)) { - return uni.upx2px(parseFloat(val)); + snap(e2) { + this._startTime = new Date().getTime(); + this._endPosition = e2; + this._solution = { + x: function() { + return 0; + }, + dx: function() { + return 0; + } + }; + } + done(e2) { + if (!e2) { + e2 = new Date().getTime(); + } + return o(this.x(), this._endPosition, 0.4) && a(this.dx(), 0.4); + } + reconfigure(e2, t2, n) { + this._m = e2; + this._k = t2; + this._c = n; + if (!this.done()) { + this._solution = this._solve(this.x() - this._endPosition, this.dx()); + this._startTime = new Date().getTime(); + } + } + springConstant() { + return this._k; + } + damping() { + return this._c; + } + configuration() { + function e2(e22, t22) { + e22.reconfigure(1, t22, e22.damping()); + } + function t2(e22, t22) { + e22.reconfigure(1, e22.springConstant(), t22); + } + return [ + { + label: "Spring Constant", + read: this.springConstant.bind(this), + write: e2.bind(this, this), + min: 100, + max: 1e3 + }, + { + label: "Damping", + read: this.damping.bind(this), + write: t2.bind(this, this), + min: 1, + max: 500 + } + ]; } - return Number(val) || 0; } -function useMovableViewState(props2, trigger, rootRef) { - const movableAreaWidth = vue.inject("movableAreaWidth", vue.ref(0)); - const movableAreaHeight = vue.inject("movableAreaHeight", vue.ref(0)); - const _isMounted = vue.inject("_isMounted", vue.ref(false)); - const movableAreaRootRef = vue.inject("movableAreaRootRef"); - vue.inject("addMovableViewContext", () => { - }); - vue.inject("removeMovableViewContext", () => { - }); - const xSync = vue.ref(_getPx(props2.x)); - const ySync = vue.ref(_getPx(props2.y)); - const scaleValueSync = vue.ref(Number(props2.scaleValue) || 1); - const width = vue.ref(0); - const height = vue.ref(0); - const minX = vue.ref(0); - const minY = vue.ref(0); - const maxX = vue.ref(0); - const maxY = vue.ref(0); - let _SFA = null; - const _offset = { - x: 0, - y: 0 - }; - const _scaleOffset = { - x: 0, - y: 0 - }; - let _scale = 1; - let _translateX = 0; - let _translateY = 0; - const dampingNumber = vue.computed(() => { - let val = Number(props2.damping); - return isNaN(val) ? 20 : val; - }); - const frictionNumber = vue.computed(() => { - let val = Number(props2.friction); - return isNaN(val) || val <= 0 ? 2 : val; - }); - const scaleMinNumber = vue.computed(() => { - let val = Number(props2.scaleMin); - return isNaN(val) ? 0.5 : val; - }); - const scaleMaxNumber = vue.computed(() => { - let val = Number(props2.scaleMax); - return isNaN(val) ? 10 : val; - }); - const xMove = vue.computed(() => props2.direction === "all" || props2.direction === "horizontal"); - const yMove = vue.computed(() => props2.direction === "all" || props2.direction === "vertical"); - const _STD = new STD(1, 9 * Math.pow(dampingNumber.value, 2) / 40, dampingNumber.value); - new Friction$1(1, frictionNumber.value); - vue.watch(() => props2.x, (val) => { - xSync.value = _getPx(val); - }); - vue.watch(() => props2.y, (val) => { - ySync.value = _getPx(val); - }); - vue.watch(xSync, (val) => { - _setX(val); - }); - vue.watch(ySync, (val) => { - _setY(val); - }); - vue.watch(() => props2.scaleValue, (val) => { - scaleValueSync.value = Number(val) || 0; - }); - vue.watch(scaleValueSync, (val) => { - _setScaleValue(val); - }); - vue.watch(scaleMinNumber, () => { - _setScaleMinOrMax(); - }); - vue.watch(scaleMaxNumber, () => { - _setScaleMinOrMax(); - }); - function FAandSFACancel() { - if (_SFA) { - _SFA.cancel(); +class Scroll { + constructor(extent, friction, spring) { + this._extent = extent; + this._friction = friction || new Friction(0.01); + this._spring = spring || new Spring(1, 90, 20); + this._startTime = 0; + this._springing = false; + this._springOffset = 0; + } + snap(e2, t2) { + this._springOffset = 0; + this._springing = true; + this._spring.snap(e2); + this._spring.setEnd(t2); + } + set(e2, t2) { + this._friction.set(e2, t2); + if (e2 > 0 && t2 >= 0) { + this._springOffset = 0; + this._springing = true; + this._spring.snap(e2); + this._spring.setEnd(0); + } else { + if (e2 < -this._extent && t2 <= 0) { + this._springOffset = 0; + this._springing = true; + this._spring.snap(e2); + this._spring.setEnd(-this._extent); + } else { + this._springing = false; + } } + this._startTime = new Date().getTime(); } - function _setX(val) { - if (xMove.value) { - if (val + _scaleOffset.x === _translateX) { - return _translateX; + x(e2) { + if (!this._startTime) { + return 0; + } + if (!e2) { + e2 = (new Date().getTime() - this._startTime) / 1e3; + } + if (this._springing) { + return this._spring.x() + this._springOffset; + } + let t2 = this._friction.x(e2); + let n = this.dx(e2); + if (t2 > 0 && n >= 0 || t2 < -this._extent && n <= 0) { + this._springing = true; + this._spring.setEnd(0, n); + if (t2 < -this._extent) { + this._springOffset = -this._extent; } else { - if (_SFA) { - _SFA.cancel(); - } - _animationTo(val + _scaleOffset.x, ySync.value + _scaleOffset.y, _scale); + this._springOffset = 0; } + t2 = this._spring.x() + this._springOffset; } - return val; + return t2; } - function _setY(val) { - if (yMove.value) { - if (val + _scaleOffset.y === _translateY) { - return _translateY; - } else { - if (_SFA) { - _SFA.cancel(); + dx(e2) { + let t2; + if (this._lastTime === e2) { + t2 = this._lastDx; + } else { + t2 = this._springing ? this._spring.dx(e2) : this._friction.dx(e2); + } + this._lastTime = e2; + this._lastDx = t2; + return t2; + } + done() { + return this._springing ? this._spring.done() : this._friction.done(); + } + setVelocityByEnd(e2) { + this._friction.setVelocityByEnd(e2); + } + configuration() { + const e2 = this._friction.configuration(); + e2.push.apply(e2, this._spring.configuration()); + return e2; + } +} +function createAnimation(scroll, onScroll, onEnd) { + const state = { + id: 0, + cancelled: false + }; + function startAnimation2(state2, scroll2, onScroll2, onEnd2) { + if (!state2 || !state2.cancelled) { + onScroll2(scroll2); + const isDone = scroll2.done(); + if (!isDone) { + if (!state2.cancelled) { + state2.id = requestAnimationFrame(startAnimation2.bind(null, state2, scroll2, onScroll2, onEnd2)); } - _animationTo(xSync.value + _scaleOffset.x, val + _scaleOffset.y, _scale); + } + if (isDone && onEnd2) { + onEnd2(scroll2); } } - return val; } - function _setScaleMinOrMax() { - if (!props2.scale) { - return false; + function cancel(state2) { + if (state2 && state2.id) { + cancelAnimationFrame(state2.id); } - _updateScale(_scale, true); - } - function _setScaleValue(scale) { - if (!props2.scale) { - return false; + if (state2) { + state2.cancelled = true; } - scale = _adjustScale(scale); - _updateScale(scale, true); - return scale; } - function _getLimitXY(x, y) { - let outOfBounds = false; - if (x > maxX.value) { - x = maxX.value; - outOfBounds = true; + startAnimation2(state, scroll, onScroll, onEnd); + return { + cancel: cancel.bind(null, state), + model: scroll + }; +} +class Scroller { + constructor(element, options) { + options = options || {}; + this._element = element; + this._options = options; + this._enableSnap = options.enableSnap || false; + this._itemSize = options.itemSize || 0; + this._enableX = options.enableX || false; + this._enableY = options.enableY || false; + this._shouldDispatchScrollEvent = !!options.onScroll; + if (this._enableX) { + this._extent = (options.scrollWidth || this._element.offsetWidth) - this._element.parentElement.offsetWidth; + this._scrollWidth = options.scrollWidth; } else { - if (x < minX.value) { - x = minX.value; - outOfBounds = true; - } + this._extent = (options.scrollHeight || this._element.offsetHeight) - this._element.parentElement.offsetHeight; + this._scrollHeight = options.scrollHeight; } - if (y > maxY.value) { - y = maxY.value; - outOfBounds = true; + this._position = 0; + this._scroll = new Scroll(this._extent, options.friction, options.spring); + this._onTransitionEnd = this.onTransitionEnd.bind(this); + this.updatePosition(); + } + onTouchStart() { + this._startPosition = this._position; + this._lastChangePos = this._startPosition; + if (this._startPosition > 0) { + this._startPosition /= 0.5; } else { - if (y < minY.value) { - y = minY.value; - outOfBounds = true; + if (this._startPosition < -this._extent) { + this._startPosition = (this._startPosition + this._extent) / 0.5 - this._extent; } } - return { - x, - y, - outOfBounds - }; - } - function _updateOffset() { - _offset.x = p(rootRef.value, movableAreaRootRef.value); - _offset.y = f(rootRef.value, movableAreaRootRef.value); - } - function _updateWH(scale) { - scale = scale || _scale; - scale = _adjustScale(scale); - let rect = rootRef.value.getBoundingClientRect(); - height.value = rect.height / _scale; - width.value = rect.width / _scale; - let _height = height.value * scale; - let _width = width.value * scale; - _scaleOffset.x = (_width - width.value) / 2; - _scaleOffset.y = (_height - height.value) / 2; + if (this._animation) { + this._animation.cancel(); + this._scrolling = false; + } + this.updatePosition(); } - function _updateBoundary() { - let x = 0 - _offset.x + _scaleOffset.x; - let _width = movableAreaWidth.value - width.value - _offset.x - _scaleOffset.x; - minX.value = Math.min(x, _width); - maxX.value = Math.max(x, _width); - let y = 0 - _offset.y + _scaleOffset.y; - let _height = movableAreaHeight.value - height.value - _offset.y - _scaleOffset.y; - minY.value = Math.min(y, _height); - maxY.value = Math.max(y, _height); + onTouchMove(x, y) { + let startPosition = this._startPosition; + if (this._enableX) { + startPosition += x; + } else if (this._enableY) { + startPosition += y; + } + if (startPosition > 0) { + startPosition *= 0.5; + } else if (startPosition < -this._extent) { + startPosition = 0.5 * (startPosition + this._extent) - this._extent; + } + this._position = startPosition; + this.updatePosition(); + this.dispatchScroll(); } - function _updateScale(scale, animat) { - if (props2.scale) { - scale = _adjustScale(scale); - _updateWH(scale); - _updateBoundary(); - const limitXY = _getLimitXY(_translateX, _translateY); - const x = limitXY.x; - const y = limitXY.y; - if (animat) { - _animationTo(x, y, scale, "", true, true); - } else { - _requestAnimationFrame(function() { - _setTransform(x, y, scale, "", true, true); - }); + onTouchEnd(x, y, o2) { + if (this._enableSnap && this._position > -this._extent && this._position < 0) { + if (this._enableY && (Math.abs(y) < this._itemSize && Math.abs(o2.y) < 300 || Math.abs(o2.y) < 150)) { + this.snap(); + return; + } + if (this._enableX && (Math.abs(x) < this._itemSize && Math.abs(o2.x) < 300 || Math.abs(o2.x) < 150)) { + this.snap(); + return; + } + } + if (this._enableX) { + this._scroll.set(this._position, o2.x); + } else if (this._enableY) { + this._scroll.set(this._position, o2.y); + } + let c; + if (this._enableSnap) { + const s = this._scroll._friction.x(100); + const l = s % this._itemSize; + c = Math.abs(l) > this._itemSize / 2 ? s - (this._itemSize - Math.abs(l)) : s - l; + if (c <= 0 && c >= -this._extent) { + this._scroll.setVelocityByEnd(c); + } + } + this._lastTime = Date.now(); + this._lastDelay = 0; + this._scrolling = true; + this._lastChangePos = this._position; + this._lastIdx = Math.floor(Math.abs(this._position / this._itemSize)); + this._animation = createAnimation(this._scroll, () => { + const e2 = Date.now(); + const i = (e2 - this._scroll._startTime) / 1e3; + const r = this._scroll.x(i); + this._position = r; + this.updatePosition(); + const o22 = this._scroll.dx(i); + if (this._shouldDispatchScrollEvent && e2 - this._lastTime > this._lastDelay) { + this.dispatchScroll(); + this._lastDelay = Math.abs(2e3 / o22); + this._lastTime = e2; + } + }, () => { + if (this._enableSnap) { + if (c <= 0 && c >= -this._extent) { + this._position = c; + this.updatePosition(); + } + if (typeof this._options.onSnap === "function") { + this._options.onSnap(Math.floor(Math.abs(this._position) / this._itemSize)); + } + } + if (this._shouldDispatchScrollEvent) { + this.dispatchScroll(); } + this._scrolling = false; + }); + } + onTransitionEnd() { + this._element.style.webkitTransition = ""; + this._element.style.transition = ""; + this._element.removeEventListener("transitionend", this._onTransitionEnd); + if (this._snapping) { + this._snapping = false; } + this.dispatchScroll(); } - function _adjustScale(scale) { - scale = Math.max(0.5, scaleMinNumber.value, scale); - scale = Math.min(10, scaleMaxNumber.value, scale); - return scale; + snap() { + const itemSize = this._itemSize; + const position = this._position % itemSize; + const i = Math.abs(position) > this._itemSize / 2 ? this._position - (itemSize - Math.abs(position)) : this._position - position; + if (this._position !== i) { + this._snapping = true; + this.scrollTo(-i); + if (typeof this._options.onSnap === "function") { + this._options.onSnap(Math.floor(Math.abs(this._position) / this._itemSize)); + } + } } - function _animationTo(x, y, scale, source, r, o2) { - FAandSFACancel(); - if (!xMove.value) { - x = _translateX; + scrollTo(position, time) { + if (this._animation) { + this._animation.cancel(); + this._scrolling = false; } - if (!yMove.value) { - y = _translateY; + if (typeof position === "number") { + this._position = -position; } - if (!props2.scale) { - scale = _scale; + if (this._position < -this._extent) { + this._position = -this._extent; + } else { + if (this._position > 0) { + this._position = 0; + } } - let limitXY = _getLimitXY(x, y); - x = limitXY.x; - y = limitXY.y; - if (!props2.animation) { - _setTransform(x, y, scale, source, r, o2); - return; + const transition = "transform " + (time || 0.2) + "s ease-out"; + this._element.style.webkitTransition = "-webkit-" + transition; + this._element.style.transition = transition; + this.updatePosition(); + this._element.addEventListener("transitionend", this._onTransitionEnd); + } + dispatchScroll() { + if (typeof this._options.onScroll === "function" && Math.round(Number(this._lastPos)) !== Math.round(this._position)) { + this._lastPos = this._position; + const event = { + target: { + scrollLeft: this._enableX ? -this._position : 0, + scrollTop: this._enableY ? -this._position : 0, + scrollHeight: this._scrollHeight || this._element.offsetHeight, + scrollWidth: this._scrollWidth || this._element.offsetWidth, + offsetHeight: this._element.parentElement.offsetHeight, + offsetWidth: this._element.parentElement.offsetWidth + } + }; + this._options.onScroll(event); } - _STD._springX._solution = null; - _STD._springY._solution = null; - _STD._springScale._solution = null; - _STD._springX._endPosition = _translateX; - _STD._springY._endPosition = _translateY; - _STD._springScale._endPosition = _scale; - _STD.setEnd(x, y, scale, 1); - _SFA = g(_STD, function() { - let data = _STD.x(); - let x2 = data.x; - let y2 = data.y; - let scale2 = data.scale; - _setTransform(x2, y2, scale2, source, r, o2); - }, function() { - _SFA.cancel(); - }); } - function _setTransform(x, y, scale, source = "", r, o2) { - if (!(x !== null && x.toString() !== "NaN" && typeof x === "number")) { - x = _translateX || 0; + update(height, scrollHeight, itemSize) { + let extent = 0; + const position = this._position; + if (this._enableX) { + extent = this._element.childNodes.length ? (scrollHeight || this._element.offsetWidth) - this._element.parentElement.offsetWidth : 0; + this._scrollWidth = scrollHeight; + } else { + extent = this._element.childNodes.length ? (scrollHeight || this._element.offsetHeight) - this._element.parentElement.offsetHeight : 0; + this._scrollHeight = scrollHeight; } - if (!(y !== null && y.toString() !== "NaN" && typeof y === "number")) { - y = _translateY || 0; + if (typeof height === "number") { + this._position = -height; } - x = Number(x.toFixed(1)); - y = Number(y.toFixed(1)); - scale = Number(scale.toFixed(1)); - if (!(_translateX === x && _translateY === y)) { - if (!r) { - trigger("change", {}, { - x: v(x, _scaleOffset.x), - y: v(y, _scaleOffset.y), - source - }); + if (this._position < -extent) { + this._position = -extent; + } else { + if (this._position > 0) { + this._position = 0; } } - if (!props2.scale) { - scale = _scale; - } - scale = _adjustScale(scale); - scale = +scale.toFixed(3); - if (o2 && scale !== _scale) { - trigger("scale", {}, { - x, - y, - scale - }); - } - let transform = "translateX(" + x + "px) translateY(" + y + "px) translateZ(0px) scale(" + scale + ")"; - rootRef.value.style.transform = transform; - rootRef.value.style.webkitTransform = transform; - _translateX = x; - _translateY = y; - _scale = scale; - } - function setParent() { - if (!_isMounted.value) { - return; - } - FAandSFACancel(); - let scale = props2.scale ? scaleValueSync.value : 1; - _updateOffset(); - _updateWH(scale); - _updateBoundary(); - _translateX = xSync.value + _scaleOffset.x; - _translateY = ySync.value + _scaleOffset.y; - let limitXY = _getLimitXY(_translateX, _translateY); - let x = limitXY.x; - let y = limitXY.y; - _setTransform(x, y, scale, "", true); - } - return { - setParent - }; -} -const OPEN_TYPES = ["navigate", "redirect", "switchTab", "reLaunch", "navigateBack"]; -const props$j = { - hoverClass: { - type: String, - default: "navigator-hover" - }, - url: { - type: String, - default: "" - }, - openType: { - type: String, - default: "navigate", - validator(value) { - return Boolean(~OPEN_TYPES.indexOf(value)); + this._itemSize = itemSize || this._itemSize; + this.updatePosition(); + if (position !== this._position) { + this.dispatchScroll(); + if (typeof this._options.onSnap === "function") { + this._options.onSnap(Math.floor(Math.abs(this._position) / this._itemSize)); + } } - }, - delta: { - type: Number, - default: 1 - }, - hoverStartTime: { - type: [Number, String], - default: 50 - }, - hoverStayTime: { - type: [Number, String], - default: 600 - }, - exists: { - type: String, - default: "" - }, - hoverStopPropagation: { - type: Boolean, - default: false + this._extent = extent; + this._scroll._extent = extent; } -}; -var index$m = /* @__PURE__ */ defineBuiltInComponent({ - name: "Navigator", - compatConfig: { - MODE: 3 - }, - props: props$j, - setup(props2, { - slots - }) { - const { - hovering, - binding - } = useHover(props2); - function onClick($event) { - if (props2.openType !== "navigateBack" && !props2.url) { - console.error(" should have url attribute when using navigateTo, redirectTo, reLaunch or switchTab"); - return; - } - switch (props2.openType) { - case "navigate": - uni.navigateTo({ - url: props2.url - }); - break; - case "redirect": - uni.redirectTo({ - url: props2.url, - exists: props2.exists - }); - break; - case "switchTab": - uni.switchTab({ - url: props2.url - }); - break; - case "reLaunch": - uni.reLaunch({ - url: props2.url - }); - break; - case "navigateBack": - uni.navigateBack({ - delta: props2.delta - }); - break; + updatePosition() { + let transform = ""; + if (this._enableX) { + transform = "translateX(" + this._position + "px) translateZ(0)"; + } else { + if (this._enableY) { + transform = "translateY(" + this._position + "px) translateZ(0)"; } } - return () => { - const { - hoverClass - } = props2; - const hasHoverClass = props2.hoverClass && props2.hoverClass !== "none"; - return vue.createVNode("uni-navigator", vue.mergeProps({ - "class": hasHoverClass && hovering.value ? hoverClass : "" - }, hasHoverClass && binding, { - "onClick": onClick - }), [slots.default && slots.default()], 16, ["onClick"]); + this._element.style.webkitTransform = transform; + this._element.style.transform = transform; + } + isScrolling() { + return this._scrolling || this._snapping; + } +} +function useScroller(element, options) { + const touchInfo = { + trackingID: -1, + maxDy: 0, + maxDx: 0 + }; + const scroller = new Scroller(element, options); + function findDelta(event) { + const touchtrackEvent = event; + const mouseEvent = event; + return touchtrackEvent.detail.state === "move" || touchtrackEvent.detail.state === "end" ? { + x: touchtrackEvent.detail.dx, + y: touchtrackEvent.detail.dy + } : { + x: mouseEvent.screenX - touchInfo.x, + y: mouseEvent.screenY - touchInfo.y }; } -}); -const props$i = { - value: { - type: Array, - default() { - return []; - }, - validator: function(val) { - return Array.isArray(val) && val.filter((val2) => typeof val2 === "number").length === val.length; + function handleTouchStart(event) { + const touchtrackEvent = event; + const mouseEvent = event; + if (touchtrackEvent.detail.state === "start") { + touchInfo.trackingID = "touch"; + touchInfo.x = touchtrackEvent.detail.x; + touchInfo.y = touchtrackEvent.detail.y; + } else { + touchInfo.trackingID = "mouse"; + touchInfo.x = mouseEvent.screenX; + touchInfo.y = mouseEvent.screenY; } - }, - indicatorStyle: { - type: String, - default: "" - }, - indicatorClass: { - type: String, - default: "" - }, - maskStyle: { - type: String, - default: "" - }, - maskClass: { - type: String, - default: "" + touchInfo.maxDx = 0; + touchInfo.maxDy = 0; + touchInfo.historyX = [0]; + touchInfo.historyY = [0]; + touchInfo.historyTime = [ + touchtrackEvent.detail.timeStamp || mouseEvent.timeStamp + ]; + touchInfo.listener = scroller; + if (scroller.onTouchStart) { + scroller.onTouchStart(); + } + event.preventDefault(); } -}; -function useState$2(props2) { - const value = vue.reactive([...props2.value]); - const state = vue.reactive({ - value, - height: 34 - }); - vue.watch(() => props2.value, (val, oldVal) => { - { - state.value.length = val.length; - val.forEach((val2, index2) => { - if (val2 !== state.value[index2]) { - state.value.splice(index2, 1, val2); + function handleTouchMove(event) { + const touchtrackEvent = event; + const mouseEvent = event; + if (touchInfo.trackingID !== -1) { + event.preventDefault(); + const delta = findDelta(event); + if (delta) { + for (touchInfo.maxDy = Math.max(touchInfo.maxDy, Math.abs(delta.y)), touchInfo.maxDx = Math.max(touchInfo.maxDx, Math.abs(delta.x)), touchInfo.historyX.push(delta.x), touchInfo.historyY.push(delta.y), touchInfo.historyTime.push(touchtrackEvent.detail.timeStamp || mouseEvent.timeStamp); touchInfo.historyTime.length > 10; ) { + touchInfo.historyTime.shift(); + touchInfo.historyX.shift(); + touchInfo.historyY.shift(); } - }); + if (touchInfo.listener && touchInfo.listener.onTouchMove) { + touchInfo.listener.onTouchMove(delta.x, delta.y); + } + } } - }); - return state; + } + function handleTouchEnd(event) { + if (touchInfo.trackingID !== -1) { + event.preventDefault(); + const delta = findDelta(event); + if (delta) { + const listener = touchInfo.listener; + touchInfo.trackingID = -1; + touchInfo.listener = null; + const length = touchInfo.historyTime.length; + const o2 = { + x: 0, + y: 0 + }; + if (length > 2) { + for (let i = touchInfo.historyTime.length - 1, time1 = touchInfo.historyTime[i], x = touchInfo.historyX[i], y = touchInfo.historyY[i]; i > 0; ) { + i--; + const time0 = touchInfo.historyTime[i]; + const time = time1 - time0; + if (time > 30 && time < 50) { + o2.x = (x - touchInfo.historyX[i]) / (time / 1e3); + o2.y = (y - touchInfo.historyY[i]) / (time / 1e3); + break; + } + } + } + touchInfo.historyTime = []; + touchInfo.historyX = []; + touchInfo.historyY = []; + if (listener && listener.onTouchEnd) { + listener.onTouchEnd(delta.x, delta.y, o2); + } + } + } + } + return { + scroller, + handleTouchStart, + handleTouchMove, + handleTouchEnd + }; } -var PickerView = /* @__PURE__ */ defineBuiltInComponent({ - name: "PickerView", - props: props$i, - emits: ["change", "pickstart", "pickend", "update:value"], +let scopedIndex = 0; +function useScopedClass(indicatorHeightRef) { + const className = `uni-picker-view-content-${scopedIndex++}`; + function updateStyle() { + const style = document.createElement("style"); + style.innerText = `.uni-picker-view-content.${className}>*{height: ${indicatorHeightRef.value}px;overflow: hidden;}`; + document.head.appendChild(style); + } + vue.watch(() => indicatorHeightRef.value, updateStyle); + return className; +} +var PickerViewColumn = /* @__PURE__ */ defineBuiltInComponent({ + name: "PickerViewColumn", setup(props2, { slots, emit: emit2 }) { const rootRef = vue.ref(null); - const trigger = useCustomEvent(rootRef, emit2); - const state = useState$2(props2); + const contentRef = vue.ref(null); + const getPickerViewColumn = vue.inject("getPickerViewColumn"); + const instance = vue.getCurrentInstance(); + const currentRef = getPickerViewColumn ? getPickerViewColumn(instance) : vue.ref(0); + const pickerViewProps = vue.inject("pickerViewProps"); + const pickerViewState = vue.inject("pickerViewState"); + const indicatorHeight = vue.ref(34); const resizeSensorRef = vue.ref(null); - let columnVNodes = []; - function getItemIndex(vnode) { - return columnVNodes.indexOf(vnode); + const maskSize = vue.computed(() => (pickerViewState.height - indicatorHeight.value) / 2); + const { + state: scopedAttrsState + } = useScopedAttrs(); + const className = useScopedClass(indicatorHeight); + let scroller; + const state = vue.reactive({ + current: currentRef.value, + length: 0 + }); + function updatesScroller() { } - const getPickerViewColumn = function(columnInstance) { - const ref = vue.computed({ - get() { - const index2 = getItemIndex(columnInstance.vnode); - return state.value[index2] || 0; - }, - set(current) { - const index2 = getItemIndex(columnInstance.vnode); - const oldCurrent = state.value[index2]; - if (oldCurrent !== current) { - state.value.splice(index2, 1, current); - const value = state.value.map((val) => val); - emit2("update:value", value); - trigger("change", {}, { - value - }); - } + vue.watch(() => currentRef.value, (current) => { + if (current !== state.current) { + state.current = current; + } + }); + vue.watch(() => state.current, (current) => currentRef.value = current); + vue.watch([() => indicatorHeight.value, () => state.length, () => pickerViewState.height], updatesScroller); + let oldDeltaY = 0; + function handleWheel(event) { + const deltaY = oldDeltaY + event.deltaY; + if (Math.abs(deltaY) > 10) { + oldDeltaY = 0; + let current = Math.min(state.current + (deltaY < 0 ? -1 : 1), state.length - 1); + state.current = current = Math.max(current, 0); + scroller.scrollTo(current * indicatorHeight.value); + } else { + oldDeltaY = deltaY; + } + event.preventDefault(); + } + function handleTap({ + clientY + }) { + const el = rootRef.value; + if (!scroller.isScrolling()) { + const rect = el.getBoundingClientRect(); + const r = clientY - rect.top - pickerViewState.height / 2; + const o2 = indicatorHeight.value / 2; + if (!(Math.abs(r) <= o2)) { + const a2 = Math.ceil((Math.abs(r) - o2) / indicatorHeight.value); + const s = r < 0 ? -a2 : a2; + let current = Math.min(state.current + s, state.length - 1); + state.current = current = Math.max(current, 0); + scroller.scrollTo(current * indicatorHeight.value); } - }); - return ref; - }; - vue.provide("getPickerViewColumn", getPickerViewColumn); - vue.provide("pickerViewProps", props2); - vue.provide("pickerViewState", state); + } + } return () => { const defaultSlots = slots.default && slots.default(); - columnVNodes = flatVNode(defaultSlots); - return vue.createVNode("uni-picker-view", { + state.length = flatVNode(defaultSlots).length; + const padding = `${maskSize.value}px 0`; + return vue.createVNode("uni-picker-view-column", { "ref": rootRef - }, [vue.createVNode(ResizeSensor, { + }, [vue.createVNode("div", { + "onWheel": handleWheel, + "onClick": handleTap, + "class": "uni-picker-view-group" + }, [vue.createVNode("div", vue.mergeProps(scopedAttrsState.attrs, { + "class": ["uni-picker-view-mask", pickerViewProps.maskClass], + "style": `background-size: 100% ${maskSize.value}px;${pickerViewProps.maskStyle}` + }), null, 16), vue.createVNode("div", vue.mergeProps(scopedAttrsState.attrs, { + "class": ["uni-picker-view-indicator", pickerViewProps.indicatorClass], + "style": pickerViewProps.indicatorStyle + }), [vue.createVNode(ResizeSensor, { "ref": resizeSensorRef, "onResize": ({ height - }) => state.height = height - }, null, 8, ["onResize"]), vue.createVNode("div", { - "class": "uni-picker-view-wrapper" - }, [defaultSlots])], 512); + }) => indicatorHeight.value = height + }, null, 8, ["onResize"])], 16), vue.createVNode("div", { + "ref": contentRef, + "class": ["uni-picker-view-content", className], + "style": { + padding + } + }, [defaultSlots], 6)], 40, ["onWheel", "onClick"])], 512); }; } }); -class Friction { - constructor(drag) { - this._drag = drag; - this._dragLog = Math.log(drag); - this._x = 0; - this._v = 0; - this._startTime = 0; - } - set(x, v2) { - this._x = x; - this._v = v2; - this._startTime = new Date().getTime(); - } - setVelocityByEnd(e2) { - this._v = (e2 - this._x) * this._dragLog / (Math.pow(this._drag, 100) - 1); - } - x(e2) { - if (e2 === void 0) { - e2 = (new Date().getTime() - this._startTime) / 1e3; +const VALUES = { + activeColor: uniShared.PRIMARY_COLOR, + backgroundColor: "#EBEBEB", + activeMode: "backwards" +}; +const props$h = { + percent: { + type: [Number, String], + default: 0, + validator(value) { + return !isNaN(parseFloat(value)); } - const t2 = e2 === this._dt && this._powDragDt ? this._powDragDt : this._powDragDt = Math.pow(this._drag, e2); - this._dt = e2; - return this._x + this._v * t2 / this._dragLog - this._v / this._dragLog; - } - dx(e2) { - if (e2 === void 0) { - e2 = (new Date().getTime() - this._startTime) / 1e3; + }, + showInfo: { + type: [Boolean, String], + default: false + }, + strokeWidth: { + type: [Number, String], + default: 6, + validator(value) { + return !isNaN(parseFloat(value)); + } + }, + color: { + type: String, + default: VALUES.activeColor + }, + activeColor: { + type: String, + default: VALUES.activeColor + }, + backgroundColor: { + type: String, + default: VALUES.backgroundColor + }, + active: { + type: [Boolean, String], + default: false + }, + activeMode: { + type: String, + default: VALUES.activeMode + }, + duration: { + type: [Number, String], + default: 30, + validator(value) { + return !isNaN(parseFloat(value)); } - const t2 = e2 === this._dt && this._powDragDt ? this._powDragDt : this._powDragDt = Math.pow(this._drag, e2); - this._dt = e2; - return this._v * t2; - } - done() { - return Math.abs(this.dx()) < 3; - } - reconfigure(e2) { - const t2 = this.x(); - const n = this.dx(); - this._drag = e2; - this._dragLog = Math.log(e2); - this.set(t2, n); - } - configuration() { - const e2 = this; - return [ - { - label: "Friction", - read: function() { - return e2._drag; - }, - write: function(t2) { - e2.reconfigure(t2); - }, - min: 1e-3, - max: 0.1, - step: 1e-3 - } - ]; } -} -function o(e2, t2, n) { - return e2 > t2 - n && e2 < t2 + n; -} -function a(e2, t2) { - return o(e2, 0, t2); -} -class Spring { - constructor(m, k, c) { - this._m = m; - this._k = k; - this._c = c; - this._solution = null; - this._endPosition = 0; - this._startTime = 0; +}; +var index$l = /* @__PURE__ */ defineBuiltInComponent({ + name: "Progress", + props: props$h, + setup(props2) { + const state = useProgressState(props2); + _activeAnimation(state, props2); + vue.watch(() => state.realPercent, (newValue, oldValue) => { + state.strokeTimer && clearInterval(state.strokeTimer); + state.lastPercent = oldValue || 0; + _activeAnimation(state, props2); + }); + return () => { + const { + showInfo + } = props2; + const { + outerBarStyle, + innerBarStyle, + currentPercent + } = state; + return vue.createVNode("uni-progress", { + "class": "uni-progress" + }, [vue.createVNode("div", { + "style": outerBarStyle, + "class": "uni-progress-bar" + }, [vue.createVNode("div", { + "style": innerBarStyle, + "class": "uni-progress-inner-bar" + }, null, 4)], 4), showInfo ? vue.createVNode("p", { + "class": "uni-progress-info" + }, [currentPercent + "%"]) : ""]); + }; } - _solve(e2, t2) { - const n = this._c; - const i = this._m; - const r = this._k; - const o2 = n * n - 4 * i * r; - if (o2 === 0) { - const a3 = -n / (2 * i); - const s2 = e2; - const l2 = t2 / (a3 * e2); - return { - x: function(e22) { - return (s2 + l2 * e22) * Math.pow(Math.E, a3 * e22); - }, - dx: function(e22) { - const t22 = Math.pow(Math.E, a3 * e22); - return a3 * (s2 + l2 * e22) * t22 + l2 * t22; - } - }; - } - if (o2 > 0) { - const c = (-n - Math.sqrt(o2)) / (2 * i); - const u = (-n + Math.sqrt(o2)) / (2 * i); - const l2 = (t2 - c * e2) / (u - c); - const s2 = e2 - l2; - return { - x: function(e22) { - let t22; - let n2; - if (e22 === this._t) { - t22 = this._powER1T; - n2 = this._powER2T; - } - this._t = e22; - if (!t22) { - t22 = this._powER1T = Math.pow(Math.E, c * e22); - } - if (!n2) { - n2 = this._powER2T = Math.pow(Math.E, u * e22); - } - return s2 * t22 + l2 * n2; - }, - dx: function(e22) { - let t22; - let n2; - if (e22 === this._t) { - t22 = this._powER1T; - n2 = this._powER2T; - } - this._t = e22; - if (!t22) { - t22 = this._powER1T = Math.pow(Math.E, c * e22); - } - if (!n2) { - n2 = this._powER2T = Math.pow(Math.E, u * e22); - } - return s2 * c * t22 + l2 * u * n2; - } - }; - } - const d = Math.sqrt(4 * i * r - n * n) / (2 * i); - const a2 = -n / 2 * i; - const s = e2; - const l = (t2 - a2 * e2) / d; - return { - x: function(e22) { - return Math.pow(Math.E, a2 * e22) * (s * Math.cos(d * e22) + l * Math.sin(d * e22)); - }, - dx: function(e22) { - const t22 = Math.pow(Math.E, a2 * e22); - const n2 = Math.cos(d * e22); - const i2 = Math.sin(d * e22); - return t22 * (l * d * n2 - s * d * i2) + a2 * t22 * (l * i2 + s * n2); +}); +function useProgressState(props2) { + const currentPercent = vue.ref(0); + const outerBarStyle = vue.computed(() => `background-color: ${props2.backgroundColor}; height: ${props2.strokeWidth}px;`); + const innerBarStyle = vue.computed(() => { + const backgroundColor = props2.color !== VALUES.activeColor && props2.activeColor === VALUES.activeColor ? props2.color : props2.activeColor; + return `width: ${currentPercent.value}%;background-color: ${backgroundColor}`; + }); + const realPercent = vue.computed(() => { + let realValue = parseFloat(props2.percent); + realValue < 0 && (realValue = 0); + realValue > 100 && (realValue = 100); + return realValue; + }); + const state = vue.reactive({ + outerBarStyle, + innerBarStyle, + realPercent, + currentPercent, + strokeTimer: 0, + lastPercent: 0 + }); + return state; +} +function _activeAnimation(state, props2) { + if (props2.active) { + state.currentPercent = props2.activeMode === VALUES.activeMode ? 0 : state.lastPercent; + state.strokeTimer = setInterval(() => { + if (state.currentPercent + 1 > state.realPercent) { + state.currentPercent = state.realPercent; + state.strokeTimer && clearInterval(state.strokeTimer); + } else { + state.currentPercent += 1; } - }; + }, parseFloat(props2.duration)); + } else { + state.currentPercent = state.realPercent; } - x(e2) { - if (e2 === void 0) { - e2 = (new Date().getTime() - this._startTime) / 1e3; - } - return this._solution ? this._endPosition + this._solution.x(e2) : 0; +} +const uniRadioGroupKey = PolySymbol(process.env.NODE_ENV !== "production" ? "uniCheckGroup" : "ucg"); +const props$g = { + name: { + type: String, + default: "" } - dx(e2) { - if (e2 === void 0) { - e2 = (new Date().getTime() - this._startTime) / 1e3; - } - return this._solution ? this._solution.dx(e2) : 0; +}; +var index$k = /* @__PURE__ */ defineBuiltInComponent({ + name: "RadioGroup", + props: props$g, + setup(props2, { + emit: emit2, + slots + }) { + const rootRef = vue.ref(null); + const trigger = useCustomEvent(rootRef, emit2); + useProvideRadioGroup(props2, trigger); + return () => { + return vue.createVNode("uni-radio-group", { + "ref": rootRef + }, [slots.default && slots.default()], 512); + }; } - setEnd(e2, t2, n) { - if (!n) { - n = new Date().getTime(); +}); +function useProvideRadioGroup(props2, trigger) { + const fields2 = []; + const getFieldsValue = () => { + var _a; + return (_a = fields2.find((field) => field.value.radioChecked)) == null ? void 0 : _a.value.value; + }; + vue.provide(uniRadioGroupKey, { + addField(field) { + fields2.push(field); + }, + removeField(field) { + fields2.splice(fields2.indexOf(field), 1); + }, + radioChange($event, field) { + const index2 = fields2.indexOf(field); + _resetRadioGroupValue(index2, true); + trigger("change", $event, { + value: getFieldsValue() + }); } - if (e2 !== this._endPosition || !a(t2, 0.4)) { - t2 = t2 || 0; - let i = this._endPosition; - if (this._solution) { - if (a(t2, 0.4)) { - t2 = this._solution.dx((n - this._startTime) / 1e3); - } - i = this._solution.x((n - this._startTime) / 1e3); - if (a(t2, 0.4)) { - t2 = 0; - } - if (a(i, 0.4)) { - i = 0; + }); + const uniForm = vue.inject(uniFormKey, false); + if (uniForm) { + uniForm.addField({ + submit: () => { + let data = ["", null]; + if (props2.name !== "") { + data[0] = props2.name; + data[1] = getFieldsValue(); } - i += this._endPosition; - } - if (!(this._solution && a(i - e2, 0.4) && a(t2, 0.4))) { - this._endPosition = e2; - this._solution = this._solve(i - this._endPosition, t2); - this._startTime = n; + return data; } - } + }); } - snap(e2) { - this._startTime = new Date().getTime(); - this._endPosition = e2; - this._solution = { - x: function() { - return 0; - }, - dx: function() { - return 0; - } + function setFieldChecked(field, radioChecked) { + field.value = { + radioChecked, + value: field.value.value }; } - done(e2) { - if (!e2) { - e2 = new Date().getTime(); - } - return o(this.x(), this._endPosition, 0.4) && a(this.dx(), 0.4); - } - reconfigure(e2, t2, n) { - this._m = e2; - this._k = t2; - this._c = n; - if (!this.done()) { - this._solution = this._solve(this.x() - this._endPosition, this.dx()); - this._startTime = new Date().getTime(); - } - } - springConstant() { - return this._k; - } - damping() { - return this._c; - } - configuration() { - function e2(e22, t22) { - e22.reconfigure(1, t22, e22.damping()); - } - function t2(e22, t22) { - e22.reconfigure(1, e22.springConstant(), t22); - } - return [ - { - label: "Spring Constant", - read: this.springConstant.bind(this), - write: e2.bind(this, this), - min: 100, - max: 1e3 - }, - { - label: "Damping", - read: this.damping.bind(this), - write: t2.bind(this, this), - min: 1, - max: 500 + function _resetRadioGroupValue(key, change) { + fields2.forEach((value, index2) => { + if (index2 === key) { + return; } - ]; + if (change) { + setFieldChecked(fields2[index2], false); + } else { + fields2.forEach((v2, i) => { + if (index2 >= i) { + return; + } + if (fields2[i].value.radioChecked) { + setFieldChecked(fields2[index2], false); + } + }); + } + }); } + return fields2; } -class Scroll { - constructor(extent, friction, spring) { - this._extent = extent; - this._friction = friction || new Friction(0.01); - this._spring = spring || new Spring(1, 90, 20); - this._startTime = 0; - this._springing = false; - this._springOffset = 0; - } - snap(e2, t2) { - this._springOffset = 0; - this._springing = true; - this._spring.snap(e2); - this._spring.setEnd(t2); +const props$f = { + 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: "" } - set(e2, t2) { - this._friction.set(e2, t2); - if (e2 > 0 && t2 >= 0) { - this._springOffset = 0; - this._springing = true; - this._spring.snap(e2); - this._spring.setEnd(0); - } else { - if (e2 < -this._extent && t2 <= 0) { - this._springOffset = 0; - this._springing = true; - this._spring.snap(e2); - this._spring.setEnd(-this._extent); - } else { - this._springing = false; +}; +var index$j = /* @__PURE__ */ defineBuiltInComponent({ + name: "Radio", + props: props$f, + setup(props2, { + slots + }) { + const radioChecked = vue.ref(props2.checked); + const radioValue = vue.ref(props2.value); + const checkedStyle = vue.computed(() => `background-color: ${props2.color};border-color: ${props2.color};`); + vue.watch([() => props2.checked, () => props2.value], ([newChecked, newModelValue]) => { + radioChecked.value = newChecked; + radioValue.value = newModelValue; + }); + const reset = () => { + radioChecked.value = false; + }; + const { + uniCheckGroup, + uniLabel, + field + } = useRadioInject(radioChecked, radioValue, reset); + const _onClick = ($event) => { + if (props2.disabled) { + return; } + radioChecked.value = true; + uniCheckGroup && uniCheckGroup.radioChange($event, field); + }; + if (!!uniLabel) { + uniLabel.addHandler(_onClick); } - this._startTime = new Date().getTime(); + return () => { + const { + booleanAttrs + } = useBooleanAttr(props2, "disabled"); + return vue.createVNode("uni-radio", vue.mergeProps(booleanAttrs, { + "onClick": _onClick + }), [vue.createVNode("div", { + "class": "uni-radio-wrapper" + }, [vue.createVNode("div", { + "class": ["uni-radio-input", { + "uni-radio-input-disabled": props2.disabled + }], + "style": radioChecked.value ? checkedStyle.value : "" + }, [radioChecked.value ? createSvgIconVNode(ICON_PATH_SUCCESS_NO_CIRCLE, "#fff", 18) : ""], 6), slots.default && slots.default()])], 16, ["onClick"]); + }; } - x(e2) { - if (!this._startTime) { - return 0; - } - if (!e2) { - e2 = (new Date().getTime() - this._startTime) / 1e3; +}); +function useRadioInject(radioChecked, radioValue, reset) { + const field = vue.computed({ + get: () => ({ + radioChecked: Boolean(radioChecked.value), + value: radioValue.value + }), + set: ({ + radioChecked: checked + }) => { + radioChecked.value = checked; } - if (this._springing) { - return this._spring.x() + this._springOffset; + }); + const formField = { + reset + }; + const uniCheckGroup = vue.inject(uniRadioGroupKey, false); + if (!!uniCheckGroup) { + uniCheckGroup.addField(field); + } + const uniForm = vue.inject(uniFormKey, false); + if (!!uniForm) { + uniForm.addField(formField); + } + const uniLabel = vue.inject(uniLabelKey, false); + return { + uniCheckGroup, + uniForm, + uniLabel, + field + }; +} +function removeDOCTYPE(html) { + return html.replace(/<\?xml.*\?>\n/, "").replace(/\n/, "").replace(/\n/, ""); +} +function parseAttrs(attrs) { + return attrs.reduce(function(pre, attr2) { + let value = attr2.value; + const name = attr2.name; + if (value.match(/ /) && name !== "style") { + value = value.split(" "); } - let t2 = this._friction.x(e2); - let n = this.dx(e2); - if (t2 > 0 && n >= 0 || t2 < -this._extent && n <= 0) { - this._springing = true; - this._spring.setEnd(0, n); - if (t2 < -this._extent) { - this._springOffset = -this._extent; + if (pre[name]) { + if (Array.isArray(pre[name])) { + pre[name].push(value); } else { - this._springOffset = 0; + pre[name] = [pre[name], value]; } - t2 = this._spring.x() + this._springOffset; - } - return t2; - } - dx(e2) { - let t2; - if (this._lastTime === e2) { - t2 = this._lastDx; } else { - t2 = this._springing ? this._spring.dx(e2) : this._friction.dx(e2); + pre[name] = value; } - this._lastTime = e2; - this._lastDx = t2; - return t2; - } - done() { - return this._springing ? this._spring.done() : this._friction.done(); - } - setVelocityByEnd(e2) { - this._friction.setVelocityByEnd(e2); - } - configuration() { - const e2 = this._friction.configuration(); - e2.push.apply(e2, this._spring.configuration()); - return e2; - } + return pre; + }, {}); } -function createAnimation(scroll, onScroll, onEnd) { - const state = { - id: 0, - cancelled: false +function parseHtml(html) { + html = removeDOCTYPE(html); + const stacks = []; + const results = { + node: "root", + children: [] }; - function startAnimation2(state2, scroll2, onScroll2, onEnd2) { - if (!state2 || !state2.cancelled) { - onScroll2(scroll2); - const isDone = scroll2.done(); - if (!isDone) { - if (!state2.cancelled) { - state2.id = requestAnimationFrame(startAnimation2.bind(null, state2, scroll2, onScroll2, onEnd2)); + HTMLParser(html, { + start: function(tag, attrs, unary) { + const node = { + name: tag + }; + if (attrs.length !== 0) { + node.attrs = parseAttrs(attrs); + } + if (unary) { + const parent = stacks[0] || results; + if (!parent.children) { + parent.children = []; } + parent.children.push(node); + } else { + stacks.unshift(node); } - if (isDone && onEnd2) { - onEnd2(scroll2); + }, + end: function(tag) { + const node = stacks.shift(); + if (node.name !== tag) + console.error("invalid state: mismatch end tag"); + if (stacks.length === 0) { + results.children.push(node); + } else { + const parent = stacks[0]; + if (!parent.children) { + parent.children = []; + } + parent.children.push(node); } + }, + chars: function(text) { + const node = { + type: "text", + text + }; + if (stacks.length === 0) { + results.children.push(node); + } else { + const parent = stacks[0]; + if (!parent.children) { + parent.children = []; + } + parent.children.push(node); + } + }, + comment: function(text) { + const node = { + node: "comment", + text + }; + const parent = stacks[0]; + if (!parent.children) { + parent.children = []; + } + parent.children.push(node); } - } - function cancel(state2) { - if (state2 && state2.id) { - cancelAnimationFrame(state2.id); - } - if (state2) { - state2.cancelled = true; - } - } - startAnimation2(state, scroll, onScroll, onEnd); - return { - cancel: cancel.bind(null, state), - model: scroll - }; + }); + return results.children; } -class Scroller { - constructor(element, options) { - options = options || {}; - this._element = element; - this._options = options; - this._enableSnap = options.enableSnap || false; - this._itemSize = options.itemSize || 0; - this._enableX = options.enableX || false; - this._enableY = options.enableY || false; - this._shouldDispatchScrollEvent = !!options.onScroll; - if (this._enableX) { - this._extent = (options.scrollWidth || this._element.offsetWidth) - this._element.parentElement.offsetWidth; - this._scrollWidth = options.scrollWidth; - } else { - this._extent = (options.scrollHeight || this._element.offsetHeight) - this._element.parentElement.offsetHeight; - this._scrollHeight = options.scrollHeight; - } - this._position = 0; - this._scroll = new Scroll(this._extent, options.friction, options.spring); - this._onTransitionEnd = this.onTransitionEnd.bind(this); - this.updatePosition(); - } - onTouchStart() { - this._startPosition = this._position; - this._lastChangePos = this._startPosition; - if (this._startPosition > 0) { - this._startPosition /= 0.5; - } else { - if (this._startPosition < -this._extent) { - this._startPosition = (this._startPosition + this._extent) / 0.5 - this._extent; - } +const TAGS = { + a: "", + abbr: "", + b: "", + blockquote: "", + br: "", + code: "", + col: ["span", "width"], + colgroup: ["span", "width"], + dd: "", + del: "", + div: "", + dl: "", + dt: "", + em: "", + fieldset: "", + h1: "", + h2: "", + h3: "", + h4: "", + h5: "", + h6: "", + hr: "", + i: "", + img: ["alt", "src", "height", "width"], + ins: "", + label: "", + legend: "", + li: "", + ol: ["start", "type"], + p: "", + q: "", + span: "", + strong: "", + sub: "", + sup: "", + table: ["width"], + tbody: "", + td: ["colspan", "rowspan", "height", "width"], + tfoot: "", + th: ["colspan", "rowspan", "height", "width"], + thead: "", + tr: "", + ul: "" +}; +const CHARS = { + amp: "&", + gt: ">", + lt: "<", + nbsp: " ", + quot: '"', + apos: "'" +}; +function decodeEntities(htmlString) { + return htmlString.replace(/&(([a-zA-Z]+)|(#x{0,1}[\da-zA-Z]+));/gi, function(match, stage) { + if (shared.hasOwn(CHARS, stage) && CHARS[stage]) { + return CHARS[stage]; } - if (this._animation) { - this._animation.cancel(); - this._scrolling = false; + if (/^#[0-9]{1,4}$/.test(stage)) { + return String.fromCharCode(stage.slice(1)); } - this.updatePosition(); - } - onTouchMove(x, y) { - let startPosition = this._startPosition; - if (this._enableX) { - startPosition += x; - } else if (this._enableY) { - startPosition += y; + if (/^#x[0-9a-f]{1,4}$/i.test(stage)) { + return String.fromCharCode("0" + stage.slice(1)); } - if (startPosition > 0) { - startPosition *= 0.5; - } else if (startPosition < -this._extent) { - startPosition = 0.5 * (startPosition + this._extent) - this._extent; + const wrap = document.createElement("div"); + wrap.innerHTML = match; + return wrap.innerText || wrap.textContent; + }); +} +function parseNodes(nodes, parentNode) { + nodes.forEach(function(node) { + if (!shared.isPlainObject(node)) { + return; } - this._position = startPosition; - this.updatePosition(); - this.dispatchScroll(); - } - onTouchEnd(x, y, o2) { - if (this._enableSnap && this._position > -this._extent && this._position < 0) { - if (this._enableY && (Math.abs(y) < this._itemSize && Math.abs(o2.y) < 300 || Math.abs(o2.y) < 150)) { - this.snap(); + if (!shared.hasOwn(node, "type") || node.type === "node") { + if (!(typeof node.name === "string" && node.name)) { return; } - if (this._enableX && (Math.abs(x) < this._itemSize && Math.abs(o2.x) < 300 || Math.abs(o2.x) < 150)) { - this.snap(); + const tagName = node.name.toLowerCase(); + if (!shared.hasOwn(TAGS, tagName)) { return; } - } - if (this._enableX) { - this._scroll.set(this._position, o2.x); - } else if (this._enableY) { - this._scroll.set(this._position, o2.y); - } - let c; - if (this._enableSnap) { - const s = this._scroll._friction.x(100); - const l = s % this._itemSize; - c = Math.abs(l) > this._itemSize / 2 ? s - (this._itemSize - Math.abs(l)) : s - l; - if (c <= 0 && c >= -this._extent) { - this._scroll.setVelocityByEnd(c); - } - } - this._lastTime = Date.now(); - this._lastDelay = 0; - this._scrolling = true; - this._lastChangePos = this._position; - this._lastIdx = Math.floor(Math.abs(this._position / this._itemSize)); - this._animation = createAnimation(this._scroll, () => { - const e2 = Date.now(); - const i = (e2 - this._scroll._startTime) / 1e3; - const r = this._scroll.x(i); - this._position = r; - this.updatePosition(); - const o22 = this._scroll.dx(i); - if (this._shouldDispatchScrollEvent && e2 - this._lastTime > this._lastDelay) { - this.dispatchScroll(); - this._lastDelay = Math.abs(2e3 / o22); - this._lastTime = e2; - } - }, () => { - if (this._enableSnap) { - if (c <= 0 && c >= -this._extent) { - this._position = c; - this.updatePosition(); - } - if (typeof this._options.onSnap === "function") { - this._options.onSnap(Math.floor(Math.abs(this._position) / this._itemSize)); - } - } - if (this._shouldDispatchScrollEvent) { - this.dispatchScroll(); + const elem = document.createElement(tagName); + if (!elem) { + return; } - this._scrolling = false; - }); - } - onTransitionEnd() { - this._element.style.webkitTransition = ""; - this._element.style.transition = ""; - this._element.removeEventListener("transitionend", this._onTransitionEnd); - if (this._snapping) { - this._snapping = false; - } - this.dispatchScroll(); - } - snap() { - const itemSize = this._itemSize; - const position = this._position % itemSize; - const i = Math.abs(position) > this._itemSize / 2 ? this._position - (itemSize - Math.abs(position)) : this._position - position; - if (this._position !== i) { - this._snapping = true; - this.scrollTo(-i); - if (typeof this._options.onSnap === "function") { - this._options.onSnap(Math.floor(Math.abs(this._position) / this._itemSize)); + const attrs = node.attrs; + if (shared.isPlainObject(attrs)) { + const tagAttrs = TAGS[tagName] || []; + Object.keys(attrs).forEach(function(name) { + let value = attrs[name]; + switch (name) { + case "class": + Array.isArray(value) && (value = value.join(" ")); + case "style": + elem.setAttribute(name, value); + break; + default: + if (tagAttrs.indexOf(name) !== -1) { + elem.setAttribute(name, value); + } + } + }); } - } - } - scrollTo(position, time) { - if (this._animation) { - this._animation.cancel(); - this._scrolling = false; - } - if (typeof position === "number") { - this._position = -position; - } - if (this._position < -this._extent) { - this._position = -this._extent; - } else { - if (this._position > 0) { - this._position = 0; + const children = node.children; + if (Array.isArray(children) && children.length) { + parseNodes(node.children, elem); } - } - const transition = "transform " + (time || 0.2) + "s ease-out"; - this._element.style.webkitTransition = "-webkit-" + transition; - this._element.style.transition = transition; - this.updatePosition(); - this._element.addEventListener("transitionend", this._onTransitionEnd); - } - dispatchScroll() { - if (typeof this._options.onScroll === "function" && Math.round(Number(this._lastPos)) !== Math.round(this._position)) { - this._lastPos = this._position; - const event = { - target: { - scrollLeft: this._enableX ? -this._position : 0, - scrollTop: this._enableY ? -this._position : 0, - scrollHeight: this._scrollHeight || this._element.offsetHeight, - scrollWidth: this._scrollWidth || this._element.offsetWidth, - offsetHeight: this._element.parentElement.offsetHeight, - offsetWidth: this._element.parentElement.offsetWidth - } - }; - this._options.onScroll(event); - } - } - update(height, scrollHeight, itemSize) { - let extent = 0; - const position = this._position; - if (this._enableX) { - extent = this._element.childNodes.length ? (scrollHeight || this._element.offsetWidth) - this._element.parentElement.offsetWidth : 0; - this._scrollWidth = scrollHeight; - } else { - extent = this._element.childNodes.length ? (scrollHeight || this._element.offsetHeight) - this._element.parentElement.offsetHeight : 0; - this._scrollHeight = scrollHeight; - } - if (typeof height === "number") { - this._position = -height; - } - if (this._position < -extent) { - this._position = -extent; + parentNode.appendChild(elem); } else { - if (this._position > 0) { - this._position = 0; + if (node.type === "text" && typeof node.text === "string" && node.text !== "") { + parentNode.appendChild(document.createTextNode(decodeEntities(node.text))); } } - this._itemSize = itemSize || this._itemSize; - this.updatePosition(); - if (position !== this._position) { - this.dispatchScroll(); - if (typeof this._options.onSnap === "function") { - this._options.onSnap(Math.floor(Math.abs(this._position) / this._itemSize)); - } + }); + return parentNode; +} +const props$e = { + nodes: { + type: [Array, String], + default: function() { + return []; } - this._extent = extent; - this._scroll._extent = extent; } - updatePosition() { - let transform = ""; - if (this._enableX) { - transform = "translateX(" + this._position + "px) translateZ(0)"; - } else { - if (this._enableY) { - transform = "translateY(" + this._position + "px) translateZ(0)"; +}; +var index$i = /* @__PURE__ */ defineBuiltInComponent({ + name: "RichText", + compatConfig: { + MODE: 3 + }, + props: props$e, + setup(props2) { + const rootRef = vue.ref(null); + function _renderNodes(nodes) { + if (typeof nodes === "string") { + nodes = parseHtml(nodes); } + const nodeList = parseNodes(nodes, document.createDocumentFragment()); + rootRef.value.firstElementChild.innerHTML = ""; + rootRef.value.firstElementChild.appendChild(nodeList); } - this._element.style.webkitTransform = transform; - this._element.style.transform = transform; + vue.watch(() => props2.nodes, (value) => { + _renderNodes(value); + }); + return () => { + return vue.createVNode("uni-rich-text", { + "ref": rootRef + }, [vue.createVNode("div", null, null)], 512); + }; } - isScrolling() { - return this._scrolling || this._snapping; +}); +uniShared.passive(true); +const props$d = { + scrollX: { + type: [Boolean, String], + default: false + }, + scrollY: { + type: [Boolean, String], + default: false + }, + upperThreshold: { + type: [Number, String], + default: 50 + }, + lowerThreshold: { + type: [Number, String], + default: 50 + }, + scrollTop: { + type: [Number, String], + default: 0 + }, + scrollLeft: { + type: [Number, String], + default: 0 + }, + scrollIntoView: { + type: String, + default: "" + }, + scrollWithAnimation: { + type: [Boolean, String], + default: false + }, + enableBackToTop: { + type: [Boolean, String], + default: false + }, + refresherEnabled: { + type: [Boolean, String], + default: false + }, + refresherThreshold: { + type: Number, + default: 45 + }, + refresherDefaultStyle: { + type: String, + default: "back" + }, + refresherBackground: { + type: String, + default: "#fff" + }, + refresherTriggered: { + type: [Boolean, String], + default: false } -} -function useScroller(element, options) { - const touchInfo = { - trackingID: -1, - maxDy: 0, - maxDx: 0 - }; - const scroller = new Scroller(element, options); - function findDelta(event) { - const touchtrackEvent = event; - const mouseEvent = event; - return touchtrackEvent.detail.state === "move" || touchtrackEvent.detail.state === "end" ? { - x: touchtrackEvent.detail.dx, - y: touchtrackEvent.detail.dy - } : { - x: mouseEvent.screenX - touchInfo.x, - y: mouseEvent.screenY - touchInfo.y +}; +var index$h = /* @__PURE__ */ defineBuiltInComponent({ + name: "ScrollView", + compatConfig: { + MODE: 3 + }, + props: props$d, + emits: ["scroll", "scrolltoupper", "scrolltolower", "refresherrefresh", "refresherrestore", "refresherpulling", "refresherabort"], + setup(props2, { + emit: emit2, + slots + }) { + const rootRef = vue.ref(null); + const main = vue.ref(null); + const wrap = vue.ref(null); + const content = vue.ref(null); + const refresherinner = vue.ref(null); + const trigger = useCustomEvent(rootRef, emit2); + const { + state, + scrollTopNumber, + scrollLeftNumber + } = useScrollViewState(props2); + useScrollViewLoader(props2, state, scrollTopNumber, scrollLeftNumber, trigger, rootRef, main, content); + const mainStyle = vue.computed(() => { + let style = ""; + props2.scrollX ? style += "overflow-x:auto;" : style += "overflow-x:hidden;"; + props2.scrollY ? style += "overflow-y:auto;" : style += "overflow-y:hidden;"; + return style; + }); + return () => { + const { + refresherEnabled, + refresherBackground, + refresherDefaultStyle + } = props2; + const { + refresherHeight, + refreshState, + refreshRotate + } = state; + return vue.createVNode("uni-scroll-view", { + "ref": rootRef + }, [vue.createVNode("div", { + "ref": wrap, + "class": "uni-scroll-view" + }, [vue.createVNode("div", { + "ref": main, + "style": mainStyle.value, + "class": "uni-scroll-view" + }, [vue.createVNode("div", { + "ref": content, + "class": "uni-scroll-view-content" + }, [refresherEnabled ? vue.createVNode("div", { + "ref": refresherinner, + "style": { + backgroundColor: refresherBackground, + height: refresherHeight + "px" + }, + "class": "uni-scroll-view-refresher" + }, [refresherDefaultStyle !== "none" ? vue.createVNode("div", { + "class": "uni-scroll-view-refresh" + }, [vue.createVNode("div", { + "class": "uni-scroll-view-refresh-inner" + }, [refreshState == "pulling" ? vue.createVNode("svg", { + "style": { + transform: "rotate(" + refreshRotate + "deg)" + }, + "fill": "#2BD009", + "class": "uni-scroll-view-refresh__icon", + "width": "24", + "height": "24", + "viewBox": "0 0 24 24" + }, [vue.createVNode("path", { + "d": "M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z" + }, null), vue.createVNode("path", { + "d": "M0 0h24v24H0z", + "fill": "none" + }, null)], 4) : null, refreshState == "refreshing" ? vue.createVNode("svg", { + "class": "uni-scroll-view-refresh__spinner", + "width": "24", + "height": "24", + "viewBox": "25 25 50 50" + }, [vue.createVNode("circle", { + "cx": "50", + "cy": "50", + "r": "20", + "fill": "none", + "style": "color: #2bd009", + "stroke-width": "3" + }, null)]) : null])]) : null, refresherDefaultStyle == "none" ? slots.refresher && slots.refresher() : null], 4) : null, slots.default && slots.default()], 512)], 4)], 512)], 512); }; } - function handleTouchStart(event) { - const touchtrackEvent = event; - const mouseEvent = event; - if (touchtrackEvent.detail.state === "start") { - touchInfo.trackingID = "touch"; - touchInfo.x = touchtrackEvent.detail.x; - touchInfo.y = touchtrackEvent.detail.y; +}); +function useScrollViewState(props2) { + const scrollTopNumber = vue.computed(() => { + return Number(props2.scrollTop) || 0; + }); + const scrollLeftNumber = vue.computed(() => { + return Number(props2.scrollLeft) || 0; + }); + const state = vue.reactive({ + lastScrollTop: scrollTopNumber.value, + lastScrollLeft: scrollLeftNumber.value, + lastScrollToUpperTime: 0, + lastScrollToLowerTime: 0, + refresherHeight: 0, + refreshRotate: 0, + refreshState: "" + }); + return { + state, + scrollTopNumber, + scrollLeftNumber + }; +} +function useScrollViewLoader(props2, state, scrollTopNumber, scrollLeftNumber, trigger, rootRef, main, content) { + let __transitionEnd = () => { + }; + vue.computed(() => { + var val = Number(props2.upperThreshold); + return isNaN(val) ? 50 : val; + }); + vue.computed(() => { + var val = Number(props2.lowerThreshold); + return isNaN(val) ? 50 : val; + }); + function scrollTo(scrollToValue, direction) { + const container = main.value; + let transformValue = 0; + let transform = ""; + scrollToValue < 0 ? scrollToValue = 0 : direction === "x" && scrollToValue > container.scrollWidth - container.offsetWidth ? scrollToValue = container.scrollWidth - container.offsetWidth : direction === "y" && scrollToValue > container.scrollHeight - container.offsetHeight && (scrollToValue = container.scrollHeight - container.offsetHeight); + direction === "x" ? transformValue = container.scrollLeft - scrollToValue : direction === "y" && (transformValue = container.scrollTop - scrollToValue); + if (transformValue === 0) + return; + let _content = content.value; + _content.style.transition = "transform .3s ease-out"; + _content.style.webkitTransition = "-webkit-transform .3s ease-out"; + if (direction === "x") { + transform = "translateX(" + transformValue + "px) translateZ(0)"; } else { - touchInfo.trackingID = "mouse"; - touchInfo.x = mouseEvent.screenX; - touchInfo.y = mouseEvent.screenY; - } - touchInfo.maxDx = 0; - touchInfo.maxDy = 0; - touchInfo.historyX = [0]; - touchInfo.historyY = [0]; - touchInfo.historyTime = [ - touchtrackEvent.detail.timeStamp || mouseEvent.timeStamp - ]; - touchInfo.listener = scroller; - if (scroller.onTouchStart) { - scroller.onTouchStart(); + direction === "y" && (transform = "translateY(" + transformValue + "px) translateZ(0)"); } - event.preventDefault(); + _content.removeEventListener("transitionend", __transitionEnd); + _content.removeEventListener("webkitTransitionEnd", __transitionEnd); + __transitionEnd = () => _transitionEnd(scrollToValue, direction); + _content.addEventListener("transitionend", __transitionEnd); + _content.addEventListener("webkitTransitionEnd", __transitionEnd); + if (direction === "x") { + container.style.overflowX = "hidden"; + } else if (direction === "y") { + container.style.overflowY = "hidden"; + } + _content.style.transform = transform; + _content.style.webkitTransform = transform; } - function handleTouchMove(event) { - const touchtrackEvent = event; - const mouseEvent = event; - if (touchInfo.trackingID !== -1) { - event.preventDefault(); - const delta = findDelta(event); - if (delta) { - for (touchInfo.maxDy = Math.max(touchInfo.maxDy, Math.abs(delta.y)), touchInfo.maxDx = Math.max(touchInfo.maxDx, Math.abs(delta.x)), touchInfo.historyX.push(delta.x), touchInfo.historyY.push(delta.y), touchInfo.historyTime.push(touchtrackEvent.detail.timeStamp || mouseEvent.timeStamp); touchInfo.historyTime.length > 10; ) { - touchInfo.historyTime.shift(); - touchInfo.historyX.shift(); - touchInfo.historyY.shift(); + function _scrollTopChanged(val) { + if (props2.scrollY) { + { + if (props2.scrollWithAnimation) { + scrollTo(val, "y"); + } else { + main.value.scrollTop = val; } - if (touchInfo.listener && touchInfo.listener.onTouchMove) { - touchInfo.listener.onTouchMove(delta.x, delta.y); + } + } + } + function _scrollLeftChanged(val) { + if (props2.scrollX) { + { + if (props2.scrollWithAnimation) { + scrollTo(val, "x"); + } else { + main.value.scrollLeft = val; } } } } - function handleTouchEnd(event) { - if (touchInfo.trackingID !== -1) { - event.preventDefault(); - const delta = findDelta(event); - if (delta) { - const listener = touchInfo.listener; - touchInfo.trackingID = -1; - touchInfo.listener = null; - const length = touchInfo.historyTime.length; - const o2 = { - x: 0, - y: 0 - }; - if (length > 2) { - for (let i = touchInfo.historyTime.length - 1, time1 = touchInfo.historyTime[i], x = touchInfo.historyX[i], y = touchInfo.historyY[i]; i > 0; ) { - i--; - const time0 = touchInfo.historyTime[i]; - const time = time1 - time0; - if (time > 30 && time < 50) { - o2.x = (x - touchInfo.historyX[i]) / (time / 1e3); - o2.y = (y - touchInfo.historyY[i]) / (time / 1e3); - break; - } + function _scrollIntoViewChanged(val) { + if (val) { + if (!/^[_a-zA-Z][-_a-zA-Z0-9:]*$/.test(val)) { + console.error(`id error: scroll-into-view=${val}`); + return; + } + var element = rootRef.value.querySelector("#" + val); + if (element) { + var mainRect = main.value.getBoundingClientRect(); + var elRect = element.getBoundingClientRect(); + if (props2.scrollX) { + var left = elRect.left - mainRect.left; + var scrollLeft = main.value.scrollLeft; + var x = scrollLeft + left; + if (props2.scrollWithAnimation) { + scrollTo(x, "x"); + } else { + main.value.scrollLeft = x; } } - touchInfo.historyTime = []; - touchInfo.historyX = []; - touchInfo.historyY = []; - if (listener && listener.onTouchEnd) { - listener.onTouchEnd(delta.x, delta.y, o2); + if (props2.scrollY) { + var top = elRect.top - mainRect.top; + var scrollTop = main.value.scrollTop; + var y = scrollTop + top; + if (props2.scrollWithAnimation) { + scrollTo(y, "y"); + } else { + main.value.scrollTop = y; + } } } } } - return { - scroller, - handleTouchStart, - handleTouchMove, - handleTouchEnd - }; -} -let scopedIndex = 0; -function useScopedClass(indicatorHeightRef) { - const className = `uni-picker-view-content-${scopedIndex++}`; - function updateStyle() { - const style = document.createElement("style"); - style.innerText = `.uni-picker-view-content.${className}>*{height: ${indicatorHeightRef.value}px;overflow: hidden;}`; - document.head.appendChild(style); - } - vue.watch(() => indicatorHeightRef.value, updateStyle); - return className; -} -var PickerViewColumn = /* @__PURE__ */ defineBuiltInComponent({ - name: "PickerViewColumn", - setup(props2, { - slots, - emit: emit2 - }) { - const rootRef = vue.ref(null); - const contentRef = vue.ref(null); - const getPickerViewColumn = vue.inject("getPickerViewColumn"); - const instance = vue.getCurrentInstance(); - const currentRef = getPickerViewColumn ? getPickerViewColumn(instance) : vue.ref(0); - const pickerViewProps = vue.inject("pickerViewProps"); - const pickerViewState = vue.inject("pickerViewState"); - const indicatorHeight = vue.ref(34); - const resizeSensorRef = vue.ref(null); - const maskSize = vue.computed(() => (pickerViewState.height - indicatorHeight.value) / 2); - const { - state: scopedAttrsState - } = useScopedAttrs(); - const className = useScopedClass(indicatorHeight); - let scroller; - const state = vue.reactive({ - current: currentRef.value, - length: 0 - }); - function updatesScroller() { - } - vue.watch(() => currentRef.value, (current) => { - if (current !== state.current) { - state.current = current; - } - }); - vue.watch(() => state.current, (current) => currentRef.value = current); - vue.watch([() => indicatorHeight.value, () => state.length, () => pickerViewState.height], updatesScroller); - let oldDeltaY = 0; - function handleWheel(event) { - const deltaY = oldDeltaY + event.deltaY; - if (Math.abs(deltaY) > 10) { - oldDeltaY = 0; - let current = Math.min(state.current + (deltaY < 0 ? -1 : 1), state.length - 1); - state.current = current = Math.max(current, 0); - scroller.scrollTo(current * indicatorHeight.value); - } else { - oldDeltaY = deltaY; - } - event.preventDefault(); + function _transitionEnd(val, direction) { + content.value.style.transition = ""; + content.value.style.webkitTransition = ""; + content.value.style.transform = ""; + content.value.style.webkitTransform = ""; + let _main = main.value; + if (direction === "x") { + _main.style.overflowX = props2.scrollX ? "auto" : "hidden"; + _main.scrollLeft = val; + } else if (direction === "y") { + _main.style.overflowY = props2.scrollY ? "auto" : "hidden"; + _main.scrollTop = val; } - function handleTap({ - clientY - }) { - const el = rootRef.value; - if (!scroller.isScrolling()) { - const rect = el.getBoundingClientRect(); - const r = clientY - rect.top - pickerViewState.height / 2; - const o2 = indicatorHeight.value / 2; - if (!(Math.abs(r) <= o2)) { - const a2 = Math.ceil((Math.abs(r) - o2) / indicatorHeight.value); - const s = r < 0 ? -a2 : a2; - let current = Math.min(state.current + s, state.length - 1); - state.current = current = Math.max(current, 0); - scroller.scrollTo(current * indicatorHeight.value); - } - } + content.value.removeEventListener("transitionend", __transitionEnd); + content.value.removeEventListener("webkitTransitionEnd", __transitionEnd); + } + function _setRefreshState(_state) { + switch (_state) { + case "refreshing": + state.refresherHeight = props2.refresherThreshold; + trigger("refresherrefresh", {}, {}); + break; + case "restore": + state.refresherHeight = 0; + trigger("refresherrestore", {}, {}); + break; } - return () => { - const defaultSlots = slots.default && slots.default(); - state.length = flatVNode(defaultSlots).length; - const padding = `${maskSize.value}px 0`; - return vue.createVNode("uni-picker-view-column", { - "ref": rootRef - }, [vue.createVNode("div", { - "onWheel": handleWheel, - "onClick": handleTap, - "class": "uni-picker-view-group" - }, [vue.createVNode("div", vue.mergeProps(scopedAttrsState.attrs, { - "class": ["uni-picker-view-mask", pickerViewProps.maskClass], - "style": `background-size: 100% ${maskSize.value}px;${pickerViewProps.maskStyle}` - }), null, 16), vue.createVNode("div", vue.mergeProps(scopedAttrsState.attrs, { - "class": ["uni-picker-view-indicator", pickerViewProps.indicatorClass], - "style": pickerViewProps.indicatorStyle - }), [vue.createVNode(ResizeSensor, { - "ref": resizeSensorRef, - "onResize": ({ - height - }) => indicatorHeight.value = height - }, null, 8, ["onResize"])], 16), vue.createVNode("div", { - "ref": contentRef, - "class": ["uni-picker-view-content", className], - "style": { - padding - } - }, [defaultSlots], 6)], 40, ["onWheel", "onClick"])], 512); - }; + state.refreshState = _state; } -}); -const VALUES = { - activeColor: uniShared.PRIMARY_COLOR, - backgroundColor: "#EBEBEB", - activeMode: "backwards" -}; -const props$h = { - percent: { - type: [Number, String], - default: 0, - validator(value) { - return !isNaN(parseFloat(value)); + vue.watch(scrollTopNumber, (val) => { + _scrollTopChanged(val); + }); + vue.watch(scrollLeftNumber, (val) => { + _scrollLeftChanged(val); + }); + vue.watch(() => props2.scrollIntoView, (val) => { + _scrollIntoViewChanged(val); + }); + vue.watch(() => props2.refresherTriggered, (val) => { + if (val === true) { + _setRefreshState("refreshing"); + } else if (val === false) { + _setRefreshState("restore"); } + }); +} +const props$c = { + name: { + type: String, + default: "" }, - showInfo: { - type: [Boolean, String], - default: false + min: { + type: [Number, String], + default: 0 }, - strokeWidth: { + max: { type: [Number, String], - default: 6, - validator(value) { - return !isNaN(parseFloat(value)); - } + default: 100 + }, + value: { + type: [Number, String], + default: 0 + }, + step: { + type: [Number, String], + default: 1 + }, + disabled: { + type: [Boolean, String], + default: false }, color: { type: String, - default: VALUES.activeColor + default: "#e9e9e9" }, - activeColor: { + backgroundColor: { type: String, - default: VALUES.activeColor + default: "#e9e9e9" }, - backgroundColor: { + activeColor: { type: String, - default: VALUES.backgroundColor + default: "#007aff" }, - active: { - type: [Boolean, String], - default: false + selectedColor: { + type: String, + default: "#007aff" }, - activeMode: { + blockColor: { type: String, - default: VALUES.activeMode + default: "#ffffff" }, - duration: { + blockSize: { type: [Number, String], - default: 30, - validator(value) { - return !isNaN(parseFloat(value)); - } + default: 28 + }, + showValue: { + type: [Boolean, String], + default: false } }; -var index$l = /* @__PURE__ */ defineBuiltInComponent({ - name: "Progress", - props: props$h, - setup(props2) { - const state = useProgressState(props2); - _activeAnimation(state, props2); - vue.watch(() => state.realPercent, (newValue, oldValue) => { - state.strokeTimer && clearInterval(state.strokeTimer); - state.lastPercent = oldValue || 0; - _activeAnimation(state, props2); +var index$g = /* @__PURE__ */ defineBuiltInComponent({ + name: "Slider", + props: props$c, + emits: ["changing", "change"], + setup(props2, { + emit: emit2 + }) { + const sliderRef = vue.ref(null); + const sliderValueRef = vue.ref(null); + const sliderHandleRef = vue.ref(null); + const sliderValue = vue.ref(Number(props2.value)); + vue.watch(() => props2.value, (val) => { + sliderValue.value = Number(val); }); + const trigger = useCustomEvent(sliderRef, emit2); + const state = useSliderState(props2, sliderValue); + const { + _onClick, + _onTrack + } = useSliderLoader(props2, sliderValue, sliderRef, sliderValueRef, trigger); return () => { const { - showInfo - } = props2; - const { - outerBarStyle, - innerBarStyle, - currentPercent + setBgColor, + setBlockBg, + setActiveColor, + setBlockStyle } = state; - return vue.createVNode("uni-progress", { - "class": "uni-progress" + return vue.createVNode("uni-slider", { + "ref": sliderRef, + "onClick": withWebEvent(_onClick) }, [vue.createVNode("div", { - "style": outerBarStyle, - "class": "uni-progress-bar" + "class": "uni-slider-wrapper" }, [vue.createVNode("div", { - "style": innerBarStyle, - "class": "uni-progress-inner-bar" - }, null, 4)], 4), showInfo ? vue.createVNode("p", { - "class": "uni-progress-info" - }, [currentPercent + "%"]) : ""]); + "class": "uni-slider-tap-area" + }, [vue.createVNode("div", { + "style": setBgColor.value, + "class": "uni-slider-handle-wrapper" + }, [vue.createVNode("div", { + "ref": sliderHandleRef, + "style": setBlockBg.value, + "class": "uni-slider-handle" + }, null, 4), vue.createVNode("div", { + "style": setBlockStyle.value, + "class": "uni-slider-thumb" + }, null, 4), vue.createVNode("div", { + "style": setActiveColor.value, + "class": "uni-slider-track" + }, null, 4)], 4)]), vue.withDirectives(vue.createVNode("span", { + "ref": sliderValueRef, + "class": "uni-slider-value" + }, [sliderValue.value], 512), [[vue.vShow, props2.showValue]])]), vue.createVNode("slot", null, null)], 8, ["onClick"]); }; } }); -function useProgressState(props2) { - const currentPercent = vue.ref(0); - const outerBarStyle = vue.computed(() => `background-color: ${props2.backgroundColor}; height: ${props2.strokeWidth}px;`); - const innerBarStyle = vue.computed(() => { - const backgroundColor = props2.color !== VALUES.activeColor && props2.activeColor === VALUES.activeColor ? props2.color : props2.activeColor; - return `width: ${currentPercent.value}%;background-color: ${backgroundColor}`; - }); - const realPercent = vue.computed(() => { - let realValue = parseFloat(props2.percent); - realValue < 0 && (realValue = 0); - realValue > 100 && (realValue = 100); - return realValue; - }); - const state = vue.reactive({ - outerBarStyle, - innerBarStyle, - realPercent, - currentPercent, - strokeTimer: 0, - lastPercent: 0 - }); +function useSliderState(props2, sliderValue) { + const _getValueWidth = () => { + const max = Number(props2.max); + const min = Number(props2.min); + return 100 * (sliderValue.value - min) / (max - min) + "%"; + }; + const _getBgColor = () => { + return props2.backgroundColor !== "#e9e9e9" ? props2.backgroundColor : props2.color !== "#007aff" ? props2.color : "#007aff"; + }; + const _getActiveColor = () => { + return props2.activeColor !== "#007aff" ? props2.activeColor : props2.selectedColor !== "#e9e9e9" ? props2.selectedColor : "#e9e9e9"; + }; + const state = { + setBgColor: vue.computed(() => ({ + backgroundColor: _getBgColor() + })), + setBlockBg: vue.computed(() => ({ + left: _getValueWidth() + })), + setActiveColor: vue.computed(() => ({ + backgroundColor: _getActiveColor(), + width: _getValueWidth() + })), + setBlockStyle: vue.computed(() => ({ + width: props2.blockSize + "px", + height: props2.blockSize + "px", + marginLeft: -props2.blockSize / 2 + "px", + marginTop: -props2.blockSize / 2 + "px", + left: _getValueWidth(), + backgroundColor: props2.blockColor + })) + }; return state; } -function _activeAnimation(state, props2) { - if (props2.active) { - state.currentPercent = props2.activeMode === VALUES.activeMode ? 0 : state.lastPercent; - state.strokeTimer = setInterval(() => { - if (state.currentPercent + 1 > state.realPercent) { - state.currentPercent = state.realPercent; - state.strokeTimer && clearInterval(state.strokeTimer); - } else { - state.currentPercent += 1; - } - }, parseFloat(props2.duration)); - } else { - state.currentPercent = state.realPercent; - } -} -const uniRadioGroupKey = PolySymbol(process.env.NODE_ENV !== "production" ? "uniCheckGroup" : "ucg"); -const props$g = { - name: { - type: String, - default: "" - } -}; -var index$k = /* @__PURE__ */ defineBuiltInComponent({ - name: "RadioGroup", - props: props$g, - setup(props2, { - emit: emit2, - slots - }) { - const rootRef = vue.ref(null); - const trigger = useCustomEvent(rootRef, emit2); - useProvideRadioGroup(props2, trigger); - return () => { - return vue.createVNode("uni-radio-group", { - "ref": rootRef - }, [slots.default && slots.default()], 512); - }; - } -}); -function useProvideRadioGroup(props2, trigger) { - const fields2 = []; - const getFieldsValue = () => { - var _a; - return (_a = fields2.find((field) => field.value.radioChecked)) == null ? void 0 : _a.value.value; +function useSliderLoader(props2, sliderValue, sliderRef, sliderValueRef, trigger) { + const _onClick = ($event) => { + if (props2.disabled) { + return; + } + _onUserChangedValue($event); + trigger("change", $event, { + value: sliderValue.value + }); + }; + const _filterValue = (e2) => { + const max = Number(props2.max); + const min = Number(props2.min); + const step = Number(props2.step); + return e2 < min ? min : e2 > max ? max : computeController.mul.call(Math.round((e2 - min) / step), step) + min; + }; + const _onUserChangedValue = (e2) => { + const max = Number(props2.max); + const min = Number(props2.min); + const sliderRightBox = sliderValueRef.value; + const sliderRightBoxLeft = getComputedStyle(sliderRightBox, null).marginLeft; + let sliderRightBoxWidth = sliderRightBox.offsetWidth; + sliderRightBoxWidth = sliderRightBoxWidth + parseInt(sliderRightBoxLeft); + const slider = sliderRef.value; + const offsetWidth = slider.offsetWidth - (props2.showValue ? sliderRightBoxWidth : 0); + const boxLeft = slider.getBoundingClientRect().left; + const value = (e2.x - boxLeft) * (max - min) / offsetWidth + min; + sliderValue.value = _filterValue(value); }; - vue.provide(uniRadioGroupKey, { - addField(field) { - fields2.push(field); - }, - removeField(field) { - fields2.splice(fields2.indexOf(field), 1); - }, - radioChange($event, field) { - const index2 = fields2.indexOf(field); - _resetRadioGroupValue(index2, true); - trigger("change", $event, { - value: getFieldsValue() + const _onTrack = (e2) => { + if (!props2.disabled) { + return e2.detail.state === "move" ? (_onUserChangedValue({ + x: e2.detail.x + }), trigger("changing", e2, { + value: sliderValue.value + }), false) : e2.detail.state === "end" && trigger("change", e2, { + value: sliderValue.value }); } - }); + }; const uniForm = vue.inject(uniFormKey, false); - if (uniForm) { - uniForm.addField({ + if (!!uniForm) { + const field = { + reset: () => sliderValue.value = Number(props2.min), submit: () => { - let data = ["", null]; + const data = ["", null]; if (props2.name !== "") { data[0] = props2.name; - data[1] = getFieldsValue(); + data[1] = sliderValue.value; } return data; } - }); - } - function setFieldChecked(field, radioChecked) { - field.value = { - radioChecked, - value: field.value.value }; + uniForm.addField(field); } - function _resetRadioGroupValue(key, change) { - fields2.forEach((value, index2) => { - if (index2 === key) { - return; - } - if (change) { - setFieldChecked(fields2[index2], false); - } else { - fields2.forEach((v2, i) => { - if (index2 >= i) { - return; - } - if (fields2[i].value.radioChecked) { - setFieldChecked(fields2[index2], false); - } - }); - } - }); - } - return fields2; + return { + _onClick, + _onTrack + }; } -const props$f = { - 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: "" +var computeController = { + mul: function(arg) { + let m = 0; + let s1 = this.toString(); + let s2 = arg.toString(); + try { + m += s1.split(".")[1].length; + } catch (e2) { + } + try { + m += s2.split(".")[1].length; + } catch (e2) { + } + return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m); } }; -var index$j = /* @__PURE__ */ defineBuiltInComponent({ - name: "Radio", - props: props$f, - setup(props2, { - slots - }) { - const radioChecked = vue.ref(props2.checked); - const radioValue = vue.ref(props2.value); - const checkedStyle = vue.computed(() => `background-color: ${props2.color};border-color: ${props2.color};`); - vue.watch([() => props2.checked, () => props2.value], ([newChecked, newModelValue]) => { - radioChecked.value = newChecked; - radioValue.value = newModelValue; - }); - const reset = () => { - radioChecked.value = false; - }; - const { - uniCheckGroup, - uniLabel, - field - } = useRadioInject(radioChecked, radioValue, reset); - const _onClick = ($event) => { - if (props2.disabled) { - return; - } - radioChecked.value = true; - uniCheckGroup && uniCheckGroup.radioChange($event, field); - }; - if (!!uniLabel) { - uniLabel.addHandler(_onClick); +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 str; +} +function validateProtocolFail(name, msg) { + console.warn(`${name}: ${msg}`); +} +function validateProtocol(name, data, protocol, onFail) { + if (!onFail) { + onFail = validateProtocolFail; + } + for (const key in protocol) { + const errMsg = validateProp(key, data[key], protocol[key], !shared.hasOwn(data, key)); + if (shared.isString(errMsg)) { + onFail(name, errMsg); } - return () => { - const { - booleanAttrs - } = useBooleanAttr(props2, "disabled"); - return vue.createVNode("uni-radio", vue.mergeProps(booleanAttrs, { - "onClick": _onClick - }), [vue.createVNode("div", { - "class": "uni-radio-wrapper" - }, [vue.createVNode("div", { - "class": ["uni-radio-input", { - "uni-radio-input-disabled": props2.disabled - }], - "style": radioChecked.value ? checkedStyle.value : "" - }, [radioChecked.value ? createSvgIconVNode(ICON_PATH_SUCCESS_NO_CIRCLE, "#fff", 18) : ""], 6), slots.default && slots.default()])], 16, ["onClick"]); - }; } -}); -function useRadioInject(radioChecked, radioValue, reset) { - const field = vue.computed({ - get: () => ({ - radioChecked: Boolean(radioChecked.value), - value: radioValue.value - }), - set: ({ - radioChecked: checked - }) => { - radioChecked.value = checked; +} +function validateProtocols(name, args, protocol, onFail) { + if (!protocol) { + return; + } + if (!shared.isArray(protocol)) { + return validateProtocol(name, args[0] || Object.create(null), protocol, onFail); + } + const len = protocol.length; + const argsLen = args.length; + for (let i = 0; i < len; i++) { + const opts = protocol[i]; + const data = Object.create(null); + if (argsLen > i) { + data[opts.name] = args[i]; } - }); - const formField = { - reset - }; - const uniCheckGroup = vue.inject(uniRadioGroupKey, false); - if (!!uniCheckGroup) { - uniCheckGroup.addField(field); + validateProtocol(name, data, {[opts.name]: opts}, onFail); } - const uniForm = vue.inject(uniFormKey, false); - if (!!uniForm) { - uniForm.addField(formField); +} +function validateProp(name, value, prop, isAbsent) { + if (!shared.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 = shared.isArray(type) ? type : [type]; + const expectedTypes = []; + for (let i = 0; i < types.length && !isValid; i++) { + const {valid, expectedType} = assertType(value, types[i]); + expectedTypes.push(expectedType || ""); + isValid = valid; + } + if (!isValid) { + return getInvalidTypeMessage(name, value, expectedTypes); + } + } + if (validator) { + return validator(value); + } +} +const isSimpleType = /* @__PURE__ */ shared.makeMap("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; + } + } else if (expectedType === "Object") { + valid = shared.isObject(value); + } else if (expectedType === "Array") { + valid = shared.isArray(value); + } else { + { + valid = value instanceof type; + } } - const uniLabel = vue.inject(uniLabelKey, false); return { - uniCheckGroup, - uniForm, - uniLabel, - field + valid, + expectedType }; } -function removeDOCTYPE(html) { - return html.replace(/<\?xml.*\?>\n/, "").replace(/\n/, "").replace(/\n/, ""); +function getInvalidTypeMessage(name, value, expectedTypes) { + let message = `Invalid args: type check failed for args "${name}". Expected ${expectedTypes.map(shared.capitalize).join(", ")}`; + const expectedType = expectedTypes[0]; + const receivedType = shared.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 parseAttrs(attrs) { - return attrs.reduce(function(pre, attr2) { - let value = attr2.value; - const name = attr2.name; - if (value.match(/ /) && name !== "style") { - value = value.split(" "); - } - if (pre[name]) { - if (Array.isArray(pre[name])) { - pre[name].push(value); - } else { - pre[name] = [pre[name], value]; - } - } else { - pre[name] = value; - } - return pre; - }, {}); +function getType(ctor) { + const match = ctor && ctor.toString().match(/^\s*function (\w+)/); + return match ? match[1] : ""; } -function parseHtml(html) { - html = removeDOCTYPE(html); - const stacks = []; - const results = { - node: "root", - children: [] - }; - HTMLParser(html, { - start: function(tag, attrs, unary) { - const node = { - name: tag - }; - if (attrs.length !== 0) { - node.attrs = parseAttrs(attrs); - } - if (unary) { - const parent = stacks[0] || results; - if (!parent.children) { - parent.children = []; - } - parent.children.push(node); - } else { - stacks.unshift(node); - } - }, - end: function(tag) { - const node = stacks.shift(); - if (node.name !== tag) - console.error("invalid state: mismatch end tag"); - if (stacks.length === 0) { - results.children.push(node); - } else { - const parent = stacks[0]; - if (!parent.children) { - parent.children = []; - } - parent.children.push(node); - } - }, - chars: function(text) { - const node = { - type: "text", - text - }; - if (stacks.length === 0) { - results.children.push(node); - } else { - const parent = stacks[0]; - if (!parent.children) { - parent.children = []; - } - parent.children.push(node); - } - }, - comment: function(text) { - const node = { - node: "comment", - text - }; - const parent = stacks[0]; - if (!parent.children) { - parent.children = []; - } - parent.children.push(node); - } - }); - return results.children; +function styleValue(value, type) { + if (type === "String") { + return `"${value}"`; + } else if (type === "Number") { + return `${Number(value)}`; + } else { + return `${value}`; + } } -const TAGS = { - a: "", - abbr: "", - b: "", - blockquote: "", - br: "", - code: "", - col: ["span", "width"], - colgroup: ["span", "width"], - dd: "", - del: "", - div: "", - dl: "", - dt: "", - em: "", - fieldset: "", - h1: "", - h2: "", - h3: "", - h4: "", - h5: "", - h6: "", - hr: "", - i: "", - img: ["alt", "src", "height", "width"], - ins: "", - label: "", - legend: "", - li: "", - ol: ["start", "type"], - p: "", - q: "", - span: "", - strong: "", - sub: "", - sup: "", - table: ["width"], - tbody: "", - td: ["colspan", "rowspan", "height", "width"], - tfoot: "", - th: ["colspan", "rowspan", "height", "width"], - thead: "", - tr: "", - ul: "" -}; -const CHARS = { - amp: "&", - gt: ">", - lt: "<", - nbsp: " ", - quot: '"', - apos: "'" -}; -function decodeEntities(htmlString) { - return htmlString.replace(/&(([a-zA-Z]+)|(#x{0,1}[\da-zA-Z]+));/gi, function(match, stage) { - if (shared.hasOwn(CHARS, stage) && CHARS[stage]) { - return CHARS[stage]; - } - if (/^#[0-9]{1,4}$/.test(stage)) { - return String.fromCharCode(stage.slice(1)); - } - if (/^#x[0-9a-f]{1,4}$/i.test(stage)) { - return String.fromCharCode("0" + stage.slice(1)); - } - const wrap = document.createElement("div"); - wrap.innerHTML = match; - return wrap.innerText || wrap.textContent; - }); +function isExplicable(type) { + const explicitTypes = ["string", "number", "boolean"]; + return explicitTypes.some((elem) => type.toLowerCase() === elem); } -function parseNodes(nodes, parentNode) { - nodes.forEach(function(node) { - if (!shared.isPlainObject(node)) { - return; - } - if (!shared.hasOwn(node, "type") || node.type === "node") { - if (!(typeof node.name === "string" && node.name)) { - return; - } - const tagName = node.name.toLowerCase(); - if (!shared.hasOwn(TAGS, tagName)) { - return; - } - const elem = document.createElement(tagName); - if (!elem) { - return; - } - const attrs = node.attrs; - if (shared.isPlainObject(attrs)) { - const tagAttrs = TAGS[tagName] || []; - Object.keys(attrs).forEach(function(name) { - let value = attrs[name]; - switch (name) { - case "class": - Array.isArray(value) && (value = value.join(" ")); - case "style": - elem.setAttribute(name, value); - break; - default: - if (tagAttrs.indexOf(name) !== -1) { - elem.setAttribute(name, value); - } - } - }); - } - const children = node.children; - if (Array.isArray(children) && children.length) { - parseNodes(node.children, elem); - } - parentNode.appendChild(elem); - } else { - if (node.type === "text" && typeof node.text === "string" && node.text !== "") { - parentNode.appendChild(document.createTextNode(decodeEntities(node.text))); - } +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); } - }); - return parentNode; + }; +} +let invokeCallbackId = 1; +const invokeCallbacks = {}; +function addInvokeCallback(id, name, callback, keepAlive = false) { + invokeCallbacks[id] = { + name, + keepAlive, + callback + }; + return id; } -const props$e = { - nodes: { - type: [Array, String], - default: function() { - return []; - } - } -}; -var index$i = /* @__PURE__ */ defineBuiltInComponent({ - name: "RichText", - compatConfig: { - MODE: 3 - }, - props: props$e, - setup(props2) { - const rootRef = vue.ref(null); - function _renderNodes(nodes) { - if (typeof nodes === "string") { - nodes = parseHtml(nodes); +function invokeCallback(id, res, extras) { + if (typeof id === "number") { + const opts = invokeCallbacks[id]; + if (opts) { + if (!opts.keepAlive) { + delete invokeCallbacks[id]; } - const nodeList = parseNodes(nodes, document.createDocumentFragment()); - rootRef.value.firstElementChild.innerHTML = ""; - rootRef.value.firstElementChild.appendChild(nodeList); + return opts.callback(res, extras); } - vue.watch(() => props2.nodes, (value) => { - _renderNodes(value); - }); - return () => { - return vue.createVNode("uni-rich-text", { - "ref": rootRef - }, [vue.createVNode("div", null, null)], 512); - }; } -}); -uniShared.passive(true); -const props$d = { - scrollX: { - type: [Boolean, String], - default: false - }, - scrollY: { - type: [Boolean, String], - default: false - }, - upperThreshold: { - type: [Number, String], - default: 50 - }, - lowerThreshold: { - type: [Number, String], - default: 50 - }, - scrollTop: { - type: [Number, String], - default: 0 - }, - scrollLeft: { - type: [Number, String], - default: 0 - }, - scrollIntoView: { - type: String, - default: "" - }, - scrollWithAnimation: { - type: [Boolean, String], - default: false - }, - enableBackToTop: { - type: [Boolean, String], - default: false - }, - refresherEnabled: { - type: [Boolean, String], - default: false - }, - refresherThreshold: { - type: Number, - default: 45 - }, - refresherDefaultStyle: { - type: String, - default: "back" - }, - refresherBackground: { - type: String, - default: "#fff" - }, - refresherTriggered: { - type: [Boolean, String], - default: false + return res; +} +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 (shared.isFunction(fn)) { + apiCallbacks[name] = tryCatch(fn); + delete args[name]; + } } -}; -var index$h = /* @__PURE__ */ defineBuiltInComponent({ - name: "ScrollView", - compatConfig: { - MODE: 3 - }, - props: props$d, - emits: ["scroll", "scrolltoupper", "scrolltolower", "refresherrefresh", "refresherrestore", "refresherpulling", "refresherabort"], - setup(props2, { - emit: emit2, - slots - }) { - const rootRef = vue.ref(null); - const main = vue.ref(null); - const wrap = vue.ref(null); - const content = vue.ref(null); - const refresherinner = vue.ref(null); - const trigger = useCustomEvent(rootRef, emit2); - const { - state, - scrollTopNumber, - scrollLeftNumber - } = useScrollViewState(props2); - useScrollViewLoader(props2, state, scrollTopNumber, scrollLeftNumber, trigger, rootRef, main, content); - const mainStyle = vue.computed(() => { - let style = ""; - props2.scrollX ? style += "overflow-x:auto;" : style += "overflow-x:hidden;"; - props2.scrollY ? style += "overflow-y:auto;" : style += "overflow-y:hidden;"; - return style; - }); - return () => { - const { - refresherEnabled, - refresherBackground, - refresherDefaultStyle - } = props2; - const { - refresherHeight, - refreshState, - refreshRotate - } = state; - return vue.createVNode("uni-scroll-view", { - "ref": rootRef - }, [vue.createVNode("div", { - "ref": wrap, - "class": "uni-scroll-view" - }, [vue.createVNode("div", { - "ref": main, - "style": mainStyle.value, - "class": "uni-scroll-view" - }, [vue.createVNode("div", { - "ref": content, - "class": "uni-scroll-view-content" - }, [refresherEnabled ? vue.createVNode("div", { - "ref": refresherinner, - "style": { - backgroundColor: refresherBackground, - height: refresherHeight + "px" - }, - "class": "uni-scroll-view-refresher" - }, [refresherDefaultStyle !== "none" ? vue.createVNode("div", { - "class": "uni-scroll-view-refresh" - }, [vue.createVNode("div", { - "class": "uni-scroll-view-refresh-inner" - }, [refreshState == "pulling" ? vue.createVNode("svg", { - "style": { - transform: "rotate(" + refreshRotate + "deg)" - }, - "fill": "#2BD009", - "class": "uni-scroll-view-refresh__icon", - "width": "24", - "height": "24", - "viewBox": "0 0 24 24" - }, [vue.createVNode("path", { - "d": "M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z" - }, null), vue.createVNode("path", { - "d": "M0 0h24v24H0z", - "fill": "none" - }, null)], 4) : null, refreshState == "refreshing" ? vue.createVNode("svg", { - "class": "uni-scroll-view-refresh__spinner", - "width": "24", - "height": "24", - "viewBox": "25 25 50 50" - }, [vue.createVNode("circle", { - "cx": "50", - "cy": "50", - "r": "20", - "fill": "none", - "style": "color: #2bd009", - "stroke-width": "3" - }, null)]) : null])]) : null, refresherDefaultStyle == "none" ? slots.refresher && slots.refresher() : null], 4) : null, slots.default && slots.default()], 512)], 4)], 512)], 512); - }; + return apiCallbacks; +} +function normalizeErrMsg(errMsg, name) { + if (!errMsg || errMsg.indexOf(":fail") === -1) { + return name + ":ok"; } -}); -function useScrollViewState(props2) { - const scrollTopNumber = vue.computed(() => { - return Number(props2.scrollTop) || 0; - }); - const scrollLeftNumber = vue.computed(() => { - return Number(props2.scrollLeft) || 0; - }); - const state = vue.reactive({ - lastScrollTop: scrollTopNumber.value, - lastScrollLeft: scrollLeftNumber.value, - lastScrollToUpperTime: 0, - lastScrollToLowerTime: 0, - refresherHeight: 0, - refreshRotate: 0, - refreshState: "" - }); - return { - state, - scrollTopNumber, - scrollLeftNumber - }; + return name + errMsg.substring(errMsg.indexOf(":fail")); } -function useScrollViewLoader(props2, state, scrollTopNumber, scrollLeftNumber, trigger, rootRef, main, content) { - let __transitionEnd = () => { - }; - vue.computed(() => { - var val = Number(props2.upperThreshold); - return isNaN(val) ? 50 : val; - }); - vue.computed(() => { - var val = Number(props2.lowerThreshold); - return isNaN(val) ? 50 : val; - }); - function scrollTo(scrollToValue, direction) { - const container = main.value; - let transformValue = 0; - let transform = ""; - scrollToValue < 0 ? scrollToValue = 0 : direction === "x" && scrollToValue > container.scrollWidth - container.offsetWidth ? scrollToValue = container.scrollWidth - container.offsetWidth : direction === "y" && scrollToValue > container.scrollHeight - container.offsetHeight && (scrollToValue = container.scrollHeight - container.offsetHeight); - direction === "x" ? transformValue = container.scrollLeft - scrollToValue : direction === "y" && (transformValue = container.scrollTop - scrollToValue); - if (transformValue === 0) - return; - let _content = content.value; - _content.style.transition = "transform .3s ease-out"; - _content.style.webkitTransition = "-webkit-transform .3s ease-out"; - if (direction === "x") { - transform = "translateX(" + transformValue + "px) translateZ(0)"; +function createAsyncApiCallback(name, args = {}, {beforeAll, beforeSuccess} = {}) { + if (!shared.isPlainObject(args)) { + args = {}; + } + const {success, fail, complete} = getApiCallbacks(args); + const hasSuccess = shared.isFunction(success); + const hasFail = shared.isFunction(fail); + const hasComplete = shared.isFunction(complete); + const callbackId = invokeCallbackId++; + addInvokeCallback(callbackId, name, (res) => { + res = res || {}; + res.errMsg = normalizeErrMsg(res.errMsg, name); + shared.isFunction(beforeAll) && beforeAll(res); + if (res.errMsg === name + ":ok") { + shared.isFunction(beforeSuccess) && beforeSuccess(res); + hasSuccess && success(res); } else { - direction === "y" && (transform = "translateY(" + transformValue + "px) translateZ(0)"); - } - _content.removeEventListener("transitionend", __transitionEnd); - _content.removeEventListener("webkitTransitionEnd", __transitionEnd); - __transitionEnd = () => _transitionEnd(scrollToValue, direction); - _content.addEventListener("transitionend", __transitionEnd); - _content.addEventListener("webkitTransitionEnd", __transitionEnd); - if (direction === "x") { - container.style.overflowX = "hidden"; - } else if (direction === "y") { - container.style.overflowY = "hidden"; + hasFail && fail(res); } - _content.style.transform = transform; - _content.style.webkitTransform = transform; + hasComplete && complete(res); + }); + return callbackId; +} +const callbacks = [API_SUCCESS, API_FAIL, API_COMPLETE]; +function hasCallback(args) { + if (shared.isPlainObject(args) && callbacks.find((cb) => shared.isFunction(args[cb]))) { + return true; } - function _scrollTopChanged(val) { - if (props2.scrollY) { - { - if (props2.scrollWithAnimation) { - scrollTo(val, "y"); - } else { - main.value.scrollTop = val; - } - } - } + return false; +} +function handlePromise(promise) { + if (__UNI_FEATURE_PROMISE__) { + return promise.then((data) => { + return [null, data]; + }).catch((err) => [err]); } - function _scrollLeftChanged(val) { - if (props2.scrollX) { - { - if (props2.scrollWithAnimation) { - scrollTo(val, "x"); - } else { - main.value.scrollLeft = val; - } - } + return promise; +} +function promisify(fn) { + return (args = {}) => { + if (hasCallback(args)) { + return fn(args); } + return handlePromise(new Promise((resolve, reject) => { + fn(shared.extend(args, {success: resolve, fail: reject})); + })); + }; +} +function formatApiArgs(args, options) { + const params = args[0]; + if (!options || !shared.isPlainObject(options.formatArgs) && shared.isPlainObject(params)) { + return; } - function _scrollIntoViewChanged(val) { - if (val) { - if (!/^[_a-zA-Z][-_a-zA-Z0-9:]*$/.test(val)) { - console.error(`id error: scroll-into-view=${val}`); - return; + const formatArgs = options.formatArgs; + const keys = Object.keys(formatArgs); + for (let i = 0; i < keys.length; i++) { + const name = keys[i]; + const formatterOrDefaultValue = formatArgs[name]; + if (shared.isFunction(formatterOrDefaultValue)) { + const errMsg = formatterOrDefaultValue(args[0][name], params); + if (shared.isString(errMsg)) { + return errMsg; } - var element = rootRef.value.querySelector("#" + val); - if (element) { - var mainRect = main.value.getBoundingClientRect(); - var elRect = element.getBoundingClientRect(); - if (props2.scrollX) { - var left = elRect.left - mainRect.left; - var scrollLeft = main.value.scrollLeft; - var x = scrollLeft + left; - if (props2.scrollWithAnimation) { - scrollTo(x, "x"); - } else { - main.value.scrollLeft = x; - } - } - if (props2.scrollY) { - var top = elRect.top - mainRect.top; - var scrollTop = main.value.scrollTop; - var y = scrollTop + top; - if (props2.scrollWithAnimation) { - scrollTo(y, "y"); - } else { - main.value.scrollTop = y; - } - } + } else { + if (!shared.hasOwn(params, name)) { + params[name] = formatterOrDefaultValue; } } } - function _transitionEnd(val, direction) { - content.value.style.transition = ""; - content.value.style.webkitTransition = ""; - content.value.style.transform = ""; - content.value.style.webkitTransform = ""; - let _main = main.value; - if (direction === "x") { - _main.style.overflowX = props2.scrollX ? "auto" : "hidden"; - _main.scrollLeft = val; - } else if (direction === "y") { - _main.style.overflowY = props2.scrollY ? "auto" : "hidden"; - _main.scrollTop = val; - } - content.value.removeEventListener("transitionend", __transitionEnd); - content.value.removeEventListener("webkitTransitionEnd", __transitionEnd); +} +function invokeSuccess(id, name, res) { + return invokeCallback(id, shared.extend(res || {}, {errMsg: name + ":ok"})); +} +function invokeFail(id, name, err) { + return invokeCallback(id, {errMsg: name + ":fail" + (err ? " " + err : "")}); +} +function beforeInvokeApi(name, args, protocol, options) { + if (process.env.NODE_ENV !== "production") { + validateProtocols(name, args, protocol); } - function _setRefreshState(_state) { - switch (_state) { - case "refreshing": - state.refresherHeight = props2.refresherThreshold; - trigger("refresherrefresh", {}, {}); - break; - case "restore": - state.refresherHeight = 0; - trigger("refresherrestore", {}, {}); - break; + if (options && options.beforeInvoke) { + const errMsg2 = options.beforeInvoke(args); + if (shared.isString(errMsg2)) { + return errMsg2; } - state.refreshState = _state; } - vue.watch(scrollTopNumber, (val) => { - _scrollTopChanged(val); - }); - vue.watch(scrollLeftNumber, (val) => { - _scrollLeftChanged(val); - }); - vue.watch(() => props2.scrollIntoView, (val) => { - _scrollIntoViewChanged(val); - }); - vue.watch(() => props2.refresherTriggered, (val) => { - if (val === true) { - _setRefreshState("refreshing"); - } else if (val === false) { - _setRefreshState("restore"); + const errMsg = formatApiArgs(args, options); + if (errMsg) { + return errMsg; + } +} +function wrapperTaskApi(name, fn, protocol, options) { + return (args) => { + const id = createAsyncApiCallback(name, args, options); + const errMsg = beforeInvokeApi(name, [args], protocol, options); + if (errMsg) { + return invokeFail(id, name, errMsg); } - }); + return fn(args, { + resolve: (res) => invokeSuccess(id, name, res), + reject: (err) => invokeFail(id, name, err) + }); + }; } -const props$c = { - name: { - type: String, - default: "" - }, - min: { - type: [Number, String], - default: 0 - }, - max: { - type: [Number, String], - default: 100 - }, - value: { - type: [Number, String], - default: 0 - }, - step: { +function wrapperSyncApi(name, fn, protocol, options) { + return (...args) => { + const errMsg = beforeInvokeApi(name, args, protocol, options); + if (errMsg) { + throw new Error(errMsg); + } + return fn.apply(null, args); + }; +} +function wrapperAsyncApi(name, fn, protocol, options) { + return wrapperTaskApi(name, fn, protocol, 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_UPX2PX = "upx2px"; +const Upx2pxProtocol = [ + { + name: "upx", type: [Number, String], - default: 1 - }, - disabled: { - type: [Boolean, String], - default: false - }, - color: { - type: String, - default: "#e9e9e9" - }, - backgroundColor: { + required: true + } +]; +const upx2px = /* @__PURE__ */ defineSyncApi(API_UPX2PX, (number, newDeviceWidth) => { + { + return number; + } +}, Upx2pxProtocol); +const canvasEventCallbacks = createCallbacks("canvasEvent"); +ServiceJSBridge.subscribe("onCanvasMethodCallback", ({callbackId, data}) => { + const callback = canvasEventCallbacks.pop(callbackId); + if (callback) { + callback(data); + } +}); +const API_ON_TAB_BAR_MID_BUTTON_TAP = "onTabBarMidButtonTap"; +const getSelectedTextRangeEventCallbacks = createCallbacks("getSelectedTextRangeEvent"); +ServiceJSBridge.subscribe && ServiceJSBridge.subscribe("onGetSelectedTextRange", ({callbackId, data}) => { + const callback = getSelectedTextRangeEventCallbacks.pop(callbackId); + if (callback) { + callback(data); + } +}); +const API_GET_STORAGE = "getStorage"; +const GetStorageProtocol = { + key: { type: String, - default: "#e9e9e9" - }, - activeColor: { + required: true + } +}; +const API_GET_STORAGE_SYNC = "getStorageSync"; +const GetStorageSyncProtocol = [ + { + name: "key", type: String, - default: "#007aff" - }, - selectedColor: { + required: true + } +]; +const API_SET_STORAGE = "setStorage"; +const SetStorageProtocol = { + key: { type: String, - default: "#007aff" + required: true }, - blockColor: { + data: { + required: true + } +}; +const API_SET_STORAGE_SYNC = "setStorageSync"; +const SetStorageSyncProtocol = [ + { + name: "key", type: String, - default: "#ffffff" - }, - blockSize: { - type: [Number, String], - default: 28 + required: true }, - showValue: { - type: [Boolean, String], - default: false + { + name: "data", + required: true } +]; +const API_REMOVE_STORAGE = "removeStorage"; +const RemoveStorageProtocol = GetStorageProtocol; +const RemoveStorageSyncProtocol = GetStorageSyncProtocol; +const API_REQUEST = "request"; +const dataType = { + JSON: "json" }; -var index$g = /* @__PURE__ */ defineBuiltInComponent({ - name: "Slider", - props: props$c, - emits: ["changing", "change"], - setup(props2, { - emit: emit2 - }) { - const sliderRef = vue.ref(null); - const sliderValueRef = vue.ref(null); - const sliderHandleRef = vue.ref(null); - const sliderValue = vue.ref(Number(props2.value)); - vue.watch(() => props2.value, (val) => { - sliderValue.value = Number(val); - }); - const trigger = useCustomEvent(sliderRef, emit2); - const state = useSliderState(props2, sliderValue); - const { - _onClick, - _onTrack - } = useSliderLoader(props2, sliderValue, sliderRef, sliderValueRef, trigger); - return () => { - const { - setBgColor, - setBlockBg, - setActiveColor, - setBlockStyle - } = state; - return vue.createVNode("uni-slider", { - "ref": sliderRef, - "onClick": withWebEvent(_onClick) - }, [vue.createVNode("div", { - "class": "uni-slider-wrapper" - }, [vue.createVNode("div", { - "class": "uni-slider-tap-area" - }, [vue.createVNode("div", { - "style": setBgColor.value, - "class": "uni-slider-handle-wrapper" - }, [vue.createVNode("div", { - "ref": sliderHandleRef, - "style": setBlockBg.value, - "class": "uni-slider-handle" - }, null, 4), vue.createVNode("div", { - "style": setBlockStyle.value, - "class": "uni-slider-thumb" - }, null, 4), vue.createVNode("div", { - "style": setActiveColor.value, - "class": "uni-slider-track" - }, null, 4)], 4)]), vue.withDirectives(vue.createVNode("span", { - "ref": sliderValueRef, - "class": "uni-slider-value" - }, [sliderValue.value], 512), [[vue.vShow, props2.showValue]])]), vue.createVNode("slot", null, null)], 8, ["onClick"]); - }; +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 (shared.hasOwn(data, key)) { + let v2 = data[key]; + if (typeof v2 === "undefined" || v2 === null) { + v2 = ""; + } else if (shared.isPlainObject(v2)) { + v2 = JSON.stringify(v2); + } + params[encode(key)] = encode(v2); + } } -}); -function useSliderState(props2, sliderValue) { - const _getValueWidth = () => { - const max = Number(props2.max); - const min = Number(props2.min); - return 100 * (sliderValue.value - min) / (max - min) + "%"; - }; - const _getBgColor = () => { - return props2.backgroundColor !== "#e9e9e9" ? props2.backgroundColor : props2.color !== "#007aff" ? props2.color : "#007aff"; - }; - const _getActiveColor = () => { - return props2.activeColor !== "#007aff" ? props2.activeColor : props2.selectedColor !== "#e9e9e9" ? props2.selectedColor : "#e9e9e9"; - }; - const state = { - setBgColor: vue.computed(() => ({ - backgroundColor: _getBgColor() - })), - setBlockBg: vue.computed(() => ({ - left: _getValueWidth() - })), - setActiveColor: vue.computed(() => ({ - backgroundColor: _getActiveColor(), - width: _getValueWidth() - })), - setBlockStyle: vue.computed(() => ({ - width: props2.blockSize + "px", - height: props2.blockSize + "px", - marginLeft: -props2.blockSize / 2 + "px", - marginTop: -props2.blockSize / 2 + "px", - left: _getValueWidth(), - backgroundColor: props2.blockColor - })) - }; - return state; + query = Object.keys(params).map((item) => `${item}=${params[item]}`).join("&"); + return url + (query ? "?" + query : "") + (hash ? "#" + hash : ""); } -function useSliderLoader(props2, sliderValue, sliderRef, sliderValueRef, trigger) { - const _onClick = ($event) => { - if (props2.disabled) { - return; - } - _onUserChangedValue($event); - trigger("change", $event, { - value: sliderValue.value - }); - }; - const _filterValue = (e2) => { - const max = Number(props2.max); - const min = Number(props2.min); - const step = Number(props2.step); - return e2 < min ? min : e2 > max ? max : computeController.mul.call(Math.round((e2 - min) / step), step) + min; - }; - const _onUserChangedValue = (e2) => { - const max = Number(props2.max); - const min = Number(props2.min); - const sliderRightBox = sliderValueRef.value; - const sliderRightBoxLeft = getComputedStyle(sliderRightBox, null).marginLeft; - let sliderRightBoxWidth = sliderRightBox.offsetWidth; - sliderRightBoxWidth = sliderRightBoxWidth + parseInt(sliderRightBoxLeft); - const slider = sliderRef.value; - const offsetWidth = slider.offsetWidth - (props2.showValue ? sliderRightBoxWidth : 0); - const boxLeft = slider.getBoundingClientRect().left; - const value = (e2.x - boxLeft) * (max - min) / offsetWidth + min; - sliderValue.value = _filterValue(value); - }; - const _onTrack = (e2) => { - if (!props2.disabled) { - return e2.detail.state === "move" ? (_onUserChangedValue({ - x: e2.detail.x - }), trigger("changing", e2, { - value: sliderValue.value - }), false) : e2.detail.state === "end" && trigger("change", e2, { - value: sliderValue.value - }); - } - }; - const uniForm = vue.inject(uniFormKey, false); - if (!!uniForm) { - const field = { - reset: () => sliderValue.value = Number(props2.min), - submit: () => { - const data = ["", null]; - if (props2.name !== "") { - data[0] = props2.name; - data[1] = sliderValue.value; +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] && shared.isPlainObject(params.data) && Object.keys(params.data).length) { + params.url = stringifyQuery(value, params.data); + } + }, + 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 data; } - }; - uniForm.addField(field); - } - return { - _onClick, - _onTrack - }; -} -var computeController = { - mul: function(arg) { - let m = 0; - let s1 = this.toString(); - let s2 = arg.toString(); - try { - m += s1.split(".")[1].length; - } catch (e2) { - } - try { - m += s2.split(".")[1].length; - } catch (e2) { + }, + 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; + } } - return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m); } }; const props$b = { @@ -7194,151 +7225,120 @@ function getSameOriginUrl(url) { } return urlToFile(url).then(fileToUrl); } -const API_UPX2PX = "upx2px"; -const Upx2pxProtocol = [ - { - name: "upx", - type: [Number, String], - required: true - } -]; -const upx2px = /* @__PURE__ */ defineSyncApi(API_UPX2PX, (number, newDeviceWidth) => { - { - return number; +function errorHandler(err, instance, info) { + if (!instance) { + throw err; } -}, Upx2pxProtocol); -const canvasEventCallbacks = createCallbacks("canvasEvent"); -ServiceJSBridge.subscribe("onCanvasMethodCallback", ({callbackId, data}) => { - const callback = canvasEventCallbacks.pop(callbackId); - if (callback) { - callback(data); + const app = getApp(); + if (!app || !app.$vm) { + throw err; } -}); -const API_ON_TAB_BAR_MID_BUTTON_TAP = "onTabBarMidButtonTap"; -const getSelectedTextRangeEventCallbacks = createCallbacks("getSelectedTextRangeEvent"); -ServiceJSBridge.subscribe && ServiceJSBridge.subscribe("onGetSelectedTextRange", ({callbackId, data}) => { - const callback = getSelectedTextRangeEventCallbacks.pop(callbackId); - if (callback) { - callback(data); + { + invokeHook(app.$vm, "onError", err); } -}); -const API_GET_STORAGE = "getStorage"; -const GetStorageProtocol = { - key: { - type: String, - required: true +} +function initApp$1(app) { + const appConfig = app._context.config; + if (shared.isFunction(app._component.onError)) { + appConfig.errorHandler = errorHandler; } -}; -const API_GET_STORAGE_SYNC = "getStorageSync"; -const GetStorageSyncProtocol = [ + const globalProperties = appConfig.globalProperties; { - name: "key", - type: String, - required: true + globalProperties.$set = set; + globalProperties.$applyOptions = applyOptions; } -]; -const API_SET_STORAGE = "setStorage"; -const SetStorageProtocol = { - key: { - type: String, - required: true - }, - data: { - required: true +} +const pageMetaKey = PolySymbol(process.env.NODE_ENV !== "production" ? "UniPageMeta" : "upm"); +function usePageMeta() { + return vue.inject(pageMetaKey); +} +function providePageMeta(id) { + const pageMeta = initPageMeta(id); + vue.provide(pageMetaKey, pageMeta); + return pageMeta; +} +function usePageRoute() { + if (__UNI_FEATURE_PAGES__) { + return vueRouter.useRoute(); } -}; -const API_SET_STORAGE_SYNC = "setStorageSync"; -const SetStorageSyncProtocol = [ - { - name: "key", - type: String, - required: true - }, - { - name: "data", - required: true + const url = location.href; + const searchPos = url.indexOf("?"); + const hashPos = url.indexOf("#", searchPos > -1 ? searchPos : 0); + let query = {}; + if (searchPos > -1) { + query = uniShared.parseQuery(url.slice(searchPos + 1, hashPos > -1 ? hashPos : url.length)); + } + const {meta} = __uniRoutes[0]; + return { + meta, + query, + path: "/" + meta.route + }; +} +function initPageMeta(id) { + if (__UNI_FEATURE_PAGES__) { + return vue.reactive(normalizePageMeta(JSON.parse(JSON.stringify(mergePageMeta(id, vueRouter.useRoute().meta))))); } + return vue.reactive(normalizePageMeta(JSON.parse(JSON.stringify(mergePageMeta(id, __uniRoutes[0].meta))))); +} +const PAGE_META_KEYS = [ + "navigationBar", + "refreshOptions" ]; -const API_REMOVE_STORAGE = "removeStorage"; -const RemoveStorageProtocol = GetStorageProtocol; -const RemoveStorageSyncProtocol = GetStorageSyncProtocol; -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]; +function mergePageMeta(id, pageMeta) { + const res = shared.extend({id}, __uniConfig.globalStyle, pageMeta); + PAGE_META_KEYS.forEach((name) => { + res[name] = shared.extend({}, __uniConfig.globalStyle[name], pageMeta[name]); }); - for (const key in data) { - if (shared.hasOwn(data, key)) { - let v2 = data[key]; - if (typeof v2 === "undefined" || v2 === null) { - v2 = ""; - } else if (shared.isPlainObject(v2)) { - v2 = JSON.stringify(v2); + return res; +} +function normalizePageMeta(pageMeta) { + if (__UNI_FEATURE_PULL_DOWN_REFRESH__) { + const {enablePullDownRefresh, navigationBar} = pageMeta; + if (enablePullDownRefresh) { + const refreshOptions = shared.extend({ + support: true, + color: "#2BD009", + style: "circle", + height: 70, + range: 150, + offset: 0 + }, pageMeta.refreshOptions); + let offset = rpx2px(refreshOptions.offset); + const {type} = navigationBar; + if (type !== "transparent" && type !== "none") { + offset += uniShared.NAVBAR_HEIGHT + 0; } - params[encode(key)] = encode(v2); + refreshOptions.offset = offset; + refreshOptions.height = rpx2px(refreshOptions.height); + refreshOptions.range = rpx2px(refreshOptions.range); + pageMeta.refreshOptions = refreshOptions; } } - query = Object.keys(params).map((item) => `${item}=${params[item]}`).join("&"); - return url + (query ? "?" + query : "") + (hash ? "#" + hash : ""); + if (__UNI_FEATURE_NAVIGATIONBAR__) { + const {navigationBar} = pageMeta; + const {titleSize, titleColor, backgroundColor} = navigationBar; + navigationBar.type = navigationBar.type || "default"; + navigationBar.backButton = pageMeta.isQuit ? false : true; + navigationBar.titleSize = titleSize || "16px"; + navigationBar.titleColor = titleColor || "#fff"; + navigationBar.backgroundColor = backgroundColor || "#F7F7F7"; + } + return pageMeta; } -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] && shared.isPlainObject(params.data) && Object.keys(params.data).length) { - params.url = stringifyQuery(value, params.data); - } - }, - 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"; - } - } - }, - 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; - } - } +function getStateId() { + { + return 1; } -}; +} +PolySymbol(process.env.NODE_ENV !== "production" ? "layout" : "l"); +let tabBar; +function useTabBar() { + if (!tabBar) { + tabBar = __uniConfig.tabBar && vue.reactive(__uniConfig.tabBar); + } + return tabBar; +} const envMethod = /* @__PURE__ */ (() => "env")(); function normalizeWindowBottom(windowBottom) { return `calc(${windowBottom}px + ${envMethod}(safe-area-inset-bottom))`; diff --git a/packages/uni-h5/dist/uni-h5.es.js b/packages/uni-h5/dist/uni-h5.es.js index e05598e6b61b1676941826d9fdf902926f812811..1226c56c79eab009d4498c655faf24ba74d21523 100644 --- a/packages/uni-h5/dist/uni-h5.es.js +++ b/packages/uni-h5/dist/uni-h5.es.js @@ -1,6 +1,6 @@ -import {isFunction, extend, hyphenate, isPlainObject, isString, isArray, hasOwn, isObject, capitalize, toRawType, makeMap as makeMap$1, isPromise, invokeArrayFns as invokeArrayFns$1} from "@vue/shared"; -import {injectHook, withModifiers, createVNode, getCurrentInstance, inject, provide, reactive, openBlock, createBlock, mergeProps, toDisplayString, defineComponent, ref, computed, watch, onUnmounted, onBeforeUnmount, onActivated, onMounted, nextTick, onBeforeMount, withDirectives, vShow, shallowRef, watchEffect, isVNode, Fragment, markRaw, createTextVNode, onBeforeActivate, onBeforeDeactivate, renderList, onDeactivated, Teleport, createApp, Transition, withCtx, KeepAlive, resolveDynamicComponent, resolveComponent, createCommentVNode, renderSlot} from "vue"; -import {once, passive, normalizeTarget, isBuiltInComponent, initCostomDataset, invokeArrayFns, NAVBAR_HEIGHT, parseQuery, PRIMARY_COLOR, debounce, getCostomDataset, callOptions, removeLeadingSlash, getLen, ON_REACH_BOTTOM_DISTANCE, decodedQuery, updateElementStyle, addFont, scrollTo, RESPONSIVE_MIN_WIDTH, formatDateTime} from "@dcloudio/uni-shared"; +import {isFunction, extend, hyphenate, isPlainObject, isString, hasOwn, isArray, isObject, capitalize, toRawType, makeMap as makeMap$1, isPromise, invokeArrayFns as invokeArrayFns$1} from "@vue/shared"; +import {injectHook, withModifiers, createVNode, getCurrentInstance, openBlock, createBlock, mergeProps, toDisplayString, defineComponent, ref, provide, computed, watch, onUnmounted, inject, onBeforeUnmount, reactive, onActivated, onMounted, nextTick, onBeforeMount, withDirectives, vShow, shallowRef, watchEffect, isVNode, Fragment, markRaw, createTextVNode, onBeforeActivate, onBeforeDeactivate, renderList, onDeactivated, Teleport, createApp, Transition, withCtx, KeepAlive, resolveDynamicComponent, resolveComponent, createCommentVNode, renderSlot} from "vue"; +import {once, passive, normalizeTarget, isBuiltInComponent, initCostomDataset, invokeArrayFns, PRIMARY_COLOR, debounce, callOptions, removeLeadingSlash, getLen, getCostomDataset, NAVBAR_HEIGHT, parseQuery, ON_REACH_BOTTOM_DISTANCE, decodedQuery, updateElementStyle, addFont, scrollTo, RESPONSIVE_MIN_WIDTH, formatDateTime} from "@dcloudio/uni-shared"; import {initVueI18n, LOCALE_EN, LOCALE_ES, LOCALE_FR, LOCALE_ZH_HANS, LOCALE_ZH_HANT} from "@dcloudio/uni-i18n"; import {useRoute, createRouter, createWebHistory, createWebHashHistory, useRouter, isNavigationFailure, RouterView} from "vue-router"; function applyOptions(options, instance2, publicThis) { @@ -485,7 +485,7 @@ var safeAreaInsets = { onChange, offChange }; -var out = safeAreaInsets; +var D__DCloud_local_git_uniAppNext_node_modules_safeAreaInsets_out = safeAreaInsets; const onEventPrevent = /* @__PURE__ */ withModifiers(() => { }, ["prevent"]); const onEventStop = /* @__PURE__ */ withModifiers(() => { @@ -497,10 +497,10 @@ function getWindowOffset() { const left = parseInt(style.getPropertyValue("--window-left")); const right = parseInt(style.getPropertyValue("--window-right")); return { - top: top ? top + out.top : 0, - bottom: bottom ? bottom + out.bottom : 0, - left: left ? left + out.left : 0, - right: right ? right + out.right : 0 + top: top ? top + D__DCloud_local_git_uniAppNext_node_modules_safeAreaInsets_out.top : 0, + bottom: bottom ? bottom + D__DCloud_local_git_uniAppNext_node_modules_safeAreaInsets_out.bottom : 0, + left: left ? left + D__DCloud_local_git_uniAppNext_node_modules_safeAreaInsets_out.left : 0, + right: right ? right + D__DCloud_local_git_uniAppNext_node_modules_safeAreaInsets_out.right : 0 }; } function updateCssVar(cssVars) { @@ -1074,6471 +1074,5829 @@ function invokeHook(vm, name, args) { const hooks = vm.$[name]; return hooks && invokeArrayFns(hooks, args); } -function initOn() { - UniServiceJSBridge.on("onAppEnterForeground", onAppEnterForeground); - UniServiceJSBridge.on("onAppEnterBackground", onAppEnterBackground); -} -function 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"); -} -function onAppEnterBackground() { - invokeHook(getApp(), "onHide"); - invokeHook(getCurrentPage(), "onHide"); +function findElem(vm) { + return vm.$el; } -const SUBSCRIBE_LIFECYCLE_HOOKS = ["onPageScroll", "onReachBottom"]; -function initSubscribe() { - SUBSCRIBE_LIFECYCLE_HOOKS.forEach((name) => UniServiceJSBridge.subscribe(name, createPageEvent(name))); +const SCHEME_RE = /^([a-z-]+:)?\/\//i; +const DATA_RE = /^data:.*,.*/; +const baseUrl = import.meta.env.BASE_URL; +function addBase(filePath) { + return baseUrl + filePath; } -function createPageEvent(name) { - return (args, pageId) => { - const vm = getPageVmById(pageId); - if (vm) { - invokeHook(vm, name, args); +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)); } - }; -} -function initService(app) { - initOn(); - initSubscribe(); - initAppConfig(app._context.config); -} -function errorHandler(err, instance2, info) { - if (!instance2) { - throw err; } - const app = getApp(); - if (!app || !app.$vm) { - throw err; + if (SCHEME_RE.test(filePath) || DATA_RE.test(filePath) || filePath.indexOf("blob:") === 0) { + return filePath; } - { - invokeHook(app.$vm, "onError", err); + const pages = getCurrentPages(); + if (pages.length) { + return addBase(getRealRoute(pages[pages.length - 1].$page.route, filePath).substr(1)); } + return filePath; } -function initApp$1(app) { - const appConfig = app._context.config; - if (isFunction(app._component.onError)) { - appConfig.errorHandler = errorHandler; - } - const globalProperties = appConfig.globalProperties; - { - globalProperties.$set = set; - globalProperties.$applyOptions = applyOptions; - } +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"; } -const pageMetaKey = PolySymbol(process.env.NODE_ENV !== "production" ? "UniPageMeta" : "upm"); -function usePageMeta() { - return inject(pageMetaKey); +function isLandscape(screenFix) { + return screenFix && Math.abs(window.orientation) === 90; } -function providePageMeta(id2) { - const pageMeta = initPageMeta(id2); - provide(pageMetaKey, pageMeta); - return pageMeta; +function getScreenWidth(screenFix, landscape) { + return screenFix ? Math[landscape ? "max" : "min"](screen.width, screen.height) : screen.width; } -function usePageRoute() { - if (__UNI_FEATURE_PAGES__) { - return useRoute(); - } - 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)); - } - const {meta} = __uniRoutes[0]; +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 { - meta, - query, - path: "/" + meta.route + platform: isIOS$1 ? "ios" : "other", + pixelRatio: window.devicePixelRatio, + windowWidth }; } -function initPageMeta(id2) { - if (__UNI_FEATURE_PAGES__) { - return reactive(normalizePageMeta(JSON.parse(JSON.stringify(mergePageMeta(id2, useRoute().meta))))); - } - return reactive(normalizePageMeta(JSON.parse(JSON.stringify(mergePageMeta(id2, __uniRoutes[0].meta))))); +function operateVideoPlayer(videoId, pageId, type, data) { + UniServiceJSBridge.publishHandler("video." + videoId, { + videoId, + type, + data + }, pageId); } -const PAGE_META_KEYS = [ - "navigationBar", - "refreshOptions" -]; -function mergePageMeta(id2, pageMeta) { - const res = extend({id: id2}, __uniConfig.globalStyle, pageMeta); - PAGE_META_KEYS.forEach((name) => { - res[name] = extend({}, __uniConfig.globalStyle[name], pageMeta[name]); - }); - return res; +function operateMap(id2, pageId, type, data) { + UniServiceJSBridge.publishHandler("map." + id2, { + type, + data + }, pageId); } -function normalizePageMeta(pageMeta) { - if (__UNI_FEATURE_PULL_DOWN_REFRESH__) { - const {enablePullDownRefresh, navigationBar} = pageMeta; - if (enablePullDownRefresh) { - const refreshOptions = extend({ - support: true, - color: "#2BD009", - style: "circle", - height: 70, - range: 150, - offset: 0 - }, pageMeta.refreshOptions); - let offset = rpx2px(refreshOptions.offset); - const {type} = navigationBar; - if (type !== "transparent" && type !== "none") { - offset += NAVBAR_HEIGHT + out.top; +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); + } + }, + methods: { + _toggleListeners(type, id2, watch2) { + if (watch2 && !id2) { + return; } - refreshOptions.offset = offset; - refreshOptions.height = rpx2px(refreshOptions.height); - refreshOptions.range = rpx2px(refreshOptions.range); - pageMeta.refreshOptions = refreshOptions; + 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 + }; } } - if (__UNI_FEATURE_NAVIGATIONBAR__) { - const {navigationBar} = pageMeta; - const {titleSize, titleColor, backgroundColor} = navigationBar; - navigationBar.type = navigationBar.type || "default"; - navigationBar.backButton = pageMeta.isQuit ? false : true; - navigationBar.titleSize = titleSize || "16px"; - navigationBar.titleColor = titleColor || "#fff"; - navigationBar.backgroundColor = backgroundColor || "#F7F7F7"; - } - if (__UNI_FEATURE_PAGES__ && history.state) { - const type = history.state.__type__; - if ((type === "redirectTo" || type === "reLaunch") && getCurrentPages().length === 0) { - pageMeta.isEntry = true; - pageMeta.isQuit = true; +}; +function throttle(fn, wait) { + let last = 0; + let timeout; + let waitCallback; + const newFn = function(...arg) { + const now = Date.now(); + clearTimeout(timeout); + waitCallback = () => { + waitCallback = null; + last = now; + fn.apply(this, arg); + }; + if (now - last < wait) { + timeout = setTimeout(waitCallback, wait - (now - last)); + return; } - } - return pageMeta; + waitCallback(); + }; + newFn.cancel = function() { + clearTimeout(timeout); + waitCallback = null; + }; + newFn.flush = function() { + clearTimeout(timeout); + waitCallback && waitCallback(); + }; + return newFn; } -const screen$1 = window.screen; -const documentElement = document.documentElement; -function checkMinWidth(minWidth) { - const sizes = [ - window.outerWidth, - window.outerHeight, - screen$1.width, - screen$1.height, - documentElement.clientWidth, - documentElement.clientHeight - ]; - return Math.max.apply(null, sizes) > minWidth; -} -function getStateId() { - return history.state && history.state.__id__ || 1; -} -PolySymbol(process.env.NODE_ENV !== "production" ? "layout" : "l"); -let tabBar; -function useTabBar() { - if (!tabBar) { - tabBar = __uniConfig.tabBar && reactive(__uniConfig.tabBar); - } - return tabBar; -} -var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -var lookup = /* @__PURE__ */ function() { - const lookup2 = new Uint8Array(256); - for (var i = 0; i < chars.length; i++) { - lookup2[chars.charCodeAt(i)] = i; - } - return lookup2; -}(); -function encode$1(arraybuffer) { - var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = ""; - for (i = 0; i < len; i += 3) { - base64 += chars[bytes[i] >> 2]; - base64 += chars[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4]; - base64 += chars[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6]; - base64 += chars[bytes[i + 2] & 63]; - } - if (len % 3 === 2) { - base64 = base64.substring(0, base64.length - 1) + "="; - } else if (len % 3 === 1) { - base64 = base64.substring(0, base64.length - 2) + "=="; - } - return base64; -} -function decode(base64) { - var bufferLength = base64.length * 0.75, len = base64.length, i, p2 = 0, encoded1, encoded2, encoded3, encoded4; - if (base64[base64.length - 1] === "=") { - bufferLength--; - if (base64[base64.length - 2] === "=") { - bufferLength--; +const _sfc_main$2 = { + 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; } } - var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer); - for (i = 0; i < len; i += 4) { - encoded1 = lookup[base64.charCodeAt(i)]; - encoded2 = lookup[base64.charCodeAt(i + 1)]; - encoded3 = lookup[base64.charCodeAt(i + 2)]; - encoded4 = lookup[base64.charCodeAt(i + 3)]; - bytes[p2++] = encoded1 << 2 | encoded2 >> 4; - bytes[p2++] = (encoded2 & 15) << 4 | encoded3 >> 2; - bytes[p2++] = (encoded3 & 3) << 6 | encoded4 & 63; - } - 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]; - } - return str; +}; +const _hoisted_1$1 = {class: "uni-audio-default"}; +const _hoisted_2$1 = {class: "uni-audio-right"}; +const _hoisted_3$1 = {class: "uni-audio-time"}; +const _hoisted_4$1 = {class: "uni-audio-info"}; +const _hoisted_5 = {class: "uni-audio-name"}; +const _hoisted_6 = {class: "uni-audio-author"}; +function _sfc_render$2(_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$1, [ + 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$1, [ + createVNode("div", _hoisted_3$1, toDisplayString($data.currentTime), 1), + createVNode("div", _hoisted_4$1, [ + createVNode("div", _hoisted_5, toDisplayString($props.name), 1), + createVNode("div", _hoisted_6, toDisplayString($props.author), 1) + ]) + ]) + ]) + ], 16, ["id", "controls"]); } -function elemsInArray(strArr, optionalVal) { - if (!isArray(strArr) || strArr.length === 0 || strArr.find((val) => optionalVal.indexOf(val) === -1)) { - return optionalVal; +_sfc_main$2.render = _sfc_render$2; +function converPx(value) { + if (/^-?\d+[ur]px$/i.test(value)) { + return value.replace(/(^-?\d+)[ur]px$/i, (text2, num) => { + return `${uni.upx2px(parseFloat(num))}px`; + }); + } else if (/^-?[\d\.]+$/.test(value)) { + return `${value}px`; } - return strArr; -} -function validateProtocolFail(name, msg) { - console.warn(`${name}: ${msg}`); + return value || ""; } -function validateProtocol(name, data, protocol, onFail) { - if (!onFail) { - onFail = validateProtocolFail; - } - for (const key in protocol) { - const errMsg = validateProp(key, data[key], protocol[key], !hasOwn(data, key)); - if (isString(errMsg)) { - onFail(name, errMsg); - } - } +function converType(type) { + return type.replace(/[A-Z]/g, (text2) => { + return `-${text2.toLowerCase()}`; + }).replace("webkit", "-webkit"); } -function validateProtocols(name, args, protocol, onFail) { - if (!protocol) { - return; - } - if (!isArray(protocol)) { - return validateProtocol(name, args[0] || Object.create(null), protocol, onFail); +function getStyle(action) { + const animateTypes1 = [ + "matrix", + "matrix3d", + "scale", + "scale3d", + "rotate3d", + "skew", + "translate", + "translate3d" + ]; + const animateTypes2 = [ + "scaleX", + "scaleY", + "scaleZ", + "rotate", + "rotateX", + "rotateY", + "rotateZ", + "skewX", + "skewY", + "translateX", + "translateY", + "translateZ" + ]; + const animateTypes3 = ["opacity", "background-color"]; + const animateTypes4 = ["width", "height", "left", "right", "top", "bottom"]; + const animates = action.animates; + const option = action.option; + const transition = option.transition; + const style = {}; + const transform = []; + animates.forEach((animate) => { + let type = animate.type; + let args = [...animate.args]; + if (animateTypes1.concat(animateTypes2).includes(type)) { + if (type.startsWith("rotate") || type.startsWith("skew")) { + args = args.map((value) => parseFloat(value) + "deg"); + } else if (type.startsWith("translate")) { + args = args.map(converPx); + } + if (animateTypes2.indexOf(type) >= 0) { + args.length = 1; + } + transform.push(`${type}(${args.join(",")})`); + } else if (animateTypes3.concat(animateTypes4).includes(args[0])) { + type = args[0]; + const value = args[1]; + style[type] = animateTypes4.includes(type) ? converPx(value) : value; + } + }); + style.transform = style.webkitTransform = transform.join(" "); + style.transition = style.webkitTransition = Object.keys(style).map((type) => `${converType(type)} ${transition.duration}ms ${transition.timingFunction} ${transition.delay}ms`).join(","); + style.transformOrigin = style.webkitTransformOrigin = option.transformOrigin; + return style; +} +function startAnimation(context) { + const animation2 = context.animation; + if (!animation2 || !animation2.actions || !animation2.actions.length) { + return; } - const len = protocol.length; - const argsLen = args.length; - for (let i = 0; i < len; i++) { - const opts = protocol[i]; - const data = Object.create(null); - if (argsLen > i) { - data[opts.name] = args[i]; + let index2 = 0; + const actions = animation2.actions; + const length = animation2.actions.length; + function animate() { + const action = actions[index2]; + const transition = action.option.transition; + const style = getStyle(action); + Object.keys(style).forEach((key) => { + context.$el.style[key] = style[key]; + }); + index2 += 1; + if (index2 < length) { + setTimeout(animate, transition.duration + transition.delay); } - validateProtocol(name, data, {[opts.name]: opts}, onFail); } + setTimeout(() => { + animate(); + }, 0); } -function validateProp(name, value, prop, isAbsent) { - if (!isPlainObject(prop)) { - prop = {type: prop}; +var animation = { + props: ["animation"], + watch: { + animation: { + deep: true, + handler() { + startAnimation(this); + } + } + }, + mounted() { + startAnimation(this); } - const {type, required, validator: validator2} = prop; - if (required && isAbsent) { - return 'Missing required args: "' + name + '"'; +}; +const defineBuiltInComponent = (options) => { + const {props: props2, mixins} = options; + if (!props2 || !props2.animation) { + (mixins || (options.mixins = [])).push(animation); } - if (value == null && !required) { - return; + return defineSystemComponent(options); +}; +const defineSystemComponent = (options) => { + options.compatConfig = { + MODE: 3 + }; + return defineComponent(options); +}; +const hoverProps = { + hoverClass: { + type: String, + default: "none" + }, + hoverStopPropagation: { + type: Boolean, + default: false + }, + hoverStartTime: { + type: [Number, String], + default: 50 + }, + hoverStayTime: { + type: [Number, String], + default: 400 } - if (type != null) { - let isValid = false; - const types = isArray(type) ? type : [type]; - const expectedTypes = []; - for (let i = 0; i < types.length && !isValid; i++) { - const {valid, expectedType} = assertType(value, types[i]); - expectedTypes.push(expectedType || ""); - isValid = valid; +}; +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 (!isValid) { - return getInvalidTypeMessage(name, value, expectedTypes); + if (!props2.hoverClass || props2.hoverClass === "none" || props2.disabled) { + return; } - } - if (validator2) { - return validator2(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; + if (evt.touches.length > 1) { + return; } - } else if (expectedType === "Object") { - valid = isObject(value); - } else if (expectedType === "Array") { - valid = isArray(value); - } else { - { - valid = value instanceof type; + if (props2.hoverStopPropagation) { + evt._hoverPropagationStopped = true; + } + hoverTouch = true; + hoverStartTimer = setTimeout(() => { + hovering.value = true; + if (!hoverTouch) { + hoverReset(); + } + }, parseInt(props2.hoverStartTime)); + } + function onTouchend() { + hoverTouch = false; + if (hovering.value) { + hoverReset(); } } + function onTouchcancel() { + hoverTouch = false; + hovering.value = false; + clearTimeout(hoverStartTimer); + } return { - valid, - expectedType + hovering, + binding: { + onTouchstartPassive, + onTouchend, + onTouchcancel + } }; } -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}.`; +function useBooleanAttr(props2, keys) { + if (isString(keys)) { + keys = [keys]; } - return message; + return keys.reduce((res, key) => { + if (props2[key]) { + res[key] = true; + } + return res; + }, Object.create(null)); } -function getType(ctor) { - const match = ctor && ctor.toString().match(/^\s*function (\w+)/); - return match ? match[1] : ""; +function withWebEvent(fn) { + return fn.__wwe = true, fn; } -function styleValue(value, type) { - if (type === "String") { - return `"${value}"`; - } else if (type === "Number") { - return `${Number(value)}`; - } else { - return `${value}`; - } +function useCustomEvent(ref2, emit2) { + return (name, evt, detail) => { + if (ref2.value) { + emit2(name, normalizeCustomEvent(name, evt, ref2.value, detail || {})); + } + }; } -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); - } +function useNativeEvent(emit2) { + return (name, evt) => { + emit2(name, createNativeEvent(evt)); }; } -let invokeCallbackId = 1; -const invokeCallbacks = {}; -function addInvokeCallback(id2, name, callback, keepAlive = false) { - invokeCallbacks[id2] = { - name, - keepAlive, - callback +function normalizeCustomEvent(name, domEvt, el, detail) { + const target = normalizeTarget(el); + return { + type: detail.type || name, + timeStamp: domEvt.timeStamp || 0, + target, + currentTarget: target, + detail }; - return id2; } -function invokeCallback(id2, res, extras) { - if (typeof id2 === "number") { - const opts = invokeCallbacks[id2]; - if (opts) { - if (!opts.keepAlive) { - delete invokeCallbacks[id2]; - } - return opts.callback(res, extras); - } +const uniFormKey = PolySymbol(process.env.NODE_ENV !== "production" ? "uniForm" : "uf"); +var index$t = /* @__PURE__ */ defineBuiltInComponent({ + name: "Form", + setup(_props, { + slots, + emit: emit2 + }) { + provideForm(emit2); + return () => createVNode("uni-form", null, [createVNode("span", null, [slots.default && slots.default()])]); } - return res; -} -function findInvokeCallbackByName(name) { - for (const key in invokeCallbacks) { - if (invokeCallbacks[key].name === name) { - return true; +}); +function provideForm(emit2) { + const fields2 = []; + provide(uniFormKey, { + addField(field) { + fields2.push(field); + }, + removeField(field) { + fields2.splice(fields2.indexOf(field), 1); + }, + submit() { + emit2("submit", { + detail: { + value: fields2.reduce((res, field) => { + if (field.submit) { + const [name, value] = field.submit(); + name && (res[name] = value); + } + return res; + }, Object.create(null)) + } + }); + }, + reset() { + fields2.forEach((field) => field.reset && field.reset()); + emit2("reset"); } - } - return false; + }); + return fields2; } -function removeKeepAliveApiCallback(name, callback) { - for (const key in invokeCallbacks) { - const item = invokeCallbacks[key]; - if (item.callback === callback && item.name === name) { - delete invokeCallbacks[key]; - } +const uniLabelKey = PolySymbol(process.env.NODE_ENV !== "production" ? "uniLabel" : "ul"); +const props$B = { + for: { + type: String, + default: "" } -} -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); +}; +var index$s = /* @__PURE__ */ defineBuiltInComponent({ + name: "Label", + props: props$B, + setup(props2, { + slots + }) { + const pageId = useCurrentPageId(); + const handlers = useProvideLabel(); + const pointer = computed(() => props2.for || slots.default && slots.default.length); + const _onClick = withWebEvent(($event) => { + const EventTarget = $event.target; + let stopPropagation = /^uni-(checkbox|radio|switch)-/.test(EventTarget.className); + if (!stopPropagation) { + stopPropagation = /^uni-(checkbox|radio|switch|button)$|^(svg|path)$/i.test(EventTarget.tagName); + } + if (stopPropagation) { + return; + } + if (props2.for) { + UniViewJSBridge.emit("uni-label-click-" + pageId + "-" + props2.for, $event, true); + } else { + handlers[0]($event, true); } + }); + return () => createVNode("uni-label", { + "class": { + "uni-label-pointer": pointer + }, + "onClick": _onClick + }, [slots.default && slots.default()], 10, ["onClick"]); + } +}); +function useProvideLabel() { + const handlers = []; + provide(uniLabelKey, { + addHandler(handler) { + handlers.push(handler); + }, + removeHandler(handler) { + handlers.splice(handlers.indexOf(handler), 1); } }); + return handlers; } -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 useListeners$1(props2, listeners) { + _addListeners(props2.id, listeners); + watch(() => props2.id, (newId, oldId) => { + _removeListeners(oldId, listeners, true); + _addListeners(newId, listeners, true); + }); + onUnmounted(() => { + _removeListeners(props2.id, listeners); + }); } -function normalizeErrMsg(errMsg, name) { - if (!errMsg || errMsg.indexOf(":fail") === -1) { - return name + ":ok"; +function _addListeners(id2, listeners, watch2) { + const pageId = useCurrentPageId(); + if (watch2 && !id2) { + return; } - return name + errMsg.substring(errMsg.indexOf(":fail")); -} -function createAsyncApiCallback(name, args = {}, {beforeAll, beforeSuccess} = {}) { - if (!isPlainObject(args)) { - args = {}; + if (!isPlainObject(listeners)) { + return; } - 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); + Object.keys(listeners).forEach((name) => { + if (watch2) { + if (name.indexOf("@") !== 0 && name.indexOf("uni-") !== 0) { + UniViewJSBridge.on(`uni-${name}-${pageId}-${id2}`, listeners[name]); + } } else { - hasFail && fail(res); + if (name.indexOf("uni-") === 0) { + UniViewJSBridge.on(name, listeners[name]); + } else if (id2) { + UniViewJSBridge.on(`uni-${name}-${pageId}-${id2}`, listeners[name]); + } } - hasComplete && complete(res); }); - return callbackId; } -const callbacks$1 = [API_SUCCESS, API_FAIL, API_COMPLETE]; -function hasCallback(args) { - if (isPlainObject(args) && callbacks$1.find((cb) => isFunction(args[cb]))) { - return true; +function _removeListeners(id2, listeners, watch2) { + const pageId = useCurrentPageId(); + if (watch2 && !id2) { + return; } - return false; -} -function handlePromise(promise) { - if (__UNI_FEATURE_PROMISE__) { - return promise.then((data) => { - return [null, data]; - }).catch((err) => [err]); + if (!isPlainObject(listeners)) { + return; } - return promise; -} -function promisify(fn) { - return (args = {}) => { - if (hasCallback(args)) { - return fn(args); + Object.keys(listeners).forEach((name) => { + if (watch2) { + if (name.indexOf("@") !== 0 && name.indexOf("uni-") !== 0) { + UniViewJSBridge.off(`uni-${name}-${pageId}-${id2}`, listeners[name]); + } + } else { + if (name.indexOf("uni-") === 0) { + UniViewJSBridge.off(name, listeners[name]); + } else if (id2) { + UniViewJSBridge.off(`uni-${name}-${pageId}-${id2}`, listeners[name]); + } } - return handlePromise(new Promise((resolve, reject) => { - fn(extend(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 i = 0; i < keys.length; i++) { - const name = keys[i]; - const formatterOrDefaultValue = formatArgs[name]; - if (isFunction(formatterOrDefaultValue)) { - const errMsg = formatterOrDefaultValue(args[0][name], params); - if (isString(errMsg)) { - return errMsg; +var index$r = /* @__PURE__ */ defineBuiltInComponent({ + 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: "" + }, + loading: { + type: [Boolean, String], + default: false + } + }, + setup(props2, { + slots + }) { + const rootRef = ref(null); + const uniForm = inject(uniFormKey, false); + const { + hovering, + binding + } = useHover(props2); + useI18n(); + const onClick = withWebEvent((e2, isLabelClick) => { + if (props2.disabled) { + return e2.stopImmediatePropagation(); } - } else { - if (!hasOwn(params, name)) { - params[name] = formatterOrDefaultValue; + if (isLabelClick) { + rootRef.value.click(); + } + const formType = props2.formType; + if (formType) { + if (!uniForm) { + return; + } + if (formType === "submit") { + uniForm.submit(); + } else if (formType === "reset") { + uniForm.reset(); + } + return; } + }); + const uniLabel = inject(uniLabelKey, false); + if (uniLabel) { + uniLabel.addHandler(onClick); + onBeforeUnmount(() => { + uniLabel.removeHandler(onClick); + }); } + useListeners$1(props2, { + "label-click": onClick + }); + return () => { + const hoverClass = props2.hoverClass; + const booleanAttrs = useBooleanAttr(props2, "disabled"); + const loadingAttrs = useBooleanAttr(props2, "loading"); + const hasHoverClass = hoverClass && hoverClass !== "none"; + return createVNode("uni-button", mergeProps({ + "ref": rootRef, + "onClick": onClick, + "class": hasHoverClass && hovering.value ? hoverClass : "" + }, hasHoverClass && binding, booleanAttrs, loadingAttrs), [slots.default && slots.default()], 16, ["onClick"]); + }; } -} -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; +}); +var ResizeSensor = /* @__PURE__ */ defineBuiltInComponent({ + name: "ResizeSensor", + props: { + initial: { + type: Boolean, + default: false } + }, + emits: ["resize"], + setup(props2, { + emit: emit2 + }) { + const rootRef = ref(null); + const reset = useResizeSensorReset(rootRef); + const update = useResizeSensorUpdate(rootRef, emit2, reset); + useResizeSensorLifecycle(rootRef, props2, update, reset); + return () => createVNode("uni-resize-sensor", { + "ref": rootRef, + "onAnimationstartOnce": update + }, [createVNode("div", { + "onScroll": update + }, [createVNode("div", null, null)], 40, ["onScroll"]), createVNode("div", { + "onScroll": update + }, [createVNode("div", null, null)], 40, ["onScroll"])], 40, ["onAnimationstartOnce"]); } - 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 useResizeSensorUpdate(rootRef, emit2, reset) { + const size = reactive({ + width: -1, + height: -1 + }); + watch(() => extend({}, size), (value) => emit2("resize", value)); + return () => { + const { + width, + height + } = rootRef.value.getBoundingClientRect(); + size.width = width; + size.height = height; + reset(); + }; } -function wrapperOnApi(name, fn, options) { - return (callback) => { - checkCallback(callback); - const errMsg = beforeInvokeApi(name, [callback], void 0, options); - if (errMsg) { - throw new Error(errMsg); - } - const isFirstInvokeOnApi = !findInvokeCallbackByName(name); - createKeepAliveApiCallback(name, callback); - if (isFirstInvokeOnApi) { - onKeepAliveApiCallback(name); - fn(); - } +function useResizeSensorReset(rootRef) { + return () => { + const { + firstElementChild, + lastElementChild + } = rootRef.value; + firstElementChild.scrollLeft = 1e5; + firstElementChild.scrollTop = 1e5; + lastElementChild.scrollLeft = 1e5; + lastElementChild.scrollTop = 1e5; }; } -function wrapperOffApi(name, fn, options) { - return (callback) => { - checkCallback(callback); - const errMsg = beforeInvokeApi(name, [callback], void 0, options); - if (errMsg) { - throw new Error(errMsg); +function useResizeSensorLifecycle(rootRef, props2, update, reset) { + onActivated(reset); + onMounted(() => { + if (props2.initial) { + nextTick(update); } - name = name.replace("off", "on"); - removeKeepAliveApiCallback(name, callback); - const hasInvokeOnApi = findInvokeCallbackByName(name); - if (!hasInvokeOnApi) { - offKeepAliveApiCallback(name); - fn(); + const rootEl = rootRef.value; + if (rootEl.offsetParent !== rootEl.parentElement) { + rootEl.parentElement.style.position = "relative"; } - }; -} -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); + if (!("AnimationEvent" in window)) { + reset(); } - return fn(args, { - resolve: (res) => invokeSuccess(id2, name, res), - reject: (err) => invokeFail(id2, name, err) - }); - }; + }); } -function wrapperSyncApi(name, fn, protocol, options) { - return (...args) => { - const errMsg = beforeInvokeApi(name, args, protocol, options); - if (errMsg) { - throw new Error(errMsg); +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; +} +let isHidpi = false; +function initHidpi() { + if (isHidpi) { + return; + } + isHidpi = true; + const forEach = function(obj, func) { + for (const key in obj) { + if (hasOwn(obj, key)) { + func(obj[key], key); + } } - return fn.apply(null, args); }; + const ratioArgs = { + fillRect: "all", + clearRect: "all", + strokeRect: "all", + moveTo: "all", + lineTo: "all", + arc: [0, 1, 2], + arcTo: "all", + bezierCurveTo: "all", + isPointinPath: "all", + isPointinStroke: "all", + quadraticCurveTo: "all", + rect: "all", + translate: "all", + createRadialGradient: "all", + createLinearGradient: "all", + setTransform: [4, 5] + }; + const proto = CanvasRenderingContext2D.prototype; + proto.drawImageByCanvas = function(_super) { + return function(canvas, srcx, srcy, srcw, srch, desx, desy, desw, desh, isScale) { + if (!this.__hidpi__) { + return _super.apply(this, arguments); + } + srcx *= pixelRatio; + srcy *= pixelRatio; + srcw *= pixelRatio; + srch *= pixelRatio; + desx *= pixelRatio; + desy *= pixelRatio; + desw = isScale ? desw * pixelRatio : desw; + desh = isScale ? desh * pixelRatio : desh; + _super.call(this, canvas, srcx, srcy, srcw, srch, desx, desy, desw, desh); + }; + }(proto.drawImage); + if (pixelRatio !== 1) { + forEach(ratioArgs, function(value, key) { + proto[key] = function(_super) { + return function() { + if (!this.__hidpi__) { + return _super.apply(this, arguments); + } + let args = Array.prototype.slice.call(arguments); + if (value === "all") { + args = args.map(function(a2) { + return a2 * pixelRatio; + }); + } else if (Array.isArray(value)) { + for (let i = 0; i < value.length; i++) { + args[value[i]] *= pixelRatio; + } + } + return _super.apply(this, args); + }; + }(proto[key]); + }); + proto.stroke = function(_super) { + return function() { + if (!this.__hidpi__) { + return _super.apply(this, arguments); + } + this.lineWidth *= pixelRatio; + _super.apply(this, arguments); + this.lineWidth /= pixelRatio; + }; + }(proto.stroke); + proto.fillText = function(_super) { + return function() { + if (!this.__hidpi__) { + return _super.apply(this, arguments); + } + const args = Array.prototype.slice.call(arguments); + args[1] *= pixelRatio; + args[2] *= pixelRatio; + var font2 = this.font; + this.font = font2.replace(/(\d+\.?\d*)(px|em|rem|pt)/g, function(w, m, u) { + return m * pixelRatio + u; + }); + _super.apply(this, args); + this.font = font2; + }; + }(proto.fillText); + proto.strokeText = function(_super) { + return function() { + if (!this.__hidpi__) { + return _super.apply(this, arguments); + } + var args = Array.prototype.slice.call(arguments); + args[1] *= pixelRatio; + args[2] *= pixelRatio; + var font2 = this.font; + this.font = font2.replace(/(\d+\.?\d*)(px|em|rem|pt)/g, function(w, m, u) { + return m * pixelRatio + u; + }); + _super.apply(this, args); + this.font = font2; + }; + }(proto.strokeText); + proto.drawImage = function(_super) { + return function() { + if (!this.__hidpi__) { + return _super.apply(this, arguments); + } + this.scale(pixelRatio, pixelRatio); + _super.apply(this, arguments); + this.scale(1 / pixelRatio, 1 / pixelRatio); + }; + }(proto.drawImage); + } } -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)); -} -function createUnsupportedMsg(name) { - return `method 'uni.${name}' not supported`; +const initHidpiOnce = /* @__PURE__ */ once(initHidpi); +function $getRealPath(src) { + return src ? getRealPath(src) : src; } -function createUnsupportedSyncApi(name) { - return () => { - console.error(createUnsupportedMsg(name)); - }; +function resolveColor(color) { + color = color.slice(0); + color[3] = color[3] / 255; + return "rgba(" + color.join(",") + ")"; } -const createUnsupportedOnApi = createUnsupportedSyncApi; -function createUnsupportedAsyncApi(name) { - return (_args, {reject}) => { - return reject(createUnsupportedMsg(name)); - }; +function processTouches(target, touches) { + const eventTarget = target; + return Array.from(touches).map((touch) => { + let boundingClientRect = eventTarget.getBoundingClientRect(); + return { + identifier: touch.identifier, + x: touch.clientX - boundingClientRect.left, + y: touch.clientY - boundingClientRect.top + }; + }); } -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 +let tempCanvas; +function getTempCanvas(width = 0, height = 0) { + if (!tempCanvas) { + tempCanvas = document.createElement("canvas"); } -]; -const base64ToArrayBuffer = /* @__PURE__ */ defineSyncApi(API_BASE64_TO_ARRAY_BUFFER, (base64) => { - return decode(base64); -}, Base64ToArrayBufferProtocol); -const arrayBufferToBase64 = /* @__PURE__ */ 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:.*,.*/; -const baseUrl = import.meta.env.BASE_URL; -function addBase(filePath) { - return baseUrl + filePath; + tempCanvas.width = width; + tempCanvas.height = height; + return tempCanvas; } -function getRealPath(filePath) { - if (__uniConfig.router.base === "./") { - filePath = filePath.replace(/^\.\/static\//, "/static/"); +const props$A = { + canvasId: { + type: String, + default: "" + }, + disableScroll: { + type: [Boolean, String], + default: false } - if (filePath.indexOf("/") === 0) { - if (filePath.indexOf("//") === 0) { - filePath = "https:" + filePath; - } else { - return addBase(filePath.substr(1)); - } - } - 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, pageId, type, data) { - UniServiceJSBridge.publishHandler("video." + videoId, { - videoId, - type, - data - }, pageId); -} -function operateMap(id2, pageId, type, data) { - UniServiceJSBridge.publishHandler("map." + id2, { - type, - data - }, pageId); -} -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); +}; +var index$q = /* @__PURE__ */ defineBuiltInComponent({ + inheritAttrs: false, + name: "Canvas", + compatConfig: { + MODE: 3 + }, + props: props$A, + computed: { + id() { + return this.canvasId; } }, - methods: { - _toggleListeners(type, id2, watch2) { - if (watch2 && !id2) { - return; + setup(props2, { + emit: emit2, + slots + }) { + initHidpiOnce(); + const canvas = ref(null); + const sensor = ref(null); + const actionsWaiting = ref(false); + const trigger = useNativeEvent(emit2); + const { + $attrs, + $excludeAttrs, + $listeners + } = useAttrs({ + excludeListeners: true + }); + const { + _listeners + } = useListeners(props2, $listeners, trigger); + const { + _handleSubscribe, + _resize + } = useMethods(canvas, actionsWaiting); + useSubscribe(_handleSubscribe, useContextInfo(props2.canvasId), true); + onMounted(() => { + _resize(); + }); + return () => { + const { + canvasId, + disableScroll + } = props2; + return createVNode("uni-canvas", mergeProps({ + "canvas-id": canvasId, + "disable-scroll": disableScroll + }, $attrs.value, $excludeAttrs.value, _listeners.value), [createVNode("canvas", { + "ref": canvas, + "class": "uni-canvas-canvas", + "width": "300", + "height": "150" + }, null, 512), createVNode("div", { + "style": "position: absolute;top: 0;left: 0;width: 100%;height: 100%;overflow: hidden;" + }, [slots.default && slots.default()]), createVNode(ResizeSensor, { + "ref": sensor, + "onResize": _resize + }, null, 8, ["onResize"])], 16, ["canvas-id", "disable-scroll"]); + }; + } +}); +function useListeners(props2, Listeners, trigger) { + const _listeners = computed(() => { + let events = ["onTouchstart", "onTouchmove", "onTouchend"]; + let _$listeners = Listeners.value; + let $listeners = extend({}, (() => { + let obj = {}; + for (const key in _$listeners) { + if (Object.prototype.hasOwnProperty.call(_$listeners, key)) { + const event = _$listeners[key]; + obj[key] = event; + } } - if (!isFunction(this._handleSubscribe)) { - return; + return obj; + })()); + events.forEach((event) => { + let existing = $listeners[event]; + let eventHandler = []; + if (existing) { + eventHandler.push(withWebEvent(($event) => { + trigger(event.replace("on", "").toLocaleLowerCase(), extend({}, (() => { + let obj = {}; + for (const key in $event) { + obj[key] = $event[key]; + } + return obj; + })(), { + touches: processTouches($event.currentTarget, $event.touches), + changedTouches: processTouches($event.currentTarget, $event.changedTouches) + })); + })); } - 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; + if (props2.disableScroll && event === "onTouchmove") { + eventHandler.push(onEventPrevent); } - return { - name: this.$options.name.replace(/VUni([A-Z])/, "$1").toLowerCase(), - id: id2, - page: this.$page.id - }; + $listeners[event] = eventHandler; + }); + return $listeners; + }); + return { + _listeners + }; +} +function useMethods(canvasRef, actionsWaiting) { + let _actionsDefer = []; + let _images = {}; + function _resize() { + var canvas = canvasRef.value; + if (canvas.width > 0 && canvas.height > 0) { + var context = canvas.getContext("2d"); + var imageData = context.getImageData(0, 0, canvas.width, canvas.height); + wrapper(canvas); + context.putImageData(imageData, 0, 0); + } else { + wrapper(canvas); } } -}; -function throttle(fn, wait) { - let last = 0; - let timeout; - let waitCallback; - const newFn = function(...arg) { - const now = Date.now(); - clearTimeout(timeout); - waitCallback = () => { - waitCallback = null; - last = now; - fn.apply(this, arg); - }; - if (now - last < wait) { - timeout = setTimeout(waitCallback, wait - (now - last)); + function actionsChanged({ + actions, + reserve, + callbackId + }) { + if (!actions) { return; } - waitCallback(); - }; - newFn.cancel = function() { - clearTimeout(timeout); - waitCallback = null; - }; - newFn.flush = function() { - clearTimeout(timeout); - waitCallback && waitCallback(); - }; - return newFn; -} -const _sfc_main$2 = { - 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: "" + if (actionsWaiting.value) { + _actionsDefer.push([actions, reserve, callbackId]); + return; } - }, - data() { - return { - playing: false, - currentTime: this.getTime(0) - }; - }, - watch: { - src(val) { - if (this.$refs.audio) { - this.$refs.audio.src = this.$getRealPath(val); - } + var canvas = canvasRef.value; + 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); } - }, - 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; + 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 = 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] = Number(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") { + const font2 = c2d.__font__ || c2d.font; + c2d.__font__ = c2d.font = font2.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 if (method1 === "font") { + c2d.__font__ = c2d.font = 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); + _images = _images || {}; + if (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; - } - }, - 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; + if (method === "clip") { + data.forEach(function(data_) { + c2d[data_.method].apply(c2d, data_.data); + }); + c2d.clip(); + } else { + c2d[method].apply(c2d, data); + } } - return str; + } + if (!actionsWaiting.value && callbackId) { + UniViewJSBridge.publishHandler("onCanvasMethodCallback", { + callbackId, + data: { + errMsg: "drawCanvas:ok" + } + }, getCurrentPageId()); } } -}; -const _hoisted_1$1 = {class: "uni-audio-default"}; -const _hoisted_2$1 = {class: "uni-audio-right"}; -const _hoisted_3$1 = {class: "uni-audio-time"}; -const _hoisted_4$1 = {class: "uni-audio-info"}; -const _hoisted_5 = {class: "uni-audio-name"}; -const _hoisted_6 = {class: "uni-audio-author"}; -function _sfc_render$2(_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$1, [ - 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$1, [ - createVNode("div", _hoisted_3$1, toDisplayString($data.currentTime), 1), - createVNode("div", _hoisted_4$1, [ - createVNode("div", _hoisted_5, toDisplayString($props.name), 1), - createVNode("div", _hoisted_6, toDisplayString($props.author), 1) - ]) - ]) - ]) - ], 16, ["id", "controls"]); -} -_sfc_main$2.render = _sfc_render$2; -function converPx(value) { - if (/^-?\d+[ur]px$/i.test(value)) { - return value.replace(/(^-?\d+)[ur]px$/i, (text2, num) => { - return `${uni.upx2px(parseFloat(num))}px`; + function preloadImage(actions) { + actions.forEach(function(action) { + var method = action.method; + var data = action.data; + var src = ""; + if (method === "drawImage") { + src = data[0]; + src = $getRealPath(src); + data[0] = src; + } else if (method === "setFillStyle" && data[0] === "pattern") { + src = data[1]; + src = $getRealPath(src); + data[1] = src; + } + if (src && !_images[src]) { + loadImage(); + } + function loadImage() { + const image2 = _images[src] = new Image(); + image2.onload = function() { + image2.ready = true; + }; + getSameOriginUrl(src).then((src2) => { + image2.src = src2; + }).catch(() => { + image2.src = src; + }); + } }); - } else if (/^-?[\d\.]+$/.test(value)) { - return `${value}px`; } - return value || ""; -} -function converType(type) { - return type.replace(/[A-Z]/g, (text2) => { - return `-${text2.toLowerCase()}`; - }).replace("webkit", "-webkit"); -} -function getStyle(action) { - const animateTypes1 = [ - "matrix", - "matrix3d", - "scale", - "scale3d", - "rotate3d", - "skew", - "translate", - "translate3d" - ]; - const animateTypes2 = [ - "scaleX", - "scaleY", - "scaleZ", - "rotate", - "rotateX", - "rotateY", - "rotateZ", - "skewX", - "skewY", - "translateX", - "translateY", - "translateZ" - ]; - const animateTypes3 = ["opacity", "background-color"]; - const animateTypes4 = ["width", "height", "left", "right", "top", "bottom"]; - const animates = action.animates; - const option = action.option; - const transition = option.transition; - const style = {}; - const transform = []; - animates.forEach((animate) => { - let type = animate.type; - let args = [...animate.args]; - if (animateTypes1.concat(animateTypes2).includes(type)) { - if (type.startsWith("rotate") || type.startsWith("skew")) { - args = args.map((value) => parseFloat(value) + "deg"); - } else if (type.startsWith("translate")) { - args = args.map(converPx); - } - if (animateTypes2.indexOf(type) >= 0) { - args.length = 1; - } - transform.push(`${type}(${args.join(",")})`); - } else if (animateTypes3.concat(animateTypes4).includes(args[0])) { - type = args[0]; - const value = args[1]; - style[type] = animateTypes4.includes(type) ? converPx(value) : value; - } - }); - style.transform = style.webkitTransform = transform.join(" "); - style.transition = style.webkitTransition = Object.keys(style).map((type) => `${converType(type)} ${transition.duration}ms ${transition.timingFunction} ${transition.delay}ms`).join(","); - style.transformOrigin = style.webkitTransformOrigin = option.transformOrigin; - return style; -} -function startAnimation(context) { - const animation2 = context.animation; - if (!animation2 || !animation2.actions || !animation2.actions.length) { - return; - } - let index2 = 0; - const actions = animation2.actions; - const length = animation2.actions.length; - function animate() { - const action = actions[index2]; - const transition = action.option.transition; - const style = getStyle(action); - Object.keys(style).forEach((key) => { - context.$el.style[key] = style[key]; - }); - index2 += 1; - if (index2 < length) { - setTimeout(animate, transition.duration + transition.delay); + function checkImageLoaded(src, actions, callbackId, fn) { + var image2 = _images[src]; + if (image2.ready) { + fn(image2); + return true; + } else { + _actionsDefer.unshift([actions, true]); + actionsWaiting.value = true; + image2.onload = function() { + image2.ready = true; + fn(image2); + actionsWaiting.value = false; + var actions2 = _actionsDefer.slice(0); + _actionsDefer = []; + for (var action = actions2.shift(); action; ) { + actionsChanged({ + actions: action[0], + reserve: action[1], + callbackId + }); + action = actions2.shift(); + } + }; + return false; } } - setTimeout(() => { - animate(); - }, 0); -} -var animation = { - props: ["animation"], - watch: { - animation: { - deep: true, - handler() { - startAnimation(this); + function getImageData({ + x = 0, + y = 0, + width, + height, + destWidth, + destHeight, + hidpi = true, + dataType: dataType2, + quality = 1, + type = "png", + callbackId + }) { + const canvas = canvasRef.value; + let data; + const maxWidth = canvas.offsetWidth - x; + width = width ? Math.min(width, maxWidth) : maxWidth; + const maxHeight = canvas.offsetHeight - y; + height = height ? Math.min(height, maxHeight) : maxHeight; + 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; } - }, - mounted() { - startAnimation(this); - } -}; -const defineBuiltInComponent = (options) => { - const {props: props2, mixins} = options; - if (!props2 || !props2.animation) { - (mixins || (options.mixins = [])).push(animation); - } - return defineSystemComponent(options); -}; -const defineSystemComponent = (options) => { - options.compatConfig = { - MODE: 3 - }; - return defineComponent(options); -}; -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 onTouchstartPassive(evt) { - if (evt._hoverPropagationStopped) { - return; + const newCanvas = getTempCanvas(destWidth, destHeight); + const context = newCanvas.getContext("2d"); + if (type === "jpeg" || type === "jpg") { + type = "jpeg"; + context.fillStyle = "#fff"; + context.fillRect(0, 0, destWidth, destHeight); } - if (!props2.hoverClass || props2.hoverClass === "none" || props2.disabled) { - return; + context.__hidpi__ = true; + context.drawImageByCanvas(canvas, x, y, width, height, 0, 0, destWidth, destHeight, false); + let result; + try { + let compressed; + if (dataType2 === "base64") { + data = newCanvas.toDataURL(`image/${type}`, quality); + } else { + const imgData = context.getImageData(0, 0, destWidth, destHeight); + if (false) + ; + else { + data = Array.prototype.slice.call(imgData.data); + } + } + result = { + errMsg: "canvasGetImageData:ok", + data, + compressed, + width: destWidth, + height: destHeight + }; + } catch (error) { + result = { + errMsg: `canvasGetImageData:fail ${error}` + }; } - if (evt.touches.length > 1) { - return; + newCanvas.height = newCanvas.width = 0; + context.__hidpi__ = false; + if (!callbackId) { + return result; + } else { + UniViewJSBridge.publishHandler("onCanvasMethodCallback", { + callbackId, + data: result + }, getCurrentPageId()); } - if (props2.hoverStopPropagation) { - evt._hoverPropagationStopped = true; + } + function putImageData({ + data, + x, + y, + width, + height, + compressed, + callbackId + }) { + try { + if (!height) { + height = Math.round(data.length / 4 / width); + } + const canvas = getTempCanvas(width, height); + const context = canvas.getContext("2d"); + if (false) + ; + context.putImageData(new ImageData(new Uint8ClampedArray(data), width, height), 0, 0); + canvasRef.value.getContext("2d").drawImage(canvas, x, y, width, height); + canvas.height = canvas.width = 0; + } catch (error) { + UniViewJSBridge.publishHandler("onCanvasMethodCallback", { + callbackId, + data: { + errMsg: "canvasPutImageData:fail" + } + }, getCurrentPageId()); + return; } - hoverTouch = true; - hoverStartTimer = setTimeout(() => { - hovering.value = true; - if (!hoverTouch) { - hoverReset(); + UniViewJSBridge.publishHandler("onCanvasMethodCallback", { + callbackId, + data: { + errMsg: "canvasPutImageData:ok" } - }, parseInt(props2.hoverStartTime)); + }, getCurrentPageId()); } - function onTouchend() { - hoverTouch = false; - if (hovering.value) { - hoverReset(); + function toTempFilePath({ + x = 0, + y = 0, + width, + height, + destWidth, + destHeight, + fileType, + quality, + dirname, + callbackId + }) { + const res = getImageData({ + x, + y, + width, + height, + destWidth, + destHeight, + hidpi: false, + dataType: "base64", + type: fileType, + quality + }); + if (!res.data || !res.data.length) { + UniViewJSBridge.publishHandler("onCanvasMethodCallback", { + callbackId, + data: { + errMsg: res.errMsg.replace("canvasPutImageData", "toTempFilePath") + } + }, getCurrentPageId()); + return; } + saveImage(res.data, dirname, (error, tempFilePath) => { + let errMsg = `toTempFilePath:${error ? "fail" : "ok"}`; + if (error) { + errMsg += ` ${error.message}`; + } + UniViewJSBridge.publishHandler("onCanvasMethodCallback", { + callbackId, + data: { + errMsg, + tempFilePath + } + }, getCurrentPageId()); + }); } - function onTouchcancel() { - hoverTouch = false; - hovering.value = false; - clearTimeout(hoverStartTimer); - } - return { - hovering, - binding: { - onTouchstartPassive, - onTouchend, - onTouchcancel - } + const methods = { + actionsChanged, + getImageData, + putImageData, + toTempFilePath }; -} -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 withWebEvent(fn) { - return fn.__wwe = true, fn; -} -function useCustomEvent(ref2, emit2) { - return (name, evt, detail) => { - if (ref2.value) { - emit2(name, normalizeCustomEvent(name, evt, ref2.value, detail || {})); + function _handleSubscribe(type, data = {}) { + let method = methods[type]; + if (type.indexOf("_") !== 0 && typeof method === "function") { + method(data); } - }; -} -function useNativeEvent(emit2) { - return (name, evt) => { - emit2(name, createNativeEvent(evt)); - }; -} -function normalizeCustomEvent(name, domEvt, el, detail) { - const target = normalizeTarget(el); - return { - type: detail.type || name, - timeStamp: domEvt.timeStamp || 0, - target, - currentTarget: target, - detail - }; + } + return extend(methods, { + _resize, + _handleSubscribe + }); } -const uniFormKey = PolySymbol(process.env.NODE_ENV !== "production" ? "uniForm" : "uf"); -var index$t = /* @__PURE__ */ defineBuiltInComponent({ - name: "Form", - setup(_props, { - slots, - emit: emit2 +const uniCheckGroupKey = PolySymbol(process.env.NODE_ENV !== "production" ? "uniCheckGroup" : "ucg"); +const props$z = { + name: { + type: String, + default: "" + } +}; +var index$p = /* @__PURE__ */ defineBuiltInComponent({ + name: "CheckboxGroup", + props: props$z, + emits: ["change"], + setup(props2, { + emit: emit2, + slots }) { - provideForm(emit2); - return () => createVNode("uni-form", null, [createVNode("span", null, [slots.default && slots.default()])]); + const rootRef = ref(null); + const trigger = useCustomEvent(rootRef, emit2); + useProvideCheckGroup(props2, trigger); + return () => { + return createVNode("uni-checkbox-group", { + "ref": rootRef + }, [slots.default && slots.default()], 512); + }; } }); -function provideForm(emit2) { +function useProvideCheckGroup(props2, trigger) { const fields2 = []; - provide(uniFormKey, { + const getFieldsValue = () => fields2.reduce((res, field) => { + if (field.value.checkboxChecked) { + res.push(field.value.value); + } + return res; + }, new Array()); + provide(uniCheckGroupKey, { addField(field) { fields2.push(field); }, removeField(field) { fields2.splice(fields2.indexOf(field), 1); }, - submit() { - emit2("submit", { - detail: { - value: fields2.reduce((res, field) => { - if (field.submit) { - const [name, value] = field.submit(); - name && (res[name] = value); - } - return res; - }, Object.create(null)) - } + checkboxChange($event) { + trigger("change", $event, { + value: getFieldsValue() }); - }, - reset() { - fields2.forEach((field) => field.reset && field.reset()); - emit2("reset"); } }); - return fields2; + const uniForm = inject(uniFormKey, false); + if (uniForm) { + uniForm.addField({ + submit: () => { + let data = ["", null]; + if (props2.name !== "") { + data[0] = props2.name; + data[1] = getFieldsValue(); + } + return data; + } + }); + } + return getFieldsValue; } -const uniLabelKey = PolySymbol(process.env.NODE_ENV !== "production" ? "uniLabel" : "ul"); -const props$B = { - for: { +const props$y = { + 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: "" } }; -var index$s = /* @__PURE__ */ defineBuiltInComponent({ - name: "Label", - props: props$B, +var index$o = /* @__PURE__ */ defineBuiltInComponent({ + name: "Checkbox", + props: props$y, setup(props2, { slots }) { - const pageId = useCurrentPageId(); - const handlers = useProvideLabel(); - const pointer = computed(() => props2.for || slots.default && slots.default.length); - const _onClick = withWebEvent(($event) => { - const EventTarget = $event.target; - let stopPropagation = /^uni-(checkbox|radio|switch)-/.test(EventTarget.className); - if (!stopPropagation) { - stopPropagation = /^uni-(checkbox|radio|switch|button)$|^(svg|path)$/i.test(EventTarget.tagName); - } - if (stopPropagation) { + const checkboxChecked = ref(props2.checked); + const checkboxValue = ref(props2.value); + watch([() => props2.checked, () => props2.value], ([newChecked, newModelValue]) => { + checkboxChecked.value = newChecked; + checkboxValue.value = newModelValue; + }); + const reset = () => { + checkboxChecked.value = false; + }; + const { + uniCheckGroup, + uniLabel + } = useCheckboxInject(checkboxChecked, checkboxValue, reset); + const _onClick = ($event) => { + if (props2.disabled) { return; } - if (props2.for) { - UniViewJSBridge.emit("uni-label-click-" + pageId + "-" + props2.for, $event, true); - } else { - handlers[0]($event, true); - } + checkboxChecked.value = !checkboxChecked.value; + uniCheckGroup && uniCheckGroup.checkboxChange($event); + }; + if (!!uniLabel) { + uniLabel.addHandler(_onClick); + onBeforeUnmount(() => { + uniLabel.removeHandler(_onClick); + }); + } + useListeners$1(props2, { + "label-click": _onClick }); - return () => createVNode("uni-label", { - "class": { - "uni-label-pointer": pointer - }, - "onClick": _onClick - }, [slots.default && slots.default()], 10, ["onClick"]); - } -}); -function useProvideLabel() { - const handlers = []; - provide(uniLabelKey, { - addHandler(handler) { - handlers.push(handler); - }, - removeHandler(handler) { - handlers.splice(handlers.indexOf(handler), 1); - } + return () => { + const { + booleanAttrs + } = useBooleanAttr(props2, "disabled"); + return createVNode("uni-checkbox", mergeProps(booleanAttrs, { + "onClick": _onClick + }), [createVNode("div", { + "class": "uni-checkbox-wrapper" + }, [createVNode("div", { + "class": ["uni-checkbox-input", { + "uni-checkbox-input-disabled": props2.disabled + }] + }, [checkboxChecked.value ? createSvgIconVNode(ICON_PATH_SUCCESS_NO_CIRCLE, props2.color, 22) : ""], 2), slots.default && slots.default()])], 16, ["onClick"]); + }; + } +}); +function useCheckboxInject(checkboxChecked, checkboxValue, reset) { + const field = computed(() => ({ + checkboxChecked: Boolean(checkboxChecked.value), + value: checkboxValue.value + })); + const formField = { + reset + }; + const uniCheckGroup = inject(uniCheckGroupKey, false); + if (!!uniCheckGroup) { + uniCheckGroup.addField(field); + } + const uniForm = inject(uniFormKey, false); + if (!!uniForm) { + uniForm.addField(formField); + } + const uniLabel = inject(uniLabelKey, false); + onBeforeUnmount(() => { + uniCheckGroup && uniCheckGroup.removeField(field); + uniForm && uniForm.removeField(formField); }); - return handlers; + return { + uniCheckGroup, + uniForm, + uniLabel + }; } -function useListeners$1(props2, listeners) { - _addListeners(props2.id, listeners); - watch(() => props2.id, (newId, oldId) => { - _removeListeners(oldId, listeners, true); - _addListeners(newId, listeners, true); - }); - onUnmounted(() => { - _removeListeners(props2.id, listeners); - }); +let resetTimer; +function iosHideKeyboard() { } -function _addListeners(id2, listeners, watch2) { - const pageId = useCurrentPageId(); - if (watch2 && !id2) { - return; +const props$x = { + cursorSpacing: { + type: [Number, String], + default: 0 + }, + showConfirmBar: { + type: [Boolean, String], + default: "auto" + }, + adjustPosition: { + type: [Boolean, String], + default: true + }, + autoBlur: { + type: [Boolean, String], + default: false } - if (!isPlainObject(listeners)) { - return; +}; +const emit$1 = ["keyboardheightchange"]; +function useKeyboard$1(props2, elRef, trigger) { + function initKeyboard(el) { + el.addEventListener("focus", () => { + clearTimeout(resetTimer); + document.addEventListener("click", iosHideKeyboard, false); + }); + const onKeyboardHide = () => { + document.removeEventListener("click", iosHideKeyboard, false); + if (String(navigator.vendor).indexOf("Apple") === 0) { + document.documentElement.scrollTo(document.documentElement.scrollLeft, document.documentElement.scrollTop); + } + }; + el.addEventListener("blur", () => { + onKeyboardHide(); + }); } - Object.keys(listeners).forEach((name) => { - if (watch2) { - if (name.indexOf("@") !== 0 && name.indexOf("uni-") !== 0) { - UniViewJSBridge.on(`uni-${name}-${pageId}-${id2}`, listeners[name]); + watch(() => elRef.value, (el) => initKeyboard(el)); +} +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]; + }; + 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()); } - }); -} -function _removeListeners(id2, listeners, watch2) { - const pageId = useCurrentPageId(); - if (watch2 && !id2) { - return; - } - if (!isPlainObject(listeners)) { - return; + if (html == last) { + throw "Parse Error: " + html; + } + last = html; } - Object.keys(listeners).forEach((name) => { - if (watch2) { - if (name.indexOf("@") !== 0 && name.indexOf("uni-") !== 0) { - UniViewJSBridge.off(`uni-${name}-${pageId}-${id2}`, listeners[name]); + parseEndTag(); + function parseStartTag(tag, tagName, rest, unary) { + tagName = tagName.toLowerCase(); + if (block[tagName]) { + while (stack.last() && inline[stack.last()]) { + parseEndTag("", stack.last()); + } + } + if (closeSelf[tagName] && stack.last() == tagName) { + parseEndTag("", tagName); + } + unary = empty[tagName] || !!unary; + if (!unary) { + stack.push(tagName); + } + 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); } + } + } + function parseEndTag(tag, tagName) { + if (!tagName) { + var pos = 0; } else { - if (name.indexOf("uni-") === 0) { - UniViewJSBridge.off(name, listeners[name]); - } else if (id2) { - UniViewJSBridge.off(`uni-${name}-${pageId}-${id2}`, listeners[name]); + for (var pos = stack.length - 1; pos >= 0; pos--) { + if (stack[pos] == tagName) { + break; + } } } - }); + if (pos >= 0) { + for (var i = stack.length - 1; i >= pos; i--) { + if (handler.end) { + handler.end(stack[i]); + } + } + stack.length = pos; + } + } } -var index$r = /* @__PURE__ */ defineBuiltInComponent({ - 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: "" - }, - loading: { - type: [Boolean, String], - default: false - } - }, - setup(props2, { - slots - }) { - const rootRef = ref(null); - const uniForm = inject(uniFormKey, false); - const { - hovering, - binding - } = useHover(props2); - useI18n(); - const onClick = withWebEvent((e2, isLabelClick) => { - if (props2.disabled) { - return e2.stopImmediatePropagation(); - } - if (isLabelClick) { - rootRef.value.click(); - } - const formType = props2.formType; - if (formType) { - if (!uniForm) { - return; - } - if (formType === "submit") { - uniForm.submit(); - } else if (formType === "reset") { - uniForm.reset(); - } - return; - } - }); - const uniLabel = inject(uniLabelKey, false); - if (uniLabel) { - uniLabel.addHandler(onClick); - onBeforeUnmount(() => { - uniLabel.removeHandler(onClick); - }); - } - useListeners$1(props2, { - "label-click": onClick - }); - return () => { - const hoverClass = props2.hoverClass; - const booleanAttrs = useBooleanAttr(props2, "disabled"); - const loadingAttrs = useBooleanAttr(props2, "loading"); - const hasHoverClass = hoverClass && hoverClass !== "none"; - return createVNode("uni-button", mergeProps({ - "ref": rootRef, - "onClick": onClick, - "class": hasHoverClass && hovering.value ? hoverClass : "" - }, hasHoverClass && binding, booleanAttrs, loadingAttrs), [slots.default && slots.default()], 16, ["onClick"]); +function makeMap(str) { + var obj = {}; + var items = str.split(","); + for (var i = 0; i < items.length; i++) { + obj[items[i]] = true; + } + return obj; +} +const scripts = {}; +function loadScript(globalName, src, callback) { + const globalObject = typeof globalName === "string" ? window[globalName] : globalName; + if (globalObject) { + callback(); + return; + } + let callbacks2 = scripts[src]; + if (!callbacks2) { + callbacks2 = scripts[src] = []; + const script = document.createElement("script"); + script.src = src; + document.body.appendChild(script); + script.onload = function() { + callbacks2.forEach((callback2) => callback2()); + delete scripts[src]; }; } -}); -var ResizeSensor = /* @__PURE__ */ defineBuiltInComponent({ - name: "ResizeSensor", - props: { - initial: { - type: Boolean, - default: false - } - }, - emits: ["resize"], - setup(props2, { - emit: emit2 - }) { - const rootRef = ref(null); - const reset = useResizeSensorReset(rootRef); - const update = useResizeSensorUpdate(rootRef, emit2, reset); - useResizeSensorLifecycle(rootRef, props2, update, reset); - return () => createVNode("uni-resize-sensor", { - "ref": rootRef, - "onAnimationstartOnce": update - }, [createVNode("div", { - "onScroll": update - }, [createVNode("div", null, null)], 40, ["onScroll"]), createVNode("div", { - "onScroll": update - }, [createVNode("div", null, null)], 40, ["onScroll"])], 40, ["onAnimationstartOnce"]); + callbacks2.push(callback); +} +function divider(Quill) { + const BlockEmbed = Quill.import("blots/block/embed"); + class Divider extends BlockEmbed { } -}); -function useResizeSensorUpdate(rootRef, emit2, reset) { - const size = reactive({ - width: -1, - height: -1 - }); - watch(() => extend({}, size), (value) => emit2("resize", value)); - return () => { - const { - width, - height - } = rootRef.value.getBoundingClientRect(); - size.width = width; - size.height = height; - reset(); + Divider.blotName = "divider"; + Divider.tagName = "HR"; + return { + "formats/divider": Divider }; } -function useResizeSensorReset(rootRef) { - return () => { - const { - firstElementChild, - lastElementChild - } = rootRef.value; - firstElementChild.scrollLeft = 1e5; - firstElementChild.scrollTop = 1e5; - lastElementChild.scrollLeft = 1e5; - lastElementChild.scrollTop = 1e5; +function ins(Quill) { + const Inline = Quill.import("blots/inline"); + class Ins extends Inline { + } + Ins.blotName = "ins"; + Ins.tagName = "INS"; + return { + "formats/ins": Ins }; } -function useResizeSensorLifecycle(rootRef, props2, update, reset) { - onActivated(reset); - onMounted(() => { - if (props2.initial) { - nextTick(update); - } - const rootEl = rootRef.value; - if (rootEl.offsetParent !== rootEl.parentElement) { - rootEl.parentElement.style.position = "relative"; - } - if (!("AnimationEvent" in window)) { - reset(); - } - }); -} -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 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 + }; } -let isHidpi = false; -function initHidpi() { - if (isHidpi) { - return; - } - isHidpi = true; - const forEach = function(obj, func) { - for (const key in obj) { - if (hasOwn(obj, key)) { - func(obj[key], key); - } - } +function direction(Quill) { + const {Scope, Attributor} = Quill.import("parchment"); + const config = { + scope: Scope.BLOCK, + whitelist: ["rtl"] }; - const ratioArgs = { - fillRect: "all", - clearRect: "all", - strokeRect: "all", - moveTo: "all", - lineTo: "all", - arc: [0, 1, 2], - arcTo: "all", - bezierCurveTo: "all", - isPointinPath: "all", - isPointinStroke: "all", - quadraticCurveTo: "all", - rect: "all", - translate: "all", - createRadialGradient: "all", - createLinearGradient: "all", - setTransform: [4, 5] + const DirectionStyle = new Attributor.Style("direction", "direction", config); + return { + "formats/direction": DirectionStyle }; - const proto = CanvasRenderingContext2D.prototype; - proto.drawImageByCanvas = function(_super) { - return function(canvas, srcx, srcy, srcw, srch, desx, desy, desw, desh, isScale) { - if (!this.__hidpi__) { - return _super.apply(this, arguments); +} +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"); } - srcx *= pixelRatio; - srcy *= pixelRatio; - srcw *= pixelRatio; - srch *= pixelRatio; - desx *= pixelRatio; - desy *= pixelRatio; - desw = isScale ? desw * pixelRatio : desw; - desh = isScale ? desh * pixelRatio : desh; - _super.call(this, canvas, srcx, srcy, srcw, srch, desx, desy, desw, desh); - }; - }(proto.drawImage); - if (pixelRatio !== 1) { - forEach(ratioArgs, function(value, key) { - proto[key] = function(_super) { - return function() { - if (!this.__hidpi__) { - return _super.apply(this, arguments); - } - let args = Array.prototype.slice.call(arguments); - if (value === "all") { - args = args.map(function(a2) { - return a2 * pixelRatio; - }); - } else if (Array.isArray(value)) { - for (let i = 0; i < value.length; i++) { - args[value[i]] *= pixelRatio; - } - } - return _super.apply(this, args); - }; - }(proto[key]); - }); - proto.stroke = function(_super) { - return function() { - if (!this.__hidpi__) { - return _super.apply(this, arguments); - } - this.lineWidth *= pixelRatio; - _super.apply(this, arguments); - this.lineWidth /= pixelRatio; - }; - }(proto.stroke); - proto.fillText = function(_super) { - return function() { - if (!this.__hidpi__) { - return _super.apply(this, arguments); - } - const args = Array.prototype.slice.call(arguments); - args[1] *= pixelRatio; - args[2] *= pixelRatio; - var font2 = this.font; - this.font = font2.replace(/(\d+\.?\d*)(px|em|rem|pt)/g, function(w, m, u) { - return m * pixelRatio + u; - }); - _super.apply(this, args); - this.font = font2; - }; - }(proto.fillText); - proto.strokeText = function(_super) { - return function() { - if (!this.__hidpi__) { - return _super.apply(this, arguments); + 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"; } - var args = Array.prototype.slice.call(arguments); - args[1] *= pixelRatio; - args[2] *= pixelRatio; - var font2 = this.font; - this.font = font2.replace(/(\d+\.?\d*)(px|em|rem|pt)/g, function(w, m, u) { - return m * pixelRatio + u; - }); - _super.apply(this, args); - this.font = font2; - }; - }(proto.strokeText); - proto.drawImage = function(_super) { - return function() { - if (!this.__hidpi__) { - return _super.apply(this, arguments); + } + 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"); } - this.scale(pixelRatio, pixelRatio); - _super.apply(this, arguments); - this.scale(1 / pixelRatio, 1 / pixelRatio); }; - }(proto.drawImage); + 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); + } + } + 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 + }; } -const initHidpiOnce = /* @__PURE__ */ once(initHidpi); -function $getRealPath(src) { - return src ? getRealPath(src) : src; +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 resolveColor(color) { - color = color.slice(0); - color[3] = color[3] / 255; - return "rgba(" + color.join(",") + ")"; +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 processTouches(target, touches) { - const eventTarget = target; - return Array.from(touches).map((touch) => { - let boundingClientRect = eventTarget.getBoundingClientRect(); - return { - identifier: touch.identifier, - x: touch.clientX - boundingClientRect.left, - y: touch.clientY - boundingClientRect.top - }; +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; } -let tempCanvas; -function getTempCanvas(width = 0, height = 0) { - if (!tempCanvas) { - tempCanvas = document.createElement("canvas"); - } - tempCanvas.width = width; - tempCanvas.height = height; - return tempCanvas; +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; } -const props$A = { - canvasId: { - type: String, - default: "" - }, - disableScroll: { - type: [Boolean, String], - default: false - } -}; -var index$q = /* @__PURE__ */ defineBuiltInComponent({ - inheritAttrs: false, - name: "Canvas", - compatConfig: { - MODE: 3 - }, - props: props$A, - computed: { - id() { - return this.canvasId; - } - }, - setup(props2, { - emit: emit2, - slots - }) { - initHidpiOnce(); - const canvas = ref(null); - const sensor = ref(null); - const actionsWaiting = ref(false); - const trigger = useNativeEvent(emit2); - const { - $attrs, - $excludeAttrs, - $listeners - } = useAttrs({ - excludeListeners: true - }); - const { - _listeners - } = useListeners(props2, $listeners, trigger); - const { - _handleSubscribe, - _resize - } = useMethods(canvas, actionsWaiting); - useSubscribe(_handleSubscribe, useContextInfo(props2.canvasId), true); - onMounted(() => { - _resize(); - }); - return () => { - const { - canvasId, - disableScroll - } = props2; - return createVNode("uni-canvas", mergeProps({ - "canvas-id": canvasId, - "disable-scroll": disableScroll - }, $attrs.value, $excludeAttrs.value, _listeners.value), [createVNode("canvas", { - "ref": canvas, - "class": "uni-canvas-canvas", - "width": "300", - "height": "150" - }, null, 512), createVNode("div", { - "style": "position: absolute;top: 0;left: 0;width: 100%;height: 100%;overflow: hidden;" - }, [slots.default && slots.default()]), createVNode(ResizeSensor, { - "ref": sensor, - "onResize": _resize - }, null, 8, ["onResize"])], 16, ["canvas-id", "disable-scroll"]); - }; - } -}); -function useListeners(props2, Listeners, trigger) { - const _listeners = computed(() => { - let events = ["onTouchstart", "onTouchmove", "onTouchend"]; - let _$listeners = Listeners.value; - let $listeners = extend({}, (() => { - let obj = {}; - for (const key in _$listeners) { - if (Object.prototype.hasOwnProperty.call(_$listeners, key)) { - const event = _$listeners[key]; - obj[key] = event; - } - } - return obj; - })()); - events.forEach((event) => { - let existing = $listeners[event]; - let eventHandler = []; - if (existing) { - eventHandler.push(withWebEvent(($event) => { - trigger(event.replace("on", "").toLocaleLowerCase(), extend({}, (() => { - let obj = {}; - for (const key in $event) { - obj[key] = $event[key]; - } - return obj; - })(), { - touches: processTouches($event.currentTarget, $event.touches), - changedTouches: processTouches($event.currentTarget, $event.changedTouches) - })); - })); +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); } - if (props2.disableScroll && event === "onTouchmove") { - eventHandler.push(onEventPrevent); + 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); } - $listeners[event] = eventHandler; - }); - return $listeners; - }); - return { - _listeners + } else { + format.call(this, name, value); + } }; } -function useMethods(canvasRef, actionsWaiting) { - let _actionsDefer = []; - let _images = {}; - function _resize() { - var canvas = canvasRef.value; - if (canvas.width > 0 && canvas.height > 0) { - var context = canvas.getContext("2d"); - var imageData = context.getImageData(0, 0, canvas.width, canvas.height); - wrapper(canvas); - context.putImageData(imageData, 0, 0); - } else { - wrapper(canvas); +function register(Quill) { + const formats = { + divider, + ins, + align, + direction, + list, + background, + box, + font, + text, + image + }; + const options = {}; + Object.values(formats).forEach((value) => extend(options, value(Quill))); + Quill.register(options, true); +} +function useQuill(props2, rootRef, trigger) { + let quillReady; + let skipMatcher; + let quill; + watch(() => props2.readOnly, (value) => { + if (quillReady) { + quill.enable(!value); + if (!value) { + quill.blur(); + } } - } - function actionsChanged({ - actions, - reserve, - callbackId - }) { - if (!actions) { - return; + }); + watch(() => props2.placeholder, (value) => { + if (quillReady) { + quill.root.setAttribute("data-placeholder", value); } - if (actionsWaiting.value) { - _actionsDefer.push([actions, reserve, callbackId]); - return; + }); + function 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; + } + } + }); + skipMatcher = true; + const delta = quill.clipboard.convert(content); + skipMatcher = false; + return delta; + } + function getContents() { + const html = quill.root.innerHTML; + const text2 = quill.getText(); + const delta = quill.getContents(); + return { + html, + text: text2, + delta + }; + } + let oldStatus = {}; + function updateStatus(range) { + const status = range ? quill.getFormat(range) : {}; + const keys = Object.keys(status); + if (keys.length !== Object.keys(oldStatus).length || keys.find((key) => status[key] !== oldStatus[key])) { + oldStatus = status; + trigger("statuschange", {}, status); } - var canvas = canvasRef.value; - 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); - } - 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 = 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] = Number(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") { - const font2 = c2d.__font__ || c2d.font; - c2d.__font__ = c2d.font = font2.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 if (method1 === "font") { - c2d.__font__ = c2d.font = 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); - _images = _images || {}; - if (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); + } + function initQuill(imageResizeModules) { + const Quill = window.Quill; + register(Quill); + const options = { + toolbar: false, + readOnly: props2.readOnly, + placeholder: props2.placeholder + }; + if (imageResizeModules.length) { + Quill.register("modules/ImageResize", window.ImageResize.default); + options.modules = { + ImageResize: { + modules: imageResizeModules } - } + }; } - if (!actionsWaiting.value && callbackId) { - UniViewJSBridge.publishHandler("onCanvasMethodCallback", { - callbackId, - data: { - errMsg: "drawCanvas:ok" + const rootEl = rootRef.value; + quill = new Quill(rootEl, options); + const $el = quill.root; + const events = ["focus", "blur", "input"]; + events.forEach((name) => { + $el.addEventListener(name, ($event) => { + if (name === "input") { + $event.stopPropagation(); + } else { + trigger(name, $event, getContents()); } - }, getCurrentPageId()); - } - } - function preloadImage(actions) { - actions.forEach(function(action) { - var method = action.method; - var data = action.data; - var src = ""; - if (method === "drawImage") { - src = data[0]; - src = $getRealPath(src); - data[0] = src; - } else if (method === "setFillStyle" && data[0] === "pattern") { - src = data[1]; - src = $getRealPath(src); - data[1] = src; - } - if (src && !_images[src]) { - loadImage(); + }); + }); + quill.on("text-change", () => { + trigger("input", {}, getContents()); + }); + quill.on("selection-change", updateStatus); + quill.on("scroll-optimize", () => { + const range = quill.selection.getRange()[0]; + updateStatus(range); + }); + quill.clipboard.addMatcher(Node.ELEMENT_NODE, (node, delta) => { + if (skipMatcher) { + return delta; } - function loadImage() { - const image2 = _images[src] = new Image(); - image2.onload = function() { - image2.ready = true; - }; - getSameOriginUrl(src).then((src2) => { - image2.src = src2; - }).catch(() => { - image2.src = src; - }); + if (delta.ops) { + delta.ops = delta.ops.filter(({insert}) => typeof insert === "string").map(({insert}) => ({insert})); } + return delta; }); + quillReady = true; + trigger("ready", {}, {}); } - function checkImageLoaded(src, actions, callbackId, fn) { - var image2 = _images[src]; - if (image2.ready) { - fn(image2); - return true; - } else { - _actionsDefer.unshift([actions, true]); - actionsWaiting.value = true; - image2.onload = function() { - image2.ready = true; - fn(image2); - actionsWaiting.value = false; - var actions2 = _actionsDefer.slice(0); - _actionsDefer = []; - for (var action = actions2.shift(); action; ) { - actionsChanged({ - actions: action[0], - reserve: action[1], - callbackId - }); - action = actions2.shift(); - } - }; - return false; + onMounted(() => { + const imageResizeModules = []; + if (props2.showImgSize) { + imageResizeModules.push("DisplaySize"); } - } - function getImageData({ - x = 0, - y = 0, - width, - height, - destWidth, - destHeight, - hidpi = true, - dataType: dataType2, - quality = 1, - type = "png", - callbackId - }) { - const canvas = canvasRef.value; - let data; - const maxWidth = canvas.offsetWidth - x; - width = width ? Math.min(width, maxWidth) : maxWidth; - const maxHeight = canvas.offsetHeight - y; - height = height ? Math.min(height, maxHeight) : maxHeight; - 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; + if (props2.showImgToolbar) { + imageResizeModules.push("Toolbar"); } - const newCanvas = getTempCanvas(destWidth, destHeight); - const context = newCanvas.getContext("2d"); - if (type === "jpeg" || type === "jpg") { - type = "jpeg"; - context.fillStyle = "#fff"; - context.fillRect(0, 0, destWidth, destHeight); + if (props2.showImgResize) { + imageResizeModules.push("Resize"); } - context.__hidpi__ = true; - context.drawImageByCanvas(canvas, x, y, width, height, 0, 0, destWidth, destHeight, false); - let result; - try { - let compressed; - if (dataType2 === "base64") { - data = newCanvas.toDataURL(`image/${type}`, quality); + const quillSrc = "https://unpkg.com/quill@1.3.7/dist/quill.min.js"; + loadScript(window.Quill, quillSrc, () => { + if (imageResizeModules.length) { + const imageResizeSrc = "https://unpkg.com/quill-image-resize-mp@3.0.1/image-resize.min.js"; + loadScript(window.ImageResize, imageResizeSrc, () => { + initQuill(imageResizeModules); + }); } else { - const imgData = context.getImageData(0, 0, destWidth, destHeight); - if (false) - ; - else { - data = Array.prototype.slice.call(imgData.data); - } + initQuill(imageResizeModules); } - result = { - errMsg: "canvasGetImageData:ok", - data, - compressed, - width: destWidth, - height: destHeight - }; - } catch (error) { - result = { - errMsg: `canvasGetImageData:fail ${error}` - }; - } - newCanvas.height = newCanvas.width = 0; - context.__hidpi__ = false; - if (!callbackId) { - return result; + }); + }); + const id2 = useContextInfo(); + useSubscribe((type, data) => { + const {options, callbackId} = data; + let res; + let range; + let errMsg; + if (quillReady) { + const Quill = window.Quill; + 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", "user"); + } else if (!value && align2 === "right") { + quill.format("align", false, "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, "user"); + } + break; + case "insertDivider": + range = quill.getSelection(true); + quill.insertText(range.index, "\n", "user"); + quill.insertEmbed(range.index + 1, "divider", true, "user"); + quill.setSelection(range.index + 2, 0, "silent"); + break; + case "insertImage": + { + range = quill.getSelection(true); + const { + src = "", + alt = "", + width = "", + height = "", + extClass = "", + data: data2 = {} + } = options; + const path = getRealPath(src); + quill.insertEmbed(range.index, "image", path, "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, 0, "silent"); + } + break; + case "insertText": + { + range = quill.getSelection(true); + const {text: text2 = ""} = options; + quill.insertText(range.index, text2, "user"); + quill.setSelection(range.index + text2.length, 0, "silent"); + } + break; + case "setContents": + { + const {delta, html} = options; + if (typeof delta === "object") { + quill.setContents(delta, "silent"); + } else if (typeof html === "string") { + quill.setContents(html2delta(html), "silent"); + } else { + errMsg = "contents is missing"; + } + } + break; + case "getContents": + res = getContents(); + break; + case "clear": + quill.setText(""); + break; + case "removeFormat": + { + range = quill.getSelection(true); + const parchment = Quill.import("parchment"); + if (range.length) { + quill.removeFormat(range.index, range.length, "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; + case "blur": + quill.blur(); + break; + case "getSelectionText": + range = quill.selection.savedRange; + res = {text: ""}; + if (range && range.length !== 0) { + res.text = quill.getText(range.index, range.length); + } + break; + case "scrollIntoView": + quill.scrollIntoView(); + break; + } + updateStatus(range); } else { - UniViewJSBridge.publishHandler("onCanvasMethodCallback", { - callbackId, - data: result - }, getCurrentPageId()); + errMsg = "not ready"; } - } - function putImageData({ - data, - x, - y, - width, - height, - compressed, - callbackId - }) { - try { - if (!height) { - height = Math.round(data.length / 4 / width); - } - const canvas = getTempCanvas(width, height); - const context = canvas.getContext("2d"); - if (false) - ; - context.putImageData(new ImageData(new Uint8ClampedArray(data), width, height), 0, 0); - canvasRef.value.getContext("2d").drawImage(canvas, x, y, width, height); - canvas.height = canvas.width = 0; - } catch (error) { - UniViewJSBridge.publishHandler("onCanvasMethodCallback", { + if (callbackId) { + UniViewJSBridge.publishHandler("onEditorMethodCallback", { callbackId, - data: { - errMsg: "canvasPutImageData:fail" - } - }, getCurrentPageId()); - return; + data: extend({}, res, { + errMsg: `${type}:${errMsg ? "fail " + errMsg : "ok"}` + }) + }); } - UniViewJSBridge.publishHandler("onCanvasMethodCallback", { - callbackId, - data: { - errMsg: "canvasPutImageData:ok" - } - }, getCurrentPageId()); + }, id2, true); +} +const props$w = /* @__PURE__ */ extend({}, props$x, { + 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 } - function toTempFilePath({ - x = 0, - y = 0, - width, - height, - destWidth, - destHeight, - fileType, - quality, - dirname, - callbackId - }) { - const res = getImageData({ - x, - y, - width, - height, - destWidth, - destHeight, - hidpi: false, - dataType: "base64", - type: fileType, - quality - }); - if (!res.data || !res.data.length) { - UniViewJSBridge.publishHandler("onCanvasMethodCallback", { - callbackId, - data: { - errMsg: res.errMsg.replace("canvasPutImageData", "toTempFilePath") - } - }, getCurrentPageId()); - return; - } - saveImage(res.data, dirname, (error, tempFilePath) => { - let errMsg = `toTempFilePath:${error ? "fail" : "ok"}`; - if (error) { - errMsg += ` ${error.message}`; - } - UniViewJSBridge.publishHandler("onCanvasMethodCallback", { - callbackId, - data: { - errMsg, - tempFilePath - } - }, getCurrentPageId()); - }); - } - const methods = { - actionsChanged, - getImageData, - putImageData, - toTempFilePath - }; - function _handleSubscribe(type, data = {}) { - let method = methods[type]; - if (type.indexOf("_") !== 0 && typeof method === "function") { - method(data); - } - } - return extend(methods, { - _resize, - _handleSubscribe - }); -} -const uniCheckGroupKey = PolySymbol(process.env.NODE_ENV !== "production" ? "uniCheckGroup" : "ucg"); -const props$z = { - name: { - type: String, - default: "" - } -}; -var index$p = /* @__PURE__ */ defineBuiltInComponent({ - name: "CheckboxGroup", - props: props$z, - emits: ["change"], +}); +var index$n = /* @__PURE__ */ defineBuiltInComponent({ + name: "Editor", + props: props$w, + emit: ["ready", "focus", "blur", "input", "statuschange", ...emit$1], setup(props2, { - emit: emit2, - slots + emit: emit2 }) { const rootRef = ref(null); const trigger = useCustomEvent(rootRef, emit2); - useProvideCheckGroup(props2, trigger); + useQuill(props2, rootRef, trigger); + useKeyboard$1(props2, rootRef); return () => { - return createVNode("uni-checkbox-group", { - "ref": rootRef - }, [slots.default && slots.default()], 512); + return createVNode("uni-editor", { + "ref": rootRef, + "id": props2.id, + "class": "ql-container" + }, null, 8, ["id"]); }; } }); -function useProvideCheckGroup(props2, trigger) { - const fields2 = []; - const getFieldsValue = () => fields2.reduce((res, field) => { - if (field.value.checkboxChecked) { - res.push(field.value.value); - } - return res; - }, new Array()); - provide(uniCheckGroupKey, { - addField(field) { - fields2.push(field); +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 + }, + success_no_circle: { + d: ICON_PATH_SUCCESS_NO_CIRCLE, + c: PRIMARY_COLOR + }, + 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 + }, + search: { + d: ICON_PATH_SEARCH, + c: GREY_COLOR + }, + clear: { + d: ICON_PATH_CLEAR, + c: GREY_COLOR + } +}; +var index$m = /* @__PURE__ */ defineBuiltInComponent({ + name: "Icon", + props: { + type: { + type: String, + required: true, + default: "" }, - removeField(field) { - fields2.splice(fields2.indexOf(field), 1); + size: { + type: [String, Number], + default: 23 }, - checkboxChange($event) { - trigger("change", $event, { - value: getFieldsValue() - }); + color: { + type: String, + default: "" } - }); - const uniForm = inject(uniFormKey, false); - if (uniForm) { - uniForm.addField({ - submit: () => { - let data = ["", null]; - if (props2.name !== "") { - data[0] = props2.name; - data[1] = getFieldsValue(); - } - return data; - } - }); - } - return getFieldsValue; -} -const props$y = { - checked: { - type: [Boolean, String], - default: false }, - id: { + setup(props2) { + const path = computed(() => ICONS[props2.type]); + return () => { + const { + value + } = path; + return createVNode("uni-icon", null, [value && value.d && createSvgIconVNode(value.d, props2.color || value.c, rpx2px(props2.size))]); + }; + } +}); +const props$v = { + src: { type: String, default: "" }, - disabled: { + mode: { + type: String, + default: "scaleToFill" + }, + lazyLoad: { type: [Boolean, String], default: false }, - color: { - type: String, - default: "#007aff" - }, - value: { - type: String, - default: "" + draggable: { + type: Boolean, + default: true } }; -var index$o = /* @__PURE__ */ defineBuiltInComponent({ - name: "Checkbox", - props: props$y, +const FIX_MODES = { + widthFix: ["width", "height"], + heightFix: ["height", "width"] +}; +const IMAGE_MODES = { + aspectFit: ["center center", "contain"], + aspectFill: ["center center", "cover"], + widthFix: [, "100% 100%"], + heightFix: [, "100% 100%"], + top: ["center top"], + bottom: ["center bottom"], + center: ["center center"], + left: ["left center"], + right: ["right center"], + "top left": ["left top"], + "top right": ["right top"], + "bottom left": ["left bottom"], + "bottom right": ["right bottom"] +}; +var index$l = /* @__PURE__ */ defineBuiltInComponent({ + name: "Image", + props: props$v, setup(props2, { - slots + emit: emit2 }) { - const checkboxChecked = ref(props2.checked); - const checkboxValue = ref(props2.value); - watch([() => props2.checked, () => props2.value], ([newChecked, newModelValue]) => { - checkboxChecked.value = newChecked; - checkboxValue.value = newModelValue; - }); - const reset = () => { - checkboxChecked.value = false; - }; + const rootRef = ref(null); + const state2 = useImageState(rootRef, props2); + const trigger = useCustomEvent(rootRef, emit2); const { - uniCheckGroup, - uniLabel - } = useCheckboxInject(checkboxChecked, checkboxValue, reset); - const _onClick = ($event) => { - if (props2.disabled) { - return; - } - checkboxChecked.value = !checkboxChecked.value; - uniCheckGroup && uniCheckGroup.checkboxChange($event); - }; - if (!!uniLabel) { - uniLabel.addHandler(_onClick); - onBeforeUnmount(() => { - uniLabel.removeHandler(_onClick); - }); - } - useListeners$1(props2, { - "label-click": _onClick + fixSize + } = useImageSize(rootRef, props2, state2); + useImageLoader(state2, { + trigger, + fixSize }); return () => { const { - booleanAttrs - } = useBooleanAttr(props2, "disabled"); - return createVNode("uni-checkbox", mergeProps(booleanAttrs, { - "onClick": _onClick - }), [createVNode("div", { - "class": "uni-checkbox-wrapper" + mode: mode2 + } = props2; + const { + imgSrc, + modeStyle + } = state2; + return createVNode("uni-image", { + "ref": rootRef }, [createVNode("div", { - "class": ["uni-checkbox-input", { - "uni-checkbox-input-disabled": props2.disabled - }] - }, [checkboxChecked.value ? createSvgIconVNode(ICON_PATH_SUCCESS_NO_CIRCLE, props2.color, 22) : ""], 2), slots.default && slots.default()])], 16, ["onClick"]); + "style": modeStyle + }, null, 4), imgSrc ? createVNode("img", { + "src": imgSrc, + "draggable": props2.draggable + }, null, 8, ["src", "draggable"]) : createVNode("img", null, null), FIX_MODES[mode2] ? createVNode(ResizeSensor, { + "onResize": fixSize + }, null, 8, ["onResize"]) : createVNode("span", null, null)], 512); }; } }); -function useCheckboxInject(checkboxChecked, checkboxValue, reset) { - const field = computed(() => ({ - checkboxChecked: Boolean(checkboxChecked.value), - value: checkboxValue.value - })); - const formField = { - reset +function useImageState(rootRef, props2) { + const imgSrc = ref(""); + const modeStyleRef = computed(() => { + let size = "auto"; + let position = ""; + const opts = IMAGE_MODES[props2.mode]; + if (!opts) { + position = "0% 0%"; + size = "100% 100%"; + } else { + opts[0] && (position = opts[0]); + opts[1] && (size = opts[1]); + } + const srcVal = imgSrc.value; + return `background-image:${srcVal ? 'url("' + srcVal + '")' : "none"};background-position:${position};background-size:${size};background-repeat:no-repeat;`; + }); + const state2 = reactive({ + rootEl: rootRef, + src: computed(() => props2.src ? getRealPath(props2.src) : ""), + origWidth: 0, + origHeight: 0, + origStyle: { + width: "", + height: "" + }, + modeStyle: modeStyleRef, + imgSrc + }); + onMounted(() => { + const rootEl = rootRef.value; + const style = rootEl.style; + state2.origWidth = Number(style.width) || 0; + state2.origHeight = Number(style.height) || 0; + }); + return state2; +} +function useImageLoader(state2, { + trigger, + fixSize +}) { + let img; + const setState = (width = 0, height = 0, imgSrc = "") => { + state2.origWidth = width; + state2.origHeight = height; + state2.imgSrc = imgSrc; }; - const uniCheckGroup = inject(uniCheckGroupKey, false); - if (!!uniCheckGroup) { - uniCheckGroup.addField(field); - } - const uniForm = inject(uniFormKey, false); - if (!!uniForm) { - uniForm.addField(formField); + const loadImage = (src) => { + if (!src) { + resetImage(); + setState(); + return; + } + if (!img) { + img = new Image(); + } + img.onload = (evt) => { + const { + width, + height + } = img; + setState(width, height, src); + fixSize(); + resetImage(); + trigger("load", evt, { + width, + height + }); + }; + img.onerror = (evt) => { + setState(); + resetImage(); + trigger("error", evt, { + errMsg: `GET ${state2.src} 404 (Not Found)` + }); + }; + img.src = src; + }; + const resetImage = () => { + if (img) { + img.onload = null; + img.onerror = null; + img = null; + } + }; + watch(() => state2.src, (value) => loadImage(value)); + onMounted(() => loadImage(state2.src)); + onBeforeUnmount(() => resetImage()); +} +const isChrome = navigator.vendor === "Google Inc."; +function fixNumber(num) { + if (isChrome && num > 10) { + num = Math.round(num / 2) * 2; } - const uniLabel = inject(uniLabelKey, false); - onBeforeUnmount(() => { - uniCheckGroup && uniCheckGroup.removeField(field); - uniForm && uniForm.removeField(formField); + return num; +} +function useImageSize(rootRef, props2, state2) { + const fixSize = () => { + const { + mode: mode2 + } = props2; + const names = FIX_MODES[mode2]; + if (!names) { + return; + } + const { + origWidth, + origHeight + } = state2; + const ratio = origWidth && origHeight ? origWidth / origHeight : 0; + if (!ratio) { + return; + } + const rootEl = rootRef.value; + const rect = rootEl.getBoundingClientRect(); + const value = rect[names[0]]; + if (value) { + rootEl.style[names[1]] = fixNumber(value / ratio) + "px"; + } + }; + const resetSize = () => { + const { + style + } = rootRef.value; + const { + origStyle: { + width, + height + } + } = state2; + style.width = width; + style.height = height; + }; + watch(() => props2.mode, (value, oldValue) => { + if (FIX_MODES[oldValue]) { + resetSize(); + } + if (FIX_MODES[value]) { + fixSize(); + } }); return { - uniCheckGroup, - uniForm, - uniLabel + fixSize, + resetSize }; } -let resetTimer; -function iosHideKeyboard() { +const passiveOptions$1 = passive(true); +const states = []; +let userInteract = 0; +let inited; +function addInteractListener(vm) { + if (!inited) { + const eventNames = [ + "touchstart", + "touchmove", + "touchend", + "mousedown", + "mouseup" + ]; + eventNames.forEach((eventName) => { + document.addEventListener(eventName, function() { + states.forEach((vm2) => { + vm2.userAction = true; + userInteract++; + setTimeout(() => { + userInteract--; + if (!userInteract) { + vm2.userAction = false; + } + }, 0); + }); + }, passiveOptions$1); + }); + inited = true; + } + states.push(vm); } -const props$x = { - cursorSpacing: { - type: [Number, String], - default: 0 - }, - showConfirmBar: { - type: [Boolean, String], - default: "auto" - }, - adjustPosition: { - type: [Boolean, String], - default: true - }, - autoBlur: { - type: [Boolean, String], - default: false +function removeInteractListener(vm) { + const index2 = states.indexOf(vm); + if (index2 >= 0) { + states.splice(index2, 1); } -}; -const emit$1 = ["keyboardheightchange"]; -function useKeyboard$1(props2, elRef, trigger) { - function initKeyboard(el) { - el.addEventListener("focus", () => { - clearTimeout(resetTimer); - document.addEventListener("click", iosHideKeyboard, false); - }); - const onKeyboardHide = () => { - document.removeEventListener("click", iosHideKeyboard, false); - if (String(navigator.vendor).indexOf("Apple") === 0) { - document.documentElement.scrollTo(document.documentElement.scrollLeft, document.documentElement.scrollTop); - } - }; - el.addEventListener("blur", () => { - onKeyboardHide(); - }); - } - watch(() => elRef.value, (el) => initKeyboard(el)); } -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 useUserAction() { + const state2 = reactive({ + userAction: false + }); + onMounted(() => { + addInteractListener(state2); + }); + onBeforeUnmount(() => { + removeInteractListener(state2); + }); + return { + state: state2 }; - 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; - } - last = html; - } - parseEndTag(); - function parseStartTag(tag, tagName, rest, unary) { - tagName = tagName.toLowerCase(); - if (block[tagName]) { - while (stack.last() && inline[stack.last()]) { - parseEndTag("", stack.last()); - } - } - if (closeSelf[tagName] && stack.last() == tagName) { - parseEndTag("", tagName); - } - unary = empty[tagName] || !!unary; - if (!unary) { - stack.push(tagName); - } - 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); - } - } - } - 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 i = stack.length - 1; i >= pos; i--) { - if (handler.end) { - handler.end(stack[i]); - } +} +function useScopedAttrs() { + const state2 = reactive({ + attrs: {} + }); + onMounted(() => { + let instance2 = getCurrentInstance(); + while (instance2) { + const scopeId = instance2.type.__scopeId; + if (scopeId) { + state2.attrs[scopeId] = ""; } - stack.length = pos; + instance2 = instance2.__isPage ? null : instance2.parent; } - } -} -function makeMap(str) { - var obj = {}; - var items = str.split(","); - for (var i = 0; i < items.length; i++) { - obj[items[i]] = true; - } - return obj; -} -const scripts = {}; -function loadScript(globalName, src, callback) { - const globalObject = typeof globalName === "string" ? window[globalName] : globalName; - if (globalObject) { - callback(); - return; - } - let callbacks2 = scripts[src]; - if (!callbacks2) { - callbacks2 = scripts[src] = []; - const script = document.createElement("script"); - script.src = src; - document.body.appendChild(script); - script.onload = function() { - callbacks2.forEach((callback2) => callback2()); - delete scripts[src]; - }; - } - callbacks2.push(callback); -} -function divider(Quill) { - const BlockEmbed = Quill.import("blots/block/embed"); - class Divider extends BlockEmbed { - } - Divider.blotName = "divider"; - Divider.tagName = "HR"; + }); return { - "formats/divider": Divider + state: state2 }; } -function ins(Quill) { - const Inline = Quill.import("blots/inline"); - class Ins extends Inline { +function useFormField(nameKey, value) { + const uniForm = inject(uniFormKey, false); + if (!uniForm) { + return; } - Ins.blotName = "ins"; - Ins.tagName = "INS"; - return { - "formats/ins": Ins + const instance2 = getCurrentInstance(); + const ctx = { + submit() { + const proxy = instance2.proxy; + return [ + proxy[nameKey], + typeof value === "string" ? proxy[value] : value.value + ]; + }, + reset() { + if (typeof value === "string") { + instance2.proxy[value] = ""; + } else { + value.value = ""; + } + } }; + uniForm.addField(ctx); + onBeforeUnmount(() => { + uniForm.removeField(ctx); + }); } -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 - }; +const pageIds = []; +const UniViewJSBridgeSubscribe = function() { + const pageId = getCurrentPageId(); + if (pageIds.includes(pageId)) + return; + pageIds.push(pageId); + UniViewJSBridge.subscribe(pageId + ".getSelectedTextRange", function({pageId: pageId2, callbackId}) { + const activeElement = document.activeElement; + if (!activeElement) + return; + const tagName = activeElement.tagName.toLowerCase(); + const tagNames = ["input", "textarea"]; + const data = {}; + if (tagNames.includes(tagName)) { + data.start = activeElement.selectionStart; + data.end = activeElement.selectionEnd; + } + UniViewJSBridge.publishHandler("onGetSelectedTextRange", { + callbackId, + data + }, pageId2); + }); +}; +function getValueString(value) { + return value === null ? "" : String(value); } -function direction(Quill) { - const {Scope, Attributor} = Quill.import("parchment"); - const config = { - scope: Scope.BLOCK, - whitelist: ["rtl"] +const props$u = /* @__PURE__ */ extend({}, { + name: { + type: String, + default: "" + }, + modelValue: { + type: [String, Number], + default: "" + }, + value: { + type: [String, Number], + default: "" + }, + disabled: { + type: [Boolean, String], + default: false + }, + autoFocus: { + type: [Boolean, String], + default: false + }, + focus: { + type: [Boolean, String], + default: false + }, + cursor: { + type: [Number, String], + default: -1 + }, + selectionStart: { + type: [Number, String], + default: -1 + }, + selectionEnd: { + type: [Number, String], + default: -1 + }, + type: { + type: String, + default: "text" + }, + password: { + type: [Boolean, String], + default: false + }, + placeholder: { + type: String, + default: "" + }, + placeholderStyle: { + type: String, + default: "" + }, + placeholderClass: { + type: String, + default: "" + }, + maxlength: { + type: [Number, String], + default: 140 + }, + confirmType: { + type: String, + default: "done" + } +}, props$x); +const emit = [ + "input", + "focus", + "blur", + "update:value", + "update:modelValue", + "update:focus", + ...emit$1 +]; +function useBase(props2, rootRef, emit2) { + const fieldRef = ref(null); + const trigger = useCustomEvent(rootRef, emit2); + const selectionStart = computed(() => { + const selectionStart2 = Number(props2.selectionStart); + return isNaN(selectionStart2) ? -1 : selectionStart2; + }); + const selectionEnd = computed(() => { + const selectionEnd2 = Number(props2.selectionEnd); + return isNaN(selectionEnd2) ? -1 : selectionEnd2; + }); + const cursor = computed(() => { + const cursor2 = Number(props2.cursor); + return isNaN(cursor2) ? -1 : cursor2; + }); + const maxlength = computed(() => { + var maxlength2 = Number(props2.maxlength); + return isNaN(maxlength2) ? 140 : maxlength2; + }); + const value = getValueString(props2.modelValue) || getValueString(props2.value); + const state2 = reactive({ + value, + valueOrigin: value, + maxlength, + focus: props2.focus, + composing: false, + selectionStart, + selectionEnd, + cursor + }); + watch(() => state2.focus, (val) => emit2("update:focus", val)); + watch(() => state2.maxlength, (val) => state2.value = state2.value.slice(0, val)); + return { + fieldRef, + state: state2, + trigger }; - const DirectionStyle = new Attributor.Style("direction", "direction", config); +} +function useValueSync(props2, state2, emit2, trigger) { + const valueChangeFn = debounce((val) => { + state2.value = getValueString(val); + }, 100); + watch(() => props2.modelValue, valueChangeFn); + watch(() => props2.value, valueChangeFn); + const triggerInputFn = throttle((event, detail) => { + emit2("update:modelValue", detail.value); + emit2("update:value", detail.value); + trigger("input", event, detail); + }, 100); + const triggerInput = (event, detail, force) => { + valueChangeFn.cancel(); + triggerInputFn(event, detail); + if (force) { + triggerInputFn.flush(); + } + }; + onBeforeMount(() => { + valueChangeFn.cancel(); + triggerInputFn.cancel(); + }); return { - "formats/direction": DirectionStyle + trigger, + triggerInput }; } -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; +function useAutoFocus(props2, fieldRef) { + useUserAction(); + const needFocus = computed(() => props2.autoFocus || props2.focus); + function focus() { + if (!needFocus.value) { + return; } - 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; + const field = fieldRef.value; + if (!field || false) { + setTimeout(focus, 100); + return; } - 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); + { + field.focus(); } - format(name, value) { - if (this.children.length > 0) { - this.children.tail.format(name, value); - } + } + function blur() { + const field = fieldRef.value; + if (field) { + field.blur(); } - formats() { - return {[this.statics.blotName]: this.statics.formats(this.domNode)}; + } + watch(() => props2.focus, (value) => { + if (value) { + focus(); + } else { + blur(); } - 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); - } + }); + onMounted(() => { + if (needFocus.value) { + nextTick(focus); } - 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(); - } + }); +} +function useEvent(fieldRef, state2, trigger, triggerInput, beforeInput) { + function checkSelection() { + const field = fieldRef.value; + if (field && state2.focus && state2.selectionStart > -1 && state2.selectionEnd > -1) { + field.selectionStart = state2.selectionStart; + field.selectionEnd = state2.selectionEnd; } - 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); + } + function checkCursor() { + const field = fieldRef.value; + if (field && state2.focus && state2.selectionStart < 0 && state2.selectionEnd < 0 && state2.cursor > -1) { + field.selectionEnd = field.selectionStart = state2.cursor; } } - 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 initField() { + const field = fieldRef.value; + const onFocus = function(event) { + state2.focus = true; + trigger("focus", event, { + value: state2.value + }); + checkSelection(); + checkCursor(); + }; + const onInput = function(event, force) { + event.stopPropagation(); + if (typeof beforeInput === "function" && beforeInput(event, state2) === false) { + return; + } + state2.value = field.value; + if (!state2.composing) { + triggerInput(event, { + value: field.value, + cursor: field.selectionEnd + }, force); + } + }; + const onBlur = function(event) { + if (state2.composing) { + state2.composing = false; + onInput(event, true); + } + state2.focus = false; + trigger("blur", event, { + value: state2.value, + cursor: event.target.selectionEnd + }); + }; + field.addEventListener("change", (event) => event.stopPropagation()); + field.addEventListener("focus", onFocus); + field.addEventListener("blur", onBlur); + field.addEventListener("input", onInput); + field.addEventListener("compositionstart", (event) => { + event.stopPropagation(); + state2.composing = true; + }); + field.addEventListener("compositionend", (event) => { + event.stopPropagation(); + if (state2.composing) { + state2.composing = false; + onInput(event); + } + }); + } + watch([() => state2.selectionStart, () => state2.selectionEnd], checkSelection); + watch(() => state2.cursor, checkCursor); + watch(() => fieldRef.value, initField); } -function font(Quill) { - const {Scope, Attributor} = Quill.import("parchment"); - const config = { - scope: Scope.INLINE +function useField(props2, rootRef, emit2, beforeInput) { + UniViewJSBridgeSubscribe(); + const {fieldRef, state: state2, trigger} = useBase(props2, rootRef, emit2); + const {triggerInput} = useValueSync(props2, state2, emit2, trigger); + useAutoFocus(props2, fieldRef); + useKeyboard$1(props2, fieldRef); + const {state: scopedAttrsState} = useScopedAttrs(); + useFormField("name", state2); + useEvent(fieldRef, state2, trigger, triggerInput, beforeInput); + const fixDisabledColor = String(navigator.vendor).indexOf("Apple") === 0 && CSS.supports("image-orientation:from-image"); + return { + fieldRef, + state: state2, + scopedAttrsState, + fixDisabledColor, + trigger }; - 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 +const props$t = /* @__PURE__ */ extend({}, props$u, { + placeholderClass: { + type: String, + default: "input-placeholder" + } +}); +var Input = /* @__PURE__ */ defineBuiltInComponent({ + name: "Input", + props: props$t, + emits: ["confirm", ...emit], + setup(props2, { + emit: emit2 + }) { + const INPUT_TYPES = ["text", "number", "idcard", "digit", "password"]; + const type = computed(() => { + let type2 = ""; + switch (props2.type) { + case "text": + if (props2.confirmType === "search") { + type2 = "search"; + } + break; + case "idcard": + type2 = "text"; + break; + case "digit": + type2 = "number"; + break; + default: + type2 = ~INPUT_TYPES.includes(props2.type) ? props2.type : "text"; + break; + } + return props2.password ? "password" : type2; }); - }); - 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); + const valid = ref(true); + const rootRef = ref(null); + const { + fieldRef, + state: state2, + scopedAttrsState, + fixDisabledColor, + trigger + } = useField(props2, rootRef, emit2, (event, state3) => { + const input = event.target; + if (NUMBER_TYPES.includes(props2.type)) { + valid.value = input.validity && input.validity.valid; } - 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); + if (type.value === "number") { + const maxlength = state3.maxlength; + if (maxlength > 0 && input.value.length > maxlength) { + input.value = input.value.slice(0, maxlength); + state3.value = input.value; + return false; + } } - } else { - format.call(this, name, value); + }); + const NUMBER_TYPES = ["number", "digit"]; + const step = computed(() => NUMBER_TYPES.includes(props2.type) ? "0.000000000000000001" : ""); + function onKeyUpEnter(event) { + if (event.key !== "Enter") { + return; + } + event.stopPropagation(); + trigger("confirm", event, { + value: event.target.value + }); } - }; -} -function register(Quill) { - const formats = { - divider, - ins, - align, - direction, - list, - background, - box, - font, - text, - image - }; - const options = {}; - Object.values(formats).forEach((value) => extend(options, value(Quill))); - Quill.register(options, true); -} -function useQuill(props2, rootRef, trigger) { - let quillReady; - let skipMatcher; - let quill; - watch(() => props2.readOnly, (value) => { - if (quillReady) { - quill.enable(!value); - if (!value) { - quill.blur(); + return () => { + let inputNode = props2.disabled && fixDisabledColor ? createVNode("input", { + "ref": fieldRef, + "value": state2.value, + "tabindex": "-1", + "readonly": !!props2.disabled, + "type": type.value, + "maxlength": state2.maxlength, + "step": step.value, + "class": "uni-input-input", + "onFocus": (event) => event.target.blur() + }, null, 40, ["value", "readonly", "type", "maxlength", "step", "onFocus"]) : createVNode("input", { + "ref": fieldRef, + "value": state2.value, + "disabled": !!props2.disabled, + "type": type.value, + "maxlength": state2.maxlength, + "step": step.value, + "enterkeyhint": props2.confirmType, + "class": "uni-input-input", + "autocomplete": "off", + "onKeyup": onKeyUpEnter + }, null, 40, ["value", "disabled", "type", "maxlength", "step", "enterkeyhint", "onKeyup"]); + return createVNode("uni-input", { + "ref": rootRef + }, [createVNode("div", { + "class": "uni-input-wrapper" + }, [withDirectives(createVNode("div", mergeProps(scopedAttrsState.attrs, { + "style": props2.placeholderStyle, + "class": ["uni-input-placeholder", props2.placeholderClass] + }), [props2.placeholder], 16), [[vShow, !(state2.value.length || !valid.value)]]), props2.confirmType === "search" ? createVNode("form", { + "action": "", + "onSubmit": (event) => event.preventDefault(), + "class": "uni-input-form" + }, [inputNode], 40, ["onSubmit"]) : inputNode])], 512); + }; + } +}); +function entries(obj) { + return Object.keys(obj).map((key) => [key, obj[key]]); +} +const DEFAULT_EXCLUDE_KEYS = ["class", "style"]; +const LISTENER_PREFIX = /^on[A-Z]+/; +const useAttrs = (params = {}) => { + const {excludeListeners = false, excludeKeys = []} = params; + const instance2 = getCurrentInstance(); + const attrs2 = shallowRef({}); + const listeners = shallowRef({}); + const excludeAttrs = shallowRef({}); + const allExcludeKeys = excludeKeys.concat(DEFAULT_EXCLUDE_KEYS); + instance2.attrs = reactive(instance2.attrs); + watchEffect(() => { + const res = entries(instance2.attrs).reduce((acc, [key, val]) => { + if (allExcludeKeys.includes(key)) { + acc.exclude[key] = val; + } else if (LISTENER_PREFIX.test(key)) { + if (!excludeListeners) { + acc.attrs[key] = val; + } + acc.listeners[key] = val; + } else { + acc.attrs[key] = val; } - } - }); - watch(() => props2.placeholder, (value) => { - if (quillReady) { - quill.root.setAttribute("data-placeholder", value); - } + return acc; + }, { + exclude: {}, + attrs: {}, + listeners: {} + }); + attrs2.value = res.attrs; + listeners.value = res.listeners; + excludeAttrs.value = res.exclude; }); - function 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; + return {$attrs: attrs2, $listeners: listeners, $excludeAttrs: excludeAttrs}; +}; +function initScrollBounce() { +} +function disableScrollBounce({disable}) { +} +function flatVNode(nodes) { + const array = []; + if (Array.isArray(nodes)) { + nodes.forEach((vnode) => { + if (isVNode(vnode)) { + if (vnode.type === Fragment) { + array.push(...flatVNode(vnode.children)); + } else { + array.push(vnode); } + } else if (Array.isArray(vnode)) { + array.push(...flatVNode(vnode)); } }); - skipMatcher = true; - const delta = quill.clipboard.convert(content); - skipMatcher = false; - return delta; - } - function getContents() { - const html = quill.root.innerHTML; - const text2 = quill.getText(); - const delta = quill.getContents(); - return { - html, - text: text2, - delta - }; } - let oldStatus = {}; - function updateStatus(range) { - const status = range ? quill.getFormat(range) : {}; - const keys = Object.keys(status); - if (keys.length !== Object.keys(oldStatus).length || keys.find((key) => status[key] !== oldStatus[key])) { - oldStatus = status; - trigger("statuschange", {}, status); - } + return array; +} +const props$s = { + scaleArea: { + type: Boolean, + default: false } - function initQuill(imageResizeModules) { - const Quill = window.Quill; - register(Quill); - const options = { - toolbar: false, - readOnly: props2.readOnly, - placeholder: props2.placeholder - }; - if (imageResizeModules.length) { - Quill.register("modules/ImageResize", window.ImageResize.default); - options.modules = { - ImageResize: { - modules: imageResizeModules - } - }; - } - const rootEl = rootRef.value; - quill = new Quill(rootEl, options); - const $el = quill.root; - const events = ["focus", "blur", "input"]; - events.forEach((name) => { - $el.addEventListener(name, ($event) => { - if (name === "input") { - $event.stopPropagation(); - } else { - trigger(name, $event, getContents()); - } - }); - }); - quill.on("text-change", () => { - trigger("input", {}, getContents()); +}; +var MovableArea = /* @__PURE__ */ defineBuiltInComponent({ + inheritAttrs: false, + name: "MovableArea", + props: props$s, + setup(props2, { + slots + }) { + const rootRef = ref(null); + const _isMounted = ref(false); + let { + setContexts, + events: movableAreaEvents + } = useMovableAreaState(props2, rootRef); + const { + $listeners, + $attrs, + $excludeAttrs + } = useAttrs(); + const _listeners = $listeners.value; + let events = ["onTouchstart", "onTouchmove", "onTouchend"]; + events.forEach((event) => { + let existing = _listeners[event]; + let ours = movableAreaEvents[`_${event}`]; + _listeners[event] = existing ? [].concat(existing, ours) : ours; }); - quill.on("selection-change", updateStatus); - quill.on("scroll-optimize", () => { - const range = quill.selection.getRange()[0]; - updateStatus(range); + onMounted(() => { + movableAreaEvents._resize(); + _isMounted.value = true; }); - quill.clipboard.addMatcher(Node.ELEMENT_NODE, (node, delta) => { - if (skipMatcher) { - return delta; - } - if (delta.ops) { - delta.ops = delta.ops.filter(({insert}) => typeof insert === "string").map(({insert}) => ({insert})); + let movableViewItems = []; + const originMovableViewContexts = []; + function updateMovableViewContexts() { + const contexts = []; + for (let index2 = 0; index2 < movableViewItems.length; index2++) { + const movableViewItem = movableViewItems[index2]; + const movableViewContext = originMovableViewContexts.find((context) => movableViewItem.el === context.rootRef.value); + if (movableViewContext) { + contexts.push(markRaw(movableViewContext)); + } } - return delta; - }); - quillReady = true; - trigger("ready", {}, {}); - } - onMounted(() => { - const imageResizeModules = []; - if (props2.showImgSize) { - imageResizeModules.push("DisplaySize"); - } - if (props2.showImgToolbar) { - imageResizeModules.push("Toolbar"); - } - if (props2.showImgResize) { - imageResizeModules.push("Resize"); + setContexts(contexts); } - const quillSrc = "https://unpkg.com/quill@1.3.7/dist/quill.min.js"; - loadScript(window.Quill, quillSrc, () => { - if (imageResizeModules.length) { - const imageResizeSrc = "https://unpkg.com/quill-image-resize-mp@3.0.1/image-resize.min.js"; - loadScript(window.ImageResize, imageResizeSrc, () => { - initQuill(imageResizeModules); - }); - } else { - initQuill(imageResizeModules); + const addMovableViewContext = (movableViewContext) => { + originMovableViewContexts.push(movableViewContext); + updateMovableViewContexts(); + }; + const removeMovableViewContext = (movableViewContext) => { + const index2 = originMovableViewContexts.indexOf(movableViewContext); + if (index2 >= 0) { + originMovableViewContexts.splice(index2, 1); + updateMovableViewContexts(); } - }); + }; + provide("_isMounted", _isMounted); + provide("movableAreaRootRef", rootRef); + provide("addMovableViewContext", addMovableViewContext); + provide("removeMovableViewContext", removeMovableViewContext); + return () => { + const defaultSlots = slots.default && slots.default(); + movableViewItems = flatVNode(defaultSlots); + return createVNode("uni-movable-area", mergeProps({ + "ref": rootRef + }, $attrs.value, $excludeAttrs.value, _listeners), [createVNode(ResizeSensor, { + "onReize": movableAreaEvents._resize + }, null, 8, ["onReize"]), movableViewItems], 16); + }; + } +}); +function calc(e2) { + return Math.sqrt(e2.x * e2.x + e2.y * e2.y); +} +function useMovableAreaState(props2, rootRef) { + const width = ref(0); + const height = ref(0); + const gapV = reactive({ + x: null, + y: null }); - const id2 = useContextInfo(); - useSubscribe((type, data) => { - const {options, callbackId} = data; - let res; - let range; - let errMsg; - if (quillReady) { - const Quill = window.Quill; - 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", "user"); - } else if (!value && align2 === "right") { - quill.format("align", false, "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, "user"); - } - break; - case "insertDivider": - range = quill.getSelection(true); - quill.insertText(range.index, "\n", "user"); - quill.insertEmbed(range.index + 1, "divider", true, "user"); - quill.setSelection(range.index + 2, 0, "silent"); - break; - case "insertImage": - { - range = quill.getSelection(true); - const { - src = "", - alt = "", - width = "", - height = "", - extClass = "", - data: data2 = {} - } = options; - const path = getRealPath(src); - quill.insertEmbed(range.index, "image", path, "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, 0, "silent"); - } - break; - case "insertText": - { - range = quill.getSelection(true); - const {text: text2 = ""} = options; - quill.insertText(range.index, text2, "user"); - quill.setSelection(range.index + text2.length, 0, "silent"); - } - break; - case "setContents": - { - const {delta, html} = options; - if (typeof delta === "object") { - quill.setContents(delta, "silent"); - } else if (typeof html === "string") { - quill.setContents(html2delta(html), "silent"); - } else { - errMsg = "contents is missing"; - } - } - break; - case "getContents": - res = getContents(); - break; - case "clear": - quill.setText(""); - break; - case "removeFormat": - { - range = quill.getSelection(true); - const parchment = Quill.import("parchment"); - if (range.length) { - quill.removeFormat(range.index, range.length, "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; - case "blur": - quill.blur(); - break; - case "getSelectionText": - range = quill.selection.savedRange; - res = {text: ""}; - if (range && range.length !== 0) { - res.text = quill.getText(range.index, range.length); - } - break; - case "scrollIntoView": - quill.scrollIntoView(); - break; + const pinchStartLen = ref(null); + let _scaleMovableView = null; + let movableViewContexts = []; + function _updateScale(e2) { + if (e2 && e2 !== 1) { + if (props2.scaleArea) { + movableViewContexts.forEach(function(item) { + item._setScale(e2); + }); + } else { + if (_scaleMovableView) { + _scaleMovableView._setScale(e2); + } } - updateStatus(range); - } else { - errMsg = "not ready"; } - if (callbackId) { - UniViewJSBridge.publishHandler("onEditorMethodCallback", { - callbackId, - data: extend({}, res, { - errMsg: `${type}:${errMsg ? "fail " + errMsg : "ok"}` - }) - }); + } + function _find(target, items = movableViewContexts) { + let root = rootRef.value; + function get(node) { + for (let i = 0; i < items.length; i++) { + const item = items[i]; + if (node === item.rootRef.value) { + return item; + } + } + if (node === root || node === document.body || node === document) { + return null; + } + return get(node.parentNode); } - }, id2, true); -} -const props$w = /* @__PURE__ */ extend({}, props$x, { - 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 get(target); } -}); -var index$n = /* @__PURE__ */ defineBuiltInComponent({ - name: "Editor", - props: props$w, - emit: ["ready", "focus", "blur", "input", "statuschange", ...emit$1], - setup(props2, { - emit: emit2 - }) { - const rootRef = ref(null); - const trigger = useCustomEvent(rootRef, emit2); - useQuill(props2, rootRef, trigger); - useKeyboard$1(props2, rootRef); - return () => { - return createVNode("uni-editor", { - "ref": rootRef, - "id": props2.id, - "class": "ql-container" - }, null, 8, ["id"]); - }; + const _onTouchstart = withWebEvent((t2) => { + let i = t2.touches; + if (i) { + if (i.length > 1) { + let r = { + x: i[1].pageX - i[0].pageX, + y: i[1].pageY - i[0].pageY + }; + pinchStartLen.value = calc(r); + gapV.x = r.x; + gapV.y = r.y; + if (!props2.scaleArea) { + let touch0 = _find(i[0].target); + let touch1 = _find(i[1].target); + _scaleMovableView = touch0 && touch0 === touch1 ? touch0 : null; + } + } + } + }); + const _onTouchmove = withWebEvent((t2) => { + let n = t2.touches; + if (n) { + if (n.length > 1) { + t2.preventDefault(); + let i = { + x: n[1].pageX - n[0].pageX, + y: n[1].pageY - n[0].pageY + }; + if (gapV.x !== null && pinchStartLen.value && pinchStartLen.value > 0) { + let r = calc(i) / pinchStartLen.value; + _updateScale(r); + } + gapV.x = i.x; + gapV.y = i.y; + } + } + }); + const _onTouchend = withWebEvent((e2) => { + let t2 = e2.touches; + if (!(t2 && t2.length)) { + if (e2.changedTouches) { + gapV.x = 0; + gapV.y = 0; + pinchStartLen.value = null; + if (props2.scaleArea) { + movableViewContexts.forEach(function(item) { + item._endScale(); + }); + } else { + if (_scaleMovableView) { + _scaleMovableView._endScale(); + } + } + } + } + }); + function _resize() { + _getWH(); + movableViewContexts.forEach(function(item, index2) { + item.setParent(); + }); } -}); -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 - }, - success_no_circle: { - d: ICON_PATH_SUCCESS_NO_CIRCLE, - c: PRIMARY_COLOR - }, - 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 - }, - search: { - d: ICON_PATH_SEARCH, - c: GREY_COLOR - }, - clear: { - d: ICON_PATH_CLEAR, - c: GREY_COLOR + function _getWH() { + let style = window.getComputedStyle(rootRef.value); + let rect = rootRef.value.getBoundingClientRect(); + width.value = rect.width - ["Left", "Right"].reduce(function(all, item) { + const LEFT = "border" + item + "Width"; + const RIGHT = "padding" + item; + return all + parseFloat(style[LEFT]) + parseFloat(style[RIGHT]); + }, 0); + height.value = rect.height - ["Top", "Bottom"].reduce(function(all, item) { + const TOP = "border" + item + "Width"; + const BOTTOM = "padding" + item; + return all + parseFloat(style[TOP]) + parseFloat(style[BOTTOM]); + }, 0); } -}; -var index$m = /* @__PURE__ */ defineBuiltInComponent({ - name: "Icon", - props: { - type: { - type: String, - required: true, - default: "" - }, - size: { - type: [String, Number], - default: 23 + provide("movableAreaWidth", width); + provide("movableAreaHeight", height); + return { + setContexts(contexts) { + movableViewContexts = contexts; }, - color: { - type: String, - default: "" + events: { + _onTouchstart, + _onTouchmove, + _onTouchend, + _resize } - }, - setup(props2) { - const path = computed(() => ICONS[props2.type]); - return () => { - const { - value - } = path; - return createVNode("uni-icon", null, [value && value.d && createSvgIconVNode(value.d, props2.color || value.c, rpx2px(props2.size))]); - }; - } -}); -const props$v = { - src: { - type: String, - default: "" - }, - mode: { - type: String, - default: "scaleToFill" - }, - lazyLoad: { - type: [Boolean, String], - default: false - }, - draggable: { - type: Boolean, - default: true - } -}; -const FIX_MODES = { - widthFix: ["width", "height"], - heightFix: ["height", "width"] -}; -const IMAGE_MODES = { - aspectFit: ["center center", "contain"], - aspectFill: ["center center", "cover"], - widthFix: [, "100% 100%"], - heightFix: [, "100% 100%"], - top: ["center top"], - bottom: ["center bottom"], - center: ["center center"], - left: ["left center"], - right: ["right center"], - "top left": ["left top"], - "top right": ["right top"], - "bottom left": ["left bottom"], - "bottom right": ["right bottom"] + }; +} +const addListenerToElement = function(element, type, callback, capture) { + element.addEventListener(type, ($event) => { + if (typeof callback === "function") { + if (callback($event) === false) { + if (typeof $event.cancelable !== "undefined" ? $event.cancelable : true) { + $event.preventDefault(); + } + $event.stopPropagation(); + } + } + }, { + passive: false + }); }; -var index$l = /* @__PURE__ */ defineBuiltInComponent({ - name: "Image", - props: props$v, - setup(props2, { - emit: emit2 - }) { - const rootRef = ref(null); - const state2 = useImageState(rootRef, props2); - const trigger = useCustomEvent(rootRef, emit2); - const { - fixSize - } = useImageSize(rootRef, props2, state2); - useImageLoader(state2, { - trigger, - fixSize - }); - return () => { - const { - mode: mode2 - } = props2; - const { - imgSrc, - modeStyle - } = state2; - return createVNode("uni-image", { - "ref": rootRef - }, [createVNode("div", { - "style": modeStyle - }, null, 4), imgSrc ? createVNode("img", { - "src": imgSrc, - "draggable": props2.draggable - }, null, 8, ["src", "draggable"]) : createVNode("img", null, null), FIX_MODES[mode2] ? createVNode(ResizeSensor, { - "onResize": fixSize - }, null, 8, ["onResize"]) : createVNode("span", null, null)], 512); - }; - } -}); -function useImageState(rootRef, props2) { - const imgSrc = ref(""); - const modeStyleRef = computed(() => { - let size = "auto"; - let position = ""; - const opts = IMAGE_MODES[props2.mode]; - if (!opts) { - position = "0% 0%"; - size = "100% 100%"; - } else { - opts[0] && (position = opts[0]); - opts[1] && (size = opts[1]); - } - const srcVal = imgSrc.value; - return `background-image:${srcVal ? 'url("' + srcVal + '")' : "none"};background-position:${position};background-size:${size};background-repeat:no-repeat;`; - }); - const state2 = reactive({ - rootEl: rootRef, - src: computed(() => props2.src ? getRealPath(props2.src) : ""), - origWidth: 0, - origHeight: 0, - origStyle: { - width: "", - height: "" - }, - modeStyle: modeStyleRef, - imgSrc - }); - onMounted(() => { - const rootEl = rootRef.value; - const style = rootEl.style; - state2.origWidth = Number(style.width) || 0; - state2.origHeight = Number(style.height) || 0; +let __mouseMoveEventListener; +let __mouseUpEventListener; +function useTouchtrack(element, method, useCancel) { + onBeforeUnmount(() => { + document.removeEventListener("mousemove", __mouseMoveEventListener); + document.removeEventListener("mouseup", __mouseUpEventListener); }); - return state2; -} -function useImageLoader(state2, { - trigger, - fixSize -}) { - let img; - const setState = (width = 0, height = 0, imgSrc = "") => { - state2.origWidth = width; - state2.origHeight = height; - state2.imgSrc = imgSrc; - }; - const loadImage = (src) => { - if (!src) { - resetImage(); - setState(); - return; - } - if (!img) { - img = new Image(); + let x0 = 0; + let y0 = 0; + let x1 = 0; + let y1 = 0; + const fn = function($event, state2, x, y) { + if (method({ + target: $event.target, + currentTarget: $event.currentTarget, + preventDefault: $event.preventDefault.bind($event), + stopPropagation: $event.stopPropagation.bind($event), + touches: $event.touches, + changedTouches: $event.changedTouches, + detail: { + state: state2, + x, + y, + dx: x - x0, + dy: y - y0, + ddx: x - x1, + ddy: y - y1, + timeStamp: $event.timeStamp + } + }) === false) { + return false; } - img.onload = (evt) => { - const { - width, - height - } = img; - setState(width, height, src); - fixSize(); - resetImage(); - trigger("load", evt, { - width, - height - }); - }; - img.onerror = (evt) => { - setState(); - resetImage(); - trigger("error", evt, { - errMsg: `GET ${state2.src} 404 (Not Found)` - }); - }; - img.src = src; }; - const resetImage = () => { - if (img) { - img.onload = null; - img.onerror = null; - img = null; + let $eventOld = null; + let hasTouchStart; + let hasMouseDown; + addListenerToElement(element, "touchstart", function($event) { + hasTouchStart = true; + if ($event.touches.length === 1 && !$eventOld) { + $eventOld = $event; + x0 = x1 = $event.touches[0].pageX; + y0 = y1 = $event.touches[0].pageY; + return fn($event, "start", x0, y0); } - }; - watch(() => state2.src, (value) => loadImage(value)); - onMounted(() => loadImage(state2.src)); - onBeforeUnmount(() => resetImage()); -} -const isChrome = navigator.vendor === "Google Inc."; -function fixNumber(num) { - if (isChrome && num > 10) { - num = Math.round(num / 2) * 2; - } - return num; -} -function useImageSize(rootRef, props2, state2) { - const fixSize = () => { - const { - mode: mode2 - } = props2; - const names = FIX_MODES[mode2]; - if (!names) { - return; + }); + addListenerToElement(element, "mousedown", function($event) { + hasMouseDown = true; + if (!hasTouchStart && !$eventOld) { + $eventOld = $event; + x0 = x1 = $event.pageX; + y0 = y1 = $event.pageY; + return fn($event, "start", x0, y0); } - const { - origWidth, - origHeight - } = state2; - const ratio = origWidth && origHeight ? origWidth / origHeight : 0; - if (!ratio) { - return; + }); + addListenerToElement(element, "touchmove", function($event) { + if ($event.touches.length === 1 && $eventOld) { + const res = fn($event, "move", $event.touches[0].pageX, $event.touches[0].pageY); + x1 = $event.touches[0].pageX; + y1 = $event.touches[0].pageY; + return res; } - const rootEl = rootRef.value; - const rect = rootEl.getBoundingClientRect(); - const value = rect[names[0]]; - if (value) { - rootEl.style[names[1]] = fixNumber(value / ratio) + "px"; + }); + const mouseMoveEventListener = __mouseMoveEventListener = function($event) { + if (!hasTouchStart && hasMouseDown && $eventOld) { + const res = fn($event, "move", $event.pageX, $event.pageY); + x1 = $event.pageX; + y1 = $event.pageY; + return res; } }; - const resetSize = () => { - const { - style - } = rootRef.value; - const { - origStyle: { - width, - height - } - } = state2; - style.width = width; - style.height = height; - }; - watch(() => props2.mode, (value, oldValue) => { - if (FIX_MODES[oldValue]) { - resetSize(); - } - if (FIX_MODES[value]) { - fixSize(); + document.addEventListener("mousemove", mouseMoveEventListener); + addListenerToElement(element, "touchend", function($event) { + if ($event.touches.length === 0 && $eventOld) { + hasTouchStart = false; + $eventOld = null; + return fn($event, "end", $event.changedTouches[0].pageX, $event.changedTouches[0].pageY); } }); - return { - fixSize, - resetSize + const mouseUpEventListener = __mouseUpEventListener = function($event) { + hasMouseDown = false; + if (!hasTouchStart && $eventOld) { + $eventOld = null; + return fn($event, "end", $event.pageX, $event.pageY); + } }; + document.addEventListener("mouseup", mouseUpEventListener); + addListenerToElement(element, "touchcancel", function($event) { + if ($eventOld) { + hasTouchStart = false; + const $eventTemp = $eventOld; + $eventOld = null; + return fn($event, useCancel ? "cancel" : "end", $eventTemp.touches[0].pageX, $eventTemp.touches[0].pageY); + } + }); } -const passiveOptions$1 = passive(true); -const states = []; -let userInteract = 0; -let inited; -function addInteractListener(vm) { - if (!inited) { - const eventNames = [ - "touchstart", - "touchmove", - "touchend", - "mousedown", - "mouseup" - ]; - eventNames.forEach((eventName) => { - document.addEventListener(eventName, function() { - states.forEach((vm2) => { - vm2.userAction = true; - userInteract++; - setTimeout(() => { - userInteract--; - if (!userInteract) { - vm2.userAction = false; - } - }, 0); - }); - }, passiveOptions$1); - }); - inited = true; - } - states.push(vm); +function e(e2, t2, n) { + return e2 > t2 - n && e2 < t2 + n; } -function removeInteractListener(vm) { - const index2 = states.indexOf(vm); - if (index2 >= 0) { - states.splice(index2, 1); - } +function t$1(t2, n) { + return e(t2, 0, n); } -function useUserAction() { - const state2 = reactive({ - userAction: false - }); - onMounted(() => { - addInteractListener(state2); - }); - onBeforeUnmount(() => { - removeInteractListener(state2); - }); +function Decline() { +} +Decline.prototype.x = function(e2) { + return Math.sqrt(e2); +}; +function Friction$1(e2, t2) { + this._m = e2; + this._f = 1e3 * t2; + this._startTime = 0; + this._v = 0; +} +Friction$1.prototype.setV = function(x, y) { + var n = Math.pow(Math.pow(x, 2) + Math.pow(y, 2), 0.5); + this._x_v = x; + this._y_v = y; + this._x_a = -this._f * this._x_v / n; + this._y_a = -this._f * this._y_v / n; + this._t = Math.abs(x / this._x_a) || Math.abs(y / this._y_a); + this._lastDt = null; + this._startTime = new Date().getTime(); +}; +Friction$1.prototype.setS = function(x, y) { + this._x_s = x; + this._y_s = y; +}; +Friction$1.prototype.s = function(t2) { + if (t2 === void 0) { + t2 = (new Date().getTime() - this._startTime) / 1e3; + } + if (t2 > this._t) { + t2 = this._t; + this._lastDt = t2; + } + var x = this._x_v * t2 + 0.5 * this._x_a * Math.pow(t2, 2) + this._x_s; + var y = this._y_v * t2 + 0.5 * this._y_a * Math.pow(t2, 2) + this._y_s; + if (this._x_a > 0 && x < this._endPositionX || this._x_a < 0 && x > this._endPositionX) { + x = this._endPositionX; + } + if (this._y_a > 0 && y < this._endPositionY || this._y_a < 0 && y > this._endPositionY) { + y = this._endPositionY; + } return { - state: state2 + x, + y }; -} -function useScopedAttrs() { - const state2 = reactive({ - attrs: {} - }); - onMounted(() => { - let instance2 = getCurrentInstance(); - while (instance2) { - const scopeId = instance2.type.__scopeId; - if (scopeId) { - state2.attrs[scopeId] = ""; - } - instance2 = instance2.__isPage ? null : instance2.parent; - } - }); +}; +Friction$1.prototype.ds = function(t2) { + if (t2 === void 0) { + t2 = (new Date().getTime() - this._startTime) / 1e3; + } + if (t2 > this._t) { + t2 = this._t; + } return { - state: state2 + dx: this._x_v + this._x_a * t2, + dy: this._y_v + this._y_a * t2 + }; +}; +Friction$1.prototype.delta = function() { + return { + x: -1.5 * Math.pow(this._x_v, 2) / this._x_a || 0, + y: -1.5 * Math.pow(this._y_v, 2) / this._y_a || 0 }; +}; +Friction$1.prototype.dt = function() { + return -this._x_v / this._x_a; +}; +Friction$1.prototype.done = function() { + var t2 = e(this.s().x, this._endPositionX) || e(this.s().y, this._endPositionY) || this._lastDt === this._t; + this._lastDt = null; + return t2; +}; +Friction$1.prototype.setEnd = function(x, y) { + this._endPositionX = x; + this._endPositionY = y; +}; +Friction$1.prototype.reconfigure = function(m, f2) { + this._m = m; + this._f = 1e3 * f2; +}; +function Spring$1(m, k, c) { + this._m = m; + this._k = k; + this._c = c; + this._solution = null; + this._endPosition = 0; + this._startTime = 0; } -function useFormField(nameKey, value) { - const uniForm = inject(uniFormKey, false); - if (!uniForm) { - return; +Spring$1.prototype._solve = function(e2, t2) { + var n = this._c; + var i = this._m; + var r = this._k; + var o2 = n * n - 4 * i * r; + if (o2 === 0) { + const a2 = -n / (2 * i); + const s = e2; + const l = t2 / (a2 * e2); + return { + x: function(e3) { + return (s + l * e3) * Math.pow(Math.E, a2 * e3); + }, + dx: function(e3) { + var t3 = Math.pow(Math.E, a2 * e3); + return a2 * (s + l * e3) * t3 + l * t3; + } + }; } - const instance2 = getCurrentInstance(); - const ctx = { - submit() { - const proxy = instance2.proxy; - return [ - proxy[nameKey], - typeof value === "string" ? proxy[value] : value.value - ]; - }, - reset() { - if (typeof value === "string") { - instance2.proxy[value] = ""; - } else { - value.value = ""; + if (o2 > 0) { + const c = (-n - Math.sqrt(o2)) / (2 * i); + const u = (-n + Math.sqrt(o2)) / (2 * i); + const d = (t2 - c * e2) / (u - c); + const h = e2 - d; + return { + x: function(e3) { + var t3; + var n2; + if (e3 === this._t) { + t3 = this._powER1T; + n2 = this._powER2T; + } + this._t = e3; + if (!t3) { + t3 = this._powER1T = Math.pow(Math.E, c * e3); + } + if (!n2) { + n2 = this._powER2T = Math.pow(Math.E, u * e3); + } + return h * t3 + d * n2; + }, + dx: function(e3) { + var t3; + var n2; + if (e3 === this._t) { + t3 = this._powER1T; + n2 = this._powER2T; + } + this._t = e3; + if (!t3) { + t3 = this._powER1T = Math.pow(Math.E, c * e3); + } + if (!n2) { + n2 = this._powER2T = Math.pow(Math.E, u * e3); + } + return h * c * t3 + d * u * n2; } + }; + } + var p2 = Math.sqrt(4 * i * r - n * n) / (2 * i); + var f2 = -n / 2 * i; + var v2 = e2; + var g2 = (t2 - f2 * e2) / p2; + return { + x: function(e3) { + return Math.pow(Math.E, f2 * e3) * (v2 * Math.cos(p2 * e3) + g2 * Math.sin(p2 * e3)); + }, + dx: function(e3) { + var t3 = Math.pow(Math.E, f2 * e3); + var n2 = Math.cos(p2 * e3); + var i2 = Math.sin(p2 * e3); + return t3 * (g2 * p2 * n2 - v2 * p2 * i2) + f2 * t3 * (g2 * i2 + v2 * n2); } }; - uniForm.addField(ctx); - onBeforeUnmount(() => { - uniForm.removeField(ctx); - }); -} -const pageIds = []; -const UniViewJSBridgeSubscribe = function() { - const pageId = getCurrentPageId(); - if (pageIds.includes(pageId)) - return; - pageIds.push(pageId); - UniViewJSBridge.subscribe(pageId + ".getSelectedTextRange", function({pageId: pageId2, callbackId}) { - const activeElement = document.activeElement; - if (!activeElement) - return; - const tagName = activeElement.tagName.toLowerCase(); - const tagNames = ["input", "textarea"]; - const data = {}; - if (tagNames.includes(tagName)) { - data.start = activeElement.selectionStart; - data.end = activeElement.selectionEnd; - } - UniViewJSBridge.publishHandler("onGetSelectedTextRange", { - callbackId, - data - }, pageId2); - }); }; -function getValueString(value) { - return value === null ? "" : String(value); -} -const props$u = /* @__PURE__ */ extend({}, { - name: { - type: String, - default: "" - }, - modelValue: { - type: [String, Number], - default: "" - }, - value: { - type: [String, Number], - default: "" - }, - disabled: { - type: [Boolean, String], - default: false - }, - autoFocus: { - type: [Boolean, String], - default: false - }, - focus: { - type: [Boolean, String], - default: false - }, - cursor: { - type: [Number, String], - default: -1 - }, - selectionStart: { +Spring$1.prototype.x = function(e2) { + if (e2 === void 0) { + e2 = (new Date().getTime() - this._startTime) / 1e3; + } + return this._solution ? this._endPosition + this._solution.x(e2) : 0; +}; +Spring$1.prototype.dx = function(e2) { + if (e2 === void 0) { + e2 = (new Date().getTime() - this._startTime) / 1e3; + } + return this._solution ? this._solution.dx(e2) : 0; +}; +Spring$1.prototype.setEnd = function(e2, n, i) { + if (!i) { + i = new Date().getTime(); + } + if (e2 !== this._endPosition || !t$1(n, 0.1)) { + n = n || 0; + var r = this._endPosition; + if (this._solution) { + if (t$1(n, 0.1)) { + n = this._solution.dx((i - this._startTime) / 1e3); + } + r = this._solution.x((i - this._startTime) / 1e3); + if (t$1(n, 0.1)) { + n = 0; + } + if (t$1(r, 0.1)) { + r = 0; + } + r += this._endPosition; + } + if (!(this._solution && t$1(r - e2, 0.1) && t$1(n, 0.1))) { + this._endPosition = e2; + this._solution = this._solve(r - this._endPosition, n); + this._startTime = i; + } + } +}; +Spring$1.prototype.snap = function(e2) { + this._startTime = new Date().getTime(); + this._endPosition = e2; + this._solution = { + x: function() { + return 0; + }, + dx: function() { + return 0; + } + }; +}; +Spring$1.prototype.done = function(n) { + if (!n) { + n = new Date().getTime(); + } + return e(this.x(), this._endPosition, 0.1) && t$1(this.dx(), 0.1); +}; +Spring$1.prototype.reconfigure = function(m, t2, c) { + this._m = m; + this._k = t2; + this._c = c; + if (!this.done()) { + this._solution = this._solve(this.x() - this._endPosition, this.dx()); + this._startTime = new Date().getTime(); + } +}; +Spring$1.prototype.springConstant = function() { + return this._k; +}; +Spring$1.prototype.damping = function() { + return this._c; +}; +Spring$1.prototype.configuration = function() { + function e2(e3, t3) { + e3.reconfigure(1, t3, e3.damping()); + } + function t2(e3, t3) { + e3.reconfigure(1, e3.springConstant(), t3); + } + return [ + { + label: "Spring Constant", + read: this.springConstant.bind(this), + write: e2.bind(this, this), + min: 100, + max: 1e3 + }, + { + label: "Damping", + read: this.damping.bind(this), + write: t2.bind(this, this), + min: 1, + max: 500 + } + ]; +}; +function STD(e2, t2, n) { + this._springX = new Spring$1(e2, t2, n); + this._springY = new Spring$1(e2, t2, n); + this._springScale = new Spring$1(e2, t2, n); + this._startTime = 0; +} +STD.prototype.setEnd = function(e2, t2, n, i) { + var r = new Date().getTime(); + this._springX.setEnd(e2, i, r); + this._springY.setEnd(t2, i, r); + this._springScale.setEnd(n, i, r); + this._startTime = r; +}; +STD.prototype.x = function() { + var e2 = (new Date().getTime() - this._startTime) / 1e3; + return { + x: this._springX.x(e2), + y: this._springY.x(e2), + scale: this._springScale.x(e2) + }; +}; +STD.prototype.done = function() { + var e2 = new Date().getTime(); + return this._springX.done(e2) && this._springY.done(e2) && this._springScale.done(e2); +}; +STD.prototype.reconfigure = function(e2, t2, n) { + this._springX.reconfigure(e2, t2, n); + this._springY.reconfigure(e2, t2, n); + this._springScale.reconfigure(e2, t2, n); +}; +const props$r = { + direction: { + type: String, + default: "none" + }, + inertia: { + type: [Boolean, String], + default: false + }, + outOfBounds: { + type: [Boolean, String], + default: false + }, + x: { type: [Number, String], - default: -1 + default: 0 }, - selectionEnd: { + y: { type: [Number, String], - default: -1 + default: 0 }, - type: { - type: String, - default: "text" + damping: { + type: [Number, String], + default: 20 }, - password: { + friction: { + type: [Number, String], + default: 2 + }, + disabled: { type: [Boolean, String], default: false }, - placeholder: { - type: String, - default: "" + scale: { + type: [Boolean, String], + default: false }, - placeholderStyle: { - type: String, - default: "" + scaleMin: { + type: [Number, String], + default: 0.5 }, - placeholderClass: { - type: String, - default: "" + scaleMax: { + type: [Number, String], + default: 10 }, - maxlength: { + scaleValue: { type: [Number, String], - default: 140 + default: 1 }, - confirmType: { - type: String, - default: "done" + animation: { + type: [Boolean, String], + default: true + } +}; +var MovableView = /* @__PURE__ */ defineBuiltInComponent({ + name: "MovableView", + props: props$r, + emits: ["change", "scale"], + setup(props2, { + slots, + emit: emit2 + }) { + const rootRef = ref(null); + const trigger = useCustomEvent(rootRef, emit2); + const { + setParent + } = useMovableViewState(props2, trigger, rootRef); + return () => { + return createVNode("uni-movable-view", { + "ref": rootRef + }, [createVNode(ResizeSensor, { + "onResize": setParent + }, null, 8, ["onResize"]), slots.default && slots.default()], 512); + }; + } +}); +let requesting = false; +function _requestAnimationFrame(e2) { + if (!requesting) { + requesting = true; + requestAnimationFrame(function() { + e2(); + requesting = false; + }); } -}, props$x); -const emit = [ - "input", - "focus", - "blur", - "update:value", - "update:modelValue", - "update:focus", - ...emit$1 -]; -function useBase(props2, rootRef, emit2) { - const fieldRef = ref(null); - const trigger = useCustomEvent(rootRef, emit2); - const selectionStart = computed(() => { - const selectionStart2 = Number(props2.selectionStart); - return isNaN(selectionStart2) ? -1 : selectionStart2; - }); - const selectionEnd = computed(() => { - const selectionEnd2 = Number(props2.selectionEnd); - return isNaN(selectionEnd2) ? -1 : selectionEnd2; - }); - const cursor = computed(() => { - const cursor2 = Number(props2.cursor); - return isNaN(cursor2) ? -1 : cursor2; - }); - const maxlength = computed(() => { - var maxlength2 = Number(props2.maxlength); - return isNaN(maxlength2) ? 140 : maxlength2; - }); - const value = getValueString(props2.modelValue) || getValueString(props2.value); - const state2 = reactive({ - value, - valueOrigin: value, - maxlength, - focus: props2.focus, - composing: false, - selectionStart, - selectionEnd, - cursor - }); - watch(() => state2.focus, (val) => emit2("update:focus", val)); - watch(() => state2.maxlength, (val) => state2.value = state2.value.slice(0, val)); - return { - fieldRef, - state: state2, - trigger - }; -} -function useValueSync(props2, state2, emit2, trigger) { - const valueChangeFn = debounce((val) => { - state2.value = getValueString(val); - }, 100); - watch(() => props2.modelValue, valueChangeFn); - watch(() => props2.value, valueChangeFn); - const triggerInputFn = throttle((event, detail) => { - emit2("update:modelValue", detail.value); - emit2("update:value", detail.value); - trigger("input", event, detail); - }, 100); - const triggerInput = (event, detail, force) => { - valueChangeFn.cancel(); - triggerInputFn(event, detail); - if (force) { - triggerInputFn.flush(); - } - }; - onBeforeMount(() => { - valueChangeFn.cancel(); - triggerInputFn.cancel(); - }); - return { - trigger, - triggerInput - }; } -function useAutoFocus(props2, fieldRef) { - useUserAction(); - const needFocus = computed(() => props2.autoFocus || props2.focus); - function focus() { - if (!needFocus.value) { - return; - } - const field = fieldRef.value; - if (!field || false) { - setTimeout(focus, 100); - return; - } - { - field.focus(); - } +function p(t2, n) { + if (t2 === n) { + return 0; } - function blur() { - const field = fieldRef.value; - if (field) { - field.blur(); - } + let i = t2.offsetLeft; + return t2.offsetParent ? i += p(t2.offsetParent, n) : 0; +} +function f(t2, n) { + if (t2 === n) { + return 0; } - watch(() => props2.focus, (value) => { - if (value) { - focus(); - } else { - blur(); - } - }); - onMounted(() => { - if (needFocus.value) { - nextTick(focus); - } - }); + let i = t2.offsetTop; + return t2.offsetParent ? i += f(t2.offsetParent, n) : 0; } -function useEvent(fieldRef, state2, trigger, triggerInput, beforeInput) { - function checkSelection() { - const field = fieldRef.value; - if (field && state2.focus && state2.selectionStart > -1 && state2.selectionEnd > -1) { - field.selectionStart = state2.selectionStart; - field.selectionEnd = state2.selectionEnd; +function v(a2, b) { + return +((1e3 * a2 - 1e3 * b) / 1e3).toFixed(1); +} +function g(friction, execute, endCallback) { + let record = { + id: 0, + cancelled: false + }; + let cancel = function(record2) { + if (record2 && record2.id) { + cancelAnimationFrame(record2.id); } - } - function checkCursor() { - const field = fieldRef.value; - if (field && state2.focus && state2.selectionStart < 0 && state2.selectionEnd < 0 && state2.cursor > -1) { - field.selectionEnd = field.selectionStart = state2.cursor; + if (record2) { + record2.cancelled = true; } - } - function initField() { - const field = fieldRef.value; - const onFocus = function(event) { - state2.focus = true; - trigger("focus", event, { - value: state2.value - }); - checkSelection(); - checkCursor(); - }; - const onInput = function(event, force) { - event.stopPropagation(); - if (typeof beforeInput === "function" && beforeInput(event, state2) === false) { - return; - } - state2.value = field.value; - if (!state2.composing) { - triggerInput(event, { - value: field.value, - cursor: field.selectionEnd - }, force); - } - }; - const onBlur = function(event) { - if (state2.composing) { - state2.composing = false; - onInput(event, true); + }; + function fn(record2, friction2, execute2, endCallback2) { + if (!record2 || !record2.cancelled) { + execute2(friction2); + let isDone = friction2.done(); + if (!isDone) { + if (!record2.cancelled) { + record2.id = requestAnimationFrame(fn.bind(null, record2, friction2, execute2, endCallback2)); + } } - state2.focus = false; - trigger("blur", event, { - value: state2.value, - cursor: event.target.selectionEnd - }); - }; - field.addEventListener("change", (event) => event.stopPropagation()); - field.addEventListener("focus", onFocus); - field.addEventListener("blur", onBlur); - field.addEventListener("input", onInput); - field.addEventListener("compositionstart", (event) => { - event.stopPropagation(); - state2.composing = true; - }); - field.addEventListener("compositionend", (event) => { - event.stopPropagation(); - if (state2.composing) { - state2.composing = false; - onInput(event); + if (isDone && endCallback2) { + endCallback2(friction2); } - }); + } } - watch([() => state2.selectionStart, () => state2.selectionEnd], checkSelection); - watch(() => state2.cursor, checkCursor); - watch(() => fieldRef.value, initField); -} -function useField(props2, rootRef, emit2, beforeInput) { - UniViewJSBridgeSubscribe(); - const {fieldRef, state: state2, trigger} = useBase(props2, rootRef, emit2); - const {triggerInput} = useValueSync(props2, state2, emit2, trigger); - useAutoFocus(props2, fieldRef); - useKeyboard$1(props2, fieldRef); - const {state: scopedAttrsState} = useScopedAttrs(); - useFormField("name", state2); - useEvent(fieldRef, state2, trigger, triggerInput, beforeInput); - const fixDisabledColor = String(navigator.vendor).indexOf("Apple") === 0 && CSS.supports("image-orientation:from-image"); + fn(record, friction, execute, endCallback); return { - fieldRef, - state: state2, - scopedAttrsState, - fixDisabledColor, - trigger + cancel: cancel.bind(null, record), + model: friction }; } -const props$t = /* @__PURE__ */ extend({}, props$u, { - placeholderClass: { - type: String, - default: "input-placeholder" +function _getPx(val) { + if (/\d+[ur]px$/i.test(val)) { + return uni.upx2px(parseFloat(val)); } -}); -var Input = /* @__PURE__ */ defineBuiltInComponent({ - name: "Input", - props: props$t, - emits: ["confirm", ...emit], - setup(props2, { - emit: emit2 - }) { - const INPUT_TYPES = ["text", "number", "idcard", "digit", "password"]; - const type = computed(() => { - let type2 = ""; - switch (props2.type) { - case "text": - if (props2.confirmType === "search") { - type2 = "search"; - } - break; - case "idcard": - type2 = "text"; - break; - case "digit": - type2 = "number"; - break; - default: - type2 = ~INPUT_TYPES.includes(props2.type) ? props2.type : "text"; - break; - } - return props2.password ? "password" : type2; - }); - const valid = ref(true); - const rootRef = ref(null); - const { - fieldRef, - state: state2, - scopedAttrsState, - fixDisabledColor, - trigger - } = useField(props2, rootRef, emit2, (event, state3) => { - const input = event.target; - if (NUMBER_TYPES.includes(props2.type)) { - valid.value = input.validity && input.validity.valid; - } - if (type.value === "number") { - const maxlength = state3.maxlength; - if (maxlength > 0 && input.value.length > maxlength) { - input.value = input.value.slice(0, maxlength); - state3.value = input.value; - return false; - } - } - }); - const NUMBER_TYPES = ["number", "digit"]; - const step = computed(() => NUMBER_TYPES.includes(props2.type) ? "0.000000000000000001" : ""); - function onKeyUpEnter(event) { - if (event.key !== "Enter") { - return; - } - event.stopPropagation(); - trigger("confirm", event, { - value: event.target.value - }); - } - return () => { - let inputNode = props2.disabled && fixDisabledColor ? createVNode("input", { - "ref": fieldRef, - "value": state2.value, - "tabindex": "-1", - "readonly": !!props2.disabled, - "type": type.value, - "maxlength": state2.maxlength, - "step": step.value, - "class": "uni-input-input", - "onFocus": (event) => event.target.blur() - }, null, 40, ["value", "readonly", "type", "maxlength", "step", "onFocus"]) : createVNode("input", { - "ref": fieldRef, - "value": state2.value, - "disabled": !!props2.disabled, - "type": type.value, - "maxlength": state2.maxlength, - "step": step.value, - "enterkeyhint": props2.confirmType, - "class": "uni-input-input", - "autocomplete": "off", - "onKeyup": onKeyUpEnter - }, null, 40, ["value", "disabled", "type", "maxlength", "step", "enterkeyhint", "onKeyup"]); - return createVNode("uni-input", { - "ref": rootRef - }, [createVNode("div", { - "class": "uni-input-wrapper" - }, [withDirectives(createVNode("div", mergeProps(scopedAttrsState.attrs, { - "style": props2.placeholderStyle, - "class": ["uni-input-placeholder", props2.placeholderClass] - }), [props2.placeholder], 16), [[vShow, !(state2.value.length || !valid.value)]]), props2.confirmType === "search" ? createVNode("form", { - "action": "", - "onSubmit": (event) => event.preventDefault(), - "class": "uni-input-form" - }, [inputNode], 40, ["onSubmit"]) : inputNode])], 512); - }; - } -}); -function entries(obj) { - return Object.keys(obj).map((key) => [key, obj[key]]); + return Number(val) || 0; } -const DEFAULT_EXCLUDE_KEYS = ["class", "style"]; -const LISTENER_PREFIX = /^on[A-Z]+/; -const useAttrs = (params = {}) => { - const {excludeListeners = false, excludeKeys = []} = params; - const instance2 = getCurrentInstance(); - const attrs2 = shallowRef({}); - const listeners = shallowRef({}); - const excludeAttrs = shallowRef({}); - const allExcludeKeys = excludeKeys.concat(DEFAULT_EXCLUDE_KEYS); - instance2.attrs = reactive(instance2.attrs); - watchEffect(() => { - const res = entries(instance2.attrs).reduce((acc, [key, val]) => { - if (allExcludeKeys.includes(key)) { - acc.exclude[key] = val; - } else if (LISTENER_PREFIX.test(key)) { - if (!excludeListeners) { - acc.attrs[key] = val; - } - acc.listeners[key] = val; - } else { - acc.attrs[key] = val; - } - return acc; - }, { - exclude: {}, - attrs: {}, - listeners: {} - }); - attrs2.value = res.attrs; - listeners.value = res.listeners; - excludeAttrs.value = res.exclude; +function useMovableViewState(props2, trigger, rootRef) { + const movableAreaWidth = inject("movableAreaWidth", ref(0)); + const movableAreaHeight = inject("movableAreaHeight", ref(0)); + const _isMounted = inject("_isMounted", ref(false)); + const movableAreaRootRef = inject("movableAreaRootRef"); + const addMovableViewContext = inject("addMovableViewContext", () => { }); - return {$attrs: attrs2, $listeners: listeners, $excludeAttrs: excludeAttrs}; -}; -function initScrollBounce() { -} -function disableScrollBounce({disable}) { -} -function flatVNode(nodes) { - const array = []; - if (Array.isArray(nodes)) { - nodes.forEach((vnode) => { - if (isVNode(vnode)) { - if (vnode.type === Fragment) { - array.push(...flatVNode(vnode.children)); - } else { - array.push(vnode); + const removeMovableViewContext = inject("removeMovableViewContext", () => { + }); + const xSync = ref(_getPx(props2.x)); + const ySync = ref(_getPx(props2.y)); + const scaleValueSync = ref(Number(props2.scaleValue) || 1); + const width = ref(0); + const height = ref(0); + const minX = ref(0); + const minY = ref(0); + const maxX = ref(0); + const maxY = ref(0); + let _SFA = null; + let _FA = null; + const _offset = { + x: 0, + y: 0 + }; + const _scaleOffset = { + x: 0, + y: 0 + }; + let _scale = 1; + let _oldScale = 1; + let _translateX = 0; + let _translateY = 0; + let _isScaling = false; + let _isTouching = false; + let __baseX; + let __baseY; + let _checkCanMove = null; + let _firstMoveDirection = null; + const _declineX = new Decline(); + const _declineY = new Decline(); + const __touchInfo = { + historyX: [0, 0], + historyY: [0, 0], + historyT: [0, 0] + }; + const dampingNumber = computed(() => { + let val = Number(props2.damping); + return isNaN(val) ? 20 : val; + }); + const frictionNumber = computed(() => { + let val = Number(props2.friction); + return isNaN(val) || val <= 0 ? 2 : val; + }); + const scaleMinNumber = computed(() => { + let val = Number(props2.scaleMin); + return isNaN(val) ? 0.5 : val; + }); + const scaleMaxNumber = computed(() => { + let val = Number(props2.scaleMax); + return isNaN(val) ? 10 : val; + }); + const xMove = computed(() => props2.direction === "all" || props2.direction === "horizontal"); + const yMove = computed(() => props2.direction === "all" || props2.direction === "vertical"); + const _STD = new STD(1, 9 * Math.pow(dampingNumber.value, 2) / 40, dampingNumber.value); + const _friction = new Friction$1(1, frictionNumber.value); + watch(() => props2.x, (val) => { + xSync.value = _getPx(val); + }); + watch(() => props2.y, (val) => { + ySync.value = _getPx(val); + }); + watch(xSync, (val) => { + _setX(val); + }); + watch(ySync, (val) => { + _setY(val); + }); + watch(() => props2.scaleValue, (val) => { + scaleValueSync.value = Number(val) || 0; + }); + watch(scaleValueSync, (val) => { + _setScaleValue(val); + }); + watch(scaleMinNumber, () => { + _setScaleMinOrMax(); + }); + watch(scaleMaxNumber, () => { + _setScaleMinOrMax(); + }); + function FAandSFACancel() { + if (_FA) { + _FA.cancel(); + } + if (_SFA) { + _SFA.cancel(); + } + } + function _setX(val) { + if (xMove.value) { + if (val + _scaleOffset.x === _translateX) { + return _translateX; + } else { + if (_SFA) { + _SFA.cancel(); } - } else if (Array.isArray(vnode)) { - array.push(...flatVNode(vnode)); + _animationTo(val + _scaleOffset.x, ySync.value + _scaleOffset.y, _scale); } - }); - } - return array; -} -const props$s = { - scaleArea: { - type: Boolean, - default: false + } + return val; } -}; -var MovableArea = /* @__PURE__ */ defineBuiltInComponent({ - inheritAttrs: false, - name: "MovableArea", - props: props$s, - setup(props2, { - slots - }) { - const rootRef = ref(null); - const _isMounted = ref(false); - let { - setContexts, - events: movableAreaEvents - } = useMovableAreaState(props2, rootRef); - const { - $listeners, - $attrs, - $excludeAttrs - } = useAttrs(); - const _listeners = $listeners.value; - let events = ["onTouchstart", "onTouchmove", "onTouchend"]; - events.forEach((event) => { - let existing = _listeners[event]; - let ours = movableAreaEvents[`_${event}`]; - _listeners[event] = existing ? [].concat(existing, ours) : ours; - }); - onMounted(() => { - movableAreaEvents._resize(); - _isMounted.value = true; - }); - let movableViewItems = []; - const originMovableViewContexts = []; - function updateMovableViewContexts() { - const contexts = []; - for (let index2 = 0; index2 < movableViewItems.length; index2++) { - const movableViewItem = movableViewItems[index2]; - const movableViewContext = originMovableViewContexts.find((context) => movableViewItem.el === context.rootRef.value); - if (movableViewContext) { - contexts.push(markRaw(movableViewContext)); + function _setY(val) { + if (yMove.value) { + if (val + _scaleOffset.y === _translateY) { + return _translateY; + } else { + if (_SFA) { + _SFA.cancel(); } + _animationTo(xSync.value + _scaleOffset.x, val + _scaleOffset.y, _scale); } - setContexts(contexts); } - const addMovableViewContext = (movableViewContext) => { - originMovableViewContexts.push(movableViewContext); - updateMovableViewContexts(); - }; - const removeMovableViewContext = (movableViewContext) => { - const index2 = originMovableViewContexts.indexOf(movableViewContext); - if (index2 >= 0) { - originMovableViewContexts.splice(index2, 1); - updateMovableViewContexts(); - } - }; - provide("_isMounted", _isMounted); - provide("movableAreaRootRef", rootRef); - provide("addMovableViewContext", addMovableViewContext); - provide("removeMovableViewContext", removeMovableViewContext); - return () => { - const defaultSlots = slots.default && slots.default(); - movableViewItems = flatVNode(defaultSlots); - return createVNode("uni-movable-area", mergeProps({ - "ref": rootRef - }, $attrs.value, $excludeAttrs.value, _listeners), [createVNode(ResizeSensor, { - "onReize": movableAreaEvents._resize - }, null, 8, ["onReize"]), movableViewItems], 16); - }; + return val; } -}); -function calc(e2) { - return Math.sqrt(e2.x * e2.x + e2.y * e2.y); -} -function useMovableAreaState(props2, rootRef) { - const width = ref(0); - const height = ref(0); - const gapV = reactive({ - x: null, - y: null - }); - const pinchStartLen = ref(null); - let _scaleMovableView = null; - let movableViewContexts = []; - function _updateScale(e2) { - if (e2 && e2 !== 1) { - if (props2.scaleArea) { - movableViewContexts.forEach(function(item) { - item._setScale(e2); - }); - } else { - if (_scaleMovableView) { - _scaleMovableView._setScale(e2); - } - } + function _setScaleMinOrMax() { + if (!props2.scale) { + return false; } + _updateScale(_scale, true); + _updateOldScale(_scale); } - function _find(target, items = movableViewContexts) { - let root = rootRef.value; - function get(node) { - for (let i = 0; i < items.length; i++) { - const item = items[i]; - if (node === item.rootRef.value) { - return item; + function _setScaleValue(scale) { + if (!props2.scale) { + return false; + } + scale = _adjustScale(scale); + _updateScale(scale, true); + _updateOldScale(scale); + return scale; + } + function __handleTouchStart() { + if (!_isScaling) { + if (!props2.disabled) { + FAandSFACancel(); + __touchInfo.historyX = [0, 0]; + __touchInfo.historyY = [0, 0]; + __touchInfo.historyT = [0, 0]; + if (xMove.value) { + __baseX = _translateX; } + if (yMove.value) { + __baseY = _translateY; + } + rootRef.value.style.willChange = "transform"; + _checkCanMove = null; + _firstMoveDirection = null; + _isTouching = true; } - if (node === root || node === document.body || node === document) { - return null; - } - return get(node.parentNode); } - return get(target); } - const _onTouchstart = withWebEvent((t2) => { - let i = t2.touches; - if (i) { - if (i.length > 1) { - let r = { - x: i[1].pageX - i[0].pageX, - y: i[1].pageY - i[0].pageY - }; - pinchStartLen.value = calc(r); - gapV.x = r.x; - gapV.y = r.y; - if (!props2.scaleArea) { - let touch0 = _find(i[0].target); - let touch1 = _find(i[1].target); - _scaleMovableView = touch0 && touch0 === touch1 ? touch0 : null; + function __handleTouchMove(event) { + if (!_isScaling && !props2.disabled && _isTouching) { + let x = _translateX; + let y = _translateY; + if (_firstMoveDirection === null) { + _firstMoveDirection = Math.abs(event.detail.dx / event.detail.dy) > 1 ? "htouchmove" : "vtouchmove"; + } + if (xMove.value) { + x = event.detail.dx + __baseX; + __touchInfo.historyX.shift(); + __touchInfo.historyX.push(x); + if (!yMove.value && _checkCanMove === null) { + _checkCanMove = Math.abs(event.detail.dx / event.detail.dy) < 1; } } - } - }); - const _onTouchmove = withWebEvent((t2) => { - let n = t2.touches; - if (n) { - if (n.length > 1) { - t2.preventDefault(); - let i = { - x: n[1].pageX - n[0].pageX, - y: n[1].pageY - n[0].pageY - }; - if (gapV.x !== null && pinchStartLen.value && pinchStartLen.value > 0) { - let r = calc(i) / pinchStartLen.value; - _updateScale(r); + if (yMove.value) { + y = event.detail.dy + __baseY; + __touchInfo.historyY.shift(); + __touchInfo.historyY.push(y); + if (!xMove.value && _checkCanMove === null) { + _checkCanMove = Math.abs(event.detail.dy / event.detail.dx) < 1; } - gapV.x = i.x; - gapV.y = i.y; } - } - }); - const _onTouchend = withWebEvent((e2) => { - let t2 = e2.touches; - if (!(t2 && t2.length)) { - if (e2.changedTouches) { - gapV.x = 0; - gapV.y = 0; - pinchStartLen.value = null; - if (props2.scaleArea) { - movableViewContexts.forEach(function(item) { - item._endScale(); - }); + __touchInfo.historyT.shift(); + __touchInfo.historyT.push(event.detail.timeStamp); + if (!_checkCanMove) { + event.preventDefault(); + let source = "touch"; + if (x < minX.value) { + if (props2.outOfBounds) { + source = "touch-out-of-bounds"; + x = minX.value - _declineX.x(minX.value - x); + } else { + x = minX.value; + } + } else if (x > maxX.value) { + if (props2.outOfBounds) { + source = "touch-out-of-bounds"; + x = maxX.value + _declineX.x(x - maxX.value); + } else { + x = maxX.value; + } + } + if (y < minY.value) { + if (props2.outOfBounds) { + source = "touch-out-of-bounds"; + y = minY.value - _declineY.x(minY.value - y); + } else { + y = minY.value; + } } else { - if (_scaleMovableView) { - _scaleMovableView._endScale(); + if (y > maxY.value) { + if (props2.outOfBounds) { + source = "touch-out-of-bounds"; + y = maxY.value + _declineY.x(y - maxY.value); + } else { + y = maxY.value; + } } } + _requestAnimationFrame(function() { + _setTransform(x, y, _scale, source); + }); } } - }); - function _resize() { - _getWH(); - movableViewContexts.forEach(function(item, index2) { - item.setParent(); - }); - } - function _getWH() { - let style = window.getComputedStyle(rootRef.value); - let rect = rootRef.value.getBoundingClientRect(); - width.value = rect.width - ["Left", "Right"].reduce(function(all, item) { - const LEFT = "border" + item + "Width"; - const RIGHT = "padding" + item; - return all + parseFloat(style[LEFT]) + parseFloat(style[RIGHT]); - }, 0); - height.value = rect.height - ["Top", "Bottom"].reduce(function(all, item) { - const TOP = "border" + item + "Width"; - const BOTTOM = "padding" + item; - return all + parseFloat(style[TOP]) + parseFloat(style[BOTTOM]); - }, 0); } - provide("movableAreaWidth", width); - provide("movableAreaHeight", height); - return { - setContexts(contexts) { - movableViewContexts = contexts; - }, - events: { - _onTouchstart, - _onTouchmove, - _onTouchend, - _resize - } - }; -} -const addListenerToElement = function(element, type, callback, capture) { - element.addEventListener(type, ($event) => { - if (typeof callback === "function") { - if (callback($event) === false) { - if (typeof $event.cancelable !== "undefined" ? $event.cancelable : true) { - $event.preventDefault(); + function __handleTouchEnd() { + if (!_isScaling && !props2.disabled && _isTouching) { + rootRef.value.style.willChange = "auto"; + _isTouching = false; + if (!_checkCanMove && !_revise("out-of-bounds") && props2.inertia) { + const xv = 1e3 * (__touchInfo.historyX[1] - __touchInfo.historyX[0]) / (__touchInfo.historyT[1] - __touchInfo.historyT[0]); + const yv = 1e3 * (__touchInfo.historyY[1] - __touchInfo.historyY[0]) / (__touchInfo.historyT[1] - __touchInfo.historyT[0]); + _friction.setV(xv, yv); + _friction.setS(_translateX, _translateY); + const x0 = _friction.delta().x; + const y0 = _friction.delta().y; + let x = x0 + _translateX; + let y = y0 + _translateY; + if (x < minX.value) { + x = minX.value; + y = _translateY + (minX.value - _translateX) * y0 / x0; + } else { + if (x > maxX.value) { + x = maxX.value; + y = _translateY + (maxX.value - _translateX) * y0 / x0; + } } - $event.stopPropagation(); - } - } - }, { - passive: false - }); -}; -let __mouseMoveEventListener; -let __mouseUpEventListener; -function useTouchtrack(element, method, useCancel) { - onBeforeUnmount(() => { - document.removeEventListener("mousemove", __mouseMoveEventListener); - document.removeEventListener("mouseup", __mouseUpEventListener); - }); - let x0 = 0; - let y0 = 0; - let x1 = 0; - let y1 = 0; - const fn = function($event, state2, x, y) { - if (method({ - target: $event.target, - currentTarget: $event.currentTarget, - preventDefault: $event.preventDefault.bind($event), - stopPropagation: $event.stopPropagation.bind($event), - touches: $event.touches, - changedTouches: $event.changedTouches, - detail: { - state: state2, - x, - y, - dx: x - x0, - dy: y - y0, - ddx: x - x1, - ddy: y - y1, - timeStamp: $event.timeStamp + if (y < minY.value) { + y = minY.value; + x = _translateX + (minY.value - _translateY) * x0 / y0; + } else { + if (y > maxY.value) { + y = maxY.value; + x = _translateX + (maxY.value - _translateY) * x0 / y0; + } + } + _friction.setEnd(x, y); + _FA = g(_friction, function() { + let t2 = _friction.s(); + let x2 = t2.x; + let y2 = t2.y; + _setTransform(x2, y2, _scale, "friction"); + }, function() { + _FA.cancel(); + }); } - }) === false) { - return false; - } - }; - let $eventOld = null; - let hasTouchStart; - let hasMouseDown; - addListenerToElement(element, "touchstart", function($event) { - hasTouchStart = true; - if ($event.touches.length === 1 && !$eventOld) { - $eventOld = $event; - x0 = x1 = $event.touches[0].pageX; - y0 = y1 = $event.touches[0].pageY; - return fn($event, "start", x0, y0); - } - }); - addListenerToElement(element, "mousedown", function($event) { - hasMouseDown = true; - if (!hasTouchStart && !$eventOld) { - $eventOld = $event; - x0 = x1 = $event.pageX; - y0 = y1 = $event.pageY; - return fn($event, "start", x0, y0); - } - }); - addListenerToElement(element, "touchmove", function($event) { - if ($event.touches.length === 1 && $eventOld) { - const res = fn($event, "move", $event.touches[0].pageX, $event.touches[0].pageY); - x1 = $event.touches[0].pageX; - y1 = $event.touches[0].pageY; - return res; - } - }); - const mouseMoveEventListener = __mouseMoveEventListener = function($event) { - if (!hasTouchStart && hasMouseDown && $eventOld) { - const res = fn($event, "move", $event.pageX, $event.pageY); - x1 = $event.pageX; - y1 = $event.pageY; - return res; } - }; - document.addEventListener("mousemove", mouseMoveEventListener); - addListenerToElement(element, "touchend", function($event) { - if ($event.touches.length === 0 && $eventOld) { - hasTouchStart = false; - $eventOld = null; - return fn($event, "end", $event.changedTouches[0].pageX, $event.changedTouches[0].pageY); + if (!props2.outOfBounds && !props2.inertia) { + FAandSFACancel(); } - }); - const mouseUpEventListener = __mouseUpEventListener = function($event) { - hasMouseDown = false; - if (!hasTouchStart && $eventOld) { - $eventOld = null; - return fn($event, "end", $event.pageX, $event.pageY); + } + function _getLimitXY(x, y) { + let outOfBounds = false; + if (x > maxX.value) { + x = maxX.value; + outOfBounds = true; + } else { + if (x < minX.value) { + x = minX.value; + outOfBounds = true; + } } - }; - document.addEventListener("mouseup", mouseUpEventListener); - addListenerToElement(element, "touchcancel", function($event) { - if ($eventOld) { - hasTouchStart = false; - const $eventTemp = $eventOld; - $eventOld = null; - return fn($event, useCancel ? "cancel" : "end", $eventTemp.touches[0].pageX, $eventTemp.touches[0].pageY); + if (y > maxY.value) { + y = maxY.value; + outOfBounds = true; + } else { + if (y < minY.value) { + y = minY.value; + outOfBounds = true; + } } - }); -} -function e(e2, t2, n) { - return e2 > t2 - n && e2 < t2 + n; -} -function t$1(t2, n) { - return e(t2, 0, n); -} -function Decline() { -} -Decline.prototype.x = function(e2) { - return Math.sqrt(e2); -}; -function Friction$1(e2, t2) { - this._m = e2; - this._f = 1e3 * t2; - this._startTime = 0; - this._v = 0; -} -Friction$1.prototype.setV = function(x, y) { - var n = Math.pow(Math.pow(x, 2) + Math.pow(y, 2), 0.5); - this._x_v = x; - this._y_v = y; - this._x_a = -this._f * this._x_v / n; - this._y_a = -this._f * this._y_v / n; - this._t = Math.abs(x / this._x_a) || Math.abs(y / this._y_a); - this._lastDt = null; - this._startTime = new Date().getTime(); -}; -Friction$1.prototype.setS = function(x, y) { - this._x_s = x; - this._y_s = y; -}; -Friction$1.prototype.s = function(t2) { - if (t2 === void 0) { - t2 = (new Date().getTime() - this._startTime) / 1e3; + return { + x, + y, + outOfBounds + }; } - if (t2 > this._t) { - t2 = this._t; - this._lastDt = t2; + function _updateOffset() { + _offset.x = p(rootRef.value, movableAreaRootRef.value); + _offset.y = f(rootRef.value, movableAreaRootRef.value); } - var x = this._x_v * t2 + 0.5 * this._x_a * Math.pow(t2, 2) + this._x_s; - var y = this._y_v * t2 + 0.5 * this._y_a * Math.pow(t2, 2) + this._y_s; - if (this._x_a > 0 && x < this._endPositionX || this._x_a < 0 && x > this._endPositionX) { - x = this._endPositionX; + function _updateWH(scale) { + scale = scale || _scale; + scale = _adjustScale(scale); + let rect = rootRef.value.getBoundingClientRect(); + height.value = rect.height / _scale; + width.value = rect.width / _scale; + let _height = height.value * scale; + let _width = width.value * scale; + _scaleOffset.x = (_width - width.value) / 2; + _scaleOffset.y = (_height - height.value) / 2; } - if (this._y_a > 0 && y < this._endPositionY || this._y_a < 0 && y > this._endPositionY) { - y = this._endPositionY; + function _updateBoundary() { + let x = 0 - _offset.x + _scaleOffset.x; + let _width = movableAreaWidth.value - width.value - _offset.x - _scaleOffset.x; + minX.value = Math.min(x, _width); + maxX.value = Math.max(x, _width); + let y = 0 - _offset.y + _scaleOffset.y; + let _height = movableAreaHeight.value - height.value - _offset.y - _scaleOffset.y; + minY.value = Math.min(y, _height); + maxY.value = Math.max(y, _height); } - return { - x, - y - }; -}; -Friction$1.prototype.ds = function(t2) { - if (t2 === void 0) { - t2 = (new Date().getTime() - this._startTime) / 1e3; + function _beginScale() { + _isScaling = true; } - if (t2 > this._t) { - t2 = this._t; + function _updateScale(scale, animat) { + if (props2.scale) { + scale = _adjustScale(scale); + _updateWH(scale); + _updateBoundary(); + const limitXY = _getLimitXY(_translateX, _translateY); + const x = limitXY.x; + const y = limitXY.y; + if (animat) { + _animationTo(x, y, scale, "", true, true); + } else { + _requestAnimationFrame(function() { + _setTransform(x, y, scale, "", true, true); + }); + } + } } - return { - dx: this._x_v + this._x_a * t2, - dy: this._y_v + this._y_a * t2 - }; -}; -Friction$1.prototype.delta = function() { - return { - x: -1.5 * Math.pow(this._x_v, 2) / this._x_a || 0, - y: -1.5 * Math.pow(this._y_v, 2) / this._y_a || 0 - }; -}; -Friction$1.prototype.dt = function() { - return -this._x_v / this._x_a; -}; -Friction$1.prototype.done = function() { - var t2 = e(this.s().x, this._endPositionX) || e(this.s().y, this._endPositionY) || this._lastDt === this._t; - this._lastDt = null; - return t2; -}; -Friction$1.prototype.setEnd = function(x, y) { - this._endPositionX = x; - this._endPositionY = y; -}; -Friction$1.prototype.reconfigure = function(m, f2) { - this._m = m; - this._f = 1e3 * f2; -}; -function Spring$1(m, k, c) { - this._m = m; - this._k = k; - this._c = c; - this._solution = null; - this._endPosition = 0; - this._startTime = 0; -} -Spring$1.prototype._solve = function(e2, t2) { - var n = this._c; - var i = this._m; - var r = this._k; - var o2 = n * n - 4 * i * r; - if (o2 === 0) { - const a2 = -n / (2 * i); - const s = e2; - const l = t2 / (a2 * e2); - return { - x: function(e3) { - return (s + l * e3) * Math.pow(Math.E, a2 * e3); - }, - dx: function(e3) { - var t3 = Math.pow(Math.E, a2 * e3); - return a2 * (s + l * e3) * t3 + l * t3; - } - }; + function _updateOldScale(scale) { + _oldScale = scale; } - if (o2 > 0) { - const c = (-n - Math.sqrt(o2)) / (2 * i); - const u = (-n + Math.sqrt(o2)) / (2 * i); - const d = (t2 - c * e2) / (u - c); - const h = e2 - d; - return { - x: function(e3) { - var t3; - var n2; - if (e3 === this._t) { - t3 = this._powER1T; - n2 = this._powER2T; - } - this._t = e3; - if (!t3) { - t3 = this._powER1T = Math.pow(Math.E, c * e3); - } - if (!n2) { - n2 = this._powER2T = Math.pow(Math.E, u * e3); - } - return h * t3 + d * n2; - }, - dx: function(e3) { - var t3; - var n2; - if (e3 === this._t) { - t3 = this._powER1T; - n2 = this._powER2T; - } - this._t = e3; - if (!t3) { - t3 = this._powER1T = Math.pow(Math.E, c * e3); - } - if (!n2) { - n2 = this._powER2T = Math.pow(Math.E, u * e3); - } - return h * c * t3 + d * u * n2; - } - }; + function _adjustScale(scale) { + scale = Math.max(0.5, scaleMinNumber.value, scale); + scale = Math.min(10, scaleMaxNumber.value, scale); + return scale; } - var p2 = Math.sqrt(4 * i * r - n * n) / (2 * i); - var f2 = -n / 2 * i; - var v2 = e2; - var g2 = (t2 - f2 * e2) / p2; - return { - x: function(e3) { - return Math.pow(Math.E, f2 * e3) * (v2 * Math.cos(p2 * e3) + g2 * Math.sin(p2 * e3)); - }, - dx: function(e3) { - var t3 = Math.pow(Math.E, f2 * e3); - var n2 = Math.cos(p2 * e3); - var i2 = Math.sin(p2 * e3); - return t3 * (g2 * p2 * n2 - v2 * p2 * i2) + f2 * t3 * (g2 * i2 + v2 * n2); + function _animationTo(x, y, scale, source, r, o2) { + FAandSFACancel(); + if (!xMove.value) { + x = _translateX; } - }; -}; -Spring$1.prototype.x = function(e2) { - if (e2 === void 0) { - e2 = (new Date().getTime() - this._startTime) / 1e3; - } - return this._solution ? this._endPosition + this._solution.x(e2) : 0; -}; -Spring$1.prototype.dx = function(e2) { - if (e2 === void 0) { - e2 = (new Date().getTime() - this._startTime) / 1e3; + if (!yMove.value) { + y = _translateY; + } + if (!props2.scale) { + scale = _scale; + } + let limitXY = _getLimitXY(x, y); + x = limitXY.x; + y = limitXY.y; + if (!props2.animation) { + _setTransform(x, y, scale, source, r, o2); + return; + } + _STD._springX._solution = null; + _STD._springY._solution = null; + _STD._springScale._solution = null; + _STD._springX._endPosition = _translateX; + _STD._springY._endPosition = _translateY; + _STD._springScale._endPosition = _scale; + _STD.setEnd(x, y, scale, 1); + _SFA = g(_STD, function() { + let data = _STD.x(); + let x2 = data.x; + let y2 = data.y; + let scale2 = data.scale; + _setTransform(x2, y2, scale2, source, r, o2); + }, function() { + _SFA.cancel(); + }); } - return this._solution ? this._solution.dx(e2) : 0; -}; -Spring$1.prototype.setEnd = function(e2, n, i) { - if (!i) { - i = new Date().getTime(); + function _revise(source) { + let limitXY = _getLimitXY(_translateX, _translateY); + let x = limitXY.x; + let y = limitXY.y; + let outOfBounds = limitXY.outOfBounds; + if (outOfBounds) { + _animationTo(x, y, _scale, source); + } + return outOfBounds; } - if (e2 !== this._endPosition || !t$1(n, 0.1)) { - n = n || 0; - var r = this._endPosition; - if (this._solution) { - if (t$1(n, 0.1)) { - n = this._solution.dx((i - this._startTime) / 1e3); - } - r = this._solution.x((i - this._startTime) / 1e3); - if (t$1(n, 0.1)) { - n = 0; - } - if (t$1(r, 0.1)) { - r = 0; + function _setTransform(x, y, scale, source = "", r, o2) { + if (!(x !== null && x.toString() !== "NaN" && typeof x === "number")) { + x = _translateX || 0; + } + if (!(y !== null && y.toString() !== "NaN" && typeof y === "number")) { + y = _translateY || 0; + } + x = Number(x.toFixed(1)); + y = Number(y.toFixed(1)); + scale = Number(scale.toFixed(1)); + if (!(_translateX === x && _translateY === y)) { + if (!r) { + trigger("change", {}, { + x: v(x, _scaleOffset.x), + y: v(y, _scaleOffset.y), + source + }); } - r += this._endPosition; } - if (!(this._solution && t$1(r - e2, 0.1) && t$1(n, 0.1))) { - this._endPosition = e2; - this._solution = this._solve(r - this._endPosition, n); - this._startTime = i; + if (!props2.scale) { + scale = _scale; } - } -}; -Spring$1.prototype.snap = function(e2) { - this._startTime = new Date().getTime(); - this._endPosition = e2; - this._solution = { - x: function() { - return 0; - }, - dx: function() { - return 0; + scale = _adjustScale(scale); + scale = +scale.toFixed(3); + if (o2 && scale !== _scale) { + trigger("scale", {}, { + x, + y, + scale + }); } - }; -}; -Spring$1.prototype.done = function(n) { - if (!n) { - n = new Date().getTime(); + let transform = "translateX(" + x + "px) translateY(" + y + "px) translateZ(0px) scale(" + scale + ")"; + rootRef.value.style.transform = transform; + rootRef.value.style.webkitTransform = transform; + _translateX = x; + _translateY = y; + _scale = scale; } - return e(this.x(), this._endPosition, 0.1) && t$1(this.dx(), 0.1); -}; -Spring$1.prototype.reconfigure = function(m, t2, c) { - this._m = m; - this._k = t2; - this._c = c; - if (!this.done()) { - this._solution = this._solve(this.x() - this._endPosition, this.dx()); - this._startTime = new Date().getTime(); + function setParent() { + if (!_isMounted.value) { + return; + } + FAandSFACancel(); + let scale = props2.scale ? scaleValueSync.value : 1; + _updateOffset(); + _updateWH(scale); + _updateBoundary(); + _translateX = xSync.value + _scaleOffset.x; + _translateY = ySync.value + _scaleOffset.y; + let limitXY = _getLimitXY(_translateX, _translateY); + let x = limitXY.x; + let y = limitXY.y; + _setTransform(x, y, scale, "", true); + _updateOldScale(scale); } -}; -Spring$1.prototype.springConstant = function() { - return this._k; -}; -Spring$1.prototype.damping = function() { - return this._c; -}; -Spring$1.prototype.configuration = function() { - function e2(e3, t3) { - e3.reconfigure(1, t3, e3.damping()); + function _endScale() { + _isScaling = false; + _updateOldScale(_scale); } - function t2(e3, t3) { - e3.reconfigure(1, e3.springConstant(), t3); + function _setScale(scale) { + if (scale) { + scale = _oldScale * scale; + _beginScale(); + _updateScale(scale); + } } - return [ - { - label: "Spring Constant", - read: this.springConstant.bind(this), - write: e2.bind(this, this), - min: 100, - max: 1e3 - }, - { - label: "Damping", - read: this.damping.bind(this), - write: t2.bind(this, this), - min: 1, - max: 500 - } - ]; -}; -function STD(e2, t2, n) { - this._springX = new Spring$1(e2, t2, n); - this._springY = new Spring$1(e2, t2, n); - this._springScale = new Spring$1(e2, t2, n); - this._startTime = 0; -} -STD.prototype.setEnd = function(e2, t2, n, i) { - var r = new Date().getTime(); - this._springX.setEnd(e2, i, r); - this._springY.setEnd(t2, i, r); - this._springScale.setEnd(n, i, r); - this._startTime = r; -}; -STD.prototype.x = function() { - var e2 = (new Date().getTime() - this._startTime) / 1e3; + onMounted(() => { + useTouchtrack(rootRef.value, (event) => { + switch (event.detail.state) { + case "start": + __handleTouchStart(); + break; + case "move": + __handleTouchMove(event); + break; + case "end": + __handleTouchEnd(); + } + }); + setParent(); + _friction.reconfigure(1, frictionNumber.value); + _STD.reconfigure(1, 9 * Math.pow(dampingNumber.value, 2) / 40, dampingNumber.value); + rootRef.value.style.transformOrigin = "center"; + const context = { + rootRef, + setParent, + _endScale, + _setScale + }; + addMovableViewContext(context); + onUnmounted(() => { + removeMovableViewContext(context); + }); + }); + onUnmounted(() => { + FAandSFACancel(); + }); return { - x: this._springX.x(e2), - y: this._springY.x(e2), - scale: this._springScale.x(e2) + setParent }; -}; -STD.prototype.done = function() { - var e2 = new Date().getTime(); - return this._springX.done(e2) && this._springY.done(e2) && this._springScale.done(e2); -}; -STD.prototype.reconfigure = function(e2, t2, n) { - this._springX.reconfigure(e2, t2, n); - this._springY.reconfigure(e2, t2, n); - this._springScale.reconfigure(e2, t2, n); -}; -const props$r = { - direction: { +} +const OPEN_TYPES = ["navigate", "redirect", "switchTab", "reLaunch", "navigateBack"]; +const props$q = { + hoverClass: { type: String, - default: "none" + default: "navigator-hover" }, - inertia: { - type: [Boolean, String], - default: false + url: { + type: String, + default: "" }, - outOfBounds: { - type: [Boolean, String], - default: false + openType: { + type: String, + default: "navigate", + validator(value) { + return Boolean(~OPEN_TYPES.indexOf(value)); + } }, - x: { - type: [Number, String], - default: 0 + delta: { + type: Number, + default: 1 }, - y: { + hoverStartTime: { type: [Number, String], - default: 0 + default: 50 }, - damping: { + hoverStayTime: { type: [Number, String], - default: 20 + default: 600 }, - friction: { - type: [Number, String], - default: 2 + exists: { + type: String, + default: "" }, - disabled: { - type: [Boolean, String], + hoverStopPropagation: { + type: Boolean, default: false + } +}; +var index$k = /* @__PURE__ */ defineBuiltInComponent({ + name: "Navigator", + compatConfig: { + MODE: 3 }, - scale: { - type: [Boolean, String], - default: false + props: props$q, + setup(props2, { + slots + }) { + const { + hovering, + binding + } = useHover(props2); + function onClick($event) { + if (props2.openType !== "navigateBack" && !props2.url) { + console.error(" should have url attribute when using navigateTo, redirectTo, reLaunch or switchTab"); + return; + } + switch (props2.openType) { + case "navigate": + uni.navigateTo({ + url: props2.url + }); + break; + case "redirect": + uni.redirectTo({ + url: props2.url, + exists: props2.exists + }); + break; + case "switchTab": + uni.switchTab({ + url: props2.url + }); + break; + case "reLaunch": + uni.reLaunch({ + url: props2.url + }); + break; + case "navigateBack": + uni.navigateBack({ + delta: props2.delta + }); + break; + } + } + return () => { + const { + hoverClass + } = props2; + const hasHoverClass = props2.hoverClass && props2.hoverClass !== "none"; + return createVNode("uni-navigator", mergeProps({ + "class": hasHoverClass && hovering.value ? hoverClass : "" + }, hasHoverClass && binding, { + "onClick": onClick + }), [slots.default && slots.default()], 16, ["onClick"]); + }; + } +}); +const props$p = { + value: { + type: Array, + default() { + return []; + }, + validator: function(val) { + return Array.isArray(val) && val.filter((val2) => typeof val2 === "number").length === val.length; + } }, - scaleMin: { - type: [Number, String], - default: 0.5 + indicatorStyle: { + type: String, + default: "" }, - scaleMax: { - type: [Number, String], - default: 10 + indicatorClass: { + type: String, + default: "" }, - scaleValue: { - type: [Number, String], - default: 1 + maskStyle: { + type: String, + default: "" }, - animation: { - type: [Boolean, String], - default: true + maskClass: { + type: String, + default: "" } }; -var MovableView = /* @__PURE__ */ defineBuiltInComponent({ - name: "MovableView", - props: props$r, - emits: ["change", "scale"], +function useState$3(props2) { + const value = reactive([...props2.value]); + const state2 = reactive({ + value, + height: 34 + }); + watch(() => props2.value, (val, oldVal) => { + { + state2.value.length = val.length; + val.forEach((val2, index2) => { + if (val2 !== state2.value[index2]) { + state2.value.splice(index2, 1, val2); + } + }); + } + }); + return state2; +} +var PickerView = /* @__PURE__ */ defineBuiltInComponent({ + name: "PickerView", + props: props$p, + emits: ["change", "pickstart", "pickend", "update:value"], setup(props2, { slots, emit: emit2 }) { const rootRef = ref(null); const trigger = useCustomEvent(rootRef, emit2); - const { - setParent - } = useMovableViewState(props2, trigger, rootRef); - return () => { - return createVNode("uni-movable-view", { - "ref": rootRef - }, [createVNode(ResizeSensor, { - "onResize": setParent - }, null, 8, ["onResize"]), slots.default && slots.default()], 512); - }; - } -}); -let requesting = false; -function _requestAnimationFrame(e2) { - if (!requesting) { - requesting = true; - requestAnimationFrame(function() { - e2(); - requesting = false; + const state2 = useState$3(props2); + const resizeSensorRef = ref(null); + onMounted(() => { + const resizeSensor = resizeSensorRef.value; + state2.height = resizeSensor.$el.getBoundingClientRect().height; }); + let columnVNodes = []; + function getItemIndex(vnode) { + return columnVNodes.indexOf(vnode); + } + const getPickerViewColumn = function(columnInstance) { + const ref2 = computed({ + get() { + const index2 = getItemIndex(columnInstance.vnode); + return state2.value[index2] || 0; + }, + set(current) { + const index2 = getItemIndex(columnInstance.vnode); + const oldCurrent = state2.value[index2]; + if (oldCurrent !== current) { + state2.value.splice(index2, 1, current); + const value = state2.value.map((val) => val); + emit2("update:value", value); + trigger("change", {}, { + value + }); + } + } + }); + return ref2; + }; + provide("getPickerViewColumn", getPickerViewColumn); + provide("pickerViewProps", props2); + provide("pickerViewState", state2); + return () => { + const defaultSlots = slots.default && slots.default(); + columnVNodes = flatVNode(defaultSlots); + return createVNode("uni-picker-view", { + "ref": rootRef + }, [createVNode(ResizeSensor, { + "ref": resizeSensorRef, + "onResize": ({ + height + }) => state2.height = height + }, null, 8, ["onResize"]), createVNode("div", { + "class": "uni-picker-view-wrapper" + }, [defaultSlots])], 512); + }; } -} -function p(t2, n) { - if (t2 === n) { - return 0; +}); +class Friction { + constructor(drag) { + this._drag = drag; + this._dragLog = Math.log(drag); + this._x = 0; + this._v = 0; + this._startTime = 0; } - let i = t2.offsetLeft; - return t2.offsetParent ? i += p(t2.offsetParent, n) : 0; -} -function f(t2, n) { - if (t2 === n) { - return 0; + set(x, v2) { + this._x = x; + this._v = v2; + this._startTime = new Date().getTime(); + } + setVelocityByEnd(e2) { + this._v = (e2 - this._x) * this._dragLog / (Math.pow(this._drag, 100) - 1); + } + x(e2) { + if (e2 === void 0) { + e2 = (new Date().getTime() - this._startTime) / 1e3; + } + const t2 = e2 === this._dt && this._powDragDt ? this._powDragDt : this._powDragDt = Math.pow(this._drag, e2); + this._dt = e2; + return this._x + this._v * t2 / this._dragLog - this._v / this._dragLog; + } + dx(e2) { + if (e2 === void 0) { + e2 = (new Date().getTime() - this._startTime) / 1e3; + } + const t2 = e2 === this._dt && this._powDragDt ? this._powDragDt : this._powDragDt = Math.pow(this._drag, e2); + this._dt = e2; + return this._v * t2; + } + done() { + return Math.abs(this.dx()) < 3; + } + reconfigure(e2) { + const t2 = this.x(); + const n = this.dx(); + this._drag = e2; + this._dragLog = Math.log(e2); + this.set(t2, n); + } + configuration() { + const e2 = this; + return [ + { + label: "Friction", + read: function() { + return e2._drag; + }, + write: function(t2) { + e2.reconfigure(t2); + }, + min: 1e-3, + max: 0.1, + step: 1e-3 + } + ]; } - let i = t2.offsetTop; - return t2.offsetParent ? i += f(t2.offsetParent, n) : 0; } -function v(a2, b) { - return +((1e3 * a2 - 1e3 * b) / 1e3).toFixed(1); +function o(e2, t2, n) { + return e2 > t2 - n && e2 < t2 + n; } -function g(friction, execute, endCallback) { - let record = { - id: 0, - cancelled: false - }; - let cancel = function(record2) { - if (record2 && record2.id) { - cancelAnimationFrame(record2.id); - } - if (record2) { - record2.cancelled = true; +function a(e2, t2) { + return o(e2, 0, t2); +} +class Spring { + constructor(m, k, c) { + this._m = m; + this._k = k; + this._c = c; + this._solution = null; + this._endPosition = 0; + this._startTime = 0; + } + _solve(e2, t2) { + const n = this._c; + const i = this._m; + const r = this._k; + const o2 = n * n - 4 * i * r; + if (o2 === 0) { + const a3 = -n / (2 * i); + const s2 = e2; + const l2 = t2 / (a3 * e2); + return { + x: function(e22) { + return (s2 + l2 * e22) * Math.pow(Math.E, a3 * e22); + }, + dx: function(e22) { + const t22 = Math.pow(Math.E, a3 * e22); + return a3 * (s2 + l2 * e22) * t22 + l2 * t22; + } + }; } - }; - function fn(record2, friction2, execute2, endCallback2) { - if (!record2 || !record2.cancelled) { - execute2(friction2); - let isDone = friction2.done(); - if (!isDone) { - if (!record2.cancelled) { - record2.id = requestAnimationFrame(fn.bind(null, record2, friction2, execute2, endCallback2)); + if (o2 > 0) { + const c = (-n - Math.sqrt(o2)) / (2 * i); + const u = (-n + Math.sqrt(o2)) / (2 * i); + const l2 = (t2 - c * e2) / (u - c); + const s2 = e2 - l2; + return { + x: function(e22) { + let t22; + let n2; + if (e22 === this._t) { + t22 = this._powER1T; + n2 = this._powER2T; + } + this._t = e22; + if (!t22) { + t22 = this._powER1T = Math.pow(Math.E, c * e22); + } + if (!n2) { + n2 = this._powER2T = Math.pow(Math.E, u * e22); + } + return s2 * t22 + l2 * n2; + }, + dx: function(e22) { + let t22; + let n2; + if (e22 === this._t) { + t22 = this._powER1T; + n2 = this._powER2T; + } + this._t = e22; + if (!t22) { + t22 = this._powER1T = Math.pow(Math.E, c * e22); + } + if (!n2) { + n2 = this._powER2T = Math.pow(Math.E, u * e22); + } + return s2 * c * t22 + l2 * u * n2; } + }; + } + const d = Math.sqrt(4 * i * r - n * n) / (2 * i); + const a2 = -n / 2 * i; + const s = e2; + const l = (t2 - a2 * e2) / d; + return { + x: function(e22) { + return Math.pow(Math.E, a2 * e22) * (s * Math.cos(d * e22) + l * Math.sin(d * e22)); + }, + dx: function(e22) { + const t22 = Math.pow(Math.E, a2 * e22); + const n2 = Math.cos(d * e22); + const i2 = Math.sin(d * e22); + return t22 * (l * d * n2 - s * d * i2) + a2 * t22 * (l * i2 + s * n2); } - if (isDone && endCallback2) { - endCallback2(friction2); - } + }; + } + x(e2) { + if (e2 === void 0) { + e2 = (new Date().getTime() - this._startTime) / 1e3; } + return this._solution ? this._endPosition + this._solution.x(e2) : 0; } - fn(record, friction, execute, endCallback); - return { - cancel: cancel.bind(null, record), - model: friction - }; -} -function _getPx(val) { - if (/\d+[ur]px$/i.test(val)) { - return uni.upx2px(parseFloat(val)); + dx(e2) { + if (e2 === void 0) { + e2 = (new Date().getTime() - this._startTime) / 1e3; + } + return this._solution ? this._solution.dx(e2) : 0; } - return Number(val) || 0; -} -function useMovableViewState(props2, trigger, rootRef) { - const movableAreaWidth = inject("movableAreaWidth", ref(0)); - const movableAreaHeight = inject("movableAreaHeight", ref(0)); - const _isMounted = inject("_isMounted", ref(false)); - const movableAreaRootRef = inject("movableAreaRootRef"); - const addMovableViewContext = inject("addMovableViewContext", () => { - }); - const removeMovableViewContext = inject("removeMovableViewContext", () => { - }); - const xSync = ref(_getPx(props2.x)); - const ySync = ref(_getPx(props2.y)); - const scaleValueSync = ref(Number(props2.scaleValue) || 1); - const width = ref(0); - const height = ref(0); - const minX = ref(0); - const minY = ref(0); - const maxX = ref(0); - const maxY = ref(0); - let _SFA = null; - let _FA = null; - const _offset = { - x: 0, - y: 0 - }; - const _scaleOffset = { - x: 0, - y: 0 - }; - let _scale = 1; - let _oldScale = 1; - let _translateX = 0; - let _translateY = 0; - let _isScaling = false; - let _isTouching = false; - let __baseX; - let __baseY; - let _checkCanMove = null; - let _firstMoveDirection = null; - const _declineX = new Decline(); - const _declineY = new Decline(); - const __touchInfo = { - historyX: [0, 0], - historyY: [0, 0], - historyT: [0, 0] - }; - const dampingNumber = computed(() => { - let val = Number(props2.damping); - return isNaN(val) ? 20 : val; - }); - const frictionNumber = computed(() => { - let val = Number(props2.friction); - return isNaN(val) || val <= 0 ? 2 : val; - }); - const scaleMinNumber = computed(() => { - let val = Number(props2.scaleMin); - return isNaN(val) ? 0.5 : val; - }); - const scaleMaxNumber = computed(() => { - let val = Number(props2.scaleMax); - return isNaN(val) ? 10 : val; - }); - const xMove = computed(() => props2.direction === "all" || props2.direction === "horizontal"); - const yMove = computed(() => props2.direction === "all" || props2.direction === "vertical"); - const _STD = new STD(1, 9 * Math.pow(dampingNumber.value, 2) / 40, dampingNumber.value); - const _friction = new Friction$1(1, frictionNumber.value); - watch(() => props2.x, (val) => { - xSync.value = _getPx(val); - }); - watch(() => props2.y, (val) => { - ySync.value = _getPx(val); - }); - watch(xSync, (val) => { - _setX(val); - }); - watch(ySync, (val) => { - _setY(val); - }); - watch(() => props2.scaleValue, (val) => { - scaleValueSync.value = Number(val) || 0; - }); - watch(scaleValueSync, (val) => { - _setScaleValue(val); - }); - watch(scaleMinNumber, () => { - _setScaleMinOrMax(); - }); - watch(scaleMaxNumber, () => { - _setScaleMinOrMax(); - }); - function FAandSFACancel() { - if (_FA) { - _FA.cancel(); - } - if (_SFA) { - _SFA.cancel(); + setEnd(e2, t2, n) { + if (!n) { + n = new Date().getTime(); } - } - function _setX(val) { - if (xMove.value) { - if (val + _scaleOffset.x === _translateX) { - return _translateX; - } else { - if (_SFA) { - _SFA.cancel(); + if (e2 !== this._endPosition || !a(t2, 0.4)) { + t2 = t2 || 0; + let i = this._endPosition; + if (this._solution) { + if (a(t2, 0.4)) { + t2 = this._solution.dx((n - this._startTime) / 1e3); } - _animationTo(val + _scaleOffset.x, ySync.value + _scaleOffset.y, _scale); + i = this._solution.x((n - this._startTime) / 1e3); + if (a(t2, 0.4)) { + t2 = 0; + } + if (a(i, 0.4)) { + i = 0; + } + i += this._endPosition; + } + if (!(this._solution && a(i - e2, 0.4) && a(t2, 0.4))) { + this._endPosition = e2; + this._solution = this._solve(i - this._endPosition, t2); + this._startTime = n; } } - return val; } - function _setY(val) { - if (yMove.value) { - if (val + _scaleOffset.y === _translateY) { - return _translateY; - } else { - if (_SFA) { - _SFA.cancel(); - } - _animationTo(xSync.value + _scaleOffset.x, val + _scaleOffset.y, _scale); + snap(e2) { + this._startTime = new Date().getTime(); + this._endPosition = e2; + this._solution = { + x: function() { + return 0; + }, + dx: function() { + return 0; } + }; + } + done(e2) { + if (!e2) { + e2 = new Date().getTime(); } - return val; + return o(this.x(), this._endPosition, 0.4) && a(this.dx(), 0.4); } - function _setScaleMinOrMax() { - if (!props2.scale) { - return false; + reconfigure(e2, t2, n) { + this._m = e2; + this._k = t2; + this._c = n; + if (!this.done()) { + this._solution = this._solve(this.x() - this._endPosition, this.dx()); + this._startTime = new Date().getTime(); } - _updateScale(_scale, true); - _updateOldScale(_scale); } - function _setScaleValue(scale) { - if (!props2.scale) { - return false; + springConstant() { + return this._k; + } + damping() { + return this._c; + } + configuration() { + function e2(e22, t22) { + e22.reconfigure(1, t22, e22.damping()); } - scale = _adjustScale(scale); - _updateScale(scale, true); - _updateOldScale(scale); - return scale; + function t2(e22, t22) { + e22.reconfigure(1, e22.springConstant(), t22); + } + return [ + { + label: "Spring Constant", + read: this.springConstant.bind(this), + write: e2.bind(this, this), + min: 100, + max: 1e3 + }, + { + label: "Damping", + read: this.damping.bind(this), + write: t2.bind(this, this), + min: 1, + max: 500 + } + ]; } - function __handleTouchStart() { - if (!_isScaling) { - if (!props2.disabled) { - FAandSFACancel(); - __touchInfo.historyX = [0, 0]; - __touchInfo.historyY = [0, 0]; - __touchInfo.historyT = [0, 0]; - if (xMove.value) { - __baseX = _translateX; - } - if (yMove.value) { - __baseY = _translateY; - } - rootRef.value.style.willChange = "transform"; - _checkCanMove = null; - _firstMoveDirection = null; - _isTouching = true; +} +class Scroll { + constructor(extent, friction, spring) { + this._extent = extent; + this._friction = friction || new Friction(0.01); + this._spring = spring || new Spring(1, 90, 20); + this._startTime = 0; + this._springing = false; + this._springOffset = 0; + } + snap(e2, t2) { + this._springOffset = 0; + this._springing = true; + this._spring.snap(e2); + this._spring.setEnd(t2); + } + set(e2, t2) { + this._friction.set(e2, t2); + if (e2 > 0 && t2 >= 0) { + this._springOffset = 0; + this._springing = true; + this._spring.snap(e2); + this._spring.setEnd(0); + } else { + if (e2 < -this._extent && t2 <= 0) { + this._springOffset = 0; + this._springing = true; + this._spring.snap(e2); + this._spring.setEnd(-this._extent); + } else { + this._springing = false; } } + this._startTime = new Date().getTime(); } - function __handleTouchMove(event) { - if (!_isScaling && !props2.disabled && _isTouching) { - let x = _translateX; - let y = _translateY; - if (_firstMoveDirection === null) { - _firstMoveDirection = Math.abs(event.detail.dx / event.detail.dy) > 1 ? "htouchmove" : "vtouchmove"; - } - if (xMove.value) { - x = event.detail.dx + __baseX; - __touchInfo.historyX.shift(); - __touchInfo.historyX.push(x); - if (!yMove.value && _checkCanMove === null) { - _checkCanMove = Math.abs(event.detail.dx / event.detail.dy) < 1; - } - } - if (yMove.value) { - y = event.detail.dy + __baseY; - __touchInfo.historyY.shift(); - __touchInfo.historyY.push(y); - if (!xMove.value && _checkCanMove === null) { - _checkCanMove = Math.abs(event.detail.dy / event.detail.dx) < 1; - } - } - __touchInfo.historyT.shift(); - __touchInfo.historyT.push(event.detail.timeStamp); - if (!_checkCanMove) { - event.preventDefault(); - let source = "touch"; - if (x < minX.value) { - if (props2.outOfBounds) { - source = "touch-out-of-bounds"; - x = minX.value - _declineX.x(minX.value - x); - } else { - x = minX.value; - } - } else if (x > maxX.value) { - if (props2.outOfBounds) { - source = "touch-out-of-bounds"; - x = maxX.value + _declineX.x(x - maxX.value); - } else { - x = maxX.value; - } - } - if (y < minY.value) { - if (props2.outOfBounds) { - source = "touch-out-of-bounds"; - y = minY.value - _declineY.x(minY.value - y); - } else { - y = minY.value; - } - } else { - if (y > maxY.value) { - if (props2.outOfBounds) { - source = "touch-out-of-bounds"; - y = maxY.value + _declineY.x(y - maxY.value); - } else { - y = maxY.value; - } - } - } - _requestAnimationFrame(function() { - _setTransform(x, y, _scale, source); - }); - } + x(e2) { + if (!this._startTime) { + return 0; } - } - function __handleTouchEnd() { - if (!_isScaling && !props2.disabled && _isTouching) { - rootRef.value.style.willChange = "auto"; - _isTouching = false; - if (!_checkCanMove && !_revise("out-of-bounds") && props2.inertia) { - const xv = 1e3 * (__touchInfo.historyX[1] - __touchInfo.historyX[0]) / (__touchInfo.historyT[1] - __touchInfo.historyT[0]); - const yv = 1e3 * (__touchInfo.historyY[1] - __touchInfo.historyY[0]) / (__touchInfo.historyT[1] - __touchInfo.historyT[0]); - _friction.setV(xv, yv); - _friction.setS(_translateX, _translateY); - const x0 = _friction.delta().x; - const y0 = _friction.delta().y; - let x = x0 + _translateX; - let y = y0 + _translateY; - if (x < minX.value) { - x = minX.value; - y = _translateY + (minX.value - _translateX) * y0 / x0; - } else { - if (x > maxX.value) { - x = maxX.value; - y = _translateY + (maxX.value - _translateX) * y0 / x0; - } - } - if (y < minY.value) { - y = minY.value; - x = _translateX + (minY.value - _translateY) * x0 / y0; - } else { - if (y > maxY.value) { - y = maxY.value; - x = _translateX + (maxY.value - _translateY) * x0 / y0; - } - } - _friction.setEnd(x, y); - _FA = g(_friction, function() { - let t2 = _friction.s(); - let x2 = t2.x; - let y2 = t2.y; - _setTransform(x2, y2, _scale, "friction"); - }, function() { - _FA.cancel(); - }); - } + if (!e2) { + e2 = (new Date().getTime() - this._startTime) / 1e3; } - if (!props2.outOfBounds && !props2.inertia) { - FAandSFACancel(); + if (this._springing) { + return this._spring.x() + this._springOffset; } - } - function _getLimitXY(x, y) { - let outOfBounds = false; - if (x > maxX.value) { - x = maxX.value; - outOfBounds = true; - } else { - if (x < minX.value) { - x = minX.value; - outOfBounds = true; + let t2 = this._friction.x(e2); + let n = this.dx(e2); + if (t2 > 0 && n >= 0 || t2 < -this._extent && n <= 0) { + this._springing = true; + this._spring.setEnd(0, n); + if (t2 < -this._extent) { + this._springOffset = -this._extent; + } else { + this._springOffset = 0; } + t2 = this._spring.x() + this._springOffset; } - if (y > maxY.value) { - y = maxY.value; - outOfBounds = true; + return t2; + } + dx(e2) { + let t2; + if (this._lastTime === e2) { + t2 = this._lastDx; } else { - if (y < minY.value) { - y = minY.value; - outOfBounds = true; - } + t2 = this._springing ? this._spring.dx(e2) : this._friction.dx(e2); } - return { - x, - y, - outOfBounds - }; - } - function _updateOffset() { - _offset.x = p(rootRef.value, movableAreaRootRef.value); - _offset.y = f(rootRef.value, movableAreaRootRef.value); + this._lastTime = e2; + this._lastDx = t2; + return t2; } - function _updateWH(scale) { - scale = scale || _scale; - scale = _adjustScale(scale); - let rect = rootRef.value.getBoundingClientRect(); - height.value = rect.height / _scale; - width.value = rect.width / _scale; - let _height = height.value * scale; - let _width = width.value * scale; - _scaleOffset.x = (_width - width.value) / 2; - _scaleOffset.y = (_height - height.value) / 2; + done() { + return this._springing ? this._spring.done() : this._friction.done(); } - function _updateBoundary() { - let x = 0 - _offset.x + _scaleOffset.x; - let _width = movableAreaWidth.value - width.value - _offset.x - _scaleOffset.x; - minX.value = Math.min(x, _width); - maxX.value = Math.max(x, _width); - let y = 0 - _offset.y + _scaleOffset.y; - let _height = movableAreaHeight.value - height.value - _offset.y - _scaleOffset.y; - minY.value = Math.min(y, _height); - maxY.value = Math.max(y, _height); + setVelocityByEnd(e2) { + this._friction.setVelocityByEnd(e2); } - function _beginScale() { - _isScaling = true; + configuration() { + const e2 = this._friction.configuration(); + e2.push.apply(e2, this._spring.configuration()); + return e2; } - function _updateScale(scale, animat) { - if (props2.scale) { - scale = _adjustScale(scale); - _updateWH(scale); - _updateBoundary(); - const limitXY = _getLimitXY(_translateX, _translateY); - const x = limitXY.x; - const y = limitXY.y; - if (animat) { - _animationTo(x, y, scale, "", true, true); - } else { - _requestAnimationFrame(function() { - _setTransform(x, y, scale, "", true, true); - }); +} +function createAnimation$1(scroll, onScroll, onEnd) { + const state2 = { + id: 0, + cancelled: false + }; + function startAnimation2(state22, scroll2, onScroll2, onEnd2) { + if (!state22 || !state22.cancelled) { + onScroll2(scroll2); + const isDone = scroll2.done(); + if (!isDone) { + if (!state22.cancelled) { + state22.id = requestAnimationFrame(startAnimation2.bind(null, state22, scroll2, onScroll2, onEnd2)); + } + } + if (isDone && onEnd2) { + onEnd2(scroll2); } } } - function _updateOldScale(scale) { - _oldScale = scale; - } - function _adjustScale(scale) { - scale = Math.max(0.5, scaleMinNumber.value, scale); - scale = Math.min(10, scaleMaxNumber.value, scale); - return scale; - } - function _animationTo(x, y, scale, source, r, o2) { - FAandSFACancel(); - if (!xMove.value) { - x = _translateX; - } - if (!yMove.value) { - y = _translateY; - } - if (!props2.scale) { - scale = _scale; + function cancel(state22) { + if (state22 && state22.id) { + cancelAnimationFrame(state22.id); } - let limitXY = _getLimitXY(x, y); - x = limitXY.x; - y = limitXY.y; - if (!props2.animation) { - _setTransform(x, y, scale, source, r, o2); - return; + if (state22) { + state22.cancelled = true; } - _STD._springX._solution = null; - _STD._springY._solution = null; - _STD._springScale._solution = null; - _STD._springX._endPosition = _translateX; - _STD._springY._endPosition = _translateY; - _STD._springScale._endPosition = _scale; - _STD.setEnd(x, y, scale, 1); - _SFA = g(_STD, function() { - let data = _STD.x(); - let x2 = data.x; - let y2 = data.y; - let scale2 = data.scale; - _setTransform(x2, y2, scale2, source, r, o2); - }, function() { - _SFA.cancel(); - }); } - function _revise(source) { - let limitXY = _getLimitXY(_translateX, _translateY); - let x = limitXY.x; - let y = limitXY.y; - let outOfBounds = limitXY.outOfBounds; - if (outOfBounds) { - _animationTo(x, y, _scale, source); + startAnimation2(state2, scroll, onScroll, onEnd); + return { + cancel: cancel.bind(null, state2), + model: scroll + }; +} +class Scroller { + constructor(element, options) { + options = options || {}; + this._element = element; + this._options = options; + this._enableSnap = options.enableSnap || false; + this._itemSize = options.itemSize || 0; + this._enableX = options.enableX || false; + this._enableY = options.enableY || false; + this._shouldDispatchScrollEvent = !!options.onScroll; + if (this._enableX) { + this._extent = (options.scrollWidth || this._element.offsetWidth) - this._element.parentElement.offsetWidth; + this._scrollWidth = options.scrollWidth; + } else { + this._extent = (options.scrollHeight || this._element.offsetHeight) - this._element.parentElement.offsetHeight; + this._scrollHeight = options.scrollHeight; } - return outOfBounds; + this._position = 0; + this._scroll = new Scroll(this._extent, options.friction, options.spring); + this._onTransitionEnd = this.onTransitionEnd.bind(this); + this.updatePosition(); } - function _setTransform(x, y, scale, source = "", r, o2) { - if (!(x !== null && x.toString() !== "NaN" && typeof x === "number")) { - x = _translateX || 0; + onTouchStart() { + this._startPosition = this._position; + this._lastChangePos = this._startPosition; + if (this._startPosition > 0) { + this._startPosition /= 0.5; + } else { + if (this._startPosition < -this._extent) { + this._startPosition = (this._startPosition + this._extent) / 0.5 - this._extent; + } } - if (!(y !== null && y.toString() !== "NaN" && typeof y === "number")) { - y = _translateY || 0; + if (this._animation) { + this._animation.cancel(); + this._scrolling = false; } - x = Number(x.toFixed(1)); - y = Number(y.toFixed(1)); - scale = Number(scale.toFixed(1)); - if (!(_translateX === x && _translateY === y)) { - if (!r) { - trigger("change", {}, { - x: v(x, _scaleOffset.x), - y: v(y, _scaleOffset.y), - source - }); + this.updatePosition(); + } + onTouchMove(x, y) { + let startPosition = this._startPosition; + if (this._enableX) { + startPosition += x; + } else if (this._enableY) { + startPosition += y; + } + if (startPosition > 0) { + startPosition *= 0.5; + } else if (startPosition < -this._extent) { + startPosition = 0.5 * (startPosition + this._extent) - this._extent; + } + this._position = startPosition; + this.updatePosition(); + this.dispatchScroll(); + } + onTouchEnd(x, y, o2) { + if (this._enableSnap && this._position > -this._extent && this._position < 0) { + if (this._enableY && (Math.abs(y) < this._itemSize && Math.abs(o2.y) < 300 || Math.abs(o2.y) < 150)) { + this.snap(); + return; + } + if (this._enableX && (Math.abs(x) < this._itemSize && Math.abs(o2.x) < 300 || Math.abs(o2.x) < 150)) { + this.snap(); + return; } } - if (!props2.scale) { - scale = _scale; + if (this._enableX) { + this._scroll.set(this._position, o2.x); + } else if (this._enableY) { + this._scroll.set(this._position, o2.y); } - scale = _adjustScale(scale); - scale = +scale.toFixed(3); - if (o2 && scale !== _scale) { - trigger("scale", {}, { - x, - y, - scale - }); + let c; + if (this._enableSnap) { + const s = this._scroll._friction.x(100); + const l = s % this._itemSize; + c = Math.abs(l) > this._itemSize / 2 ? s - (this._itemSize - Math.abs(l)) : s - l; + if (c <= 0 && c >= -this._extent) { + this._scroll.setVelocityByEnd(c); + } } - let transform = "translateX(" + x + "px) translateY(" + y + "px) translateZ(0px) scale(" + scale + ")"; - rootRef.value.style.transform = transform; - rootRef.value.style.webkitTransform = transform; - _translateX = x; - _translateY = y; - _scale = scale; + this._lastTime = Date.now(); + this._lastDelay = 0; + this._scrolling = true; + this._lastChangePos = this._position; + this._lastIdx = Math.floor(Math.abs(this._position / this._itemSize)); + this._animation = createAnimation$1(this._scroll, () => { + const e2 = Date.now(); + const i = (e2 - this._scroll._startTime) / 1e3; + const r = this._scroll.x(i); + this._position = r; + this.updatePosition(); + const o22 = this._scroll.dx(i); + if (this._shouldDispatchScrollEvent && e2 - this._lastTime > this._lastDelay) { + this.dispatchScroll(); + this._lastDelay = Math.abs(2e3 / o22); + this._lastTime = e2; + } + }, () => { + if (this._enableSnap) { + if (c <= 0 && c >= -this._extent) { + this._position = c; + this.updatePosition(); + } + if (typeof this._options.onSnap === "function") { + this._options.onSnap(Math.floor(Math.abs(this._position) / this._itemSize)); + } + } + if (this._shouldDispatchScrollEvent) { + this.dispatchScroll(); + } + this._scrolling = false; + }); } - function setParent() { - if (!_isMounted.value) { - return; + onTransitionEnd() { + this._element.style.webkitTransition = ""; + this._element.style.transition = ""; + this._element.removeEventListener("transitionend", this._onTransitionEnd); + if (this._snapping) { + this._snapping = false; } - FAandSFACancel(); - let scale = props2.scale ? scaleValueSync.value : 1; - _updateOffset(); - _updateWH(scale); - _updateBoundary(); - _translateX = xSync.value + _scaleOffset.x; - _translateY = ySync.value + _scaleOffset.y; - let limitXY = _getLimitXY(_translateX, _translateY); - let x = limitXY.x; - let y = limitXY.y; - _setTransform(x, y, scale, "", true); - _updateOldScale(scale); - } - function _endScale() { - _isScaling = false; - _updateOldScale(_scale); + this.dispatchScroll(); } - function _setScale(scale) { - if (scale) { - scale = _oldScale * scale; - _beginScale(); - _updateScale(scale); + snap() { + const itemSize = this._itemSize; + const position = this._position % itemSize; + const i = Math.abs(position) > this._itemSize / 2 ? this._position - (itemSize - Math.abs(position)) : this._position - position; + if (this._position !== i) { + this._snapping = true; + this.scrollTo(-i); + if (typeof this._options.onSnap === "function") { + this._options.onSnap(Math.floor(Math.abs(this._position) / this._itemSize)); + } } } - onMounted(() => { - useTouchtrack(rootRef.value, (event) => { - switch (event.detail.state) { - case "start": - __handleTouchStart(); - break; - case "move": - __handleTouchMove(event); - break; - case "end": - __handleTouchEnd(); + scrollTo(position, time) { + if (this._animation) { + this._animation.cancel(); + this._scrolling = false; + } + if (typeof position === "number") { + this._position = -position; + } + if (this._position < -this._extent) { + this._position = -this._extent; + } else { + if (this._position > 0) { + this._position = 0; } - }); - setParent(); - _friction.reconfigure(1, frictionNumber.value); - _STD.reconfigure(1, 9 * Math.pow(dampingNumber.value, 2) / 40, dampingNumber.value); - rootRef.value.style.transformOrigin = "center"; - const context = { - rootRef, - setParent, - _endScale, - _setScale - }; - addMovableViewContext(context); - onUnmounted(() => { - removeMovableViewContext(context); - }); - }); - onUnmounted(() => { - FAandSFACancel(); - }); - return { - setParent - }; -} -const OPEN_TYPES = ["navigate", "redirect", "switchTab", "reLaunch", "navigateBack"]; -const props$q = { - hoverClass: { - type: String, - default: "navigator-hover" - }, - url: { - type: String, - default: "" - }, - openType: { - type: String, - default: "navigate", - validator(value) { - return Boolean(~OPEN_TYPES.indexOf(value)); } - }, - delta: { - type: Number, - default: 1 - }, - hoverStartTime: { - type: [Number, String], - default: 50 - }, - hoverStayTime: { - type: [Number, String], - default: 600 - }, - exists: { - type: String, - default: "" - }, - hoverStopPropagation: { - type: Boolean, - default: false + const transition = "transform " + (time || 0.2) + "s ease-out"; + this._element.style.webkitTransition = "-webkit-" + transition; + this._element.style.transition = transition; + this.updatePosition(); + this._element.addEventListener("transitionend", this._onTransitionEnd); } -}; -var index$k = /* @__PURE__ */ defineBuiltInComponent({ - name: "Navigator", - compatConfig: { - MODE: 3 - }, - props: props$q, - setup(props2, { - slots - }) { - const { - hovering, - binding - } = useHover(props2); - function onClick($event) { - if (props2.openType !== "navigateBack" && !props2.url) { - console.error(" should have url attribute when using navigateTo, redirectTo, reLaunch or switchTab"); - return; + dispatchScroll() { + if (typeof this._options.onScroll === "function" && Math.round(Number(this._lastPos)) !== Math.round(this._position)) { + this._lastPos = this._position; + const event = { + target: { + scrollLeft: this._enableX ? -this._position : 0, + scrollTop: this._enableY ? -this._position : 0, + scrollHeight: this._scrollHeight || this._element.offsetHeight, + scrollWidth: this._scrollWidth || this._element.offsetWidth, + offsetHeight: this._element.parentElement.offsetHeight, + offsetWidth: this._element.parentElement.offsetWidth + } + }; + this._options.onScroll(event); + } + } + update(height, scrollHeight, itemSize) { + let extent = 0; + const position = this._position; + if (this._enableX) { + extent = this._element.childNodes.length ? (scrollHeight || this._element.offsetWidth) - this._element.parentElement.offsetWidth : 0; + this._scrollWidth = scrollHeight; + } else { + extent = this._element.childNodes.length ? (scrollHeight || this._element.offsetHeight) - this._element.parentElement.offsetHeight : 0; + this._scrollHeight = scrollHeight; + } + if (typeof height === "number") { + this._position = -height; + } + if (this._position < -extent) { + this._position = -extent; + } else { + if (this._position > 0) { + this._position = 0; } - switch (props2.openType) { - case "navigate": - uni.navigateTo({ - url: props2.url - }); - break; - case "redirect": - uni.redirectTo({ - url: props2.url, - exists: props2.exists - }); - break; - case "switchTab": - uni.switchTab({ - url: props2.url - }); - break; - case "reLaunch": - uni.reLaunch({ - url: props2.url - }); - break; - case "navigateBack": - uni.navigateBack({ - delta: props2.delta - }); - break; + } + this._itemSize = itemSize || this._itemSize; + this.updatePosition(); + if (position !== this._position) { + this.dispatchScroll(); + if (typeof this._options.onSnap === "function") { + this._options.onSnap(Math.floor(Math.abs(this._position) / this._itemSize)); } } - return () => { - const { - hoverClass - } = props2; - const hasHoverClass = props2.hoverClass && props2.hoverClass !== "none"; - return createVNode("uni-navigator", mergeProps({ - "class": hasHoverClass && hovering.value ? hoverClass : "" - }, hasHoverClass && binding, { - "onClick": onClick - }), [slots.default && slots.default()], 16, ["onClick"]); - }; + this._extent = extent; + this._scroll._extent = extent; } -}); -const props$p = { - value: { - type: Array, - default() { - return []; - }, - validator: function(val) { - return Array.isArray(val) && val.filter((val2) => typeof val2 === "number").length === val.length; + updatePosition() { + let transform = ""; + if (this._enableX) { + transform = "translateX(" + this._position + "px) translateZ(0)"; + } else { + if (this._enableY) { + transform = "translateY(" + this._position + "px) translateZ(0)"; + } } - }, - indicatorStyle: { - type: String, - default: "" - }, - indicatorClass: { - type: String, - default: "" - }, - maskStyle: { - type: String, - default: "" - }, - maskClass: { - type: String, - default: "" + this._element.style.webkitTransform = transform; + this._element.style.transform = transform; + } + isScrolling() { + return this._scrolling || this._snapping; } -}; -function useState$3(props2) { - const value = reactive([...props2.value]); - const state2 = reactive({ - value, - height: 34 - }); - watch(() => props2.value, (val, oldVal) => { - { - state2.value.length = val.length; - val.forEach((val2, index2) => { - if (val2 !== state2.value[index2]) { - state2.value.splice(index2, 1, val2); - } - }); - } - }); - return state2; } -var PickerView = /* @__PURE__ */ defineBuiltInComponent({ - name: "PickerView", - props: props$p, - emits: ["change", "pickstart", "pickend", "update:value"], - setup(props2, { - slots, - emit: emit2 - }) { - const rootRef = ref(null); - const trigger = useCustomEvent(rootRef, emit2); - const state2 = useState$3(props2); - const resizeSensorRef = ref(null); - onMounted(() => { - const resizeSensor = resizeSensorRef.value; - state2.height = resizeSensor.$el.getBoundingClientRect().height; - }); - let columnVNodes = []; - function getItemIndex(vnode) { - return columnVNodes.indexOf(vnode); - } - const getPickerViewColumn = function(columnInstance) { - const ref2 = computed({ - get() { - const index2 = getItemIndex(columnInstance.vnode); - return state2.value[index2] || 0; - }, - set(current) { - const index2 = getItemIndex(columnInstance.vnode); - const oldCurrent = state2.value[index2]; - if (oldCurrent !== current) { - state2.value.splice(index2, 1, current); - const value = state2.value.map((val) => val); - emit2("update:value", value); - trigger("change", {}, { - value - }); - } - } - }); - return ref2; - }; - provide("getPickerViewColumn", getPickerViewColumn); - provide("pickerViewProps", props2); - provide("pickerViewState", state2); - return () => { - const defaultSlots = slots.default && slots.default(); - columnVNodes = flatVNode(defaultSlots); - return createVNode("uni-picker-view", { - "ref": rootRef - }, [createVNode(ResizeSensor, { - "ref": resizeSensorRef, - "onResize": ({ - height - }) => state2.height = height - }, null, 8, ["onResize"]), createVNode("div", { - "class": "uni-picker-view-wrapper" - }, [defaultSlots])], 512); +function useScroller(element, options) { + const touchInfo = { + trackingID: -1, + maxDy: 0, + maxDx: 0 + }; + const scroller = new Scroller(element, options); + function findDelta(event) { + const touchtrackEvent = event; + const mouseEvent = event; + return touchtrackEvent.detail.state === "move" || touchtrackEvent.detail.state === "end" ? { + x: touchtrackEvent.detail.dx, + y: touchtrackEvent.detail.dy + } : { + x: mouseEvent.screenX - touchInfo.x, + y: mouseEvent.screenY - touchInfo.y }; } -}); -class Friction { - constructor(drag) { - this._drag = drag; - this._dragLog = Math.log(drag); - this._x = 0; - this._v = 0; - this._startTime = 0; - } - set(x, v2) { - this._x = x; - this._v = v2; - this._startTime = new Date().getTime(); - } - setVelocityByEnd(e2) { - this._v = (e2 - this._x) * this._dragLog / (Math.pow(this._drag, 100) - 1); - } - x(e2) { - if (e2 === void 0) { - e2 = (new Date().getTime() - this._startTime) / 1e3; - } - const t2 = e2 === this._dt && this._powDragDt ? this._powDragDt : this._powDragDt = Math.pow(this._drag, e2); - this._dt = e2; - return this._x + this._v * t2 / this._dragLog - this._v / this._dragLog; - } - dx(e2) { - if (e2 === void 0) { - e2 = (new Date().getTime() - this._startTime) / 1e3; + function handleTouchStart(event) { + const touchtrackEvent = event; + const mouseEvent = event; + if (touchtrackEvent.detail.state === "start") { + touchInfo.trackingID = "touch"; + touchInfo.x = touchtrackEvent.detail.x; + touchInfo.y = touchtrackEvent.detail.y; + } else { + touchInfo.trackingID = "mouse"; + touchInfo.x = mouseEvent.screenX; + touchInfo.y = mouseEvent.screenY; } - const t2 = e2 === this._dt && this._powDragDt ? this._powDragDt : this._powDragDt = Math.pow(this._drag, e2); - this._dt = e2; - return this._v * t2; - } - done() { - return Math.abs(this.dx()) < 3; - } - reconfigure(e2) { - const t2 = this.x(); - const n = this.dx(); - this._drag = e2; - this._dragLog = Math.log(e2); - this.set(t2, n); - } - configuration() { - const e2 = this; - return [ - { - label: "Friction", - read: function() { - return e2._drag; - }, - write: function(t2) { - e2.reconfigure(t2); - }, - min: 1e-3, - max: 0.1, - step: 1e-3 - } + touchInfo.maxDx = 0; + touchInfo.maxDy = 0; + touchInfo.historyX = [0]; + touchInfo.historyY = [0]; + touchInfo.historyTime = [ + touchtrackEvent.detail.timeStamp || mouseEvent.timeStamp ]; + touchInfo.listener = scroller; + if (scroller.onTouchStart) { + scroller.onTouchStart(); + } + event.preventDefault(); } -} -function o(e2, t2, n) { - return e2 > t2 - n && e2 < t2 + n; -} -function a(e2, t2) { - return o(e2, 0, t2); -} -class Spring { - constructor(m, k, c) { - this._m = m; - this._k = k; - this._c = c; - this._solution = null; - this._endPosition = 0; - this._startTime = 0; - } - _solve(e2, t2) { - const n = this._c; - const i = this._m; - const r = this._k; - const o2 = n * n - 4 * i * r; - if (o2 === 0) { - const a3 = -n / (2 * i); - const s2 = e2; - const l2 = t2 / (a3 * e2); - return { - x: function(e22) { - return (s2 + l2 * e22) * Math.pow(Math.E, a3 * e22); - }, - dx: function(e22) { - const t22 = Math.pow(Math.E, a3 * e22); - return a3 * (s2 + l2 * e22) * t22 + l2 * t22; + function handleTouchMove(event) { + const touchtrackEvent = event; + const mouseEvent = event; + if (touchInfo.trackingID !== -1) { + event.preventDefault(); + const delta = findDelta(event); + if (delta) { + for (touchInfo.maxDy = Math.max(touchInfo.maxDy, Math.abs(delta.y)), touchInfo.maxDx = Math.max(touchInfo.maxDx, Math.abs(delta.x)), touchInfo.historyX.push(delta.x), touchInfo.historyY.push(delta.y), touchInfo.historyTime.push(touchtrackEvent.detail.timeStamp || mouseEvent.timeStamp); touchInfo.historyTime.length > 10; ) { + touchInfo.historyTime.shift(); + touchInfo.historyX.shift(); + touchInfo.historyY.shift(); } - }; - } - if (o2 > 0) { - const c = (-n - Math.sqrt(o2)) / (2 * i); - const u = (-n + Math.sqrt(o2)) / (2 * i); - const l2 = (t2 - c * e2) / (u - c); - const s2 = e2 - l2; - return { - x: function(e22) { - let t22; - let n2; - if (e22 === this._t) { - t22 = this._powER1T; - n2 = this._powER2T; - } - this._t = e22; - if (!t22) { - t22 = this._powER1T = Math.pow(Math.E, c * e22); - } - if (!n2) { - n2 = this._powER2T = Math.pow(Math.E, u * e22); - } - return s2 * t22 + l2 * n2; - }, - dx: function(e22) { - let t22; - let n2; - if (e22 === this._t) { - t22 = this._powER1T; - n2 = this._powER2T; - } - this._t = e22; - if (!t22) { - t22 = this._powER1T = Math.pow(Math.E, c * e22); - } - if (!n2) { - n2 = this._powER2T = Math.pow(Math.E, u * e22); - } - return s2 * c * t22 + l2 * u * n2; + if (touchInfo.listener && touchInfo.listener.onTouchMove) { + touchInfo.listener.onTouchMove(delta.x, delta.y); } - }; - } - const d = Math.sqrt(4 * i * r - n * n) / (2 * i); - const a2 = -n / 2 * i; - const s = e2; - const l = (t2 - a2 * e2) / d; - return { - x: function(e22) { - return Math.pow(Math.E, a2 * e22) * (s * Math.cos(d * e22) + l * Math.sin(d * e22)); - }, - dx: function(e22) { - const t22 = Math.pow(Math.E, a2 * e22); - const n2 = Math.cos(d * e22); - const i2 = Math.sin(d * e22); - return t22 * (l * d * n2 - s * d * i2) + a2 * t22 * (l * i2 + s * n2); } - }; - } - x(e2) { - if (e2 === void 0) { - e2 = (new Date().getTime() - this._startTime) / 1e3; - } - return this._solution ? this._endPosition + this._solution.x(e2) : 0; - } - dx(e2) { - if (e2 === void 0) { - e2 = (new Date().getTime() - this._startTime) / 1e3; } - return this._solution ? this._solution.dx(e2) : 0; } - setEnd(e2, t2, n) { - if (!n) { - n = new Date().getTime(); - } - if (e2 !== this._endPosition || !a(t2, 0.4)) { - t2 = t2 || 0; - let i = this._endPosition; - if (this._solution) { - if (a(t2, 0.4)) { - t2 = this._solution.dx((n - this._startTime) / 1e3); - } - i = this._solution.x((n - this._startTime) / 1e3); - if (a(t2, 0.4)) { - t2 = 0; + function handleTouchEnd(event) { + if (touchInfo.trackingID !== -1) { + event.preventDefault(); + const delta = findDelta(event); + if (delta) { + const listener2 = touchInfo.listener; + touchInfo.trackingID = -1; + touchInfo.listener = null; + const length = touchInfo.historyTime.length; + const o2 = { + x: 0, + y: 0 + }; + if (length > 2) { + for (let i = touchInfo.historyTime.length - 1, time1 = touchInfo.historyTime[i], x = touchInfo.historyX[i], y = touchInfo.historyY[i]; i > 0; ) { + i--; + const time0 = touchInfo.historyTime[i]; + const time = time1 - time0; + if (time > 30 && time < 50) { + o2.x = (x - touchInfo.historyX[i]) / (time / 1e3); + o2.y = (y - touchInfo.historyY[i]) / (time / 1e3); + break; + } + } } - if (a(i, 0.4)) { - i = 0; + touchInfo.historyTime = []; + touchInfo.historyX = []; + touchInfo.historyY = []; + if (listener2 && listener2.onTouchEnd) { + listener2.onTouchEnd(delta.x, delta.y, o2); } - i += this._endPosition; - } - if (!(this._solution && a(i - e2, 0.4) && a(t2, 0.4))) { - this._endPosition = e2; - this._solution = this._solve(i - this._endPosition, t2); - this._startTime = n; - } - } - } - snap(e2) { - this._startTime = new Date().getTime(); - this._endPosition = e2; - this._solution = { - x: function() { - return 0; - }, - dx: function() { - return 0; } - }; - } - done(e2) { - if (!e2) { - e2 = new Date().getTime(); } - return o(this.x(), this._endPosition, 0.4) && a(this.dx(), 0.4); } - reconfigure(e2, t2, n) { - this._m = e2; - this._k = t2; - this._c = n; - if (!this.done()) { - this._solution = this._solve(this.x() - this._endPosition, this.dx()); - this._startTime = new Date().getTime(); - } - } - springConstant() { - return this._k; - } - damping() { - return this._c; + return { + scroller, + handleTouchStart, + handleTouchMove, + handleTouchEnd + }; +} +let scopedIndex = 0; +function useScopedClass(indicatorHeightRef) { + const className = `uni-picker-view-content-${scopedIndex++}`; + function updateStyle2() { + const style = document.createElement("style"); + style.innerText = `.uni-picker-view-content.${className}>*{height: ${indicatorHeightRef.value}px;overflow: hidden;}`; + document.head.appendChild(style); } - configuration() { - function e2(e22, t22) { - e22.reconfigure(1, t22, e22.damping()); - } - function t2(e22, t22) { - e22.reconfigure(1, e22.springConstant(), t22); + watch(() => indicatorHeightRef.value, updateStyle2); + return className; +} +function useCustomClick(dom) { + const MAX_MOVE = 20; + let x = 0; + let y = 0; + dom.addEventListener("touchstart", (event) => { + const info = event.changedTouches[0]; + x = info.clientX; + y = info.clientY; + }); + dom.addEventListener("touchend", (event) => { + const info = event.changedTouches[0]; + if (Math.abs(info.clientX - x) < MAX_MOVE && Math.abs(info.clientY - y) < MAX_MOVE) { + const options = { + bubbles: true, + cancelable: true, + target: event.target, + currentTarget: event.currentTarget + }; + const customClick = new CustomEvent("click", options); + const props2 = ["screenX", "screenY", "clientX", "clientY", "pageX", "pageY"]; + props2.forEach((key) => { + customClick[key] = info[key]; + }); + event.target.dispatchEvent(customClick); } - return [ - { - label: "Spring Constant", - read: this.springConstant.bind(this), - write: e2.bind(this, this), - min: 100, - max: 1e3 - }, - { - label: "Damping", - read: this.damping.bind(this), - write: t2.bind(this, this), - min: 1, - max: 500 - } - ]; - } + }); } -class Scroll { - constructor(extent, friction, spring) { - this._extent = extent; - this._friction = friction || new Friction(0.01); - this._spring = spring || new Spring(1, 90, 20); - this._startTime = 0; - this._springing = false; - this._springOffset = 0; - } - snap(e2, t2) { - this._springOffset = 0; - this._springing = true; - this._spring.snap(e2); - this._spring.setEnd(t2); - } - set(e2, t2) { - this._friction.set(e2, t2); - if (e2 > 0 && t2 >= 0) { - this._springOffset = 0; - this._springing = true; - this._spring.snap(e2); - this._spring.setEnd(0); - } else { - if (e2 < -this._extent && t2 <= 0) { - this._springOffset = 0; - this._springing = true; - this._spring.snap(e2); - this._spring.setEnd(-this._extent); - } else { - this._springing = false; +var PickerViewColumn = /* @__PURE__ */ defineBuiltInComponent({ + name: "PickerViewColumn", + setup(props2, { + slots, + emit: emit2 + }) { + const rootRef = ref(null); + const contentRef = ref(null); + const getPickerViewColumn = inject("getPickerViewColumn"); + const instance2 = getCurrentInstance(); + const currentRef = getPickerViewColumn ? getPickerViewColumn(instance2) : ref(0); + const pickerViewProps = inject("pickerViewProps"); + const pickerViewState = inject("pickerViewState"); + const indicatorHeight = ref(34); + const resizeSensorRef = ref(null); + onMounted(() => { + const resizeSensor = resizeSensorRef.value; + indicatorHeight.value = resizeSensor.$el.getBoundingClientRect().height; + }); + const maskSize = computed(() => (pickerViewState.height - indicatorHeight.value) / 2); + const { + state: scopedAttrsState + } = useScopedAttrs(); + const className = useScopedClass(indicatorHeight); + let scroller; + const state2 = reactive({ + current: currentRef.value, + length: 0 + }); + function updatesScroller() { + if (scroller) { + nextTick(() => { + let current = Math.min(state2.current, state2.length - 1); + current = Math.max(current, 0); + scroller.update(current * indicatorHeight.value, void 0, indicatorHeight.value); + }); } } - this._startTime = new Date().getTime(); - } - x(e2) { - if (!this._startTime) { - return 0; - } - if (!e2) { - e2 = (new Date().getTime() - this._startTime) / 1e3; - } - if (this._springing) { - return this._spring.x() + this._springOffset; - } - let t2 = this._friction.x(e2); - let n = this.dx(e2); - if (t2 > 0 && n >= 0 || t2 < -this._extent && n <= 0) { - this._springing = true; - this._spring.setEnd(0, n); - if (t2 < -this._extent) { - this._springOffset = -this._extent; + watch(() => currentRef.value, (current) => { + if (current !== state2.current) { + state2.current = current; + updatesScroller(); + } + }); + watch(() => state2.current, (current) => currentRef.value = current); + watch([() => indicatorHeight.value, () => state2.length, () => pickerViewState.height], updatesScroller); + let oldDeltaY = 0; + function handleWheel(event) { + const deltaY = oldDeltaY + event.deltaY; + if (Math.abs(deltaY) > 10) { + oldDeltaY = 0; + let current = Math.min(state2.current + (deltaY < 0 ? -1 : 1), state2.length - 1); + state2.current = current = Math.max(current, 0); + scroller.scrollTo(current * indicatorHeight.value); } else { - this._springOffset = 0; + oldDeltaY = deltaY; } - t2 = this._spring.x() + this._springOffset; - } - return t2; - } - dx(e2) { - let t2; - if (this._lastTime === e2) { - t2 = this._lastDx; - } else { - t2 = this._springing ? this._spring.dx(e2) : this._friction.dx(e2); + event.preventDefault(); } - this._lastTime = e2; - this._lastDx = t2; - return t2; - } - done() { - return this._springing ? this._spring.done() : this._friction.done(); - } - setVelocityByEnd(e2) { - this._friction.setVelocityByEnd(e2); - } - configuration() { - const e2 = this._friction.configuration(); - e2.push.apply(e2, this._spring.configuration()); - return e2; - } -} -function createAnimation$1(scroll, onScroll, onEnd) { - const state2 = { - id: 0, - cancelled: false - }; - function startAnimation2(state22, scroll2, onScroll2, onEnd2) { - if (!state22 || !state22.cancelled) { - onScroll2(scroll2); - const isDone = scroll2.done(); - if (!isDone) { - if (!state22.cancelled) { - state22.id = requestAnimationFrame(startAnimation2.bind(null, state22, scroll2, onScroll2, onEnd2)); + function handleTap({ + clientY + }) { + const el = rootRef.value; + if (!scroller.isScrolling()) { + const rect = el.getBoundingClientRect(); + const r = clientY - rect.top - pickerViewState.height / 2; + const o2 = indicatorHeight.value / 2; + if (!(Math.abs(r) <= o2)) { + const a2 = Math.ceil((Math.abs(r) - o2) / indicatorHeight.value); + const s = r < 0 ? -a2 : a2; + let current = Math.min(state2.current + s, state2.length - 1); + state2.current = current = Math.max(current, 0); + scroller.scrollTo(current * indicatorHeight.value); } } - if (isDone && onEnd2) { - onEnd2(scroll2); - } - } - } - function cancel(state22) { - if (state22 && state22.id) { - cancelAnimationFrame(state22.id); - } - if (state22) { - state22.cancelled = true; } - } - startAnimation2(state2, scroll, onScroll, onEnd); - return { - cancel: cancel.bind(null, state2), - model: scroll - }; -} -class Scroller { - constructor(element, options) { - options = options || {}; - this._element = element; - this._options = options; - this._enableSnap = options.enableSnap || false; - this._itemSize = options.itemSize || 0; - this._enableX = options.enableX || false; - this._enableY = options.enableY || false; - this._shouldDispatchScrollEvent = !!options.onScroll; - if (this._enableX) { - this._extent = (options.scrollWidth || this._element.offsetWidth) - this._element.parentElement.offsetWidth; - this._scrollWidth = options.scrollWidth; - } else { - this._extent = (options.scrollHeight || this._element.offsetHeight) - this._element.parentElement.offsetHeight; - this._scrollHeight = options.scrollHeight; - } - this._position = 0; - this._scroll = new Scroll(this._extent, options.friction, options.spring); - this._onTransitionEnd = this.onTransitionEnd.bind(this); - this.updatePosition(); - } - onTouchStart() { - this._startPosition = this._position; - this._lastChangePos = this._startPosition; - if (this._startPosition > 0) { - this._startPosition /= 0.5; - } else { - if (this._startPosition < -this._extent) { - this._startPosition = (this._startPosition + this._extent) / 0.5 - this._extent; - } - } - if (this._animation) { - this._animation.cancel(); - this._scrolling = false; - } - this.updatePosition(); - } - onTouchMove(x, y) { - let startPosition = this._startPosition; - if (this._enableX) { - startPosition += x; - } else if (this._enableY) { - startPosition += y; - } - if (startPosition > 0) { - startPosition *= 0.5; - } else if (startPosition < -this._extent) { - startPosition = 0.5 * (startPosition + this._extent) - this._extent; - } - this._position = startPosition; - this.updatePosition(); - this.dispatchScroll(); - } - onTouchEnd(x, y, o2) { - if (this._enableSnap && this._position > -this._extent && this._position < 0) { - if (this._enableY && (Math.abs(y) < this._itemSize && Math.abs(o2.y) < 300 || Math.abs(o2.y) < 150)) { - this.snap(); - return; - } - if (this._enableX && (Math.abs(x) < this._itemSize && Math.abs(o2.x) < 300 || Math.abs(o2.x) < 150)) { - this.snap(); - return; - } - } - if (this._enableX) { - this._scroll.set(this._position, o2.x); - } else if (this._enableY) { - this._scroll.set(this._position, o2.y); - } - let c; - if (this._enableSnap) { - const s = this._scroll._friction.x(100); - const l = s % this._itemSize; - c = Math.abs(l) > this._itemSize / 2 ? s - (this._itemSize - Math.abs(l)) : s - l; - if (c <= 0 && c >= -this._extent) { - this._scroll.setVelocityByEnd(c); - } - } - this._lastTime = Date.now(); - this._lastDelay = 0; - this._scrolling = true; - this._lastChangePos = this._position; - this._lastIdx = Math.floor(Math.abs(this._position / this._itemSize)); - this._animation = createAnimation$1(this._scroll, () => { - const e2 = Date.now(); - const i = (e2 - this._scroll._startTime) / 1e3; - const r = this._scroll.x(i); - this._position = r; - this.updatePosition(); - const o22 = this._scroll.dx(i); - if (this._shouldDispatchScrollEvent && e2 - this._lastTime > this._lastDelay) { - this.dispatchScroll(); - this._lastDelay = Math.abs(2e3 / o22); - this._lastTime = e2; - } - }, () => { - if (this._enableSnap) { - if (c <= 0 && c >= -this._extent) { - this._position = c; - this.updatePosition(); + onMounted(() => { + const el = rootRef.value; + const content = contentRef.value; + const { + scroller: scrollerOrigin, + handleTouchStart, + handleTouchMove, + handleTouchEnd + } = useScroller(content, { + enableY: true, + enableX: false, + enableSnap: true, + itemSize: indicatorHeight.value, + friction: new Friction(1e-4), + spring: new Spring(2, 90, 20), + onSnap: (index2) => { + if (!isNaN(index2) && index2 !== state2.current) { + state2.current = index2; + } } - if (typeof this._options.onSnap === "function") { - this._options.onSnap(Math.floor(Math.abs(this._position) / this._itemSize)); + }); + scroller = scrollerOrigin; + useTouchtrack(el, (e2) => { + switch (e2.detail.state) { + case "start": + handleTouchStart(e2); + break; + case "move": + handleTouchMove(e2); + break; + case "end": + case "cancel": + handleTouchEnd(e2); } - } - if (this._shouldDispatchScrollEvent) { - this.dispatchScroll(); - } - this._scrolling = false; + }, true); + useCustomClick(el); + updatesScroller(); }); + return () => { + const defaultSlots = slots.default && slots.default(); + state2.length = flatVNode(defaultSlots).length; + const padding = `${maskSize.value}px 0`; + return createVNode("uni-picker-view-column", { + "ref": rootRef + }, [createVNode("div", { + "onWheel": handleWheel, + "onClick": handleTap, + "class": "uni-picker-view-group" + }, [createVNode("div", mergeProps(scopedAttrsState.attrs, { + "class": ["uni-picker-view-mask", pickerViewProps.maskClass], + "style": `background-size: 100% ${maskSize.value}px;${pickerViewProps.maskStyle}` + }), null, 16), createVNode("div", mergeProps(scopedAttrsState.attrs, { + "class": ["uni-picker-view-indicator", pickerViewProps.indicatorClass], + "style": pickerViewProps.indicatorStyle + }), [createVNode(ResizeSensor, { + "ref": resizeSensorRef, + "onResize": ({ + height + }) => indicatorHeight.value = height + }, null, 8, ["onResize"])], 16), createVNode("div", { + "ref": contentRef, + "class": ["uni-picker-view-content", className], + "style": { + padding + } + }, [defaultSlots], 6)], 40, ["onWheel", "onClick"])], 512); + }; } - onTransitionEnd() { - this._element.style.webkitTransition = ""; - this._element.style.transition = ""; - this._element.removeEventListener("transitionend", this._onTransitionEnd); - if (this._snapping) { - this._snapping = false; - } - this.dispatchScroll(); - } - snap() { - const itemSize = this._itemSize; - const position = this._position % itemSize; - const i = Math.abs(position) > this._itemSize / 2 ? this._position - (itemSize - Math.abs(position)) : this._position - position; - if (this._position !== i) { - this._snapping = true; - this.scrollTo(-i); - if (typeof this._options.onSnap === "function") { - this._options.onSnap(Math.floor(Math.abs(this._position) / this._itemSize)); - } - } - } - scrollTo(position, time) { - if (this._animation) { - this._animation.cancel(); - this._scrolling = false; +}); +const VALUES = { + activeColor: PRIMARY_COLOR, + backgroundColor: "#EBEBEB", + activeMode: "backwards" +}; +const props$o = { + percent: { + type: [Number, String], + default: 0, + validator(value) { + return !isNaN(parseFloat(value)); } - if (typeof position === "number") { - this._position = -position; + }, + showInfo: { + type: [Boolean, String], + default: false + }, + strokeWidth: { + type: [Number, String], + default: 6, + validator(value) { + return !isNaN(parseFloat(value)); } - if (this._position < -this._extent) { - this._position = -this._extent; - } else { - if (this._position > 0) { - this._position = 0; - } + }, + color: { + type: String, + default: VALUES.activeColor + }, + activeColor: { + type: String, + default: VALUES.activeColor + }, + backgroundColor: { + type: String, + default: VALUES.backgroundColor + }, + active: { + type: [Boolean, String], + default: false + }, + activeMode: { + type: String, + default: VALUES.activeMode + }, + duration: { + type: [Number, String], + default: 30, + validator(value) { + return !isNaN(parseFloat(value)); } - const transition = "transform " + (time || 0.2) + "s ease-out"; - this._element.style.webkitTransition = "-webkit-" + transition; - this._element.style.transition = transition; - this.updatePosition(); - this._element.addEventListener("transitionend", this._onTransitionEnd); } - dispatchScroll() { - if (typeof this._options.onScroll === "function" && Math.round(Number(this._lastPos)) !== Math.round(this._position)) { - this._lastPos = this._position; - const event = { - target: { - scrollLeft: this._enableX ? -this._position : 0, - scrollTop: this._enableY ? -this._position : 0, - scrollHeight: this._scrollHeight || this._element.offsetHeight, - scrollWidth: this._scrollWidth || this._element.offsetWidth, - offsetHeight: this._element.parentElement.offsetHeight, - offsetWidth: this._element.parentElement.offsetWidth - } - }; - this._options.onScroll(event); - } - } - update(height, scrollHeight, itemSize) { - let extent = 0; - const position = this._position; - if (this._enableX) { - extent = this._element.childNodes.length ? (scrollHeight || this._element.offsetWidth) - this._element.parentElement.offsetWidth : 0; - this._scrollWidth = scrollHeight; - } else { - extent = this._element.childNodes.length ? (scrollHeight || this._element.offsetHeight) - this._element.parentElement.offsetHeight : 0; - this._scrollHeight = scrollHeight; - } - if (typeof height === "number") { - this._position = -height; - } - if (this._position < -extent) { - this._position = -extent; - } else { - if (this._position > 0) { - this._position = 0; - } - } - this._itemSize = itemSize || this._itemSize; - this.updatePosition(); - if (position !== this._position) { - this.dispatchScroll(); - if (typeof this._options.onSnap === "function") { - this._options.onSnap(Math.floor(Math.abs(this._position) / this._itemSize)); - } - } - this._extent = extent; - this._scroll._extent = extent; +}; +var index$j = /* @__PURE__ */ defineBuiltInComponent({ + name: "Progress", + props: props$o, + setup(props2) { + const state2 = useProgressState(props2); + _activeAnimation(state2, props2); + watch(() => state2.realPercent, (newValue, oldValue) => { + state2.strokeTimer && clearInterval(state2.strokeTimer); + state2.lastPercent = oldValue || 0; + _activeAnimation(state2, props2); + }); + return () => { + const { + showInfo + } = props2; + const { + outerBarStyle, + innerBarStyle, + currentPercent + } = state2; + return createVNode("uni-progress", { + "class": "uni-progress" + }, [createVNode("div", { + "style": outerBarStyle, + "class": "uni-progress-bar" + }, [createVNode("div", { + "style": innerBarStyle, + "class": "uni-progress-inner-bar" + }, null, 4)], 4), showInfo ? createVNode("p", { + "class": "uni-progress-info" + }, [currentPercent + "%"]) : ""]); + }; } - updatePosition() { - let transform = ""; - if (this._enableX) { - transform = "translateX(" + this._position + "px) translateZ(0)"; - } else { - if (this._enableY) { - transform = "translateY(" + this._position + "px) translateZ(0)"; +}); +function useProgressState(props2) { + const currentPercent = ref(0); + const outerBarStyle = computed(() => `background-color: ${props2.backgroundColor}; height: ${props2.strokeWidth}px;`); + const innerBarStyle = computed(() => { + const backgroundColor = props2.color !== VALUES.activeColor && props2.activeColor === VALUES.activeColor ? props2.color : props2.activeColor; + return `width: ${currentPercent.value}%;background-color: ${backgroundColor}`; + }); + const realPercent = computed(() => { + let realValue = parseFloat(props2.percent); + realValue < 0 && (realValue = 0); + realValue > 100 && (realValue = 100); + return realValue; + }); + const state2 = reactive({ + outerBarStyle, + innerBarStyle, + realPercent, + currentPercent, + strokeTimer: 0, + lastPercent: 0 + }); + return state2; +} +function _activeAnimation(state2, props2) { + if (props2.active) { + state2.currentPercent = props2.activeMode === VALUES.activeMode ? 0 : state2.lastPercent; + state2.strokeTimer = setInterval(() => { + if (state2.currentPercent + 1 > state2.realPercent) { + state2.currentPercent = state2.realPercent; + state2.strokeTimer && clearInterval(state2.strokeTimer); + } else { + state2.currentPercent += 1; } - } - this._element.style.webkitTransform = transform; - this._element.style.transform = transform; - } - isScrolling() { - return this._scrolling || this._snapping; + }, parseFloat(props2.duration)); + } else { + state2.currentPercent = state2.realPercent; } } -function useScroller(element, options) { - const touchInfo = { - trackingID: -1, - maxDy: 0, - maxDx: 0 - }; - const scroller = new Scroller(element, options); - function findDelta(event) { - const touchtrackEvent = event; - const mouseEvent = event; - return touchtrackEvent.detail.state === "move" || touchtrackEvent.detail.state === "end" ? { - x: touchtrackEvent.detail.dx, - y: touchtrackEvent.detail.dy - } : { - x: mouseEvent.screenX - touchInfo.x, - y: mouseEvent.screenY - touchInfo.y +const uniRadioGroupKey = PolySymbol(process.env.NODE_ENV !== "production" ? "uniCheckGroup" : "ucg"); +const props$n = { + name: { + type: String, + default: "" + } +}; +var index$i = /* @__PURE__ */ defineBuiltInComponent({ + name: "RadioGroup", + props: props$n, + setup(props2, { + emit: emit2, + slots + }) { + const rootRef = ref(null); + const trigger = useCustomEvent(rootRef, emit2); + useProvideRadioGroup(props2, trigger); + return () => { + return createVNode("uni-radio-group", { + "ref": rootRef + }, [slots.default && slots.default()], 512); }; } - function handleTouchStart(event) { - const touchtrackEvent = event; - const mouseEvent = event; - if (touchtrackEvent.detail.state === "start") { - touchInfo.trackingID = "touch"; - touchInfo.x = touchtrackEvent.detail.x; - touchInfo.y = touchtrackEvent.detail.y; - } else { - touchInfo.trackingID = "mouse"; - touchInfo.x = mouseEvent.screenX; - touchInfo.y = mouseEvent.screenY; - } - touchInfo.maxDx = 0; - touchInfo.maxDy = 0; - touchInfo.historyX = [0]; - touchInfo.historyY = [0]; - touchInfo.historyTime = [ - touchtrackEvent.detail.timeStamp || mouseEvent.timeStamp - ]; - touchInfo.listener = scroller; - if (scroller.onTouchStart) { - scroller.onTouchStart(); +}); +function useProvideRadioGroup(props2, trigger) { + const fields2 = []; + onMounted(() => { + _resetRadioGroupValue(fields2.length - 1); + }); + const getFieldsValue = () => fields2.find((field) => field.value.radioChecked)?.value.value; + provide(uniRadioGroupKey, { + addField(field) { + fields2.push(field); + }, + removeField(field) { + fields2.splice(fields2.indexOf(field), 1); + }, + radioChange($event, field) { + const index2 = fields2.indexOf(field); + _resetRadioGroupValue(index2, true); + trigger("change", $event, { + value: getFieldsValue() + }); } - event.preventDefault(); - } - function handleTouchMove(event) { - const touchtrackEvent = event; - const mouseEvent = event; - if (touchInfo.trackingID !== -1) { - event.preventDefault(); - const delta = findDelta(event); - if (delta) { - for (touchInfo.maxDy = Math.max(touchInfo.maxDy, Math.abs(delta.y)), touchInfo.maxDx = Math.max(touchInfo.maxDx, Math.abs(delta.x)), touchInfo.historyX.push(delta.x), touchInfo.historyY.push(delta.y), touchInfo.historyTime.push(touchtrackEvent.detail.timeStamp || mouseEvent.timeStamp); touchInfo.historyTime.length > 10; ) { - touchInfo.historyTime.shift(); - touchInfo.historyX.shift(); - touchInfo.historyY.shift(); - } - if (touchInfo.listener && touchInfo.listener.onTouchMove) { - touchInfo.listener.onTouchMove(delta.x, delta.y); + }); + const uniForm = inject(uniFormKey, false); + if (uniForm) { + uniForm.addField({ + submit: () => { + let data = ["", null]; + if (props2.name !== "") { + data[0] = props2.name; + data[1] = getFieldsValue(); } + return data; } - } + }); } - function handleTouchEnd(event) { - if (touchInfo.trackingID !== -1) { - event.preventDefault(); - const delta = findDelta(event); - if (delta) { - const listener2 = touchInfo.listener; - touchInfo.trackingID = -1; - touchInfo.listener = null; - const length = touchInfo.historyTime.length; - const o2 = { - x: 0, - y: 0 - }; - if (length > 2) { - for (let i = touchInfo.historyTime.length - 1, time1 = touchInfo.historyTime[i], x = touchInfo.historyX[i], y = touchInfo.historyY[i]; i > 0; ) { - i--; - const time0 = touchInfo.historyTime[i]; - const time = time1 - time0; - if (time > 30 && time < 50) { - o2.x = (x - touchInfo.historyX[i]) / (time / 1e3); - o2.y = (y - touchInfo.historyY[i]) / (time / 1e3); - break; - } - } - } - touchInfo.historyTime = []; - touchInfo.historyX = []; - touchInfo.historyY = []; - if (listener2 && listener2.onTouchEnd) { - listener2.onTouchEnd(delta.x, delta.y, o2); - } - } - } - } - return { - scroller, - handleTouchStart, - handleTouchMove, - handleTouchEnd - }; -} -let scopedIndex = 0; -function useScopedClass(indicatorHeightRef) { - const className = `uni-picker-view-content-${scopedIndex++}`; - function updateStyle2() { - const style = document.createElement("style"); - style.innerText = `.uni-picker-view-content.${className}>*{height: ${indicatorHeightRef.value}px;overflow: hidden;}`; - document.head.appendChild(style); + function setFieldChecked(field, radioChecked) { + field.value = { + radioChecked, + value: field.value.value + }; } - watch(() => indicatorHeightRef.value, updateStyle2); - return className; -} -function useCustomClick(dom) { - const MAX_MOVE = 20; - let x = 0; - let y = 0; - dom.addEventListener("touchstart", (event) => { - const info = event.changedTouches[0]; - x = info.clientX; - y = info.clientY; - }); - dom.addEventListener("touchend", (event) => { - const info = event.changedTouches[0]; - if (Math.abs(info.clientX - x) < MAX_MOVE && Math.abs(info.clientY - y) < MAX_MOVE) { - const options = { - bubbles: true, - cancelable: true, - target: event.target, - currentTarget: event.currentTarget - }; - const customClick = new CustomEvent("click", options); - const props2 = ["screenX", "screenY", "clientX", "clientY", "pageX", "pageY"]; - props2.forEach((key) => { - customClick[key] = info[key]; - }); - event.target.dispatchEvent(customClick); - } - }); -} -var PickerViewColumn = /* @__PURE__ */ defineBuiltInComponent({ - name: "PickerViewColumn", - setup(props2, { - slots, - emit: emit2 - }) { - const rootRef = ref(null); - const contentRef = ref(null); - const getPickerViewColumn = inject("getPickerViewColumn"); - const instance2 = getCurrentInstance(); - const currentRef = getPickerViewColumn ? getPickerViewColumn(instance2) : ref(0); - const pickerViewProps = inject("pickerViewProps"); - const pickerViewState = inject("pickerViewState"); - const indicatorHeight = ref(34); - const resizeSensorRef = ref(null); - onMounted(() => { - const resizeSensor = resizeSensorRef.value; - indicatorHeight.value = resizeSensor.$el.getBoundingClientRect().height; - }); - const maskSize = computed(() => (pickerViewState.height - indicatorHeight.value) / 2); - const { - state: scopedAttrsState - } = useScopedAttrs(); - const className = useScopedClass(indicatorHeight); - let scroller; - const state2 = reactive({ - current: currentRef.value, - length: 0 - }); - function updatesScroller() { - if (scroller) { - nextTick(() => { - let current = Math.min(state2.current, state2.length - 1); - current = Math.max(current, 0); - scroller.update(current * indicatorHeight.value, void 0, indicatorHeight.value); - }); - } - } - watch(() => currentRef.value, (current) => { - if (current !== state2.current) { - state2.current = current; - updatesScroller(); + function _resetRadioGroupValue(key, change) { + fields2.forEach((value, index2) => { + if (index2 === key) { + return; } - }); - watch(() => state2.current, (current) => currentRef.value = current); - watch([() => indicatorHeight.value, () => state2.length, () => pickerViewState.height], updatesScroller); - let oldDeltaY = 0; - function handleWheel(event) { - const deltaY = oldDeltaY + event.deltaY; - if (Math.abs(deltaY) > 10) { - oldDeltaY = 0; - let current = Math.min(state2.current + (deltaY < 0 ? -1 : 1), state2.length - 1); - state2.current = current = Math.max(current, 0); - scroller.scrollTo(current * indicatorHeight.value); + if (change) { + setFieldChecked(fields2[index2], false); } else { - oldDeltaY = deltaY; - } - event.preventDefault(); - } - function handleTap({ - clientY - }) { - const el = rootRef.value; - if (!scroller.isScrolling()) { - const rect = el.getBoundingClientRect(); - const r = clientY - rect.top - pickerViewState.height / 2; - const o2 = indicatorHeight.value / 2; - if (!(Math.abs(r) <= o2)) { - const a2 = Math.ceil((Math.abs(r) - o2) / indicatorHeight.value); - const s = r < 0 ? -a2 : a2; - let current = Math.min(state2.current + s, state2.length - 1); - state2.current = current = Math.max(current, 0); - scroller.scrollTo(current * indicatorHeight.value); - } - } - } - onMounted(() => { - const el = rootRef.value; - const content = contentRef.value; - const { - scroller: scrollerOrigin, - handleTouchStart, - handleTouchMove, - handleTouchEnd - } = useScroller(content, { - enableY: true, - enableX: false, - enableSnap: true, - itemSize: indicatorHeight.value, - friction: new Friction(1e-4), - spring: new Spring(2, 90, 20), - onSnap: (index2) => { - if (!isNaN(index2) && index2 !== state2.current) { - state2.current = index2; + fields2.forEach((v2, i) => { + if (index2 >= i) { + return; } - } - }); - scroller = scrollerOrigin; - useTouchtrack(el, (e2) => { - switch (e2.detail.state) { - case "start": - handleTouchStart(e2); - break; - case "move": - handleTouchMove(e2); - break; - case "end": - case "cancel": - handleTouchEnd(e2); - } - }, true); - useCustomClick(el); - updatesScroller(); + if (fields2[i].value.radioChecked) { + setFieldChecked(fields2[index2], false); + } + }); + } }); - return () => { - const defaultSlots = slots.default && slots.default(); - state2.length = flatVNode(defaultSlots).length; - const padding = `${maskSize.value}px 0`; - return createVNode("uni-picker-view-column", { - "ref": rootRef - }, [createVNode("div", { - "onWheel": handleWheel, - "onClick": handleTap, - "class": "uni-picker-view-group" - }, [createVNode("div", mergeProps(scopedAttrsState.attrs, { - "class": ["uni-picker-view-mask", pickerViewProps.maskClass], - "style": `background-size: 100% ${maskSize.value}px;${pickerViewProps.maskStyle}` - }), null, 16), createVNode("div", mergeProps(scopedAttrsState.attrs, { - "class": ["uni-picker-view-indicator", pickerViewProps.indicatorClass], - "style": pickerViewProps.indicatorStyle - }), [createVNode(ResizeSensor, { - "ref": resizeSensorRef, - "onResize": ({ - height - }) => indicatorHeight.value = height - }, null, 8, ["onResize"])], 16), createVNode("div", { - "ref": contentRef, - "class": ["uni-picker-view-content", className], - "style": { - padding - } - }, [defaultSlots], 6)], 40, ["onWheel", "onClick"])], 512); - }; } -}); -const VALUES = { - activeColor: PRIMARY_COLOR, - backgroundColor: "#EBEBEB", - activeMode: "backwards" -}; -const props$o = { - percent: { - type: [Number, String], - default: 0, - validator(value) { - return !isNaN(parseFloat(value)); - } - }, - showInfo: { + return fields2; +} +const props$m = { + checked: { type: [Boolean, String], default: false }, - strokeWidth: { - type: [Number, String], - default: 6, - validator(value) { - return !isNaN(parseFloat(value)); - } - }, - color: { - type: String, - default: VALUES.activeColor - }, - activeColor: { - type: String, - default: VALUES.activeColor - }, - backgroundColor: { + id: { type: String, - default: VALUES.backgroundColor + default: "" }, - active: { + disabled: { type: [Boolean, String], default: false }, - activeMode: { + color: { type: String, - default: VALUES.activeMode - }, - duration: { - type: [Number, String], - default: 30, - validator(value) { - return !isNaN(parseFloat(value)); - } - } -}; -var index$j = /* @__PURE__ */ defineBuiltInComponent({ - name: "Progress", - props: props$o, - setup(props2) { - const state2 = useProgressState(props2); - _activeAnimation(state2, props2); - watch(() => state2.realPercent, (newValue, oldValue) => { - state2.strokeTimer && clearInterval(state2.strokeTimer); - state2.lastPercent = oldValue || 0; - _activeAnimation(state2, props2); - }); - return () => { - const { - showInfo - } = props2; - const { - outerBarStyle, - innerBarStyle, - currentPercent - } = state2; - return createVNode("uni-progress", { - "class": "uni-progress" - }, [createVNode("div", { - "style": outerBarStyle, - "class": "uni-progress-bar" - }, [createVNode("div", { - "style": innerBarStyle, - "class": "uni-progress-inner-bar" - }, null, 4)], 4), showInfo ? createVNode("p", { - "class": "uni-progress-info" - }, [currentPercent + "%"]) : ""]); - }; - } -}); -function useProgressState(props2) { - const currentPercent = ref(0); - const outerBarStyle = computed(() => `background-color: ${props2.backgroundColor}; height: ${props2.strokeWidth}px;`); - const innerBarStyle = computed(() => { - const backgroundColor = props2.color !== VALUES.activeColor && props2.activeColor === VALUES.activeColor ? props2.color : props2.activeColor; - return `width: ${currentPercent.value}%;background-color: ${backgroundColor}`; - }); - const realPercent = computed(() => { - let realValue = parseFloat(props2.percent); - realValue < 0 && (realValue = 0); - realValue > 100 && (realValue = 100); - return realValue; - }); - const state2 = reactive({ - outerBarStyle, - innerBarStyle, - realPercent, - currentPercent, - strokeTimer: 0, - lastPercent: 0 - }); - return state2; -} -function _activeAnimation(state2, props2) { - if (props2.active) { - state2.currentPercent = props2.activeMode === VALUES.activeMode ? 0 : state2.lastPercent; - state2.strokeTimer = setInterval(() => { - if (state2.currentPercent + 1 > state2.realPercent) { - state2.currentPercent = state2.realPercent; - state2.strokeTimer && clearInterval(state2.strokeTimer); - } else { - state2.currentPercent += 1; - } - }, parseFloat(props2.duration)); - } else { - state2.currentPercent = state2.realPercent; - } -} -const uniRadioGroupKey = PolySymbol(process.env.NODE_ENV !== "production" ? "uniCheckGroup" : "ucg"); -const props$n = { - name: { - type: String, - default: "" - } -}; -var index$i = /* @__PURE__ */ defineBuiltInComponent({ - name: "RadioGroup", - props: props$n, - setup(props2, { - emit: emit2, - slots - }) { - const rootRef = ref(null); - const trigger = useCustomEvent(rootRef, emit2); - useProvideRadioGroup(props2, trigger); - return () => { - return createVNode("uni-radio-group", { - "ref": rootRef - }, [slots.default && slots.default()], 512); - }; - } -}); -function useProvideRadioGroup(props2, trigger) { - const fields2 = []; - onMounted(() => { - _resetRadioGroupValue(fields2.length - 1); - }); - const getFieldsValue = () => fields2.find((field) => field.value.radioChecked)?.value.value; - provide(uniRadioGroupKey, { - addField(field) { - fields2.push(field); - }, - removeField(field) { - fields2.splice(fields2.indexOf(field), 1); - }, - radioChange($event, field) { - const index2 = fields2.indexOf(field); - _resetRadioGroupValue(index2, true); - trigger("change", $event, { - value: getFieldsValue() - }); - } - }); - const uniForm = inject(uniFormKey, false); - if (uniForm) { - uniForm.addField({ - submit: () => { - let data = ["", null]; - if (props2.name !== "") { - data[0] = props2.name; - data[1] = getFieldsValue(); - } - return data; - } - }); - } - function setFieldChecked(field, radioChecked) { - field.value = { - radioChecked, - value: field.value.value - }; - } - function _resetRadioGroupValue(key, change) { - fields2.forEach((value, index2) => { - if (index2 === key) { - return; - } - if (change) { - setFieldChecked(fields2[index2], false); - } else { - fields2.forEach((v2, i) => { - if (index2 >= i) { - return; - } - if (fields2[i].value.radioChecked) { - setFieldChecked(fields2[index2], false); - } - }); - } - }); - } - return fields2; -} -const props$m = { - checked: { - type: [Boolean, String], - default: false - }, - id: { - type: String, - default: "" - }, - disabled: { - type: [Boolean, String], - default: false - }, - color: { - type: String, - default: "#007aff" + default: "#007aff" }, value: { type: String, @@ -8565,1393 +7923,568 @@ var computeController = { return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m); } }; -const props$i = { - indicatorDots: { - type: [Boolean, String], - default: false - }, - vertical: { - type: [Boolean, String], - default: false - }, - autoplay: { - type: [Boolean, String], - default: false - }, - circular: { - type: [Boolean, String], - default: false - }, - interval: { - type: [Number, String], - default: 5e3 - }, - duration: { - type: [Number, String], - default: 500 - }, - current: { - type: [Number, String], - default: 0 - }, - indicatorColor: { - type: String, - default: "" - }, - indicatorActiveColor: { - type: String, - default: "" - }, - previousMargin: { - type: String, - default: "" - }, - nextMargin: { - type: String, - default: "" - }, - currentItemId: { - type: String, - default: "" - }, - skipHiddenItemLayout: { - type: [Boolean, String], - default: false - }, - displayMultipleItems: { - type: [Number, String], - default: 1 - }, - disableTouch: { - type: [Boolean, String], - default: false - } -}; -function upx2pxStr(val) { - if (/\d+[ur]px$/i.test(val)) { - val.replace(/\d+[ur]px$/i, (text2) => { - return `${upx2px(parseFloat(text2))}px`; - }); +var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +var lookup = /* @__PURE__ */ function() { + const lookup2 = new Uint8Array(256); + for (var i = 0; i < chars.length; i++) { + lookup2[chars.charCodeAt(i)] = i; } - return val || ""; -} -function useState$2(props2) { - const interval = computed(() => { - const interval2 = Number(props2.interval); - return isNaN(interval2) ? 5e3 : interval2; - }); - const duration = computed(() => { - const duration2 = Number(props2.duration); - return isNaN(duration2) ? 500 : duration2; - }); - const displayMultipleItems = computed(() => { - const displayMultipleItems2 = Math.round(props2.displayMultipleItems); - return isNaN(displayMultipleItems2) ? 1 : displayMultipleItems2; - }); - const state2 = reactive({ - interval, - duration, - displayMultipleItems, - current: Math.round(props2.current) || 0, - currentItemId: props2.currentItemId, - userTracking: false - }); - return state2; + return lookup2; +}(); +function encode$1(arraybuffer) { + var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = ""; + for (i = 0; i < len; i += 3) { + base64 += chars[bytes[i] >> 2]; + base64 += chars[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4]; + base64 += chars[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6]; + base64 += chars[bytes[i + 2] & 63]; + } + if (len % 3 === 2) { + base64 = base64.substring(0, base64.length - 1) + "="; + } else if (len % 3 === 1) { + base64 = base64.substring(0, base64.length - 2) + "=="; + } + return base64; } -function useLayout(props2, state2, swiperContexts, slideFrameRef, emit2, trigger) { - function cancelSchedule() { - if (timer) { - clearTimeout(timer); - timer = null; +function decode(base64) { + var bufferLength = base64.length * 0.75, len = base64.length, i, p2 = 0, encoded1, encoded2, encoded3, encoded4; + if (base64[base64.length - 1] === "=") { + bufferLength--; + if (base64[base64.length - 2] === "=") { + bufferLength--; } } - let timer = null; - let invalid = true; - let viewportPosition = 0; - let viewportMoveRatio = 1; - let animating = null; - let requestedAnimation = false; - let contentTrackViewport = 0; - let transitionStart; - let currentChangeSource = ""; - let animationFrame; - const circularEnabled = computed(() => props2.circular && swiperContexts.value.length > state2.displayMultipleItems); - function checkCircularLayout(index2) { - if (!invalid) { - for (let items = swiperContexts.value, n = items.length, i = index2 + state2.displayMultipleItems, r = 0; r < n; r++) { - const item = items[r]; - const s = Math.floor(index2 / n) * n + r; - const l = s + n; - const c = s - n; - const u = Math.max(index2 - (s + 1), s - i, 0); - const d = Math.max(index2 - (l + 1), l - i, 0); - const h = Math.max(index2 - (c + 1), c - i, 0); - const p2 = Math.min(u, d, h); - const position = [s, l, c][[u, d, h].indexOf(p2)]; - item.updatePosition(position, props2.vertical); - } - } + var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer); + for (i = 0; i < len; i += 4) { + encoded1 = lookup[base64.charCodeAt(i)]; + encoded2 = lookup[base64.charCodeAt(i + 1)]; + encoded3 = lookup[base64.charCodeAt(i + 2)]; + encoded4 = lookup[base64.charCodeAt(i + 3)]; + bytes[p2++] = encoded1 << 2 | encoded2 >> 4; + bytes[p2++] = (encoded2 & 15) << 4 | encoded3 >> 2; + bytes[p2++] = (encoded3 & 3) << 6 | encoded4 & 63; } - function updateViewport(index2) { - if (!(Math.floor(2 * viewportPosition) === Math.floor(2 * index2) && Math.ceil(2 * viewportPosition) === Math.ceil(2 * index2))) { - if (circularEnabled.value) { - checkCircularLayout(index2); - } - } - const x = props2.vertical ? "0" : 100 * -index2 * viewportMoveRatio + "%"; - const y = props2.vertical ? 100 * -index2 * viewportMoveRatio + "%" : "0"; - const transform = "translate(" + x + ", " + y + ") translateZ(0)"; - const slideFrame = slideFrameRef.value; - if (slideFrame) { - slideFrame.style.webkitTransform = transform; - slideFrame.style.transform = transform; - } - viewportPosition = index2; - if (!transitionStart) { - if (index2 % 1 === 0) { - return; - } - transitionStart = index2; - } - index2 -= Math.floor(transitionStart); - const items = swiperContexts.value; - if (index2 <= -(items.length - 1)) { - index2 += items.length; - } else if (index2 >= items.length) { - index2 -= items.length; + 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]; + } + return str; +} +function elemsInArray(strArr, optionalVal) { + if (!isArray(strArr) || strArr.length === 0 || strArr.find((val) => optionalVal.indexOf(val) === -1)) { + return optionalVal; + } + return strArr; +} +function validateProtocolFail(name, msg) { + console.warn(`${name}: ${msg}`); +} +function validateProtocol(name, data, protocol, onFail) { + if (!onFail) { + onFail = validateProtocolFail; + } + for (const key in protocol) { + const errMsg = validateProp(key, data[key], protocol[key], !hasOwn(data, key)); + if (isString(errMsg)) { + onFail(name, errMsg); } - index2 = transitionStart % 1 > 0.5 || transitionStart < 0 ? index2 - 1 : index2; - trigger("transition", {}, { - dx: props2.vertical ? 0 : index2 * slideFrame.offsetWidth, - dy: props2.vertical ? index2 * slideFrame.offsetHeight : 0 - }); } - function endViewportAnimation() { - if (animating) { - updateViewport(animating.toPos); - animating = null; +} +function validateProtocols(name, args, protocol, onFail) { + if (!protocol) { + return; + } + if (!isArray(protocol)) { + return validateProtocol(name, args[0] || Object.create(null), protocol, onFail); + } + const len = protocol.length; + const argsLen = args.length; + for (let i = 0; i < len; i++) { + const opts = protocol[i]; + const data = Object.create(null); + if (argsLen > i) { + data[opts.name] = args[i]; } + validateProtocol(name, data, {[opts.name]: opts}, onFail); } - function normalizeCurrentValue(current) { - const length = swiperContexts.value.length; - if (!length) { - return -1; +} +function validateProp(name, value, prop, isAbsent) { + if (!isPlainObject(prop)) { + prop = {type: prop}; + } + const {type, required, validator: validator2} = 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 i = 0; i < types.length && !isValid; i++) { + const {valid, expectedType} = assertType(value, types[i]); + expectedTypes.push(expectedType || ""); + isValid = valid; } - const index2 = (Math.round(current) % length + length) % length; - if (circularEnabled.value) { - if (length <= state2.displayMultipleItems) { - return 0; - } - } else if (index2 > length - state2.displayMultipleItems) { - return length - state2.displayMultipleItems; + if (!isValid) { + return getInvalidTypeMessage(name, value, expectedTypes); } - return index2; } - function cancelViewportAnimation() { - animating = null; + if (validator2) { + return validator2(value); } - function animateFrameFuncProto() { - if (!animating) { - requestedAnimation = false; - return; +} +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; } - const _animating = animating; - const toPos = _animating.toPos; - const acc = _animating.acc; - const endTime = _animating.endTime; - const source = _animating.source; - const time = endTime - Date.now(); - if (time <= 0) { - updateViewport(toPos); - animating = null; - requestedAnimation = false; - transitionStart = null; - const item = swiperContexts.value[state2.current]; - if (item) { - const currentItemId = item.getItemId(); - trigger("animationfinish", {}, { - current: state2.current, - currentItemId, - source - }); - } - return; + } else if (expectedType === "Object") { + valid = isObject(value); + } else if (expectedType === "Array") { + valid = isArray(value); + } else { + { + valid = value instanceof type; } - const s = acc * time * time / 2; - const l = toPos + s; - updateViewport(l); - animationFrame = requestAnimationFrame(animateFrameFuncProto); } - function animateViewport(current, source, n) { - cancelViewportAnimation(); - const duration = state2.duration; - const length = swiperContexts.value.length; - let position = viewportPosition; - if (circularEnabled.value) { - if (n < 0) { - for (; position < current; ) { - position += length; - } - for (; position - length > current; ) { - position -= length; - } - } else if (n > 0) { - for (; position > current; ) { - position -= length; - } - for (; position + length < current; ) { - position += length; - } - } else { - for (; position + length < current; ) { - position += length; - } - for (; position - length > current; ) { - position -= length; - } - if (position + length - current < current - position) { - position += length; - } - } - } - animating = { - toPos: current, - acc: 2 * (position - current) / (duration * duration), - endTime: Date.now() + duration, - source - }; - if (!requestedAnimation) { - requestedAnimation = true; - animationFrame = requestAnimationFrame(animateFrameFuncProto); - } + 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}`; } - function scheduleAutoplay() { - cancelSchedule(); - const items = swiperContexts.value; - const callback = function() { - timer = null; - currentChangeSource = "autoplay"; - if (circularEnabled.value) { - state2.current = normalizeCurrentValue(state2.current + 1); - } else { - state2.current = state2.current + state2.displayMultipleItems < items.length ? state2.current + 1 : 0; - } - animateViewport(state2.current, "autoplay", circularEnabled.value ? 1 : 0); - timer = setTimeout(callback, state2.interval); - }; - if (!(invalid || items.length <= state2.displayMultipleItems)) { - timer = setTimeout(callback, state2.interval); - } + message += `, got ${receivedType} `; + if (isExplicable(receivedType)) { + message += `with value ${receivedValue}.`; } - function resetLayout() { - cancelSchedule(); - endViewportAnimation(); - const items = swiperContexts.value; - for (let i = 0; i < items.length; i++) { - items[i].updatePosition(i, props2.vertical); - } - viewportMoveRatio = 1; - const slideFrameEl = slideFrameRef.value; - if (state2.displayMultipleItems === 1 && items.length) { - const itemRect = items[0].getBoundingClientRect(); - const slideFrameRect = slideFrameEl.getBoundingClientRect(); - viewportMoveRatio = itemRect.width / slideFrameRect.width; - if (!(viewportMoveRatio > 0 && viewportMoveRatio < 1)) { - viewportMoveRatio = 1; - } + 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); } - const position = viewportPosition; - viewportPosition = -2; - const current = state2.current; - if (current >= 0) { - invalid = false; - if (state2.userTracking) { - updateViewport(position + current - contentTrackViewport); - contentTrackViewport = current; - } else { - updateViewport(current); - if (props2.autoplay) { - scheduleAutoplay(); - } + }; +} +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]; } - } else { - invalid = true; - updateViewport(-state2.displayMultipleItems - 1); + return opts.callback(res, extras); } } - watch([() => props2.current, () => props2.currentItemId, () => [...swiperContexts.value]], () => { - let current = -1; - if (props2.currentItemId) { - for (let i = 0, items = swiperContexts.value; i < items.length; i++) { - const itemId = items[i].getItemId(); - if (itemId === props2.currentItemId) { - current = i; - break; - } - } - } - if (current < 0) { - current = Math.round(props2.current) || 0; + return res; +} +function findInvokeCallbackByName(name) { + for (const key in invokeCallbacks) { + if (invokeCallbacks[key].name === name) { + return true; } - current = current < 0 ? 0 : current; - if (state2.current !== current) { - currentChangeSource = ""; - state2.current = current; + } + 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]; } - }); - watch([() => props2.vertical, () => circularEnabled.value, () => state2.displayMultipleItems, () => [...swiperContexts.value]], resetLayout); - watch(() => state2.interval, () => { - if (timer) { - cancelSchedule(); - scheduleAutoplay(); + } +} +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 currentChanged(current, history2) { - const source = currentChangeSource; - currentChangeSource = ""; - const items = swiperContexts.value; - if (!source) { - const length = items.length; - animateViewport(current, "", circularEnabled.value && history2 + (length - current) % length > length / 2 ? 1 : 0); - } - const item = items[current]; - if (item) { - const currentItemId = state2.currentItemId = item.getItemId(); - trigger("change", {}, { - current: state2.current, - currentItemId, - source - }); +} +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]; } } - watch(() => state2.current, (val, oldVal) => { - currentChanged(val, oldVal); - emit2("update:current", val); - }); - watch(() => state2.currentItemId, (val) => { - emit2("update:currentItemId", val); - }); - function inintAutoplay(enable) { - if (enable) { - scheduleAutoplay(); - } else { - cancelSchedule(); - } + return apiCallbacks; +} +function normalizeErrMsg(errMsg, name) { + if (!errMsg || errMsg.indexOf(":fail") === -1) { + return name + ":ok"; } - watch(() => props2.autoplay && !state2.userTracking, inintAutoplay); - inintAutoplay(props2.autoplay && !state2.userTracking); - onMounted(() => { - let userDirectionChecked = false; - let contentTrackSpeed = 0; - let contentTrackT = 0; - function handleTrackStart() { - cancelSchedule(); - contentTrackViewport = viewportPosition; - contentTrackSpeed = 0; - contentTrackT = Date.now(); - cancelViewportAnimation(); - } - function handleTrackMove(data) { - const oldContentTrackT = contentTrackT; - contentTrackT = Date.now(); - const length = swiperContexts.value.length; - const other = length - state2.displayMultipleItems; - function calc2(val) { - return 0.5 - 0.25 / (val + 0.5); - } - function move(oldVal, newVal) { - let val = contentTrackViewport + oldVal; - contentTrackSpeed = 0.6 * contentTrackSpeed + 0.4 * newVal; - if (!circularEnabled.value) { - if (val < 0 || val > other) { - if (val < 0) { - val = -calc2(-val); - } else { - if (val > other) { - val = other + calc2(val - other); - } - } - contentTrackSpeed = 0; - } - } - updateViewport(val); - } - const time = contentTrackT - oldContentTrackT || 1; - const slideFrameEl = slideFrameRef.value; - if (props2.vertical) { - move(-data.dy / slideFrameEl.offsetHeight, -data.ddy / time); - } else { - move(-data.dx / slideFrameEl.offsetWidth, -data.ddx / time); - } - } - function handleTrackEnd(isCancel) { - state2.userTracking = false; - const t2 = contentTrackSpeed / Math.abs(contentTrackSpeed); - let n = 0; - if (!isCancel && Math.abs(contentTrackSpeed) > 0.2) { - n = 0.5 * t2; - } - const current = normalizeCurrentValue(viewportPosition + n); - if (isCancel) { - updateViewport(contentTrackViewport); - } else { - currentChangeSource = "touch"; - state2.current = current; - animateViewport(current, "touch", n !== 0 ? n : current === 0 && circularEnabled.value && viewportPosition >= 1 ? 1 : 0); - } + 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); } - useTouchtrack(slideFrameRef.value, (event) => { - if (props2.disableTouch) { - return; - } - if (!invalid) { - if (event.detail.state === "start") { - state2.userTracking = true; - userDirectionChecked = false; - return handleTrackStart(); - } - if (event.detail.state === "end") { - return handleTrackEnd(false); - } - if (event.detail.state === "cancel") { - return handleTrackEnd(true); - } - if (state2.userTracking) { - if (!userDirectionChecked) { - userDirectionChecked = true; - const t2 = Math.abs(event.detail.dx); - const n = Math.abs(event.detail.dy); - if (t2 >= n && props2.vertical) { - state2.userTracking = false; - } else { - if (t2 <= n && !props2.vertical) { - state2.userTracking = false; - } - } - if (!state2.userTracking) { - if (props2.autoplay) { - scheduleAutoplay(); - } - return; - } - } - handleTrackMove(event.detail); - return false; - } - } - }); - }); - onUnmounted(() => { - cancelSchedule(); - cancelAnimationFrame(animationFrame); + hasComplete && complete(res); }); - function onSwiperDotClick(index2) { - animateViewport(state2.current = index2, currentChangeSource = "click", circularEnabled.value ? 1 : 0); + return callbackId; +} +const callbacks$1 = [API_SUCCESS, API_FAIL, API_COMPLETE]; +function hasCallback(args) { + if (isPlainObject(args) && callbacks$1.find((cb) => isFunction(args[cb]))) { + return true; } - return { - onSwiperDotClick + 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); + } + return handlePromise(new Promise((resolve, reject) => { + fn(extend(args, {success: resolve, fail: reject})); + })); }; } -var Swiper = /* @__PURE__ */ defineBuiltInComponent({ - name: "Swiper", - props: props$i, - emits: ["change", "transition", "animationfinish", "update:current", "update:currentItemId"], - setup(props2, { - slots, - emit: emit2 - }) { - const rootRef = ref(null); - const trigger = useCustomEvent(rootRef, emit2); - const slidesWrapperRef = ref(null); - const slideFrameRef = ref(null); - const state2 = useState$2(props2); - const slidesStyle = computed(() => { - let style = {}; - if (props2.nextMargin || props2.previousMargin) { - style = props2.vertical ? { - left: 0, - right: 0, - top: upx2pxStr(props2.previousMargin), - bottom: upx2pxStr(props2.nextMargin) - } : { - top: 0, - bottom: 0, - left: upx2pxStr(props2.previousMargin), - right: upx2pxStr(props2.nextMargin) - }; +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 i = 0; i < keys.length; i++) { + const name = keys[i]; + const formatterOrDefaultValue = formatArgs[name]; + if (isFunction(formatterOrDefaultValue)) { + const errMsg = formatterOrDefaultValue(args[0][name], params); + if (isString(errMsg)) { + return errMsg; } - return style; - }); - const slideFrameStyle = computed(() => { - const value = Math.abs(100 / state2.displayMultipleItems) + "%"; - return { - width: props2.vertical ? "100%" : value, - height: !props2.vertical ? "100%" : value - }; - }); - let swiperItems = []; - const originSwiperContexts = []; - const swiperContexts = ref([]); - function updateSwiperContexts() { - const contexts = []; - for (let index2 = 0; index2 < swiperItems.length; index2++) { - const swiperItem = swiperItems[index2]; - const swiperContext = originSwiperContexts.find((context) => swiperItem.el === context.rootRef.value); - if (swiperContext) { - contexts.push(markRaw(swiperContext)); - } + } else { + if (!hasOwn(params, name)) { + params[name] = formatterOrDefaultValue; } - swiperContexts.value = contexts; } - const addSwiperContext = function(swiperContext) { - originSwiperContexts.push(swiperContext); - updateSwiperContexts(); - }; - provide("addSwiperContext", addSwiperContext); - const removeSwiperContext = function(swiperContext) { - const index2 = originSwiperContexts.indexOf(swiperContext); - if (index2 >= 0) { - originSwiperContexts.splice(index2, 1); - updateSwiperContexts(); - } - }; - provide("removeSwiperContext", removeSwiperContext); - const { - onSwiperDotClick - } = useLayout(props2, state2, swiperContexts, slideFrameRef, emit2, trigger); - return () => { - const defaultSlots = slots.default && slots.default(); - swiperItems = flatVNode(defaultSlots); - return createVNode("uni-swiper", { - "ref": rootRef - }, [createVNode("div", { - "ref": slidesWrapperRef, - "class": "uni-swiper-wrapper" - }, [createVNode("div", { - "class": "uni-swiper-slides", - "style": slidesStyle.value - }, [createVNode("div", { - "ref": slideFrameRef, - "class": "uni-swiper-slide-frame", - "style": slideFrameStyle.value - }, [defaultSlots], 4)], 4), props2.indicatorDots && createVNode("div", { - "class": ["uni-swiper-dots", props2.vertical ? "uni-swiper-dots-vertical" : "uni-swiper-dots-horizontal"] - }, [swiperContexts.value.map((_, index2, array) => createVNode("div", { - "onClick": () => onSwiperDotClick(index2), - "class": { - "uni-swiper-dot": true, - "uni-swiper-dot-active": index2 < state2.current + state2.displayMultipleItems && index2 >= state2.current || index2 < state2.current + state2.displayMultipleItems - array.length - }, - "style": { - background: index2 === state2.current ? props2.indicatorActiveColor : props2.indicatorColor - } - }, null, 14, ["onClick"]))], 2)], 512)], 512); - }; } -}); -const props$h = { - itemId: { - type: String, - default: "" +} +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); } -}; -var SwiperItem = /* @__PURE__ */ defineBuiltInComponent({ - name: "SwiperItem", - props: props$h, - setup(props2, { - slots - }) { - const rootRef = ref(null); - const context = { - rootRef, - getItemId() { - return props2.itemId; - }, - getBoundingClientRect() { - const el = rootRef.value; - return el.getBoundingClientRect(); - }, - updatePosition(position, vertical) { - const x = vertical ? "0" : 100 * position + "%"; - const y = vertical ? 100 * position + "%" : "0"; - const rootEl = rootRef.value; - const value = `translate(${x},${y}) translateZ(0)`; - if (rootEl) { - rootEl.style.webkitTransform = value; - rootEl.style.transform = value; - } - } - }; - onMounted(() => { - const addSwiperContext = inject("addSwiperContext"); - if (addSwiperContext) { - addSwiperContext(context); - } - }); - onUnmounted(() => { - const removeSwiperContext = inject("removeSwiperContext"); - if (removeSwiperContext) { - removeSwiperContext(context); - } - }); - return () => { - return createVNode("uni-swiper-item", { - "ref": rootRef, - "style": { - position: "absolute", - width: "100%", - height: "100%" - } - }, [slots.default && slots.default()], 512); - }; + if (options && options.beforeInvoke) { + const errMsg2 = options.beforeInvoke(args); + if (isString(errMsg2)) { + return errMsg2; + } } -}); -const props$g = { - name: { - type: String, - default: "" - }, - checked: { - type: [Boolean, String], - default: false - }, - type: { - type: String, - default: "switch" - }, - id: { - type: String, - default: "" - }, - disabled: { - type: [Boolean, String], - default: false - }, - color: { - type: String, - default: "#007aff" + const errMsg = formatApiArgs(args, options); + if (errMsg) { + return errMsg; } -}; -var index$e = /* @__PURE__ */ defineBuiltInComponent({ - name: "Switch", - props: props$g, - emits: ["change"], - setup(props2, { - emit: emit2 - }) { - const rootRef = ref(null); - const switchChecked = ref(props2.checked); - const uniLabel = useSwitchInject(props2, switchChecked); - const trigger = useCustomEvent(rootRef, emit2); - watch(() => props2.checked, (val) => { - switchChecked.value = val; - }); - const _onClick = ($event) => { - if (props2.disabled) { - return; - } - switchChecked.value = !switchChecked.value; - trigger("change", $event, { - value: switchChecked.value - }); - }; - if (!!uniLabel) { - uniLabel.addHandler(_onClick); - onBeforeUnmount(() => { - uniLabel.removeHandler(_onClick); - }); - } - useListeners$1(props2, { - "label-click": _onClick - }); - return () => { - const { - color, - type - } = props2; - const { - booleanAttrs - } = useBooleanAttr(props2, "disabled"); - return createVNode("uni-switch", mergeProps({ - "ref": rootRef - }, booleanAttrs, { - "onClick": _onClick - }), [createVNode("div", { - "class": "uni-switch-wrapper" - }, [withDirectives(createVNode("div", { - "class": ["uni-switch-input", [switchChecked.value ? "uni-switch-input-checked" : ""]], - "style": { - backgroundColor: switchChecked.value ? color : "#DFDFDF", - borderColor: switchChecked.value ? color : "#DFDFDF" - } - }, null, 6), [[vShow, type === "switch"]]), withDirectives(createVNode("div", { - "class": "uni-checkbox-input" - }, [switchChecked.value ? createSvgIconVNode(ICON_PATH_SUCCESS_NO_CIRCLE, props2.color, 22) : ""], 512), [[vShow, type === "checkbox"]])])], 16, ["onClick"]); - }; +} +function checkCallback(callback) { + if (!isFunction(callback)) { + throw new Error('Invalid args: type check failed for args "callback". Expected Function'); } -}); -function useSwitchInject(props2, switchChecked) { - const uniForm = inject(uniFormKey, false); - const uniLabel = inject(uniLabelKey, false); - const formField = { - submit: () => { - const data = ["", null]; - if (props2.name) { - data[0] = props2.name; - data[1] = switchChecked.value; - } - return data; - }, - reset: () => { - switchChecked.value = false; +} +function wrapperOnApi(name, fn, options) { + return (callback) => { + checkCallback(callback); + const errMsg = beforeInvokeApi(name, [callback], void 0, options); + if (errMsg) { + throw new Error(errMsg); + } + const isFirstInvokeOnApi = !findInvokeCallbackByName(name); + createKeepAliveApiCallback(name, callback); + if (isFirstInvokeOnApi) { + onKeepAliveApiCallback(name); + fn(); } }; - if (!!uniForm) { - uniForm.addField(formField); - onUnmounted(() => { - uniForm.removeField(formField); - }); - } - return uniLabel; } -const SPACE_UNICODE = { - ensp: "\u2002", - emsp: "\u2003", - nbsp: "\xA0" -}; -function normalizeText(text2, { - space, - decode: decode2 -}) { - if (space && SPACE_UNICODE[space]) { - text2 = text2.replace(/ /g, SPACE_UNICODE[space]); - } - if (!decode2) { - return text2; - } - return text2.replace(/ /g, SPACE_UNICODE.nbsp).replace(/ /g, SPACE_UNICODE.ensp).replace(/ /g, SPACE_UNICODE.emsp).replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&").replace(/"/g, '"').replace(/'/g, "'"); +function wrapperOffApi(name, fn, options) { + return (callback) => { + checkCallback(callback); + const errMsg = beforeInvokeApi(name, [callback], void 0, options); + if (errMsg) { + throw new Error(errMsg); + } + name = name.replace("off", "on"); + removeKeepAliveApiCallback(name, callback); + const hasInvokeOnApi = findInvokeCallbackByName(name); + if (!hasInvokeOnApi) { + offKeepAliveApiCallback(name); + fn(); + } + }; } -var index$d = /* @__PURE__ */ defineBuiltInComponent({ - name: "Text", - props: { - selectable: { - type: [Boolean, String], - default: false - }, - space: { - type: String, - default: "" - }, - decode: { - type: [Boolean, String], - default: false +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); } - }, - setup(props2, { - slots - }) { - return () => { - const children = []; - if (slots.default) { - slots.default().forEach((vnode) => { - if (vnode.shapeFlag & 8) { - const lines = vnode.children.replace(/\\n/g, "\n").split("\n"); - const len = lines.length - 1; - lines.forEach((text2, index2) => { - if (index2 === 0 && !text2) - ; - else { - children.push(createTextVNode(normalizeText(text2, { - space: props2.space, - decode: props2.decode - }))); - } - if (index2 !== len) { - children.push(createVNode("br")); - } - }); - } else { - if (process.env.NODE_ENV !== "production" && vnode.shapeFlag & 6 && vnode.type.name !== "Text") { - console.warn("Do not nest other components in the text component, as there may be display differences on different platforms."); - } - children.push(vnode); - } - }); - } - return createVNode("uni-text", { - "selectable": props2.selectable ? true : null - }, [createVNode("span", null, children)], 8, ["selectable"]); - }; - } -}); -const props$f = /* @__PURE__ */ extend({}, props$u, { - placeholderClass: { - type: String, - default: "input-placeholder" - }, - autoHeight: { - type: [Boolean, String], - default: false - }, - confirmType: { - type: String, - default: "" - } -}); -var index$c = /* @__PURE__ */ defineBuiltInComponent({ - name: "Textarea", - props: props$f, - emit: ["confirm", "linechange", ...emit], - setup(props2, { - emit: emit2 - }) { - const rootRef = ref(null); - const { - fieldRef, - state: state2, - scopedAttrsState, - fixDisabledColor, - trigger - } = useField(props2, rootRef, emit2); - const valueCompute = computed(() => state2.value.split("\n")); - const isDone = computed(() => ["done", "go", "next", "search", "send"].includes(props2.confirmType)); - const heightRef = ref(0); - const lineRef = ref(null); - watch(() => heightRef.value, (height) => { - const el = rootRef.value; - const lineEl = lineRef.value; - let lineHeight = parseFloat(getComputedStyle(el).lineHeight); - if (isNaN(lineHeight)) { - lineHeight = lineEl.offsetHeight; - } - var lineCount = Math.round(height / lineHeight); - trigger("linechange", {}, { - height, - heightRpx: 750 / window.innerWidth * height, - lineCount - }); - if (props2.autoHeight) { - el.style.height = height + "px"; - } + return fn(args, { + resolve: (res) => invokeSuccess(id2, name, res), + reject: (err) => invokeFail(id2, name, err) }); - function onResize2({ - height - }) { - heightRef.value = height; - } - function confirm(event) { - trigger("confirm", event, { - value: state2.value - }); - } - function onKeyDownEnter(event) { - if (event.key !== "Enter") { - return; - } - if (isDone.value) { - event.preventDefault(); - } - } - function onKeyUpEnter(event) { - if (event.key !== "Enter") { - return; - } - if (isDone.value) { - confirm(event); - const textarea = event.target; - textarea.blur(); - } + }; +} +function wrapperSyncApi(name, fn, protocol, options) { + return (...args) => { + const errMsg = beforeInvokeApi(name, args, protocol, options); + if (errMsg) { + throw new Error(errMsg); } - const DARK_TEST_STRING = "(prefers-color-scheme: dark)"; - const fixMargin = String(navigator.platform).indexOf("iP") === 0 && String(navigator.vendor).indexOf("Apple") === 0 && window.matchMedia(DARK_TEST_STRING).media !== DARK_TEST_STRING; - return () => { - let textareaNode = props2.disabled && fixDisabledColor ? createVNode("textarea", { - "ref": fieldRef, - "value": state2.value, - "tabindex": "-1", - "readonly": !!props2.disabled, - "maxlength": state2.maxlength, - "class": { - "uni-textarea-textarea": true, - "uni-textarea-textarea-fix-margin": fixMargin - }, - "style": { - overflowY: props2.autoHeight ? "hidden" : "auto" - }, - "onFocus": (event) => event.target.blur() - }, null, 46, ["value", "readonly", "maxlength", "onFocus"]) : createVNode("textarea", { - "ref": fieldRef, - "value": state2.value, - "disabled": !!props2.disabled, - "maxlength": state2.maxlength, - "enterkeyhint": props2.confirmType, - "class": { - "uni-textarea-textarea": true, - "uni-textarea-textarea-fix-margin": fixMargin - }, - "style": { - overflowY: props2.autoHeight ? "hidden" : "auto" - }, - "onKeydown": onKeyDownEnter, - "onKeyup": onKeyUpEnter - }, null, 46, ["value", "disabled", "maxlength", "enterkeyhint", "onKeydown", "onKeyup"]); - return createVNode("uni-textarea", { - "ref": rootRef - }, [createVNode("div", { - "class": "uni-textarea-wrapper" - }, [withDirectives(createVNode("div", mergeProps(scopedAttrsState.attrs, { - "style": props2.placeholderStyle, - "class": ["uni-textarea-placeholder", props2.placeholderClass] - }), [props2.placeholder], 16), [[vShow, !state2.value.length]]), createVNode("div", { - "ref": lineRef, - "class": "uni-textarea-line" - }, [" "], 512), createVNode("div", { - "class": "uni-textarea-compute" - }, [valueCompute.value.map((item) => createVNode("div", null, [item.trim() ? item : "."])), createVNode(ResizeSensor, { - "initial": true, - "onResize": onResize2 - }, null, 8, ["initial", "onResize"])]), props2.confirmType === "search" ? createVNode("form", { - "action": "", - "onSubmit": () => false, - "class": "uni-input-form" - }, [textareaNode], 40, ["onSubmit"]) : textareaNode])], 512); - }; - } -}); -var index$b = /* @__PURE__ */ defineBuiltInComponent({ - name: "View", - props: extend({}, hoverProps), - setup(props2, { - slots - }) { - const { - hovering, - binding - } = useHover(props2); - return () => { - const hoverClass = props2.hoverClass; - if (hoverClass && hoverClass !== "none") { - return createVNode("uni-view", mergeProps({ - "class": hovering.value ? hoverClass : "" - }, binding), [slots.default && slots.default()], 16); - } - return createVNode("uni-view", null, [slots.default && slots.default()]); - }; - } -}); -function normalizeEvent(pageId, vm, id2) { - if (!id2) { - id2 = vm.id; - } - if (!id2) { - return; - } - return pageId + "." + vm.$options.name.toLowerCase() + "." + id2; + return fn.apply(null, args); + }; } -function addSubscribe(name, callback) { - if (!name) { - return; - } - UniViewJSBridge.subscribe(name, ({type, data}) => { - callback(type, data); - }); +function wrapperAsyncApi(name, fn, protocol, options) { + return wrapperTaskApi(name, fn, protocol, options); } -function removeSubscribe(name) { - if (!name) { - return; - } - UniViewJSBridge.unsubscribe(name); +function defineOnApi(name, fn, options) { + return wrapperOnApi(name, fn, options); } -function useSubscribe(callback, name, multiple) { - const instance2 = getCurrentInstance(); - const vm = instance2.proxy; - const pageId = multiple || !name ? useCurrentPageId() : 0; - onMounted(() => { - addSubscribe(name || normalizeEvent(pageId, vm), callback); - if (multiple || !name) { - watch(() => vm.id, (value, oldValue) => { - addSubscribe(normalizeEvent(pageId, vm, value), callback); - removeSubscribe(oldValue && normalizeEvent(pageId, vm, oldValue)); - }); - } - }); - onBeforeUnmount(() => { - removeSubscribe(name || normalizeEvent(pageId, vm)); - }); +function defineOffApi(name, fn, options) { + return wrapperOffApi(name, fn, options); } -function useOn(name, callback) { - onMounted(() => UniViewJSBridge.on(name, callback)); - onBeforeUnmount(() => UniViewJSBridge.off(name)); +function defineTaskApi(name, fn, protocol, options) { + return promisify(wrapperTaskApi(name, fn, process.env.NODE_ENV !== "production" ? protocol : void 0, options)); } -let index$a = 0; -function useContextInfo(_id) { - const page = useCurrentPageId(); - const instance2 = getCurrentInstance(); - const vm = instance2.proxy; - const type = vm.$options.name.toLowerCase(); - const id2 = _id || vm.id || `context${index$a++}`; - onMounted(() => { - const el = vm.$el; - el.__uniContextInfo = { - id: id2, - type, - page - }; - }); - return `${page}.${type}.${id2}`; +function defineSyncApi(name, fn, protocol, options) { + return wrapperSyncApi(name, fn, process.env.NODE_ENV !== "production" ? protocol : void 0, options); } -function getContextInfo(el) { - return el.__uniContextInfo; +function defineAsyncApi(name, fn, protocol, options) { + return promisify(wrapperAsyncApi(name, fn, process.env.NODE_ENV !== "production" ? protocol : void 0, options)); } -function getRootInfo(fields2) { - const info = {}; - if (fields2.id) { - info.id = ""; - } - if (fields2.dataset) { - info.dataset = {}; - } - if (fields2.rect) { - info.left = 0; - info.right = 0; - info.top = 0; - info.bottom = 0; +function createUnsupportedMsg(name) { + return `method 'uni.${name}' not supported`; +} +function createUnsupportedSyncApi(name) { + return () => { + console.error(createUnsupportedMsg(name)); + }; +} +const createUnsupportedOnApi = createUnsupportedSyncApi; +function createUnsupportedAsyncApi(name) { + return (_args, {reject}) => { + return reject(createUnsupportedMsg(name)); + }; +} +const API_BASE64_TO_ARRAY_BUFFER = "base64ToArrayBuffer"; +const Base64ToArrayBufferProtocol = [ + { + name: "base64", + type: String, + required: true } - if (fields2.size) { - info.width = document.documentElement.clientWidth; - info.height = document.documentElement.clientHeight; +]; +const API_ARRAY_BUFFER_TO_BASE64 = "arrayBufferToBase64"; +const ArrayBufferToBase64Protocol = [ + { + name: "arrayBuffer", + type: [ArrayBuffer, Uint8Array], + required: true } - if (fields2.scrollOffset) { - const documentElement2 = document.documentElement; - const body = document.body; - info.scrollLeft = documentElement2.scrollLeft || body.scrollLeft || 0; - info.scrollTop = documentElement2.scrollTop || body.scrollTop || 0; - info.scrollHeight = documentElement2.scrollHeight || body.scrollHeight || 0; - info.scrollWidth = documentElement2.scrollWidth || body.scrollWidth || 0; +]; +const base64ToArrayBuffer = /* @__PURE__ */ defineSyncApi(API_BASE64_TO_ARRAY_BUFFER, (base64) => { + return decode(base64); +}, Base64ToArrayBufferProtocol); +const arrayBufferToBase64 = /* @__PURE__ */ 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 info; +]; +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"; } -function getNodeInfo(el, fields2) { - const info = {}; - const {top} = getWindowOffset(); - if (fields2.id) { - info.id = el.id; - } - if (fields2.dataset) { - info.dataset = getCostomDataset(el); +const upx2px = /* @__PURE__ */ defineSyncApi(API_UPX2PX, (number, newDeviceWidth) => { + if (deviceWidth === 0) { + checkDeviceWidth(); } - if (fields2.rect || fields2.size) { - const rect = el.getBoundingClientRect(); - if (fields2.rect) { - info.left = rect.left; - info.right = rect.right; - info.top = rect.top - top; - info.bottom = rect.bottom - top; - } - if (fields2.size) { - info.width = rect.width; - info.height = rect.height; - } + number = Number(number); + if (number === 0) { + return 0; } - if (Array.isArray(fields2.properties)) { - fields2.properties.forEach((prop) => { - prop = prop.replace(/-([a-z])/g, function(e2, t2) { - return t2.toUpperCase(); - }); - }); + let result = number / BASE_DEVICE_WIDTH * (newDeviceWidth || deviceWidth); + if (result < 0) { + result = -result; } - if (fields2.scrollOffset) { - if (el.tagName === "UNI-SCROLL-VIEW") { - const scroll = el.children[0].children[0]; - info.scrollLeft = scroll.scrollLeft; - info.scrollTop = scroll.scrollTop; - info.scrollHeight = scroll.scrollHeight; - info.scrollWidth = scroll.scrollWidth; + result = Math.floor(result + EPS); + if (result === 0) { + if (deviceDPR === 1 || !isIOS) { + result = 1; } else { - info.scrollLeft = 0; - info.scrollTop = 0; - info.scrollHeight = 0; - info.scrollWidth = 0; + result = 0.5; } } - if (Array.isArray(fields2.computedStyle)) { - const sytle = getComputedStyle(el); - fields2.computedStyle.forEach((name) => { - info[name] = sytle[name]; - }); - } - if (fields2.context) { - info.contextInfo = getContextInfo(el); - } - return info; -} -function findElm(component, pageVm) { - return component ? component.$el : pageVm.$el; -} -function getNodesInfo(pageVm, component, selector, single, fields2) { - const parentElement = findElm(component, pageVm).parentElement; - if (!parentElement) { - return single ? null : []; + 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 } - if (single) { - const node = parentElement.querySelector(selector); - if (node) { - return getNodeInfo(node, fields2); - } - return null; - } else { - let infos = []; - const nodeList = parentElement.querySelectorAll(selector); - if (nodeList && nodeList.length) { - [].forEach.call(nodeList, (node) => { - infos.push(getNodeInfo(node, fields2)); - }); +]; +const RemoveInterceptorProtocol = AddInterceptorProtocol; +function mergeInterceptorHook(interceptors, interceptor) { + Object.keys(interceptor).forEach((hook) => { + if (isFunction(interceptor[hook])) { + interceptors[hook] = mergeHook(interceptors[hook], interceptor[hook]); } - return infos; - } + }); } -function requestComponentInfo(page, reqs, callback) { - const result = []; - reqs.forEach(({component, selector, single, fields: fields2}) => { - if (component === null) { - result.push(getRootInfo(fields2)); - } else { - result.push(getNodesInfo(page, component, selector, single, fields2)); +function removeInterceptorHook(interceptors, interceptor) { + if (!interceptors || !interceptor) { + return; + } + Object.keys(interceptor).forEach((hook) => { + if (isFunction(interceptor[hook])) { + removeHook(interceptors[hook], interceptor[hook]); } }); - callback(result); -} -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]; - } +function mergeHook(parentVal, childVal) { + const res = childVal ? parentVal ? parentVal.concat(childVal) : isArray(childVal) ? childVal : [childVal] : parentVal; + return res ? dedupeHooks(res) : res; } -let mediaQueryObserver; -let listener$2; -function handleMediaQueryStr($props) { - const mediaQueryArr = []; - const propsMenu = [ - "width", - "minWidth", - "maxWidth", - "height", - "minHeight", - "maxHeight", - "orientation" - ]; - for (const item of propsMenu) { - if (item !== "orientation" && $props[item] && Number($props[item] >= 0)) { - mediaQueryArr.push(`(${humpToLine(item)}: ${Number($props[item])}px)`); - } - if (item === "orientation" && $props[item]) { - mediaQueryArr.push(`(${humpToLine(item)}: ${$props[item]})`); +function dedupeHooks(hooks) { + const res = []; + for (let i = 0; i < hooks.length; i++) { + if (res.indexOf(hooks[i]) === -1) { + res.push(hooks[i]); } } - const mediaQueryStr = mediaQueryArr.join(" and "); - return mediaQueryStr; -} -function humpToLine(name) { - return name.replace(/([A-Z])/g, "-$1").toLowerCase(); -} -function addMediaQueryObserver({reqId, component, options, callback}, _pageId) { - mediaQueryObserver = window.matchMedia(handleMediaQueryStr(options)); - listener$2 = (observer) => callback(observer.matches); - listener$2(mediaQueryObserver); - mediaQueryObserver.addListener(listener$2); + return res; } -function removeMediaQueryObserver({reqId, component}, _pageId) { - if (mediaQueryObserver) { - mediaQueryObserver.removeListener(listener$2); - } -} -function saveImage(base64, dirname, callback) { - callback(null, base64); -} -const TEMP_PATH = ""; -const files = {}; -function urlToFile(url, local) { - const file = files[url]; - if (file) { - return Promise.resolve(file); - } - if (/^data:[a-z-]+\/[a-z-]+;base64,/.test(url)) { - return Promise.resolve(base64ToFile(url)); - } - if (local) { - return Promise.reject(new Error("not find")); - } - return new Promise((resolve, reject) => { - const xhr = new XMLHttpRequest(); - xhr.open("GET", url, true); - xhr.responseType = "blob"; - xhr.onload = function() { - resolve(this.response); - }; - xhr.onerror = reject; - xhr.send(); - }); -} -function base64ToFile(base64) { - const base64Array = base64.split(","); - const res = base64Array[0].match(/:(.*?);/); - const type = res ? res[1] : ""; - const str = atob(base64Array[1]); - let n = str.length; - const array = new Uint8Array(n); - while (n--) { - array[n] = str.charCodeAt(n); - } - return blobToFile(array, type); -} -function getExtname(type) { - const extname = type.split("/")[1]; - return extname ? `.${extname}` : ""; -} -function getFileName(url) { - url = url.split("#")[0].split("?")[0]; - const array = url.split("/"); - return array[array.length - 1]; -} -function blobToFile(blob, type) { - let file; - if (blob instanceof File) { - file = blob; - } else { - type = type || blob.type || ""; - const filename = `${Date.now()}${getExtname(type)}`; - try { - file = new File([blob], filename, {type}); - } catch (error) { - blob = blob instanceof Blob ? blob : new Blob([blob], {type}); - file = blob; - file.name = file.name || filename; - } - } - return file; -} -function fileToUrl(file) { - for (const key in files) { - if (hasOwn(files, key)) { - const oldFile = files[key]; - if (oldFile === file) { - return key; - } - } - } - var url = (window.URL || window.webkitURL).createObjectURL(file); - files[url] = file; - return url; -} -function getSameOriginUrl(url) { - const a2 = document.createElement("a"); - a2.href = url; - if (a2.origin === location.origin) { - return Promise.resolve(url); - } - return urlToFile(url).then(fileToUrl); -} -function revokeObjectURL(url) { - const URL = window.URL || window.webkitURL; - URL.revokeObjectURL(url); - delete files[url]; -} -const API_UPX2PX = "upx2px"; -const Upx2pxProtocol = [ - { - name: "upx", - type: [Number, String], - required: true - } -]; -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"; -} -const upx2px = /* @__PURE__ */ defineSyncApi(API_UPX2PX, (number, newDeviceWidth) => { - if (deviceWidth === 0) { - checkDeviceWidth(); - } - number = Number(number); - if (number === 0) { - return 0; - } - let result = number / BASE_DEVICE_WIDTH * (newDeviceWidth || deviceWidth); - if (result < 0) { - result = -result; - } - result = Math.floor(result + EPS); - if (result === 0) { - if (deviceDPR === 1 || !isIOS) { - result = 1; - } else { - result = 0.5; - } - } - return number < 0 ? -result : result; -}, 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]); - } - }); -} -function removeInterceptorHook(interceptors, interceptor) { - if (!interceptors || !interceptor) { - return; - } - Object.keys(interceptor).forEach((hook) => { - if (isFunction(interceptor[hook])) { - removeHook(interceptors[hook], interceptor[hook]); - } - }); -} -function mergeHook(parentVal, childVal) { - const res = childVal ? parentVal ? parentVal.concat(childVal) : isArray(childVal) ? childVal : [childVal] : parentVal; - return res ? dedupeHooks(res) : res; -} -function dedupeHooks(hooks) { - const res = []; - for (let i = 0; i < hooks.length; i++) { - if (res.indexOf(hooks[i]) === -1) { - res.push(hooks[i]); - } - } - return res; -} -function removeHook(hooks, hook) { - if (!hooks) { - return; - } - const index2 = hooks.indexOf(hook); - if (index2 !== -1) { - hooks.splice(index2, 1); +function removeHook(hooks, hook) { + if (!hooks) { + return; + } + const index2 = hooks.indexOf(hook); + if (index2 !== -1) { + hooks.splice(index2, 1); } } const addInterceptor = /* @__PURE__ */ defineSyncApi(API_ADD_INTERCEPTOR, (method, interceptor) => { @@ -10455,2452 +8988,3927 @@ const predefinedColor = { yellowgreen: "#9acd32", transparent: "#00000000" }; -function checkColor(e2) { - e2 = e2 || "#000000"; - var t2 = null; - if ((t2 = /^#([0-9|A-F|a-f]{6})$/.exec(e2)) != null) { - const n = parseInt(t2[1].slice(0, 2), 16); - const o2 = parseInt(t2[1].slice(2, 4), 16); - const r = parseInt(t2[1].slice(4), 16); - return [n, o2, r, 255]; +function checkColor(e2) { + e2 = e2 || "#000000"; + var t2 = null; + if ((t2 = /^#([0-9|A-F|a-f]{6})$/.exec(e2)) != null) { + const n = parseInt(t2[1].slice(0, 2), 16); + const o2 = parseInt(t2[1].slice(2, 4), 16); + const r = parseInt(t2[1].slice(4), 16); + return [n, o2, r, 255]; + } + if ((t2 = /^#([0-9|A-F|a-f]{3})$/.exec(e2)) != null) { + let n = t2[1].slice(0, 1); + let o2 = t2[1].slice(1, 2); + let r = t2[1].slice(2, 3); + n = parseInt(n + n, 16); + o2 = parseInt(o2 + o2, 16); + r = parseInt(r + r, 16); + return [n, o2, r, 255]; + } + if ((t2 = /^rgb\((.+)\)$/.exec(e2)) != null) { + return t2[1].split(",").map(function(e22) { + return Math.min(255, parseInt(e22.trim())); + }).concat(255); + } + if ((t2 = /^rgba\((.+)\)$/.exec(e2)) != null) { + return t2[1].split(",").map(function(e22, t22) { + return t22 === 3 ? Math.floor(255 * parseFloat(e22.trim())) : Math.min(255, parseInt(e22.trim())); + }); + } + var i = e2.toLowerCase(); + if (hasOwn(predefinedColor, i)) { + t2 = /^#([0-9|A-F|a-f]{6,8})$/.exec(predefinedColor[i]); + const n = parseInt(t2[1].slice(0, 2), 16); + const o2 = parseInt(t2[1].slice(2, 4), 16); + const r = parseInt(t2[1].slice(4, 6), 16); + let a2 = parseInt(t2[1].slice(6, 8), 16); + a2 = a2 >= 0 ? a2 : 255; + return [n, o2, r, a2]; + } + console.error("unsupported color:" + e2); + return [0, 0, 0, 255]; +} +class CanvasGradient { + constructor(type, data) { + this.type = type; + this.data = data; + this.colorStop = []; + } + addColorStop(position, color) { + this.colorStop.push([position, checkColor(color)]); + } +} +class Pattern { + constructor(image2, repetition) { + this.image = image2; + this.repetition = repetition; + } +} +class TextMetrics { + constructor(width) { + this.width = width; + } +} +class CanvasContext { + constructor(id2, pageId) { + this.id = id2; + this.pageId = pageId; + this.actions = []; + this.path = []; + this.subpath = []; + this.drawingState = []; + this.state = { + lineDash: [0, 0], + shadowOffsetX: 0, + shadowOffsetY: 0, + shadowBlur: 0, + shadowColor: [0, 0, 0, 0], + font: "10px sans-serif", + fontSize: 10, + fontWeight: "normal", + fontStyle: "normal", + fontFamily: "sans-serif" + }; + } + draw(reserve = false, callback) { + var actions = [...this.actions]; + this.actions = []; + this.path = []; + var callbackId; + if (typeof callback === "function") { + callbackId = canvasEventCallbacks.push(callback); + } + operateCanvas(this.id, this.pageId, "actionsChanged", { + actions, + reserve, + callbackId + }); + } + createLinearGradient(x0, y0, x1, y1) { + return new CanvasGradient("linear", [x0, y0, x1, y1]); + } + createCircularGradient(x, y, r) { + return new CanvasGradient("radial", [x, y, r]); + } + createPattern(image2, repetition) { + if (repetition === void 0) { + console.error("Failed to execute 'createPattern' on 'CanvasContext': 2 arguments required, but only 1 present."); + } else if (["repeat", "repeat-x", "repeat-y", "no-repeat"].indexOf(repetition) < 0) { + console.error("Failed to execute 'createPattern' on 'CanvasContext': The provided type ('" + repetition + "') is not one of 'repeat', 'no-repeat', 'repeat-x', or 'repeat-y'."); + } else { + return new Pattern(image2, repetition); + } + } + measureText(text2) { + const font2 = this.state.font; + let width = 0; + { + width = measureText(text2, font2); + } + return new TextMetrics(width); + } + save() { + this.actions.push({ + method: "save", + data: [] + }); + this.drawingState.push(this.state); + } + restore() { + this.actions.push({ + method: "restore", + data: [] + }); + this.state = this.drawingState.pop() || { + lineDash: [0, 0], + shadowOffsetX: 0, + shadowOffsetY: 0, + shadowBlur: 0, + shadowColor: [0, 0, 0, 0], + font: "10px sans-serif", + fontSize: 10, + fontWeight: "normal", + fontStyle: "normal", + fontFamily: "sans-serif" + }; + } + beginPath() { + this.path = []; + this.subpath = []; + } + moveTo(x, y) { + this.path.push({ + method: "moveTo", + data: [x, y] + }); + this.subpath = [[x, y]]; + } + lineTo(x, y) { + if (this.path.length === 0 && this.subpath.length === 0) { + this.path.push({ + method: "moveTo", + data: [x, y] + }); + } else { + this.path.push({ + method: "lineTo", + data: [x, y] + }); + } + this.subpath.push([x, y]); + } + quadraticCurveTo(cpx, cpy, x, y) { + this.path.push({ + method: "quadraticCurveTo", + data: [cpx, cpy, x, y] + }); + this.subpath.push([x, y]); + } + bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) { + this.path.push({ + method: "bezierCurveTo", + data: [cp1x, cp1y, cp2x, cp2y, x, y] + }); + this.subpath.push([x, y]); + } + arc(x, y, r, sAngle, eAngle, counterclockwise = false) { + this.path.push({ + method: "arc", + data: [x, y, r, sAngle, eAngle, counterclockwise] + }); + this.subpath.push([x, y]); + } + rect(x, y, width, height) { + this.path.push({ + method: "rect", + data: [x, y, width, height] + }); + this.subpath = [[x, y]]; + } + arcTo(x1, y1, x2, y2, radius) { + this.path.push({ + method: "arcTo", + data: [x1, y1, x2, y2, radius] + }); + this.subpath.push([x2, y2]); + } + clip() { + this.actions.push({ + method: "clip", + data: [...this.path] + }); + } + closePath() { + this.path.push({ + method: "closePath", + data: [] + }); + if (this.subpath.length) { + this.subpath = [this.subpath.shift()]; + } + } + clearActions() { + this.actions = []; + this.path = []; + this.subpath = []; + } + getActions() { + var actions = [...this.actions]; + this.clearActions(); + return actions; + } + set lineDashOffset(value) { + this.actions.push({ + method: "setLineDashOffset", + data: [value] + }); + } + set globalCompositeOperation(type) { + this.actions.push({ + method: "setGlobalCompositeOperation", + data: [type] + }); + } + set shadowBlur(level) { + this.actions.push({ + method: "setShadowBlur", + data: [level] + }); + } + set shadowColor(color) { + this.actions.push({ + method: "setShadowColor", + data: [color] + }); + } + set shadowOffsetX(x) { + this.actions.push({ + method: "setShadowOffsetX", + data: [x] + }); + } + set shadowOffsetY(y) { + this.actions.push({ + method: "setShadowOffsetY", + data: [y] + }); + } + set font(value) { + var self2 = this; + this.state.font = value; + var fontFormat = value.match(/^(([\w\-]+\s)*)(\d+r?px)(\/(\d+\.?\d*(r?px)?))?\s+(.*)/); + if (fontFormat) { + var style = fontFormat[1].trim().split(/\s/); + var fontSize = parseFloat(fontFormat[3]); + var fontFamily = fontFormat[7]; + var actions = []; + style.forEach(function(value2, index2) { + if (["italic", "oblique", "normal"].indexOf(value2) > -1) { + actions.push({ + method: "setFontStyle", + data: [value2] + }); + self2.state.fontStyle = value2; + } else if (["bold", "normal"].indexOf(value2) > -1) { + actions.push({ + method: "setFontWeight", + data: [value2] + }); + self2.state.fontWeight = value2; + } else if (index2 === 0) { + actions.push({ + method: "setFontStyle", + data: ["normal"] + }); + self2.state.fontStyle = "normal"; + } else if (index2 === 1) { + pushAction(); + } + }); + if (style.length === 1) { + pushAction(); + } + style = actions.map(function(action) { + return action.data[0]; + }).join(" "); + this.state.fontSize = fontSize; + this.state.fontFamily = fontFamily; + this.actions.push({ + method: "setFont", + data: [`${style} ${fontSize}px ${fontFamily}`] + }); + } else { + console.warn("Failed to set 'font' on 'CanvasContext': invalid format."); + } + function pushAction() { + actions.push({ + method: "setFontWeight", + data: ["normal"] + }); + self2.state.fontWeight = "normal"; + } + } + get font() { + return this.state.font; + } + set fillStyle(color) { + this.setFillStyle(color); + } + set strokeStyle(color) { + this.setStrokeStyle(color); + } + set globalAlpha(value) { + value = Math.floor(255 * parseFloat(value)); + this.actions.push({ + method: "setGlobalAlpha", + data: [value] + }); + } + set textAlign(align2) { + this.actions.push({ + method: "setTextAlign", + data: [align2] + }); + } + set lineCap(type) { + this.actions.push({ + method: "setLineCap", + data: [type] + }); + } + set lineJoin(type) { + this.actions.push({ + method: "setLineJoin", + data: [type] + }); + } + set lineWidth(value) { + this.actions.push({ + method: "setLineWidth", + data: [value] + }); + } + set miterLimit(value) { + this.actions.push({ + method: "setMiterLimit", + data: [value] + }); + } + set textBaseline(type) { + this.actions.push({ + method: "setTextBaseline", + data: [type] + }); + } +} +const initCanvasContextProperty = /* @__PURE__ */ once(() => { + [...methods1, ...methods2].forEach(function(method) { + function get(method2) { + switch (method2) { + case "fill": + case "stroke": + return function() { + this.actions.push({ + method: method2 + "Path", + data: [...this.path] + }); + }; + case "fillRect": + return function(x, y, width, height) { + this.actions.push({ + method: "fillPath", + data: [ + { + method: "rect", + data: [x, y, width, height] + } + ] + }); + }; + case "strokeRect": + return function(x, y, width, height) { + this.actions.push({ + method: "strokePath", + data: [ + { + method: "rect", + data: [x, y, width, height] + } + ] + }); + }; + case "fillText": + case "strokeText": + return function(text2, x, y, maxWidth) { + var data = [text2.toString(), x, y]; + if (typeof maxWidth === "number") { + data.push(maxWidth); + } + this.actions.push({ + method: method2, + data + }); + }; + case "drawImage": + return function(imageResource, dx, dy, dWidth, dHeight, sx, sy, sWidth, sHeight) { + if (sHeight === void 0) { + sx = dx; + sy = dy; + sWidth = dWidth; + sHeight = dHeight; + dx = void 0; + dy = void 0; + dWidth = void 0; + dHeight = void 0; + } + var data; + function isNumber(e2) { + return typeof e2 === "number"; + } + data = isNumber(dx) && isNumber(dy) && isNumber(dWidth) && isNumber(dHeight) ? [ + imageResource, + sx, + sy, + sWidth, + sHeight, + dx, + dy, + dWidth, + dHeight + ] : isNumber(sWidth) && isNumber(sHeight) ? [imageResource, sx, sy, sWidth, sHeight] : [imageResource, sx, sy]; + this.actions.push({ + method: method2, + data + }); + }; + default: + return function(...data) { + this.actions.push({ + method: method2, + data + }); + }; + } + } + CanvasContext.prototype[method] = get(method); + }); + methods3.forEach(function(method) { + function get(method2) { + switch (method2) { + case "setFillStyle": + case "setStrokeStyle": + return function(color) { + if (typeof color !== "object") { + this.actions.push({ + method: method2, + data: ["normal", checkColor(color)] + }); + } else { + this.actions.push({ + method: method2, + data: [color.type, color.data, color.colorStop] + }); + } + }; + case "setGlobalAlpha": + return function(alpha) { + alpha = Math.floor(255 * parseFloat(alpha)); + this.actions.push({ + method: method2, + data: [alpha] + }); + }; + case "setShadow": + return function(offsetX, offsetY, blur, color) { + color = checkColor(color); + this.actions.push({ + method: method2, + data: [offsetX, offsetY, blur, color] + }); + this.state.shadowBlur = blur; + this.state.shadowColor = color; + this.state.shadowOffsetX = offsetX; + this.state.shadowOffsetY = offsetY; + }; + case "setLineDash": + return function(pattern, offset) { + pattern = pattern || [0, 0]; + offset = offset || 0; + this.actions.push({ + method: method2, + data: [pattern, offset] + }); + this.state.lineDash = pattern; + }; + case "setFontSize": + return function(fontSize) { + this.state.font = this.state.font.replace(/\d+\.?\d*px/, fontSize + "px"); + this.state.fontSize = fontSize; + this.actions.push({ + method: method2, + data: [fontSize] + }); + }; + default: + return function(...data) { + this.actions.push({ + method: method2, + data + }); + }; + } + } + CanvasContext.prototype[method] = get(method); + }); +}); +const createCanvasContext = /* @__PURE__ */ defineSyncApi(API_CREATE_CANVAS_CONTEXT, (canvasId, componentInstance) => { + initCanvasContextProperty(); + if (componentInstance) { + return new CanvasContext(canvasId, getPageIdByVm(componentInstance)); + } + const pageId = getPageIdByVm(getCurrentPageVm()); + if (pageId) { + return new CanvasContext(canvasId, pageId); + } else { + UniServiceJSBridge.emit("onError", "createCanvasContext:fail"); + } +}, CreateCanvasContextProtocol); +const canvasGetImageData = /* @__PURE__ */ defineAsyncApi(API_CANVAS_GET_IMAGE_DATA, ({canvasId, x, y, width, height}, {resolve, reject}) => { + const pageId = getPageIdByVm(getCurrentPageVm()); + if (!pageId) { + reject(); + return; + } + const cId = canvasEventCallbacks.push(async function(data) { + let imgData = data.data; + if (imgData && imgData.length) { + data.data = new Uint8ClampedArray(imgData); + } + resolve(data); + }); + operateCanvas(canvasId, pageId, "getImageData", { + x, + y, + width, + height, + callbackId: cId + }); +}, CanvasGetImageDataProtocol, CanvasGetImageDataOptions); +const canvasPutImageData = /* @__PURE__ */ defineAsyncApi(API_CANVAS_PUT_IMAGE_DATA, async ({canvasId, data, x, y, width, height}, {resolve, reject}) => { + var pageId = getPageIdByVm(getCurrentPageVm()); + if (!pageId) { + reject(); + return; + } + var cId = canvasEventCallbacks.push(function(data2) { + resolve(data2); + }); + let compressed; + { + data = Array.prototype.slice.call(data); + } + operateCanvas(canvasId, pageId, "putImageData", { + data, + x, + y, + width, + height, + compressed, + callbackId: cId + }); +}, CanvasPutImageDataProtocol, CanvasPutImageDataOptions); +const canvasToTempFilePath = /* @__PURE__ */ defineAsyncApi(API_CANVAS_TO_TEMP_FILE_PATH, ({ + x = 0, + y = 0, + width, + height, + destWidth, + destHeight, + canvasId, + fileType, + quality +}, {resolve, reject}) => { + var pageId = getPageIdByVm(getCurrentPageVm()); + if (!pageId) { + reject(); + return; + } + const cId = canvasEventCallbacks.push(function(res) { + resolve(res); + }); + const dirname = `${TEMP_PATH}/canvas`; + operateCanvas(canvasId, pageId, "toTempFilePath", { + x, + y, + width, + height, + destWidth, + destHeight, + fileType, + quality, + dirname, + callbackId: cId + }); +}, CanvasToTempFilePathProtocol, CanvasToTempFilePathOptions); +const defaultOptions = { + thresholds: [0], + initialRatio: 0, + observeAll: false +}; +const MARGINS = ["top", "right", "bottom", "left"]; +let reqComponentObserverId$1 = 1; +function normalizeRootMargin(margins = {}) { + return MARGINS.map((name) => `${Number(margins[name]) || 0}px`).join(" "); +} +class ServiceIntersectionObserver { + constructor(component, options) { + this._pageId = getPageIdByVm(component); + 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$1++; + 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 = /* @__PURE__ */ defineSyncApi("createIntersectionObserver", (context, options) => { + if (context && !getPageIdByVm(context)) { + options = context; + context = null; + } + if (context) { + return new ServiceIntersectionObserver(context, options); + } + return new ServiceIntersectionObserver(getCurrentPageVm(), options); +}); +let reqComponentObserverId = 1; +class ServiceMediaQueryObserver { + constructor(component) { + this._pageId = component.$page && component.$page.id; + this._component = component; + } + observe(options, callback) { + if (!isFunction(callback)) { + return; + } + this._reqId = reqComponentObserverId++; + addMediaQueryObserver({ + reqId: this._reqId, + component: this._component, + options, + callback + }, this._pageId); + } + disconnect() { + this._reqId && removeMediaQueryObserver({ + reqId: this._reqId, + component: this._component + }, this._pageId); + } +} +const createMediaQueryObserver = /* @__PURE__ */ defineSyncApi("createMediaQueryObserver", (context) => { + if (context && !getPageIdByVm(context)) { + context = null; + } + if (context) { + return new ServiceMediaQueryObserver(context); + } + return new ServiceMediaQueryObserver(getCurrentPageVm()); +}); +let eventReady = false; +let index$e = 0; +let optionsCache = {}; +function operateEditor(componentId, pageId, type, options) { + const data = {}; + if (options && ("success" in options || "fail" in options || "complete" in options)) { + const callbackId = String(index$e++); + data.callbackId = callbackId; + optionsCache[callbackId] = options; + if (!eventReady) { + ServiceJSBridge.subscribe("onEditorMethodCallback", ({callbackId: callbackId2, data: data2}) => { + callOptions(optionsCache[callbackId2], data2); + delete optionsCache[callbackId2]; + }); + eventReady = true; + } + } + data.options = options; + ServiceJSBridge.publishHandler("editor." + componentId, { + componentId, + type, + data + }, pageId); +} +class EditorContext { + constructor(id2, pageId) { + this.id = id2; + this.pageId = pageId; + } + format(name, value) { + this._exec("format", { + name, + value + }); + } + insertDivider() { + this._exec("insertDivider"); + } + insertImage(options) { + this._exec("insertImage", options); + } + insertText(options) { + this._exec("insertText", options); + } + setContents(options) { + this._exec("setContents", options); + } + getContents(options) { + this._exec("getContents", options); + } + clear(options) { + this._exec("clear", options); + } + removeFormat(options) { + this._exec("removeFormat", options); + } + undo(options) { + this._exec("undo", options); + } + redo(options) { + this._exec("redo", options); + } + blur(options) { + this._exec("blur", options); + } + getSelectionText(options) { + this._exec("getSelectionText", options); + } + scrollIntoView(options) { + this._exec("scrollIntoView", options); + } + _exec(method, options) { + operateEditor(this.id, this.pageId, method, options); + } +} +const ContextClasss = { + canvas: CanvasContext, + map: MapContext, + video: VideoContext, + editor: EditorContext +}; +function convertContext(result) { + if (result && result.contextInfo) { + const {id: id2, type, page} = result.contextInfo; + const ContextClass = ContextClasss[type]; + result.context = new ContextClass(id2, page); + delete result.contextInfo; + } +} +class NodesRef { + constructor(selectorQuery, component, selector, single) { + this._selectorQuery = selectorQuery; + this._component = component; + this._selector = selector; + this._single = single; + } + boundingClientRect(callback) { + this._selectorQuery._push(this._selector, this._component, this._single, { + id: true, + dataset: true, + rect: true, + size: true + }, callback); + return this._selectorQuery; + } + fields(fields2, callback) { + this._selectorQuery._push(this._selector, this._component, this._single, fields2, callback); + return this._selectorQuery; + } + scrollOffset(callback) { + this._selectorQuery._push(this._selector, this._component, this._single, { + id: true, + dataset: true, + scrollOffset: true + }, callback); + return this._selectorQuery; + } + context(callback) { + this._selectorQuery._push(this._selector, this._component, this._single, { + context: true + }, callback); + return this._selectorQuery; + } +} +class SelectorQuery { + constructor(page) { + this._component = void 0; + this._page = page; + this._queue = []; + this._queueCb = []; + } + exec(callback) { + requestComponentInfo(this._page, this._queue, (res) => { + const queueCbs = this._queueCb; + res.forEach((result, index2) => { + if (Array.isArray(result)) { + result.forEach(convertContext); + } else { + convertContext(result); + } + const queueCb = queueCbs[index2]; + if (typeof queueCb === "function") { + queueCb.call(this, result); + } + }); + if (typeof callback === "function") { + callback.call(this, res); + } + }); + return this._nodesRef; + } + in(component) { + this._component = component || void 0; + return this; + } + select(selector) { + return this._nodesRef = new NodesRef(this, this._component, selector, true); + } + selectAll(selector) { + return this._nodesRef = new NodesRef(this, this._component, selector, false); + } + selectViewport() { + return this._nodesRef = new NodesRef(this, null, "", true); + } + _push(selector, component, single, fields2, callback) { + this._queue.push({ + component, + selector, + single, + fields: fields2 + }); + this._queueCb.push(callback); + } +} +const createSelectorQuery = /* @__PURE__ */ defineSyncApi("createSelectorQuery", (context) => { + if (context && !getPageIdByVm(context)) { + context = null; + } + return new SelectorQuery(context || getCurrentPageVm()); +}); +const API_CREATE_ANIMATION = "createAnimation"; +const CreateAnimationOptions = { + formatArgs: {} +}; +const CreateAnimationProtocol = { + duration: Number, + timingFunction: String, + delay: Number, + transformOrigin: String +}; +const defaultOption = { + duration: 400, + timingFunction: "linear", + delay: 0, + transformOrigin: "50% 50% 0" +}; +class MPAnimation { + constructor(option) { + this.actions = []; + this.currentTransform = {}; + this.currentStepAnimates = []; + this.option = extend({}, defaultOption, option); } - if ((t2 = /^#([0-9|A-F|a-f]{3})$/.exec(e2)) != null) { - let n = t2[1].slice(0, 1); - let o2 = t2[1].slice(1, 2); - let r = t2[1].slice(2, 3); - n = parseInt(n + n, 16); - o2 = parseInt(o2 + o2, 16); - r = parseInt(r + r, 16); - return [n, o2, r, 255]; + _getOption(option) { + const _option = { + transition: extend({}, this.option, option), + transformOrigin: "" + }; + _option.transformOrigin = _option.transition.transformOrigin; + delete _option.transition.transformOrigin; + return _option; } - if ((t2 = /^rgb\((.+)\)$/.exec(e2)) != null) { - return t2[1].split(",").map(function(e22) { - return Math.min(255, parseInt(e22.trim())); - }).concat(255); + _pushAnimates(type, args) { + this.currentStepAnimates.push({ + type, + args + }); } - if ((t2 = /^rgba\((.+)\)$/.exec(e2)) != null) { - return t2[1].split(",").map(function(e22, t22) { - return t22 === 3 ? Math.floor(255 * parseFloat(e22.trim())) : Math.min(255, parseInt(e22.trim())); + _converType(type) { + return type.replace(/[A-Z]/g, (text2) => { + return `-${text2.toLowerCase()}`; }); } - var i = e2.toLowerCase(); - if (hasOwn(predefinedColor, i)) { - t2 = /^#([0-9|A-F|a-f]{6,8})$/.exec(predefinedColor[i]); - const n = parseInt(t2[1].slice(0, 2), 16); - const o2 = parseInt(t2[1].slice(2, 4), 16); - const r = parseInt(t2[1].slice(4, 6), 16); - let a2 = parseInt(t2[1].slice(6, 8), 16); - a2 = a2 >= 0 ? a2 : 255; - return [n, o2, r, a2]; + _getValue(value) { + return typeof value === "number" ? `${value}px` : value; + } + export() { + const actions = this.actions; + this.actions = []; + return { + actions + }; + } + step(option) { + this.currentStepAnimates.forEach((animate) => { + if (animate.type !== "style") { + this.currentTransform[animate.type] = animate; + } else { + this.currentTransform[`${animate.type}.${animate.args[0]}`] = animate; + } + }); + this.actions.push({ + animates: Object.values(this.currentTransform), + option: this._getOption(option) + }); + this.currentStepAnimates = []; + return this; } - console.error("unsupported color:" + e2); - return [0, 0, 0, 255]; } -class CanvasGradient { - constructor(type, data) { - this.type = type; - this.data = data; - this.colorStop = []; +const initAnimationProperty = /* @__PURE__ */ once(() => { + const animateTypes1 = [ + "matrix", + "matrix3d", + "rotate", + "rotate3d", + "rotateX", + "rotateY", + "rotateZ", + "scale", + "scale3d", + "scaleX", + "scaleY", + "scaleZ", + "skew", + "skewX", + "skewY", + "translate", + "translate3d", + "translateX", + "translateY", + "translateZ" + ]; + const animateTypes2 = ["opacity", "backgroundColor"]; + const animateTypes3 = ["width", "height", "left", "right", "top", "bottom"]; + animateTypes1.concat(animateTypes2, animateTypes3).forEach((type) => { + MPAnimation.prototype[type] = function(...args) { + if (animateTypes2.concat(animateTypes3).includes(type)) { + this._pushAnimates("style", [ + this._converType(type), + animateTypes3.includes(type) ? this._getValue(args[0]) : args[0] + ]); + } else { + this._pushAnimates(type, args); + } + return this; + }; + }); +}); +const createAnimation = /* @__PURE__ */ defineSyncApi(API_CREATE_ANIMATION, (option) => { + initAnimationProperty(); + return new MPAnimation(option); +}, CreateAnimationProtocol, CreateAnimationOptions); +const API_ON_TAB_BAR_MID_BUTTON_TAP = "onTabBarMidButtonTap"; +const onTabBarMidButtonTap = /* @__PURE__ */ defineOnApi(API_ON_TAB_BAR_MID_BUTTON_TAP, () => { +}); +const API_GET_SELECTED_TEXT_RANGE = "getSelectedTextRange"; +const getSelectedTextRangeEventCallbacks = createCallbacks("getSelectedTextRangeEvent"); +ServiceJSBridge.subscribe && ServiceJSBridge.subscribe("onGetSelectedTextRange", ({callbackId, data}) => { + const callback = getSelectedTextRangeEventCallbacks.pop(callbackId); + if (callback) { + callback(data); } - addColorStop(position, color) { - this.colorStop.push([position, checkColor(color)]); +}); +const getSelectedTextRange = /* @__PURE__ */ defineAsyncApi(API_GET_SELECTED_TEXT_RANGE, (_, {resolve, reject}) => { + const pageId = getCurrentPageId(); + ServiceJSBridge.publishHandler && ServiceJSBridge.publishHandler("getSelectedTextRange", { + pageId, + callbackId: getSelectedTextRangeEventCallbacks.push(function(res) { + if (typeof res.end === "undefined" && typeof res.start === "undefined") { + reject("no focused"); + } else { + resolve(res); + } + }) + }, pageId); +}); +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 } -} -class Pattern { - constructor(image2, repetition) { - this.image = image2; - this.repetition = repetition; +}; +const API_GET_STORAGE_SYNC = "getStorageSync"; +const GetStorageSyncProtocol = [ + { + name: "key", + type: String, + required: true } -} -class TextMetrics { - constructor(width) { - this.width = width; +]; +const API_SET_STORAGE = "setStorage"; +const SetStorageProtocol = { + key: { + type: String, + required: true + }, + data: { + required: true } -} -class CanvasContext { - constructor(id2, pageId) { - this.id = id2; - this.pageId = pageId; - this.actions = []; - this.path = []; - this.subpath = []; - this.drawingState = []; - this.state = { - lineDash: [0, 0], - shadowOffsetX: 0, - shadowOffsetY: 0, - shadowBlur: 0, - shadowColor: [0, 0, 0, 0], - font: "10px sans-serif", - fontSize: 10, - fontWeight: "normal", - fontStyle: "normal", - fontFamily: "sans-serif" - }; +}; +const API_SET_STORAGE_SYNC = "setStorageSync"; +const SetStorageSyncProtocol = [ + { + name: "key", + type: String, + required: true + }, + { + name: "data", + required: true } - draw(reserve = false, callback) { - var actions = [...this.actions]; - this.actions = []; - this.path = []; - var callbackId; - if (typeof callback === "function") { - callbackId = canvasEventCallbacks.push(callback); +]; +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); } - operateCanvas(this.id, this.pageId, "actionsChanged", { - actions, - reserve, - callbackId - }); } - createLinearGradient(x0, y0, x1, y1) { - return new CanvasGradient("linear", [x0, y0, x1, y1]); +}; +const GetFileInfoProtocol = { + filePath: { + type: String, + required: true } - createCircularGradient(x, y, r) { - return new CanvasGradient("radial", [x, y, r]); +}; +const API_OPEN_DOCUMENT = "openDocument"; +const OpenDocumentOptions = { + formatArgs: { + filePath(filePath, params) { + params.filePath = getRealPath(filePath); + } } - createPattern(image2, repetition) { - if (repetition === void 0) { - console.error("Failed to execute 'createPattern' on 'CanvasContext': 2 arguments required, but only 1 present."); - } else if (["repeat", "repeat-x", "repeat-y", "no-repeat"].indexOf(repetition) < 0) { - console.error("Failed to execute 'createPattern' on 'CanvasContext': The provided type ('" + repetition + "') is not one of 'repeat', 'no-repeat', 'repeat-x', or 'repeat-y'."); - } else { - return new Pattern(image2, repetition); +}; +const OpenDocumentProtocol = { + filePath: { + type: String, + required: true + }, + fileType: String +}; +const API_HIDE_KEYBOARD = "hideKeyboard"; +const API_CHOOSE_LOCATION = "chooseLocation"; +const ChooseLocationProtocol = { + keyword: String, + latitude: Number, + longitude: Number +}; +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; + } + }, + altitude(value, params) { + params.altitude = value ? value : false; } } - measureText(text2) { - const font2 = this.state.font; - let width = 0; - { - width = measureText(text2, font2); +}; +const GetLocationProtocol = { + type: String, + altitude: Boolean +}; +const API_OPEN_LOCATION = "openLocation"; +const OpenLocationOptions = { + formatArgs: { + scale(value, params) { + value = Math.floor(value); + params.scale = value >= 5 && value <= 18 ? value : 18; } - return new TextMetrics(width); } - save() { - this.actions.push({ - method: "save", - data: [] - }); - this.drawingState.push(this.state); +}; +const OpenLocationProtocol = { + latitude: { + type: Number, + required: true + }, + longitude: { + type: Number, + required: true + }, + scale: Number, + name: String, + address: String +}; +const API_CHOOSE_IMAGE = "chooseImage"; +const ChooseImageOptions = { + formatArgs: { + count(value, params) { + if (!value || value <= 0) { + params.count = 9; + } + }, + 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."; + } + if (!extension) + params.extension = [""]; + } } - restore() { - this.actions.push({ - method: "restore", - data: [] - }); - this.state = this.drawingState.pop() || { - lineDash: [0, 0], - shadowOffsetX: 0, - shadowOffsetY: 0, - shadowBlur: 0, - shadowColor: [0, 0, 0, 0], - font: "10px sans-serif", - fontSize: 10, - fontWeight: "normal", - fontStyle: "normal", - fontFamily: "sans-serif" - }; +}; +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."; + } + if (!extension) + params.extension = [""]; + } + } +}; +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; + } + }, + 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 = [""]; + } } - beginPath() { - this.path = []; - this.subpath = []; +}; +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); + } } - moveTo(x, y) { - this.path.push({ - method: "moveTo", - data: [x, y] - }); - this.subpath = [[x, y]]; +}; +const GetImageInfoProtocol = { + src: { + type: String, + required: true } - lineTo(x, y) { - if (this.path.length === 0 && this.subpath.length === 0) { - this.path.push({ - method: "moveTo", - data: [x, y] - }); - } else { - this.path.push({ - method: "lineTo", - data: [x, y] - }); +}; +const API_PREVIEW_IMAGE = "previewImage"; +const PreviewImageOptions = { + formatArgs: { + urls(urls, params) { + params.urls = urls.map((url) => typeof url === "string" && url ? getRealPath(url) : ""); + }, + current(current, params) { + if (typeof current === "number") { + params.current = current > 0 && current < params.urls.length ? current : 0; + } else if (typeof current === "string" && current) { + params.current = getRealPath(current); + } } - this.subpath.push([x, y]); } - quadraticCurveTo(cpx, cpy, x, y) { - this.path.push({ - method: "quadraticCurveTo", - data: [cpx, cpy, x, y] - }); - this.subpath.push([x, y]); +}; +const PreviewImageProtocol = { + urls: { + type: Array, + required: true + }, + current: { + type: [Number, String] } - bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) { - this.path.push({ - method: "bezierCurveTo", - data: [cp1x, cp1y, cp2x, cp2y, x, y] - }); - this.subpath.push([x, y]); +}; +const API_GET_VIDEO_INFO = "getVideoInfo"; +const GetVideoInfoOptions = { + formatArgs: { + src(src, params) { + params.src = getRealPath(src); + } } - arc(x, y, r, sAngle, eAngle, counterclockwise = false) { - this.path.push({ - method: "arc", - data: [x, y, r, sAngle, eAngle, counterclockwise] - }); - this.subpath.push([x, y]); +}; +const GetVideoInfoProtocol = { + src: { + type: String, + required: true } - rect(x, y, width, height) { - this.path.push({ - method: "rect", - data: [x, y, width, height] - }); - this.subpath = [[x, y]]; +}; +const API_SAVE_IMAGE_TO_PHOTOS_ALBUM = "saveImageToPhotosAlbum"; +const API_SAVE_VIDEO_TO_PHOTOS_ALBUM = "saveVideoToPhotosAlbum"; +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(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); + } } - arcTo(x1, y1, x2, y2, radius) { - this.path.push({ - method: "arcTo", - data: [x1, y1, x2, y2, radius] - }); - this.subpath.push([x2, y2]); + 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); + } + }, + 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"; + } + } + }, + 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; + } + } } - clip() { - this.actions.push({ - method: "clip", - data: [...this.path] - }); +}; +const API_DOWNLOAD_FILE = "downloadFile"; +const DownloadFileOptions = { + formatArgs: { + header(value, params) { + params.header = value || {}; + } } - closePath() { - this.path.push({ - method: "closePath", - data: [] - }); - if (this.subpath.length) { - this.subpath = [this.subpath.shift()]; +}; +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); + } + }, + 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]; + } } } - clearActions() { - this.actions = []; - this.path = []; - this.subpath = []; - } - getActions() { - var actions = [...this.actions]; - this.clearActions(); - return actions; - } - set lineDashOffset(value) { - this.actions.push({ - method: "setLineDashOffset", - data: [value] - }); +}; +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; } - set globalCompositeOperation(type) { - this.actions.push({ - method: "setGlobalCompositeOperation", - data: [type] - }); + const index2 = url.indexOf("?"); + if (index2 === -1) { + return url; } - set shadowBlur(level) { - this.actions.push({ - method: "setShadowBlur", - data: [level] - }); + const query = url.substr(index2 + 1).trim().replace(/^(\?|#|&)/, ""); + if (!query) { + return url; } - set shadowColor(color) { - this.actions.push({ - method: "setShadowColor", - data: [color] - }); + 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 } - set shadowOffsetX(x) { - this.actions.push({ - method: "setShadowOffsetX", - data: [x] - }); +}; +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 } - set shadowOffsetY(y) { - this.actions.push({ - method: "setShadowOffsetY", - data: [y] - }); +}, createAnimationProtocol(ANIMATION_OUT)); +const RedirectToProtocol = BaseRouteProtocol; +const ReLaunchProtocol = BaseRouteProtocol; +const SwitchTabProtocol = BaseRouteProtocol; +const PreloadPageProtocol = 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); + } } - set font(value) { - var self2 = this; - this.state.font = value; - var fontFormat = value.match(/^(([\w\-]+\s)*)(\d+r?px)(\/(\d+\.?\d*(r?px)?))?\s+(.*)/); - if (fontFormat) { - var style = fontFormat[1].trim().split(/\s/); - var fontSize = parseFloat(fontFormat[3]); - var fontFamily = fontFormat[7]; - var actions = []; - style.forEach(function(value2, index2) { - if (["italic", "oblique", "normal"].indexOf(value2) > -1) { - actions.push({ - method: "setFontStyle", - data: [value2] - }); - self2.state.fontStyle = value2; - } else if (["bold", "normal"].indexOf(value2) > -1) { - actions.push({ - method: "setFontWeight", - data: [value2] - }); - self2.state.fontWeight = value2; - } else if (index2 === 0) { - actions.push({ - method: "setFontStyle", - data: ["normal"] - }); - self2.state.fontStyle = "normal"; - } else if (index2 === 1) { - pushAction(); +}; +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 (style.length === 1) { - pushAction(); } - style = actions.map(function(action) { - return action.data[0]; - }).join(" "); - this.state.fontSize = fontSize; - this.state.fontFamily = fontFamily; - this.actions.push({ - method: "setFont", - data: [`${style} ${fontSize}px ${fontFamily}`] - }); - } else { - console.warn("Failed to set 'font' on 'CanvasContext': invalid format."); - } - function pushAction() { - actions.push({ - method: "setFontWeight", - data: ["normal"] - }); - self2.state.fontWeight = "normal"; + }, + 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 ((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(); + const tabBarPagePath = routeOptions.path.substr(1); + if (pages.find((page) => page.route === tabBarPagePath)) { + return "tabBar page `" + tabBarPagePath + "` already exists"; + } + } + return; + } + if (navigatorLock === url && params.openType !== "appLaunch") { + return `${navigatorLock} locked`; + } + if (__uniConfig.ready) { + navigatorLock = url; + } + }; +} +const API_HIDE_LOADING = "hideLoading"; +const API_HIDE_TOAST = "hideToast"; +const API_LOAD_FONT_FACE = "loadFontFace"; +const LoadFontFaceProtocol = { + family: { + type: String, + required: true + }, + source: { + type: String, + required: true + }, + desc: Object +}; +const FRONT_COLORS = ["#ffffff", "#000000"]; +const API_SET_NAVIGATION_BAR_COLOR = "setNavigationBarColor"; +const SetNavigationBarColorOptions = { + formatArgs: { + animation(animation2, params) { + if (!animation2) { + animation2 = {duration: 0, timingFunc: "linear"}; + } + params.animation = { + duration: animation2.duration || 0, + timingFunc: animation2.timingFunc || "linear" + }; } } - get font() { - return this.state.font; - } - set fillStyle(color) { - this.setFillStyle(color); - } - set strokeStyle(color) { - this.setStrokeStyle(color); - } - set globalAlpha(value) { - value = Math.floor(255 * parseFloat(value)); - this.actions.push({ - method: "setGlobalAlpha", - data: [value] - }); - } - set textAlign(align2) { - this.actions.push({ - method: "setTextAlign", - data: [align2] - }); - } - set lineCap(type) { - this.actions.push({ - method: "setLineCap", - data: [type] - }); - } - set lineJoin(type) { - this.actions.push({ - method: "setLineJoin", - data: [type] - }); +}; +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 } - set lineWidth(value) { - this.actions.push({ - method: "setLineWidth", - data: [value] - }); +}; +const API_SHOW_NAVIGATION_BAR_LOADING = "showNavigationBarLoading"; +const API_HIDE_NAVIGATION_BAR_LOADING = "hideNavigationBarLoading"; +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); + } } - set miterLimit(value) { - this.actions.push({ - method: "setMiterLimit", - data: [value] - }); +}; +const API_SHOW_ACTION_SHEET = "showActionSheet"; +const ShowActionSheetProtocol = { + itemList: { + type: Array, + required: true + }, + itemColor: String, + popover: Object +}; +const ShowActionSheetOptions = { + formatArgs: { + itemColor: "#000" } - set textBaseline(type) { - this.actions.push({ - method: "setTextBaseline", - data: [type] - }); +}; +const API_SHOW_LOADING = "showLoading"; +const ShowLoadingProtocol = { + title: String, + mask: Boolean +}; +const ShowLoadingOptions = { + formatArgs: { + title: "", + mask: false } -} -const initCanvasContextProperty = /* @__PURE__ */ once(() => { - [...methods1, ...methods2].forEach(function(method) { - function get(method2) { - switch (method2) { - case "fill": - case "stroke": - return function() { - this.actions.push({ - method: method2 + "Path", - data: [...this.path] - }); - }; - case "fillRect": - return function(x, y, width, height) { - this.actions.push({ - method: "fillPath", - data: [ - { - method: "rect", - data: [x, y, width, height] - } - ] - }); - }; - case "strokeRect": - return function(x, y, width, height) { - this.actions.push({ - method: "strokePath", - data: [ - { - method: "rect", - data: [x, y, width, height] - } - ] - }); - }; - case "fillText": - case "strokeText": - return function(text2, x, y, maxWidth) { - var data = [text2.toString(), x, y]; - if (typeof maxWidth === "number") { - data.push(maxWidth); - } - this.actions.push({ - method: method2, - data - }); - }; - case "drawImage": - return function(imageResource, dx, dy, dWidth, dHeight, sx, sy, sWidth, sHeight) { - if (sHeight === void 0) { - sx = dx; - sy = dy; - sWidth = dWidth; - sHeight = dHeight; - dx = void 0; - dy = void 0; - dWidth = void 0; - dHeight = void 0; - } - var data; - function isNumber(e2) { - return typeof e2 === "number"; - } - data = isNumber(dx) && isNumber(dy) && isNumber(dWidth) && isNumber(dHeight) ? [ - imageResource, - sx, - sy, - sWidth, - sHeight, - dx, - dy, - dWidth, - dHeight - ] : isNumber(sWidth) && isNumber(sHeight) ? [imageResource, sx, sy, sWidth, sHeight] : [imageResource, sx, sy]; - this.actions.push({ - method: method2, - data - }); - }; - default: - return function(...data) { - this.actions.push({ - method: method2, - data - }); - }; +}; +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(params, "cancelText")) { + const {t: t2} = useI18n(); + params.cancelText = t2("uni.showModal.cancel"); + } + }, + cancelColor: "#000", + confirmText(_value, params) { + if (!hasOwn(params, "confirmText")) { + const {t: t2} = useI18n(); + params.confirmText = t2("uni.showModal.confirm"); + } + }, + confirmColor: PRIMARY_COLOR + } +}; +const API_SHOW_TOAST = "showToast"; +const SHOW_TOAST_ICON = [ + "success", + "loading", + "none" +]; +const ShowToastProtocol = { + title: String, + icon: String, + image: String, + duration: Number, + mask: Boolean +}; +const ShowToastOptions = { + formatArgs: { + title: "", + icon(type, params) { + params.icon = elemInArray(type, SHOW_TOAST_ICON); + }, + image(value, params) { + if (value) { + params.image = getRealPath(value); + } else { + params.image = ""; } + }, + duration: 1500, + mask: false + } +}; +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"; } - CanvasContext.prototype[method] = get(method); - }); - methods3.forEach(function(method) { - function get(method2) { - switch (method2) { - case "setFillStyle": - case "setStrokeStyle": - return function(color) { - if (typeof color !== "object") { - this.actions.push({ - method: method2, - data: ["normal", checkColor(color)] - }); - } else { - this.actions.push({ - method: method2, - data: [color.type, color.data, color.colorStop] - }); - } - }; - case "setGlobalAlpha": - return function(alpha) { - alpha = Math.floor(255 * parseFloat(alpha)); - this.actions.push({ - method: method2, - data: [alpha] - }); - }; - case "setShadow": - return function(offsetX, offsetY, blur, color) { - color = checkColor(color); - this.actions.push({ - method: method2, - data: [offsetX, offsetY, blur, color] - }); - this.state.shadowBlur = blur; - this.state.shadowColor = color; - this.state.shadowOffsetX = offsetX; - this.state.shadowOffsetY = offsetY; - }; - case "setLineDash": - return function(pattern, offset) { - pattern = pattern || [0, 0]; - offset = offset || 0; - this.actions.push({ - method: method2, - data: [pattern, offset] - }); - this.state.lineDash = pattern; - }; - case "setFontSize": - return function(fontSize) { - this.state.font = this.state.font.replace(/\d+\.?\d*px/, fontSize + "px"); - this.state.fontSize = fontSize; - this.actions.push({ - method: method2, - data: [fontSize] - }); - }; - default: - return function(...data) { - this.actions.push({ - method: method2, - data - }); - }; + }, + formatArgs: { + index(value) { + if (!__uniConfig.tabBar.list[value]) { + return "tabbar item not found"; } } - CanvasContext.prototype[method] = get(method); - }); -}); -const createCanvasContext = /* @__PURE__ */ defineSyncApi(API_CREATE_CANVAS_CONTEXT, (canvasId, componentInstance) => { - initCanvasContextProperty(); - if (componentInstance) { - return new CanvasContext(canvasId, getPageIdByVm(componentInstance)); - } - const pageId = getPageIdByVm(getCurrentPageVm()); - if (pageId) { - return new CanvasContext(canvasId, pageId); - } else { - UniServiceJSBridge.emit("onError", "createCanvasContext:fail"); } -}, CreateCanvasContextProtocol); -const canvasGetImageData = /* @__PURE__ */ defineAsyncApi(API_CANVAS_GET_IMAGE_DATA, ({canvasId, x, y, width, height}, {resolve, reject}) => { - const pageId = getPageIdByVm(getCurrentPageVm()); - if (!pageId) { - reject(); - return; - } - const cId = canvasEventCallbacks.push(async function(data) { - let imgData = data.data; - if (imgData && imgData.length) { - data.data = new Uint8ClampedArray(imgData); +}; +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"; + } } - resolve(data); - }); - operateCanvas(canvasId, pageId, "getImageData", { - x, - y, - width, - height, - callbackId: cId - }); -}, CanvasGetImageDataProtocol, CanvasGetImageDataOptions); -const canvasPutImageData = /* @__PURE__ */ defineAsyncApi(API_CANVAS_PUT_IMAGE_DATA, async ({canvasId, data, x, y, width, height}, {resolve, reject}) => { - var pageId = getPageIdByVm(getCurrentPageVm()); - if (!pageId) { - reject(); - return; } - var cId = canvasEventCallbacks.push(function(data2) { - resolve(data2); - }); - let compressed; - { - data = Array.prototype.slice.call(data); +}; +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 } - operateCanvas(canvasId, pageId, "putImageData", { - data, - x, - y, - width, - height, - compressed, - callbackId: cId - }); -}, CanvasPutImageDataProtocol, CanvasPutImageDataOptions); -const canvasToTempFilePath = /* @__PURE__ */ defineAsyncApi(API_CANVAS_TO_TEMP_FILE_PATH, ({ - x = 0, - y = 0, - width, - height, - destWidth, - destHeight, - canvasId, - fileType, - quality -}, {resolve, reject}) => { - var pageId = getPageIdByVm(getCurrentPageVm()); - if (!pageId) { - reject(); +}, IndexProtocol); +const SetTabBarBadgeOptions = { + beforeInvoke: IndexOptions.beforeInvoke, + formatArgs: /* @__PURE__ */ extend({ + text(value, params) { + if (getLen(value) >= 4) { + params.text = "..."; + } + } + }, IndexOptions.formatArgs) +}; +const API_ON_WINDOW_RESIZE = "onWindowResize"; +const API_OFF_WINDOW_RESIZE = "offWindowResize"; +const initIntersectionObserverPolyfill = function() { + if (typeof window !== "object") { return; } - const cId = canvasEventCallbacks.push(function(res) { - resolve(res); - }); - const dirname = `${TEMP_PATH}/canvas`; - operateCanvas(canvasId, pageId, "toTempFilePath", { - x, - y, - width, - height, - destWidth, - destHeight, - fileType, - quality, - dirname, - callbackId: cId - }); -}, CanvasToTempFilePathProtocol, CanvasToTempFilePathOptions); -const defaultOptions = { - thresholds: [0], - initialRatio: 0, - observeAll: false -}; -const MARGINS = ["top", "right", "bottom", "left"]; -let reqComponentObserverId$1 = 1; -function normalizeRootMargin(margins = {}) { - return MARGINS.map((name) => `${Number(margins[name]) || 0}px`).join(" "); -} -class ServiceIntersectionObserver { - constructor(component, options) { - this._pageId = getPageIdByVm(component); - this._component = component; - this._options = extend({}, defaultOptions, options); + 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; } - relativeTo(selector, margins) { - this._options.relativeToSelector = selector; - this._options.rootMargin = normalizeRootMargin(margins); - return this; + function getFrameElement(doc) { + try { + return doc.defaultView && doc.defaultView.frameElement || null; + } catch (e2) { + return null; + } } - relativeToViewport(margins) { - this._options.relativeToSelector = void 0; - this._options.rootMargin = normalizeRootMargin(margins); - return this; + 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; + } } - observe(selector, callback) { - if (!isFunction(callback)) { + 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 = []; + } + 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, i, 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[i - 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; } - this._options.selector = selector; - this._reqId = reqComponentObserverId$1++; - 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 = /* @__PURE__ */ defineSyncApi("createIntersectionObserver", (context, options) => { - if (context && !getPageIdByVm(context)) { - options = context; - context = null; - } - if (context) { - return new ServiceIntersectionObserver(context, options); - } - return new ServiceIntersectionObserver(getCurrentPageVm(), options); -}); -let reqComponentObserverId = 1; -class ServiceMediaQueryObserver { - constructor(component) { - this._pageId = component.$page && component.$page.id; - this._component = component; - } - observe(options, callback) { - if (!isFunction(callback)) { + 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); + } + } + }; + IntersectionObserver2.prototype._unmonitorAllIntersections = function() { + var unsubscribes = this._monitoringUnsubscribes.slice(0); + this._monitoringDocuments.length = 0; + this._monitoringUnsubscribes.length = 0; + for (var i = 0; i < unsubscribes.length; i++) { + unsubscribes[i](); + } + }; + IntersectionObserver2.prototype._checkForIntersections = function() { + if (!this.root && crossOriginUpdater && !crossOriginRect) { return; } - this._reqId = reqComponentObserverId++; - addMediaQueryObserver({ - reqId: this._reqId, - component: this._component, - options, - callback - }, this._pageId); - } - disconnect() { - this._reqId && removeMediaQueryObserver({ - reqId: this._reqId, - component: this._component - }, this._pageId); - } -} -const createMediaQueryObserver = /* @__PURE__ */ defineSyncApi("createMediaQueryObserver", (context) => { - if (context && !getPageIdByVm(context)) { - context = null; - } - if (context) { - return new ServiceMediaQueryObserver(context); - } - return new ServiceMediaQueryObserver(getCurrentPageVm()); -}); -let eventReady = false; -let index$9 = 0; -let optionsCache = {}; -function operateEditor(componentId, pageId, type, options) { - const data = {}; - if (options && ("success" in options || "fail" in options || "complete" in options)) { - const callbackId = String(index$9++); - data.callbackId = callbackId; - optionsCache[callbackId] = options; - if (!eventReady) { - ServiceJSBridge.subscribe("onEditorMethodCallback", ({callbackId: callbackId2, data: data2}) => { - callOptions(optionsCache[callbackId2], data2); - delete optionsCache[callbackId2]; + 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 }); - eventReady = true; + 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); } - } - data.options = options; - ServiceJSBridge.publishHandler("editor." + componentId, { - componentId, - type, - data - }, pageId); -} -class EditorContext { - constructor(id2, pageId) { - this.id = id2; - this.pageId = pageId; - } - format(name, value) { - this._exec("format", { - name, - value - }); - } - insertDivider() { - this._exec("insertDivider"); - } - insertImage(options) { - this._exec("insertImage", options); - } - insertText(options) { - this._exec("insertText", options); - } - setContents(options) { - this._exec("setContents", options); - } - getContents(options) { - this._exec("getContents", options); - } - clear(options) { - this._exec("clear", options); - } - removeFormat(options) { - this._exec("removeFormat", options); - } - undo(options) { - this._exec("undo", options); - } - redo(options) { - this._exec("redo", options); - } - blur(options) { - this._exec("blur", options); - } - getSelectionText(options) { - this._exec("getSelectionText", options); - } - scrollIntoView(options) { - this._exec("scrollIntoView", options); - } - _exec(method, options) { - operateEditor(this.id, this.pageId, method, options); - } -} -const ContextClasss = { - canvas: CanvasContext, - map: MapContext, - video: VideoContext, - editor: EditorContext -}; -function convertContext(result) { - if (result && result.contextInfo) { - const {id: id2, type, page} = result.contextInfo; - const ContextClass = ContextClasss[type]; - result.context = new ContextClass(id2, page); - delete result.contextInfo; - } -} -class NodesRef { - constructor(selectorQuery, component, selector, single) { - this._selectorQuery = selectorQuery; - this._component = component; - this._selector = selector; - this._single = single; - } - boundingClientRect(callback) { - this._selectorQuery._push(this._selector, this._component, this._single, { - id: true, - dataset: true, - rect: true, - size: true - }, callback); - return this._selectorQuery; - } - fields(fields2, callback) { - this._selectorQuery._push(this._selector, this._component, this._single, fields2, callback); - return this._selectorQuery; - } - scrollOffset(callback) { - this._selectorQuery._push(this._selector, this._component, this._single, { - id: true, - dataset: true, - scrollOffset: true - }, callback); - return this._selectorQuery; - } - context(callback) { - this._selectorQuery._push(this._selector, this._component, this._single, { - context: true - }, callback); - return this._selectorQuery; - } -} -class SelectorQuery { - constructor(page) { - this._component = void 0; - this._page = page; - this._queue = []; - this._queueCb = []; - } - exec(callback) { - requestComponentInfo(this._page, this._queue, (res) => { - const queueCbs = this._queueCb; - res.forEach((result, index2) => { - if (Array.isArray(result)) { - result.forEach(convertContext); + }; + 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 { - convertContext(result); + 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; + } } - const queueCb = queueCbs[index2]; - if (typeof queueCb === "function") { - queueCb.call(this, result); + } else { + var doc = parent.ownerDocument; + if (parent != doc.body && parent != doc.documentElement && parentComputedStyle.overflow != "visible") { + parentRect = getBoundingClientRect(parent); } - }); - if (typeof callback === "function") { - callback.call(this, res); } + if (parentRect) { + intersectionRect = computeRectIntersection(parentRect, intersectionRect); + } + if (!intersectionRect) + break; + parent = parent && getParentNode(parent); + } + 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 + }; + } + return this._expandRectByRootMargin(rootRect); + }; + IntersectionObserver2.prototype._expandRectByRootMargin = function(rect) { + var margins = this._rootMarginValues.map(function(margin, i) { + return margin.unit == "px" ? margin.value : margin.value * (i % 2 ? rect.width : rect.height) / 100; }); - return this._nodesRef; + 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 i = 0; i < this.thresholds.length; i++) { + var threshold = this.thresholds[i]; + if (threshold == oldRatio || threshold == newRatio || threshold < oldRatio !== threshold < newRatio) { + return true; + } + } + }; + 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(); } - in(component) { - this._component = component || void 0; - return this; + function throttle2(fn, timeout) { + var timer = null; + return function() { + if (!timer) { + timer = setTimeout(function() { + fn(); + timer = null; + }, timeout); + } + }; } - select(selector) { - return this._nodesRef = new NodesRef(this, this._component, selector, true); + function addEvent(node, event, fn, opt_useCapture) { + if (typeof node.addEventListener == "function") { + node.addEventListener(event, fn, opt_useCapture || false); + } else if (typeof node.attachEvent == "function") { + node.attachEvent("on" + event, fn); + } } - selectAll(selector) { - return this._nodesRef = new NodesRef(this, this._component, selector, false); + function removeEvent(node, event, fn, opt_useCapture) { + if (typeof node.removeEventListener == "function") { + node.removeEventListener(event, fn, opt_useCapture || false); + } else if (typeof node.detatchEvent == "function") { + node.detatchEvent("on" + event, fn); + } } - selectViewport() { - return this._nodesRef = new NodesRef(this, null, "", true); + 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; } - _push(selector, component, single, fields2, callback) { - this._queue.push({ - component, - selector, - single, - fields: fields2 - }); - this._queueCb.push(callback); + function getBoundingClientRect(el) { + var rect; + try { + rect = el.getBoundingClientRect(); + } catch (err) { + } + 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; } -} -const createSelectorQuery = /* @__PURE__ */ defineSyncApi("createSelectorQuery", (context) => { - if (context && !getPageIdByVm(context)) { - context = null; + function getEmptyRect() { + return { + top: 0, + bottom: 0, + left: 0, + right: 0, + width: 0, + height: 0 + }; } - return new SelectorQuery(context || getCurrentPageVm()); -}); -const API_CREATE_ANIMATION = "createAnimation"; -const CreateAnimationOptions = { - formatArgs: {} -}; -const CreateAnimationProtocol = { - duration: Number, - timingFunction: String, - delay: Number, - transformOrigin: String -}; -const defaultOption = { - duration: 400, - timingFunction: "linear", - delay: 0, - transformOrigin: "50% 50% 0" -}; -class MPAnimation { - constructor(option) { - this.actions = []; - this.currentTransform = {}; - this.currentStepAnimates = []; - this.option = extend({}, defaultOption, option); + 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 + }; + } + 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); + } + return false; } - _getOption(option) { - const _option = { - transition: extend({}, this.option, option), - transformOrigin: "" - }; - _option.transformOrigin = _option.transition.transformOrigin; - delete _option.transition.transformOrigin; - return _option; + function getParentNode(node) { + var parent = node.parentNode; + if (node.nodeType == 9 && node != document2) { + return getFrameElement(node); + } + if (parent && parent.assignedSlot) { + parent = parent.assignedSlot.parentNode; + } + if (parent && parent.nodeType == 11 && parent.host) { + return parent.host; + } + return parent; } - _pushAnimates(type, args) { - this.currentStepAnimates.push({ - type, - args - }); + function isDoc(node) { + return node && node.nodeType === 9; } - _converType(type) { - return type.replace(/[A-Z]/g, (text2) => { - return `-${text2.toLowerCase()}`; + 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 requestComponentObserver($el, options, callback) { + initIntersectionObserverPolyfill(); + const root = options.relativeToSelector ? $el.querySelector(options.relativeToSelector) : null; + const intersectionObserver = new IntersectionObserver((entries2) => { + entries2.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 i = 0; i < nodeList.length; i++) { + intersectionObserver.observe(nodeList[i]); + } + } 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); + } } - _getValue(value) { - return typeof value === "number" ? `${value}px` : value; - } - export() { - const actions = this.actions; - this.actions = []; - return { - actions - }; + return intersectionObserver; +} +const props$i = { + indicatorDots: { + type: [Boolean, String], + default: false + }, + vertical: { + type: [Boolean, String], + default: false + }, + autoplay: { + type: [Boolean, String], + default: false + }, + circular: { + type: [Boolean, String], + default: false + }, + interval: { + type: [Number, String], + default: 5e3 + }, + duration: { + type: [Number, String], + default: 500 + }, + current: { + type: [Number, String], + default: 0 + }, + indicatorColor: { + type: String, + default: "" + }, + indicatorActiveColor: { + type: String, + default: "" + }, + previousMargin: { + type: String, + default: "" + }, + nextMargin: { + type: String, + default: "" + }, + currentItemId: { + type: String, + default: "" + }, + skipHiddenItemLayout: { + type: [Boolean, String], + default: false + }, + displayMultipleItems: { + type: [Number, String], + default: 1 + }, + disableTouch: { + type: [Boolean, String], + default: false } - step(option) { - this.currentStepAnimates.forEach((animate) => { - if (animate.type !== "style") { - this.currentTransform[animate.type] = animate; - } else { - this.currentTransform[`${animate.type}.${animate.args[0]}`] = animate; - } - }); - this.actions.push({ - animates: Object.values(this.currentTransform), - option: this._getOption(option) +}; +function upx2pxStr(val) { + if (/\d+[ur]px$/i.test(val)) { + val.replace(/\d+[ur]px$/i, (text2) => { + return `${upx2px(parseFloat(text2))}px`; }); - this.currentStepAnimates = []; - return this; } + return val || ""; } -const initAnimationProperty = /* @__PURE__ */ once(() => { - const animateTypes1 = [ - "matrix", - "matrix3d", - "rotate", - "rotate3d", - "rotateX", - "rotateY", - "rotateZ", - "scale", - "scale3d", - "scaleX", - "scaleY", - "scaleZ", - "skew", - "skewX", - "skewY", - "translate", - "translate3d", - "translateX", - "translateY", - "translateZ" - ]; - const animateTypes2 = ["opacity", "backgroundColor"]; - const animateTypes3 = ["width", "height", "left", "right", "top", "bottom"]; - animateTypes1.concat(animateTypes2, animateTypes3).forEach((type) => { - MPAnimation.prototype[type] = function(...args) { - if (animateTypes2.concat(animateTypes3).includes(type)) { - this._pushAnimates("style", [ - this._converType(type), - animateTypes3.includes(type) ? this._getValue(args[0]) : args[0] - ]); - } else { - this._pushAnimates(type, args); - } - return this; - }; +function useState$2(props2) { + const interval = computed(() => { + const interval2 = Number(props2.interval); + return isNaN(interval2) ? 5e3 : interval2; }); -}); -const createAnimation = /* @__PURE__ */ defineSyncApi(API_CREATE_ANIMATION, (option) => { - initAnimationProperty(); - return new MPAnimation(option); -}, CreateAnimationProtocol, CreateAnimationOptions); -const API_ON_TAB_BAR_MID_BUTTON_TAP = "onTabBarMidButtonTap"; -const onTabBarMidButtonTap = /* @__PURE__ */ defineOnApi(API_ON_TAB_BAR_MID_BUTTON_TAP, () => { -}); -const API_GET_SELECTED_TEXT_RANGE = "getSelectedTextRange"; -const getSelectedTextRangeEventCallbacks = createCallbacks("getSelectedTextRangeEvent"); -ServiceJSBridge.subscribe && ServiceJSBridge.subscribe("onGetSelectedTextRange", ({callbackId, data}) => { - const callback = getSelectedTextRangeEventCallbacks.pop(callbackId); - if (callback) { - callback(data); + const duration = computed(() => { + const duration2 = Number(props2.duration); + return isNaN(duration2) ? 500 : duration2; + }); + const displayMultipleItems = computed(() => { + const displayMultipleItems2 = Math.round(props2.displayMultipleItems); + return isNaN(displayMultipleItems2) ? 1 : displayMultipleItems2; + }); + const state2 = reactive({ + interval, + duration, + displayMultipleItems, + current: Math.round(props2.current) || 0, + currentItemId: props2.currentItemId, + userTracking: false + }); + return state2; +} +function useLayout(props2, state2, swiperContexts, slideFrameRef, emit2, trigger) { + function cancelSchedule() { + if (timer) { + clearTimeout(timer); + timer = null; + } } -}); -const getSelectedTextRange = /* @__PURE__ */ defineAsyncApi(API_GET_SELECTED_TEXT_RANGE, (_, {resolve, reject}) => { - const pageId = getCurrentPageId(); - ServiceJSBridge.publishHandler && ServiceJSBridge.publishHandler("getSelectedTextRange", { - pageId, - callbackId: getSelectedTextRangeEventCallbacks.push(function(res) { - if (typeof res.end === "undefined" && typeof res.start === "undefined") { - reject("no focused"); - } else { - resolve(res); + let timer = null; + let invalid = true; + let viewportPosition = 0; + let viewportMoveRatio = 1; + let animating = null; + let requestedAnimation = false; + let contentTrackViewport = 0; + let transitionStart; + let currentChangeSource = ""; + let animationFrame; + const circularEnabled = computed(() => props2.circular && swiperContexts.value.length > state2.displayMultipleItems); + function checkCircularLayout(index2) { + if (!invalid) { + for (let items = swiperContexts.value, n = items.length, i = index2 + state2.displayMultipleItems, r = 0; r < n; r++) { + const item = items[r]; + const s = Math.floor(index2 / n) * n + r; + const l = s + n; + const c = s - n; + const u = Math.max(index2 - (s + 1), s - i, 0); + const d = Math.max(index2 - (l + 1), l - i, 0); + const h = Math.max(index2 - (c + 1), c - i, 0); + const p2 = Math.min(u, d, h); + const position = [s, l, c][[u, d, h].indexOf(p2)]; + item.updatePosition(position, props2.vertical); } - }) - }, pageId); -}); -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 + function updateViewport(index2) { + if (!(Math.floor(2 * viewportPosition) === Math.floor(2 * index2) && Math.ceil(2 * viewportPosition) === Math.ceil(2 * index2))) { + if (circularEnabled.value) { + checkCircularLayout(index2); + } + } + const x = props2.vertical ? "0" : 100 * -index2 * viewportMoveRatio + "%"; + const y = props2.vertical ? 100 * -index2 * viewportMoveRatio + "%" : "0"; + const transform = "translate(" + x + ", " + y + ") translateZ(0)"; + const slideFrame = slideFrameRef.value; + if (slideFrame) { + slideFrame.style.webkitTransform = transform; + slideFrame.style.transform = transform; + } + viewportPosition = index2; + if (!transitionStart) { + if (index2 % 1 === 0) { + return; + } + transitionStart = index2; + } + index2 -= Math.floor(transitionStart); + const items = swiperContexts.value; + if (index2 <= -(items.length - 1)) { + index2 += items.length; + } else if (index2 >= items.length) { + index2 -= items.length; + } + index2 = transitionStart % 1 > 0.5 || transitionStart < 0 ? index2 - 1 : index2; + trigger("transition", {}, { + dx: props2.vertical ? 0 : index2 * slideFrame.offsetWidth, + dy: props2.vertical ? index2 * slideFrame.offsetHeight : 0 + }); } -}; -const API_GET_STORAGE_SYNC = "getStorageSync"; -const GetStorageSyncProtocol = [ - { - name: "key", - type: String, - required: true + function endViewportAnimation() { + if (animating) { + updateViewport(animating.toPos); + animating = null; + } } -]; -const API_SET_STORAGE = "setStorage"; -const SetStorageProtocol = { - key: { - type: String, - required: true - }, - data: { - required: true + function normalizeCurrentValue(current) { + const length = swiperContexts.value.length; + if (!length) { + return -1; + } + const index2 = (Math.round(current) % length + length) % length; + if (circularEnabled.value) { + if (length <= state2.displayMultipleItems) { + return 0; + } + } else if (index2 > length - state2.displayMultipleItems) { + return length - state2.displayMultipleItems; + } + return index2; } -}; -const API_SET_STORAGE_SYNC = "setStorageSync"; -const SetStorageSyncProtocol = [ - { - name: "key", - type: String, - required: true - }, - { - name: "data", - required: true + function cancelViewportAnimation() { + animating = null; } -]; -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); + function animateFrameFuncProto() { + if (!animating) { + requestedAnimation = false; + return; } + const _animating = animating; + const toPos = _animating.toPos; + const acc = _animating.acc; + const endTime = _animating.endTime; + const source = _animating.source; + const time = endTime - Date.now(); + if (time <= 0) { + updateViewport(toPos); + animating = null; + requestedAnimation = false; + transitionStart = null; + const item = swiperContexts.value[state2.current]; + if (item) { + const currentItemId = item.getItemId(); + trigger("animationfinish", {}, { + current: state2.current, + currentItemId, + source + }); + } + return; + } + const s = acc * time * time / 2; + const l = toPos + s; + updateViewport(l); + animationFrame = requestAnimationFrame(animateFrameFuncProto); } -}; -const GetFileInfoProtocol = { - filePath: { - type: String, - required: true - } -}; -const API_OPEN_DOCUMENT = "openDocument"; -const OpenDocumentOptions = { - formatArgs: { - filePath(filePath, params) { - params.filePath = getRealPath(filePath); + function animateViewport(current, source, n) { + cancelViewportAnimation(); + const duration = state2.duration; + const length = swiperContexts.value.length; + let position = viewportPosition; + if (circularEnabled.value) { + if (n < 0) { + for (; position < current; ) { + position += length; + } + for (; position - length > current; ) { + position -= length; + } + } else if (n > 0) { + for (; position > current; ) { + position -= length; + } + for (; position + length < current; ) { + position += length; + } + } else { + for (; position + length < current; ) { + position += length; + } + for (; position - length > current; ) { + position -= length; + } + if (position + length - current < current - position) { + position += length; + } + } + } + animating = { + toPos: current, + acc: 2 * (position - current) / (duration * duration), + endTime: Date.now() + duration, + source + }; + if (!requestedAnimation) { + requestedAnimation = true; + animationFrame = requestAnimationFrame(animateFrameFuncProto); } } -}; -const OpenDocumentProtocol = { - filePath: { - type: String, - required: true - }, - fileType: String -}; -const API_HIDE_KEYBOARD = "hideKeyboard"; -const API_CHOOSE_LOCATION = "chooseLocation"; -const ChooseLocationProtocol = { - keyword: String, - latitude: Number, - longitude: Number -}; -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]; + function scheduleAutoplay() { + cancelSchedule(); + const items = swiperContexts.value; + const callback = function() { + timer = null; + currentChangeSource = "autoplay"; + if (circularEnabled.value) { + state2.current = normalizeCurrentValue(state2.current + 1); } else { - params.type = value; + state2.current = state2.current + state2.displayMultipleItems < items.length ? state2.current + 1 : 0; } - }, - altitude(value, params) { - params.altitude = value ? value : false; + animateViewport(state2.current, "autoplay", circularEnabled.value ? 1 : 0); + timer = setTimeout(callback, state2.interval); + }; + if (!(invalid || items.length <= state2.displayMultipleItems)) { + timer = setTimeout(callback, state2.interval); } } -}; -const GetLocationProtocol = { - type: String, - altitude: Boolean -}; -const API_OPEN_LOCATION = "openLocation"; -const OpenLocationOptions = { - formatArgs: { - scale(value, params) { - value = Math.floor(value); - params.scale = value >= 5 && value <= 18 ? value : 18; + function resetLayout() { + cancelSchedule(); + endViewportAnimation(); + const items = swiperContexts.value; + for (let i = 0; i < items.length; i++) { + items[i].updatePosition(i, props2.vertical); } - } -}; -const OpenLocationProtocol = { - latitude: { - type: Number, - required: true - }, - longitude: { - type: Number, - required: true - }, - scale: Number, - name: String, - address: String -}; -const API_CHOOSE_IMAGE = "chooseImage"; -const ChooseImageOptions = { - formatArgs: { - count(value, params) { - if (!value || value <= 0) { - params.count = 9; - } - }, - 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."; + viewportMoveRatio = 1; + const slideFrameEl = slideFrameRef.value; + if (state2.displayMultipleItems === 1 && items.length) { + const itemRect = items[0].getBoundingClientRect(); + const slideFrameRect = slideFrameEl.getBoundingClientRect(); + viewportMoveRatio = itemRect.width / slideFrameRect.width; + if (!(viewportMoveRatio > 0 && viewportMoveRatio < 1)) { + viewportMoveRatio = 1; } - 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."; + const position = viewportPosition; + viewportPosition = -2; + const current = state2.current; + if (current >= 0) { + invalid = false; + if (state2.userTracking) { + updateViewport(position + current - contentTrackViewport); + contentTrackViewport = current; + } else { + updateViewport(current); + if (props2.autoplay) { + scheduleAutoplay(); + } } - if (!extension) - params.extension = [""]; + } else { + invalid = true; + updateViewport(-state2.displayMultipleItems - 1); } } -}; -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; - } - }, - 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."; + watch([() => props2.current, () => props2.currentItemId, () => [...swiperContexts.value]], () => { + let current = -1; + if (props2.currentItemId) { + for (let i = 0, items = swiperContexts.value; i < items.length; i++) { + const itemId = items[i].getItemId(); + if (itemId === props2.currentItemId) { + current = i; + break; + } } - if (!extension) - params.extension = [""]; } - } -}; -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 (current < 0) { + current = Math.round(props2.current) || 0; } - } -}; -const GetImageInfoProtocol = { - src: { - type: String, - required: true - } -}; -const API_PREVIEW_IMAGE = "previewImage"; -const PreviewImageOptions = { - formatArgs: { - urls(urls, params) { - params.urls = urls.map((url) => typeof url === "string" && url ? getRealPath(url) : ""); - }, - current(current, params) { - if (typeof current === "number") { - params.current = current > 0 && current < params.urls.length ? current : 0; - } else if (typeof current === "string" && current) { - params.current = getRealPath(current); - } + current = current < 0 ? 0 : current; + if (state2.current !== current) { + currentChangeSource = ""; + state2.current = current; } - } -}; -const PreviewImageProtocol = { - urls: { - type: Array, - required: true - }, - current: { - type: [Number, String] - } -}; -const API_GET_VIDEO_INFO = "getVideoInfo"; -const GetVideoInfoOptions = { - formatArgs: { - src(src, params) { - params.src = getRealPath(src); + }); + watch([() => props2.vertical, () => circularEnabled.value, () => state2.displayMultipleItems, () => [...swiperContexts.value]], resetLayout); + watch(() => state2.interval, () => { + if (timer) { + cancelSchedule(); + scheduleAutoplay(); + } + }); + function currentChanged(current, history2) { + const source = currentChangeSource; + currentChangeSource = ""; + const items = swiperContexts.value; + if (!source) { + const length = items.length; + animateViewport(current, "", circularEnabled.value && history2 + (length - current) % length > length / 2 ? 1 : 0); + } + const item = items[current]; + if (item) { + const currentItemId = state2.currentItemId = item.getItemId(); + trigger("change", {}, { + current: state2.current, + currentItemId, + source + }); } } -}; -const GetVideoInfoProtocol = { - src: { - type: String, - required: true - } -}; -const API_SAVE_IMAGE_TO_PHOTOS_ALBUM = "saveImageToPhotosAlbum"; -const API_SAVE_VIDEO_TO_PHOTOS_ALBUM = "saveVideoToPhotosAlbum"; -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]; + watch(() => state2.current, (val, oldVal) => { + currentChanged(val, oldVal); + emit2("update:current", val); }); - for (const key in data) { - if (hasOwn(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); + watch(() => state2.currentItemId, (val) => { + emit2("update:currentItemId", val); + }); + function inintAutoplay(enable) { + if (enable) { + scheduleAutoplay(); + } else { + cancelSchedule(); } } - 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); + watch(() => props2.autoplay && !state2.userTracking, inintAutoplay); + inintAutoplay(props2.autoplay && !state2.userTracking); + onMounted(() => { + let userDirectionChecked = false; + let contentTrackSpeed = 0; + let contentTrackT = 0; + function handleTrackStart() { + cancelSchedule(); + contentTrackViewport = viewportPosition; + contentTrackSpeed = 0; + contentTrackT = Date.now(); + cancelViewportAnimation(); + } + function handleTrackMove(data) { + const oldContentTrackT = contentTrackT; + contentTrackT = Date.now(); + const length = swiperContexts.value.length; + const other = length - state2.displayMultipleItems; + function calc2(val) { + return 0.5 - 0.25 / (val + 0.5); } - }, - 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"; + function move(oldVal, newVal) { + let val = contentTrackViewport + oldVal; + contentTrackSpeed = 0.6 * contentTrackSpeed + 0.4 * newVal; + if (!circularEnabled.value) { + if (val < 0 || val > other) { + if (val < 0) { + val = -calc2(-val); + } else { + if (val > other) { + val = other + calc2(val - other); + } + } + contentTrackSpeed = 0; + } } + updateViewport(val); } - }, - 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 time = contentTrackT - oldContentTrackT || 1; + const slideFrameEl = slideFrameRef.value; + if (props2.vertical) { + move(-data.dy / slideFrameEl.offsetHeight, -data.ddy / time); + } else { + move(-data.dx / slideFrameEl.offsetWidth, -data.ddx / time); } } - } -}; -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); + function handleTrackEnd(isCancel) { + state2.userTracking = false; + const t2 = contentTrackSpeed / Math.abs(contentTrackSpeed); + let n = 0; + if (!isCancel && Math.abs(contentTrackSpeed) > 0.2) { + n = 0.5 * t2; + } + const current = normalizeCurrentValue(viewportPosition + n); + if (isCancel) { + updateViewport(contentTrackViewport); + } else { + currentChangeSource = "touch"; + state2.current = current; + animateViewport(current, "touch", n !== 0 ? n : current === 0 && circularEnabled.value && viewportPosition >= 1 ? 1 : 0); } - }, - header(value, params) { - params.header = value || {}; - }, - formData(value, params) { - params.formData = value || {}; } + useTouchtrack(slideFrameRef.value, (event) => { + if (props2.disableTouch) { + return; + } + if (!invalid) { + if (event.detail.state === "start") { + state2.userTracking = true; + userDirectionChecked = false; + return handleTrackStart(); + } + if (event.detail.state === "end") { + return handleTrackEnd(false); + } + if (event.detail.state === "cancel") { + return handleTrackEnd(true); + } + if (state2.userTracking) { + if (!userDirectionChecked) { + userDirectionChecked = true; + const t2 = Math.abs(event.detail.dx); + const n = Math.abs(event.detail.dy); + if (t2 >= n && props2.vertical) { + state2.userTracking = false; + } else { + if (t2 <= n && !props2.vertical) { + state2.userTracking = false; + } + } + if (!state2.userTracking) { + if (props2.autoplay) { + scheduleAutoplay(); + } + return; + } + } + handleTrackMove(event.detail); + return false; + } + } + }); + }); + onUnmounted(() => { + cancelSchedule(); + cancelAnimationFrame(animationFrame); + }); + function onSwiperDotClick(index2) { + animateViewport(state2.current = index2, currentChangeSource = "click", circularEnabled.value ? 1 : 0); } -}; -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]; + return { + onSwiperDotClick + }; +} +var Swiper = /* @__PURE__ */ defineBuiltInComponent({ + name: "Swiper", + props: props$i, + emits: ["change", "transition", "animationfinish", "update:current", "update:currentItemId"], + setup(props2, { + slots, + emit: emit2 + }) { + const rootRef = ref(null); + const trigger = useCustomEvent(rootRef, emit2); + const slidesWrapperRef = ref(null); + const slideFrameRef = ref(null); + const state2 = useState$2(props2); + const slidesStyle = computed(() => { + let style = {}; + if (props2.nextMargin || props2.previousMargin) { + style = props2.vertical ? { + left: 0, + right: 0, + top: upx2pxStr(props2.previousMargin), + bottom: upx2pxStr(props2.nextMargin) + } : { + top: 0, + bottom: 0, + left: upx2pxStr(props2.previousMargin), + right: upx2pxStr(props2.nextMargin) + }; + } + return style; + }); + const slideFrameStyle = computed(() => { + const value = Math.abs(100 / state2.displayMultipleItems) + "%"; + return { + width: props2.vertical ? "100%" : value, + height: !props2.vertical ? "100%" : value + }; + }); + let swiperItems = []; + const originSwiperContexts = []; + const swiperContexts = ref([]); + function updateSwiperContexts() { + const contexts = []; + for (let index2 = 0; index2 < swiperItems.length; index2++) { + const swiperItem = swiperItems[index2]; + const swiperContext = originSwiperContexts.find((context) => swiperItem.el === context.rootRef.value); + if (swiperContext) { + contexts.push(markRaw(swiperContext)); + } } + swiperContexts.value = contexts; } + const addSwiperContext = function(swiperContext) { + originSwiperContexts.push(swiperContext); + updateSwiperContexts(); + }; + provide("addSwiperContext", addSwiperContext); + const removeSwiperContext = function(swiperContext) { + const index2 = originSwiperContexts.indexOf(swiperContext); + if (index2 >= 0) { + originSwiperContexts.splice(index2, 1); + updateSwiperContexts(); + } + }; + provide("removeSwiperContext", removeSwiperContext); + const { + onSwiperDotClick + } = useLayout(props2, state2, swiperContexts, slideFrameRef, emit2, trigger); + return () => { + const defaultSlots = slots.default && slots.default(); + swiperItems = flatVNode(defaultSlots); + return createVNode("uni-swiper", { + "ref": rootRef + }, [createVNode("div", { + "ref": slidesWrapperRef, + "class": "uni-swiper-wrapper" + }, [createVNode("div", { + "class": "uni-swiper-slides", + "style": slidesStyle.value + }, [createVNode("div", { + "ref": slideFrameRef, + "class": "uni-swiper-slide-frame", + "style": slideFrameStyle.value + }, [defaultSlots], 4)], 4), props2.indicatorDots && createVNode("div", { + "class": ["uni-swiper-dots", props2.vertical ? "uni-swiper-dots-vertical" : "uni-swiper-dots-horizontal"] + }, [swiperContexts.value.map((_, index2, array) => createVNode("div", { + "onClick": () => onSwiperDotClick(index2), + "class": { + "uni-swiper-dot": true, + "uni-swiper-dot-active": index2 < state2.current + state2.displayMultipleItems && index2 >= state2.current || index2 < state2.current + state2.displayMultipleItems - array.length + }, + "style": { + background: index2 === state2.current ? props2.indicatorActiveColor : props2.indicatorColor + } + }, null, 14, ["onClick"]))], 2)], 512)], 512); + }; } -}; -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: { +}); +const props$h = { + itemId: { 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 PreloadPageProtocol = 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); - } + default: "" } }; -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("`|`") + "`)"; +var SwiperItem = /* @__PURE__ */ defineBuiltInComponent({ + name: "SwiperItem", + props: props$h, + setup(props2, { + slots + }) { + const rootRef = ref(null); + const context = { + rootRef, + getItemId() { + return props2.itemId; + }, + getBoundingClientRect() { + const el = rootRef.value; + return el.getBoundingClientRect(); + }, + updatePosition(position, vertical) { + const x = vertical ? "0" : 100 * position + "%"; + const y = vertical ? 100 * position + "%" : "0"; + const rootEl = rootRef.value; + const value = `translate(${x},${y}) translateZ(0)`; + if (rootEl) { + rootEl.style.webkitTransform = value; + rootEl.style.transform = value; } } - }, - 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`; + }; + onMounted(() => { + const addSwiperContext = inject("addSwiperContext"); + if (addSwiperContext) { + addSwiperContext(context); } - } else if (type === API_SWITCH_TAB) { - if (!routeOptions.meta.isTabBar) { - return "can not switch to no-tabBar page"; + }); + onUnmounted(() => { + const removeSwiperContext = inject("removeSwiperContext"); + if (removeSwiperContext) { + removeSwiperContext(context); } - } - 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(); - const tabBarPagePath = routeOptions.path.substr(1); - if (pages.find((page) => page.route === tabBarPagePath)) { - return "tabBar page `" + tabBarPagePath + "` already exists"; + }); + return () => { + return createVNode("uni-swiper-item", { + "ref": rootRef, + "style": { + position: "absolute", + width: "100%", + height: "100%" } - } - return; - } - if (navigatorLock === url && params.openType !== "appLaunch") { - return `${navigatorLock} locked`; - } - if (__uniConfig.ready) { - navigatorLock = url; - } - }; -} -const API_HIDE_LOADING = "hideLoading"; -const API_HIDE_TOAST = "hideToast"; -const API_LOAD_FONT_FACE = "loadFontFace"; -const LoadFontFaceProtocol = { - family: { + }, [slots.default && slots.default()], 512); + }; + } +}); +const props$g = { + name: { type: String, - required: true + default: "" }, - source: { - type: String, - required: true + checked: { + type: [Boolean, String], + default: false }, - desc: Object -}; -const FRONT_COLORS = ["#ffffff", "#000000"]; -const API_SET_NAVIGATION_BAR_COLOR = "setNavigationBarColor"; -const SetNavigationBarColorOptions = { - formatArgs: { - animation(animation2, params) { - if (!animation2) { - animation2 = {duration: 0, timingFunc: "linear"}; - } - params.animation = { - duration: animation2.duration || 0, - timingFunc: animation2.timingFunc || "linear" - }; - } - } -}; -const SetNavigationBarColorProtocol = { - frontColor: { + type: { type: String, - required: true, - validator(frontColor) { - if (FRONT_COLORS.indexOf(frontColor) === -1) { - return `invalid frontColor "${frontColor}"`; - } - } + default: "switch" }, - backgroundColor: { + id: { type: String, - required: true + default: "" }, - 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 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 API_SHOW_ACTION_SHEET = "showActionSheet"; -const ShowActionSheetProtocol = { - itemList: { - type: Array, - required: true + disabled: { + type: [Boolean, String], + default: false }, - itemColor: String, - popover: Object -}; -const ShowActionSheetOptions = { - formatArgs: { - itemColor: "#000" - } -}; -const API_SHOW_LOADING = "showLoading"; -const ShowLoadingProtocol = { - title: String, - mask: Boolean -}; -const ShowLoadingOptions = { - formatArgs: { - title: "", - mask: false + color: { + type: String, + default: "#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(params, "cancelText")) { - const {t: t2} = useI18n(); - params.cancelText = t2("uni.showModal.cancel"); - } - }, - cancelColor: "#000", - confirmText(_value, params) { - if (!hasOwn(params, "confirmText")) { - const {t: t2} = useI18n(); - params.confirmText = t2("uni.showModal.confirm"); +var index$d = /* @__PURE__ */ defineBuiltInComponent({ + name: "Switch", + props: props$g, + emits: ["change"], + setup(props2, { + emit: emit2 + }) { + const rootRef = ref(null); + const switchChecked = ref(props2.checked); + const uniLabel = useSwitchInject(props2, switchChecked); + const trigger = useCustomEvent(rootRef, emit2); + watch(() => props2.checked, (val) => { + switchChecked.value = val; + }); + const _onClick = ($event) => { + if (props2.disabled) { + return; } - }, - confirmColor: PRIMARY_COLOR + switchChecked.value = !switchChecked.value; + trigger("change", $event, { + value: switchChecked.value + }); + }; + if (!!uniLabel) { + uniLabel.addHandler(_onClick); + onBeforeUnmount(() => { + uniLabel.removeHandler(_onClick); + }); + } + useListeners$1(props2, { + "label-click": _onClick + }); + return () => { + const { + color, + type + } = props2; + const { + booleanAttrs + } = useBooleanAttr(props2, "disabled"); + return createVNode("uni-switch", mergeProps({ + "ref": rootRef + }, booleanAttrs, { + "onClick": _onClick + }), [createVNode("div", { + "class": "uni-switch-wrapper" + }, [withDirectives(createVNode("div", { + "class": ["uni-switch-input", [switchChecked.value ? "uni-switch-input-checked" : ""]], + "style": { + backgroundColor: switchChecked.value ? color : "#DFDFDF", + borderColor: switchChecked.value ? color : "#DFDFDF" + } + }, null, 6), [[vShow, type === "switch"]]), withDirectives(createVNode("div", { + "class": "uni-checkbox-input" + }, [switchChecked.value ? createSvgIconVNode(ICON_PATH_SUCCESS_NO_CIRCLE, props2.color, 22) : ""], 512), [[vShow, type === "checkbox"]])])], 16, ["onClick"]); + }; } -}; -const API_SHOW_TOAST = "showToast"; -const SHOW_TOAST_ICON = [ - "success", - "loading", - "none" -]; -const ShowToastProtocol = { - title: String, - icon: String, - image: String, - duration: Number, - mask: Boolean -}; -const ShowToastOptions = { - formatArgs: { - title: "", - icon(type, params) { - params.icon = elemInArray(type, SHOW_TOAST_ICON); - }, - image(value, params) { - if (value) { - params.image = getRealPath(value); - } else { - params.image = ""; +}); +function useSwitchInject(props2, switchChecked) { + const uniForm = inject(uniFormKey, false); + const uniLabel = inject(uniLabelKey, false); + const formField = { + submit: () => { + const data = ["", null]; + if (props2.name) { + data[0] = props2.name; + data[1] = switchChecked.value; } + return data; }, - duration: 1500, - mask: false - } -}; -const API_START_PULL_DOWN_REFRESH = "startPullDownRefresh"; -const API_STOP_PULL_DOWN_REFRESH = "stopPullDownRefresh"; -const IndexProtocol = { - index: { - type: Number, - required: true + reset: () => { + switchChecked.value = false; + } + }; + if (!!uniForm) { + uniForm.addField(formField); + onUnmounted(() => { + uniForm.removeField(formField); + }); } + return uniLabel; +} +const SPACE_UNICODE = { + ensp: "\u2002", + emsp: "\u2003", + nbsp: "\xA0" }; -const IndexOptions = { - beforeInvoke() { - const pageMeta = getCurrentPageMeta(); - if (pageMeta && !pageMeta.isTabBar) { - return "not TabBar page"; +function normalizeText(text2, { + space, + decode: decode2 +}) { + if (space && SPACE_UNICODE[space]) { + text2 = text2.replace(/ /g, SPACE_UNICODE[space]); + } + if (!decode2) { + return text2; + } + return text2.replace(/ /g, SPACE_UNICODE.nbsp).replace(/ /g, SPACE_UNICODE.ensp).replace(/ /g, SPACE_UNICODE.emsp).replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&").replace(/"/g, '"').replace(/'/g, "'"); +} +var index$c = /* @__PURE__ */ defineBuiltInComponent({ + name: "Text", + props: { + selectable: { + type: [Boolean, String], + default: false + }, + space: { + type: String, + default: "" + }, + decode: { + type: [Boolean, String], + default: false } }, - formatArgs: { - index(value) { - if (!__uniConfig.tabBar.list[value]) { - return "tabbar item not found"; + setup(props2, { + slots + }) { + return () => { + const children = []; + if (slots.default) { + slots.default().forEach((vnode) => { + if (vnode.shapeFlag & 8) { + const lines = vnode.children.replace(/\\n/g, "\n").split("\n"); + const len = lines.length - 1; + lines.forEach((text2, index2) => { + if (index2 === 0 && !text2) + ; + else { + children.push(createTextVNode(normalizeText(text2, { + space: props2.space, + decode: props2.decode + }))); + } + if (index2 !== len) { + children.push(createVNode("br")); + } + }); + } else { + if (process.env.NODE_ENV !== "production" && vnode.shapeFlag & 6 && vnode.type.name !== "Text") { + console.warn("Do not nest other components in the text component, as there may be display differences on different platforms."); + } + children.push(vnode); + } + }); } - } + return createVNode("uni-text", { + "selectable": props2.selectable ? true : null + }, [createVNode("span", null, children)], 8, ["selectable"]); + }; } -}; -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); +}); +const props$f = /* @__PURE__ */ extend({}, props$u, { + placeholderClass: { + type: String, + default: "input-placeholder" + }, + autoHeight: { + type: [Boolean, String], + default: false + }, + confirmType: { + type: String, + default: "" + } +}); +var index$b = /* @__PURE__ */ defineBuiltInComponent({ + name: "Textarea", + props: props$f, + emit: ["confirm", "linechange", ...emit], + setup(props2, { + emit: emit2 + }) { + const rootRef = ref(null); + const { + fieldRef, + state: state2, + scopedAttrsState, + fixDisabledColor, + trigger + } = useField(props2, rootRef, emit2); + const valueCompute = computed(() => state2.value.split("\n")); + const isDone = computed(() => ["done", "go", "next", "search", "send"].includes(props2.confirmType)); + const heightRef = ref(0); + const lineRef = ref(null); + watch(() => heightRef.value, (height) => { + const el = rootRef.value; + const lineEl = lineRef.value; + let lineHeight = parseFloat(getComputedStyle(el).lineHeight); + if (isNaN(lineHeight)) { + lineHeight = lineEl.offsetHeight; + } + var lineCount = Math.round(height / lineHeight); + trigger("linechange", {}, { + height, + heightRpx: 750 / window.innerWidth * height, + lineCount + }); + if (props2.autoHeight) { + el.style.height = height + "px"; } + }); + function onResize2({ + height + }) { + heightRef.value = height; } - }, 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); + function confirm(event) { + trigger("confirm", event, { + value: state2.value + }); + } + function onKeyDownEnter(event) { + if (event.key !== "Enter") { + return; } - }, - borderStyle(value, params) { - if (value) { - params.borderStyle = value === "white" ? "white" : "black"; + if (isDone.value) { + event.preventDefault(); + } + } + function onKeyUpEnter(event) { + if (event.key !== "Enter") { + return; + } + if (isDone.value) { + confirm(event); + const textarea = event.target; + textarea.blur(); + } + } + const DARK_TEST_STRING = "(prefers-color-scheme: dark)"; + const fixMargin = String(navigator.platform).indexOf("iP") === 0 && String(navigator.vendor).indexOf("Apple") === 0 && window.matchMedia(DARK_TEST_STRING).media !== DARK_TEST_STRING; + return () => { + let textareaNode = props2.disabled && fixDisabledColor ? createVNode("textarea", { + "ref": fieldRef, + "value": state2.value, + "tabindex": "-1", + "readonly": !!props2.disabled, + "maxlength": state2.maxlength, + "class": { + "uni-textarea-textarea": true, + "uni-textarea-textarea-fix-margin": fixMargin + }, + "style": { + overflowY: props2.autoHeight ? "hidden" : "auto" + }, + "onFocus": (event) => event.target.blur() + }, null, 46, ["value", "readonly", "maxlength", "onFocus"]) : createVNode("textarea", { + "ref": fieldRef, + "value": state2.value, + "disabled": !!props2.disabled, + "maxlength": state2.maxlength, + "enterkeyhint": props2.confirmType, + "class": { + "uni-textarea-textarea": true, + "uni-textarea-textarea-fix-margin": fixMargin + }, + "style": { + overflowY: props2.autoHeight ? "hidden" : "auto" + }, + "onKeydown": onKeyDownEnter, + "onKeyup": onKeyUpEnter + }, null, 46, ["value", "disabled", "maxlength", "enterkeyhint", "onKeydown", "onKeyup"]); + return createVNode("uni-textarea", { + "ref": rootRef + }, [createVNode("div", { + "class": "uni-textarea-wrapper" + }, [withDirectives(createVNode("div", mergeProps(scopedAttrsState.attrs, { + "style": props2.placeholderStyle, + "class": ["uni-textarea-placeholder", props2.placeholderClass] + }), [props2.placeholder], 16), [[vShow, !state2.value.length]]), createVNode("div", { + "ref": lineRef, + "class": "uni-textarea-line" + }, [" "], 512), createVNode("div", { + "class": "uni-textarea-compute" + }, [valueCompute.value.map((item) => createVNode("div", null, [item.trim() ? item : "."])), createVNode(ResizeSensor, { + "initial": true, + "onResize": onResize2 + }, null, 8, ["initial", "onResize"])]), props2.confirmType === "search" ? createVNode("form", { + "action": "", + "onSubmit": () => false, + "class": "uni-input-form" + }, [textareaNode], 40, ["onSubmit"]) : textareaNode])], 512); + }; + } +}); +var index$a = /* @__PURE__ */ defineBuiltInComponent({ + name: "View", + props: extend({}, hoverProps), + setup(props2, { + slots + }) { + const { + hovering, + binding + } = useHover(props2); + return () => { + const hoverClass = props2.hoverClass; + if (hoverClass && hoverClass !== "none") { + return createVNode("uni-view", mergeProps({ + "class": hovering.value ? hoverClass : "" + }, binding), [slots.default && slots.default()], 16); } - } + return createVNode("uni-view", null, [slots.default && slots.default()]); + }; } -}; -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 +}); +function normalizeEvent(pageId, vm, id2) { + if (!id2) { + id2 = vm.id; } -}, IndexProtocol); -const SetTabBarBadgeOptions = { - beforeInvoke: IndexOptions.beforeInvoke, - formatArgs: /* @__PURE__ */ extend({ - text(value, params) { - if (getLen(value) >= 4) { - params.text = "..."; - } - } - }, IndexOptions.formatArgs) -}; -const API_ON_WINDOW_RESIZE = "onWindowResize"; -const API_OFF_WINDOW_RESIZE = "offWindowResize"; -const initIntersectionObserverPolyfill = function() { - if (typeof window !== "object") { + if (!id2) { 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; - } - }); - } + return pageId + "." + vm.$options.name.toLowerCase() + "." + id2; +} +function addSubscribe(name, callback) { + if (!name) { 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; - } + UniViewJSBridge.subscribe(name, ({type, data}) => { + callback(type, data); + }); +} +function removeSubscribe(name) { + if (!name) { + return; } - 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"); + UniViewJSBridge.unsubscribe(name); +} +function useSubscribe(callback, name, multiple) { + const instance2 = getCurrentInstance(); + const vm = instance2.proxy; + const pageId = multiple || !name ? useCurrentPageId() : 0; + onMounted(() => { + addSubscribe(name || normalizeEvent(pageId, vm), callback); + if (multiple || !name) { + watch(() => vm.id, (value, oldValue) => { + addSubscribe(normalizeEvent(pageId, vm, value), callback); + removeSubscribe(oldValue && normalizeEvent(pageId, vm, oldValue)); + }); } - 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 = []; + }); + onBeforeUnmount(() => { + removeSubscribe(name || normalizeEvent(pageId, vm)); + }); +} +function useOn(name, callback) { + onMounted(() => UniViewJSBridge.on(name, callback)); + onBeforeUnmount(() => UniViewJSBridge.off(name)); +} +let index$9 = 0; +function useContextInfo(_id) { + const page = useCurrentPageId(); + const instance2 = getCurrentInstance(); + const vm = instance2.proxy; + const type = vm.$options.name.toLowerCase(); + const id2 = _id || vm.id || `context${index$9++}`; + onMounted(() => { + const el = vm.$el; + el.__uniContextInfo = { + id: id2, + type, + page + }; + }); + return `${page}.${type}.${id2}`; +} +function getContextInfo(el) { + return el.__uniContextInfo; +} +function getRootInfo(fields2) { + const info = {}; + if (fields2.id) { + info.id = ""; } - 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, i, 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[i - 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; + if (fields2.dataset) { + info.dataset = {}; + } + if (fields2.rect) { + info.left = 0; + info.right = 0; + info.top = 0; + info.bottom = 0; + } + if (fields2.size) { + info.width = document.documentElement.clientWidth; + info.height = document.documentElement.clientHeight; + } + if (fields2.scrollOffset) { + const documentElement2 = document.documentElement; + const body = document.body; + info.scrollLeft = documentElement2.scrollLeft || body.scrollLeft || 0; + info.scrollTop = documentElement2.scrollTop || body.scrollTop || 0; + info.scrollHeight = documentElement2.scrollHeight || body.scrollHeight || 0; + info.scrollWidth = documentElement2.scrollWidth || body.scrollWidth || 0; + } + return info; +} +function getNodeInfo(el, fields2) { + const info = {}; + const {top} = getWindowOffset(); + if (fields2.id) { + info.id = el.id; + } + if (fields2.dataset) { + info.dataset = getCostomDataset(el); + } + if (fields2.rect || fields2.size) { + const rect = el.getBoundingClientRect(); + if (fields2.rect) { + info.left = rect.left; + info.right = rect.right; + info.top = rect.top - top; + info.bottom = rect.bottom - top; } - 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 - }); - } + if (fields2.size) { + info.width = rect.width; + info.height = rect.height; } - 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(); - } + } + if (Array.isArray(fields2.properties)) { + fields2.properties.forEach((prop) => { + prop = prop.replace(/-([a-z])/g, function(e2, t2) { + return t2.toUpperCase(); + }); }); - 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; + } + if (fields2.scrollOffset) { + if (el.tagName === "UNI-SCROLL-VIEW") { + const scroll = el.children[0].children[0]; + info.scrollLeft = scroll.scrollLeft; + info.scrollTop = scroll.scrollTop; + info.scrollHeight = scroll.scrollHeight; + info.scrollWidth = scroll.scrollWidth; + } else { + info.scrollLeft = 0; + info.scrollTop = 0; + info.scrollHeight = 0; + info.scrollWidth = 0; } - 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 (Array.isArray(fields2.computedStyle)) { + const sytle = getComputedStyle(el); + fields2.computedStyle.forEach((name) => { + info[name] = sytle[name]; }); - if (hasDependentTargets) { - return; - } - 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); - } - } - }; - IntersectionObserver2.prototype._unmonitorAllIntersections = function() { - var unsubscribes = this._monitoringUnsubscribes.slice(0); - this._monitoringDocuments.length = 0; - this._monitoringUnsubscribes.length = 0; - for (var i = 0; i < unsubscribes.length; i++) { - unsubscribes[i](); - } - }; - IntersectionObserver2.prototype._checkForIntersections = function() { - if (!this.root && crossOriginUpdater && !crossOriginRect) { - return; - } - 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); + } + if (fields2.context) { + info.contextInfo = getContextInfo(el); + } + return info; +} +function findElm(component, pageVm) { + return component ? component.$el : pageVm.$el; +} +function getNodesInfo(pageVm, component, selector, single, fields2) { + const parentElement = findElm(component, pageVm).parentElement; + if (!parentElement) { + return single ? null : []; + } + if (single) { + const node = parentElement.querySelector(selector); + if (node) { + return getNodeInfo(node, fields2); } - }; - 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 null; + } else { + let infos = []; + const nodeList = parentElement.querySelectorAll(selector); + if (nodeList && nodeList.length) { + [].forEach.call(nodeList, (node) => { + infos.push(getNodeInfo(node, fields2)); + }); } - return intersectionRect; - }; - IntersectionObserver2.prototype._getRootRect = function() { - var rootRect; - if (this.root && !isDoc(this.root)) { - rootRect = getBoundingClientRect(this.root); + return infos; + } +} +function requestComponentInfo(page, reqs, callback) { + const result = []; + reqs.forEach(({component, selector, single, fields: fields2}) => { + if (component === null) { + result.push(getRootInfo(fields2)); } 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 - }; + result.push(getNodesInfo(page, component, selector, single, fields2)); } - return this._expandRectByRootMargin(rootRect); - }; - IntersectionObserver2.prototype._expandRectByRootMargin = function(rect) { - var margins = this._rootMarginValues.map(function(margin, i) { - return margin.unit == "px" ? margin.value : margin.value * (i % 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 i = 0; i < this.thresholds.length; i++) { - var threshold = this.thresholds[i]; - if (threshold == oldRatio || threshold == newRatio || threshold < oldRatio !== threshold < newRatio) { - return true; - } + }); + callback(result); +} +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]; + } +} +let mediaQueryObserver; +let listener$2; +function handleMediaQueryStr($props) { + const mediaQueryArr = []; + const propsMenu = [ + "width", + "minWidth", + "maxWidth", + "height", + "minHeight", + "maxHeight", + "orientation" + ]; + for (const item of propsMenu) { + if (item !== "orientation" && $props[item] && Number($props[item] >= 0)) { + mediaQueryArr.push(`(${humpToLine(item)}: ${Number($props[item])}px)`); } - }; - 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); + if (item === "orientation" && $props[item]) { + mediaQueryArr.push(`(${humpToLine(item)}: ${$props[item]})`); } - }; - 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 throttle2(fn, timeout) { - var timer = null; - return function() { - if (!timer) { - timer = setTimeout(function() { - fn(); - timer = null; - }, timeout); - } + const mediaQueryStr = mediaQueryArr.join(" and "); + return mediaQueryStr; +} +function humpToLine(name) { + return name.replace(/([A-Z])/g, "-$1").toLowerCase(); +} +function addMediaQueryObserver({reqId, component, options, callback}, _pageId) { + mediaQueryObserver = window.matchMedia(handleMediaQueryStr(options)); + listener$2 = (observer) => callback(observer.matches); + listener$2(mediaQueryObserver); + mediaQueryObserver.addListener(listener$2); +} +function removeMediaQueryObserver({reqId, component}, _pageId) { + if (mediaQueryObserver) { + mediaQueryObserver.removeListener(listener$2); + } +} +function saveImage(base64, dirname, callback) { + callback(null, base64); +} +const TEMP_PATH = ""; +const files = {}; +function urlToFile(url, local) { + const file = files[url]; + if (file) { + return Promise.resolve(file); + } + if (/^data:[a-z-]+\/[a-z-]+;base64,/.test(url)) { + return Promise.resolve(base64ToFile(url)); + } + if (local) { + return Promise.reject(new Error("not find")); + } + return new Promise((resolve, reject) => { + const xhr = new XMLHttpRequest(); + xhr.open("GET", url, true); + xhr.responseType = "blob"; + xhr.onload = function() { + resolve(this.response); }; + xhr.onerror = reject; + xhr.send(); + }); +} +function base64ToFile(base64) { + const base64Array = base64.split(","); + const res = base64Array[0].match(/:(.*?);/); + const type = res ? res[1] : ""; + const str = atob(base64Array[1]); + let n = str.length; + const array = new Uint8Array(n); + while (n--) { + array[n] = str.charCodeAt(n); } - function addEvent(node, event, fn, opt_useCapture) { - if (typeof node.addEventListener == "function") { - node.addEventListener(event, fn, opt_useCapture || false); - } else if (typeof node.attachEvent == "function") { - node.attachEvent("on" + event, fn); + return blobToFile(array, type); +} +function getExtname(type) { + const extname = type.split("/")[1]; + return extname ? `.${extname}` : ""; +} +function getFileName(url) { + url = url.split("#")[0].split("?")[0]; + const array = url.split("/"); + return array[array.length - 1]; +} +function blobToFile(blob, type) { + let file; + if (blob instanceof File) { + file = blob; + } else { + type = type || blob.type || ""; + const filename = `${Date.now()}${getExtname(type)}`; + try { + file = new File([blob], filename, {type}); + } catch (error) { + blob = blob instanceof Blob ? blob : new Blob([blob], {type}); + file = blob; + file.name = file.name || filename; } } - function removeEvent(node, event, fn, opt_useCapture) { - if (typeof node.removeEventListener == "function") { - node.removeEventListener(event, fn, opt_useCapture || false); - } else if (typeof node.detatchEvent == "function") { - node.detatchEvent("on" + event, fn); + return file; +} +function fileToUrl(file) { + for (const key in files) { + if (hasOwn(files, key)) { + const oldFile = files[key]; + if (oldFile === file) { + return key; + } } } - 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; + var url = (window.URL || window.webkitURL).createObjectURL(file); + files[url] = file; + return url; +} +function getSameOriginUrl(url) { + const a2 = document.createElement("a"); + a2.href = url; + if (a2.origin === location.origin) { + return Promise.resolve(url); + } + return urlToFile(url).then(fileToUrl); +} +function revokeObjectURL(url) { + const URL = window.URL || window.webkitURL; + URL.revokeObjectURL(url); + delete files[url]; +} +function onWebInvokeAppService({name, arg}, pageId) { + if (name === "postMessage") + ; + else { + uni[name](arg); + } +} +function initOn() { + UniServiceJSBridge.on("onAppEnterForeground", onAppEnterForeground); + UniServiceJSBridge.on("onAppEnterBackground", onAppEnterBackground); + UniServiceJSBridge.on("onWebInvokeAppService", onWebInvokeAppService); +} +function onAppEnterForeground() { + const page = getCurrentPage(); + const showOptions = { + path: "", + query: {} + }; + if (page) { + showOptions.path = page.$page.route; + showOptions.query = page.$page.options; } - function getBoundingClientRect(el) { - var rect; - try { - rect = el.getBoundingClientRect(); - } catch (err) { - } - 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 - }; + invokeHook(getApp(), "onShow", showOptions); + invokeHook(page, "onShow"); +} +function onAppEnterBackground() { + invokeHook(getApp(), "onHide"); + invokeHook(getCurrentPage(), "onHide"); +} +const SUBSCRIBE_LIFECYCLE_HOOKS = ["onPageScroll", "onReachBottom"]; +function initSubscribe() { + SUBSCRIBE_LIFECYCLE_HOOKS.forEach((name) => UniServiceJSBridge.subscribe(name, createPageEvent(name))); +} +function createPageEvent(name) { + return (args, pageId) => { + const vm = getPageVmById(pageId); + if (vm) { + invokeHook(vm, name, args); } - return rect; + }; +} +function initService(app) { + initOn(); + initSubscribe(); + initAppConfig(app._context.config); +} +function errorHandler(err, instance2, info) { + if (!instance2) { + throw err; } - function getEmptyRect() { - return { - top: 0, - bottom: 0, - left: 0, - right: 0, - width: 0, - height: 0 - }; + const app = getApp(); + if (!app || !app.$vm) { + throw err; } - 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 - }; + { + invokeHook(app.$vm, "onError", err); } - 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 initApp$1(app) { + const appConfig = app._context.config; + if (isFunction(app._component.onError)) { + appConfig.errorHandler = errorHandler; } - function containsDeep(parent, child) { - var node = child; - while (node) { - if (node == parent) - return true; - node = getParentNode(node); - } - return false; + const globalProperties = appConfig.globalProperties; + { + globalProperties.$set = set; + globalProperties.$applyOptions = applyOptions; } - function getParentNode(node) { - var parent = node.parentNode; - if (node.nodeType == 9 && node != document2) { - return getFrameElement(node); - } - if (parent && parent.assignedSlot) { - parent = parent.assignedSlot.parentNode; - } - if (parent && parent.nodeType == 11 && parent.host) { - return parent.host; - } - return parent; +} +const pageMetaKey = PolySymbol(process.env.NODE_ENV !== "production" ? "UniPageMeta" : "upm"); +function usePageMeta() { + return inject(pageMetaKey); +} +function providePageMeta(id2) { + const pageMeta = initPageMeta(id2); + provide(pageMetaKey, pageMeta); + return pageMeta; +} +function usePageRoute() { + if (__UNI_FEATURE_PAGES__) { + return useRoute(); } - function isDoc(node) { - return node && node.nodeType === 9; + 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)); } - window.IntersectionObserver = IntersectionObserver2; - window.IntersectionObserverEntry = IntersectionObserverEntry; -}; -function normalizeRect(rect) { - const {bottom, height, left, right, top, width} = rect || {}; + const {meta} = __uniRoutes[0]; return { - bottom, - height, - left, - right, - top, - width + meta, + query, + path: "/" + meta.route }; } -function requestComponentObserver($el, options, callback) { - initIntersectionObserverPolyfill(); - const root = options.relativeToSelector ? $el.querySelector(options.relativeToSelector) : null; - const intersectionObserver = new IntersectionObserver((entries2) => { - entries2.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 +function initPageMeta(id2) { + if (__UNI_FEATURE_PAGES__) { + return reactive(normalizePageMeta(JSON.parse(JSON.stringify(mergePageMeta(id2, useRoute().meta))))); + } + return reactive(normalizePageMeta(JSON.parse(JSON.stringify(mergePageMeta(id2, __uniRoutes[0].meta))))); +} +const PAGE_META_KEYS = [ + "navigationBar", + "refreshOptions" +]; +function mergePageMeta(id2, pageMeta) { + const res = extend({id: id2}, __uniConfig.globalStyle, pageMeta); + PAGE_META_KEYS.forEach((name) => { + res[name] = extend({}, __uniConfig.globalStyle[name], pageMeta[name]); }); - if (options.observeAll) { - intersectionObserver.USE_MUTATION_OBSERVER = true; - const nodeList = $el.querySelectorAll(options.selector); - for (let i = 0; i < nodeList.length; i++) { - intersectionObserver.observe(nodeList[i]); + return res; +} +function normalizePageMeta(pageMeta) { + if (__UNI_FEATURE_PULL_DOWN_REFRESH__) { + const {enablePullDownRefresh, navigationBar} = pageMeta; + if (enablePullDownRefresh) { + const refreshOptions = extend({ + support: true, + color: "#2BD009", + style: "circle", + height: 70, + range: 150, + offset: 0 + }, pageMeta.refreshOptions); + let offset = rpx2px(refreshOptions.offset); + const {type} = navigationBar; + if (type !== "transparent" && type !== "none") { + offset += NAVBAR_HEIGHT + D__DCloud_local_git_uniAppNext_node_modules_safeAreaInsets_out.top; + } + refreshOptions.offset = offset; + refreshOptions.height = rpx2px(refreshOptions.height); + refreshOptions.range = rpx2px(refreshOptions.range); + pageMeta.refreshOptions = refreshOptions; } - } 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); + } + if (__UNI_FEATURE_NAVIGATIONBAR__) { + const {navigationBar} = pageMeta; + const {titleSize, titleColor, backgroundColor} = navigationBar; + navigationBar.type = navigationBar.type || "default"; + navigationBar.backButton = pageMeta.isQuit ? false : true; + navigationBar.titleSize = titleSize || "16px"; + navigationBar.titleColor = titleColor || "#fff"; + navigationBar.backgroundColor = backgroundColor || "#F7F7F7"; + } + if (__UNI_FEATURE_PAGES__ && history.state) { + const type = history.state.__type__; + if ((type === "redirectTo" || type === "reLaunch") && getCurrentPages().length === 0) { + pageMeta.isEntry = true; + pageMeta.isQuit = true; } } - return intersectionObserver; + return pageMeta; +} +const screen$1 = window.screen; +const documentElement = document.documentElement; +function checkMinWidth(minWidth) { + const sizes = [ + window.outerWidth, + window.outerHeight, + screen$1.width, + screen$1.height, + documentElement.clientWidth, + documentElement.clientHeight + ]; + return Math.max.apply(null, sizes) > minWidth; +} +function getStateId() { + return history.state && history.state.__id__ || 1; +} +PolySymbol(process.env.NODE_ENV !== "production" ? "layout" : "l"); +let tabBar; +function useTabBar() { + if (!tabBar) { + tabBar = __uniConfig.tabBar && reactive(__uniConfig.tabBar); + } + return tabBar; } const supports = window.CSS && window.CSS.supports; function cssSupports(css) { @@ -13292,6 +13300,11 @@ function setupApp(comp) { onBeforeMount(onLaunch); } onMounted(() => { + window.addEventListener("message", function(evt) { + if (isPlainObject(evt.data) && evt.data.type === "WEB_INVOKE_APPSERVICE") { + UniServiceJSBridge.emit("onWebInvokeAppService", evt.data.data, evt.data.pageId); + } + }); document.addEventListener("visibilitychange", function() { if (document.visibilityState === "visible") { UniServiceJSBridge.emit("onAppEnterForeground"); @@ -15038,7 +15051,7 @@ const getSystemInfoSync = /* @__PURE__ */ defineSyncApi("getSystemInfoSync", () const windowWidth = getWindowWidth(screenWidth); let windowHeight = window.innerHeight; const language = navigator.language; - const statusBarHeight = out.top; + const statusBarHeight = D__DCloud_local_git_uniAppNext_node_modules_safeAreaInsets_out.top; let osname; let osversion; let model; @@ -15151,12 +15164,12 @@ const getSystemInfoSync = /* @__PURE__ */ defineSyncApi("getSystemInfoSync", () const system = `${osname} ${osversion}`; const platform = osname.toLocaleLowerCase(); const safeArea = { - left: out.left, - right: windowWidth - out.right, - top: out.top, - bottom: windowHeight - out.bottom, - width: windowWidth - out.left - out.right, - height: windowHeight - out.top - out.bottom + left: D__DCloud_local_git_uniAppNext_node_modules_safeAreaInsets_out.left, + right: windowWidth - D__DCloud_local_git_uniAppNext_node_modules_safeAreaInsets_out.right, + top: D__DCloud_local_git_uniAppNext_node_modules_safeAreaInsets_out.top, + bottom: windowHeight - D__DCloud_local_git_uniAppNext_node_modules_safeAreaInsets_out.bottom, + width: windowWidth - D__DCloud_local_git_uniAppNext_node_modules_safeAreaInsets_out.left - D__DCloud_local_git_uniAppNext_node_modules_safeAreaInsets_out.right, + height: windowHeight - D__DCloud_local_git_uniAppNext_node_modules_safeAreaInsets_out.top - D__DCloud_local_git_uniAppNext_node_modules_safeAreaInsets_out.bottom }; const {top: windowTop, bottom: windowBottom} = getWindowOffset(); windowHeight -= windowTop; @@ -15176,10 +15189,10 @@ const getSystemInfoSync = /* @__PURE__ */ defineSyncApi("getSystemInfoSync", () model, safeArea, safeAreaInsets: { - top: out.top, - right: out.right, - bottom: out.bottom, - left: out.left + top: D__DCloud_local_git_uniAppNext_node_modules_safeAreaInsets_out.top, + right: D__DCloud_local_git_uniAppNext_node_modules_safeAreaInsets_out.right, + bottom: D__DCloud_local_git_uniAppNext_node_modules_safeAreaInsets_out.bottom, + left: D__DCloud_local_git_uniAppNext_node_modules_safeAreaInsets_out.left } }; }); @@ -20664,4 +20677,4 @@ var index = /* @__PURE__ */ defineSystemComponent({ return openBlock(), createBlock("div", clazz, [loadingVNode]); } }); -export {$emit, $off, $on, $once, index$1 as AsyncErrorComponent, index as AsyncLoadingComponent, _sfc_main$2 as Audio, index$r as Button, index$q as Canvas, index$o as Checkbox, index$p as CheckboxGroup, index$3 as CoverImage, index$4 as CoverView, index$n as Editor, index$t as Form, Friction, index$m as Icon, index$l as Image, Input, index$s as Label, LayoutComponent, Map$1 as Map, MovableArea, MovableView, index$k as Navigator, index$2 as PageComponent, _sfc_main$1 as Picker, PickerView, PickerViewColumn, index$j as Progress, index$h as Radio, index$i as RadioGroup, ResizeSensor, index$g as RichText, ScrollView, Scroller, index$f as Slider, Spring, Swiper, SwiperItem, index$e as Switch, index$d as Text, index$c as Textarea, UniServiceJSBridge$1 as UniServiceJSBridge, UniViewJSBridge$1 as UniViewJSBridge, index$7 as Video, index$b as View, index$6 as WebView, addInterceptor, addPhoneContact, arrayBufferToBase64, base64ToArrayBuffer, canIUse, canvasGetImageData, canvasPutImageData, canvasToTempFilePath, chooseFile, chooseImage, chooseLocation, chooseVideo, clearStorage, clearStorageSync, closeSocket, connectSocket, createAnimation, createCameraContext, createCanvasContext, createInnerAudioContext, createIntersectionObserver, createLivePlayerContext, createMapContext, createMediaQueryObserver, createSelectorQuery, createVideoContext, cssBackdropFilter, cssConstant, cssEnv, cssVar, defineBuiltInComponent, defineSystemComponent, disableScrollBounce, downloadFile, getApp$1 as getApp, getContextInfo, getCurrentPages$1 as getCurrentPages, getFileInfo, getImageInfo, getLeftWindowStyle, getLocation, getNetworkType, getProvider, getRecorderManager, getRightWindowStyle, getSavedFileInfo, getSavedFileList, getScreenBrightness, getSelectedTextRange, getStorage, getStorageInfo, getStorageInfoSync, getStorageSync, getSystemInfo, getSystemInfoSync, getTopWindowStyle, getVideoInfo, hideKeyboard, hideLeftWindow, hideLoading, hideNavigationBarLoading, hideRightWindow, hideTabBar, hideTabBarRedDot, hideToast, hideTopWindow, initScrollBounce, loadFontFace, login, makePhoneCall, navigateBack, navigateTo, offAccelerometerChange, offCompassChange, offNetworkStatusChange, offWindowResize, onAccelerometerChange, onCompassChange, onGyroscopeChange, onMemoryWarning, onNetworkStatusChange, onSocketClose, onSocketError, onSocketMessage, onSocketOpen, onTabBarMidButtonTap, onUserCaptureScreen, onWindowResize, openDocument, openLocation, pageScrollTo, index$8 as plugin, preloadPage, previewImage, promiseInterceptor, reLaunch, redirectTo, removeInterceptor, removeSavedFileInfo, removeStorage, removeStorageSync, removeTabBarBadge, request, saveFile, saveImageToPhotosAlbum, saveVideoToPhotosAlbum, scanCode, sendSocketMessage, setKeepScreenOn, setLeftWindowStyle, setNavigationBarColor, setNavigationBarTitle, setRightWindowStyle, setScreenBrightness, setStorage, setStorageSync, setTabBarBadge, setTabBarItem, setTabBarStyle, setTopWindowStyle, setupApp, setupPage, showActionSheet, showLeftWindow, showLoading, showModal, showNavigationBarLoading, showRightWindow, showTabBar, showTabBarRedDot, showToast, showTopWindow, startAccelerometer, startCompass, startGyroscope, startPullDownRefresh, stopAccelerometer, stopCompass, stopGyroscope, stopPullDownRefresh, switchTab, uni$1 as uni, uniFormKey, uploadFile, upx2px, useAttrs, useBooleanAttr, useContextInfo, useCustomEvent, useNativeEvent, useOn, useScroller, useSubscribe, useTouchtrack, useUserAction, vibrateLong, vibrateShort, withWebEvent}; +export {$emit, $off, $on, $once, index$1 as AsyncErrorComponent, index as AsyncLoadingComponent, _sfc_main$2 as Audio, index$r as Button, index$q as Canvas, index$o as Checkbox, index$p as CheckboxGroup, index$3 as CoverImage, index$4 as CoverView, index$n as Editor, index$t as Form, Friction, index$m as Icon, index$l as Image, Input, index$s as Label, LayoutComponent, Map$1 as Map, MovableArea, MovableView, index$k as Navigator, index$2 as PageComponent, _sfc_main$1 as Picker, PickerView, PickerViewColumn, index$j as Progress, index$h as Radio, index$i as RadioGroup, ResizeSensor, index$g as RichText, ScrollView, Scroller, index$f as Slider, Spring, Swiper, SwiperItem, index$d as Switch, index$c as Text, index$b as Textarea, UniServiceJSBridge$1 as UniServiceJSBridge, UniViewJSBridge$1 as UniViewJSBridge, index$7 as Video, index$a as View, index$6 as WebView, addInterceptor, addPhoneContact, arrayBufferToBase64, base64ToArrayBuffer, canIUse, canvasGetImageData, canvasPutImageData, canvasToTempFilePath, chooseFile, chooseImage, chooseLocation, chooseVideo, clearStorage, clearStorageSync, closeSocket, connectSocket, createAnimation, createCameraContext, createCanvasContext, createInnerAudioContext, createIntersectionObserver, createLivePlayerContext, createMapContext, createMediaQueryObserver, createSelectorQuery, createVideoContext, cssBackdropFilter, cssConstant, cssEnv, cssVar, defineBuiltInComponent, defineSystemComponent, disableScrollBounce, downloadFile, getApp$1 as getApp, getContextInfo, getCurrentPages$1 as getCurrentPages, getFileInfo, getImageInfo, getLeftWindowStyle, getLocation, getNetworkType, getProvider, getRecorderManager, getRightWindowStyle, getSavedFileInfo, getSavedFileList, getScreenBrightness, getSelectedTextRange, getStorage, getStorageInfo, getStorageInfoSync, getStorageSync, getSystemInfo, getSystemInfoSync, getTopWindowStyle, getVideoInfo, hideKeyboard, hideLeftWindow, hideLoading, hideNavigationBarLoading, hideRightWindow, hideTabBar, hideTabBarRedDot, hideToast, hideTopWindow, initScrollBounce, loadFontFace, login, makePhoneCall, navigateBack, navigateTo, offAccelerometerChange, offCompassChange, offNetworkStatusChange, offWindowResize, onAccelerometerChange, onCompassChange, onGyroscopeChange, onMemoryWarning, onNetworkStatusChange, onSocketClose, onSocketError, onSocketMessage, onSocketOpen, onTabBarMidButtonTap, onUserCaptureScreen, onWindowResize, openDocument, openLocation, pageScrollTo, index$8 as plugin, preloadPage, previewImage, promiseInterceptor, reLaunch, redirectTo, removeInterceptor, removeSavedFileInfo, removeStorage, removeStorageSync, removeTabBarBadge, request, saveFile, saveImageToPhotosAlbum, saveVideoToPhotosAlbum, scanCode, sendSocketMessage, setKeepScreenOn, setLeftWindowStyle, setNavigationBarColor, setNavigationBarTitle, setRightWindowStyle, setScreenBrightness, setStorage, setStorageSync, setTabBarBadge, setTabBarItem, setTabBarStyle, setTopWindowStyle, setupApp, setupPage, showActionSheet, showLeftWindow, showLoading, showModal, showNavigationBarLoading, showRightWindow, showTabBar, showTabBarRedDot, showToast, showTopWindow, startAccelerometer, startCompass, startGyroscope, startPullDownRefresh, stopAccelerometer, stopCompass, stopGyroscope, stopPullDownRefresh, switchTab, uni$1 as uni, uniFormKey, uploadFile, upx2px, useAttrs, useBooleanAttr, useContextInfo, useCustomEvent, useNativeEvent, useOn, useScroller, useSubscribe, useTouchtrack, useUserAction, vibrateLong, vibrateShort, withWebEvent}; diff --git a/packages/uni-h5/src/framework/setup/index.ts b/packages/uni-h5/src/framework/setup/index.ts index 6b1231a41e88391133a6b2d51963af821c32e56b..5114847a03e6485d930fddda8ca6cff501018804 100644 --- a/packages/uni-h5/src/framework/setup/index.ts +++ b/packages/uni-h5/src/framework/setup/index.ts @@ -1,4 +1,4 @@ -import { invokeArrayFns } from '@vue/shared' +import { invokeArrayFns, isPlainObject } from '@vue/shared' import { ComponentInternalInstance, ComponentPublicInstance, @@ -127,6 +127,23 @@ export function setupApp(comp: any) { onBeforeMount(onLaunch) } onMounted(() => { + window.addEventListener( + 'message', + function (evt: { + data?: { type: string; data: any; pageId: number } + }) { + if ( + isPlainObject(evt.data) && + evt.data.type === 'WEB_INVOKE_APPSERVICE' + ) { + UniServiceJSBridge.emit( + 'onWebInvokeAppService', + evt.data.data, + evt.data.pageId + ) + } + } + ) document.addEventListener('visibilitychange', function () { if (document.visibilityState === 'visible') { UniServiceJSBridge.emit('onAppEnterForeground') diff --git a/packages/uni-h5/src/platform/index.ts b/packages/uni-h5/src/platform/index.ts index e2d68a239f9c8349b463e6497231e351fa810a89..1fe5ba9121c7ea4187ea294e506e101969e33d6d 100644 --- a/packages/uni-h5/src/platform/index.ts +++ b/packages/uni-h5/src/platform/index.ts @@ -14,3 +14,4 @@ export { export * from './saveImage' export * from './constants' export { getSameOriginUrl } from '../helpers/file' +export { onWebInvokeAppService } from '../service/onWebInvokeAppService' diff --git a/packages/uni-h5/src/service/onWebInvokeAppService.ts b/packages/uni-h5/src/service/onWebInvokeAppService.ts new file mode 100644 index 0000000000000000000000000000000000000000..6b9dde3fcb49303130f37da85e5d7821d38d6395 --- /dev/null +++ b/packages/uni-h5/src/service/onWebInvokeAppService.ts @@ -0,0 +1,18 @@ +type Name = + | 'navigateTo' + | 'navigateBack' + | 'switchTab' + | 'reLaunch' + | 'redirectTo' + | 'postMessage' + +export function onWebInvokeAppService( + { name, arg }: { name: Name; arg: any }, + pageId: number +) { + if (name === 'postMessage') { + // TODO 小程序后退、组件销毁、分享时通知 + } else { + uni[name](arg) + } +}