From f166163f4b58eda238ca9bfd145bba6efd57f941 Mon Sep 17 00:00:00 2001 From: fxy060608 Date: Fri, 30 Apr 2021 20:44:12 +0800 Subject: [PATCH] feat: ssr --- package.json | 1 + packages/global.d.ts | 1 + .../src/components/canvas/index.vue | 2 +- .../src/components/image/index.tsx | 8 +- .../src/components/progress/index.tsx | 6 +- packages/uni-components/src/helpers/hidpi.js | 30 +- .../uni-components/src/helpers/useField.ts | 8 +- .../src/helpers/useListeners.ts | 3 + packages/uni-core/src/helpers/dom.ts | 2 +- packages/uni-core/src/helpers/util.ts | 3 + packages/uni-core/src/i18n/useI18n.ts | 9 +- packages/uni-core/src/service/plugin/index.ts | 3 + packages/uni-core/src/view/plugin/index.ts | 3 + packages/uni-h5-vue/dist/vue.runtime.cjs.js | 579 +- packages/uni-h5/dist/uni-h5.cjs.js | 8552 ++++------------- packages/uni-h5/dist/uni-h5.es.js | 432 +- .../src/framework/components/layout/index.tsx | 35 +- .../src/framework/components/page/index.ts | 5 +- .../framework/components/page/pageBody.tsx | 8 +- .../uni-h5/src/framework/plugin/router.ts | 4 + packages/uni-h5/src/framework/setup/index.ts | 11 + packages/uni-h5/src/framework/setup/page.ts | 7 +- .../src/framework/setup/provide/page.ts | 4 +- packages/uni-h5/src/helpers/dom.ts | 7 + .../uni-h5/src/service/api/base/canIUse.ts | 16 +- packages/uni-h5/src/service/api/index.ts | 4 + .../src/view/components/map/MapLocation.tsx | 76 +- packages/uni-h5/vite.config.ts | 40 +- packages/uni-shared/dist/uni-shared.cjs.js | 7 + packages/uni-shared/dist/uni-shared.d.ts | 2 + packages/uni-shared/dist/uni-shared.es.js | 8 +- packages/uni-shared/src/index.ts | 2 + packages/uni-shared/src/node/locale.ts | 5 + packages/vite-plugin-uni/package.json | 2 + packages/vite-plugin-uni/src/config/define.ts | 7 +- packages/vite-plugin-uni/src/config/index.ts | 2 +- .../src/configResolved/config.ts | 26 + .../src/configResolved/index.ts | 3 +- .../src/configResolved/plugins/index.ts | 2 +- .../src/configResolved/plugins/mainJs.ts | 2 +- .../src/configResolved/plugins/pagesJson.ts | 56 +- packages/vite-plugin-uni/src/utils/ssr.ts | 44 + rollup.config.js | 5 +- scripts/build.js | 9 + yarn.lock | 47 +- 45 files changed, 2614 insertions(+), 7474 deletions(-) create mode 100644 packages/uni-shared/src/node/locale.ts create mode 100644 packages/vite-plugin-uni/src/configResolved/config.ts create mode 100644 packages/vite-plugin-uni/src/utils/ssr.ts diff --git a/package.json b/package.json index 5243e947b..8d2278111 100644 --- a/package.json +++ b/package.json @@ -62,6 +62,7 @@ "module-alias": "^2.2.2", "prettier": "^2.2.1", "rollup": "^2.35.1", + "rollup-plugin-jscc": "^2.0.0", "rollup-plugin-node-builtins": "^2.1.2", "rollup-plugin-node-globals": "^1.4.0", "rollup-plugin-terser": "^7.0.2", diff --git a/packages/global.d.ts b/packages/global.d.ts index 49bc3e7cd..bb3930bc8 100644 --- a/packages/global.d.ts +++ b/packages/global.d.ts @@ -9,6 +9,7 @@ declare var __GLOBAL__: Record // Global compile-time constants declare var __DEV__: boolean declare var __TEST__: boolean +declare var __NODE_JS__: boolean // Feature flags declare var __VUE_OPTIONS_API__: boolean diff --git a/packages/uni-components/src/components/canvas/index.vue b/packages/uni-components/src/components/canvas/index.vue index a3581f139..5d1e51917 100644 --- a/packages/uni-components/src/components/canvas/index.vue +++ b/packages/uni-components/src/components/canvas/index.vue @@ -18,7 +18,7 @@ import { initHidpi } from '../../helpers/hidpi' -/*#__PURE__*/ initHidpi() +!__NODE_JS__ && /*#__PURE__*/ initHidpi() function resolveColor(color) { color = color.slice(0) diff --git a/packages/uni-components/src/components/image/index.tsx b/packages/uni-components/src/components/image/index.tsx index 45f976fe7..ad51c6244 100644 --- a/packages/uni-components/src/components/image/index.tsx +++ b/packages/uni-components/src/components/image/index.tsx @@ -74,9 +74,11 @@ export default /*#__PURE__*/ defineComponent({ return (
- {imgSrc && } - {FIX_MODES[mode as keyof typeof FIX_MODES] && ( + {imgSrc ? : } + {FIX_MODES[mode as keyof typeof FIX_MODES] ? ( + ) : ( + )} ) @@ -181,7 +183,7 @@ function useImageLoader( onBeforeUnmount(() => resetImage()) } -const isChrome = navigator.vendor === 'Google Inc.' +const isChrome = __NODE_JS__ ? false : navigator.vendor === 'Google Inc.' function fixNumber(num: number) { // fix: 解决 Chrome 浏览器上某些情况下导致 1px 缝隙的问题 if (isChrome && num > 10) { diff --git a/packages/uni-components/src/components/progress/index.tsx b/packages/uni-components/src/components/progress/index.tsx index f30b95daf..7365c3082 100644 --- a/packages/uni-components/src/components/progress/index.tsx +++ b/packages/uni-components/src/components/progress/index.tsx @@ -90,7 +90,11 @@ export default /*#__PURE__*/ defineComponent({
- {showInfo ?

{currentPercent}%

: ''} + {showInfo ? ( // {currentPercent}% 的写法会影响 SSR Hydration +

{currentPercent + '%'}

+ ) : ( + '' + )} ) } diff --git a/packages/uni-components/src/helpers/hidpi.js b/packages/uni-components/src/helpers/hidpi.js index 0ad06c3f9..6617c90b3 100644 --- a/packages/uni-components/src/helpers/hidpi.js +++ b/packages/uni-components/src/helpers/hidpi.js @@ -1,19 +1,21 @@ import { hasOwn } from '@vue/shared' -export 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 -})() +export const pixelRatio = __NODE_JS__ + ? 1 + : /*#__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 + })() export function wrapper(canvas) { canvas.width = canvas.offsetWidth * pixelRatio diff --git a/packages/uni-components/src/helpers/useField.ts b/packages/uni-components/src/helpers/useField.ts index f8b2a4351..1b6de6aee 100644 --- a/packages/uni-components/src/helpers/useField.ts +++ b/packages/uni-components/src/helpers/useField.ts @@ -365,9 +365,11 @@ export function useField( useEvent(fieldRef, state, trigger, triggerInput, beforeInput) // Safari 14 以上修正禁用状态颜色 - const fixDisabledColor = - String(navigator.vendor).indexOf('Apple') === 0 && - CSS.supports('image-orientation:from-image') + // TODO fixDisabledColor 可以调整到beforeMount或mounted做修正,确保不影响SSR + const fixDisabledColor = __NODE_JS__ + ? false + : String(navigator.vendor).indexOf('Apple') === 0 && + CSS.supports('image-orientation:from-image') return { fieldRef, diff --git a/packages/uni-components/src/helpers/useListeners.ts b/packages/uni-components/src/helpers/useListeners.ts index 4e435a6db..ff90f4a6a 100644 --- a/packages/uni-components/src/helpers/useListeners.ts +++ b/packages/uni-components/src/helpers/useListeners.ts @@ -6,6 +6,9 @@ export function useListeners( props: { id: string }, listeners: Record ) { + if (__NODE_JS__) { + return + } _addListeners(props.id, listeners) watch( diff --git a/packages/uni-core/src/helpers/dom.ts b/packages/uni-core/src/helpers/dom.ts index f03919c2b..13f14b026 100644 --- a/packages/uni-core/src/helpers/dom.ts +++ b/packages/uni-core/src/helpers/dom.ts @@ -26,9 +26,9 @@ interface PageCssVars { '--window-margin'?: string '--top-window-height'?: string } -const style = document.documentElement.style export function updateCssVar(cssVars: Record) { + const style = document.documentElement.style Object.keys(cssVars).forEach((name) => { style.setProperty(name, cssVars[name]) }) diff --git a/packages/uni-core/src/helpers/util.ts b/packages/uni-core/src/helpers/util.ts index c07e2a7b3..30badbb6c 100644 --- a/packages/uni-core/src/helpers/util.ts +++ b/packages/uni-core/src/helpers/util.ts @@ -3,6 +3,9 @@ export function PolySymbol(name: string) { } export function rpx2px(str: string | number) { + if (__NODE_JS__) { + return parseInt(str + '') + } if (typeof str === 'string') { const res = parseInt(str) || 0 if (str.indexOf('rpx') !== -1 || str.indexOf('upx') !== -1) { diff --git a/packages/uni-core/src/i18n/useI18n.ts b/packages/uni-core/src/i18n/useI18n.ts index c2512e9f1..57a99ede6 100644 --- a/packages/uni-core/src/i18n/useI18n.ts +++ b/packages/uni-core/src/i18n/useI18n.ts @@ -1,10 +1,17 @@ +import { getEnvLocale } from '@dcloudio/uni-shared' import { BuiltInLocale, initVueI18n } from '@dcloudio/uni-i18n' + let i18n: ReturnType + export function useI18n() { if (!i18n) { let language: BuiltInLocale if (__PLATFORM__ === 'h5') { - language = navigator.language as BuiltInLocale + if (__NODE_JS__) { + language = getEnvLocale() as BuiltInLocale + } else { + language = navigator.language as BuiltInLocale + } } else if (__PLATFORM__ === 'app') { // TODO 需替换为新API language = plus.os.language as BuiltInLocale diff --git a/packages/uni-core/src/service/plugin/index.ts b/packages/uni-core/src/service/plugin/index.ts index 500316aa8..a2485fc50 100644 --- a/packages/uni-core/src/service/plugin/index.ts +++ b/packages/uni-core/src/service/plugin/index.ts @@ -4,6 +4,9 @@ import { initOn } from './on' import { initSubscribe } from './subscribe' export * from './page' export function initService(app: App) { + if (__NODE_JS__) { + return + } initOn() initSubscribe() diff --git a/packages/uni-core/src/view/plugin/index.ts b/packages/uni-core/src/view/plugin/index.ts index 28648d5cc..e822b5160 100644 --- a/packages/uni-core/src/view/plugin/index.ts +++ b/packages/uni-core/src/view/plugin/index.ts @@ -4,6 +4,9 @@ import { initLongPress } from './longPress' import { initAppConfig } from './appConfig' export function initView(app: App) { + if (__NODE_JS__) { + return + } if (__UNI_FEATURE_LONGPRESS__) { initLongPress() } diff --git a/packages/uni-h5-vue/dist/vue.runtime.cjs.js b/packages/uni-h5-vue/dist/vue.runtime.cjs.js index 44167d018..14255bd97 100644 --- a/packages/uni-h5-vue/dist/vue.runtime.cjs.js +++ b/packages/uni-h5-vue/dist/vue.runtime.cjs.js @@ -1,9 +1,9 @@ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -var shared = require('@vue/shared'); - +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var shared = require('@vue/shared'); + const targetMap = new WeakMap(); const effectStack = []; let activeEffect; @@ -191,8 +191,8 @@ function trigger(target, type, key, newValue, oldValue, oldTarget) { } }; effects.forEach(run); -} - +} + const isNonTrackableKeys = /*#__PURE__*/ shared.makeMap(`__proto__,__v_isRef,__isVue`); const builtInSymbols = new Set(Object.getOwnPropertyNames(Symbol) .map(key => Symbol[key]) @@ -357,8 +357,8 @@ const shallowReactiveHandlers = shared.extend({}, mutableHandlers, { // retain the reactivity of the normal readonly object. const shallowReadonlyHandlers = shared.extend({}, readonlyHandlers, { get: shallowReadonlyGet -}); - +}); + const toReactive = (value) => shared.isObject(value) ? reactive(value) : value; const toReadonly = (value) => shared.isObject(value) ? readonly(value) : value; const toShallow = (value) => value; @@ -632,8 +632,8 @@ function checkIdentityKeys(target, has, key) { `Avoid differentiating between the raw and reactive versions ` + `of an object and only use the reactive version if possible.`); } -} - +} + const reactiveMap = new WeakMap(); const shallowReactiveMap = new WeakMap(); const readonlyMap = new WeakMap(); @@ -733,8 +733,8 @@ function toRaw(observed) { function markRaw(value) { shared.def(value, "__v_skip" /* SKIP */, true); return value; -} - +} + const convert = (val) => shared.isObject(val) ? reactive(val) : val; function isRef(r) { return Boolean(r && r.__v_isRef === true); @@ -838,8 +838,8 @@ function toRef(object, key) { return isRef(object[key]) ? object[key] : new ObjectRefImpl(object, key); -} - +} + class ComputedRefImpl { constructor(getter, _setter, isReadonly) { this._setter = _setter; @@ -885,8 +885,8 @@ function computed(getterOrOptions) { setter = getterOrOptions.set; } return new ComputedRefImpl(getter, setter, shared.isFunction(getterOrOptions) || !getterOrOptions.set); -} - +} + const stack = []; function pushWarningContext(vnode) { stack.push(vnode); @@ -999,8 +999,8 @@ function formatProp(key, value, raw) { value = toRaw(value); return raw ? value : [`${key}=`, value]; } -} - +} + const ErrorTypeStrings = { ["bc" /* BEFORE_CREATE */]: 'beforeCreate hook', ["c" /* CREATED */]: 'created hook', @@ -1104,8 +1104,8 @@ function logError(err, type, contextVNode, throwInDev = true) { console.error(err); } } -} - +} + let isFlushing = false; let isFlushPending = false; const queue = []; @@ -1295,8 +1295,8 @@ function checkRecursiveUpdates(seen, fn) { seen.set(fn, count + 1); } } -} - +} + /* eslint-disable no-restricted-globals */ let isHmrUpdating = false; const hmrDirtyComponents = new Set(); @@ -1422,8 +1422,8 @@ function tryWrap(fn) { `Full reload required.`); } }; -} - +} + function setDevtoolsHook(hook) { exports.devtools = hook; } @@ -1457,8 +1457,8 @@ function devtoolsComponentEmit(component, event, params) { if (!exports.devtools) return; exports.devtools.emit("component:emit" /* COMPONENT_EMIT */, component.appContext.app, component, event, params); -} - +} + function emit(instance, event, ...rawArgs) { const props = instance.vnode.props || shared.EMPTY_OBJ; { @@ -1579,8 +1579,8 @@ function isEmitListener(options, key) { return (shared.hasOwn(options, key[0].toLowerCase() + key.slice(1)) || shared.hasOwn(options, shared.hyphenate(key)) || shared.hasOwn(options, key)); -} - +} + let isRenderingCompiledSlot = 0; const setCompiledSlotRendering = (n) => (isRenderingCompiledSlot += n); /** @@ -1627,8 +1627,8 @@ function ensureValidVNode(vnodes) { }) ? vnodes : null; -} - +} + /** * mark the current rendering instance for asset resolution (e.g. * resolveComponent, resolveDirective) during render @@ -1698,8 +1698,8 @@ function withCtx(fn, ctx = currentRenderingInstance) { // rendering flag. renderFnWithContext._c = true; return renderFnWithContext; -} - +} + /** * dev only flag to track whether $attrs was used during render. * If $attrs was used during render then the warning for failed attrs @@ -1993,8 +1993,8 @@ function updateHOCHostEl({ vnode, parent }, el // HostNode (vnode = parent.vnode).el = el; parent = parent.parent; } -} - +} + const isSuspense = (type) => type.__isSuspense; // Suspense exposes a component-like API, and is treated like a component // in the compiler, but internally it's a special built-in type that hooks @@ -2413,8 +2413,8 @@ function setActiveBranch(suspense, branch) { parentComponent.vnode.el = el; updateHOCHostEl(parentComponent, el); } -} - +} + function initProps(instance, rawProps, isStateful, // result of bitwise flag comparison isSSR = false) { const props = {}; @@ -2812,8 +2812,8 @@ function isExplicable(type) { */ function isBoolean(...args) { return args.some(elem => elem.toLowerCase() === 'boolean'); -} - +} + function injectHook(type, hook, target = currentInstance, prepend = false) { if (target) { const hooks = target[type] || (target[type] = []); @@ -2868,8 +2868,8 @@ const onRenderTriggered = createHook("rtg" /* RENDER_TRIGGERED */); const onRenderTracked = createHook("rtc" /* RENDER_TRACKED */); const onErrorCaptured = (hook, target = currentInstance) => { injectHook("ec" /* ERROR_CAPTURED */, hook, target); -}; - +}; + // Simple effect. function watchEffect(effect, options) { return doWatch(effect, null, options); @@ -2962,6 +2962,23 @@ function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = sh callWithErrorHandling(fn, instance, 4 /* WATCH_CLEANUP */); }; }; + // in SSR there is no need to setup an actual effect, and it should be noop + // unless it's eager + if (exports.isInSSRComponentSetup) { + // we will also not call the invalidate callback (+ runner is not set up) + onInvalidate = shared.NOOP; + if (!cb) { + getter(); + } + else if (immediate) { + callWithAsyncErrorHandling(cb, instance, 3 /* WATCH_CALLBACK */, [ + getter(), + undefined, + onInvalidate + ]); + } + return shared.NOOP; + } let oldValue = shared.isArray(source) ? [] : INITIAL_WATCHER_VALUE; const job = () => { if (!runner.active) { @@ -3073,8 +3090,8 @@ function traverse(value, seen = new Set()) { } } return value; -} - +} + function useTransitionState() { const state = { isMounted: false, @@ -3385,8 +3402,8 @@ function getTransitionRawChildren(children, keepComment = false) { } } return ret; -} - +} + const isKeepAlive = (vnode) => vnode.type.__isKeepAlive; class Cache { constructor(max) { @@ -3452,7 +3469,7 @@ const KeepAliveImpl = { // if the internal renderer is not registered, it indicates that this is server-side rendering, // for KeepAlive, we just need to render its children if (!sharedContext.renderer) { - return slots.default; + return ()=>slots.default()[0]; } if (props.cache && shared.hasOwn(props, 'max')) { warn('The `max` prop will be ignored if you provide a custom caching strategy'); @@ -3730,8 +3747,8 @@ function invokeKeepAliveHooks(hooks) { } function resetHookState(hooks) { hooks.forEach((hook) => (hook.__called = false)); -} - +} + const isInternalKey = (key) => key[0] === '_' || key === '$stable'; const normalizeSlotValue = (value) => shared.isArray(value) ? value.map(normalizeVNode) @@ -3834,15 +3851,15 @@ const updateSlots = (instance, children) => { } } } -}; - +}; + /** Runtime helper for applying directives to a vnode. Example usage: - + const comp = resolveComponent('comp') const foo = resolveDirective('foo') const bar = resolveDirective('bar') - + return withDirectives(h(comp), [ [foo, this.x], [bar, this.y] @@ -3902,8 +3919,8 @@ function invokeDirectiveHook(vnode, prevVNode, instance, name) { ]); } } -} - +} + function createAppContext() { return { app: null, @@ -4066,8 +4083,8 @@ function createAppAPI(render, hydrate) { }); return app; }; -} - +} + let hasMismatch = false; const isSVGContainer = (container) => /svg/.test(container.namespaceURI) && container.tagName !== 'foreignObject'; const isComment = (node) => node.nodeType === 8 /* COMMENT */; @@ -4374,8 +4391,8 @@ function createHydrationFunctions(rendererInternals) { return node; }; return [hydrate, hydrateNode]; -} - +} + let supported; let perf; function startMeasure(instance, type) { @@ -4407,13 +4424,13 @@ function isSupported() { } /* eslint-enable no-restricted-globals */ return supported; -} - +} + // implementation, close to no-op function defineComponent(options) { return shared.isFunction(options) ? { setup: options, name: options.name } : options; -} - +} + const isAsyncWrapper = (i) => !!i.type.__asyncLoader; function defineAsyncComponent(source) { if (shared.isFunction(source)) { @@ -4481,7 +4498,7 @@ function defineAsyncComponent(source) { }; // suspense-controlled or SSR. if ((suspensible && instance.suspense) || - (false )) { + (exports.isInSSRComponentSetup)) { return load() .then(comp => { return () => createInnerComp(comp, instance); @@ -4541,8 +4558,8 @@ function createInnerComp(comp, { vnode: { ref, props, children } }) { // ensure inner component inherits the async wrapper's ref owner vnode.ref = ref; return vnode; -} - +} + function createDevEffectOptions(instance) { return { scheduler: queueJob, @@ -5895,8 +5912,8 @@ function getSequence(arr) { v = p[v]; } return result; -} - +} + const isTeleport = (type) => type.__isTeleport; const isTeleportDisabled = (props) => props && (props.disabled || props.disabled === ''); const isTargetSVG = (target) => typeof SVGElement !== 'undefined' && target instanceof SVGElement; @@ -6084,8 +6101,8 @@ function hydrateTeleport(node, vnode, parentComponent, parentSuspense, slotScope return vnode.anchor && nextSibling(vnode.anchor); } // Force-casted public typing for h and TSX props inference -const Teleport = TeleportImpl; - +const Teleport = TeleportImpl; + const COMPONENTS = 'components'; const DIRECTIVES = 'directives'; /** @@ -6153,8 +6170,8 @@ function resolve(registry, name) { (registry[name] || registry[shared.camelize(name)] || registry[shared.capitalize(shared.camelize(name))])); -} - +} + const Fragment = Symbol('Fragment' ); const Text = Symbol('Text' ); const Comment = Symbol('Comment' ); @@ -6587,8 +6604,8 @@ function mergeProps(...args) { } } return ret; -} - +} + function provide(key, value) { if (!currentInstance) { { @@ -6637,8 +6654,8 @@ function inject(key, defaultValue, treatDefaultAsFactory = false) { else { warn(`inject() can only be used inside setup() or functional components.`); } -} - +} + function createDuplicateChecker() { const cache = Object.create(null); return (type, key) => { @@ -7039,8 +7056,8 @@ function mergeOptions(to, from, instance) { to[key] = from[key]; } } -} - +} + /** * #2437 In Vue 3, functional components do not have a public instance proxy but * they exist in the internal parent chain. For code that relies on traversing @@ -7299,8 +7316,8 @@ function exposeSetupStateOnRenderContext(instance) { set: shared.NOOP }); }); -} - +} + const emptyAppContext = createAppContext(); let uid$2 = 0; function createComponentInstance(vnode, parent, suspense) { @@ -7471,7 +7488,12 @@ function setupStatefulComponent(instance, isSSR) { function handleSetupResult(instance, setupResult, isSSR) { if (shared.isFunction(setupResult)) { // setup returned an inline render function - { + if (instance.type.__ssrInlineRender) { + // when the function's name is `ssrRender` (compiled by SFC inline mode), + // set it as ssrRender instead. + instance.ssrRender = setupResult; + } + else { instance.render = setupResult; } } @@ -7508,7 +7530,17 @@ function registerRuntimeCompiler(_compile) { function finishComponentSetup(instance, isSSR) { const Component = instance.type; // template / render function normalization - if (!instance.render) { + if (isSSR) { + // 1. the render function may already exist, returned by `setup` + // 2. otherwise try to use the `Component.render` + // 3. if the component doesn't have a render function, + // set `instance.render` to NOOP so that it can inherit the render + // function from mixins/extend + instance.render = (instance.render || + Component.render || + shared.NOOP); + } + else if (!instance.render) { // could be set from setup() if (compile && Component.template && !Component.render) { { @@ -7632,14 +7664,14 @@ function formatComponentName(instance, Component, isRoot = false) { } function isClassComponent(value) { return shared.isFunction(value) && '__vccOpts' in value; -} - +} + function computed$1(getterOrOptions) { const c = computed(getterOrOptions); recordInstanceBoundEffect(c.effect); return c; -} - +} + // implementation function defineProps() { { @@ -7664,8 +7696,8 @@ function useContext() { warn(`useContext() called without active instance.`); } return i.setupContext || (i.setupContext = createSetupContext(i)); -} - +} + // Actual implementation function h(type, propsOrChildren, children) { const l = arguments.length; @@ -7692,8 +7724,8 @@ function h(type, propsOrChildren, children) { } return createVNode(type, propsOrChildren, children); } -} - +} + const ssrContextKey = Symbol(`ssrContext` ); const useSSRContext = () => { { @@ -7704,8 +7736,8 @@ const useSSRContext = () => { } return ctx; } -}; - +}; + function initCustomFormatter() { /* eslint-disable no-restricted-globals */ if (typeof window === 'undefined') { @@ -7893,8 +7925,8 @@ function initCustomFormatter() { else { window.devtoolsFormatters = [formatter]; } -} - +} + /** * Actual implementation */ @@ -7933,8 +7965,8 @@ function renderList(source, renderItem) { ret = []; } return ret; -} - +} + /** * For prefixing keys in v-on="obj" with "on" * @private @@ -7949,8 +7981,8 @@ function toHandlers(obj) { ret[shared.toHandlerKey(key)] = obj[key]; } return ret; -} - +} + /** * Compiler runtime helper for creating dynamic slots object * @private @@ -7970,16 +8002,24 @@ function createSlots(slots, dynamicSlots) { } } return slots; -} - +} + // Core API ------------------------------------------------------------------ const version = "3.0.9"; +const _ssrUtils = { + createComponentInstance, + setupComponent, + renderComponentRoot, + setCurrentRenderingInstance, + isVNode, + normalizeVNode +}; /** * SSR utils for \@vue/server-renderer. Only exposed in cjs builds. * @internal */ -const ssrUtils = (null); - +const ssrUtils = (_ssrUtils ); + const svgNS = 'http://www.w3.org/2000/svg'; const doc = (typeof document !== 'undefined' ? document : null); let tempContainer; @@ -8053,8 +8093,8 @@ const nodeOps = { } return [first, last]; } -}; - +}; + // compiler should normalize class + :class bindings on the same element // into a single binding ['staticClass', dynamic] function patchClass(el, value, isSVG) { @@ -8076,8 +8116,8 @@ function patchClass(el, value, isSVG) { } el.className = value; } -} - +} + function patchStyle(el, prev, next) { const style = el.style; if (!next) { @@ -8166,8 +8206,8 @@ const normalizeRpx = (val) => { }); } return val; -}; - +}; + const xlinkNS = 'http://www.w3.org/1999/xlink'; function patchAttr(el, key, value, isSVG) { if (isSVG && key.startsWith('xlink:')) { @@ -8189,8 +8229,8 @@ function patchAttr(el, key, value, isSVG) { el.setAttribute(key, isBoolean ? '' : value); } } -} - +} + // __UNSAFE__ // functions. The user is responsible for using them with only trusted content. function patchDOMProp(el, key, value, @@ -8245,8 +8285,8 @@ prevChildren, parentComponent, parentSuspense, unmountChildren) { `value ${value} is invalid.`, e); } } -} - +} + // Async edge case fix requires storing an event listener's attach timestamp. let _getNow = Date.now; // Determine what event timestamp the browser is using. Annoyingly, the @@ -8353,8 +8393,8 @@ function patchStopImmediatePropagation(e, value) { else { return value; } -} - +} + function patchWxs(el, rawName, nextValue, instance = null) { if (!el.__wxsWatches) { el.__wxsWatches = {}; @@ -8372,8 +8412,8 @@ function patchWxs(el, rawName, nextValue, instance = null) { deep: true }); } -} - +} + const nativeOnRE = /^on[a-z]/; const forcePatchProp = (_, key) => key === 'value'; const patchProp = (el, key, prevValue, nextValue, isSVG = false, prevChildren, parentComponent, parentSuspense, unmountChildren) => { @@ -8455,8 +8495,8 @@ function shouldSetAsProp(el, key, value, isSVG) { return false; } return key in el; -} - +} + function useCssModule(name = '$style') { /* istanbul ignore else */ { @@ -8477,16 +8517,16 @@ function useCssModule(name = '$style') { } return mod; } -} - +} + /** * Runtime helper for SFC's CSS variable injection feature. * @private */ function useCssVars(getter) { return; -} - +} + const TRANSITION = 'transition'; const ANIMATION = 'animation'; // DOM Transition is a higher-order-component based on the platform-agnostic @@ -8740,8 +8780,8 @@ function toMs(s) { // synchronously force layout to put elements into a certain state function forceReflow() { return document.body.offsetHeight; -} - +} + const positionMap = new WeakMap(); const newPositionMap = new WeakMap(); const TransitionGroupImpl = { @@ -8861,8 +8901,8 @@ function hasCSSTransform(el, root, moveClass) { const { hasTransform } = getTransitionInfo(clone); container.removeChild(clone); return hasTransform; -} - +} + const getModelAssigner = (vnode) => { const fn = vnode.props['onUpdate:modelValue']; return shared.isArray(fn) ? value => shared.invokeArrayFns(fn, value) : fn; @@ -9109,8 +9149,32 @@ function callModelHook(el, binding, vnode, prevVNode, hook) { } const fn = modelToUse[hook]; fn && fn(el, binding, vnode, prevVNode); -} - +} +// SSR vnode transforms +{ + vModelText.getSSRProps = ({ value }) => ({ value }); + vModelRadio.getSSRProps = ({ value }, vnode) => { + if (vnode.props && shared.looseEqual(vnode.props.value, value)) { + return { checked: true }; + } + }; + vModelCheckbox.getSSRProps = ({ value }, vnode) => { + if (shared.isArray(value)) { + if (vnode.props && shared.looseIndexOf(value, vnode.props.value) > -1) { + return { checked: true }; + } + } + else if (shared.isSet(value)) { + if (vnode.props && value.has(vnode.props.value)) { + return { checked: true }; + } + } + else if (value) { + return { checked: true }; + } + }; +} + const systemModifiers = ['ctrl', 'shift', 'alt', 'meta']; const modifierGuards = { stop: e => e.stopPropagation(), @@ -9164,8 +9228,8 @@ const withKeys = (fn, modifiers) => { } return fn(event); }; -}; - +}; + const vShow = { beforeMount(el, { value }, { transition }) { el._vod = el.style.display === 'none' ? '' : el.style.display; @@ -9204,10 +9268,17 @@ const vShow = { setDisplay(el, value); } }; +{ + vShow.getSSRProps = ({ value }) => { + if (!value) { + return { style: { display: 'none' } }; + } + }; +} function setDisplay(el, value) { el.style.display = value ? el._vod : 'none'; -} - +} + const rendererOptions = shared.extend({ patchProp, forcePatchProp }, nodeOps); // lazy create the renderer - this makes core renderer logic tree-shakable // in case the user only imports reactivity utilities from Vue. @@ -9308,131 +9379,131 @@ function normalizeContainer(container) { warn(`mounting on a ShadowRoot with \`{mode: "closed"}\` may lead to unpredictable bugs`); } return container; -} - +} + // This entry exports the runtime only, and is built as const compile$1 = () => { { warn(`Runtime compilation is not supported in this build of Vue.` + (``) /* should not happen */); } -}; - -exports.camelize = shared.camelize; -exports.capitalize = shared.capitalize; -exports.toDisplayString = shared.toDisplayString; -exports.toHandlerKey = shared.toHandlerKey; -exports.BaseTransition = BaseTransition; -exports.Comment = Comment; -exports.Fragment = Fragment; -exports.KeepAlive = KeepAlive; -exports.Static = Static; -exports.Suspense = Suspense; -exports.Teleport = Teleport; -exports.Text = Text; -exports.Transition = Transition; -exports.TransitionGroup = TransitionGroup; -exports.callWithAsyncErrorHandling = callWithAsyncErrorHandling; -exports.callWithErrorHandling = callWithErrorHandling; -exports.cloneVNode = cloneVNode; -exports.compile = compile$1; -exports.computed = computed$1; -exports.createApp = createApp; -exports.createBlock = createBlock; -exports.createCommentVNode = createCommentVNode; -exports.createHydrationRenderer = createHydrationRenderer; -exports.createRenderer = createRenderer; -exports.createSSRApp = createSSRApp; -exports.createSlots = createSlots; -exports.createStaticVNode = createStaticVNode; -exports.createTextVNode = createTextVNode; -exports.createVNode = createVNode; -exports.createVueApp = createApp; -exports.createVueSSRApp = createSSRApp; -exports.customRef = customRef; -exports.defineAsyncComponent = defineAsyncComponent; -exports.defineComponent = defineComponent; -exports.defineEmit = defineEmit; -exports.defineProps = defineProps; -exports.getCurrentInstance = getCurrentInstance; -exports.getTransitionRawChildren = getTransitionRawChildren; -exports.h = h; -exports.handleError = handleError; -exports.hydrate = hydrate; -exports.initCustomFormatter = initCustomFormatter; -exports.inject = inject; -exports.injectHook = injectHook; -exports.isProxy = isProxy; -exports.isReactive = isReactive; -exports.isReadonly = isReadonly; -exports.isRef = isRef; -exports.isRuntimeOnly = isRuntimeOnly; -exports.isVNode = isVNode; -exports.markRaw = markRaw; -exports.mergeProps = mergeProps; -exports.nextTick = nextTick; -exports.onActivated = onActivated; -exports.onBeforeActivate = onBeforeActivate; -exports.onBeforeDeactivate = onBeforeDeactivate; -exports.onBeforeMount = onBeforeMount; -exports.onBeforeUnmount = onBeforeUnmount; -exports.onBeforeUpdate = onBeforeUpdate; -exports.onDeactivated = onDeactivated; -exports.onErrorCaptured = onErrorCaptured; -exports.onMounted = onMounted; -exports.onRenderTracked = onRenderTracked; -exports.onRenderTriggered = onRenderTriggered; -exports.onUnmounted = onUnmounted; -exports.onUpdated = onUpdated; -exports.openBlock = openBlock; -exports.popScopeId = popScopeId; -exports.provide = provide; -exports.proxyRefs = proxyRefs; -exports.pushScopeId = pushScopeId; -exports.queuePostFlushCb = queuePostFlushCb; -exports.reactive = reactive; -exports.readonly = readonly; -exports.ref = ref; -exports.registerRuntimeCompiler = registerRuntimeCompiler; -exports.render = render; -exports.renderList = renderList; -exports.renderSlot = renderSlot; -exports.resolveComponent = resolveComponent; -exports.resolveDirective = resolveDirective; -exports.resolveDynamicComponent = resolveDynamicComponent; -exports.resolveTransitionHooks = resolveTransitionHooks; -exports.setBlockTracking = setBlockTracking; -exports.setDevtoolsHook = setDevtoolsHook; -exports.setTransitionHooks = setTransitionHooks; -exports.shallowReactive = shallowReactive; -exports.shallowReadonly = shallowReadonly; -exports.shallowRef = shallowRef; -exports.ssrContextKey = ssrContextKey; -exports.ssrUtils = ssrUtils; -exports.toHandlers = toHandlers; -exports.toRaw = toRaw; -exports.toRef = toRef; -exports.toRefs = toRefs; -exports.transformVNodeArgs = transformVNodeArgs; -exports.triggerRef = triggerRef; -exports.unref = unref; -exports.useContext = useContext; -exports.useCssModule = useCssModule; -exports.useCssVars = useCssVars; -exports.useSSRContext = useSSRContext; -exports.useTransitionState = useTransitionState; -exports.vModelCheckbox = vModelCheckbox; -exports.vModelDynamic = vModelDynamic; -exports.vModelRadio = vModelRadio; -exports.vModelSelect = vModelSelect; -exports.vModelText = vModelText; -exports.vShow = vShow; -exports.version = version; -exports.warn = warn; -exports.watch = watch; -exports.watchEffect = watchEffect; -exports.withCtx = withCtx; -exports.withDirectives = withDirectives; -exports.withKeys = withKeys; -exports.withModifiers = withModifiers; -exports.withScopeId = withScopeId; +}; + +exports.camelize = shared.camelize; +exports.capitalize = shared.capitalize; +exports.toDisplayString = shared.toDisplayString; +exports.toHandlerKey = shared.toHandlerKey; +exports.BaseTransition = BaseTransition; +exports.Comment = Comment; +exports.Fragment = Fragment; +exports.KeepAlive = KeepAlive; +exports.Static = Static; +exports.Suspense = Suspense; +exports.Teleport = Teleport; +exports.Text = Text; +exports.Transition = Transition; +exports.TransitionGroup = TransitionGroup; +exports.callWithAsyncErrorHandling = callWithAsyncErrorHandling; +exports.callWithErrorHandling = callWithErrorHandling; +exports.cloneVNode = cloneVNode; +exports.compile = compile$1; +exports.computed = computed$1; +exports.createApp = createApp; +exports.createBlock = createBlock; +exports.createCommentVNode = createCommentVNode; +exports.createHydrationRenderer = createHydrationRenderer; +exports.createRenderer = createRenderer; +exports.createSSRApp = createSSRApp; +exports.createSlots = createSlots; +exports.createStaticVNode = createStaticVNode; +exports.createTextVNode = createTextVNode; +exports.createVNode = createVNode; +exports.createVueApp = createApp; +exports.createVueSSRApp = createSSRApp; +exports.customRef = customRef; +exports.defineAsyncComponent = defineAsyncComponent; +exports.defineComponent = defineComponent; +exports.defineEmit = defineEmit; +exports.defineProps = defineProps; +exports.getCurrentInstance = getCurrentInstance; +exports.getTransitionRawChildren = getTransitionRawChildren; +exports.h = h; +exports.handleError = handleError; +exports.hydrate = hydrate; +exports.initCustomFormatter = initCustomFormatter; +exports.inject = inject; +exports.injectHook = injectHook; +exports.isProxy = isProxy; +exports.isReactive = isReactive; +exports.isReadonly = isReadonly; +exports.isRef = isRef; +exports.isRuntimeOnly = isRuntimeOnly; +exports.isVNode = isVNode; +exports.markRaw = markRaw; +exports.mergeProps = mergeProps; +exports.nextTick = nextTick; +exports.onActivated = onActivated; +exports.onBeforeActivate = onBeforeActivate; +exports.onBeforeDeactivate = onBeforeDeactivate; +exports.onBeforeMount = onBeforeMount; +exports.onBeforeUnmount = onBeforeUnmount; +exports.onBeforeUpdate = onBeforeUpdate; +exports.onDeactivated = onDeactivated; +exports.onErrorCaptured = onErrorCaptured; +exports.onMounted = onMounted; +exports.onRenderTracked = onRenderTracked; +exports.onRenderTriggered = onRenderTriggered; +exports.onUnmounted = onUnmounted; +exports.onUpdated = onUpdated; +exports.openBlock = openBlock; +exports.popScopeId = popScopeId; +exports.provide = provide; +exports.proxyRefs = proxyRefs; +exports.pushScopeId = pushScopeId; +exports.queuePostFlushCb = queuePostFlushCb; +exports.reactive = reactive; +exports.readonly = readonly; +exports.ref = ref; +exports.registerRuntimeCompiler = registerRuntimeCompiler; +exports.render = render; +exports.renderList = renderList; +exports.renderSlot = renderSlot; +exports.resolveComponent = resolveComponent; +exports.resolveDirective = resolveDirective; +exports.resolveDynamicComponent = resolveDynamicComponent; +exports.resolveTransitionHooks = resolveTransitionHooks; +exports.setBlockTracking = setBlockTracking; +exports.setDevtoolsHook = setDevtoolsHook; +exports.setTransitionHooks = setTransitionHooks; +exports.shallowReactive = shallowReactive; +exports.shallowReadonly = shallowReadonly; +exports.shallowRef = shallowRef; +exports.ssrContextKey = ssrContextKey; +exports.ssrUtils = ssrUtils; +exports.toHandlers = toHandlers; +exports.toRaw = toRaw; +exports.toRef = toRef; +exports.toRefs = toRefs; +exports.transformVNodeArgs = transformVNodeArgs; +exports.triggerRef = triggerRef; +exports.unref = unref; +exports.useContext = useContext; +exports.useCssModule = useCssModule; +exports.useCssVars = useCssVars; +exports.useSSRContext = useSSRContext; +exports.useTransitionState = useTransitionState; +exports.vModelCheckbox = vModelCheckbox; +exports.vModelDynamic = vModelDynamic; +exports.vModelRadio = vModelRadio; +exports.vModelSelect = vModelSelect; +exports.vModelText = vModelText; +exports.vShow = vShow; +exports.version = version; +exports.warn = warn; +exports.watch = watch; +exports.watchEffect = watchEffect; +exports.withCtx = withCtx; +exports.withDirectives = withDirectives; +exports.withKeys = withKeys; +exports.withModifiers = withModifiers; +exports.withScopeId = withScopeId; diff --git a/packages/uni-h5/dist/uni-h5.cjs.js b/packages/uni-h5/dist/uni-h5.cjs.js index e8f4dfbff..4c904e13d 100644 --- a/packages/uni-h5/dist/uni-h5.cjs.js +++ b/packages/uni-h5/dist/uni-h5.cjs.js @@ -6,12 +6,12 @@ var vue = require("vue"); var uniShared = require("@dcloudio/uni-shared"); var uniI18n = require("@dcloudio/uni-i18n"); var vueRouter = require("vue-router"); -function applyOptions(options, instance2, publicThis) { +function applyOptions(options, instance, publicThis) { Object.keys(options).forEach((name) => { if (name.indexOf("on") === 0) { const hook = options[name]; if (shared.isFunction(hook)) { - vue.injectHook(name, hook.bind(publicThis), instance2); + vue.injectHook(name, hook.bind(publicThis), instance); } } }); @@ -24,7 +24,9 @@ function useI18n() { if (!i18n$1) { let language; { - language = navigator.language; + { + language = uniShared.getEnvLocale(); + } } i18n$1 = uniI18n.initVueI18n(language); } @@ -61,80 +63,6 @@ const initI18nAsyncMsgsOnce = /* @__PURE__ */ uniShared.once(() => { i18n.add(uniI18n.LOCALE_ZH_HANT, normalizeMessages(name, {error: "\u9023\u63A5\u670D\u52D9\u5668\u8D85\u6642\uFF0C\u9EDE\u64CA\u5C4F\u5E55\u91CD\u8A66"})); } }); -const initI18nShowToastMsgsOnce = /* @__PURE__ */ uniShared.once(() => { - const name = "uni.showToast."; - if (__UNI_FEATURE_I18N_EN__) { - i18n.add(uniI18n.LOCALE_EN, normalizeMessages(name, { - unpaired: "Please note showToast must be paired with hideToast" - })); - } - if (__UNI_FEATURE_I18N_ES__) { - i18n.add(uniI18n.LOCALE_ES, normalizeMessages(name, { - unpaired: "Tenga en cuenta que showToast debe estar emparejado con hideToast" - })); - } - if (__UNI_FEATURE_I18N_FR__) { - i18n.add(uniI18n.LOCALE_FR, normalizeMessages(name, { - unpaired: "Veuillez noter que showToast doit \xEAtre associ\xE9 \xE0 hideToast" - })); - } - if (__UNI_FEATURE_I18N_ZH_HANS__) { - i18n.add(uniI18n.LOCALE_ZH_HANS, normalizeMessages(name, { - unpaired: "\u8BF7\u6CE8\u610F showToast \u4E0E hideToast \u5FC5\u987B\u914D\u5BF9\u4F7F\u7528" - })); - } - if (__UNI_FEATURE_I18N_ZH_HANT__) { - i18n.add(uniI18n.LOCALE_ZH_HANT, normalizeMessages(name, { - unpaired: "\u8ACB\u6CE8\u610F showToast \u8207 hideToast \u5FC5\u9808\u914D\u5C0D\u4F7F\u7528" - })); - } -}); -const initI18nShowLoadingMsgsOnce = /* @__PURE__ */ uniShared.once(() => { - const name = "uni.showLoading."; - if (__UNI_FEATURE_I18N_EN__) { - i18n.add(uniI18n.LOCALE_EN, normalizeMessages(name, { - unpaired: "Please note showLoading must be paired with hideLoading" - })); - } - if (__UNI_FEATURE_I18N_ES__) { - i18n.add(uniI18n.LOCALE_ES, normalizeMessages(name, { - unpaired: "Tenga en cuenta que showLoading debe estar emparejado con hideLoading" - })); - } - if (__UNI_FEATURE_I18N_FR__) { - i18n.add(uniI18n.LOCALE_FR, normalizeMessages(name, { - unpaired: "Veuillez noter que showLoading doit \xEAtre associ\xE9 \xE0 hideLoading" - })); - } - if (__UNI_FEATURE_I18N_ZH_HANS__) { - i18n.add(uniI18n.LOCALE_ZH_HANS, normalizeMessages(name, { - unpaired: "\u8BF7\u6CE8\u610F showLoading \u4E0E hideLoading \u5FC5\u987B\u914D\u5BF9\u4F7F\u7528" - })); - } - if (__UNI_FEATURE_I18N_ZH_HANT__) { - i18n.add(uniI18n.LOCALE_ZH_HANT, normalizeMessages(name, { - unpaired: "\u8ACB\u6CE8\u610F showLoading \u8207 hideLoading \u5FC5\u9808\u914D\u5C0D\u4F7F\u7528" - })); - } -}); -const initI18nShowModalMsgsOnce = /* @__PURE__ */ uniShared.once(() => { - const name = "uni.showModal."; - if (__UNI_FEATURE_I18N_EN__) { - i18n.add(uniI18n.LOCALE_EN, normalizeMessages(name, {cancel: "Cancel", confirm: "OK"})); - } - if (__UNI_FEATURE_I18N_ES__) { - i18n.add(uniI18n.LOCALE_ES, normalizeMessages(name, {cancel: "Cancelar", confirm: "OK"})); - } - if (__UNI_FEATURE_I18N_FR__) { - i18n.add(uniI18n.LOCALE_FR, normalizeMessages(name, {cancel: "Annuler", confirm: "OK"})); - } - if (__UNI_FEATURE_I18N_ZH_HANS__) { - i18n.add(uniI18n.LOCALE_ZH_HANS, normalizeMessages(name, {cancel: "\u53D6\u6D88", confirm: "\u786E\u5B9A"})); - } - if (__UNI_FEATURE_I18N_ZH_HANT__) { - i18n.add(uniI18n.LOCALE_ZH_HANT, normalizeMessages(name, {cancel: "\u53D6\u6D88", confirm: "\u78BA\u5B9A"})); - } -}); const initI18nVideoMsgsOnce = /* @__PURE__ */ uniShared.once(() => { const name = "uni.video."; if (__UNI_FEATURE_I18N_EN__) { @@ -166,12 +94,12 @@ E.prototype = { }, once: function(name, callback2, ctx) { var self = this; - function listener2() { - self.off(name, listener2); + function listener() { + self.off(name, listener); callback2.apply(ctx, arguments); } - listener2._ = callback2; - return this.on(name, listener2, ctx); + listener._ = callback2; + return this.on(name, listener, ctx); }, emit: function(name) { var data = [].slice.call(arguments, 1); @@ -215,261 +143,9 @@ function initBridge(namespace) { }); } const ViewJSBridge = /* @__PURE__ */ initBridge("view"); -const LONGPRESS_TIMEOUT = 350; -const LONGPRESS_THRESHOLD = 10; -const passiveOptions$2 = uniShared.passive(true); -let longPressTimer = 0; -function clearLongPressTimer() { - if (longPressTimer) { - clearTimeout(longPressTimer); - longPressTimer = 0; - } -} -let startPageX = 0; -let startPageY = 0; -function touchstart(evt) { - clearLongPressTimer(); - if (evt.touches.length !== 1) { - return; - } - const {pageX, pageY} = evt.touches[0]; - startPageX = pageX; - startPageY = pageY; - longPressTimer = setTimeout(function() { - const customEvent = new CustomEvent("longpress", { - bubbles: true, - cancelable: true, - target: evt.target, - currentTarget: evt.currentTarget - }); - customEvent.touches = evt.touches; - customEvent.changedTouches = evt.changedTouches; - evt.target.dispatchEvent(customEvent); - }, LONGPRESS_TIMEOUT); -} -function touchmove(evt) { - if (!longPressTimer) { - return; - } - if (evt.touches.length !== 1) { - return clearLongPressTimer(); - } - const {pageX, pageY} = evt.touches[0]; - if (Math.abs(pageX - startPageX) > LONGPRESS_THRESHOLD || Math.abs(pageY - startPageY) > LONGPRESS_THRESHOLD) { - return clearLongPressTimer(); - } -} -function initLongPress() { - window.addEventListener("touchstart", touchstart, passiveOptions$2); - window.addEventListener("touchmove", touchmove, passiveOptions$2); - window.addEventListener("touchend", clearLongPressTimer, passiveOptions$2); - window.addEventListener("touchcancel", clearLongPressTimer, passiveOptions$2); -} -var attrs = ["top", "left", "right", "bottom"]; -var inited$1; -var elementComputedStyle = {}; -var support; -function getSupport() { - if (!("CSS" in window) || typeof CSS.supports != "function") { - support = ""; - } else if (CSS.supports("top: env(safe-area-inset-top)")) { - support = "env"; - } else if (CSS.supports("top: constant(safe-area-inset-top)")) { - support = "constant"; - } else { - support = ""; - } - return support; -} -function init() { - support = typeof support === "string" ? support : getSupport(); - if (!support) { - attrs.forEach(function(attr2) { - elementComputedStyle[attr2] = 0; - }); - return; - } - function setStyle(el, style2) { - var elStyle = el.style; - Object.keys(style2).forEach(function(key) { - var val = style2[key]; - elStyle[key] = val; - }); - } - var cbs = []; - function parentReady(callback2) { - if (callback2) { - cbs.push(callback2); - } else { - cbs.forEach(function(cb) { - cb(); - }); - } - } - var passiveEvents = false; - try { - var opts = Object.defineProperty({}, "passive", { - get: function() { - passiveEvents = {passive: true}; - } - }); - window.addEventListener("test", null, opts); - } catch (e2) { - } - function addChild(parent, attr2) { - var a1 = document.createElement("div"); - var a2 = document.createElement("div"); - var a1Children = document.createElement("div"); - var a2Children = document.createElement("div"); - var W = 100; - var MAX = 1e4; - var aStyle = { - position: "absolute", - width: W + "px", - height: "200px", - boxSizing: "border-box", - overflow: "hidden", - paddingBottom: support + "(safe-area-inset-" + attr2 + ")" - }; - setStyle(a1, aStyle); - setStyle(a2, aStyle); - setStyle(a1Children, { - transition: "0s", - animation: "none", - width: "400px", - height: "400px" - }); - setStyle(a2Children, { - transition: "0s", - animation: "none", - width: "250%", - height: "250%" - }); - a1.appendChild(a1Children); - a2.appendChild(a2Children); - parent.appendChild(a1); - parent.appendChild(a2); - parentReady(function() { - a1.scrollTop = a2.scrollTop = MAX; - var a1LastScrollTop = a1.scrollTop; - var a2LastScrollTop = a2.scrollTop; - function onScroll() { - if (this.scrollTop === (this === a1 ? a1LastScrollTop : a2LastScrollTop)) { - return; - } - a1.scrollTop = a2.scrollTop = MAX; - a1LastScrollTop = a1.scrollTop; - a2LastScrollTop = a2.scrollTop; - attrChange(attr2); - } - a1.addEventListener("scroll", onScroll, passiveEvents); - a2.addEventListener("scroll", onScroll, passiveEvents); - }); - var computedStyle = getComputedStyle(a1); - Object.defineProperty(elementComputedStyle, attr2, { - configurable: true, - get: function() { - return parseFloat(computedStyle.paddingBottom); - } - }); - } - var parentDiv = document.createElement("div"); - setStyle(parentDiv, { - position: "absolute", - left: "0", - top: "0", - width: "0", - height: "0", - zIndex: "-1", - overflow: "hidden", - visibility: "hidden" - }); - attrs.forEach(function(key) { - addChild(parentDiv, key); - }); - document.body.appendChild(parentDiv); - parentReady(); - inited$1 = true; -} -function getAttr(attr2) { - if (!inited$1) { - init(); - } - return elementComputedStyle[attr2]; -} -var changeAttrs = []; -function attrChange(attr2) { - if (!changeAttrs.length) { - setTimeout(function() { - var style2 = {}; - changeAttrs.forEach(function(attr3) { - style2[attr3] = elementComputedStyle[attr3]; - }); - changeAttrs.length = 0; - callbacks$2.forEach(function(callback2) { - callback2(style2); - }); - }, 0); - } - changeAttrs.push(attr2); -} -var callbacks$2 = []; -function onChange(callback2) { - if (!getSupport()) { - return; - } - if (!inited$1) { - init(); - } - if (typeof callback2 === "function") { - callbacks$2.push(callback2); - } -} -function offChange(callback2) { - var index2 = callbacks$2.indexOf(callback2); - if (index2 >= 0) { - callbacks$2.splice(index2, 1); - } -} -var safeAreaInsets = { - get support() { - return (typeof support === "string" ? support : getSupport()).length != 0; - }, - get top() { - return getAttr("top"); - }, - get left() { - return getAttr("left"); - }, - get right() { - return getAttr("right"); - }, - get bottom() { - return getAttr("bottom"); - }, - onChange, - offChange -}; -var D__DCloud_local_git_uniAppNext_node_modules_safeAreaInsets_out = safeAreaInsets; -const onEventPrevent = /* @__PURE__ */ vue.withModifiers(() => { -}, ["prevent"]); -const onEventStop = /* @__PURE__ */ vue.withModifiers(() => { -}, ["stop"]); -function getWindowOffset() { - const style2 = document.documentElement.style; - const top = parseInt(style2.getPropertyValue("--window-top")); - const bottom = parseInt(style2.getPropertyValue("--window-bottom")); - const left = parseInt(style2.getPropertyValue("--window-left")); - const right = parseInt(style2.getPropertyValue("--window-right")); - return { - top: top ? top + 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 - }; -} -const style = document.documentElement.style; +uniShared.passive(true); function updateCssVar(cssVars) { + const style = document.documentElement.style; Object.keys(cssVars).forEach((name) => { style.setProperty(name, cssVars[name]); }); @@ -478,46 +154,41 @@ function updatePageCssVar(cssVars) { return updateCssVar(cssVars); } const sheetsMap = new Map(); -function updateStyle(id2, content) { - let style2 = sheetsMap.get(id2); - if (style2 && !(style2 instanceof HTMLStyleElement)) { - removeStyle(id2); - style2 = void 0; - } - if (!style2) { - style2 = document.createElement("style"); - style2.setAttribute("type", "text/css"); - style2.innerHTML = content; - document.head.appendChild(style2); +function updateStyle(id, content) { + let style = sheetsMap.get(id); + if (style && !(style instanceof HTMLStyleElement)) { + removeStyle(id); + style = void 0; + } + if (!style) { + style = document.createElement("style"); + style.setAttribute("type", "text/css"); + style.innerHTML = content; + document.head.appendChild(style); } else { - style2.innerHTML = content; + style.innerHTML = content; } - sheetsMap.set(id2, style2); + sheetsMap.set(id, style); } -function removeStyle(id2) { - let style2 = sheetsMap.get(id2); - if (style2) { - if (style2 instanceof CSSStyleSheet) { - document.adoptedStyleSheets.indexOf(style2); - document.adoptedStyleSheets = document.adoptedStyleSheets.filter((s) => s !== style2); +function removeStyle(id) { + let style = sheetsMap.get(id); + if (style) { + if (style instanceof CSSStyleSheet) { + document.adoptedStyleSheets.indexOf(style); + document.adoptedStyleSheets = document.adoptedStyleSheets.filter((s) => s !== style); } else { - document.head.removeChild(style2); + document.head.removeChild(style); } - sheetsMap.delete(id2); + sheetsMap.delete(id); } } function PolySymbol(name) { return Symbol(process.env.NODE_ENV !== "production" ? "[uni-app]: " + name : name); } function rpx2px(str) { - if (typeof str === "string") { - const res = parseInt(str) || 0; - if (str.indexOf("rpx") !== -1 || str.indexOf("upx") !== -1) { - return uni.upx2px(res); - } - return res; + { + return parseInt(str + ""); } - return str; } const ICON_PATH_CANCEL = "M20.928 10.176l-4.928 4.928-4.928-4.928-0.896 0.896 4.928 4.928-4.928 4.928 0.896 0.896 4.928-4.928 4.928 4.928 0.896-0.896-4.928-4.928 4.928-4.928-0.896-0.896zM16 2.080q-3.776 0-7.040 1.888-3.136 1.856-4.992 4.992-1.888 3.264-1.888 7.040t1.888 7.040q1.856 3.136 4.992 4.992 3.264 1.888 7.040 1.888t7.040-1.888q3.136-1.856 4.992-4.992 1.888-3.264 1.888-7.040t-1.888-7.040q-1.856-3.136-4.992-4.992-3.264-1.888-7.040-1.888zM16 28.64q-3.424 0-6.4-1.728-2.848-1.664-4.512-4.512-1.728-2.976-1.728-6.4t1.728-6.4q1.664-2.848 4.512-4.512 2.976-1.728 6.4-1.728t6.4 1.728q2.848 1.664 4.512 4.512 1.728 2.976 1.728 6.4t-1.728 6.4q-1.664 2.848-4.512 4.512-2.976 1.728-6.4 1.728z"; const ICON_PATH_CLEAR = "M16 0q-4.352 0-8.064 2.176-3.616 2.144-5.76 5.76-2.176 3.712-2.176 8.064t2.176 8.064q2.144 3.616 5.76 5.76 3.712 2.176 8.064 2.176t8.064-2.176q3.616-2.144 5.76-5.76 2.176-3.712 2.176-8.064t-2.176-8.064q-2.144-3.616-5.76-5.76-3.712-2.176-8.064-2.176zM22.688 21.408q0.32 0.32 0.304 0.752t-0.336 0.736-0.752 0.304-0.752-0.32l-5.184-5.376-5.376 5.184q-0.32 0.32-0.752 0.304t-0.736-0.336-0.304-0.752 0.32-0.752l5.376-5.184-5.184-5.376q-0.32-0.32-0.304-0.752t0.336-0.752 0.752-0.304 0.752 0.336l5.184 5.376 5.376-5.184q0.32-0.32 0.752-0.304t0.752 0.336 0.304 0.752-0.336 0.752l-5.376 5.184 5.184 5.376z"; @@ -543,73 +214,6 @@ function createSvgIconVNode(path, color = "#000", size = 27) { function useCurrentPageId() { return vue.getCurrentInstance().root.proxy.$page.id; } -function getPageIdByVm(vm) { - if (!vm.$) { - return; - } - const rootProxy = vm.$.root.proxy; - if (rootProxy && rootProxy.$page) { - return rootProxy.$page.id; - } -} -function disableScrollListener(evt) { - evt.preventDefault(); -} -let testReachBottomTimer; -let lastScrollHeight = 0; -function createScrollListener({ - onPageScroll, - onReachBottom, - onReachBottomDistance -}) { - let ticking = false; - let hasReachBottom = false; - let reachBottomLocking = true; - const isReachBottom = () => { - const {scrollHeight} = document.documentElement; - const windowHeight = window.innerHeight; - const scrollY = window.scrollY; - const isBottom = scrollY > 0 && scrollHeight > windowHeight && scrollY + windowHeight + onReachBottomDistance >= scrollHeight; - const heightChanged = Math.abs(scrollHeight - lastScrollHeight) > onReachBottomDistance; - if (isBottom && (!hasReachBottom || heightChanged)) { - lastScrollHeight = scrollHeight; - hasReachBottom = true; - return true; - } - if (!isBottom && hasReachBottom) { - hasReachBottom = false; - } - return false; - }; - const trigger = () => { - onPageScroll && onPageScroll(window.pageYOffset); - function testReachBottom() { - if (isReachBottom()) { - onReachBottom && onReachBottom(); - reachBottomLocking = false; - setTimeout(function() { - reachBottomLocking = true; - }, 350); - return true; - } - } - if (onReachBottom && reachBottomLocking) { - if (testReachBottom()) - ; - else { - testReachBottomTimer = setTimeout(testReachBottom, 300); - } - } - ticking = false; - }; - return function onScroll() { - clearTimeout(testReachBottomTimer); - if (!ticking) { - requestAnimationFrame(trigger); - } - ticking = true; - }; -} function getRealRoute(fromRoute, toRoute) { if (!toRoute) { toRoute = fromRoute; @@ -641,316 +245,11 @@ function getRealRoute(fromRoute, toRoute) { fromRouteArray.splice(fromRouteArray.length - i2 - 1, i2 + 1); return "/" + fromRouteArray.concat(toRouteArray).join("/"); } -const isClickEvent = (val) => val.type === "click"; -const isMouseEvent = (val) => val.type.indexOf("mouse") === 0; -function $nne(evt) { - const {currentTarget} = evt; - if (!(evt instanceof Event) || !(currentTarget instanceof HTMLElement)) { - return evt; - } - if (currentTarget.tagName.indexOf("UNI-") !== 0) { - return evt; - } - const res = createNativeEvent(evt); - if (isClickEvent(evt)) { - normalizeClickEvent(res, evt); - } else if (isMouseEvent(evt)) { - normalizeMouseEvent(res, evt); - } else if (evt instanceof TouchEvent) { - const {top} = getWindowOffset(); - res.touches = normalizeTouchEvent(evt.touches, top); - res.changedTouches = normalizeTouchEvent(evt.changedTouches, top); - } - return res; -} -function createNativeEvent(evt) { - const {type, timeStamp, currentTarget} = evt; - const target = uniShared.normalizeTarget(currentTarget); - const event = { - type, - timeStamp, - target, - detail: {}, - currentTarget: target - }; - { - shared.extend(event, { - preventDefault() { - if (process.env.NODE_ENV !== "production") { - console.warn("preventDefault is only supported in h5, use `.prevent` instead."); - } - return evt.preventDefault(); - }, - stopPropagation() { - if (process.env.NODE_ENV !== "production") { - console.warn("stopPropagation is only supported in h5, use `.stop` instead."); - } - return evt.stopPropagation(); - } - }); - } - return event; -} -function normalizeClickEvent(evt, mouseEvt) { - const {x, y} = mouseEvt; - const {top} = getWindowOffset(); - evt.detail = {x, y: y - top}; - evt.touches = evt.changedTouches = [createTouchEvent(mouseEvt)]; -} -function normalizeMouseEvent(evt, mouseEvt) { - const {top} = getWindowOffset(); - evt.pageX = mouseEvt.pageX; - evt.pageY = mouseEvt.pageY - top; - evt.clientX = mouseEvt.clientX; - evt.clientY = mouseEvt.clientY - top; -} -function createTouchEvent(evt) { - return { - force: 1, - identifier: 0, - clientX: evt.clientX, - clientY: evt.clientY, - pageX: evt.pageX, - pageY: evt.pageY - }; -} -function normalizeTouchEvent(touches, top) { - const res = []; - for (let i2 = 0; i2 < touches.length; i2++) { - const {identifier, pageX, pageY, clientX, clientY, force} = touches[i2]; - res.push({ - identifier, - pageX, - pageY: pageY - top, - clientX, - clientY: clientY - top, - force: force || 0 - }); - } - return res; -} -var instance = /* @__PURE__ */ Object.freeze({ - __proto__: null, - [Symbol.toStringTag]: "Module", - $nne -}); -const CLASS_RE = /^\s+|\s+$/g; -const WXS_CLASS_RE = /\s+/; -function getWxsClsArr(clsArr, classList, isAdd) { - const wxsClsArr = []; - let checkClassList = function(cls) { - if (isAdd) { - checkClassList = function(cls2) { - return !classList.contains(cls2); - }; - } else { - checkClassList = function(cls2) { - return classList.contains(cls2); - }; - } - return checkClassList(cls); - }; - clsArr.forEach((cls) => { - cls = cls.replace(CLASS_RE, ""); - checkClassList(cls) && wxsClsArr.push(cls); - }); - return wxsClsArr; -} -function parseStyleText(cssText) { - const res = {}; - const listDelimiter = /;(?![^(]*\))/g; - const propertyDelimiter = /:(.+)/; - cssText.split(listDelimiter).forEach(function(item) { - if (item) { - const tmp = item.split(propertyDelimiter); - tmp.length > 1 && (res[tmp[0].trim()] = tmp[1].trim()); - } - }); - return res; -} -class ComponentDescriptor { - constructor(vm) { - this.$vm = vm; - this.$el = vm.$el; - } - selectComponent(selector) { - if (!this.$el || !selector) { - return; - } - const el = this.$el.querySelector(selector); - return el && el.__vue__ && createComponentDescriptor(el.__vue__, false); - } - selectAllComponents(selector) { - if (!this.$el || !selector) { - return []; - } - const descriptors = []; - const els = this.$el.querySelectorAll(selector); - for (let i2 = 0; i2 < els.length; i2++) { - const el = els[i2]; - el.__vue__ && descriptors.push(createComponentDescriptor(el.__vue__, false)); - } - return descriptors; - } - setStyle(style2) { - if (!this.$el || !style2) { - return this; - } - if (typeof style2 === "string") { - style2 = parseStyleText(style2); - } - if (shared.isPlainObject(style2)) { - this.$el.__wxsStyle = style2; - this.$vm.$forceUpdate(); - } - return this; - } - addClass(...clsArr) { - if (!this.$el || !clsArr.length) { - return this; - } - const wxsClsArr = getWxsClsArr(clsArr, this.$el.classList, true); - if (wxsClsArr.length) { - const wxsClass = this.$el.__wxsAddClass || ""; - this.$el.__wxsAddClass = wxsClass + (wxsClass ? " " : "") + wxsClsArr.join(" "); - this.$vm.$forceUpdate(); - } - return this; - } - removeClass(...clsArr) { - if (!this.$el || !clsArr.length) { - return this; - } - const classList = this.$el.classList; - const addWxsClsArr = this.$el.__wxsAddClass ? this.$el.__wxsAddClass.split(WXS_CLASS_RE) : []; - const wxsClsArr = getWxsClsArr(clsArr, classList, false); - if (wxsClsArr.length) { - const removeWxsClsArr = []; - wxsClsArr.forEach((cls) => { - const clsIndex = addWxsClsArr.findIndex((oldCls) => oldCls === cls); - if (clsIndex !== -1) { - addWxsClsArr.splice(clsIndex, 1); - } - removeWxsClsArr.push(cls); - }); - this.$el.__wxsRemoveClass = removeWxsClsArr; - this.$el.__wxsAddClass = addWxsClsArr.join(" "); - this.$vm.$forceUpdate(); - } - return this; - } - hasClass(cls) { - return this.$el && this.$el.classList.contains(cls); - } - getComputedStyle() { - if (this.$el) { - return window.getComputedStyle(this.$el); - } - return {}; - } - getDataset() { - return this.$el && this.$el.dataset; - } - callMethod(funcName, args = {}) { - const func = this.$vm[funcName]; - if (shared.isFunction(func)) { - func(JSON.parse(JSON.stringify(args))); - } else if (this.$vm._$id) { - UniViewJSBridge.publishHandler("onWxsInvokeCallMethod", { - cid: this.$vm._$id, - method: funcName, - args - }); - } - } - requestAnimationFrame(callback2) { - return window.requestAnimationFrame(callback2), this; - } - getState() { - return this.$el && (this.$el.__wxsState || (this.$el.__wxsState = {})); - } - triggerEvent(eventName, detail = {}) { - return this.$vm.$emit(eventName, detail), this; - } -} -function createComponentDescriptor(vm, isOwnerInstance = true) { - if (isOwnerInstance && vm && vm.$options.name && uniShared.isBuiltInComponent(shared.hyphenate(vm.$options.name))) { - vm = vm.$parent; - } - if (vm && vm.$el) { - if (!vm.$el.__wxsComponentDescriptor) { - vm.$el.__wxsComponentDescriptor = new ComponentDescriptor(vm); - } - return vm.$el.__wxsComponentDescriptor; - } -} -function getComponentDescriptor(instance2, isOwnerInstance) { - return createComponentDescriptor(instance2, isOwnerInstance); -} -function initAppConfig$1(appConfig) { - const globalProperties = appConfig.globalProperties; - shared.extend(globalProperties, instance); - if (__UNI_FEATURE_WXS__) { - globalProperties.$gcd = getComponentDescriptor; - } -} -function initView(app) { - if (__UNI_FEATURE_LONGPRESS__) { - initLongPress(); - } - initAppConfig$1(app._context.config); -} const ServiceJSBridge = /* @__PURE__ */ shared.extend(initBridge("service"), { invokeOnCallback(name, res) { return UniServiceJSBridge.emit("api." + name, res); } }); -function querySelector(vm, selector) { - const el = vm.$el.querySelector(selector); - return el && el.__vue__; -} -function querySelectorAll(vm, selector) { - const nodeList = vm.$el.querySelectorAll(selector); - if (nodeList) { - return [...nodeList].map((node) => node.__vue__).filter(Boolean); - } - return []; -} -function createSelectorQuery$1() { - return uni.createSelectorQuery().in(this); -} -function createIntersectionObserver$1(options) { - return uni.createIntersectionObserver(this, options); -} -function selectComponent(selector) { - return querySelector(this, selector); -} -function selectAllComponents(selector) { - return querySelectorAll(this, selector); -} -var wxInstance = /* @__PURE__ */ Object.freeze({ - __proto__: null, - [Symbol.toStringTag]: "Module", - createSelectorQuery: createSelectorQuery$1, - createIntersectionObserver: createIntersectionObserver$1, - selectComponent, - selectAllComponents -}); -function initAppConfig(appConfig) { - if (__UNI_FEATURE_WX__) { - const globalProperties = appConfig.globalProperties; - shared.extend(globalProperties, wxInstance); - } -} -function getPageById(id2) { - return getCurrentPages().find((page) => page.$page.id === id2); -} -function getPageVmById(id2) { - const page = getPageById(id2); - if (page) { - return page.$vm; - } -} function getCurrentPage() { const pages = getCurrentPages(); const len = pages.length; @@ -958,19 +257,6 @@ function getCurrentPage() { return pages[len - 1]; } } -function getCurrentPageMeta() { - const page = getCurrentPage(); - if (page) { - return page.$page.meta; - } -} -function getCurrentPageId() { - const meta = getCurrentPageMeta(); - if (meta) { - return meta.id; - } - return -1; -} function getCurrentPageVm() { const page = getCurrentPage(); if (page) { @@ -996,46 +282,8 @@ function invokeHook(vm, name, args) { const hooks = vm.$[name]; return hooks && uniShared.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"); -} -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); - } - }; -} -function initService(app) { - initOn(); - initSubscribe(); - initAppConfig(app._context.config); -} -function errorHandler(err, instance2, info) { - if (!instance2) { +function errorHandler(err, instance, info) { + if (!instance) { throw err; } const app = getApp(); @@ -1061,8 +309,8 @@ const pageMetaKey = PolySymbol(process.env.NODE_ENV !== "production" ? "UniPageM function usePageMeta() { return vue.inject(pageMetaKey); } -function providePageMeta(id2) { - const pageMeta = initPageMeta(id2); +function providePageMeta(id) { + const pageMeta = initPageMeta(id); vue.provide(pageMetaKey, pageMeta); return pageMeta; } @@ -1084,18 +332,18 @@ function usePageRoute() { path: "/" + meta.route }; } -function initPageMeta(id2) { +function initPageMeta(id) { if (__UNI_FEATURE_PAGES__) { - return vue.reactive(normalizePageMeta(JSON.parse(JSON.stringify(mergePageMeta(id2, vueRouter.useRoute().meta))))); + return vue.reactive(normalizePageMeta(JSON.parse(JSON.stringify(mergePageMeta(id, vueRouter.useRoute().meta))))); } - return vue.reactive(normalizePageMeta(JSON.parse(JSON.stringify(mergePageMeta(id2, __uniRoutes[0].meta))))); + return vue.reactive(normalizePageMeta(JSON.parse(JSON.stringify(mergePageMeta(id, __uniRoutes[0].meta))))); } const PAGE_META_KEYS = [ "navigationBar", "refreshOptions" ]; -function mergePageMeta(id2, pageMeta) { - const res = Object.assign({id: id2}, __uniConfig.globalStyle, pageMeta); +function mergePageMeta(id, pageMeta) { + const res = Object.assign({id}, __uniConfig.globalStyle, pageMeta); PAGE_META_KEYS.forEach((name) => { res[name] = Object.assign({}, __uniConfig.globalStyle[name] || {}, pageMeta[name] || {}); }); @@ -1116,7 +364,7 @@ function normalizePageMeta(pageMeta) { let offset = rpx2px(refreshOptions.offset); const {type} = navigationBar; if (type !== "transparent" && type !== "none") { - offset += uniShared.NAVBAR_HEIGHT + D__DCloud_local_git_uniAppNext_node_modules_safeAreaInsets_out.top; + offset += uniShared.NAVBAR_HEIGHT + 0; } refreshOptions.offset = offset; refreshOptions.height = rpx2px(refreshOptions.height); @@ -1132,15 +380,13 @@ function normalizePageMeta(pageMeta) { 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 pageMeta; } +function getStateId() { + { + return 1; + } +} PolySymbol(process.env.NODE_ENV !== "production" ? "layout" : "l"); let tabBar; function useTabBar() { @@ -1149,51 +395,6 @@ function useTabBar() { } return tabBar; } -var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -var lookup = /* @__PURE__ */ function() { - const lookup2 = new Uint8Array(256); - for (var i2 = 0; i2 < chars.length; i2++) { - lookup2[chars.charCodeAt(i2)] = i2; - } - return lookup2; -}(); -function encode$1(arraybuffer) { - var bytes = new Uint8Array(arraybuffer), i2, len = bytes.length, base64 = ""; - for (i2 = 0; i2 < len; i2 += 3) { - base64 += chars[bytes[i2] >> 2]; - base64 += chars[(bytes[i2] & 3) << 4 | bytes[i2 + 1] >> 4]; - base64 += chars[(bytes[i2 + 1] & 15) << 2 | bytes[i2 + 2] >> 6]; - base64 += chars[bytes[i2 + 2] & 63]; - } - if (len % 3 === 2) { - base64 = base64.substring(0, base64.length - 1) + "="; - } else if (len % 3 === 1) { - base64 = base64.substring(0, base64.length - 2) + "=="; - } - return base64; -} -function decode(base64) { - var bufferLength = base64.length * 0.75, len = base64.length, i2, p2 = 0, encoded1, encoded2, encoded3, encoded4; - if (base64[base64.length - 1] === "=") { - bufferLength--; - if (base64[base64.length - 2] === "=") { - bufferLength--; - } - } - var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer); - for (i2 = 0; i2 < len; i2 += 4) { - encoded1 = lookup[base64.charCodeAt(i2)]; - encoded2 = lookup[base64.charCodeAt(i2 + 1)]; - encoded3 = lookup[base64.charCodeAt(i2 + 2)]; - encoded4 = lookup[base64.charCodeAt(i2 + 3)]; - bytes[p2++] = encoded1 << 2 | encoded2 >> 4; - bytes[p2++] = (encoded2 & 15) << 4 | encoded3 >> 2; - bytes[p2++] = (encoded3 & 3) << 6 | encoded4 & 63; - } - return arraybuffer; -} -const CHOOSE_SIZE_TYPES = ["original", "compressed"]; -const CHOOSE_SOURCE_TYPES = ["album", "camera"]; const HTTP_METHODS = [ "GET", "OPTIONS", @@ -1210,12 +411,6 @@ function elemInArray(str, arr) { } return str; } -function elemsInArray(strArr, optionalVal) { - if (!shared.isArray(strArr) || strArr.length === 0 || strArr.find((val) => optionalVal.indexOf(val) === -1)) { - return optionalVal; - } - return strArr; -} function validateProtocolFail(name, msg) { console.warn(`${name}: ${msg}`); } @@ -1249,7 +444,7 @@ function validateProp(name, value, prop, isAbsent) { if (!shared.isPlainObject(prop)) { prop = {type: prop}; } - const {type, required, validator: validator2} = prop; + const {type, required, validator} = prop; if (required && isAbsent) { return 'Missing required args: "' + name + '"'; } @@ -1269,8 +464,8 @@ function validateProp(name, value, prop, isAbsent) { return getInvalidTypeMessage(name, value, expectedTypes); } } - if (validator2) { - return validator2(value); + if (validator) { + return validator(value); } } const isSimpleType = /* @__PURE__ */ shared.makeMap("String,Number,Boolean,Function,Symbol"); @@ -1343,58 +538,26 @@ function tryCatch(fn) { } let invokeCallbackId = 1; const invokeCallbacks = {}; -function addInvokeCallback(id2, name, callback2, keepAlive = false) { - invokeCallbacks[id2] = { +function addInvokeCallback(id, name, callback2, keepAlive = false) { + invokeCallbacks[id] = { name, keepAlive, callback: callback2 }; - return id2; + return id; } -function invokeCallback(id2, res, extras) { - if (typeof id2 === "number") { - const opts = invokeCallbacks[id2]; +function invokeCallback(id, res, extras) { + if (typeof id === "number") { + const opts = invokeCallbacks[id]; if (opts) { if (!opts.keepAlive) { - delete invokeCallbacks[id2]; + delete invokeCallbacks[id]; } return opts.callback(res, extras); } } return res; } -function findInvokeCallbackByName(name) { - for (const key in invokeCallbacks) { - if (invokeCallbacks[key].name === name) { - return true; - } - } - return false; -} -function removeKeepAliveApiCallback(name, callback2) { - for (const key in invokeCallbacks) { - const item = invokeCallbacks[key]; - if (item.callback === callback2 && item.name === name) { - delete invokeCallbacks[key]; - } - } -} -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 createKeepAliveApiCallback(name, callback2) { - return addInvokeCallback(invokeCallbackId++, name, callback2, true); -} const API_SUCCESS = "success"; const API_FAIL = "fail"; const API_COMPLETE = "complete"; @@ -1485,11 +648,11 @@ function formatApiArgs(args, options) { } } } -function invokeSuccess(id2, name, res) { - return invokeCallback(id2, shared.extend(res || {}, {errMsg: name + ":ok"})); +function invokeSuccess(id, name, res) { + return invokeCallback(id, shared.extend(res || {}, {errMsg: name + ":ok"})); } -function invokeFail(id2, name, err) { - return invokeCallback(id2, {errMsg: name + ":fail" + (err ? " " + err : "")}); +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") { @@ -1506,107 +669,22 @@ function beforeInvokeApi(name, args, protocol, options) { return errMsg; } } -function checkCallback(callback2) { - if (!shared.isFunction(callback2)) { - throw new Error('Invalid args: type check failed for args "callback". Expected Function'); - } -} -function wrapperOnApi(name, fn, options) { - return (callback2) => { - checkCallback(callback2); - const errMsg = beforeInvokeApi(name, [callback2], void 0, options); - if (errMsg) { - throw new Error(errMsg); - } - const isFirstInvokeOnApi = !findInvokeCallbackByName(name); - createKeepAliveApiCallback(name, callback2); - if (isFirstInvokeOnApi) { - onKeepAliveApiCallback(name); - fn(); - } - }; -} -function wrapperOffApi(name, fn, options) { - return (callback2) => { - checkCallback(callback2); - const errMsg = beforeInvokeApi(name, [callback2], void 0, options); - if (errMsg) { - throw new Error(errMsg); - } - name = name.replace("off", "on"); - removeKeepAliveApiCallback(name, callback2); - const hasInvokeOnApi = findInvokeCallbackByName(name); - if (!hasInvokeOnApi) { - offKeepAliveApiCallback(name); - fn(); - } - }; -} function wrapperTaskApi(name, fn, protocol, options) { return (args) => { - const id2 = createAsyncApiCallback(name, args, options); + const id = createAsyncApiCallback(name, args, options); const errMsg = beforeInvokeApi(name, [args], protocol, options); if (errMsg) { - return invokeFail(id2, name, errMsg); + return invokeFail(id, name, errMsg); } return fn(args, { - resolve: (res) => invokeSuccess(id2, name, res), - reject: (err) => invokeFail(id2, name, err) + 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); - } - return fn.apply(null, args); - }; -} -function wrapperAsyncApi(name, fn, protocol, options) { - return wrapperTaskApi(name, fn, protocol, options); -} -function defineOnApi(name, fn, options) { - return wrapperOnApi(name, fn, options); -} -function defineOffApi(name, fn, options) { - return wrapperOffApi(name, fn, options); -} function defineTaskApi(name, fn, protocol, options) { return promisify(wrapperTaskApi(name, fn, process.env.NODE_ENV !== "production" ? protocol : void 0, options)); } -function defineSyncApi(name, fn, protocol, options) { - return wrapperSyncApi(name, fn, process.env.NODE_ENV !== "production" ? protocol : void 0, options); -} -function defineAsyncApi(name, fn, protocol, options) { - return promisify(wrapperAsyncApi(name, fn, process.env.NODE_ENV !== "production" ? protocol : void 0, options)); -} -const API_BASE64_TO_ARRAY_BUFFER = "base64ToArrayBuffer"; -const Base64ToArrayBufferProtocol = [ - { - name: "base64", - type: String, - required: true - } -]; -const API_ARRAY_BUFFER_TO_BASE64 = "arrayBufferToBase64"; -const ArrayBufferToBase64Protocol = [ - { - name: "arrayBuffer", - type: [ArrayBuffer, Uint8Array], - required: true - } -]; -const base64ToArrayBuffer = defineSyncApi(API_BASE64_TO_ARRAY_BUFFER, (base64) => { - return decode(base64); -}, Base64ToArrayBufferProtocol); -const arrayBufferToBase64 = defineSyncApi(API_ARRAY_BUFFER_TO_BASE64, (arrayBuffer) => { - return encode$1(arrayBuffer); -}, ArrayBufferToBase64Protocol); -function findElem(vm) { - return vm.$el; -} const SCHEME_RE = /^([a-z-]+:)?\/\//i; const DATA_RE = /^data:.*,.*/; function addBase(filePath) { @@ -1641,586 +719,7 @@ function getRealPath(filePath) { } return filePath; } -const ua = navigator.userAgent; -const isAndroid = /* @__PURE__ */ /android/i.test(ua); -const isIOS$1 = /* @__PURE__ */ /iphone|ipad|ipod/i.test(ua); -const isWindows = /* @__PURE__ */ ua.match(/Windows NT ([\d|\d.\d]*)/i); -const isMac = /* @__PURE__ */ /Macintosh|Mac/i.test(ua); -const isLinux = /* @__PURE__ */ /Linux|X11/i.test(ua); -const isIPadOS = isMac && navigator.maxTouchPoints > 0; -function getScreenFix() { - return /^Apple/.test(navigator.vendor) && typeof window.orientation === "number"; -} -function isLandscape(screenFix) { - return screenFix && Math.abs(window.orientation) === 90; -} -function getScreenWidth(screenFix, landscape) { - return screenFix ? Math[landscape ? "max" : "min"](screen.width, screen.height) : screen.width; -} -function getScreenHeight(screenFix, landscape) { - return screenFix ? Math[landscape ? "min" : "max"](screen.height, screen.width) : screen.height; -} -function getWindowWidth(screenWidth) { - return Math.min(window.innerWidth, document.documentElement.clientWidth, screenWidth) || screenWidth; -} -function getBaseSystemInfo() { - const screenFix = getScreenFix(); - const windowWidth = getWindowWidth(getScreenWidth(screenFix, isLandscape(screenFix))); - return { - platform: isIOS$1 ? "ios" : "other", - pixelRatio: window.devicePixelRatio, - windowWidth - }; -} -function operateVideoPlayer(videoId, vm, type, data) { - const pageId = getPageIdByVm(vm); - UniServiceJSBridge.publishHandler("video." + videoId, { - videoId, - type, - data - }, pageId); -} -function operateMap(id2, vm, type, data) { - const pageId = getPageIdByVm(vm); - UniServiceJSBridge.publishHandler("map." + id2, { - type, - data - }, pageId); -} -function addIntersectionObserver({reqId, component, options, callback: callback2}, _pageId) { - const $el = findElem(component); - ($el.__io || ($el.__io = {}))[reqId] = requestComponentObserver($el, options, callback2); -} -function removeIntersectionObserver({reqId, component}, _pageId) { - const $el = findElem(component); - const intersectionObserver = $el.__io && $el.__io[reqId]; - if (intersectionObserver) { - intersectionObserver.disconnect(); - delete $el.__io[reqId]; - } -} -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 = 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 (shared.isFunction(interceptor[hook])) { - interceptors[hook] = mergeHook(interceptors[hook], interceptor[hook]); - } - }); -} -function removeInterceptorHook(interceptors, interceptor) { - if (!interceptors || !interceptor) { - return; - } - Object.keys(interceptor).forEach((hook) => { - if (shared.isFunction(interceptor[hook])) { - removeHook(interceptors[hook], interceptor[hook]); - } - }); -} -function mergeHook(parentVal, childVal) { - const res = childVal ? parentVal ? parentVal.concat(childVal) : shared.isArray(childVal) ? childVal : [childVal] : parentVal; - return res ? dedupeHooks(res) : res; -} -function dedupeHooks(hooks) { - const res = []; - for (let i2 = 0; i2 < hooks.length; i2++) { - if (res.indexOf(hooks[i2]) === -1) { - res.push(hooks[i2]); - } - } - return res; -} -function removeHook(hooks, hook) { - if (!hooks) { - return; - } - const index2 = hooks.indexOf(hook); - if (index2 !== -1) { - hooks.splice(index2, 1); - } -} -const addInterceptor = defineSyncApi(API_ADD_INTERCEPTOR, (method, interceptor) => { - if (typeof method === "string" && shared.isPlainObject(interceptor)) { - mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), interceptor); - } else if (shared.isPlainObject(method)) { - mergeInterceptorHook(globalInterceptors, method); - } -}, AddInterceptorProtocol); -const removeInterceptor = defineSyncApi(API_REMOVE_INTERCEPTOR, (method, interceptor) => { - if (typeof method === "string") { - if (shared.isPlainObject(interceptor)) { - removeInterceptorHook(scopedInterceptors[method], interceptor); - } else { - delete scopedInterceptors[method]; - } - } else if (shared.isPlainObject(method)) { - removeInterceptorHook(globalInterceptors, method); - } -}, RemoveInterceptorProtocol); -const promiseInterceptor = { - returnValue(res) { - if (!shared.isPromise(res)) { - return res; - } - return res.then((res2) => { - return res2[1]; - }).catch((res2) => { - return res2[0]; - }); - } -}; -const validator = [ - { - name: "id", - type: String, - required: true - } -]; -const API_CREATE_VIDEO_CONTEXT = "createVideoContext"; -const API_CREATE_MAP_CONTEXT = "createMapContext"; -const CreateMapContextProtocol = validator; -const API_CREATE_INNER_AUDIO_CONTEXT = "createInnerAudioContext"; -const RATES = [0.5, 0.8, 1, 1.25, 1.5, 2]; -class VideoContext { - constructor(id2, vm) { - this.id = id2; - this.vm = vm; - } - play() { - operateVideoPlayer(this.id, this.vm, "play"); - } - pause() { - operateVideoPlayer(this.id, this.vm, "pause"); - } - stop() { - operateVideoPlayer(this.id, this.vm, "stop"); - } - seek(position) { - operateVideoPlayer(this.id, this.vm, "seek", { - position - }); - } - sendDanmu(args) { - operateVideoPlayer(this.id, this.vm, "sendDanmu", args); - } - playbackRate(rate) { - if (!~RATES.indexOf(rate)) { - rate = 1; - } - operateVideoPlayer(this.id, this.vm, "playbackRate", { - rate - }); - } - requestFullScreen(args = {}) { - operateVideoPlayer(this.id, this.vm, "requestFullScreen", args); - } - exitFullScreen() { - operateVideoPlayer(this.id, this.vm, "exitFullScreen"); - } - showStatusBar() { - operateVideoPlayer(this.id, this.vm, "showStatusBar"); - } - hideStatusBar() { - operateVideoPlayer(this.id, this.vm, "hideStatusBar"); - } -} -const createVideoContext = defineSyncApi(API_CREATE_VIDEO_CONTEXT, (id2, context) => { - if (context) { - return new VideoContext(id2, context); - } - return new VideoContext(id2, getCurrentPageVm()); -}); -class MapContext { - constructor(id2, vm) { - this.id = id2; - this.vm = vm; - } - getCenterLocation(options) { - operateMap(this.id, this.vm, "getCenterLocation", options); - } - moveToLocation() { - operateMap(this.id, this.vm, "moveToLocation"); - } - getScale(options) { - operateMap(this.id, this.vm, "getScale", options); - } - getRegion(options) { - operateMap(this.id, this.vm, "getRegion", options); - } - includePoints(options) { - operateMap(this.id, this.vm, "includePoints", options); - } - translateMarker(options) { - operateMap(this.id, this.vm, "translateMarker", options); - } - addCustomLayer() { - } - removeCustomLayer() { - } - addGroundOverlay() { - } - removeGroundOverlay() { - } - updateGroundOverlay() { - } - initMarkerCluster() { - } - addMarkers() { - } - removeMarkers() { - } - moveAlong() { - } - openMapAp() { - } - $getAppMap() { - } -} -const createMapContext = defineSyncApi(API_CREATE_MAP_CONTEXT, (id2, context) => { - if (context) { - return new MapContext(id2, context); - } - return new MapContext(id2, getCurrentPageVm()); -}, CreateMapContextProtocol); -const defaultOptions = { - thresholds: [0], - initialRatio: 0, - observeAll: false -}; -const MARGINS = ["top", "right", "bottom", "left"]; -let reqComponentObserverId = 1; -function normalizeRootMargin(margins = {}) { - return MARGINS.map((name) => `${Number(margins[name]) || 0}px`).join(" "); -} -class ServiceIntersectionObserver { - constructor(component, options) { - this._pageId = getPageIdByVm(component); - this._component = component; - this._options = shared.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, callback2) { - if (!shared.isFunction(callback2)) { - return; - } - this._options.selector = selector; - this._reqId = reqComponentObserverId++; - addIntersectionObserver({ - reqId: this._reqId, - component: this._component, - options: this._options, - callback: callback2 - }, this._pageId); - } - disconnect() { - this._reqId && removeIntersectionObserver({reqId: this._reqId, component: this._component}, this._pageId); - } -} -const createIntersectionObserver = defineSyncApi("createIntersectionObserver", (context, options) => { - if (context && !getPageIdByVm(context)) { - options = context; - context = null; - } - if (context) { - return new ServiceIntersectionObserver(context, options); - } - return new ServiceIntersectionObserver(getCurrentPageVm(), options); -}); -const createSelectorQuery = () => { -}; const API_ON_TAB_BAR_MID_BUTTON_TAP = "onTabBarMidButtonTap"; -const onTabBarMidButtonTap = defineOnApi(API_ON_TAB_BAR_MID_BUTTON_TAP, () => { -}); -const API_CAN_I_USE = "canIUse"; -const CanIUseProtocol = [ - { - name: "schema", - type: String, - required: true - } -]; -const API_MAKE_PHONE_CALL = "makePhoneCall"; -const MakePhoneCallProtocol = { - phoneNumber: String -}; -const API_ON_ACCELEROMETER = "onAccelerometer"; -const API_OFF_ACCELEROMETER = "offAccelerometer"; -const API_START_ACCELEROMETER = "startAccelerometer"; -const API_STOP_ACCELEROMETER = "stopAccelerometer"; -const API_ON_COMPASS = "onCompass"; -const API_OFF_COMPASS = "offCompass"; -const API_START_COMPASS = "startCompass"; -const API_STOP_COMPASS = "stopCompass"; -const API_VIBRATE_SHORT = "vibrateShort"; -const API_VIBRATE_LONG = "vibrateLong"; -const API_GET_STORAGE = "getStorage"; -const GetStorageProtocol = { - key: { - type: String, - required: true - } -}; -const API_GET_STORAGE_SYNC = "getStorageSync"; -const GetStorageSyncProtocol = [ - { - name: "key", - type: String, - required: true - } -]; -const API_SET_STORAGE = "setStorage"; -const SetStorageProtocol = { - key: { - type: String, - required: true - }, - data: { - required: true - } -}; -const API_SET_STORAGE_SYNC = "setStorageSync"; -const SetStorageSyncProtocol = [ - { - name: "key", - type: String, - required: true - }, - { - name: "data", - required: true - } -]; -const API_REMOVE_STORAGE = "removeStorage"; -const RemoveStorageProtocol = GetStorageProtocol; -const RemoveStorageSyncProtocol = GetStorageSyncProtocol; -const API_GET_FILE_INFO = "getFileInfo"; -const GetFileInfoOptions = { - formatArgs: { - filePath(filePath, params) { - params.filePath = getRealPath(filePath); - } - } -}; -const GetFileInfoProtocol = { - filePath: { - type: String, - required: true - } -}; -const API_OPEN_DOCUMENT = "openDocument"; -const OpenDocumentOptions = { - formatArgs: { - filePath(filePath, params) { - params.filePath = getRealPath(filePath); - } - } -}; -const OpenDocumentProtocol = { - filePath: { - type: String, - required: true - }, - fileType: String -}; -const API_HIDE_KEYBOARD = "hideKeyboard"; -const API_GET_LOCATION = "getLocation"; -const coordTypes = ["WGS84", "GCJ02"]; -const GetLocationOptions = { - formatArgs: { - type(value, params) { - value = (value || "").toUpperCase(); - if (coordTypes.indexOf(value) === -1) { - params.type = coordTypes[0]; - } else { - params.type = value; - } - }, - altitude(value, params) { - params.altitude = value ? value : false; - } - } -}; -const GetLocationProtocol = { - type: String, - altitude: Boolean -}; -const API_CHOOSE_IMAGE = "chooseImage"; -const ChooseImageOptions = { - formatArgs: { - count(value, params) { - if (!value || value <= 0) { - params.count = 9; - } - }, - 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 = [""]; - } - } -}; -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 = [""]; - } - } -}; -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); - } - } -}; -const GetImageInfoProtocol = { - src: { - type: String, - required: true - } -}; -const API_GET_VIDEO_INFO = "getVideoInfo"; -const GetVideoInfoOptions = { - formatArgs: { - src(src, params) { - params.src = getRealPath(src); - } - } -}; -const GetVideoInfoProtocol = { - src: { - type: String, - required: true - } -}; const API_REQUEST = "request"; const dataType = { JSON: "json" @@ -2298,2055 +797,816 @@ const RequestOptions = { } } }; -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); - } - }, - header(value, params) { - params.header = value || {}; - }, - formData(value, params) { - params.formData = value || {}; +const envMethod = /* @__PURE__ */ (() => "env")(); +function normalizeWindowBottom(windowBottom) { + return `calc(${windowBottom}px + ${envMethod}(safe-area-inset-bottom))`; +} +const SEP = "$$"; +const currentPagesMap = new Map(); +function pruneCurrentPages() { + currentPagesMap.forEach((page, id2) => { + if (page.$.isUnmounted) { + currentPagesMap.delete(id2); } - } -}; -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]; + }); +} +function getCurrentPages$1() { + const curPages = []; + const pages = currentPagesMap.values(); + for (const page of pages) { + if (page.__isTabBar) { + if (page.$.__isActive) { + curPages.push(page); } + } else { + curPages.push(page); } } -}; -const ConnectSocketProtocol = { - url: { - type: String, - required: true - }, - header: { - type: Object - }, - method: String, - protocols: [Array, String] -}; -const API_SEND_SOCKET_MESSAGE = "sendSocketMessage"; -const SendSocketMessageProtocol = { - data: [String, ArrayBuffer] -}; -const API_CLOSE_SOCKET = "closeSocket"; -const CloseSocketProtocol = { - code: Number, - reason: String -}; -function encodeQueryString(url) { - if (typeof url !== "string") { - return url; - } - const index2 = url.indexOf("?"); - if (index2 === -1) { - return url; - } - const query = url.substr(index2 + 1).trim().replace(/^(\?|#|&)/, ""); - if (!query) { - return url; - } - url = url.substr(0, index2); - const params = []; - query.split("&").forEach((param) => { - const parts = param.replace(/\+/g, " ").split("="); - const key = parts.shift(); - const val = parts.length > 0 ? parts.join("=") : ""; - params.push(key + "=" + encodeURIComponent(val)); - }); - return params.length ? url + "?" + params.join("&") : url; -} -const ANIMATION_IN = [ - "slide-in-right", - "slide-in-left", - "slide-in-top", - "slide-in-bottom", - "fade-in", - "zoom-out", - "zoom-fade-out", - "pop-in", - "none" -]; -const ANIMATION_OUT = [ - "slide-out-right", - "slide-out-left", - "slide-out-top", - "slide-out-bottom", - "fade-out", - "zoom-in", - "zoom-fade-in", - "pop-out", - "none" -]; -const BaseRouteProtocol = { - url: { - type: String, - required: true - } -}; -const API_NAVIGATE_TO = "navigateTo"; -const API_REDIRECT_TO = "redirectTo"; -const API_RE_LAUNCH = "reLaunch"; -const API_SWITCH_TAB = "switchTab"; -const API_NAVIGATE_BACK = "navigateBack"; -const API_PRELOAD_PAGE = "preloadPage"; -const API_UN_PRELOAD_PAGE = "unPreloadPage"; -const NavigateToProtocol = /* @__PURE__ */ shared.extend({}, BaseRouteProtocol, createAnimationProtocol(ANIMATION_IN)); -const NavigateBackProtocol = /* @__PURE__ */ shared.extend({ - delta: { - type: Number - } -}, createAnimationProtocol(ANIMATION_OUT)); -const RedirectToProtocol = BaseRouteProtocol; -const ReLaunchProtocol = BaseRouteProtocol; -const SwitchTabProtocol = BaseRouteProtocol; -const NavigateToOptions = /* @__PURE__ */ createRouteOptions(API_NAVIGATE_TO); -const RedirectToOptions = /* @__PURE__ */ createRouteOptions(API_REDIRECT_TO); -const ReLaunchOptions = /* @__PURE__ */ createRouteOptions(API_RE_LAUNCH); -const SwitchTabOptions = /* @__PURE__ */ createRouteOptions(API_SWITCH_TAB); -const NavigateBackOptions = { - formatArgs: { - delta(value, params) { - value = parseInt(value + "") || 1; - params.delta = Math.min(getCurrentPages().length - 1, value); - } + return curPages; +} +function initPublicPage(route) { + const meta = usePageMeta(); + if (!__UNI_FEATURE_PAGES__) { + const {path: path2, alias} = __uniRoutes[0]; + return { + id: meta.id, + path: path2, + route: alias.substr(1), + fullPath: path2, + options: {}, + meta + }; } -}; -function createAnimationProtocol(animationTypes) { + const {path} = route; return { - animationType: { - type: String, - validator(type) { - if (type && animationTypes.indexOf(type) === -1) { - return "`" + type + "` is not supported for `animationType` (supported values are: `" + animationTypes.join("`|`") + "`)"; - } - } - }, - animationDuration: { - type: Number - } + id: meta.id, + path, + route: route.meta.route, + fullPath: route.meta.isEntry ? route.meta.pagePath : route.fullPath, + options: {}, + meta }; } -let navigatorLock; -function beforeRoute() { - navigatorLock = ""; +function initPage(vm) { + const route = vm.$route; + const page = initPublicPage(route); + vm.$vm = vm; + vm.$page = page; + vm.__isTabBar = page.meta.isTabBar; + currentPagesMap.set(normalizeRouteKey(page.path, page.id), vm); } -function createRouteOptions(type) { - return { - formatArgs: { - url: createNormalizeUrl(type) - }, - beforeAll: beforeRoute - }; +function normalizeRouteKey(path, id2) { + return path + SEP + id2; } -function createNormalizeUrl(type) { - return function normalizeUrl(url, params) { - if (!url) { - return `Missing required args: "url"`; - } - url = getRealRoute(url); - const pagePath = url.split("?")[0]; - const routeOptions = __uniRoutes.find(({path, alias}) => path === pagePath || alias === pagePath); - if (!routeOptions) { - return "page `" + url + "` is not found"; - } - if (type === API_NAVIGATE_TO || type === API_REDIRECT_TO) { - if (routeOptions.meta.isTabBar) { - return `can not ${type} a tabbar page`; - } - } else if (type === API_SWITCH_TAB) { - if (!routeOptions.meta.isTabBar) { - return "can not switch to no-tabBar page"; - } - } - if ((type === API_SWITCH_TAB || type === API_PRELOAD_PAGE) && routeOptions.meta.isTabBar && params.openType !== "appLaunch") { - url = pagePath; - } - if (routeOptions.meta.isEntry) { - url = url.replace(routeOptions.alias, "/"); - } - params.url = encodeQueryString(url); - if (type === API_UN_PRELOAD_PAGE) { - return; - } else if (type === API_PRELOAD_PAGE) { - if (routeOptions.meta.isTabBar) { - const pages = getCurrentPages(true); - const tabBarPagePath = routeOptions.path.substr(1); - if (pages.find((page) => page.route === tabBarPagePath)) { - return "tabBar page `" + tabBarPagePath + "` already exists"; - } - } - return; - } - if (navigatorLock === url && params.openType !== "appLaunch") { - return `${navigatorLock} locked`; - } - if (__uniConfig.ready) { - navigatorLock = url; - } +function useKeepAliveRoute() { + const route = vueRouter.useRoute(); + const routeKey = vue.computed(() => normalizeRouteKey(route.path, getStateId())); + const isTabBar = vue.computed(() => route.meta.isTabBar); + return { + routeKey, + isTabBar, + routeCache }; } -const API_HIDE_LOADING = "hideLoading"; -const API_HIDE_TOAST = "hideToast"; -const API_LOAD_FONT_FACE = "loadFontFace"; -const LoadFontFaceProtocol = { - family: { - type: String, - required: true +const pageCacheMap = new Map(); +const routeCache = { + get(key) { + return pageCacheMap.get(key); }, - source: { - type: String, - required: true + set(key, value) { + pruneRouteCache(key); + pageCacheMap.set(key, value); }, - desc: Object -}; -const FRONT_COLORS = ["#ffffff", "#000000"]; -const API_SET_NAVIGATION_BAR_COLOR = "setNavigationBarColor"; -const SetNavigationBarColorOptions = { - formatArgs: { - animation(animation, params) { - if (!animation) { - animation = {duration: 0, timingFunc: "linear"}; - } - params.animation = { - duration: animation.duration || 0, - timingFunc: animation.timingFunc || "linear" - }; + delete(key) { + const vnode = pageCacheMap.get(key); + if (!vnode) { + return; } + pageCacheMap.delete(key); + }, + forEach(fn) { + pageCacheMap.forEach(fn); } }; -const SetNavigationBarColorProtocol = { - frontColor: { - type: String, - required: true, - validator(frontColor) { - if (FRONT_COLORS.indexOf(frontColor) === -1) { - return `invalid frontColor "${frontColor}"`; +function isTabBarVNode(vnode) { + return vnode.props.type === "tabBar"; +} +function pruneRouteCache(key) { + const pageId = parseInt(key.split(SEP)[1]); + if (!pageId) { + return; + } + routeCache.forEach((vnode, key2) => { + const cPageId = parseInt(key2.split(SEP)[1]); + if (cPageId && cPageId > pageId) { + if (__UNI_FEATURE_TABBAR__ && isTabBarVNode(vnode)) { + return; } + routeCache.delete(key2); + routeCache.pruneCacheEntry(vnode); + vue.nextTick(() => pruneCurrentPages()); } - }, - backgroundColor: { - type: String, - required: true - }, - animation: Object -}; -const API_SET_NAVIGATION_BAR_TITLE = "setNavigationBarTitle"; -const SetNavigationBarTitleProtocol = { - title: { - type: String, - required: true + }); +} +function initRouter(app) { + const router = vueRouter.createRouter(createRouterOptions()); + app.router = router; + app.use(router); +} +const scrollBehavior = (_to, _from, savedPosition) => { + if (savedPosition) { + return savedPosition; } }; -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); +function createRouterOptions() { + return { + history: initHistory(), + strict: !!__uniConfig.router.strict, + routes: __uniRoutes, + scrollBehavior + }; +} +function initHistory() { + { + return vueRouter.createMemoryHistory(); + } +} +var index$m = { + install(app) { + initApp$1(app); + if (__UNI_FEATURE_PAGES__) { + initRouter(app); } } }; -const API_SHOW_LOADING = "showLoading"; -const ShowLoadingProtocol = { - title: String, - mask: Boolean -}; -const ShowLoadingOptions = { - formatArgs: { - title: "", - mask: false +let appVm; +function getApp$1() { + return appVm; +} +function initApp(vm) { + appVm = vm; + appVm.$vm = vm; + appVm.globalData = appVm.$options.globalData || {}; +} +function wrapperComponentSetup(comp, {init, setup, after}) { + const oldSetup = comp.setup; + comp.setup = (props2, ctx) => { + const instance = vue.getCurrentInstance(); + init(instance.proxy); + const query = setup(instance); + if (oldSetup) { + return oldSetup(query, ctx); + } + }; + after && after(comp); +} +function setupComponent(comp, options) { + if (comp && (comp.__esModule || comp[Symbol.toStringTag] === "Module")) { + wrapperComponentSetup(comp.default, options); + } else { + wrapperComponentSetup(comp, options); } -}; -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 (!shared.hasOwn(params, "cancelText")) { - const {t: t2} = useI18n(); - params.cancelText = t2("uni.showModal.cancel"); + return comp; +} +function setupPage(comp) { + return setupComponent(comp, { + init: initPage, + setup(instance) { + instance.__isPage = true; + instance.root = instance; + const route = usePageRoute(); + if (route.meta.isTabBar) { + instance.__isActive = true; } - }, - cancelColor: "#000", - confirmText(_value, params) { - if (!shared.hasOwn(params, "confirmText")) { - const {t: t2} = useI18n(); - params.confirmText = t2("uni.showModal.confirm"); + { + return route.query; } - }, - confirmColor: uniShared.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 = ""; + } + }); +} +function setupApp(comp) { + return setupComponent(comp, { + init: initApp, + setup(instance) { + const route = usePageRoute(); + { + return route.query; } }, - 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"; + after(comp2) { + comp2.mpType = "app"; + comp2.render = () => (vue.openBlock(), vue.createBlock(LayoutComponent)); } + }); +} +var hover = { + data() { + return { + hovering: false + }; }, - formatArgs: { - index(value) { - if (!__uniConfig.tabBar.list[value]) { - return "tabbar item not found"; - } + props: { + hoverClass: { + type: String, + default: "none" + }, + hoverStopPropagation: { + type: Boolean, + default: false + }, + hoverStartTime: { + type: [Number, String], + default: 50 + }, + hoverStayTime: { + type: [Number, String], + default: 400 } - } -}; -const API_SET_TAB_BAR_ITEM = "setTabBarItem"; -const SetTabBarItemProtocol = /* @__PURE__ */ shared.extend({ - text: String, - iconPath: String, - selectedIconPath: String, - pagePath: String -}, IndexProtocol); -const SetTabBarItemOptions = { - beforeInvoke: IndexOptions.beforeInvoke, - formatArgs: /* @__PURE__ */ shared.extend({ - pagePath(value, params) { - if (value) { - params.pagePath = uniShared.removeLeadingSlash(value); + }, + methods: { + _hoverTouchStart(evt) { + if (evt._hoverPropagationStopped) { + return; } - } - }, 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); + if (!this.hoverClass || this.hoverClass === "none" || this.disabled) { + return; } - }, - borderStyle(value, params) { - if (value) { - params.borderStyle = value === "white" ? "white" : "black"; + if (evt.touches.length > 1) { + return; } - } - } -}; -const API_HIDE_TAB_BAR = "hideTabBar"; -const HideTabBarProtocol = { - animation: Boolean -}; -const API_SHOW_TAB_BAR = "showTabBar"; -const ShowTabBarProtocol = HideTabBarProtocol; -const API_HIDE_TAB_BAR_RED_DOT = "hideTabBarRedDot"; -const HideTabBarRedDotProtocol = IndexProtocol; -const HideTabBarRedDotOptions = IndexOptions; -const API_SHOW_TAB_BAR_RED_DOT = "showTabBarRedDot"; -const ShowTabBarRedDotProtocol = IndexProtocol; -const ShowTabBarRedDotOptions = IndexOptions; -const API_REMOVE_TAB_BAR_BADGE = "removeTabBarBadge"; -const RemoveTabBarBadgeProtocol = IndexProtocol; -const RemoveTabBarBadgeOptions = IndexOptions; -const API_SET_TAB_BAR_BADGE = "setTabBarBadge"; -const SetTabBarBadgeProtocol = /* @__PURE__ */ shared.extend({ - text: { - type: String, - required: true - } -}, IndexProtocol); -const SetTabBarBadgeOptions = { - beforeInvoke: IndexOptions.beforeInvoke, - formatArgs: /* @__PURE__ */ shared.extend({ - text(value, params) { - if (uniShared.getLen(value) >= 4) { - params.text = "..."; + if (this.hoverStopPropagation) { + evt._hoverPropagationStopped = true; } - } - }, IndexOptions.formatArgs) -}; -const initIntersectionObserverPolyfill = function() { - if (typeof window !== "object") { - return; - } - if ("IntersectionObserver" in window && "IntersectionObserverEntry" in window && "intersectionRatio" in window.IntersectionObserverEntry.prototype) { - if (!("isIntersecting" in window.IntersectionObserverEntry.prototype)) { - Object.defineProperty(window.IntersectionObserverEntry.prototype, "isIntersecting", { - get: function() { - return this.intersectionRatio > 0; + this._hoverTouch = true; + this._hoverStartTimer = setTimeout(() => { + this.hovering = true; + if (!this._hoverTouch) { + this._hoverReset(); } + }, this.hoverStartTime); + }, + _hoverTouchEnd(evt) { + this._hoverTouch = false; + if (this.hovering) { + this._hoverReset(); + } + }, + _hoverReset() { + requestAnimationFrame(() => { + clearTimeout(this._hoverStayTimer); + this._hoverStayTimer = setTimeout(() => { + this.hovering = false; + }, this.hoverStayTime); }); - } - return; - } - function getFrameElement(doc) { - try { - return doc.defaultView && doc.defaultView.frameElement || null; - } catch (e2) { - return null; + }, + _hoverTouchCancel(evt) { + this._hoverTouch = false; + this.hovering = false; + clearTimeout(this._hoverStartTimer); } } - 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; - } - } - function IntersectionObserver2(callback2, opt_options) { - var options = opt_options || {}; - if (typeof callback2 != "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 = callback2; - 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, i2, a2) { - if (typeof t2 != "number" || isNaN(t2) || t2 < 0 || t2 > 1) { - throw new Error("threshold must be a number between 0 and 1 inclusively"); - } - return t2 !== a2[i2 - 1]; - }); - }; - IntersectionObserver2.prototype._parseRootMargin = function(opt_rootMargin) { - var marginString = opt_rootMargin || "0px"; - var margins = marginString.split(/\s+/).map(function(margin) { - var parts = /^(-?\d*\.?\d+)(px|%)$/.exec(margin); - if (!parts) { - throw new Error("rootMargin must be specified in pixels or percent"); - } - return {value: parseFloat(parts[1]), unit: parts[2]}; - }); - margins[1] = margins[1] || margins[0]; - margins[2] = margins[2] || margins[0]; - margins[3] = margins[3] || margins[1]; - return margins; - }; - IntersectionObserver2.prototype._monitorIntersections = function(doc) { - var win = doc.defaultView; - if (!win) { - return; - } - if (this._monitoringDocuments.indexOf(doc) != -1) { - return; - } - var callback2 = this._checkForIntersections; - var monitoringInterval = null; - var domObserver = null; - if (this.POLL_INTERVAL) { - monitoringInterval = win.setInterval(callback2, this.POLL_INTERVAL); - } else { - addEvent(win, "resize", callback2, true); - addEvent(doc, "scroll", callback2, true); - if (this.USE_MUTATION_OBSERVER && "MutationObserver" in win) { - domObserver = new win.MutationObserver(callback2); - 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", callback2, true); - } - removeEvent(doc, "scroll", callback2, 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; +}; +var subscriber = { + mounted() { + this._toggleListeners("subscribe", this.id); + this.$watch("id", (newId, oldId) => { + this._toggleListeners("unsubscribe", oldId, true); + this._toggleListeners("subscribe", newId, true); }); - 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 i2 = 0; i2 < unsubscribes.length; i2++) { - unsubscribes[i2](); - } - }; - IntersectionObserver2.prototype._checkForIntersections = function() { - if (!this.root && crossOriginUpdater && !crossOriginRect) { - return; + }, + beforeDestroy() { + this._toggleListeners("unsubscribe", this.id); + if (this._contextId) { + this._toggleListeners("unsubscribe", this._contextId); } - 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); - } + }, + methods: { + _toggleListeners(type, id, watch) { + if (watch && !id) { + return; } - }, this); - if (this._queuedEntries.length) { - this._callback(this.takeRecords(), this); - } - }; - 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 (!shared.isFunction(this._handleSubscribe)) { + return; } - if (parentRect) { - intersectionRect = computeRectIntersection(parentRect, intersectionRect); + 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 (!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 { + name: this.$options.name.replace(/VUni([A-Z])/, "$1").toLowerCase(), + id, + page: this.$page.id }; } - return this._expandRectByRootMargin(rootRect); - }; - IntersectionObserver2.prototype._expandRectByRootMargin = function(rect) { - var margins = this._rootMarginValues.map(function(margin, i2) { - return margin.unit == "px" ? margin.value : margin.value * (i2 % 2 ? rect.width : rect.height) / 100; - }); - var newRect = { - top: rect.top - margins[0], - right: rect.right + margins[1], - bottom: rect.bottom + margins[2], - left: rect.left - margins[3] + } +}; +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); }; - 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) + if (now - last < wait) { + timeout = setTimeout(waitCallback, wait - (now - last)); return; - for (var i2 = 0; i2 < this.thresholds.length; i2++) { - var threshold = this.thresholds[i2]; - if (threshold == oldRatio || threshold == newRatio || threshold < oldRatio !== threshold < newRatio) { - return true; - } } + waitCallback(); }; - IntersectionObserver2.prototype._rootIsInDom = function() { - return !this.root || containsDeep(document2, this.root); + newFn.cancel = function() { + clearTimeout(timeout); + waitCallback = null; }; - IntersectionObserver2.prototype._rootContainsTarget = function(target) { - var rootDoc = this.root && (this.root.ownerDocument || this.root) || document2; - return containsDeep(rootDoc, target) && (!this.root || rootDoc == target.ownerDocument); + newFn.flush = function() { + clearTimeout(timeout); + waitCallback && waitCallback(); }; - IntersectionObserver2.prototype._registerInstance = function() { - if (registry.indexOf(this) < 0) { - registry.push(this); + return newFn; +} +const _sfc_main$9 = { + 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: "" } - }; - 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); - } + }, + data() { + return { + playing: false, + currentTime: this.getTime(0) }; - } - 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); - } - } - 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); + }, + watch: { + src(val) { + if (this.$refs.audio) { + this.$refs.audio.src = this.$getRealPath(val); + } } - } - function computeRectIntersection(rect1, rect2) { - var top = Math.max(rect1.top, rect2.top); - var bottom = Math.min(rect1.bottom, rect2.bottom); - var left = Math.max(rect1.left, rect2.left); - var right = Math.min(rect1.right, rect2.right); - var width = right - left; - var height = bottom - top; - return width >= 0 && height >= 0 && { - top, - bottom, - left, - right, - width, - height - } || null; - } - function getBoundingClientRect(el) { - var rect; - try { - rect = el.getBoundingClientRect(); - } catch (err) { - } - 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 - }; + }, + 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 rect; - } - function getEmptyRect() { - return { - top: 0, - bottom: 0, - left: 0, - right: 0, - width: 0, - height: 0 - }; } - function ensureDOMRect(rect) { - if (!rect || "x" in rect) { - return rect; - } - return { - top: rect.top, - y: rect.top, - bottom: rect.bottom, - left: rect.left, - x: rect.left, - right: rect.right, - width: rect.width, - height: rect.height - }; +}; +const _hoisted_1$6 = {class: "uni-audio-default"}; +const _hoisted_2$3 = {class: "uni-audio-right"}; +const _hoisted_3$2 = {class: "uni-audio-time"}; +const _hoisted_4$2 = {class: "uni-audio-info"}; +const _hoisted_5$1 = {class: "uni-audio-name"}; +const _hoisted_6$1 = {class: "uni-audio-author"}; +function _sfc_render$9(_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$6, [ + 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$3, [ + vue.createVNode("div", _hoisted_3$2, vue.toDisplayString($data.currentTime), 1), + vue.createVNode("div", _hoisted_4$2, [ + vue.createVNode("div", _hoisted_5$1, vue.toDisplayString($props.name), 1), + vue.createVNode("div", _hoisted_6$1, vue.toDisplayString($props.author), 1) + ]) + ]) + ]) + ], 16, ["id", "controls"]); +} +_sfc_main$9.render = _sfc_render$9; +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 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 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 containsDeep(parent, child) { - var node = child; - while (node) { - if (node == parent) - return true; - node = getParentNode(node); + function onTouchstartPassive(evt) { + if (evt._hoverPropagationStopped) { + return; } - return false; - } - function getParentNode(node) { - var parent = node.parentNode; - if (node.nodeType == 9 && node != document2) { - return getFrameElement(node); + if (!props2.hoverClass || props2.hoverClass === "none" || props2.disabled) { + return; } - if (parent && parent.assignedSlot) { - parent = parent.assignedSlot.parentNode; + if (evt.touches.length > 1) { + return; } - if (parent && parent.nodeType == 11 && parent.host) { - return parent.host; + if (props2.hoverStopPropagation) { + evt._hoverPropagationStopped = true; } - return parent; + hoverTouch = true; + hoverStartTimer = setTimeout(() => { + hovering.value = true; + if (!hoverTouch) { + hoverReset(); + } + }, parseInt(props2.hoverStartTime)); } - function isDoc(node) { - return node && node.nodeType === 9; + function onTouchend() { + hoverTouch = false; + if (hovering.value) { + hoverReset(); + } + } + function onTouchcancel() { + hoverTouch = false; + hovering.value = false; + clearTimeout(hoverStartTimer); } - 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, callback2) { - initIntersectionObserverPolyfill(); - const root = options.relativeToSelector ? $el.querySelector(options.relativeToSelector) : null; - const intersectionObserver = new IntersectionObserver((entries2) => { - entries2.forEach((entrie) => { - callback2({ - intersectionRatio: entrie.intersectionRatio, - intersectionRect: normalizeRect(entrie.intersectionRect), - boundingClientRect: normalizeRect(entrie.boundingClientRect), - relativeRect: normalizeRect(entrie.rootBounds), - time: Date.now() - }); - }); - }, { - root, - rootMargin: options.rootMargin, - threshold: options.thresholds - }); - if (options.observeAll) { - intersectionObserver.USE_MUTATION_OBSERVER = true; - const nodeList = $el.querySelectorAll(options.selector); - for (let i2 = 0; i2 < nodeList.length; i2++) { - intersectionObserver.observe(nodeList[i2]); - } - } else { - intersectionObserver.USE_MUTATION_OBSERVER = false; - const el = $el.querySelector(options.selector); - if (!el) { - console.warn(`Node ${options.selector} is not found. Intersection observer will not trigger.`); - } else { - intersectionObserver.observe(el); + hovering, + binding: { + onTouchstartPassive, + onTouchend, + onTouchcancel } - } - return intersectionObserver; -} -const supports = window.CSS && window.CSS.supports; -function cssSupports(css) { - return supports && (supports(css) || supports.apply(window.CSS, css.split(":"))); + }; } -const cssVar = /* @__PURE__ */ cssSupports("--a:0"); -const cssEnv = /* @__PURE__ */ cssSupports("top:env(a)"); -const cssConstant = /* @__PURE__ */ cssSupports("top:constant(a)"); -const cssBackdropFilter = /* @__PURE__ */ cssSupports("backdrop-filter:blur(10px)"); -const SCHEMA_CSS = { - "css.var": cssVar, - "css.env": cssEnv, - "css.constant": cssConstant, - "css.backdrop-filter": cssBackdropFilter -}; -const canIUse = defineSyncApi(API_CAN_I_USE, (schema) => { - if (shared.hasOwn(SCHEMA_CSS, schema)) { - return SCHEMA_CSS[schema]; - } - return true; -}, CanIUseProtocol); -const envMethod = /* @__PURE__ */ (() => cssEnv ? "env" : cssConstant ? "constant" : "")(); -function updateCurPageCssVar(pageMeta) { - let windowTopValue = 0; - let windowBottomValue = 0; - if (__UNI_FEATURE_NAVIGATIONBAR__ && ["default", "float"].indexOf(pageMeta.navigationBar.type) > -1) { - windowTopValue = uniShared.NAVBAR_HEIGHT; - } - if (__UNI_FEATURE_TABBAR__ && pageMeta.isTabBar) { - const tabBar2 = useTabBar(); - tabBar2.shown && (windowBottomValue = parseInt(tabBar2.height)); +function useBooleanAttr(props2, keys) { + if (shared.isString(keys)) { + keys = [keys]; } - updatePageCssVar({ - "--window-top": normalizeWindowBottom(windowTopValue), - "--window-bottom": normalizeWindowBottom(windowBottomValue) - }); -} -function normalizeWindowBottom(windowBottom) { - return envMethod ? `calc(${windowBottom}px + ${envMethod}(safe-area-inset-bottom))` : `${windowBottom}px`; -} -const SEP = "$$"; -const currentPagesMap = new Map(); -function pruneCurrentPages() { - currentPagesMap.forEach((page, id2) => { - if (page.$.isUnmounted) { - currentPagesMap.delete(id2); + return keys.reduce((res, key) => { + if (props2[key]) { + res[key] = true; } - }); -} -function getCurrentPagesMap() { - return currentPagesMap; + return res; + }, Object.create(null)); } -function getCurrentPages$1() { - const curPages = []; - const pages = currentPagesMap.values(); - for (const page of pages) { - if (page.__isTabBar) { - if (page.$.__isActive) { - curPages.push(page); - } - } else { - curPages.push(page); - } +const uniFormKey = PolySymbol(process.env.NODE_ENV !== "production" ? "uniForm" : "uf"); +var index$l = /* @__PURE__ */ vue.defineComponent({ + name: "Form", + setup(_props, { + slots, + emit: emit2 + }) { + provideForm(emit2); + return () => vue.createVNode("uni-form", null, [vue.createVNode("span", null, [slots.default && slots.default()])]); } - return curPages; -} -function removeRouteCache(routeKey) { - const vnode = pageCacheMap.get(routeKey); - if (vnode) { - pageCacheMap.delete(routeKey); - routeCache.pruneCacheEntry(vnode); - } -} -function removePage(routeKey, removeRouteCaches = true) { - const pageVm = currentPagesMap.get(routeKey); - pageVm.$.__isUnload = true; - invokeHook(pageVm, "onUnload"); - currentPagesMap.delete(routeKey); - removeRouteCaches && removeRouteCache(routeKey); -} -let id = /* @__PURE__ */ (() => history.state && history.state.__id__ || 1)(); -function createPageState(type, __id__) { - return { - __id__: __id__ || ++id, - __type__: type - }; -} -function initPublicPage(route) { - const meta = usePageMeta(); - if (!__UNI_FEATURE_PAGES__) { - const {path: path2, alias} = __uniRoutes[0]; - return { - id: meta.id, - path: path2, - route: alias.substr(1), - fullPath: path2, - options: {}, - meta - }; - } - const {path} = route; - return { - id: meta.id, - path, - route: route.meta.route, - fullPath: route.meta.isEntry ? route.meta.pagePath : route.fullPath, - options: {}, - meta - }; -} -function initPage(vm) { - const route = vm.$route; - const page = initPublicPage(route); - vm.$vm = vm; - vm.$page = page; - vm.__isTabBar = page.meta.isTabBar; - currentPagesMap.set(normalizeRouteKey(page.path, page.id), vm); -} -function normalizeRouteKey(path, id2) { - return path + SEP + id2; -} -function useKeepAliveRoute() { - const route = vueRouter.useRoute(); - const routeKey = vue.computed(() => normalizeRouteKey(route.path, history.state.__id__ || 1)); - const isTabBar = vue.computed(() => route.meta.isTabBar); - return { - routeKey, - isTabBar, - routeCache - }; -} -const pageCacheMap = new Map(); -const routeCache = { - get(key) { - return pageCacheMap.get(key); - }, - set(key, value) { - pruneRouteCache(key); - pageCacheMap.set(key, value); - }, - delete(key) { - const vnode = pageCacheMap.get(key); - if (!vnode) { - return; - } - pageCacheMap.delete(key); - }, - forEach(fn) { - pageCacheMap.forEach(fn); - } -}; -function isTabBarVNode(vnode) { - return vnode.props.type === "tabBar"; -} -function pruneRouteCache(key) { - const pageId = parseInt(key.split(SEP)[1]); - if (!pageId) { - return; - } - routeCache.forEach((vnode, key2) => { - const cPageId = parseInt(key2.split(SEP)[1]); - if (cPageId && cPageId > pageId) { - if (__UNI_FEATURE_TABBAR__ && isTabBarVNode(vnode)) { - return; - } - routeCache.delete(key2); - routeCache.pruneCacheEntry(vnode); - vue.nextTick(() => pruneCurrentPages()); - } - }); -} -function onPageShow(instance2, pageMeta) { - updateBodyScopeId(instance2); - updateCurPageCssVar(pageMeta); - initPageScrollListener(instance2, pageMeta); -} -function onPageReady(instance2) { - const scopeId = getScopeId(instance2); - scopeId && updateCurPageBodyScopeId(scopeId); -} -function updateCurPageBodyScopeId(scopeId) { - const pageBodyEl = document.querySelector("uni-page-body"); - if (pageBodyEl) { - pageBodyEl.setAttribute(scopeId, ""); - } else if (process.env.NODE_ENV !== "production") { - console.warn("uni-page-body not found"); - } -} -function getScopeId(instance2) { - return instance2.type.__scopeId; -} -let curScopeId; -function updateBodyScopeId(instance2) { - const scopeId = getScopeId(instance2); - const {body} = document; - curScopeId && body.removeAttribute(curScopeId); - scopeId && body.setAttribute(scopeId, ""); - curScopeId = scopeId; -} -let curScrollListener; -function initPageScrollListener(instance2, pageMeta) { - document.removeEventListener("touchmove", disableScrollListener); - if (curScrollListener) { - document.removeEventListener("scroll", curScrollListener); - } - if (pageMeta.disableScroll) { - return document.addEventListener("touchmove", disableScrollListener); - } - const {onPageScroll, onReachBottom} = instance2; - const navigationBarTransparent = pageMeta.navigationBar.type === "transparent"; - if (!onPageScroll && !onReachBottom && !navigationBarTransparent) { - return; - } - const opts = {}; - const pageId = instance2.proxy.$page.id; - if (onPageScroll || navigationBarTransparent) { - opts.onPageScroll = createOnPageScroll(pageId, onPageScroll, navigationBarTransparent); - } - if (onReachBottom) { - opts.onReachBottomDistance = pageMeta.onReachBottomDistance || uniShared.ON_REACH_BOTTOM_DISTANCE; - opts.onReachBottom = () => UniViewJSBridge.publishHandler("onReachBottom", {}, pageId); - } - curScrollListener = createScrollListener(opts); - requestAnimationFrame(() => document.addEventListener("scroll", curScrollListener)); -} -function createOnPageScroll(pageId, onPageScroll, navigationBarTransparent) { - return (scrollTop) => { - if (onPageScroll) { - UniViewJSBridge.publishHandler("onPageScroll", {scrollTop}, pageId); - } - if (navigationBarTransparent) { - UniViewJSBridge.emit(pageId + ".onPageScroll", { - scrollTop - }); - } - }; -} -function initRouter(app) { - const router = vueRouter.createRouter(createRouterOptions()); - app.router = router; - app.use(router); -} -const scrollBehavior = (_to, _from, savedPosition) => { - if (savedPosition) { - return savedPosition; - } -}; -function createRouterOptions() { - return { - history: initHistory(), - strict: !!__uniConfig.router.strict, - routes: __uniRoutes, - scrollBehavior - }; -} -function removeCurrentPages(delta = 1) { - const keys = getCurrentPages$1(); - const start = keys.length - 1; - const end = start - delta; - for (let i2 = start; i2 > end; i2--) { - const page = keys[i2].$page; - removePage(normalizeRouteKey(page.path, page.id), false); - } -} -function initHistory() { - const history2 = __UNI_FEATURE_ROUTER_MODE__ === "history" ? vueRouter.createWebHistory() : vueRouter.createWebHashHistory(); - history2.listen((_to, _from, info) => { - if (info.direction === "back") { - removeCurrentPages(Math.abs(info.delta)); - } - }); - return history2; -} -var index$m = { - install(app) { - initApp$1(app); - initView(app); - initService(app); - if (__UNI_FEATURE_PAGES__) { - initRouter(app); - } - } -}; -let appVm; -function getApp$1() { - return appVm; -} -function initApp(vm) { - appVm = vm; - appVm.$vm = vm; - appVm.globalData = appVm.$options.globalData || {}; -} -function wrapperComponentSetup(comp, {init: init2, setup, after}) { - const oldSetup = comp.setup; - comp.setup = (props2, ctx) => { - const instance2 = vue.getCurrentInstance(); - init2(instance2.proxy); - const query = setup(instance2); - if (oldSetup) { - return oldSetup(query, ctx); - } - }; - after && after(comp); -} -function setupComponent(comp, options) { - if (comp && (comp.__esModule || comp[Symbol.toStringTag] === "Module")) { - wrapperComponentSetup(comp.default, options); - } else { - wrapperComponentSetup(comp, options); - } - return comp; -} -function setupPage(comp) { - return setupComponent(comp, { - init: initPage, - setup(instance2) { - instance2.__isPage = true; - instance2.root = instance2; - const route = usePageRoute(); - if (route.meta.isTabBar) { - instance2.__isActive = true; - } - const pageMeta = usePageMeta(); - vue.onBeforeMount(() => { - onPageShow(instance2, pageMeta); - const {onLoad, onShow} = instance2; - onLoad && shared.invokeArrayFns(onLoad, uniShared.decodedQuery(route.query)); - instance2.__isVisible = true; - onShow && shared.invokeArrayFns(onShow); - }); - vue.onMounted(() => { - onPageReady(instance2); - const {onReady} = instance2; - onReady && shared.invokeArrayFns(onReady); - }); - vue.onBeforeActivate(() => { - if (!instance2.__isVisible) { - onPageShow(instance2, pageMeta); - instance2.__isVisible = true; - const {onShow} = instance2; - onShow && shared.invokeArrayFns(onShow); - } - }); - vue.onBeforeDeactivate(() => { - if (instance2.__isVisible && !instance2.__isUnload) { - instance2.__isVisible = false; - const {onHide} = instance2; - onHide && shared.invokeArrayFns(onHide); +}); +function provideForm(emit2) { + const fields = []; + vue.provide(uniFormKey, { + addField(field) { + fields.push(field); + }, + removeField(field) { + fields.splice(fields.indexOf(field), 1); + }, + submit() { + emit2("submit", { + detail: { + value: fields.reduce((res, field) => { + if (field.submit) { + const [name, value] = field.submit(); + name && (res[name] = value); + } + return res; + }, Object.create(null)) } }); - return route.query; - } - }); -} -function setupApp(comp) { - return setupComponent(comp, { - init: initApp, - setup(instance2) { - const route = usePageRoute(); - const onLaunch = () => { - const {onLaunch: onLaunch2, onShow} = instance2; - const path = route.path.substr(1); - const launchOptions = { - path: path || __uniRoutes[0].meta.route, - query: uniShared.decodedQuery(route.query), - scene: 1001 - }; - onLaunch2 && shared.invokeArrayFns(onLaunch2, launchOptions); - onShow && shared.invokeArrayFns(onShow, launchOptions); - }; - if (__UNI_FEATURE_PAGES__) { - vueRouter.useRouter().isReady().then(onLaunch); - } else { - vue.onBeforeMount(onLaunch); - } - vue.onMounted(() => { - document.addEventListener("visibilitychange", function() { - if (document.visibilityState === "visible") { - UniServiceJSBridge.emit("onAppEnterForeground"); - } else { - UniServiceJSBridge.emit("onAppEnterBackground"); - } - }); - }); - return route.query; }, - after(comp2) { - comp2.mpType = "app"; - comp2.render = () => (vue.openBlock(), vue.createBlock(LayoutComponent)); + reset() { + fields.forEach((field) => field.reset && field.reset()); + emit2("reset"); } }); + return fields; } -var hover = { - data() { - return { - hovering: false - }; - }, +var index$k = /* @__PURE__ */ vue.defineComponent({ + name: "Button", props: { - hoverClass: { + id: { type: String, - default: "none" + default: "" }, - hoverStopPropagation: { - type: Boolean, - default: false + hoverClass: { + type: String, + default: "button-hover" }, hoverStartTime: { type: [Number, String], - default: 50 + default: 20 }, hoverStayTime: { type: [Number, String], - default: 400 + default: 70 + }, + hoverStopPropagation: { + type: Boolean, + default: false + }, + disabled: { + type: [Boolean, String], + default: false + }, + formType: { + type: String, + default: "" + }, + openType: { + type: String, + default: "" } }, - methods: { - _hoverTouchStart(evt) { - if (evt._hoverPropagationStopped) { - return; - } - if (!this.hoverClass || this.hoverClass === "none" || this.disabled) { - return; - } - if (evt.touches.length > 1) { - return; - } - if (this.hoverStopPropagation) { - evt._hoverPropagationStopped = true; - } - this._hoverTouch = true; - this._hoverStartTimer = setTimeout(() => { - this.hovering = true; - if (!this._hoverTouch) { - this._hoverReset(); - } - }, this.hoverStartTime); - }, - _hoverTouchEnd(evt) { - this._hoverTouch = false; - if (this.hovering) { - this._hoverReset(); - } - }, - _hoverReset() { - requestAnimationFrame(() => { - clearTimeout(this._hoverStayTimer); - this._hoverStayTimer = setTimeout(() => { - this.hovering = false; - }, this.hoverStayTime); - }); - }, - _hoverTouchCancel(evt) { - this._hoverTouch = false; - this.hovering = false; - clearTimeout(this._hoverStartTimer); - } - } -}; -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, watch) { - if (watch && !id2) { + setup(props2, { + slots + }) { + const uniForm = vue.inject(uniFormKey, false); + const { + hovering, + binding + } = useHover(props2); + useI18n(); + function onClick() { + if (props2.disabled) { return; } - if (!shared.isFunction(this._handleSubscribe)) { + const formType = props2.formType; + if (formType) { + if (!uniForm) { + return; + } + if (formType === "submit") { + uniForm.submit(); + } else if (formType === "reset") { + uniForm.reset(); + } return; } - UniViewJSBridge[type](this.$page.id + "-" + this.$options.name.replace(/VUni([A-Z])/, "$1").toLowerCase() + "-" + id2, this._handleSubscribe); - }, - _getContextInfo() { - const id2 = `context-${this._uid}`; - if (!this._contextId) { - this._toggleListeners("subscribe", id2); - this._contextId = id2; - } - return { - name: this.$options.name.replace(/VUni([A-Z])/, "$1").toLowerCase(), - id: id2, - page: this.$page.id - }; } + return () => { + const hoverClass = props2.hoverClass; + const booleanAttrs = useBooleanAttr(props2, "disabled"); + if (hoverClass && hoverClass !== "none") { + return vue.createVNode("uni-button", vue.mergeProps({ + onClick, + class: hovering.value ? hoverClass : "" + }, binding, booleanAttrs), [slots.default && slots.default()], 16, ["onClick"]); + } + return vue.createVNode("uni-button", vue.mergeProps({ + onClick + }, booleanAttrs), [slots.default && slots.default()], 16, ["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); +}); +const pixelRatio = 1; +function wrapper(canvas) { + canvas.width = canvas.offsetWidth * pixelRatio; + canvas.height = canvas.offsetHeight * pixelRatio; + canvas.getContext("2d").__hidpi__ = true; +} +function resolveColor(color) { + color = color.slice(0); + color[3] = color[3] / 255; + return "rgba(" + color.join(",") + ")"; +} +function processTouches(target, touches) { + return [].map.call(touches, (touch) => { + var boundingClientRect = target.getBoundingClientRect(); + return { + identifier: touch.identifier, + x: touch.clientX - boundingClientRect.left, + y: touch.clientY - boundingClientRect.top }; - if (now - last < wait) { - timeout = setTimeout(waitCallback, wait - (now - last)); - return; - } - waitCallback(); - }; - newFn.cancel = function() { - clearTimeout(timeout); - waitCallback = null; - }; - newFn.flush = function() { - clearTimeout(timeout); - waitCallback && waitCallback(); - }; - return newFn; + }); } -const _sfc_main$9 = { - name: "Audio", +var tempCanvas; +function getTempCanvas(width = 0, height = 0) { + if (!tempCanvas) { + tempCanvas = document.createElement("canvas"); + } + tempCanvas.width = width; + tempCanvas.height = height; + return tempCanvas; +} +const _sfc_main$8 = { + name: "Canvas", mixins: [subscriber], props: { - id: { - type: String, - default: "" - }, - src: { + canvasId: { type: String, default: "" }, - loop: { - type: [Boolean, String], - default: false - }, - controls: { + disableScroll: { 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) + actionsWaiting: false }; }, - watch: { - src(val) { - if (this.$refs.audio) { - this.$refs.audio.src = this.$getRealPath(val); - } + computed: { + id() { + return this.canvasId; + }, + _listeners() { + var $listeners = Object.assign({}, this.$listeners); + var events = ["touchstart", "touchmove", "touchend"]; + events.forEach((event) => { + var existing = $listeners[event]; + var eventHandler = []; + if (existing) { + eventHandler.push(($event) => { + this.$trigger(event, Object.assign({}, $event, { + touches: processTouches($event.currentTarget, $event.touches), + changedTouches: processTouches($event.currentTarget, $event.changedTouches) + })); + }); + } + if (this.disableScroll && event === "touchmove") { + eventHandler.push(this._touchmove); + } + $listeners[event] = eventHandler; + }); + return $listeners; } }, + created() { + this._actionsDefer = []; + this._images = {}; + }, 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 - }); + this._resize({ + width: this.$refs.sensor.$el.offsetWidth, + height: this.$refs.sensor.$el.offsetHeight }); - audio.src = this.$getRealPath(this.src); + }, + beforeDestroy() { + const canvas = this.$refs.canvas; + canvas.height = canvas.width = 0; }, 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; + var method = this[type]; + if (type.indexOf("_") !== 0 && typeof method === "function") { + method(data); } }, - trigger() { - if (this.playing) { - this.$refs.audio.pause(); + _resize() { + var canvas = this.$refs.canvas; + if (canvas.width > 0 && canvas.height > 0) { + var context = canvas.getContext("2d"); + var imageData = context.getImageData(0, 0, canvas.width, canvas.height); + wrapper(this.$refs.canvas); + context.putImageData(imageData, 0, 0); } else { - this.$refs.audio.play(); - } - }, - getTime(time) { - var h = Math.floor(time / 3600); - var m = Math.floor(time % 3600 / 60); - var s = Math.floor(time % 3600 % 60); - h = (h < 10 ? "0" : "") + h; - m = (m < 10 ? "0" : "") + m; - s = (s < 10 ? "0" : "") + s; - var str = m + ":" + s; - if (h !== "00") { - str = h + ":" + str; - } - return str; - } - } -}; -const _hoisted_1$6 = {class: "uni-audio-default"}; -const _hoisted_2$3 = {class: "uni-audio-right"}; -const _hoisted_3$2 = {class: "uni-audio-time"}; -const _hoisted_4$2 = {class: "uni-audio-info"}; -const _hoisted_5$1 = {class: "uni-audio-name"}; -const _hoisted_6$1 = {class: "uni-audio-author"}; -function _sfc_render$9(_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$6, [ - 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$3, [ - vue.createVNode("div", _hoisted_3$2, vue.toDisplayString($data.currentTime), 1), - vue.createVNode("div", _hoisted_4$2, [ - vue.createVNode("div", _hoisted_5$1, vue.toDisplayString($props.name), 1), - vue.createVNode("div", _hoisted_6$1, vue.toDisplayString($props.author), 1) - ]) - ]) - ]) - ], 16, ["id", "controls"]); -} -_sfc_main$9.render = _sfc_render$9; -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 = vue.ref(false); - let hoverTouch = false; - let hoverStartTimer; - let hoverStayTimer; - function hoverReset() { - requestAnimationFrame(() => { - clearTimeout(hoverStayTimer); - hoverStayTimer = setTimeout(() => { - hovering.value = false; - }, parseInt(props2.hoverStayTime)); - }); - } - function onTouchstartPassive(evt) { - if (evt._hoverPropagationStopped) { - return; - } - if (!props2.hoverClass || props2.hoverClass === "none" || props2.disabled) { - return; - } - if (evt.touches.length > 1) { - return; - } - if (props2.hoverStopPropagation) { - evt._hoverPropagationStopped = true; - } - hoverTouch = true; - hoverStartTimer = setTimeout(() => { - hovering.value = true; - if (!hoverTouch) { - hoverReset(); + wrapper(this.$refs.canvas); } - }, parseInt(props2.hoverStartTime)); - } - function onTouchend() { - hoverTouch = false; - if (hovering.value) { - hoverReset(); - } - } - function onTouchcancel() { - hoverTouch = false; - hovering.value = false; - clearTimeout(hoverStartTimer); - } - return { - hovering, - binding: { - onTouchstartPassive, - onTouchend, - onTouchcancel - } - }; -} -function useBooleanAttr(props2, keys) { - if (shared.isString(keys)) { - keys = [keys]; - } - return keys.reduce((res, key) => { - if (props2[key]) { - res[key] = true; - } - return res; - }, Object.create(null)); -} -const uniFormKey = PolySymbol(process.env.NODE_ENV !== "production" ? "uniForm" : "uf"); -var index$l = /* @__PURE__ */ vue.defineComponent({ - name: "Form", - setup(_props, { - slots, - emit: emit2 - }) { - provideForm(emit2); - return () => vue.createVNode("uni-form", null, [vue.createVNode("span", null, [slots.default && slots.default()])]); - } -}); -function provideForm(emit2) { - const fields = []; - vue.provide(uniFormKey, { - addField(field) { - fields.push(field); - }, - removeField(field) { - fields.splice(fields.indexOf(field), 1); - }, - submit() { - emit2("submit", { - detail: { - value: fields.reduce((res, field) => { - if (field.submit) { - const [name, value] = field.submit(); - name && (res[name] = value); - } - return res; - }, Object.create(null)) - } - }); - }, - reset() { - fields.forEach((field) => field.reset && field.reset()); - emit2("reset"); - } - }); - return fields; -} -var index$k = /* @__PURE__ */ vue.defineComponent({ - name: "Button", - props: { - id: { - type: String, - default: "" - }, - hoverClass: { - type: String, - default: "button-hover" - }, - hoverStartTime: { - type: [Number, String], - default: 20 - }, - hoverStayTime: { - type: [Number, String], - default: 70 - }, - hoverStopPropagation: { - type: Boolean, - default: false - }, - disabled: { - type: [Boolean, String], - default: false }, - formType: { - type: String, - default: "" + _touchmove(event) { + event.preventDefault(); }, - openType: { - type: String, - default: "" - } - }, - setup(props2, { - slots - }) { - const uniForm = vue.inject(uniFormKey, false); - const { - hovering, - binding - } = useHover(props2); - useI18n(); - function onClick() { - if (props2.disabled) { - return; - } - const formType = props2.formType; - if (formType) { - if (!uniForm) { - return; - } - if (formType === "submit") { - uniForm.submit(); - } else if (formType === "reset") { - uniForm.reset(); - } - return; - } - } - return () => { - const hoverClass = props2.hoverClass; - const booleanAttrs = useBooleanAttr(props2, "disabled"); - if (hoverClass && hoverClass !== "none") { - return vue.createVNode("uni-button", vue.mergeProps({ - onClick, - class: hovering.value ? hoverClass : "" - }, binding, booleanAttrs), [slots.default && slots.default()], 16, ["onClick"]); - } - return vue.createVNode("uni-button", vue.mergeProps({ - onClick - }, booleanAttrs), [slots.default && slots.default()], 16, ["onClick"]); - }; - } -}); -const pixelRatio = /* @__PURE__ */ function() { - const canvas = document.createElement("canvas"); - canvas.height = canvas.width = 0; - const context = canvas.getContext("2d"); - const backingStore = context.backingStorePixelRatio || context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1; - return (window.devicePixelRatio || 1) / backingStore; -}(); -function wrapper(canvas) { - canvas.width = canvas.offsetWidth * pixelRatio; - canvas.height = canvas.offsetHeight * pixelRatio; - canvas.getContext("2d").__hidpi__ = true; -} -function resolveColor(color) { - color = color.slice(0); - color[3] = color[3] / 255; - return "rgba(" + color.join(",") + ")"; -} -function processTouches(target, touches) { - return [].map.call(touches, (touch) => { - var boundingClientRect = target.getBoundingClientRect(); - return { - identifier: touch.identifier, - x: touch.clientX - boundingClientRect.left, - y: touch.clientY - boundingClientRect.top - }; - }); -} -var tempCanvas; -function getTempCanvas(width = 0, height = 0) { - if (!tempCanvas) { - tempCanvas = document.createElement("canvas"); - } - tempCanvas.width = width; - tempCanvas.height = height; - return tempCanvas; -} -const _sfc_main$8 = { - name: "Canvas", - mixins: [subscriber], - props: { - canvasId: { - type: String, - default: "" - }, - disableScroll: { - type: [Boolean, String], - default: false - } - }, - data() { - return { - actionsWaiting: false - }; - }, - computed: { - id() { - return this.canvasId; - }, - _listeners() { - var $listeners = Object.assign({}, this.$listeners); - var events = ["touchstart", "touchmove", "touchend"]; - events.forEach((event) => { - var existing = $listeners[event]; - var eventHandler = []; - if (existing) { - eventHandler.push(($event) => { - this.$trigger(event, Object.assign({}, $event, { - touches: processTouches($event.currentTarget, $event.touches), - changedTouches: processTouches($event.currentTarget, $event.changedTouches) - })); - }); - } - if (this.disableScroll && event === "touchmove") { - eventHandler.push(this._touchmove); - } - $listeners[event] = eventHandler; - }); - return $listeners; - } - }, - created() { - this._actionsDefer = []; - this._images = {}; - }, - mounted() { - this._resize({ - width: this.$refs.sensor.$el.offsetWidth, - height: this.$refs.sensor.$el.offsetHeight - }); - }, - beforeDestroy() { - const canvas = this.$refs.canvas; - canvas.height = canvas.width = 0; - }, - methods: { - _handleSubscribe({ - type, - data = {} - }) { - var method = this[type]; - if (type.indexOf("_") !== 0 && typeof method === "function") { - method(data); - } - }, - _resize() { - var canvas = this.$refs.canvas; - if (canvas.width > 0 && canvas.height > 0) { - var context = canvas.getContext("2d"); - var imageData = context.getImageData(0, 0, canvas.width, canvas.height); - wrapper(this.$refs.canvas); - context.putImageData(imageData, 0, 0); - } else { - wrapper(this.$refs.canvas); - } - }, - _touchmove(event) { - event.preventDefault(); - }, - actionsChanged({ - actions, - reserve, - callbackId - }) { - var self = this; - if (!actions) { + actionsChanged({ + actions, + reserve, + callbackId + }) { + var self = this; + if (!actions) { return; } if (this.actionsWaiting) { @@ -4777,60 +2037,6 @@ function _sfc_render$8(_ctx, _cache, $props, $setup, $data, $options) { ], 16, ["canvas-id", "disable-scroll"]); } _sfc_main$8.render = _sfc_render$8; -function useListeners(props2, listeners) { - _addListeners(props2.id, listeners); - vue.watch(() => props2.id, (newId, oldId) => { - _removeListeners(oldId, listeners, true); - _addListeners(newId, listeners, true); - }); - vue.onUnmounted(() => { - _removeListeners(props2.id, listeners); - }); -} -function _addListeners(id2, listeners, watch2) { - const pageId = useCurrentPageId(); - if (watch2 && !id2) { - return; - } - if (!shared.isPlainObject(listeners)) { - return; - } - Object.keys(listeners).forEach((name) => { - if (watch2) { - if (name.indexOf("@") !== 0 && name.indexOf("uni-") !== 0) { - UniViewJSBridge.on(`uni-${name}-${pageId}-${id2}`, listeners[name]); - } - } else { - if (name.indexOf("uni-") === 0) { - UniViewJSBridge.on(name, listeners[name]); - } else if (id2) { - UniViewJSBridge.on(`uni-${name}-${pageId}-${id2}`, listeners[name]); - } - } - }); -} -function _removeListeners(id2, listeners, watch2) { - const pageId = useCurrentPageId(); - if (watch2 && !id2) { - return; - } - if (!shared.isPlainObject(listeners)) { - return; - } - 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]); - } - } - }); -} function withWebEvent(fn) { return fn.__wwe = true, fn; } @@ -4850,7 +2056,7 @@ function normalizeCustomEvent(name, domEvt, el, detail) { }; } const uniCheckGroupKey = PolySymbol(process.env.NODE_ENV !== "production" ? "uniCheckGroup" : "ucg"); -const props$m = { +const props$k = { name: { type: String, default: "" @@ -4858,7 +2064,7 @@ const props$m = { }; var index$j = /* @__PURE__ */ vue.defineComponent({ name: "CheckboxGroup", - props: props$m, + props: props$k, emits: ["change"], setup(props2, { emit: emit2, @@ -4911,7 +2117,7 @@ function useProvideCheckGroup(props2, trigger) { return getFieldsValue; } const uniLabelKey = PolySymbol(process.env.NODE_ENV !== "production" ? "uniLabel" : "ul"); -const props$l = { +const props$j = { for: { type: String, default: "" @@ -4919,7 +2125,7 @@ const props$l = { }; var index$i = /* @__PURE__ */ vue.defineComponent({ name: "Label", - props: props$l, + props: props$j, setup(props2, { emit: emit2, slots @@ -4964,7 +2170,7 @@ function useProvideLabel() { }); return handlers; } -const props$k = { +const props$i = { checked: { type: [Boolean, String], default: false @@ -4988,7 +2194,7 @@ const props$k = { }; var index$h = /* @__PURE__ */ vue.defineComponent({ name: "Checkbox", - props: props$k, + props: props$i, setup(props2, { slots }) { @@ -5018,9 +2224,6 @@ var index$h = /* @__PURE__ */ vue.defineComponent({ uniLabel.removeHandler(_onClick); }); } - useListeners(props2, { - "label-click": _onClick - }); return () => { const { booleanAttrs @@ -5067,7 +2270,7 @@ function useCheckboxInject(checkboxChecked, checkboxValue, reset) { let resetTimer; function iosHideKeyboard() { } -const props$j = { +const props$h = { cursorSpacing: { type: [Number, String], default: 0 @@ -5086,7 +2289,7 @@ const props$j = { } }; const emit$1 = ["keyboardheightchange"]; -function useKeyboard$1(props2, elRef, trigger) { +function useKeyboard(props2, elRef, trigger) { function initKeyboard(el) { el.addEventListener("focus", () => { clearTimeout(resetTimer); @@ -5115,7 +2318,7 @@ var fillAttrs = /* @__PURE__ */ makeMap("checked,compact,declare,defer,disabled, var special = /* @__PURE__ */ makeMap("script,style"); function HTMLParser(html, handler) { var index2; - var chars2; + var chars; var match; var stack = []; var last = html; @@ -5123,7 +2326,7 @@ function HTMLParser(html, handler) { return this[this.length - 1]; }; while (html) { - chars2 = true; + chars = true; if (!stack.last() || !special[stack.last()]) { if (html.indexOf(""); @@ -5132,24 +2335,24 @@ function HTMLParser(html, handler) { handler.comment(html.substring(4, index2)); } html = html.substring(index2 + 3); - chars2 = false; + chars = false; } } else if (html.indexOf(" `${name}="${value}"`).join(" "); @@ -5811,7 +3014,7 @@ function useQuill(props2, rootRef, trigger) { } }); } -const props$i = /* @__PURE__ */ Object.assign({}, props$j, { +const props$g = /* @__PURE__ */ Object.assign({}, props$h, { id: { type: String, default: "" @@ -5839,7 +3042,7 @@ const props$i = /* @__PURE__ */ Object.assign({}, props$j, { }); var index$g = /* @__PURE__ */ vue.defineComponent({ name: "Editor", - props: props$i, + props: props$g, emit: ["ready", "focus", "blur", "input", "statuschange", ...emit$1], setup(props2, { emit: emit2 @@ -5847,7 +3050,7 @@ var index$g = /* @__PURE__ */ vue.defineComponent({ const rootRef = vue.ref(null); const trigger = useCustomEvent(rootRef, emit2); useQuill(props2, rootRef, trigger); - useKeyboard$1(props2, rootRef); + useKeyboard(props2, rootRef); return () => { return vue.createVNode("uni-editor", { ref: rootRef, @@ -5990,7 +3193,7 @@ function useResizeSensorLifecycle(rootRef, props2, update, reset) { } }); } -const props$h = { +const props$f = { src: { type: String, default: "" @@ -6029,7 +3232,7 @@ const IMAGE_MODES = { }; var index$e = /* @__PURE__ */ vue.defineComponent({ name: "Image", - props: props$h, + props: props$f, setup(props2, { emit: emit2 }) { @@ -6055,12 +3258,12 @@ var index$e = /* @__PURE__ */ vue.defineComponent({ ref: rootRef }, [vue.createVNode("div", { style: modeStyle - }, null, 4), imgSrc && vue.createVNode("img", { + }, null, 4), imgSrc ? vue.createVNode("img", { src: imgSrc, draggable: props2.draggable - }, null, 8, ["src", "draggable"]), FIX_MODES[mode] && vue.createVNode(ResizeSensor, { + }, null, 8, ["src", "draggable"]) : vue.createVNode("img", null, null), FIX_MODES[mode] ? vue.createVNode(ResizeSensor, { onResize: fixSize - }, null, 8, ["onResize"])], 512); + }, null, 8, ["onResize"]) : vue.createVNode("span", null, null)], 512); }; } }); @@ -6094,9 +3297,9 @@ function useImageState(rootRef, props2) { }); vue.onMounted(() => { const rootEl = rootRef.value; - const style2 = rootEl.style; - state.origWidth = Number(style2.width) || 0; - state.origHeight = Number(style2.height) || 0; + const style = rootEl.style; + state.origWidth = Number(style.width) || 0; + state.origHeight = Number(style.height) || 0; }); return state; } @@ -6152,11 +3355,7 @@ function useImageLoader(state, { vue.onMounted(() => loadImage(state.src)); vue.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, state) { @@ -6185,7 +3384,7 @@ function useImageSize(rootRef, props2, state) { }; const resetSize = () => { const { - style: style2 + style } = rootRef.value; const { origStyle: { @@ -6193,8 +3392,8 @@ function useImageSize(rootRef, props2, state) { height } } = state; - style2.width = width; - style2.height = height; + style.width = width; + style.height = height; }; vue.watch(() => props2.mode, (value, oldValue) => { if (FIX_MODES[oldValue]) { @@ -6265,13 +3464,13 @@ function useScopedAttrs() { attrs: {} }); vue.onMounted(() => { - let instance2 = vue.getCurrentInstance(); - while (instance2) { - const scopeId = instance2.type.__scopeId; + let instance = vue.getCurrentInstance(); + while (instance) { + const scopeId = instance.type.__scopeId; if (scopeId) { state.attrs[scopeId] = ""; } - instance2 = instance2.__isPage ? null : instance2.parent; + instance = instance.__isPage ? null : instance.parent; } }); return { @@ -6283,10 +3482,10 @@ function useFormField(nameKey, value) { if (!uniForm) { return; } - const instance2 = vue.getCurrentInstance(); + const instance = vue.getCurrentInstance(); const ctx = { submit() { - const proxy = instance2.proxy; + const proxy = instance.proxy; return [ proxy[nameKey], typeof value === "string" ? proxy[value] : value.value @@ -6294,7 +3493,7 @@ function useFormField(nameKey, value) { }, reset() { if (typeof value === "string") { - instance2.proxy[value] = ""; + instance.proxy[value] = ""; } else { value.value = ""; } @@ -6308,7 +3507,7 @@ function useFormField(nameKey, value) { function getValueString(value) { return value === null ? "" : String(value); } -const props$g = /* @__PURE__ */ Object.assign({}, { +const props$e = /* @__PURE__ */ Object.assign({}, { name: { type: String, default: "" @@ -6369,7 +3568,7 @@ const props$g = /* @__PURE__ */ Object.assign({}, { type: String, default: "done" } -}, props$j); +}, props$h); const emit = ["input", "focus", "blur", ...emit$1]; function useBase(props2, rootRef, emit2) { const fieldRef = vue.ref(null); @@ -6541,11 +3740,11 @@ function useField(props2, rootRef, emit2, beforeInput) { const {fieldRef, state, trigger} = useBase(props2, rootRef, emit2); const {triggerInput} = useValueSync(props2, state, emit2, trigger); useAutoFocus(props2, fieldRef); - useKeyboard$1(props2, fieldRef); + useKeyboard(props2, fieldRef); const {state: scopedAttrsState} = useScopedAttrs(); useFormField("name", state); useEvent(fieldRef, state, trigger, triggerInput, beforeInput); - const fixDisabledColor = String(navigator.vendor).indexOf("Apple") === 0 && CSS.supports("image-orientation:from-image"); + const fixDisabledColor = false; return { fieldRef, state, @@ -6554,7 +3753,7 @@ function useField(props2, rootRef, emit2, beforeInput) { trigger }; } -const props$f = /* @__PURE__ */ Object.assign({}, props$g, { +const props$d = /* @__PURE__ */ Object.assign({}, props$e, { placeholderClass: { type: String, default: "input-placeholder" @@ -6562,7 +3761,7 @@ const props$f = /* @__PURE__ */ Object.assign({}, props$g, { }); var Input = /* @__PURE__ */ vue.defineComponent({ name: "Input", - props: props$f, + props: props$d, emit: ["confirm", ...emit], setup(props2, { emit: emit2 @@ -7788,7 +4987,7 @@ const VALUES = { backgroundColor: "#EBEBEB", activeMode: "backwards" }; -const props$e = { +const props$c = { percent: { type: [Number, String], default: 0, @@ -7837,7 +5036,7 @@ const props$e = { }; var index$d = /* @__PURE__ */ vue.defineComponent({ name: "Progress", - props: props$e, + props: props$c, setup(props2) { const state = useProgressState(props2); _activeAnimation(state, props2); @@ -7865,7 +5064,7 @@ var index$d = /* @__PURE__ */ vue.defineComponent({ class: "uni-progress-inner-bar" }, null, 4)], 4), showInfo ? vue.createVNode("p", { class: "uni-progress-info" - }, [currentPercent, vue.createTextVNode("%")]) : ""]); + }, [currentPercent + "%"]) : ""]); }; } }); @@ -7908,7 +5107,7 @@ function _activeAnimation(state, props2) { } } const uniRadioGroupKey = PolySymbol(process.env.NODE_ENV !== "production" ? "uniCheckGroup" : "ucg"); -const props$d = { +const props$b = { name: { type: String, default: "" @@ -7916,7 +5115,7 @@ const props$d = { }; var index$c = /* @__PURE__ */ vue.defineComponent({ name: "RadioGroup", - props: props$d, + props: props$b, setup(props2, { emit: emit2, slots @@ -7995,7 +5194,7 @@ function useProvideRadioGroup(props2, trigger) { } return fields; } -const props$c = { +const props$a = { checked: { type: [Boolean, String], default: false @@ -8019,7 +5218,7 @@ const props$c = { }; var index$b = /* @__PURE__ */ vue.defineComponent({ name: "Radio", - props: props$c, + props: props$a, setup(props2, { slots }) { @@ -8051,9 +5250,6 @@ var index$b = /* @__PURE__ */ vue.defineComponent({ uniLabel.removeHandler(_onClick); }); } - useListeners(props2, { - "label-click": _onClick - }); return () => { const { booleanAttrs @@ -8109,8 +5305,8 @@ function useRadioInject(radioChecked, radioValue, reset) { function removeDOCTYPE(html) { return html.replace(/<\?xml.*\?>\n/, "").replace(/\n/, "").replace(/\n/, ""); } -function parseAttrs(attrs2) { - return attrs2.reduce(function(pre, attr2) { +function parseAttrs(attrs) { + return attrs.reduce(function(pre, attr2) { let value = attr2.value; const name = attr2.name; if (value.match(/ /) && name !== "style") { @@ -8136,12 +5332,12 @@ function parseHtml(html) { children: [] }; HTMLParser(html, { - start: function(tag, attrs2, unary) { + start: function(tag, attrs, unary) { const node = { name: tag }; - if (attrs2.length !== 0) { - node.attrs = parseAttrs(attrs2); + if (attrs.length !== 0) { + node.attrs = parseAttrs(attrs); } if (unary) { const parent = stacks[0] || results; @@ -8282,11 +5478,11 @@ function parseNodes(nodes, parentNode) { if (!elem) { return; } - const attrs2 = node.attrs; - if (shared.isPlainObject(attrs2)) { + const attrs = node.attrs; + if (shared.isPlainObject(attrs)) { const tagAttrs = TAGS[tagName] || []; - Object.keys(attrs2).forEach(function(name) { - let value = attrs2[name]; + Object.keys(attrs).forEach(function(name) { + let value = attrs[name]; switch (name) { case "class": Array.isArray(value) && (value = value.join(" ")); @@ -8989,7 +6185,7 @@ var scroller = { event.preventDefault(); var delta = this._findDelta(event); if (delta) { - var listener2 = touchInfo.listener; + var listener = touchInfo.listener; touchInfo.trackingID = -1; touchInfo.listener = null; var r = touchInfo.historyTime.length; @@ -9012,8 +6208,8 @@ var scroller = { touchInfo.historyTime = []; touchInfo.historyX = []; touchInfo.historyY = []; - if (listener2 && listener2.onTouchEnd) { - listener2.onTouchEnd(delta.x, delta.y, o2); + if (listener && listener.onTouchEnd) { + listener.onTouchEnd(delta.x, delta.y, o2); } } } @@ -9659,7 +6855,7 @@ function useTouchtrack(element, method, useCancel) { } }); } -const props$b = { +const props$9 = { name: { type: String, default: "" @@ -9715,7 +6911,7 @@ const props$b = { }; var index$a = /* @__PURE__ */ vue.defineComponent({ name: "Slider", - props: props$b, + props: props$9, emits: ["changing", "change"], setup(props2, { emit: emit2 @@ -9907,7 +7103,7 @@ function _sfc_render$3(_ctx, _cache, $props, $setup, $data, $options) { ], 16); } _sfc_main$3.render = _sfc_render$3; -const props$a = { +const props$8 = { name: { type: String, default: "" @@ -9935,7 +7131,7 @@ const props$a = { }; var index$9 = /* @__PURE__ */ vue.defineComponent({ name: "Switch", - props: props$a, + props: props$8, emits: ["change"], setup(props2, { emit: emit2 @@ -9962,9 +7158,6 @@ var index$9 = /* @__PURE__ */ vue.defineComponent({ uniLabel.removeHandler(_onClick); }); } - useListeners(props2, { - "label-click": _onClick - }); return () => { const { color, @@ -10022,12 +7215,12 @@ const SPACE_UNICODE = { }; function normalizeText(text2, { space, - decode: decode2 + decode }) { if (space && SPACE_UNICODE[space]) { text2 = text2.replace(/ /g, SPACE_UNICODE[space]); } - if (!decode2) { + if (!decode) { 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, "'"); @@ -10081,7 +7274,7 @@ var index$8 = /* @__PURE__ */ vue.defineComponent({ }; } }); -const props$9 = /* @__PURE__ */ Object.assign({}, props$g, { +const props$7 = /* @__PURE__ */ Object.assign({}, props$e, { placeholderClass: { type: String, default: "input-placeholder" @@ -10097,7 +7290,7 @@ const props$9 = /* @__PURE__ */ Object.assign({}, props$g, { }); var index$7 = /* @__PURE__ */ vue.defineComponent({ name: "Textarea", - props: props$9, + props: props$7, emit: ["confirm", "linechange", ...emit], setup(props2, { emit: emit2 @@ -10236,14 +7429,14 @@ var index$6 = /* @__PURE__ */ vue.defineComponent({ }; } }); -function normalizeEvent(pageId, vm, id2) { - if (!id2) { - id2 = vm.id; +function normalizeEvent(pageId, vm, id) { + if (!id) { + id = vm.id; } - if (!id2) { + if (!id) { return; } - return pageId + "." + vm.$options.name.toLowerCase() + "." + id2; + return pageId + "." + vm.$options.name.toLowerCase() + "." + id; } function addSubscribe(name, callback2) { if (!name) { @@ -10260,13 +7453,13 @@ function removeSubscribe(name) { UniViewJSBridge.unsubscribe(name); } function useSubscribe(callback2, name) { - const instance2 = vue.getCurrentInstance(); - const vm = instance2.proxy; + const instance = vue.getCurrentInstance(); + const vm = instance.proxy; const pageId = name ? 0 : useCurrentPageId(); vue.onMounted(() => { addSubscribe(name || normalizeEvent(pageId, vm), callback2); if (!name) { - vue.watch(() => instance2.id, (value, oldValue) => { + vue.watch(() => instance.id, (value, oldValue) => { addSubscribe(normalizeEvent(pageId, vm, value), callback2); removeSubscribe(normalizeEvent(pageId, vm, oldValue)); }); @@ -10287,14 +7480,14 @@ const DEFAULT_EXCLUDE_KEYS = ["class", "style"]; const LISTENER_PREFIX = /^on[A-Z]+/; const useAttrs = (params = {}) => { const {excludeListeners = false, excludeKeys = []} = params; - const instance2 = vue.getCurrentInstance(); - const attrs2 = vue.shallowRef({}); + const instance = vue.getCurrentInstance(); + const attrs = vue.shallowRef({}); const listeners = vue.shallowRef({}); const excludeAttrs = vue.shallowRef({}); const allExcludeKeys = excludeKeys.concat(DEFAULT_EXCLUDE_KEYS); - instance2.attrs = vue.reactive(instance2.attrs); + instance.attrs = vue.reactive(instance.attrs); vue.watchEffect(() => { - const res = entries(instance2.attrs).reduce((acc, [key, val]) => { + const res = entries(instance.attrs).reduce((acc, [key, val]) => { if (allExcludeKeys.includes(key)) { acc.exclude[key] = val; } else if (LISTENER_PREFIX.test(key)) { @@ -10311,11 +7504,11 @@ const useAttrs = (params = {}) => { attrs: {}, listeners: {} }); - attrs2.value = res.attrs; + attrs.value = res.attrs; listeners.value = res.listeners; excludeAttrs.value = res.exclude; }); - return {$attrs: attrs2, $listeners: listeners, $excludeAttrs: excludeAttrs}; + return {$attrs: attrs, $listeners: listeners, $excludeAttrs: excludeAttrs}; }; function formatTime(val) { val = val > 0 && val < Infinity ? val : 0; @@ -10512,7 +7705,7 @@ function useFullscreen(trigger, containerRef, videoRef, userActionState, rootRef exitFullScreen }; } -function useVideo(props2, attrs2, trigger) { +function useVideo(props2, attrs, trigger) { const videoRef = vue.ref(null); const src = vue.computed(() => getRealPath(props2.src)); const state = vue.reactive({ @@ -10702,7 +7895,7 @@ function useControls(props2, videoState, seek) { let moveOnce = true; let originProgress; const ball = ballRef.value; - function touchmove2(event) { + function touchmove(event) { const toucher = event.targetTouches[0]; const pageX = toucher.pageX; const pageY = toucher.pageY; @@ -10726,7 +7919,7 @@ function useControls(props2, videoState, seek) { function touchend(event) { state.controlsTouching = false; if (state.touching) { - ball.removeEventListener("touchmove", touchmove2, passiveOptions2); + ball.removeEventListener("touchmove", touchmove, passiveOptions2); if (!moveOnce) { event.preventDefault(); event.stopPropagation(); @@ -10743,7 +7936,7 @@ function useControls(props2, videoState, seek) { originProgress = videoState.progress; moveOnce = true; state.touching = true; - ball.addEventListener("touchmove", touchmove2, passiveOptions2); + ball.addEventListener("touchmove", touchmove, passiveOptions2); }); ball.addEventListener("touchend", touchend); ball.addEventListener("touchcancel", touchend); @@ -10810,13 +8003,13 @@ function useDanmu(props2, videoState) { const p2 = document.createElement("p"); p2.className = "uni-video-danmu-item"; p2.innerText = danmu.text; - let style2 = `bottom: ${Math.random() * 100}%;color: ${danmu.color};`; - p2.setAttribute("style", style2); + let style = `bottom: ${Math.random() * 100}%;color: ${danmu.color};`; + p2.setAttribute("style", style); const danmuEl = danmuRef.value; danmuEl.appendChild(p2); setTimeout(function() { - style2 += "left: 0;-webkit-transform: translateX(-100%);transform: translateX(-100%);"; - p2.setAttribute("style", style2); + style += "left: 0;-webkit-transform: translateX(-100%);transform: translateX(-100%);"; + p2.setAttribute("style", style); setTimeout(function() { p2.remove(); }, 4e3); @@ -10865,7 +8058,7 @@ function useContext(play, pause, seek, sendDanmu, playbackRate, requestFullScree } }); } -const props$8 = { +const props$6 = { id: { type: String, default: "" @@ -10951,11 +8144,11 @@ const props$8 = { }; var index$5 = /* @__PURE__ */ vue.defineComponent({ name: "Video", - props: props$8, + props: props$6, emits: ["fullscreenchange", "progress", "loadedmetadata", "waiting", "error", "play", "pause", "ended", "timeupdate"], setup(props2, { emit: emit2, - attrs: attrs2, + attrs, slots }) { const rootRef = vue.ref(null); @@ -10990,7 +8183,7 @@ var index$5 = /* @__PURE__ */ vue.defineComponent({ onPause, onEnded, onTimeUpdate - } = useVideo(props2, attrs2, trigger); + } = useVideo(props2, attrs, trigger); const { state: danmuState, danmuRef, @@ -11153,2979 +8346,767 @@ var index$5 = /* @__PURE__ */ vue.defineComponent({ class: "uni-video-toast-volume-grids-item" }, null))])], 4)])], 2), vue.createVNode("div", { class: { - "uni-video-toast": true, - "uni-video-toast-progress": gestureState.gestureType === "progress" - } - }, [vue.createVNode("div", { - class: "uni-video-toast-title" - }, [formatTime(gestureState.currentTimeNew), " / ", formatTime(videoState.duration)])], 2), vue.createVNode("div", { - class: "uni-video-slots" - }, [slots.default && slots.default()])], 40, ["onTouchstart", "onTouchend", "onTouchmove", "onFullscreenchange", "onWebkitfullscreenchange"])], 8, ["id"]); - }; - } -}); -const props$7 = { - src: { - type: String, - default: "" - } -}; -var index$4 = /* @__PURE__ */ vue.defineComponent({ - inheritAttrs: false, - name: "WebView", - props: props$7, - setup(props2, { - attrs: attrs2 - }) { - const rootRef = vue.ref(null); - const iframeRef = vue.ref(null); - const _resize = useWebViewSize(rootRef, iframeRef); - const { - $attrs, - $excludeAttrs, - $listeners - } = useAttrs({ - excludeListeners: true - }); - vue.onMounted(() => { - _resize(); - }); - vue.onActivated(() => { - iframeRef.value && (iframeRef.value.style.display = "block"); - }); - vue.onDeactivated(() => { - iframeRef.value && (iframeRef.value.style.display = "none"); - }); - return () => { - return vue.createVNode(vue.Fragment, null, [vue.createVNode("uni-web-view", vue.mergeProps($listeners.value, $excludeAttrs.value, { - ref: rootRef - }), [vue.createVNode(ResizeSensor, { - onResize: _resize - }, null, 8, ["onResize"])], 16), vue.createVNode(vue.Teleport, { - to: "body" - }, { - default: () => [vue.createVNode("iframe", vue.mergeProps({ - ref: iframeRef, - src: getRealPath(props2.src) - }, $attrs.value), null, 16, ["src"])] - })]); - }; - } -}); -function useWebViewSize(rootRef, iframeRef) { - const _resize = () => { - const { - top, - left, - width, - height - } = rootRef.value.getBoundingClientRect(); - iframeRef.value && uniShared.updateElementStyle(iframeRef.value, { - position: "absolute", - display: "block", - border: "0", - top: top + "px", - left: left + "px", - width: width + "px", - height: height + "px" - }); - }; - return _resize; -} -function callback(options, data) { - options = options || {}; - if (typeof data === "string") { - data = { - errMsg: data - }; - } - if (/:ok$/.test(data.errMsg)) { - if (typeof options.success === "function") { - options.success(data); - } - } else { - if (typeof options.fail === "function") { - options.fail(data); - } - } - if (typeof options.complete === "function") { - options.complete(data); - } -} -function createCallout(maps2) { - const overlay = new maps2.Overlay(); - class Callout { - constructor(option = {}) { - this.setMap = overlay.setMap; - this.getMap = overlay.getMap; - this.getPanes = overlay.getPanes; - this.getProjection = overlay.getProjection; - this.map_changed = overlay.map_changed; - this.set = overlay.set; - this.get = overlay.get; - this.setOptions = overlay.setOptions; - this.bindTo = overlay.bindTo; - this.bindsTo = overlay.bindsTo; - this.notify = overlay.notify; - this.setValues = overlay.setValues; - this.unbind = overlay.unbind; - this.unbindAll = overlay.unbindAll; - this.option = option || {}; - const map = option.map; - this.position = option.position; - this.index = 1; - const visible = this.visible = this.alwaysVisible = option.display === "ALWAYS"; - const div = this.div = document.createElement("div"); - const divStyle = div.style; - divStyle.position = "absolute"; - divStyle.whiteSpace = "nowrap"; - divStyle.transform = "translateX(-50%) translateY(-100%)"; - divStyle.zIndex = "1"; - divStyle.boxShadow = option.boxShadow || "none"; - divStyle.display = visible ? "block" : "none"; - const triangle = this.triangle = document.createElement("div"); - triangle.setAttribute("style", "position: absolute;white-space: nowrap;border-width: 4px;border-style: solid;border-color: #fff transparent transparent;border-image: initial;font-size: 12px;padding: 0px;background-color: transparent;width: 0px;height: 0px;transform: translate(-50%, 100%);left: 50%;bottom: 0;"); - this.setStyle(option); - div.appendChild(triangle); - if (map) { - this.setMap(map); - } - } - set onclick(callback2) { - this.div.onclick = callback2; - } - get onclick() { - return this.div.onclick; - } - construct() { - const div = this.div; - const panes = this.getPanes(); - panes.floatPane.appendChild(div); - } - setOption(option) { - this.option = option; - this.setPosition(option.position); - if (option.display === "ALWAYS") { - this.alwaysVisible = this.visible = true; - } else { - this.alwaysVisible = false; - } - this.setStyle(option); - } - setStyle(option) { - const div = this.div; - const divStyle = div.style; - div.innerText = option.content || ""; - divStyle.lineHeight = (option.fontSize || 14) + "px"; - divStyle.fontSize = (option.fontSize || 14) + "px"; - divStyle.padding = (option.padding || 8) + "px"; - divStyle.color = option.color || "#000"; - divStyle.borderRadius = (option.borderRadius || 0) + "px"; - divStyle.backgroundColor = option.bgColor || "#fff"; - divStyle.marginTop = "-" + ((option.top || 0) + 5) + "px"; - this.triangle.style.borderColor = `${option.bgColor || "#fff"} transparent transparent`; - } - setPosition(position) { - this.position = position; - this.draw(); - } - draw() { - const overlayProjection = this.getProjection(); - if (!this.position || !this.div || !overlayProjection) { - return; - } - const pixel = overlayProjection.fromLatLngToDivPixel(this.position); - const divStyle = this.div.style; - divStyle.left = pixel.x + "px"; - divStyle.top = pixel.y + "px"; - } - changed() { - const divStyle = this.div.style; - divStyle.display = this.visible ? "block" : "none"; - } - destroy() { - const parentNode = this.div.parentNode; - if (parentNode) { - parentNode.removeChild(this.div); - } - } - } - return Callout; -} -let maps; -const callbacks = []; -const QQ_MAP_CALLBACKNAME = "__qq_map_callback__"; -function loadMaps(callback2) { - if (maps) { - callback2(maps); - } else if (window.qq && window.qq.maps) { - maps = window.qq.maps; - callback2(maps); - } else if (callbacks.length) { - callbacks.push(callback2); - } else { - callbacks.push(callback2); - const key = __uniConfig.qqMapKey; - const globalExt = window; - globalExt[QQ_MAP_CALLBACKNAME] = function() { - delete globalExt[QQ_MAP_CALLBACKNAME]; - maps = window.qq.maps; - maps.Callout = createCallout(maps); - callbacks.forEach((callback22) => callback22(maps)); - callbacks.length = 0; - }; - const script = document.createElement("script"); - script.src = `https://map.qq.com/api/js?v=2.exp&key=${key}&callback=${QQ_MAP_CALLBACKNAME}&libraries=geometry`; - document.body.appendChild(script); - } -} -const props$6 = { - id: { - type: [Number, String], - default: "" - }, - latitude: { - type: [Number, String], - require: true - }, - longitude: { - type: [Number, String], - require: true - }, - title: { - type: String, - default: "" - }, - iconPath: { - type: String, - require: true - }, - rotate: { - type: [Number, String], - default: 0 - }, - alpha: { - type: [Number, String], - default: 1 - }, - width: { - type: [Number, String], - default: "" - }, - height: { - type: [Number, String], - default: "" - }, - callout: { - type: Object, - default: null - }, - label: { - type: Object, - default: null - }, - anchor: { - type: Object, - default: null - }, - clusterId: { - type: [Number, String], - default: "" - }, - customCallout: { - type: Object, - default: null - }, - ariaLabel: { - type: String, - default: "" - } -}; -var MapMarker = /* @__PURE__ */ vue.defineComponent({ - name: "MapMarker", - props: props$6, - setup(props2) { - const id2 = String(Number(props2.id) !== NaN ? props2.id : ""); - const onMapReady = vue.inject("onMapReady"); - let marker; - function removeMarker() { - if (marker) { - if (marker.label) { - marker.label.setMap(null); - } - if (marker.callout) { - marker.callout.setMap(null); - } - marker.setMap(null); - } - } - onMapReady((map, maps2, trigger) => { - function updateMarker(option) { - const title = option.title; - const position = new maps2.LatLng(option.latitude, option.longitude); - const img = new Image(); - img.onload = () => { - const anchor = option.anchor || {}; - let icon; - let w; - let h; - let top; - let x = anchor.x; - let y = anchor.y; - if (option.iconPath && (option.width || option.height)) { - w = option.width || img.width / img.height * option.height; - h = option.height || img.height / img.width * option.width; - } else { - w = img.width / 2; - h = img.height / 2; - } - x = (typeof x === "number" ? x : 0.5) * w; - y = (typeof y === "number" ? y : 1) * h; - top = h - (h - y); - icon = new maps2.MarkerImage(img.src, null, null, new maps2.Point(x, y), new maps2.Size(w, h)); - marker.setPosition(position); - marker.setIcon(icon); - marker.setRotation(option.rotate || 0); - const labelOpt = option.label || {}; - if (marker.label) { - marker.label.setMap(null); - delete marker.label; - } - let label; - if (labelOpt.content) { - label = new maps2.Label({ - position, - map, - clickable: false, - content: labelOpt.content, - style: { - border: "none", - padding: "8px", - background: "none", - color: labelOpt.color, - fontSize: (labelOpt.fontSize || 14) + "px", - lineHeight: (labelOpt.fontSize || 14) + "px", - marginLeft: labelOpt.x, - marginTop: labelOpt.y - } - }); - marker.label = label; - } - const calloutOpt = option.callout || {}; - let callout = marker.callout; - let calloutStyle; - if (calloutOpt.content || title) { - calloutStyle = calloutOpt.content ? { - position, - map, - top, - content: calloutOpt.content, - color: calloutOpt.color, - fontSize: calloutOpt.fontSize, - borderRadius: calloutOpt.borderRadius, - bgColor: calloutOpt.bgColor, - padding: calloutOpt.padding, - boxShadow: calloutOpt.boxShadow, - display: calloutOpt.display - } : { - position, - map, - top, - content: title, - boxShadow: "0px 0px 3px 1px rgba(0,0,0,0.5)" - }; - if (callout) { - callout.setOption(calloutStyle); - } else { - callout = marker.callout = new maps2.Callout(calloutStyle); - callout.div.onclick = function($event) { - if (id2 !== "") { - trigger("callouttap", $event, { - markerId: Number(id2) - }); - } - $event.stopPropagation(); - $event.preventDefault(); - }; - } - } else { - if (callout) { - callout.setMap(null); - delete marker.callout; - } - } - }; - img.src = getRealPath(option.iconPath); - } - function addMarker(props3) { - marker = new maps2.Marker({ - map, - flat: true, - autoRotation: false - }); - updateMarker(props3); - maps2.event.addListener(marker, "click", () => { - const callout = marker.callout; - if (callout) { - const div = callout.div; - const parent = div.parentNode; - if (!callout.alwaysVisible) { - callout.set("visible", !callout.visible); - } - if (callout.visible) { - parent.removeChild(div); - parent.appendChild(div); - } - } - if (id2) { - trigger("markertap", {}, { - markerId: Number(id2) - }); - } - }); - } - addMarker(props2); - vue.watch(props2, updateMarker); - }); - if (id2) { - const addMapChidlContext = vue.inject("addMapChidlContext"); - const removeMapChidlContext = vue.inject("removeMapChidlContext"); - const context = { - id: id2, - translate(data) { - onMapReady((map, maps2, trigger) => { - const destination = data.destination; - const duration = data.duration; - const autoRotate = !!data.autoRotate; - let rotate = Number(data.rotate) || 0; - const rotation = marker.getRotation(); - const a2 = marker.getPosition(); - const b = new maps2.LatLng(destination.latitude, destination.longitude); - const distance = maps2.geometry.spherical.computeDistanceBetween(a2, b) / 1e3; - const time = (typeof duration === "number" ? duration : 1e3) / (1e3 * 60 * 60); - const speed = distance / time; - const movingEvent = maps2.event.addListener(marker, "moving", (e2) => { - const latLng = e2.latLng; - const label = marker.label; - if (label) { - label.setPosition(latLng); - } - const callout = marker.callout; - if (callout) { - callout.setPosition(latLng); - } - }); - const event = maps2.event.addListener(marker, "moveend", () => { - event.remove(); - movingEvent.remove(); - marker.lastPosition = a2; - marker.setPosition(b); - const label = marker.label; - if (label) { - label.setPosition(b); - } - const callout = marker.callout; - if (callout) { - callout.setPosition(b); - } - const cb = data.animationEnd; - if (typeof cb === "function") { - cb(); - } - }); - let lastRtate = 0; - if (autoRotate) { - if (marker.lastPosition) { - lastRtate = maps2.geometry.spherical.computeHeading(marker.lastPosition, a2); - } - rotate = maps2.geometry.spherical.computeHeading(a2, b) - lastRtate; - } - marker.setRotation(rotation + rotate); - marker.moveTo(b, speed); - }); - } - }; - addMapChidlContext(context); - vue.onUnmounted(() => removeMapChidlContext(context)); - } - vue.onUnmounted(removeMarker); - return () => { - return null; - }; - } -}); -const props$5 = { - points: { - type: Array, - require: true - }, - color: { - type: String, - default: "#000000" - }, - width: { - type: [Number, String], - default: "" - }, - dottedLine: { - type: [Boolean, String], - default: false - }, - arrowLine: { - type: [Boolean, String], - default: false - }, - arrowIconPath: { - type: String, - default: "" - }, - borderColor: { - type: String, - default: "#000000" - }, - borderWidth: { - type: [Number, String], - default: "" - }, - colorList: { - type: Array, - default() { - return []; - } - }, - level: { - type: String, - default: "" - } -}; -var MapPolyline = /* @__PURE__ */ vue.defineComponent({ - name: "MapPolyline", - props: props$5, - setup(props2) { - const onMapReady = vue.inject("onMapReady"); - let polyline; - let polylineBorder; - function removePolyline() { - if (polyline) { - polyline.setMap(null); - } - if (polylineBorder) { - polylineBorder.setMap(null); - } - } - onMapReady((map, maps2) => { - function updatePolyline(option) { - removePolyline(); - addPolyline(option); - } - function addPolyline(option) { - const path = []; - option.points.forEach((point) => { - path.push(new maps2.LatLng(point.latitude, point.longitude)); - }); - const strokeWeight = Number(option.width) || 1; - polyline = new maps2.Polyline({ - map, - clickable: false, - path, - strokeWeight, - strokeColor: option.color || void 0, - strokeDashStyle: option.dottedLine ? "dash" : "solid" - }); - const borderWidth = Number(option.borderWidth) || 0; - if (borderWidth) { - polylineBorder = new maps2.Polyline({ - map, - clickable: false, - path, - strokeWeight: strokeWeight + borderWidth * 2, - strokeColor: option.borderColor || void 0, - strokeDashStyle: option.dottedLine ? "dash" : "solid" - }); - } - } - addPolyline(props2); - vue.watch(props2, updatePolyline); - }); - vue.onUnmounted(removePolyline); - return () => { - return null; - }; - } -}); -const props$4 = { - latitude: { - type: [Number, String], - require: true - }, - longitude: { - type: [Number, String], - require: true - }, - color: { - type: String, - default: "" - }, - fillColor: { - type: String, - default: "" - }, - radius: { - type: [Number, String], - require: true - }, - strokeWidth: { - type: [Number, String], - default: "" - }, - level: { - type: String, - default: "" - } -}; -var MapCircle = /* @__PURE__ */ vue.defineComponent({ - name: "MapCircle", - props: props$4, - setup(props2) { - const onMapReady = vue.inject("onMapReady"); - let circle; - function removeCircle() { - if (circle) { - circle.setMap(null); - } - } - onMapReady((map, maps2) => { - function updateCircle(option) { - removeCircle(); - addCircle(option); - } - function addCircle(option) { - const center = new maps2.LatLng(option.latitude, option.longitude); - function getColor(color) { - const c = color.match(/#[0-9A-Fa-f]{6}([0-9A-Fa-f]{2})?/); - if (c && c.length) { - return maps2.Color.fromHex(c[0], Number("0x" + c[1] || 255) / 255); - } else { - return void 0; - } - } - circle = new maps2.Circle({ - map, - center, - clickable: false, - radius: option.radius, - strokeWeight: Number(option.strokeWidth) || 1, - fillColor: getColor(option.fillColor) || getColor("#00000001"), - strokeColor: getColor(option.color) || "#000000", - strokeDashStyle: "solid" - }); - } - addCircle(props2); - vue.watch(props2, updateCircle); - }); - vue.onUnmounted(removeCircle); - return () => { - return null; - }; - } -}); -const props$3 = { - id: { - type: [Number, String], - default: "" - }, - position: { - type: Object, - require: true - }, - iconPath: { - type: String, - require: true - }, - clickable: { - type: [Boolean, String], - default: "" - } -}; -var MapControl = /* @__PURE__ */ vue.defineComponent({ - name: "MapControl", - props: props$3, - setup(props2) { - const onMapReady = vue.inject("onMapReady"); - let control; - function removeControl() { - if (control) { - control.remove(); - } - } - onMapReady((map, maps2, trigger) => { - function updateControl(option) { - removeControl(); - addControl(option); - } - function addControl(option) { - const position = option.position || {}; - control = document.createElement("div"); - const img = new Image(); - control.appendChild(img); - const style2 = control.style; - style2.position = "absolute"; - style2.width = "0"; - style2.height = "0"; - img.onload = () => { - if (option.position.width) { - img.width = option.position.width; - } - if (option.position.height) { - img.height = option.position.height; - } - const style3 = img.style; - style3.position = "absolute"; - style3.left = (position.left || 0) + "px"; - style3.top = (position.top || 0) + "px"; - style3.maxWidth = "initial"; - }; - img.src = getRealPath(option.iconPath); - img.onclick = function($event) { - if (option.clickable) { - trigger("controltap", $event, { - controlId: option.id - }); - } - }; - map.controls[maps2.ControlPosition.TOP_LEFT].push(control); - } - addControl(props2); - vue.watch(props2, updateControl); - }); - vue.onUnmounted(removeControl); - return () => { - return null; - }; - } -}); -const innerAudioContextEventNames = [ - "onCanplay", - "onPlay", - "onPause", - "onStop", - "onEnded", - "onTimeUpdate", - "onError", - "onWaiting", - "onSeeking", - "onSeeked" -]; -const innerAudioContextOffEventNames = [ - "offCanplay", - "offPlay", - "offPause", - "offStop", - "offEnded", - "offTimeUpdate", - "offError", - "offWaiting", - "offSeeking", - "offSeeked" -]; -const propertys = [ - "src", - "autoplay", - "loop", - "duration", - "currentTime", - "paused", - "volume" -]; -class InnerAudioContext { - constructor() { - this._src = ""; - var audio = this._audio = new Audio(); - this._stoping = false; - propertys.forEach((property) => { - Object.defineProperty(this, property, { - set: property === "src" ? (src) => { - audio.src = getRealPath(src); - this._src = src; - return src; - } : (val) => { - audio.setAttribute(property, val); - return val; - }, - get: property === "src" ? () => { - return this._src; - } : () => { - return audio[property]; - } - }); - }); - this.startTime = 0; - Object.defineProperty(this, "obeyMuteSwitch", { - set: () => false, - get: () => false - }); - Object.defineProperty(this, "buffered", { - set: () => false, - get() { - var buffered = audio.buffered; - if (buffered.length) { - return buffered.end(buffered.length - 1); - } else { - return 0; - } - } - }); - this._events = {}; - innerAudioContextEventNames.forEach((eventName) => { - this._events[eventName] = []; - }); - audio.addEventListener("loadedmetadata", () => { - var startTime = Number(this.startTime) || 0; - if (startTime > 0) { - audio.currentTime = startTime; - } - }); - var eventNames = [ - "canplay", - "play", - "pause", - "ended", - "timeUpdate", - "error", - "waiting", - "seeking", - "seeked" - ]; - var stopEventNames = ["canplay", "pause", "seeking", "seeked", "timeUpdate"]; - eventNames.forEach((eventName) => { - audio.addEventListener(eventName.toLowerCase(), () => { - if (this._stoping && stopEventNames.indexOf(eventName) >= 0) { - return; - } - const EventName = `on${eventName.substr(0, 1).toUpperCase()}${eventName.substr(1)}`; - this._events[EventName].forEach((callback2) => { - callback2(); - }); - }, false); - }); - } - play() { - this._stoping = false; - this._audio.play(); - } - pause() { - this._audio.pause(); - } - stop() { - this._stoping = true; - this._audio.pause(); - this._audio.currentTime = 0; - this._events.onStop.forEach((callback2) => { - callback2(); - }); - } - seek(position) { - this._stoping = false; - position = Number(position); - if (typeof position === "number" && !isNaN(position)) { - this._audio.currentTime = position; - } - } - destroy() { - this.stop(); - } -} -innerAudioContextEventNames.forEach((eventName) => { - InnerAudioContext.prototype[eventName] = function(callback2) { - if (typeof callback2 === "function") { - this._events[eventName].push(callback2); - } - }; -}); -innerAudioContextOffEventNames.forEach((eventName) => { - InnerAudioContext.prototype[eventName] = function(callback2) { - var handle = this._events[eventName.replace("off", "on")]; - var index2 = handle.indexOf(callback2); - if (index2 >= 0) { - handle.splice(index2, 1); - } - }; -}); -const createInnerAudioContext = defineSyncApi(API_CREATE_INNER_AUDIO_CONTEXT, () => { - return new InnerAudioContext(); -}); -const makePhoneCall = defineAsyncApi(API_MAKE_PHONE_CALL, ({phoneNumber}, {resolve}) => { - window.location.href = `tel:${phoneNumber}`; - return resolve(); -}, MakePhoneCallProtocol); -const getSystemInfoSync = defineSyncApi("getSystemInfoSync", () => { - const pixelRatio2 = window.devicePixelRatio; - const screenFix = getScreenFix(); - const landscape = isLandscape(screenFix); - const screenWidth = getScreenWidth(screenFix, landscape); - const screenHeight = getScreenHeight(screenFix, landscape); - const windowWidth = getWindowWidth(screenWidth); - let windowHeight = window.innerHeight; - const language = navigator.language; - const statusBarHeight = D__DCloud_local_git_uniAppNext_node_modules_safeAreaInsets_out.top; - let osname; - let osversion; - let model; - if (isIOS$1) { - osname = "iOS"; - const osversionFind = ua.match(/OS\s([\w_]+)\slike/); - if (osversionFind) { - osversion = osversionFind[1].replace(/_/g, "."); - } - const modelFind = ua.match(/\(([a-zA-Z]+);/); - if (modelFind) { - model = modelFind[1]; - } - } else if (isAndroid) { - osname = "Android"; - const osversionFind = ua.match(/Android[\s/]([\w\.]+)[;\s]/); - if (osversionFind) { - osversion = osversionFind[1]; - } - const infoFind = ua.match(/\((.+?)\)/); - const infos = infoFind ? infoFind[1].split(";") : ua.split(" "); - const otherInfo = [ - /\bAndroid\b/i, - /\bLinux\b/i, - /\bU\b/i, - /^\s?[a-z][a-z]$/i, - /^\s?[a-z][a-z]-[a-z][a-z]$/i, - /\bwv\b/i, - /\/[\d\.,]+$/, - /^\s?[\d\.,]+$/, - /\bBrowser\b/i, - /\bMobile\b/i - ]; - for (let i2 = 0; i2 < infos.length; i2++) { - const info = infos[i2]; - if (info.indexOf("Build") > 0) { - model = info.split("Build")[0].trim(); - break; - } - let other; - for (let o2 = 0; o2 < otherInfo.length; o2++) { - if (otherInfo[o2].test(info)) { - other = true; - break; - } - } - if (!other) { - model = info.trim(); - break; - } - } - } else if (isIPadOS) { - model = "iPad"; - osname = "iOS"; - osversion = typeof window.BigInt === "function" ? "14.0" : "13.0"; - } else if (isWindows || isMac || isLinux) { - model = "PC"; - osname = "PC"; - osversion = "0"; - let osversionFind = ua.match(/\((.+?)\)/)[1]; - if (isWindows) { - osname = "Windows"; - switch (isWindows[1]) { - case "5.1": - osversion = "XP"; - break; - case "6.0": - osversion = "Vista"; - break; - case "6.1": - osversion = "7"; - break; - case "6.2": - osversion = "8"; - break; - case "6.3": - osversion = "8.1"; - break; - case "10.0": - osversion = "10"; - break; - } - const framework = osversionFind && osversionFind.match(/[Win|WOW]([\d]+)/); - if (framework) { - osversion += ` x${framework[1]}`; - } - } else if (isMac) { - osname = "Mac"; - osversion = osversionFind && osversionFind.match(/Mac OS X (.+)/) || ""; - if (osversion) { - osversion = osversion[1].replace(/_/g, "."); - if (osversion.indexOf(";") !== -1) { - osversion = osversion.split(";")[0]; - } - } - } else if (isLinux) { - osname = "Linux"; - osversion = osversionFind && osversionFind.match(/Linux (.*)/) || ""; - if (osversion) { - osversion = osversion[1]; - if (osversion.indexOf(";") !== -1) { - osversion = osversion.split(";")[0]; - } - } - } - } else { - osname = "Other"; - osversion = "0"; - } - const system = `${osname} ${osversion}`; - const platform = osname.toLocaleLowerCase(); - const safeArea = { - 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; - windowHeight -= windowBottom; - return { - windowTop, - windowBottom, - windowWidth, - windowHeight, - pixelRatio: pixelRatio2, - screenWidth, - screenHeight, - language, - statusBarHeight, - system, - platform, - model, - safeArea, - safeAreaInsets: { - 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 - } - }; -}); -const getSystemInfo = defineAsyncApi("getSystemInfo", (_args, {resolve}) => { - return resolve(getSystemInfoSync()); -}); -const API_ON_NETWORK_STATUS_CHANGE = "onNetworkStatusChange"; -function networkListener() { - getNetworkType().then(({networkType}) => { - UniServiceJSBridge.invokeOnCallback(API_ON_NETWORK_STATUS_CHANGE, { - isConnected: networkType !== "none", - networkType - }); - }); -} -function getConnection() { - return navigator.connection || navigator.webkitConnection || navigator.mozConnection; -} -const onNetworkStatusChange = defineOnApi(API_ON_NETWORK_STATUS_CHANGE, () => { - const connection = getConnection(); - if (connection) { - connection.addEventListener("change", networkListener); - } else { - window.addEventListener("offline", networkListener); - window.addEventListener("online", networkListener); - } -}); -const offNetworkStatusChange = defineOffApi("offNetworkStatusChange", () => { - const connection = getConnection(); - if (connection) { - connection.removeEventListener("change", networkListener); - } else { - window.removeEventListener("offline", networkListener); - window.removeEventListener("online", networkListener); - } -}); -const getNetworkType = defineAsyncApi("getNetworkType", (_args, {resolve}) => { - const connection = getConnection(); - let networkType = "unknown"; - if (connection) { - networkType = connection.type; - if (networkType === "cellular" && connection.effectiveType) { - networkType = connection.effectiveType.replace("slow-", ""); - } else if (!["none", "wifi"].includes(networkType)) { - networkType = "unknown"; - } - } else if (navigator.onLine === false) { - networkType = "none"; - } - return resolve({networkType}); -}); -let listener$1 = null; -const onAccelerometerChange = defineOnApi(API_ON_ACCELEROMETER, () => { - startAccelerometer(); -}); -const offAccelerometerChange = defineOnApi(API_OFF_ACCELEROMETER, () => { - stopAccelerometer(); -}); -const startAccelerometer = defineAsyncApi(API_START_ACCELEROMETER, (_, {resolve, reject}) => { - if (!window.DeviceMotionEvent) { - reject(); - return; - } - function addEventListener() { - listener$1 = function(event) { - const acceleration = event.acceleration || event.accelerationIncludingGravity; - UniServiceJSBridge.invokeOnCallback(API_ON_ACCELEROMETER, { - x: acceleration && acceleration.x || 0, - y: acceleration && acceleration.y || 0, - z: acceleration && acceleration.z || 0 - }); - }; - window.addEventListener("devicemotion", listener$1, false); - } - if (!listener$1) { - if (DeviceMotionEvent.requestPermission) { - DeviceMotionEvent.requestPermission().then((res) => { - if (res === "granted") { - addEventListener(); - resolve(); - } else { - reject(`${res}`); - } - }).catch((error) => { - reject(`${error}`); - }); - return; - } - addEventListener(); - } - resolve(); -}); -const stopAccelerometer = defineAsyncApi(API_STOP_ACCELEROMETER, (_, {resolve}) => { - if (listener$1) { - window.removeEventListener("devicemotion", listener$1, false); - listener$1 = null; - } - resolve(); -}); -let listener = null; -const onCompassChange = defineOnApi(API_ON_COMPASS, () => { - startCompass(); -}); -const offCompassChange = defineOnApi(API_OFF_COMPASS, () => { - stopCompass(); -}); -const startCompass = defineAsyncApi(API_START_COMPASS, (_, {resolve, reject}) => { - if (!window.DeviceOrientationEvent) { - reject(); - return; - } - function addEventListener() { - listener = function(event) { - const direction2 = 360 - (event.alpha !== null ? event.alpha : 360); - UniServiceJSBridge.invokeOnCallback(API_ON_COMPASS, { - direction: direction2 - }); - }; - window.addEventListener("deviceorientation", listener, false); - } - if (!listener) { - if (DeviceOrientationEvent.requestPermission) { - DeviceOrientationEvent.requestPermission().then((res) => { - if (res === "granted") { - addEventListener(); - resolve(); - } else { - reject(`${res}`); + "uni-video-toast": true, + "uni-video-toast-progress": gestureState.gestureType === "progress" } - }).catch((error) => { - reject(`${error}`); - }); - return; - } - addEventListener(); - } - resolve(); -}); -const stopCompass = defineAsyncApi(API_STOP_COMPASS, (_, {resolve}) => { - if (listener) { - window.removeEventListener("deviceorientation", listener, false); - listener = null; - } - resolve(); -}); -const _isSupport = !!window.navigator.vibrate; -const vibrateShort = defineAsyncApi(API_VIBRATE_SHORT, (args, {resolve, reject}) => { - if (_isSupport && window.navigator.vibrate(15)) { - resolve(); - } else { - reject("vibrateLong:fail"); - } -}); -const vibrateLong = defineAsyncApi(API_VIBRATE_LONG, (args, {resolve, reject}) => { - if (_isSupport && window.navigator.vibrate(400)) { - resolve(); - } else { - reject("vibrateLong:fail"); + }, [vue.createVNode("div", { + class: "uni-video-toast-title" + }, [formatTime(gestureState.currentTimeNew), " / ", formatTime(videoState.duration)])], 2), vue.createVNode("div", { + class: "uni-video-slots" + }, [slots.default && slots.default()])], 40, ["onTouchstart", "onTouchend", "onTouchmove", "onFullscreenchange", "onWebkitfullscreenchange"])], 8, ["id"]); + }; } }); -const STORAGE_KEYS = "uni-storage-keys"; -function parseValue(value) { - const types = ["object", "string", "number", "boolean", "undefined"]; - try { - const object = typeof value === "string" ? JSON.parse(value) : value; - const type = object.type; - if (types.indexOf(type) >= 0) { - const keys = Object.keys(object); - if (keys.length === 2 && "data" in object) { - if (typeof object.data === type) { - return object.data; - } - if (type === "object" && /^\d{4}-\d{2}-\d{2}T\d{2}\:\d{2}\:\d{2}\.\d{3}Z$/.test(object.data)) { - return new Date(object.data); - } - } else if (keys.length === 1) { - return ""; - } - } - } catch (error) { +const props$5 = { + src: { + type: String, + default: "" } -} -const setStorageSync = defineSyncApi(API_SET_STORAGE_SYNC, (key, data) => { - const type = typeof data; - const value = type === "string" ? data : JSON.stringify({ - type, - data - }); - localStorage.setItem(key, value); -}, SetStorageSyncProtocol); -const setStorage = defineAsyncApi(API_SET_STORAGE, ({key, data}, {resolve, reject}) => { - try { - setStorageSync(key, data); - resolve(); - } catch (error) { - reject(error.message); - } -}, SetStorageProtocol); -function getStorageOrigin(key) { - const value = localStorage && localStorage.getItem(key); - if (typeof value !== "string") { - throw new Error("data not found"); - } - let data = value; - try { - const object = JSON.parse(value); - const result = parseValue(object); - if (result !== void 0) { - data = result; - } - } catch (error) { - } - return data; -} -const getStorageSync = defineSyncApi(API_GET_STORAGE_SYNC, (key, t2) => { - try { - return getStorageOrigin(key); - } catch (error) { - return ""; - } -}, GetStorageSyncProtocol); -const getStorage = defineAsyncApi(API_GET_STORAGE, ({key}, {resolve, reject}) => { - try { - const data = getStorageOrigin(key); - resolve({ - data +}; +var index$4 = /* @__PURE__ */ vue.defineComponent({ + inheritAttrs: false, + name: "WebView", + props: props$5, + setup(props2, { + attrs + }) { + const rootRef = vue.ref(null); + const iframeRef = vue.ref(null); + const _resize = useWebViewSize(rootRef, iframeRef); + const { + $attrs, + $excludeAttrs, + $listeners + } = useAttrs({ + excludeListeners: true }); - } catch (error) { - reject(error.message); - } -}, GetStorageProtocol); -const removeStorageSync = defineSyncApi(API_REMOVE_STORAGE, (key) => { - if (localStorage) { - localStorage.removeItem(key); - } -}, RemoveStorageSyncProtocol); -const removeStorage = defineAsyncApi(API_REMOVE_STORAGE, ({key}, {resolve}) => { - removeStorageSync(key); - resolve(); -}, RemoveStorageProtocol); -const clearStorageSync = defineSyncApi("clearStorageSync", () => { - if (localStorage) { - localStorage.clear(); - } -}); -const clearStorage = defineAsyncApi("clearStorage", (_, {resolve}) => { - clearStorageSync(); - resolve(); -}); -const getStorageInfoSync = defineSyncApi("getStorageInfoSync", () => { - const length = localStorage && localStorage.length || 0; - const keys = []; - let currentSize = 0; - for (let index2 = 0; index2 < length; index2++) { - const key = localStorage.key(index2); - const value = localStorage.getItem(key) || ""; - currentSize += key.length + value.length; - if (key !== STORAGE_KEYS) { - keys.push(key); - } - } - return { - keys, - currentSize: Math.ceil(currentSize * 2 / 1024), - limitSize: Number.MAX_VALUE - }; -}); -const getStorageInfo = defineAsyncApi("getStorageInfo", (_, {resolve}) => { - resolve(getStorageInfoSync()); -}); -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 (shared.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 revokeObjectURL(url) { - const URL = window.URL || window.webkitURL; - URL.revokeObjectURL(url); - delete files[url]; -} -const getFileInfo = defineAsyncApi(API_GET_FILE_INFO, ({filePath}, {resolve, reject}) => { - urlToFile(filePath).then((res) => { - resolve({ - size: res.size + vue.onMounted(() => { + _resize(); }); - }).catch((err) => { - reject(String(err)); - }); -}, GetFileInfoProtocol, GetFileInfoOptions); -const openDocument = defineAsyncApi(API_OPEN_DOCUMENT, ({filePath}, {resolve}) => { - window.open(filePath); - return resolve(); -}, OpenDocumentProtocol, OpenDocumentOptions); -const hideKeyboard = defineAsyncApi(API_HIDE_KEYBOARD, (args, {resolve, reject}) => { - const activeElement = document.activeElement; - if (activeElement && (activeElement.tagName === "TEXTAREA" || activeElement.tagName === "INPUT")) { - activeElement.blur(); - resolve(); - } -}); -function getServiceAddress() { - return window.location.protocol + "//" + window.location.host; -} -const getImageInfo = defineAsyncApi(API_GET_IMAGE_INFO, ({src}, {resolve, reject}) => { - const img = new Image(); - img.onload = function() { - resolve({ - width: img.naturalWidth, - height: img.naturalHeight, - path: src.indexOf("/") === 0 ? getServiceAddress() + src : src + vue.onActivated(() => { + iframeRef.value && (iframeRef.value.style.display = "block"); }); - }; - img.onerror = function() { - reject(); - }; - img.src = src; -}, GetImageInfoProtocol, GetImageInfoOptions); -const getVideoInfo = defineAsyncApi(API_GET_VIDEO_INFO, ({src}, {resolve, reject}) => { - urlToFile(src, true).then((file) => { - return file; - }).catch(() => { - return null; - }).then((file) => { - const video = document.createElement("video"); - if (video.onloadedmetadata !== void 0) { - const handle = setTimeout(() => { - video.onloadedmetadata = null; - video.onerror = null; - reject(); - }, src.startsWith("data:") || src.startsWith("blob:") ? 300 : 3e3); - video.onloadedmetadata = function() { - clearTimeout(handle); - video.onerror = null; - resolve({ - size: file ? file.size : void 0, - duration: video.duration || 0, - width: video.videoWidth || 0, - height: video.videoHeight || 0 - }); - }; - video.onerror = function() { - clearTimeout(handle); - video.onloadedmetadata = null; - reject(); - }; - video.src = src; - } else { - reject(); - } - }); -}, GetVideoInfoProtocol, GetVideoInfoOptions); -const MIMEType = { - image: { - jpg: "jpeg", - jpe: "jpeg", - pbm: "x-portable-bitmap", - pgm: "x-portable-graymap", - pnm: "x-portable-anymap", - ppm: "x-portable-pixmap", - psd: "vnd.adobe.photoshop", - pic: "x-pict", - rgb: "x-rgb", - svg: "svg+xml", - svgz: "svg+xml", - tif: "tiff", - xif: "vnd.xiff", - wbmp: "vnd.wap.wbmp", - wdp: "vnd.ms-photo", - xbm: "x-xbitmap", - ico: "x-icon" - }, - video: { - "3g2": "3gpp2", - "3gp": "3gpp", - avi: "x-msvideo", - f4v: "x-f4v", - flv: "x-flv", - jpgm: "jpm", - jpgv: "jpeg", - m1v: "mpeg", - m2v: "mpeg", - mpe: "mpeg", - mpg: "mpeg", - mpg4: "mpeg", - m4v: "x-m4v", - mkv: "x-matroska", - mov: "quicktime", - qt: "quicktime", - movie: "x-sgi-movie", - mp4v: "mp4", - ogv: "ogg", - smv: "x-smv", - wm: "x-ms-wm", - wmv: "x-ms-wmv", - wmx: "x-ms-wmx", - wvx: "x-ms-wvx" - } -}; -const ALL = "all"; -function isWXEnv() { - const ua2 = window.navigator.userAgent.toLowerCase(); - const matchUA = ua2.match(/MicroMessenger/i); - return !!(matchUA && matchUA[0] === "micromessenger"); -} -function _createInput({ - count, - sourceType, - type, - extension -}) { - const inputEl = document.createElement("input"); - inputEl.type = "file"; - uniShared.updateElementStyle(inputEl, { - position: "absolute", - visibility: "hidden", - zIndex: "-999", - width: "0", - height: "0", - top: "0", - left: "0" - }); - inputEl.accept = extension.map((item) => { - if (type !== ALL) { - const MIMEKey = item.replace(".", ""); - return `${type}/${MIMEType[type][MIMEKey] || MIMEKey}`; - } else { - if (isWXEnv()) { - return "."; - } - return item.indexOf(".") === 0 ? item : `.${item}`; - } - }).join(","); - if (count && count > 1) { - inputEl.multiple = true; - } - if (type !== ALL && sourceType instanceof Array && sourceType.length === 1 && sourceType[0] === "camera") { - inputEl.setAttribute("capture", "camera"); - } - return inputEl; -} -let fileInput = null; -const chooseFile = defineAsyncApi(API_CHOOSE_FILE, ({ - count, - sourceType, - type, - extension -}, {resolve, reject}) => { - if (fileInput) { - document.body.removeChild(fileInput); - fileInput = null; - } - fileInput = _createInput({ - count, - sourceType, - type, - extension - }); - document.body.appendChild(fileInput); - fileInput.addEventListener("change", function(event) { - const eventTarget = event.target; - const tempFiles = []; - if (eventTarget && eventTarget.files) { - const fileCount = eventTarget.files.length; - for (let i2 = 0; i2 < fileCount; i2++) { - const file = eventTarget.files[i2]; - let filePath; - Object.defineProperty(file, "path", { - get() { - filePath = filePath || fileToUrl(file); - return filePath; - } - }); - if (i2 < count) - tempFiles.push(file); - } - } - const res = { - get tempFilePaths() { - return tempFiles.map(({path}) => path); - }, - tempFiles - }; - resolve(res); - }); - fileInput.click(); -}, ChooseFileProtocol, ChooseFileOptions); -let imageInput = null; -const chooseImage = defineAsyncApi(API_CHOOSE_IMAGE, ({ - count, - sourceType, - extension -}, {resolve, reject}) => { - if (imageInput) { - document.body.removeChild(imageInput); - imageInput = null; - } - imageInput = _createInput({ - count, - sourceType, - extension, - type: "image" - }); - document.body.appendChild(imageInput); - imageInput.addEventListener("change", function(event) { - const eventTarget = event.target; - const tempFiles = []; - if (eventTarget && eventTarget.files) { - const fileCount = eventTarget.files.length; - for (let i2 = 0; i2 < fileCount; i2++) { - const file = eventTarget.files[i2]; - let filePath; - Object.defineProperty(file, "path", { - get() { - filePath = filePath || fileToUrl(file); - return filePath; - } - }); - if (i2 < count) - tempFiles.push(file); - } - } - const res = { - get tempFilePaths() { - return tempFiles.map(({path}) => path); - }, - tempFiles - }; - resolve(res); - }); - imageInput.click(); -}, ChooseImageProtocol, ChooseImageOptions); -let videoInput = null; -const chooseVideo = defineAsyncApi(API_CHOOSE_VIDEO, ({sourceType, extension}, {resolve, reject}) => { - if (videoInput) { - document.body.removeChild(videoInput); - videoInput = null; - } - videoInput = _createInput({ - sourceType, - extension, - type: "video" - }); - document.body.appendChild(videoInput); - videoInput.addEventListener("change", function(event) { - const eventTarget = event.target; - const file = eventTarget.files[0]; - let filePath = ""; - const callbackResult = { - tempFilePath: filePath, - tempFile: file, - size: file.size, - duration: 0, - width: 0, - height: 0, - name: file.name - }; - Object.defineProperty(callbackResult, "tempFilePath", { - get() { - filePath = filePath || fileToUrl(this.tempFile); - return filePath; - } + vue.onDeactivated(() => { + iframeRef.value && (iframeRef.value.style.display = "none"); }); - const video = document.createElement("video"); - if (video.onloadedmetadata !== void 0) { - const filePath2 = fileToUrl(file); - video.onloadedmetadata = function() { - revokeObjectURL(filePath2); - resolve(Object.assign(callbackResult, { - duration: video.duration || 0, - width: video.videoWidth || 0, - height: video.videoHeight || 0 - })); - }; - setTimeout(() => { - video.onloadedmetadata = null; - revokeObjectURL(filePath2); - resolve(callbackResult); - }, 300); - video.src = filePath2; - } else { - resolve(callbackResult); - } - }); - videoInput.click(); -}, ChooseVideoProtocol, ChooseVideoOptions); -const request = defineTaskApi(API_REQUEST, ({ - url, - data, - header, - method, - dataType: dataType2, - responseType, - withCredentials, - timeout = __uniConfig.networkTimeout.request -}, {resolve, reject}) => { - let body = null; - const contentType = normalizeContentType(header); - if (method !== "GET") { - if (typeof data === "string" || data instanceof ArrayBuffer) { - body = data; - } else { - if (contentType === "json") { - try { - body = JSON.stringify(data); - } catch (error) { - body = data.toString(); - } - } else if (contentType === "urlencoded") { - const bodyArray = []; - for (const key in data) { - if (shared.hasOwn(data, key)) { - bodyArray.push(encodeURIComponent(key) + "=" + encodeURIComponent(data[key])); - } - } - body = bodyArray.join("&"); - } else { - body = data.toString(); - } - } - } - const xhr = new XMLHttpRequest(); - const requestTask = new RequestTask(xhr); - xhr.open(method, url); - for (const key in header) { - if (shared.hasOwn(header, key)) { - xhr.setRequestHeader(key, header[key]); - } + return () => { + return vue.createVNode(vue.Fragment, null, [vue.createVNode("uni-web-view", vue.mergeProps($listeners.value, $excludeAttrs.value, { + ref: rootRef + }), [vue.createVNode(ResizeSensor, { + onResize: _resize + }, null, 8, ["onResize"])], 16), vue.createVNode(vue.Teleport, { + to: "body" + }, { + default: () => [vue.createVNode("iframe", vue.mergeProps({ + ref: iframeRef, + src: getRealPath(props2.src) + }, $attrs.value), null, 16, ["src"])] + })]); + }; } - const timer = setTimeout(function() { - xhr.onload = xhr.onabort = xhr.onerror = null; - requestTask.abort(); - reject("timeout"); - }, timeout); - xhr.responseType = responseType; - xhr.onload = function() { - clearTimeout(timer); - const statusCode = xhr.status; - let res = responseType === "text" ? xhr.responseText : xhr.response; - if (responseType === "text" && dataType2 === "json") { - try { - res = JSON.parse(res); - } catch (error) { - } - } - resolve({ - data: res, - statusCode, - header: parseHeaders(xhr.getAllResponseHeaders()), - cookies: [] +}); +function useWebViewSize(rootRef, iframeRef) { + const _resize = () => { + const { + top, + left, + width, + height + } = rootRef.value.getBoundingClientRect(); + iframeRef.value && uniShared.updateElementStyle(iframeRef.value, { + position: "absolute", + display: "block", + border: "0", + top: top + "px", + left: left + "px", + width: width + "px", + height: height + "px" }); }; - xhr.onabort = function() { - clearTimeout(timer); - reject("abort"); - }; - xhr.onerror = function() { - clearTimeout(timer); - reject(); - }; - xhr.withCredentials = withCredentials; - xhr.send(body); - return requestTask; -}, RequestProtocol, RequestOptions); -function normalizeContentType(header) { - const name = Object.keys(header).find((name2) => name2.toLowerCase() === "content-type"); - if (!name) { - return; - } - const contentType = header[name]; - if (contentType.indexOf("application/json") === 0) { - return "json"; - } else if (contentType.indexOf("application/x-www-form-urlencoded") === 0) { - return "urlencoded"; - } - return "string"; -} -class RequestTask { - constructor(xhr) { - this._xhr = xhr; + return _resize; +} +function callback(options, data) { + options = options || {}; + if (typeof data === "string") { + data = { + errMsg: data + }; } - abort() { - if (this._xhr) { - this._xhr.abort(); - delete this._xhr; + if (/:ok$/.test(data.errMsg)) { + if (typeof options.success === "function") { + options.success(data); + } + } else { + if (typeof options.fail === "function") { + options.fail(data); } } - onHeadersReceived(callback2) { - throw new Error("Method not implemented."); - } - offHeadersReceived(callback2) { - throw new Error("Method not implemented."); + if (typeof options.complete === "function") { + options.complete(data); } } -function parseHeaders(headers) { - const headersObject = {}; - headers.split("\n").forEach((header) => { - const find = header.match(/(\S+\s*):\s*(.*)/); - if (!find || find.length !== 3) { - return; +function createCallout(maps2) { + const overlay = new maps2.Overlay(); + class Callout { + constructor(option = {}) { + this.setMap = overlay.setMap; + this.getMap = overlay.getMap; + this.getPanes = overlay.getPanes; + this.getProjection = overlay.getProjection; + this.map_changed = overlay.map_changed; + this.set = overlay.set; + this.get = overlay.get; + this.setOptions = overlay.setOptions; + this.bindTo = overlay.bindTo; + this.bindsTo = overlay.bindsTo; + this.notify = overlay.notify; + this.setValues = overlay.setValues; + this.unbind = overlay.unbind; + this.unbindAll = overlay.unbindAll; + this.option = option || {}; + const map = option.map; + this.position = option.position; + this.index = 1; + const visible = this.visible = this.alwaysVisible = option.display === "ALWAYS"; + const div = this.div = document.createElement("div"); + const divStyle = div.style; + divStyle.position = "absolute"; + divStyle.whiteSpace = "nowrap"; + divStyle.transform = "translateX(-50%) translateY(-100%)"; + divStyle.zIndex = "1"; + divStyle.boxShadow = option.boxShadow || "none"; + divStyle.display = visible ? "block" : "none"; + const triangle = this.triangle = document.createElement("div"); + triangle.setAttribute("style", "position: absolute;white-space: nowrap;border-width: 4px;border-style: solid;border-color: #fff transparent transparent;border-image: initial;font-size: 12px;padding: 0px;background-color: transparent;width: 0px;height: 0px;transform: translate(-50%, 100%);left: 50%;bottom: 0;"); + this.setStyle(option); + div.appendChild(triangle); + if (map) { + this.setMap(map); + } } - headersObject[find[1]] = find[2]; - }); - return headersObject; -} -class DownloadTask { - constructor(xhr) { - this._callbacks = []; - this._xhr = xhr; - } - onProgressUpdate(callback2) { - if (typeof callback2 !== "function") { - return; + set onclick(callback2) { + this.div.onclick = callback2; } - this._callbacks.push(callback2); - } - offProgressUpdate(callback2) { - const index2 = this._callbacks.indexOf(callback2); - if (index2 >= 0) { - this._callbacks.splice(index2, 1); + get onclick() { + return this.div.onclick; } - } - abort() { - if (this._xhr) { - this._xhr.abort(); - delete this._xhr; + construct() { + const div = this.div; + const panes = this.getPanes(); + panes.floatPane.appendChild(div); } - } - onHeadersReceived(callback2) { - throw new Error("Method not implemented."); - } - offHeadersReceived(callback2) { - throw new Error("Method not implemented."); - } -} -const downloadFile = defineTaskApi(API_DOWNLOAD_FILE, ({url, header, timeout = __uniConfig.networkTimeout.downloadFile}, {resolve, reject}) => { - var timer; - var xhr = new XMLHttpRequest(); - var downloadTask = new DownloadTask(xhr); - xhr.open("GET", url, true); - Object.keys(header).forEach((key) => { - xhr.setRequestHeader(key, header[key]); - }); - xhr.responseType = "blob"; - xhr.onload = function() { - clearTimeout(timer); - const statusCode = xhr.status; - const blob = this.response; - let filename; - const contentDisposition = xhr.getResponseHeader("content-disposition"); - if (contentDisposition) { - const res = contentDisposition.match(/filename="?(\S+)"?\b/); - if (res) { - filename = res[1]; + setOption(option) { + this.option = option; + this.setPosition(option.position); + if (option.display === "ALWAYS") { + this.alwaysVisible = this.visible = true; + } else { + this.alwaysVisible = false; } + this.setStyle(option); } - blob.name = filename || getFileName(url); - resolve({ - statusCode, - tempFilePath: fileToUrl(blob) - }); - }; - xhr.onabort = function() { - clearTimeout(timer); - reject("abort"); - }; - xhr.onerror = function() { - clearTimeout(timer); - reject(); - }; - xhr.onprogress = function(event) { - downloadTask._callbacks.forEach((callback2) => { - var totalBytesWritten = event.loaded; - var totalBytesExpectedToWrite = event.total; - var progress = Math.round(totalBytesWritten / totalBytesExpectedToWrite * 100); - callback2({ - progress, - totalBytesWritten, - totalBytesExpectedToWrite - }); - }); - }; - xhr.send(); - timer = setTimeout(function() { - xhr.onprogress = xhr.onload = xhr.onabort = xhr.onerror = null; - downloadTask.abort(); - reject("timeout"); - }, timeout); - return downloadTask; -}, DownloadFileProtocol, DownloadFileOptions); -class UploadTask { - constructor(xhr) { - this._callbacks = []; - this._xhr = xhr; - } - onProgressUpdate(callback2) { - if (typeof callback2 !== "function") { - return; + setStyle(option) { + const div = this.div; + const divStyle = div.style; + div.innerText = option.content || ""; + divStyle.lineHeight = (option.fontSize || 14) + "px"; + divStyle.fontSize = (option.fontSize || 14) + "px"; + divStyle.padding = (option.padding || 8) + "px"; + divStyle.color = option.color || "#000"; + divStyle.borderRadius = (option.borderRadius || 0) + "px"; + divStyle.backgroundColor = option.bgColor || "#fff"; + divStyle.marginTop = "-" + ((option.top || 0) + 5) + "px"; + this.triangle.style.borderColor = `${option.bgColor || "#fff"} transparent transparent`; } - this._callbacks.push(callback2); - } - offProgressUpdate(callback2) { - const index2 = this._callbacks.indexOf(callback2); - if (index2 >= 0) { - this._callbacks.splice(index2, 1); + setPosition(position) { + this.position = position; + this.draw(); } - } - abort() { - this._isAbort = true; - if (this._xhr) { - this._xhr.abort(); - delete this._xhr; + draw() { + const overlayProjection = this.getProjection(); + if (!this.position || !this.div || !overlayProjection) { + return; + } + const pixel = overlayProjection.fromLatLngToDivPixel(this.position); + const divStyle = this.div.style; + divStyle.left = pixel.x + "px"; + divStyle.top = pixel.y + "px"; + } + changed() { + const divStyle = this.div.style; + divStyle.display = this.visible ? "block" : "none"; + } + destroy() { + const parentNode = this.div.parentNode; + if (parentNode) { + parentNode.removeChild(this.div); + } } } - onHeadersReceived(callback2) { - throw new Error("Method not implemented."); + return Callout; +} +let maps; +const callbacks = []; +const QQ_MAP_CALLBACKNAME = "__qq_map_callback__"; +function loadMaps(callback2) { + if (maps) { + callback2(maps); + } else if (window.qq && window.qq.maps) { + maps = window.qq.maps; + callback2(maps); + } else if (callbacks.length) { + callbacks.push(callback2); + } else { + callbacks.push(callback2); + const key = __uniConfig.qqMapKey; + const globalExt = window; + globalExt[QQ_MAP_CALLBACKNAME] = function() { + delete globalExt[QQ_MAP_CALLBACKNAME]; + maps = window.qq.maps; + maps.Callout = createCallout(maps); + callbacks.forEach((callback22) => callback22(maps)); + callbacks.length = 0; + }; + const script = document.createElement("script"); + script.src = `https://map.qq.com/api/js?v=2.exp&key=${key}&callback=${QQ_MAP_CALLBACKNAME}&libraries=geometry`; + document.body.appendChild(script); } - offHeadersReceived(callback2) { - throw new Error("Method not implemented."); +} +const props$4 = { + id: { + type: [Number, String], + default: "" + }, + latitude: { + type: [Number, String], + require: true + }, + longitude: { + type: [Number, String], + require: true + }, + title: { + type: String, + default: "" + }, + iconPath: { + type: String, + require: true + }, + rotate: { + type: [Number, String], + default: 0 + }, + alpha: { + type: [Number, String], + default: 1 + }, + width: { + type: [Number, String], + default: "" + }, + height: { + type: [Number, String], + default: "" + }, + callout: { + type: Object, + default: null + }, + label: { + type: Object, + default: null + }, + anchor: { + type: Object, + default: null + }, + clusterId: { + type: [Number, String], + default: "" + }, + customCallout: { + type: Object, + default: null + }, + ariaLabel: { + type: String, + default: "" } -} -const uploadFile = defineTaskApi(API_UPLOAD_FILE, ({ - url, - file, - filePath, - name, - files: files2, - header, - formData, - timeout = __uniConfig.networkTimeout.uploadFile -}, {resolve, reject}) => { - var uploadTask = new UploadTask(); - if (!Array.isArray(files2) || !files2.length) { - files2 = [ - { - name, - file, - uri: filePath +}; +var MapMarker = /* @__PURE__ */ vue.defineComponent({ + name: "MapMarker", + props: props$4, + setup(props2) { + const id = String(Number(props2.id) !== NaN ? props2.id : ""); + const onMapReady = vue.inject("onMapReady"); + let marker; + function removeMarker() { + if (marker) { + if (marker.label) { + marker.label.setMap(null); + } + if (marker.callout) { + marker.callout.setMap(null); + } + marker.setMap(null); } - ]; - } - function upload(realFiles) { - var xhr = new XMLHttpRequest(); - var form = new FormData(); - var timer; - Object.keys(formData).forEach((key) => { - form.append(key, formData[key]); - }); - Object.values(files2).forEach(({name: name2}, index2) => { - const file2 = realFiles[index2]; - form.append(name2 || "file", file2, file2.name || `file-${Date.now()}`); - }); - xhr.open("POST", url); - Object.keys(header).forEach((key) => { - xhr.setRequestHeader(key, header[key]); - }); - xhr.upload.onprogress = function(event) { - uploadTask._callbacks.forEach((callback2) => { - var totalBytesSent = event.loaded; - var totalBytesExpectedToSend = event.total; - var progress = Math.round(totalBytesSent / totalBytesExpectedToSend * 100); - callback2({ - progress, - totalBytesSent, - totalBytesExpectedToSend - }); - }); - }; - xhr.onerror = function() { - clearTimeout(timer); - reject(); - }; - xhr.onabort = function() { - clearTimeout(timer); - reject("abort"); - }; - xhr.onload = function() { - clearTimeout(timer); - const statusCode = xhr.status; - resolve({ - statusCode, - data: xhr.responseText || xhr.response - }); - }; - if (!uploadTask._isAbort) { - timer = setTimeout(function() { - xhr.upload.onprogress = xhr.onload = xhr.onabort = xhr.onerror = null; - uploadTask.abort(); - reject("timeout"); - }, timeout); - xhr.send(form); - uploadTask._xhr = xhr; - } else { - reject("abort"); } - } - Promise.all(files2.map(({file: file2, uri}) => file2 instanceof Blob ? Promise.resolve(blobToFile(file2)) : urlToFile(uri))).then(upload).catch(() => { - setTimeout(() => { - reject("file error"); - }, 0); - }); - return uploadTask; -}, UploadFileProtocol, UploadFileOptions); -const socketTasks = []; -const globalEvent = { - open: "", - close: "", - error: "", - message: "" -}; -class SocketTask { - constructor(url, protocols, callback2) { - this._callbacks = { - open: [], - close: [], - error: [], - message: [] - }; - let error; - try { - const webSocket = this._webSocket = new WebSocket(url, protocols); - webSocket.binaryType = "arraybuffer"; - const eventNames = ["open", "close", "error", "message"]; - eventNames.forEach((name) => { - this._callbacks[name] = []; - webSocket.addEventListener(name, (event) => { - const res = name === "message" ? { - data: event.data - } : {}; - this._callbacks[name].forEach((callback3) => { - try { - callback3(res); - } catch (e2) { - console.error(`thirdScriptError -${e2};at socketTask.on${shared.capitalize(name)} callback function -`, e2); - } - }); - if (this === socketTasks[0] && globalEvent[name]) { - UniServiceJSBridge.invokeOnCallback(globalEvent[name], res); + onMapReady((map, maps2, trigger) => { + function updateMarker(option) { + const title = option.title; + const position = new maps2.LatLng(option.latitude, option.longitude); + const img = new Image(); + img.onload = () => { + const anchor = option.anchor || {}; + let icon; + let w; + let h; + let top; + let x = anchor.x; + let y = anchor.y; + if (option.iconPath && (option.width || option.height)) { + w = option.width || img.width / img.height * option.height; + h = option.height || img.height / img.width * option.width; + } else { + w = img.width / 2; + h = img.height / 2; + } + x = (typeof x === "number" ? x : 0.5) * w; + y = (typeof y === "number" ? y : 1) * h; + top = h - (h - y); + icon = new maps2.MarkerImage(img.src, null, null, new maps2.Point(x, y), new maps2.Size(w, h)); + marker.setPosition(position); + marker.setIcon(icon); + marker.setRotation(option.rotate || 0); + const labelOpt = option.label || {}; + if (marker.label) { + marker.label.setMap(null); + delete marker.label; + } + let label; + if (labelOpt.content) { + label = new maps2.Label({ + position, + map, + clickable: false, + content: labelOpt.content, + style: { + border: "none", + padding: "8px", + background: "none", + color: labelOpt.color, + fontSize: (labelOpt.fontSize || 14) + "px", + lineHeight: (labelOpt.fontSize || 14) + "px", + marginLeft: labelOpt.x, + marginTop: labelOpt.y + } + }); + marker.label = label; } - if (name === "error" || name === "close") { - const index2 = socketTasks.indexOf(this); - if (index2 >= 0) { - socketTasks.splice(index2, 1); + const calloutOpt = option.callout || {}; + let callout = marker.callout; + let calloutStyle; + if (calloutOpt.content || title) { + calloutStyle = calloutOpt.content ? { + position, + map, + top, + content: calloutOpt.content, + color: calloutOpt.color, + fontSize: calloutOpt.fontSize, + borderRadius: calloutOpt.borderRadius, + bgColor: calloutOpt.bgColor, + padding: calloutOpt.padding, + boxShadow: calloutOpt.boxShadow, + display: calloutOpt.display + } : { + position, + map, + top, + content: title, + boxShadow: "0px 0px 3px 1px rgba(0,0,0,0.5)" + }; + if (callout) { + callout.setOption(calloutStyle); + } else { + callout = marker.callout = new maps2.Callout(calloutStyle); + callout.div.onclick = function($event) { + if (id !== "") { + trigger("callouttap", $event, { + markerId: Number(id) + }); + } + $event.stopPropagation(); + $event.preventDefault(); + }; + } + } else { + if (callout) { + callout.setMap(null); + delete marker.callout; } } + }; + img.src = getRealPath(option.iconPath); + } + function addMarker(props3) { + marker = new maps2.Marker({ + map, + flat: true, + autoRotation: false }); - }); - const propertys2 = [ - "CLOSED", - "CLOSING", - "CONNECTING", - "OPEN", - "readyState" - ]; - propertys2.forEach((property) => { - Object.defineProperty(this, property, { - get() { - return webSocket[property]; + updateMarker(props3); + maps2.event.addListener(marker, "click", () => { + const callout = marker.callout; + if (callout) { + const div = callout.div; + const parent = div.parentNode; + if (!callout.alwaysVisible) { + callout.set("visible", !callout.visible); + } + if (callout.visible) { + parent.removeChild(div); + parent.appendChild(div); + } + } + if (id) { + trigger("markertap", {}, { + markerId: Number(id) + }); } }); - }); - } catch (e2) { - error = e2; - } - callback2 && callback2(error, this); - } - send(options) { - const data = (options || {}).data; - const ws = this._webSocket; - try { - if (ws.readyState !== ws.OPEN) { - throw new Error("SocketTask.readyState is not OPEN"); - } - ws.send(data); - callback(options, "sendSocketMessage:ok"); - } catch (error) { - callback(options, `sendSocketMessage:fail ${error}`); - } - } - close(options = {}) { - const ws = this._webSocket; - try { - const code = options.code || 1e3; - const reason = options.reason; - if (typeof reason === "string") { - ws.close(code, reason); - } else { - ws.close(code); } - callback(options, "closeSocket:ok"); - } catch (error) { - callback(options, `closeSocket:fail ${error}`); - } - } - onOpen(callback2) { - this._callbacks.open.push(callback2); - } - onMessage(callback2) { - this._callbacks.message.push(callback2); - } - onError(callback2) { - this._callbacks.error.push(callback2); - } - onClose(callback2) { - this._callbacks.close.push(callback2); - } -} -const connectSocket = defineTaskApi(API_CONNECT_SOCKET, ({url, protocols}, {resolve, reject}) => { - return new SocketTask(url, protocols, (error, socketTask) => { - if (error) { - reject(error.toString()); - return; - } - socketTasks.push(socketTask); - resolve(); - }); -}, ConnectSocketProtocol, ConnectSocketOptions); -function callSocketTask(socketTask, method, option, resolve, reject) { - const fn = socketTask[method]; - if (typeof fn === "function") { - fn.call(socketTask, Object.assign({}, option, { - success() { - resolve(); - }, - fail({errMsg}) { - reject(errMsg.replace("sendSocketMessage:fail ", "")); - }, - complete: void 0 - })); - } -} -const sendSocketMessage = defineAsyncApi(API_SEND_SOCKET_MESSAGE, (options, {resolve, reject}) => { - const socketTask = socketTasks[0]; - if (socketTask && socketTask.readyState === socketTask.OPEN) { - callSocketTask(socketTask, "send", options, resolve, reject); - } else { - reject("WebSocket is not connected"); - } -}, SendSocketMessageProtocol); -const closeSocket = defineAsyncApi(API_CLOSE_SOCKET, (options, {resolve, reject}) => { - const socketTask = socketTasks[0]; - if (socketTask) { - callSocketTask(socketTask, "send", options, resolve, reject); - } else { - reject("WebSocket is not connected"); - } -}, CloseSocketProtocol); -function on(event) { - const api2 = `onSocket${shared.capitalize(event)}`; - return defineOnApi(api2, () => { - globalEvent[event] = api2; - }); -} -const onSocketOpen = /* @__PURE__ */ on("open"); -const onSocketError = /* @__PURE__ */ on("error"); -const onSocketMessage = /* @__PURE__ */ on("message"); -const onSocketClose = /* @__PURE__ */ on("close"); -function getJSONP(url, options, success, error) { - var js = document.createElement("script"); - var callbackKey = options.callback || "callback"; - var callbackName = "__callback" + Date.now(); - var timeout = options.timeout || 3e4; - var timing; - function end() { - clearTimeout(timing); - delete window[callbackName]; - js.remove(); - } - window[callbackName] = (res) => { - if (typeof success === "function") { - success(res); - } - end(); - }; - js.onerror = () => { - if (typeof error === "function") { - error(); - } - end(); - }; - timing = setTimeout(function() { - if (typeof error === "function") { - error(); - } - end(); - }, timeout); - js.src = url + (url.indexOf("?") >= 0 ? "&" : "?") + callbackKey + "=" + callbackName; - document.body.appendChild(js); -} -const getLocation = defineAsyncApi(API_GET_LOCATION, ({type, altitude}, {resolve, reject}) => { - const key = __uniConfig.qqMapKey; - new Promise((resolve2, reject2) => { - if (navigator.geolocation) { - navigator.geolocation.getCurrentPosition((res) => resolve2(res.coords), reject2, { - enableHighAccuracy: altitude, - timeout: 1e3 * 100 - }); - } else { - reject2(new Error("device nonsupport geolocation")); - } - }).catch(() => { - return new Promise((resolve2, reject2) => { - getJSONP(`https://apis.map.qq.com/ws/location/v1/ip?output=jsonp&key=${key}`, { - callback: "callback" - }, (res) => { - if ("result" in res && res.result.location) { - const location2 = res.result.location; - resolve2({ - latitude: location2.lat, - longitude: location2.lng - }, true); - } else { - reject2(new Error(res.message || JSON.stringify(res))); - } - }, () => reject2(new Error("network error"))); + addMarker(props2); + vue.watch(props2, updateMarker); }); - }).then((coords, skip) => { - if (type && type.toUpperCase() === "WGS84" || skip) { - return coords; - } - return new Promise((resolve2) => { - getJSONP(`https://apis.map.qq.com/jsapi?qt=translate&type=1&points=${coords.longitude},${coords.latitude}&key=${key}&output=jsonp&pf=jsapi&ref=jsapi`, { - callback: "cb" - }, (res) => { - if ("detail" in res && "points" in res.detail && res.detail.points.length) { - const location2 = res.detail.points[0]; - resolve2(Object.assign({}, coords, { - longitude: location2.lng, - latitude: location2.lat - })); - } else { - resolve2(coords); + if (id) { + const addMapChidlContext = vue.inject("addMapChidlContext"); + const removeMapChidlContext = vue.inject("removeMapChidlContext"); + const context = { + id, + translate(data) { + onMapReady((map, maps2, trigger) => { + const destination = data.destination; + const duration = data.duration; + const autoRotate = !!data.autoRotate; + let rotate = Number(data.rotate) || 0; + const rotation = marker.getRotation(); + const a2 = marker.getPosition(); + const b = new maps2.LatLng(destination.latitude, destination.longitude); + const distance = maps2.geometry.spherical.computeDistanceBetween(a2, b) / 1e3; + const time = (typeof duration === "number" ? duration : 1e3) / (1e3 * 60 * 60); + const speed = distance / time; + const movingEvent = maps2.event.addListener(marker, "moving", (e2) => { + const latLng = e2.latLng; + const label = marker.label; + if (label) { + label.setPosition(latLng); + } + const callout = marker.callout; + if (callout) { + callout.setPosition(latLng); + } + }); + const event = maps2.event.addListener(marker, "moveend", () => { + event.remove(); + movingEvent.remove(); + marker.lastPosition = a2; + marker.setPosition(b); + const label = marker.label; + if (label) { + label.setPosition(b); + } + const callout = marker.callout; + if (callout) { + callout.setPosition(b); + } + const cb = data.animationEnd; + if (typeof cb === "function") { + cb(); + } + }); + let lastRtate = 0; + if (autoRotate) { + if (marker.lastPosition) { + lastRtate = maps2.geometry.spherical.computeHeading(marker.lastPosition, a2); + } + rotate = maps2.geometry.spherical.computeHeading(a2, b) - lastRtate; + } + marker.setRotation(rotation + rotate); + marker.moveTo(b, speed); + }); } - }, () => resolve2(coords)); - }); - }).then((coords) => { - resolve(Object.assign({}, coords, { - speed: coords.altitude || 0, - altitude: coords.altitude || 0, - verticalAccuracy: coords.altitudeAccuracy || 0, - horizontalAccuracy: coords.accuracy || 0 - })); - }).catch((error) => { - reject(error.message); - }); -}, GetLocationProtocol, GetLocationOptions); -const navigateBack = defineAsyncApi(API_NAVIGATE_BACK, ({delta}, {resolve, reject}) => { - let canBack = true; - if (invokeHook("onBackPress") === true) { - canBack = false; - } - if (!canBack) { - return reject("onBackPress"); - } - getApp().$router.go(-delta); - return resolve(); -}, NavigateBackProtocol, NavigateBackOptions); -function navigate(type, url, __id__) { - const router = getApp().$router; - return new Promise((resolve, reject) => { - router[type === "navigateTo" ? "push" : "replace"]({ - path: url, - force: true, - state: createPageState(type, __id__) - }).then((failure) => { - if (vueRouter.isNavigationFailure(failure)) { - return reject(failure.message); - } - return resolve(void 0); - }); - }); -} -const navigateTo = defineAsyncApi(API_NAVIGATE_TO, ({url}, {resolve, reject}) => navigate(API_NAVIGATE_TO, url).then(resolve).catch(reject), NavigateToProtocol, NavigateToOptions); -function removeLastPage() { - const page = getCurrentPage(); - if (!page) { - return; - } - const $page = page.$page; - removePage(normalizeRouteKey($page.path, $page.id)); -} -const redirectTo = defineAsyncApi(API_REDIRECT_TO, ({url}, {resolve, reject}) => { - return removeLastPage(), navigate(API_REDIRECT_TO, url).then(resolve).catch(reject); -}, RedirectToProtocol, RedirectToOptions); -function removeAllPages() { - const keys = getCurrentPagesMap().keys(); - for (const routeKey of keys) { - removePage(routeKey); - } -} -const reLaunch = defineAsyncApi(API_RE_LAUNCH, ({url}, {resolve, reject}) => { - return removeAllPages(), navigate(API_RE_LAUNCH, url).then(resolve).catch(reject); -}, ReLaunchProtocol, ReLaunchOptions); -function removeNonTabBarPages() { - const curTabBarPageVm = getCurrentPageVm(); - if (!curTabBarPageVm) { - return; - } - const pagesMap = getCurrentPagesMap(); - const keys = pagesMap.keys(); - for (const routeKey of keys) { - const page = pagesMap.get(routeKey); - if (!page.__isTabBar) { - removePage(routeKey); - } else { - page.$.__isActive = false; - } - } - if (curTabBarPageVm.__isTabBar) { - curTabBarPageVm.$.__isVisible = false; - invokeHook(curTabBarPageVm, "onHide"); - } -} -function getTabBarPageId(url) { - const pages = getCurrentPagesMap().values(); - for (const page of pages) { - const $page = page.$page; - if ($page.path === url) { - page.$.__isActive = true; - return $page.id; - } - } -} -const switchTab = defineAsyncApi(API_SWITCH_TAB, ({url}, {resolve, reject}) => { - return removeNonTabBarPages(), navigate(API_SWITCH_TAB, url, getTabBarPageId(url)).then(resolve).catch(reject); -}, SwitchTabProtocol, SwitchTabOptions); -const KEY_MAPS = { - esc: ["Esc", "Escape"], - enter: ["Enter"] -}; -const KEYS = Object.keys(KEY_MAPS); -function useKeyboard() { - const key = vue.ref(""); - const disable = vue.ref(false); - const onKeyup = (evt) => { - if (disable.value) { - return; - } - const res = KEYS.find((key2) => KEY_MAPS[key2].indexOf(evt.key) !== -1); - if (res) { - key.value = res; - } - }; - vue.onMounted(() => { - document.addEventListener("keyup", onKeyup); - }); - vue.onBeforeUnmount(() => { - document.removeEventListener("keyup", onKeyup); - }); - return { - key, - disable - }; -} -const VNODE_MASK = /* @__PURE__ */ vue.createVNode("div", {class: "uni-mask"}, null, -1); -function createRootApp(component, rootState, callback2) { - const onClose = (...args) => (rootState.visible = false, callback2.apply(null, args)); - return vue.createApp(vue.defineComponent({ - setup() { - return () => (vue.openBlock(), vue.createBlock(component, vue.mergeProps({ - onClose - }, rootState))); + }; + addMapChidlContext(context); + vue.onUnmounted(() => removeMapChidlContext(context)); } - })); -} -function ensureRoot(id2) { - let rootEl = document.getElementById(id2); - if (!rootEl) { - rootEl = document.createElement("div"); - rootEl.id = id2; - document.body.append(rootEl); + vue.onUnmounted(removeMarker); + return () => { + return null; + }; } - return rootEl; -} -function usePopup(props2, { - onEsc, - onEnter -}) { - const visible = vue.ref(props2.visible); - const {key, disable} = useKeyboard(); - vue.watch(() => props2.visible, (value) => visible.value = value); - vue.watch(() => visible.value, (value) => disable.value = !value); - vue.watchEffect(() => { - const {value} = key; - if (value === "esc") { - onEsc && onEsc(); - } else if (value === "enter") { - onEnter && onEnter(); - } - }); - return visible; -} -const props$2 = { - title: { - type: String, - default: "" +}); +const props$3 = { + points: { + type: Array, + require: true }, - content: { + color: { type: String, + default: "#000000" + }, + width: { + type: [Number, String], default: "" }, - showCancel: { - type: Boolean, - default: true + dottedLine: { + type: [Boolean, String], + default: false + }, + arrowLine: { + type: [Boolean, String], + default: false }, - cancelText: { + arrowIconPath: { type: String, - default: "Cancel" + default: "" }, - cancelColor: { + borderColor: { type: String, default: "#000000" }, - confirmText: { - type: String, - default: "OK" + borderWidth: { + type: [Number, String], + default: "" }, - confirmColor: { - type: String, - default: "#007aff" + colorList: { + type: Array, + default() { + return []; + } }, - visible: { - type: Boolean + level: { + type: String, + default: "" } }; -var modal = /* @__PURE__ */ vue.defineComponent({ - props: props$2, - setup(props2, { - emit: emit2 - }) { - const close = () => visible.value = false; - const cancel = () => (close(), emit2("close", "cancel")); - const confirm = () => (close(), emit2("close", "confirm")); - const visible = usePopup(props2, { - onEsc: cancel, - onEnter: confirm +var MapPolyline = /* @__PURE__ */ vue.defineComponent({ + name: "MapPolyline", + props: props$3, + setup(props2) { + const onMapReady = vue.inject("onMapReady"); + let polyline; + let polylineBorder; + function removePolyline() { + if (polyline) { + polyline.setMap(null); + } + if (polylineBorder) { + polylineBorder.setMap(null); + } + } + onMapReady((map, maps2) => { + function updatePolyline(option) { + removePolyline(); + addPolyline(option); + } + function addPolyline(option) { + const path = []; + option.points.forEach((point) => { + path.push(new maps2.LatLng(point.latitude, point.longitude)); + }); + const strokeWeight = Number(option.width) || 1; + polyline = new maps2.Polyline({ + map, + clickable: false, + path, + strokeWeight, + strokeColor: option.color || void 0, + strokeDashStyle: option.dottedLine ? "dash" : "solid" + }); + const borderWidth = Number(option.borderWidth) || 0; + if (borderWidth) { + polylineBorder = new maps2.Polyline({ + map, + clickable: false, + path, + strokeWeight: strokeWeight + borderWidth * 2, + strokeColor: option.borderColor || void 0, + strokeDashStyle: option.dottedLine ? "dash" : "solid" + }); + } + } + addPolyline(props2); + vue.watch(props2, updatePolyline); }); + vue.onUnmounted(removePolyline); return () => { - const { - title, - content, - showCancel, - confirmText, - confirmColor - } = props2; - return vue.createVNode(vue.Transition, { - name: "uni-fade" - }, { - default: () => [vue.withDirectives(vue.createVNode("uni-modal", { - onTouchmove: onEventPrevent - }, [VNODE_MASK, vue.createVNode("div", { - class: "uni-modal" - }, [title && vue.createVNode("div", { - class: "uni-modal__hd" - }, [vue.createVNode("strong", { - class: "uni-modal__title", - textContent: title - }, null, 8, ["textContent"])]), vue.createVNode("div", { - class: "uni-modal__bd", - onTouchmovePassive: onEventStop, - textContent: content - }, null, 40, ["onTouchmovePassive", "textContent"]), vue.createVNode("div", { - class: "uni-modal__ft" - }, [showCancel && vue.createVNode("div", { - style: { - color: props2.cancelColor - }, - class: "uni-modal__btn uni-modal__btn_default", - onClick: cancel - }, [props2.cancelText], 12, ["onClick"]), vue.createVNode("div", { - style: { - color: confirmColor - }, - class: "uni-modal__btn uni-modal__btn_primary", - onClick: confirm - }, [confirmText], 12, ["onClick"])])])], 40, ["onTouchmove"]), [[vue.vShow, visible.value]])] - }); + return null; }; } }); -let showModalState; -let currentShowModalResolve; -function onModalClose(type) { - currentShowModalResolve && currentShowModalResolve({ - confirm: type === "confirm", - cancel: type === "cancel" - }); -} -const showModal = defineAsyncApi(API_SHOW_MODAL, (args, {resolve}) => { - currentShowModalResolve = resolve; - if (!showModalState) { - showModalState = vue.reactive(args); - vue.nextTick(() => (createRootApp(modal, showModalState, onModalClose).mount(ensureRoot("u-a-m")), vue.nextTick(() => showModalState.visible = true))); - } else { - shared.extend(showModalState, args); - showModalState.visible = true; - } -}, ShowModalProtocol, ShowModalOptions); -const props$1 = { - title: { +const props$2 = { + latitude: { + type: [Number, String], + require: true + }, + longitude: { + type: [Number, String], + require: true + }, + color: { type: String, default: "" }, - icon: { - default: "success", - validator(value) { - return SHOW_TOAST_ICON.indexOf(value) !== -1; - } - }, - image: { + fillColor: { type: String, default: "" }, - duration: { - type: Number, - default: 1500 + radius: { + type: [Number, String], + require: true }, - mask: { - type: Boolean, - default: false + strokeWidth: { + type: [Number, String], + default: "" }, - visible: { - type: Boolean + level: { + type: String, + default: "" } }; -const ToastIconClassName = "uni-toast__icon"; -var Toast = /* @__PURE__ */ vue.defineComponent({ - name: "Toast", - props: props$1, +var MapCircle = /* @__PURE__ */ vue.defineComponent({ + name: "MapCircle", + props: props$2, setup(props2) { - initI18nShowToastMsgsOnce(); - initI18nShowLoadingMsgsOnce(); - const { - Icon - } = useToastIcon(props2); - const visible = usePopup(props2, {}); + const onMapReady = vue.inject("onMapReady"); + let circle; + function removeCircle() { + if (circle) { + circle.setMap(null); + } + } + onMapReady((map, maps2) => { + function updateCircle(option) { + removeCircle(); + addCircle(option); + } + function addCircle(option) { + const center = new maps2.LatLng(option.latitude, option.longitude); + function getColor(color) { + const c = color.match(/#[0-9A-Fa-f]{6}([0-9A-Fa-f]{2})?/); + if (c && c.length) { + return maps2.Color.fromHex(c[0], Number("0x" + c[1] || 255) / 255); + } else { + return void 0; + } + } + circle = new maps2.Circle({ + map, + center, + clickable: false, + radius: option.radius, + strokeWeight: Number(option.strokeWidth) || 1, + fillColor: getColor(option.fillColor) || getColor("#00000001"), + strokeColor: getColor(option.color) || "#000000", + strokeDashStyle: "solid" + }); + } + addCircle(props2); + vue.watch(props2, updateCircle); + }); + vue.onUnmounted(removeCircle); return () => { - const { - mask, - duration, - title, - image: image2 - } = props2; - return vue.createVNode(vue.Transition, { - name: "uni-fade" - }, { - default: () => [vue.withDirectives(vue.createVNode("uni-toast", { - "data-duration": duration - }, [mask ? vue.createVNode("div", { - class: "uni-mask", - style: "background: transparent;", - onTouchmove: onEventPrevent - }, null, 40, ["onTouchmove"]) : "", !image2 && !Icon.value ? vue.createVNode("div", { - class: "uni-sample-toast" - }, [vue.createVNode("p", { - class: "uni-simple-toast__text" - }, [title])]) : vue.createVNode("div", { - class: "uni-toast" - }, [image2 ? vue.createVNode("img", { - src: image2, - class: ToastIconClassName - }, null, 10, ["src"]) : Icon.value, vue.createVNode("p", { - class: "uni-toast__content" - }, [title])])], 8, ["data-duration"]), [[vue.vShow, visible.value]])] - }); + return null; }; } }); -function useToastIcon(props2) { - const Icon = vue.computed(() => props2.icon === "success" ? vue.createVNode(createSvgIconVNode(ICON_PATH_SUCCESS_NO_CIRCLE, "#fff", 38), { - class: ToastIconClassName - }) : props2.icon === "loading" ? vue.createVNode("i", { - class: [ToastIconClassName, "uni-loading"] - }, null, 2) : null); - return { - Icon - }; -} -let showToastState; -let showType = ""; -let timeoutId; -const onHidePopupOnce = /* @__PURE__ */ uniShared.once(() => { - UniServiceJSBridge.on("onHidePopup", () => hidePopup("onHidePopup")); -}); -function createToast(args) { - if (!showToastState) { - showToastState = vue.reactive(args); - vue.nextTick(() => { - createRootApp(Toast, showToastState, () => { - }).mount(ensureRoot("u-a-t")); - }); - } else { - shared.extend(showToastState, args); +const props$1 = { + id: { + type: [Number, String], + default: "" + }, + position: { + type: Object, + require: true + }, + iconPath: { + type: String, + require: true + }, + clickable: { + type: [Boolean, String], + default: "" } - setTimeout(() => { - showToastState.visible = true; - }, 10); - vue.watchEffect(() => { - if (showToastState.visible) { - timeoutId && clearTimeout(timeoutId); - timeoutId = setTimeout(() => { - hidePopup("onHideToast"); - }, showToastState.duration); - } else { - timeoutId && clearTimeout(timeoutId); - } - }); - onHidePopupOnce(); -} -const showToast = defineAsyncApi(API_SHOW_TOAST, (args, {resolve, reject}) => { - createToast(args); - showType = "onShowToast"; - resolve(); -}, ShowToastProtocol, ShowToastOptions); -const showLoadingDefaultState = { - icon: "loading", - duration: 1e8, - image: "" }; -const showLoading = defineAsyncApi(API_SHOW_LOADING, (args, {resolve, reject}) => { - shared.extend(args, showLoadingDefaultState); - createToast(args); - showType = "onShowLoading"; - resolve(); -}, ShowLoadingProtocol, ShowLoadingOptions); -const hideToast = defineAsyncApi(API_HIDE_TOAST, (args, {resolve, reject}) => { - hidePopup("onHideToast"); - resolve(); -}); -const hideLoading = defineAsyncApi(API_HIDE_LOADING, (args, {resolve, reject}) => { - hidePopup("onHideLoading"); - resolve(); -}); -function hidePopup(type) { - const {t: t2} = useI18n(); - if (!showType) { - return; - } - let warnMsg = ""; - if (type === "onHideToast" && showType !== "onShowToast") { - warnMsg = t2("uni.showToast.unpaired"); - } else if (type === "onHideLoading" && showType !== "onShowLoading") { - warnMsg = t2("uni.showLoading.unpaired"); - } - if (warnMsg) { - return console.warn(warnMsg); - } - showType = ""; - setTimeout(() => { - showToastState.visible = false; - }, 10); -} -const loadFontFace = defineAsyncApi(API_LOAD_FONT_FACE, ({family, source, desc}, {resolve, reject}) => { - uniShared.addFont(family, source, desc).then(() => { - resolve(); - }).catch((err) => { - reject(`loadFontFace:fail ${err}`); - }); -}, LoadFontFaceProtocol); -function setNavigationBar(pageMeta, type, args, resolve, reject) { - if (!pageMeta) { - return reject("page not found"); - } - const {navigationBar} = pageMeta; - switch (type) { - case API_SET_NAVIGATION_BAR_COLOR: - const {frontColor, backgroundColor, animation} = args; - const {duration, timingFunc} = animation; - if (frontColor) { - navigationBar.titleColor = frontColor === "#000000" ? "#000" : "#fff"; - } - if (backgroundColor) { - navigationBar.backgroundColor = backgroundColor; - } - navigationBar.duration = duration + "ms"; - navigationBar.timingFunc = timingFunc; - break; - case API_SHOW_NAVIGATION_BAR_LOADING: - navigationBar.loading = true; - break; - case API_HIDE_NAVIGATION_BAR_LOADING: - navigationBar.loading = false; - break; - case API_SET_NAVIGATION_BAR_TITLE: - const {title} = args; - navigationBar.titleText = title; - break; - } - resolve(); -} -const setNavigationBarColor = defineAsyncApi(API_SET_NAVIGATION_BAR_COLOR, (args, {resolve, reject}) => { - setNavigationBar(getCurrentPageMeta(), API_SET_NAVIGATION_BAR_COLOR, args, resolve, reject); -}, SetNavigationBarColorProtocol, SetNavigationBarColorOptions); -const showNavigationBarLoading = defineAsyncApi(API_SHOW_NAVIGATION_BAR_LOADING, (args, {resolve, reject}) => { - setNavigationBar(getCurrentPageMeta(), API_SHOW_NAVIGATION_BAR_LOADING, args, resolve, reject); -}); -const hideNavigationBarLoading = defineAsyncApi(API_HIDE_NAVIGATION_BAR_LOADING, (args, {resolve, reject}) => { - setNavigationBar(getCurrentPageMeta(), API_HIDE_NAVIGATION_BAR_LOADING, args, resolve, reject); -}); -const setNavigationBarTitle = defineAsyncApi(API_SET_NAVIGATION_BAR_TITLE, (args, {resolve, reject}) => { - setNavigationBar(getCurrentPageMeta(), API_SET_NAVIGATION_BAR_TITLE, args, resolve, reject); -}, SetNavigationBarTitleProtocol); -const pageScrollTo = defineAsyncApi(API_PAGE_SCROLL_TO, ({scrollTop, selector, duration}, {resolve}) => { - uniShared.scrollTo(selector || scrollTop || 0, duration); - resolve(); -}, PageScrollToProtocol, PageScrollToOptions); -const startPullDownRefresh = defineAsyncApi(API_START_PULL_DOWN_REFRESH, (_args, {resolve}) => { - UniServiceJSBridge.publishHandler(API_START_PULL_DOWN_REFRESH, {}, getCurrentPageId()); - resolve(); -}); -const stopPullDownRefresh = defineAsyncApi(API_STOP_PULL_DOWN_REFRESH, (_args, {resolve}) => { - UniServiceJSBridge.publishHandler(API_STOP_PULL_DOWN_REFRESH, {}, getCurrentPageId()); - resolve(); -}); -const setTabBarItemProps = ["text", "iconPath", "selectedIconPath"]; -const setTabBarStyleProps = [ - "color", - "selectedColor", - "backgroundColor", - "borderStyle" -]; -const setTabBarBadgeProps = ["badge", "redDot"]; -function setProperties(item, props2, propsData) { - props2.forEach(function(name) { - if (shared.hasOwn(propsData, name)) { - item[name] = propsData[name]; +var MapControl = /* @__PURE__ */ vue.defineComponent({ + name: "MapControl", + props: props$1, + setup(props2) { + const onMapReady = vue.inject("onMapReady"); + let control; + function removeControl() { + if (control) { + control.remove(); + } } - }); -} -function normalizeRoute(index2, oldPagePath, newPagePath) { - const oldTabBarRoute = __uniRoutes.find((item) => item.meta.route === oldPagePath); - if (oldTabBarRoute) { - const {meta} = oldTabBarRoute; - delete meta.tabBarIndex; - meta.isQuit = meta.isTabBar = false; - } - const newTabBarRoute = __uniRoutes.find((item) => item.meta.route === newPagePath); - if (newTabBarRoute) { - const {meta} = newTabBarRoute; - meta.tabBarIndex = index2; - meta.isQuit = meta.isTabBar = false; + onMapReady((map, maps2, trigger) => { + function updateControl(option) { + removeControl(); + addControl(option); + } + function addControl(option) { + const position = option.position || {}; + control = document.createElement("div"); + const img = new Image(); + control.appendChild(img); + const style = control.style; + style.position = "absolute"; + style.width = "0"; + style.height = "0"; + img.onload = () => { + if (option.position.width) { + img.width = option.position.width; + } + if (option.position.height) { + img.height = option.position.height; + } + const style2 = img.style; + style2.position = "absolute"; + style2.left = (position.left || 0) + "px"; + style2.top = (position.top || 0) + "px"; + style2.maxWidth = "initial"; + }; + img.src = getRealPath(option.iconPath); + img.onclick = function($event) { + if (option.clickable) { + trigger("controltap", $event, { + controlId: option.id + }); + } + }; + map.controls[maps2.ControlPosition.TOP_LEFT].push(control); + } + addControl(props2); + vue.watch(props2, updateControl); + }); + vue.onUnmounted(removeControl); + return () => { + return null; + }; } -} -function setTabBar(type, args, resolve) { - const tabBar2 = useTabBar(); - switch (type) { - case API_SHOW_TAB_BAR: - tabBar2.shown = true; - break; - case API_HIDE_TAB_BAR: - tabBar2.shown = false; - break; - case API_SET_TAB_BAR_ITEM: - const {index: index2} = args; - const tabBarItem = tabBar2.list[index2]; - const oldPagePath = tabBarItem.pagePath; - setProperties(tabBarItem, setTabBarItemProps, args); - const {pagePath} = args; - if (pagePath && pagePath !== oldPagePath) { - normalizeRoute(index2, oldPagePath, pagePath); - } - break; - case API_SET_TAB_BAR_STYLE: - setProperties(tabBar2, setTabBarStyleProps, args); - break; - case API_SHOW_TAB_BAR_RED_DOT: - setProperties(tabBar2.list[args.index], setTabBarBadgeProps, { - badge: "", - redDot: true - }); - break; - case API_SET_TAB_BAR_BADGE: - setProperties(tabBar2.list[args.index], setTabBarBadgeProps, { - badge: args.text, - redDot: true - }); - break; - case API_HIDE_TAB_BAR_RED_DOT: - case API_REMOVE_TAB_BAR_BADGE: - setProperties(tabBar2.list[args.index], setTabBarBadgeProps, { - badge: "", - redDot: false - }); - break; - } - resolve(); -} -const setTabBarItem = defineAsyncApi(API_SET_TAB_BAR_ITEM, (args, {resolve}) => { - setTabBar(API_SET_TAB_BAR_ITEM, args, resolve); -}, SetTabBarItemProtocol, SetTabBarItemOptions); -const setTabBarStyle = defineAsyncApi(API_SET_TAB_BAR_STYLE, (args, {resolve}) => { - setTabBar(API_SET_TAB_BAR_STYLE, args, resolve); -}, SetTabBarStyleProtocol, SetTabBarStyleOptions); -const hideTabBar = defineAsyncApi(API_HIDE_TAB_BAR, (args, {resolve}) => { - setTabBar(API_HIDE_TAB_BAR, args, resolve); -}, HideTabBarProtocol); -const showTabBar = defineAsyncApi(API_SHOW_TAB_BAR, (args, {resolve}) => { - setTabBar(API_SHOW_TAB_BAR, args, resolve); -}, ShowTabBarProtocol); -const hideTabBarRedDot = defineAsyncApi(API_HIDE_TAB_BAR_RED_DOT, (args, {resolve}) => { - setTabBar(API_HIDE_TAB_BAR_RED_DOT, args, resolve); -}, HideTabBarRedDotProtocol, HideTabBarRedDotOptions); -const showTabBarRedDot = defineAsyncApi(API_SHOW_TAB_BAR_RED_DOT, (args, {resolve}) => { - setTabBar(API_SHOW_TAB_BAR_RED_DOT, args, resolve); -}, ShowTabBarRedDotProtocol, ShowTabBarRedDotOptions); -const removeTabBarBadge = defineAsyncApi(API_REMOVE_TAB_BAR_BADGE, (args, {resolve}) => { - setTabBar(API_REMOVE_TAB_BAR_BADGE, args, resolve); -}, RemoveTabBarBadgeProtocol, RemoveTabBarBadgeOptions); -const setTabBarBadge = defineAsyncApi(API_SET_TAB_BAR_BADGE, (args, {resolve}) => { - setTabBar(API_SET_TAB_BAR_BADGE, args, resolve); -}, SetTabBarBadgeProtocol, SetTabBarBadgeOptions); -var api = /* @__PURE__ */ Object.freeze({ - __proto__: null, - [Symbol.toStringTag]: "Module", - upx2px, - addInterceptor, - removeInterceptor, - promiseInterceptor, - arrayBufferToBase64, - base64ToArrayBuffer, - createIntersectionObserver, - createSelectorQuery, - createVideoContext, - createMapContext, - onTabBarMidButtonTap, - cssVar, - cssEnv, - cssConstant, - cssBackdropFilter, - canIUse, - createInnerAudioContext, - makePhoneCall, - getSystemInfo, - getSystemInfoSync, - onNetworkStatusChange, - offNetworkStatusChange, - getNetworkType, - onAccelerometerChange, - offAccelerometerChange, - startAccelerometer, - stopAccelerometer, - onCompassChange, - offCompassChange, - startCompass, - stopCompass, - vibrateShort, - vibrateLong, - setStorageSync, - setStorage, - getStorageSync, - getStorage, - removeStorageSync, - removeStorage, - clearStorageSync, - clearStorage, - getStorageInfoSync, - getStorageInfo, - getFileInfo, - openDocument, - hideKeyboard, - getImageInfo, - getVideoInfo, - chooseFile, - chooseImage, - chooseVideo, - request, - downloadFile, - uploadFile, - connectSocket, - sendSocketMessage, - closeSocket, - onSocketOpen, - onSocketError, - onSocketMessage, - onSocketClose, - getLocation, - navigateBack, - navigateTo, - redirectTo, - reLaunch, - switchTab, - showModal, - showToast, - showLoading, - hideToast, - hideLoading, - loadFontFace, - setNavigationBarColor, - showNavigationBarLoading, - hideNavigationBarLoading, - setNavigationBarTitle, - pageScrollTo, - startPullDownRefresh, - stopPullDownRefresh, - setTabBarItem, - setTabBarStyle, - hideTabBar, - showTabBar, - hideTabBarRedDot, - showTabBarRedDot, - removeTabBarBadge, - setTabBarBadge }); const CONTEXT_ID = "MAP_LOCATION"; const ICON_PATH = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIQAAACECAMAAABmmnOVAAAC01BMVEUAAAAAef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef8Aef96quGStdqStdpbnujMzMzCyM7Gyc7Ky83MzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMwAef8GfP0yjfNWnOp0qOKKsdyYt9mju9aZt9mMstx1qeJYnekyjvIIfP0qivVmouaWttnMzMyat9lppOUujPQKffxhoOfNzc3Y2Njh4eHp6enu7u7y8vL19fXv7+/i4uLZ2dnOzs6auNgOf/sKff15quHR0dHx8fH9/f3////j4+N6quFdn+iywdPb29vw8PD+/v7c3NyywtLa2tr29vbS0tLd3d38/Pzf39/o6Ojc7f+q0v+HwP9rsf9dqv9Hnv9Vpv/q6urj8P+Vx/9Am/8Pgf8Iff/z8/OAvP95uf/n5+c5l//V6f+52v+y1//7+/vt7e0rkP/09PTQ0NDq9P8Whf+cy//W1tbe3t7A3v/m5ubs7OxOov/r6+vk5OQiaPjKAAAAknRSTlMACBZ9oB71/jiqywJBZATT6hBukRXv+zDCAVrkDIf4JbQsTb7eVeJLbwfa8Rh4G/OlPS/6/kxQ9/xdmZudoJxNVhng7B6wtWdzAtQOipcF1329wS44doK/BAkyP1pvgZOsrbnGXArAg34G2IsD1eMRe7bi7k5YnqFT9V0csyPedQyYD3p/Fje+hDpskq/MwpRBC6yKp2MAAAQdSURBVHja7Zn1exMxGIAPHbrhDsPdneHuNtzd3d3dIbjLh93o2o4i7TpgG1Jk0g0mMNwd/gTa5rq129reHnK5e/bk/TFNk/dJ7r5894XjGAwGg8GgTZasCpDIll1+hxw5vXLJLpEboTx5ZXbIhyzkl9fB28cqUaCgrBKFkI3CcjoUKYolihWXUSI7EihRUjaHXF52CVRKLoe8eZIdUOkyMknkRw6UlcehYAFHiXK+skgURk6Ul8OhQjFnCVRRBolKqRxQ5SzUHaqgNGSj7VCmalqJnDkoS5RF6ZCbroNvufQkUD6qEuXTdUA+3hQdqiEXVKfnUKOmK4latalJ1EEuoZZ6162HJ9x/4OChw0eOHj12/MTJU6dxG7XUu751tjNnz4ET5y9ctLZTSr0beKFLl89bpuUDrqgC1RqNWqsKuqqzNFw7e51S6u3tc+OmZUJ9kCHY6ECwOkRvab51iUrqXej2HYDQsHBjWgx3Ae7dppB6N2wEcF9jdMGDUIDGTaR2aNoM9FqjG7QmaN5CWgc/gIePjG559BigpZQOrYB/4jBfRGRUtDkmJjY6KjLCofkpD62lc2gDfMpWPIuLdwyV8XEpHgaddBZ+wBuSFcwJqSN2ovmZ/dfnOvCTxqGtwzq8SEjv4EhISn48eWgnhUP7DvDSvgzxrs6vV6+FLiro2EkCic4QKkzwJsH1KYreCp0eQhfyDl1B/w4P/xa5JVJ4U03QjbRD9x7wXlgH5IE3wmMBHXoSlugFAcI6f/AkkSi8q6HQm6xDn77wEQ8djTwSj3tqAMguRTe4ikeOQyJ4YV+KfkQl+oNW5GbY4gWOWgbwJ+kwAD6Fi90MK2ZsrIeBBCUGwRXbqJ+/iJMQliIEBhOU6AJhtlG/IpHE2bqrYQg5h6HA4yQiRqwEfkGCdTCMmMRw+IbPDCQaHCsCYAQxiZHw3TbmD/ESOHgHwShiEqPhp/gggYkSztIxxCRawy/bmEniJaJtfwiEscQkxkFgRqJESqQwwHhiEuMBp3Vm8RK/cZoHEzKXhCK2QxEPpiJe0YlKCFaKCNv/cYBNUsBRPlkJSc0U+dM7E9H0ThGJbgZT/iR7yj+VqMS06Qr4+OFm2JdCxIa8lugzkJs5K6MfxAaYPUcBpYG5khZJEkUUSb7DPCnKRfPBXj6M8FwuegoLpCgXcQszVjhbJFUJUee2hBhLoYTIcYtB57KY+opSMdVqwatSlZVj05aV//CwJLMX2DluaUcwhXm4ali2XOoLjxUrPV26zFtF4f5p0Gp310+z13BUWNvbehEXona6iAtX/zVZmtfN4WixfsNky4S6gCCVVq3RPLdfSfpv3MRRZfPoLc6Xs/5bt3EyMGzE9h07/Xft2t15z6i9+zgGg8FgMBgMBoPBYDAYDAYj8/APG67Rie8pUDsAAAAASUVORK5CYII="; var MapLocation = /* @__PURE__ */ vue.defineComponent({ name: "MapLocation", setup() { - const onMapReady = vue.inject("onMapReady"); const state = vue.reactive({ latitude: 0, longitude: 0, rotate: 0 }); - let timer; - function compassChangeHandler(res) { - state.rotate = res.direction; - } - function updateLocation() { - getLocation({ - type: "gcj02", - success: (res) => { - state.latitude = res.latitude; - state.longitude = res.longitude; - }, - complete: () => { - timer = setTimeout(updateLocation, 3e4); - } - }); - } - function removeLocation() { - if (timer) { - clearTimeout(timer); - } - offCompassChange(compassChangeHandler); - } - onCompassChange(compassChangeHandler); - onMapReady(updateLocation); - vue.onUnmounted(removeLocation); - const addMapChidlContext = vue.inject("addMapChidlContext"); - const removeMapChidlContext = vue.inject("removeMapChidlContext"); - const context = { - id: CONTEXT_ID, - state - }; - addMapChidlContext(context); - vue.onUnmounted(() => removeMapChidlContext(context)); return () => { return state.latitude ? vue.createVNode(MapMarker, vue.mergeProps({ anchor: { @@ -14584,6 +9565,130 @@ const UniViewJSBridge$1 = /* @__PURE__ */ shared.extend(ViewJSBridge, { window.UniServiceJSBridge.subscribeHandler(event, args, pageId); } }); +const request = /* @__PURE__ */ defineTaskApi(API_REQUEST, ({ + url, + data, + header, + method, + dataType: dataType2, + responseType, + withCredentials, + timeout = __uniConfig.networkTimeout.request +}, {resolve, reject}) => { + let body = null; + const contentType = normalizeContentType(header); + if (method !== "GET") { + if (typeof data === "string" || data instanceof ArrayBuffer) { + body = data; + } else { + if (contentType === "json") { + try { + body = JSON.stringify(data); + } catch (error) { + body = data.toString(); + } + } else if (contentType === "urlencoded") { + const bodyArray = []; + for (const key in data) { + if (shared.hasOwn(data, key)) { + bodyArray.push(encodeURIComponent(key) + "=" + encodeURIComponent(data[key])); + } + } + body = bodyArray.join("&"); + } else { + body = data.toString(); + } + } + } + const xhr = new XMLHttpRequest(); + const requestTask = new RequestTask(xhr); + xhr.open(method, url); + for (const key in header) { + if (shared.hasOwn(header, key)) { + xhr.setRequestHeader(key, header[key]); + } + } + const timer = setTimeout(function() { + xhr.onload = xhr.onabort = xhr.onerror = null; + requestTask.abort(); + reject("timeout"); + }, timeout); + xhr.responseType = responseType; + xhr.onload = function() { + clearTimeout(timer); + const statusCode = xhr.status; + let res = responseType === "text" ? xhr.responseText : xhr.response; + if (responseType === "text" && dataType2 === "json") { + try { + res = JSON.parse(res); + } catch (error) { + } + } + resolve({ + data: res, + statusCode, + header: parseHeaders(xhr.getAllResponseHeaders()), + cookies: [] + }); + }; + xhr.onabort = function() { + clearTimeout(timer); + reject("abort"); + }; + xhr.onerror = function() { + clearTimeout(timer); + reject(); + }; + xhr.withCredentials = withCredentials; + xhr.send(body); + return requestTask; +}, RequestProtocol, RequestOptions); +function normalizeContentType(header) { + const name = Object.keys(header).find((name2) => name2.toLowerCase() === "content-type"); + if (!name) { + return; + } + const contentType = header[name]; + if (contentType.indexOf("application/json") === 0) { + return "json"; + } else if (contentType.indexOf("application/x-www-form-urlencoded") === 0) { + return "urlencoded"; + } + return "string"; +} +class RequestTask { + constructor(xhr) { + this._xhr = xhr; + } + abort() { + if (this._xhr) { + this._xhr.abort(); + delete this._xhr; + } + } + onHeadersReceived(callback2) { + throw new Error("Method not implemented."); + } + offHeadersReceived(callback2) { + throw new Error("Method not implemented."); + } +} +function parseHeaders(headers) { + const headersObject = {}; + headers.split("\n").forEach((header) => { + const find = header.match(/(\S+\s*):\s*(.*)/); + if (!find || find.length !== 3) { + return; + } + headersObject[find[1]] = find[2]; + }); + return headersObject; +} +var api = /* @__PURE__ */ Object.freeze({ + __proto__: null, + [Symbol.toStringTag]: "Module", + request +}); const uni$1 = api; const UniServiceJSBridge$1 = /* @__PURE__ */ shared.extend(ServiceJSBridge, { publishHandler(event, args, pageId) { @@ -14597,7 +9702,7 @@ var TabBar = /* @__PURE__ */ vue.defineComponent({ useTabBarCssVar(tabBar2); const onSwitchTab = useSwitchTab(vueRouter.useRoute(), tabBar2); const { - style: style2, + style, borderStyle, placeholderStyle } = useTabBarStyle(tabBar2); @@ -14607,7 +9712,7 @@ var TabBar = /* @__PURE__ */ vue.defineComponent({ class: "uni-tabbar-" + tabBar2.position }, [vue.createVNode("div", { class: "uni-tabbar", - style: style2.value + style: style.value }, [vue.createVNode("div", { class: "uni-tabbar-border", style: borderStyle.value @@ -14681,11 +9786,11 @@ const BORDER_COLORS = { black: "rgba(0, 0, 0, 0.33)" }; function useTabBarStyle(tabBar2) { - const style2 = vue.computed(() => { + const style = vue.computed(() => { let backgroundColor = tabBar2.backgroundColor; const blurEffect = tabBar2.blurEffect; if (!backgroundColor) { - if (cssBackdropFilter && blurEffect && blurEffect !== "none") { + if (blurEffect && blurEffect !== "none") { backgroundColor = BLUR_EFFECT_COLORS[blurEffect]; } } @@ -14708,7 +9813,7 @@ function useTabBarStyle(tabBar2) { }; }); return { - style: style2, + style, borderStyle, placeholderStyle }; @@ -14761,13 +9866,13 @@ function createTabBarItemIconTsx(iconPath, tabBarItem, tabBar2) { iconWidth } = tabBar2; const clazz2 = "uni-tabbar__icon" + (text2 ? " uni-tabbar__icon__diff" : ""); - const style2 = { + const style = { width: iconWidth, height: iconWidth }; return vue.createVNode("div", { class: clazz2, - style: style2 + style }, [type !== "midButton" && vue.createVNode("img", { src: getRealPath(iconPath) }, null, 8, ["src"]), redDot && createTabBarItemRedDotTsx(tabBarItem.badge)], 6); @@ -14782,7 +9887,7 @@ function createTabBarItemTextTsx(color, tabBarItem, tabBar2) { fontSize, spacing } = tabBar2; - const style2 = { + const style = { color, fontSize, lineHeight: !iconPath ? 1.8 : "normal", @@ -14790,7 +9895,7 @@ function createTabBarItemTextTsx(color, tabBarItem, tabBar2) { }; return vue.createVNode("div", { class: "uni-tabbar__label", - style: style2 + style }, [text2, redDot && !iconPath && createTabBarItemRedDotTsx(tabBarItem.badge)], 4); } function createTabBarItemRedDotTsx(badge) { @@ -14829,15 +9934,6 @@ function createTabBarMidButtonTsx(color, iconPath, midButton, tabBar2, index2, o src: getRealPath(iconPath) }, null, 12, ["src"])], 4), createTabBarItemBdTsx(color, iconPath, midButton, tabBar2)], 12, ["onClick"]); } -const DEFAULT_CSS_VAR_VALUE = "0px"; -updateCssVar({ - "--status-bar-height": DEFAULT_CSS_VAR_VALUE, - "--top-window-height": DEFAULT_CSS_VAR_VALUE, - "--window-left": DEFAULT_CSS_VAR_VALUE, - "--window-right": DEFAULT_CSS_VAR_VALUE, - "--window-margin": DEFAULT_CSS_VAR_VALUE, - "--tab-bar-height": DEFAULT_CSS_VAR_VALUE -}); var LayoutComponent = vue.defineComponent({ name: "Layout", setup(_props, { @@ -14847,22 +9943,22 @@ var LayoutComponent = vue.defineComponent({ __UNI_FEATURE_TOPWINDOW__ && useTopWindow(); __UNI_FEATURE_LEFTWINDOW__ && useLeftWindow(); __UNI_FEATURE_RIGHTWINDOW__ && useRightWindow(); - const showTabBar2 = __UNI_FEATURE_TABBAR__ && useShowTabBar(); - const clazz2 = useAppClass(showTabBar2); + const showTabBar = __UNI_FEATURE_TABBAR__ && useShowTabBar(); + const clazz2 = useAppClass(showTabBar); return () => { const layoutTsx = createLayoutTsx(keepAliveRoute); - const tabBarTsx = __UNI_FEATURE_TABBAR__ && createTabBarTsx(showTabBar2); + const tabBarTsx = __UNI_FEATURE_TABBAR__ && createTabBarTsx(showTabBar); return vue.createVNode("uni-app", { class: clazz2.value - }, [[layoutTsx, tabBarTsx]], 2); + }, [layoutTsx, tabBarTsx], 2); }; } }); -function useAppClass(showTabBar2) { +function useAppClass(showTabBar) { const showMaxWidth = vue.ref(false); return vue.computed(() => { return { - "uni-app--showtabbar": showTabBar2 && showTabBar2.value, + "uni-app--showtabbar": showTabBar && showTabBar.value, "uni-app--maxwidth": showMaxWidth.value }; }); @@ -14880,14 +9976,11 @@ function createLayoutTsx(keepAliveRoute, topWindow, leftWindow, rightWindow) { function useShowTabBar(emit2) { const route = vueRouter.useRoute(); const tabBar2 = useTabBar(); - const showTabBar2 = vue.computed(() => route.meta.isTabBar && tabBar2.shown); - updateCssVar({ - "--tab-bar-height": tabBar2.height - }); - return showTabBar2; + const showTabBar = vue.computed(() => route.meta.isTabBar && tabBar2.shown); + return showTabBar; } -function createTabBarTsx(showTabBar2) { - return vue.withDirectives(vue.createVNode(TabBar, null, null, 512), [[vue.vShow, showTabBar2.value]]); +function createTabBarTsx(showTabBar) { + return vue.withDirectives(vue.createVNode(TabBar, null, null, 512), [[vue.vShow, showTabBar.value]]); } function createPageVNode() { return vue.createVNode(__uniRoutes[0].component); @@ -14980,7 +10073,7 @@ function usePageHeadTransparentBackgroundColor(backgroundColor) { return `rgba(${r},${g2},${b},0)`; } function usePageHeadTransparent(headRef, { - id: id2, + id, navigationBar: {titleColor, coverage, backgroundColor} }) { let A = 0; @@ -15006,7 +10099,7 @@ function usePageHeadTransparent(headRef, { borderRadiusElemsStyles.push(borderRadiusElem.style); } }); - useOn(id2 + ".onPageScroll", ({scrollTop}) => { + useOn(id + ".onPageScroll", ({scrollTop}) => { const alpha = Math.min(scrollTop / offset, 1); if (alpha === 1 && A === 1) { return; @@ -15053,7 +10146,7 @@ var PageHead = /* @__PURE__ */ vue.defineComponent({ const navigationBar = pageMeta.navigationBar; const { clazz: clazz2, - style: style2 + style } = usePageHead(navigationBar); const buttons = __UNI_FEATURE_NAVIGATIONBAR_BUTTONS__ && usePageHeadButtons(pageMeta); const searchInput = __UNI_FEATURE_NAVIGATIONBAR_SEARCHINPUT__ && navigationBar.searchInput && usePageHeadSearchInput(pageMeta); @@ -15074,7 +10167,7 @@ var PageHead = /* @__PURE__ */ vue.defineComponent({ }, [vue.createVNode("div", { ref: headRef, class: clazz2.value, - style: style2.value + style: style.value }, [vue.createVNode("div", { class: "uni-page-head-hd" }, [backButtonTsx, ...leftButtonsTsx]), createPageHeadBdTsx(navigationBar, searchInput), vue.createVNode("div", { @@ -15237,7 +10330,7 @@ function usePageHead(navigationBar) { } return clazz3; }); - const style2 = vue.computed(() => { + const style = vue.computed(() => { const backgroundColor = __UNI_FEATURE_NAVIGATIONBAR_TRANSPARENT__ && navigationBar.type === "transparent" ? usePageHeadTransparentBackgroundColor(navigationBar.backgroundColor) : navigationBar.backgroundColor; return { backgroundColor, @@ -15248,11 +10341,11 @@ function usePageHead(navigationBar) { }); return { clazz: clazz2, - style: style2 + style }; } function usePageHeadButtons({ - id: id2, + id, navigationBar }) { const left = []; @@ -15277,7 +10370,7 @@ function usePageHeadButtons({ } btn.fontFamily = fontFamily; } - const pageHeadBtn = usePageHeadButton(id2, index2, btn, isTransparent); + const pageHeadBtn = usePageHeadButton(id, index2, btn, isTransparent); if (btn.float === "left") { left.push(pageHeadBtn); } else { @@ -15321,7 +10414,7 @@ function usePageHeadButton(pageId, index2, btn, isTransparent) { }; } function usePageHeadSearchInput({ - id: id2, + id, navigationBar: { searchInput } @@ -15334,7 +10427,7 @@ function usePageHeadSearchInput({ } = searchInput; if (disabled) { const onClick = () => { - invokeHook(id2, "onNavigationBarSearchInputClicked"); + invokeHook(id, "onNavigationBarSearchInputClicked"); }; return { focus, @@ -15345,25 +10438,25 @@ function usePageHeadSearchInput({ } const onFocus = () => { focus.value = true; - invokeHook(id2, "onNavigationBarSearchInputFocusChanged", { + invokeHook(id, "onNavigationBarSearchInputFocusChanged", { focus: true }); }; const onBlur = () => { focus.value = false; - invokeHook(id2, "onNavigationBarSearchInputFocusChanged", { + invokeHook(id, "onNavigationBarSearchInputFocusChanged", { focus: false }); }; const onInput = (evt) => { text2.value = evt.detail.value; - invokeHook(id2, "onNavigationBarSearchInputChanged", { + invokeHook(id, "onNavigationBarSearchInputChanged", { text: text2.value }); }; const onKeyup = (evt) => { if (evt.key === "Enter" || evt.keyCode === 13) { - invokeHook(id2, "onNavigationBarSearchInputConfirmed", { + invokeHook(id, "onNavigationBarSearchInputConfirmed", { text: text2.value }); } @@ -15434,213 +10527,15 @@ function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) { ]); } _sfc_main.render = _sfc_render; -function processDeltaY(ev, identifier, startY) { - const touch = Array.prototype.slice.call(ev.changedTouches).filter((touch2) => touch2.identifier === identifier)[0]; - if (!touch) { - return false; - } - ev.deltaY = touch.pageY - startY; - return true; -} -const PULLING = "pulling"; -const REACHED = "reached"; -const ABORTING = "aborting"; -const REFRESHING = "refreshing"; -const RESTORING = "restoring"; -function usePageRefresh(refreshRef) { - const {id: id2, refreshOptions} = usePageMeta(); - const {range, height} = refreshOptions; - let refreshContainerElem; - let refreshControllerElem; - let refreshControllerElemStyle; - let refreshInnerElemStyle; - useSubscribe(() => { - if (!state) { - state = REFRESHING; - addClass(); - setTimeout(() => { - refreshing(); - }, 50); - } - }, id2 + "." + API_START_PULL_DOWN_REFRESH); - useSubscribe(() => { - if (state === REFRESHING) { - removeClass(); - state = RESTORING; - addClass(); - restoring(() => { - removeClass(); - state = distance = offset = null; - }); - } - }, id2 + "." + API_STOP_PULL_DOWN_REFRESH); - vue.onMounted(() => { - refreshContainerElem = refreshRef.value.$el; - refreshControllerElem = refreshContainerElem.querySelector(".uni-page-refresh"); - refreshControllerElemStyle = refreshControllerElem.style; - refreshInnerElemStyle = refreshControllerElem.querySelector(".uni-page-refresh-inner").style; - }); - let touchId; - let startY; - let canRefresh; - let state; - let distance = null; - let offset = null; - function toggleClass(type) { - if (!state) { - return; - } - if (refreshContainerElem) { - refreshContainerElem.classList[type]("uni-page-refresh--" + state); - } - } - function addClass() { - toggleClass("add"); - } - function removeClass() { - toggleClass("remove"); - } - function pulling(deltaY) { - if (!refreshControllerElem) { - return; - } - let rotate = deltaY / range; - if (rotate > 1) { - rotate = 1; - } else { - rotate = rotate * rotate * rotate; - } - const y = Math.round(deltaY / (range / height)) || 0; - refreshInnerElemStyle.transform = "rotate(" + 360 * rotate + "deg)"; - refreshControllerElemStyle.clip = "rect(" + (45 - y) + "px,45px,45px,-5px)"; - refreshControllerElemStyle.transform = "translate3d(-50%, " + y + "px, 0)"; - } - const onTouchstartPassive = withWebEvent((ev) => { - const touch = ev.changedTouches[0]; - touchId = touch.identifier; - startY = touch.pageY; - if ([ABORTING, REFRESHING, RESTORING].indexOf(state) >= 0) { - canRefresh = false; - } else { - canRefresh = true; - } - }); - const onTouchmove = withWebEvent((ev) => { - if (!canRefresh) { - return; - } - if (!processDeltaY(ev, touchId, startY)) { - return; - } - let {deltaY} = ev; - if ((document.documentElement.scrollTop || document.body.scrollTop) !== 0) { - touchId = null; - return; - } - if (deltaY < 0 && !state) { - return; - } - ev.preventDefault(); - if (distance === null) { - offset = deltaY; - state = PULLING; - addClass(); - } - deltaY = deltaY - offset; - if (deltaY < 0) { - deltaY = 0; - } - distance = deltaY; - const isReached = deltaY >= range && state !== REACHED; - const isPulling = deltaY < range && state !== PULLING; - if (isReached || isPulling) { - removeClass(); - state = state === REACHED ? PULLING : REACHED; - addClass(); - } - pulling(deltaY); - }); - const onTouchend = withWebEvent((ev) => { - if (!processDeltaY(ev, touchId, startY)) { - return; - } - if (state === null) { - return; - } - if (state === PULLING) { - removeClass(); - state = ABORTING; - addClass(); - aborting(() => { - removeClass(); - state = distance = offset = null; - }); - } else if (state === REACHED) { - removeClass(); - state = REFRESHING; - addClass(); - refreshing(); - } - }); - function aborting(callback2) { - if (!refreshControllerElem) { - return; - } - if (refreshControllerElemStyle.transform) { - refreshControllerElemStyle.transition = "-webkit-transform 0.3s"; - refreshControllerElemStyle.transform = "translate3d(-50%, 0, 0)"; - const abortTransitionEnd = function() { - timeout && clearTimeout(timeout); - refreshControllerElem.removeEventListener("webkitTransitionEnd", abortTransitionEnd); - refreshControllerElemStyle.transition = ""; - callback2(); - }; - refreshControllerElem.addEventListener("webkitTransitionEnd", abortTransitionEnd); - const timeout = setTimeout(abortTransitionEnd, 350); - } else { - callback2(); - } - } - function refreshing() { - if (!refreshControllerElem) { - return; - } - refreshControllerElemStyle.transition = "-webkit-transform 0.2s"; - refreshControllerElemStyle.transform = "translate3d(-50%, " + height + "px, 0)"; - invokeHook(id2, "onPullDownRefresh"); - } - function restoring(callback2) { - if (!refreshControllerElem) { - return; - } - refreshControllerElemStyle.transition = "-webkit-transform 0.3s"; - refreshControllerElemStyle.transform += " scale(0.01)"; - const restoreTransitionEnd = function() { - timeout && clearTimeout(timeout); - refreshControllerElem.removeEventListener("webkitTransitionEnd", restoreTransitionEnd); - refreshControllerElemStyle.transition = ""; - refreshControllerElemStyle.transform = "translate3d(-50%, 0, 0)"; - callback2(); - }; - refreshControllerElem.addEventListener("webkitTransitionEnd", restoreTransitionEnd); - const timeout = setTimeout(restoreTransitionEnd, 350); - } - return { - onTouchstartPassive, - onTouchmove, - onTouchend, - onTouchcancel: onTouchend - }; -} var PageBody = vue.defineComponent({ name: "PageBody", setup(props2, ctx) { const pageMeta = __UNI_FEATURE_PULL_DOWN_REFRESH__ && usePageMeta(); const refreshRef = __UNI_FEATURE_PULL_DOWN_REFRESH__ && vue.ref(null); - const pageRefresh = __UNI_FEATURE_PULL_DOWN_REFRESH__ && pageMeta.enablePullDownRefresh ? usePageRefresh(refreshRef) : null; + const pageRefresh = null; return () => { const pageRefreshTsx = __UNI_FEATURE_PULL_DOWN_REFRESH__ && createPageRefreshTsx(refreshRef, pageMeta); - return vue.createVNode(vue.Fragment, null, [pageRefreshTsx, vue.createVNode("uni-page-wrapper", pageRefresh, [vue.createVNode("uni-page-body", null, [vue.renderSlot(ctx.slots, "default")])], 16)]); + return vue.createVNode("div", null, [pageRefreshTsx, vue.createVNode("uni-page-wrapper", pageRefresh, [vue.createVNode("uni-page-body", null, [vue.renderSlot(ctx.slots, "default")])], 16)]); }; } }); @@ -15655,7 +10550,7 @@ function createPageRefreshTsx(refreshRef, pageMeta) { var index$2 = vue.defineComponent({ name: "Page", setup(_props, ctx) { - const {navigationBar} = providePageMeta(history.state && history.state.__id__ || 1); + const {navigationBar} = providePageMeta(getStateId()); return () => vue.createVNode("uni-page", null, __UNI_FEATURE_NAVIGATIONBAR__ && navigationBar.style !== "custom" ? [vue.createVNode(PageHead), createPageBodyVNode(ctx)] : [createPageBodyVNode(ctx)]); } }); @@ -15725,103 +10620,16 @@ exports.UniViewJSBridge = UniViewJSBridge$1; exports.Video = index$5; exports.View = index$6; exports.WebView = index$4; -exports.addInterceptor = addInterceptor; -exports.arrayBufferToBase64 = arrayBufferToBase64; -exports.base64ToArrayBuffer = base64ToArrayBuffer; -exports.canIUse = canIUse; -exports.chooseFile = chooseFile; -exports.chooseImage = chooseImage; -exports.chooseVideo = chooseVideo; -exports.clearStorage = clearStorage; -exports.clearStorageSync = clearStorageSync; -exports.closeSocket = closeSocket; -exports.connectSocket = connectSocket; -exports.createInnerAudioContext = createInnerAudioContext; -exports.createIntersectionObserver = createIntersectionObserver; -exports.createMapContext = createMapContext; -exports.createSelectorQuery = createSelectorQuery; -exports.createVideoContext = createVideoContext; -exports.cssBackdropFilter = cssBackdropFilter; -exports.cssConstant = cssConstant; -exports.cssEnv = cssEnv; -exports.cssVar = cssVar; -exports.downloadFile = downloadFile; exports.getApp = getApp$1; exports.getCurrentPages = getCurrentPages$1; -exports.getFileInfo = getFileInfo; -exports.getImageInfo = getImageInfo; -exports.getLocation = getLocation; -exports.getNetworkType = getNetworkType; -exports.getStorage = getStorage; -exports.getStorageInfo = getStorageInfo; -exports.getStorageInfoSync = getStorageInfoSync; -exports.getStorageSync = getStorageSync; -exports.getSystemInfo = getSystemInfo; -exports.getSystemInfoSync = getSystemInfoSync; -exports.getVideoInfo = getVideoInfo; -exports.hideKeyboard = hideKeyboard; -exports.hideLoading = hideLoading; -exports.hideNavigationBarLoading = hideNavigationBarLoading; -exports.hideTabBar = hideTabBar; -exports.hideTabBarRedDot = hideTabBarRedDot; -exports.hideToast = hideToast; -exports.loadFontFace = loadFontFace; -exports.makePhoneCall = makePhoneCall; -exports.navigateBack = navigateBack; -exports.navigateTo = navigateTo; -exports.offAccelerometerChange = offAccelerometerChange; -exports.offCompassChange = offCompassChange; -exports.offNetworkStatusChange = offNetworkStatusChange; -exports.onAccelerometerChange = onAccelerometerChange; -exports.onCompassChange = onCompassChange; -exports.onNetworkStatusChange = onNetworkStatusChange; -exports.onSocketClose = onSocketClose; -exports.onSocketError = onSocketError; -exports.onSocketMessage = onSocketMessage; -exports.onSocketOpen = onSocketOpen; -exports.onTabBarMidButtonTap = onTabBarMidButtonTap; -exports.openDocument = openDocument; -exports.pageScrollTo = pageScrollTo; exports.plugin = index$m; -exports.promiseInterceptor = promiseInterceptor; -exports.reLaunch = reLaunch; -exports.redirectTo = redirectTo; -exports.removeInterceptor = removeInterceptor; -exports.removeStorage = removeStorage; -exports.removeStorageSync = removeStorageSync; -exports.removeTabBarBadge = removeTabBarBadge; exports.request = request; -exports.sendSocketMessage = sendSocketMessage; -exports.setNavigationBarColor = setNavigationBarColor; -exports.setNavigationBarTitle = setNavigationBarTitle; -exports.setStorage = setStorage; -exports.setStorageSync = setStorageSync; -exports.setTabBarBadge = setTabBarBadge; -exports.setTabBarItem = setTabBarItem; -exports.setTabBarStyle = setTabBarStyle; exports.setupApp = setupApp; exports.setupPage = setupPage; -exports.showLoading = showLoading; -exports.showModal = showModal; -exports.showNavigationBarLoading = showNavigationBarLoading; -exports.showTabBar = showTabBar; -exports.showTabBarRedDot = showTabBarRedDot; -exports.showToast = showToast; -exports.startAccelerometer = startAccelerometer; -exports.startCompass = startCompass; -exports.startPullDownRefresh = startPullDownRefresh; -exports.stopAccelerometer = stopAccelerometer; -exports.stopCompass = stopCompass; -exports.stopPullDownRefresh = stopPullDownRefresh; -exports.switchTab = switchTab; exports.uni = uni$1; -exports.uploadFile = uploadFile; -exports.upx2px = upx2px; exports.useAttrs = useAttrs; exports.useCustomEvent = useCustomEvent; exports.useOn = useOn; exports.useSubscribe = useSubscribe; exports.useUserAction = useUserAction; -exports.vibrateLong = vibrateLong; -exports.vibrateShort = vibrateShort; exports.withWebEvent = withWebEvent; diff --git a/packages/uni-h5/dist/uni-h5.es.js b/packages/uni-h5/dist/uni-h5.es.js index 7b0ecf4d3..b07aa8c01 100644 --- a/packages/uni-h5/dist/uni-h5.es.js +++ b/packages/uni-h5/dist/uni-h5.es.js @@ -1,5 +1,5 @@ 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, computed, nextTick, onBeforeMount, onMounted, onBeforeActivate, onBeforeDeactivate, openBlock, createBlock, mergeProps, toDisplayString, ref, defineComponent, resolveComponent, toHandlers, renderSlot, watch, onUnmounted, onBeforeUnmount, onActivated, withDirectives, vShow, createTextVNode, createCommentVNode, shallowRef, watchEffect, renderList, onDeactivated, Fragment, Teleport, createApp, Transition, withCtx, KeepAlive, resolveDynamicComponent} from "vue"; +import {injectHook, withModifiers, createVNode, getCurrentInstance, inject, provide, reactive, computed, nextTick, onBeforeMount, onMounted, onBeforeActivate, onBeforeDeactivate, openBlock, createBlock, mergeProps, toDisplayString, ref, defineComponent, resolveComponent, toHandlers, renderSlot, watch, onUnmounted, onBeforeUnmount, onActivated, withDirectives, vShow, createCommentVNode, createTextVNode, shallowRef, watchEffect, renderList, onDeactivated, Fragment, Teleport, createApp, Transition, withCtx, KeepAlive, resolveDynamicComponent} from "vue"; import {once, passive, normalizeTarget, isBuiltInComponent, invokeArrayFns, NAVBAR_HEIGHT, parseQuery, PRIMARY_COLOR, removeLeadingSlash, getLen, ON_REACH_BOTTOM_DISTANCE, decodedQuery, debounce, plusReady, updateElementStyle, addFont, scrollTo} 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"; @@ -21,7 +21,9 @@ function useI18n() { if (!i18n$1) { let language; { - language = navigator.language; + { + language = navigator.language; + } } i18n$1 = initVueI18n(language); } @@ -286,10 +288,10 @@ function init() { }); return; } - function setStyle(el, style2) { + function setStyle(el, style) { var elStyle = el.style; - Object.keys(style2).forEach(function(key) { - var val = style2[key]; + Object.keys(style).forEach(function(key) { + var val = style[key]; elStyle[key] = val; }); } @@ -398,13 +400,13 @@ var changeAttrs = []; function attrChange(attr2) { if (!changeAttrs.length) { setTimeout(function() { - var style2 = {}; + var style = {}; changeAttrs.forEach(function(attr3) { - style2[attr3] = elementComputedStyle[attr3]; + style[attr3] = elementComputedStyle[attr3]; }); changeAttrs.length = 0; callbacks$2.forEach(function(callback2) { - callback2(style2); + callback2(style); }); }, 0); } @@ -447,26 +449,26 @@ var safeAreaInsets = { onChange, offChange }; -var D__DCloud_local_git_uniAppNext_node_modules_safeAreaInsets_out = safeAreaInsets; +var out = safeAreaInsets; const onEventPrevent = /* @__PURE__ */ withModifiers(() => { }, ["prevent"]); const onEventStop = /* @__PURE__ */ withModifiers(() => { }, ["stop"]); function getWindowOffset() { - const style2 = document.documentElement.style; - const top = parseInt(style2.getPropertyValue("--window-top")); - const bottom = parseInt(style2.getPropertyValue("--window-bottom")); - const left = parseInt(style2.getPropertyValue("--window-left")); - const right = parseInt(style2.getPropertyValue("--window-right")); + const style = document.documentElement.style; + const top = parseInt(style.getPropertyValue("--window-top")); + const bottom = parseInt(style.getPropertyValue("--window-bottom")); + const left = parseInt(style.getPropertyValue("--window-left")); + const right = parseInt(style.getPropertyValue("--window-right")); return { - top: top ? top + D__DCloud_local_git_uniAppNext_node_modules_safeAreaInsets_out.top : 0, - bottom: bottom ? bottom + D__DCloud_local_git_uniAppNext_node_modules_safeAreaInsets_out.bottom : 0, - left: left ? left + D__DCloud_local_git_uniAppNext_node_modules_safeAreaInsets_out.left : 0, - right: right ? right + D__DCloud_local_git_uniAppNext_node_modules_safeAreaInsets_out.right : 0 + top: top ? top + out.top : 0, + bottom: bottom ? bottom + out.bottom : 0, + left: left ? left + out.left : 0, + right: right ? right + out.right : 0 }; } -const style = document.documentElement.style; function updateCssVar(cssVars) { + const style = document.documentElement.style; Object.keys(cssVars).forEach((name) => { style.setProperty(name, cssVars[name]); }); @@ -476,29 +478,29 @@ function updatePageCssVar(cssVars) { } const sheetsMap = new Map(); function updateStyle(id2, content) { - let style2 = sheetsMap.get(id2); - if (style2 && !(style2 instanceof HTMLStyleElement)) { + let style = sheetsMap.get(id2); + if (style && !(style instanceof HTMLStyleElement)) { removeStyle(id2); - style2 = void 0; + style = void 0; } - if (!style2) { - style2 = document.createElement("style"); - style2.setAttribute("type", "text/css"); - style2.innerHTML = content; - document.head.appendChild(style2); + if (!style) { + style = document.createElement("style"); + style.setAttribute("type", "text/css"); + style.innerHTML = content; + document.head.appendChild(style); } else { - style2.innerHTML = content; + style.innerHTML = content; } - sheetsMap.set(id2, style2); + sheetsMap.set(id2, style); } function removeStyle(id2) { - let style2 = sheetsMap.get(id2); - if (style2) { - if (style2 instanceof CSSStyleSheet) { - document.adoptedStyleSheets.indexOf(style2); - document.adoptedStyleSheets = document.adoptedStyleSheets.filter((s) => s !== style2); + let style = sheetsMap.get(id2); + if (style) { + if (style instanceof CSSStyleSheet) { + document.adoptedStyleSheets.indexOf(style); + document.adoptedStyleSheets = document.adoptedStyleSheets.filter((s) => s !== style); } else { - document.head.removeChild(style2); + document.head.removeChild(style); } sheetsMap.delete(id2); } @@ -789,15 +791,15 @@ class ComponentDescriptor { } return descriptors; } - setStyle(style2) { - if (!this.$el || !style2) { + setStyle(style) { + if (!this.$el || !style) { return this; } - if (typeof style2 === "string") { - style2 = parseStyleText(style2); + if (typeof style === "string") { + style = parseStyleText(style); } - if (isPlainObject(style2)) { - this.$el.__wxsStyle = style2; + if (isPlainObject(style)) { + this.$el.__wxsStyle = style; this.$vm.$forceUpdate(); } return this; @@ -1113,7 +1115,7 @@ function normalizePageMeta(pageMeta) { 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; + offset += NAVBAR_HEIGHT + out.top; } refreshOptions.offset = offset; refreshOptions.height = rpx2px(refreshOptions.height); @@ -1138,6 +1140,9 @@ function normalizePageMeta(pageMeta) { } return pageMeta; } +function getStateId() { + return history.state && history.state.__id__ || 1; +} PolySymbol(process.env.NODE_ENV !== "production" ? "layout" : "l"); let tabBar; function useTabBar() { @@ -1595,10 +1600,10 @@ const ArrayBufferToBase64Protocol = [ required: true } ]; -const base64ToArrayBuffer = defineSyncApi(API_BASE64_TO_ARRAY_BUFFER, (base64) => { +const base64ToArrayBuffer = /* @__PURE__ */ defineSyncApi(API_BASE64_TO_ARRAY_BUFFER, (base64) => { return decode(base64); }, Base64ToArrayBufferProtocol); -const arrayBufferToBase64 = defineSyncApi(API_ARRAY_BUFFER_TO_BASE64, (arrayBuffer) => { +const arrayBufferToBase64 = /* @__PURE__ */ defineSyncApi(API_ARRAY_BUFFER_TO_BASE64, (arrayBuffer) => { return encode$1(arrayBuffer); }, ArrayBufferToBase64Protocol); function findElem(vm) { @@ -1715,7 +1720,7 @@ function checkDeviceWidth() { deviceDPR = pixelRatio2; isIOS = platform === "ios"; } -const upx2px = defineSyncApi(API_UPX2PX, (number, newDeviceWidth) => { +const upx2px = /* @__PURE__ */ defineSyncApi(API_UPX2PX, (number, newDeviceWidth) => { if (deviceWidth === 0) { checkDeviceWidth(); } @@ -1788,14 +1793,14 @@ function removeHook(hooks, hook) { hooks.splice(index2, 1); } } -const addInterceptor = defineSyncApi(API_ADD_INTERCEPTOR, (method, interceptor) => { +const addInterceptor = /* @__PURE__ */ defineSyncApi(API_ADD_INTERCEPTOR, (method, interceptor) => { if (typeof method === "string" && isPlainObject(interceptor)) { mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), interceptor); } else if (isPlainObject(method)) { mergeInterceptorHook(globalInterceptors, method); } }, AddInterceptorProtocol); -const removeInterceptor = defineSyncApi(API_REMOVE_INTERCEPTOR, (method, interceptor) => { +const removeInterceptor = /* @__PURE__ */ defineSyncApi(API_REMOVE_INTERCEPTOR, (method, interceptor) => { if (typeof method === "string") { if (isPlainObject(interceptor)) { removeInterceptorHook(scopedInterceptors[method], interceptor); @@ -1873,7 +1878,7 @@ class VideoContext { operateVideoPlayer(this.id, this.vm, "hideStatusBar"); } } -const createVideoContext = defineSyncApi(API_CREATE_VIDEO_CONTEXT, (id2, context) => { +const createVideoContext = /* @__PURE__ */ defineSyncApi(API_CREATE_VIDEO_CONTEXT, (id2, context) => { if (context) { return new VideoContext(id2, context); } @@ -1925,7 +1930,7 @@ class MapContext { $getAppMap() { } } -const createMapContext = defineSyncApi(API_CREATE_MAP_CONTEXT, (id2, context) => { +const createMapContext = /* @__PURE__ */ defineSyncApi(API_CREATE_MAP_CONTEXT, (id2, context) => { if (context) { return new MapContext(id2, context); } @@ -1974,7 +1979,7 @@ class ServiceIntersectionObserver { this._reqId && removeIntersectionObserver({reqId: this._reqId, component: this._component}, this._pageId); } } -const createIntersectionObserver = defineSyncApi("createIntersectionObserver", (context, options) => { +const createIntersectionObserver = /* @__PURE__ */ defineSyncApi("createIntersectionObserver", (context, options) => { if (context && !getPageIdByVm(context)) { options = context; context = null; @@ -1987,7 +1992,7 @@ const createIntersectionObserver = defineSyncApi("createIntersectionObserver", ( const createSelectorQuery = () => { }; const API_ON_TAB_BAR_MID_BUTTON_TAP = "onTabBarMidButtonTap"; -const onTabBarMidButtonTap = defineOnApi(API_ON_TAB_BAR_MID_BUTTON_TAP, () => { +const onTabBarMidButtonTap = /* @__PURE__ */ defineOnApi(API_ON_TAB_BAR_MID_BUTTON_TAP, () => { }); const API_CAN_I_USE = "canIUse"; const CanIUseProtocol = [ @@ -3353,7 +3358,7 @@ const SCHEMA_CSS = { "css.constant": cssConstant, "css.backdrop-filter": cssBackdropFilter }; -const canIUse = defineSyncApi(API_CAN_I_USE, (schema) => { +const canIUse = /* @__PURE__ */ defineSyncApi(API_CAN_I_USE, (schema) => { if (hasOwn(SCHEMA_CSS, schema)) { return SCHEMA_CSS[schema]; } @@ -3418,7 +3423,7 @@ function removePage(routeKey, removeRouteCaches = true) { currentPagesMap.delete(routeKey); removeRouteCaches && removeRouteCache(routeKey); } -let id = /* @__PURE__ */ (() => history.state && history.state.__id__ || 1)(); +let id = /* @__PURE__ */ getStateId(); function createPageState(type, __id__) { return { __id__: __id__ || ++id, @@ -3461,7 +3466,7 @@ function normalizeRouteKey(path, id2) { } function useKeepAliveRoute() { const route = useRoute(); - const routeKey = computed(() => normalizeRouteKey(route.path, history.state.__id__ || 1)); + const routeKey = computed(() => normalizeRouteKey(route.path, getStateId())); const isTabBar = computed(() => route.meta.isTabBar); return { routeKey, @@ -6052,12 +6057,12 @@ var index$e = /* @__PURE__ */ defineComponent({ ref: rootRef }, [createVNode("div", { style: modeStyle - }, null, 4), imgSrc && createVNode("img", { + }, null, 4), imgSrc ? createVNode("img", { src: imgSrc, draggable: props2.draggable - }, null, 8, ["src", "draggable"]), FIX_MODES[mode] && createVNode(ResizeSensor, { + }, null, 8, ["src", "draggable"]) : createVNode("img", null, null), FIX_MODES[mode] ? createVNode(ResizeSensor, { onResize: fixSize - }, null, 8, ["onResize"])], 512); + }, null, 8, ["onResize"]) : createVNode("span", null, null)], 512); }; } }); @@ -6091,9 +6096,9 @@ function useImageState(rootRef, props2) { }); onMounted(() => { const rootEl = rootRef.value; - const style2 = rootEl.style; - state.origWidth = Number(style2.width) || 0; - state.origHeight = Number(style2.height) || 0; + const style = rootEl.style; + state.origWidth = Number(style.width) || 0; + state.origHeight = Number(style.height) || 0; }); return state; } @@ -6182,7 +6187,7 @@ function useImageSize(rootRef, props2, state) { }; const resetSize = () => { const { - style: style2 + style } = rootRef.value; const { origStyle: { @@ -6190,8 +6195,8 @@ function useImageSize(rootRef, props2, state) { height } } = state; - style2.width = width; - style2.height = height; + style.width = width; + style.height = height; }; watch(() => props2.mode, (value, oldValue) => { if (FIX_MODES[oldValue]) { @@ -7862,7 +7867,7 @@ var index$d = /* @__PURE__ */ defineComponent({ class: "uni-progress-inner-bar" }, null, 4)], 4), showInfo ? createVNode("p", { class: "uni-progress-info" - }, [currentPercent, createTextVNode("%")]) : ""]); + }, [currentPercent + "%"]) : ""]); }; } }); @@ -10807,13 +10812,13 @@ function useDanmu(props2, videoState) { const p2 = document.createElement("p"); p2.className = "uni-video-danmu-item"; p2.innerText = danmu.text; - let style2 = `bottom: ${Math.random() * 100}%;color: ${danmu.color};`; - p2.setAttribute("style", style2); + let style = `bottom: ${Math.random() * 100}%;color: ${danmu.color};`; + p2.setAttribute("style", style); const danmuEl = danmuRef.value; danmuEl.appendChild(p2); setTimeout(function() { - style2 += "left: 0;-webkit-transform: translateX(-100%);transform: translateX(-100%);"; - p2.setAttribute("style", style2); + style += "left: 0;-webkit-transform: translateX(-100%);transform: translateX(-100%);"; + p2.setAttribute("style", style); setTimeout(function() { p2.remove(); }, 4e3); @@ -11865,10 +11870,10 @@ var MapControl = /* @__PURE__ */ defineComponent({ control = document.createElement("div"); const img = new Image(); control.appendChild(img); - const style2 = control.style; - style2.position = "absolute"; - style2.width = "0"; - style2.height = "0"; + const style = control.style; + style.position = "absolute"; + style.width = "0"; + style.height = "0"; img.onload = () => { if (option.position.width) { img.width = option.position.width; @@ -11876,11 +11881,11 @@ var MapControl = /* @__PURE__ */ defineComponent({ if (option.position.height) { img.height = option.position.height; } - const style3 = img.style; - style3.position = "absolute"; - style3.left = (position.left || 0) + "px"; - style3.top = (position.top || 0) + "px"; - style3.maxWidth = "initial"; + const style2 = img.style; + style2.position = "absolute"; + style2.left = (position.left || 0) + "px"; + style2.top = (position.top || 0) + "px"; + style2.maxWidth = "initial"; }; img.src = getRealPath(option.iconPath); img.onclick = function($event) { @@ -12048,14 +12053,14 @@ innerAudioContextOffEventNames.forEach((eventName) => { } }; }); -const createInnerAudioContext = defineSyncApi(API_CREATE_INNER_AUDIO_CONTEXT, () => { +const createInnerAudioContext = /* @__PURE__ */ defineSyncApi(API_CREATE_INNER_AUDIO_CONTEXT, () => { return new InnerAudioContext(); }); -const makePhoneCall = defineAsyncApi(API_MAKE_PHONE_CALL, ({phoneNumber}, {resolve}) => { +const makePhoneCall = /* @__PURE__ */ defineAsyncApi(API_MAKE_PHONE_CALL, ({phoneNumber}, {resolve}) => { window.location.href = `tel:${phoneNumber}`; return resolve(); }, MakePhoneCallProtocol); -const getSystemInfoSync = defineSyncApi("getSystemInfoSync", () => { +const getSystemInfoSync = /* @__PURE__ */ defineSyncApi("getSystemInfoSync", () => { const pixelRatio2 = window.devicePixelRatio; const screenFix = getScreenFix(); const landscape = isLandscape(screenFix); @@ -12064,7 +12069,7 @@ const getSystemInfoSync = defineSyncApi("getSystemInfoSync", () => { const windowWidth = getWindowWidth(screenWidth); let windowHeight = window.innerHeight; const language = navigator.language; - const statusBarHeight = D__DCloud_local_git_uniAppNext_node_modules_safeAreaInsets_out.top; + const statusBarHeight = out.top; let osname; let osversion; let model; @@ -12177,12 +12182,12 @@ const getSystemInfoSync = defineSyncApi("getSystemInfoSync", () => { const system = `${osname} ${osversion}`; const platform = osname.toLocaleLowerCase(); const safeArea = { - 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 + 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 }; const {top: windowTop, bottom: windowBottom} = getWindowOffset(); windowHeight -= windowTop; @@ -12202,14 +12207,14 @@ const getSystemInfoSync = defineSyncApi("getSystemInfoSync", () => { model, safeArea, safeAreaInsets: { - 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 + top: out.top, + right: out.right, + bottom: out.bottom, + left: out.left } }; }); -const getSystemInfo = defineAsyncApi("getSystemInfo", (_args, {resolve}) => { +const getSystemInfo = /* @__PURE__ */ defineAsyncApi("getSystemInfo", (_args, {resolve}) => { return resolve(getSystemInfoSync()); }); const API_ON_NETWORK_STATUS_CHANGE = "onNetworkStatusChange"; @@ -12224,7 +12229,7 @@ function networkListener() { function getConnection() { return navigator.connection || navigator.webkitConnection || navigator.mozConnection; } -const onNetworkStatusChange = defineOnApi(API_ON_NETWORK_STATUS_CHANGE, () => { +const onNetworkStatusChange = /* @__PURE__ */ defineOnApi(API_ON_NETWORK_STATUS_CHANGE, () => { const connection = getConnection(); if (connection) { connection.addEventListener("change", networkListener); @@ -12233,7 +12238,7 @@ const onNetworkStatusChange = defineOnApi(API_ON_NETWORK_STATUS_CHANGE, () => { window.addEventListener("online", networkListener); } }); -const offNetworkStatusChange = defineOffApi("offNetworkStatusChange", () => { +const offNetworkStatusChange = /* @__PURE__ */ defineOffApi("offNetworkStatusChange", () => { const connection = getConnection(); if (connection) { connection.removeEventListener("change", networkListener); @@ -12242,7 +12247,7 @@ const offNetworkStatusChange = defineOffApi("offNetworkStatusChange", () => { window.removeEventListener("online", networkListener); } }); -const getNetworkType = defineAsyncApi("getNetworkType", (_args, {resolve}) => { +const getNetworkType = /* @__PURE__ */ defineAsyncApi("getNetworkType", (_args, {resolve}) => { const connection = getConnection(); let networkType = "unknown"; if (connection) { @@ -12258,13 +12263,13 @@ const getNetworkType = defineAsyncApi("getNetworkType", (_args, {resolve}) => { return resolve({networkType}); }); let listener$1 = null; -const onAccelerometerChange = defineOnApi(API_ON_ACCELEROMETER, () => { +const onAccelerometerChange = /* @__PURE__ */ defineOnApi(API_ON_ACCELEROMETER, () => { startAccelerometer(); }); -const offAccelerometerChange = defineOnApi(API_OFF_ACCELEROMETER, () => { +const offAccelerometerChange = /* @__PURE__ */ defineOnApi(API_OFF_ACCELEROMETER, () => { stopAccelerometer(); }); -const startAccelerometer = defineAsyncApi(API_START_ACCELEROMETER, (_, {resolve, reject}) => { +const startAccelerometer = /* @__PURE__ */ defineAsyncApi(API_START_ACCELEROMETER, (_, {resolve, reject}) => { if (!window.DeviceMotionEvent) { reject(); return; @@ -12298,7 +12303,7 @@ const startAccelerometer = defineAsyncApi(API_START_ACCELEROMETER, (_, {resolve, } resolve(); }); -const stopAccelerometer = defineAsyncApi(API_STOP_ACCELEROMETER, (_, {resolve}) => { +const stopAccelerometer = /* @__PURE__ */ defineAsyncApi(API_STOP_ACCELEROMETER, (_, {resolve}) => { if (listener$1) { window.removeEventListener("devicemotion", listener$1, false); listener$1 = null; @@ -12306,13 +12311,13 @@ const stopAccelerometer = defineAsyncApi(API_STOP_ACCELEROMETER, (_, {resolve}) resolve(); }); let listener = null; -const onCompassChange = defineOnApi(API_ON_COMPASS, () => { +const onCompassChange = /* @__PURE__ */ defineOnApi(API_ON_COMPASS, () => { startCompass(); }); -const offCompassChange = defineOnApi(API_OFF_COMPASS, () => { +const offCompassChange = /* @__PURE__ */ defineOnApi(API_OFF_COMPASS, () => { stopCompass(); }); -const startCompass = defineAsyncApi(API_START_COMPASS, (_, {resolve, reject}) => { +const startCompass = /* @__PURE__ */ defineAsyncApi(API_START_COMPASS, (_, {resolve, reject}) => { if (!window.DeviceOrientationEvent) { reject(); return; @@ -12344,7 +12349,7 @@ const startCompass = defineAsyncApi(API_START_COMPASS, (_, {resolve, reject}) => } resolve(); }); -const stopCompass = defineAsyncApi(API_STOP_COMPASS, (_, {resolve}) => { +const stopCompass = /* @__PURE__ */ defineAsyncApi(API_STOP_COMPASS, (_, {resolve}) => { if (listener) { window.removeEventListener("deviceorientation", listener, false); listener = null; @@ -12352,14 +12357,14 @@ const stopCompass = defineAsyncApi(API_STOP_COMPASS, (_, {resolve}) => { resolve(); }); const _isSupport = !!window.navigator.vibrate; -const vibrateShort = defineAsyncApi(API_VIBRATE_SHORT, (args, {resolve, reject}) => { +const vibrateShort = /* @__PURE__ */ defineAsyncApi(API_VIBRATE_SHORT, (args, {resolve, reject}) => { if (_isSupport && window.navigator.vibrate(15)) { resolve(); } else { reject("vibrateLong:fail"); } }); -const vibrateLong = defineAsyncApi(API_VIBRATE_LONG, (args, {resolve, reject}) => { +const vibrateLong = /* @__PURE__ */ defineAsyncApi(API_VIBRATE_LONG, (args, {resolve, reject}) => { if (_isSupport && window.navigator.vibrate(400)) { resolve(); } else { @@ -12388,7 +12393,7 @@ function parseValue(value) { } catch (error) { } } -const setStorageSync = defineSyncApi(API_SET_STORAGE_SYNC, (key, data) => { +const setStorageSync = /* @__PURE__ */ defineSyncApi(API_SET_STORAGE_SYNC, (key, data) => { const type = typeof data; const value = type === "string" ? data : JSON.stringify({ type, @@ -12396,7 +12401,7 @@ const setStorageSync = defineSyncApi(API_SET_STORAGE_SYNC, (key, data) => { }); localStorage.setItem(key, value); }, SetStorageSyncProtocol); -const setStorage = defineAsyncApi(API_SET_STORAGE, ({key, data}, {resolve, reject}) => { +const setStorage = /* @__PURE__ */ defineAsyncApi(API_SET_STORAGE, ({key, data}, {resolve, reject}) => { try { setStorageSync(key, data); resolve(); @@ -12420,14 +12425,14 @@ function getStorageOrigin(key) { } return data; } -const getStorageSync = defineSyncApi(API_GET_STORAGE_SYNC, (key, t2) => { +const getStorageSync = /* @__PURE__ */ defineSyncApi(API_GET_STORAGE_SYNC, (key, t2) => { try { return getStorageOrigin(key); } catch (error) { return ""; } }, GetStorageSyncProtocol); -const getStorage = defineAsyncApi(API_GET_STORAGE, ({key}, {resolve, reject}) => { +const getStorage = /* @__PURE__ */ defineAsyncApi(API_GET_STORAGE, ({key}, {resolve, reject}) => { try { const data = getStorageOrigin(key); resolve({ @@ -12437,25 +12442,25 @@ const getStorage = defineAsyncApi(API_GET_STORAGE, ({key}, {resolve, reject}) => reject(error.message); } }, GetStorageProtocol); -const removeStorageSync = defineSyncApi(API_REMOVE_STORAGE, (key) => { +const removeStorageSync = /* @__PURE__ */ defineSyncApi(API_REMOVE_STORAGE, (key) => { if (localStorage) { localStorage.removeItem(key); } }, RemoveStorageSyncProtocol); -const removeStorage = defineAsyncApi(API_REMOVE_STORAGE, ({key}, {resolve}) => { +const removeStorage = /* @__PURE__ */ defineAsyncApi(API_REMOVE_STORAGE, ({key}, {resolve}) => { removeStorageSync(key); resolve(); }, RemoveStorageProtocol); -const clearStorageSync = defineSyncApi("clearStorageSync", () => { +const clearStorageSync = /* @__PURE__ */ defineSyncApi("clearStorageSync", () => { if (localStorage) { localStorage.clear(); } }); -const clearStorage = defineAsyncApi("clearStorage", (_, {resolve}) => { +const clearStorage = /* @__PURE__ */ defineAsyncApi("clearStorage", (_, {resolve}) => { clearStorageSync(); resolve(); }); -const getStorageInfoSync = defineSyncApi("getStorageInfoSync", () => { +const getStorageInfoSync = /* @__PURE__ */ defineSyncApi("getStorageInfoSync", () => { const length = localStorage && localStorage.length || 0; const keys = []; let currentSize = 0; @@ -12473,7 +12478,7 @@ const getStorageInfoSync = defineSyncApi("getStorageInfoSync", () => { limitSize: Number.MAX_VALUE }; }); -const getStorageInfo = defineAsyncApi("getStorageInfo", (_, {resolve}) => { +const getStorageInfo = /* @__PURE__ */ defineAsyncApi("getStorageInfo", (_, {resolve}) => { resolve(getStorageInfoSync()); }); const files = {}; @@ -12555,7 +12560,7 @@ function revokeObjectURL(url) { URL.revokeObjectURL(url); delete files[url]; } -const getFileInfo = defineAsyncApi(API_GET_FILE_INFO, ({filePath}, {resolve, reject}) => { +const getFileInfo = /* @__PURE__ */ defineAsyncApi(API_GET_FILE_INFO, ({filePath}, {resolve, reject}) => { urlToFile(filePath).then((res) => { resolve({ size: res.size @@ -12564,11 +12569,11 @@ const getFileInfo = defineAsyncApi(API_GET_FILE_INFO, ({filePath}, {resolve, rej reject(String(err)); }); }, GetFileInfoProtocol, GetFileInfoOptions); -const openDocument = defineAsyncApi(API_OPEN_DOCUMENT, ({filePath}, {resolve}) => { +const openDocument = /* @__PURE__ */ defineAsyncApi(API_OPEN_DOCUMENT, ({filePath}, {resolve}) => { window.open(filePath); return resolve(); }, OpenDocumentProtocol, OpenDocumentOptions); -const hideKeyboard = defineAsyncApi(API_HIDE_KEYBOARD, (args, {resolve, reject}) => { +const hideKeyboard = /* @__PURE__ */ defineAsyncApi(API_HIDE_KEYBOARD, (args, {resolve, reject}) => { const activeElement = document.activeElement; if (activeElement && (activeElement.tagName === "TEXTAREA" || activeElement.tagName === "INPUT")) { activeElement.blur(); @@ -12578,7 +12583,7 @@ const hideKeyboard = defineAsyncApi(API_HIDE_KEYBOARD, (args, {resolve, reject}) function getServiceAddress() { return window.location.protocol + "//" + window.location.host; } -const getImageInfo = defineAsyncApi(API_GET_IMAGE_INFO, ({src}, {resolve, reject}) => { +const getImageInfo = /* @__PURE__ */ defineAsyncApi(API_GET_IMAGE_INFO, ({src}, {resolve, reject}) => { const img = new Image(); img.onload = function() { resolve({ @@ -12592,7 +12597,7 @@ const getImageInfo = defineAsyncApi(API_GET_IMAGE_INFO, ({src}, {resolve, reject }; img.src = src; }, GetImageInfoProtocol, GetImageInfoOptions); -const getVideoInfo = defineAsyncApi(API_GET_VIDEO_INFO, ({src}, {resolve, reject}) => { +const getVideoInfo = /* @__PURE__ */ defineAsyncApi(API_GET_VIDEO_INFO, ({src}, {resolve, reject}) => { urlToFile(src, true).then((file) => { return file; }).catch(() => { @@ -12716,7 +12721,7 @@ function _createInput({ return inputEl; } let fileInput = null; -const chooseFile = defineAsyncApi(API_CHOOSE_FILE, ({ +const chooseFile = /* @__PURE__ */ defineAsyncApi(API_CHOOSE_FILE, ({ count, sourceType, type, @@ -12762,7 +12767,7 @@ const chooseFile = defineAsyncApi(API_CHOOSE_FILE, ({ fileInput.click(); }, ChooseFileProtocol, ChooseFileOptions); let imageInput = null; -const chooseImage = defineAsyncApi(API_CHOOSE_IMAGE, ({ +const chooseImage = /* @__PURE__ */ defineAsyncApi(API_CHOOSE_IMAGE, ({ count, sourceType, extension @@ -12807,7 +12812,7 @@ const chooseImage = defineAsyncApi(API_CHOOSE_IMAGE, ({ imageInput.click(); }, ChooseImageProtocol, ChooseImageOptions); let videoInput = null; -const chooseVideo = defineAsyncApi(API_CHOOSE_VIDEO, ({sourceType, extension}, {resolve, reject}) => { +const chooseVideo = /* @__PURE__ */ defineAsyncApi(API_CHOOSE_VIDEO, ({sourceType, extension}, {resolve, reject}) => { if (videoInput) { document.body.removeChild(videoInput); videoInput = null; @@ -12860,7 +12865,7 @@ const chooseVideo = defineAsyncApi(API_CHOOSE_VIDEO, ({sourceType, extension}, { }); videoInput.click(); }, ChooseVideoProtocol, ChooseVideoOptions); -const request = defineTaskApi(API_REQUEST, ({ +const request = /* @__PURE__ */ defineTaskApi(API_REQUEST, ({ url, data, header, @@ -13009,7 +13014,7 @@ class DownloadTask { throw new Error("Method not implemented."); } } -const downloadFile = defineTaskApi(API_DOWNLOAD_FILE, ({url, header, timeout = __uniConfig.networkTimeout.downloadFile}, {resolve, reject}) => { +const downloadFile = /* @__PURE__ */ defineTaskApi(API_DOWNLOAD_FILE, ({url, header, timeout = __uniConfig.networkTimeout.downloadFile}, {resolve, reject}) => { var timer; var xhr = new XMLHttpRequest(); var downloadTask = new DownloadTask(xhr); @@ -13095,7 +13100,7 @@ class UploadTask { throw new Error("Method not implemented."); } } -const uploadFile = defineTaskApi(API_UPLOAD_FILE, ({ +const uploadFile = /* @__PURE__ */ defineTaskApi(API_UPLOAD_FILE, ({ url, file, filePath, @@ -13283,7 +13288,7 @@ ${e2};at socketTask.on${capitalize(name)} callback function this._callbacks.close.push(callback2); } } -const connectSocket = defineTaskApi(API_CONNECT_SOCKET, ({url, protocols}, {resolve, reject}) => { +const connectSocket = /* @__PURE__ */ defineTaskApi(API_CONNECT_SOCKET, ({url, protocols}, {resolve, reject}) => { return new SocketTask(url, protocols, (error, socketTask) => { if (error) { reject(error.toString()); @@ -13307,7 +13312,7 @@ function callSocketTask(socketTask, method, option, resolve, reject) { })); } } -const sendSocketMessage = defineAsyncApi(API_SEND_SOCKET_MESSAGE, (options, {resolve, reject}) => { +const sendSocketMessage = /* @__PURE__ */ defineAsyncApi(API_SEND_SOCKET_MESSAGE, (options, {resolve, reject}) => { const socketTask = socketTasks[0]; if (socketTask && socketTask.readyState === socketTask.OPEN) { callSocketTask(socketTask, "send", options, resolve, reject); @@ -13315,7 +13320,7 @@ const sendSocketMessage = defineAsyncApi(API_SEND_SOCKET_MESSAGE, (options, {res reject("WebSocket is not connected"); } }, SendSocketMessageProtocol); -const closeSocket = defineAsyncApi(API_CLOSE_SOCKET, (options, {resolve, reject}) => { +const closeSocket = /* @__PURE__ */ defineAsyncApi(API_CLOSE_SOCKET, (options, {resolve, reject}) => { const socketTask = socketTasks[0]; if (socketTask) { callSocketTask(socketTask, "send", options, resolve, reject); @@ -13325,7 +13330,7 @@ const closeSocket = defineAsyncApi(API_CLOSE_SOCKET, (options, {resolve, reject} }, CloseSocketProtocol); function on(event) { const api2 = `onSocket${capitalize(event)}`; - return defineOnApi(api2, () => { + return /* @__PURE__ */ defineOnApi(api2, () => { globalEvent[event] = api2; }); } @@ -13365,7 +13370,7 @@ function getJSONP(url, options, success, error) { js.src = url + (url.indexOf("?") >= 0 ? "&" : "?") + callbackKey + "=" + callbackName; document.body.appendChild(js); } -const getLocation = defineAsyncApi(API_GET_LOCATION, ({type, altitude}, {resolve, reject}) => { +const getLocation = /* @__PURE__ */ defineAsyncApi(API_GET_LOCATION, ({type, altitude}, {resolve, reject}) => { const key = __uniConfig.qqMapKey; new Promise((resolve2, reject2) => { if (navigator.geolocation) { @@ -13422,7 +13427,7 @@ const getLocation = defineAsyncApi(API_GET_LOCATION, ({type, altitude}, {resolve reject(error.message); }); }, GetLocationProtocol, GetLocationOptions); -const navigateBack = defineAsyncApi(API_NAVIGATE_BACK, ({delta}, {resolve, reject}) => { +const navigateBack = /* @__PURE__ */ defineAsyncApi(API_NAVIGATE_BACK, ({delta}, {resolve, reject}) => { let canBack = true; if (invokeHook("onBackPress") === true) { canBack = false; @@ -13448,7 +13453,7 @@ function navigate(type, url, __id__) { }); }); } -const navigateTo = defineAsyncApi(API_NAVIGATE_TO, ({url}, {resolve, reject}) => navigate(API_NAVIGATE_TO, url).then(resolve).catch(reject), NavigateToProtocol, NavigateToOptions); +const navigateTo = /* @__PURE__ */ defineAsyncApi(API_NAVIGATE_TO, ({url}, {resolve, reject}) => navigate(API_NAVIGATE_TO, url).then(resolve).catch(reject), NavigateToProtocol, NavigateToOptions); function removeLastPage() { const page = getCurrentPage(); if (!page) { @@ -13457,7 +13462,7 @@ function removeLastPage() { const $page = page.$page; removePage(normalizeRouteKey($page.path, $page.id)); } -const redirectTo = defineAsyncApi(API_REDIRECT_TO, ({url}, {resolve, reject}) => { +const redirectTo = /* @__PURE__ */ defineAsyncApi(API_REDIRECT_TO, ({url}, {resolve, reject}) => { return removeLastPage(), navigate(API_REDIRECT_TO, url).then(resolve).catch(reject); }, RedirectToProtocol, RedirectToOptions); function removeAllPages() { @@ -13466,7 +13471,7 @@ function removeAllPages() { removePage(routeKey); } } -const reLaunch = defineAsyncApi(API_RE_LAUNCH, ({url}, {resolve, reject}) => { +const reLaunch = /* @__PURE__ */ defineAsyncApi(API_RE_LAUNCH, ({url}, {resolve, reject}) => { return removeAllPages(), navigate(API_RE_LAUNCH, url).then(resolve).catch(reject); }, ReLaunchProtocol, ReLaunchOptions); function removeNonTabBarPages() { @@ -13499,7 +13504,7 @@ function getTabBarPageId(url) { } } } -const switchTab = defineAsyncApi(API_SWITCH_TAB, ({url}, {resolve, reject}) => { +const switchTab = /* @__PURE__ */ defineAsyncApi(API_SWITCH_TAB, ({url}, {resolve, reject}) => { return removeNonTabBarPages(), navigate(API_SWITCH_TAB, url, getTabBarPageId(url)).then(resolve).catch(reject); }, SwitchTabProtocol, SwitchTabOptions); const KEY_MAPS = { @@ -13664,7 +13669,7 @@ function onModalClose(type) { cancel: type === "cancel" }); } -const showModal = defineAsyncApi(API_SHOW_MODAL, (args, {resolve}) => { +const showModal = /* @__PURE__ */ defineAsyncApi(API_SHOW_MODAL, (args, {resolve}) => { currentShowModalResolve = resolve; if (!showModalState) { showModalState = reactive(args); @@ -13785,7 +13790,7 @@ function createToast(args) { }); onHidePopupOnce(); } -const showToast = defineAsyncApi(API_SHOW_TOAST, (args, {resolve, reject}) => { +const showToast = /* @__PURE__ */ defineAsyncApi(API_SHOW_TOAST, (args, {resolve, reject}) => { createToast(args); showType = "onShowToast"; resolve(); @@ -13795,17 +13800,17 @@ const showLoadingDefaultState = { duration: 1e8, image: "" }; -const showLoading = defineAsyncApi(API_SHOW_LOADING, (args, {resolve, reject}) => { +const showLoading = /* @__PURE__ */ defineAsyncApi(API_SHOW_LOADING, (args, {resolve, reject}) => { extend(args, showLoadingDefaultState); createToast(args); showType = "onShowLoading"; resolve(); }, ShowLoadingProtocol, ShowLoadingOptions); -const hideToast = defineAsyncApi(API_HIDE_TOAST, (args, {resolve, reject}) => { +const hideToast = /* @__PURE__ */ defineAsyncApi(API_HIDE_TOAST, (args, {resolve, reject}) => { hidePopup("onHideToast"); resolve(); }); -const hideLoading = defineAsyncApi(API_HIDE_LOADING, (args, {resolve, reject}) => { +const hideLoading = /* @__PURE__ */ defineAsyncApi(API_HIDE_LOADING, (args, {resolve, reject}) => { hidePopup("onHideLoading"); resolve(); }); @@ -13828,7 +13833,7 @@ function hidePopup(type) { showToastState.visible = false; }, 10); } -const loadFontFace = defineAsyncApi(API_LOAD_FONT_FACE, ({family, source, desc}, {resolve, reject}) => { +const loadFontFace = /* @__PURE__ */ defineAsyncApi(API_LOAD_FONT_FACE, ({family, source, desc}, {resolve, reject}) => { addFont(family, source, desc).then(() => { resolve(); }).catch((err) => { @@ -13866,27 +13871,27 @@ function setNavigationBar(pageMeta, type, args, resolve, reject) { } resolve(); } -const setNavigationBarColor = defineAsyncApi(API_SET_NAVIGATION_BAR_COLOR, (args, {resolve, reject}) => { +const setNavigationBarColor = /* @__PURE__ */ defineAsyncApi(API_SET_NAVIGATION_BAR_COLOR, (args, {resolve, reject}) => { setNavigationBar(getCurrentPageMeta(), API_SET_NAVIGATION_BAR_COLOR, args, resolve, reject); }, SetNavigationBarColorProtocol, SetNavigationBarColorOptions); -const showNavigationBarLoading = defineAsyncApi(API_SHOW_NAVIGATION_BAR_LOADING, (args, {resolve, reject}) => { +const showNavigationBarLoading = /* @__PURE__ */ defineAsyncApi(API_SHOW_NAVIGATION_BAR_LOADING, (args, {resolve, reject}) => { setNavigationBar(getCurrentPageMeta(), API_SHOW_NAVIGATION_BAR_LOADING, args, resolve, reject); }); -const hideNavigationBarLoading = defineAsyncApi(API_HIDE_NAVIGATION_BAR_LOADING, (args, {resolve, reject}) => { +const hideNavigationBarLoading = /* @__PURE__ */ defineAsyncApi(API_HIDE_NAVIGATION_BAR_LOADING, (args, {resolve, reject}) => { setNavigationBar(getCurrentPageMeta(), API_HIDE_NAVIGATION_BAR_LOADING, args, resolve, reject); }); -const setNavigationBarTitle = defineAsyncApi(API_SET_NAVIGATION_BAR_TITLE, (args, {resolve, reject}) => { +const setNavigationBarTitle = /* @__PURE__ */ defineAsyncApi(API_SET_NAVIGATION_BAR_TITLE, (args, {resolve, reject}) => { setNavigationBar(getCurrentPageMeta(), API_SET_NAVIGATION_BAR_TITLE, args, resolve, reject); }, SetNavigationBarTitleProtocol); -const pageScrollTo = defineAsyncApi(API_PAGE_SCROLL_TO, ({scrollTop, selector, duration}, {resolve}) => { +const pageScrollTo = /* @__PURE__ */ defineAsyncApi(API_PAGE_SCROLL_TO, ({scrollTop, selector, duration}, {resolve}) => { scrollTo(selector || scrollTop || 0, duration); resolve(); }, PageScrollToProtocol, PageScrollToOptions); -const startPullDownRefresh = defineAsyncApi(API_START_PULL_DOWN_REFRESH, (_args, {resolve}) => { +const startPullDownRefresh = /* @__PURE__ */ defineAsyncApi(API_START_PULL_DOWN_REFRESH, (_args, {resolve}) => { UniServiceJSBridge.publishHandler(API_START_PULL_DOWN_REFRESH, {}, getCurrentPageId()); resolve(); }); -const stopPullDownRefresh = defineAsyncApi(API_STOP_PULL_DOWN_REFRESH, (_args, {resolve}) => { +const stopPullDownRefresh = /* @__PURE__ */ defineAsyncApi(API_STOP_PULL_DOWN_REFRESH, (_args, {resolve}) => { UniServiceJSBridge.publishHandler(API_STOP_PULL_DOWN_REFRESH, {}, getCurrentPageId()); resolve(); }); @@ -13963,28 +13968,28 @@ function setTabBar(type, args, resolve) { } resolve(); } -const setTabBarItem = defineAsyncApi(API_SET_TAB_BAR_ITEM, (args, {resolve}) => { +const setTabBarItem = /* @__PURE__ */ defineAsyncApi(API_SET_TAB_BAR_ITEM, (args, {resolve}) => { setTabBar(API_SET_TAB_BAR_ITEM, args, resolve); }, SetTabBarItemProtocol, SetTabBarItemOptions); -const setTabBarStyle = defineAsyncApi(API_SET_TAB_BAR_STYLE, (args, {resolve}) => { +const setTabBarStyle = /* @__PURE__ */ defineAsyncApi(API_SET_TAB_BAR_STYLE, (args, {resolve}) => { setTabBar(API_SET_TAB_BAR_STYLE, args, resolve); }, SetTabBarStyleProtocol, SetTabBarStyleOptions); -const hideTabBar = defineAsyncApi(API_HIDE_TAB_BAR, (args, {resolve}) => { +const hideTabBar = /* @__PURE__ */ defineAsyncApi(API_HIDE_TAB_BAR, (args, {resolve}) => { setTabBar(API_HIDE_TAB_BAR, args, resolve); }, HideTabBarProtocol); -const showTabBar = defineAsyncApi(API_SHOW_TAB_BAR, (args, {resolve}) => { +const showTabBar = /* @__PURE__ */ defineAsyncApi(API_SHOW_TAB_BAR, (args, {resolve}) => { setTabBar(API_SHOW_TAB_BAR, args, resolve); }, ShowTabBarProtocol); -const hideTabBarRedDot = defineAsyncApi(API_HIDE_TAB_BAR_RED_DOT, (args, {resolve}) => { +const hideTabBarRedDot = /* @__PURE__ */ defineAsyncApi(API_HIDE_TAB_BAR_RED_DOT, (args, {resolve}) => { setTabBar(API_HIDE_TAB_BAR_RED_DOT, args, resolve); }, HideTabBarRedDotProtocol, HideTabBarRedDotOptions); -const showTabBarRedDot = defineAsyncApi(API_SHOW_TAB_BAR_RED_DOT, (args, {resolve}) => { +const showTabBarRedDot = /* @__PURE__ */ defineAsyncApi(API_SHOW_TAB_BAR_RED_DOT, (args, {resolve}) => { setTabBar(API_SHOW_TAB_BAR_RED_DOT, args, resolve); }, ShowTabBarRedDotProtocol, ShowTabBarRedDotOptions); -const removeTabBarBadge = defineAsyncApi(API_REMOVE_TAB_BAR_BADGE, (args, {resolve}) => { +const removeTabBarBadge = /* @__PURE__ */ defineAsyncApi(API_REMOVE_TAB_BAR_BADGE, (args, {resolve}) => { setTabBar(API_REMOVE_TAB_BAR_BADGE, args, resolve); }, RemoveTabBarBadgeProtocol, RemoveTabBarBadgeOptions); -const setTabBarBadge = defineAsyncApi(API_SET_TAB_BAR_BADGE, (args, {resolve}) => { +const setTabBarBadge = /* @__PURE__ */ defineAsyncApi(API_SET_TAB_BAR_BADGE, (args, {resolve}) => { setTabBar(API_SET_TAB_BAR_BADGE, args, resolve); }, SetTabBarBadgeProtocol, SetTabBarBadgeOptions); var api = /* @__PURE__ */ Object.freeze({ @@ -14084,45 +14089,45 @@ const ICON_PATH = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIQAAACECAMAAAB var MapLocation = /* @__PURE__ */ defineComponent({ name: "MapLocation", setup() { - const onMapReady = inject("onMapReady"); const state = reactive({ latitude: 0, longitude: 0, rotate: 0 }); - let timer; - function compassChangeHandler(res) { - state.rotate = res.direction; - } - function updateLocation() { - getLocation({ - type: "gcj02", - success: (res) => { - state.latitude = res.latitude; - state.longitude = res.longitude; - }, - complete: () => { - timer = setTimeout(updateLocation, 3e4); + { + let compassChangeHandler = function(res) { + state.rotate = res.direction; + }, updateLocation = function() { + getLocation({ + type: "gcj02", + success: (res) => { + state.latitude = res.latitude; + state.longitude = res.longitude; + }, + complete: () => { + timer = setTimeout(updateLocation, 3e4); + } + }); + }, removeLocation = function() { + if (timer) { + clearTimeout(timer); } - }); - } - function removeLocation() { - if (timer) { - clearTimeout(timer); - } - offCompassChange(compassChangeHandler); + offCompassChange(compassChangeHandler); + }; + const onMapReady = inject("onMapReady"); + let timer; + onCompassChange(compassChangeHandler); + onMapReady(updateLocation); + onUnmounted(removeLocation); + const addMapChidlContext = inject("addMapChidlContext"); + const removeMapChidlContext = inject("removeMapChidlContext"); + const context = { + id: CONTEXT_ID, + state + }; + addMapChidlContext(context); + onUnmounted(() => removeMapChidlContext(context)); } - onCompassChange(compassChangeHandler); - onMapReady(updateLocation); - onUnmounted(removeLocation); - const addMapChidlContext = inject("addMapChidlContext"); - const removeMapChidlContext = inject("removeMapChidlContext"); - const context = { - id: CONTEXT_ID, - state - }; - addMapChidlContext(context); - onUnmounted(() => removeMapChidlContext(context)); return () => { return state.latitude ? createVNode(MapMarker, mergeProps({ anchor: { @@ -14594,7 +14599,7 @@ var TabBar = /* @__PURE__ */ defineComponent({ useTabBarCssVar(tabBar2); const onSwitchTab = useSwitchTab(useRoute(), tabBar2); const { - style: style2, + style, borderStyle, placeholderStyle } = useTabBarStyle(tabBar2); @@ -14604,7 +14609,7 @@ var TabBar = /* @__PURE__ */ defineComponent({ class: "uni-tabbar-" + tabBar2.position }, [createVNode("div", { class: "uni-tabbar", - style: style2.value + style: style.value }, [createVNode("div", { class: "uni-tabbar-border", style: borderStyle.value @@ -14678,7 +14683,7 @@ const BORDER_COLORS = { black: "rgba(0, 0, 0, 0.33)" }; function useTabBarStyle(tabBar2) { - const style2 = computed(() => { + const style = computed(() => { let backgroundColor = tabBar2.backgroundColor; const blurEffect = tabBar2.blurEffect; if (!backgroundColor) { @@ -14705,7 +14710,7 @@ function useTabBarStyle(tabBar2) { }; }); return { - style: style2, + style, borderStyle, placeholderStyle }; @@ -14758,13 +14763,13 @@ function createTabBarItemIconTsx(iconPath, tabBarItem, tabBar2) { iconWidth } = tabBar2; const clazz2 = "uni-tabbar__icon" + (text2 ? " uni-tabbar__icon__diff" : ""); - const style2 = { + const style = { width: iconWidth, height: iconWidth }; return createVNode("div", { class: clazz2, - style: style2 + style }, [type !== "midButton" && createVNode("img", { src: getRealPath(iconPath) }, null, 8, ["src"]), redDot && createTabBarItemRedDotTsx(tabBarItem.badge)], 6); @@ -14779,7 +14784,7 @@ function createTabBarItemTextTsx(color, tabBarItem, tabBar2) { fontSize, spacing } = tabBar2; - const style2 = { + const style = { color, fontSize, lineHeight: !iconPath ? 1.8 : "normal", @@ -14787,7 +14792,7 @@ function createTabBarItemTextTsx(color, tabBarItem, tabBar2) { }; return createVNode("div", { class: "uni-tabbar__label", - style: style2 + style }, [text2, redDot && !iconPath && createTabBarItemRedDotTsx(tabBarItem.badge)], 4); } function createTabBarItemRedDotTsx(badge) { @@ -14827,19 +14832,12 @@ function createTabBarMidButtonTsx(color, iconPath, midButton, tabBar2, index2, o }, null, 12, ["src"])], 4), createTabBarItemBdTsx(color, iconPath, midButton, tabBar2)], 12, ["onClick"]); } const DEFAULT_CSS_VAR_VALUE = "0px"; -updateCssVar({ - "--status-bar-height": DEFAULT_CSS_VAR_VALUE, - "--top-window-height": DEFAULT_CSS_VAR_VALUE, - "--window-left": DEFAULT_CSS_VAR_VALUE, - "--window-right": DEFAULT_CSS_VAR_VALUE, - "--window-margin": DEFAULT_CSS_VAR_VALUE, - "--tab-bar-height": DEFAULT_CSS_VAR_VALUE -}); var LayoutComponent = defineComponent({ name: "Layout", setup(_props, { emit: emit2 }) { + initCssVar(); const keepAliveRoute = __UNI_FEATURE_PAGES__ && useKeepAliveRoute(); __UNI_FEATURE_TOPWINDOW__ && useTopWindow(); __UNI_FEATURE_LEFTWINDOW__ && useLeftWindow(); @@ -14851,7 +14849,7 @@ var LayoutComponent = defineComponent({ const tabBarTsx = __UNI_FEATURE_TABBAR__ && createTabBarTsx(showTabBar2); return createVNode("uni-app", { class: clazz2.value - }, [[layoutTsx, tabBarTsx]], 2); + }, [layoutTsx, tabBarTsx], 2); }; } }); @@ -14864,6 +14862,16 @@ function useAppClass(showTabBar2) { }; }); } +function initCssVar() { + updateCssVar({ + "--status-bar-height": DEFAULT_CSS_VAR_VALUE, + "--top-window-height": DEFAULT_CSS_VAR_VALUE, + "--window-left": DEFAULT_CSS_VAR_VALUE, + "--window-right": DEFAULT_CSS_VAR_VALUE, + "--window-margin": DEFAULT_CSS_VAR_VALUE, + "--tab-bar-height": DEFAULT_CSS_VAR_VALUE + }); +} function createLayoutTsx(keepAliveRoute, topWindow, leftWindow, rightWindow) { const routerVNode = __UNI_FEATURE_PAGES__ ? createRouterViewVNode(keepAliveRoute) : createPageVNode(); if (!__UNI_FEATURE_RESPONSIVE__) { @@ -15050,7 +15058,7 @@ var PageHead = /* @__PURE__ */ defineComponent({ const navigationBar = pageMeta.navigationBar; const { clazz: clazz2, - style: style2 + style } = usePageHead(navigationBar); const buttons = __UNI_FEATURE_NAVIGATIONBAR_BUTTONS__ && usePageHeadButtons(pageMeta); const searchInput = __UNI_FEATURE_NAVIGATIONBAR_SEARCHINPUT__ && navigationBar.searchInput && usePageHeadSearchInput(pageMeta); @@ -15071,7 +15079,7 @@ var PageHead = /* @__PURE__ */ defineComponent({ }, [createVNode("div", { ref: headRef, class: clazz2.value, - style: style2.value + style: style.value }, [createVNode("div", { class: "uni-page-head-hd" }, [backButtonTsx, ...leftButtonsTsx]), createPageHeadBdTsx(navigationBar, searchInput), createVNode("div", { @@ -15234,7 +15242,7 @@ function usePageHead(navigationBar) { } return clazz3; }); - const style2 = computed(() => { + const style = computed(() => { const backgroundColor = __UNI_FEATURE_NAVIGATIONBAR_TRANSPARENT__ && navigationBar.type === "transparent" ? usePageHeadTransparentBackgroundColor(navigationBar.backgroundColor) : navigationBar.backgroundColor; return { backgroundColor, @@ -15245,7 +15253,7 @@ function usePageHead(navigationBar) { }); return { clazz: clazz2, - style: style2 + style }; } function usePageHeadButtons({ @@ -15637,7 +15645,7 @@ var PageBody = defineComponent({ const pageRefresh = __UNI_FEATURE_PULL_DOWN_REFRESH__ && pageMeta.enablePullDownRefresh ? usePageRefresh(refreshRef) : null; return () => { const pageRefreshTsx = __UNI_FEATURE_PULL_DOWN_REFRESH__ && createPageRefreshTsx(refreshRef, pageMeta); - return createVNode(Fragment, null, [pageRefreshTsx, createVNode("uni-page-wrapper", pageRefresh, [createVNode("uni-page-body", null, [renderSlot(ctx.slots, "default")])], 16)]); + return createVNode("div", null, [pageRefreshTsx, createVNode("uni-page-wrapper", pageRefresh, [createVNode("uni-page-body", null, [renderSlot(ctx.slots, "default")])], 16)]); }; } }); @@ -15652,7 +15660,7 @@ function createPageRefreshTsx(refreshRef, pageMeta) { var index$2 = defineComponent({ name: "Page", setup(_props, ctx) { - const {navigationBar} = providePageMeta(history.state && history.state.__id__ || 1); + const {navigationBar} = providePageMeta(getStateId()); return () => createVNode("uni-page", null, __UNI_FEATURE_NAVIGATIONBAR__ && navigationBar.style !== "custom" ? [createVNode(PageHead), createPageBodyVNode(ctx)] : [createPageBodyVNode(ctx)]); } }); diff --git a/packages/uni-h5/src/framework/components/layout/index.tsx b/packages/uni-h5/src/framework/components/layout/index.tsx index 5d50e0a07..591445f3a 100644 --- a/packages/uni-h5/src/framework/components/layout/index.tsx +++ b/packages/uni-h5/src/framework/components/layout/index.tsx @@ -25,17 +25,11 @@ import TabBar from './tabBar' type KeepAliveRoute = ReturnType const DEFAULT_CSS_VAR_VALUE = '0px' -updateCssVar({ - '--status-bar-height': DEFAULT_CSS_VAR_VALUE, - '--top-window-height': DEFAULT_CSS_VAR_VALUE, - '--window-left': DEFAULT_CSS_VAR_VALUE, - '--window-right': DEFAULT_CSS_VAR_VALUE, - '--window-margin': DEFAULT_CSS_VAR_VALUE, - '--tab-bar-height': DEFAULT_CSS_VAR_VALUE, -}) + export default defineComponent({ name: 'Layout', setup(_props, { emit }) { + !__NODE_JS__ && initCssVar() const keepAliveRoute = (__UNI_FEATURE_PAGES__ && useKeepAliveRoute()) as KeepAliveRoute const topWindow = __UNI_FEATURE_TOPWINDOW__ && useTopWindow() @@ -52,7 +46,12 @@ export default defineComponent({ rightWindow ) const tabBarTsx = __UNI_FEATURE_TABBAR__ && createTabBarTsx(showTabBar) - return {[layoutTsx, tabBarTsx]} + return ( + + {layoutTsx} + {tabBarTsx} + + ) } }, }) @@ -67,6 +66,17 @@ function useAppClass(showTabBar?: ComputedRef) { }) } +function initCssVar() { + updateCssVar({ + '--status-bar-height': DEFAULT_CSS_VAR_VALUE, + '--top-window-height': DEFAULT_CSS_VAR_VALUE, + '--window-left': DEFAULT_CSS_VAR_VALUE, + '--window-right': DEFAULT_CSS_VAR_VALUE, + '--window-margin': DEFAULT_CSS_VAR_VALUE, + '--tab-bar-height': DEFAULT_CSS_VAR_VALUE, + }) +} + function createLayoutTsx( keepAliveRoute: KeepAliveRoute, topWindow?: unknown, @@ -106,9 +116,10 @@ function useShowTabBar(emit: SetupContext<['change']>['emit']) { const tabBar = useTabBar()! // TODO meida query const showTabBar = computed(() => route.meta.isTabBar && tabBar.shown) - updateCssVar({ - '--tab-bar-height': tabBar.height!, - }) + !__NODE_JS__ && + updateCssVar({ + '--tab-bar-height': tabBar.height!, + }) return showTabBar } diff --git a/packages/uni-h5/src/framework/components/page/index.ts b/packages/uni-h5/src/framework/components/page/index.ts index c84d6f741..7cc357acf 100644 --- a/packages/uni-h5/src/framework/components/page/index.ts +++ b/packages/uni-h5/src/framework/components/page/index.ts @@ -11,13 +11,12 @@ import { import PageHead from './pageHead' import PageBody from './pageBody' import { providePageMeta } from '../../setup/provide' +import { getStateId } from '../../../helpers/dom' export default defineComponent({ name: 'Page', setup(_props, ctx) { - const { navigationBar } = providePageMeta( - (history.state && history.state.__id__) || 1 - ) + const { navigationBar } = providePageMeta(getStateId()) return () => createVNode( 'uni-page', diff --git a/packages/uni-h5/src/framework/components/page/pageBody.tsx b/packages/uni-h5/src/framework/components/page/pageBody.tsx index 43fbbf262..f06f0ee81 100644 --- a/packages/uni-h5/src/framework/components/page/pageBody.tsx +++ b/packages/uni-h5/src/framework/components/page/pageBody.tsx @@ -16,7 +16,9 @@ export default defineComponent({ ref(null)) as Ref const pageRefresh = - __UNI_FEATURE_PULL_DOWN_REFRESH__ && pageMeta.enablePullDownRefresh + !__NODE_JS__ && + __UNI_FEATURE_PULL_DOWN_REFRESH__ && + pageMeta.enablePullDownRefresh ? usePageRefresh(refreshRef) : null @@ -25,12 +27,12 @@ export default defineComponent({ __UNI_FEATURE_PULL_DOWN_REFRESH__ && createPageRefreshTsx(refreshRef, pageMeta) return ( - <> +
{pageRefreshTsx} {renderSlot(ctx.slots, 'default')} - +
) } }, diff --git a/packages/uni-h5/src/framework/plugin/router.ts b/packages/uni-h5/src/framework/plugin/router.ts index 0f7b4dc49..a983333be 100644 --- a/packages/uni-h5/src/framework/plugin/router.ts +++ b/packages/uni-h5/src/framework/plugin/router.ts @@ -4,6 +4,7 @@ import { createRouter, createWebHistory, createWebHashHistory, + createMemoryHistory, } from 'vue-router' import { getCurrentPages, normalizeRouteKey, removePage } from '../setup/page' @@ -44,6 +45,9 @@ function removeCurrentPages(delta: number = 1) { } function initHistory() { + if (__NODE_JS__) { + return createMemoryHistory() + } const history = __UNI_FEATURE_ROUTER_MODE__ === 'history' ? createWebHistory() diff --git a/packages/uni-h5/src/framework/setup/index.ts b/packages/uni-h5/src/framework/setup/index.ts index ffd2ab4d3..8a7f42970 100644 --- a/packages/uni-h5/src/framework/setup/index.ts +++ b/packages/uni-h5/src/framework/setup/index.ts @@ -60,7 +60,13 @@ export function setupPage(comp: any) { //初始化时,状态肯定是激活 instance.__isActive = true } + // node环境不触发Page生命周期 + if (__NODE_JS__) { + return route.query + } + const pageMeta = usePageMeta() + onBeforeMount(() => { onPageShow(instance, pageMeta) const { onLoad, onShow } = instance @@ -88,6 +94,7 @@ export function setupPage(comp: any) { onHide && invokeArrayFns(onHide) } }) + return route.query }, }) @@ -98,6 +105,10 @@ export function setupApp(comp: any) { init: initApp, setup(instance) { const route = usePageRoute() + // node环境不触发App生命周期 + if (__NODE_JS__) { + return route.query + } const onLaunch = () => { const { onLaunch, onShow } = instance const path = route.path.substr(1) diff --git a/packages/uni-h5/src/framework/setup/page.ts b/packages/uni-h5/src/framework/setup/page.ts index fa98ed40d..5ec6d007e 100644 --- a/packages/uni-h5/src/framework/setup/page.ts +++ b/packages/uni-h5/src/framework/setup/page.ts @@ -17,6 +17,7 @@ import { ON_REACH_BOTTOM_DISTANCE } from '@dcloudio/uni-shared' import { usePageMeta } from './provide' import { NavigateType } from '../../service/api/route/utils' import { updateCurPageCssVar } from '../../helpers/cssVar' +import { getStateId } from '../../helpers/dom' const SEP = '$$' @@ -65,7 +66,7 @@ export function removePage(routeKey: string, removeRouteCaches = true) { removeRouteCaches && removeRouteCache(routeKey) } -let id = /*#__PURE__*/ (() => (history.state && history.state.__id__) || 1)() +let id = /*#__PURE__*/ getStateId() export function createPageState(type: NavigateType, __id__?: number) { return { @@ -116,9 +117,7 @@ export function normalizeRouteKey(path: string, id: number) { export function useKeepAliveRoute() { const route = useRoute() - const routeKey = computed(() => - normalizeRouteKey(route.path, history.state.__id__ || 1) - ) + const routeKey = computed(() => normalizeRouteKey(route.path, getStateId())) const isTabBar = computed(() => route.meta.isTabBar) return { routeKey, diff --git a/packages/uni-h5/src/framework/setup/provide/page.ts b/packages/uni-h5/src/framework/setup/provide/page.ts index a2cccbc24..832ee6abb 100644 --- a/packages/uni-h5/src/framework/setup/provide/page.ts +++ b/packages/uni-h5/src/framework/setup/provide/page.ts @@ -94,7 +94,7 @@ function normalizePageMeta(pageMeta: UniApp.PageRouteMeta) { let offset = rpx2px(refreshOptions.offset) const { type } = navigationBar if (type !== 'transparent' && type !== 'none') { - offset += NAVBAR_HEIGHT + safeAreaInsets.top + offset += NAVBAR_HEIGHT + (__NODE_JS__ ? 0 : safeAreaInsets.top) } refreshOptions.offset = offset refreshOptions.height = rpx2px(refreshOptions.height) @@ -110,7 +110,7 @@ function normalizePageMeta(pageMeta: UniApp.PageRouteMeta) { navigationBar.titleColor = titleColor || '#fff' navigationBar.backgroundColor = backgroundColor || '#F7F7F7' } - if (__UNI_FEATURE_PAGES__ && history.state) { + if (!__NODE_JS__ && __UNI_FEATURE_PAGES__ && history.state) { // 首页执行了redirectTo const type = history.state.__type__ if ( diff --git a/packages/uni-h5/src/helpers/dom.ts b/packages/uni-h5/src/helpers/dom.ts index fa3797cda..2006b0793 100644 --- a/packages/uni-h5/src/helpers/dom.ts +++ b/packages/uni-h5/src/helpers/dom.ts @@ -12,3 +12,10 @@ export function checkMinWidth(minWidth: number) { ] return Math.max.apply(null, sizes) > minWidth } + +export function getStateId() { + if (__NODE_JS__) { + return 1 + } + return (history.state && history.state.__id__) || 1 +} diff --git a/packages/uni-h5/src/service/api/base/canIUse.ts b/packages/uni-h5/src/service/api/base/canIUse.ts index f510fadb0..e5e841d15 100644 --- a/packages/uni-h5/src/service/api/base/canIUse.ts +++ b/packages/uni-h5/src/service/api/base/canIUse.ts @@ -16,12 +16,16 @@ function cssSupports(css: string) { ) } -export const cssVar = /*#__PURE__*/ cssSupports('--a:0') -export const cssEnv = /*#__PURE__*/ cssSupports('top:env(a)') -export const cssConstant = /*#__PURE__*/ cssSupports('top:constant(a)') -export const cssBackdropFilter = /*#__PURE__*/ cssSupports( - 'backdrop-filter:blur(10px)' -) +export const cssVar = __NODE_JS__ ? true : /*#__PURE__*/ cssSupports('--a:0') +export const cssEnv = __NODE_JS__ + ? true + : /*#__PURE__*/ cssSupports('top:env(a)') +export const cssConstant = __NODE_JS__ + ? true + : /*#__PURE__*/ cssSupports('top:constant(a)') +export const cssBackdropFilter = __NODE_JS__ + ? true + : /*#__PURE__*/ cssSupports('backdrop-filter:blur(10px)') const SCHEMA_CSS = { 'css.var': cssVar, diff --git a/packages/uni-h5/src/service/api/index.ts b/packages/uni-h5/src/service/api/index.ts index f0c4dd8b7..1e2b69b4e 100644 --- a/packages/uni-h5/src/service/api/index.ts +++ b/packages/uni-h5/src/service/api/index.ts @@ -1,3 +1,6 @@ +//#if _NODE_JS_ +export * from './network/request' +//#else export * from './base/canIUse' export * from './context/createInnerAudioContext' @@ -58,3 +61,4 @@ export { createMapContext, onTabBarMidButtonTap, } from '@dcloudio/uni-api' +//#endif diff --git a/packages/uni-h5/src/view/components/map/MapLocation.tsx b/packages/uni-h5/src/view/components/map/MapLocation.tsx index cde4949a9..1b18821ca 100644 --- a/packages/uni-h5/src/view/components/map/MapLocation.tsx +++ b/packages/uni-h5/src/view/components/map/MapLocation.tsx @@ -1,10 +1,12 @@ import { defineComponent, inject, onUnmounted, reactive } from 'vue' import { useCustomEvent } from '@dcloudio/uni-components' +//#if !_NODE_JS_ import { onCompassChange, offCompassChange, getLocation, } from '../../../service/api' +//#endif import { Map } from './qqMap/types' import { QQMapsExt } from './qqMap' import MapMarker from './MapMarker' @@ -39,49 +41,51 @@ const ICON_PATH = export default /*#__PURE__*/ defineComponent({ name: 'MapLocation', setup() { - const onMapReady: OnMapReady = inject('onMapReady') as OnMapReady const state: State = reactive({ latitude: 0, longitude: 0, rotate: 0, }) - let timer: number - function compassChangeHandler(res: { direction: number }) { - state.rotate = res.direction - } - function updateLocation() { - getLocation({ - type: 'gcj02', - success: (res) => { - state.latitude = res.latitude - state.longitude = res.longitude - }, - complete: () => { - timer = setTimeout(updateLocation, 30000) - }, - }) - } - function removeLocation() { - if (timer) { - clearTimeout(timer) + if (!__NODE_JS__) { + const onMapReady: OnMapReady = inject('onMapReady') as OnMapReady + let timer: number + function compassChangeHandler(res: { direction: number }) { + state.rotate = res.direction } - offCompassChange(compassChangeHandler) - } - onCompassChange(compassChangeHandler) - onMapReady(updateLocation) - onUnmounted(removeLocation) - const addMapChidlContext: AddMapChidlContext = inject( - 'addMapChidlContext' - ) as AddMapChidlContext - const removeMapChidlContext: RemoveMapChidlContext = inject( - 'removeMapChidlContext' - ) as RemoveMapChidlContext - const context: Context = { - id: CONTEXT_ID, - state, + function updateLocation() { + getLocation({ + type: 'gcj02', + success: (res) => { + state.latitude = res.latitude + state.longitude = res.longitude + }, + complete: () => { + timer = setTimeout(updateLocation, 30000) + }, + }) + } + function removeLocation() { + if (timer) { + clearTimeout(timer) + } + offCompassChange(compassChangeHandler) + } + onCompassChange(compassChangeHandler) + onMapReady(updateLocation) + onUnmounted(removeLocation) + const addMapChidlContext: AddMapChidlContext = inject( + 'addMapChidlContext' + ) as AddMapChidlContext + const removeMapChidlContext: RemoveMapChidlContext = inject( + 'removeMapChidlContext' + ) as RemoveMapChidlContext + const context: Context = { + id: CONTEXT_ID, + state, + } + addMapChidlContext(context) + onUnmounted(() => removeMapChidlContext(context)) } - addMapChidlContext(context) - onUnmounted(() => removeMapChidlContext(context)) return () => { return state.latitude ? ( ): Record; +export declare function getEnvLocale(): string; + export declare function getLen(str?: string): number; export declare const invokeArrayFns: (fns: Function[], arg?: any) => any; diff --git a/packages/uni-shared/dist/uni-shared.es.js b/packages/uni-shared/dist/uni-shared.es.js index 27e43e652..bd0137cf2 100644 --- a/packages/uni-shared/dist/uni-shared.es.js +++ b/packages/uni-shared/dist/uni-shared.es.js @@ -293,4 +293,10 @@ const RESPONSIVE_MIN_WIDTH = 768; const COMPONENT_NAME_PREFIX = 'VUni'; const PRIMARY_COLOR = '#007aff'; -export { BUILT_IN_TAGS, COMPONENT_NAME_PREFIX, COMPONENT_PREFIX, COMPONENT_SELECTOR_PREFIX, NAVBAR_HEIGHT, ON_REACH_BOTTOM_DISTANCE, PLUS_RE, PRIMARY_COLOR, RESPONSIVE_MIN_WIDTH, TABBAR_HEIGHT, TAGS, addFont, debounce, decode, decodedQuery, getLen, invokeArrayFns, isBuiltInComponent, isCustomElement, isNativeTag, normalizeDataset, normalizeTarget, once, parseQuery, passive, plusReady, removeLeadingSlash, scrollTo, stringifyQuery, updateElementStyle }; +function getEnvLocale() { + const { env } = process; + const lang = env.LC_ALL || env.LC_MESSAGES || env.LANG || env.LANGUAGE; + return (lang && lang.replace(/[.:].*/, '')) || 'en'; +} + +export { BUILT_IN_TAGS, COMPONENT_NAME_PREFIX, COMPONENT_PREFIX, COMPONENT_SELECTOR_PREFIX, NAVBAR_HEIGHT, ON_REACH_BOTTOM_DISTANCE, PLUS_RE, PRIMARY_COLOR, RESPONSIVE_MIN_WIDTH, TABBAR_HEIGHT, TAGS, addFont, debounce, decode, decodedQuery, getEnvLocale, getLen, invokeArrayFns, isBuiltInComponent, isCustomElement, isNativeTag, normalizeDataset, normalizeTarget, once, parseQuery, passive, plusReady, removeLeadingSlash, scrollTo, stringifyQuery, updateElementStyle }; diff --git a/packages/uni-shared/src/index.ts b/packages/uni-shared/src/index.ts index fdbb40500..b996ddc61 100644 --- a/packages/uni-shared/src/index.ts +++ b/packages/uni-shared/src/index.ts @@ -5,3 +5,5 @@ export * from './utils' export * from './query' export * from './debounce' export * from './constants' + +export * from './node/locale' diff --git a/packages/uni-shared/src/node/locale.ts b/packages/uni-shared/src/node/locale.ts new file mode 100644 index 000000000..711ba9673 --- /dev/null +++ b/packages/uni-shared/src/node/locale.ts @@ -0,0 +1,5 @@ +export function getEnvLocale() { + const { env } = process + const lang = env.LC_ALL || env.LC_MESSAGES || env.LANG || env.LANGUAGE + return (lang && lang.replace(/[.:].*/, '')) || 'en' +} diff --git a/packages/vite-plugin-uni/package.json b/packages/vite-plugin-uni/package.json index df412339a..5ed3032ff 100644 --- a/packages/vite-plugin-uni/package.json +++ b/packages/vite-plugin-uni/package.json @@ -29,6 +29,7 @@ "jsonc-parser": "^3.0.0", "magic-string": "^0.25.7", "mime": "^2.5.2", + "module-alias": "^2.2.2", "postcss-selector-parser": "^6.0.4", "rollup-plugin-copy": "^3.4.0", "slash": "^3.0.0" @@ -41,6 +42,7 @@ }, "devDependencies": { "@types/mime": "^2.0.3", + "@types/module-alias": "^2.0.0", "@types/sass": "^1.16.0", "@vue/compiler-sfc": "^3.0.11" }, diff --git a/packages/vite-plugin-uni/src/config/define.ts b/packages/vite-plugin-uni/src/config/define.ts index bad8a1db4..f0c674da4 100644 --- a/packages/vite-plugin-uni/src/config/define.ts +++ b/packages/vite-plugin-uni/src/config/define.ts @@ -8,13 +8,18 @@ import { initFeatures } from '../utils' export function createDefine( { inputDir, platform }: VitePluginUniResolvedOptions, + { server }: UserConfig, { command }: ConfigEnv ): UserConfig['define'] { - return initFeatures({ + const features = initFeatures({ inputDir, command, platform, pagesJson: parsePagesJsonOnce(inputDir, platform), manifestJson: parseManifestJsonOnce(inputDir), }) + if (server && server.middlewareMode) { + Object.assign(globalThis, features) + } + return features } diff --git a/packages/vite-plugin-uni/src/config/index.ts b/packages/vite-plugin-uni/src/config/index.ts index 761fd5fdc..947e8695d 100644 --- a/packages/vite-plugin-uni/src/config/index.ts +++ b/packages/vite-plugin-uni/src/config/index.ts @@ -28,7 +28,7 @@ export function createConfig( options.platform = (process.env.UNI_PLATFORM as UniApp.PLATFORM) || 'h5' options.inputDir = normalizeInputDir(config) options.compiler.init() - const define = createDefine(options, env) + const define = createDefine(options, config, env) return { define: extend(define, options.compiler.define()), resolve: createResolve(options, config), diff --git a/packages/vite-plugin-uni/src/configResolved/config.ts b/packages/vite-plugin-uni/src/configResolved/config.ts new file mode 100644 index 000000000..8e5b9493c --- /dev/null +++ b/packages/vite-plugin-uni/src/configResolved/config.ts @@ -0,0 +1,26 @@ +import { ResolvedConfig } from 'vite' +import { parserOptions } from '@vue/compiler-dom' +import { isNativeTag } from '@dcloudio/uni-shared' +// import alias from 'module-alias' +export function initConfig(config: ResolvedConfig) { + if (config.server.middlewareMode) { + // TODO compiler-ssr时,传入的 isNativeTag 会被 @vue/compiler-dom 的 isNativeTag 覆盖 + // https://github.com/vuejs/vue-next/blob/master/packages/compiler-ssr/src/index.ts#L36 + parserOptions.isNativeTag = isNativeTag + } + // let ssr = (config as any).ssr as SSROptions + // if (!ssr) { + // ssr = {} + // } + // if (ssr.external) { + // const index = ssr.external.findIndex((name) => name === 'vue') + // if (index !== -1) { + // ssr.external.splice(index, 1) + // } + // } + // if (!ssr.noExternal) { + // ssr.noExternal = ['vue'] + // } else if (!ssr.noExternal.includes('vue')) { + // ssr.noExternal.push('vue') + // } +} diff --git a/packages/vite-plugin-uni/src/configResolved/index.ts b/packages/vite-plugin-uni/src/configResolved/index.ts index 71b5cb424..133fc1738 100644 --- a/packages/vite-plugin-uni/src/configResolved/index.ts +++ b/packages/vite-plugin-uni/src/configResolved/index.ts @@ -4,15 +4,16 @@ import { VitePluginUniResolvedOptions } from '..' import { initEnv } from './env' import { initLogger } from './logger' +import { initConfig } from './config' import { initOptions } from './options' import { initPlugins } from './plugins' export function createConfigResolved(options: VitePluginUniResolvedOptions) { return ((config) => { initEnv(config) + initConfig(config) initOptions(options, config) initPlugins(config, options) - if (options.command === 'serve') { initLogger(config) } diff --git a/packages/vite-plugin-uni/src/configResolved/plugins/index.ts b/packages/vite-plugin-uni/src/configResolved/plugins/index.ts index f0927a4f0..cbb1b9356 100644 --- a/packages/vite-plugin-uni/src/configResolved/plugins/index.ts +++ b/packages/vite-plugin-uni/src/configResolved/plugins/index.ts @@ -145,7 +145,7 @@ export function initPlugins( addPlugin(plugins, uniPageVuePlugin(options), 'vite:vue') addPlugin(plugins, uniJsonPlugin(options), 'vite:json', 'pre') addPlugin(plugins, uniStaticPlugin(options, config), 'vite:asset', 'pre') - if (command === 'build') { + if (command === 'build' && !config.build.ssr) { addPlugin(plugins, uniCopyPlugin(options), plugins.length) } if (process.env.DEBUG) { diff --git a/packages/vite-plugin-uni/src/configResolved/plugins/mainJs.ts b/packages/vite-plugin-uni/src/configResolved/plugins/mainJs.ts index a8e1a3d91..90aee79a6 100644 --- a/packages/vite-plugin-uni/src/configResolved/plugins/mainJs.ts +++ b/packages/vite-plugin-uni/src/configResolved/plugins/mainJs.ts @@ -15,7 +15,7 @@ export function uniMainJsPlugin(options: VitePluginUniResolvedOptions): Plugin { let wrapperCode = `function createApp(rootComponent,rootProps){return createVueApp(rootComponent, rootProps).use(plugin)}` if (code.includes('createSSRApp')) { code = code.replace('createSSRApp', 'createVueSSRApp') - wrapperCode = `function createSSRApp(rootComponent,rootProps){return createVueSSRApp(rootComponent, rootProps).use(plugin)}` + wrapperCode = `function createSSRApp(App){return createVueSSRApp(App).use(plugin)}` } else { code = code.replace('createApp', 'createVueApp') } diff --git a/packages/vite-plugin-uni/src/configResolved/plugins/pagesJson.ts b/packages/vite-plugin-uni/src/configResolved/plugins/pagesJson.ts index 6ade8ceaa..adb396105 100644 --- a/packages/vite-plugin-uni/src/configResolved/plugins/pagesJson.ts +++ b/packages/vite-plugin-uni/src/configResolved/plugins/pagesJson.ts @@ -29,13 +29,17 @@ export function uniPagesJsonPlugin( return pagesJsonPath + '.js' } }, - transform(code, id) { + transform(code, id, ssr) { if (id.endsWith(PAGES_JSON_JS)) { return { code: - (config.define!.__UNI_FEATURE_RPX__ ? registerGlobalCode : '') + - (options.command === 'serve' ? registerDevServerGlobalCode : '') + - generatePagesJsonCode(code, config, options), + (config.define!.__UNI_FEATURE_RPX__ + ? registerGlobalCode(ssr) + : '') + + (options.command === 'serve' + ? registerDevServerGlobalCode(ssr) + : '') + + generatePagesJsonCode(ssr, code, config, options), map: { mappings: '' }, } } @@ -55,14 +59,16 @@ interface PageRouteOptions { } function generatePagesJsonCode( + ssr: boolean | undefined, jsonStr: string, config: ResolvedConfig, options: VitePluginUniResolvedOptions ) { + const globalName = getGlobal(ssr) const pagesJson = normalizePagesJson(jsonStr, options.platform) const definePagesCode = generatePagesDefineCode(pagesJson, config) - const uniRoutesCode = generateRoutes(pagesJson) - const uniConfigCode = generateConfig(pagesJson, options) + const uniRoutesCode = generateRoutes(globalName, pagesJson) + const uniConfigCode = generateConfig(globalName, pagesJson, options) const manifestJsonPath = slash( path.resolve(options.inputDir, 'manifest.json.js') ) @@ -90,17 +96,26 @@ const hmrCode = `if(import.meta.hot){ }) }` -const registerGlobalCode = `import {upx2px} from '@dcloudio/uni-h5' -window.rpx2px = upx2px -` +function getGlobal(ssr?: boolean) { + return ssr ? 'global' : 'window' +} -const registerDevServerGlobalCode = `import {uni,getCurrentPages,getApp,UniServiceJSBridge,UniViewJSBridge} from '@dcloudio/uni-h5' -window.getApp = getApp -window.getCurrentPages = getCurrentPages -window.uni = uni -window.UniViewJSBridge = UniViewJSBridge -window.UniServiceJSBridge = UniServiceJSBridge +function registerGlobalCode(ssr?: boolean) { + const name = getGlobal(ssr) + return `import {upx2px} from '@dcloudio/uni-h5' +${name}.rpx2px = upx2px ` +} +function registerDevServerGlobalCode(ssr?: boolean) { + const name = getGlobal(ssr) + return `import {uni,getCurrentPages,getApp,UniServiceJSBridge,UniViewJSBridge} from '@dcloudio/uni-h5' +${name}.getApp = getApp +${name}.getCurrentPages = getCurrentPages +${name}.uni = uni +${name}.UniViewJSBridge = UniViewJSBridge +${name}.UniServiceJSBridge = UniServiceJSBridge +` +} function normalizePageIdentifier(path: string) { return capitalize(camelize(path.replace(/\//g, '-'))) @@ -220,17 +235,18 @@ function generatePagesRoute(pagesRouteOptions: PageRouteOptions[]) { return pagesRouteOptions.map((pageOptions) => generatePageRoute(pageOptions)) } -function generateRoutes(pagesJson: UniApp.PagesJson) { +function generateRoutes(globalName: string, pagesJson: UniApp.PagesJson) { return ` function renderPage(component){ return (openBlock(), createBlock(PageComponent, null, {page: withCtx(() => [createVNode(component, { ref: "page" }, null, 512 /* NEED_PATCH */)]), _: 1 /* STABLE */})) } -window.__uniRoutes=[${[ +${globalName}.__uniRoutes=[${[ ...generatePagesRoute(normalizePagesRoute(pagesJson)), ].join(',')}]` } function generateConfig( + globalName: string, pagesJson: Record, options: VitePluginUniResolvedOptions ) { @@ -241,10 +257,10 @@ function generateConfig( return ( (options.command === 'serve' ? '' - : `window['____'+appid+'____']=true -delete window['____'+appid+'____'] + : `${globalName}['____'+appid+'____']=true +delete ${globalName}['____'+appid+'____'] `) + - `window.__uniConfig=Object.assign(${JSON.stringify(pagesJson)},{ + `${globalName}.__uniConfig=Object.assign(${JSON.stringify(pagesJson)},{ async, debug, networkTimeout, diff --git a/packages/vite-plugin-uni/src/utils/ssr.ts b/packages/vite-plugin-uni/src/utils/ssr.ts new file mode 100644 index 000000000..ebb95a019 --- /dev/null +++ b/packages/vite-plugin-uni/src/utils/ssr.ts @@ -0,0 +1,44 @@ +function serializeDefine(define: Record): string { + let res = `{` + for (const key in define) { + const val = define[key] + res += `${JSON.stringify(key)}: ${ + typeof val === 'string' ? `(${val})` : JSON.stringify(val) + }, ` + } + return res + `}` +} + +export function generateSSREnvCode(define: Record): string { + return envCode.replace('__DEFINES__', serializeDefine(define)) +} + +const envCode = `const context = (() => { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof window !== 'undefined') { + return window; + } + else { + return Function('return this')(); + } +})(); +// assign defines +const defines = __DEFINES__; +Object.keys(defines).forEach((key) => { + const segments = key.split('.'); + let target = context; + for (let i = 0; i < segments.length; i++) { + const segment = segments[i]; + if (i === segments.length - 1) { + target[segment] = defines[key]; + } + else { + target = target[segment] || (target[segment] = {}); + } + } +});` diff --git a/rollup.config.js b/rollup.config.js index 81dcda63d..282d17b2c 100644 --- a/rollup.config.js +++ b/rollup.config.js @@ -85,7 +85,7 @@ function createConfig(entryFile, output, plugins = []) { namedExports: false, }), tsPlugin, - createReplacePlugin(buildOptions), + createReplacePlugin(buildOptions, output.format), ...plugins, ], output, @@ -113,10 +113,11 @@ function createAliasPlugin(buildOptions) { return alias(buildOptions.alias || {}) } -function createReplacePlugin(buildOptions) { +function createReplacePlugin(buildOptions, format) { const replacements = { __DEV__: `(process.env.NODE_ENV !== 'production')`, __TEST__: false, + __NODE_JS__: format === 'cjs', } if (buildOptions.replacements) { Object.assign(replacements, buildOptions.replacements) diff --git a/scripts/build.js b/scripts/build.js index 4f5271f56..ab347792f 100644 --- a/scripts/build.js +++ b/scripts/build.js @@ -56,11 +56,20 @@ async function build(target) { const env = devOnly ? 'development' : 'production' if (bundler === 'vite') { + await execa( + 'vite', + ['build', '--config', path.resolve(pkgDir, 'vite.config.ts')], + { + stdio: 'inherit', + env: Object.assign({ FORMAT: 'es' }, process.env), + } + ) return await execa( 'vite', ['build', '--config', path.resolve(pkgDir, 'vite.config.ts')], { stdio: 'inherit', + env: Object.assign({ FORMAT: 'cjs' }, process.env), } ) } else if (bundler === 'tsc') { diff --git a/yarn.lock b/yarn.lock index 964e7c41f..382be1789 100644 --- a/yarn.lock +++ b/yarn.lock @@ -543,6 +543,16 @@ "@types/yargs" "^15.0.0" chalk "^4.0.0" +"@jsbits/escape-regex-str@^1.0.2": + version "1.0.3" + resolved "https://registry.yarnpkg.com/@jsbits/escape-regex-str/-/escape-regex-str-1.0.3.tgz#d35a2d21dfdc81a0e5ebeb68b6a16e17ca36ad20" + integrity sha512-0800vYI2fg1nuUq/T9Tqv8DMOLLNiRAltxFbKIbR7szrvW6qTuI2+zGK51hV7NAAmUr4G83Kvpj2R6Yyg07iIw== + +"@jsbits/get-package-version@^1.0.2", "@jsbits/get-package-version@^1.0.3": + version "1.0.3" + resolved "https://registry.yarnpkg.com/@jsbits/get-package-version/-/get-package-version-1.0.3.tgz#a47dfd077420beee435580c3bc197931fe3c694c" + integrity sha512-IJy1jRL01x7p6UEpgKa1lVLstMUx8EiIR8pPoS5sBfsHEoeLkzYiNpAfxPx8zLDUJyS1yBbChJjcWdPqyH285w== + "@microsoft/api-extractor-model@7.13.0": version "7.13.0" resolved "https://registry.yarnpkg.com/@microsoft/api-extractor-model/-/api-extractor-model-7.13.0.tgz#11327c1ab32939a375596859a27ec256eb17d68e" @@ -869,6 +879,11 @@ resolved "https://registry.yarnpkg.com/@types/minimatch/-/minimatch-3.0.4.tgz#f0ec25dbf2f0e4b18647313ac031134ca5b24b21" integrity sha512-1z8k4wzFnNjVK/tlxvrWuK5WMt6mydWWP7+zvH5eFep4oj+UkrfiJTRtjCeBXNpwaA/FYqqtb4/QS4ianFpIRA== +"@types/module-alias@^2.0.0": + version "2.0.0" + resolved "https://registry.yarnpkg.com/@types/module-alias/-/module-alias-2.0.0.tgz#882668f8b8cdbda44812c3b592c590909e18849e" + integrity sha512-e3sW4oEH0qS1QxSfX7PT6xIi5qk/YSMsrB9Lq8EtkhQBZB+bKyfkP+jpLJRySanvBhAQPSv2PEBe81M8Iy/7yg== + "@types/node@*": version "15.0.1" resolved "https://registry.yarnpkg.com/@types/node/-/node-15.0.1.tgz#ef34dea0881028d11398be5bf4e856743e3dc35a" @@ -3838,6 +3853,17 @@ jsbn@~0.1.0: resolved "https://registry.yarnpkg.com/jsbn/-/jsbn-0.1.1.tgz#a5e654c2e5a2deb5f201d96cefbca80c0ef2f513" integrity sha1-peZUwuWi3rXyAdls77yoDA7y9RM= +jscc@^1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/jscc/-/jscc-1.1.1.tgz#fb329325773a80bcf3e3db3acec6a3f21e61ed0e" + integrity sha512-anpZkTXwZbxfxLEBMciKxXMHx2xOLK2qhynIhTnoSyC+wGOEPrAoofxnADgblbarn0kijVMt1U71cQGmRF/1Og== + dependencies: + "@jsbits/escape-regex-str" "^1.0.2" + "@jsbits/get-package-version" "^1.0.2" + magic-string "^0.25.1" + perf-regexes "^1.0.1" + skip-regex "^1.0.2" + jsdom@^16.4.0: version "16.5.3" resolved "https://registry.yarnpkg.com/jsdom/-/jsdom-16.5.3.tgz#13a755b3950eb938b4482c407238ddf16f0d2136" @@ -4241,7 +4267,7 @@ magic-string@^0.22.5: dependencies: vlq "^0.2.2" -magic-string@^0.25.7: +magic-string@^0.25.1, magic-string@^0.25.7: version "0.25.7" resolved "https://registry.yarnpkg.com/magic-string/-/magic-string-0.25.7.tgz#3f497d6fd34c669c6798dcb821f2ef31f5445051" integrity sha512-4CrMT5DOHTDk4HYDlzmwu4FVCcIYI8gauveasrdCu2IKIFOJ3f0v/8MDGJCDL9oD2ppz/Av1b0Nj345H9M+XIA== @@ -4772,6 +4798,11 @@ pend@~1.2.0: resolved "https://registry.yarnpkg.com/pend/-/pend-1.2.0.tgz#7a57eb550a6783f9115331fcf4663d5c8e007a50" integrity sha1-elfrVQpng/kRUzH89GY9XI4AelA= +perf-regexes@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/perf-regexes/-/perf-regexes-1.0.1.tgz#6da1d62f5a94bf9353a0451bccacf69068b75d0b" + integrity sha512-L7MXxUDtqr4PUaLFCDCXBfGV/6KLIuSEccizDI7JxT+c9x1G1v04BQ4+4oag84SHaCdrBgQAIs/Cqn+flwFPng== + performance-now@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/performance-now/-/performance-now-2.1.0.tgz#6309f4e0e5fa913ec1c69307ae364b4b377c9e7b" @@ -5268,6 +5299,15 @@ rollup-plugin-copy@^3.4.0: globby "10.0.1" is-plain-object "^3.0.0" +rollup-plugin-jscc@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/rollup-plugin-jscc/-/rollup-plugin-jscc-2.0.0.tgz#1ad2f74ab3248dcaaa5ebff0b838418e22243ce6" + integrity sha512-5jG9q79K2u5uRBTKA+GA4gqt1zA7qHQRpcabZMoVs913gr75s428O7K3r58n2vADDzwIhiOKMo7rCMhOyks6dw== + dependencies: + "@jsbits/get-package-version" "^1.0.3" + jscc "^1.1.1" + rollup-pluginutils "^2.8.2" + rollup-plugin-node-builtins@^2.1.2: version "2.1.2" resolved "https://registry.yarnpkg.com/rollup-plugin-node-builtins/-/rollup-plugin-node-builtins-2.1.2.tgz#24a1fed4a43257b6b64371d8abc6ce1ab14597e9" @@ -5512,6 +5552,11 @@ size-limit@^4.10.1: ora "^5.4.0" read-pkg-up "^7.0.1" +skip-regex@^1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/skip-regex/-/skip-regex-1.0.2.tgz#ac655d77e7c771ac2b9f37585fea37bff56ad65b" + integrity sha512-pEjMUbwJ5Pl/6Vn6FsamXHXItJXSRftcibixDmNCWbWhic0hzHrwkMZo0IZ7fMRH9KxcWDFSkzhccB4285PutA== + slash@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/slash/-/slash-3.0.0.tgz#6539be870c165adbd5240220dbe361f1bc4d4634" -- GitLab