Files
OpenMaopaoya/frontend-uni/node_modules/@dcloudio/uni-h5/dist-x-vapor/uni-h5.es.js
T

35216 lines
1.1 MiB
Plaintext

import { getGlobal, UTS as UTS$1, UTSJSONObject, UTSValueIterable, UniError as UniError$1, getUniElementPage, initVaporDataset, once, UNI_STORAGE_LOCALE, I18N_JSON_DELIMITERS, Emitter, passive, resolveComponentInstance, normalizeStyles, addLeadingSlash, ON_BACK_PRESS, invokeArrayFnsWithResults, invokeArrayFns, removeLeadingSlash, ON_SHOW, ON_HIDE, resolveOwnerVm, resolveOwnerEl, ON_WXS_INVOKE_CALL_METHOD, ON_RESIZE, ON_APP_ENTER_FOREGROUND, ON_APP_ENTER_BACKGROUND, ON_PAGE_SCROLL, ON_REACH_BOTTOM, EventChannel, LINEFEED, parseQuery, NAVBAR_HEIGHT, ON_ERROR, callOptions, ON_UNHANDLE_REJECTION, ON_PAGE_NOT_FOUND, getLen, getCustomDataset, createUniDOMStringMap, parseUrl, stringifyQuery as stringifyQuery$1, decodedQuery, ON_THEME_CHANGE, ON_REACH_BOTTOM_DISTANCE, normalizeTitleColor, setUniElementPage, ON_UNLOAD, SCHEME_RE, DATA_RE, addFont, ON_NAVIGATION_BAR_CHANGE, RESPONSIVE_MIN_WIDTH, debounce, WEB_INVOKE_APPSERVICE, ON_WEB_INVOKE_APP_SERVICE, ON_NAVIGATION_BAR_BUTTON_TAP, ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED, ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED, ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED, ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED, ON_PULL_DOWN_REFRESH, PRIMARY_COLOR, ON_LOAD, ON_READY, isUniLifecycleHook, UniLifecycleHooks, invokeCreateErrorHandler, invokeCreateVueAppHook, ON_HOST_THEME_CHANGE, OFF_HOST_THEME_CHANGE, OFF_THEME_CHANGE, updateElementStyle, scrollTo, onCreateVueApp } from "@dcloudio/uni-shared";
import { UTS as UTS2, UTSJSONObject as UTSJSONObject2, UTSValueIterable as UTSValueIterable2, UniError as UniError2, onCreateVueApp as onCreateVueApp2 } from "@dcloudio/uni-shared";
import * as Vue from "vue";
import { defineVaporComponent, createPlainElement, template, ref, watch, withModifiers, setAttr, getCurrentInstance, warn, unref, reactive, onMounted, onBeforeUnmount, computed, inject, onBeforeMount, nextTick, Fragment, EffectScope, createTemplateRefSetter, child, next, renderEffect, setDynamicProps, applyVShow, txt, setInsertionState, createIf, on as on$1, setBlockKey, setValue as setValue$1, setProp, setClass, setStyle, onActivated, setClassName, shallowRef, watchEffect, provide, injectHook, isReactive, markRaw, querySelectorInComponent, querySelectorAllInComponent, createFor, setText, toDisplayString, withComponentId, createDynamicComponent, setStaticTemplateRef, createComponent as createComponent$1, VaporKeepAlive, extend as extend$1, onServerPrefetch, initUniPageHooks, onBeforeActivate, onBeforeDeactivate, onUnmounted, initUniElementType, initUniElement, setHtml, createSlot, toRaw, createKeyedFragment, createTextNode, remove as remove$1, effectScope, insert, syncSelectValue, setHover, createComponentWithFallback, useAttrs as useAttrs$1, useSlots, getBlockFirstNode, isInSSRComponentSetup, normalizeUniText, queuePostFlushCb, logError, setUniPageHooksInitializer, setRealPathResolver, setNativeEventNormalizer, createVaporApp, VaporTransition, nthChild, withImageEventDetail, setImageMode, setImageSrc } from "vue";
import { capitalize, camelize, isArray, isString, extend, remove, stringifyStyle, parseStringStyle, isPlainObject, isFunction, hyphenate, hasOwn, isObject, toRawType, makeMap as makeMap$1, isPromise, invokeArrayFns as invokeArrayFns$1, EMPTY_OBJ, Namespaces } from "@vue/shared";
import { useRoute, isNavigationFailure, VaporRouterView, useRouter, createRouter, createWebHistory, createWebHashHistory } from "vue-router";
import { initVueI18n, isI18nStr, LOCALE_EN, LOCALE_ES, LOCALE_FR, LOCALE_ZH_HANS, LOCALE_ZH_HANT } from "@dcloudio/uni-i18n";
const realGlobal = getGlobal();
realGlobal.UTS = UTS$1;
realGlobal.UTSJSONObject = UTSJSONObject;
realGlobal.UTSValueIterable = UTSValueIterable;
realGlobal.UniError = UniError$1;
function defineComponent(options) {
const setup = options.setup;
if (setup) {
options.setup = (props2, context) => {
const result = setup(props2, context);
return typeof result === "function" ? result() : result;
};
}
return defineVaporComponent(options);
}
function createUnsupportedRender$1(name) {
const element = createPlainElement("div", null, null, true);
element.setAttribute("uni-" + name, "");
element.setAttribute("uni-view", "");
element.textContent = name + " is unsupported";
return element;
}
function converPx(value) {
if (/^-?\d+[ur]px$/i.test(value)) {
return value.replace(/(^-?\d+)[ur]px$/i, (text2, num) => {
return `${uni.upx2px(parseFloat(num))}px`;
});
} else if (/^-?[\d\.]+$/.test(value)) {
return `${value}px`;
}
return value || "";
}
function converType(type) {
return type.replace(/[A-Z]/g, (text2) => {
return `-${text2.toLowerCase()}`;
}).replace("webkit", "-webkit");
}
function getStyle(action) {
const animateTypes1 = [
"matrix",
"matrix3d",
"scale",
"scale3d",
"rotate3d",
"skew",
"translate",
"translate3d"
];
const animateTypes2 = [
"scaleX",
"scaleY",
"scaleZ",
"rotate",
"rotateX",
"rotateY",
"rotateZ",
"skewX",
"skewY",
"translateX",
"translateY",
"translateZ"
];
const animateTypes3 = ["opacity", "background-color"];
const animateTypes4 = ["width", "height", "left", "right", "top", "bottom"];
const animates = action.animates;
const option = action.option;
const transition = option.transition;
const style = {};
const transform = [];
animates.forEach((animate) => {
let type = animate.type;
let args = [...animate.args];
if (animateTypes1.concat(animateTypes2).includes(type)) {
if (type.startsWith("rotate") || type.startsWith("skew")) {
args = args.map((value) => parseFloat(value) + "deg");
} else if (type.startsWith("translate")) {
args = args.map(converPx);
}
if (animateTypes2.indexOf(type) >= 0) {
args.length = 1;
}
transform.push(`${type}(${args.join(",")})`);
} else if (animateTypes3.concat(animateTypes4).includes(args[0])) {
type = args[0];
const value = args[1];
style[type] = animateTypes4.includes(type) ? converPx(value) : value;
}
});
style.transform = style.webkitTransform = transform.join(" ");
style.transition = style.webkitTransition = Object.keys(style).map(
(type) => `${converType(type)} ${transition.duration}ms ${transition.timingFunction} ${transition.delay}ms`
).join(",");
style.transformOrigin = style.webkitTransformOrigin = option.transformOrigin;
return style;
}
function startAnimation(context) {
const animation2 = context.animation;
if (!animation2 || !animation2.actions || !animation2.actions.length) {
return;
}
let index2 = 0;
const actions = animation2.actions;
const length = animation2.actions.length;
function animate() {
const action = actions[index2];
const transition = action.option.transition;
const style = getStyle(action);
Object.keys(style).forEach((key) => {
context.$el.style[key] = style[key];
});
index2 += 1;
if (index2 < length) {
setTimeout(animate, transition.duration + transition.delay);
}
}
setTimeout(() => {
animate();
}, 0);
}
const animation = {
props: ["animation"],
watch: {
animation: {
deep: true,
handler() {
startAnimation(this);
}
}
},
mounted() {
startAnimation(this);
}
};
const defineRuntimeComponent = defineComponent;
const createUnsupportedRender = createUnsupportedRender$1;
const defineBuiltInComponent = (options) => {
options.__reserved = true;
const { props: props2, mixins } = options;
if (!props2 || !props2.animation) {
(mixins || (options.mixins = [])).push(animation);
}
return defineSystemComponent(options);
};
const defineSystemComponent = (options) => {
options.__reserved = true;
options.compatConfig = {
MODE: 3
// 标记为vue3
};
return defineRuntimeComponent(options);
};
const defineUnsupportedComponent = (name) => {
return defineBuiltInComponent({
name: capitalize(camelize(name)),
setup() {
return createUnsupportedRender(name);
}
});
};
let UniElement$1 = class UniElement extends HTMLElement {
getPage() {
return getUniElementPage(this);
}
get uniPage() {
return this.getPage();
}
getBoundingClientRectAsync(callback) {
var _a, _b;
if (callback) {
const domRect = this.getBoundingClientRect();
try {
(_a = callback.success) == null ? void 0 : _a.call(callback, domRect);
} catch (error) {
console.error(error);
}
try {
(_b = callback.complete) == null ? void 0 : _b.call(callback, domRect);
} catch (error) {
console.error(error);
}
return;
}
return new Promise((resolve, reject) => {
const domRect = this.getBoundingClientRect();
resolve(domRect);
});
}
};
const UniElement2 = UniElement$1;
const _UniCanvasElement = class _UniCanvasElement extends UniElement2 {
static [Symbol.hasInstance](value) {
const el = value;
return this === _UniCanvasElement && (el == null ? void 0 : el.nodeType) === 1 && el.localName === "canvas" && el.hasAttribute("uni-canvas") || Function.prototype[Symbol.hasInstance].call(this, value);
}
};
_UniCanvasElement.__uniElement = {};
let UniCanvasElement = _UniCanvasElement;
function initCanvasElement(root) {
const canvas = root;
Object.defineProperties(root, {
uniTagName: { value: "CANVAS" },
// 方法只绑定一次,保留原生参数、返回值和异常行为。
getContext: { value: canvas.getContext.bind(canvas) },
toBlob: { value: canvas.toBlob.bind(canvas) },
toDataURL: { value: canvas.toDataURL.bind(canvas) }
});
}
const canvasProps = {
disableScroll: {
type: [Boolean, String],
default: false
}
};
const _t0$g = template("<canvas uni-canvas class=uni-canvas-canvas>", 3);
const indexVapor$8 = /* @__PURE__ */ defineBuiltInComponent({
name: "Canvas",
props: canvasProps,
rootElement: {
name: "uni-canvas",
class: UniCanvasElement
},
setup() {
const root = (() => {
const _n0 = _t0$g();
return _n0;
})();
initCanvasElement(root);
return root;
}
});
const selectionProperty = "--uni-selection-background-color";
const selectionAttribute = "data-uni-selection";
const probeBackgroundProperty = "--uni-selection-probe-background-color";
const fieldSelectionProps = {
selectionClass: {
type: String,
default: ""
}
};
const fieldSelectionProbeStyle = "display: none !important;";
function clearSelection(field) {
field.style.removeProperty(selectionProperty);
field.removeAttribute(selectionAttribute);
}
function resolveSelectionColor(probe) {
const color = getComputedStyle(probe).backgroundColor;
if (color === "transparent" || color.replace(/\s/g, "") === "rgba(0,0,0,0)") {
probe.style.setProperty(probeBackgroundProperty, "#000000");
try {
return getComputedStyle(probe).backgroundColor === color ? color : "";
} finally {
probe.style.removeProperty(probeBackgroundProperty);
}
}
return color;
}
function updateSelection(field, color) {
if (!color) {
clearSelection(field);
return;
}
if (field.style.getPropertyValue(selectionProperty) !== color) {
field.style.setProperty(selectionProperty, color);
}
if (!field.hasAttribute(selectionAttribute)) {
field.setAttribute(selectionAttribute, "");
}
}
function observeSelection(probe, field) {
let refreshFrame = null;
function refreshSelection() {
refreshFrame = null;
if (!field.isConnected || field.ownerDocument.activeElement !== field) {
return;
}
updateSelection(field, resolveSelectionColor(probe));
refreshFrame = requestAnimationFrame(refreshSelection);
}
function startRefresh() {
if (refreshFrame === null) {
refreshSelection();
}
}
function stopRefresh() {
if (refreshFrame !== null) {
cancelAnimationFrame(refreshFrame);
refreshFrame = null;
}
}
field.addEventListener("focus", startRefresh);
field.addEventListener("blur", stopRefresh);
startRefresh();
return () => {
field.removeEventListener("focus", startRefresh);
field.removeEventListener("blur", stopRefresh);
stopRefresh();
clearSelection(field);
};
}
function useFieldSelection(props2, fieldRef) {
const selectionRef = ref(null);
watch(
[() => props2.selectionClass, fieldRef, selectionRef],
([className, field, probe], _, onCleanup) => {
if (className && field && probe) {
onCleanup(observeSelection(probe, field));
}
},
{ immediate: true, flush: "post" }
);
return selectionRef;
}
const nativeHasInstance = Function.prototype[Symbol.hasInstance];
function isUniNativeElement(value, tag, marker) {
const el = value;
return (el == null ? void 0 : el.nodeType) === 1 && el.localName === tag && el.hasAttribute(marker);
}
const NativeUniElement = UniElement2;
class UniViewElement extends NativeUniElement {
static [Symbol.hasInstance](value) {
return this === UniViewElement && isUniNativeElement(value, "div", "uni-view") || nativeHasInstance.call(this, value);
}
}
class UniTextElement extends NativeUniElement {
// Web 直接读取 DOM 文字,不缓存、不触发布局;不提供会删除 Vue 子节点的 setter。
// 类上保留 getter,供 Button 等复合 Element 的 super.value 复用。
get value() {
return this.textContent ?? "";
}
static [Symbol.hasInstance](value) {
return this === UniTextElement && isUniNativeElement(value, "span", "uni-text") || nativeHasInstance.call(this, value);
}
}
class UniImageElement extends NativeUniElement {
static [Symbol.hasInstance](value) {
return this === UniImageElement && isUniNativeElement(value, "img", "uni-image") || nativeHasInstance.call(this, value);
}
}
function installWebVaporElements(realm) {
if (!realm)
return;
if (!Object.getOwnPropertyDescriptor(UniElement2, Symbol.hasInstance)) {
Object.defineProperty(UniElement2, Symbol.hasInstance, {
configurable: true,
value(value) {
const el = value;
if (this === UniElement2 && (el == null ? void 0 : el.nodeType) === 1) {
if ("uniTagName" in el)
return !!el.uniTagName || nativeHasInstance.call(this, value);
let marker;
switch (el.localName) {
case "div":
marker = "uni-view";
break;
case "span":
marker = "uni-text";
break;
case "img":
marker = "uni-image";
break;
case "canvas":
marker = "uni-canvas";
break;
}
if (marker && el.hasAttribute(marker))
return true;
}
return nativeHasInstance.call(this, value);
}
});
}
const descriptors2 = {
getPage: {
value() {
return this.uniTagName ? UniElement2.prototype.getPage.call(this) : null;
},
writable: true
},
uniPage: {
get() {
return this.getPage();
}
},
// 仅复用无实例状态的公共方法,不复制 dataset、style、属性或标签名重写。
getBoundingClientRectAsync: {
value: UniElement2.prototype.getBoundingClientRectAsync,
writable: true
}
};
const hosts = realm;
if (!("value" in hosts.HTMLSpanElement.prototype)) {
Object.defineProperty(
hosts.HTMLSpanElement.prototype,
"value",
Object.getOwnPropertyDescriptor(UniTextElement.prototype, "value")
);
}
for (const [Host, marker, tagName] of [
[hosts.HTMLDivElement, "uni-view", "VIEW"],
[hosts.HTMLSpanElement, "uni-text", "TEXT"],
[hosts.HTMLImageElement, "uni-image", "IMAGE"],
[hosts.HTMLCanvasElement, "uni-canvas", "CANVAS"]
]) {
const prototype = Host.prototype;
if (!("uniTagName" in prototype)) {
Object.defineProperty(prototype, "uniTagName", {
configurable: true,
get() {
return this.hasAttribute(marker) ? tagName : void 0;
}
});
}
for (const key in descriptors2) {
if (!(key in prototype)) {
Object.defineProperty(
prototype,
key,
Object.assign({ configurable: true }, descriptors2[key])
);
}
}
}
initVaporDataset(realm);
}
const _UniInputElement = class _UniInputElement extends UniViewElement {
static [Symbol.hasInstance](value) {
return this === _UniInputElement && value instanceof UniViewElement && value.hasAttribute("uni-input") || Function.prototype[Symbol.hasInstance].call(this, value);
}
focus(options) {
var _a;
(_a = this.querySelector("input")) == null ? void 0 : _a.focus(options);
}
get value() {
return this.querySelector("input").value;
}
set value(value) {
this.querySelector("input").value = value;
}
};
_UniInputElement.__uniElement = {};
let UniInputElement = _UniInputElement;
const descriptors$1 = {
uniTagName: { value: "INPUT" },
focus: Object.getOwnPropertyDescriptor(UniInputElement.prototype, "focus"),
value: Object.getOwnPropertyDescriptor(UniInputElement.prototype, "value")
};
function initInputElement(root) {
Object.defineProperties(root, descriptors$1);
}
const isEnableLocale = /* @__PURE__ */ once(
() => typeof __uniConfig !== "undefined" && __uniConfig.locales && !!Object.keys(__uniConfig.locales).length
);
let i18n;
function getLocaleMessage() {
const locale = uni.getLocale();
const locales = __uniConfig.locales;
return locales[locale] || locales[__uniConfig.fallbackLocale] || locales.en || {};
}
function formatI18n(message) {
if (isI18nStr(message, I18N_JSON_DELIMITERS)) {
return useI18n().f(message, getLocaleMessage(), I18N_JSON_DELIMITERS);
}
return message;
}
function resolveJsonObj(jsonObj, names) {
if (names.length === 1) {
if (jsonObj) {
const _isI18nStr = (value2) => isString(value2) && isI18nStr(value2, I18N_JSON_DELIMITERS);
const _name = names[0];
let filterJsonObj = [];
if (isArray(jsonObj) && (filterJsonObj = jsonObj.filter((item) => _isI18nStr(item[_name]))).length) {
return filterJsonObj;
}
const value = jsonObj[names[0]];
if (_isI18nStr(value)) {
return jsonObj;
}
}
return;
}
const name = names.shift();
return resolveJsonObj(jsonObj && jsonObj[name], names);
}
function defineI18nProperties(obj, names) {
return names.map((name) => defineI18nProperty(obj, name));
}
function defineI18nProperty(obj, names) {
const jsonObj = resolveJsonObj(obj, names);
if (!jsonObj) {
return false;
}
const prop = names[names.length - 1];
if (isArray(jsonObj)) {
jsonObj.forEach((item) => defineI18nProperty(item, [prop]));
} else {
let value = jsonObj[prop];
Object.defineProperty(jsonObj, prop, {
get() {
return formatI18n(value);
},
set(v2) {
value = v2;
}
});
}
return true;
}
function useI18n() {
if (!i18n) {
let locale;
{
{
locale = navigator.cookieEnabled && window.localStorage && localStorage[UNI_STORAGE_LOCALE] || __uniConfig.locale || navigator.language;
}
}
i18n = initVueI18n(locale);
if (isEnableLocale()) {
const localeKeys = Object.keys(__uniConfig.locales || {});
if (localeKeys.length) {
localeKeys.forEach(
(locale2) => i18n.add(locale2, __uniConfig.locales[locale2])
);
}
i18n.setLocale(locale);
}
}
return i18n;
}
function normalizeMessages(module, keys, values) {
return keys.reduce((res, name, index2) => {
res[module + name] = values[index2];
return res;
}, {});
}
const initI18nAppVmMsgsOnce = /* @__PURE__ */ once(() => {
const name = "uni.appVm.";
const keys = ["methodWarning"];
if (__UNI_FEATURE_I18N_EN__) {
useI18n().add(
LOCALE_EN,
normalizeMessages(name, keys, [
'Method "{methodName}" should not be called directly on UniApp. Use "{methodCall}" instead.'
]),
false
);
}
if (__UNI_FEATURE_I18N_ES__) {
useI18n().add(
LOCALE_ES,
normalizeMessages(name, keys, [
'El método "{methodName}" no debe llamarse directamente en UniApp. Use "{methodCall}" en su lugar.'
]),
false
);
}
if (__UNI_FEATURE_I18N_FR__) {
useI18n().add(
LOCALE_FR,
normalizeMessages(name, keys, [
'La méthode "{methodName}" ne doit pas être appelée directement sur UniApp. Utilisez "{methodCall}" à la place.'
]),
false
);
}
if (__UNI_FEATURE_I18N_ZH_HANS__) {
useI18n().add(
LOCALE_ZH_HANS,
normalizeMessages(name, keys, [
"不应直接通过 UniApp 调用方法“{methodName}”,请改用“{methodCall}”。"
]),
false
);
}
if (__UNI_FEATURE_I18N_ZH_HANT__) {
useI18n().add(
LOCALE_ZH_HANT,
normalizeMessages(name, keys, [
"不應直接透過 UniApp 呼叫方法「{methodName}」,請改用「{methodCall}」。"
]),
false
);
}
});
const initI18nAsyncMsgsOnce = /* @__PURE__ */ once(() => {
const name = "uni.async.";
const keys = ["error"];
if (__UNI_FEATURE_I18N_EN__) {
useI18n().add(
LOCALE_EN,
normalizeMessages(name, keys, [
"The connection timed out, click the screen to try again."
]),
false
);
}
if (__UNI_FEATURE_I18N_ES__) {
useI18n().add(
LOCALE_ES,
normalizeMessages(name, keys, [
"Se agotó el tiempo de conexión, haga clic en la pantalla para volver a intentarlo."
]),
false
);
}
if (__UNI_FEATURE_I18N_FR__) {
useI18n().add(
LOCALE_FR,
normalizeMessages(name, keys, [
"La connexion a expiré, cliquez sur l'écran pour réessayer."
]),
false
);
}
if (__UNI_FEATURE_I18N_ZH_HANS__) {
useI18n().add(
LOCALE_ZH_HANS,
normalizeMessages(name, keys, ["连接服务器超时,点击屏幕重试"]),
false
);
}
if (__UNI_FEATURE_I18N_ZH_HANT__) {
useI18n().add(
LOCALE_ZH_HANT,
normalizeMessages(name, keys, ["連接服務器超時,點擊屏幕重試"]),
false
);
}
});
const initI18nShowToastMsgsOnce = /* @__PURE__ */ once(() => {
const name = "uni.showToast.";
const keys = ["unpaired"];
if (__UNI_FEATURE_I18N_EN__) {
useI18n().add(
LOCALE_EN,
normalizeMessages(name, keys, [
"Please note showToast must be paired with hideToast"
]),
false
);
}
if (__UNI_FEATURE_I18N_ES__) {
useI18n().add(
LOCALE_ES,
normalizeMessages(name, keys, [
"Tenga en cuenta que showToast debe estar emparejado con hideToast"
]),
false
);
}
if (__UNI_FEATURE_I18N_FR__) {
useI18n().add(
LOCALE_FR,
normalizeMessages(name, keys, [
"Veuillez noter que showToast doit être associé à hideToast"
]),
false
);
}
if (__UNI_FEATURE_I18N_ZH_HANS__) {
useI18n().add(
LOCALE_ZH_HANS,
normalizeMessages(name, keys, [
"请注意 showToast 与 hideToast 必须配对使用"
]),
false
);
}
if (__UNI_FEATURE_I18N_ZH_HANT__) {
useI18n().add(
LOCALE_ZH_HANT,
normalizeMessages(name, keys, [
"請注意 showToast 與 hideToast 必須配對使用"
]),
false
);
}
});
const initI18nShowLoadingMsgsOnce = /* @__PURE__ */ once(() => {
const name = "uni.showLoading.";
const keys = ["unpaired"];
if (__UNI_FEATURE_I18N_EN__) {
useI18n().add(
LOCALE_EN,
normalizeMessages(name, keys, [
"Please note showLoading must be paired with hideLoading"
]),
false
);
}
if (__UNI_FEATURE_I18N_ES__) {
useI18n().add(
LOCALE_ES,
normalizeMessages(name, keys, [
"Tenga en cuenta que showLoading debe estar emparejado con hideLoading"
]),
false
);
}
if (__UNI_FEATURE_I18N_FR__) {
useI18n().add(
LOCALE_FR,
normalizeMessages(name, keys, [
"Veuillez noter que showLoading doit être associé à hideLoading"
]),
false
);
}
if (__UNI_FEATURE_I18N_ZH_HANS__) {
useI18n().add(
LOCALE_ZH_HANS,
normalizeMessages(name, keys, [
"请注意 showLoading 与 hideLoading 必须配对使用"
]),
false
);
}
if (__UNI_FEATURE_I18N_ZH_HANT__) {
useI18n().add(
LOCALE_ZH_HANT,
normalizeMessages(name, keys, [
"請注意 showLoading 與 hideLoading 必須配對使用"
]),
false
);
}
});
const initI18nChooseFileMsgsOnce = /* @__PURE__ */ once(() => {
const name = "uni.chooseFile.";
const keys = ["notUserActivation"];
if (__UNI_FEATURE_I18N_EN__) {
useI18n().add(
LOCALE_EN,
normalizeMessages(name, keys, [
"File chooser dialog can only be shown with a user activation"
]),
false
);
}
if (__UNI_FEATURE_I18N_ES__) {
useI18n().add(
LOCALE_ES,
normalizeMessages(name, keys, [
"El cuadro de diálogo del selector de archivos solo se puede mostrar con la activación del usuario"
]),
false
);
}
if (__UNI_FEATURE_I18N_FR__) {
useI18n().add(
LOCALE_FR,
normalizeMessages(name, keys, [
"La boîte de dialogue du sélecteur de fichier ne peut être affichée qu'avec une activation par l'utilisateur"
]),
false
);
}
if (__UNI_FEATURE_I18N_ZH_HANS__) {
useI18n().add(
LOCALE_ZH_HANS,
normalizeMessages(name, keys, ["文件选择器对话框只能在由用户激活时显示"]),
false
);
}
if (__UNI_FEATURE_I18N_ZH_HANT__) {
useI18n().add(
LOCALE_ZH_HANT,
normalizeMessages(name, keys, ["文件選擇器對話框只能在由用戶激活時顯示"]),
false
);
}
});
const initI18nSetClipboardDataMsgsOnce = /* @__PURE__ */ once(() => {
const name = "uni.setClipboardData.";
const keys = ["success", "fail"];
if (__UNI_FEATURE_I18N_EN__) {
useI18n().add(
LOCALE_EN,
normalizeMessages(name, keys, [
"Content copied",
"Copy failed, please copy manually"
]),
false
);
}
if (__UNI_FEATURE_I18N_ES__) {
useI18n().add(
LOCALE_ES,
normalizeMessages(name, keys, [
"Contenido copiado",
"Error al copiar, copie manualmente"
]),
false
);
}
if (__UNI_FEATURE_I18N_FR__) {
useI18n().add(
LOCALE_FR,
normalizeMessages(name, keys, [
"Contenu copié",
"Échec de la copie, copiez manuellement"
]),
false
);
}
if (__UNI_FEATURE_I18N_ZH_HANS__) {
useI18n().add(
LOCALE_ZH_HANS,
normalizeMessages(name, keys, ["内容已复制", "复制失败,请手动复制"]),
false
);
}
if (__UNI_FEATURE_I18N_ZH_HANT__) {
useI18n().add(
LOCALE_ZH_HANT,
normalizeMessages(name, keys, ["內容已復制", "復制失敗,請手動復製"]),
false
);
}
});
const initI18nGetClipboardDataMsgsOnce = /* @__PURE__ */ once(() => {
const name = "uni.getClipboardData.";
const keys = ["fail"];
if (__UNI_FEATURE_I18N_EN__) {
useI18n().add(
LOCALE_EN,
normalizeMessages(name, keys, ["Reading failed, please paste manually"]),
false
);
}
if (__UNI_FEATURE_I18N_ES__) {
useI18n().add(
LOCALE_ES,
normalizeMessages(name, keys, ["Error de lectura, pegue manualmente"]),
false
);
}
if (__UNI_FEATURE_I18N_FR__) {
useI18n().add(
LOCALE_FR,
normalizeMessages(name, keys, [
"Échec de la lecture, veuillez coller manuellement"
]),
false
);
}
if (__UNI_FEATURE_I18N_ZH_HANS__) {
useI18n().add(
LOCALE_ZH_HANS,
normalizeMessages(name, keys, ["读取失败,请手动粘贴"]),
false
);
}
if (__UNI_FEATURE_I18N_ZH_HANT__) {
useI18n().add(
LOCALE_ZH_HANT,
normalizeMessages(name, keys, ["讀取失敗,請手動粘貼"]),
false
);
}
});
const initI18nVideoMsgsOnce = /* @__PURE__ */ once(() => {
const name = "uni.video.";
const keys = ["danmu", "volume"];
if (__UNI_FEATURE_I18N_EN__) {
useI18n().add(
LOCALE_EN,
normalizeMessages(name, keys, ["Danmu", "Volume"]),
false
);
}
if (__UNI_FEATURE_I18N_ES__) {
useI18n().add(
LOCALE_ES,
normalizeMessages(name, keys, ["Danmu", "Volumen"]),
false
);
}
if (__UNI_FEATURE_I18N_FR__) {
useI18n().add(
LOCALE_FR,
normalizeMessages(name, keys, ["Danmu", "Le Volume"]),
false
);
}
if (__UNI_FEATURE_I18N_ZH_HANS__) {
useI18n().add(
LOCALE_ZH_HANS,
normalizeMessages(name, keys, ["弹幕", "音量"]),
false
);
}
if (__UNI_FEATURE_I18N_ZH_HANT__) {
useI18n().add(
LOCALE_ZH_HANT,
normalizeMessages(name, keys, ["彈幕", "音量"]),
false
);
}
});
function initNavigationBarI18n(navigationBar) {
if (isEnableLocale()) {
return defineI18nProperties(navigationBar, [
["titleText"],
["searchInput", "placeholder"],
["buttons", "text"]
]);
}
}
function initTabBarI18n(tabBar) {
if (isEnableLocale() && tabBar.list) {
tabBar.list.forEach((item) => {
defineI18nProperty(item, ["text"]);
});
}
if (isEnableLocale() && tabBar.midButton) {
defineI18nProperty(tabBar.midButton, ["text"]);
}
return tabBar;
}
function initBridge(subscribeNamespace) {
const emitter = new Emitter();
return {
on(event, callback) {
return emitter.on(event, callback);
},
once(event, callback) {
return emitter.once(event, callback);
},
off(event, callback) {
return emitter.off(event, callback);
},
emit(event, ...args) {
return emitter.emit(event, ...args);
},
subscribe(event, callback, once2 = false) {
emitter[once2 ? "once" : "on"](`${subscribeNamespace}.${event}`, callback);
},
unsubscribe(event, callback) {
emitter.off(`${subscribeNamespace}.${event}`, callback);
},
subscribeHandler(event, args, pageId) {
emitter.emit(`${subscribeNamespace}.${event}`, args, pageId);
}
};
}
const INVOKE_VIEW_API = "invokeViewApi";
const INVOKE_SERVICE_API = "invokeServiceApi";
let invokeServiceMethodId = 1;
const invokeServiceMethod = (name, args, callback) => {
const { subscribe, publishHandler } = UniViewJSBridge;
const id2 = callback ? invokeServiceMethodId++ : 0;
callback && subscribe(INVOKE_SERVICE_API + "." + id2, callback, true);
publishHandler(INVOKE_SERVICE_API, { id: id2, name, args });
};
const viewMethods = /* @__PURE__ */ Object.create(null);
function normalizeViewMethodName(pageId, name) {
return pageId + "." + name;
}
function subscribeViewMethod(pageId, wrapper) {
UniViewJSBridge.subscribe(
normalizeViewMethodName(pageId, INVOKE_VIEW_API),
onInvokeViewMethod
);
}
function unsubscribeViewMethod(pageId) {
UniViewJSBridge.unsubscribe(normalizeViewMethodName(pageId, INVOKE_VIEW_API));
Object.keys(viewMethods).forEach((name) => {
if (name.indexOf(pageId + ".") === 0) {
delete viewMethods[name];
}
});
}
function registerViewMethod(pageId, name, fn) {
name = normalizeViewMethodName(pageId, name);
if (!viewMethods[name]) {
viewMethods[name] = fn;
}
}
function unregisterViewMethod(pageId, name) {
name = normalizeViewMethodName(pageId, name);
delete viewMethods[name];
}
function onInvokeViewMethod({
id: id2,
name,
args
}, pageId) {
name = normalizeViewMethodName(pageId, name);
const publish = (res) => {
id2 && UniViewJSBridge.publishHandler(INVOKE_VIEW_API + "." + id2, res);
};
const handler = viewMethods[name];
if (handler) {
handler(args, publish);
} else {
publish({});
}
}
const ViewJSBridge = /* @__PURE__ */ extend(
/* @__PURE__ */ initBridge("service"),
{
invokeServiceMethod
}
);
const LONGPRESS_TIMEOUT = 350;
const LONGPRESS_THRESHOLD = 10;
const passiveOptions$3 = /* @__PURE__ */ passive(true);
let longPressTimer;
function clearLongPressTimer() {
if (longPressTimer) {
clearTimeout(longPressTimer);
longPressTimer = null;
}
}
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,
// @ts-expect-error
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$3);
window.addEventListener("touchmove", touchmove, passiveOptions$3);
window.addEventListener("touchend", clearLongPressTimer, passiveOptions$3);
window.addEventListener("touchcancel", clearLongPressTimer, passiveOptions$3);
}
function checkValue$1(value, defaultValue) {
const newValue = Number(value);
return isNaN(newValue) ? defaultValue : newValue;
}
const isApple$1 = () => /^Apple/.test(navigator.vendor);
function getWindowWidth$1() {
const isApple2 = /^Apple/.test(navigator.vendor);
const screenFix = isApple2 && window.matchMedia("(orientation:landscape)").matches;
var screenWidth = screenFix ? Math.max(screen.width, screen.height) : screen.width;
var windowWidth = isApple2 ? Math.min(
window.innerWidth,
document.documentElement.clientWidth,
screenWidth
) || screenWidth : Math.min(window.innerWidth, document.documentElement.clientWidth);
return windowWidth;
}
function useRem() {
const config = __uniConfig.globalStyle || {};
const maxWidth2 = checkValue$1(config.rpxCalcMaxDeviceWidth, 960);
const baseWidth2 = checkValue$1(config.rpxCalcBaseDeviceWidth, 375);
function updateRem() {
let width = getWindowWidth$1();
width = width <= maxWidth2 ? width : baseWidth2;
document.documentElement.style.fontSize = width / 23.4375 + "px";
}
updateRem();
document.addEventListener("DOMContentLoaded", updateRem);
window.addEventListener("load", updateRem);
window.addEventListener("resize", updateRem);
if (isApple$1()) {
window.addEventListener("orientationchange", () => {
updateRem();
setTimeout(updateRem, 50);
});
}
}
function initView() {
useRem();
if (__UNI_FEATURE_LONGPRESS__) {
initLongPress();
}
}
function getDefaultExportFromCjs(x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
}
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 setStyle2(el, style) {
var elStyle = el.style;
Object.keys(style).forEach(function(key) {
var val = style[key];
elStyle[key] = val;
});
}
var cbs = [];
function parentReady(callback) {
if (callback) {
cbs.push(callback);
} 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 + ")"
};
setStyle2(a1, aStyle);
setStyle2(a2, aStyle);
setStyle2(a1Children, {
transition: "0s",
animation: "none",
width: "400px",
height: "400px"
});
setStyle2(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");
setStyle2(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 style = {};
changeAttrs.forEach(function(attr3) {
style[attr3] = elementComputedStyle[attr3];
});
changeAttrs.length = 0;
callbacks.forEach(function(callback) {
callback(style);
});
}, 0);
}
changeAttrs.push(attr2);
}
var callbacks = [];
function onChange(callback) {
if (!getSupport()) {
return;
}
if (!inited$1) {
init();
}
if (typeof callback === "function") {
callbacks.push(callback);
}
}
function offChange(callback) {
var index2 = callbacks.indexOf(callback);
if (index2 >= 0) {
callbacks.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 out = safeAreaInsets;
const safeAreaInsets$1 = /* @__PURE__ */ getDefaultExportFromCjs(out);
const onEventPrevent = /* @__PURE__ */ withModifiers(() => {
}, ["prevent"]);
function getWindowOffsetCssVar(style, name) {
return parseInt((style.getPropertyValue(name).match(/\d+/) || ["0"])[0]);
}
function getWindowTop() {
const style = document.documentElement.style;
const top = getWindowOffsetCssVar(style, "--window-top");
return top ? top + safeAreaInsets$1.top : 0;
}
function getWindowOffset() {
const style = document.documentElement.style;
const top = getWindowTop();
const bottom = getWindowOffsetCssVar(style, "--window-bottom");
const left = getWindowOffsetCssVar(style, "--window-left");
const right = getWindowOffsetCssVar(style, "--window-right");
const topWindowHeight = getWindowOffsetCssVar(style, "--top-window-height");
return {
top,
bottom: bottom ? bottom + safeAreaInsets$1.bottom : 0,
left: left ? left + safeAreaInsets$1.left : 0,
right: right ? right + safeAreaInsets$1.right : 0,
topWindowHeight: topWindowHeight || 0
};
}
function updateCssVar(cssVars) {
const style = document.documentElement.style;
Object.keys(cssVars).forEach((name) => {
style.setProperty(name, cssVars[name]);
});
}
function updatePageCssVar(cssVars) {
return updateCssVar(cssVars);
}
const sheetsMap = /* @__PURE__ */ new Map();
function updateStyle(id2, content) {
let style = sheetsMap.get(id2);
if (style && !(style instanceof HTMLStyleElement)) {
removeStyle(id2);
style = void 0;
}
if (!style) {
style = document.createElement("style");
style.setAttribute("type", "text/css");
style.innerHTML = content;
document.head.appendChild(style);
} else {
style.innerHTML = content;
}
sheetsMap.set(id2, style);
}
function removeStyle(id2) {
let style = sheetsMap.get(id2);
if (style) {
if (style instanceof CSSStyleSheet) {
document.adoptedStyleSheets = document.adoptedStyleSheets.filter(
(s) => s !== style
);
} else {
document.head.removeChild(style);
}
sheetsMap.delete(id2);
}
}
function PolySymbol(name) {
return Symbol(process.env.NODE_ENV !== "production" ? "[uni-app]: " + name : name);
}
function hasRpx(str) {
str = str + "";
return str.indexOf("rpx") !== -1 || str.indexOf("upx") !== -1;
}
function rpx2px(str, replace = false) {
if (replace) {
return rpx2pxWithReplace(str);
}
if (isString(str)) {
const res = parseInt(str) || 0;
if (hasRpx(str)) {
return uni.upx2px(res);
}
return res;
}
return str;
}
function rpx2pxWithReplace(str) {
if (!hasRpx(str)) {
return str;
}
return str.replace(/(\d+(\.\d+)?)[ru]px/g, (_a, b) => {
return uni.upx2px(parseFloat(b)) + "px";
});
}
function get$pageByPage(page) {
return page.vm.$basePage;
}
function isBuiltInElement(target) {
{
return !!target.uniTagName;
}
}
let svgIcon = () => {
svgIcon = template('<svg viewBox="0 0 32 32"><path></path></svg>', 0, 1);
return svgIcon();
};
function createSvgIcon(path, color = "#000", size = 27, stroke = false) {
const svg = svgIcon();
setAttr(svg, "width", size, true);
setAttr(svg, "height", size, true);
setAttr(svg.firstChild, "d", path, true);
setAttr(svg.firstChild, "fill", stroke ? "none" : color, true);
if (stroke) {
setAttr(svg.firstChild, "stroke", color, true);
setAttr(svg.firstChild, "stroke-width", 2, true);
setAttr(svg.firstChild, "stroke-linecap", "round", true);
}
return svg;
}
const createSvgIconVNode = createSvgIcon;
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";
const ICON_PATH_DOWNLOAD = "M15.808 1.696q-3.776 0-7.072 1.984-3.2 1.888-5.088 5.152-1.952 3.392-1.952 7.36 0 3.776 1.952 7.072 1.888 3.2 5.088 5.088 3.296 1.952 7.072 1.952 3.968 0 7.36-1.952 3.264-1.888 5.152-5.088 1.984-3.296 1.984-7.072 0-4-1.984-7.36-1.888-3.264-5.152-5.152-3.36-1.984-7.36-1.984zM20.864 18.592l-3.776 4.928q-0.448 0.576-1.088 0.576t-1.088-0.576l-3.776-4.928q-0.448-0.576-0.24-0.992t0.944-0.416h2.976v-8.928q0-0.256 0.176-0.432t0.4-0.176h1.216q0.224 0 0.4 0.176t0.176 0.432v8.928h2.976q0.736 0 0.944 0.416t-0.24 0.992z";
const ICON_PATH_INFO = "M15.808 0.128q-4.224 0-7.872 2.176-3.552 2.112-5.632 5.728-2.176 3.776-2.176 8.16 0 4.224 2.176 7.872 2.080 3.552 5.632 5.632 3.648 2.176 7.872 2.176 4.384 0 8.16-2.176 3.616-2.080 5.728-5.632 2.176-3.648 2.176-7.872 0-4.416-2.176-8.16-2.112-3.616-5.728-5.728-3.744-2.176-8.16-2.176zM16.864 23.776q0 0.064-0.064 0.064h-1.568q-0.096 0-0.096-0.064l-0.256-11.328q0-0.064 0.064-0.064h2.112q0.096 0 0.064 0.064l-0.256 11.328zM16 10.88q-0.576 0-0.976-0.4t-0.4-0.96 0.4-0.96 0.976-0.4 0.976 0.4 0.4 0.96-0.4 0.96-0.976 0.4z";
const ICON_PATH_SEARCH = "M20.928 22.688q-1.696 1.376-3.744 2.112-2.112 0.768-4.384 0.768-3.488 0-6.464-1.728-2.88-1.696-4.576-4.608-1.76-2.976-1.76-6.464t1.76-6.464q1.696-2.88 4.576-4.576 2.976-1.76 6.464-1.76t6.464 1.76q2.912 1.696 4.608 4.576 1.728 2.976 1.728 6.464 0 2.272-0.768 4.384-0.736 2.048-2.112 3.744l9.312 9.28-1.824 1.824-9.28-9.312zM12.8 23.008q2.784 0 5.184-1.376 2.304-1.376 3.68-3.68 1.376-2.4 1.376-5.184t-1.376-5.152q-1.376-2.336-3.68-3.68-2.4-1.408-5.184-1.408t-5.152 1.408q-2.336 1.344-3.68 3.68-1.408 2.368-1.408 5.152t1.408 5.184q1.344 2.304 3.68 3.68 2.368 1.376 5.152 1.376zM12.8 23.008v0z";
const ICON_PATH_SUCCESS_NO_CIRCLE = "M1.952 18.080q-0.32-0.352-0.416-0.88t0.128-0.976l0.16-0.352q0.224-0.416 0.64-0.528t0.8 0.176l6.496 4.704q0.384 0.288 0.912 0.272t0.88-0.336l17.312-14.272q0.352-0.288 0.848-0.256t0.848 0.352l-0.416-0.416q0.32 0.352 0.32 0.816t-0.32 0.816l-18.656 18.912q-0.32 0.352-0.8 0.352t-0.8-0.32l-7.936-8.064z";
const ICON_PATH_SUCCESS = "M15.808 0.16q-4.224 0-7.872 2.176-3.552 2.112-5.632 5.728-2.144 3.744-2.144 8.128 0 4.192 2.144 7.872 2.112 3.52 5.632 5.632 3.68 2.144 7.872 2.144 4.384 0 8.128-2.144 3.616-2.080 5.728-5.632 2.176-3.648 2.176-7.872 0-4.384-2.176-8.128-2.112-3.616-5.728-5.728-3.744-2.176-8.128-2.176zM24.832 11.328l-11.264 11.104q-0.032 0.032-0.112 0.032t-0.112-0.032l-5.216-5.376q-0.096-0.128 0-0.288l0.704-0.96q0.032-0.064 0.112-0.064t0.112 0.032l4.256 3.264q0.064 0.032 0.144 0.032t0.112-0.032l10.336-8.608q0.064-0.064 0.144-0.064t0.112 0.064l0.672 0.672q0.128 0.128 0 0.224z";
const ICON_PATH_WAITING = "M15.84 0.096q-4.224 0-7.872 2.176-3.552 2.112-5.632 5.728-2.144 3.744-2.144 8.128 0 4.192 2.144 7.872 2.112 3.52 5.632 5.632 3.68 2.144 7.872 2.144 4.384 0 8.128-2.144 3.616-2.080 5.728-5.632 2.176-3.648 2.176-7.872 0-4.384-2.176-8.128-2.112-3.616-5.728-5.728-3.744-2.176-8.128-2.176zM23.008 21.92l-0.512 0.896q-0.096 0.128-0.224 0.064l-8-3.808q-0.096-0.064-0.16-0.128-0.128-0.096-0.128-0.288l0.512-12.096q0-0.064 0.048-0.112t0.112-0.048h1.376q0.064 0 0.112 0.048t0.048 0.112l0.448 10.848 6.304 4.256q0.064 0.064 0.080 0.128t-0.016 0.128z";
const ICON_PATH_WARN = "M15.808 0.16q-4.224 0-7.872 2.176-3.552 2.112-5.632 5.728-2.144 3.744-2.144 8.128 0 4.192 2.144 7.872 2.112 3.52 5.632 5.632 3.68 2.144 7.872 2.144 4.384 0 8.128-2.144 3.616-2.080 5.728-5.632 2.176-3.648 2.176-7.872 0-4.384-2.176-8.128-2.112-3.616-5.728-5.728-3.744-2.176-8.128-2.176zM15.136 8.672h1.728q0.128 0 0.224 0.096t0.096 0.256l-0.384 10.24q0 0.064-0.048 0.112t-0.112 0.048h-1.248q-0.096 0-0.144-0.048t-0.048-0.112l-0.384-10.24q0-0.16 0.096-0.256t0.224-0.096zM16 23.328q-0.48 0-0.832-0.352t-0.352-0.848 0.352-0.848 0.832-0.352 0.832 0.352 0.352 0.848-0.352 0.848-0.832 0.352z";
const ICON_PATH_BACK = "M20 25L11 16L20 7";
const ICON_PATH_CLOSE = "M17.25 16.156l7.375-7.313q0.281-0.281 0.281-0.641t-0.281-0.641q-0.25-0.25-0.625-0.25t-0.625 0.25l-7.375 7.344-7.313-7.344q-0.25-0.25-0.625-0.25t-0.625 0.25q-0.281 0.25-0.281 0.625t0.281 0.625l7.313 7.344-7.375 7.344q-0.281 0.25-0.281 0.625t0.281 0.625q0.125 0.125 0.281 0.188t0.344 0.063q0.156 0 0.328-0.063t0.297-0.188l7.375-7.344 7.375 7.406q0.125 0.156 0.297 0.219t0.328 0.063q0.188 0 0.344-0.078t0.281-0.203q0.281-0.25 0.281-0.609t-0.281-0.641l-7.375-7.406z";
function useCurrentPageId() {
{
const { $pageInstance } = getCurrentInstance();
return $pageInstance && getPageProxyId($pageInstance.proxy);
}
}
function getPageIdByVm(instance2) {
const vm = resolveComponentInstance(instance2);
if (vm.$page) {
return getPageProxyId(vm);
}
if (!vm.$) {
return;
}
{
const { $pageInstance } = vm.$;
if ($pageInstance) {
return getPageProxyId($pageInstance.proxy);
}
}
const rootProxy = vm.$.root.proxy;
if (rootProxy && rootProxy.$page) {
return getPageProxyId(rootProxy);
}
}
function getCurrentPage() {
const pages = getCurrentPages();
const len = pages.length;
if (len) {
return pages[len - 1];
}
}
function getCurrentPageMeta() {
var _a, _b;
const $page = (_b = (_a = getCurrentPage()) == null ? void 0 : _a.vm) == null ? void 0 : _b.$basePage;
if ($page) {
return $page.meta;
}
}
function getCurrentPageId() {
const meta = getCurrentPageMeta();
if (meta) {
return meta.id;
}
return -1;
}
function getCurrentPageVm() {
var _a;
const page = (_a = getCurrentPage()) == null ? void 0 : _a.vm;
if (page) {
return page.$vm;
}
}
const PAGE_META_KEYS = ["navigationBar", "pullToRefresh"];
function initGlobalStyle() {
return JSON.parse(JSON.stringify(__uniConfig.globalStyle || {}));
}
function initRouteMeta(pageMeta, id2) {
const globalStyle = initGlobalStyle();
const res = extend({ id: id2 }, globalStyle, pageMeta);
PAGE_META_KEYS.forEach((name) => {
res[name] = extend({}, globalStyle[name], pageMeta[name]);
});
const { navigationBar } = res;
navigationBar.titleText && navigationBar.titleImage && (navigationBar.titleText = "");
return res;
}
function normalizePullToRefreshRpx(pullToRefresh) {
if (pullToRefresh.offset) {
pullToRefresh.offset = rpx2px(pullToRefresh.offset);
}
if (pullToRefresh.height) {
pullToRefresh.height = rpx2px(pullToRefresh.height);
}
if (pullToRefresh.range) {
pullToRefresh.range = rpx2px(pullToRefresh.range);
}
return pullToRefresh;
}
function initPageInternalInstance(openType, url, pageQuery, meta, eventChannel, themeMode) {
const { id: id2, route } = meta;
const titleColor = normalizeStyles(
meta.navigationBar,
__uniConfig.themeConfig,
themeMode
).titleColor;
return {
id: id2,
path: addLeadingSlash(route),
route,
fullPath: url,
options: pageQuery,
meta,
openType,
eventChannel,
statusBarStyle: titleColor === "#ffffff" ? "light" : "dark"
};
}
function getPageProxyId(proxy) {
var _a, _b;
return ((_a = proxy.$page) == null ? void 0 : _a.id) || ((_b = proxy.$basePage) == null ? void 0 : _b.id);
}
function removeHook(vm, name, hook) {
const hooks = vm.$[name];
if (!isArray(hooks)) {
return;
}
if (hook.__weh) {
remove(hooks, hook.__weh);
}
}
function invokeHook(vm, name, args) {
if (isString(vm)) {
args = name;
name = vm;
vm = getCurrentPageVm();
} else if (typeof vm === "number") {
const page = getCurrentPages().find(
(page2) => get$pageByPage(page2).id === vm
);
if (page) {
vm = page.$vm;
} else {
vm = getCurrentPageVm();
}
}
if (!vm) {
return;
}
const hooks = vm.$[name];
if (name === ON_BACK_PRESS) {
return hooks && invokeArrayFnsWithResults(hooks, args).some((ret) => ret === true);
}
return hooks && invokeArrayFns(hooks, args);
}
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 normalizeRoute(toRoute) {
if (toRoute.indexOf("/") === 0 || toRoute.indexOf("uni:") === 0) {
return toRoute;
}
let fromRoute = "";
const pages = getCurrentPages();
if (pages.length) {
fromRoute = get$pageByPage(pages[pages.length - 1]).route;
}
return getRealRoute(fromRoute, toRoute);
}
function getRealRoute(fromRoute, toRoute) {
if (toRoute.indexOf("/") === 0) {
return toRoute;
}
if (toRoute.indexOf("./") === 0) {
return getRealRoute(fromRoute, toRoute.slice(2));
}
const toRouteArray = toRoute.split("/");
const toRouteLength = toRouteArray.length;
let i = 0;
for (; i < toRouteLength && toRouteArray[i] === ".."; i++) {
}
toRouteArray.splice(0, i);
toRoute = toRouteArray.join("/");
const fromRouteArray = fromRoute.length > 0 ? fromRoute.split("/") : [];
fromRouteArray.splice(fromRouteArray.length - i - 1, i + 1);
return addLeadingSlash(fromRouteArray.concat(toRouteArray).join("/"));
}
function getRouteOptions(path, alias = false) {
if (alias) {
return __uniRoutes.find(
(route) => route.path === path || route.alias === path
);
}
return __uniRoutes.find((route) => route.path === path);
}
function normalizeTabBarRoute(index2, oldPagePath, newPagePath) {
const oldTabBarRoute = getRouteOptions(addLeadingSlash(oldPagePath));
if (oldTabBarRoute) {
const { meta } = oldTabBarRoute;
delete meta.tabBarIndex;
meta.isQuit = meta.isTabBar = false;
}
const newTabBarRoute = getRouteOptions(addLeadingSlash(newPagePath));
if (newTabBarRoute) {
const { meta } = newTabBarRoute;
meta.tabBarIndex = index2;
meta.isQuit = meta.isTabBar = true;
const tabBar = __uniConfig.tabBar;
if (tabBar && tabBar.list && tabBar.list[index2]) {
tabBar.list[index2].pagePath = removeLeadingSlash(newPagePath);
}
}
}
const SYSTEM_DIALOG_PAGE_PATH_STARTER = "uni:";
const SYSTEM_DIALOG_ACTION_SHEET_PAGE_PATH$1 = "uni:actionSheet";
function isSystemDialogPage(page) {
return page.route.startsWith(SYSTEM_DIALOG_PAGE_PATH_STARTER);
}
function isSystemActionSheetDialogPage(page) {
return page.route.startsWith(SYSTEM_DIALOG_ACTION_SHEET_PAGE_PATH$1);
}
function dialogPageTriggerParentHide(dialogPage, onBeforeTrigger, skipDialogPageCheck = false) {
return dialogPageTriggerParentLifeCycle(
dialogPage,
ON_HIDE,
0,
onBeforeTrigger,
skipDialogPageCheck
);
}
function dialogPageTriggerParentShow(dialogPage, triggerParentHideDialogPageNum = 0, skipDialogPageCheck = false) {
dialogPageTriggerParentLifeCycle(
dialogPage,
ON_SHOW,
triggerParentHideDialogPageNum,
void 0,
skipDialogPageCheck
);
}
function dialogPageTriggerParentLifeCycle(dialogPage, lifeCycle, triggerParentHideDialogPageNum = 0, onBeforeTrigger, skipDialogPageCheck = false) {
if (!dialogPage.$triggerParentHide)
return false;
const pages = getCurrentPages();
const currentPage = pages[pages.length - 1];
if (!currentPage)
return false;
const parentPage = dialogPage.getParentPage();
if (!parentPage)
return false;
if (parentPage !== currentPage)
return false;
if (!skipDialogPageCheck) {
const dialogPages = currentPage.getDialogPages();
for (let i = 0; i < dialogPages.length; i++) {
if (!!dialogPages[i].$triggerParentHide) {
triggerParentHideDialogPageNum++;
if (triggerParentHideDialogPageNum > 1) {
return false;
}
}
}
if (triggerParentHideDialogPageNum <= 1) {
const systemDialogPages = getSystemDialogPages(parentPage);
for (let i = 0; i < systemDialogPages.length; i++) {
if (!!systemDialogPages[i].$triggerParentHide) {
triggerParentHideDialogPageNum++;
if (triggerParentHideDialogPageNum > 1) {
return false;
}
}
}
}
}
invokeHook(currentPage.vm, lifeCycle);
return true;
}
function getSystemDialogPages(parentPage) {
if (!parentPage)
return [];
return parentPage.$getSystemDialogPages();
}
function dialogPageTriggerPrevDialogPageLifeCycle(parentPage, lifeCycle) {
if (!parentPage)
return;
const pages = getCurrentPages();
const currentPage = pages[pages.length - 1];
if (!currentPage || parentPage !== currentPage)
return;
let prevDialogPage = getLastDialogPage(currentPage);
prevDialogPage && invokeHook(prevDialogPage.vm, lifeCycle);
}
function getLastDialogPage(parentPage) {
var _a, _b, _c, _d;
if (!parentPage)
return null;
const dialogPages = parentPage.getDialogPages();
const systemDialogPages = getSystemDialogPages(parentPage);
const lastSystemDialogPage = systemDialogPages[systemDialogPages.length - 1];
const lastDialogPage = dialogPages[dialogPages.length - 1];
if (!lastDialogPage)
return lastSystemDialogPage;
if (!lastSystemDialogPage)
return lastDialogPage;
const lastSystemDialogPageId = ((_b = (_a = lastSystemDialogPage.vm) == null ? void 0 : _a.$basePage) == null ? void 0 : _b.id) || Number.MAX_SAFE_INTEGER;
const lastDialogPageId = ((_d = (_c = lastDialogPage.vm) == null ? void 0 : _c.$basePage) == null ? void 0 : _d.id) || Number.MAX_SAFE_INTEGER;
return lastSystemDialogPageId > lastDialogPageId ? lastSystemDialogPage : lastDialogPage;
}
function invokeLastDialogPageHookByUniPage(parentPage, hook) {
const lastDialogPage = getLastDialogPage(parentPage);
if (lastDialogPage) {
invokeHook(lastDialogPage.vm, hook);
}
}
function invokeNewDialogPageHook(page, hook) {
const currentPage = getCurrentPage();
let shouldInvoke = false;
if (!currentPage) {
shouldInvoke = true;
} else {
if (isSystemDialogPage(page)) {
const systemDialogPages = getSystemDialogPages(currentPage);
shouldInvoke = systemDialogPages.includes(page);
} else {
const dialogPages = currentPage.getDialogPages();
shouldInvoke = dialogPages.includes(page);
}
}
shouldInvoke && invokeHook(page.vm, hook);
}
function getPageInstanceByChild(child2) {
var _a;
let pageInstance = child2;
while (pageInstance && ((_a = pageInstance.type) == null ? void 0 : _a.name) !== "Page") {
pageInstance = pageInstance.parent;
}
return pageInstance;
}
const DIALOG_TAG = "dialog";
const SYSTEM_DIALOG_TAG = "systemDialog";
function isDialogPageInstance(vm) {
if (!vm)
return false;
return isNormalDialogPageInstance(vm) || isSystemDialogPageInstance(vm);
}
function isNormalDialogPageInstance(vm) {
return vm.attrs["data-type"] === DIALOG_TAG;
}
function isSystemDialogPageInstance(vm) {
return vm.attrs["data-type"] === SYSTEM_DIALOG_TAG;
}
function warnUniAppVmMethod(methodName) {
initI18nAppVmMsgsOnce();
const methodCall = `getApp().vm?.${methodName}()`;
warn(
useI18n().t("uni.appVm.methodWarning", {
methodName,
methodCall
})
);
}
function createInitUniAppVmMethodWarnings() {
const VM_METHOD_WARNING_GETTER = Symbol.for(
"uni-app.vm-method-warning-getter"
);
const UNI_APP_METHODS = /* @__PURE__ */ new Set([
"$vm",
"globalData",
"getAndroidApplication",
"getHarmonyAbility",
"restart",
"vm"
]);
function getMethodSources(vm) {
var _a;
const instance2 = vm.$;
if (instance2.exposed) {
return [instance2.exposed];
}
return [
instance2.ctx,
((_a = instance2.setupState) == null ? void 0 : _a.__isScriptSetup) ? void 0 : instance2.setupState
];
}
function getVmMethodNames(vm) {
const methodNames = /* @__PURE__ */ new Set();
getMethodSources(vm).forEach((source) => {
if (!source) {
return;
}
Object.getOwnPropertyNames(source).forEach((name) => {
const descriptor = Object.getOwnPropertyDescriptor(source, name);
if (typeof unref(descriptor == null ? void 0 : descriptor.value) === "function") {
methodNames.add(name);
}
});
});
return methodNames;
}
function createWarningGetter(methodName, getter) {
const warningGetter = function() {
warnUniAppVmMethod(methodName);
return Reflect.apply(getter, this, []);
};
Object.defineProperty(warningGetter, VM_METHOD_WARNING_GETTER, {
value: { methodName }
});
return warningGetter;
}
function findPropertyDescriptor(target, methodName) {
try {
let owner = target;
while (owner) {
const descriptor = Object.getOwnPropertyDescriptor(owner, methodName);
if (descriptor) {
return { descriptor, own: owner === target };
}
owner = Object.getPrototypeOf(owner);
}
} catch {
return;
}
}
function defineProperty(target, methodName, descriptor) {
try {
Object.defineProperty(target, methodName, descriptor);
} catch {
}
}
function wrapAccessor(uniApp, methodName, descriptor, own) {
var _a;
const getter = descriptor.get;
if (!getter || ((_a = getter[VM_METHOD_WARNING_GETTER]) == null ? void 0 : _a.methodName) === methodName || own && !descriptor.configurable) {
return;
}
defineProperty(uniApp, methodName, {
configurable: own ? descriptor.configurable : true,
enumerable: descriptor.enumerable,
get: createWarningGetter(methodName, getter),
set: descriptor.set
});
}
function wrapDataProperty(uniApp, methodName, value, descriptor, own = false) {
if (own && !(descriptor == null ? void 0 : descriptor.configurable)) {
return;
}
let currentValue = value;
defineProperty(uniApp, methodName, {
configurable: own ? descriptor == null ? void 0 : descriptor.configurable : true,
enumerable: (descriptor == null ? void 0 : descriptor.enumerable) ?? false,
get: createWarningGetter(methodName, () => currentValue),
set: (descriptor == null ? void 0 : descriptor.writable) === false ? void 0 : (value2) => {
currentValue = value2;
}
});
}
function wrapUniAppMethod(uniApp, methodName, wrapMissingProperty = false) {
if (UNI_APP_METHODS.has(methodName)) {
return;
}
const property = findPropertyDescriptor(uniApp, methodName);
if (property) {
const { descriptor, own } = property;
if (descriptor.get) {
wrapAccessor(uniApp, methodName, descriptor, own);
} else if (typeof descriptor.value === "function") {
wrapDataProperty(uniApp, methodName, descriptor.value, descriptor, own);
}
return;
}
let method;
try {
method = uniApp[methodName];
} catch {
return;
}
if (typeof method === "function" || wrapMissingProperty) {
wrapDataProperty(uniApp, methodName, method);
}
}
return function initUniAppVmMethodWarnings2(uniApp) {
if (!uniApp.vm) {
return /* @__PURE__ */ new Set();
}
const methodNames = getVmMethodNames(uniApp.vm);
UNI_APP_METHODS.forEach((methodName) => methodNames.delete(methodName));
methodNames.forEach((methodName) => {
wrapUniAppMethod(uniApp, methodName, false);
});
return methodNames;
};
}
const initUniAppVmMethodWarnings = process.env.NODE_ENV !== "production" ? createInitUniAppVmMethodWarnings() : () => /* @__PURE__ */ new Set();
class ComponentDescriptor {
constructor(vm) {
this.$bindClass = false;
this.$bindStyle = false;
this.$vm = vm;
{
this.$el = resolveOwnerEl(vm.$);
}
if (this.$el.getAttribute) {
this.$bindClass = !!this.$el.getAttribute("class");
this.$bindStyle = !!this.$el.getAttribute("style");
}
}
selectComponent(selector) {
if (!this.$el || !selector) {
return;
}
const wxsVm = getWxsVm(this.$el.querySelector(selector));
if (!wxsVm) {
return;
}
return createComponentDescriptor(wxsVm, false);
}
selectAllComponents(selector) {
if (!this.$el || !selector) {
return [];
}
const descriptors2 = [];
const els = this.$el.querySelectorAll(selector);
for (let i = 0; i < els.length; i++) {
const wxsVm = getWxsVm(els[i]);
if (wxsVm) {
descriptors2.push(createComponentDescriptor(wxsVm, false));
}
}
return descriptors2;
}
forceUpdate(type) {
if (type === "class") {
if (this.$bindClass) {
this.$el.__wxsClassChanged = true;
this.$vm.$forceUpdate();
} else {
this.updateWxsClass();
}
} else if (type === "style") {
if (this.$bindStyle) {
this.$el.__wxsStyleChanged = true;
this.$vm.$forceUpdate();
} else {
this.updateWxsStyle();
}
}
}
updateWxsClass() {
const { __wxsAddClass } = this.$el;
if (__wxsAddClass.length) {
this.$el.className = __wxsAddClass.join(" ");
}
}
updateWxsStyle() {
const { __wxsStyle } = this.$el;
if (__wxsStyle) {
this.$el.setAttribute("style", stringifyStyle(__wxsStyle));
}
}
setStyle(style) {
if (!this.$el || !style) {
return this;
}
if (isString(style)) {
style = parseStringStyle(style);
}
if (isPlainObject(style)) {
this.$el.__wxsStyle = style;
this.forceUpdate("style");
}
return this;
}
addClass(clazz) {
if (!this.$el || !clazz) {
return this;
}
const __wxsAddClass = this.$el.__wxsAddClass || (this.$el.__wxsAddClass = []);
if (__wxsAddClass.indexOf(clazz) === -1) {
__wxsAddClass.push(clazz);
this.forceUpdate("class");
}
return this;
}
removeClass(clazz) {
if (!this.$el || !clazz) {
return this;
}
const { __wxsAddClass } = this.$el;
if (__wxsAddClass) {
const index2 = __wxsAddClass.indexOf(clazz);
if (index2 > -1) {
__wxsAddClass.splice(index2, 1);
}
}
const __wxsRemoveClass = this.$el.__wxsRemoveClass || (this.$el.__wxsRemoveClass = []);
if (__wxsRemoveClass.indexOf(clazz) === -1) {
__wxsRemoveClass.push(clazz);
this.forceUpdate("class");
}
return this;
}
hasClass(cls) {
return this.$el && this.$el.classList.contains(cls);
}
getDataset() {
return this.$el && this.$el.dataset;
}
callMethod(funcName, args = {}) {
const func = this.$vm[funcName];
if (isFunction(func)) {
func(JSON.parse(JSON.stringify(args)));
} else if (this.$vm.ownerId) {
UniViewJSBridge.publishHandler(ON_WXS_INVOKE_CALL_METHOD, {
nodeId: this.$el.__id,
ownerId: this.$vm.ownerId,
method: funcName,
args
});
}
}
requestAnimationFrame(callback) {
return window.requestAnimationFrame(callback);
}
getState() {
return this.$el && (this.$el.__wxsState || (this.$el.__wxsState = {}));
}
triggerEvent(eventName, detail = {}) {
return this.$vm.$emit(eventName, detail), this;
}
getComputedStyle(names) {
if (this.$el) {
const styles = window.getComputedStyle(this.$el);
if (names && names.length) {
return names.reduce((res, n) => {
res[n] = styles[n];
return res;
}, {});
}
return styles;
}
return {};
}
setTimeout(handler, timeout) {
return window.setTimeout(handler, timeout);
}
clearTimeout(handle) {
return window.clearTimeout(handle);
}
getBoundingClientRect() {
return this.$el.getBoundingClientRect();
}
}
function createComponentDescriptor(vm, isOwnerInstance = true) {
{
if (isOwnerInstance && vm) {
vm = resolveOwnerVm(vm.$);
}
}
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 resolveOwnerComponentPublicInstance(eventValue, instance2, checkArgsLength = true) {
if (!instance2) {
return false;
}
if (checkArgsLength && eventValue.length < 2) {
return false;
}
const ownerVm = resolveOwnerVm(instance2);
if (!ownerVm) {
return false;
}
const type = ownerVm.$.type;
if (!type.$wxs && !type.$renderjs) {
return false;
}
return ownerVm;
}
function wrapperH5WxsEvent(event, eventValue, instance2, checkArgsLength = true) {
if (eventValue) {
if (!event.__instance) {
event.__instance = true;
Object.defineProperty(event, "instance", {
get() {
return getComponentDescriptor(instance2.proxy, false);
}
});
}
const ownerVm = resolveOwnerComponentPublicInstance(
eventValue,
instance2,
checkArgsLength
);
if (ownerVm) {
return [event, getComponentDescriptor(ownerVm, false)];
}
}
}
function getWxsVm(el) {
if (!el) {
return;
}
{
return el.__vueParentComponent && el.__vueParentComponent.proxy;
}
}
function $nne(evt, eventValue, instance2) {
const { currentTarget } = evt;
if (!(evt instanceof Event) || !(currentTarget instanceof HTMLElement)) {
return [evt];
}
const isHTMLTarget = !isBuiltInElement(currentTarget);
{
if (isHTMLTarget) {
return wrapperH5WxsEvent(
evt,
eventValue,
instance2,
false
// 原生标签事件可能被cache,参数长度不准确,故默认不校验
) || [evt];
}
}
const res = createNativeEvent(evt, isHTMLTarget);
{
return wrapperH5WxsEvent(
res,
eventValue,
instance2
) || [res];
}
}
function findUniTarget(target) {
while (target && !isBuiltInElement(target)) {
target = target.parentElement;
}
return target;
}
function createNativeEvent(evt, htmlElement = false) {
const { target, currentTarget } = evt;
let realTarget, realCurrentTarget;
{
realTarget = htmlElement ? target : findUniTarget(target);
realCurrentTarget = currentTarget;
}
let detail;
return new Proxy(evt, {
get(target2, key) {
if (key === "target")
return realTarget;
if (key === "currentTarget")
return realCurrentTarget;
if (key === "detail") {
const value2 = target2.detail;
return isPlainObject(value2) ? value2 : detail || (detail = {});
}
const value = target2[key];
return isFunction(value) ? value.bind(target2) : value;
}
});
}
const instance = /* @__PURE__ */ Object.defineProperty({
__proto__: null,
$nne,
createNativeEvent
}, Symbol.toStringTag, { value: "Module" });
function initAppConfig$1(appConfig) {
const globalProperties = appConfig.globalProperties;
extend(globalProperties, instance);
if (__UNI_FEATURE_WXS__) {
globalProperties.$gcd = getComponentDescriptor;
}
}
function initViewPlugin(app) {
initAppConfig$1(app._context.config);
}
function normalizeVaporNativeEvent(event) {
const { currentTarget } = event;
if (!(event instanceof Event) || !(currentTarget instanceof HTMLElement) || !isBuiltInElement(currentTarget)) {
return event;
}
return createNativeEvent(event);
}
const invokeOnCallback = (name, res) => UniServiceJSBridge.emit("api." + name, res);
let invokeViewMethodId = 1;
function publishViewMethodName(pageId) {
return (pageId || getCurrentPageId()) + "." + INVOKE_VIEW_API;
}
const invokeViewMethod = (name, args, pageId, callback) => {
const { subscribe, publishHandler } = UniServiceJSBridge;
const id2 = callback ? invokeViewMethodId++ : 0;
callback && subscribe(INVOKE_VIEW_API + "." + id2, callback, true);
publishHandler(publishViewMethodName(pageId), { id: id2, name, args }, pageId);
};
const invokeViewMethodKeepAlive = (name, args, callback, pageId) => {
const { subscribe, unsubscribe, publishHandler } = UniServiceJSBridge;
const id2 = invokeViewMethodId++;
const subscribeName = INVOKE_VIEW_API + "." + id2;
subscribe(subscribeName, callback);
publishHandler(publishViewMethodName(pageId), { id: id2, name, args }, pageId);
return () => {
unsubscribe(subscribeName);
};
};
const ServiceJSBridge = /* @__PURE__ */ extend(
/* @__PURE__ */ initBridge(
"view"
/* view 指的是 service 层订阅的是 view 层事件 */
),
{
invokeOnCallback,
invokeViewMethod,
invokeViewMethodKeepAlive
}
);
function initOn() {
const { on: on2 } = UniServiceJSBridge;
on2(ON_RESIZE, onResize$2);
on2(ON_APP_ENTER_FOREGROUND, onAppEnterForeground);
on2(ON_APP_ENTER_BACKGROUND, onAppEnterBackground);
}
function onResize$2(res) {
var _a;
const page = (_a = getCurrentPage()) == null ? void 0 : _a.vm;
invokeHook(page, ON_RESIZE, res);
{
const dialogPages = page == null ? void 0 : page.$page.getDialogPages();
if ((dialogPages == null ? void 0 : dialogPages.length) > 0) {
invokeHook(dialogPages[dialogPages.length - 1].vm, ON_RESIZE, res);
}
const systemDialogPages = page == null ? void 0 : page.$page.$getSystemDialogPages();
if ((systemDialogPages == null ? void 0 : systemDialogPages.length) > 0) {
invokeHook(
systemDialogPages[systemDialogPages.length - 1].vm,
ON_RESIZE,
res
);
}
}
UniServiceJSBridge.invokeOnCallback("onWindowResize", res);
}
function onAppEnterForeground(enterOptions2) {
var _a;
const page = (_a = getCurrentPage()) == null ? void 0 : _a.vm;
invokeHook(
getApp().vm,
ON_SHOW,
enterOptions2
);
invokeHook(page, ON_SHOW);
}
function onAppEnterBackground() {
var _a;
invokeHook(
getApp().vm,
ON_HIDE
);
invokeHook(
(_a = getCurrentPage()) == null ? void 0 : _a.vm,
ON_HIDE
);
}
const SUBSCRIBE_LIFECYCLE_HOOKS = [ON_PAGE_SCROLL, ON_REACH_BOTTOM];
function initSubscribe() {
SUBSCRIBE_LIFECYCLE_HOOKS.forEach(
(name) => UniServiceJSBridge.subscribe(name, createPageEvent(name))
);
}
function createPageEvent(name) {
return (args, pageId) => {
invokeHook(parseInt(pageId), name, args);
};
}
function initService() {
{
initOn();
initSubscribe();
}
}
function initAppVm(appVm2) {
appVm2.$vm = appVm2;
appVm2.$mpType = "app";
const locale = ref(useI18n().getLocale());
Object.defineProperty(appVm2, "$locale", {
get() {
return locale.value;
},
set(v2) {
locale.value = v2;
}
});
}
function initPageVm(pageVm, page) {
pageVm.route = page.route;
pageVm.$vm = pageVm;
{
pageVm.$basePage = page;
}
pageVm.$mpType = "page";
pageVm.$fontFamilySet = /* @__PURE__ */ new Set();
if (page.meta.isTabBar) {
pageVm.$.__isTabBar = true;
pageVm.$.__isActive = true;
}
}
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 createMediaQueryObserver$1() {
return uni.createMediaQueryObserver(this);
}
function createIntersectionObserver$1(options) {
return uni.createIntersectionObserver(this, options);
}
function selectComponent(selector) {
return querySelector(this, selector);
}
function selectAllComponents(selector) {
return querySelectorAll(this, selector);
}
const wxInstance = /* @__PURE__ */ Object.defineProperty({
__proto__: null,
createIntersectionObserver: createIntersectionObserver$1,
createMediaQueryObserver: createMediaQueryObserver$1,
createSelectorQuery: createSelectorQuery$1,
selectAllComponents,
selectComponent
}, Symbol.toStringTag, { value: "Module" });
function getOpenerEventChannel() {
{
const page = this.$basePage;
if (page) {
if (!page.eventChannel) {
page.eventChannel = new EventChannel(page.id);
}
return page.eventChannel;
}
}
}
function initAppConfig(appConfig) {
const globalProperties = appConfig.globalProperties;
globalProperties.getOpenerEventChannel = getOpenerEventChannel;
if (__UNI_FEATURE_WX__) {
extend(globalProperties, wxInstance);
}
}
function initServicePlugin(app) {
initAppConfig(app._context.config);
}
function createLaunchOptions() {
return {
path: "",
query: {},
scene: 1001,
referrerInfo: {
appId: "",
extraData: {}
}
};
}
function defineGlobalData(app, defaultGlobalData) {
const options = app.$options || {};
options.globalData = extend(options.globalData || {}, defaultGlobalData);
Object.defineProperty(app, "globalData", {
get() {
return options.globalData;
},
set(newGlobalData) {
options.globalData = newGlobalData;
}
});
}
function throttle(fn, wait) {
let last = 0;
let timeout;
let waitCallback;
const newFn = function(...arg) {
const now = Date.now();
clearTimeout(timeout);
waitCallback = () => {
waitCallback = null;
last = now;
fn.apply(this, arg);
};
if (now - last < wait) {
timeout = setTimeout(waitCallback, wait - (now - last));
return;
}
waitCallback();
};
newFn.cancel = function() {
clearTimeout(timeout);
waitCallback = null;
};
newFn.flush = function() {
clearTimeout(timeout);
waitCallback && waitCallback();
};
return newFn;
}
function withWebEvent(fn) {
return fn.__wwe = true, fn;
}
function useCustomEvent(ref2, emit2) {
return (name, evt, detail) => {
if (ref2.value) {
emit2(name, normalizeCustomEvent(name, evt, ref2.value, detail || {}));
}
};
}
function normalizeCustomEvent(name, domEvt, el, detail) {
const target = el;
return {
type: domEvt.__evName || detail.type || name,
timeStamp: domEvt.timeStamp || 0,
target,
currentTarget: target,
detail
};
}
const passiveOptions$2 = /* @__PURE__ */ passive(true);
const states = [];
let userInteract = 0;
let inited = false;
const setUserAction = (userAction) => states.forEach((vm) => vm.userAction = userAction);
function addInteractListener(vm = { userAction: false }) {
if (!inited) {
const eventNames = [
"touchstart",
"touchmove",
"touchend",
"mousedown",
"mouseup"
];
eventNames.forEach((eventName) => {
document.addEventListener(
eventName,
function() {
!userInteract && setUserAction(true);
userInteract++;
setTimeout(() => {
!--userInteract && setUserAction(false);
}, 0);
},
passiveOptions$2
);
});
inited = true;
}
states.push(vm);
}
function removeInteractListener(vm) {
const index2 = states.indexOf(vm);
if (index2 >= 0) {
states.splice(index2, 1);
}
}
const getInteractStatus = () => !!userInteract;
function useUserAction() {
const state = reactive({
/**
* 是否用户激活
*/
userAction: false
});
onMounted(() => {
addInteractListener(state);
});
onBeforeUnmount(() => {
removeInteractListener(state);
});
return {
state
};
}
let resetTimer;
function iosHideKeyboard() {
}
const props$b = {
cursorSpacing: {
type: [Number, String],
default: 0
},
showConfirmBar: {
type: [Boolean, String],
default: "auto"
},
adjustPosition: {
type: [Boolean, String],
default: true
},
autoBlur: {
type: [Boolean, String],
default: false
}
};
const emit$1 = ["keyboardheightchange"];
function useKeyboard$1(props2, elRef, trigger) {
function initKeyboard(el) {
const isApple2 = computed(
() => String(navigator.vendor).indexOf("Apple") === 0
);
el.addEventListener("focus", () => {
clearTimeout(resetTimer);
document.addEventListener("click", iosHideKeyboard, false);
});
const onKeyboardHide = () => {
document.removeEventListener("click", iosHideKeyboard, false);
if (isApple2.value) {
document.documentElement.scrollTo(
document.documentElement.scrollLeft,
document.documentElement.scrollTop
);
}
};
el.addEventListener("blur", () => {
if (isApple2.value) {
el.blur();
}
onKeyboardHide();
});
}
watch(
() => elRef.value,
(el) => el && initKeyboard(el)
);
}
function useScopedAttrs() {
const state = reactive({
attrs: {}
});
onMounted(() => {
let instance2 = getCurrentInstance();
while (instance2) {
const scopeId = instance2.type.__scopeId;
if (scopeId) {
state.attrs[scopeId] = "";
}
instance2 = instance2.proxy && instance2.proxy.$mpType === "page" ? null : instance2.parent;
}
});
return {
state
};
}
function useVaporFormField(props2, state) {
const form = inject("UNI_FORM_CTX", null);
if (!form)
return;
const initialValue = state.value;
const getValue = () => state.value;
const reset = () => {
state.value = initialValue;
};
watch(
() => props2.name,
(name, oldName) => {
if (oldName)
form.unregisterField(oldName);
if (name)
form.registerField({ name, getValue, reset });
},
{ immediate: true, flush: "sync" }
);
onBeforeUnmount(() => {
if (props2.name)
form.unregisterField(props2.name);
});
}
function getSelectedTextRange$1(_, resolve) {
const activeElement = document.activeElement;
if (!activeElement) {
return resolve({});
}
const data = {};
if (["input", "textarea"].includes(activeElement.tagName.toLowerCase())) {
data.start = activeElement.selectionStart;
data.end = activeElement.selectionEnd;
}
resolve(data);
}
const UniViewJSBridgeSubscribe = function() {
registerViewMethod(
getCurrentPageId(),
"getSelectedTextRange",
getSelectedTextRange$1
);
};
function getValueString(value, type, maxlength) {
if (type === "number" && isNaN(Number(value))) {
value = "";
}
const valueStr = value === null || value === void 0 ? "" : String(value);
if (maxlength == void 0) {
return valueStr;
}
return valueStr.slice(0, maxlength);
}
const INPUT_MODES = [
"none",
"text",
"decimal",
"numeric",
"tel",
"search",
"email",
"url"
];
const props$a = /* @__PURE__ */ extend(
{},
{
name: {
type: String,
default: ""
},
modelValue: {
type: [String, Number]
},
value: {
type: [String, Number]
},
disabled: {
type: [Boolean, String],
default: false
},
/**
* 已废弃属性,用于历史兼容
*/
autoFocus: {
type: [Boolean, String],
default: false
},
focus: {
type: [Boolean, String],
default: false
},
cursor: {
type: [Number, String],
default: -1
},
selectionStart: {
type: [Number, String],
default: -1
},
selectionEnd: {
type: [Number, String],
default: -1
},
type: {
type: String,
default: "text"
},
password: {
type: [Boolean, String],
default: false
},
placeholder: {
type: String,
default: ""
},
placeholderStyle: {
type: String,
default: ""
},
placeholderClass: {
type: String,
default: ""
},
maxlength: {
type: [Number, String],
default: Infinity
},
confirmType: {
type: String,
default: "done"
},
confirmHold: {
type: Boolean,
default: false
},
ignoreCompositionEvent: {
type: Boolean,
default: true
},
step: {
type: String,
default: "0.000000000000000001"
},
inputmode: {
type: String,
default: void 0,
validator: (value) => !!~INPUT_MODES.indexOf(value)
},
cursorColor: {
type: String,
default: ""
}
},
props$b
);
const emit = [
"input",
"focus",
"blur",
"update:value",
"update:modelValue",
"update:focus",
"compositionstart",
"compositionupdate",
"compositionend",
...emit$1
];
function useBase(props2, rootRef, emit2) {
const fieldRef = ref(null);
const trigger = useCustomEvent(rootRef, emit2);
const selectionStart = computed(() => {
const selectionStart2 = Number(props2.selectionStart);
return isNaN(selectionStart2) ? -1 : selectionStart2;
});
const selectionEnd = computed(() => {
const selectionEnd2 = Number(props2.selectionEnd);
return isNaN(selectionEnd2) ? -1 : selectionEnd2;
});
const cursor = computed(() => {
const cursor2 = Number(props2.cursor);
return isNaN(cursor2) ? -1 : cursor2;
});
const maxlength = computed(() => {
var maxlength2 = Number(props2.maxlength);
{
return isNaN(maxlength2) || maxlength2 < 0 ? Infinity : Math.floor(maxlength2);
}
});
let value = "";
{
const modelValueString = getValueString(
props2.modelValue,
props2.type,
maxlength.value
);
const valueString = getValueString(props2.value, props2.type, maxlength.value);
value = props2.modelValue !== void 0 ? modelValueString !== null && modelValueString !== void 0 ? modelValueString : valueString : valueString;
}
const state = reactive({
value,
valueOrigin: value,
maxlength,
focus: props2.focus,
composing: false,
selectionStart,
selectionEnd,
cursor
});
watch(
() => state.focus,
(val) => emit2("update:focus", val)
);
watch(
() => state.maxlength,
(val) => {
if (val >= 0) {
state.value = state.value.slice(0, val);
}
},
{
immediate: true
}
);
return {
fieldRef,
state,
trigger
};
}
function useValueSync(props2, state, emit2, trigger, fieldRef) {
let valueChangeFn = null;
{
valueChangeFn = throttle((val) => {
state.value = getValueString(val, props2.type, state.maxlength);
}, 100);
}
watch(() => props2.modelValue, valueChangeFn);
watch(() => props2.value, valueChangeFn);
const triggerInputFn = throttle((event, detail) => {
valueChangeFn.cancel();
emit2("update:modelValue", detail.value);
emit2("update:value", detail.value);
trigger("input", event, detail);
}, 100);
const triggerInput = (event, detail, force) => {
valueChangeFn.cancel();
detail.value;
triggerInputFn(event, detail);
if (force) {
triggerInputFn.flush();
}
};
onBeforeMount(() => {
valueChangeFn.cancel();
triggerInputFn.cancel();
});
return {
trigger,
triggerInput
};
}
function useAutoFocus(props2, fieldRef) {
useUserAction();
const needFocus = computed(() => props2.autoFocus || props2.focus);
function focus() {
if (!needFocus.value) {
return;
}
const field = fieldRef.value;
if (!field || false) {
setTimeout(focus, 100);
return;
}
{
field.focus();
}
}
function blur() {
const field = fieldRef.value;
if (field) {
field.blur();
}
}
watch(
() => props2.focus,
(value) => {
if (value) {
focus();
} else {
blur();
}
}
);
onMounted(() => {
if (needFocus.value) {
nextTick(focus);
}
});
}
function useEvent(fieldRef, state, props2, trigger, triggerInput, beforeInput) {
function checkSelection() {
const field = fieldRef.value;
if (field && state.focus && state.selectionStart > -1 && state.selectionEnd > -1 && typeof field.selectionStart === "number") {
field.selectionStart = state.selectionStart;
field.selectionEnd = state.selectionEnd;
}
}
function checkCursor() {
const field = fieldRef.value;
if (field && state.focus && state.selectionStart < 0 && state.selectionEnd < 0 && state.cursor > -1 && typeof field.selectionStart === "number") {
field.selectionEnd = field.selectionStart = state.cursor;
}
}
function getFieldSelectionEnd(field) {
if (field.type === "number") {
return null;
} else {
return field.selectionEnd;
}
}
function initField() {
const field = fieldRef.value;
if (!field)
return;
const onFocus = function(event) {
state.focus = true;
trigger("focus", event, {
value: state.value
});
checkSelection();
checkCursor();
};
const onInput = function(event, force) {
event.stopPropagation();
if (isFunction(beforeInput) && beforeInput(event, state) === false) {
return;
}
state.value = field.value;
if (!state.composing || !props2.ignoreCompositionEvent) {
triggerInput(
event,
{
value: field.value,
cursor: getFieldSelectionEnd(field)
},
force
);
}
};
const onBlur = function(event) {
if (state.composing) {
state.composing = false;
onInput(event, true);
}
state.focus = false;
trigger("blur", event, {
value: state.value,
cursor: getFieldSelectionEnd(event.target)
});
};
field.addEventListener("change", (event) => event.stopPropagation());
field.addEventListener("focus", onFocus);
field.addEventListener("blur", onBlur);
field.addEventListener("input", onInput);
field.addEventListener("compositionstart", (event) => {
event.stopPropagation();
state.composing = true;
_onComposition(event);
});
field.addEventListener("compositionend", (event) => {
event.stopPropagation();
if (state.composing) {
state.composing = false;
onInput(event);
}
_onComposition(event);
});
field.addEventListener("compositionupdate", _onComposition);
function _onComposition(event) {
if (!props2.ignoreCompositionEvent) {
trigger(event.type, event, {
value: event.data
});
}
}
}
watch([() => state.selectionStart, () => state.selectionEnd], checkSelection);
watch(() => state.cursor, checkCursor);
watch(() => fieldRef.value, initField);
}
function useField(props2, rootRef, emit2, beforeInput) {
UniViewJSBridgeSubscribe();
const { fieldRef, state, trigger } = useBase(props2, rootRef, emit2);
const { triggerInput } = useValueSync(props2, state, emit2, trigger);
useAutoFocus(props2, fieldRef);
useKeyboard$1(props2, fieldRef);
const { state: scopedAttrsState } = useScopedAttrs();
useVaporFormField(props2, state);
useEvent(fieldRef, state, props2, trigger, triggerInput, beforeInput);
const fixDisabledColor = String(navigator.vendor).indexOf("Apple") === 0 && CSS.supports("image-orientation:from-image");
return {
fieldRef,
state,
scopedAttrsState,
fixDisabledColor,
trigger
};
}
once(() => {
{
const ua2 = navigator.userAgent;
let osVersion = "";
const osVersionFind = ua2.match(/OS\s([\w_]+)\slike/);
if (osVersionFind) {
osVersion = osVersionFind[1].replace(/_/g, ".");
} else if (/Macintosh|Mac/i.test(ua2) && navigator.maxTouchPoints > 0) {
const versionMatched = ua2.match(/Version\/(\S*)\b/);
if (versionMatched) {
osVersion = versionMatched[1];
}
}
return !!osVersion && parseInt(osVersion) >= 16 && parseFloat(osVersion) < 17.2;
}
});
const webSelectionProps$1 = fieldSelectionProps;
const props$9 = /* @__PURE__ */ extend(
{},
props$a,
{
placeholderClass: {
type: String,
default: "input-placeholder"
},
textContentType: {
type: String,
default: ""
}
},
webSelectionProps$1
);
function isPaste(event) {
return event.inputType === "insertFromPaste";
}
function useCache(props2, type) {
if (type.value === "number") {
const value = typeof props2.modelValue === "undefined" ? props2.value : props2.modelValue;
const cache = ref(
typeof value !== "undefined" && value !== null ? value.toLocaleString() : ""
);
watch(
() => props2.modelValue,
(value2) => {
cache.value = typeof value2 !== "undefined" && value2 !== null ? value2.toLocaleString() : "";
}
);
watch(
() => props2.value,
(value2) => {
cache.value = typeof value2 !== "undefined" && value2 !== null ? value2.toLocaleString() : "";
}
);
return cache;
} else {
return ref("");
}
}
const emits$2 = ["confirm", ...emit];
function useInput(props2, { emit: emit2, expose }) {
const INPUT_TYPES = [
"text",
"number",
"idcard",
"digit",
"password",
"tel",
"search",
"email"
];
const AUTOCOMPLETES = ["off", "one-time-code"];
const type = computed(() => {
let type2 = "";
switch (props2.type) {
case "text":
type2 = "text";
if (props2.confirmType === "search") {
type2 = "search";
}
break;
case "idcard":
type2 = "text";
break;
case "digit":
type2 = "number";
break;
case "none":
type2 = "text";
break;
default:
type2 = INPUT_TYPES.includes(props2.type) ? props2.type : "text";
break;
}
return props2.password ? "password" : type2;
});
const autocomplete = computed(() => {
const camelizeIndex = AUTOCOMPLETES.indexOf(props2.textContentType);
const kebabCaseIndex = AUTOCOMPLETES.indexOf(
hyphenate(props2.textContentType)
);
const index2 = camelizeIndex !== -1 ? camelizeIndex : kebabCaseIndex !== -1 ? kebabCaseIndex : 0;
return AUTOCOMPLETES[index2];
});
const inputmode = computed(() => {
if (props2.inputmode !== void 0) {
return props2.inputmode;
}
if (INPUT_MODES.includes(props2.type)) {
return props2.type;
}
let inputmodeMap = {};
{
inputmodeMap = {
number: "numeric",
digit: "decimal",
idcard: "text"
};
}
return inputmodeMap[props2.type];
});
let cache = useCache(props2, type);
const rootRef = ref(null);
const { fieldRef, state, scopedAttrsState, fixDisabledColor, trigger } = useField(props2, rootRef, emit2, (event, state2) => {
{
return;
}
});
const selectionRef = useFieldSelection(props2, fieldRef);
watch(
() => state.value,
(value) => {
if (props2.type === "number" && !(cache.value === "-" && value === "")) {
cache.value = value.toString();
}
}
);
watch(
() => props2.maxlength,
(length) => {
length = parseInt(length, 10);
if (!(length >= 0)) {
return;
}
const realValue = state.value.slice(0, length);
realValue !== state.value && (state.value = realValue);
}
);
const NUMBER_TYPES = ["number", "digit"];
const step = computed(
() => NUMBER_TYPES.includes(props2.type) ? props2.step : ""
);
function onKeyUpEnter(event) {
if (event.key !== "Enter") {
return;
}
const input = event.target;
event.stopPropagation();
trigger("confirm", event, {
value: input.value
});
!props2.confirmHold && input.blur();
}
expose({
$triggerInput: (detail) => {
emit2("update:modelValue", detail.value);
emit2("update:value", detail.value);
state.value = detail.value;
}
});
function onInput(event) {
const value = event.target.value.toString();
if (type.value === "number" && state.maxlength > 0 && value.length > state.maxlength) {
if (isPaste(event)) {
state.value = value.slice(0, state.maxlength);
}
return;
}
if (value.length === 0 && event.inputType === "insertText" && event.data === ".") {
return;
}
state.value = value;
}
return {
rootRef,
fieldRef,
state,
scopedAttrsState,
selectionRef,
fixDisabledColor,
type,
autocomplete,
inputmode,
cache,
step,
onKeyUpEnter,
onInput
};
}
const createComponent = (type, ...args) => {
if (type === Fragment) {
const slots = args[1];
return slots ? typeof slots === "function" ? slots() : typeof slots.default === "function" ? slots.default() : [] : [];
}
return Vue.createComponentWithFallback(
createProxyComponent(Vue.resolveDynamicComponent(type)),
...args
);
};
const proxyCache = /* @__PURE__ */ new WeakMap();
function createProxyComponent(type, normalizeNode2) {
if (typeof type === "function") {
const existing = proxyCache.get(type);
if (existing)
return existing;
const i = Vue.currentInstance || getCurrentInstance();
const proxy = new Proxy(type, {
apply(target, ctx, args) {
if (typeof target.__setup === "function") {
target.__setup.apply(ctx, args);
}
const node = Reflect.apply(target, ctx, args);
return node;
},
get(target, p2, receiver) {
const result = Reflect.get(target, p2, receiver);
if (p2 === "__vapor" && result === void 0 && i && i.appContext.vapor) {
return true;
}
return result;
}
});
proxyCache.set(type, proxy);
return proxy;
}
return type;
}
function createFragment(nodes, anchor = document.createTextNode("")) {
const frag = new Vue.VaporFragment(nodes);
frag.anchor = anchor;
return frag;
}
function normalizeBlock(node, anchor, processFunction = false) {
if (node instanceof Node || Vue.isFragment(node)) {
return node;
} else if (Vue.isVaporComponent(node)) {
return createFragment(node, anchor);
} else if (Array.isArray(node)) {
return createFragment(
node.map((i) => normalizeBlock(i, void 0, processFunction)),
anchor
);
} else if (processFunction && typeof node === "function") {
return resolveValues([node], anchor, true)[0];
} else {
const result = node == null || typeof node === "boolean" ? "" : String(node);
if (anchor) {
anchor.textContent = result;
return anchor;
} else {
return document.createTextNode(result);
}
}
}
function resolveValue(current, value, anchor, processFunction = false) {
anchor = anchor || (current instanceof Node && current.nodeType === 3 ? current : void 0);
const node = normalizeBlock(value, anchor, processFunction);
if (current) {
if (Vue.isFragment(current)) {
if (current.anchor && current.anchor.parentNode) {
Vue.remove(current.nodes, current.anchor.parentNode);
Vue.insert(node, current.anchor.parentNode, current.anchor);
if (!anchor)
current.anchor.parentNode.removeChild(current.anchor);
if (current.scope)
current.scope.stop();
}
} else if (current instanceof Node) {
if (current.nodeType === 3 && (!(node instanceof Node) || node.nodeType !== 3)) {
current.textContent = "";
}
if (Vue.isFragment(node) && current.parentNode) {
Vue.insert(node, current.parentNode, current);
if (!anchor || current.nodeType !== 3) {
current.parentNode.removeChild(current);
}
} else if (node instanceof Node) {
if (current.nodeType === 3 && node.nodeType === 3) {
current.textContent = node.textContent;
return current;
} else if (current.parentNode) {
current.parentNode.replaceChild(node, current);
}
}
}
}
return node;
}
function resolveValues(values = [], _anchor, processFunction = false) {
const nodes = [];
const scopes = [];
for (const [index2, value] of values.entries()) {
const anchor = index2 === values.length - 1 ? _anchor : void 0;
if (typeof value === "function") {
Vue.renderEffect(() => {
if (scopes[index2])
scopes[index2].stop();
scopes[index2] = new EffectScope();
nodes[index2] = scopes[index2].run(
() => resolveValue(nodes[index2], value(), anchor, processFunction)
);
});
} else {
nodes[index2] = resolveValue(nodes[index2], value, anchor, processFunction);
}
}
return nodes;
}
function setNodes(anchor, ...values) {
const resolvedValues = resolveValues(values, anchor);
if (anchor.parentNode)
Vue.insert(resolvedValues, anchor.parentNode, anchor);
}
function createNodes(...values) {
return resolveValues(values);
}
const _t0$f = template("<input tabindex=-1>");
const _t1$4 = template("<input>");
const _t2$3 = template("<form action novalidate class=uni-input-form> ");
const _t3$3 = template("<div uni-input uni-view><div class=uni-input-wrapper> <div> </div>", 1);
const _t4$3 = template("<div>", 1);
const __syscom_0$2 = /* @__PURE__ */ defineBuiltInComponent({
name: "Input",
props: props$9,
emits: emits$2,
rootElement: {
name: "uni-input",
class: UniInputElement
},
setup(props2, context) {
const { rootRef, fieldRef, state, scopedAttrsState, selectionRef, fixDisabledColor, type, autocomplete, inputmode, cache, step, onKeyUpEnter, onInput } = useInput(props2, context);
const renderInput = () => (() => {
const _setTemplateRef = createTemplateRefSetter();
const _n0 = createIf(() => props2.disabled && fixDisabledColor, () => {
const _n2 = _t0$f();
setBlockKey(_n2, "disabled-input");
on$1(
_n2,
// fix: 禁止 readonly 状态获取焦点
"focus",
(event) => event.target.blur()
);
renderEffect(() => {
setValue$1(_n2, state.value);
setProp(_n2, "readonly", !!props2.disabled);
setProp(_n2, "type", type.value);
setProp(_n2, "maxlength", state.maxlength);
setProp(_n2, "step", step.value);
setClass(_n2, props2.selectionClass ? "uni-input-input uni-field-selection" : "uni-input-input");
setStyle(_n2, props2.cursorColor ? { caretColor: props2.cursorColor } : {});
setProp(_n2, "inputmode", inputmode.value);
_setTemplateRef(_n2, fieldRef);
});
return _n2;
}, () => {
const _n4 = _t1$4();
setBlockKey(_n4, "input");
on$1(_n4, "input", withModifiers(onInput, ["stop"]));
on$1(_n4, "keyup", onKeyUpEnter);
renderEffect(() => {
setValue$1(_n4, state.value);
setProp(_n4, "disabled", !!props2.disabled);
setProp(_n4, "type", type.value);
setProp(_n4, "maxlength", state.maxlength);
setProp(_n4, "step", step.value);
setProp(_n4, "enterkeyhint", props2.confirmType);
setProp(_n4, "pattern", props2.type === "number" ? "[0-9]*" : void 0);
setClass(_n4, props2.selectionClass ? "uni-input-input uni-field-selection" : "uni-input-input");
setStyle(_n4, props2.cursorColor ? { caretColor: props2.cursorColor } : {});
setProp(_n4, "autocomplete", autocomplete.value);
setProp(_n4, "inputmode", inputmode.value);
_setTemplateRef(_n4, fieldRef);
});
return _n4;
}, 261);
return _n0;
})();
const root = (() => {
const _setTemplateRef = createTemplateRefSetter();
const _n8 = _t3$3();
const _n7 = child(_n8);
const _n0 = child(_n7, true);
const _n1 = next(_n0);
setNodes(_n0, () => props2.selectionClass && (() => {
const _setTemplateRef2 = createTemplateRefSetter();
const _n02 = _t4$3();
renderEffect(() => {
setDynamicProps(_n02, [scopedAttrsState.attrs, {
class: ["uni-field-selection-probe", props2.selectionClass],
"aria-hidden": "true",
style: fieldSelectionProbeStyle
}]);
_setTemplateRef2(_n02, selectionRef);
});
return _n02;
})());
applyVShow(_n1, () => !(state.value.length || cache.value === "-" || cache.value.includes(".")));
const _x1 = txt(_n1);
setNodes(_x1, () => props2.placeholder);
renderEffect(() => setDynamicProps(_n1, [scopedAttrsState.attrs, {
style: props2.placeholderStyle,
class: ["uni-input-placeholder", props2.placeholderClass]
}]));
setInsertionState(_n7, 2);
createIf(() => props2.confirmType === "search", () => {
const _n4 = _t2$3();
on$1(_n4, "submit", (event) => event.preventDefault());
const _x4 = txt(_n4);
setNodes(_x4, () => renderInput());
return _n4;
}, () => {
const _n6 = createNodes(() => renderInput());
return _n6;
}, 265);
renderEffect(() => _setTemplateRef(_n8, rootRef));
return _n8;
})();
initInputElement(root);
return root;
}
});
const resizeSensorProps = {
initial: {
type: Boolean,
default: false
}
};
function useResizeSensor(props2, emit2) {
const rootRef = ref(null);
const reset = useResizeSensorReset(rootRef);
const update = useResizeSensorUpdate(rootRef, emit2, reset);
useResizeSensorLifecycle(rootRef, props2, update, reset);
return { rootRef, update };
}
function useResizeSensorUpdate(rootRef, emit2, reset) {
const size = reactive({ width: -1, height: -1 });
watch(
() => extend({}, size),
(value) => emit2("resize", value)
);
return () => {
const rootEl = rootRef.value;
if (!rootEl)
return;
const rect = rootEl.getBoundingClientRect();
size.width = rect.width;
size.height = rect.height;
reset();
};
}
function useResizeSensorReset(rootRef) {
return () => {
const { firstElementChild, lastElementChild } = rootRef.value;
firstElementChild.scrollLeft = 1e5;
firstElementChild.scrollTop = 1e5;
lastElementChild.scrollLeft = 1e5;
lastElementChild.scrollTop = 1e5;
};
}
function useResizeSensorLifecycle(rootRef, props2, update, reset) {
onActivated(reset);
onMounted(() => {
if (props2.initial) {
nextTick(update);
}
const rootEl = rootRef.value;
if (rootEl.offsetParent !== rootEl.parentElement) {
rootEl.parentElement.style.position = "relative";
}
if (!("AnimationEvent" in window)) {
reset();
}
});
}
const _t0$e = template("<div uni-resize-sensor><div><div></div></div><div><div>", 1);
const ResizeSensor = /* @__PURE__ */ defineBuiltInComponent({
name: "ResizeSensor",
props: resizeSensorProps,
emits: ["resize"],
setup(props2, { emit: emit2 }) {
const { rootRef, update } = useResizeSensor(props2, emit2);
const root = (() => {
const _setTemplateRef = createTemplateRefSetter();
const _n2 = _t0$e();
const _n0 = child(_n2);
const _n1 = next(_n0);
on$1(_n0, "scroll", update);
on$1(_n1, "scroll", update);
renderEffect(() => _setTemplateRef(_n2, rootRef));
return _n2;
})();
on$1(root, "animationstart", update, { once: true });
return root;
}
});
const _UniTextareaElement = class _UniTextareaElement extends UniViewElement {
static [Symbol.hasInstance](value) {
return this === _UniTextareaElement && value instanceof UniViewElement && value.hasAttribute("uni-textarea") || Function.prototype[Symbol.hasInstance].call(this, value);
}
focus(options) {
var _a;
(_a = this.querySelector("textarea")) == null ? void 0 : _a.focus(options);
}
};
_UniTextareaElement.__uniElement = {};
let UniTextareaElement = _UniTextareaElement;
const descriptors = {
uniTagName: { value: "TEXTAREA" },
focus: Object.getOwnPropertyDescriptor(
UniTextareaElement.prototype,
"focus"
)
};
function setValue(value) {
this.querySelector("textarea").value = value;
}
function initTextareaElement(root, state) {
Object.defineProperties(root, descriptors);
Object.defineProperty(root, "value", {
get: () => state.value,
set: setValue
});
}
const webSelectionProps = fieldSelectionProps;
const props$8 = /* @__PURE__ */ extend(
{},
props$a,
{
placeholderClass: {
type: String,
default: "input-placeholder"
},
autoHeight: {
type: [Boolean, String],
default: false
},
confirmType: {
type: String,
default: "return",
validator(val) {
return ConfirmTypes.concat("return").includes(val);
}
}
},
webSelectionProps
);
let fixMargin = false;
const ConfirmTypes = ["done", "go", "next", "search", "send"];
function setFixMargin() {
const DARK_TEST_STRING = "(prefers-color-scheme: dark)";
fixMargin = String(navigator.platform).indexOf("iP") === 0 && String(navigator.vendor).indexOf("Apple") === 0 && window.matchMedia(DARK_TEST_STRING).media !== DARK_TEST_STRING;
}
const emits$1 = ["confirm", "change", "linechange", ...emit];
function useTextarea(props2, { emit: emit2, expose }) {
const rootRef = ref(null);
const wrapperRef = ref(null);
const { fieldRef, state, scopedAttrsState, fixDisabledColor, trigger } = useField(props2, rootRef, emit2);
const selectionRef = useFieldSelection(props2, fieldRef);
const valueCompute = computed(() => state.value.split(LINEFEED));
const isDone = computed(() => ConfirmTypes.includes(props2.confirmType));
const heightRef = ref(0);
const lineRef = ref(null);
watch(
() => heightRef.value,
(height) => {
const el = rootRef.value;
const lineEl = lineRef.value;
const wrapper = wrapperRef.value;
let lineHeight = parseFloat(getComputedStyle(el).lineHeight);
if (isNaN(lineHeight)) {
lineHeight = lineEl.offsetHeight;
}
var lineCount = Math.round(height / lineHeight);
trigger("linechange", {}, {
height,
heightRpx: 750 / window.innerWidth * height,
lineCount
});
if (props2.autoHeight) {
wrapper.style.height = height + "px";
}
}
);
watch(
() => props2.autoHeight,
(autoHeight) => {
const wrapper = wrapperRef.value;
if (autoHeight) {
wrapper.style.height = heightRef.value + "px";
} else {
wrapper.style.height = "";
}
}
);
function onResize2({ height }) {
heightRef.value = height;
}
function onChange2(event) {
{
trigger("change", event, {
value: state.value
});
}
}
function confirm(event) {
trigger("confirm", event, {
value: state.value
});
}
function onKeyDownEnter(event) {
if (event.key !== "Enter") {
return;
}
if (isDone.value) {
event.preventDefault();
}
}
function onKeyUpEnter(event) {
if (event.key !== "Enter") {
return;
}
if (isDone.value) {
confirm(event);
const textarea = event.target;
!props2.confirmHold && textarea.blur();
}
}
{
setFixMargin();
}
expose({
$triggerInput: (detail) => {
emit2("update:modelValue", detail.value);
emit2("update:value", detail.value);
state.value = detail.value;
}
});
return {
rootRef,
wrapperRef,
fieldRef,
state,
scopedAttrsState,
selectionRef,
fixDisabledColor,
valueCompute,
lineRef,
onResize: onResize2,
onChange: onChange2,
onKeyDownEnter,
onKeyUpEnter
};
}
const _t0$d = template("<textarea tabindex=-1>");
const _t1$3 = template("<textarea>");
const _t2$2 = template("<form action class=uni-input-form> ");
const _t3$2 = template("<div uni-textarea uni-view><div class=uni-textarea-wrapper> <div> </div><div class=uni-textarea-line> </div><div> </div>", 1);
const _t4$2 = template("<div>", 1);
const __syscom_0$1 = /* @__PURE__ */ defineBuiltInComponent({
name: "Textarea",
props: props$8,
emits: emits$1,
rootElement: {
name: "uni-textarea",
class: UniTextareaElement
},
setup(props2, context) {
const { rootRef, wrapperRef, fieldRef, state, scopedAttrsState, selectionRef, fixDisabledColor, valueCompute, lineRef, onResize: onResize2, onChange: onChange2, onKeyDownEnter, onKeyUpEnter } = useTextarea(props2, context);
const renderTextarea = () => (() => {
const _setTemplateRef = createTemplateRefSetter();
const _n0 = createIf(() => props2.disabled && fixDisabledColor, () => {
const _n2 = _t0$d();
setBlockKey(_n2, "disabled-textarea");
on$1(
_n2,
// fix: 禁止 readonly 状态获取焦点
"focus",
(event) => event.target.blur()
);
renderEffect(() => {
setValue$1(_n2, state.value);
setProp(_n2, "readonly", !!props2.disabled);
setProp(_n2, "maxlength", state.maxlength);
setClassName(_n2, 1 | (!!props2.selectionClass ? 2 : 0) | (fixMargin ? 4 : 0), [
" uni-textarea-textarea",
" uni-field-selection",
" uni-textarea-textarea-fix-margin"
]);
setStyle(_n2, {
overflowY: props2.autoHeight ? "hidden" : "auto",
/* eslint-disable no-restricted-syntax */
...props2.cursorColor && { caretColor: props2.cursorColor }
});
_setTemplateRef(_n2, fieldRef);
});
return _n2;
}, () => {
const _n4 = _t1$3();
setBlockKey(_n4, "textarea");
on$1(_n4, "keydown", onKeyDownEnter);
on$1(_n4, "keyup", onKeyUpEnter);
on$1(_n4, "change", onChange2);
renderEffect(() => {
setValue$1(_n4, state.value);
setProp(_n4, "disabled", !!props2.disabled);
setProp(_n4, "maxlength", state.maxlength);
setProp(_n4, "enterkeyhint", props2.confirmType);
setProp(_n4, "inputmode", props2.inputmode);
setClassName(_n4, 1 | (!!props2.selectionClass ? 2 : 0) | (fixMargin ? 4 : 0), [
" uni-textarea-textarea",
" uni-field-selection",
" uni-textarea-textarea-fix-margin"
]);
setStyle(_n4, {
overflowY: props2.autoHeight ? "hidden" : "auto",
/* eslint-disable no-restricted-syntax */
...props2.cursorColor && { caretColor: props2.cursorColor }
});
_setTemplateRef(_n4, fieldRef);
});
return _n4;
}, 261);
return _n0;
})();
const root = (() => {
const _setTemplateRef = createTemplateRefSetter();
const _n12 = _t3$2();
const _n11 = child(_n12);
const _n0 = child(_n11, true);
const _n1 = next(_n0);
const _n2 = next(_n1);
const _n5 = next(_n2);
const _n3 = child(_n5, true);
setNodes(_n0, () => props2.selectionClass && (() => {
const _setTemplateRef2 = createTemplateRefSetter();
const _n02 = _t4$2();
renderEffect(() => {
setDynamicProps(_n02, [scopedAttrsState.attrs, {
class: ["uni-field-selection-probe", props2.selectionClass],
"aria-hidden": "true",
style: fieldSelectionProbeStyle
}]);
_setTemplateRef2(_n02, selectionRef);
});
return _n02;
})());
applyVShow(_n1, () => !state.value.length);
const _x1 = txt(_n1);
setNodes(_x1, () => props2.placeholder);
setNodes(_n3, () => valueCompute.value.map((item) => (() => {
const _n52 = _t4$2();
setInsertionState(_n52);
createIf(() => item.trim(), () => {
const _n22 = createNodes(() => item);
return _n22;
}, () => {
const _n42 = createNodes(".");
return _n42;
}, 266);
return _n52;
})()));
renderEffect(() => {
setAttr(_n12, "auto-height", props2.autoHeight);
setDynamicProps(_n1, [scopedAttrsState.attrs, {
style: props2.placeholderStyle,
class: ["uni-textarea-placeholder", props2.placeholderClass]
}]);
_setTemplateRef(_n2, lineRef);
setClassName(_n5, 1 | (props2.autoHeight ? 2 : 0), [" uni-textarea-compute", " uni-textarea-compute-auto-height"]);
});
setInsertionState(_n5, 1);
createComponent(ResizeSensor, {
initial: true,
onResize: () => onResize2
});
setInsertionState(_n11, 4);
createIf(() => props2.confirmType === "search", () => {
const _n8 = _t2$2();
on$1(_n8, "submit", (event) => event.preventDefault());
const _x8 = txt(_n8);
setNodes(_x8, () => renderTextarea());
return _n8;
}, () => {
const _n10 = createNodes(() => renderTextarea());
return _n10;
}, 265);
renderEffect(() => {
_setTemplateRef(_n11, wrapperRef);
_setTemplateRef(_n12, rootRef);
});
return _n12;
})();
initTextareaElement(root, state);
return root;
}
});
function normalizeEvent(vm, id2) {
if (!id2) {
id2 = vm.id;
}
if (!id2) {
return;
}
return vm.$options.name.toLowerCase() + "." + id2;
}
function addSubscribe(name, callback, pageId) {
if (!name) {
return;
}
registerViewMethod(
pageId || getCurrentPageId(),
name,
({ type, data }, resolve) => {
callback(type, data, resolve);
}
);
}
function removeSubscribe(name, pageId) {
if (!name) {
return;
}
unregisterViewMethod(pageId || getCurrentPageId(), name);
}
function useSubscribe(callback, name, multiple, pageId) {
const instance2 = getCurrentInstance();
const vm = instance2.proxy;
pageId = pageId == null ? useCurrentPageId() : pageId;
onMounted(() => {
addSubscribe(name || normalizeEvent(vm), callback, pageId);
if (multiple || !name) {
watch(
() => vm.id,
(value, oldValue) => {
addSubscribe(normalizeEvent(vm, value), callback, pageId);
removeSubscribe(oldValue && normalizeEvent(vm, oldValue));
}
);
}
});
onBeforeUnmount(() => {
removeSubscribe(name || normalizeEvent(vm), pageId);
});
}
function useOn(name, callback) {
onMounted(() => UniViewJSBridge.on(name, callback));
onBeforeUnmount(() => UniViewJSBridge.off(name));
}
let index$8 = 0;
function useContextInfo(_id) {
const page = useCurrentPageId();
const instance2 = getCurrentInstance();
const vm = instance2.proxy;
const type = vm.$options.name.toLowerCase();
const id2 = vm.id || `context${index$8++}`;
onMounted(() => {
const el = vm.$el;
el.__uniContextInfo = {
id: id2,
type,
page
};
});
return `${type}.${id2}`;
}
function getContextInfo(el) {
return el.__uniContextInfo;
}
function entries(obj) {
return Object.keys(obj).map((key) => [key, obj[key]]);
}
const DEFAULT_EXCLUDE_KEYS = ["class", "style"];
const LISTENER_PREFIX = /^on[A-Z]+/;
const useAttrs = (params = {}) => {
const { excludeListeners = false, excludeKeys = [] } = params;
const instance2 = getCurrentInstance();
const attrs2 = shallowRef({});
const listeners2 = shallowRef({});
const excludeAttrs = shallowRef({});
const allExcludeKeys = excludeKeys.concat(DEFAULT_EXCLUDE_KEYS);
instance2.attrs = reactive(instance2.attrs);
watchEffect(() => {
const res = entries(instance2.attrs).reduce(
(acc, [key, val]) => {
if (allExcludeKeys.includes(key)) {
acc.exclude[key] = val;
} else if (LISTENER_PREFIX.test(key)) {
if (!excludeListeners) {
acc.attrs[key] = val;
}
acc.listeners[key] = val;
} else {
acc.attrs[key] = val;
}
return acc;
},
{
exclude: {},
attrs: {},
listeners: {}
}
);
attrs2.value = res.attrs;
listeners2.value = res.listeners;
excludeAttrs.value = res.exclude;
});
return { $attrs: attrs2, $listeners: listeners2, $excludeAttrs: excludeAttrs };
};
const addListenerToElement = function(element, type, callback, capture) {
element.addEventListener(
type,
($event) => {
if (isFunction(callback)) {
if (callback($event) === false) {
if (typeof $event.cancelable !== "undefined" ? $event.cancelable : true) {
$event.preventDefault();
}
$event.stopPropagation();
}
}
},
{
passive: false
}
);
};
let __mouseMoveEventListener;
let __mouseUpEventListener;
function useTouchtrack(element, method, useCancel) {
onBeforeUnmount(() => {
document.removeEventListener("mousemove", __mouseMoveEventListener);
document.removeEventListener("mouseup", __mouseUpEventListener);
});
let x0 = 0;
let y0 = 0;
let x1 = 0;
let y1 = 0;
const fn = function($event, state, x, y) {
if (method({
// @ts-expect-error
cancelable: $event.cancelable,
target: $event.target,
currentTarget: $event.currentTarget,
preventDefault: $event.preventDefault.bind($event),
stopPropagation: $event.stopPropagation.bind($event),
touches: $event.touches,
changedTouches: $event.changedTouches,
detail: {
state,
x,
y,
dx: x - x0,
dy: y - y0,
ddx: x - x1,
ddy: y - y1,
timeStamp: $event.timeStamp
}
}) === false) {
return false;
}
};
let $eventOld = null;
let hasTouchStart;
let hasMouseDown;
addListenerToElement(element, "touchstart", function($event) {
hasTouchStart = true;
if ($event.touches.length === 1 && !$eventOld) {
$eventOld = $event;
x0 = x1 = $event.touches[0].pageX;
y0 = y1 = $event.touches[0].pageY;
return fn($event, "start", x0, y0);
}
});
addListenerToElement(element, "mousedown", function($event) {
hasMouseDown = true;
if (!hasTouchStart && !$eventOld) {
$eventOld = $event;
x0 = x1 = $event.pageX;
y0 = y1 = $event.pageY;
return fn($event, "start", x0, y0);
}
});
addListenerToElement(element, "touchmove", function($event) {
if ($event.touches.length === 1 && $eventOld) {
const res = fn(
$event,
"move",
$event.touches[0].pageX,
$event.touches[0].pageY
);
x1 = $event.touches[0].pageX;
y1 = $event.touches[0].pageY;
return res;
}
});
const mouseMoveEventListener = __mouseMoveEventListener = function($event) {
if (!hasTouchStart && hasMouseDown && $eventOld) {
const res = fn($event, "move", $event.pageX, $event.pageY);
x1 = $event.pageX;
y1 = $event.pageY;
return res;
}
};
document.addEventListener("mousemove", mouseMoveEventListener);
addListenerToElement(element, "touchend", function($event) {
if ($event.touches.length === 0 && $eventOld) {
hasTouchStart = false;
$eventOld = null;
return fn(
$event,
"end",
$event.changedTouches[0].pageX,
$event.changedTouches[0].pageY
);
}
});
const mouseUpEventListener = __mouseUpEventListener = function($event) {
hasMouseDown = false;
if (!hasTouchStart && $eventOld) {
$eventOld = null;
return fn($event, "end", $event.pageX, $event.pageY);
}
};
document.addEventListener("mouseup", mouseUpEventListener);
addListenerToElement(element, "touchcancel", function($event) {
if ($eventOld) {
hasTouchStart = false;
const $eventTemp = $eventOld;
$eventOld = null;
return fn(
$event,
"end",
$eventTemp.touches[0].pageX,
$eventTemp.touches[0].pageY
);
}
});
}
const TEMP_PATH = "";
const pageMetaKey = PolySymbol(process.env.NODE_ENV !== "production" ? "UniPageMeta" : "upm");
function usePageMeta() {
return inject(pageMetaKey);
}
function providePageMeta(id2) {
const pageMeta = initPageMeta(id2);
provide(pageMetaKey, pageMeta);
return pageMeta;
}
function usePageRoute() {
if (__UNI_FEATURE_PAGES__) {
return useRoute();
}
const url = location.href;
const searchPos = url.indexOf("?");
const hashPos = url.indexOf("#", searchPos > -1 ? searchPos : 0);
let query = {};
if (searchPos > -1) {
query = parseQuery(
url.slice(searchPos + 1, hashPos > -1 ? hashPos : url.length)
);
}
const { meta } = __uniRoutes[0];
const path = addLeadingSlash(meta.route);
return {
meta,
query,
path,
matched: [{ path }]
};
}
function initPageMeta(id2) {
if (__UNI_FEATURE_PAGES__) {
return reactive(
normalizePageMeta(
JSON.parse(
JSON.stringify(
initRouteMeta(
useRoute().meta,
id2
)
)
)
)
);
}
return reactive(
normalizePageMeta(
JSON.parse(JSON.stringify(initRouteMeta(__uniRoutes[0].meta, id2)))
)
);
}
function normalizePageMeta(pageMeta) {
if (__UNI_FEATURE_PULL_DOWN_REFRESH__) {
const { enablePullDownRefresh, navigationBar } = pageMeta;
{
const pullToRefresh = normalizePullToRefreshRpx(
extend(
{
support: true,
color: "#2BD009",
style: "circle",
height: 70,
range: 150,
offset: 0
},
pageMeta.pullToRefresh
)
);
const { type, style } = navigationBar;
if (style !== "custom" && type !== "transparent") {
pullToRefresh.offset += NAVBAR_HEIGHT + safeAreaInsets$1.top;
}
pageMeta.pullToRefresh = pullToRefresh;
}
}
if (__UNI_FEATURE_NAVIGATIONBAR__ || __UNI_FEATURE_I18N_LOCALE__) {
const { navigationBar } = pageMeta;
const { titleSize, titleColor, backgroundColor } = navigationBar;
navigationBar.titleText = navigationBar.titleText || "";
navigationBar.type = navigationBar.type || "default";
navigationBar.titleSize = titleSize || "16px";
navigationBar.titleColor = titleColor || "#000000";
navigationBar.backgroundColor = backgroundColor || "#F8F8F8";
__UNI_FEATURE_I18N_LOCALE__ && initNavigationBarI18n(navigationBar);
}
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 checkMinWidth(minWidth) {
const screen2 = window.screen;
const documentElement = document.documentElement;
const sizes = [
window.outerWidth,
window.outerHeight,
screen2.width,
screen2.height,
documentElement.clientWidth,
documentElement.clientHeight
];
return Math.max.apply(null, sizes) > minWidth;
}
function getStateId() {
return history.state && history.state.__id__ || 1;
}
let router;
function setRouterInstance(value) {
router = value;
}
function getRouterInstance() {
return router;
}
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var lookup = /* @__PURE__ */ function() {
const lookup2 = new Uint8Array(256);
for (var i = 0; i < chars.length; i++) {
lookup2[chars.charCodeAt(i)] = i;
}
return lookup2;
}();
function encode$1(arraybuffer) {
var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = "";
for (i = 0; i < len; i += 3) {
base64 += chars[bytes[i] >> 2];
base64 += chars[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];
base64 += chars[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];
base64 += chars[bytes[i + 2] & 63];
}
if (len % 3 === 2) {
base64 = base64.substring(0, base64.length - 1) + "=";
} else if (len % 3 === 1) {
base64 = base64.substring(0, base64.length - 2) + "==";
}
return base64;
}
function decode(base64) {
var bufferLength = base64.length * 0.75, len = base64.length, i, p2 = 0, encoded1, encoded2, encoded3, encoded4;
if (base64[base64.length - 1] === "=") {
bufferLength--;
if (base64[base64.length - 2] === "=") {
bufferLength--;
}
}
var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);
for (i = 0; i < len; i += 4) {
encoded1 = lookup[base64.charCodeAt(i)];
encoded2 = lookup[base64.charCodeAt(i + 1)];
encoded3 = lookup[base64.charCodeAt(i + 2)];
encoded4 = lookup[base64.charCodeAt(i + 3)];
bytes[p2++] = encoded1 << 2 | encoded2 >> 4;
bytes[p2++] = (encoded2 & 15) << 4 | encoded3 >> 2;
bytes[p2++] = (encoded3 & 3) << 6 | encoded4 & 63;
}
return arraybuffer;
}
const CHOOSE_SIZE_TYPES = ["original", "compressed"];
const CHOOSE_SOURCE_TYPES = ["album", "camera"];
const HTTP_METHODS = [
"GET",
"OPTIONS",
"HEAD",
"POST",
"PUT",
"DELETE",
"TRACE",
"CONNECT",
"PATCH"
];
function elemInArray(str, arr) {
if (!str || arr.indexOf(str) === -1) {
return arr[0];
}
return str;
}
function elemsInArray(strArr, optionalVal) {
if (!isArray(strArr) || strArr.length === 0 || strArr.find((val) => optionalVal.indexOf(val) === -1)) {
return optionalVal;
}
return strArr;
}
function validateProtocolFail(name, msg) {
console.warn(`${name}: ${msg}`);
}
function validateProtocol(name, data, protocol, onFail) {
if (!onFail) {
onFail = validateProtocolFail;
}
for (const key in protocol) {
const errMsg = validateProp(
key,
data[key],
protocol[key],
!hasOwn(data, key)
);
if (isString(errMsg)) {
onFail(name, errMsg);
}
}
}
function validateProtocols(name, args, protocol, onFail) {
if (!protocol) {
return;
}
if (!isArray(protocol)) {
return validateProtocol(
name,
args[0] || /* @__PURE__ */ Object.create(null),
protocol,
onFail
);
}
const len = protocol.length;
const argsLen = args.length;
for (let i = 0; i < len; i++) {
const opts = protocol[i];
const data = /* @__PURE__ */ Object.create(null);
if (argsLen > i) {
data[opts.name] = args[i];
}
validateProtocol(name, data, { [opts.name]: opts }, onFail);
}
}
function validateProp(name, value, prop, isAbsent) {
if (!isPlainObject(prop)) {
prop = { type: prop };
}
const { type, required, validator: validator2 } = prop;
if (required && isAbsent) {
return 'Missing required args: "' + name + '"';
}
if (value == null && !required) {
return;
}
if (type != null) {
let isValid = false;
const types = isArray(type) ? type : [type];
const expectedTypes = [];
for (let i = 0; i < types.length && !isValid; i++) {
const { valid, expectedType } = assertType(value, types[i]);
expectedTypes.push(expectedType || "");
isValid = valid;
}
if (!isValid) {
return getInvalidTypeMessage(name, value, expectedTypes);
}
}
if (validator2) {
return validator2(value);
}
}
const isSimpleType = /* @__PURE__ */ makeMap$1(
"String,Number,Boolean,Function,Symbol"
);
function assertType(value, type) {
let valid;
const expectedType = getType(type);
if (isSimpleType(expectedType)) {
const t12 = typeof value;
valid = t12 === expectedType.toLowerCase();
if (!valid && t12 === "object") {
valid = value instanceof type;
}
} else if (expectedType === "Object") {
valid = isObject(value);
} else if (expectedType === "Array") {
valid = isArray(value);
} else {
{
valid = value instanceof type;
}
}
return {
valid,
expectedType
};
}
function getInvalidTypeMessage(name, value, expectedTypes) {
let message = `Invalid args: type check failed for args "${name}". Expected ${expectedTypes.map(capitalize).join(", ")}`;
const expectedType = expectedTypes[0];
const receivedType = toRawType(value);
const expectedValue = styleValue(value, expectedType);
const receivedValue = styleValue(value, receivedType);
if (expectedTypes.length === 1 && isExplicable(expectedType) && !isBoolean(expectedType, receivedType)) {
message += ` with value ${expectedValue}`;
}
message += `, got ${receivedType} `;
if (isExplicable(receivedType)) {
message += `with value ${receivedValue}.`;
}
return message;
}
function getType(ctor) {
const match = ctor && ctor.toString().match(/^\s*function (\w+)/);
return match ? match[1] : "";
}
function styleValue(value, type) {
if (type === "String") {
return `"${value}"`;
} else if (type === "Number") {
return `${Number(value)}`;
} else {
return `${value}`;
}
}
function isExplicable(type) {
const explicitTypes = ["string", "number", "boolean"];
return explicitTypes.some((elem) => type.toLowerCase() === elem);
}
function isBoolean(...args) {
return args.some((elem) => elem.toLowerCase() === "boolean");
}
function tryCatch(fn) {
return function() {
try {
return fn.apply(fn, arguments);
} catch (e2) {
console.error(e2);
}
};
}
let invokeCallbackId = 1;
const invokeCallbacks = {};
function addInvokeCallback(id2, name, callback, keepAlive = false) {
invokeCallbacks[id2] = {
name,
keepAlive,
callback
};
return id2;
}
function invokeCallback(id2, res, extras) {
if (typeof id2 === "number") {
const opts = invokeCallbacks[id2];
if (opts) {
if (!opts.keepAlive) {
delete invokeCallbacks[id2];
}
return opts.callback(res, extras);
}
}
return res;
}
function findInvokeCallbackByName(name) {
for (const key in invokeCallbacks) {
if (invokeCallbacks[key].name === name) {
return true;
}
}
return false;
}
function removeKeepAliveApiCallback(name, callback) {
for (const key in invokeCallbacks) {
const item = invokeCallbacks[key];
if (item.callback === callback && item.name === name) {
delete invokeCallbacks[key];
}
}
}
function removeAllKeepAliveApiCallbacks(name) {
for (const key in invokeCallbacks) {
if (invokeCallbacks[key].name === name) {
delete invokeCallbacks[key];
}
}
}
function offKeepAliveApiCallback(name, eventTransport2) {
const eventName = eventTransport2 ? name : "api." + name;
const transport = eventTransport2 || UniServiceJSBridge;
transport.off(eventName);
}
function onKeepAliveApiCallback(name, eventTransport2) {
const eventName = eventTransport2 ? name : "api." + name;
const transport = eventTransport2 || UniServiceJSBridge;
transport.on(eventName, (res) => {
for (const key in invokeCallbacks) {
const opts = invokeCallbacks[key];
if (opts.name === name) {
opts.callback(res);
}
}
});
}
function createKeepAliveApiCallback(name, callback) {
return addInvokeCallback(invokeCallbackId++, name, callback, true);
}
const API_SUCCESS = "success";
const API_FAIL = "fail";
const API_COMPLETE = "complete";
function getApiCallbacks(args) {
const apiCallbacks = {};
for (const name in args) {
const fn = args[name];
if (isFunction(fn)) {
apiCallbacks[name] = tryCatch(fn);
delete args[name];
}
}
return apiCallbacks;
}
function normalizeErrMsg(errMsg, name) {
if (!errMsg || errMsg.indexOf(":fail") === -1) {
return name + ":ok";
}
return name + errMsg.substring(errMsg.indexOf(":fail"));
}
function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } = {}) {
if (!isPlainObject(args)) {
args = {};
}
const { success, fail, complete } = getApiCallbacks(args);
const hasSuccess = isFunction(success);
const hasFail = isFunction(fail);
const hasComplete = isFunction(complete);
const callbackId = invokeCallbackId++;
addInvokeCallback(callbackId, name, (res) => {
res = res || {};
res.errMsg = normalizeErrMsg(res.errMsg, name);
isFunction(beforeAll) && beforeAll(res);
if (res.errMsg === name + ":ok") {
isFunction(beforeSuccess) && beforeSuccess(res, args);
hasSuccess && success(res);
} else {
hasFail && fail(res);
}
hasComplete && complete(res);
});
return callbackId;
}
const HOOK_SUCCESS = "success";
const HOOK_FAIL = "fail";
const HOOK_COMPLETE = "complete";
const globalInterceptors = {};
const scopedInterceptors = {};
function wrapperHook(hook, params) {
return function(data) {
return hook(data, params) || data;
};
}
function queue(hooks, data, params) {
let promise = false;
for (let i = 0; i < hooks.length; i++) {
const hook = hooks[i];
if (promise) {
promise = Promise.resolve(wrapperHook(hook, params));
} else {
const res = hook(data, params);
if (isPromise(res)) {
promise = Promise.resolve(res);
}
if (res === false) {
return {
then() {
},
catch() {
}
};
}
}
}
return promise || {
then(callback) {
return callback(data);
},
catch() {
}
};
}
function wrapperOptions(interceptors2, options = {}) {
[HOOK_SUCCESS, HOOK_FAIL, HOOK_COMPLETE].forEach((name) => {
const hooks = interceptors2[name];
if (!isArray(hooks)) {
return;
}
const oldCallback = options[name];
options[name] = function callbackInterceptor(res) {
queue(hooks, res, options).then((res2) => {
return isFunction(oldCallback) && oldCallback(res2) || res2;
});
};
});
return options;
}
function wrapperReturnValue(method, returnValue) {
const returnValueHooks = [];
if (isArray(globalInterceptors.returnValue)) {
returnValueHooks.push(...globalInterceptors.returnValue);
}
const interceptor = scopedInterceptors[method];
if (interceptor && isArray(interceptor.returnValue)) {
returnValueHooks.push(...interceptor.returnValue);
}
returnValueHooks.forEach((hook) => {
returnValue = hook(returnValue) || returnValue;
});
return returnValue;
}
function getApiInterceptorHooks(method) {
const interceptor = /* @__PURE__ */ Object.create(null);
Object.keys(globalInterceptors).forEach((hook) => {
if (hook !== "returnValue") {
interceptor[hook] = globalInterceptors[hook].slice();
}
});
const scopedInterceptor = scopedInterceptors[method];
if (scopedInterceptor) {
Object.keys(scopedInterceptor).forEach((hook) => {
if (hook !== "returnValue") {
interceptor[hook] = (interceptor[hook] || []).concat(
scopedInterceptor[hook]
);
}
});
}
return interceptor;
}
function invokeApi(method, api2, options, params) {
const interceptor = getApiInterceptorHooks(method);
if (interceptor && Object.keys(interceptor).length) {
if (isArray(interceptor.invoke)) {
const res = queue(interceptor.invoke, options);
return res.then((options2) => {
return api2(
wrapperOptions(getApiInterceptorHooks(method), options2),
...params
);
});
} else {
return api2(wrapperOptions(interceptor, options), ...params);
}
}
return api2(options, ...params);
}
function hasCallback(args) {
if (isPlainObject(args) && [API_SUCCESS, API_FAIL, API_COMPLETE].find(
(cb) => isFunction(args[cb])
)) {
return true;
}
return false;
}
function handlePromise(promise) {
return promise;
}
function promisify(name, fn) {
return (args = {}, ...rest) => {
if (hasCallback(args)) {
return wrapperReturnValue(
name,
invokeApi(name, fn, extend({}, args), rest)
);
}
return wrapperReturnValue(
name,
handlePromise(
new Promise((resolve, reject) => {
invokeApi(
name,
fn,
extend({}, args, { success: resolve, fail: reject }),
rest
);
})
)
);
};
}
function normalizeFormatApiParams(args) {
const params = args[0];
if (isPlainObject(params)) {
return params;
}
const normalizedParams = {};
args[0] = normalizedParams;
return normalizedParams;
}
function formatApiArgs(args, options) {
const rawParams = args[0];
if (!options || !options.formatArgs || !isPlainObject(options.formatArgs) && isPlainObject(rawParams)) {
return;
}
const params = normalizeFormatApiParams(args);
const formatArgs = options.formatArgs;
const keys = Object.keys(formatArgs);
for (let i = 0; i < keys.length; i++) {
const name = keys[i];
const formatterOrDefaultValue = formatArgs[name];
if (isFunction(formatterOrDefaultValue)) {
const errMsg = formatterOrDefaultValue(params[name], params);
if (isString(errMsg)) {
return errMsg;
}
} else {
if (!hasOwn(params, name)) {
params[name] = formatterOrDefaultValue;
}
}
}
}
function invokeSuccess(id2, name, res) {
const result = {
errMsg: name + ":ok"
};
{
result.errSubject = name;
}
return invokeCallback(id2, extend(res || {}, result));
}
function invokeFail(id2, name, errMsg, errRes = {}) {
const errMsgPrefix = name + ":fail";
let apiErrMsg = "";
if (!errMsg) {
apiErrMsg = errMsgPrefix;
} else if (errMsg.indexOf(errMsgPrefix) === 0) {
apiErrMsg = errMsg;
} else {
apiErrMsg = errMsgPrefix + " " + errMsg;
}
let res = extend({ errMsg: apiErrMsg }, errRes);
{
if (typeof UniError !== "undefined") {
const errOptions = extend({}, errRes);
if (typeof errOptions.errSubject === "undefined") {
errOptions.errSubject = name;
}
res = new UniError(apiErrMsg, errOptions);
}
}
return invokeCallback(id2, res);
}
function beforeInvokeApi(name, args, protocol, options) {
if (process.env.NODE_ENV !== "production") {
validateProtocols(name, args, protocol);
}
if (options && options.beforeInvoke) {
const errMsg2 = options.beforeInvoke(args);
if (isString(errMsg2)) {
return errMsg2;
}
}
const errMsg = formatApiArgs(args, options);
if (errMsg) {
return errMsg;
}
}
function checkCallback(callback) {
if (!isFunction(callback)) {
throw new Error(
'Invalid args: type check failed for args "callback". Expected Function'
);
}
}
function wrapperOnApi(name, fn, options) {
return (callback) => {
checkCallback(callback);
const errMsg = beforeInvokeApi(name, [callback], void 0, options);
if (errMsg) {
throw new Error(errMsg);
}
const isFirstInvokeOnApi = !findInvokeCallbackByName(name);
createKeepAliveApiCallback(name, callback);
if (isFirstInvokeOnApi) {
onKeepAliveApiCallback(name, options == null ? void 0 : options.eventTransport);
fn();
}
};
}
function wrapperOffApi(name, fn, options) {
return (callback) => {
const clearAll = (options == null ? void 0 : options.allowClearAll) === true && callback == null;
if (!clearAll) {
checkCallback(callback);
}
const errMsg = beforeInvokeApi(
name,
clearAll ? [] : [callback],
void 0,
options
);
if (errMsg) {
throw new Error(errMsg);
}
const onApiName = name.replace("off", "on");
if (clearAll) {
removeAllKeepAliveApiCallbacks(onApiName);
} else {
removeKeepAliveApiCallback(onApiName, callback);
}
const hasInvokeOnApi = findInvokeCallbackByName(onApiName);
if (!hasInvokeOnApi) {
offKeepAliveApiCallback(onApiName, options == null ? void 0 : options.eventTransport);
fn();
}
};
}
function parseErrMsg(errMsg) {
if (!errMsg || isString(errMsg)) {
return errMsg;
}
if (errMsg.stack) {
return errMsg.message;
}
return errMsg;
}
function wrapperTaskApi(name, fn, protocol, options) {
return (args) => {
const id2 = createAsyncApiCallback(name, args, options);
const errMsg = beforeInvokeApi(name, [args], protocol, options);
if (errMsg) {
return invokeFail(id2, name, errMsg);
}
return fn(args, {
resolve: (res) => invokeSuccess(id2, name, res),
reject: (errMsg2, errRes) => invokeFail(id2, name, parseErrMsg(errMsg2), errRes)
});
};
}
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(
name,
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(
name,
wrapperAsyncApi(name, fn, process.env.NODE_ENV !== "production" ? protocol : void 0, options)
);
}
function createUnsupportedMsg(name) {
return `method 'uni.${name}' not supported`;
}
function createUnsupportedSyncApi(name) {
return () => {
console.error(createUnsupportedMsg(name));
};
}
const createUnsupportedOnApi = createUnsupportedSyncApi;
function createUnsupportedAsyncApi(name) {
return (_args, { reject }) => {
return reject(createUnsupportedMsg(name));
};
}
const API_BASE64_TO_ARRAY_BUFFER = "base64ToArrayBuffer";
const Base64ToArrayBufferProtocol = [
{
name: "base64",
type: String,
required: true
}
];
const API_ARRAY_BUFFER_TO_BASE64 = "arrayBufferToBase64";
const ArrayBufferToBase64Protocol = [
{
name: "arrayBuffer",
type: [ArrayBuffer, Uint8Array],
required: true
}
];
const base64ToArrayBuffer = /* @__PURE__ */ defineSyncApi(
API_BASE64_TO_ARRAY_BUFFER,
(base64) => {
return decode(base64);
},
Base64ToArrayBufferProtocol
);
const arrayBufferToBase64 = /* @__PURE__ */ defineSyncApi(
API_ARRAY_BUFFER_TO_BASE64,
(arrayBuffer) => {
return encode$1(arrayBuffer);
},
ArrayBufferToBase64Protocol
);
const API_UPX2PX = "upx2px";
const Upx2pxProtocol = [
{
name: "upx",
type: [Number, String],
required: true
}
];
const EPS = 1e-4;
const BASE_DEVICE_WIDTH = 750;
let isIOS$1 = false;
let deviceWidth = 0;
let deviceDPR = 0;
let maxWidth = 960;
let baseWidth = 375;
let includeWidth = 750;
function checkDeviceWidth() {
let windowWidth, pixelRatio, platform;
{
const { windowWidth: w, pixelRatio: p2, platform: pf } = getBaseSystemInfo();
windowWidth = w;
pixelRatio = p2;
platform = pf;
}
deviceWidth = windowWidth;
deviceDPR = pixelRatio;
isIOS$1 = platform === "ios";
}
function checkValue(value, defaultValue) {
const newValue = Number(value);
return isNaN(newValue) ? defaultValue : newValue;
}
function checkMaxWidth() {
const config = __uniConfig.globalStyle || {};
maxWidth = checkValue(config.rpxCalcMaxDeviceWidth, 960);
baseWidth = checkValue(config.rpxCalcBaseDeviceWidth, 375);
includeWidth = checkValue(config.rpxCalcBaseDeviceWidth, 750);
}
const upx2px = /* @__PURE__ */ defineSyncApi(
API_UPX2PX,
(number, newDeviceWidth) => {
if (deviceWidth === 0) {
checkDeviceWidth();
{
checkMaxWidth();
}
}
number = Number(number);
if (number === 0) {
return 0;
}
let width = newDeviceWidth || deviceWidth;
{
width = number === includeWidth || width <= maxWidth ? width : baseWidth;
}
let result = number / BASE_DEVICE_WIDTH * width;
if (result < 0) {
result = -result;
}
result = Math.floor(result + EPS);
if (result === 0) {
if (deviceDPR === 1 || !isIOS$1) {
result = 1;
} else {
result = 0.5;
}
}
return number < 0 ? -result : result;
},
Upx2pxProtocol
);
const API_ADD_INTERCEPTOR = "addInterceptor";
const API_REMOVE_INTERCEPTOR = "removeInterceptor";
const AddInterceptorProtocol = [
{
name: "method",
type: [String, Object],
required: true
}
];
const RemoveInterceptorProtocol = AddInterceptorProtocol;
function mergeInterceptorHook(interceptors2, interceptor) {
Object.keys(interceptor).forEach((hook) => {
if (isFunction(interceptor[hook])) {
interceptors2[hook] = mergeHook(
interceptors2[hook],
interceptor[hook]
);
}
});
}
function removeInterceptorHook(interceptors2, interceptor) {
if (!interceptors2 || !interceptor) {
return;
}
Object.keys(interceptor).forEach((name) => {
const hooks = interceptors2[name];
const hook = interceptor[name];
if (isArray(hooks) && isFunction(hook)) {
remove(hooks, hook);
}
});
}
function mergeHook(parentVal, childVal) {
const res = childVal ? parentVal ? parentVal.concat(childVal) : isArray(childVal) ? childVal : [childVal] : parentVal;
return res ? dedupeHooks(res) : res;
}
function dedupeHooks(hooks) {
const res = [];
for (let i = 0; i < hooks.length; i++) {
if (res.indexOf(hooks[i]) === -1) {
res.push(hooks[i]);
}
}
return res;
}
const addInterceptor = /* @__PURE__ */ defineSyncApi(
API_ADD_INTERCEPTOR,
(method, interceptor) => {
if (isString(method) && isPlainObject(interceptor)) {
mergeInterceptorHook(
scopedInterceptors[method] || (scopedInterceptors[method] = {}),
interceptor
);
} else if (isPlainObject(method)) {
mergeInterceptorHook(globalInterceptors, method);
}
},
AddInterceptorProtocol
);
const removeInterceptor = /* @__PURE__ */ defineSyncApi(
API_REMOVE_INTERCEPTOR,
(method, interceptor) => {
if (isString(method)) {
if (isPlainObject(interceptor)) {
removeInterceptorHook(scopedInterceptors[method], interceptor);
} else {
delete scopedInterceptors[method];
}
} else if (isPlainObject(method)) {
removeInterceptorHook(globalInterceptors, method);
}
},
RemoveInterceptorProtocol
);
const interceptors = {};
const API_ON = "$on";
const OnProtocol = [
{
name: "event",
type: String,
required: true
},
{
name: "callback",
type: Function,
required: true
}
];
const API_ONCE = "$once";
const OnceProtocol = OnProtocol;
const API_OFF = "$off";
const OffProtocol = [
{
name: "event",
type: [String, Array]
},
{
name: "callback",
type: [Function, Number]
}
];
const API_EMIT = "$emit";
const EmitProtocol = [
{
name: "event",
type: String,
required: true
}
];
class EventBus {
constructor() {
this.$emitter = new Emitter();
}
on(name, callback) {
return this.$emitter.on(name, callback);
}
once(name, callback) {
return this.$emitter.once(name, callback);
}
off(name, callback) {
if (!name) {
this.$emitter.e = {};
return;
}
this.$emitter.off(name, callback);
}
emit(name, ...args) {
this.$emitter.emit(name, ...args);
}
}
const eventBus = new EventBus();
const $on = /* @__PURE__ */ defineSyncApi(
API_ON,
(name, callback) => {
const id2 = eventBus.on(name, callback);
{
return id2;
}
},
OnProtocol
);
const $once = /* @__PURE__ */ defineSyncApi(
API_ONCE,
(name, callback) => {
const id2 = eventBus.once(name, callback);
{
return id2;
}
},
OnceProtocol
);
const $off = /* @__PURE__ */ defineSyncApi(
API_OFF,
(name, callback) => {
if (!isArray(name))
name = name ? [name] : [];
name.forEach((n) => {
eventBus.off(n, callback);
});
},
OffProtocol
);
const $emit = /* @__PURE__ */ defineSyncApi(
API_EMIT,
(name, ...args) => {
eventBus.emit(name, ...args);
},
EmitProtocol
);
function __f__(type, filename, ...args) {
if (filename) {
args.push(filename);
}
console[type].apply(console, args);
}
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_CANVAS_CONTEXT = "createCanvasContext";
const CreateCanvasContextProtocol = [
{
name: "canvasId",
type: String,
required: true
},
{
name: "componentInstance",
type: Object
}
];
const API_CREATE_INNER_AUDIO_CONTEXT = "createInnerAudioContext";
validator.concat({
name: "componentInstance",
type: Object
});
const RATES = [0.5, 0.8, 1, 1.25, 1.5, 2];
class VideoContext {
constructor(id2, pageId) {
this.id = id2;
this.pageId = pageId;
}
play() {
operateVideoPlayer(this.id, this.pageId, "play");
}
pause() {
operateVideoPlayer(this.id, this.pageId, "pause");
}
stop() {
operateVideoPlayer(this.id, this.pageId, "stop");
}
seek(position) {
operateVideoPlayer(this.id, this.pageId, "seek", {
position
});
}
sendDanmu(args) {
operateVideoPlayer(this.id, this.pageId, "sendDanmu", args);
}
playbackRate(rate) {
if (!~RATES.indexOf(rate)) {
rate = 1;
}
operateVideoPlayer(this.id, this.pageId, "playbackRate", {
rate
});
}
requestFullScreen(args = {}) {
operateVideoPlayer(this.id, this.pageId, "requestFullScreen", args);
}
exitFullScreen() {
operateVideoPlayer(this.id, this.pageId, "exitFullScreen");
}
showStatusBar() {
operateVideoPlayer(this.id, this.pageId, "showStatusBar");
}
hideStatusBar() {
operateVideoPlayer(this.id, this.pageId, "hideStatusBar");
}
}
const createVideoContext = /* @__PURE__ */ defineSyncApi(
API_CREATE_VIDEO_CONTEXT,
(id2, context) => {
if (context) {
return new VideoContext(id2, getPageIdByVm(context));
}
return new VideoContext(id2, getPageIdByVm(getCurrentPageVm()));
}
);
const operateMapCallback = (options, res) => {
const errMsg = res.errMsg || "";
if (new RegExp("\\:\\s*fail").test(errMsg)) {
options.fail && options.fail(res);
} else {
options.success && options.success(res);
}
options.complete && options.complete(res);
};
const operateMapWrap = (id2, pageId, type, options) => {
operateMap(id2, pageId, type, options, (res) => {
options && operateMapCallback(options, res);
});
};
class MapContext {
constructor(id2, pageId) {
this.id = id2;
this.pageId = pageId;
}
getCenterLocation(options) {
operateMapWrap(this.id, this.pageId, "getCenterLocation", options);
}
moveToLocation(options) {
operateMapWrap(this.id, this.pageId, "moveToLocation", options);
}
getScale(options) {
operateMapWrap(this.id, this.pageId, "getScale", options);
}
getRegion(options) {
operateMapWrap(this.id, this.pageId, "getRegion", options);
}
includePoints(options) {
operateMapWrap(this.id, this.pageId, "includePoints", options);
}
translateMarker(options) {
operateMapWrap(this.id, this.pageId, "translateMarker", options);
}
$getAppMap() {
}
addCustomLayer(options) {
operateMapWrap(this.id, this.pageId, "addCustomLayer", options);
}
removeCustomLayer(options) {
operateMapWrap(this.id, this.pageId, "removeCustomLayer", options);
}
addGroundOverlay(options) {
operateMapWrap(this.id, this.pageId, "addGroundOverlay", options);
}
removeGroundOverlay(options) {
operateMapWrap(this.id, this.pageId, "removeGroundOverlay", options);
}
updateGroundOverlay(options) {
operateMapWrap(this.id, this.pageId, "updateGroundOverlay", options);
}
initMarkerCluster(options) {
operateMapWrap(this.id, this.pageId, "initMarkerCluster", options);
}
addMarkers(options) {
operateMapWrap(this.id, this.pageId, "addMarkers", options);
}
removeMarkers(options) {
operateMapWrap(this.id, this.pageId, "removeMarkers", options);
}
moveAlong(options) {
operateMapWrap(this.id, this.pageId, "moveAlong", options);
}
setLocMarkerIcon(options) {
operateMapWrap(this.id, this.pageId, "setLocMarkerIcon", options);
}
openMapApp(options) {
operateMapWrap(this.id, this.pageId, "openMapApp", options);
}
on(name, callback) {
operateMapWrap(this.id, this.pageId, "on", { name, callback });
}
}
const createMapContext = /* @__PURE__ */ defineSyncApi(
API_CREATE_MAP_CONTEXT,
(id2, context) => {
if (context) {
return new MapContext(id2, getPageIdByVm(context));
}
return new MapContext(id2, getPageIdByVm(getCurrentPageVm()));
},
CreateMapContextProtocol
);
function getInt(name, defaultValue) {
return function(value, params) {
if (value) {
params[name] = Math.round(value);
} else if (typeof defaultValue !== "undefined") {
params[name] = defaultValue;
}
};
}
const formatWidth = getInt("width");
const formatHeight = getInt("height");
const API_CANVAS_GET_IMAGE_DATA = "canvasGetImageData";
const CanvasGetImageDataOptions = {
formatArgs: {
x: getInt("x"),
y: getInt("y"),
width: formatWidth,
height: formatHeight
}
};
const CanvasGetImageDataProtocol = {
canvasId: {
type: String,
required: true
},
x: {
type: Number,
required: true
},
y: {
type: Number,
required: true
},
width: {
type: Number,
required: true
},
height: {
type: Number,
required: true
}
};
const API_CANVAS_PUT_IMAGE_DATA = "canvasPutImageData";
const CanvasPutImageDataOptions = CanvasGetImageDataOptions;
const CanvasPutImageDataProtocol = /* @__PURE__ */ extend(
{
data: {
type: Uint8ClampedArray,
required: true
}
},
CanvasGetImageDataProtocol,
{
height: {
type: Number
}
}
);
const fileTypes = {
PNG: "png",
JPG: "jpg",
JPEG: "jpg"
};
const API_CANVAS_TO_TEMP_FILE_PATH = "canvasToTempFilePath";
const CanvasToTempFilePathOptions = {
formatArgs: {
x: getInt("x", 0),
y: getInt("y", 0),
width: formatWidth,
height: formatHeight,
destWidth: getInt("destWidth"),
destHeight: getInt("destHeight"),
fileType(value, params) {
value = (value || "").toUpperCase();
let type = fileTypes[value];
if (!type) {
type = fileTypes.PNG;
}
params.fileType = type;
},
quality(value, params) {
params.quality = value && value > 0 && value < 1 ? value : 1;
}
}
};
const CanvasToTempFilePathProtocol = {
x: Number,
y: Number,
width: Number,
height: Number,
destWidth: Number,
destHeight: Number,
canvasId: {
type: String,
required: true
},
fileType: String,
quality: Number
};
function operateCanvas(canvasId, pageId, type, data, callback) {
UniServiceJSBridge.invokeViewMethod(
`canvas.${canvasId}`,
{
type,
data
},
pageId,
(data2) => {
if (callback)
callback(data2);
}
);
}
var methods1 = ["scale", "rotate", "translate", "setTransform", "transform"];
var methods2 = [
"drawImage",
"fillText",
"fill",
"stroke",
"fillRect",
"strokeRect",
"clearRect",
"strokeText"
];
var methods3 = [
"setFillStyle",
"setTextAlign",
"setStrokeStyle",
"setGlobalAlpha",
"setShadow",
"setFontSize",
"setLineCap",
"setLineJoin",
"setLineWidth",
"setMiterLimit",
"setTextBaseline",
"setLineDash"
];
function measureText(text2, font2) {
const canvas = document.createElement("canvas");
const c2d = canvas.getContext("2d");
c2d.font = font2;
return c2d.measureText(text2).width || 0;
}
const predefinedColor = {
aliceblue: "#f0f8ff",
antiquewhite: "#faebd7",
aqua: "#00ffff",
aquamarine: "#7fffd4",
azure: "#f0ffff",
beige: "#f5f5dc",
bisque: "#ffe4c4",
black: "#000000",
blanchedalmond: "#ffebcd",
blue: "#0000ff",
blueviolet: "#8a2be2",
brown: "#a52a2a",
burlywood: "#deb887",
cadetblue: "#5f9ea0",
chartreuse: "#7fff00",
chocolate: "#d2691e",
coral: "#ff7f50",
cornflowerblue: "#6495ed",
cornsilk: "#fff8dc",
crimson: "#dc143c",
cyan: "#00ffff",
darkblue: "#00008b",
darkcyan: "#008b8b",
darkgoldenrod: "#b8860b",
darkgray: "#a9a9a9",
darkgrey: "#a9a9a9",
darkgreen: "#006400",
darkkhaki: "#bdb76b",
darkmagenta: "#8b008b",
darkolivegreen: "#556b2f",
darkorange: "#ff8c00",
darkorchid: "#9932cc",
darkred: "#8b0000",
darksalmon: "#e9967a",
darkseagreen: "#8fbc8f",
darkslateblue: "#483d8b",
darkslategray: "#2f4f4f",
darkslategrey: "#2f4f4f",
darkturquoise: "#00ced1",
darkviolet: "#9400d3",
deeppink: "#ff1493",
deepskyblue: "#00bfff",
dimgray: "#696969",
dimgrey: "#696969",
dodgerblue: "#1e90ff",
firebrick: "#b22222",
floralwhite: "#fffaf0",
forestgreen: "#228b22",
fuchsia: "#ff00ff",
gainsboro: "#dcdcdc",
ghostwhite: "#f8f8ff",
gold: "#ffd700",
goldenrod: "#daa520",
gray: "#808080",
grey: "#808080",
green: "#008000",
greenyellow: "#adff2f",
honeydew: "#f0fff0",
hotpink: "#ff69b4",
indianred: "#cd5c5c",
indigo: "#4b0082",
ivory: "#fffff0",
khaki: "#f0e68c",
lavender: "#e6e6fa",
lavenderblush: "#fff0f5",
lawngreen: "#7cfc00",
lemonchiffon: "#fffacd",
lightblue: "#add8e6",
lightcoral: "#f08080",
lightcyan: "#e0ffff",
lightgoldenrodyellow: "#fafad2",
lightgray: "#d3d3d3",
lightgrey: "#d3d3d3",
lightgreen: "#90ee90",
lightpink: "#ffb6c1",
lightsalmon: "#ffa07a",
lightseagreen: "#20b2aa",
lightskyblue: "#87cefa",
lightslategray: "#778899",
lightslategrey: "#778899",
lightsteelblue: "#b0c4de",
lightyellow: "#ffffe0",
lime: "#00ff00",
limegreen: "#32cd32",
linen: "#faf0e6",
magenta: "#ff00ff",
maroon: "#800000",
mediumaquamarine: "#66cdaa",
mediumblue: "#0000cd",
mediumorchid: "#ba55d3",
mediumpurple: "#9370db",
mediumseagreen: "#3cb371",
mediumslateblue: "#7b68ee",
mediumspringgreen: "#00fa9a",
mediumturquoise: "#48d1cc",
mediumvioletred: "#c71585",
midnightblue: "#191970",
mintcream: "#f5fffa",
mistyrose: "#ffe4e1",
moccasin: "#ffe4b5",
navajowhite: "#ffdead",
navy: "#000080",
oldlace: "#fdf5e6",
olive: "#808000",
olivedrab: "#6b8e23",
orange: "#ffa500",
orangered: "#ff4500",
orchid: "#da70d6",
palegoldenrod: "#eee8aa",
palegreen: "#98fb98",
paleturquoise: "#afeeee",
palevioletred: "#db7093",
papayawhip: "#ffefd5",
peachpuff: "#ffdab9",
peru: "#cd853f",
pink: "#ffc0cb",
plum: "#dda0dd",
powderblue: "#b0e0e6",
purple: "#800080",
rebeccapurple: "#663399",
red: "#ff0000",
rosybrown: "#bc8f8f",
royalblue: "#4169e1",
saddlebrown: "#8b4513",
salmon: "#fa8072",
sandybrown: "#f4a460",
seagreen: "#2e8b57",
seashell: "#fff5ee",
sienna: "#a0522d",
silver: "#c0c0c0",
skyblue: "#87ceeb",
slateblue: "#6a5acd",
slategray: "#708090",
slategrey: "#708090",
snow: "#fffafa",
springgreen: "#00ff7f",
steelblue: "#4682b4",
tan: "#d2b48c",
teal: "#008080",
thistle: "#d8bfd8",
tomato: "#ff6347",
turquoise: "#40e0d0",
violet: "#ee82ee",
wheat: "#f5deb3",
white: "#ffffff",
whitesmoke: "#f5f5f5",
yellow: "#ffff00",
yellowgreen: "#9acd32",
transparent: "#00000000"
};
function checkColor(e2) {
e2 = e2 || "#000000";
let t12 = null;
if ((t12 = /^#([0-9|A-F|a-f]{6})$/.exec(e2)) != null) {
const n = parseInt(t12[1].slice(0, 2), 16);
const o = parseInt(t12[1].slice(2, 4), 16);
const r = parseInt(t12[1].slice(4), 16);
return [n, o, r, 255];
}
if ((t12 = /^#([0-9|A-F|a-f]{3})$/.exec(e2)) != null) {
let n = t12[1].slice(0, 1);
let o = t12[1].slice(1, 2);
let r = t12[1].slice(2, 3);
n = parseInt(n + n, 16);
o = parseInt(o + o, 16);
r = parseInt(r + r, 16);
return [n, o, r, 255];
}
if ((t12 = /^rgb\((.+)\)$/.exec(e2)) != null) {
return t12[1].split(",").map(function(e22) {
return Math.min(255, parseInt(e22.trim()));
}).concat(255);
}
if ((t12 = /^rgba\((.+)\)$/.exec(e2)) != null) {
return t12[1].split(",").map(function(e22, t22) {
return t22 === 3 ? Math.floor(255 * parseFloat(e22.trim())) : Math.min(255, parseInt(e22.trim()));
});
}
var i = e2.toLowerCase();
if (hasOwn(predefinedColor, i)) {
t12 = /^#([0-9|A-F|a-f]{6,8})$/.exec(predefinedColor[i]);
const n = parseInt(t12[1].slice(0, 2), 16);
const o = parseInt(t12[1].slice(2, 4), 16);
const r = parseInt(t12[1].slice(4, 6), 16);
let a = parseInt(t12[1].slice(6, 8), 16);
a = a >= 0 ? a : 255;
return [n, o, r, a];
}
console.error("unsupported color:" + e2);
return [0, 0, 0, 255];
}
class CanvasGradient {
constructor(type, data) {
this.type = type;
this.data = data;
this.colorStop = [];
}
addColorStop(position, color) {
this.colorStop.push([position, checkColor(color)]);
}
}
class Pattern {
constructor(image2, repetition) {
this.type = "pattern";
this.data = image2;
this.colorStop = repetition;
}
}
class TextMetrics {
constructor(width) {
this.width = width;
}
}
const getTempPath = () => {
let _TEMP_PATH = TEMP_PATH;
return _TEMP_PATH;
};
class CanvasContext {
constructor(id2, pageId) {
this.id = id2;
this.pageId = pageId;
this.actions = [];
this.path = [];
this.subpath = [];
this.drawingState = [];
this.state = {
lineDash: [0, 0],
shadowOffsetX: 0,
shadowOffsetY: 0,
shadowBlur: 0,
shadowColor: [0, 0, 0, 0],
font: "10px sans-serif",
fontSize: 10,
fontWeight: "normal",
fontStyle: "normal",
fontFamily: "sans-serif"
};
}
setFillStyle(color) {
console.log("initCanvasContextProperty implemented.");
}
setStrokeStyle(color) {
console.log("initCanvasContextProperty implemented.");
}
setShadow(offsetX, offsetY, blur, color) {
console.log("initCanvasContextProperty implemented.");
}
addColorStop(stop, color) {
console.log("initCanvasContextProperty implemented.");
}
setLineWidth(lineWidth) {
console.log("initCanvasContextProperty implemented.");
}
setLineCap(lineCap) {
console.log("initCanvasContextProperty implemented.");
}
setLineJoin(lineJoin) {
console.log("initCanvasContextProperty implemented.");
}
setLineDash(pattern, offset) {
console.log("initCanvasContextProperty implemented.");
}
setMiterLimit(miterLimit) {
console.log("initCanvasContextProperty implemented.");
}
fillRect(x, y, width, height) {
console.log("initCanvasContextProperty implemented.");
}
strokeRect(x, y, width, height) {
console.log("initCanvasContextProperty implemented.");
}
clearRect(x, y, width, height) {
console.log("initCanvasContextProperty implemented.");
}
fill() {
console.log("initCanvasContextProperty implemented.");
}
stroke() {
console.log("initCanvasContextProperty implemented.");
}
scale(scaleWidth, scaleHeight) {
console.log("initCanvasContextProperty implemented.");
}
rotate(rotate) {
console.log("initCanvasContextProperty implemented.");
}
translate(x, y) {
console.log("initCanvasContextProperty implemented.");
}
setFontSize(fontSize) {
console.log("initCanvasContextProperty implemented.");
}
fillText(text2, x, y, maxWidth2) {
console.log("initCanvasContextProperty implemented.");
}
setTextAlign(align2) {
console.log("initCanvasContextProperty implemented.");
}
setTextBaseline(textBaseline) {
console.log("initCanvasContextProperty implemented.");
}
drawImage(imageResource, dx, dy, dWidth, dHeigt, sx, sy, sWidth, sHeight) {
console.log("initCanvasContextProperty implemented.");
}
setGlobalAlpha(alpha) {
console.log("initCanvasContextProperty implemented.");
}
strokeText(text2, x, y, maxWidth2) {
console.log("initCanvasContextProperty implemented.");
}
setTransform(scaleX, skewX, skewY, scaleY, translateX, translateY) {
console.log("initCanvasContextProperty implemented.");
}
draw(reserve = false, callback) {
var actions = [...this.actions];
this.actions = [];
this.path = [];
operateCanvas(
this.id,
this.pageId,
"actionsChanged",
{
actions,
reserve
},
callback
);
}
createLinearGradient(x0, y0, x1, y1) {
return new CanvasGradient("linear", [x0, y0, x1, y1]);
}
createCircularGradient(x, y, r) {
return new CanvasGradient("radial", [x, y, r]);
}
createPattern(image2, repetition) {
if (void 0 === repetition) {
console.error(
"Failed to execute 'createPattern' on 'CanvasContext': 2 arguments required, but only 1 present."
);
} else if (["repeat", "repeat-x", "repeat-y", "no-repeat"].indexOf(repetition) < 0) {
console.error(
"Failed to execute 'createPattern' on 'CanvasContext': The provided type ('" + repetition + "') is not one of 'repeat', 'no-repeat', 'repeat-x', or 'repeat-y'."
);
} else {
return new Pattern(image2, repetition);
}
}
measureText(text2, callback) {
const font2 = this.state.font;
let width = 0;
{
width = measureText(text2, font2);
}
return new TextMetrics(width);
}
save() {
this.actions.push({
method: "save",
data: []
});
this.drawingState.push(this.state);
}
restore() {
this.actions.push({
method: "restore",
data: []
});
this.state = this.drawingState.pop() || {
lineDash: [0, 0],
shadowOffsetX: 0,
shadowOffsetY: 0,
shadowBlur: 0,
shadowColor: [0, 0, 0, 0],
font: "10px sans-serif",
fontSize: 10,
fontWeight: "normal",
fontStyle: "normal",
fontFamily: "sans-serif"
};
}
beginPath() {
this.path = [];
this.subpath = [];
this.path.push({
method: "beginPath",
data: []
});
}
moveTo(x, y) {
this.path.push({
method: "moveTo",
data: [x, y]
});
this.subpath = [[x, y]];
}
lineTo(x, y) {
if (this.path.length === 0 && this.subpath.length === 0) {
this.path.push({
method: "moveTo",
data: [x, y]
});
} else {
this.path.push({
method: "lineTo",
data: [x, y]
});
}
this.subpath.push([x, y]);
}
quadraticCurveTo(cpx, cpy, x, y) {
this.path.push({
method: "quadraticCurveTo",
data: [cpx, cpy, x, y]
});
this.subpath.push([x, y]);
}
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) {
this.path.push({
method: "bezierCurveTo",
data: [cp1x, cp1y, cp2x, cp2y, x, y]
});
this.subpath.push([x, y]);
}
arc(x, y, r, sAngle, eAngle, counterclockwise = false) {
this.path.push({
method: "arc",
data: [x, y, r, sAngle, eAngle, counterclockwise]
});
this.subpath.push([x, y]);
}
rect(x, y, width, height) {
this.path.push({
method: "rect",
data: [x, y, width, height]
});
this.subpath = [[x, y]];
}
arcTo(x1, y1, x2, y2, radius) {
this.path.push({
method: "arcTo",
data: [x1, y1, x2, y2, radius]
});
this.subpath.push([x2, y2]);
}
clip() {
this.actions.push({
method: "clip",
data: [...this.path]
});
}
closePath() {
this.path.push({
method: "closePath",
data: []
});
if (this.subpath.length) {
this.subpath = [this.subpath.shift()];
}
}
clearActions() {
this.actions = [];
this.path = [];
this.subpath = [];
}
getActions() {
var actions = [...this.actions];
this.clearActions();
return actions;
}
set lineDashOffset(value) {
this.actions.push({
method: "setLineDashOffset",
data: [value]
});
}
set globalCompositeOperation(type) {
this.actions.push({
method: "setGlobalCompositeOperation",
data: [type]
});
}
set shadowBlur(level) {
this.actions.push({
method: "setShadowBlur",
data: [level]
});
}
set shadowColor(color) {
this.actions.push({
method: "setShadowColor",
data: [color]
});
}
set shadowOffsetX(x) {
this.actions.push({
method: "setShadowOffsetX",
data: [x]
});
}
set shadowOffsetY(y) {
this.actions.push({
method: "setShadowOffsetY",
data: [y]
});
}
set font(value) {
var self = this;
this.state.font = value;
var fontFormat = value.match(
// 支持小数点 github #5329
/^(([\w\-]+\s)*)(\d+\.?\d*r?px)(\/(\d+\.?\d*(r?px)?))?\s+(.*)/
);
if (fontFormat) {
var style = fontFormat[1].trim().split(/\s/);
var fontSize = parseFloat(fontFormat[3]);
var fontFamily = fontFormat[7];
var actions = [];
style.forEach(function(value2, index2) {
if (["italic", "oblique", "normal"].indexOf(value2) > -1) {
actions.push({
method: "setFontStyle",
data: [value2]
});
self.state.fontStyle = value2;
} else if (["bold", "normal", "lighter", "bolder"].indexOf(value2) > -1 || /^\d+$/.test(value2)) {
actions.push({
method: "setFontWeight",
data: [value2]
});
self.state.fontWeight = value2;
} else if (index2 === 0) {
actions.push({
method: "setFontStyle",
data: ["normal"]
});
self.state.fontStyle = "normal";
} else if (index2 === 1) {
pushAction();
}
});
if (style.length === 1) {
pushAction();
}
style = actions.map(function(action) {
return action.data[0];
}).join(" ");
this.state.fontSize = fontSize;
this.state.fontFamily = fontFamily;
this.actions.push({
method: "setFont",
data: [`${style} ${fontSize}px ${fontFamily}`]
});
} else {
console.warn("Failed to set 'font' on 'CanvasContext': invalid format.");
}
function pushAction() {
actions.push({
method: "setFontWeight",
data: ["normal"]
});
self.state.fontWeight = "normal";
}
}
get font() {
return this.state.font;
}
set fillStyle(color) {
this.setFillStyle(color);
}
set strokeStyle(color) {
this.setStrokeStyle(color);
}
set globalAlpha(value) {
value = Math.floor(255 * parseFloat(value));
this.actions.push({
method: "setGlobalAlpha",
data: [value]
});
}
set textAlign(align2) {
this.actions.push({
method: "setTextAlign",
data: [align2]
});
}
set lineCap(type) {
this.actions.push({
method: "setLineCap",
data: [type]
});
}
set lineJoin(type) {
this.actions.push({
method: "setLineJoin",
data: [type]
});
}
set lineWidth(value) {
this.actions.push({
method: "setLineWidth",
data: [value]
});
}
set miterLimit(value) {
this.actions.push({
method: "setMiterLimit",
data: [value]
});
}
set textBaseline(type) {
this.actions.push({
method: "setTextBaseline",
data: [type]
});
}
}
const initCanvasContextProperty = /* @__PURE__ */ once(() => {
[...methods1, ...methods2].forEach(function(method) {
function get(method2) {
switch (method2) {
case "fill":
case "stroke":
return function() {
this.actions.push({
method: method2 + "Path",
// @ts-expect-error
data: [...this.path]
});
};
case "fillRect":
return function(x, y, width, height) {
this.actions.push({
method: "fillPath",
data: [
{
method: "rect",
data: [x, y, width, height]
}
]
});
};
case "strokeRect":
return function(x, y, width, height) {
this.actions.push({
method: "strokePath",
data: [
{
method: "rect",
data: [x, y, width, height]
}
]
});
};
case "fillText":
case "strokeText":
return function(text2, x, y, maxWidth2) {
var data = [text2.toString(), x, y];
if (typeof maxWidth2 === "number") {
data.push(maxWidth2);
}
this.actions.push({
method: method2,
data
});
};
case "drawImage":
return function(imageResource, dx, dy, dWidth, dHeight, sx, sy, sWidth, sHeight) {
if (sHeight === void 0) {
sx = dx;
sy = dy;
sWidth = dWidth;
sHeight = dHeight;
dx = void 0;
dy = void 0;
dWidth = void 0;
dHeight = void 0;
}
var data;
function isNumber(e2) {
return typeof e2 === "number";
}
data = isNumber(dx) && isNumber(dy) && isNumber(dWidth) && isNumber(dHeight) ? [
imageResource,
sx,
sy,
sWidth,
sHeight,
dx,
dy,
dWidth,
dHeight
] : isNumber(sWidth) && isNumber(sHeight) ? [imageResource, sx, sy, sWidth, sHeight] : [imageResource, sx, sy];
this.actions.push({
method: method2,
data
});
};
default:
return function(...data) {
this.actions.push({
method: method2,
data
});
};
}
}
CanvasContext.prototype[method] = get(method);
});
methods3.forEach(function(method) {
function get(method2) {
switch (method2) {
case "setFillStyle":
case "setStrokeStyle":
return function(color) {
if (typeof color !== "object") {
this.actions.push({
method: method2,
data: ["normal", checkColor(color)]
});
} else {
this.actions.push({
method: method2,
data: [color.type, color.data, color.colorStop]
});
}
};
case "setGlobalAlpha":
return function(alpha) {
alpha = Math.floor(255 * parseFloat(alpha));
this.actions.push({
method: method2,
data: [alpha]
});
};
case "setShadow":
return function(offsetX, offsetY, blur, color) {
color = checkColor(color);
this.actions.push({
method: method2,
data: [offsetX, offsetY, blur, color]
});
this.state.shadowBlur = blur;
this.state.shadowColor = color;
this.state.shadowOffsetX = offsetX;
this.state.shadowOffsetY = offsetY;
};
case "setLineDash":
return function(pattern, offset) {
pattern = pattern || [0, 0];
offset = offset || 0;
this.actions.push({
method: method2,
data: [pattern, offset]
});
this.state.lineDash = pattern;
};
case "setFontSize":
return function(fontSize) {
this.state.font = this.state.font.replace(
/\d+\.?\d*px/,
fontSize + "px"
);
this.state.fontSize = fontSize;
this.actions.push({
method: method2,
data: [fontSize]
});
};
default:
return function(...data) {
this.actions.push({
method: method2,
data
});
};
}
}
CanvasContext.prototype[method] = get(method);
});
});
const createCanvasContext = /* @__PURE__ */ defineSyncApi(
API_CREATE_CANVAS_CONTEXT,
(canvasId, componentInstance) => {
initCanvasContextProperty();
if (componentInstance) {
return new CanvasContext(canvasId, getPageIdByVm(componentInstance));
}
const pageId = getPageIdByVm(getCurrentPageVm());
if (pageId) {
return new CanvasContext(canvasId, pageId);
} else {
UniServiceJSBridge.emit(ON_ERROR, "createCanvasContext:fail");
}
},
CreateCanvasContextProtocol
);
const canvasGetImageData = /* @__PURE__ */ defineAsyncApi(
API_CANVAS_GET_IMAGE_DATA,
({ canvasId, x, y, width, height }, { resolve, reject }) => {
const pageId = getPageIdByVm(getCurrentPageVm());
if (!pageId) {
reject();
return;
}
function callback(data) {
if (data.errMsg && data.errMsg.indexOf("fail") !== -1) {
reject("", data);
return;
}
let imgData = data.data;
if (imgData && imgData.length) {
data.data = new Uint8ClampedArray(imgData);
}
delete data.compressed;
resolve(data);
}
operateCanvas(
canvasId,
pageId,
"getImageData",
{
x,
y,
width,
height
},
callback
);
},
CanvasGetImageDataProtocol,
CanvasGetImageDataOptions
);
const canvasPutImageData = /* @__PURE__ */ defineAsyncApi(
API_CANVAS_PUT_IMAGE_DATA,
({ canvasId, data, x, y, width, height }, { resolve, reject }) => {
var pageId = getPageIdByVm(getCurrentPageVm());
if (!pageId) {
reject();
return;
}
let compressed;
const operate = () => {
operateCanvas(
canvasId,
pageId,
"putImageData",
{
data,
x,
y,
width,
height,
compressed
},
(data2) => {
if (data2.errMsg && data2.errMsg.indexOf("fail") !== -1) {
reject();
return;
}
resolve(data2);
}
);
};
{
data = Array.prototype.slice.call(data);
}
operate();
},
CanvasPutImageDataProtocol,
CanvasPutImageDataOptions
);
const canvasToTempFilePath = /* @__PURE__ */ defineAsyncApi(
API_CANVAS_TO_TEMP_FILE_PATH,
({
x = 0,
y = 0,
width,
height,
destWidth,
destHeight,
canvasId,
fileType,
quality
}, { resolve, reject }) => {
var pageId = getPageIdByVm(getCurrentPageVm());
if (!pageId) {
reject();
return;
}
let dirname = `${getTempPath()}/canvas`;
operateCanvas(
canvasId,
pageId,
"toTempFilePath",
{
x,
y,
width,
height,
destWidth,
destHeight,
fileType,
quality,
dirname
},
(res) => {
if (res.errMsg && res.errMsg.indexOf("fail") !== -1) {
reject("", res);
return;
}
resolve(res);
}
);
},
CanvasToTempFilePathProtocol,
CanvasToTempFilePathOptions
);
const innerAudioContextEventNames = [
"onCanplay",
"onPlay",
"onPause",
"onStop",
"onEnded",
"onTimeUpdate",
"onError",
"onWaiting",
"onSeeking",
"onSeeked"
];
const innerAudioContextOffEventNames = [
"offCanplay",
"offPlay",
"offPause",
"offStop",
"offEnded",
"offTimeUpdate",
"offError",
"offWaiting",
"offSeeking",
"offSeeked"
];
let index$7 = 0;
let optionsCache = {};
function operateEditor(componentId, pageId, type, options) {
const data = { options };
const needCallOptions = options && ("success" in options || "fail" in options || "complete" in options);
if (needCallOptions) {
const callbackId = String(index$7++);
data.callbackId = callbackId;
optionsCache[callbackId] = options;
}
UniServiceJSBridge.invokeViewMethod(
`editor.${componentId}`,
{
type,
data
},
pageId,
({ callbackId, data: data2 }) => {
if (needCallOptions) {
callOptions(optionsCache[callbackId], data2);
delete optionsCache[callbackId];
}
}
);
}
class EditorContext {
constructor(id2, pageId) {
this.id = id2;
this.pageId = pageId;
}
format(name, value) {
this._exec("format", {
name,
value
});
}
insertDivider() {
this._exec("insertDivider");
}
insertMention(options) {
this._exec("insertMention", options);
}
insertLink(options) {
this._exec("insertLink", options);
}
insertImage(options) {
this._exec("insertImage", options);
}
insertText(options) {
this._exec("insertText", options);
}
setContents(options) {
this._exec("setContents", options);
}
getContents(options) {
this._exec("getContents", options);
}
clear(options) {
this._exec("clear", options);
}
removeFormat(options) {
this._exec("removeFormat", options);
}
undo(options) {
this._exec("undo", options);
}
redo(options) {
this._exec("redo", options);
}
blur(options) {
this._exec("blur", options);
}
getSelectionText(options) {
this._exec("getSelectionText", options);
}
scrollIntoView(options) {
this._exec("scrollIntoView", options);
}
_exec(method, options) {
operateEditor(this.id, this.pageId, method, options);
}
}
const defaultOptions = {
thresholds: [0],
initialRatio: 0,
observeAll: false
};
const MARGINS = ["top", "right", "bottom", "left"];
let reqComponentObserverId$1 = 1;
function normalizeRootMargin(margins = {}) {
return MARGINS.map(
(name) => `${Number(margins[name]) || 0}px`
).join(" ");
}
class ServiceIntersectionObserver {
constructor(component, options) {
this._pageId = getPageIdByVm(component);
this._component = component;
this._options = extend({}, defaultOptions, options);
}
relativeTo(selector, margins) {
this._options.relativeToSelector = selector;
this._options.rootMargin = normalizeRootMargin(margins);
return this;
}
relativeToViewport(margins) {
this._options.relativeToSelector = void 0;
this._options.rootMargin = normalizeRootMargin(margins);
return this;
}
observe(selector, callback) {
if (!isFunction(callback)) {
return;
}
this._options.selector = selector;
this._reqId = reqComponentObserverId$1++;
addIntersectionObserver(
{
reqId: this._reqId,
component: this._component,
options: this._options,
callback
},
this._pageId
);
}
disconnect() {
this._reqId && removeIntersectionObserver(
{ reqId: this._reqId, component: this._component },
this._pageId
);
}
}
const createIntersectionObserver = /* @__PURE__ */ defineSyncApi("createIntersectionObserver", (context, options) => {
context = resolveComponentInstance(context);
if (context && !getPageIdByVm(context)) {
options = context;
context = null;
}
if (context) {
return new ServiceIntersectionObserver(context, options);
}
return new ServiceIntersectionObserver(getCurrentPageVm(), options);
});
let reqComponentObserverId = 1;
class ServiceMediaQueryObserver {
constructor(component) {
this._pageId = (component == null ? void 0 : component.$page) && component.$page.id;
this._component = component;
}
observe(options, callback) {
if (!isFunction(callback)) {
return;
}
this._reqId = reqComponentObserverId++;
addMediaQueryObserver(
{
reqId: this._reqId,
component: this._component,
options,
callback
},
this._pageId
);
}
disconnect() {
this._reqId && removeMediaQueryObserver(
{
reqId: this._reqId,
component: this._component
},
this._pageId
);
}
}
const createMediaQueryObserver = /* @__PURE__ */ defineSyncApi("createMediaQueryObserver", (context) => {
context = resolveComponentInstance(context);
if (context && !getPageIdByVm(context)) {
context = null;
}
if (context) {
return new ServiceMediaQueryObserver(context);
}
return new ServiceMediaQueryObserver(getCurrentPageVm());
});
const ContextClasss = {
canvas: CanvasContext,
map: MapContext,
video: VideoContext,
editor: EditorContext
};
function convertContext(result) {
if (result && result.contextInfo) {
const { id: id2, type, page } = result.contextInfo;
const ContextClass = ContextClasss[type];
result.context = new ContextClass(id2, page);
delete result.contextInfo;
}
}
class NodesRef {
constructor(selectorQuery, component, selector, single) {
this._selectorQuery = selectorQuery;
this._component = component;
this._selector = selector;
this._single = single;
}
boundingClientRect(callback) {
this._selectorQuery._push(
this._selector,
this._component,
this._single,
{
id: true,
dataset: true,
rect: true,
size: true
},
callback
);
return this._selectorQuery;
}
fields(fields, callback) {
this._selectorQuery._push(
this._selector,
this._component,
this._single,
fields,
callback
);
return this._selectorQuery;
}
scrollOffset(callback) {
this._selectorQuery._push(
this._selector,
this._component,
this._single,
{
id: true,
dataset: true,
scrollOffset: true
},
callback
);
return this._selectorQuery;
}
context(callback) {
this._selectorQuery._push(
this._selector,
this._component,
this._single,
{
context: true
},
callback
);
return this._selectorQuery;
}
node(callback) {
this._selectorQuery._push(
this._selector,
this._component,
this._single,
{
node: true
},
callback
);
return this._selectorQuery;
}
}
class SelectorQuery {
constructor(page) {
this._component = void 0;
this._page = page;
this._queue = [];
this._queueCb = [];
}
exec(callback) {
requestComponentInfo(
this._page,
this._queue,
(res) => {
const queueCbs = this._queueCb;
res.forEach((result, index2) => {
if (isArray(result)) {
result.forEach(convertContext);
} else {
convertContext(result);
}
const queueCb = queueCbs[index2];
if (isFunction(queueCb)) {
queueCb.call(this, result);
}
});
if (isFunction(callback)) {
callback.call(this, res);
}
}
);
return this._nodesRef;
}
in(component) {
this._component = resolveComponentInstance(component);
if (this._component && this._component.$root) {
const root = resolveComponentInstance(this._component.$root);
if (root) {
this._page = root;
}
}
return this;
}
select(selector) {
return this._nodesRef = new NodesRef(
this,
this._component,
selector,
true
);
}
selectAll(selector) {
return this._nodesRef = new NodesRef(
this,
this._component,
selector,
false
);
}
selectViewport() {
return this._nodesRef = new NodesRef(this, null, "", true);
}
_push(selector, component, single, fields, callback) {
this._queue.push({
component,
selector,
single,
fields
});
this._queueCb.push(callback);
}
}
const createSelectorQuery = /* @__PURE__ */ defineSyncApi("createSelectorQuery", (context) => {
context = resolveComponentInstance(context);
if (context && !getPageIdByVm(context)) {
context = null;
}
return new SelectorQuery(context || getCurrentPageVm());
});
const API_CREATE_ANIMATION = "createAnimation";
const CreateAnimationOptions = {
// 目前参数校验不支持此api校验
formatArgs: {
/* duration: 400,
timingFunction(timingFunction, params) {
params.timingFunction = elemInArray(timingFunction, timingFunctions)
},
delay: 0,
transformOrigin: '50% 50% 0', */
}
};
const CreateAnimationProtocol = {
duration: Number,
timingFunction: String,
delay: Number,
transformOrigin: String
};
const defaultOption = {
duration: 400,
timingFunction: "linear",
delay: 0,
transformOrigin: "50% 50% 0"
};
class MPAnimation {
constructor(option) {
this.actions = [];
this.currentTransform = {};
this.currentStepAnimates = [];
this.option = extend({}, defaultOption, option);
}
_getOption(option) {
const _option = {
transition: extend({}, this.option, option),
transformOrigin: ""
};
_option.transformOrigin = _option.transition.transformOrigin;
delete _option.transition.transformOrigin;
return _option;
}
_pushAnimates(type, args) {
this.currentStepAnimates.push({
type,
args
});
}
_converType(type) {
return type.replace(/[A-Z]/g, (text2) => {
return `-${text2.toLowerCase()}`;
});
}
_getValue(value) {
return typeof value === "number" ? `${value}px` : value;
}
export() {
const actions = this.actions;
this.actions = [];
return {
actions
};
}
step(option) {
this.currentStepAnimates.forEach((animate) => {
if (animate.type !== "style") {
this.currentTransform[animate.type] = animate;
} else {
this.currentTransform[`${animate.type}.${animate.args[0]}`] = animate;
}
});
this.actions.push({
animates: Object.values(
this.currentTransform
),
option: this._getOption(option)
});
this.currentStepAnimates = [];
return this;
}
}
const initAnimationProperty = /* @__PURE__ */ once(() => {
const animateTypes1 = [
"matrix",
"matrix3d",
"rotate",
"rotate3d",
"rotateX",
"rotateY",
"rotateZ",
"scale",
"scale3d",
"scaleX",
"scaleY",
"scaleZ",
"skew",
"skewX",
"skewY",
"translate",
"translate3d",
"translateX",
"translateY",
"translateZ"
];
const animateTypes2 = ["opacity", "backgroundColor"];
const animateTypes3 = ["width", "height", "left", "right", "top", "bottom"];
animateTypes1.concat(animateTypes2, animateTypes3).forEach((type) => {
MPAnimation.prototype[type] = function(...args) {
if (animateTypes2.concat(animateTypes3).includes(type)) {
this._pushAnimates("style", [
this._converType(type),
animateTypes3.includes(type) ? this._getValue(args[0]) : args[0]
]);
} else {
this._pushAnimates(type, args);
}
return this;
};
});
});
const createAnimation = /* @__PURE__ */ defineSyncApi(
API_CREATE_ANIMATION,
(option) => {
initAnimationProperty();
return new MPAnimation(option);
},
CreateAnimationProtocol,
CreateAnimationOptions
);
const API_ON_TAB_BAR_MID_BUTTON_TAP = "onTabBarMidButtonTap";
const onTabBarMidButtonTap = /* @__PURE__ */ defineOnApi(
API_ON_TAB_BAR_MID_BUTTON_TAP,
() => {
}
);
const API_ON_WINDOW_RESIZE = "onWindowResize";
const API_OFF_WINDOW_RESIZE = "offWindowResize";
const onWindowResize = /* @__PURE__ */ defineOnApi(
API_ON_WINDOW_RESIZE,
() => {
}
);
const offWindowResize = /* @__PURE__ */ defineOffApi(
API_OFF_WINDOW_RESIZE,
() => {
}
);
const API_SET_LOCALE = "setLocale";
const API_GET_LOCALE = "getLocale";
const API_ON_LOCALE_CHANGE = "onLocaleChange";
const getLocale = /* @__PURE__ */ defineSyncApi(
API_GET_LOCALE,
() => {
const app = getApp({ allowDefault: true });
if (app && app.$vm) {
return app.$vm.$locale;
}
return useI18n().getLocale();
}
);
const onLocaleChange = /* @__PURE__ */ defineOnApi(
API_ON_LOCALE_CHANGE,
() => {
}
);
const setLocale = /* @__PURE__ */ defineSyncApi(
API_SET_LOCALE,
(locale) => {
const app = getApp();
if (!app) {
return false;
}
const oldLocale = app.$vm.$locale;
if (oldLocale !== locale) {
app.$vm.$locale = locale;
{
navigator.cookieEnabled && window.localStorage && (localStorage[UNI_STORAGE_LOCALE] = locale);
}
UniServiceJSBridge.invokeOnCallback(API_ON_LOCALE_CHANGE, { locale });
return true;
}
return false;
}
);
const API_SET_PAGE_META = "setPageMeta";
const setPageMeta = /* @__PURE__ */ defineAsyncApi(
API_SET_PAGE_META,
(options, { resolve }) => {
resolve(setCurrentPageMeta(getCurrentPageVm(), options));
}
);
const API_GET_SELECTED_TEXT_RANGE = "getSelectedTextRange";
const getSelectedTextRange = /* @__PURE__ */ defineAsyncApi(
API_GET_SELECTED_TEXT_RANGE,
(_, { resolve, reject }) => {
UniServiceJSBridge.invokeViewMethod(API_GET_SELECTED_TEXT_RANGE, {}, getCurrentPageId(), (res) => {
if (typeof res.end === "undefined" && typeof res.start === "undefined") {
reject("no focused");
} else {
resolve(res);
}
});
}
);
const appHooks = {
[ON_UNHANDLE_REJECTION]: [],
[ON_PAGE_NOT_FOUND]: [],
[ON_ERROR]: [],
[ON_SHOW]: [],
[ON_HIDE]: []
};
function onAppHook(type, hook) {
const app = getApp({ allowDefault: true });
if (app && app.$vm) {
return injectHook(type, hook, app.$vm.$);
}
appHooks[type].push(hook);
}
function injectAppHooks(appInstance) {
Object.keys(appHooks).forEach((type) => {
appHooks[type].forEach((hook) => {
injectHook(type, hook, appInstance);
});
});
}
function offAppHook(type, hook) {
const app = getApp({ allowDefault: true });
if (app && app.$vm) {
return removeHook(app.$vm, type, hook);
}
remove(appHooks[type], hook);
}
function onUnhandledRejection(hook) {
onAppHook(ON_UNHANDLE_REJECTION, hook);
}
function offUnhandledRejection(hook) {
offAppHook(ON_UNHANDLE_REJECTION, hook);
}
function onPageNotFound(hook) {
onAppHook(ON_PAGE_NOT_FOUND, hook);
}
function offPageNotFound(hook) {
offAppHook(ON_PAGE_NOT_FOUND, hook);
}
function onError(hook) {
onAppHook(ON_ERROR, hook);
}
function offError(hook) {
offAppHook(ON_ERROR, hook);
}
function onAppShow(hook) {
onAppHook(ON_SHOW, hook);
}
function offAppShow(hook) {
offAppHook(ON_SHOW, hook);
}
function onAppHide(hook) {
onAppHook(ON_HIDE, hook);
}
function offAppHide(hook) {
offAppHook(ON_HIDE, hook);
}
const API_GET_ENTER_OPTIONS_SYNC = "getEnterOptionsSync";
const getEnterOptionsSync = /* @__PURE__ */ defineSyncApi(
API_GET_ENTER_OPTIONS_SYNC,
() => {
return getEnterOptions();
}
);
const API_GET_LAUNCH_OPTIONS_SYNC = "getLaunchOptionsSync";
const getLaunchOptionsSync = /* @__PURE__ */ defineSyncApi(
API_GET_LAUNCH_OPTIONS_SYNC,
() => {
return getLaunchOptions();
}
);
const API_ON_APP_ROUTE = "onAppRoute";
const API_OFF_APP_ROUTE = "offAppRoute";
const API_ON_BEFORE_APP_ROUTE = "onBeforeAppRoute";
const API_OFF_BEFORE_APP_ROUTE = "offBeforeAppRoute";
const API_REWRITE_ROUTE = "rewriteRoute";
const eventTransport = /* @__PURE__ */ new Emitter();
let activeBeforeAppRouteContext;
const MAX_APP_ROUTE_REWRITE_COUNT = 100;
const APP_ROUTE_ERROR_CODE = 4;
function createAppRouteRuntime(options = {}) {
let routeEventId = 0;
const onAppRoute2 = /* @__PURE__ */ defineOnApi(API_ON_APP_ROUTE, () => {
}, {
eventTransport
});
const offAppRoute2 = /* @__PURE__ */ defineOffApi(API_OFF_APP_ROUTE, () => {
}, {
allowClearAll: true,
eventTransport
});
const onBeforeAppRoute2 = /* @__PURE__ */ defineOnApi(
API_ON_BEFORE_APP_ROUTE,
() => {
},
{ eventTransport }
);
const offBeforeAppRoute2 = /* @__PURE__ */ defineOffApi(
API_OFF_BEFORE_APP_ROUTE,
() => {
},
{
allowClearAll: true,
eventTransport
}
);
const rewriteRoute2 = /* @__PURE__ */ defineAsyncApi(
API_REWRITE_ROUTE,
({ url, preserveQuery }, { resolve, reject }) => {
const rejectRewriteRoute = (errMsg) => reject(errMsg, { errCode: APP_ROUTE_ERROR_CODE });
const context = activeBeforeAppRouteContext;
if (!context) {
rejectRewriteRoute(
"rewriteRoute is only allowed in a onBeforeAppRoute callback"
);
return;
}
if (context.event.openType === "navigateBack") {
rejectRewriteRoute(
'a "navigateBack" event is not allowed to be rewritten'
);
return;
}
if (context.rewrite) {
rejectRewriteRoute(
`rewriteRoute can only be called once in a route event, this page has been rewritten to "${context.rewrite.path}"`
);
return;
}
if ((context.rewriteCount || 0) >= MAX_APP_ROUTE_REWRITE_COUNT) {
rejectRewriteRoute(
`rewriteRoute exceeded the maximum rewrite count of ${MAX_APP_ROUTE_REWRITE_COUNT}`
);
return;
}
if (!context.normalizeRewriteRoute) {
rejectRewriteRoute("not supported");
return;
}
const rewrite = context.normalizeRewriteRoute(
{ url, preserveQuery },
context.event
);
if (typeof rewrite === "string") {
rejectRewriteRoute(rewrite);
return;
}
context.rewrite = rewrite;
resolve();
},
{
url: {
type: String,
required: true
},
preserveQuery: Boolean
}
);
function createAppRouteContext2(event) {
const timeStamp = event.timeStamp ?? Date.now();
return {
event: {
path: event.path,
query: Object.assign({}, event.query),
openType: event.openType,
notFound: event.notFound,
timeStamp,
routeEventId: event.routeEventId ?? `${timeStamp}-${++routeEventId}`
},
normalizeRewriteRoute: options.normalizeRewriteRoute
};
}
function dispatchBeforeAppRoute(context) {
const event = context.event;
const beforeEvent = {
path: event.path,
query: Object.assign({}, event.query),
openType: event.openType,
notFound: event.notFound,
routeEventId: event.routeEventId
};
const previousContext = activeBeforeAppRouteContext;
activeBeforeAppRouteContext = context;
try {
eventTransport.emit(API_ON_BEFORE_APP_ROUTE, beforeEvent);
} catch (error) {
console.error(error);
} finally {
activeBeforeAppRouteContext = previousContext;
}
return context.rewrite;
}
function dispatchAppRoute2(context) {
const event = context.event;
try {
const routeEvent = {
path: event.path,
query: Object.assign({}, event.query),
openType: event.openType,
notFound: event.notFound,
timeStamp: event.timeStamp,
routeEventId: event.routeEventId
};
eventTransport.emit(API_ON_APP_ROUTE, routeEvent);
} catch (error) {
console.error(error);
}
}
return {
onAppRoute: onAppRoute2,
offAppRoute: offAppRoute2,
onBeforeAppRoute: onBeforeAppRoute2,
offBeforeAppRoute: offBeforeAppRoute2,
rewriteRoute: rewriteRoute2,
createAppRouteContext: createAppRouteContext2,
dispatchBeforeAppRoute,
dispatchAppRoute: dispatchAppRoute2
};
}
let cid;
let cidErrMsg;
let enabled;
function normalizePushMessage(message) {
try {
return JSON.parse(message);
} catch (e2) {
}
return message;
}
function invokePushCallback(args) {
if (args.type === "enabled") {
enabled = true;
} else if (args.type === "clientId") {
cid = args.cid;
cidErrMsg = args.errMsg;
invokeGetPushCidCallbacks(cid, args.errMsg);
} else if (args.type === "pushMsg") {
const message = {
type: "receive",
data: normalizePushMessage(args.message)
};
for (let i = 0; i < onPushMessageCallbacks.length; i++) {
const callback = onPushMessageCallbacks[i];
callback(message);
if (message.stopped) {
break;
}
}
} else if (args.type === "click") {
onPushMessageCallbacks.forEach((callback) => {
callback({
type: "click",
data: normalizePushMessage(args.message)
});
});
}
}
const getPushCidCallbacks = [];
function invokeGetPushCidCallbacks(cid2, errMsg) {
getPushCidCallbacks.forEach((callback) => {
callback(cid2, errMsg);
});
getPushCidCallbacks.length = 0;
}
const API_GET_PUSH_CLIENT_ID = "getPushClientId";
const getPushClientId = /* @__PURE__ */ defineAsyncApi(
API_GET_PUSH_CLIENT_ID,
(_, { resolve, reject }) => {
Promise.resolve().then(() => {
if (typeof enabled === "undefined") {
enabled = false;
cid = "";
cidErrMsg = "uniPush is not enabled";
}
getPushCidCallbacks.push((cid2, errMsg) => {
if (cid2) {
resolve({ cid: cid2 });
} else {
reject(errMsg);
}
});
if (typeof cid !== "undefined") {
invokeGetPushCidCallbacks(cid, cidErrMsg);
}
});
}
);
const onPushMessageCallbacks = [];
const onPushMessage = (fn) => {
if (onPushMessageCallbacks.indexOf(fn) === -1) {
onPushMessageCallbacks.push(fn);
}
};
const offPushMessage = (fn) => {
if (!fn) {
onPushMessageCallbacks.length = 0;
} else {
const index2 = onPushMessageCallbacks.indexOf(fn);
if (index2 > -1) {
onPushMessageCallbacks.splice(index2, 1);
}
}
};
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_GET_CLIPBOARD_DATA = "getClipboardData";
const API_SET_CLIPBOARD_DATA = "setClipboardData";
const SetClipboardDataOptions = {
formatArgs: {
showToast: true
},
beforeInvoke() {
initI18nSetClipboardDataMsgsOnce();
},
beforeSuccess(res, params) {
if (!params.showToast)
return;
const { t: t12 } = useI18n();
const title = t12("uni.setClipboardData.success");
if (title) {
uni.showToast({
title,
icon: "success",
mask: false
});
}
}
};
const SetClipboardDataProtocol = {
data: {
type: String,
required: true
},
showToast: {
type: Boolean
}
};
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_SET_KEEP_SCREEN_ON = "setKeepScreenOn";
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_CHOOSE_LOCATION = "chooseLocation";
const API_GET_LOCATION = "getLocation";
const coordTypes$1 = ["wgs84", "gcj02"];
const GetLocationOptions = {
formatArgs: {
type(value, params) {
value = (value || "").toLowerCase();
if (coordTypes$1.indexOf(value) === -1) {
params.type = coordTypes$1[0];
} else {
params.type = value;
}
},
altitude(value, params) {
params.altitude = value ? value : false;
}
}
};
const GetLocationProtocol = {
type: String,
altitude: Boolean
};
const API_OPEN_LOCATION = "openLocation";
const checkProps = (key, value) => {
if (value === void 0) {
return `${key} should not be empty.`;
}
if (typeof value !== "number") {
let receivedType = typeof value;
receivedType = receivedType[0].toUpperCase() + receivedType.substring(1);
return `Expected Number, got ${receivedType} with value ${JSON.stringify(
value
)}.`;
}
};
const OpenLocationOptions = {
formatArgs: {
latitude(value, params) {
const checkedInfo = checkProps("latitude", value);
if (checkedInfo) {
return checkedInfo;
}
params.latitude = value;
},
longitude(value, params) {
const checkedInfo = checkProps("longitude", value);
if (checkedInfo) {
return checkedInfo;
}
params.longitude = value;
},
scale(value, params) {
value = Math.floor(value);
params.scale = value >= 5 && value <= 18 ? value : 18;
}
}
};
const OpenLocationProtocol = {
latitude: Number,
longitude: Number,
scale: Number,
name: String,
address: String
};
const API_CHOOSE_IMAGE = "chooseImage";
const ChooseImageOptions = {
formatArgs: {
count(value, params) {
if (!value || value <= 0) {
params.count = 9;
}
},
sizeType(sizeType, params) {
params.sizeType = elemsInArray(sizeType, CHOOSE_SIZE_TYPES);
},
sourceType(sourceType, params) {
params.sourceType = elemsInArray(sourceType, CHOOSE_SOURCE_TYPES);
},
extension(extension, params) {
if (extension instanceof Array && extension.length === 0) {
return "param extension should not be empty.";
}
if (!extension)
params.extension = ["*"];
}
}
};
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) {
if (params.type === "all" || !params.type) {
params.extension = [""];
} else {
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_PREVIEW_IMAGE = "previewImage";
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_SAVE_IMAGE_TO_PHOTOS_ALBUM = "saveImageToPhotosAlbum";
const API_SAVE_VIDEO_TO_PHOTOS_ALBUM = "saveVideoToPhotosAlbum";
const API_REQUEST = "request";
const dataType = {
JSON: "json"
};
const RESPONSE_TYPE = ["text", "arraybuffer"];
const DEFAULT_RESPONSE_TYPE = "text";
const encode = encodeURIComponent;
function stringifyQuery(url, data) {
let str = url.split("#");
const hash = str[1] || "";
str = str[0].split("?");
let query = str[1] || "";
url = str[0];
const search = query.split("&").filter((item) => item);
const params = {};
search.forEach((item) => {
const part = item.split("=");
params[part[0]] = part[1];
});
for (const key in data) {
if (hasOwn(data, key)) {
let v2 = data[key];
if (typeof v2 === "undefined" || v2 === null) {
v2 = "";
} else if (isPlainObject(v2)) {
v2 = JSON.stringify(v2);
}
params[encode(key)] = encode(v2);
}
}
query = Object.keys(params).map((item) => `${item}=${params[item]}`).join("&");
return url + (query ? "?" + query : "") + (hash ? "#" + hash : "");
}
const RequestProtocol = {
method: String,
data: [Object, String, Array, ArrayBuffer],
url: {
type: String,
required: true
},
header: Object,
dataType: String,
responseType: String,
withCredentials: Boolean
};
const RequestOptions = {
formatArgs: {
method(value, params) {
params.method = elemInArray(
(value || "").toUpperCase(),
HTTP_METHODS
);
},
data(value, params) {
params.data = value || "";
},
url(value, params) {
if (params.method === HTTP_METHODS[0] && isPlainObject(params.data) && Object.keys(params.data).length) {
params.url = stringifyQuery(value, params.data);
}
},
header(value, params) {
const header = params.header = value || {};
if (params.method !== HTTP_METHODS[0]) {
if (!Object.keys(header).find(
(key) => key.toLowerCase() === "content-type"
)) {
header["Content-Type"] = "application/json";
}
}
},
dataType(value, params) {
params.dataType = (value || dataType.JSON).toLowerCase();
},
responseType(value, params) {
params.responseType = (value || "").toLowerCase();
if (RESPONSE_TYPE.indexOf(params.responseType) === -1) {
params.responseType = DEFAULT_RESPONSE_TYPE;
}
}
}
};
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 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 (isString(protocols)) {
params.protocols = [protocols];
}
}
}
};
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
};
const API_START_LOCATION_UPDATE = "startLocationUpdate";
const API_ON_LOCATION_CHANGE = "onLocationChange";
const API_STOP_LOCATION_UPDATE = "stopLocationUpdate";
const API_OFF_LOCATION_CHANGE = "offLocationChange";
const API_OFF_LOCATION_CHANGE_ERROR = "offLocationChangeError";
const API_ON_LOCATION_CHANGE_ERROR = "onLocationChangeError";
const coordTypes = ["wgs84", "gcj02"];
const StartLocationUpdateProtocol = {
type: String
};
const StartLocationUpdateOptions = {
formatArgs: {
type(value, params) {
value = (value || "").toLowerCase();
if (coordTypes.indexOf(value) === -1) {
params.type = coordTypes[1];
} else {
params.type = value;
}
}
}
};
function encodeQueryString(url) {
if (!isString(url)) {
return url;
}
const index2 = url.indexOf("?");
if (index2 === -1) {
return url;
}
const query = url.slice(index2 + 1).trim().replace(/^(\?|#|&)/, "");
if (!query) {
return url;
}
url = url.slice(0, index2);
const params = [];
query.split("&").forEach((param) => {
const parts = param.replace(/\+/g, " ").split("=");
const key = parts.shift();
const val = parts.length > 0 ? parts.join("=") : "";
params.push(key + "=" + encodeURIComponent(val));
});
return params.length ? url + "?" + params.join("&") : url;
}
const ANIMATION_IN = [
"slide-in-right",
"slide-in-left",
"slide-in-top",
"slide-in-bottom",
"fade-in",
"zoom-out",
"zoom-fade-out",
"pop-in",
"none"
];
const ANIMATION_OUT = [
"slide-out-right",
"slide-out-left",
"slide-out-top",
"slide-out-bottom",
"fade-out",
"zoom-in",
"zoom-fade-in",
"pop-out",
"none"
];
const BaseRouteProtocol = {
url: {
type: String,
required: true
}
};
const API_NAVIGATE_TO = "navigateTo";
const API_REDIRECT_TO = "redirectTo";
const API_RE_LAUNCH = "reLaunch";
const API_SWITCH_TAB = "switchTab";
const API_NAVIGATE_BACK = "navigateBack";
const API_PRELOAD_PAGE = "preloadPage";
const API_UN_PRELOAD_PAGE = "unPreloadPage";
const NavigateToProtocol = /* @__PURE__ */ extend(
{},
BaseRouteProtocol,
createAnimationProtocol(ANIMATION_IN)
);
const NavigateBackProtocol = /* @__PURE__ */ extend(
{
delta: {
type: Number
}
},
createAnimationProtocol(ANIMATION_OUT)
);
const RedirectToProtocol = BaseRouteProtocol;
const ReLaunchProtocol = BaseRouteProtocol;
const SwitchTabProtocol = BaseRouteProtocol;
const PreloadPageProtocol = BaseRouteProtocol;
const NavigateToOptions = /* @__PURE__ */ createRouteOptions(API_NAVIGATE_TO);
const RedirectToOptions = /* @__PURE__ */ createRouteOptions(API_REDIRECT_TO);
const ReLaunchOptions = /* @__PURE__ */ createRouteOptions(API_RE_LAUNCH);
const SwitchTabOptions = /* @__PURE__ */ createRouteOptions(API_SWITCH_TAB);
const NavigateBackOptions = {
formatArgs: {
delta(value, params) {
value = parseInt(value + "") || 1;
params.delta = Math.min(getCurrentPages().length - 1, value);
}
}
};
function createAnimationProtocol(animationTypes) {
return {
animationType: {
type: String,
validator(type) {
if (type && animationTypes.indexOf(type) === -1) {
return "`" + type + "` is not supported for `animationType` (supported values are: `" + animationTypes.join("`|`") + "`)";
}
}
},
animationDuration: {
type: Number
}
};
}
let navigatorLock;
let navigatorLockId = 0;
function beforeRoute() {
navigatorLock = "";
navigatorLockId++;
}
function createRouteOptions(type) {
return {
formatArgs: {
url: createNormalizeUrl(type)
},
beforeAll: beforeRoute
};
}
function createNormalizeUrl(type, options = {}) {
return function normalizeUrl(url, params) {
var _a;
if (!url) {
return `Missing required args: "url"`;
}
url = normalizeRoute(url);
const pagePath = url.split("?")[0];
const routeOptions = getRouteOptions(pagePath, true);
if (!routeOptions) {
return "page `" + url + "` is not found";
}
if (type === API_NAVIGATE_TO || type === API_REDIRECT_TO) {
if (routeOptions.meta.isTabBar) {
return `can not ${type} a tabbar page`;
}
} else if (type === API_SWITCH_TAB) {
if (!routeOptions.meta.isTabBar) {
return "can not switch to no-tabBar page";
}
}
if ((type === API_SWITCH_TAB || type === API_PRELOAD_PAGE) && routeOptions.meta.isTabBar && params.openType !== "appLaunch") {
url = pagePath;
}
if (routeOptions.meta.isEntry) {
url = url.replace(routeOptions.alias, "/");
}
params.url = encodeQueryString(url);
if (type === API_UN_PRELOAD_PAGE) {
return;
} else if (type === API_PRELOAD_PAGE) {
if (routeOptions.meta.isTabBar) {
const pages = getCurrentPages();
const tabBarPagePath = routeOptions.path.slice(1);
if (pages.find((page) => page.route === tabBarPagePath)) {
return "tabBar page `" + tabBarPagePath + "` already exists";
}
}
return;
}
if (!options.skipNavigatorLock && navigatorLock === url && params.openType !== "appLaunch") {
return `${navigatorLock} locked`;
}
if (!options.skipNavigatorLock && __uniConfig.ready) {
navigatorLock = url;
const lockId = ++navigatorLockId;
(_a = options.onNavigatorLock) == null ? void 0 : _a.call(options, () => {
if (lockId === navigatorLockId) {
beforeRoute();
}
});
}
};
}
const API_HIDE_TOAST = "hideToast";
const HideToastProtocol = {
allType: Boolean
};
const HideToastOptions = {
formatArgs: {
allType: false
}
};
const API_LOAD_FONT_FACE = "loadFontFace";
const LoadFontFaceProtocol = {
family: {
type: String,
required: true
},
source: {
type: String,
required: true
},
desc: Object
};
const FRONT_COLORS = ["#ffffff", "#000000"];
const API_SET_NAVIGATION_BAR_COLOR = "setNavigationBarColor";
const SetNavigationBarColorOptions = {
formatArgs: {
animation(animation2, params) {
if (!animation2) {
animation2 = { duration: 0, timingFunc: "linear" };
}
params.animation = {
duration: animation2.duration || 0,
timingFunc: animation2.timingFunc || "linear"
};
}
}
};
const SetNavigationBarColorProtocol = {
frontColor: {
type: String,
required: true,
validator(frontColor) {
if (FRONT_COLORS.indexOf(frontColor) === -1) {
return `invalid frontColor "${frontColor}"`;
}
}
},
backgroundColor: {
type: String,
required: true
},
animation: Object
};
const API_SET_NAVIGATION_BAR_TITLE = "setNavigationBarTitle";
const SetNavigationBarTitleProtocol = {
title: {
type: String,
required: true
}
};
const API_SHOW_NAVIGATION_BAR_LOADING = "showNavigationBarLoading";
const API_HIDE_NAVIGATION_BAR_LOADING = "hideNavigationBarLoading";
const API_PAGE_SCROLL_TO = "pageScrollTo";
const PageScrollToProtocol = {
scrollTop: Number,
selector: String,
duration: Number
};
const PageScrollToOptions = {
formatArgs: {
duration: 300
}
};
const API_SHOW_ACTION_SHEET = "showActionSheet";
const API_SHOW_LOADING = "showLoading";
const API_SHOW_MODAL = "showModal";
const API_SHOW_TOAST = "showToast";
const SHOW_TOAST_ICON = [
"success",
"loading",
"none",
"error"
];
const ShowToastProtocol = {
title: String,
icon: String,
image: String,
duration: Number,
position: String,
mask: Boolean
};
const ShowToastOptions = {
formatArgs: {
title: "",
icon(type, params) {
params.icon = elemInArray(type, SHOW_TOAST_ICON);
},
image(value, params) {
if (value) {
params.image = getRealPath(value);
} else {
params.image = "";
}
},
duration: 1500,
mask: false
}
};
const API_START_PULL_DOWN_REFRESH = "startPullDownRefresh";
const API_STOP_PULL_DOWN_REFRESH = "stopPullDownRefresh";
const IndexProtocol = {
index: {
type: Number,
required: true
}
};
const IndexOptions = {
beforeInvoke() {
const pageMeta = getCurrentPageMeta();
if (pageMeta && !pageMeta.isTabBar) {
return "not TabBar page";
}
},
formatArgs: {
index(value) {
if (!__uniConfig.tabBar.list[value]) {
return "tabbar item not found";
}
}
}
};
const API_SET_TAB_BAR_ITEM = "setTabBarItem";
const SetTabBarItemProtocol = /* @__PURE__ */ extend(
{
text: String,
iconPath: String,
selectedIconPath: String,
pagePath: String
},
IndexProtocol
);
const SetTabBarItemOptions = {
beforeInvoke: IndexOptions.beforeInvoke,
formatArgs: /* @__PURE__ */ extend(
{
pagePath(value, params) {
if (value) {
params.pagePath = removeLeadingSlash(value);
}
}
},
IndexOptions.formatArgs
)
};
const API_SET_TAB_BAR_STYLE = "setTabBarStyle";
const SetTabBarStyleProtocol = {
color: String,
selectedColor: String,
backgroundColor: String,
backgroundImage: String,
backgroundRepeat: String,
borderStyle: String
};
const GRADIENT_RE = /^(linear|radial)-gradient\(.+?\);?$/;
const SetTabBarStyleOptions = {
beforeInvoke: IndexOptions.beforeInvoke,
formatArgs: {
backgroundImage(value, params) {
if (value && !GRADIENT_RE.test(value)) {
params.backgroundImage = getRealPath(value);
}
},
borderStyle(value, params) {
if (value) {
params.borderStyle = value === "white" ? "white" : "black";
}
}
}
};
const API_HIDE_TAB_BAR = "hideTabBar";
const HideTabBarProtocol = {
animation: Boolean
};
const API_SHOW_TAB_BAR = "showTabBar";
const ShowTabBarProtocol = HideTabBarProtocol;
const API_HIDE_TAB_BAR_RED_DOT = "hideTabBarRedDot";
const HideTabBarRedDotProtocol = IndexProtocol;
const HideTabBarRedDotOptions = IndexOptions;
const API_SHOW_TAB_BAR_RED_DOT = "showTabBarRedDot";
const ShowTabBarRedDotProtocol = IndexProtocol;
const ShowTabBarRedDotOptions = IndexOptions;
const API_REMOVE_TAB_BAR_BADGE = "removeTabBarBadge";
const RemoveTabBarBadgeProtocol = IndexProtocol;
const RemoveTabBarBadgeOptions = IndexOptions;
const API_SET_TAB_BAR_BADGE = "setTabBarBadge";
const SetTabBarBadgeProtocol = /* @__PURE__ */ extend(
{
text: {
type: String,
required: true
}
},
IndexProtocol
);
const SetTabBarBadgeOptions = {
beforeInvoke: IndexOptions.beforeInvoke,
formatArgs: /* @__PURE__ */ extend(
{
text(value, params) {
if (getLen(value) >= 4) {
params.text = "...";
}
}
},
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;
}
}
);
}
return;
}
function getFrameElement(doc) {
try {
return doc.defaultView && doc.defaultView.frameElement || null;
} catch (e2) {
return null;
}
}
var document2 = function(startDoc) {
var doc = startDoc;
var frame = getFrameElement(doc);
while (frame) {
doc = frame.ownerDocument;
frame = getFrameElement(doc);
}
return doc;
}(window.document);
var registry = [];
var crossOriginUpdater = null;
var crossOriginRect = null;
function IntersectionObserverEntry(entry) {
this.time = entry.time;
this.target = entry.target;
this.rootBounds = ensureDOMRect(entry.rootBounds);
this.boundingClientRect = ensureDOMRect(entry.boundingClientRect);
this.intersectionRect = ensureDOMRect(
entry.intersectionRect || getEmptyRect()
);
this.isIntersecting = !!entry.intersectionRect;
var targetRect = this.boundingClientRect;
var targetArea = targetRect.width * targetRect.height;
var intersectionRect = this.intersectionRect;
var intersectionArea = intersectionRect.width * intersectionRect.height;
if (targetArea) {
this.intersectionRatio = Number(
(intersectionArea / targetArea).toFixed(4)
);
} else {
this.intersectionRatio = this.isIntersecting ? 1 : 0;
}
}
function IntersectionObserver2(callback, opt_options) {
var options = opt_options || {};
if (typeof callback != "function") {
throw new Error("callback must be a function");
}
if (options.root && options.root.nodeType != 1 && options.root.nodeType != 9) {
throw new Error("root must be a Document or Element");
}
this._checkForIntersections = throttle2(
this._checkForIntersections.bind(this),
this.THROTTLE_TIMEOUT
);
this._callback = callback;
this._observationTargets = [];
this._queuedEntries = [];
this._rootMarginValues = this._parseRootMargin(options.rootMargin);
this.thresholds = this._initThresholds(options.threshold);
this.root = options.root || null;
this.rootMargin = this._rootMarginValues.map(function(margin) {
return margin.value + margin.unit;
}).join(" ");
this._monitoringDocuments = [];
this._monitoringUnsubscribes = [];
}
IntersectionObserver2.prototype.THROTTLE_TIMEOUT = 100;
IntersectionObserver2.prototype.POLL_INTERVAL = null;
IntersectionObserver2.prototype.USE_MUTATION_OBSERVER = true;
IntersectionObserver2._setupCrossOriginUpdater = function() {
if (!crossOriginUpdater) {
crossOriginUpdater = function(boundingClientRect, intersectionRect) {
if (!boundingClientRect || !intersectionRect) {
crossOriginRect = getEmptyRect();
} else {
crossOriginRect = convertFromParentRect(
boundingClientRect,
intersectionRect
);
}
registry.forEach(function(observer) {
observer._checkForIntersections();
});
};
}
return crossOriginUpdater;
};
IntersectionObserver2._resetCrossOriginUpdater = function() {
crossOriginUpdater = null;
crossOriginRect = null;
};
IntersectionObserver2.prototype.observe = function(target) {
var isTargetAlreadyObserved = this._observationTargets.some(function(item) {
return item.element == target;
});
if (isTargetAlreadyObserved) {
return;
}
if (!(target && target.nodeType == 1)) {
throw new Error("target must be an Element");
}
this._registerInstance();
this._observationTargets.push({ element: target, entry: null });
this._monitorIntersections(target.ownerDocument);
this._checkForIntersections();
};
IntersectionObserver2.prototype.unobserve = function(target) {
this._observationTargets = this._observationTargets.filter(function(item) {
return item.element != target;
});
this._unmonitorIntersections(target.ownerDocument);
if (this._observationTargets.length == 0) {
this._unregisterInstance();
}
};
IntersectionObserver2.prototype.disconnect = function() {
this._observationTargets = [];
this._unmonitorAllIntersections();
this._unregisterInstance();
};
IntersectionObserver2.prototype.takeRecords = function() {
var records = this._queuedEntries.slice();
this._queuedEntries = [];
return records;
};
IntersectionObserver2.prototype._initThresholds = function(opt_threshold) {
var threshold2 = opt_threshold || [0];
if (!Array.isArray(threshold2))
threshold2 = [threshold2];
return threshold2.sort().filter(function(t12, i, a) {
if (typeof t12 != "number" || isNaN(t12) || t12 < 0 || t12 > 1) {
throw new Error(
"threshold must be a number between 0 and 1 inclusively"
);
}
return t12 !== a[i - 1];
});
};
IntersectionObserver2.prototype._parseRootMargin = function(opt_rootMargin) {
var marginString = opt_rootMargin || "0px";
var margins = marginString.split(/\s+/).map(function(margin) {
var parts = /^(-?\d*\.?\d+)(px|%)$/.exec(margin);
if (!parts) {
throw new Error("rootMargin must be specified in pixels or percent");
}
return { value: parseFloat(parts[1]), unit: parts[2] };
});
margins[1] = margins[1] || margins[0];
margins[2] = margins[2] || margins[0];
margins[3] = margins[3] || margins[1];
return margins;
};
IntersectionObserver2.prototype._monitorIntersections = function(doc) {
var win = doc.defaultView;
if (!win) {
return;
}
if (this._monitoringDocuments.indexOf(doc) != -1) {
return;
}
var callback = this._checkForIntersections;
var monitoringInterval = null;
var domObserver = null;
if (this.POLL_INTERVAL) {
monitoringInterval = win.setInterval(callback, this.POLL_INTERVAL);
} else {
addEvent(win, "resize", callback, true);
addEvent(doc, "scroll", callback, true);
if (this.USE_MUTATION_OBSERVER && "MutationObserver" in win) {
domObserver = new win.MutationObserver(callback);
domObserver.observe(doc, {
attributes: true,
childList: true,
characterData: true,
subtree: true
});
}
}
this._monitoringDocuments.push(doc);
this._monitoringUnsubscribes.push(function() {
var win2 = doc.defaultView;
if (win2) {
if (monitoringInterval) {
win2.clearInterval(monitoringInterval);
}
removeEvent(win2, "resize", callback, true);
}
removeEvent(doc, "scroll", callback, true);
if (domObserver) {
domObserver.disconnect();
}
});
var rootDoc = this.root && (this.root.ownerDocument || this.root) || document2;
if (doc != rootDoc) {
var frame = getFrameElement(doc);
if (frame) {
this._monitorIntersections(frame.ownerDocument);
}
}
};
IntersectionObserver2.prototype._unmonitorIntersections = function(doc) {
var index2 = this._monitoringDocuments.indexOf(doc);
if (index2 == -1) {
return;
}
var rootDoc = this.root && (this.root.ownerDocument || this.root) || document2;
var hasDependentTargets = this._observationTargets.some(function(item) {
var itemDoc = item.element.ownerDocument;
if (itemDoc == doc) {
return true;
}
while (itemDoc && itemDoc != rootDoc) {
var frame2 = getFrameElement(itemDoc);
itemDoc = frame2 && frame2.ownerDocument;
if (itemDoc == doc) {
return true;
}
}
return false;
});
if (hasDependentTargets) {
return;
}
var unsubscribe = this._monitoringUnsubscribes[index2];
this._monitoringDocuments.splice(index2, 1);
this._monitoringUnsubscribes.splice(index2, 1);
unsubscribe();
if (doc != rootDoc) {
var frame = getFrameElement(doc);
if (frame) {
this._unmonitorIntersections(frame.ownerDocument);
}
}
};
IntersectionObserver2.prototype._unmonitorAllIntersections = function() {
var unsubscribes = this._monitoringUnsubscribes.slice(0);
this._monitoringDocuments.length = 0;
this._monitoringUnsubscribes.length = 0;
for (var i = 0; i < unsubscribes.length; i++) {
unsubscribes[i]();
}
};
IntersectionObserver2.prototype._checkForIntersections = function() {
if (!this.root && crossOriginUpdater && !crossOriginRect) {
return;
}
var rootIsInDom = this._rootIsInDom();
var rootRect = rootIsInDom ? this._getRootRect() : getEmptyRect();
this._observationTargets.forEach(function(item) {
var target = item.element;
var targetRect = getBoundingClientRect(target);
var rootContainsTarget = this._rootContainsTarget(target);
var oldEntry = item.entry;
var intersectionRect = rootIsInDom && rootContainsTarget && this._computeTargetAndRootIntersection(target, targetRect, rootRect);
var rootBounds = null;
if (!this._rootContainsTarget(target)) {
rootBounds = getEmptyRect();
} else if (!crossOriginUpdater || this.root) {
rootBounds = rootRect;
}
var newEntry = item.entry = new IntersectionObserverEntry({
time: now(),
target,
boundingClientRect: targetRect,
rootBounds,
intersectionRect
});
if (!oldEntry) {
this._queuedEntries.push(newEntry);
} else if (rootIsInDom && rootContainsTarget) {
if (this._hasCrossedThreshold(oldEntry, newEntry)) {
this._queuedEntries.push(newEntry);
}
} else {
if (oldEntry && oldEntry.isIntersecting) {
this._queuedEntries.push(newEntry);
}
}
}, this);
if (this._queuedEntries.length) {
this._callback(this.takeRecords(), this);
}
};
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 == /* DOCUMENT */
9) {
atRoot = true;
if (parent == this.root || parent == document2) {
if (crossOriginUpdater && !this.root) {
if (!crossOriginRect || crossOriginRect.width == 0 && crossOriginRect.height == 0) {
parent = null;
parentRect = null;
intersectionRect = null;
} else {
parentRect = crossOriginRect;
}
} else {
parentRect = rootRect;
}
} else {
var frame = getParentNode(parent);
var frameRect = frame && getBoundingClientRect(frame);
var frameIntersect = frame && this._computeTargetAndRootIntersection(frame, frameRect, rootRect);
if (frameRect && frameIntersect) {
parent = frame;
parentRect = convertFromParentRect(frameRect, frameIntersect);
} else {
parent = null;
intersectionRect = null;
}
}
} else {
var doc = parent.ownerDocument;
if (parent != doc.body && parent != doc.documentElement && parentComputedStyle.overflow != "visible") {
parentRect = getBoundingClientRect(parent);
}
}
if (parentRect) {
intersectionRect = computeRectIntersection(parentRect, intersectionRect);
}
if (!intersectionRect)
break;
parent = parent && getParentNode(parent);
}
return intersectionRect;
};
IntersectionObserver2.prototype._getRootRect = function() {
var rootRect;
if (this.root && !isDoc(this.root)) {
rootRect = getBoundingClientRect(this.root);
} else {
var doc = isDoc(this.root) ? this.root : document2;
var html = doc.documentElement;
var body = doc.body;
rootRect = {
top: 0,
left: 0,
right: html.clientWidth || body.clientWidth,
width: html.clientWidth || body.clientWidth,
bottom: html.clientHeight || body.clientHeight,
height: html.clientHeight || body.clientHeight
};
}
return this._expandRectByRootMargin(rootRect);
};
IntersectionObserver2.prototype._expandRectByRootMargin = function(rect) {
var margins = this._rootMarginValues.map(function(margin, i) {
return margin.unit == "px" ? margin.value : margin.value * (i % 2 ? rect.width : rect.height) / 100;
});
var newRect = {
top: rect.top - margins[0],
right: rect.right + margins[1],
bottom: rect.bottom + margins[2],
left: rect.left - margins[3]
};
newRect.width = newRect.right - newRect.left;
newRect.height = newRect.bottom - newRect.top;
return newRect;
};
IntersectionObserver2.prototype._hasCrossedThreshold = function(oldEntry, newEntry) {
var oldRatio = oldEntry && oldEntry.isIntersecting ? oldEntry.intersectionRatio || 0 : -1;
var newRatio = newEntry.isIntersecting ? newEntry.intersectionRatio || 0 : -1;
if (oldRatio === newRatio)
return;
for (var i = 0; i < this.thresholds.length; i++) {
var threshold2 = this.thresholds[i];
if (threshold2 == oldRatio || threshold2 == newRatio || threshold2 < oldRatio !== threshold2 < newRatio) {
return true;
}
}
};
IntersectionObserver2.prototype._rootIsInDom = function() {
return !this.root || containsDeep(document2, this.root);
};
IntersectionObserver2.prototype._rootContainsTarget = function(target) {
var rootDoc = this.root && (this.root.ownerDocument || this.root) || document2;
return containsDeep(rootDoc, target) && (!this.root || rootDoc == target.ownerDocument);
};
IntersectionObserver2.prototype._registerInstance = function() {
if (registry.indexOf(this) < 0) {
registry.push(this);
}
};
IntersectionObserver2.prototype._unregisterInstance = function() {
var index2 = registry.indexOf(this);
if (index2 != -1)
registry.splice(index2, 1);
};
function now() {
return window.performance && performance.now && performance.now();
}
function throttle2(fn, timeout) {
var timer = null;
return function() {
if (!timer) {
timer = setTimeout(function() {
fn();
timer = null;
}, timeout);
}
};
}
function addEvent(node, event, fn, opt_useCapture) {
if (typeof node.addEventListener == "function") {
node.addEventListener(event, fn, opt_useCapture);
} 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);
} else if (typeof node.detatchEvent == "function") {
node.detatchEvent("on" + event, fn);
}
}
function computeRectIntersection(rect1, rect2) {
var top = Math.max(rect1.top, rect2.top);
var bottom = Math.min(rect1.bottom, rect2.bottom);
var left = Math.max(rect1.left, rect2.left);
var right = Math.min(rect1.right, rect2.right);
var width = right - left;
var height = bottom - top;
return width >= 0 && height >= 0 && {
top,
bottom,
left,
right,
width,
height
} || null;
}
function getBoundingClientRect(el) {
var rect;
try {
rect = el.getBoundingClientRect();
} catch (err) {
}
if (!rect)
return getEmptyRect();
if (!(rect.width && rect.height)) {
rect = {
top: rect.top,
right: rect.right,
bottom: rect.bottom,
left: rect.left,
width: rect.right - rect.left,
height: rect.bottom - rect.top
};
}
return rect;
}
function 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
};
}
function convertFromParentRect(parentBoundingRect, parentIntersectionRect) {
var top = parentIntersectionRect.top - parentBoundingRect.top;
var left = parentIntersectionRect.left - parentBoundingRect.left;
return {
top,
left,
height: parentIntersectionRect.height,
width: parentIntersectionRect.width,
bottom: top + parentIntersectionRect.height,
right: left + parentIntersectionRect.width
};
}
function containsDeep(parent, child2) {
var node = child2;
while (node) {
if (node == parent)
return true;
node = getParentNode(node);
}
return false;
}
function getParentNode(node) {
var parent = node.parentNode;
if (node.nodeType == /* DOCUMENT */
9 && node != document2) {
return getFrameElement(node);
}
if (parent && parent.assignedSlot) {
parent = parent.assignedSlot.parentNode;
}
if (parent && parent.nodeType == 11 && parent.host) {
return parent.host;
}
return parent;
}
function isDoc(node) {
return node && node.nodeType === 9;
}
window.IntersectionObserver = IntersectionObserver2;
window.IntersectionObserverEntry = IntersectionObserverEntry;
};
function normalizeRect(rect) {
const { bottom, height, left, right, top, width } = rect || {};
return {
bottom,
height,
left,
right,
top,
width
};
}
function createDatasetSnapshot$1(el) {
const dataset = getCustomDataset(el);
return createUniDOMStringMap(dataset);
}
function rectifyIntersectionRatio(entrie) {
const {
intersectionRatio,
boundingClientRect: { height: overAllHeight, width: overAllWidth },
intersectionRect: { height: intersectionHeight, width: intersectionWidth }
} = entrie;
if (intersectionRatio !== 0)
return intersectionRatio;
return intersectionHeight === overAllHeight ? intersectionWidth / overAllWidth : intersectionHeight / overAllHeight;
}
function requestComponentObserver($el, options, callback) {
initIntersectionObserverPolyfill();
const root = options.relativeToSelector ? $el.querySelector(options.relativeToSelector) : null;
const intersectionObserver = new IntersectionObserver(
(entries2) => {
entries2.forEach((entrie) => {
callback({
intersectionRatio: rectifyIntersectionRatio(entrie),
intersectionRect: normalizeRect(entrie.intersectionRect),
boundingClientRect: normalizeRect(entrie.boundingClientRect),
relativeRect: normalizeRect(entrie.rootBounds),
time: Date.now(),
dataset: createDatasetSnapshot$1(entrie.target),
id: entrie.target.id
});
});
},
{
root,
rootMargin: options.rootMargin,
threshold: options.thresholds
}
);
if (options.observeAll) {
intersectionObserver.USE_MUTATION_OBSERVER = true;
const nodeList = $el.querySelectorAll(options.selector);
for (let i = 0; i < nodeList.length; i++) {
intersectionObserver.observe(nodeList[i]);
}
} else {
intersectionObserver.USE_MUTATION_OBSERVER = false;
const el = $el.matches(options.selector) ? $el : $el.querySelector(options.selector);
if (!el) {
console.warn(
`Node ${options.selector} is not found. Intersection observer will not trigger.`
);
} else {
intersectionObserver.observe(el);
}
}
return intersectionObserver;
}
function removeNonTabBarPages(targetPageId) {
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 = targetPageId !== void 0 && getPage$BasePage(page).id === targetPageId;
}
}
if (curTabBarPageVm.$.__isTabBar && (targetPageId === void 0 || getPage$BasePage(curTabBarPageVm).id !== targetPageId)) {
curTabBarPageVm.$.__isVisible = false;
invokeHook(curTabBarPageVm, ON_HIDE);
}
}
function isSamePage(url, $page) {
return url === $page.fullPath || url === "/" && $page.meta.isEntry;
}
function getTabBarPageId(url) {
const pages = getCurrentPagesMap().values();
for (const page of pages) {
const $page = getPage$BasePage(page);
if (isSamePage(url, $page)) {
page.$.__isActive = true;
return $page.id;
}
}
}
const switchTab = /* @__PURE__ */ defineAsyncApi(
API_SWITCH_TAB,
// @ts-expect-error
({ url, tabBarText, isAutomatedTesting }, { resolve, reject }) => {
if (!entryPageState.handledBeforeEntryPageRoutes) {
switchTabPagesBeforeEntryPages.push({
args: { type: API_SWITCH_TAB, url, tabBarText, isAutomatedTesting },
resolve,
reject
});
return;
}
return navigate(
{ type: API_SWITCH_TAB, url, tabBarText, isAutomatedTesting },
void 0
).then(resolve).catch(reject);
},
SwitchTabProtocol,
SwitchTabOptions
);
function removeLastPage() {
var _a;
const page = (_a = getCurrentPage()) == null ? void 0 : _a.vm;
if (!page) {
return;
}
const $page = getPage$BasePage(page);
removePage(normalizeRouteKey($page.path, $page.id));
}
const redirectTo = /* @__PURE__ */ defineAsyncApi(
API_REDIRECT_TO,
// @ts-expect-error
({ url, isAutomatedTesting }, { resolve, reject }) => {
if (!entryPageState.handledBeforeEntryPageRoutes) {
redirectToPagesBeforeEntryPages.push({
args: { type: API_REDIRECT_TO, url, isAutomatedTesting },
resolve,
reject
});
return;
}
return navigate({ type: API_REDIRECT_TO, url, isAutomatedTesting }).then(resolve).catch(reject);
},
RedirectToProtocol,
RedirectToOptions
);
function removeAllPages() {
const keys = getCurrentPagesMap().keys();
for (const routeKey of keys) {
removePage(routeKey);
}
}
const reLaunch = /* @__PURE__ */ defineAsyncApi(
API_RE_LAUNCH,
// @ts-expect-error
({ url, isAutomatedTesting }, { resolve, reject }) => {
if (!entryPageState.handledBeforeEntryPageRoutes) {
reLaunchPagesBeforeEntryPages.push({
args: { type: API_RE_LAUNCH, url, isAutomatedTesting },
resolve,
reject
});
return;
}
return navigate({ type: API_RE_LAUNCH, url, isAutomatedTesting }).then(resolve).catch(reject);
},
ReLaunchProtocol,
ReLaunchOptions
);
function normalizeAppRoutePath(path) {
const route = getRouteOptions(path, true);
const pagePath = route == null ? void 0 : route.meta.route;
return typeof pagePath === "string" ? pagePath : removeLeadingSlash((route == null ? void 0 : route.path) || path);
}
function normalizeRewriteRoute({ url, preserveQuery }, event) {
if (preserveQuery) {
url = parseUrl(url).path + stringifyQuery$1(event.query);
}
const params = { url, openType: event.openType };
const errMsg = createNormalizeUrl(event.openType, {
skipNavigatorLock: true
})(url, params);
if (errMsg) {
return errMsg;
}
const { path, query } = parseUrl(params.url);
return {
url: params.url,
path: normalizeAppRoutePath(path),
query: decodedQuery(query),
notFound: false
};
}
const appRouteRuntime = createAppRouteRuntime({ normalizeRewriteRoute });
const pendingProgrammaticRoutes = [];
const routeTransactions = /* @__PURE__ */ new WeakMap();
let pendingHistoryRoute;
let appRouteStarted = false;
let launchExecutor;
let resolveLaunchExecutor;
const launchExecutorReady = new Promise((resolve) => {
resolveLaunchExecutor = resolve;
});
let singlePageAppRouteContext;
const onAppRoute = appRouteRuntime.onAppRoute;
const offAppRoute = appRouteRuntime.offAppRoute;
const onBeforeAppRoute = appRouteRuntime.onBeforeAppRoute;
const offBeforeAppRoute = appRouteRuntime.offBeforeAppRoute;
const rewriteRoute = appRouteRuntime.rewriteRoute;
function createAppRouteContext(path, query, openType, notFound = false) {
return appRouteRuntime.createAppRouteContext({
path: normalizeAppRoutePath(path),
query: decodedQuery(query),
openType,
notFound
});
}
function resolveAppRoute(url, openType, notFound = false) {
let routeUrl = url;
let routeNotFound = notFound;
let rewriteCount = 0;
while (true) {
const { path, query } = parseUrl(routeUrl);
const context = createAppRouteContext(path, query, openType, routeNotFound);
context.rewriteCount = rewriteCount;
const rewrite = appRouteRuntime.dispatchBeforeAppRoute(context);
if (!rewrite) {
return { url: routeUrl, context };
}
routeUrl = rewrite.url;
routeNotFound = rewrite.notFound;
rewriteCount++;
}
}
function dispatchAppRoute(context) {
const event = context.event;
if (event.notFound) {
invokeHook(getApp().vm, ON_PAGE_NOT_FOUND, {
path: event.path,
query: Object.assign({}, event.query),
isEntryPage: event.openType === "appLaunch"
});
}
appRouteRuntime.dispatchAppRoute(context);
}
function createWebAppRouteTransaction(finalFullPath, openType, context) {
return {
finalFullPath,
openType,
context
};
}
function queueWebAppRouteTransaction(transaction) {
pendingProgrammaticRoutes.push(transaction);
}
function discardWebAppRouteTransaction(transaction) {
transaction.cancelled = true;
const index2 = pendingProgrammaticRoutes.indexOf(transaction);
if (index2 !== -1) {
pendingProgrammaticRoutes.splice(index2, 1);
}
}
function takePendingProgrammaticRoute(to) {
const redirectedFrom = getOriginalRoute(to.redirectedFrom);
for (let index2 = pendingProgrammaticRoutes.length - 1; index2 >= 0; index2--) {
const transaction = pendingProgrammaticRoutes[index2];
if (!transaction.cancelled && (transaction.finalFullPath === to.fullPath || transaction.finalFullPath === (redirectedFrom == null ? void 0 : redirectedFrom.fullPath))) {
return pendingProgrammaticRoutes.splice(index2, 1)[0];
}
}
}
function takePendingHistoryRoute(to) {
const redirectedFrom = getOriginalRoute(to.redirectedFrom);
if (pendingHistoryRoute && (pendingHistoryRoute.fullPath === to.fullPath || pendingHistoryRoute.fullPath === (redirectedFrom == null ? void 0 : redirectedFrom.fullPath))) {
const route = pendingHistoryRoute;
pendingHistoryRoute = void 0;
return route;
}
}
function getOriginalRoute(route) {
while (route == null ? void 0 : route.redirectedFrom) {
route = route.redirectedFrom;
}
return route;
}
function getRouteUrl(route) {
return route.fullPath || route.path;
}
function resolveFullPath(router2, url) {
const { path, query } = parseUrl(url);
return router2.resolve({ path, query }).fullPath;
}
function toRouteLocation(url) {
const { path, query } = parseUrl(url);
return { path, query };
}
function bindRouteTransaction(route, transaction) {
routeTransactions.set(route, transaction);
const originalRoute = getOriginalRoute(route.redirectedFrom);
if (originalRoute) {
routeTransactions.set(originalRoute, transaction);
}
}
function findRouteTransaction(route) {
const transaction = routeTransactions.get(route) || (getOriginalRoute(route.redirectedFrom) ? routeTransactions.get(getOriginalRoute(route.redirectedFrom)) : void 0);
return (transaction == null ? void 0 : transaction.cancelled) ? void 0 : transaction;
}
function replaceTransactionRoute(router2, transaction, route) {
const routeUrl = getRouteUrl(route);
const resolved = resolveAppRoute(
routeUrl,
transaction.openType,
route.matched.length === 0
);
transaction.finalFullPath = resolveFullPath(router2, resolved.url);
transaction.context = resolved.context;
return resolved;
}
function bindOrRedirectTransaction(router2, to, transaction) {
if (transaction.finalFullPath !== to.fullPath) {
const resolved = replaceTransactionRoute(router2, transaction, to);
if (transaction.finalFullPath !== to.fullPath) {
pendingProgrammaticRoutes.push(transaction);
return toRouteLocation(resolved.url);
}
}
bindRouteTransaction(to, transaction);
}
async function createLaunchTransaction(router2, to) {
await launchExecutorReady;
const originalRoute = getOriginalRoute(to) || to;
const resolved = await launchExecutor(originalRoute);
const sourceFullPath = originalRoute.fullPath;
const transaction = createWebAppRouteTransaction(
resolveFullPath(router2, resolved.url),
"appLaunch",
resolved.context
);
if (transaction.finalFullPath !== sourceFullPath) {
pendingProgrammaticRoutes.push(transaction);
return {
transaction,
redirect: toRouteLocation(resolved.url)
};
}
return { transaction };
}
function registerWebAppRouteLaunchExecutor(executor) {
launchExecutor = executor;
resolveLaunchExecutor == null ? void 0 : resolveLaunchExecutor();
resolveLaunchExecutor = void 0;
}
function setSinglePageAppRoute(resolved, originalUrl) {
singlePageAppRouteContext = resolved.context;
if (resolved.url === originalUrl) {
return;
}
const queryIndex = resolved.url.indexOf("?");
const search = queryIndex === -1 ? "" : resolved.url.slice(queryIndex);
const url = location.pathname + search + location.hash;
history.replaceState(history.state, "", url);
}
function dispatchWebAppRoute(route) {
let context;
if (route) {
const transaction = findRouteTransaction(route);
if (transaction && !transaction.cancelled) {
context = transaction.context;
routeTransactions.delete(route);
const originalRoute = getOriginalRoute(route.redirectedFrom);
if (originalRoute) {
routeTransactions.delete(originalRoute);
}
}
} else {
context = singlePageAppRouteContext;
singlePageAppRouteContext = void 0;
}
if (context) {
dispatchAppRoute(context);
}
}
function setWebAppRouteHistoryDirection(fullPath, direction2, delta = 0) {
pendingHistoryRoute = {
fullPath,
openType: direction2 === "back" ? API_NAVIGATE_BACK : API_NAVIGATE_TO,
delta: Math.abs(delta)
};
}
function initWebAppRouteListener(router2, { onRouteConfirmed, onMissingRoute }) {
router2.beforeEach(async (to) => {
const route = to;
if (!appRouteStarted) {
appRouteStarted = true;
const launch = await createLaunchTransaction(router2, route);
if (launch.redirect) {
return launch.redirect;
}
return bindOrRedirectTransaction(router2, route, launch.transaction);
}
let transaction = takePendingProgrammaticRoute(route);
if (!transaction) {
const historyRoute = takePendingHistoryRoute(route);
if (historyRoute) {
const originalRoute = getOriginalRoute(route.redirectedFrom) || route;
const resolved = resolveAppRoute(
historyRoute.fullPath,
historyRoute.openType,
originalRoute.matched.length === 0
);
transaction = createWebAppRouteTransaction(
resolveFullPath(router2, resolved.url),
historyRoute.openType,
resolved.context
);
transaction.delta = historyRoute.delta;
if (transaction.finalFullPath !== historyRoute.fullPath) {
pendingProgrammaticRoutes.push(transaction);
return toRouteLocation(resolved.url);
}
}
}
if (!transaction) {
transaction = findRouteTransaction(route);
}
if (!transaction) {
const originalRoute = getOriginalRoute(route.redirectedFrom) || route;
const resolved = resolveAppRoute(
getRouteUrl(originalRoute),
API_NAVIGATE_TO,
originalRoute.matched.length === 0
);
transaction = createWebAppRouteTransaction(
resolveFullPath(router2, resolved.url),
API_NAVIGATE_TO,
resolved.context
);
if (transaction.finalFullPath !== originalRoute.fullPath) {
pendingProgrammaticRoutes.push(transaction);
return toRouteLocation(resolved.url);
}
}
return bindOrRedirectTransaction(router2, route, transaction);
});
router2.afterEach((to, _from, failure) => {
var _a;
const route = to;
const transaction = findRouteTransaction(route);
if (!transaction) {
return;
}
if (failure) {
discardWebAppRouteTransaction(transaction);
routeTransactions.delete(route);
return;
}
if (!transaction.cleaned) {
transaction.cleaned = true;
onRouteConfirmed(transaction);
}
if (!transaction.context) {
routeTransactions.delete(route);
return;
}
if ((_a = transaction.context) == null ? void 0 : _a.event.notFound) {
dispatchWebAppRoute(route);
onMissingRoute(transaction);
}
});
router2.onError((_error, to) => {
if (!to) {
return;
}
const route = to;
const transaction = findRouteTransaction(route);
if (transaction) {
discardWebAppRouteTransaction(transaction);
routeTransactions.delete(route);
}
});
}
function isCurrentTabBarPage(url) {
const pages = getCurrentBasePages();
const currentPage = pages[pages.length - 1];
if (!(currentPage == null ? void 0 : currentPage.$.__isTabBar)) {
return false;
}
const path = parseUrl(url).path;
const $page = getPage$BasePage(currentPage);
return path === $page.path || path === "/" && $page.meta.isEntry;
}
function findTabBarPageId(url) {
const path = parseUrl(url).path;
const pages = getCurrentPagesMap().values();
for (const page of pages) {
const $page = getPage$BasePage(page);
if (path === $page.path || path === "/" && $page.meta.isEntry) {
return $page.id;
}
}
}
function navigate({ type, url, tabBarText, events, isAutomatedTesting }, __id__) {
if (process.env.NODE_ENV !== "production" && !__UNI_FEATURE_PAGES__) {
console.warn(
"当前项目为单页面工程,不能执行页面跳转api。如果需进行页面跳转, 需要在pages.json文件的pages字段中配置多个页面,然后重新运行。"
);
}
let router2;
router2 = getRouterInstance();
return new Promise((resolve, reject) => {
let routeUrl = url;
let transaction;
{
const shouldDispatchAppRoute = type !== "switchTab" || !isCurrentTabBarPage(url);
const appRoute = shouldDispatchAppRoute ? resolveAppRoute(url, type) : void 0;
routeUrl = (appRoute == null ? void 0 : appRoute.url) || url;
const { path: path2, query: query2 } = parseUrl(routeUrl);
transaction = createWebAppRouteTransaction(
router2.resolve({ path: path2, query: query2 }).fullPath,
type,
appRoute == null ? void 0 : appRoute.context
);
}
const { path, query } = parseUrl(routeUrl);
const tabBarPageId = type === "switchTab" ? findTabBarPageId(routeUrl) : __id__;
const state = createPageState(type, tabBarPageId);
if (transaction) {
transaction.pageId = state.__id__;
queueWebAppRouteTransaction(transaction);
}
const navigation = router2[type === "navigateTo" ? "push" : "replace"]({
path,
query,
state,
force: true
}).then((failure) => {
if (isNavigationFailure(failure)) {
transaction && discardWebAppRouteTransaction(transaction);
return reject(failure.message);
}
if (type === "switchTab") {
const finalTabBarText = routeUrl === url ? tabBarText : router2.resolve({ path, query }).meta.tabBarText;
router2.currentRoute.value.meta.tabBarText = finalTabBarText;
}
if (type === "navigateTo") {
const meta = router2.currentRoute.value.meta;
if (!meta.eventChannel) {
meta.eventChannel = new EventChannel(state.__id__, events);
} else if (events) {
Object.keys(events).forEach((eventName) => {
meta.eventChannel._addListener(
eventName,
"on",
events[eventName]
);
});
meta.eventChannel._clearCache();
}
return isAutomatedTesting ? resolve({
__id__: state.__id__
}) : resolve({
eventChannel: meta.eventChannel
});
}
return isAutomatedTesting ? resolve({ __id__: state.__id__ }) : resolve();
});
{
navigation.catch((error) => {
transaction && discardWebAppRouteTransaction(transaction);
reject(error instanceof Error ? error.message : error);
});
}
});
}
function handleBeforeEntryPageRoutes() {
if (entryPageState.handledBeforeEntryPageRoutes) {
return;
}
entryPageState.handledBeforeEntryPageRoutes = true;
const navigateToPages = [...navigateToPagesBeforeEntryPages];
navigateToPagesBeforeEntryPages.length = 0;
navigateToPages.forEach(
({ args, resolve, reject }) => (
// @ts-expect-error
navigate(args).then(resolve).catch(reject)
)
);
const switchTabPages = [...switchTabPagesBeforeEntryPages];
switchTabPagesBeforeEntryPages.length = 0;
switchTabPages.forEach(({ args, resolve, reject }) => {
navigate(args, void 0).then(resolve).catch(reject);
});
const redirectToPages = [...redirectToPagesBeforeEntryPages];
redirectToPagesBeforeEntryPages.length = 0;
redirectToPages.forEach(({ args, resolve, reject }) => {
navigate(args).then(resolve).catch(reject);
});
const reLaunchPages = [...reLaunchPagesBeforeEntryPages];
reLaunchPagesBeforeEntryPages.length = 0;
reLaunchPages.forEach(({ args, resolve, reject }) => {
navigate(args).then(resolve).catch(reject);
});
}
const ua = navigator.userAgent;
const isAndroid = /* @__PURE__ */ /android/i.test(ua);
const isIOS = /* @__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;
const isHarmony = /OpenHarmony/i.test(ua);
const isHarmony2in1 = isHarmony && /PC/i.test(ua);
const isHarmonyTablet = isHarmony && /Tablet/i.test(ua);
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() {
const screenFix = getScreenFix();
if (screenFix) {
const screenWidth = getScreenWidth(screenFix, isLandscape(screenFix));
return Math.min(
window.innerWidth,
document.documentElement.clientWidth,
screenWidth
) || screenWidth;
} else {
return Math.min(window.innerWidth, document.documentElement.clientWidth);
}
}
function getBaseSystemInfo() {
const windowWidth = getWindowWidth();
return {
platform: isIOS ? "ios" : "other",
pixelRatio: window.devicePixelRatio,
windowWidth
};
}
function IEVersion() {
const userAgent = navigator.userAgent;
const isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1;
const isEdge = userAgent.indexOf("Edge") > -1 && !isIE;
const isIE11 = userAgent.indexOf("Trident") > -1 && userAgent.indexOf("rv:11.0") > -1;
if (isIE) {
const reIE = new RegExp("MSIE (\\d+\\.\\d+);");
reIE.test(userAgent);
const fIEVersion = parseFloat(RegExp.$1);
if (fIEVersion > 6) {
return fIEVersion;
} else {
return 6;
}
} else if (isEdge) {
return -1;
} else if (isIE11) {
return 11;
} else {
return -1;
}
}
function getTheme() {
if (__uniConfig.darkmode == null || __uniConfig.darkmode === false)
return void 0;
if (__uniConfig.darkmode !== true)
return isString(__uniConfig.darkmode) ? __uniConfig.darkmode : "light";
try {
return window.matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark";
} catch (error) {
return "light";
}
}
function getBrowserInfo() {
let osname;
let osversion = "0";
let model;
let deviceType = "phone";
let platform = "";
let deviceBrand;
const language = navigator.language;
if (isIOS) {
deviceBrand = "iPhone";
osname = "iOS";
const osversionFind = ua.match(/OS\s([\w_]+)\slike/);
if (osversionFind) {
osversion = osversionFind[1].replace(/_/g, ".");
}
const iosVersion = osversion.split(".")[0];
if (Number(iosVersion) >= 18) {
const versionMatch = ua.match(/Version\/([\d\.]+)/);
if (versionMatch) {
osversion = versionMatch[1];
}
}
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 i = 0; i < infos.length; i++) {
const info = infos[i];
if (info.indexOf("Build") > 0) {
model = info.split("Build")[0].trim();
break;
}
let other;
for (let o = 0; o < otherInfo.length; o++) {
if (otherInfo[o].test(info)) {
other = true;
break;
}
}
if (!other) {
model = info.trim();
break;
}
}
} else if (isIPadOS) {
deviceBrand = "iPad";
model = "iPad";
osname = "iOS";
deviceType = "pad";
osversion = isFunction(window.BigInt) ? "14.0" : "13.0";
if (parseInt(osversion) === 14) {
const versionMatched = ua.match(/Version\/(\S*)\b/);
if (versionMatched) {
osversion = versionMatched[1];
}
}
} else if (isWindows || isMac || isLinux) {
model = "PC";
osname = "PC";
deviceType = "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 = "macos";
platform = "mac";
const _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";
const _osversion = osversionFind && osversionFind.match(/Linux (.*)/) || "";
if (_osversion) {
osversion = _osversion[1];
if (osversion.indexOf(";") !== -1) {
osversion = osversion.split(";")[0];
}
}
}
} else if (isHarmony) {
deviceBrand = "HUAWEI";
osname = "harmonyos";
deviceType = isHarmony2in1 ? "pc" : isHarmonyTablet ? "pad" : "phone";
const osversionFind = ua.match(/OpenHarmony\s([\d\.]+)/);
if (osversionFind) {
osversion = osversionFind[1];
}
model = void 0;
} else {
osname = "Other";
osversion = "0";
deviceType = "unknown";
}
const system = `${osname} ${osversion}`;
if (!platform)
platform = osname.toLowerCase();
let browserName = "";
let browserVersion = String(IEVersion());
if (browserVersion !== "-1") {
browserName = "IE";
} else {
const browseVendors = ["Version", "Firefox", "Chrome", "Edge{0,1}"];
const vendors = ["Safari", "Firefox", "Chrome", "Edge"];
for (let index2 = 0; index2 < browseVendors.length; index2++) {
const vendor = browseVendors[index2];
const reg = new RegExp(`(${vendor})/(\\S*)\\b`);
if (reg.test(ua)) {
browserName = vendors[index2];
browserVersion = ua.match(reg)[2];
}
}
}
let deviceOrientation = "portrait";
if (window.matchMedia) {
try {
if (window.matchMedia("(orientation:landscape)").matches) {
deviceOrientation = "landscape";
}
} catch {
}
}
if (deviceOrientation === "portrait" && window.screen.orientation !== void 0) {
deviceOrientation = [90, 270].includes(window.screen.orientation.angle) ? "landscape" : "portrait";
}
if (deviceOrientation === "portrait" && window.orientation != null) {
deviceOrientation = Math.abs(window.orientation) === 90 ? "landscape" : "portrait";
}
return {
deviceBrand,
brand: deviceBrand,
deviceModel: model,
deviceOrientation,
model,
system,
platform,
browserName: browserName.toLocaleLowerCase(),
browserVersion,
language,
deviceType,
ua,
osname,
osversion,
theme: getTheme()
};
}
function onThemeChange$2(callback) {
if (__uniConfig.darkmode) {
UniServiceJSBridge.on(ON_THEME_CHANGE, callback);
}
}
function parseTheme(pageStyle) {
let parsedStyle = {};
if (__uniConfig.darkmode) {
parsedStyle = normalizeStyles(
pageStyle,
__uniConfig.themeConfig,
getTheme()
);
}
return __uniConfig.darkmode ? parsedStyle : pageStyle;
}
function useTheme(pageStyle, onThemeChangeCallback) {
const isReactivity = isReactive(pageStyle);
const reactivePageStyle = isReactivity ? reactive(parseTheme(pageStyle)) : parseTheme(pageStyle);
if (__uniConfig.darkmode && isReactivity) {
watch(pageStyle, (value) => {
const _pageStyle = parseTheme(value);
for (const key in _pageStyle) {
reactivePageStyle[key] = _pageStyle[key];
}
});
}
onThemeChangeCallback && onThemeChange$2(onThemeChangeCallback);
return reactivePageStyle;
}
let _tabBar;
let _tabBarStyle;
function updateTabBarStyle() {
const tabBar = _tabBarStyle;
const tabBarConfig = _tabBar;
if (!tabBar || !tabBarConfig) {
return;
}
const tabBarStyle = parseTheme(tabBarConfig);
tabBar.backgroundColor = tabBarStyle.backgroundColor;
tabBar.borderStyle = tabBarStyle.borderStyle;
tabBar.color = tabBarStyle.color;
tabBar.selectedColor = tabBarStyle.selectedColor;
tabBar.blurEffect = tabBarStyle.blurEffect;
tabBar.midButton = tabBarStyle.midButton;
if (tabBarStyle.list && tabBarStyle.list.length) {
tabBarStyle.list.forEach((item, index2) => {
tabBar.list[index2].iconPath = item.iconPath;
tabBar.list[index2].selectedIconPath = item.selectedIconPath;
});
}
}
function useTabBar() {
if (!_tabBarStyle) {
const tabBar = __uniConfig.tabBar;
if (!tabBar) {
return;
}
_tabBar = reactive(initTabBarI18n(tabBar));
_tabBarStyle = useTheme(_tabBar, updateTabBarStyle);
}
return _tabBarStyle;
}
function cssSupports(css) {
const supports = window.CSS && window.CSS.supports;
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 = /* @__PURE__ */ defineSyncApi(
API_CAN_I_USE,
(schema) => {
if (hasOwn(SCHEMA_CSS, schema)) {
return SCHEMA_CSS[schema];
}
if (hasOwn(uni, schema)) {
return true;
}
return false;
},
CanIUseProtocol
);
const envMethod = /* @__PURE__ */ (() => cssEnv ? "env" : cssConstant ? "constant" : "")();
function updateCurPageCssVar(pageMeta) {
let windowTopValue = 0;
let windowBottomValue = 0;
if (__UNI_FEATURE_NAVIGATIONBAR__ && pageMeta.navigationBar.style !== "custom" && ["default", "float"].indexOf(pageMeta.navigationBar.type) > -1) {
windowTopValue = NAVBAR_HEIGHT;
}
if (__UNI_FEATURE_TABBAR__ && pageMeta.isTabBar) {
const tabBar = useTabBar();
tabBar.shown && (windowBottomValue = parseInt(tabBar.height));
}
updatePageCssVar({
"--window-top": normalizeWindowTop(windowTopValue),
"--window-bottom": normalizeWindowBottom(windowBottomValue)
});
}
function normalizeWindowTop(windowTop) {
return envMethod ? `calc(${windowTop}px + ${envMethod}(safe-area-inset-top))` : `${windowTop}px`;
}
function normalizeWindowBottom(windowBottom) {
return envMethod ? `calc(${windowBottom}px + ${envMethod}(safe-area-inset-bottom))` : `${windowBottom}px`;
}
const launchOptions = /* @__PURE__ */ createLaunchOptions();
const enterOptions = /* @__PURE__ */ createLaunchOptions();
function getEnterOptions() {
return extend({}, enterOptions);
}
function getLaunchOptions() {
return extend({}, launchOptions);
}
function initLaunchOptions({
path,
query
}) {
extend(launchOptions, {
path,
query
});
extend(enterOptions, launchOptions);
return extend({}, launchOptions);
}
function getScopeId(instance2) {
return instance2.type.__scopeId;
}
const SAFE_AREA_INSET_PROPERTY_PREFIX = "--uni-safe-area-inset-";
function getSafeAreaInset(style, position) {
const value = parseFloat(
style.getPropertyValue(`${SAFE_AREA_INSET_PROPERTY_PREFIX}${position}`)
);
return isNaN(value) ? safeAreaInsets$1[position] : value;
}
function getPageWrapperInfo(pageBody) {
const pageWrapper = pageBody || document.querySelector("uni-page-wrapper");
const pageWrapperRect = pageWrapper.getBoundingClientRect();
const bodyRect = document.body.getBoundingClientRect();
return {
top: pageWrapperRect.top,
left: pageWrapperRect.left,
right: bodyRect.right - pageWrapperRect.right,
bottom: bodyRect.bottom - pageWrapperRect.bottom,
width: pageWrapperRect.width,
height: pageWrapperRect.height
};
}
const getSystemSafeAreaInsets = function() {
if (!process.env.UNI_AUTOMATOR_WS_ENDPOINT) {
return {
top: safeAreaInsets$1.top,
right: safeAreaInsets$1.right,
bottom: safeAreaInsets$1.bottom,
left: safeAreaInsets$1.left
};
}
const bodyStyle = getComputedStyle(document.body);
return {
top: getSafeAreaInset(bodyStyle, "top"),
right: getSafeAreaInset(bodyStyle, "right"),
bottom: getSafeAreaInset(bodyStyle, "bottom"),
left: getSafeAreaInset(bodyStyle, "left")
};
};
function getSafeAreaInsets(pageBody) {
const pageWrapperEdge = getPageWrapperInfo(pageBody);
const systemSafeAreaInsets = getSystemSafeAreaInsets();
return {
top: Math.max(pageWrapperEdge.top, systemSafeAreaInsets.top),
left: Math.max(pageWrapperEdge.left, systemSafeAreaInsets.left),
right: Math.max(pageWrapperEdge.right, systemSafeAreaInsets.right),
bottom: Math.max(pageWrapperEdge.bottom, systemSafeAreaInsets.bottom)
};
}
let escBackPageNum = 0;
const homeDialogPages = [];
const homeSystemDialogPages = [];
function getPageElement(page) {
var _a;
const currentPage = getCurrentPage();
if (page !== currentPage) {
const dialogPages = currentPage.getDialogPages();
const dialogPage = dialogPages[dialogPages.length - 1];
if (dialogPage !== page) {
const systemDialogPages = currentPage.vm.$pageLayoutInstance.$systemDialogPages.value;
const systemDialogPage = systemDialogPages[systemDialogPages.length - 1];
if (systemDialogPage !== page) {
throw new Error("Can't get element of other page");
}
}
}
const pageEle = document.querySelector(
`uni-page[data-page="${(_a = page.vm) == null ? void 0 : _a.route}"]`
);
if (!pageEle) {
throw new Error("page not found");
}
return pageEle;
}
class UniPageImpl {
constructor({
route,
options,
vm
}) {
this.getParentPage = () => null;
this.route = (vm == null ? void 0 : vm.route) || route;
this.options = options;
this.vm = vm;
this.$vm = vm;
}
get statusBarHeight() {
return safeAreaInsets$1.top;
}
get width() {
return this.pageBody.width;
}
get height() {
const pageEle = getPageElement(this);
const pageHead = pageEle.querySelector("uni-page-head");
return this.pageBody.height + (pageHead ? pageHead.clientHeight : 0);
}
get pageBody() {
const pageEle = getPageElement(this);
const pageBody = pageEle.querySelector("uni-page-wrapper");
const pageWrapperInfo = getPageWrapperInfo(pageBody);
return {
top: pageWrapperInfo.top,
left: pageWrapperInfo.left,
right: pageWrapperInfo.left + pageWrapperInfo.width,
bottom: pageWrapperInfo.top + pageWrapperInfo.height,
width: pageWrapperInfo.width,
height: pageWrapperInfo.height
};
}
get safeAreaInsets() {
const pageEle = getPageElement(this);
const pageBody = pageEle.querySelector("uni-page-wrapper");
return getSafeAreaInsets(pageBody);
}
getPageStyle() {
var _a, _b, _c, _d, _e;
const pageMeta = ((_a = this.vm) == null ? void 0 : _a.$basePage.meta) ? normalizeStyles((_b = this.vm) == null ? void 0 : _b.$basePage.meta, __uniConfig.themeConfig) : void 0;
const scriptLang = (_e = (_d = (_c = this.vm) == null ? void 0 : _c.$) == null ? void 0 : _d.type) == null ? void 0 : _e.__scriptLang;
const pageStyle = pageMeta ? {
navigationBarBackgroundColor: pageMeta.navigationBar.backgroundColor,
navigationBarTextStyle: pageMeta.navigationBar.titleColor,
navigationBarTitleText: pageMeta.navigationBar.titleText,
titleImage: pageMeta.navigationBar.titleImage || "",
navigationStyle: pageMeta.navigationBar.style || "default",
disableScroll: pageMeta.disableScroll || false,
enablePullDownRefresh: pageMeta.enablePullDownRefresh || false,
onReachBottomDistance: pageMeta.onReachBottomDistance || ON_REACH_BOTTOM_DISTANCE,
backgroundColorContent: pageMeta.backgroundColorContent
} : {};
if (!scriptLang || scriptLang === "uts") {
return new UTSJSONObject(pageStyle);
}
return pageStyle;
}
$getPageStyle() {
return this.getPageStyle();
}
setPageStyle(style) {
var _a;
const pageMeta = (_a = this.vm) == null ? void 0 : _a.$basePage.meta;
if (!pageMeta)
return;
for (const key in style) {
switch (key) {
case "navigationBarBackgroundColor":
pageMeta.navigationBar.backgroundColor = style[key];
break;
case "navigationBarTextStyle":
const textStyle = style[key];
if (textStyle == null) {
continue;
}
pageMeta.navigationBar.titleColor = ["black", "white"].includes(
textStyle
) ? normalizeTitleColor(textStyle || "") : textStyle;
break;
case "navigationBarTitleText":
pageMeta.navigationBar.titleText = style[key];
break;
case "titleImage":
pageMeta.navigationBar.titleImage = style[key];
break;
case "navigationStyle":
pageMeta.navigationBar.style = style[key];
break;
default:
pageMeta[key] = style[key];
break;
}
}
}
$setPageStyle(style) {
this.setPageStyle(style);
}
getElementById(id2) {
const currentPage = getCurrentPage();
if (currentPage !== this) {
return null;
}
const uniPageBody = document.querySelector("uni-page-body");
return uniPageBody ? uniPageBody.querySelector(`#${id2}`) : null;
}
querySelector(selector) {
const currentPage = getCurrentPage();
if (currentPage !== this) {
return null;
}
const uniPageBody = document.querySelector("uni-page-body");
return uniPageBody ? uniPageBody.querySelector(selector) : null;
}
querySelectorAll(selector) {
const res = [];
const currentPage = getCurrentPage();
if (currentPage !== this) {
return res;
}
const uniPageBody = document.querySelector("uni-page-body");
if (!uniPageBody) {
return res;
}
const nodeList = uniPageBody.querySelectorAll(selector);
nodeList.forEach((node) => {
res.push(node);
});
return res;
}
getAndroidView() {
return null;
}
getIOSView() {
return null;
}
getHTMLElement() {
const currentPage = getCurrentPage();
if (currentPage !== this) {
return null;
}
return document.querySelector("uni-page-body");
}
getDialogPages() {
return [];
}
$getSystemDialogPages() {
var _a, _b, _c;
return ((_c = (_b = (_a = this.vm) == null ? void 0 : _a.$pageLayoutInstance) == null ? void 0 : _b.$systemDialogPages) == null ? void 0 : _c.value) || [];
}
__$$getSystemDialogPages() {
return [];
}
getAndroidActivity() {
return null;
}
exitFullscreen() {
}
createElement() {
return null;
}
onLayoutChange() {
return -1;
}
offLayoutChange() {
}
onRenderChange() {
return -1;
}
offRenderChange() {
}
onTouchStart() {
return -1;
}
offTouchStart() {
}
onTouchEnd() {
return -1;
}
offTouchEnd() {
}
takeSnapshot() {
}
}
class UniNormalPageImpl extends UniPageImpl {
getDialogPages() {
var _a, _b;
return ((_b = (_a = this.vm) == null ? void 0 : _a.$pageLayoutInstance) == null ? void 0 : _b.$dialogPages.value) || [];
}
constructor({
route,
options,
vm
}) {
super({ route, options, vm });
}
}
class UniDialogPageImpl extends UniPageImpl {
constructor({
route,
options,
$component,
$triggerParentHide,
getParentPage,
$disableEscBack = false
}) {
super({ route, options, vm: null });
this.$component = null;
this.$disableEscBack = false;
this.$triggerParentHide = false;
this.$component = markRaw($component);
this.getParentPage = getParentPage;
this.$disableEscBack = !!$disableEscBack;
this.$triggerParentHide = !!$triggerParentHide;
}
getElementById(id2) {
var _a;
const currentPage = getCurrentPage();
if (currentPage !== this.getParentPage()) {
return null;
}
const uniPageBody = document.querySelector(
`uni-page[data-page="${(_a = this.vm) == null ? void 0 : _a.route}"] uni-page-body`
);
return uniPageBody ? uniPageBody.querySelector(`#${id2}`) : null;
}
getHTMLElement() {
var _a;
const currentPage = getCurrentPage();
if (currentPage !== this.getParentPage()) {
return null;
}
return document.querySelector(
`uni-page[data-page="${(_a = this.vm) == null ? void 0 : _a.route}"] uni-page-body`
);
}
}
function initXPage(vm, route, page) {
var _a, _b, _c;
initPageVm(vm, page);
if (!("$pageLayoutInstance" in vm)) {
Object.defineProperty(vm, "$pageLayoutInstance", {
get() {
var _a2, _b2;
let res = (_a2 = vm.$) == null ? void 0 : _a2.parent;
while (res && ((_b2 = res.type) == null ? void 0 : _b2.name) !== "Page") {
res = res.parent;
}
return res;
}
});
}
vm.$.$waitNativeRender = (callback) => {
vm.$nextTick(() => {
callback && callback();
});
};
const pageInstance = vm.$pageLayoutInstance;
if (!isDialogPageInstance(pageInstance)) {
const scriptLang = vm.$.type.__scriptLang;
const isUTS = !scriptLang || scriptLang === "uts";
const uniPage = new UniNormalPageImpl({
route: (route == null ? void 0 : route.path) ? removeLeadingSlash(route == null ? void 0 : route.path) : "",
// 忽略类型,不同环境UTSJSONObject表示不同类型
options: isUTS ? new UTSJSONObject((route == null ? void 0 : route.query) || {}) : (route == null ? void 0 : route.query) || {},
vm
});
vm.$.page = uniPage;
vm.$dialogPage = (_a = vm.$pageLayoutInstance) == null ? void 0 : _a.$dialogPage;
currentPagesMap.set(normalizeRouteKey(page.path, page.id), vm);
if (currentPagesMap.size === 1) {
setTimeout(() => {
handleBeforeEntryPageRoutes();
}, 0);
if (homeDialogPages.length) {
homeDialogPages.forEach((dialogPage) => {
dialogPage.getParentPage = () => vm.$page;
pageInstance.$dialogPages.value.push(dialogPage);
});
homeDialogPages.length = 0;
}
if (homeSystemDialogPages.length) {
homeSystemDialogPages.forEach((dialogPage) => {
dialogPage.getParentPage = () => vm.$page;
pageInstance.$systemDialogPages.value.push(dialogPage);
});
homeSystemDialogPages.length = 0;
}
}
} else {
vm.$.page = (_b = vm.$pageLayoutInstance) == null ? void 0 : _b.$dialogPage;
pageInstance.$dialogPage.vm = vm;
pageInstance.$dialogPage.$vm = vm;
vm.$basePage.fullPath = vm.$basePage.path;
}
const pageElement = (_c = pageInstance.proxy) == null ? void 0 : _c.$el;
if (pageElement instanceof Element) {
setUniElementPage(pageElement, vm.$.page);
}
}
function useBackgroundColorContent$1(vm) {
vm && watchEffect(() => {
const uniPageBody = document.querySelector(
`uni-page[data-page="${vm.route}"] uni-page-body`
);
if (uniPageBody && vm.$basePage.meta.backgroundColorContent) {
uniPageBody.style.backgroundColor = vm.$basePage.meta.backgroundColorContent;
}
});
}
function handleEscKeyPress(event) {
if (event.key !== "Escape" && event.key !== "Esc") {
return;
}
const currentPage = getCurrentPage();
const dialogPage = getLastDialogPage(currentPage);
if (dialogPage && !dialogPage.$disableEscBack) {
const onBackPressRes = invokeHook(dialogPage.vm, ON_BACK_PRESS, {
from: "navigateBack"
});
if (onBackPressRes !== true) {
closeDialogPage({ dialogPage });
}
}
}
function incrementEscBackPageNum() {
escBackPageNum++;
if (escBackPageNum === 1) {
document.addEventListener("keydown", handleEscKeyPress);
}
}
function decrementEscBackPageNum() {
escBackPageNum--;
if (escBackPageNum === 0) {
document.removeEventListener("keydown", handleEscKeyPress);
}
}
const closeDialogPage = (options) => {
var _a, _b, _c, _d, _e;
const currentPages = getCurrentPages();
const currentPage = currentPages[currentPages.length - 1];
if (!currentPage) {
triggerFailCallback$1(options, "currentPage is null");
return;
}
if (options == null ? void 0 : options.dialogPage) {
const dialogPage = options == null ? void 0 : options.dialogPage;
const parentPage = dialogPage.getParentPage();
if (!isSystemDialogPage(dialogPage)) {
if (parentPage && (parentPage.vm.$basePage.meta.isTabBar || currentPages.indexOf(parentPage) !== -1)) {
const parentDialogPages = parentPage.getDialogPages();
const index2 = parentDialogPages.indexOf(dialogPage);
invokeHook(dialogPage.vm, ON_UNLOAD);
parentDialogPages.splice(index2, 1);
if (index2 === parentDialogPages.length) {
dialogPageTriggerPrevDialogPageLifeCycle(parentPage, ON_SHOW);
}
dialogPageTriggerParentShow(dialogPage, 1);
if (!dialogPage.$disableEscBack) {
decrementEscBackPageNum();
}
} else {
triggerFailCallback$1(options, "dialogPage is not a valid page");
return;
}
} else {
const parentSystemDialogPages = (_c = (_b = (_a = parentPage.vm) == null ? void 0 : _a.$pageLayoutInstance) == null ? void 0 : _b.$systemDialogPages) == null ? void 0 : _c.value;
if (!parentSystemDialogPages) {
triggerFailCallback$1(options, "dialogPage is not a valid page");
return;
}
const index2 = parentSystemDialogPages.indexOf(dialogPage);
if (index2 > -1) {
invokeHook(parentSystemDialogPages[index2].vm, ON_UNLOAD);
parentSystemDialogPages.splice(index2, 1);
if (index2 === parentSystemDialogPages.length) {
dialogPageTriggerPrevDialogPageLifeCycle(parentPage, ON_SHOW);
}
dialogPageTriggerParentShow(dialogPage, 1);
if (!dialogPage.$disableEscBack) {
decrementEscBackPageNum();
}
} else {
triggerFailCallback$1(options, "dialogPage is not a valid page");
}
return;
}
} else {
const dialogPages = currentPage.getDialogPages();
for (let i = dialogPages.length - 1; i >= 0; i--) {
invokeHook(dialogPages[i].vm, ON_UNLOAD);
if (i > 0) {
invokeHook(dialogPages[i - 1].vm, ON_SHOW);
}
dialogPageTriggerParentShow(dialogPages[i]);
if ((!dialogPages[i]).$disableEscBack) {
decrementEscBackPageNum();
}
}
dialogPages.length = 0;
}
const successOptions = { errMsg: "closeDialogPage: ok" };
(_d = options == null ? void 0 : options.success) == null ? void 0 : _d.call(options, successOptions);
(_e = options == null ? void 0 : options.complete) == null ? void 0 : _e.call(options, successOptions);
};
function triggerFailCallback$1(options, errMsg) {
var _a, _b;
const failOptions = new UniError(
"uni-closeDialogPage",
4,
`closeDialogPage: fail, ${errMsg}`
);
(_a = options == null ? void 0 : options.fail) == null ? void 0 : _a.call(options, failOptions);
(_b = options == null ? void 0 : options.complete) == null ? void 0 : _b.call(options, failOptions);
}
function clearDialogPages(uniPage) {
var _a, _b;
const dialogPages = uniPage.getDialogPages();
for (let i = dialogPages.length - 1; i >= 0; i--) {
closeDialogPage({ dialogPage: dialogPages[i] });
}
const systemDialogPages = (_b = (_a = uniPage.vm.$pageLayoutInstance) == null ? void 0 : _a.$systemDialogPages) == null ? void 0 : _b.value;
if (systemDialogPages) {
for (let i = systemDialogPages.length - 1; i >= 0; i--) {
closeDialogPage({ dialogPage: systemDialogPages[i] });
}
}
}
function closePreSystemDialogPage(dialogPages, type, onClose) {
const targetSystemDialogPages = dialogPages.filter(
(page) => page.route.startsWith(type)
);
if (targetSystemDialogPages.length > 1) {
const preSystemDialogPage = targetSystemDialogPages[0];
setTimeout(() => {
const index2 = dialogPages.indexOf(preSystemDialogPage);
if (index2 > -1) {
dialogPages.splice(index2, 1);
onClose == null ? void 0 : onClose(preSystemDialogPage);
}
}, 150);
}
}
const SEP = "$$";
const currentPagesMap = /* @__PURE__ */ new Map();
function getPage$BasePage(page) {
return page.$basePage;
}
const entryPageState = {
handledBeforeEntryPageRoutes: false
};
const navigateToPagesBeforeEntryPages = [];
const switchTabPagesBeforeEntryPages = [];
const redirectToPagesBeforeEntryPages = [];
const reLaunchPagesBeforeEntryPages = [];
function pruneCurrentPages() {
currentPagesMap.forEach((page, id2) => {
if (page.$.isUnmounted) {
currentPagesMap.delete(id2);
}
});
}
function getCurrentPagesMap() {
return currentPagesMap;
}
const pageUnloadCallbacks = /* @__PURE__ */ new Set();
function onPageUnload(callback) {
pageUnloadCallbacks.add(callback);
return () => pageUnloadCallbacks.delete(callback);
}
function getCurrentPages$1() {
const curPages = getCurrentBasePages();
{
return curPages.map((page) => page.$page);
}
}
function getCurrentBasePages() {
const curPages = [];
const pages = currentPagesMap.values();
for (const page of pages) {
if (page.$.__isTabBar) {
if (page.$.__isActive) {
curPages.push(page);
}
} else {
curPages.push(page);
}
}
return curPages;
}
function removeRouteCache(routeKey) {
const cacheEntry = pageCacheMap.get(routeKey);
if (cacheEntry) {
pageCacheMap.delete(routeKey);
routeCache.pruneCacheEntry(cacheEntry);
}
}
function removePage(routeKey, removeRouteCaches = true) {
const pageVm = currentPagesMap.get(routeKey);
if (!pageVm) {
return;
}
const pageId = getPage$BasePage(pageVm).id;
{
clearDialogPages(pageVm.$page);
}
pageVm.$.__isUnload = true;
invokeHook(pageVm, ON_UNLOAD);
pageUnloadCallbacks.forEach((callback) => callback(pageId));
currentPagesMap.delete(routeKey);
removeRouteCaches && removeRouteCache(routeKey);
{
pageVm.$page.vm = null;
}
}
let id$1 = /* @__PURE__ */ getStateId();
function createPageState(type, __id__) {
return {
__id__: __id__ || ++id$1,
__type__: type
};
}
let dialogPageId = Number.MIN_SAFE_INTEGER;
function createDialogPageId() {
return ++dialogPageId;
}
function initPublicPage(route) {
const meta = usePageMeta();
if (!__UNI_FEATURE_PAGES__) {
return initPageInternalInstance("navigateTo", __uniRoutes[0].path, {}, meta);
}
let fullPath = route.fullPath;
if (route.meta.isEntry && fullPath.indexOf(route.meta.route) === -1) {
fullPath = "/" + route.meta.route + fullPath.replace("/", "");
}
return initPageInternalInstance("navigateTo", fullPath, {}, meta);
}
function initPage(vm) {
let route;
route = usePageRoute();
const page = initPublicPage(route);
const routeMeta = route.meta;
Object.defineProperty(page, "eventChannel", {
configurable: true,
enumerable: true,
get: () => routeMeta.eventChannel,
set: (eventChannel) => routeMeta.eventChannel = eventChannel
});
initPageVm(vm, page);
{
initXPage(vm, route, page);
}
}
function normalizeRouteKey(path, id2) {
return path + SEP + id2;
}
function useKeepAliveRoute() {
const route = useRoute();
const routeKey = computed(
() => normalizeRouteKey("/" + route.meta.route, getStateId())
);
const isTabBar = computed(() => route.meta.isTabBar);
return {
routeKey,
isTabBar,
routeCache
};
}
const pageCacheMap = /* @__PURE__ */ 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 isTabBarCacheEntry(cacheEntry) {
var _a;
return ((_a = cacheEntry.attrs || cacheEntry.props) == null ? void 0 : _a.type) === "tabBar";
}
function pruneRouteCache(key) {
const pageId = parseInt(key.split(SEP)[1]);
if (!pageId) {
return;
}
routeCache.forEach((cacheEntry, key2) => {
const cPageId = parseInt(key2.split(SEP)[1]);
if (cPageId && cPageId > pageId) {
if (__UNI_FEATURE_TABBAR__ && isTabBarCacheEntry(cacheEntry)) {
return;
}
routeCache.delete(key2);
routeCache.pruneCacheEntry(cacheEntry);
nextTick(() => pruneCurrentPages());
}
});
}
function updateCurPageAttrs(pageMeta) {
{
const uvueDirKey = "uvue-dir-" + __uniConfig.uvue["flex-direction"];
document.body.setAttribute("uvue", "");
document.body.setAttribute(uvueDirKey, "");
}
}
function onPageShow(instance2, pageMeta) {
updateCurPageBodyScopeId(instance2);
updateBodyScopeId(instance2);
updateCurPageCssVar(pageMeta);
updateCurPageAttrs();
if (isDialogPageInstance(getPageInstanceByChild(instance2))) {
return;
}
initPageScrollListener(instance2, pageMeta);
}
function onPageReady(instance2) {
if (!updateCurPageBodyScopeId(instance2) && process.env.NODE_ENV !== "production") {
console.warn("uni-page-body not found");
}
}
function updateCurPageBodyScopeId(instance2) {
var _a, _b;
const pageRoot = (_b = (_a = getPageInstanceByChild(instance2)) == null ? void 0 : _a.proxy) == null ? void 0 : _b.$el;
const pageBodyEl = pageRoot == null ? void 0 : pageRoot.querySelector("uni-page-body");
if (!pageBodyEl) {
return false;
}
const type = instance2.type;
if (type.styleIsolation !== "isolated") {
const appScopeId = getScopeId(instance2.root);
appScopeId && pageBodyEl.setAttribute(appScopeId, "");
}
const pageScopeId = getScopeId(instance2);
pageScopeId && pageBodyEl.setAttribute(pageScopeId, "");
return true;
}
let curScopeId;
function updateBodyScopeId(instance2) {
const scopeId = getScopeId(instance2);
const { body } = document;
curScopeId && body.removeAttribute(curScopeId);
scopeId && body.setAttribute(scopeId, "");
curScopeId = scopeId;
}
const supportsPassive = /* @__PURE__ */ (() => {
let supportsPassive2 = false;
try {
const opts = {};
Object.defineProperty(opts, "passive", {
get() {
supportsPassive2 = true;
}
});
window.addEventListener("test-passive", () => {
}, opts);
} catch (e2) {
}
return supportsPassive2;
})();
const passiveOptions$1 = supportsPassive ? {
passive: false
} : false;
let curScrollListener;
function initPageScrollListener(instance2, pageMeta) {
document.removeEventListener("touchmove", disableScrollListener);
if (curScrollListener) {
document.removeEventListener("scroll", curScrollListener);
}
if (pageMeta.disableScroll) {
return document.addEventListener(
"touchmove",
disableScrollListener,
passiveOptions$1
);
}
const { onPageScroll, onReachBottom } = instance2;
const navigationBarTransparent = pageMeta.navigationBar.type === "transparent";
if (!(onPageScroll == null ? void 0 : onPageScroll.length) && !(onReachBottom == null ? void 0 : onReachBottom.length) && !navigationBarTransparent) {
return;
}
const opts = {};
const pageId = getPage$BasePage(instance2.proxy).id;
if (onPageScroll || navigationBarTransparent) {
opts.onPageScroll = createOnPageScroll(
pageId,
onPageScroll,
navigationBarTransparent
);
}
if (onReachBottom == null ? void 0 : onReachBottom.length) {
opts.onReachBottomDistance = pageMeta.onReachBottomDistance || ON_REACH_BOTTOM_DISTANCE;
opts.onReachBottom = () => UniViewJSBridge.publishHandler(ON_REACH_BOTTOM, {}, pageId);
}
curScrollListener = createScrollListener(opts);
requestAnimationFrame(
() => document.addEventListener("scroll", curScrollListener)
);
{
watch(
() => pageMeta.onReachBottomDistance,
(onReachBottomDistance) => {
if (!onReachBottom) {
return;
}
opts.onReachBottomDistance = onReachBottomDistance || ON_REACH_BOTTOM_DISTANCE;
document.removeEventListener("scroll", curScrollListener);
curScrollListener = createScrollListener(opts);
document.addEventListener("scroll", curScrollListener);
}
);
watch(
() => pageMeta.disableScroll,
(disableScroll) => {
document.removeEventListener("touchmove", disableScrollListener);
if (disableScroll) {
return document.addEventListener("touchmove", disableScrollListener);
}
}
);
}
}
function createOnPageScroll(pageId, onPageScroll, navigationBarTransparent) {
return (scrollTop) => {
if (onPageScroll) {
UniViewJSBridge.publishHandler(ON_PAGE_SCROLL, { scrollTop }, pageId);
}
if (navigationBarTransparent) {
UniViewJSBridge.emit(pageId + "." + ON_PAGE_SCROLL, {
scrollTop
});
}
};
}
function findElem(vm) {
return vm.$el;
}
function addBase(filePath) {
const { base: baseUrl } = __uniConfig.router;
if (addLeadingSlash(filePath).indexOf(baseUrl) === 0) {
return addLeadingSlash(filePath);
}
return baseUrl + filePath;
}
function getRealPath(filePath) {
const { base, assets } = __uniConfig.router;
if (base === "./") {
if (filePath.indexOf("./") === 0 && (filePath.includes("/static/") || filePath.indexOf("./" + (assets || "assets") + "/") === 0)) {
filePath = filePath.slice(1);
}
}
if (filePath.indexOf("/") === 0) {
if (filePath.indexOf("//") === 0) {
filePath = "https:" + filePath;
} else {
return addBase(filePath.slice(1));
}
}
if (SCHEME_RE.test(filePath) || DATA_RE.test(filePath) || filePath.indexOf("blob:") === 0) {
return filePath;
}
{
if (process.env.NODE_ENV !== "production") {
if (!filePath.includes("/static/")) {
return filePath;
}
}
}
const pages = getCurrentBasePages();
if (pages.length) {
return addBase(
getRealRoute(
getPage$BasePage(pages[pages.length - 1]).route,
filePath
).slice(1)
);
}
return filePath;
}
function operateVideoPlayer(videoId, pageId, type, data) {
UniServiceJSBridge.invokeViewMethod(
"video." + videoId,
{
videoId,
type,
data
},
pageId
);
}
function operateMap(id2, pageId, type, data, operateMapCallback2) {
UniServiceJSBridge.invokeViewMethod(
"map." + id2,
{
type,
data
},
pageId,
operateMapCallback2
);
}
function createDatasetSnapshot(dataset) {
return createUniDOMStringMap(dataset);
}
function getRootInfo(fields) {
const info = {};
if (fields.id) {
info.id = "";
}
if (fields.dataset) {
info.dataset = createDatasetSnapshot({});
}
if (fields.rect) {
info.left = 0;
info.right = 0;
info.top = 0;
info.bottom = 0;
}
if (fields.size) {
info.width = document.documentElement.clientWidth;
info.height = document.documentElement.clientHeight;
}
if (fields.scrollOffset) {
const documentElement = document.documentElement;
const body = document.body;
info.scrollLeft = documentElement.scrollLeft || body.scrollLeft || 0;
info.scrollTop = documentElement.scrollTop || body.scrollTop || 0;
info.scrollHeight = documentElement.scrollHeight || body.scrollHeight || 0;
info.scrollWidth = documentElement.scrollWidth || body.scrollWidth || 0;
}
return info;
}
function getNodeInfo(el, fields) {
const info = {};
const { top, topWindowHeight } = getWindowOffset();
if (fields.node) {
info.node = el;
}
if (fields.id) {
info.id = el.id;
}
if (fields.dataset) {
info.dataset = createDatasetSnapshot(getCustomDataset(el));
}
if (fields.rect || fields.size) {
const rect = el.getBoundingClientRect();
if (fields.rect) {
info.left = rect.left;
info.right = rect.right;
info.top = rect.top - top - topWindowHeight;
info.bottom = rect.bottom - top - topWindowHeight;
}
if (fields.size) {
info.width = rect.width;
info.height = rect.height;
}
}
if (isArray(fields.properties)) {
fields.properties.forEach((prop) => {
prop = prop.replace(/-([a-z])/g, function(e2, t12) {
return t12.toUpperCase();
});
});
}
if (fields.scrollOffset) {
info.scrollLeft = el.scrollLeft;
info.scrollTop = el.scrollTop;
info.scrollHeight = el.scrollHeight;
info.scrollWidth = el.scrollWidth;
}
if (isArray(fields.computedStyle)) {
const style = getComputedStyle(el);
fields.computedStyle.forEach((name) => {
info[name] = style[name];
});
}
if (fields.context) {
info.contextInfo = getContextInfo(el);
}
return info;
}
function getNodesInfo(pageVm, component, selector, single, fields) {
const instance2 = (component || pageVm).$;
if (single) {
const node = querySelectorInComponent(instance2, selector);
return node ? getNodeInfo(node, fields) : null;
}
return querySelectorAllInComponent(instance2, selector).map(
(node) => getNodeInfo(node, fields)
);
}
function requestComponentInfo(page, reqs, callback) {
const result = [];
reqs.forEach(({ component, selector, single, fields }) => {
if (component === null) {
result.push(getRootInfo(fields));
} else {
result.push(getNodesInfo(page, component, selector, single, fields));
}
});
callback(result);
}
function setCurrentPageMeta(_page, { pageStyle, rootFontSize }) {
if (pageStyle) {
const pageElm = document.querySelector("uni-page-body") || document.body;
pageElm.setAttribute("style", pageStyle);
}
if (rootFontSize && document.documentElement.style.fontSize !== rootFontSize) {
document.documentElement.style.fontSize = rootFontSize;
}
}
function addIntersectionObserver({ reqId, component, options, callback }, _pageId) {
const $el = findElem(component);
($el.__io || ($el.__io = {}))[reqId] = requestComponentObserver(
$el,
options,
callback
);
}
function removeIntersectionObserver({ reqId, component }, _pageId) {
const $el = findElem(component);
const intersectionObserver = $el.__io && $el.__io[reqId];
if (intersectionObserver) {
intersectionObserver.disconnect();
delete $el.__io[reqId];
}
}
let mediaQueryObservers = {};
let listeners = {};
function handleMediaQueryStr($props) {
const mediaQueryArr = [];
const propsMenu = [
"width",
"minWidth",
"maxWidth",
"height",
"minHeight",
"maxHeight",
"orientation"
];
for (const item of propsMenu) {
if (item !== "orientation" && $props[item] && Number($props[item] >= 0)) {
mediaQueryArr.push(
`(${humpToLine(item)}: ${Number(
$props[item]
)}px)`
);
}
if (item === "orientation" && $props[item]) {
mediaQueryArr.push(`(${humpToLine(item)}: ${$props[item]})`);
}
}
const mediaQueryStr = mediaQueryArr.join(" and ");
return mediaQueryStr;
}
function humpToLine(name) {
return name.replace(/([A-Z])/g, "-$1").toLowerCase();
}
function addMediaQueryObserver({ reqId, component, options, callback }, _pageId) {
const mediaQueryObserver = mediaQueryObservers[reqId] = window.matchMedia(
handleMediaQueryStr(options)
);
const listener2 = listeners[reqId] = (observer) => callback(observer.matches);
listener2(mediaQueryObserver);
mediaQueryObserver.addListener(listener2);
}
function removeMediaQueryObserver({ reqId, component }, _pageId) {
const listener2 = listeners[reqId];
const mediaQueryObserver = mediaQueryObservers[reqId];
if (mediaQueryObserver) {
mediaQueryObserver.removeListener(listener2);
delete listeners[reqId];
delete mediaQueryObservers[reqId];
}
}
const files = {};
function urlToFile(url, local) {
const file = files[url];
if (file) {
return Promise.resolve(file);
}
if (/^data:[a-z-]+\/[a-z-]+;base64,/.test(url)) {
return Promise.resolve(base64ToFile(url));
}
if (local) {
return Promise.reject(new Error("not find"));
}
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = function() {
resolve(this.response);
};
xhr.onerror = reject;
xhr.send();
});
}
function base64ToFile(base64) {
const base64Array = base64.split(",");
const res = base64Array[0].match(/:(.*?);/);
const type = res ? res[1] : "";
const str = atob(base64Array[1]);
let n = str.length;
const array = new Uint8Array(n);
while (n--) {
array[n] = str.charCodeAt(n);
}
return blobToFile(array, type);
}
function getExtname(type) {
const extname = type.split("/")[1];
return extname ? `.${extname}` : "";
}
function getFileName(url) {
url = url.split("#")[0].split("?")[0];
const array = url.split("/");
return array[array.length - 1];
}
function blobToFile(blob, type) {
let file;
if (blob instanceof File) {
file = blob;
} else {
type = type || blob.type || "";
const filename = `${Date.now()}${getExtname(type)}`;
try {
file = new File([blob], filename, { type });
} catch (error) {
blob = blob instanceof Blob ? blob : new Blob([blob], { type });
file = blob;
file.name = file.name || filename;
}
}
return file;
}
function fileToUrl(file) {
for (const key in files) {
if (hasOwn(files, key)) {
const oldFile = files[key];
if (oldFile === file) {
return key;
}
}
}
var url = (window.URL || window.webkitURL).createObjectURL(file);
files[url] = file;
return url;
}
function revokeObjectURL(url) {
const URL = window.URL || window.webkitURL;
URL.revokeObjectURL(url);
delete files[url];
}
const loadFontFace = /* @__PURE__ */ defineAsyncApi(
API_LOAD_FONT_FACE,
({ family, source, desc }, { resolve, reject }) => {
if (source.startsWith(`url("`) || source.startsWith(`url('`)) {
source = `url('${getRealPath(source.substring(5, source.length - 2))}')`;
} else if (source.startsWith("url(")) {
source = `url('${getRealPath(source.substring(4, source.length - 1))}')`;
} else {
source = getRealPath(source);
}
addFont(family, source, desc).then(() => {
resolve();
}).catch((err) => {
reject(`loadFontFace:fail ${err}`);
});
},
LoadFontFaceProtocol
);
const t0$G = template("<img>");
const t1$l = template("<div class=uni-tabbar__mid>");
const t2$b = template("<div class=uni-tabbar__iconfont> ");
const t3$8 = template("<div>");
const t4$5 = template("<div class=uni-tabbar__label> ");
const t5$4 = template("<div> ");
const t6$3 = template("<div class=uni-tabbar__item><!><div class=uni-tabbar__bd></div>");
const t7$2 = template("<uni-tabbar><div class=uni-tabbar><div class=uni-tabbar-border></div></div><div class=uni-placeholder>", 1);
const UNI_TABBAR_ICON_FONT = "UniTabbarIconFont";
const DEFAULT_BG_COLOR = "#f7f7fa";
const BLUR_EFFECT_COLOR_DARK = "rgb(0, 0, 0, 0.8)";
const BLUR_EFFECT_COLOR_LIGHT = "rgb(250, 250, 250, 0.8)";
const _sfc_main$G = /* @__PURE__ */ defineVaporComponent({
...{
name: "TabBar",
__reserved: true,
compatConfig: { MODE: 3 }
},
__name: "tabBar",
setup(__props) {
const hasMidButton = __UNI_FEATURE_TABBAR_MIDBUTTON__;
const _middleButton = {
width: "50px",
height: "50px",
iconWidth: "24px"
};
const visibleList = ref([]);
const tabBar = useTabBar();
useVisibleList(tabBar, visibleList);
useTabBarCssVar(tabBar);
const onSwitchTab = useSwitchTab(useRoute(), tabBar, visibleList);
const { style, borderStyle, placeholderStyle } = useTabBarStyle(tabBar);
onMounted(() => {
if (tabBar.iconfontSrc) {
loadFontFace({
family: UNI_TABBAR_ICON_FONT,
source: `url("${tabBar.iconfontSrc}")`
});
}
});
function useTabBarCssVar(tabBar2) {
watch(
() => tabBar2.shown,
(value) => {
updatePageCssVar({
"--window-bottom": normalizeWindowBottom(
value ? parseInt(tabBar2.height) : 0
)
});
}
);
}
function useVisibleList(tabBar2, visibleList2) {
const internalMidButton = ref(
extend({ type: "midButton" }, tabBar2.midButton)
);
function setVisibleList() {
let tempList = [];
tempList = tabBar2.list.filter((item) => item.visible !== false);
if (hasMidButton && tabBar2.midButton) {
internalMidButton.value = extend(
{},
_middleButton,
internalMidButton.value,
tabBar2.midButton
);
tempList = tempList.filter((item) => !isMidButton(item));
if (tempList.length % 2 === 0) {
tempList.splice(
Math.floor(tempList.length / 2),
0,
internalMidButton.value
);
}
}
visibleList2.value = tempList;
}
watchEffect(setVisibleList);
}
function useSwitchTab(route, tabBar2, visibleList2) {
watchEffect(() => {
const meta = route.meta;
if (meta.isTabBar) {
const pagePath = meta.route;
const index2 = visibleList2.value.findIndex(
(item) => item.pagePath === pagePath
);
tabBar2.selectedIndex = index2;
}
});
return (tabBarItem, index2) => {
const { type } = tabBarItem;
if (hasMidButton && type === "midButton") {
return UniServiceJSBridge.invokeOnCallback(
API_ON_TAB_BAR_MID_BUTTON_TAP
);
}
const { pagePath, text: text2 } = tabBarItem;
let url = addLeadingSlash(pagePath);
if (url === __uniRoutes[0].alias) {
url = "/";
}
if (route.path !== url) {
uni.switchTab({ from: "tabBar", url, tabBarText: text2 });
} else {
invokeHook("onTabItemTap", {
index: index2,
text: text2,
pagePath
});
}
};
}
const BLUR_EFFECT_COLORS = {
dark: BLUR_EFFECT_COLOR_DARK,
light: BLUR_EFFECT_COLOR_LIGHT,
extralight: BLUR_EFFECT_COLOR_LIGHT
};
const BORDER_COLORS = {
white: "rgba(255, 255, 255, 0.33)",
black: "rgba(0, 0, 0, 0.33)"
};
function useTabBarStyle(tabBar2) {
const style2 = computed(() => {
let backgroundColor = tabBar2.backgroundColor;
const blurEffect = tabBar2.blurEffect;
if (!backgroundColor) {
if (cssBackdropFilter && blurEffect && blurEffect !== "none") {
backgroundColor = BLUR_EFFECT_COLORS[blurEffect];
}
}
return {
backgroundColor: backgroundColor || DEFAULT_BG_COLOR,
backdropFilter: blurEffect !== "none" ? "blur(10px)" : blurEffect
};
});
const borderStyle2 = computed(() => {
const { borderStyle: borderStyle3, borderColor } = tabBar2;
if (borderColor && isString(borderColor)) {
return {
backgroundColor: borderColor
};
}
return {
backgroundColor: BORDER_COLORS[borderStyle3] || BORDER_COLORS["black"]
};
});
const placeholderStyle2 = computed(() => {
return {
height: tabBar2.height
};
});
return {
style: style2,
borderStyle: borderStyle2,
placeholderStyle: placeholderStyle2
};
}
function isMidButton(item) {
return item.type === "midButton";
}
function isRenderedMidButton(item) {
return hasMidButton && isMidButton(item);
}
function getMidButton(item) {
return item;
}
function getItemStyle(item) {
if (!isRenderedMidButton(item)) {
return;
}
return {
flex: "0 0 " + item.width,
position: "relative"
};
}
function getMidButtonStyle(item) {
const { width, height, backgroundImage } = getMidButton(item);
return {
width,
height,
backgroundImage: backgroundImage ? "url('" + getRealPath(backgroundImage) + "')" : "none"
};
}
function isSelected(index2) {
return tabBar.selectedIndex === index2;
}
function getTextColor(index2) {
return isSelected(index2) ? tabBar.selectedColor : tabBar.color;
}
function getIconPath(item, index2) {
return (isSelected(index2) ? item.selectedIconPath || item.iconPath : item.iconPath) || "";
}
function getIconfontText(item, index2) {
if (!item.iconfont) {
return;
}
return isSelected(index2) ? item.iconfont.selectedText || item.iconfont.text : item.iconfont.text;
}
function getIconfontColor(item, index2) {
if (!item.iconfont) {
return;
}
return isSelected(index2) ? item.iconfont.selectedColor || item.iconfont.color : item.iconfont.color;
}
function getIconClass(item) {
return "uni-tabbar__icon" + (item.text ? " uni-tabbar__icon__diff" : "");
}
function getIconStyle() {
return { width: tabBar.iconWidth, height: tabBar.iconWidth };
}
function getIconfontStyle(item, index2) {
var _a;
return {
fontSize: ((_a = item.iconfont) == null ? void 0 : _a.fontSize) || tabBar.iconWidth,
color: getIconfontColor(item, index2) || BLUR_EFFECT_COLOR_DARK
};
}
function getLabelStyle(item, index2) {
return {
color: getTextColor(index2),
fontSize: tabBar.fontSize,
lineHeight: !item.iconPath ? 1.8 : "normal",
marginTop: !item.iconPath ? "inherit" : tabBar.spacing
};
}
const n31 = t7$2();
const n29 = child(n31);
const n0 = child(n29);
const n30 = next(n29);
renderEffect(() => {
setClass(n31, "uni-tabbar-" + unref(tabBar).position);
setStyle(n29, unref(style));
setStyle(n0, unref(borderStyle));
});
setInsertionState(n29, 1);
createFor(
() => visibleList.value,
(_for_item0, _for_key0) => {
const n28 = t6$3();
const n27 = child(n28);
const n26 = next(n27);
renderEffect(() => setStyle(n28, getItemStyle(_for_item0.value)));
setInsertionState(n28, n27);
createIf(() => isRenderedMidButton(_for_item0.value), () => {
const n8 = t1$l();
renderEffect(() => setStyle(n8, getMidButtonStyle(_for_item0.value)));
setInsertionState(n8);
createIf(() => getIconPath(_for_item0.value, _for_key0.value), () => {
const n7 = t0$G();
renderEffect(() => {
setStyle(n7, {
width: getMidButton(_for_item0.value).iconWidth,
height: getMidButton(_for_item0.value).iconWidth
});
setProp(n7, "src", unref(getRealPath)(getIconPath(_for_item0.value, _for_key0.value)));
});
return n7;
});
return n8;
});
renderEffect(() => setStyle(n26, { height: unref(tabBar).height }));
setInsertionState(n26);
createIf(
() => getIconfontText(_for_item0.value, _for_key0.value),
() => {
const n14 = t3$8();
renderEffect(() => {
setClass(n14, getIconClass(_for_item0.value));
setStyle(n14, getIconStyle());
});
setInsertionState(n14);
createIf(() => _for_item0.value.type !== "midButton", () => {
const n13 = t2$b();
const x13 = txt(n13);
renderEffect(() => {
const _item = _for_item0.value;
const _index = _for_key0.value;
setStyle(n13, getIconfontStyle(_item, _index));
setText(x13, toDisplayString(getIconfontText(_item, _index)));
});
return n13;
});
return n14;
},
() => createIf(() => getIconPath(_for_item0.value, _for_key0.value), () => {
const n19 = t3$8();
renderEffect(() => {
setClass(n19, getIconClass(_for_item0.value));
setStyle(n19, getIconStyle());
});
setInsertionState(n19);
createIf(() => _for_item0.value.type !== "midButton", () => {
const n18 = t0$G();
renderEffect(() => setProp(n18, "src", unref(getRealPath)(getIconPath(_for_item0.value, _for_key0.value))));
return n18;
});
return n19;
}),
1037
/* TRUE_SINGLE_ROOT, FALSE_ELSE_IF, KEYED_INDEX_3 */
);
setInsertionState(n26, 1);
createIf(() => _for_item0.value.text, () => {
const n22 = t4$5();
const x22 = txt(n22);
renderEffect(() => {
const _item = _for_item0.value;
setStyle(n22, getLabelStyle(_item, _for_key0.value));
setText(x22, toDisplayString(_item.text));
});
return n22;
});
setInsertionState(n26, 2);
createIf(() => _for_item0.value.redDot, () => {
const n25 = t5$4();
const x25 = txt(n25);
renderEffect(() => {
const _item_badge = _for_item0.value.badge;
setClass(n25, [
"uni-tabbar__reddot",
_item_badge ? "uni-tabbar__badge" : ""
]);
setText(x25, toDisplayString(_item_badge));
});
return n25;
});
on$1(n28, "click", () => unref(onSwitchTab)(_for_item0.value, _for_key0.value));
return n28;
},
(item, index2) => isRenderedMidButton(item) ? "midButton" : index2,
8
/* IS_SINGLE_NODE */
);
renderEffect(() => setStyle(n30, unref(placeholderStyle)));
return n31;
}
});
let globalLayoutState;
function getLayoutState() {
return globalLayoutState;
}
function setLayoutState(state) {
globalLayoutState = state;
}
const t0$F = template("<uni-top-window><div class=uni-top-window></div><div class=uni-top-window--placeholder>");
const t1$k = template("<div class=uni-mask>");
const t2$a = template("<uni-left-window><!><div class=uni-left-window>");
const t3$7 = template("<uni-right-window><!><div class=uni-right-window>");
const t4$4 = template("<uni-layout><!><uni-content><uni-main></uni-main>");
const t5$3 = template("<uni-app>", 1);
const _sfc_main$F = /* @__PURE__ */ defineVaporComponent({
...{
name: "Layout",
__reserved: true,
compatConfig: { MODE: 3 }
},
__name: "index-vapor",
setup(__props) {
const DEFAULT_CSS_VAR_VALUE = "0px";
const hasPages = __UNI_FEATURE_PAGES__;
const hasResponsive = __UNI_FEATURE_RESPONSIVE__;
const hasTopWindow = __UNI_FEATURE_TOPWINDOW__;
const hasLeftWindow = __UNI_FEATURE_LEFTWINDOW__;
const hasRightWindow = __UNI_FEATURE_RIGHTWINDOW__;
const hasTabBar = __UNI_FEATURE_TABBAR__;
const rootRef = ref(null);
initCssVar();
const firstPageComponent = !hasPages && __uniRoutes[0].component;
const keepAliveRoute = hasPages ? useKeepAliveRoute() : void 0;
const routeKey = keepAliveRoute == null ? void 0 : keepAliveRoute.routeKey;
const isTabBar = keepAliveRoute == null ? void 0 : keepAliveRoute.isTabBar;
const routeCache2 = keepAliveRoute == null ? void 0 : keepAliveRoute.routeCache;
const route = hasPages ? useRoute() : void 0;
const { layoutState, windowState } = useState();
useMaxWidth(layoutState, rootRef);
const topWindow = hasTopWindow && useTopWindow(layoutState);
const leftWindow = hasLeftWindow && useLeftWindow(layoutState);
const rightWindow = hasRightWindow && useRightWindow(layoutState);
const TopWindow = topWindow && topWindow.component;
const LeftWindow = leftWindow && leftWindow.component;
const RightWindow = rightWindow && rightWindow.component;
const topWindowRef = topWindow && topWindow.windowRef;
const leftWindowRef = leftWindow && leftWindow.windowRef;
const rightWindowRef = rightWindow && rightWindow.windowRef;
const showTabBar2 = hasTabBar && useShowTabBar();
const clazz = useAppClass(showTabBar2);
setLayoutState(layoutState);
function useAppClass(showTabBar22) {
const showMaxWidth = ref(false);
return computed(() => {
return {
"uni-app--showtabbar": showTabBar22 && showTabBar22.value,
"uni-app--maxwidth": showMaxWidth.value
};
});
}
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 initMediaQuery(minWidth, callback) {
const mediaQueryList = window.matchMedia("(min-width: " + minWidth + "px)");
if (mediaQueryList.addEventListener) {
mediaQueryList.addEventListener("change", callback);
} else {
mediaQueryList.addListener(callback);
}
return mediaQueryList.matches;
}
function useMaxWidth(layoutState2, rootRef2) {
const route2 = usePageRoute();
function checkMaxWidth2() {
const windowWidth = document.body.clientWidth;
const pages = getCurrentBasePages();
let meta = {};
if (pages.length > 0) {
const curPage = pages[pages.length - 1];
meta = getPage$BasePage(curPage).meta;
} else {
const routeOptions = getRouteOptions(route2.path, true);
if (routeOptions) {
meta = routeOptions.meta;
}
}
const maxWidth2 = parseInt(
String(
(hasOwn(meta, "maxWidth") ? meta.maxWidth : __uniConfig.globalStyle.maxWidth) || Number.MAX_SAFE_INTEGER
)
);
let showMaxWidth = false;
if (windowWidth > maxWidth2) {
showMaxWidth = true;
} else {
showMaxWidth = false;
}
if (showMaxWidth && maxWidth2) {
layoutState2.marginWidth = (windowWidth - maxWidth2) / 2;
nextTick(() => {
const rootEl = rootRef2.value;
if (rootEl) {
rootEl.setAttribute(
"style",
"max-width:" + maxWidth2 + "px;margin:0 auto;"
);
}
});
} else {
layoutState2.marginWidth = 0;
nextTick(() => {
const rootEl = rootRef2.value;
if (rootEl) {
rootEl.removeAttribute("style");
}
});
}
}
watch([() => route2.path], checkMaxWidth2);
onMounted(() => {
checkMaxWidth2();
window.addEventListener("resize", checkMaxWidth2);
});
}
function useState() {
const route2 = usePageRoute();
if (!hasResponsive) {
const layoutState3 = reactive({
marginWidth: 0,
leftWindowWidth: 0,
rightWindowWidth: 0
});
watch(
() => layoutState3.marginWidth,
(value) => updateCssVar({ "--window-margin": value + "px" })
);
watch(
() => layoutState3.leftWindowWidth + layoutState3.marginWidth,
(value) => {
updateCssVar({ "--window-left": value + "px" });
}
);
watch(
() => layoutState3.rightWindowWidth + layoutState3.marginWidth,
(value) => {
updateCssVar({ "--window-right": value + "px" });
}
);
return {
layoutState: layoutState3,
windowState: computed(() => ({}))
};
}
const topWindowMediaQuery = ref(false);
const leftWindowMediaQuery = ref(false);
const rightWindowMediaQuery = ref(false);
const showTopWindow2 = computed(
() => hasTopWindow && route2.meta.topWindow !== false && topWindowMediaQuery.value
);
const showLeftWindow2 = computed(
() => hasLeftWindow && route2.meta.leftWindow !== false && leftWindowMediaQuery.value
);
const showRightWindow2 = computed(
() => hasRightWindow && route2.meta.rightWindow !== false && rightWindowMediaQuery.value
);
const layoutState2 = reactive({
topWindowMediaQuery,
showTopWindow: showTopWindow2,
apiShowTopWindow: false,
leftWindowMediaQuery,
showLeftWindow: showLeftWindow2,
apiShowLeftWindow: false,
rightWindowMediaQuery,
showRightWindow: showRightWindow2,
apiShowRightWindow: false,
topWindowHeight: 0,
marginWidth: 0,
leftWindowWidth: 0,
rightWindowWidth: 0,
navigationBarTitleText: "",
topWindowStyle: {},
leftWindowStyle: {},
rightWindowStyle: {}
});
const props2 = [
"topWindow",
"leftWindow",
"rightWindow"
];
props2.forEach((prop) => {
var _a;
const matchMedia = (_a = __uniConfig[prop]) == null ? void 0 : _a.matchMedia;
let topWindowMinWidth = RESPONSIVE_MIN_WIDTH;
if (matchMedia && hasOwn(matchMedia, "minWidth")) {
const minWidth = matchMedia.minWidth;
topWindowMinWidth = checkMinWidth(minWidth) ? minWidth : topWindowMinWidth;
}
const matches = initMediaQuery(topWindowMinWidth, (ev) => {
layoutState2[`${prop}MediaQuery`] = ev.matches;
});
layoutState2[`${prop}MediaQuery`] = matches;
});
watch(
() => layoutState2.topWindowHeight,
(value) => updateCssVar({ "--top-window-height": value + "px" })
);
watch(
() => layoutState2.marginWidth,
(value) => updateCssVar({ "--window-margin": value + "px" })
);
watch(
() => layoutState2.leftWindowWidth + layoutState2.marginWidth,
(value) => {
updateCssVar({ "--window-left": value + "px" });
}
);
watch(
() => layoutState2.rightWindowWidth + layoutState2.marginWidth,
(value) => {
updateCssVar({ "--window-right": value + "px" });
}
);
UniServiceJSBridge.on(ON_NAVIGATION_BAR_CHANGE, (navigationBar) => {
layoutState2.navigationBarTitleText = navigationBar.titleText;
});
const windowState2 = computed(() => ({
matchTopWindow: layoutState2.topWindowMediaQuery,
showTopWindow: layoutState2.showTopWindow || layoutState2.apiShowTopWindow,
matchLeftWindow: layoutState2.leftWindowMediaQuery,
showLeftWindow: layoutState2.showLeftWindow || layoutState2.apiShowLeftWindow,
matchRightWindow: layoutState2.rightWindowMediaQuery,
showRightWindow: layoutState2.showRightWindow || layoutState2.apiShowRightWindow
}));
return {
layoutState: layoutState2,
windowState: windowState2
};
}
function useShowTabBar() {
const route2 = usePageRoute();
const tabBar = useTabBar();
const showTabBar22 = computed(() => route2.meta.isTabBar && tabBar.shown);
updateCssVar({
"--tab-bar-height": tabBar.height
});
return showTabBar22;
}
function useTopWindow(layoutState2) {
const { component, style } = __uniConfig.topWindow;
const windowRef = ref(null);
function updateWindow() {
const instance2 = windowRef.value;
if (!instance2) {
return;
}
const el = instance2.$el;
if (!el) {
return;
}
const uniTopWindowStyleEl = el.parentElement;
if (!uniTopWindowStyleEl) {
return;
}
const height = uniTopWindowStyleEl.getBoundingClientRect().height;
layoutState2.topWindowHeight = height;
}
watch(
() => windowRef.value,
() => {
updateWindow();
}
);
watch(
() => layoutState2.showTopWindow || layoutState2.apiShowTopWindow,
() => nextTick(updateWindow)
);
watch(
() => layoutState2.topWindowStyle,
() => nextTick(updateWindow)
);
layoutState2.topWindowStyle = style;
return {
component,
windowRef
};
}
function useLeftWindow(layoutState2) {
const { component, style } = __uniConfig.leftWindow;
const windowRef = ref(null);
function updateWindow() {
const instance2 = windowRef.value;
if (!instance2) {
return;
}
const el = instance2.$el;
if (!el) {
return;
}
const uniLeftWindowStyleEl = el.parentElement && el.parentElement.parentElement;
if (!uniLeftWindowStyleEl) {
return;
}
const width = uniLeftWindowStyleEl.getBoundingClientRect().width;
layoutState2.leftWindowWidth = width;
}
watch(
() => windowRef.value,
() => {
updateWindow();
}
);
watch(
() => layoutState2.showLeftWindow || layoutState2.apiShowLeftWindow,
() => nextTick(updateWindow)
);
watch(
() => layoutState2.leftWindowStyle,
() => nextTick(updateWindow)
);
layoutState2.leftWindowStyle = style;
return {
component,
windowRef
};
}
function useRightWindow(layoutState2) {
const { component, style } = __uniConfig.rightWindow;
const windowRef = ref(null);
function updateWindow() {
const instance2 = windowRef.value;
if (!instance2) {
return;
}
const el = instance2.$el;
if (!el) {
return;
}
const uniRightWindowStyleEl = el.parentElement && el.parentElement.parentElement;
if (!uniRightWindowStyleEl) {
return;
}
const width = uniRightWindowStyleEl.getBoundingClientRect().width;
layoutState2.rightWindowWidth = width;
}
watch(
() => windowRef.value,
() => {
updateWindow();
}
);
watch(
() => layoutState2.showRightWindow || layoutState2.apiShowRightWindow,
() => nextTick(updateWindow)
);
watch(
() => layoutState2.rightWindowStyle,
() => nextTick(updateWindow)
);
layoutState2.rightWindowStyle = style;
return {
component,
windowRef
};
}
const n49 = t5$3();
renderEffect(() => setClass(n49, unref(clazz)));
setInsertionState(n49);
createIf(
() => unref(hasResponsive),
() => {
const n36 = t4$4();
const n35 = child(n36);
const n34 = next(n35);
const n15 = child(n34);
renderEffect(() => {
const _layoutState = unref(layoutState);
setClassName(n36, (unref(hasTopWindow) && _layoutState.showTopWindow ? 1 : 0) | (unref(hasLeftWindow) && _layoutState.showLeftWindow ? 2 : 0) | (unref(hasRightWindow) && _layoutState.showRightWindow ? 4 : 0), [" uni-app--showtopwindow", " uni-app--showleftwindow", " uni-app--showrightwindow"]);
});
setInsertionState(n36, n35);
createIf(() => unref(hasTopWindow) && unref(TopWindow), () => {
const n7 = t0$F();
const n5 = child(n7);
const n6 = next(n5);
renderEffect(() => setStyle(n5, unref(layoutState).topWindowStyle));
setInsertionState(n5);
const n4 = withComponentId("7b5159a7", () => createDynamicComponent(() => unref(TopWindow), {
"navigation-bar-title-text": () => unref(layoutState).navigationBarTitleText,
$: [
() => unref(windowState)
]
}));
setStaticTemplateRef(n4, topWindowRef, null, "topWindowRef");
applyVShow(n7, () => unref(layoutState).showTopWindow || unref(layoutState).apiShowTopWindow);
renderEffect(() => setStyle(n6, { height: unref(layoutState).topWindowHeight + "px" }));
return n7;
});
setInsertionState(n15);
createIf(
() => {
var _a;
return unref(hasPages) && ((_a = unref(route)) == null ? void 0 : _a.meta.route);
},
() => {
const n12 = withComponentId("2251cd94", () => createComponent$1(unref(VaporRouterView), { type: () => unref(isTabBar) ? "tabBar" : "" }, (_slotProps0) => {
const n11 = withComponentId("2251bf54", () => createComponent$1(
VaporKeepAlive,
{
"match-by": "key",
cache: () => unref(routeCache2)
},
extend$1(() => {
const n10 = withComponentId("2251bdde", () => createDynamicComponent(() => _slotProps0.Component, null, null, 5, () => unref(routeKey)));
return n10;
}, {
_: 1
/* NON_STABLE */
}),
2
/* SLOT */
));
return n11;
}));
return n12;
},
() => createIf(() => !unref(hasPages), () => {
const n14 = withComponentId("2251b652", () => createDynamicComponent(() => unref(firstPageComponent)));
return n14;
}),
525
/* TRUE_SINGLE_ROOT, FALSE_ELSE_IF, KEYED_INDEX_1 */
);
setInsertionState(n34, 1);
createIf(() => unref(hasLeftWindow) && unref(LeftWindow), () => {
const n24 = t2$a();
const n23 = child(n24);
const n22 = next(n23);
renderEffect(() => {
const _layoutState = unref(layoutState);
setAttr(n24, "data-show", _layoutState.apiShowLeftWindow || void 0);
setStyle(n24, _layoutState.leftWindowStyle);
});
setInsertionState(n24, n23);
createIf(() => unref(layoutState).apiShowLeftWindow, () => {
const n20 = t1$k();
on$1(n20, "click", () => unref(layoutState).apiShowLeftWindow = false);
return n20;
});
setInsertionState(n22);
const n21 = withComponentId("2250de56", () => createDynamicComponent(() => unref(LeftWindow), { $: [
() => unref(windowState)
] }));
setStaticTemplateRef(n21, leftWindowRef, null, "leftWindowRef");
applyVShow(n24, () => unref(layoutState).showLeftWindow || unref(layoutState).apiShowLeftWindow);
return n24;
});
setInsertionState(n34, 2);
createIf(() => unref(hasRightWindow) && unref(RightWindow), () => {
const n33 = t3$7();
const n32 = child(n33);
const n31 = next(n32);
renderEffect(() => {
const _layoutState = unref(layoutState);
setAttr(n33, "data-show", _layoutState.apiShowRightWindow || void 0);
setStyle(n33, _layoutState.rightWindowStyle);
});
setInsertionState(n33, n32);
createIf(() => unref(layoutState).apiShowRightWindow, () => {
const n29 = t1$k();
on$1(n29, "click", () => unref(layoutState).apiShowRightWindow = false);
return n29;
});
setInsertionState(n31);
const n30 = withComponentId("22500414", () => createDynamicComponent(() => unref(RightWindow), { $: [
() => unref(windowState)
] }));
setStaticTemplateRef(n30, rightWindowRef, null, "rightWindowRef");
applyVShow(n33, () => unref(layoutState).showRightWindow || unref(layoutState).apiShowRightWindow);
return n33;
});
return n36;
},
() => {
const n38 = createIf(
() => {
var _a;
return unref(hasPages) && ((_a = unref(route)) == null ? void 0 : _a.meta.route);
},
() => {
const n42 = withComponentId("224ff418", () => createComponent$1(unref(VaporRouterView), { type: () => unref(isTabBar) ? "tabBar" : "" }, (_slotProps0) => {
const n41 = withComponentId("224fe654", () => createComponent$1(
VaporKeepAlive,
{
"match-by": "key",
cache: () => unref(routeCache2)
},
extend$1(() => {
const n40 = withComponentId("224fe510", () => createDynamicComponent(() => _slotProps0.Component, null, null, 5, () => unref(routeKey)));
return n40;
}, {
_: 1
/* NON_STABLE */
}),
2
/* SLOT */
));
return n41;
}));
return n42;
},
() => createIf(() => !unref(hasPages), () => {
const n44 = withComponentId("224fdd9c", () => createDynamicComponent(() => unref(firstPageComponent)));
return n44;
}),
2317
/* TRUE_SINGLE_ROOT, FALSE_ELSE_IF, KEYED_INDEX_8 */
);
return n38;
},
2057
/* TRUE_SINGLE_ROOT, FALSE_MULTI_ROOT, KEYED_INDEX_7 */
);
setInsertionState(n49, 1);
createIf(() => unref(hasTabBar), () => {
const n48 = withComponentId("224fd694", () => createComponent$1(_sfc_main$G));
applyVShow(n48, () => unref(showTabBar2));
return n48;
});
setStaticTemplateRef(n49, rootRef, null, "rootRef");
return n49;
}
});
const t0$E = template("<div class=uni-async-loading><i class=uni-loading>", 3);
const _sfc_main$E = /* @__PURE__ */ defineVaporComponent({
...{
name: "AsyncLoading",
__reserved: true,
compatConfig: { MODE: 3 }
},
__name: "asyncLoading",
setup(__props) {
const n0 = t0$E();
return n0;
}
});
const t0$D = template("<div class=uni-async-error> ", 1);
const _sfc_main$D = /* @__PURE__ */ defineVaporComponent({
...{
name: "AsyncError",
__reserved: true,
compatConfig: { MODE: 3 }
},
__name: "asyncError",
props: ["error"],
setup(__props) {
initI18nAsyncMsgsOnce();
const { t: t12 } = useI18n();
function reload() {
window.location.reload();
}
const n0 = t0$D();
const x0 = txt(n0);
on$1(n0, "click", reload);
renderEffect(() => setText(x0, toDisplayString(unref(t12)("uni.async.error"))));
return n0;
}
});
let appVm;
let $uniApp;
let uniAppVmMethodNames = /* @__PURE__ */ new Set();
{
class UniAppImpl {
get vm() {
return appVm;
}
get $vm() {
return appVm;
}
get globalData() {
return (appVm == null ? void 0 : appVm.globalData) || {};
}
getAndroidApplication() {
return null;
}
getHarmonyAbility() {
return null;
}
}
const uniApp = new UniAppImpl();
$uniApp = process.env.NODE_ENV !== "production" ? new Proxy(uniApp, {
get(target, key, receiver) {
const value = Reflect.get(target, key, receiver);
if (typeof key === "string" && value === void 0 && uniAppVmMethodNames.has(key)) {
warnUniAppVmMethod(key);
}
return value;
}
}) : uniApp;
}
function getApp$1() {
{
return $uniApp;
}
}
function initApp$1(vm) {
appVm = vm;
if (process.env.NODE_ENV !== "production") {
const initVmMethodWarnings = () => {
uniAppVmMethodNames = initUniAppVmMethodWarnings($uniApp);
};
onBeforeMount(initVmMethodWarnings);
onServerPrefetch(initVmMethodWarnings);
}
Object.defineProperty(appVm.$.ctx, "$children", {
get() {
return getCurrentBasePages().map((page) => page.$vm);
}
});
const app = appVm.$.appContext.app;
if (!app.component(_sfc_main$E.name)) {
app.component(_sfc_main$E.name, _sfc_main$E);
}
if (!app.component(_sfc_main$D.name)) {
app.component(_sfc_main$D.name, _sfc_main$D);
}
initAppVm(appVm);
defineGlobalData(appVm);
initService();
initView();
{
updateAppBodyScopeId(appVm);
}
}
function updateAppBodyScopeId(vm) {
const scopeId = getScopeId(vm.$);
if (scopeId) {
document.body.setAttribute(scopeId, "");
}
}
function wrapperComponentSetup(comp, { type, clone, init: init2, setup, before, options }) {
if (clone) {
comp = extend({}, comp);
}
before && before(comp);
const oldSetup = comp.setup;
comp.setup = (props2, ctx) => {
const instance2 = getCurrentInstance();
init2(instance2.proxy);
setup(instance2);
if (oldSetup) {
return oldSetup(props2, ctx);
}
if (type === "page") {
initUniPageHooks();
}
};
if (type === "page" || type === "window") {
const styleIsolation = comp.styleIsolation || (__uniConfig.styleIsolation || {})[comp.__filename];
if (styleIsolation !== "isolated") {
comp.styleIsolation = "app";
}
}
return comp;
}
function setupComponent(comp, options) {
if (comp && (comp.__esModule || comp[Symbol.toStringTag] === "Module")) {
return wrapperComponentSetup(comp.default, options);
}
return wrapperComponentSetup(comp, options);
}
function setupWindow(comp, id2) {
return setupComponent(comp, {
type: "window",
init: (vm) => {
{
vm.$basePage = {
id: id2
};
}
},
setup(instance2) {
instance2.$pageInstance = instance2;
}
});
}
function setupPage(comp, path) {
if (process.env.NODE_ENV !== "production") {
comp.__mpType = "page";
}
if (path) {
comp.__filename = path;
}
return setupComponent(comp, {
type: "page",
clone: true,
// 页面组件可能会被其他地方手动引用,比如 windows 等,需要 clone 一份新的作为页面组件
before(comp2) {
comp2.inheritAttrs = false;
},
init: initPage,
setup(instance2) {
instance2.$pageInstance = instance2;
const route = usePageRoute();
const router2 = __UNI_FEATURE_PAGES__ ? useRouter() : void 0;
const query = decodedQuery(route.query);
instance2.__pageQuery = query;
{
const pageInstance = getPageInstanceByChild(instance2);
if (isDialogPageInstance(pageInstance)) {
const dialogQuery = decodedQuery(
parseQuery(
(pageInstance == null ? void 0 : pageInstance.attrs.route).split("?")[1] || ""
)
);
instance2.__pageQuery = dialogQuery;
}
}
getPage$BasePage(instance2.proxy).options = query;
instance2.proxy.options = query;
const pageMeta = usePageMeta();
updateCurPageCssVar(pageMeta);
instance2.onReachBottom = reactive([]);
instance2.onPageScroll = reactive([]);
watch(
[instance2.onReachBottom, instance2.onPageScroll],
() => {
const currentPage = getCurrentPage().vm;
if (instance2.proxy === currentPage) {
initPageScrollListener(instance2, pageMeta);
}
},
{ once: true }
);
onBeforeMount(() => {
onPageShow(instance2, pageMeta);
{
const pageInstance = getPageInstanceByChild(instance2);
if (!isDialogPageInstance(pageInstance)) {
dispatchWebAppRoute(router2 == null ? void 0 : router2.currentRoute.value);
}
}
});
onMounted(() => {
var _a;
{
const pageInstance = getPageInstanceByChild(instance2);
if (isDialogPageInstance(pageInstance)) {
useBackgroundColorContent$1(instance2.proxy);
}
dialogPageTriggerParentHide((_a = instance2.proxy) == null ? void 0 : _a.$page);
}
onPageReady(instance2);
const { onReady: onReady2 } = instance2;
onReady2 && invokeArrayFns$1(onReady2);
invokeOnTabItemTap(route);
});
onBeforeActivate(() => {
var _a;
if (!instance2.__isVisible) {
onPageShow(instance2, pageMeta);
instance2.__isVisible = true;
{
const pageInstance = getPageInstanceByChild(instance2);
if (!isDialogPageInstance(pageInstance)) {
const { onShow } = instance2;
onShow && invokeArrayFns$1(onShow);
dispatchWebAppRoute(router2 == null ? void 0 : router2.currentRoute.value);
invokeLastDialogPageHookByUniPage(
(_a = instance2.proxy) == null ? void 0 : _a.$page,
ON_SHOW
);
}
}
nextTick(() => {
invokeOnTabItemTap(route);
});
}
});
onBeforeDeactivate(() => {
var _a;
if (instance2.__isVisible && !instance2.__isUnload) {
instance2.__isVisible = false;
{
const pageInstance = getPageInstanceByChild(instance2);
if (!isDialogPageInstance(pageInstance)) {
const { onHide } = instance2;
onHide && invokeArrayFns$1(onHide);
invokeLastDialogPageHookByUniPage(
(_a = instance2.proxy) == null ? void 0 : _a.$page,
ON_HIDE
);
}
}
}
});
const pageId = getPageProxyId(instance2.proxy);
subscribeViewMethod(pageId);
onBeforeUnmount(() => {
unsubscribeViewMethod(pageId);
});
return query;
}
});
}
function setupApp(comp) {
if (process.env.NODE_ENV !== "production") {
comp.__mpType = "app";
}
return setupComponent(comp, {
init: initApp$1,
setup(instance2) {
const route = usePageRoute();
const onLaunch = (launchRoute = route) => {
injectAppHooks(instance2);
const { onLaunch: onLaunch2, onShow, onPageNotFound: onPageNotFound2 } = instance2;
const path = launchRoute.path.slice(1);
const launchOptions2 = initLaunchOptions({
path: path || __uniRoutes[0].meta.route,
query: decodedQuery(launchRoute.query)
});
onLaunch2 && invokeArrayFns$1(onLaunch2, launchOptions2);
onShow && invokeArrayFns$1(onShow, launchOptions2);
const originalUrl = __UNI_FEATURE_PAGES__ ? launchRoute.fullPath : launchRoute.path + stringifyQuery$1(launchRoute.query);
const resolved = resolveAppRoute(
originalUrl,
"appLaunch",
__UNI_FEATURE_PAGES__ && !launchRoute.matched.length
);
if (!__UNI_FEATURE_PAGES__) {
setSinglePageAppRoute(resolved, originalUrl);
}
return resolved;
};
if (__UNI_FEATURE_PAGES__) {
registerWebAppRouteLaunchExecutor(async (launchRoute) => {
await Promise.resolve();
return onLaunch(launchRoute);
});
} else {
onBeforeMount(onLaunch);
}
onMounted(() => {
window.addEventListener(
"resize",
debounce(onResize$1, 50, { setTimeout, clearTimeout })
);
window.addEventListener("message", onMessage);
document.addEventListener("visibilitychange", onVisibilityChange$1);
onThemeChange$1();
});
return route.query;
},
before(comp2) {
comp2.mpType = "app";
const { setup } = comp2;
const render = () => {
return createComponent$1(_sfc_main$F, null, null, true);
};
comp2.setup = (props2, ctx) => {
const res = setup && setup(props2, ctx);
if (isPromise(res)) {
return res.then((value) => value || EMPTY_OBJ);
}
return isFunction(res) ? render : res;
};
comp2.render = render;
}
});
}
function onResize$1() {
const { windowWidth, windowHeight, screenWidth, screenHeight } = uni.getSystemInfoSync();
const landscape = Math.abs(Number(window.orientation)) === 90;
const deviceOrientation = landscape ? "landscape" : "portrait";
UniServiceJSBridge.emit(ON_RESIZE, {
deviceOrientation,
size: {
windowWidth,
windowHeight,
screenWidth,
screenHeight
}
});
}
function onMessage(evt) {
if (isPlainObject(evt.data) && evt.data.type === WEB_INVOKE_APPSERVICE) {
UniServiceJSBridge.emit(
ON_WEB_INVOKE_APP_SERVICE,
evt.data.data,
evt.data.pageId
);
}
}
function onVisibilityChange$1() {
const { emit: emit2 } = UniServiceJSBridge;
if (document.visibilityState === "visible") {
emit2(ON_APP_ENTER_FOREGROUND, getEnterOptions());
} else {
emit2(ON_APP_ENTER_BACKGROUND);
}
}
function onThemeChange$1() {
let mediaQueryList = null;
try {
mediaQueryList = window.matchMedia("(prefers-color-scheme: dark)");
} catch (error) {
}
if (mediaQueryList) {
let callback = (e2) => {
UniServiceJSBridge.emit(ON_THEME_CHANGE, {
theme: e2.matches ? "dark" : "light"
});
};
if (mediaQueryList.addEventListener) {
mediaQueryList.addEventListener("change", callback);
} else {
mediaQueryList.addListener(callback);
}
}
}
function invokeOnTabItemTap(route) {
const { tabBarText, tabBarIndex, route: pagePath } = route.meta;
if (tabBarText) {
invokeHook("onTabItemTap", {
index: tabBarIndex,
text: tabBarText,
pagePath
});
}
}
function updateDocumentTitle(title) {
if (title && title !== document.title) {
document.title = title;
}
UniServiceJSBridge.emit(ON_NAVIGATION_BAR_CHANGE, { titleText: title });
}
function useDocumentTitle(pageMeta) {
function update() {
updateDocumentTitle(pageMeta.navigationBar.titleText);
}
watchEffect(update);
onActivated(update);
}
function updateBackgroundColorContent(backgroundColorContent) {
if (backgroundColorContent) {
document.body.style.setProperty(
"--background-color-content",
backgroundColorContent
);
} else {
document.body.style.removeProperty("--background-color-content");
}
}
function useBackgroundColorContent(pageMeta) {
function update() {
if (pageMeta.backgroundColorContent) {
updateBackgroundColorContent(
parseTheme({ backgroundColorContent: pageMeta.backgroundColorContent }).backgroundColorContent
);
} else {
updateBackgroundColorContent("transparent");
}
}
onThemeChange$2(update);
watchEffect(update);
onActivated(update);
}
const _UniLoadingElement = class _UniLoadingElement extends UniViewElement {
};
_UniLoadingElement.__uniElement = {};
let UniLoadingElement = _UniLoadingElement;
function useLoadingStyle(targetElement, bold) {
const loadingSize = ref("16px");
const loadingBorderWidth = ref("1px");
const loadingBorderRadius = ref("8px");
let observer = null;
const calculateLoadingWidth = (element, bold2) => {
const { width, height } = element.getBoundingClientRect();
const coefficient = bold2 ? 2 : 1;
const minSide = Math.min(width, height);
const calculatedWidth = minSide / 16 * coefficient;
loadingSize.value = `${minSide}px`;
loadingBorderWidth.value = `${calculatedWidth}px`;
loadingBorderRadius.value = `${minSide / 2}px`;
};
const setupObserver = (cb) => {
const el = targetElement.value;
if (!el)
return;
observer = new ResizeObserver((entries2) => {
cb(el);
});
observer.observe(el);
};
onMounted(() => {
setupObserver((el) => {
calculateLoadingWidth(el, bold.value);
});
watchEffect(() => {
const _bold = bold.value;
const el = targetElement.value;
if (el !== null) {
calculateLoadingWidth(el, _bold);
}
});
});
onUnmounted(() => {
if (observer) {
observer.disconnect();
}
});
return {
width: loadingSize,
height: loadingSize,
borderWidth: loadingBorderWidth
// borderRadius: loadingBorderRadius,
};
}
const t0$C = template('<div uni-loading uni-view data-v-212d40c7 class="default __uni_loading_container__" style="display: flex;"><div uni-view data-v-212d40c7>', 257);
const _uniLoadingElement = { value: "LOADING" };
const _sfc_main$C = /* @__PURE__ */ defineVaporComponent({
...{
name: "loading",
styleIsolation: "app-and-page",
// @ts-ignore
rootElement: {
class: /* @__PURE__ */ initUniElementType(UniLoadingElement, "loading")
}
},
__name: "loading",
props: {
paused: { type: Boolean, default: false },
bold: { type: Boolean, default: false },
iosSpinner: { type: Boolean, default: false }
},
setup(__props) {
const props2 = __props;
const LoadingRef = ref(null);
const loadingStyle = reactive(useLoadingStyle(LoadingRef, computed(() => props2.bold)));
const n0 = t0$C();
const n1 = child(n0);
initUniElement(n0, _uniLoadingElement);
setStaticTemplateRef(n0, LoadingRef, null, "LoadingRef");
renderEffect(() => {
setClassName(n1, props2.paused ? 1 : 0, " __uni-loading__paused", "__uni-loading__ __loading-4-3__");
setStyle(n1, loadingStyle);
});
return n0;
}
});
function hexToRgba(hex) {
if (!hex) {
return {
r: 0,
g: 0,
b: 0,
a: 0
};
}
let tmpHex = hex.slice(1);
const tmpHexLen = tmpHex.length;
if (![3, 4, 6, 8].includes(tmpHexLen)) {
return {
r: 0,
g: 0,
b: 0,
a: 0
};
}
if (tmpHexLen === 3 || tmpHexLen === 4) {
tmpHex = tmpHex.replace(/(\w{1})/g, "$1$1");
}
let [sr, sg, sb, sa] = tmpHex.match(/(\w{2})/g);
const r = parseInt(sr, 16), g2 = parseInt(sg, 16), b = parseInt(sb, 16);
if (!sa) {
return { r, g: g2, b, a: 1 };
}
return {
r,
g: g2,
b,
a: (`0x100${sa}` - 65536) / 255
};
}
function usePageHeadTransparentBackgroundColor(backgroundColor) {
const { r, g: g2, b } = hexToRgba(backgroundColor);
return `rgba(${r},${g2},${b},0)`;
}
function usePageHeadTransparent(headRef, {
id: id2,
navigationBar: { titleColor, coverage, backgroundColor }
}) {
let A = 0;
const rgb = computed(() => hexToRgba(backgroundColor));
const offset = parseInt(coverage);
let titleElem;
let transparentElemStyle;
const iconElemsPaths = [];
const borderRadiusElemsStyles = [];
const oldColors = [];
onMounted(() => {
const $el = headRef.value;
transparentElemStyle = $el.style;
titleElem = $el.querySelector(".uni-page-head__title");
const borderRadiusElems = $el.querySelectorAll(
".uni-page-head-btn"
);
const iconSvgElems = $el.querySelectorAll(
"svg path"
);
for (let i = 0; i < iconSvgElems.length; i++) {
iconElemsPaths.push(iconSvgElems[i]);
}
for (let i = 0; i < borderRadiusElems.length; i++) {
const borderRadiusElem = borderRadiusElems[i];
oldColors.push(getComputedStyle(borderRadiusElem).backgroundColor);
borderRadiusElemsStyles.push(borderRadiusElem.style);
}
});
useOn(id2 + ".onPageScroll", ({ scrollTop }) => {
const alpha = Math.min(scrollTop / offset, 1);
if (alpha === 1 && A === 1) {
return;
}
if (alpha > 0.5 && A <= 0.5) {
iconElemsPaths.forEach(function(iconElemPath) {
iconElemPath.setAttribute("fill", titleColor);
});
} else if (alpha <= 0.5 && A > 0.5) {
iconElemsPaths.forEach(function(iconElemPath) {
iconElemPath.setAttribute("fill", "#fff");
});
}
A = alpha;
if (titleElem) {
titleElem.style.opacity = alpha;
}
const bg = rgb.value;
transparentElemStyle.backgroundColor = `rgba(${bg.r},${bg.g},${bg.b},${alpha})`;
borderRadiusElemsStyles.forEach(function(borderRadiusElemStyle, index2) {
const oldColor = oldColors[index2];
const rgba = oldColor.match(/[\d+\.]+/g);
rgba[3] = (1 - alpha) * (rgba.length === 4 ? rgba[3] : 1);
borderRadiusElemStyle.backgroundColor = `rgba(${rgba})`;
});
});
}
const t0$B = template('<div class=uni-page-head-btn><svg width=26 height=26 viewBox="0 0 32 32"><path fill=none stroke-width=2 stroke-linecap=round>');
const t1$j = template('<svg viewBox="0 0 32 32"><path>', 0, 1);
const t2$9 = template('<span><i class=uni-btn-icon></i><svg width=14 height=14 viewBox="0 0 32 32"><path fill=none stroke=#000 stroke-width=2 stroke-linecap=round>');
const t3$6 = template("<i class=uni-btn-icon></i>");
const t4$3 = template("<div>");
const t5$2 = template("<i class=uni-loading></i>", 2);
const t6$2 = template("<img class=uni-page-head__title_image>");
const t7$1 = template(" ");
const t8 = template("<div class=uni-page-head-bd><div class=uni-page-head__title></div>");
const t9 = template('<div class=uni-page-head-search><div><div class=uni-page-head-search-icon><svg width=20 height=20 viewBox="0 0 32 32"><path></div></div>');
const t10 = template('<span><i class=uni-btn-icon></i><svg width=14 height=14 viewBox="0 0 32 32"><path fill=#000>');
const t11 = template("<uni-page-head><div><div class=uni-page-head-hd></div><!><div class=uni-page-head-ft></div></div>", 1);
const _sfc_main$B = /* @__PURE__ */ defineVaporComponent({
...{
name: "PageHead",
__reserved: true,
compatConfig: { MODE: 3 }
},
__name: "pageHead",
setup(__props) {
const hasPages = __UNI_FEATURE_PAGES__;
const hasButtons = __UNI_FEATURE_NAVIGATIONBAR_BUTTONS__;
const hasSearchInput = __UNI_FEATURE_NAVIGATIONBAR_SEARCHINPUT__;
const isXVapor = true;
const ICON_PATHS = {
none: "",
forward: "M11 7.844q-0.25-0.219-0.25-0.578t0.25-0.578q0.219-0.25 0.563-0.25t0.563 0.25l9.656 9.125q0.125 0.125 0.188 0.297t0.063 0.328q0 0.188-0.063 0.359t-0.188 0.297l-9.656 9.125q-0.219 0.25-0.563 0.25t-0.563-0.25q-0.25-0.219-0.25-0.578t0.25-0.609l9.063-8.594-9.063-8.594z",
back: ICON_PATH_BACK,
select: ICON_PATH_BACK,
share: "M26.563 24.844q0 0.125-0.109 0.234t-0.234 0.109h-17.938q-0.125 0-0.219-0.109t-0.094-0.234v-13.25q0-0.156 0.094-0.25t0.219-0.094h5.5v-1.531h-6q-0.531 0-0.906 0.391t-0.375 0.922v14.375q0 0.531 0.375 0.922t0.906 0.391h18.969q0.531 0 0.891-0.391t0.359-0.953v-5.156h-1.438v4.625zM29.813 10.969l-5.125-5.375-1.031 1.094 3.438 3.594-3.719 0.031q-2.313 0.188-4.344 1.125t-3.578 2.422-2.5 3.453-1.109 4.188l-0.031 0.25h1.469v-0.219q0.156-1.875 1-3.594t2.25-3.063 3.234-2.125 3.828-0.906l0.188-0.031 3.313-0.031-3.438 3.625 1.031 1.063 5.125-5.375-0.031-0.063 0.031-0.063z",
favorite: "M27.594 13.375q-0.063-0.188-0.219-0.313t-0.344-0.156l-7.094-0.969-3.219-6.406q-0.094-0.188-0.25-0.281t-0.375-0.094q-0.188 0-0.344 0.094t-0.25 0.281l-3.125 6.438-7.094 1.094q-0.188 0.031-0.344 0.156t-0.219 0.313q-0.031 0.188 0.016 0.375t0.172 0.313l5.156 4.969-1.156 7.063q-0.031 0.188 0.047 0.375t0.234 0.313q0.094 0.063 0.188 0.094t0.219 0.031q0.063 0 0.141-0.031t0.172-0.063l6.313-3.375 6.375 3.313q0.063 0.031 0.141 0.047t0.172 0.016q0.188 0 0.344-0.094t0.25-0.281q0.063-0.094 0.078-0.234t-0.016-0.234q0-0.031 0-0.063l-1.25-6.938 5.094-5.031q0.156-0.156 0.203-0.344t-0.016-0.375zM11.469 19.063q0.031-0.188-0.016-0.344t-0.172-0.281l-4.406-4.25 6.063-0.906q0.156-0.031 0.297-0.125t0.203-0.25l2.688-5.531 2.75 5.5q0.063 0.156 0.203 0.25t0.297 0.125l6.094 0.844-4.375 4.281q-0.125 0.125-0.172 0.297t-0.016 0.328l1.063 6.031-5.438-2.813q-0.156-0.094-0.328-0.078t-0.297 0.078l-5.438 2.875 1-6.031z",
home: "M23.719 16.5q-0.313 0-0.531 0.219t-0.219 0.5v7.063q0 0.219-0.172 0.391t-0.391 0.172h-12.344q-0.25 0-0.422-0.172t-0.172-0.391v-7.063q0-0.281-0.219-0.5t-0.531-0.219q-0.281 0-0.516 0.219t-0.234 0.5v7.063q0.031 0.844 0.625 1.453t1.438 0.609h12.375q0.844 0 1.453-0.609t0.609-1.453v-7.063q0-0.125-0.063-0.266t-0.156-0.234q-0.094-0.125-0.234-0.172t-0.297-0.047zM26.5 14.875l-8.813-8.813q-0.313-0.313-0.688-0.453t-0.781-0.141-0.781 0.141-0.656 0.422l-8.813 8.844q-0.188 0.219-0.188 0.516t0.219 0.484q0.094 0.125 0.234 0.172t0.297 0.047q0.125 0 0.25-0.047t0.25-0.141l8.781-8.781q0.156-0.156 0.406-0.156t0.406 0.156l8.813 8.781q0.219 0.188 0.516 0.188t0.516-0.219q0.188-0.188 0.203-0.484t-0.172-0.516z",
menu: "M8.938 18.313q0.875 0 1.484-0.609t0.609-1.453-0.609-1.453-1.484-0.609q-0.844 0-1.453 0.609t-0.609 1.453 0.609 1.453 1.453 0.609zM16.188 18.313q0.875 0 1.484-0.609t0.609-1.453-0.609-1.453-1.484-0.609q-0.844 0-1.453 0.609t-0.609 1.453 0.609 1.453 1.453 0.609zM23.469 18.313q0.844 0 1.453-0.609t0.609-1.453-0.609-1.453-1.453-0.609q-0.875 0-1.484 0.609t-0.609 1.453 0.609 1.453 1.484 0.609z",
close: ICON_PATH_CLOSE
};
const headRef = ref(null);
const pageMeta = usePageMeta();
const navigationBar = useTheme(pageMeta.navigationBar, () => {
const _navigationBar = parseTheme(pageMeta.navigationBar);
navigationBar.backgroundColor = _navigationBar.backgroundColor;
navigationBar.titleColor = _navigationBar.titleColor;
});
const { clazz, style } = usePageHead(navigationBar);
const buttons = hasButtons && usePageHeadButtons(pageMeta);
const searchInput = hasSearchInput && navigationBar.searchInput && usePageHeadSearchInput(pageMeta);
const searchFocus = searchInput && searchInput.focus;
const searchText = searchInput && searchInput.text;
const searchComposing = searchInput && searchInput.composing;
const searchOnClick = searchInput && searchInput.onClick;
const searchOnFocus = searchInput && searchInput.onFocus;
const searchOnBlur = searchInput && searchInput.onBlur;
const searchOnInput = searchInput && searchInput.onInput;
const searchOnConfirm = searchInput && searchInput.onConfirm;
__UNI_FEATURE_NAVIGATIONBAR_TRANSPARENT__ && navigationBar.type === "transparent" && usePageHeadTransparent(headRef, pageMeta);
function getSvgSize(size) {
return size == null ? 27 : size;
}
function getSvgColor(color) {
return color == null ? "#000" : color;
}
function onPageHeadBackButton() {
if (getCurrentPages().length === 1) {
uni.reLaunch({
url: "/"
});
} else {
uni.navigateBack({
from: "backbutton",
success() {
}
// 传入空方法,避免返回Promise,因为onBackPress可能导致fail
});
}
}
function usePageHead(navigationBar2) {
const clazz2 = computed(() => {
const { type, titlePenetrate, shadowColorType } = navigationBar2;
const clazz3 = {
"uni-page-head": true,
"uni-page-head-transparent": type === "transparent",
"uni-page-head-titlePenetrate": titlePenetrate === "YES",
"uni-page-head-shadow": !!shadowColorType
};
if (shadowColorType) {
clazz3[`uni-page-head-shadow-${shadowColorType}`] = true;
}
return clazz3;
});
const style2 = computed(() => {
const backgroundColor = __UNI_FEATURE_NAVIGATIONBAR_TRANSPARENT__ && navigationBar2.type === "transparent" ? usePageHeadTransparentBackgroundColor(navigationBar2.backgroundColor) : navigationBar2.backgroundColor;
return {
backgroundColor,
color: navigationBar2.titleColor,
transitionDuration: navigationBar2.duration,
transitionTimingFunction: navigationBar2.timingFunc
};
});
return { clazz: clazz2, style: style2 };
}
function usePageHeadButtons({ id: id2, navigationBar: navigationBar2 }) {
const left = [];
const right = [];
const { buttons: buttons2 } = navigationBar2;
if (isArray(buttons2)) {
const { type } = navigationBar2;
const isTransparent = type === "transparent";
const fonts = /* @__PURE__ */ Object.create(null);
buttons2.forEach((btn, index2) => {
if (btn.fontSrc && !btn.fontFamily) {
const fontSrc = getRealPath(btn.fontSrc);
let fontFamily = fonts[fontSrc];
if (!fontFamily) {
fontFamily = `font${Date.now()}`;
fonts[fontSrc] = fontFamily;
onBeforeMount(
() => updateStyle(
"uni-btn-" + fontFamily,
`@font-face{font-family: "${fontFamily}";src: url("${fontSrc}") format("truetype")}`
)
);
}
btn.fontFamily = fontFamily;
}
const pageHeadBtn = usePageHeadButton(id2, index2, btn, isTransparent);
if (btn.float === "left") {
left.push(pageHeadBtn);
} else {
right.push(pageHeadBtn);
}
});
}
return { left, right };
}
function usePageHeadButton(pageId, index2, btn, isTransparent) {
const iconStyle = {
color: btn.color,
fontSize: btn.fontSize,
fontWeight: btn.fontWeight
};
if (btn.fontFamily) {
iconStyle.fontFamily = btn.fontFamily;
}
return new Proxy(
{
btnClass: {
"uni-page-head-btn": true,
"uni-page-head-btn-red-dot": !!(btn.redDot || btn.badgeText),
"uni-page-head-btn-select": !!btn.select
},
btnStyle: {
backgroundColor: isTransparent ? btn.background : "transparent",
width: btn.width
},
btnText: "",
btnIconPath: ICON_PATHS[btn.type],
badgeText: btn.badgeText,
iconStyle,
onClick() {
invokeHook(pageId, ON_NAVIGATION_BAR_BUTTON_TAP, extend({ index: index2 }, btn));
},
btnSelect: btn.select
},
{
get(target, key, receiver) {
if (["btnText"].includes(key)) {
return btn.fontSrc && btn.fontFamily ? btn.text.replace("\\u", "&#x") : btn.text;
} else {
return Reflect.get(target, key, receiver);
}
}
}
);
}
function usePageHeadSearchInput({
id: id2,
navigationBar: { searchInput: searchInput2 }
}) {
const focus = ref(false);
const text2 = ref("");
const composing = ref(false);
const { disabled } = searchInput2;
if (disabled) {
const onClick = () => {
invokeHook(id2, ON_NAVIGATION_BAR_SEARCH_INPUT_CLICKED);
};
return { focus, text: text2, composing, onClick };
}
const onFocus = () => {
focus.value = true;
invokeHook(id2, ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED, {
focus: true
});
};
const onBlur = () => {
focus.value = false;
invokeHook(id2, ON_NAVIGATION_BAR_SEARCH_INPUT_FOCUS_CHANGED, {
focus: false
});
};
const onInput = (evt) => {
text2.value = evt.detail.value;
invokeHook(id2, ON_NAVIGATION_BAR_SEARCH_INPUT_CHANGED, {
text: text2.value
});
};
const onConfirm = (evt) => {
invokeHook(id2, ON_NAVIGATION_BAR_SEARCH_INPUT_CONFIRMED, {
text: text2.value
});
};
return { focus, text: text2, composing, onFocus, onBlur, onInput, onConfirm };
}
const n66 = t11();
const n62 = child(n66);
const n19 = child(n62);
const n61 = next(n19);
const n60 = next(n61);
renderEffect(() => {
setAttr(n66, "uni-page-head-type", unref(navigationBar).type || "default");
setClass(n62, unref(clazz));
setStyle(n62, unref(style));
});
setInsertionState(n19);
createIf(() => unref(hasPages) && !unref(pageMeta).isQuit, () => {
const n3 = t0$B();
const n2 = child(child(n3));
on$1(n3, "click", onPageHeadBackButton);
renderEffect(() => {
const _navigationBar = unref(navigationBar);
setAttr(n2, "d", unref(ICON_PATH_BACK), true);
setAttr(
n2,
"stroke",
_navigationBar.type === "transparent" ? "#fff" : _navigationBar.titleColor,
true
);
});
return n3;
});
setInsertionState(n19, 1);
createIf(() => unref(hasButtons) && unref(buttons), () => {
const n6 = createFor(
() => unref(buttons).left,
(_for_item0, _for_key0) => {
const n18 = t4$3();
renderEffect(() => {
const _button = _for_item0.value;
setClass(n18, _button.btnClass);
setStyle(n18, _button.btnStyle);
setAttr(n18, "badge-text", _button.badgeText);
});
setInsertionState(n18);
createIf(
() => _for_item0.value.btnIconPath,
() => {
const n11 = t1$j();
const n10 = child(n11);
renderEffect(() => {
const _button = _for_item0.value;
const _button_iconStyle = _button.iconStyle;
const _getSvgSize_button_iconStyle_fontSize = getSvgSize(_button_iconStyle.fontSize);
setAttr(n11, "width", _getSvgSize_button_iconStyle_fontSize, true);
setAttr(n11, "height", _getSvgSize_button_iconStyle_fontSize, true);
setAttr(n10, "d", _button.btnIconPath, true);
setAttr(n10, "fill", getSvgColor(_button_iconStyle.color), true);
});
return n11;
},
() => createIf(
() => _for_item0.value.btnSelect,
() => {
const n15 = t2$9();
const n13 = child(n15);
const n14 = child(next(n13));
renderEffect(() => {
const _button = _for_item0.value;
setStyle(n15, _button.iconStyle);
setHtml(n13, _button.btnText);
setAttr(n14, "d", ICON_PATHS.select, true);
});
return n15;
},
() => {
const n17 = t3$6();
renderEffect(() => {
const _button = _for_item0.value;
setStyle(n17, _button.iconStyle);
setHtml(n17, _button.btnText);
});
return n17;
},
773
/* TRUE_SINGLE_ROOT, FALSE_SINGLE_ROOT, KEYED_INDEX_2 */
),
525
/* TRUE_SINGLE_ROOT, FALSE_ELSE_IF, KEYED_INDEX_1 */
);
on$1(n18, "click", (e2) => _for_item0.value.onClick(e2));
return n18;
},
(button, index2) => index2,
8
/* IS_SINGLE_NODE */
);
return n6;
});
setInsertionState(n62, n61);
createIf(
() => !unref(hasSearchInput) || !unref(navigationBar).searchInput,
() => {
const n32 = t8();
const n31 = child(n32);
renderEffect(() => {
const _navigationBar = unref(navigationBar);
setStyle(n31, {
fontSize: _navigationBar.titleSize,
opacity: _navigationBar.type === "transparent" ? 0 : 1
});
});
setInsertionState(n31);
createIf(
() => !unref(isXVapor) && unref(navigationBar).loading,
() => {
const n24 = t5$2();
return n24;
},
() => createIf(
() => unref(isXVapor) && unref(navigationBar).loading,
() => {
const n26 = withComponentId("96682308", () => createComponent$1(unref(_sfc_main$C), { style: { "display": "inline-block", "width": "20px", "height": "20px", "margin-top": "7px" } }));
return n26;
},
() => createIf(
() => unref(navigationBar).titleImage,
() => {
const n28 = t6$2();
renderEffect(() => setProp(n28, "src", unref(navigationBar).titleImage));
return n28;
},
() => {
const n30 = t7$1();
renderEffect(() => setText(n30, toDisplayString(unref(navigationBar).titleText)));
return n30;
},
1801
/* TRUE_SINGLE_ROOT, FALSE_MULTI_ROOT, KEYED_INDEX_6 */
),
1549
/* TRUE_SINGLE_ROOT, FALSE_ELSE_IF, KEYED_INDEX_5 */
),
1293
/* TRUE_SINGLE_ROOT, FALSE_ELSE_IF, KEYED_INDEX_4 */
);
return n32;
},
() => {
const n44 = t9();
const n38 = child(n44);
const n34 = child(child(child(n38)));
renderEffect(() => {
const _navigationBar = unref(navigationBar);
const _navigationBar_searchInput = _navigationBar.searchInput;
setStyle(n44, {
borderRadius: _navigationBar_searchInput.borderRadius,
backgroundColor: _navigationBar_searchInput.backgroundColor
});
setStyle(n38, { color: _navigationBar_searchInput.placeholderColor });
setClass(n38, [
"uni-page-head-search-placeholder",
`uni-page-head-search-placeholder-${unref(searchFocus) || unref(searchText) ? "left" : _navigationBar_searchInput.align}`
]);
setAttr(n34, "d", unref(ICON_PATH_SEARCH), true);
setAttr(n34, "fill", _navigationBar_searchInput.placeholderColor, true);
});
setInsertionState(n38, 1);
createIf(
() => !(unref(searchText) || unref(searchComposing)),
() => {
const n37 = t7$1();
renderEffect(() => setText(n37, toDisplayString(unref(navigationBar).searchInput.placeholder)));
return n37;
},
null,
2
/* TRUE_MULTI_ROOT */
);
setInsertionState(n44, 1);
createIf(
() => unref(navigationBar).searchInput.disabled,
() => {
const _on_click = ($event) => unref(searchOnClick) && unref(searchOnClick)($event);
const n41 = withComponentId("96671b3c", () => createComponent$1(unref(__syscom_0$2), {
disabled: true,
style: () => ({ color: unref(navigationBar).searchInput.color }),
"placeholder-style": () => "color: " + unref(navigationBar).searchInput.placeholderColor,
class: "uni-page-head-search-input",
"confirm-type": "search",
onClick: () => _on_click
}));
return n41;
},
() => {
const _on_focus = ($event) => unref(searchOnFocus) && unref(searchOnFocus)($event);
const _on_blur = ($event) => unref(searchOnBlur) && unref(searchOnBlur)($event);
const _on_input = ($event) => unref(searchOnInput) && unref(searchOnInput)($event);
const _on_confirm = ($event) => unref(searchOnConfirm) && unref(searchOnConfirm)($event);
const n43 = withComponentId("96665f1e", () => createComponent$1(unref(__syscom_0$2), {
focus: () => unref(navigationBar).searchInput.autoFocus,
style: () => ({ color: unref(navigationBar).searchInput.color }),
"placeholder-style": () => "color: " + unref(navigationBar).searchInput.placeholderColor,
class: "uni-page-head-search-input",
"confirm-type": "search",
onFocus: () => _on_focus,
onBlur: () => _on_blur,
onInput: () => _on_input,
onConfirm: () => _on_confirm
}));
return n43;
},
2565
/* TRUE_SINGLE_ROOT, FALSE_SINGLE_ROOT, KEYED_INDEX_9 */
);
return n44;
},
2053
/* TRUE_SINGLE_ROOT, FALSE_SINGLE_ROOT, KEYED_INDEX_7 */
);
setInsertionState(n60);
createIf(() => unref(hasButtons) && unref(buttons), () => {
const n47 = createFor(
() => unref(buttons).right,
(_for_item0, _for_key0) => {
const n59 = t4$3();
renderEffect(() => {
const _button = _for_item0.value;
setClass(n59, _button.btnClass);
setStyle(n59, _button.btnStyle);
setAttr(n59, "badge-text", _button.badgeText);
});
setInsertionState(n59);
createIf(
() => _for_item0.value.btnIconPath,
() => {
const n52 = t1$j();
const n51 = child(n52);
renderEffect(() => {
const _button = _for_item0.value;
const _button_iconStyle = _button.iconStyle;
const _getSvgSize_button_iconStyle_fontSize = getSvgSize(_button_iconStyle.fontSize);
setAttr(n52, "width", _getSvgSize_button_iconStyle_fontSize, true);
setAttr(n52, "height", _getSvgSize_button_iconStyle_fontSize, true);
setAttr(n51, "d", _button.btnIconPath, true);
setAttr(n51, "fill", getSvgColor(_button_iconStyle.color), true);
});
return n52;
},
() => createIf(
() => _for_item0.value.btnSelect,
() => {
const n56 = t10();
const n54 = child(n56);
const n55 = child(next(n54));
renderEffect(() => {
const _button = _for_item0.value;
setStyle(n56, _button.iconStyle);
setHtml(n54, _button.btnText);
setAttr(n55, "d", ICON_PATHS.select, true);
});
return n56;
},
() => {
const n58 = t3$6();
renderEffect(() => {
const _button = _for_item0.value;
setStyle(n58, _button.iconStyle);
setHtml(n58, _button.btnText);
});
return n58;
},
3077
/* TRUE_SINGLE_ROOT, FALSE_SINGLE_ROOT, KEYED_INDEX_11 */
),
2829
/* TRUE_SINGLE_ROOT, FALSE_ELSE_IF, KEYED_INDEX_10 */
);
on$1(n59, "click", (e2) => _for_item0.value.onClick(e2));
return n59;
},
(button, index2) => index2,
8
/* IS_SINGLE_NODE */
);
return n47;
});
setStaticTemplateRef(n62, headRef, null, "headRef");
setInsertionState(n66, 1);
createIf(() => unref(navigationBar).type !== "transparent" && unref(navigationBar).type !== "float", () => {
const n65 = t4$3();
renderEffect(() => setClassName(n65, 1 | (unref(navigationBar).titlePenetrate ? 2 : 0), [" uni-placeholder", " uni-placeholder-titlePenetrate"]));
return n65;
});
return n66;
}
});
const t0$A = template('<uni-page-refresh><div class=uni-page-refresh><div class=uni-page-refresh-inner><svg class=uni-page-refresh__icon width=24 height=24 viewBox="0 0 24 24"><path d="M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"></path><path d="M0 0h24v24H0z" fill=none></svg><svg class=uni-page-refresh__spinner width=24 height=24 viewBox="25 25 50 50"><circle class=uni-page-refresh__path cx=50 cy=50 r=20 fill=none stroke-width=4 stroke-miterlimit=10>', 1);
const _sfc_main$A = /* @__PURE__ */ defineVaporComponent({
...{ name: "PageRefresh" },
__name: "component",
setup(__props) {
const { pullToRefresh } = usePageMeta();
const offset = pullToRefresh.offset;
const color = pullToRefresh.color;
const n3 = t0$A();
const n2 = child(n3);
const n0 = child(child(n2));
const n1 = child(next(n0));
renderEffect(() => {
const _color = unref(color);
setStyle(n2, { "margin-top": unref(offset) + "px" });
setAttr(n0, "fill", _color, true);
setAttr(n1, "stroke", _color, true);
});
return n3;
}
});
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 pageMeta = usePageMeta();
const { id: id2, pullToRefresh } = pageMeta;
const { range, height } = pullToRefresh;
let refreshContainerElem;
let refreshControllerElem;
let refreshControllerElemStyle;
let refreshInnerElemStyle;
useSubscribe(
() => {
if (!pageMeta.enablePullDownRefresh) {
return;
}
if (!state) {
state = REFRESHING;
addClass();
setTimeout(() => {
refreshing();
}, 50);
}
},
API_START_PULL_DOWN_REFRESH,
false,
id2
);
useSubscribe(
() => {
if (!pageMeta.enablePullDownRefresh) {
return;
}
if (state === REFRESHING) {
removeClass();
state = RESTORING;
addClass();
restoring(() => {
removeClass();
state = distance = offset = null;
});
}
},
API_STOP_PULL_DOWN_REFRESH,
false,
id2
);
function initElement() {
refreshContainerElem = refreshRef.value.$el;
refreshControllerElem = refreshContainerElem.querySelector(".uni-page-refresh");
refreshControllerElemStyle = refreshControllerElem.style;
refreshInnerElemStyle = refreshControllerElem.querySelector(
".uni-page-refresh-inner"
).style;
}
onMounted(() => {
initElement();
});
{
watch(
() => pageMeta.enablePullDownRefresh,
(enablePullDownRefresh) => {
if (enablePullDownRefresh) {
nextTick(() => {
initElement();
});
}
}
);
}
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) => {
if (!pageMeta.enablePullDownRefresh) {
return;
}
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 (!pageMeta.enablePullDownRefresh) {
return;
}
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;
}
if (ev.cancelable) {
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 (!pageMeta.enablePullDownRefresh) {
return;
}
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(callback) {
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 = "";
callback();
};
refreshControllerElem.addEventListener(
"webkitTransitionEnd",
abortTransitionEnd
);
const timeout = setTimeout(abortTransitionEnd, 350);
} else {
callback();
}
}
function refreshing() {
if (!refreshControllerElem) {
return;
}
refreshControllerElemStyle.transition = "-webkit-transform 0.2s";
refreshControllerElemStyle.transform = "translate3d(-50%, " + height + "px, 0)";
invokeHook(id2, ON_PULL_DOWN_REFRESH);
}
function restoring(callback) {
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)";
callback();
};
refreshControllerElem.addEventListener(
"webkitTransitionEnd",
restoreTransitionEnd
);
const timeout = setTimeout(restoreTransitionEnd, 350);
}
return {
onTouchstartPassive,
onTouchmove,
onTouchend,
onTouchcancel: onTouchend
};
}
const t0$z = template("<uni-page-wrapper><uni-page-body>");
const _sfc_main$z = /* @__PURE__ */ defineVaporComponent({
...{
name: "PageBody",
__reserved: true,
compatConfig: { MODE: 3 }
},
__name: "pageBody",
__multiRoot: true,
setup(__props) {
const isX = true;
const hasPullDownRefresh = __UNI_FEATURE_PULL_DOWN_REFRESH__;
const pageMeta = hasPullDownRefresh ? usePageMeta() : null;
const refreshRef = ref(null);
const wrapperRef = ref(null);
const _pageRefresh = hasPullDownRefresh && pageMeta && (pageMeta.enablePullDownRefresh || isX) ? usePageRefresh(refreshRef) : null;
const pageRefresh = ref(null);
watch(
() => pageMeta == null ? void 0 : pageMeta.enablePullDownRefresh,
() => {
pageRefresh.value = (pageMeta == null ? void 0 : pageMeta.enablePullDownRefresh) ? _pageRefresh : null;
},
{
immediate: true
}
);
function resize() {
const { top, left, right, bottom } = getSafeAreaInsets(wrapperRef.value);
const vars = {
"--uni-safe-area-inset-top": `${top}px`,
"--uni-safe-area-inset-left": `${left}px`,
"--uni-safe-area-inset-right": `${right}px`,
"--uni-safe-area-inset-bottom": `${bottom}px`
};
for (const key in vars) {
wrapperRef.value.style.setProperty(key, vars[key]);
}
}
const n0 = createIf(() => unref(hasPullDownRefresh) && !!unref(pageMeta) && (unref(isX) || !!unref(pageMeta).enablePullDownRefresh), () => {
const n2 = withComponentId("2d14e6de", () => createComponent$1(_sfc_main$A));
setStaticTemplateRef(n2, refreshRef, null, "refreshRef");
return n2;
});
const n8 = t0$z();
const n4 = child(n8);
renderEffect(() => setDynamicProps(n8, [pageRefresh.value]));
setInsertionState(n4);
createSlot();
setInsertionState(n8, 1);
createIf(() => unref(isX), () => {
const n7 = withComponentId("3b76aa59", () => createComponent$1(unref(ResizeSensor), { onResize: () => resize }));
return n7;
});
setStaticTemplateRef(n8, wrapperRef, null, "wrapperRef");
return [n0, n8];
}
});
const t0$y = template("<uni-page>", 1);
const _sfc_main$y = /* @__PURE__ */ defineVaporComponent({
...{
name: "Page",
__reserved: true,
compatConfig: { MODE: 3 }
},
__name: "index-vapor",
setup(__props) {
var _a;
const hasNavigationBar = __UNI_FEATURE_NAVIGATIONBAR__;
const pageStyle = {};
let pageMeta = providePageMeta(getStateId());
const navigationBar = pageMeta.navigationBar;
const currentInstance = getCurrentInstance();
const attrs2 = currentInstance.attrs;
const routeComponent = currentInstance.type;
const pageComponent = routeComponent.__uniPageComponent;
const pageProps = usePageRoute().query;
useDocumentTitle(pageMeta);
currentInstance.$dialogPages = ref([]);
currentInstance.$systemDialogPages = ref([]);
if (isDialogPageInstance(currentInstance)) {
pageMeta.route = attrs2.route;
const routePageMeta = (_a = __uniRoutes.find(
(route) => route.path === pageMeta.route.split("?")[0]
)) == null ? void 0 : _a.meta;
if (routePageMeta) {
routePageMeta.navigationBar = Object.assign(
navigationBar,
routePageMeta.navigationBar
);
pageMeta = Object.assign(pageMeta, routePageMeta);
}
pageMeta.id = createDialogPageId();
if (!(routePageMeta == null ? void 0 : routePageMeta.backgroundColorContent)) {
pageMeta.backgroundColorContent = "transparent";
}
if (!(routePageMeta == null ? void 0 : routePageMeta.navigationBar.style)) {
pageMeta.navigationBar.style = "custom";
}
if (attrs2["data-type"] === SYSTEM_DIALOG_TAG) {
pageMeta.navigationBar.titleText = "";
}
const parentInstance = inject("parentInstance");
if (currentInstance && parentInstance) {
currentInstance.$parentInstance = parentInstance;
assignDialogPage(currentInstance, parentInstance, currentInstance);
}
} else {
useBackgroundColorContent(pageMeta);
provide("parentInstance", currentInstance);
}
function getDialogPages() {
const pages = [
...currentInstance.$dialogPages.value.map((page) => ({
page,
type: DIALOG_TAG
})),
...currentInstance.$systemDialogPages.value.map((page) => ({
page,
type: SYSTEM_DIALOG_TAG
}))
];
pages.sort((a, b) => {
var _a2, _b, _c, _d;
const aId = ((_b = (_a2 = a.page.vm) == null ? void 0 : _a2.$basePage) == null ? void 0 : _b.id) || Number.MAX_SAFE_INTEGER;
const bId = ((_d = (_c = b.page.vm) == null ? void 0 : _c.$basePage) == null ? void 0 : _d.id) || Number.MAX_SAFE_INTEGER;
return aId - bId;
});
return pages.map(({ page, type }) => ({
component: page.$component,
type,
route: `${page.route}${stringifyQuery$1(page.options)}`
}));
}
const dialogPageStyle = {
position: "fixed",
zIndex: 999,
top: 0,
right: 0,
bottom: 0,
left: 0
};
function assignDialogPage(ctx, parentInstance, currentInstance2) {
let parentDialogPages = [];
if (isNormalDialogPageInstance(ctx)) {
parentDialogPages = parentInstance.$dialogPages.value;
}
if (isSystemDialogPageInstance(ctx)) {
parentDialogPages = parentInstance.$systemDialogPages.value;
}
if (!parentDialogPages.length)
return;
for (let i = 0; i < parentDialogPages.length; i++) {
const dialogPage = parentDialogPages[i];
if (!dialogPage.$assigned) {
dialogPage.$assigned = true;
currentInstance2.$dialogPage = dialogPage;
break;
}
}
}
const n8 = t0$y();
renderEffect(() => {
setAttr(n8, "data-page", unref(pageMeta).route);
setStyle(n8, pageStyle);
});
setInsertionState(n8);
createIf(() => unref(hasNavigationBar) && unref(navigationBar).style !== "custom", () => {
const n2 = withComponentId("6ae207a0", () => createComponent$1(_sfc_main$B));
return n2;
});
setInsertionState(n8, 1);
withComponentId("f15f11c4", () => createComponent$1(_sfc_main$z, null, extend$1(() => {
const n3 = withComponentId("f15f1178", () => createDynamicComponent(
() => unref(pageComponent),
{ $: [
() => unref(pageProps)
] },
null,
36
/* SLOT_SINGLE_ROOT, SLOT_ROOT */
));
setStaticTemplateRef(n3, "page");
return n3;
}, {
_: 1
/* NON_STABLE */
})));
setInsertionState(n8, 2);
createFor(
() => getDialogPages(),
(_for_item0) => {
const n7 = withComponentId("f15f0a40-" + _for_item0.value.route, () => createDynamicComponent(() => _for_item0.value.component, {
style: () => dialogPageStyle,
"data-type": () => _for_item0.value.type,
route: () => _for_item0.value.route
}));
return n7;
},
(dialogPage) => dialogPage.route,
18
/* IS_COMPONENT, IS_FRAGMENT */
);
return n8;
}
});
function createVaporPageRouteComponent(pageComponent) {
return Object.assign({}, _sfc_main$y, {
__uniPageComponent: pageComponent
});
}
const systemRoutes = [];
function registerSystemRoute(route, page, meta = {}) {
if (systemRoutes.includes(route)) {
return;
}
systemRoutes.push(route);
if (isArray(page.styles) && page.styles.length > 0) {
page.styles.forEach((style, index2) => {
updateStyle(`${route}-style-${index2}`, style);
});
}
const __uniPage = setupPage(page);
let routeComponent;
routeComponent = createVaporPageRouteComponent(__uniPage);
routeComponent.mpType = "page";
__uniRoutes.push({
path: route,
component: routeComponent,
meta: extend(
{
isQuit: false,
isEntry: false,
navigationBar: {},
route
},
meta
)
});
}
var startTag = /^<([-A-Za-z0-9_]+)((?:\s+[a-zA-Z_:][-a-zA-Z0-9_:.]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/;
var endTag = /^<\/([-A-Za-z0-9_]+)[^>]*>/;
var attr = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g;
var empty = /* @__PURE__ */ makeMap(
"area,base,basefont,br,col,frame,hr,img,input,link,meta,param,embed,command,keygen,source,track,wbr"
);
var block = /* @__PURE__ */ makeMap(
"a,address,article,applet,aside,audio,blockquote,button,canvas,center,dd,del,dir,div,dl,dt,fieldset,figcaption,figure,footer,form,frameset,h1,h2,h3,h4,h5,h6,header,hgroup,hr,iframe,isindex,li,map,menu,noframes,noscript,object,ol,output,p,pre,section,script,table,tbody,td,tfoot,th,thead,tr,ul,video"
);
var inline = /* @__PURE__ */ makeMap(
"abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var"
);
var closeSelf = /* @__PURE__ */ makeMap(
"colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr"
);
var fillAttrs = /* @__PURE__ */ makeMap(
"checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected"
);
var special = /* @__PURE__ */ makeMap("script,style");
function HTMLParser(html, handler) {
var index2;
var chars2;
var match;
var stack = [];
var last = html;
stack.last = function() {
return this[this.length - 1];
};
while (html) {
chars2 = true;
if (!stack.last() || !special[stack.last()]) {
if (html.indexOf("<!--") == 0) {
index2 = html.indexOf("-->");
if (index2 >= 0) {
if (handler.comment) {
handler.comment(html.substring(4, index2));
}
html = html.substring(index2 + 3);
chars2 = false;
}
} else if (html.indexOf("</") == 0) {
match = html.match(endTag);
if (match) {
html = html.substring(match[0].length);
match[0].replace(endTag, parseEndTag);
chars2 = false;
}
} else if (html.indexOf("<") == 0) {
match = html.match(startTag);
if (match) {
html = html.substring(match[0].length);
match[0].replace(startTag, parseStartTag);
chars2 = false;
}
}
if (chars2) {
index2 = html.indexOf("<");
var text2 = index2 < 0 ? html : html.substring(0, index2);
html = index2 < 0 ? "" : html.substring(index2);
if (handler.chars) {
handler.chars(text2);
}
}
} else {
html = html.replace(
new RegExp("([\\s\\S]*?)</" + stack.last() + "[^>]*>"),
function(all, text3) {
text3 = text3.replace(
/<!--([\s\S]*?)-->|<!\[CDATA\[([\s\S]*?)]]>/g,
"$1$2"
);
if (handler.chars) {
handler.chars(text3);
}
return "";
}
);
parseEndTag("", stack.last());
}
if (html == last) {
throw "Parse Error: " + html;
}
last = html;
}
parseEndTag();
function parseStartTag(tag, tagName, rest, unary) {
tagName = tagName.toLowerCase();
if (block[tagName]) {
while (stack.last() && inline[stack.last()]) {
parseEndTag("", stack.last());
}
}
if (closeSelf[tagName] && stack.last() == tagName) {
parseEndTag("", tagName);
}
unary = empty[tagName] || !!unary;
if (!unary) {
stack.push(tagName);
}
if (handler.start) {
var attrs2 = [];
rest.replace(attr, function(match2, name) {
var value = arguments[2] ? arguments[2] : arguments[3] ? arguments[3] : arguments[4] ? arguments[4] : fillAttrs[name] ? name : "";
attrs2.push({
name,
value,
escaped: value.replace(/(^|[^\\])"/g, '$1\\"')
// "
});
});
if (handler.start) {
handler.start(tagName, attrs2, unary);
}
}
}
function parseEndTag(tag, tagName) {
if (!tagName) {
var pos = 0;
} else {
for (var pos = stack.length - 1; pos >= 0; pos--) {
if (stack[pos] == tagName) {
break;
}
}
}
if (pos >= 0) {
for (var i = stack.length - 1; i >= pos; i--) {
if (handler.end) {
handler.end(stack[i]);
}
}
stack.length = pos;
}
}
}
function makeMap(str) {
var obj = {};
var items = str.split(",");
for (var i = 0; i < items.length; i++) {
obj[items[i]] = true;
}
return obj;
}
const scripts = {};
function loadScript(globalName, src, callback) {
const globalObject = isString(globalName) ? window[globalName] : globalName;
if (globalObject) {
callback();
return;
}
let callbacks2 = scripts[src];
if (!callbacks2) {
callbacks2 = scripts[src] = [];
const script = document.createElement("script");
script.src = src;
document.body.appendChild(script);
script.onload = function() {
callbacks2.forEach((callback2) => callback2());
delete scripts[src];
};
}
callbacks2.push(callback);
}
function divider(Quill) {
const BlockEmbed = Quill.import("blots/block/embed");
class Divider extends BlockEmbed {
}
Divider.blotName = "divider";
Divider.tagName = "HR";
return {
"formats/divider": Divider
};
}
function ins(Quill) {
const Inline = Quill.import("blots/inline");
class Ins extends Inline {
}
Ins.blotName = "ins";
Ins.tagName = "INS";
return {
"formats/ins": Ins
};
}
function align(Quill) {
const { Scope, Attributor } = Quill.import("parchment");
const config = {
scope: Scope.BLOCK,
whitelist: ["left", "right", "center", "justify"]
};
const AlignStyle = new Attributor.Style("align", "text-align", config);
return {
"formats/align": AlignStyle
};
}
function direction(Quill) {
const { Scope, Attributor } = Quill.import("parchment");
const config = {
scope: Scope.BLOCK,
whitelist: ["rtl"]
};
const DirectionStyle = new Attributor.Style("direction", "direction", config);
return {
"formats/direction": DirectionStyle
};
}
function list(Quill) {
const Parchment = Quill.import("parchment");
const Container = Quill.import("blots/container");
const ListItem = Quill.import("formats/list/item");
class List extends Container {
static create(value) {
const tagName = value === "ordered" ? "OL" : "UL";
const node = super.create(tagName);
if (value === "checked" || value === "unchecked") {
node.setAttribute("data-checked", value === "checked");
}
return node;
}
static formats(domNode) {
if (domNode.tagName === "OL")
return "ordered";
if (domNode.tagName === "UL") {
if (domNode.hasAttribute("data-checked")) {
return domNode.getAttribute("data-checked") === "true" ? "checked" : "unchecked";
} else {
return "bullet";
}
}
return void 0;
}
constructor(domNode) {
super(domNode);
const listEventHandler = (e2) => {
if (e2.target.parentNode !== domNode)
return;
const format = this.statics.formats(domNode);
const blot = Parchment.find(e2.target);
if (format === "checked") {
blot.format("list", "unchecked");
} else if (format === "unchecked") {
blot.format("list", "checked");
}
};
domNode.addEventListener("click", listEventHandler);
}
format(name, value) {
if (this.children.length > 0) {
this.children.tail.format(name, value);
}
}
formats() {
return { [this.statics.blotName]: this.statics.formats(this.domNode) };
}
insertBefore(blot, ref2) {
if (blot instanceof ListItem) {
super.insertBefore(blot, ref2);
} else {
const index2 = ref2 == null ? this.length() : ref2.offset(this);
const after = this.split(index2);
after.parent.insertBefore(blot, after);
}
}
optimize(context) {
super.optimize(context);
const next2 = this.next;
if (next2 != null && next2.prev === this && next2.statics.blotName === this.statics.blotName && next2.domNode.tagName === this.domNode.tagName && next2.domNode.getAttribute("data-checked") === this.domNode.getAttribute("data-checked")) {
next2.moveChildren(this);
next2.remove();
}
}
replace(target) {
if (target.statics.blotName !== this.statics.blotName) {
const item = Parchment.create(this.statics.defaultChild);
target.moveChildren(item);
this.appendChild(item);
}
super.replace(target);
}
}
List.blotName = "list";
List.scope = Parchment.Scope.BLOCK_BLOT;
List.tagName = ["OL", "UL"];
List.defaultChild = "list-item";
List.allowedChildren = [ListItem];
return {
"formats/list": List
};
}
function background(Quill) {
const { Scope } = Quill.import("parchment");
const BackgroundStyle = Quill.import("formats/background");
const BackgroundColorStyle = new BackgroundStyle.constructor(
"backgroundColor",
"background-color",
{
scope: Scope.INLINE
}
);
return {
"formats/backgroundColor": BackgroundColorStyle
};
}
function box(Quill) {
const { Scope, Attributor } = Quill.import("parchment");
const config = {
scope: Scope.BLOCK
};
const margin = [
"margin",
"marginTop",
"marginBottom",
"marginLeft",
"marginRight"
];
const padding = [
"padding",
"paddingTop",
"paddingBottom",
"paddingLeft",
"paddingRight"
];
const result = {};
margin.concat(padding).forEach((name) => {
result[`formats/${name}`] = new Attributor.Style(
name,
hyphenate(name),
config
);
});
return result;
}
function font(Quill) {
const { Scope, Attributor } = Quill.import("parchment");
const config = {
scope: Scope.INLINE
};
const font2 = [
"font",
"fontSize",
"fontStyle",
"fontVariant",
"fontWeight",
"fontFamily"
];
const result = {};
font2.forEach((name) => {
result[`formats/${name}`] = new Attributor.Style(
name,
hyphenate(name),
config
);
});
return result;
}
function text(Quill) {
const { Scope, Attributor } = Quill.import("parchment");
const text2 = [
{
name: "lineHeight",
scope: Scope.BLOCK
},
{
name: "letterSpacing",
scope: Scope.INLINE
},
{
name: "textDecoration",
scope: Scope.INLINE
},
{
name: "textIndent",
scope: Scope.BLOCK
}
];
const result = {};
text2.forEach(({ name, scope: scope2 }) => {
result[`formats/${name}`] = new Attributor.Style(name, hyphenate(name), {
scope: scope2
});
});
return result;
}
function image(Quill) {
const Image2 = Quill.import("formats/image");
const ATTRIBUTES = [
"alt",
"height",
"width",
"data-custom",
"class",
"data-local"
];
Image2.sanitize = (url) => url ? getRealPath(url) : url;
Image2.formats = function formats(domNode) {
return ATTRIBUTES.reduce(
function(formats2, attribute) {
if (domNode.hasAttribute(attribute)) {
formats2[attribute] = domNode.getAttribute(attribute);
}
return formats2;
},
{}
);
};
const format = Image2.prototype.format;
Image2.prototype.format = function(name, value) {
if (ATTRIBUTES.indexOf(name) > -1) {
if (value) {
this.domNode.setAttribute(name, value);
} else {
this.domNode.removeAttribute(name);
}
} else {
format.call(this, name, value);
}
};
}
function link(Quill) {
const Link = Quill.import("formats/link");
Link.sanitize = (url) => {
const anchor = document.createElement("a");
anchor.href = url;
const protocol = anchor.href.slice(0, anchor.href.indexOf(":"));
return Link.PROTOCOL_WHITELIST.concat("file").indexOf(protocol) > -1 ? url : Link.SANITIZED_URL;
};
}
const SupportStyleList = ["color", "background", "padding", "radius"];
const MentionStyleMap = {
color: "color",
background: "background",
padding: "padding",
radius: "border-radius"
};
function getMentionStyleValue(node, styleKey) {
const cssName = MentionStyleMap[styleKey];
if (!cssName) {
return "";
}
return node.style.getPropertyValue(cssName).trim();
}
const isApple = /^Apple/.test(navigator.vendor);
function mention(Quill) {
const Embed = Quill.import("blots/embed");
class MentionBlot extends Embed {
static create(data) {
const node = super.create();
const id2 = data.id == null ? "" : data.id;
const name = data.name == null ? "" : data.name;
if (!isApple) {
node.setAttribute("contenteditable", "false");
}
node.setAttribute("data-id", id2);
node.setAttribute("data-name", name);
let style = "";
if (isApple) {
style += "-webkit-user-select: none;";
}
SupportStyleList.forEach((item) => {
const styleName = MentionStyleMap[item] || item;
if (data[item]) {
style += `${hyphenate(styleName)}: ${data[item]};`;
}
});
if (style) {
node.setAttribute("style", style);
}
node.innerText = `@${name}`;
return node;
}
static value(node) {
const value = {
id: node.dataset.id == null ? "" : node.dataset.id,
name: node.dataset.name == null ? "" : node.dataset.name
};
SupportStyleList.forEach((item) => {
const styleValue2 = getMentionStyleValue(node, item);
if (styleValue2) {
value[item] = styleValue2;
}
});
return value;
}
}
MentionBlot.blotName = "mention";
MentionBlot.tagName = "span";
MentionBlot.className = "mention";
return {
"formats/mention": MentionBlot
};
}
function register(Quill) {
const formats = {
divider,
ins,
align,
direction,
list,
background,
box,
font,
text,
image,
link,
mention
};
const options = {};
Object.values(formats).forEach((value) => extend(options, value(Quill)));
Quill.register(options, true);
}
const STATUS_KEY_MAP = { "code-block": "codeBlock" };
function useQuill(props2, rootRef, trigger) {
let quillReady;
let skipMatcher;
let quill;
watch(
() => props2.readOnly,
(value) => {
if (quillReady) {
quill.enable(!value);
if (value) {
quill.blur();
}
}
}
);
watch(
() => props2.placeholder,
(value) => {
if (quillReady) {
setPlaceHolder(value);
}
}
);
watch(
() => props2.type,
(value) => {
if (quillReady) {
setInputMode(value);
}
}
);
function html2delta(html) {
const tags = [
"span",
"strong",
"b",
"ins",
"em",
"i",
"u",
"a",
"del",
"s",
"sub",
"sup",
"img",
"div",
"p",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"hr",
"ol",
"ul",
"li",
"br",
"blockquote",
"pre",
"code"
];
let content = "";
let disable;
HTMLParser(html, {
start: function(tag, attrs2, unary) {
if (!tags.includes(tag)) {
disable = !unary;
return;
}
disable = false;
const arrts = attrs2.map(({ name, value }) => `${name}="${value}"`).join(" ");
const start = `<${tag} ${arrts} ${unary ? "/" : ""}>`;
content += start;
},
end: function(tag) {
if (!disable) {
content += `</${tag}>`;
}
},
chars: function(text2) {
if (!disable) {
content += text2;
}
}
});
skipMatcher = true;
const delta = quill.clipboard.convert(content);
skipMatcher = false;
return delta;
}
function getContents() {
const html = quill.root.innerHTML;
const text2 = quill.getText();
const delta = quill.getContents();
return {
html,
text: text2,
delta
};
}
function setPlaceHolder(placeholder) {
const placeHolderAttrName = "data-placeholder";
const QuillRoot = quill.root;
QuillRoot.getAttribute(placeHolderAttrName) !== placeholder && QuillRoot.setAttribute(placeHolderAttrName, placeholder);
}
function setInputMode(type) {
const QuillRoot = quill.root;
if (type === "none") {
QuillRoot.setAttribute("inputmode", "none");
} else {
QuillRoot.removeAttribute("inputmode");
}
}
let oldStatus = {};
function updateStatus(range) {
const status = range ? quill.getFormat(range) : {};
const keys = Object.keys(status);
if (keys.length !== Object.keys(oldStatus).length || keys.find((key) => status[key] !== oldStatus[key])) {
oldStatus = status;
const normalizedStatus = {};
Object.keys(status).forEach((k) => {
normalizedStatus[STATUS_KEY_MAP[k] || k] = status[k];
});
trigger("statuschange", {}, normalizedStatus);
}
}
function fixCursor() {
var _a;
const range = quill.getSelection();
if (!range)
return;
const [leaf] = quill.getLeaf(range.index - 1);
if (((_a = leaf == null ? void 0 : leaf.statics) == null ? void 0 : _a.blotName) === "mention") {
quill.setSelection(range.index, 0, "silent");
}
}
function textChangeHandler() {
fixCursor();
trigger("input", {}, getContents());
}
function initQuill(imageResizeModules) {
const Quill = window.Quill;
register(Quill);
const options = {
toolbar: false,
readOnly: props2.readOnly,
placeholder: props2.placeholder
};
if (imageResizeModules.length) {
Quill.register(
"modules/ImageResize",
window.ImageResize.default
);
options.modules = {
syntax: true,
ImageResize: {
modules: imageResizeModules
}
};
}
const rootEl = rootRef.value;
quill = new Quill(rootEl, options);
setInputMode(props2.type);
const $el = quill.root;
const events = ["focus", "blur", "input"];
events.forEach((name) => {
$el.addEventListener(name, ($event) => {
const contents = getContents();
if (name === "input") {
if (getBaseSystemInfo().platform === "ios") {
const regExpContent = (contents.html.match(
/<span [\s\S]*>([\s\S]*)<\/span>/
) || [])[1];
const placeholder = regExpContent && regExpContent.replace(/\s/g, "") ? "" : props2.placeholder;
setPlaceHolder(placeholder);
}
$event.stopPropagation();
} else {
trigger(name, $event, contents);
}
});
});
quill.on("text-change", textChangeHandler);
quill.on("selection-change", updateStatus);
quill.on("scroll-optimize", () => {
const range = quill.selection.getRange()[0];
updateStatus(range);
});
quill.clipboard.addMatcher(Node.ELEMENT_NODE, (node, delta) => {
if (skipMatcher) {
return delta;
}
if (delta.ops) {
delta.ops = delta.ops.filter(({ insert: insert2 }) => isString(insert2)).map(({ insert: insert2 }) => ({ insert: insert2 }));
}
return delta;
});
quillReady = true;
trigger("ready", {}, {});
}
const id2 = useContextInfo();
useSubscribe(
(type, data, resolve) => {
const { options, callbackId } = data;
let res;
let range;
let errMsg;
if (quillReady) {
const Quill = window.Quill;
switch (type) {
case "format":
{
let { name = "", value = false } = options;
range = quill.getSelection(true);
if (!name) {
break;
}
let format = quill.getFormat(range)[name] || false;
if (["bold", "italic", "underline", "strike", "ins"].includes(name)) {
value = !format;
} else if (name === "direction") {
value = value === "rtl" && format ? false : value;
const align2 = quill.getFormat(range).align;
if (value === "rtl" && !align2) {
quill.format("align", "right", "user");
} else if (!value && align2 === "right") {
quill.format("align", false, "user");
}
} else if (name === "indent") {
const rtl = quill.getFormat(range).direction === "rtl";
value = value === "+1";
if (rtl) {
value = !value;
}
value = value ? "+1" : "-1";
} else {
if (name === "list") {
value = value === "check" ? "unchecked" : value;
format = format === "checked" ? "unchecked" : format;
}
value = format && format !== (value || false) || !format && value ? value : !format;
}
quill.format(name, value, "user");
}
break;
case "insertDivider":
range = quill.getSelection(true);
quill.insertText(range.index, LINEFEED, "user");
quill.insertEmbed(range.index + 1, "divider", true, "user");
quill.setSelection(range.index + 2, 0, "silent");
break;
case "insertMention":
{
range = quill.getSelection(true);
const mentionData = extend({ id: "", name: "" }, options);
quill.insertEmbed(range.index, "mention", mentionData, "user");
quill.setSelection(range.index + 1, 0);
}
break;
case "insertImage":
{
range = quill.getSelection(true);
const {
src = "",
alt = "",
width = "",
height = "",
extClass = "",
data: data2 = {}
} = options;
const path = getRealPath(src);
quill.insertEmbed(range.index, "image", path, "silent");
const local = /^(file|blob):/.test(path) ? path : false;
quill.formatText(range.index, 1, "data-local", local, "silent");
quill.formatText(range.index, 1, "alt", alt, "silent");
quill.formatText(range.index, 1, "width", width, "silent");
quill.formatText(range.index, 1, "height", height, "silent");
quill.formatText(range.index, 1, "class", extClass, "silent");
quill.formatText(
range.index,
1,
"data-custom",
Object.keys(data2).map((key) => `${key}=${data2[key]}`).join("&"),
"silent"
);
quill.setSelection(range.index + 1, 0, "silent");
quill.scrollIntoView();
setTimeout(() => {
textChangeHandler();
}, 1e3);
}
break;
case "insertText":
{
range = quill.getSelection(true);
const { text: text2 = "" } = options;
quill.insertText(range.index, text2, "user");
quill.setSelection(range.index + text2.length, 0, "silent");
}
break;
case "insertLink":
{
range = quill.getSelection(true);
const { text: text2 = "", href = "" } = options;
if (!href)
break;
if (range.length > 0) {
quill.format("link", href, "user");
} else {
const linkText = text2 || href;
quill.insertText(range.index, linkText, "link", href, "user");
quill.setSelection(range.index + linkText.length, 0, "silent");
}
}
break;
case "setContents":
{
const { delta, html } = options;
if (typeof delta === "object") {
quill.setContents(delta, "silent");
} else if (isString(html)) {
quill.setContents(html2delta(html), "silent");
} else {
errMsg = "contents is missing";
}
}
break;
case "getContents":
res = getContents();
break;
case "clear":
quill.setText("");
break;
case "removeFormat":
{
range = quill.getSelection(true);
const parchment = Quill.import("parchment");
if (range.length) {
quill.removeFormat(range.index, range.length, "user");
} else {
Object.keys(quill.getFormat(range)).forEach((key) => {
if (parchment.query(key, parchment.Scope.INLINE)) {
quill.format(key, false);
}
});
}
}
break;
case "undo":
quill.history.undo();
break;
case "redo":
quill.history.redo();
break;
case "blur":
quill.blur();
break;
case "getSelectionText":
range = quill.selection.savedRange;
res = { text: "" };
if (range && range.length !== 0) {
res.text = quill.getText(range.index, range.length);
}
break;
case "scrollIntoView":
quill.scrollIntoView();
break;
}
updateStatus(range);
} else {
errMsg = "not ready";
}
if (callbackId) {
resolve({
callbackId,
data: extend({}, res, {
errMsg: `${type}:${errMsg ? "fail " + errMsg : "ok"}`
})
});
}
},
id2,
true
);
onMounted(() => {
const imageResizeModules = [];
if (props2.showImgSize) {
imageResizeModules.push("DisplaySize");
}
if (props2.showImgToolbar) {
imageResizeModules.push("Toolbar");
}
if (props2.showImgResize) {
imageResizeModules.push("Resize");
}
const quillSrc = "https://unpkg.com/quill@1.3.7/dist/quill.min.js";
const quillHighlightSrc = "https://unpkg.com/@highlightjs/cdn-assets@11.11.1/highlight.min.js";
loadScript("hljs", quillHighlightSrc, () => {
loadScript(window.Quill, quillSrc, () => {
if (imageResizeModules.length) {
const imageResizeSrc = "https://unpkg.com/quill-image-resize-mp@3.0.1/image-resize.min.js";
loadScript(window.ImageResize, imageResizeSrc, () => {
initQuill(imageResizeModules);
});
} else {
initQuill(imageResizeModules);
}
});
});
});
}
const editorProps = /* @__PURE__ */ extend({}, props$b, {
id: {
type: String,
default: ""
},
readOnly: {
type: [Boolean, String],
default: false
},
type: {
type: String,
default: ""
},
placeholder: {
type: String,
default: ""
},
showImgSize: {
type: [Boolean, String],
default: false
},
showImgToolbar: {
type: [Boolean, String],
default: false
},
showImgResize: {
type: [Boolean, String],
default: false
}
});
const editorEmit = [
"ready",
"focus",
"blur",
"input",
"statuschange",
...emit$1
];
function useEditor(props2, emit2) {
const rootRef = ref(null);
const trigger = useCustomEvent(rootRef, emit2);
useQuill(props2, rootRef, trigger);
useKeyboard$1(props2, rootRef);
return rootRef;
}
const _t0$c = template("<div uni-editor uni-view class=ql-container>", 1);
class UniEditorElement extends UniViewElement {
static [Symbol.hasInstance](value) {
return this === UniEditorElement && value instanceof UniViewElement && value.hasAttribute("uni-editor") || Function.prototype[Symbol.hasInstance].call(this, value);
}
}
const uniTagName$8 = { value: "EDITOR" };
const indexVapor$7 = /* @__PURE__ */ defineBuiltInComponent({
name: "Editor",
props: editorProps,
emits: editorEmit,
rootElement: {
name: "uni-editor",
class: UniEditorElement
},
setup(props2, { emit: emit2 }) {
const rootRef = useEditor(props2, emit2);
const root = (() => {
const _setTemplateRef = createTemplateRefSetter();
const _n0 = _t0$c();
renderEffect(() => {
setProp(_n0, "id", props2.id);
_setTemplateRef(_n0, rootRef);
});
return _n0;
})();
Object.defineProperty(root, "uniTagName", uniTagName$8);
return root;
}
});
const INFO_COLOR = "#10aeff";
const WARN_COLOR = "#f76260";
const GREY_COLOR = "#b2b2b2";
const CANCEL_COLOR = "#f43530";
const ICONS = {
success: {
d: ICON_PATH_SUCCESS,
c: PRIMARY_COLOR
},
success_no_circle: {
d: ICON_PATH_SUCCESS_NO_CIRCLE,
c: PRIMARY_COLOR
},
info: {
d: ICON_PATH_INFO,
c: INFO_COLOR
},
warn: {
d: ICON_PATH_WARN,
c: WARN_COLOR
},
waiting: {
d: ICON_PATH_WAITING,
c: INFO_COLOR
},
cancel: {
d: ICON_PATH_CANCEL,
c: CANCEL_COLOR
},
download: {
d: ICON_PATH_DOWNLOAD,
c: PRIMARY_COLOR
},
search: {
d: ICON_PATH_SEARCH,
c: GREY_COLOR
},
clear: {
d: ICON_PATH_CLEAR,
c: GREY_COLOR
}
};
const iconProps = {
type: {
type: String,
required: true,
default: ""
},
size: {
type: [String, Number],
default: 23
},
color: {
type: String,
default: ""
}
};
function useIcon(props2) {
return computed(() => ICONS[props2.type]);
}
const _t0$b = template("<div uni-icon uni-view> ", 1);
class UniIconElement extends UniViewElement {
static [Symbol.hasInstance](value) {
return this === UniIconElement && value instanceof UniViewElement && value.hasAttribute("uni-icon") || Function.prototype[Symbol.hasInstance].call(this, value);
}
}
const uniTagName$7 = { value: "ICON" };
const indexVapor$6 = /* @__PURE__ */ defineBuiltInComponent({
name: "Icon",
props: iconProps,
rootElement: {
name: "uni-icon",
class: UniIconElement
},
setup(props2) {
const path = useIcon(props2);
const root = (() => {
const _n0 = _t0$b();
const _x0 = txt(_n0);
setNodes(_x0, () => path.value && path.value.d && createSvgIconVNode(path.value.d, props2.color || path.value.c, rpx2px(props2.size)));
return _n0;
})();
Object.defineProperty(root, "uniTagName", uniTagName$7);
return root;
}
});
const movableAreaProps = {
scaleArea: {
type: Boolean,
default: false
}
};
function useMovableAreaChildren$1(rootRef, slots, setContexts) {
const contexts = [];
setContexts(contexts);
const add = (context) => {
var _a;
if (((_a = context.rootRef.value) == null ? void 0 : _a.parentElement) === rootRef.value) {
contexts.push(markRaw(context));
}
};
const remove2 = (context) => {
const index2 = contexts.indexOf(context);
if (index2 >= 0) {
contexts.splice(index2, 1);
}
};
provide("addMovableViewContext", add);
provide("removeMovableViewContext", remove2);
return () => slots.default && slots.default();
}
const useMovableAreaChildren = useMovableAreaChildren$1;
function useMovableArea(props2, slots) {
const rootRef = ref(null);
const _isMounted = ref(false);
let { setContexts, events: movableAreaEvents } = useMovableAreaState(
props2,
rootRef
);
const { $listeners, $attrs, $excludeAttrs } = useAttrs();
const _listeners = $listeners.value;
let events = ["onTouchstart", "onTouchmove", "onTouchend"];
events.forEach((event) => {
let existing = _listeners[event];
let ours = movableAreaEvents[`_${event}`];
_listeners[event] = existing ? [].concat(existing, ours) : ours;
});
onMounted(() => {
movableAreaEvents._resize();
_isMounted.value = true;
});
const renderChildren = useMovableAreaChildren(rootRef, slots, setContexts);
provide("_isMounted", _isMounted);
provide("movableAreaRootRef", rootRef);
return {
rootRef,
renderChildren,
movableAreaEvents,
$attrs,
$excludeAttrs,
_listeners
};
}
function calc(e2) {
return Math.sqrt(e2.x * e2.x + e2.y * e2.y);
}
function useMovableAreaState(props2, rootRef) {
const width = ref(0);
const height = ref(0);
const gapV = reactive({
x: null,
y: null
});
const pinchStartLen = ref(null);
let _scaleMovableView = null;
let movableViewContexts = [];
function _updateScale(e2) {
if (e2 && e2 !== 1) {
if (props2.scaleArea) {
movableViewContexts.forEach(function(item) {
item._setScale(e2);
});
} else {
if (_scaleMovableView) {
_scaleMovableView._setScale(e2);
}
}
}
}
function _find(target, items = movableViewContexts) {
let root = rootRef.value;
function get(node) {
for (let i = 0; i < items.length; i++) {
const item = items[i];
if (node === item.rootRef.value) {
return item;
}
}
if (node === root || node === document.body || node === document) {
return null;
}
return get(node.parentNode);
}
return get(target);
}
const _onTouchstart = withWebEvent((t12) => {
let i = t12.touches;
if (i) {
if (i.length > 1) {
let r = {
x: i[1].pageX - i[0].pageX,
y: i[1].pageY - i[0].pageY
};
pinchStartLen.value = calc(r);
gapV.x = r.x;
gapV.y = r.y;
if (!props2.scaleArea) {
let touch0 = _find(i[0].target);
let touch1 = _find(i[1].target);
_scaleMovableView = touch0 && touch0 === touch1 ? touch0 : null;
}
}
}
});
const _onTouchmove = withWebEvent((t12) => {
let n = t12.touches;
if (n) {
if (n.length > 1) {
t12.preventDefault();
let i = {
x: n[1].pageX - n[0].pageX,
y: n[1].pageY - n[0].pageY
};
if (gapV.x !== null && pinchStartLen.value && pinchStartLen.value > 0) {
let r = calc(i) / pinchStartLen.value;
_updateScale(r);
}
gapV.x = i.x;
gapV.y = i.y;
}
}
});
const _onTouchend = withWebEvent((e2) => {
let t12 = e2.touches;
if (!(t12 && t12.length)) {
if (e2.changedTouches) {
gapV.x = 0;
gapV.y = 0;
pinchStartLen.value = null;
if (props2.scaleArea) {
movableViewContexts.forEach(function(item) {
item._endScale();
});
} else {
if (_scaleMovableView) {
_scaleMovableView._endScale();
}
}
}
}
});
function _resize() {
_getWH();
movableViewContexts.forEach(function(item, index2) {
item.setParent();
});
}
function _getWH() {
let style = window.getComputedStyle(rootRef.value);
let rect = rootRef.value.getBoundingClientRect();
width.value = rect.width - ["Left", "Right"].reduce(function(all, item) {
const LEFT = "border" + item + "Width";
const RIGHT = "padding" + item;
return all + parseFloat(style[LEFT]) + parseFloat(style[RIGHT]);
}, 0);
height.value = rect.height - ["Top", "Bottom"].reduce(function(all, item) {
const TOP = "border" + item + "Width";
const BOTTOM = "padding" + item;
return all + parseFloat(style[TOP]) + parseFloat(style[BOTTOM]);
}, 0);
}
provide("movableAreaWidth", width);
provide("movableAreaHeight", height);
return {
setContexts(contexts) {
movableViewContexts = contexts;
},
events: {
_onTouchstart,
_onTouchmove,
_onTouchend,
_resize
}
};
}
const _t0$a = template("<div><!> ", 1);
class UniMovableAreaElement extends UniViewElement {
static [Symbol.hasInstance](value) {
return this === UniMovableAreaElement && value instanceof UniViewElement && value.hasAttribute("uni-movable-area") || Function.prototype[Symbol.hasInstance].call(this, value);
}
}
const uniTagName$6 = { value: "MOVABLE-AREA" };
const indexVapor$5 = /* @__PURE__ */ defineBuiltInComponent({
inheritAttrs: false,
name: "MovableArea",
props: movableAreaProps,
rootElement: {
name: "uni-movable-area",
class: UniMovableAreaElement
},
setup(props2, { slots }) {
const { rootRef, renderChildren, movableAreaEvents, $attrs, $excludeAttrs, _listeners } = useMovableArea(props2, slots);
const movableViewItems = renderChildren();
const root = (() => {
const _setTemplateRef = createTemplateRefSetter();
const _n3 = _t0$a();
const _n2 = child(_n3);
const _n1 = next(_n2, true);
renderEffect(() => setDynamicProps(_n3, [
{
"uni-movable-area": "",
"uni-view": ""
},
$attrs.value,
$excludeAttrs.value,
_listeners
]));
setInsertionState(_n3, _n2);
createComponent(ResizeSensor, { onResize: () => movableAreaEvents._resize });
setNodes(_n1, () => movableViewItems);
renderEffect(() => _setTemplateRef(_n3, rootRef));
return _n3;
})();
Object.defineProperty(root, "uniTagName", uniTagName$6);
return root;
}
});
function e(e2, t12, n) {
return e2 > t12 - n && e2 < t12 + n;
}
function t(t12, n) {
return e(t12, 0, n);
}
function Decline() {
}
Decline.prototype.x = function(e2) {
return Math.sqrt(e2);
};
function Friction$1(e2, t12) {
this._m = e2;
this._f = 1e3 * t12;
this._startTime = 0;
this._v = 0;
}
Friction$1.prototype.setV = function(x, y) {
const n = Math.pow(Math.pow(x, 2) + Math.pow(y, 2), 0.5);
this._x_v = x;
this._y_v = y;
this._x_a = -this._f * this._x_v / n;
this._y_a = -this._f * this._y_v / n;
this._t = Math.abs(x / this._x_a) || Math.abs(y / this._y_a);
this._lastDt = null;
this._startTime = (/* @__PURE__ */ new Date()).getTime();
};
Friction$1.prototype.setS = function(x, y) {
this._x_s = x;
this._y_s = y;
};
Friction$1.prototype.s = function(t12) {
if (void 0 === t12) {
t12 = ((/* @__PURE__ */ new Date()).getTime() - this._startTime) / 1e3;
}
if (t12 > this._t) {
t12 = this._t;
this._lastDt = t12;
}
let x = this._x_v * t12 + 0.5 * this._x_a * Math.pow(t12, 2) + this._x_s;
let y = this._y_v * t12 + 0.5 * this._y_a * Math.pow(t12, 2) + this._y_s;
if (this._x_a > 0 && x < this._endPositionX || this._x_a < 0 && x > this._endPositionX) {
x = this._endPositionX;
}
if (this._y_a > 0 && y < this._endPositionY || this._y_a < 0 && y > this._endPositionY) {
y = this._endPositionY;
}
return {
x,
y
};
};
Friction$1.prototype.ds = function(t12) {
if (void 0 === t12) {
t12 = ((/* @__PURE__ */ new Date()).getTime() - this._startTime) / 1e3;
}
if (t12 > this._t) {
t12 = this._t;
}
return {
dx: this._x_v + this._x_a * t12,
dy: this._y_v + this._y_a * t12
};
};
Friction$1.prototype.delta = function() {
return {
x: -1.5 * Math.pow(this._x_v, 2) / this._x_a || 0,
y: -1.5 * Math.pow(this._y_v, 2) / this._y_a || 0
};
};
Friction$1.prototype.dt = function() {
return -this._x_v / this._x_a;
};
Friction$1.prototype.done = function() {
const t12 = e(this.s().x, this._endPositionX) || e(this.s().y, this._endPositionY) || this._lastDt === this._t;
this._lastDt = null;
return t12;
};
Friction$1.prototype.setEnd = function(x, y) {
this._endPositionX = x;
this._endPositionY = y;
};
Friction$1.prototype.reconfigure = function(m, f2) {
this._m = m;
this._f = 1e3 * f2;
};
function Spring(m, k, c) {
this._m = m;
this._k = k;
this._c = c;
this._solution = null;
this._endPosition = 0;
this._startTime = 0;
}
Spring.prototype._solve = function(e2, t12) {
const n = this._c;
const i = this._m;
const r = this._k;
const o = n * n - 4 * i * r;
if (o === 0) {
const a = -n / (2 * i);
const s = e2;
const l = t12 / (a * e2);
return {
x: function(e3) {
return (s + l * e3) * Math.pow(Math.E, a * e3);
},
dx: function(e3) {
const t13 = Math.pow(Math.E, a * e3);
return a * (s + l * e3) * t13 + l * t13;
}
};
}
if (o > 0) {
const c = (-n - Math.sqrt(o)) / (2 * i);
const u = (-n + Math.sqrt(o)) / (2 * i);
const d = (t12 - c * e2) / (u - c);
const h = e2 - d;
return {
x: function(e3) {
let t13;
let n2;
if (e3 === this._t) {
t13 = this._powER1T;
n2 = this._powER2T;
}
this._t = e3;
if (!t13) {
t13 = this._powER1T = Math.pow(Math.E, c * e3);
}
if (!n2) {
n2 = this._powER2T = Math.pow(Math.E, u * e3);
}
return h * t13 + d * n2;
},
dx: function(e3) {
let t13;
let n2;
if (e3 === this._t) {
t13 = this._powER1T;
n2 = this._powER2T;
}
this._t = e3;
if (!t13) {
t13 = this._powER1T = Math.pow(Math.E, c * e3);
}
if (!n2) {
n2 = this._powER2T = Math.pow(Math.E, u * e3);
}
return h * c * t13 + d * u * n2;
}
};
}
const p2 = Math.sqrt(4 * i * r - n * n) / (2 * i);
const f2 = -n / 2 * i;
const v2 = e2;
const g2 = (t12 - f2 * e2) / p2;
return {
x: function(e3) {
return Math.pow(Math.E, f2 * e3) * (v2 * Math.cos(p2 * e3) + g2 * Math.sin(p2 * e3));
},
dx: function(e3) {
const t13 = Math.pow(Math.E, f2 * e3);
const n2 = Math.cos(p2 * e3);
const i2 = Math.sin(p2 * e3);
return t13 * (g2 * p2 * n2 - v2 * p2 * i2) + f2 * t13 * (g2 * i2 + v2 * n2);
}
};
};
Spring.prototype.x = function(e2) {
if (void 0 === e2) {
e2 = ((/* @__PURE__ */ new Date()).getTime() - this._startTime) / 1e3;
}
return this._solution ? this._endPosition + this._solution.x(e2) : 0;
};
Spring.prototype.dx = function(e2) {
if (void 0 === e2) {
e2 = ((/* @__PURE__ */ new Date()).getTime() - this._startTime) / 1e3;
}
return this._solution ? this._solution.dx(e2) : 0;
};
Spring.prototype.setEnd = function(e2, n, i) {
if (!i) {
i = (/* @__PURE__ */ new Date()).getTime();
}
if (e2 !== this._endPosition || !t(n, 0.1)) {
n = n || 0;
let r = this._endPosition;
if (this._solution) {
if (t(n, 0.1)) {
n = this._solution.dx((i - this._startTime) / 1e3);
}
r = this._solution.x((i - this._startTime) / 1e3);
if (t(n, 0.1)) {
n = 0;
}
if (t(r, 0.1)) {
r = 0;
}
r += this._endPosition;
}
if (!(this._solution && t(r - e2, 0.1) && t(n, 0.1))) {
this._endPosition = e2;
this._solution = this._solve(r - this._endPosition, n);
this._startTime = i;
}
}
};
Spring.prototype.snap = function(e2) {
this._startTime = (/* @__PURE__ */ new Date()).getTime();
this._endPosition = e2;
this._solution = {
x: function() {
return 0;
},
dx: function() {
return 0;
}
};
};
Spring.prototype.done = function(n) {
if (!n) {
n = (/* @__PURE__ */ new Date()).getTime();
}
return e(this.x(), this._endPosition, 0.1) && t(this.dx(), 0.1);
};
Spring.prototype.reconfigure = function(m, t12, c) {
this._m = m;
this._k = t12;
this._c = c;
if (!this.done()) {
this._solution = this._solve(this.x() - this._endPosition, this.dx());
this._startTime = (/* @__PURE__ */ new Date()).getTime();
}
};
Spring.prototype.springConstant = function() {
return this._k;
};
Spring.prototype.damping = function() {
return this._c;
};
Spring.prototype.configuration = function() {
function e2(e3, t13) {
e3.reconfigure(1, t13, e3.damping());
}
function t12(e3, t13) {
e3.reconfigure(1, e3.springConstant(), t13);
}
return [
{
label: "Spring Constant",
read: this.springConstant.bind(this),
write: e2.bind(this, this),
min: 100,
max: 1e3
},
{
label: "Damping",
read: this.damping.bind(this),
write: t12.bind(this, this),
min: 1,
max: 500
}
];
};
function STD(e2, t12, n) {
this._springX = new Spring(e2, t12, n);
this._springY = new Spring(e2, t12, n);
this._springScale = new Spring(e2, t12, n);
this._startTime = 0;
}
STD.prototype.setEnd = function(e2, t12, n, i) {
const r = (/* @__PURE__ */ new Date()).getTime();
this._springX.setEnd(e2, i, r);
this._springY.setEnd(t12, i, r);
this._springScale.setEnd(n, i, r);
this._startTime = r;
};
STD.prototype.x = function() {
const e2 = ((/* @__PURE__ */ new Date()).getTime() - this._startTime) / 1e3;
return {
x: this._springX.x(e2),
y: this._springY.x(e2),
scale: this._springScale.x(e2)
};
};
STD.prototype.done = function() {
const e2 = (/* @__PURE__ */ new Date()).getTime();
return this._springX.done(e2) && this._springY.done(e2) && this._springScale.done(e2);
};
STD.prototype.reconfigure = function(e2, t12, n) {
this._springX.reconfigure(e2, t12, n);
this._springY.reconfigure(e2, t12, n);
this._springScale.reconfigure(e2, t12, n);
};
const movableViewProps = {
direction: {
type: String,
default: "none"
},
inertia: {
type: [Boolean, String],
default: false
},
outOfBounds: {
type: [Boolean, String],
default: false
},
x: {
type: [Number, String],
default: 0
},
y: {
type: [Number, String],
default: 0
},
damping: {
type: [Number, String],
default: 20
},
friction: {
type: [Number, String],
default: 2
},
disabled: {
type: [Boolean, String],
default: false
},
scale: {
type: [Boolean, String],
default: false
},
scaleMin: {
type: [Number, String],
default: 0.1
},
scaleMax: {
type: [Number, String],
default: 10
},
scaleValue: {
type: [Number, String],
default: 1
},
animation: {
type: [Boolean, String],
default: true
}
};
function v(a, b) {
return +((1e3 * a - 1e3 * b) / 1e3).toFixed(1);
}
function useMovableViewFrame() {
let frame;
let pending;
function run() {
const callback = pending;
frame = void 0;
pending = void 0;
callback == null ? void 0 : callback();
}
function cancel() {
if (frame !== void 0)
cancelAnimationFrame(frame);
frame = void 0;
pending = void 0;
}
function flush() {
if (frame !== void 0)
cancelAnimationFrame(frame);
run();
}
onBeforeUnmount(cancel);
return {
request(callback) {
pending = callback;
if (frame === void 0)
frame = requestAnimationFrame(run);
},
flush,
cancel
};
}
function useMovableView(props2, emit2) {
const rootRef = ref(null);
const trigger = useCustomEvent(rootRef, emit2);
const { setParent } = useMovableViewState(props2, trigger, rootRef);
return { rootRef, setParent };
}
function p(t12, n) {
if (t12 === n) {
return 0;
}
let i = t12.offsetLeft;
return t12.offsetParent ? i += p(t12.offsetParent, n) : 0;
}
function f(t12, n) {
if (t12 === n) {
return 0;
}
let i = t12.offsetTop;
return t12.offsetParent ? i += f(t12.offsetParent, n) : 0;
}
function g(friction, execute, endCallback) {
let record = {
id: 0,
cancelled: false
};
let cancel = function(record2) {
if (record2 && record2.id) {
cancelAnimationFrame(record2.id);
}
if (record2) {
record2.cancelled = true;
}
};
function fn(record2, friction2, execute2, endCallback2) {
if (!record2 || !record2.cancelled) {
execute2(friction2);
let isDone = friction2.done();
if (!isDone) {
if (!record2.cancelled) {
record2.id = requestAnimationFrame(
fn.bind(null, record2, friction2, execute2, endCallback2)
);
}
}
if (isDone && endCallback2) {
endCallback2(friction2);
}
}
}
fn(record, friction, execute, endCallback);
return {
cancel: cancel.bind(null, record),
model: friction
};
}
function _getPx(val) {
if (/\d+[ur]px$/i.test(val)) {
return uni.upx2px(parseFloat(val));
}
return Number(val) || 0;
}
function useMovableViewLayout(rootRef, _scale, _adjustScale) {
const movableAreaWidth = inject("movableAreaWidth", ref(0));
const movableAreaHeight = inject("movableAreaHeight", ref(0));
const movableAreaRootRef = inject("movableAreaRootRef");
const _offset = {
x: 0,
y: 0
};
const _scaleOffset = {
x: 0,
y: 0
};
const width = ref(0);
const height = ref(0);
const minX = ref(0);
const minY = ref(0);
const maxX = ref(0);
const maxY = ref(0);
function _updateBoundary() {
let x = 0 - _offset.x + _scaleOffset.x;
let _width = movableAreaWidth.value - width.value - _offset.x - _scaleOffset.x;
minX.value = Math.min(x, _width);
maxX.value = Math.max(x, _width);
let y = 0 - _offset.y + _scaleOffset.y;
let _height = movableAreaHeight.value - height.value - _offset.y - _scaleOffset.y;
minY.value = Math.min(y, _height);
maxY.value = Math.max(y, _height);
}
function _updateOffset() {
_offset.x = p(rootRef.value, movableAreaRootRef.value);
_offset.y = f(rootRef.value, movableAreaRootRef.value);
}
function _updateWH(scale) {
scale = scale || _scale.value;
scale = _adjustScale(scale);
let rect = rootRef.value.getBoundingClientRect();
height.value = rect.height / _scale.value;
width.value = rect.width / _scale.value;
let _height = height.value * scale;
let _width = width.value * scale;
_scaleOffset.x = (_width - width.value) / 2;
_scaleOffset.y = (_height - height.value) / 2;
}
return {
_updateBoundary,
_updateOffset,
_updateWH,
_scaleOffset,
minX,
minY,
maxX,
maxY
};
}
function useMovableViewTransform(rootRef, props2, _scaleOffset, _scale, maxX, maxY, minX, minY, _translateX, _translateY, _SFA, _FA, _adjustScale, trigger) {
const frame = useMovableViewFrame();
const dampingNumber = computed(() => {
let val = Number(props2.damping);
return isNaN(val) ? 20 : val;
});
const xMove = computed(
() => props2.direction === "all" || props2.direction === "horizontal"
);
const yMove = computed(
() => props2.direction === "all" || props2.direction === "vertical"
);
const xSync = ref(_getPx(props2.x));
const ySync = ref(_getPx(props2.y));
watch(
() => props2.x,
(val) => {
xSync.value = _getPx(val);
}
);
watch(
() => props2.y,
(val) => {
ySync.value = _getPx(val);
}
);
watch(xSync, (val) => {
_setX(val);
});
watch(ySync, (val) => {
_setY(val);
});
const _STD = new STD(
1,
9 * Math.pow(dampingNumber.value, 2) / 40,
dampingNumber.value
);
function _getLimitXY(x, y) {
let outOfBounds = false;
if (x > maxX.value) {
x = maxX.value;
outOfBounds = true;
} else {
if (x < minX.value) {
x = minX.value;
outOfBounds = true;
}
}
if (y > maxY.value) {
y = maxY.value;
outOfBounds = true;
} else {
if (y < minY.value) {
y = minY.value;
outOfBounds = true;
}
}
return {
x,
y,
outOfBounds
};
}
function FAandSFACancel() {
frame.cancel();
if (_FA) {
_FA.cancel();
}
if (_SFA) {
_SFA.cancel();
}
}
function _animationTo(x, y, scale, source, r, o) {
FAandSFACancel();
if (!xMove.value) {
x = _translateX.value;
}
if (!yMove.value) {
y = _translateY.value;
}
if (!props2.scale) {
scale = _scale.value;
}
let limitXY = _getLimitXY(x, y);
x = limitXY.x;
y = limitXY.y;
if (!props2.animation) {
_setTransform(x, y, scale, source, r, o);
return;
}
_STD._springX._solution = null;
_STD._springY._solution = null;
_STD._springScale._solution = null;
_STD._springX._endPosition = _translateX.value;
_STD._springY._endPosition = _translateY.value;
_STD._springScale._endPosition = _scale.value;
_STD.setEnd(x, y, scale, 1);
_SFA = g(
_STD,
function() {
let data = _STD.x();
let x2 = data.x;
let y2 = data.y;
let scale2 = data.scale;
_setTransform(x2, y2, scale2, source, r, o);
},
function() {
_SFA.cancel();
}
);
}
function _setTransform(x, y, scale, source = "", r, o) {
if (!(x !== null && x.toString() !== "NaN" && typeof x === "number")) {
x = _translateX.value || 0;
}
if (!(y !== null && y.toString() !== "NaN" && typeof y === "number")) {
y = _translateY.value || 0;
}
x = Number(x.toFixed(1));
y = Number(y.toFixed(1));
scale = Number(scale.toFixed(1));
if (!(_translateX.value === x && _translateY.value === y)) {
if (!r) {
trigger("change", {}, {
x: v(x, _scaleOffset.x),
y: v(y, _scaleOffset.y),
source
});
}
}
if (!props2.scale) {
scale = _scale.value;
}
scale = _adjustScale(scale);
scale = +scale.toFixed(3);
if (o && scale !== _scale.value) {
trigger("scale", {}, {
x,
y,
scale
});
}
let transform = "translateX(" + x + "px) translateY(" + y + "px) translateZ(0px) scale(" + scale + ")";
if (rootRef.value) {
rootRef.value.style.transform = transform;
rootRef.value.style.webkitTransform = transform;
_translateX.value = x;
_translateY.value = y;
_scale.value = scale;
}
}
function _revise(source) {
let limitXY = _getLimitXY(_translateX.value, _translateY.value);
let x = limitXY.x;
let y = limitXY.y;
let outOfBounds = limitXY.outOfBounds;
if (outOfBounds) {
_animationTo(x, y, _scale.value, source);
}
return outOfBounds;
}
function _setX(val) {
if (xMove.value) {
if (val + _scaleOffset.x === _translateX.value) {
return _translateX;
} else {
if (_SFA) {
_SFA.cancel();
}
_animationTo(
val + _scaleOffset.x,
ySync.value + _scaleOffset.y,
_scale.value
);
}
}
return val;
}
function _setY(val) {
if (yMove.value) {
if (val + _scaleOffset.y === _translateY.value) {
return _translateY;
} else {
if (_SFA) {
_SFA.cancel();
}
_animationTo(
xSync.value + _scaleOffset.x,
val + _scaleOffset.y,
_scale.value
);
}
}
return val;
}
return {
frame,
FAandSFACancel,
_getLimitXY,
_animationTo,
_setTransform,
_revise,
dampingNumber,
xMove,
yMove,
xSync,
ySync,
_STD
};
}
function useMovableViewInit(props2, rootRef, trigger, _scale, _oldScale, _isScaling, _translateX, _translateY, _SFA, _FA) {
const scaleMinNumber = computed(() => {
let val = Number(props2.scaleMin);
return isNaN(val) ? 0.1 : val;
});
const scaleMaxNumber = computed(() => {
let val = Number(props2.scaleMax);
return isNaN(val) ? 10 : val;
});
const scaleValueSync = ref(Number(props2.scaleValue) || 1);
watch(scaleValueSync, (val) => {
_setScaleValue(val);
});
watch(scaleMinNumber, () => {
_setScaleMinOrMax();
});
watch(scaleMaxNumber, () => {
_setScaleMinOrMax();
});
watch(
() => props2.scaleValue,
(val) => {
scaleValueSync.value = Number(val) || 0;
}
);
const {
_updateBoundary,
_updateOffset,
_updateWH,
_scaleOffset,
minX,
minY,
maxX,
maxY
} = useMovableViewLayout(rootRef, _scale, _adjustScale);
const {
frame,
FAandSFACancel,
_getLimitXY,
_animationTo,
_setTransform,
_revise,
dampingNumber,
xMove,
yMove,
xSync,
ySync,
_STD
} = useMovableViewTransform(
rootRef,
props2,
_scaleOffset,
_scale,
maxX,
maxY,
minX,
minY,
_translateX,
_translateY,
_SFA,
_FA,
_adjustScale,
trigger
);
const _requestAnimationFrame2 = frame.request;
function _updateScale(scale, animat) {
if (props2.scale) {
scale = _adjustScale(scale);
_updateWH(scale);
_updateBoundary();
const limitXY = _getLimitXY(_translateX.value, _translateY.value);
const x = limitXY.x;
const y = limitXY.y;
if (animat) {
_animationTo(x, y, scale, "", true, true);
} else {
_requestAnimationFrame2(function() {
_setTransform(x, y, scale, "", true, true);
});
}
}
}
function _beginScale() {
_isScaling.value = true;
}
function _updateOldScale(scale) {
_oldScale.value = scale;
}
function _adjustScale(scale) {
scale = Math.max(0.1, scaleMinNumber.value, scale);
scale = Math.min(10, scaleMaxNumber.value, scale);
return scale;
}
function _setScaleMinOrMax() {
if (!props2.scale) {
return false;
}
_updateScale(_scale.value, true);
_updateOldScale(_scale.value);
}
function _setScaleValue(scale) {
if (!props2.scale) {
return false;
}
scale = _adjustScale(scale);
_updateScale(scale, true);
_updateOldScale(scale);
return scale;
}
function _endScale() {
frame.flush();
_isScaling.value = false;
_updateOldScale(_scale.value);
}
function _setScale(scale) {
if (scale) {
scale = _oldScale.value * scale;
_beginScale();
_updateScale(scale);
}
}
return {
// scale
_updateOldScale,
_endScale,
_setScale,
scaleValueSync,
frame,
// layout
_updateBoundary,
_updateOffset,
_updateWH,
_scaleOffset,
minX,
minY,
maxX,
maxY,
// transform
FAandSFACancel,
_getLimitXY,
_animationTo,
_setTransform,
_revise,
dampingNumber,
xMove,
yMove,
xSync,
ySync,
_STD
};
}
function useMovableViewState(props2, trigger, rootRef) {
const _isMounted = inject("_isMounted", ref(false));
const addMovableViewContext = inject(
"addMovableViewContext",
() => {
}
);
const removeMovableViewContext = inject(
"removeMovableViewContext",
() => {
}
);
let _scale = ref(1);
let _oldScale = ref(1);
let _isScaling = ref(false);
let _translateX = ref(0);
let _translateY = ref(0);
let _SFA = null;
let _FA = null;
let _isTouching = false;
let __baseX;
let __baseY;
let _checkCanMove = null;
let _firstMoveDirection = null;
const _declineX = new Decline();
const _declineY = new Decline();
const __touchInfo = {
historyX: [0, 0],
historyY: [0, 0],
historyT: [0, 0]
};
const frictionNumber = computed(() => {
let val = Number(props2.friction);
return isNaN(val) || val <= 0 ? 2 : val;
});
const _friction = new Friction$1(1, frictionNumber.value);
watch(
() => props2.disabled,
() => {
__handleTouchStart();
}
);
const {
// scale
_updateOldScale,
_endScale,
_setScale,
scaleValueSync,
frame,
// layout
_updateBoundary,
_updateOffset,
_updateWH,
_scaleOffset,
minX,
minY,
maxX,
maxY,
// transform
FAandSFACancel,
_getLimitXY,
_setTransform,
_revise,
dampingNumber,
xMove,
yMove,
xSync,
ySync,
_STD
} = useMovableViewInit(
props2,
rootRef,
trigger,
_scale,
_oldScale,
_isScaling,
_translateX,
_translateY,
_SFA,
_FA
);
const _requestAnimationFrame2 = frame.request;
function __handleTouchStart() {
if (!_isScaling.value) {
if (!props2.disabled) {
FAandSFACancel();
__touchInfo.historyX = [0, 0];
__touchInfo.historyY = [0, 0];
__touchInfo.historyT = [0, 0];
if (xMove.value) {
__baseX = _translateX.value;
}
if (yMove.value) {
__baseY = _translateY.value;
}
rootRef.value.style.willChange = "transform";
_checkCanMove = null;
_firstMoveDirection = null;
_isTouching = true;
}
}
}
function __handleTouchMove(event) {
if (!_isScaling.value && !props2.disabled && _isTouching) {
let x = _translateX.value;
let y = _translateY.value;
if (_firstMoveDirection === null) {
_firstMoveDirection = Math.abs(event.detail.dx / event.detail.dy) > 1 ? "htouchmove" : "vtouchmove";
}
if (xMove.value) {
x = event.detail.dx + __baseX;
__touchInfo.historyX.shift();
__touchInfo.historyX.push(x);
if (!yMove.value && _checkCanMove === null) {
_checkCanMove = Math.abs(event.detail.dx / event.detail.dy) < 1;
}
}
if (yMove.value) {
y = event.detail.dy + __baseY;
__touchInfo.historyY.shift();
__touchInfo.historyY.push(y);
if (!xMove.value && _checkCanMove === null) {
_checkCanMove = Math.abs(event.detail.dy / event.detail.dx) < 1;
}
}
__touchInfo.historyT.shift();
__touchInfo.historyT.push(event.detail.timeStamp);
if (!_checkCanMove) {
event.preventDefault();
let source = "touch";
if (x < minX.value) {
if (props2.outOfBounds) {
source = "touch-out-of-bounds";
x = minX.value - _declineX.x(minX.value - x);
} else {
x = minX.value;
}
} else if (x > maxX.value) {
if (props2.outOfBounds) {
source = "touch-out-of-bounds";
x = maxX.value + _declineX.x(x - maxX.value);
} else {
x = maxX.value;
}
}
if (y < minY.value) {
if (props2.outOfBounds) {
source = "touch-out-of-bounds";
y = minY.value - _declineY.x(minY.value - y);
} else {
y = minY.value;
}
} else {
if (y > maxY.value) {
if (props2.outOfBounds) {
source = "touch-out-of-bounds";
y = maxY.value + _declineY.x(y - maxY.value);
} else {
y = maxY.value;
}
}
}
_requestAnimationFrame2(function() {
_setTransform(x, y, _scale.value, source);
});
}
}
}
function __handleTouchEnd() {
frame.flush();
if (!_isScaling.value && !props2.disabled && _isTouching) {
rootRef.value.style.willChange = "auto";
_isTouching = false;
if (!_checkCanMove && !_revise("out-of-bounds") && props2.inertia) {
const xv = 1e3 * (__touchInfo.historyX[1] - __touchInfo.historyX[0]) / (__touchInfo.historyT[1] - __touchInfo.historyT[0]);
const yv = 1e3 * (__touchInfo.historyY[1] - __touchInfo.historyY[0]) / (__touchInfo.historyT[1] - __touchInfo.historyT[0]);
const __translateX = _translateX.value;
const __translateY = _translateY.value;
_friction.setV(xv, yv);
_friction.setS(__translateX, __translateY);
const x0 = _friction.delta().x;
const y0 = _friction.delta().y;
let x = x0 + __translateX;
let y = y0 + __translateY;
if (x < minX.value) {
x = minX.value;
y = __translateY + (minX.value - __translateX) * y0 / x0;
} else {
if (x > maxX.value) {
x = maxX.value;
y = __translateY + (maxX.value - __translateX) * y0 / x0;
}
}
if (y < minY.value) {
y = minY.value;
x = __translateX + (minY.value - __translateY) * x0 / y0;
} else {
if (y > maxY.value) {
y = maxY.value;
x = __translateX + (maxY.value - __translateY) * x0 / y0;
}
}
_friction.setEnd(x, y);
_FA = g(
_friction,
function() {
let t12 = _friction.s();
let x2 = t12.x;
let y2 = t12.y;
_setTransform(x2, y2, _scale.value, "friction");
},
function() {
_FA.cancel();
}
);
}
}
if (!props2.outOfBounds && !props2.inertia) {
FAandSFACancel();
}
}
function setParent() {
if (!_isMounted.value) {
return;
}
FAandSFACancel();
let scale = props2.scale ? scaleValueSync.value : 1;
_updateOffset();
_updateWH(scale);
_updateBoundary();
let limitXY = _getLimitXY(
xSync.value + _scaleOffset.x,
ySync.value + _scaleOffset.y
);
let x = limitXY.x;
let y = limitXY.y;
_setTransform(x, y, scale, "", true);
_updateOldScale(scale);
}
onMounted(() => {
useTouchtrack(rootRef.value, (event) => {
switch (event.detail.state) {
case "start":
__handleTouchStart();
break;
case "move":
__handleTouchMove(event);
break;
case "end":
__handleTouchEnd();
}
});
setParent();
_friction.reconfigure(1, frictionNumber.value);
_STD.reconfigure(
1,
9 * Math.pow(dampingNumber.value, 2) / 40,
dampingNumber.value
);
rootRef.value.style.transformOrigin = "center";
const context = {
rootRef,
setParent,
_endScale,
_setScale
};
addMovableViewContext(context);
onUnmounted(() => {
removeMovableViewContext(context);
});
});
onUnmounted(() => {
FAandSFACancel();
});
return {
setParent
};
}
const _t0$9 = template("<div uni-movable-view uni-view><!> ", 1);
class UniMovableViewElement extends UniViewElement {
static [Symbol.hasInstance](value) {
return this === UniMovableViewElement && value instanceof UniViewElement && value.hasAttribute("uni-movable-view") || Function.prototype[Symbol.hasInstance].call(this, value);
}
}
const uniTagName$5 = { value: "MOVABLE-VIEW" };
const indexVapor$4 = /* @__PURE__ */ defineBuiltInComponent({
name: "MovableView",
props: movableViewProps,
emits: ["change", "scale"],
rootElement: {
name: "uni-movable-view",
class: UniMovableViewElement
},
setup(props2, { slots, emit: emit2 }) {
const { rootRef, setParent } = useMovableView(props2, emit2);
const root = (() => {
const _setTemplateRef = createTemplateRefSetter();
const _n3 = _t0$9();
const _n2 = child(_n3);
const _n1 = next(_n2, true);
setInsertionState(_n3, _n2);
createComponent(ResizeSensor, { onResize: () => setParent });
setNodes(_n1, () => slots.default && slots.default());
renderEffect(() => _setTemplateRef(_n3, rootRef));
return _n3;
})();
Object.defineProperty(root, "uniTagName", uniTagName$5);
return root;
}
});
function removeDOCTYPE(html) {
return html.replace(/<\?xml.*\?>\n/, "").replace(/<!doctype.*>\n/, "").replace(/<!DOCTYPE.*>\n/, "");
}
function parseAttrs(attrs2) {
return attrs2.reduce(function(pre, attr2) {
let value = attr2.value;
const name = attr2.name;
if (value.match(/ /) && ["style", "src"].indexOf(name) === -1) {
value = value.split(" ");
}
if (pre[name]) {
if (Array.isArray(pre[name])) {
pre[name].push(value);
} else {
pre[name] = [pre[name], value];
}
} else {
pre[name] = value;
}
return pre;
}, {});
}
function parseHtml(html) {
html = removeDOCTYPE(html);
const stacks = [];
const results = {
node: "root",
children: []
};
HTMLParser(html, {
start: function(tag, attrs2, unary) {
const node = {
name: tag
};
if (attrs2.length !== 0) {
node.attrs = parseAttrs(attrs2);
}
if (unary) {
const parent = stacks[0] || results;
if (!parent.children) {
parent.children = [];
}
parent.children.push(node);
} else {
stacks.unshift(node);
}
},
end: function(tag) {
const node = stacks.shift();
if (node.name !== tag)
console.error("invalid state: mismatch end tag");
if (stacks.length === 0) {
results.children.push(node);
} else {
const parent = stacks[0];
if (!parent.children) {
parent.children = [];
}
parent.children.push(node);
}
},
chars: function(text2) {
const node = {
type: "text",
text: text2
};
if (stacks.length === 0) {
results.children.push(node);
} else {
const parent = stacks[0];
if (!parent.children) {
parent.children = [];
}
parent.children.push(node);
}
},
comment: function(text2) {
const node = {
node: "comment",
text: text2
};
const parent = stacks[0];
if (parent) {
if (!parent.children) {
parent.children = [];
}
parent.children.push(node);
}
}
});
return results.children;
}
const props$7 = {
nodes: {
type: [Array, String],
default: function() {
return [];
}
},
/** @deprecated 请使用 user-select */
selectable: {
type: [Boolean, String],
default: false
},
userSelect: {
type: [Boolean, String],
default: false
}
};
const CHARS = {
amp: "&",
gt: ">",
lt: "<",
nbsp: " ",
quot: '"',
apos: "'",
ldquo: "“",
rdquo: "”",
yen: "¥",
radic: "√",
lceil: "⌈",
rceil: "⌉",
lfloor: "⌊",
rfloor: "⌋",
hellip: "…"
};
function decodeEntities(htmlString) {
return htmlString.replace(
/&(([a-zA-Z]+)|(#x{0,1}[\da-zA-Z]+));/gi,
function(match, stage) {
if (hasOwn(CHARS, stage) && CHARS[stage]) {
return CHARS[stage];
}
if (/^#[0-9]{1,4}$/.test(stage)) {
return String.fromCharCode(stage.slice(1));
}
if (/^#x[0-9a-f]{1,4}$/i.test(stage)) {
return String.fromCharCode(Number("0" + stage.slice(1)));
}
return match;
}
);
}
function processClickEvent(node, triggerItemClick) {
if (node.name && ["a", "img"].includes(node.name) && triggerItemClick) {
return {
onClickCapture: (e2) => {
if (node.name === "a") {
triggerItemClick(e2, { href: (node.attrs || {}).href });
} else {
triggerItemClick(e2, { src: (node.attrs || {}).src });
}
e2.stopPropagation();
e2.preventDefault();
e2.returnValue = false;
}
};
}
}
function normalizeValue(tagName, name, value) {
if (tagName === "img" && name === "src" && isString(value)) {
return getRealPath(value);
}
return value;
}
function normalizeAttrs(tagName, attrs2) {
if (!isPlainObject(attrs2))
return;
const normalizedAttrs = {};
Object.keys(attrs2).forEach((name) => {
normalizedAttrs[name] = normalizeValue(tagName, name, attrs2[name]);
});
return normalizedAttrs;
}
function nodeType(node) {
if (!isPlainObject(node))
return "";
if ((!hasOwn(node, "type") || node.type === "text") && isString(node.text) && node.text !== "") {
return "#text";
}
return (!hasOwn(node, "type") || node.type === "node") && isString(node.name) && node.name ? node.name : "";
}
function hasContent(attrs2) {
return attrs2 && (attrs2.innerHTML != null || attrs2.textContent != null || attrs2[".innerHTML"] != null || attrs2[".textContent"] != null);
}
function nodeKey(node) {
if (!isPlainObject(node == null ? void 0 : node.attrs))
return;
const key = node.attrs.key;
if (key == null || node.type === "text")
return;
if (!hasOwn(node, "type") && isString(node.text) && node.text !== "")
return;
return key;
}
function nodeList2Block(source, scopeId, triggerItemClick, namespace = () => Namespaces.HTML) {
let previous = [];
let hadUnkeyed = false;
let renderedTypes;
const unkeyedTypes = /* @__PURE__ */ new WeakMap();
function unkeyedType(node) {
if (!isPlainObject(node))
return "";
let type = unkeyedTypes.get(node);
if (!type)
unkeyedTypes.set(node, type = computed(() => nodeType(node)));
return type.value;
}
const keyedSource = computed(() => {
var _a;
const nodes = source() || [];
if (!nodes.length) {
previous = [];
hadUnkeyed = false;
renderedTypes = void 0;
return { nodes, keys: [] };
}
let hasUnkeyed = false;
const next2 = Array.from(nodes, (node) => {
const key = nodeKey(node);
if (key == null)
hasUnkeyed = true;
return {
key,
// 显式 key 的标签更新由节点分支处理,不订阅整个列表。
type: key != null ? hadUnkeyed ? nodeType(toRaw(node)) : "" : unkeyedType(node),
id: key
};
});
const same = (old, entry) => old.key === entry.key && ((renderedTypes == null ? void 0 : renderedTypes.get(old.id)) ?? old.type) === entry.type;
let start = 0;
let oldEnd = previous.length - 1;
let newEnd = next2.length - 1;
while (start <= oldEnd && start <= newEnd && same(previous[start], next2[start])) {
next2[start].id = previous[start].id;
start++;
}
while (start <= oldEnd && start <= newEnd && same(previous[oldEnd], next2[newEnd])) {
next2[newEnd--].id = previous[oldEnd--].id;
}
let unkeyed;
for (let i = oldEnd; i >= start; i--) {
const entry = previous[i];
if (entry.key != null)
continue;
const pool = unkeyed || (unkeyed = /* @__PURE__ */ new Map());
let ids = pool.get(entry.type);
if (!ids)
pool.set(entry.type, ids = []);
ids.push(entry.id);
}
for (let i = start; i <= newEnd; i++) {
const entry = next2[i];
if (entry.key == null)
entry.id = ((_a = unkeyed == null ? void 0 : unkeyed.get(entry.type)) == null ? void 0 : _a.pop()) ?? Symbol();
}
const keys = [];
let nextRenderedTypes;
for (const entry of next2) {
keys.push(entry.id);
if (entry.key != null) {
const types = nextRenderedTypes || (nextRenderedTypes = /* @__PURE__ */ new Map());
types.set(entry.id, (renderedTypes == null ? void 0 : renderedTypes.get(entry.id)) ?? entry.type);
}
}
renderedTypes = nextRenderedTypes;
previous = next2;
hadUnkeyed = hasUnkeyed;
return { nodes, keys };
});
return createFor(
() => keyedSource.value.nodes,
(item) => createKeyedFragment(
() => {
const type = nodeType(item.value);
const key = nodeKey(item.value);
if (key != null)
renderedTypes.set(key, type);
return type + ":" + namespace();
},
() => {
const name = nodeType(item.value);
if (!name)
return [];
if (name === "#text") {
const text2 = createTextNode();
renderEffect(() => setText(text2, decodeEntities(item.value.text)));
return text2;
}
const ns = name === "svg" ? Namespaces.SVG : name === "math" ? Namespaces.MATH_ML : namespace();
const element = createPlainElement(name, null, null, false, false, ns);
let childScope;
let children;
renderEffect(() => {
var _a;
const node = item.value;
const attrs2 = normalizeAttrs(name.toLowerCase(), node.attrs);
const content = hasContent(attrs2);
if (content && childScope) {
childScope.stop();
remove$1(children, element);
children = void 0;
childScope = void 0;
}
setDynamicProps(
element,
[
extend(
scopeId ? { [scopeId]: "" } : {},
processClickEvent(node, triggerItemClick),
attrs2
)
],
void 0,
ns === Namespaces.SVG
);
if (!content && !childScope && ((_a = node.children) == null ? void 0 : _a.length)) {
childScope = effectScope();
children = childScope.run(
() => nodeList2Block(
() => item.value.children || [],
scopeId,
triggerItemClick,
() => {
var _a2, _b;
return ns === Namespaces.SVG && name === "foreignObject" || ns === Namespaces.MATH_ML && name === "annotation-xml" && ((_b = (_a2 = item.value.attrs) == null ? void 0 : _a2.encoding) == null ? void 0 : _b.includes("html")) ? Namespaces.HTML : ns;
}
)
);
insert(children, element);
}
});
if (element.tagName === "SELECT")
syncSelectValue(element);
return element;
}
),
(_node, index2) => keyedSource.value.keys[index2]
);
}
function renderRichText(props2, rootRef, triggerItemClick) {
const vm = getCurrentInstance();
const nodes = computed(
() => isString(props2.nodes) ? parseHtml(props2.nodes) : props2.nodes
);
const root = createPlainElement(
"div",
{
selectable: () => props2.userSelect || props2.selectable ? true : null
},
{
default: () => createPlainElement("div", null, {
default: () => (
// 与 VDOM vnode.scopeId 对应,保留调用方的作用域样式。
nodeList2Block(
() => nodes.value,
vm.scopeId || "",
triggerItemClick
)
)
})
},
true
);
root.setAttribute("uni-rich-text", "");
root.setAttribute("uni-view", "");
rootRef.value = root;
return root;
}
class UniRichTextElement extends UniViewElement {
static [Symbol.hasInstance](value) {
return this === UniRichTextElement && value instanceof UniViewElement && value.hasAttribute("uni-rich-text") || Function.prototype[Symbol.hasInstance].call(this, value);
}
}
const uniTagName$4 = { value: "RICH-TEXT" };
const indexVapor$3 = /* @__PURE__ */ defineBuiltInComponent({
name: "RichText",
compatConfig: { MODE: 3 },
props: props$7,
emits: ["itemclick"],
rootElement: {
name: "uni-rich-text",
class: UniRichTextElement
},
setup(props2, { emit: emit2 }) {
const rootRef = ref(null);
const trigger = useCustomEvent(rootRef, emit2);
function triggerItemClick(e2, detail = {}) {
trigger("itemclick", e2, detail);
}
const result = renderRichText(props2, rootRef, triggerItemClick);
Object.defineProperty(result, "uniTagName", uniTagName$4);
return result;
}
});
const _UniScrollViewElement = class _UniScrollViewElement extends UniViewElement {
static [Symbol.hasInstance](value) {
return this === _UniScrollViewElement && value instanceof UniViewElement && value.hasAttribute("uni-scroll-view") || Function.prototype[Symbol.hasInstance].call(this, value);
}
};
_UniScrollViewElement.__uniElement = {};
let UniScrollViewElement = _UniScrollViewElement;
function initScrollViewElement(root) {
Object.defineProperty(root, "uniTagName", {
value: "SCROLL-VIEW",
configurable: true
});
}
const SCROLL_END_DELAY = 100;
const passiveOptions = { passive: true };
function onScrollend(element, listener2) {
if ("onscrollend" in element) {
element.addEventListener("scrollend", listener2, passiveOptions);
return () => {
element.removeEventListener("scrollend", listener2);
};
}
const activeTouches = /* @__PURE__ */ new Set();
let lastScrollEvent = null;
let waitingForTouchEnd = false;
const schedule = debounce(
() => {
if (activeTouches.size > 0) {
waitingForTouchEnd = true;
} else if (lastScrollEvent !== null) {
const event = lastScrollEvent;
lastScrollEvent = null;
listener2(event);
}
},
SCROLL_END_DELAY,
{ setTimeout, clearTimeout }
);
const onScroll = (event) => {
waitingForTouchEnd = false;
lastScrollEvent = event;
schedule();
};
const onTouchStart = (event) => {
for (let i = 0; i < event.changedTouches.length; i++) {
activeTouches.add(event.changedTouches[i].identifier);
}
};
const onTouchEnd = (event) => {
for (let i = 0; i < event.changedTouches.length; i++) {
activeTouches.delete(event.changedTouches[i].identifier);
}
if (activeTouches.size === 0 && waitingForTouchEnd) {
waitingForTouchEnd = false;
schedule();
}
};
element.addEventListener("touchstart", onTouchStart, passiveOptions);
element.addEventListener("touchend", onTouchEnd, passiveOptions);
element.addEventListener("touchcancel", onTouchEnd, passiveOptions);
element.addEventListener("scroll", onScroll, passiveOptions);
return () => {
element.removeEventListener("touchstart", onTouchStart);
element.removeEventListener("touchend", onTouchEnd);
element.removeEventListener("touchcancel", onTouchEnd);
element.removeEventListener("scroll", onScroll);
schedule.cancel();
activeTouches.clear();
lastScrollEvent = null;
waitingForTouchEnd = false;
};
}
const props$6 = {
direction: { type: String, default: "vertical" },
showScrollbar: { type: [Boolean, String], default: true },
upperThreshold: { type: [Number, String], default: 50 },
lowerThreshold: { type: [Number, String], default: 50 },
scrollTop: { type: [Number, String], default: 0 },
scrollLeft: { type: [Number, String], default: 0 },
scrollIntoView: { type: String, default: "" },
scrollWithAnimation: { type: [Boolean, String], default: false }
};
const emits = ["scroll", "scrollend", "scrolltoupper", "scrolltolower"];
function threshold(value) {
const number = Number(value);
return isNaN(number) ? 50 : number;
}
function useScrollView(props2, { emit: emit2, expose }) {
const rootRef = ref(null);
const trigger = useCustomEvent(rootRef, emit2);
const scrollX = computed(
() => props2.direction === "horizontal" || props2.direction === "all"
);
const scrollY = computed(
() => props2.direction === "vertical" || props2.direction === "all"
);
const rootStyle = computed(
() => `overflow-x:${scrollX.value ? "auto" : "hidden"};overflow-y:${scrollY.value ? "auto" : "hidden"};`
);
const scrollBarClassName = computed(
() => props2.showScrollbar === false ? "uni-scroll-view-scrollbar-hidden" : ""
);
let lastScrollTop = 0;
let lastScrollLeft = 0;
let lastUpperTime = 0;
let lastLowerTime = 0;
function scrollTo2(options) {
var _a;
(_a = rootRef.value) == null ? void 0 : _a.scrollTo(
Object.assign(options, {
behavior: props2.scrollWithAnimation ? "smooth" : "instant"
})
);
}
function scrollIntoView(id2) {
const root = rootRef.value;
if (!root || !id2)
return;
if (!/^[_a-zA-Z][-_a-zA-Z0-9:]*$/.test(id2)) {
console.error(`id error: scroll-into-view=${id2}`);
return;
}
const element = root.querySelector(`[id="${id2}"]`);
if (!element)
return;
const rootRect = root.getBoundingClientRect();
const rect = element.getBoundingClientRect();
const options = {};
if (scrollX.value) {
options.left = root.scrollLeft + rect.left - rootRect.left - root.clientLeft;
}
if (scrollY.value) {
options.top = root.scrollTop + rect.top - rootRect.top - root.clientTop;
}
if (options.left !== void 0 || options.top !== void 0)
scrollTo2(options);
}
function detail(root) {
return {
scrollLeft: root.scrollLeft,
scrollTop: root.scrollTop,
scrollHeight: root.scrollHeight,
scrollWidth: root.scrollWidth,
deltaX: lastScrollLeft - root.scrollLeft,
deltaY: lastScrollTop - root.scrollTop
};
}
function checkBoundary(event, position, previous, size, total, upper, lower) {
if (position <= threshold(props2.upperThreshold) && position < previous && event.timeStamp - lastUpperTime > 200) {
trigger("scrolltoupper", event, { direction: upper });
lastUpperTime = event.timeStamp;
}
if (position + size + threshold(props2.lowerThreshold) >= total && position > previous && event.timeStamp - lastLowerTime > 200) {
trigger("scrolltolower", event, { direction: lower });
lastLowerTime = event.timeStamp;
}
}
function handleScroll(event) {
const root = rootRef.value;
if (event.target !== root)
return;
event.stopPropagation();
trigger("scroll", event, detail(root));
if (scrollY.value) {
checkBoundary(
event,
root.scrollTop,
lastScrollTop,
root.clientHeight,
root.scrollHeight,
"top",
"bottom"
);
}
if (scrollX.value) {
checkBoundary(
event,
root.scrollLeft,
lastScrollLeft,
root.clientWidth,
root.scrollWidth,
"left",
"right"
);
}
lastScrollTop = root.scrollTop;
lastScrollLeft = root.scrollLeft;
}
function handleScrollEnd(event) {
if (event.target === rootRef.value) {
trigger("scrollend", event, detail(rootRef.value));
}
}
let touchStart = null;
function handleTouchStart(event) {
touchStart = event.touches.length === 1 ? { x: event.touches[0].pageX, y: event.touches[0].pageY } : null;
}
function handleTouchMove(event) {
if (!touchStart || event.touches.length !== 1)
return;
const root = rootRef.value;
const dx = event.touches[0].pageX - touchStart.x;
const dy = event.touches[0].pageY - touchStart.y;
const horizontal = Math.abs(dx) > Math.abs(dy);
if (horizontal ? !scrollX.value : !scrollY.value)
return;
const position = horizontal ? root.scrollLeft : root.scrollTop;
const max = horizontal ? root.scrollWidth - root.clientWidth : root.scrollHeight - root.clientHeight;
const delta = horizontal ? dx : dy;
if (delta > 0 && position > 0 || delta < 0 && position < max) {
event.stopPropagation();
}
}
function handleTouchEnd() {
touchStart = null;
}
let removeListeners;
onMounted(() => {
const root = rootRef.value;
const passive2 = { passive: true };
root.addEventListener("scroll", handleScroll, passive2);
root.addEventListener("touchstart", handleTouchStart, passive2);
root.addEventListener("touchmove", handleTouchMove, passive2);
root.addEventListener("touchend", handleTouchEnd, passive2);
root.addEventListener("touchcancel", handleTouchEnd, passive2);
const removeScrollend = onScrollend(root, handleScrollEnd);
removeListeners = () => {
root.removeEventListener("scroll", handleScroll);
root.removeEventListener("touchstart", handleTouchStart);
root.removeEventListener("touchmove", handleTouchMove);
root.removeEventListener("touchend", handleTouchEnd);
root.removeEventListener("touchcancel", handleTouchEnd);
removeScrollend();
};
nextTick(() => {
if (!rootRef.value)
return;
const options = {};
if (scrollX.value)
options.left = Number(props2.scrollLeft) || 0;
if (scrollY.value)
options.top = Number(props2.scrollTop) || 0;
if (options.left !== void 0 || options.top !== void 0)
scrollTo2(options);
scrollIntoView(props2.scrollIntoView);
});
});
onBeforeUnmount(() => removeListeners == null ? void 0 : removeListeners());
onActivated(() => {
var _a;
const options = { behavior: "instant" };
if (scrollX.value)
options.left = lastScrollLeft;
if (scrollY.value)
options.top = lastScrollTop;
(_a = rootRef.value) == null ? void 0 : _a.scrollTo(options);
});
watch(
() => [props2.scrollTop, props2.scrollLeft],
([top, left], [previousTop, previousLeft]) => {
const options = {};
if (scrollY.value && top !== previousTop)
options.top = Number(top) || 0;
if (scrollX.value && left !== previousLeft)
options.left = Number(left) || 0;
if (options.left !== void 0 || options.top !== void 0)
scrollTo2(options);
},
{ flush: "post" }
);
watch(() => props2.scrollIntoView, scrollIntoView, { flush: "post" });
expose({ $getMain: () => rootRef.value });
return { rootRef, rootStyle, scrollBarClassName };
}
const _t0$8 = template("<div uni-scroll-view uni-view> ", 1);
const __syscom_1 = /* @__PURE__ */ defineBuiltInComponent({
name: "ScrollView",
props: props$6,
emits,
rootElement: {
name: "uni-scroll-view",
class: UniScrollViewElement
},
setup(props2, context) {
const { rootRef, rootStyle, scrollBarClassName } = useScrollView(props2, context);
const { slots } = context;
const root = (() => {
const _setTemplateRef = createTemplateRefSetter();
const _n0 = _t0$8();
const _x0 = txt(_n0);
setNodes(_x0, () => slots.default && slots.default());
renderEffect(() => {
setStyle(_n0, rootStyle.value);
setClass(_n0, scrollBarClassName.value);
_setTemplateRef(_n0, rootRef);
});
return _n0;
})();
initScrollViewElement(root);
return root;
}
});
const FORM_KEY = "UNI_FORM_CTX";
const LABEL_KEY = "UNI_LABEL_CTX";
const RADIO_GROUP_KEY = "UNI_RADIO_GROUP_CTX";
const CHECKBOX_GROUP_KEY = "UNI_CHECKBOX_GROUP_CTX";
const PICKER_VIEW_KEY = "UNI_PICKER_VIEW_CTX";
const labelTargets = /* @__PURE__ */ new Map();
function registerLabelTarget(id2, target) {
if (id2.length === 0) {
return () => {
};
}
let targets = labelTargets.get(id2);
if (targets == null) {
targets = [];
labelTargets.set(id2, targets);
}
targets.push(target);
return () => {
const current = labelTargets.get(id2);
if (current == null)
return;
const index2 = current.indexOf(target);
if (index2 !== -1)
current.splice(index2, 1);
if (current.length === 0)
labelTargets.delete(id2);
};
}
function findLabelTarget(id2) {
if (id2.length === 0)
return null;
const targets = labelTargets.get(id2);
if (targets == null || targets.length === 0)
return null;
return targets[targets.length - 1];
}
function buildPointerEvent(event) {
return new MouseEvent("click", {
bubbles: true,
cancelable: true,
clientX: event.clientX,
clientY: event.clientY,
screenX: event.screenX,
screenY: event.screenY
});
}
function dispatchLabelClick(element, event) {
element.dispatchEvent(buildPointerEvent(event));
}
function toStringOrEmpty(val) {
if (val == null) {
return "";
}
return val + "";
}
function classes(...classList) {
return classList.map((className) => {
if (Array.isArray(className)) {
const classNames = className;
const condition = classNames[0];
const truthy = classNames[1];
const falsy = classNames.length > 2 ? classNames[2] : "";
return (condition ? truthy : falsy) ?? "";
}
return className ?? "";
});
}
function createSpaceKeyHandlers(isDisabled) {
let spacePressed = false;
function handleKeydown(event) {
if (event.key !== " " || event.target !== event.currentTarget || event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey) {
return;
}
event.preventDefault();
if (!event.repeat) {
spacePressed = !isDisabled();
}
}
function handleKeyup(event) {
var _a;
if (event.key !== " " || event.target !== event.currentTarget) {
return;
}
const shouldActivate = spacePressed;
spacePressed = false;
if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey) {
return;
}
event.preventDefault();
if (shouldActivate && !isDisabled()) {
(_a = event.currentTarget) == null ? void 0 : _a.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
}
}
function handleBlur() {
spacePressed = false;
}
return { handleKeydown, handleKeyup, handleBlur };
}
const _UniButtonElement = class _UniButtonElement extends UniTextElement {
constructor() {
super(...arguments);
this.tagName = "BUTTON";
this.nodeName = "BUTTON";
this._value = "";
}
get value() {
var _a, _b;
if ((_a = this.vm) == null ? void 0 : _a.isLoading()) {
return ((_b = this.vm) == null ? void 0 : _b.getValue()) ?? this._value;
}
return super.value ?? this._value;
}
};
_UniButtonElement.__uniElement = { vm: true, init() {
Object.defineProperty(this, "_value", { value: "", writable: true, enumerable: true, configurable: true });
} };
let UniButtonElement = _UniButtonElement;
const t0$x = template('<div uni-button uni-view style="display: flex;justify-content: center;flex-direction: row;align-items: center" role=button><!><span uni-text>', 1);
const t1$i = template("<span uni-button uni-text role=button>", 1);
const _uniButtonElement = { value: "BUTTON" };
const DEFAULT_BUTTON_HOVER_CLASS_NAME = "button-hover";
const _sfc_main$x = /* @__PURE__ */ defineVaporComponent({
...{
name: "button",
// @ts-ignore
rootElement: {
class: /* @__PURE__ */ initUniElementType(UniButtonElement, "button")
},
externalClasses: ["hover-class", "loading-class", "loading-text-class"]
},
__name: "button",
props: {
disabled: { type: Boolean, default: false },
type: { type: String },
size: { default: "default", type: String },
plain: { type: Boolean, default: false },
loadingClass: { type: null },
loadingTextClass: { type: null },
hoverClass: { type: null },
hoverStartTime: { default: 20, type: Number },
hoverStayTime: { default: 70, type: Number },
hoverStopPropagation: { type: Boolean, default: false },
loading: { type: Boolean, default: false },
formType: { type: String },
openType: { default: "", type: String },
iosLoadingSnow: { type: Boolean, default: false }
},
emits: ["click"],
setup(__props, { expose: __expose, emit: __emit }) {
const emit2 = __emit;
const props2 = __props;
const { handleKeydown: handleSpaceKeydown, handleKeyup, handleBlur } = createSpaceKeyHandlers(() => props2.disabled);
function handleKeydown(event) {
var _a;
if (event.key !== "Enter") {
handleSpaceKeydown(event);
return;
}
if (event.target !== event.currentTarget || event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey) {
return;
}
event.preventDefault();
if (!props2.disabled && !event.repeat) {
(_a = event.currentTarget) == null ? void 0 : _a.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
}
}
const loadingRootRef = ref(null);
watch(() => props2.loading && !props2.disabled, (_loading, wasLoading) => {
const element = wasLoading ? loadingRootRef.value : textRef.value;
if (element == null || document.activeElement !== element) {
return;
}
handleBlur();
nextTick(() => {
if (!props2.disabled && document.activeElement === document.body) {
const element2 = props2.loading && !props2.disabled ? loadingRootRef.value : textRef.value;
if (element2 instanceof HTMLElement) {
element2.focus();
}
}
});
});
const textRef = ref(null);
const buttonType = computed(() => {
return props2.type == null ? "default" : props2.type;
});
const loadingTextStyle = computed(() => {
let style = "font-size:inherit;line-height:inherit;font-weight:inherit;text-align:inherit;";
if (props2.loadingTextClass == null) {
style += "color:inherit;";
}
return style;
});
const formCtx = inject(FORM_KEY, null);
const enableTransition = ref(false);
onMounted(() => {
enableTransition.value = true;
});
const hoverClasses = computed(() => {
let isDefaultHoverClass = false;
if (props2.hoverClass != null) {
const hoverClass = `${props2.hoverClass}`.replace(/^\^+/, "");
if (hoverClass == "" || hoverClass == "none") {
return "none";
}
if (hoverClass != DEFAULT_BUTTON_HOVER_CLASS_NAME) {
return `${props2.hoverClass}`;
}
isDefaultHoverClass = true;
}
const classes2 = [];
if (!props2.plain) {
switch (buttonType.value) {
case "default":
classes2.push("uni-button-view_default_hover");
break;
case "primary":
classes2.push("uni-button-view_primary_hover");
break;
case "warn":
classes2.push("uni-button-view_warn_hover");
break;
}
} else {
switch (buttonType.value) {
case "default":
classes2.push("uni-button-view_plain_default_hover");
break;
case "primary":
classes2.push("uni-button-view_plain_primary_hover");
break;
case "warn":
classes2.push("uni-button-view_plain_warn_hover");
break;
}
}
if (isDefaultHoverClass) {
classes2.push(`${props2.hoverClass}`);
}
return classes2.join(" ");
});
const checkFormAndSubmitOrReset = () => {
if (props2.formType != "submit" && props2.formType != "reset") {
return;
}
if (formCtx == null) {
return;
}
if (props2.formType == "submit") {
formCtx.submit();
} else if (props2.formType == "reset") {
formCtx.reset();
}
};
const handleTap = (event) => {
if (props2.disabled) {
return;
}
emit2("click", event);
checkFormAndSubmitOrReset();
};
__expose({
getValue() {
if (textRef.value == null) {
return "";
}
return textRef.value.value;
},
isLoading() {
return props2.loading && !props2.disabled;
}
});
const _component_loading = _sfc_main$C;
const n0 = createIf(
() => __props.loading && !__props.disabled,
() => {
const n2 = t0$x();
const n6 = child(n2);
const n5 = next(n6);
initUniElement(n2, _uniButtonElement);
renderEffect(() => {
const _disabled = __props.disabled;
const _buttonType = unref(buttonType);
const _size = __props.size;
const _plain = __props.plain;
setHover(n2, _disabled ? "none" : unref(hoverClasses), __props.hoverStopPropagation, __props.hoverStartTime, __props.hoverStayTime, "");
setClass(n2, ["uni-button", unref(classes)(
[_buttonType == "default", "uni-button-type-default_view"],
[_buttonType == "primary", "uni-button-type-primary_view"],
[_buttonType == "warn", "uni-button-type-warn_view"],
[__props.type != null, "uni-button-has-type", "uni-button-no-type"],
[_disabled, "uni-button-disabled"],
[_size == "mini", "uni-button-size-mini"],
[unref(enableTransition), "transition-enabled"],
[_buttonType == "default", "uni-button-type-default_text"],
[_buttonType == "primary", "uni-button-type-primary_text"],
[_buttonType == "warn", "uni-button-type-warn_text"],
[_plain && __props.loading, "uni-button-text-plain"],
[_plain, "uni-button-view-plain"],
[_size == "mini", "uni-button-text-size-mini"],
[_size == "default", "uni-button-text-size-default"]
)]);
setProp(n2, "tabindex", _disabled ? -1 : 0);
setAttr(n2, "aria-disabled", _disabled);
});
setInsertionState(n2, n6);
withComponentId("0ed9fc4b", () => createComponentWithFallback(_component_loading, { class: () => ["uni-button-loading-icon", unref(classes)(
[unref(buttonType) == "default", "uni-loading-default"],
[__props.plain && unref(buttonType) == "primary", "uni-loading-plain-primary"],
[__props.plain && unref(buttonType) == "warn", "uni-loading-plain-warn"],
__props.loadingClass || "uni-button-loading-color-inherit"
)] }));
renderEffect(() => {
setClass(n5, ["uni-button-loading-text", __props.loadingTextClass || ""]);
setStyle(n5, unref(loadingTextStyle));
});
setInsertionState(n5);
createSlot(
"default",
null,
null,
256
/* TEXT_MODE */
);
setStaticTemplateRef(n5, textRef, null, "textRef");
on$1(n2, "keydown", handleKeydown);
on$1(n2, "keyup", (e2) => unref(handleKeyup)(e2));
on$1(n2, "blur", (e2) => unref(handleBlur)(e2));
on$1(n2, "click", handleTap);
setStaticTemplateRef(n2, loadingRootRef, null, "loadingRootRef");
return n2;
},
() => {
const n8 = t1$i();
initUniElement(n8, _uniButtonElement);
renderEffect(() => {
const _disabled = __props.disabled;
const _buttonType = unref(buttonType);
const _size = __props.size;
const _plain = __props.plain;
setHover(n8, _disabled ? "none" : unref(hoverClasses), __props.hoverStopPropagation, __props.hoverStartTime, __props.hoverStayTime, "");
setClass(n8, ["uni-button uni-button-text", unref(classes)(
[_buttonType == "default", "uni-button-type-default_view"],
[_buttonType == "primary", "uni-button-type-primary_view"],
[_buttonType == "warn", "uni-button-type-warn_view"],
[__props.type != null, "uni-button-has-type", "uni-button-no-type"],
[_disabled, "uni-button-disabled"],
[_size == "mini", "uni-button-size-mini"],
[unref(enableTransition), "transition-enabled"],
[_buttonType == "default", "uni-button-type-default_text"],
[_buttonType == "primary", "uni-button-type-primary_text"],
[_buttonType == "warn", "uni-button-type-warn_text"],
[_plain && __props.loading, "uni-button-text-plain"],
[_plain, "uni-button-view-plain"],
[_size == "mini", "uni-button-text-size-mini"],
[_size == "default", "uni-button-text-size-default"]
)]);
setProp(n8, "tabindex", _disabled ? -1 : 0);
setAttr(n8, "aria-disabled", _disabled);
});
setInsertionState(n8);
createSlot(
"default",
null,
null,
256
/* TEXT_MODE */
);
on$1(n8, "keydown", handleKeydown);
on$1(n8, "keyup", (e2) => unref(handleKeyup)(e2));
on$1(n8, "blur", (e2) => unref(handleBlur)(e2));
on$1(n8, "click", handleTap);
setStaticTemplateRef(n8, textRef, null, "textRef");
return n8;
},
261
/* TRUE_SINGLE_ROOT, FALSE_SINGLE_ROOT, KEYED_INDEX_0 */
);
return n0;
}
});
const _UniCheckboxElement = class _UniCheckboxElement extends UniViewElement {
constructor() {
super(...arguments);
this.tagName = "CHECKBOX";
this.nodeName = "CHECKBOX";
this._checked = false;
}
get checked() {
var _a;
return ((_a = this.vm) == null ? void 0 : _a.getCheckboxChecked()) ?? this._checked;
}
set checked(val) {
var _a;
if (this._checked == val) {
return;
}
this._checked = val;
(_a = this.vm) == null ? void 0 : _a.setCheckboxChecked(val);
}
};
_UniCheckboxElement.__uniElement = { vm: true, init() {
Object.defineProperty(this, "_checked", { value: false, writable: true, enumerable: true, configurable: true });
} };
let UniCheckboxElement = _UniCheckboxElement;
const t0$w = template('<svg class=uni-checkbox-svg viewBox="0 0 32 32"><path fill=currentColor>', 0, 1);
const t1$h = template("<div uni-checkbox uni-view role=checkbox>", 1);
const t2$8 = template("<span uni-text>");
const t3$5 = template("<div uni-checkbox uni-view class=uni-checkbox role=checkbox><div uni-view></div>", 1);
const _uniCheckboxElement = { value: "CHECKBOX" };
const iconPath$1 = "M1.952 18.080q-0.32-0.352-0.416-0.88t0.128-0.976l0.16-0.352q0.224-0.416 0.64-0.528t0.8 0.176l6.496 4.704q0.384 0.288 0.912 0.272t0.88-0.336l17.312-14.272q0.352-0.288 0.848-0.256t0.848 0.352l-0.416-0.416q0.32 0.352 0.32 0.816t-0.32 0.816l-18.656 18.912q-0.32 0.352-0.8 0.352t-0.8-0.32l-7.936-8.064z";
const _sfc_main$w = /* @__PURE__ */ defineVaporComponent({
...{
name: "checkbox",
// @ts-ignore
rootElement: {
class: /* @__PURE__ */ initUniElementType(UniCheckboxElement, "checkbox")
},
externalClasses: ["icon-class", "checkbox-class", "checkbox-active-class"]
},
__name: "checkbox",
props: {
color: { default: "", type: String },
disabled: { type: Boolean, default: false },
checked: { type: Boolean, default: false },
value: { default: "", type: String },
iconClass: { default: "", type: null },
checkboxClass: { default: "", type: null },
checkboxActiveClass: { default: "", type: null }
},
setup(__props, { expose: __expose }) {
var _a, _b;
const props2 = __props;
const { handleKeydown, handleKeyup, handleBlur } = createSpaceKeyHandlers(() => props2.disabled);
const attrs2 = useAttrs$1();
const id2 = attrs2.id;
const slots = useSlots();
const isStringSlot = ((_a = slots["default"]) == null ? void 0 : _a["returnType"]) == "string";
const hasDefaultSlot = slots["default"] != null;
const proxy = (_b = getCurrentInstance()) == null ? void 0 : _b.proxy;
const isChecked = ref(props2.checked);
const activeStyle = computed(() => {
if (isChecked.value && !props2.disabled && props2.color) {
return { color: props2.color };
}
return {};
});
const group = inject(CHECKBOX_GROUP_KEY, null);
const labelCtx = inject(LABEL_KEY, null);
let unregisterLabelTarget = null;
const setChecked = (checked, syncGroup) => {
if (isChecked.value == checked) {
return;
}
isChecked.value = checked;
if (syncGroup && group != null) {
group.toggle(toStringOrEmpty(props2.value), checked, false);
}
};
watch(() => props2.checked, (value) => {
setChecked(value, true);
});
onMounted(() => {
if (group != null) {
const value = toStringOrEmpty(props2.value);
const current = group.isChecked(value);
const initial = current ? true : props2.checked;
isChecked.value = initial;
group.register(value, isChecked.value, (checked) => {
setChecked(checked, false);
});
}
const target = {
id: id2 || toStringOrEmpty(props2.value),
activate: (event) => {
const element = proxy == null ? void 0 : proxy.$el;
if (element != null) {
dispatchLabelClick(element, event);
}
},
getDisabled: () => props2.disabled
};
if (labelCtx != null) {
labelCtx.register(target);
}
if (id2 != null && id2.length > 0) {
unregisterLabelTarget = registerLabelTarget(id2, target);
}
});
onUnmounted(() => {
if (group != null) {
group.unregister(toStringOrEmpty(props2.value));
}
if (labelCtx != null) {
labelCtx.unregister(id2 || toStringOrEmpty(props2.value));
}
unregisterLabelTarget == null ? void 0 : unregisterLabelTarget();
unregisterLabelTarget = null;
});
const handleTap = () => {
if (props2.disabled) {
return;
}
isChecked.value = !isChecked.value;
if (group != null) {
group.toggle(toStringOrEmpty(props2.value), isChecked.value, true);
}
};
__expose({
getCheckboxChecked: () => {
return isChecked.value;
},
setCheckboxChecked: (checked) => {
setChecked(checked, true);
}
});
const n0 = createIf(
() => !hasDefaultSlot,
() => {
const n2 = t1$h();
initUniElement(n2, _uniCheckboxElement);
renderEffect(() => {
const _disabled = __props.disabled;
const _isChecked = unref(isChecked);
setClass(n2, ["uni-checkbox-view uni-checkbox-icon", unref(classes)(
[_disabled, "uni-checkbox-disabled"],
[!_disabled && _isChecked, __props.checkboxActiveClass],
[!_disabled && !_isChecked, __props.checkboxClass],
[!_disabled, __props.iconClass]
)]);
setStyle(n2, unref(activeStyle));
setProp(n2, "tabindex", _disabled ? -1 : 0);
setAttr(n2, "aria-checked", _isChecked);
setAttr(n2, "aria-disabled", _disabled);
});
setInsertionState(n2);
createIf(() => unref(isChecked), () => {
const n6 = t0$w();
const n5 = child(n6);
setAttr(n5, "d", iconPath$1, true);
return n6;
});
on$1(n2, "keydown", (e2) => unref(handleKeydown)(e2));
on$1(n2, "keyup", (e2) => unref(handleKeyup)(e2));
on$1(n2, "blur", (e2) => unref(handleBlur)(e2));
on$1(n2, "click", withModifiers(handleTap, ["stop"]));
return n2;
},
() => {
const n8 = t3$5();
const n13 = child(n8);
initUniElement(n8, _uniCheckboxElement);
renderEffect(() => {
const _disabled = __props.disabled;
const _isChecked = unref(isChecked);
setProp(n8, "tabindex", _disabled ? -1 : 0);
setAttr(n8, "aria-checked", _isChecked);
setAttr(n8, "aria-disabled", _disabled);
setClass(n13, ["uni-checkbox-view uni-checkbox-icon", unref(classes)(
[_disabled, "uni-checkbox-disabled"],
[!_disabled && _isChecked, __props.checkboxActiveClass],
[!_disabled && !_isChecked, __props.checkboxClass],
[!_disabled, __props.iconClass]
)]);
setStyle(n13, unref(activeStyle));
});
setInsertionState(n13);
createIf(() => unref(isChecked), () => {
const n12 = t0$w();
const n11 = child(n12);
setAttr(n11, "d", iconPath$1, true);
return n12;
});
setInsertionState(n8, 1);
createIf(
() => isStringSlot,
() => {
const n17 = t2$8();
setInsertionState(n17);
createSlot(
"default",
null,
null,
256
/* TEXT_MODE */
);
return n17;
},
() => {
const n19 = createSlot();
return n19;
},
1029
/* TRUE_SINGLE_ROOT, FALSE_SINGLE_ROOT, KEYED_INDEX_3 */
);
on$1(n8, "keydown", (e2) => unref(handleKeydown)(e2));
on$1(n8, "keyup", (e2) => unref(handleKeyup)(e2));
on$1(n8, "blur", (e2) => unref(handleBlur)(e2));
on$1(n8, "click", withModifiers(handleTap, ["stop"]));
return n8;
},
517
/* TRUE_SINGLE_ROOT, FALSE_SINGLE_ROOT, KEYED_INDEX_1 */
);
return n0;
}
});
const _UniCheckboxGroupElement = class _UniCheckboxGroupElement extends UniViewElement {
};
_UniCheckboxGroupElement.__uniElement = {};
let UniCheckboxGroupElement = _UniCheckboxGroupElement;
const t0$v = template("<div uni-checkbox-group uni-view>", 1);
const _uniCheckboxGroupElement = { value: "CHECKBOX-GROUP" };
const _sfc_main$v = /* @__PURE__ */ defineVaporComponent({
...{
name: "checkbox-group",
// @ts-ignore
rootElement: {
class: /* @__PURE__ */ initUniElementType(UniCheckboxGroupElement, "checkbox-group")
}
},
__name: "checkbox-group",
props: {
name: { default: "", type: String }
},
emits: ["change"],
setup(__props, { emit: __emit }) {
const props2 = __props;
class UniCustomEvent3 {
constructor(type, detail) {
this.detail = detail;
}
}
class UniCheckboxGroupChangeEvent extends UniCustomEvent3 {
constructor(value) {
super("change", { value });
}
}
const emit2 = __emit;
const selectedValues = ref([]);
const initialSelected = ref([]);
const childSetters = /* @__PURE__ */ new Map();
let elementOrderCounter = 0;
const elementOrderMap = /* @__PURE__ */ new Map();
const ensureIncluded = (value) => {
if (selectedValues.value.indexOf(value) == -1) {
selectedValues.value.push(value);
}
};
const ensureExcluded = (value) => {
const i = selectedValues.value.indexOf(value);
if (i != -1) {
selectedValues.value.splice(i, 1);
}
};
const updateSelection2 = (value, checked) => {
if (checked) {
ensureIncluded(value);
} else {
ensureExcluded(value);
}
};
const dispatchEvent = () => {
const sortedValues = selectedValues.value.slice().sort((a, b) => {
const orderA = elementOrderMap.get(a) ?? 0;
const orderB = elementOrderMap.get(b) ?? 0;
return orderA - orderB;
});
emit2("change", new UniCheckboxGroupChangeEvent(sortedValues));
};
const ctx = {
register: (value, checked, setChecked) => {
childSetters.set(value, setChecked);
elementOrderMap.set(value, elementOrderCounter++);
updateSelection2(value, checked);
if (initialSelected.value.indexOf(value) == -1 && checked) {
initialSelected.value.push(value);
}
},
unregister: (value) => {
ensureExcluded(value);
childSetters.delete(value);
elementOrderMap.delete(value);
},
toggle: (value, checked, emitChange) => {
updateSelection2(value, checked);
if (emitChange) {
dispatchEvent();
}
},
isChecked: (value) => {
return selectedValues.value.indexOf(value) != -1;
},
name: props2.name
};
provide(CHECKBOX_GROUP_KEY, ctx);
const formCtx = inject(FORM_KEY, null);
onMounted(() => {
if (formCtx && props2.name) {
initialSelected.value = selectedValues.value.slice();
formCtx.registerField({
name: props2.name,
getValue: () => selectedValues.value.slice(),
reset: () => {
const initial = new Set(initialSelected.value);
selectedValues.value = initialSelected.value.slice();
childSetters.forEach((setChecked, val) => {
setChecked(initial.has(val));
});
dispatchEvent();
}
});
}
});
onUnmounted(() => {
if (formCtx && props2.name) {
formCtx.unregisterField(props2.name);
}
elementOrderMap.clear();
elementOrderCounter = 0;
});
const n0 = t0$v();
initUniElement(n0, _uniCheckboxGroupElement);
setInsertionState(n0);
createSlot();
return n0;
}
});
const _UniFlowItemElement = class _UniFlowItemElement extends UniViewElement {
};
_UniFlowItemElement.__uniElement = {};
let UniFlowItemElement = _UniFlowItemElement;
const _UniWaterflowElement = class _UniWaterflowElement extends UniScrollViewElement {
};
_UniWaterflowElement.__uniElement = {};
let UniWaterflowElement = _UniWaterflowElement;
const t0$u = template('<div uni-flow-item uni-view class=uni-flow-item style="position: absolute; top: 0; left: 0; width: 0px">', 1);
const _uniFlowItemElement = { value: "FLOW-ITEM" };
const _sfc_main$u = /* @__PURE__ */ defineVaporComponent({
...{
name: "flow-item",
rootElement: {
class: /* @__PURE__ */ initUniElementType(UniFlowItemElement, "flow-item")
}
},
__name: "flow-item",
props: {
itemKey: { type: [String, Number], required: true },
itemHeight: { type: Number, default: 0 }
},
setup(__props, { expose: __expose }) {
const props2 = __props;
const waterflow = inject("__uni_recycle_waterflow");
const element = ref(null);
const itemKeyRef = computed(() => String(props2.itemKey));
let registeredKey;
let recycled = false;
let destroyed = false;
const item = {
size: -1,
updateItemOffset(x, y) {
if (element.value)
element.value.style.translate = `${x}px ${y}px`;
},
updateItemCrossAxisSize(width) {
if (element.value)
element.value.style.width = `${width}px`;
}
};
const recycleHooks = /* @__PURE__ */ new Map([
["brc", [recycle]],
["ru", [reuse]]
]);
provide("__uni_recycle_state_key_ref", itemKeyRef);
provide("__uni_recycle_hooks", recycleHooks);
const observer = new UniResizeObserver(() => measure());
function unregister() {
if (registeredKey !== void 0 && waterflow.itemInstanceMap.get(registeredKey) === item) {
waterflow.itemInstanceMap.delete(registeredKey);
}
registeredKey = void 0;
}
function measure() {
if (destroyed || recycled || !element.value || !element.value.isConnected)
return;
const key = String(props2.itemKey);
if (registeredKey !== key) {
unregister();
registeredKey = key;
waterflow.itemInstanceMap.set(key, item);
}
item.updateItemCrossAxisSize(waterflow.getItemCrossAxisSize());
item.updateItemOffset(...waterflow.getItemOffset(key));
const rect = element.value.getBoundingClientRect();
if (rect.width > 0) {
item.size = rect.height;
waterflow.updateItemSize(key, item.size);
}
}
function recycle() {
recycled = true;
observer.disconnect();
unregister();
}
function reuse() {
recycled = false;
nextTick(() => {
if (destroyed || recycled || !element.value)
return;
observer.observe(element.value);
measure();
});
}
onMounted(reuse);
watch(
() => props2.itemKey,
() => measure(),
{ flush: "post" }
);
onBeforeUnmount(() => {
destroyed = true;
observer.disconnect();
unregister();
});
__expose({ recycleHooks });
const n0 = t0$u();
initUniElement(n0, _uniFlowItemElement);
setInsertionState(n0);
createSlot();
setStaticTemplateRef(n0, element, null, "element");
return n0;
}
});
const _UniFormElement = class _UniFormElement extends UniViewElement {
};
_UniFormElement.__uniElement = {};
let UniFormElement = _UniFormElement;
const t0$t = template("<div uni-form uni-view class=uni-form>", 1);
const _uniFormElement = { value: "FORM" };
const _sfc_main$t = /* @__PURE__ */ defineVaporComponent({
...{
name: "form",
// @ts-ignore
rootElement: {
class: /* @__PURE__ */ initUniElementType(UniFormElement, "form")
}
},
__name: "form",
props: {
disabled: { type: Boolean, default: false }
},
emits: ["submit", "reset"],
setup(__props, { expose: __expose, emit: __emit }) {
const props2 = __props;
class UniCustomEvent3 {
constructor(type, detail) {
this.detail = detail;
}
}
class UniFormSubmitEvent extends UniCustomEvent3 {
constructor(value) {
super("submit", { value });
}
}
class UniFormResetEvent extends UniCustomEvent3 {
constructor() {
super("reset", {});
}
}
const emit2 = __emit;
const fields = /* @__PURE__ */ new Map();
function registerField(field) {
if (!field.name) {
return;
}
fields.set(field.name, field);
}
function unregisterField(name) {
if (!name) {
return;
}
fields.delete(name);
}
function submit() {
if (props2.disabled) {
return;
}
const data = {};
fields.forEach((field, name) => {
data[name] = field.getValue();
});
emit2("submit", new UniFormSubmitEvent(data));
}
function reset() {
if (props2.disabled) {
return;
}
fields.forEach((field) => {
field.reset && field.reset();
});
emit2("reset", new UniFormResetEvent());
}
const ctx = { registerField, unregisterField, submit, reset };
provide(FORM_KEY, ctx);
__expose({ submit, reset });
const n0 = t0$t();
initUniElement(n0, _uniFormElement);
setInsertionState(n0);
createSlot();
return n0;
}
});
const _UniLabelElement = class _UniLabelElement extends UniViewElement {
};
_UniLabelElement.__uniElement = {};
let UniLabelElement = _UniLabelElement;
const t0$s = template("<div uni-label uni-view class=uni-label>", 1);
const _uniLabelElement = { value: "LABEL" };
const _sfc_main$s = /* @__PURE__ */ defineVaporComponent({
...{
name: "label",
// @ts-ignore
rootElement: {
class: /* @__PURE__ */ initUniElementType(UniLabelElement, "label")
}
},
__name: "label",
props: {
disabled: { type: Boolean, default: false },
for: { default: "", type: String }
},
setup(__props) {
const props2 = __props;
const { handleKeydown, handleKeyup, handleBlur } = createSpaceKeyHandlers(() => props2.disabled);
const children = [];
function register2(child2) {
if (child2.id && child2.id.length > 0) {
const idx = children.findIndex((c) => c.id === child2.id);
if (idx !== -1) {
children[idx] = child2;
return;
}
}
children.push(child2);
}
function unregister(id2) {
if (!id2)
return;
const idx = children.findIndex((c) => c.id === id2);
if (idx !== -1) {
children.splice(idx, 1);
}
}
const ctx = { register: register2, unregister };
provide(LABEL_KEY, ctx);
function findTarget() {
if (props2.for && props2.for.length > 0) {
const byId = children.find((c) => c.id === props2.for);
if (byId)
return byId;
const byScopeId = findLabelTarget(props2.for);
if (byScopeId)
return byScopeId;
}
if (children.length === 0)
return null;
return children[0];
}
const handleTap = (event) => {
var _a;
const eventTarget = event.target;
const element = (eventTarget == null ? void 0 : eventTarget.nodeType) === 1 ? eventTarget : eventTarget == null ? void 0 : eventTarget.parentElement;
if (element == null ? void 0 : element.closest("uni-button, [uni-button], .uni-button")) {
return;
}
const classList = ((_a = event.target) == null ? void 0 : _a.classList) ? event.target.classList : [];
for (let i = 0; i < classList.length; i++) {
if (/^uni-(checkbox|radio|switch)/.test(classList[i])) {
return;
}
}
if (props2.disabled) {
return;
}
const target = findTarget();
if (target == null)
return;
if (target.getDisabled && target.getDisabled())
return;
target.activate(event);
};
const n0 = t0$s();
initUniElement(n0, _uniLabelElement);
renderEffect(() => {
const _disabled = __props.disabled;
setProp(n0, "tabindex", _disabled ? -1 : 0);
setAttr(n0, "aria-disabled", _disabled);
});
setInsertionState(n0);
createSlot();
on$1(n0, "keydown", (e2) => unref(handleKeydown)(e2));
on$1(n0, "keyup", (e2) => unref(handleKeyup)(e2));
on$1(n0, "blur", (e2) => unref(handleBlur)(e2));
on$1(n0, "click", handleTap);
return n0;
}
});
const _UniListItemElement = class _UniListItemElement extends UniViewElement {
};
_UniListItemElement.__uniElement = {};
let UniListItemElement = _UniListItemElement;
const _UniStickySectionElement = class _UniStickySectionElement extends UniViewElement {
};
_UniStickySectionElement.__uniElement = {};
let UniStickySectionElement = _UniStickySectionElement;
const _UniStickyHeaderElement = class _UniStickyHeaderElement extends UniViewElement {
};
_UniStickyHeaderElement.__uniElement = {};
let UniStickyHeaderElement = _UniStickyHeaderElement;
const _UniListViewElement = class _UniListViewElement extends UniScrollViewElement {
};
_UniListViewElement.__uniElement = {};
let UniListViewElement = _UniListViewElement;
const t0$r = template('<div uni-list-item uni-view class=uni-list-item style="position: absolute; top: 0; left: 0; width: 100%">', 1);
const _uniListItemElement = { value: "LIST-ITEM" };
const _sfc_main$r = /* @__PURE__ */ defineVaporComponent({
...{
name: "list-item",
rootElement: {
class: /* @__PURE__ */ initUniElementType(UniListItemElement, "list-item")
}
},
__name: "list-item",
props: {
itemKey: { type: [String, Number], required: true }
},
setup(__props, { expose: __expose }) {
const props2 = __props;
const container = inject("__uni_recycle_container");
const sectionId = inject("__uni_recycle_section_id", 0);
const element = ref(null);
const itemKeyRef = computed(() => `${sectionId}:${props2.itemKey}`);
let registeredKey;
let recycled = false;
let destroyed = false;
const item = {
size: -1,
updateItemOffset(offset) {
if (element.value)
element.value.style.translate = `0 ${offset}px`;
}
};
const recycleHooks = /* @__PURE__ */ new Map([
["brc", [recycle]],
["ru", [reuse]]
]);
provide("__uni_recycle_state_key_ref", itemKeyRef);
provide("__uni_recycle_hooks", recycleHooks);
const observer = new ResizeObserver(() => measure());
function unregister() {
if (registeredKey !== void 0 && container.store.itemInstanceMap.get(registeredKey) === item) {
container.store.itemInstanceMap.delete(registeredKey);
}
registeredKey = void 0;
}
function measure() {
if (destroyed || recycled || !element.value || !element.value.isConnected)
return;
const key = String(props2.itemKey);
if (registeredKey !== key) {
unregister();
registeredKey = key;
container.store.itemInstanceMap.set(key, item);
}
item.updateItemOffset(container.getItemOffset(key));
item.size = element.value.getBoundingClientRect().height;
container.updateItemSize(key, item.size);
}
function recycle() {
recycled = true;
observer.disconnect();
unregister();
}
function reuse() {
recycled = false;
nextTick(() => {
if (destroyed || recycled || !element.value)
return;
observer.observe(element.value);
measure();
});
}
onMounted(reuse);
watch(
() => props2.itemKey,
() => measure(),
{ flush: "post" }
);
onBeforeUnmount(() => {
destroyed = true;
observer.disconnect();
unregister();
});
__expose({ recycleHooks });
const n0 = t0$r();
initUniElement(n0, _uniListItemElement);
setInsertionState(n0);
createSlot();
setStaticTemplateRef(n0, element, null, "element");
return n0;
}
});
class RecycleListItemDataStore {
constructor() {
this.list = [];
this.keyItemMap = /* @__PURE__ */ new Map();
this.itemInstanceMap = /* @__PURE__ */ new Map();
this.defaultItemSize = 150;
}
realItemSize(item) {
return item.size < 0 ? this.defaultItemSize : item.size;
}
get contentSize() {
const last = this.list[this.list.length - 1];
return last ? last.offset + this.realItemSize(last) : 0;
}
updateKeyList(keys) {
const oldItems = this.keyItemMap;
this.keyItemMap = /* @__PURE__ */ new Map();
this.list = keys.map((key, index2) => {
const instance2 = this.itemInstanceMap.get(key);
const item = oldItems.get(key) || {
key,
index: index2,
size: instance2 ? instance2.size : -1,
offset: 0
};
item.index = index2;
this.keyItemMap.set(key, item);
return item;
});
this.rebuildItemOffsetsFrom(0);
}
rebuildItemOffsetsFrom(start) {
for (let i = start; i < this.list.length; i++) {
const previous = this.list[i - 1];
this.list[i].offset = previous ? previous.offset + this.realItemSize(previous) : 0;
}
}
updateItemOffset(baseOffset) {
this.itemInstanceMap.forEach((instance2, key) => {
const item = this.keyItemMap.get(key);
if (item)
instance2.updateItemOffset(item.offset + baseOffset);
});
}
getRenderRange(min, max) {
let low = 0;
let high = this.list.length;
while (low < high) {
const mid = low + high >>> 1;
const item = this.list[mid];
if (item.offset + this.realItemSize(item) < min)
low = mid + 1;
else
high = mid;
}
const start = low;
high = this.list.length;
while (low < high) {
const mid = low + high >>> 1;
if (this.list[mid].offset <= max)
low = mid + 1;
else
high = mid;
}
return [start, low - start];
}
}
const t0$q = template("<div uni-view></div>");
const t1$g = template('<div uni-view style="position: relative; overflow: visible; overflow-anchor: none"><div uni-view style="width: 1px; flex-shrink: 0;"></div></div>');
const _uniListViewElement = { value: "LIST-VIEW" };
const _sfc_main$q = /* @__PURE__ */ defineVaporComponent({
...{
name: "list-view",
rootElement: {
class: /* @__PURE__ */ initUniElementType(UniListViewElement, "list-view")
}
},
__name: "list-view",
props: {
scrollIntoView: { type: String, default: "" },
scrollAnchoring: { type: [Boolean, String], default: false },
initialScrollBottom: { type: [Boolean, String], default: false }
},
setup(__props, { expose: __expose }) {
const props2 = __props;
useAttrs$1();
const scrollElement = ref(null);
const headerElement = ref(null);
const bodyElement = ref(null);
const placeholderElement = ref(null);
const renderRange = ref([0, 0]);
const store = new RecycleListItemDataStore();
const sectionMap = /* @__PURE__ */ new Map();
const idKeyMap = /* @__PURE__ */ new Map();
let keys = [];
let listIds = [];
let size = 0;
let headerSize = 0;
let realScrollOffset = 0;
let scrollOffset = 0;
let fastScrollOffset = 0;
let lastScrollTimestamp = 0;
let lastScrollOffset = 0;
let cachedSizeStart = 200;
let cachedSizeEnd = 200;
let scrolling = false;
let scrollEndTimer;
let queued = false;
let destroyed = false;
let listDataStatus = 0;
let maintainInitialScrollBottom = true;
let anchorKey;
let anchorOffset = 0;
let scrollTarget;
let pendingScrollId = props2.scrollIntoView;
let targetOffset = -1;
let itemSizeChangedCompensation = 0;
let sizeChangeAnchorKey;
let sizeChangeAnchorOffset = 0;
provide("__uni_recycle_view_instance", getCurrentInstance());
provide("__uni_recycle_state_map", /* @__PURE__ */ new Map());
provide("__uni_recycle_list", {
sectionMap,
queueLayout,
syncDefaultItemSize
});
provide("__uni_recycle_container", {
store,
updateItemSize,
getItemOffset
});
function updateIdKeyMap() {
if (listIds.length !== keys.length)
return;
idKeyMap.clear();
listIds.forEach((id2, index2) => {
if (id2 && keys[index2])
idKeyMap.set(id2, keys[index2]);
});
}
function updateList(newList) {
if (listDataStatus === 0 && newList.length)
listDataStatus = 1;
else if (listDataStatus === 1)
listDataStatus = 2;
keys = newList;
store.updateKeyList(newList);
updateIdKeyMap();
queueLayout();
}
function updateListIds(ids) {
listIds = ids;
updateIdKeyMap();
queueLayout();
}
function updateRenderInfo(start, length) {
if (renderRange.value[0] !== start || renderRange.value[1] !== length) {
renderRange.value = [start, length];
}
}
function getItemOffset(key) {
const item = store.keyItemMap.get(key);
return item ? item.offset + fastScrollOffset - itemSizeChangedCompensation : -1;
}
function updateItemSize(key, height) {
const item = store.keyItemMap.get(key);
if (!item || item.size === height)
return;
item.size = height;
store.rebuildItemOffsetsFrom(item.index + 1);
if (scrolling && !scrollTarget && sizeChangeAnchorKey) {
const anchor = store.keyItemMap.get(sizeChangeAnchorKey);
if (anchor)
itemSizeChangedCompensation = anchor.offset - sizeChangeAnchorOffset;
}
queueLayout();
}
function syncDefaultItemSize(height) {
if (height > 0)
sectionMap.forEach((section) => section.applyDefaultItemSize(height));
}
function queueLayout() {
if (queued || destroyed)
return;
queued = true;
nextTick(() => {
queued = false;
if (!destroyed && scrollElement.value)
updateRenderList();
});
}
function linkSection() {
const sections = Array.from(sectionMap.values()).filter(
(section) => section.element && section.element.isConnected
);
sections.sort(
(a, b) => a.element.compareDocumentPosition(b.element) & 4 ? -1 : 1
);
let offsetTop = 0;
sections.forEach((section) => {
section.offsetTop = offsetTop;
offsetTop += section.placeholderSize;
});
return sections;
}
function resolveScrollTarget(sections) {
if (!pendingScrollId)
return;
const key = idKeyMap.get(pendingScrollId);
if (key !== void 0)
scrollTarget = { key };
else {
for (const section of sections) {
const sectionKey = section.resolveKeyById(pendingScrollId);
if (sectionKey !== void 0) {
scrollTarget = { key: sectionKey, section };
break;
}
if (section.element.id === pendingScrollId || section.headerElement && section.headerElement.id === pendingScrollId) {
scrollTarget = { key: "", section };
break;
}
}
}
if (scrollTarget) {
pendingScrollId = "";
maintainInitialScrollBottom = false;
cachedSizeStart = 0;
targetOffset = -1;
}
}
function scrollToOffset(offset) {
const element = scrollElement.value;
element.scrollTo(0, offset);
realScrollOffset = element.scrollTop;
scrollOffset = realScrollOffset;
fastScrollOffset = 0;
}
function updateRenderList() {
const element = scrollElement.value;
const sections = linkSection();
if (placeholderElement.value)
placeholderElement.value.style.height = `${sections.length ? 0 : store.contentSize}px`;
resolveScrollTarget(sections);
if (scrollTarget) {
const { key, section } = scrollTarget;
const item = store.keyItemMap.get(key);
const offset = section ? section.offsetTop + (key ? section.getItemOffset(key) : 0) : item ? item.offset : -1;
if (offset >= 0 && targetOffset !== offset + headerSize) {
targetOffset = offset + headerSize;
scrollToOffset(
targetOffset
);
}
} else if (!sections.length && !scrolling) {
if (props2.initialScrollBottom && maintainInitialScrollBottom && listDataStatus === 1) {
scrollToOffset(
Math.max(element.scrollHeight, headerSize + store.contentSize) - size
);
} else if (props2.scrollAnchoring && anchorKey) {
const anchor = store.keyItemMap.get(anchorKey);
if (anchor) {
scrollToOffset(realScrollOffset + anchor.offset - anchorOffset);
anchorOffset = anchor.offset;
} else
anchorKey = void 0;
}
}
const min = Math.max(
0,
scrollOffset - headerSize - cachedSizeStart + itemSizeChangedCompensation + 0.2
);
const max = scrollOffset - headerSize + size + cachedSizeEnd + itemSizeChangedCompensation - 0.2;
store.updateItemOffset(fastScrollOffset - itemSizeChangedCompensation);
updateRenderInfo(...store.getRenderRange(min, max));
for (const section of sections) {
section.onScrollContextUpdate({
containerSize: size,
headerSize,
renderStartOffset: min + headerSize,
renderEndOffset: max + headerSize
});
}
if (!scrolling)
updateScrollAnchorItem();
}
function updateScrollAnchorItem() {
anchorKey = void 0;
if (!props2.scrollAnchoring || realScrollOffset <= 0 || sectionMap.size)
return;
const offset = realScrollOffset - headerSize;
const [index2] = store.getRenderRange(offset, offset);
const item = store.list[index2];
if (item) {
anchorKey = item.key;
anchorOffset = item.offset;
}
}
function onScroll(e2) {
const element = scrollElement.value;
const offset = Math.max(0, e2.detail.scrollTop);
if (offset < element.scrollHeight - size - 0.2 && Math.abs(offset - realScrollOffset) > 0.2)
maintainInitialScrollBottom = false;
if (!scrolling) {
scrolling = true;
anchorKey = void 0;
const item = store.list[renderRange.value[0] + renderRange.value[1] - 1];
sizeChangeAnchorKey = item && item.key;
sizeChangeAnchorOffset = item ? item.offset : 0;
}
if (offset === 0 || offset >= store.contentSize - size)
itemSizeChangedCompensation = 0;
if (offset + itemSizeChangedCompensation < 0) {
itemSizeChangedCompensation = 0;
scrollToOffset(0);
return;
}
const timestamp = Date.now();
const elapsed = timestamp - lastScrollTimestamp;
const delta = offset - lastScrollOffset;
realScrollOffset = offset;
cachedSizeStart = scrollTarget ? 0 : 200;
cachedSizeEnd = 200;
const fast = sectionMap.size === 0 && !scrollTarget && lastScrollTimestamp > 0 && elapsed > 0 && Math.abs(delta / elapsed) > 15 && offset > 1 && offset < element.scrollHeight - size - 1;
if (fast) {
if (delta > 0)
cachedSizeStart = 0;
else
cachedSizeEnd = 0;
scrollOffset += Math.sign(delta) * Math.min(Math.abs(delta), 120);
fastScrollOffset = offset - scrollOffset;
} else {
scrollOffset = offset;
fastScrollOffset = 0;
}
lastScrollOffset = offset;
lastScrollTimestamp = timestamp;
updateRenderList();
clearTimeout(scrollEndTimer);
scrollEndTimer = setTimeout(onScrollEnd, 150);
}
function onScrollEnd() {
clearTimeout(scrollEndTimer);
if (!scrolling)
return;
scrolling = false;
if (itemSizeChangedCompensation)
scrollToOffset(realScrollOffset + itemSizeChangedCompensation);
itemSizeChangedCompensation = 0;
sizeChangeAnchorKey = void 0;
scrollOffset = realScrollOffset;
fastScrollOffset = 0;
lastScrollTimestamp = 0;
updateRenderList();
scrollTarget = void 0;
cachedSizeStart = 200;
cachedSizeEnd = 200;
updateScrollAnchorItem();
}
const resizeObserver = new ResizeObserver((entries2) => {
for (const entry of entries2) {
if (entry.target === scrollElement.value)
size = entry.contentRect.height;
else if (entry.target === headerElement.value)
headerSize = entry.borderBoxSize[0].blockSize;
}
queueLayout();
});
const sectionObserver = new MutationObserver(queueLayout);
onMounted(() => {
const element = scrollElement.value;
size = element.clientHeight;
realScrollOffset = scrollOffset = element.scrollTop;
headerSize = headerElement.value.getBoundingClientRect().height;
resizeObserver.observe(element);
resizeObserver.observe(headerElement.value);
sectionObserver.observe(bodyElement.value, { childList: true });
queueLayout();
});
watch(
() => props2.scrollIntoView,
(id2) => {
pendingScrollId = id2;
scrollTarget = void 0;
queueLayout();
}
);
watch(() => props2.scrollAnchoring, updateScrollAnchorItem);
watch(() => props2.initialScrollBottom, queueLayout);
onBeforeUnmount(() => {
destroyed = true;
clearTimeout(scrollEndTimer);
resizeObserver.disconnect();
sectionObserver.disconnect();
store.itemInstanceMap.clear();
sectionMap.clear();
});
__expose({ renderRange, updateList, updateListIds, updateRenderInfo });
const n9 = withComponentId("34459316", () => createComponent$1(__syscom_1, { onScroll: () => onScroll }, {
"refresher": extend$1(() => {
const n7 = createSlot(
"refresher",
null,
null,
4
/* FORWARDED */
);
return n7;
}, {
_: 1
/* NON_STABLE */
}),
"default": () => {
const n1 = t0$q();
setInsertionState(n1);
createSlot("header");
const n4 = t1$g();
const n2 = child(n4);
setStaticTemplateRef(n1, headerElement, null, "headerElement");
setStaticTemplateRef(n2, placeholderElement, null, "placeholderElement");
setInsertionState(n4, 1);
createSlot();
const n6 = t0$q();
setStaticTemplateRef(n4, bodyElement, null, "bodyElement");
setInsertionState(n6);
createSlot("footer");
return [n1, n4, n6];
}
}, true));
setStaticTemplateRef(n9, scrollElement, null, "scrollElement");
const _uniListViewRoot = getBlockFirstNode(n9);
if (_uniListViewRoot && _uniListViewRoot.nodeType === 1) {
_uniListViewRoot.setAttribute("uni-list-view", "");
initUniElement(_uniListViewRoot, _uniListViewElement);
}
return n9;
}
});
const _UniMatchMediaElement = class _UniMatchMediaElement extends UniViewElement {
};
_UniMatchMediaElement.__uniElement = {};
let UniMatchMediaElement = _UniMatchMediaElement;
const createLifeCycleHook = (lifecycle, flag = 0) => (hook, target = getCurrentInstance()) => {
if (isInSSRComponentSetup)
return;
injectHook(lifecycle, hook, target);
};
const onLoad = /* @__PURE__ */ createLifeCycleHook(
ON_LOAD,
2
/* HookFlags.PAGE */
);
const onReady = /* @__PURE__ */ createLifeCycleHook(
ON_READY,
2
/* HookFlags.PAGE */
);
const onUnload = /* @__PURE__ */ createLifeCycleHook(
ON_UNLOAD,
2
/* HookFlags.PAGE */
);
const onResize = /* @__PURE__ */ createLifeCycleHook(
ON_RESIZE,
2
/* HookFlags.PAGE */
);
const onBackPress = /* @__PURE__ */ createLifeCycleHook(
ON_BACK_PRESS,
2
/* HookFlags.PAGE */
);
const t0$p = template("<div uni-match-media uni-view>", 1);
const _uniMatchMediaElement = { value: "MATCH-MEDIA" };
const _sfc_main$p = /* @__PURE__ */ defineVaporComponent({
...{
name: "match-media",
// @ts-ignore
rootElement: {
class: /* @__PURE__ */ initUniElementType(UniMatchMediaElement, "match-media")
}
},
__name: "match-media",
props: {
orientation: { type: String },
width: { default: "", type: [String, Number] },
minWidth: { default: "", type: [String, Number] },
maxWidth: { default: "", type: [String, Number] },
height: { default: "", type: [String, Number] },
minHeight: { default: "", type: [String, Number] },
maxHeight: { default: "", type: [String, Number] }
},
setup(__props) {
const RE_MQ_FEATURE = /^(min|max)?([A-Z]?[a-z]+)(?:([A-Z])([a-z]+))?$/;
const props2 = __props;
const show = ref(false);
show.value = isValid(getExpressions(), {
width: uni.getWindowInfo().windowWidth,
height: uni.getWindowInfo().windowHeight,
orientation: uni.getDeviceInfo().deviceOrientation
});
onResize((res) => {
const expressions = getExpressions();
show.value = isValid(expressions, {
width: res.size.windowWidth,
height: res.size.windowHeight,
orientation: res.deviceOrientation
});
});
watch(props2, () => {
const expressions = getExpressions();
const { windowWidth, windowHeight } = uni.getWindowInfo();
show.value = isValid(expressions, {
width: windowWidth,
height: windowHeight,
orientation: uni.getDeviceInfo().deviceOrientation
});
});
function getExpressions() {
const expressions = [];
Object.keys(props2).forEach((key) => {
const value = props2[key];
const feature = key.match(RE_MQ_FEATURE);
if (value != null && feature != null && feature.length > 0) {
expressions.push({
modifier: feature[1] != null ? feature[1] : "",
feature: feature[2] != null ? feature[2].toLowerCase() : "",
value
});
}
});
return expressions;
}
function isValid(expressions, values) {
return expressions.every((expression) => {
switch (expression.feature) {
case "orientation":
return props2.orientation != null ? values.orientation === props2.orientation : true;
}
if (expression.value === "") {
return true;
}
const expressionValue = values[expression.feature];
switch (expression.modifier) {
case "min":
return parseFloat(expression.value) <= expressionValue;
case "max":
return parseFloat(expression.value) >= expressionValue;
default:
return parseFloat(expression.value) === expressionValue;
}
});
}
const n0 = t0$p();
initUniElement(n0, _uniMatchMediaElement);
setInsertionState(n0);
createSlot();
applyVShow(n0, () => unref(show));
return n0;
}
});
const _UniNavigatorElement = class _UniNavigatorElement extends UniViewElement {
};
_UniNavigatorElement.__uniElement = {};
let UniNavigatorElement = _UniNavigatorElement;
const t0$o = template("<span uni-navigator uni-text>", 1);
const t1$f = template("<div uni-navigator uni-view>", 1);
const _uniNavigatorElement = { value: "NAVIGATOR" };
const _sfc_main$o = /* @__PURE__ */ defineVaporComponent({
...{
name: "navigator",
// @ts-ignore
rootElement: {
class: /* @__PURE__ */ initUniElementType(UniNavigatorElement, "navigator")
}
},
__name: "navigator",
props: {
openType: { default: "navigate", type: String },
url: { default: "", type: String },
animationType: { default: "", type: String },
animationDuration: { default: 300, type: Number },
delta: { default: 1, type: Number }
},
setup(__props) {
var _a;
const props2 = __props;
const slots = useSlots();
const isStringSlot = ((_a = slots["default"]) == null ? void 0 : _a["returnType"]) === "string";
const handleTap = () => {
const url = props2.url;
const openType = props2.openType;
const onFail = (res) => {
console.error(res.errMsg);
};
switch (openType) {
case "navigate":
uni.navigateTo({
url,
animationType: props2.animationType || "pop-in",
animationDuration: props2.animationDuration,
fail: onFail
});
break;
case "navigateBack":
uni.navigateBack({
delta: props2.delta,
animationType: props2.animationType || "pop-out",
animationDuration: props2.animationDuration,
fail: onFail
});
break;
case "redirect":
uni.redirectTo({
url,
fail: onFail
});
break;
case "reLaunch":
uni.reLaunch({
url,
fail: onFail
});
break;
case "switchTab":
uni.switchTab({
url,
fail: onFail
});
break;
default:
console.log("<navigator/> openType attribute invalid");
break;
}
};
const n0 = createIf(
() => isStringSlot,
() => {
const n2 = t0$o();
initUniElement(n2, _uniNavigatorElement);
setInsertionState(n2);
createSlot(
"default",
null,
null,
256
/* TEXT_MODE */
);
on$1(n2, "click", handleTap);
return n2;
},
() => {
const n5 = t1$f();
initUniElement(n5, _uniNavigatorElement);
setInsertionState(n5);
createSlot();
on$1(n5, "click", handleTap);
return n5;
},
261
/* TRUE_SINGLE_ROOT, FALSE_SINGLE_ROOT, KEYED_INDEX_0 */
);
return n0;
}
});
class UniVueElement extends HTMLElement {
}
const _UniPageContainerElement = class _UniPageContainerElement extends UniVueElement {
};
_UniPageContainerElement.__uniElement = {};
let UniPageContainerElement = _UniPageContainerElement;
const t0$n = template("<div uni-view class=uni-page-container-overlay>");
const t1$e = template("<div uni-view>");
const MAX_SLIDER_DISTANCE = 100;
const MIN_SLIDER_VELOCITY = 0.3;
const _sfc_main$n = /* @__PURE__ */ defineVaporComponent({
...{
name: "page-container",
rootElement: {
class: UniPageContainerElement
}
},
__name: "page-container",
props: {
show: { type: Boolean, default: false },
duration: { default: 300, type: Number },
zIndex: { default: 100, type: Number },
overlay: { type: Boolean, default: true },
round: { type: Boolean, default: false },
position: { default: "bottom", type: String },
customStyle: { default: "", type: String },
overlayStyle: { default: "", type: String },
closeOnSlideDown: { type: Boolean, default: false }
},
emits: ["beforeenter", "enter", "afterenter", "beforeleave", "leave", "afterleave", "clickoverlay"],
__multiRoot: true,
setup(__props, { emit: __emit }) {
const props2 = __props;
const emits2 = __emit;
const showPageContainer = ref(false);
const isAnimating = ref(false);
const transitionTimer = ref(null);
const isEntered = ref(false);
const transitionType = ref(null);
let transitionVersion = 0;
let touchStartX = 0;
let touchStartY = 0;
let touchStartTime = 0;
let isDragging = false;
const translateValue = ref(0);
const isSlideClosing = ref(false);
const isSlideLeaving = ref(false);
const overlayStyleMap = computed(() => {
const styleMap = {
"z-index": props2.zIndex,
"transition-duration": props2.duration + "ms"
};
if (isEntered.value) {
styleMap["opacity"] = "1";
styleMap["pointer-events"] = "auto";
}
return styleMap;
});
const innerStyleMap = computed(() => {
const styleMap = {
"z-index": props2.zIndex + 1,
"transition-duration": props2.duration + "ms"
};
if (translateValue.value != 0 && (isDragging || isSlideClosing.value)) {
let transformValue = "";
if (isSlideLeaving.value) {
switch (props2.position) {
case "bottom":
transformValue = "translateY(100%)";
break;
case "top":
transformValue = "translateY(-100%)";
break;
case "left":
transformValue = "translateX(-100%)";
break;
case "right":
transformValue = "translateX(100%)";
break;
}
} else {
switch (props2.position) {
case "bottom":
case "top":
transformValue = `translateY(${translateValue.value}px)`;
break;
case "left":
case "right":
transformValue = `translateX(${translateValue.value}px)`;
break;
}
}
if (transformValue != "") {
styleMap["transform"] = transformValue;
styleMap["transition"] = isDragging ? "none" : `transform ${props2.duration}ms ease`;
}
} else if (translateValue.value != 0 && !isDragging) {
styleMap["transition"] = `transform ${props2.duration}ms ease`;
}
return styleMap;
});
const popupClasses = computed(() => {
const classes2 = [];
if (props2.position != null) {
classes2.push(`uni-page-container-popup-${props2.position}`);
}
if (props2.round) {
classes2.push("uni-page-container-popup-round");
}
if (isEntered.value) {
classes2.push("uni-page-container-popup-enter");
}
return classes2;
});
function resetDragState() {
isDragging = false;
isSlideClosing.value = false;
isSlideLeaving.value = false;
translateValue.value = 0;
}
function clearTransitionTimer() {
if (transitionTimer.value != null) {
clearTimeout(transitionTimer.value);
transitionTimer.value = null;
}
}
function cancelTransition() {
transitionVersion++;
clearTransitionTimer();
isAnimating.value = false;
transitionType.value = null;
}
function onAnimationEnd(type, version) {
if (version != transitionVersion || transitionType.value != type) {
return;
}
isAnimating.value = false;
clearTransitionTimer();
transitionType.value = null;
if (type == "enter") {
emits2("afterenter");
} else if (type == "leave") {
showPageContainer.value = false;
isEntered.value = false;
resetDragState();
emits2("afterleave");
}
}
function listenTransitionEnd(type, version) {
clearTransitionTimer();
transitionTimer.value = setTimeout(() => {
onAnimationEnd(type, version);
}, props2.duration);
}
function closeContainer() {
if (!showPageContainer.value || transitionType.value == "leave") {
return;
}
if (transitionType.value == "enter") {
cancelTransition();
}
emits2("beforeleave");
isAnimating.value = true;
transitionType.value = "leave";
transitionVersion++;
const version = transitionVersion;
nextTick(() => {
if (version != transitionVersion || transitionType.value != "leave") {
return;
}
isEntered.value = false;
emits2("leave");
listenTransitionEnd("leave", version);
});
}
function openContainer() {
if (transitionType.value == "enter" && showPageContainer.value) {
return;
}
if (transitionType.value == "leave") {
cancelTransition();
}
emits2("beforeenter");
showPageContainer.value = true;
isEntered.value = false;
isAnimating.value = true;
transitionType.value = "enter";
transitionVersion++;
const version = transitionVersion;
resetDragState();
nextTick(() => {
if (version != transitionVersion || transitionType.value != "enter") {
return;
}
emits2("enter");
requestAnimationFrame(() => {
if (version != transitionVersion || transitionType.value != "enter") {
return;
}
requestAnimationFrame(() => {
if (version != transitionVersion || transitionType.value != "enter") {
return;
}
if (!props2.show) {
closeContainer();
return;
}
isEntered.value = true;
listenTransitionEnd("enter", version);
});
});
});
}
watch(() => props2.show, (newVal) => {
if (newVal && (!showPageContainer.value || transitionType.value == "leave")) {
openContainer();
} else if (!newVal && showPageContainer.value && transitionType.value != "leave") {
closeContainer();
}
});
function onClickOverlay(event) {
if (isAnimating.value) {
return;
}
emits2("clickoverlay", event);
nextTick(() => {
closeContainer();
});
}
function onTouchStart(e2) {
if (!props2.closeOnSlideDown) {
return;
}
if (e2.touches.length > 0) {
const { clientX, clientY } = e2.touches[0];
touchStartX = clientX;
touchStartY = clientY;
touchStartTime = Date.now();
isDragging = false;
}
}
function onTouchMove(e2) {
if (!props2.closeOnSlideDown) {
e2.preventDefault();
e2.stopPropagation();
return;
}
if (e2.touches.length > 0) {
const { clientX, clientY } = e2.touches[0];
const deltaX = clientX - touchStartX;
const deltaY = clientY - touchStartY;
let shouldDrag = false;
let dragValue = 0;
switch (props2.position) {
case "bottom":
if (deltaY > 0) {
shouldDrag = true;
dragValue = deltaY;
}
break;
case "top":
if (deltaY < 0) {
shouldDrag = true;
dragValue = deltaY;
}
break;
case "left":
if (deltaX < 0) {
shouldDrag = true;
dragValue = deltaX;
}
break;
case "right":
if (deltaX > 0) {
shouldDrag = true;
dragValue = deltaX;
}
break;
}
if (shouldDrag) {
isDragging = true;
translateValue.value = dragValue;
e2.preventDefault();
e2.stopPropagation();
}
}
}
function onTouchEnd() {
if (!props2.closeOnSlideDown) {
return;
}
if (isDragging) {
const deltaTime = Date.now() - touchStartTime;
const velocity = Math.abs(translateValue.value) / deltaTime;
const shouldClose = Math.abs(translateValue.value) > MAX_SLIDER_DISTANCE || velocity > MIN_SLIDER_VELOCITY;
if (shouldClose) {
resetDragState();
closeContainer();
} else {
resetDragState();
}
}
}
function onTouchCancel() {
if (!props2.closeOnSlideDown) {
return;
}
if (isDragging) {
resetDragState();
}
}
function onKeydown(event) {
if (showPageContainer.value && (event.key == "Escape" || event.key == "Esc")) {
closeContainer();
}
}
onMounted(() => {
document.addEventListener("keydown", onKeydown);
if (props2.show) {
openContainer();
}
});
onBeforeUnmount(() => {
document.removeEventListener("keydown", onKeydown);
transitionVersion++;
clearTransitionTimer();
});
const n0 = createIf(() => __props.overlay && unref(showPageContainer), () => {
const n2 = t0$n();
on$1(n2, "click", onClickOverlay);
on$1(n2, "touchmove", withModifiers(() => {
}, ["prevent", "stop"]));
renderEffect(() => setStyle(n2, [unref(overlayStyleMap), __props.overlayStyle]));
return n2;
});
const n3 = createIf(() => unref(showPageContainer), () => {
const n6 = t1$e();
renderEffect(() => {
setClass(n6, ["uni-page-container-popup", unref(popupClasses)]);
setStyle(n6, [unref(innerStyleMap), __props.customStyle]);
});
setInsertionState(n6);
createSlot();
on$1(n6, "touchstart", onTouchStart);
on$1(n6, "touchmove", onTouchMove);
on$1(n6, "touchend", onTouchEnd);
on$1(n6, "touchcancel", onTouchCancel);
return n6;
});
return [n0, n3];
}
});
const _UniPickerElement = class _UniPickerElement extends UniViewElement {
constructor() {
super(...arguments);
this.tagName = "PICKER";
this.nodeName = "PICKER";
this._value = "";
}
get value() {
var _a;
return ((_a = this.vm) == null ? void 0 : _a.getPickerValue()) ?? this._value;
}
set value(val) {
var _a;
this._value = val;
(_a = this.vm) == null ? void 0 : _a.setPickerValue(val);
}
};
_UniPickerElement.__uniElement = { vm: true, init() {
Object.defineProperty(this, "_value", { value: "", writable: true, enumerable: true, configurable: true });
} };
let UniPickerElement = _UniPickerElement;
const t0$m = template("<div uni-picker uni-view>", 1);
const _uniPickerElement = { value: "PICKER" };
const OPEN_LOCK_DURATION = 300;
const DEFAULT_START_YEAR = 1970;
const DEFAULT_END_YEAR = 2099;
const _sfc_main$m = /* @__PURE__ */ defineVaporComponent({
...{
name: "picker",
// @ts-ignore
rootElement: {
class: /* @__PURE__ */ initUniElementType(UniPickerElement, "picker")
}
},
__name: "picker",
props: {
disabled: { type: Boolean, default: false },
mode: { default: "selector", type: String },
selectorType: { default: "", type: String },
range: { default: [], type: Array },
rangeKey: { default: "", type: String },
value: { default: "", type: [Number, String, Array] },
start: { default: "", type: String },
end: { default: "", type: String },
fields: { default: "day", type: String },
name: { default: "", type: String }
},
emits: ["change", "columnchange", "cancel"],
setup(__props, { expose: __expose, emit: __emit }) {
var _a;
const uuid = `${Date.now()}${Math.floor(Math.random() * 1e7)}`;
const baseEventName = `uni_picker_${uuid}`;
const readyEventName = `${baseEventName}_ready`;
const optionsEventName = `${baseEventName}_options`;
const layoutEventName = `${optionsEventName}_layout`;
const selectorChangeEventName = `${baseEventName}_selector_change`;
const cancelEventName = `${baseEventName}_cancel_change`;
const multiSelectorChangeEventName = `${baseEventName}_multiSelector_change`;
const timeChangeEventName = `${baseEventName}_time_change`;
const columnChangeEventName = `${baseEventName}_column_change`;
class UniCustomEvent3 {
constructor(type, options) {
this.detail = options.detail;
}
}
class UniPickerCancelEvent extends UniCustomEvent3 {
constructor() {
super("cancel", {
detail: {}
});
}
}
class UniPickerChangeEvent extends UniCustomEvent3 {
constructor(value) {
super("change", {
detail: { value }
});
}
}
class UniPickerColumnChangeEvent extends UniCustomEvent3 {
constructor(column, value) {
super("columnchange", {
detail: { value, column }
});
}
}
const props2 = __props;
const emit2 = __emit;
const formCtx = inject(FORM_KEY, null);
const labelCtx = inject(LABEL_KEY, null);
const attrs2 = useAttrs$1();
const id2 = attrs2.id;
const proxy = (_a = getCurrentInstance()) == null ? void 0 : _a.proxy;
let unregisterLabelTarget = null;
const innerValue = ref(props2.value);
const initialValue = ref("");
const isOpening = ref(false);
watch(() => props2.value, (value) => {
innerValue.value = value;
if (props2.mode == "multiSelector") {
uni.$emit(optionsEventName, {
range: props2.range,
rangeKey: props2.rangeKey,
multiSelectorValue: value ?? []
});
}
}, { deep: true });
function handleClick() {
if (props2.disabled) {
return;
}
if (isOpening.value) {
return;
}
isOpening.value = true;
uni.openDialogPage({
url: `uni:picker?readyEventName=${readyEventName}&optionsEventName=${optionsEventName}&cancelEventName=${cancelEventName}&selectorChangeEventName=${selectorChangeEventName}&multiSelectorChangeEventName=${multiSelectorChangeEventName}&timeChangeEventName=${timeChangeEventName}&columnChangeEventName=${columnChangeEventName}`,
success() {
setTimeout(() => {
isOpening.value = false;
}, OPEN_LOCK_DURATION);
},
fail() {
isOpening.value = false;
uni.$off(readyEventName);
uni.$off(optionsEventName);
}
});
}
function getPopover() {
const element = proxy == null ? void 0 : proxy.$el;
if (element == null)
return null;
const { top, left, width, height } = element.getBoundingClientRect();
return { top, left, width, height };
}
function sendLayout() {
uni.$emit(optionsEventName, {
layoutOnly: true,
popover: getPopover()
});
}
function sendOptions(eventName) {
const baseParams = {
mode: props2.mode
};
const isAppleTouchDevice = navigator.vendor.indexOf("Apple") === 0 && navigator.maxTouchPoints > 0;
baseParams.selectorType = props2.selectorType === "picker" || props2.selectorType === "select" ? props2.selectorType : isAppleTouchDevice ? "picker" : "select";
baseParams.popover = getPopover();
const currentValue = innerValue.value;
switch (props2.mode) {
case "selector":
baseParams.range = props2.range;
baseParams.rangeKey = props2.rangeKey;
baseParams.selectorValue = currentValue ?? 0;
break;
case "multiSelector":
baseParams.range = props2.range;
baseParams.rangeKey = props2.rangeKey;
baseParams.multiSelectorValue = currentValue ?? [];
break;
case "time":
baseParams.timeValue = getCurrentTimeValue();
baseParams.start = parseStartAndEndTime("start");
baseParams.end = parseStartAndEndTime("end");
break;
case "date":
baseParams.dateValue = getCurrentDateValue();
baseParams.fields = props2.fields;
baseParams.start = parseStartAndEndDate("start");
baseParams.end = parseStartAndEndDate("end");
}
uni.$emit(eventName, baseParams);
}
onMounted(() => {
initialValue.value = props2.value;
const target = {
id: id2,
activate: (event) => {
const element = proxy == null ? void 0 : proxy.$el;
if (element != null)
dispatchLabelClick(element, event);
},
getDisabled: () => props2.disabled
};
if (labelCtx != null)
labelCtx.register(target);
if (id2 != null && id2.length > 0)
unregisterLabelTarget = registerLabelTarget(id2, target);
if (formCtx && props2.name) {
formCtx.registerField({
name: props2.name,
getValue: () => innerValue.value,
reset: () => {
innerValue.value = initialValue.value;
}
});
}
uni.$on(layoutEventName, sendLayout);
uni.$on(readyEventName, () => {
sendOptions(optionsEventName);
});
uni.$on(cancelEventName, () => {
emit2("cancel", new UniPickerCancelEvent());
});
uni.$on(selectorChangeEventName, (value) => {
innerValue.value = value;
emit2("change", new UniPickerChangeEvent(value));
});
uni.$on(multiSelectorChangeEventName, (value) => {
innerValue.value = value;
emit2("change", new UniPickerChangeEvent(value));
});
uni.$on(timeChangeEventName, (value) => {
innerValue.value = value;
emit2("change", new UniPickerChangeEvent(value));
});
uni.$on(columnChangeEventName, (column, value) => {
emit2("columnchange", new UniPickerColumnChangeEvent(column, value));
});
});
onUnmounted(() => {
if (labelCtx != null)
labelCtx.unregister(id2);
unregisterLabelTarget == null ? void 0 : unregisterLabelTarget();
unregisterLabelTarget = null;
if (formCtx && props2.name) {
formCtx.unregisterField(props2.name);
}
uni.$off(layoutEventName, sendLayout);
uni.$off(readyEventName);
uni.$off(selectorChangeEventName);
uni.$off(multiSelectorChangeEventName);
uni.$off(timeChangeEventName);
uni.$off(columnChangeEventName);
uni.$off(cancelEventName);
});
function getCurrentDateValue() {
const today = parseTime(/* @__PURE__ */ new Date());
let date = innerValue.value;
let date_data = [];
if (date != "" && date != null) {
let date_val = date.split("-");
while (date_val.length < 3) {
date_val.push("1");
}
const year = Number(date_val[0]);
const startYear = props2.start ? Number(props2.start.split("-")[0]) : DEFAULT_START_YEAR;
const endYear = props2.end ? Number(props2.end.split("-")[0]) : DEFAULT_END_YEAR;
if (year < startYear) {
date_val[0] = String(startYear);
} else if (year > endYear) {
date_val[0] = String(endYear);
}
try {
const year2 = Number(date_val[0]);
const month = Number(date_val[1]);
const day = Number(date_val[2]);
date_data = parseTime(new Date(year2, month - 1, day));
} catch (_) {
date_data = today;
}
} else {
date_data = today;
}
return date_data;
}
function getCurrentTimeValue() {
const now = /* @__PURE__ */ new Date();
const hours = String(now.getHours()).padStart(2, "0");
const minutes = String(now.getMinutes()).padStart(2, "0");
const timeArray = [hours, minutes];
let time = innerValue.value;
let val;
if (time) {
let timeVal = time.split(":");
if (time.length < 2) {
val = timeArray;
} else {
val = formatTime2(timeVal);
}
} else {
val = timeArray;
}
return val;
}
function formatTime2(time) {
const formattedHours = String(time[0]).padStart(2, "0");
const formattedMinutes = String(time[1]).padStart(2, "0");
return [formattedHours, formattedMinutes];
}
function parseTime(date) {
const year = date.getFullYear().toString().padStart(2, "0");
const month = (date.getMonth() + 1).toString().padStart(2, "0");
const day = date.getDate().toString().padStart(2, "0");
return [year, month, day];
}
function parseStartAndEndTime(type) {
let time = props2[type];
let defaultVal = ["00", "00"];
if (type == "end") {
defaultVal = ["23", "59"];
}
let val;
if (time) {
let timeVal = time.split(":");
if (time.length < 2) {
val = defaultVal;
} else {
val = formatTime2(timeVal);
}
} else {
return defaultVal;
}
return val;
}
function parseStartAndEndDate(type) {
const dateStr = props2[type];
const defaultDate = type == "start" ? [String(DEFAULT_START_YEAR), "01", "01"] : [String(DEFAULT_END_YEAR), "12", "31"];
if (dateStr == null || dateStr.length == 0)
return defaultDate;
const parts = dateStr.split("-");
if (parts.length != 3)
return defaultDate;
const formatPart = (value, length) => {
return value.padStart(length, "0").slice(0, length);
};
const year = formatPart(parts[0], 4);
const month = formatPart(parts[1], 2);
const day = formatPart(parts[2], 2);
return [year, month, day];
}
__expose({
getPickerValue: () => {
return innerValue.value;
},
setPickerValue: (value) => {
innerValue.value = value;
}
});
const n0 = t0$m();
initUniElement(n0, _uniPickerElement);
setInsertionState(n0);
createSlot();
on$1(n0, "click", handleClick);
return n0;
}
});
const _UniPickerViewElement = class _UniPickerViewElement extends UniViewElement {
};
_UniPickerViewElement.__uniElement = {};
let UniPickerViewElement = _UniPickerViewElement;
const t0$l = template("<div uni-picker-view uni-view class=uni-picker-view>", 1);
const _uniPickerViewElement = { value: "PICKER-VIEW" };
const _sfc_main$l = /* @__PURE__ */ defineVaporComponent({
...{
name: "picker-view",
// @ts-ignore
rootElement: {
class: /* @__PURE__ */ initUniElementType(UniPickerViewElement, "picker-view")
},
externalClasses: ["mask-class", "indicator-class"]
},
__name: "picker-view",
props: {
indicatorStyle: { default: "", type: String },
indicatorClass: { default: "", type: null },
maskClass: { default: "", type: null },
maskTopStyle: { default: "", type: String },
maskBottomStyle: { default: "", type: String },
name: { default: "", type: String },
value: { default: () => [], type: Array }
},
emits: ["change"],
setup(__props, { emit: __emit }) {
const props2 = __props;
class UniCustomEvent3 {
constructor(type, detail) {
this.detail = detail;
}
}
class UniPickerViewChangeEvent extends UniCustomEvent3 {
constructor(value) {
super("change", { value });
}
}
const emit2 = __emit;
function parseIndicatorHeight(styleStr) {
const re = /height\s*:\s*(\d+)px/i;
const m = re.exec(styleStr);
if (m && m.length > 1) {
const n = parseInt(m[1]);
if (!isNaN(n) && n > 0)
return n;
}
return 50;
}
const itemHeight = computed(() => parseIndicatorHeight(props2.indicatorStyle));
const pickViewRef = ref(null);
const offsetHeight = ref(100);
const containerPaddingPx = computed(() => (offsetHeight.value - itemHeight.value) / 2 + "px");
const maskTopInlineStyle = computed(() => props2.maskTopStyle ? props2.maskTopStyle : {});
const maskBottomInlineStyle = computed(() => props2.maskBottomStyle ? props2.maskBottomStyle : {});
const indicatorInlineStyle = computed(() => props2.indicatorStyle ? props2.indicatorStyle : {});
const innerValue = ref([]);
const columns = [];
function normalizeValue2(value) {
return columns.map((_, i) => value[i] ?? 0);
}
function syncFromProp(indexes) {
innerValue.value = indexes;
setTimeout(() => {
for (let i = 0; i < columns.length; i++) {
const api2 = columns[i];
const index2 = indexes[i];
api2.setScrollTop(index2);
}
}, 30);
}
watch(() => props2.value, (newValue) => {
syncFromProp(normalizeValue2(newValue));
}, { deep: true });
function registerColumn(api2) {
columns.push(api2);
const idx = columns.length - 1;
return idx;
}
function unregisterColumn(api2) {
const i = columns.indexOf(api2);
if (i >= 0) {
columns.splice(i, 1);
}
}
function onColumnIndexChange(col, index2) {
const curr = innerValue.value.slice();
if (curr[col] !== index2) {
curr[col] = index2;
innerValue.value = curr;
emit2("change", new UniPickerViewChangeEvent(curr));
}
}
provide(PICKER_VIEW_KEY, {
itemHeight: () => itemHeight.value,
containerPaddingPx: () => containerPaddingPx.value,
maskClass: () => props2.maskClass,
indicatorClass: () => props2.indicatorClass,
maskTopStyle: () => maskTopInlineStyle.value,
maskBottomStyle: () => maskBottomInlineStyle.value,
indicatorStyle: () => indicatorInlineStyle.value,
registerColumn,
unregisterColumn,
onColumnIndexChange
});
const formCtx = inject(FORM_KEY, null);
onMounted(() => {
const initialValue = props2.value;
if (formCtx && props2.name) {
formCtx.registerField({
name: props2.name,
getValue: () => innerValue.value,
reset: () => {
syncFromProp(normalizeValue2(initialValue));
}
});
}
offsetHeight.value = pickViewRef.value.offsetHeight;
syncFromProp(normalizeValue2(initialValue));
});
onUnmounted(() => {
columns.splice(0, columns.length);
});
const n0 = t0$l();
initUniElement(n0, _uniPickerViewElement);
setInsertionState(n0);
createSlot();
setStaticTemplateRef(n0, pickViewRef, null, "pickViewRef");
return n0;
}
});
const _UniPickerViewColumnElement = class _UniPickerViewColumnElement extends UniViewElement {
};
_UniPickerViewColumnElement.__uniElement = {};
let UniPickerViewColumnElement = _UniPickerViewColumnElement;
const t0$k = template("<div uni-view>");
const t1$d = template("<div uni-picker-view-column uni-view class=picker-view-column tabindex=0><!><div uni-view></div><div uni-view></div><div uni-view>", 1);
const _uniPickerViewColumnElement = { value: "PICKER-VIEW-COLUMN" };
const EPSILON = 1;
const _sfc_main$k = /* @__PURE__ */ defineVaporComponent({
...{
name: "picker-view-column",
// @ts-ignore
rootElement: {
class: /* @__PURE__ */ initUniElementType(UniPickerViewColumnElement, "picker-view-column")
}
},
__name: "picker-view-column",
setup(__props) {
const ctx = inject(PICKER_VIEW_KEY);
const itemHeight = computed(() => ctx ? ctx.itemHeight() : 50);
const containerPaddingPx = computed(() => ctx ? ctx.containerPaddingPx() : "50%");
const maskClass = computed(() => ctx ? ctx.maskClass() : "");
const indicatorClass = computed(() => ctx ? ctx.indicatorClass() : "");
const maskTopInlineStyle = computed(() => ctx ? ctx.maskTopStyle() : {});
const maskBottomInlineStyle = computed(() => ctx ? ctx.maskBottomStyle() : {});
const indicatorInlineStyle = computed(() => ctx ? ctx.indicatorStyle() : {});
const selectedIndex = ref(0);
const isScrolling = ref(false);
const scrollViewRef = ref(null);
const rootRef = ref(null);
const contentRef = ref(null);
const scrollWithAnimation = ref(false);
let keyboardTargetIndex = null;
function clearKeyboardTarget() {
keyboardTargetIndex = null;
}
function handleKeydown(event) {
var _a;
if (event.target !== event.currentTarget || event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey || event.key !== "ArrowUp" && event.key !== "ArrowDown") {
return;
}
event.preventDefault();
const itemCount = ((_a = contentRef.value) == null ? void 0 : _a.children.length) ?? 0;
if (itemCount === 0 || scrollViewRef.value == null) {
return;
}
const step = event.key === "ArrowUp" ? -1 : 1;
const targetIndex = Math.max(0, Math.min(itemCount - 1, selectedIndex.value + step));
if (targetIndex === selectedIndex.value) {
return;
}
keyboardTargetIndex = targetIndex;
setScrollTop(targetIndex);
ctx == null ? void 0 : ctx.onColumnIndexChange(columnIndex, targetIndex);
}
let isAdjusting = false;
let columnIndex = -1;
function setScrollTop(idx) {
var _a;
if (idx < 0) {
idx = 0;
}
if (keyboardTargetIndex != null && keyboardTargetIndex !== idx) {
clearKeyboardTarget();
}
selectedIndex.value = idx;
const scrollTop = Math.max(0, idx * itemHeight.value);
(_a = scrollViewRef.value) == null ? void 0 : _a.scrollTo(0, scrollTop);
}
function getIndex() {
return selectedIndex.value;
}
const api2 = { setScrollTop, getIndex };
onMounted(() => {
if (ctx) {
columnIndex = ctx.registerColumn(api2);
}
setTimeout(() => {
scrollWithAnimation.value = true;
}, 100);
});
onUnmounted(() => {
if (ctx) {
ctx.unregisterColumn(api2);
}
});
function onScroll() {
if (!isScrolling.value) {
isScrolling.value = true;
}
}
function onScrollEnd(e2) {
var _a;
isScrolling.value = false;
if (isAdjusting) {
return;
}
const top = Math.max(e2.detail.scrollTop, 0);
if (keyboardTargetIndex != null) {
const itemCount = ((_a = contentRef.value) == null ? void 0 : _a.children.length) ?? 0;
if (keyboardTargetIndex < itemCount) {
if (Math.abs(top - keyboardTargetIndex * itemHeight.value) > EPSILON) {
setScrollTop(keyboardTargetIndex);
} else {
clearKeyboardTarget();
}
return;
}
clearKeyboardTarget();
}
const idx = Math.round(top / itemHeight.value);
const valueChanged = selectedIndex.value !== idx;
if (Math.abs(top - idx * itemHeight.value) > EPSILON) {
isAdjusting = true;
setScrollTop(idx);
setTimeout(() => {
isAdjusting = false;
}, 0);
} else {
selectedIndex.value = idx;
}
if (valueChanged) {
ctx == null ? void 0 : ctx.onColumnIndexChange(columnIndex, idx);
}
}
function handleClick(e2) {
var _a, _b;
if (!rootRef.value || !scrollViewRef.value || isScrolling.value) {
return;
}
const { top, height } = rootRef.value.getBoundingClientRect();
const y = e2.clientY - top;
let containerPadding = 0;
const paddingStr = containerPaddingPx.value;
if (paddingStr.includes("%")) {
containerPadding = parseFloat(paddingStr) / 100 * height;
} else {
containerPadding = parseFloat(paddingStr);
}
const currentScrollTop = scrollViewRef.value.scrollTop;
const actualY = y + currentScrollTop - containerPadding;
const targetIndex = Math.floor(actualY / itemHeight.value);
const itemCount = (_b = (_a = contentRef.value) == null ? void 0 : _a.children) == null ? void 0 : _b.length;
const isIndexValid = targetIndex >= 0 && (itemCount ? targetIndex < itemCount : true);
if (isIndexValid && targetIndex !== selectedIndex.value) {
setScrollTop(targetIndex);
ctx == null ? void 0 : ctx.onColumnIndexChange(columnIndex, targetIndex);
}
}
const n0 = t1$d();
const n7 = child(n0);
const n4 = next(n7);
const n5 = next(n4);
const n6 = next(n5);
initUniElement(n0, _uniPickerViewColumnElement);
setInsertionState(n0, n7);
const n3 = withComponentId("8e57cce2", () => createComponent$1(__syscom_1, {
class: "picker-view-scroll",
direction: "vertical",
"show-scrollbar": false,
"scroll-with-animation": () => unref(scrollWithAnimation),
onScrollend: () => onScrollEnd,
onScroll: () => onScroll
}, () => {
const n2 = t0$k();
renderEffect(() => {
const _containerPaddingPx = unref(containerPaddingPx);
setStyle(n2, { "padding-top": _containerPaddingPx, "padding-bottom": _containerPaddingPx });
});
setInsertionState(n2);
createSlot();
setStaticTemplateRef(n2, contentRef, null, "contentRef");
return n2;
}));
setStaticTemplateRef(n3, scrollViewRef, null, "scrollViewRef");
on$1(n0, "keydown", handleKeydown);
on$1(n0, "mousedown", clearKeyboardTarget);
on$1(n0, "touchstart", clearKeyboardTarget);
on$1(n0, "wheel", clearKeyboardTarget);
on$1(n0, "click", handleClick);
setStaticTemplateRef(n0, rootRef, null, "rootRef");
renderEffect(() => {
const _maskClass = unref(maskClass);
setClass(n4, ["uni-picker-view-mask uni-picker-view-mask-top", _maskClass]);
setStyle(n4, unref(maskTopInlineStyle));
setClass(n5, ["uni-picker-view-indicator", unref(indicatorClass)]);
setStyle(n5, unref(indicatorInlineStyle));
setClass(n6, ["uni-picker-view-mask uni-picker-view-mask-bottom", _maskClass]);
setStyle(n6, unref(maskBottomInlineStyle));
});
return n0;
}
});
const _UniProgressElement = class _UniProgressElement extends UniViewElement {
};
_UniProgressElement.__uniElement = {};
let UniProgressElement = _UniProgressElement;
const t0$j = template("<span uni-text class=uni-progress-value> ");
const t1$c = template("<div uni-progress uni-view class=uni-progress><div uni-view class=uni-progress-background><div uni-view class=uni-progress-fill></div></div>", 1);
const _uniProgressElement = { value: "PROGRESS" };
const _sfc_main$j = /* @__PURE__ */ defineVaporComponent({
...{
name: "progress",
// @ts-ignore
rootElement: {
class: /* @__PURE__ */ initUniElementType(UniProgressElement, "progress")
}
},
__name: "progress",
props: {
duration: { default: 30, type: Number },
percent: { default: 0, type: Number },
active: { type: Boolean, default: false },
activeMode: { default: "backwards", type: String },
backgroundColor: { default: "#ebebeb", type: String },
strokeWidth: { default: 3, type: Number },
activeColor: { default: "#007aff", type: String },
showInfo: { type: Boolean, default: false },
borderRadius: { default: 0, type: Number },
fontSize: { default: 12, type: Number }
},
emits: ["activeend"],
setup(__props, { emit: __emit }) {
const props2 = __props;
class UniCustomEvent3 {
constructor(type, detail) {
this.detail = detail;
}
}
class UniProgressActiveendEvent extends UniCustomEvent3 {
constructor(type, curPercent) {
super(type, { curPercent });
}
}
const emit2 = __emit;
const fillRef = ref(null);
let _timerId = 0;
let _rafId = 0;
let _lastPercent = 0;
let _startPercent = 0;
let _targetPercent = 0;
let _startTime = 0;
const percentText = ref("0%");
const backgroundStyle = computed(() => {
return {
"background-color": props2.backgroundColor,
"height": props2.strokeWidth + "px",
"border-radius": props2.borderRadius + "px"
};
});
const foregroundStyle = computed(() => {
return {
"background-color": props2.activeColor
};
});
const fontStyle = computed(() => {
return {
"font-size": props2.fontSize + "px"
};
});
watch(() => props2.percent, () => {
_animate();
});
onMounted(() => {
_animate();
});
function renderVisuals(percent) {
percentText.value = Math.round(percent) + "%";
let scale = percent / 100;
if (scale > 0 && scale < 1e-3) {
scale = 1e-3;
}
const fillEl = fillRef.value;
if (fillEl != null) {
fillEl.style.setProperty("transform", `scaleX(${scale})`);
}
}
function _animate() {
const final_percent = Math.max(0, Math.min(100, props2.percent));
if (!props2.active) {
renderVisuals(final_percent);
return;
}
clearTimer();
_startPercent = props2.activeMode == "forwards" ? _lastPercent : 0;
_targetPercent = final_percent;
_startTime = Date.now();
renderVisuals(_startPercent);
function animateFrame() {
const currentTime = Date.now();
const elapsed = currentTime - _startTime;
const totalDuration = props2.duration * Math.abs(_targetPercent - _startPercent);
if (elapsed >= totalDuration) {
renderVisuals(_targetPercent);
emit2("activeend", new UniProgressActiveendEvent("activeend", _targetPercent));
_lastPercent = _targetPercent;
_rafId = 0;
} else {
const progress = elapsed / totalDuration;
const currentPercent = _startPercent + (_targetPercent - _startPercent) * progress;
renderVisuals(currentPercent);
_rafId = requestAnimationFrame(animateFrame);
}
}
_rafId = requestAnimationFrame(animateFrame);
}
function clearTimer() {
clearInterval(_timerId);
if (_rafId != 0) {
cancelAnimationFrame(_rafId);
_rafId = 0;
}
}
onUnmounted(() => {
clearTimer();
});
const n0 = t1$c();
const n2 = child(n0);
const n1 = child(n2);
initUniElement(n0, _uniProgressElement);
setStaticTemplateRef(n1, fillRef, null, "fillRef");
renderEffect(() => {
setStyle(n2, unref(backgroundStyle));
setStyle(n1, unref(foregroundStyle));
});
setInsertionState(n0, 1);
createIf(() => __props.showInfo, () => {
const n5 = t0$j();
const x5 = txt(n5);
renderEffect(() => {
setStyle(n5, unref(fontStyle));
setText(x5, normalizeUniText(toDisplayString(unref(percentText))));
});
return n5;
});
return n0;
}
});
const _UniRadioElement = class _UniRadioElement extends UniViewElement {
constructor() {
super(...arguments);
this.tagName = "RADIO";
this.nodeName = "RADIO";
this._checked = false;
}
get checked() {
var _a;
return ((_a = this.vm) == null ? void 0 : _a.getRadioChecked()) ?? this._checked;
}
set checked(val) {
var _a;
this._checked = val;
(_a = this.vm) == null ? void 0 : _a.setRadioChecked(val);
}
};
_UniRadioElement.__uniElement = { vm: true, init() {
Object.defineProperty(this, "_checked", { value: false, writable: true, enumerable: true, configurable: true });
} };
let UniRadioElement = _UniRadioElement;
const t0$i = template('<svg class=uni-radio-svg viewBox="0 0 32 32"><path fill=currentColor>', 0, 1);
const t1$b = template("<div uni-radio uni-view role=radio>", 1);
const t2$7 = template("<span uni-text>");
const t3$4 = template("<div uni-radio uni-view class=uni-radio role=radio><div uni-view></div>", 1);
const _uniRadioElement = { value: "RADIO" };
const iconPath = "M1.952 18.080q-0.32-0.352-0.416-0.88t0.128-0.976l0.16-0.352q0.224-0.416 0.64-0.528t0.8 0.176l6.496 4.704q0.384 0.288 0.912 0.272t0.88-0.336l17.312-14.272q0.352-0.288 0.848-0.256t0.848 0.352l-0.416-0.416q0.32 0.352 0.32 0.816t-0.32 0.816l-18.656 18.912q-0.32 0.352-0.8 0.352t-0.8-0.32l-7.936-8.064z";
const _sfc_main$i = /* @__PURE__ */ defineVaporComponent({
...{
name: "radio",
// @ts-ignore
rootElement: {
class: /* @__PURE__ */ initUniElementType(UniRadioElement, "radio")
},
externalClasses: ["icon-class", "radio-class", "radio-active-class"]
},
__name: "radio",
props: {
color: { default: "", type: String },
disabled: { type: Boolean, default: false },
checked: { type: Boolean, default: false },
value: { default: "", type: String },
iconClass: { default: "", type: null },
radioClass: { default: "", type: null },
radioActiveClass: { default: "", type: null }
},
setup(__props, { expose: __expose }) {
var _a, _b;
const props2 = __props;
const { handleKeydown, handleKeyup, handleBlur } = createSpaceKeyHandlers(() => props2.disabled);
const attrs2 = useAttrs$1();
const id2 = attrs2.id;
const slots = useSlots();
const isStringSlot = ((_a = slots["default"]) == null ? void 0 : _a["returnType"]) == "string";
const hasDefaultSlot = slots["default"] != null;
const proxy = (_b = getCurrentInstance()) == null ? void 0 : _b.proxy;
const isChecked = ref(false);
const activeStyle = computed(() => {
if (isChecked.value && !props2.disabled && props2.color) {
return {
"background-color": props2.color,
"border-color": props2.color
};
}
return {};
});
const groupCtx = inject(RADIO_GROUP_KEY, null);
const labelCtx = inject(LABEL_KEY, null);
let unregisterLabelTarget = null;
const setChecked = (checked, syncGroup) => {
if (syncGroup && groupCtx != null) {
const value = toStringOrEmpty(props2.value);
if (checked) {
groupCtx.setSelectedValue(value);
} else if (groupCtx.selectedValue.value == value) {
groupCtx.setSelectedValue(null);
}
return;
}
isChecked.value = checked;
};
if (groupCtx != null) {
watch(() => groupCtx.selectedValue.value, (val) => {
setChecked(val == toStringOrEmpty(props2.value), false);
}, { immediate: true });
watch(() => props2.checked, (value) => {
setChecked(value, true);
});
} else {
watch(() => props2.checked, (value) => {
setChecked(value, false);
}, { immediate: true });
}
const handleTap = () => {
if (props2.disabled || isChecked.value) {
return;
}
if (groupCtx != null) {
groupCtx.change(toStringOrEmpty(props2.value));
} else {
setChecked(true, false);
}
};
onMounted(() => {
if (groupCtx != null && props2.checked) {
if (groupCtx.selectedValue.value == null || groupCtx.selectedValue.value.length == 0) {
groupCtx.setSelectedValue(toStringOrEmpty(props2.value));
}
}
const target = {
id: id2 || toStringOrEmpty(props2.value),
activate: (event) => {
const element = proxy == null ? void 0 : proxy.$el;
if (element != null) {
dispatchLabelClick(element, event);
}
},
getDisabled: () => props2.disabled
};
if (labelCtx != null) {
labelCtx.register(target);
}
if (id2 != null && id2.length > 0) {
unregisterLabelTarget = registerLabelTarget(id2, target);
}
});
onUnmounted(() => {
if (labelCtx != null) {
labelCtx.unregister(id2 || toStringOrEmpty(props2.value));
}
unregisterLabelTarget == null ? void 0 : unregisterLabelTarget();
unregisterLabelTarget = null;
});
__expose({
getRadioChecked: () => {
return isChecked.value;
},
setRadioChecked: (checked) => {
setChecked(checked, true);
}
});
const n0 = createIf(
() => !hasDefaultSlot,
() => {
const n2 = t1$b();
initUniElement(n2, _uniRadioElement);
renderEffect(() => {
const _disabled = __props.disabled;
const _isChecked = unref(isChecked);
setClass(n2, ["uni-radio-view uni-radio-icon", unref(classes)(
[_disabled, "uni-radio-disabled"],
[!_disabled && _isChecked, "uni-radio-active"],
[!_disabled && _isChecked, __props.radioActiveClass],
[!_disabled && !_isChecked, __props.radioClass],
[!_disabled, __props.iconClass]
)]);
setStyle(n2, unref(activeStyle));
setProp(n2, "tabindex", _disabled ? -1 : 0);
setAttr(n2, "aria-checked", _isChecked);
setAttr(n2, "aria-disabled", _disabled);
});
setInsertionState(n2);
createIf(() => unref(isChecked), () => {
const n6 = t0$i();
const n5 = child(n6);
setAttr(n5, "d", iconPath, true);
return n6;
});
on$1(n2, "keydown", (e2) => unref(handleKeydown)(e2));
on$1(n2, "keyup", (e2) => unref(handleKeyup)(e2));
on$1(n2, "blur", (e2) => unref(handleBlur)(e2));
on$1(n2, "click", withModifiers(handleTap, ["stop"]));
return n2;
},
() => {
const n8 = t3$4();
const n13 = child(n8);
initUniElement(n8, _uniRadioElement);
renderEffect(() => {
const _disabled = __props.disabled;
const _isChecked = unref(isChecked);
setProp(n8, "tabindex", _disabled ? -1 : 0);
setAttr(n8, "aria-checked", _isChecked);
setAttr(n8, "aria-disabled", _disabled);
setClass(n13, ["uni-radio-view uni-radio-icon", unref(classes)(
[_disabled, "uni-radio-disabled"],
[!_disabled && _isChecked, "uni-radio-active"],
[!_disabled && _isChecked, __props.radioActiveClass],
[!_disabled && !_isChecked, __props.radioClass],
[!_disabled, __props.iconClass]
)]);
setStyle(n13, unref(activeStyle));
});
setInsertionState(n13);
createIf(() => unref(isChecked), () => {
const n12 = t0$i();
const n11 = child(n12);
setAttr(n11, "d", iconPath, true);
return n12;
});
setInsertionState(n8, 1);
createIf(
() => isStringSlot,
() => {
const n17 = t2$7();
setInsertionState(n17);
createSlot(
"default",
null,
null,
256
/* TEXT_MODE */
);
return n17;
},
() => {
const n19 = createSlot();
return n19;
},
1029
/* TRUE_SINGLE_ROOT, FALSE_SINGLE_ROOT, KEYED_INDEX_3 */
);
on$1(n8, "keydown", (e2) => unref(handleKeydown)(e2));
on$1(n8, "keyup", (e2) => unref(handleKeyup)(e2));
on$1(n8, "blur", (e2) => unref(handleBlur)(e2));
on$1(n8, "click", withModifiers(handleTap, ["stop"]));
return n8;
},
517
/* TRUE_SINGLE_ROOT, FALSE_SINGLE_ROOT, KEYED_INDEX_1 */
);
return n0;
}
});
const _UniRadioGroupElement = class _UniRadioGroupElement extends UniViewElement {
};
_UniRadioGroupElement.__uniElement = {};
let UniRadioGroupElement = _UniRadioGroupElement;
const t0$h = template("<div uni-radio-group uni-view role=radiogroup>", 1);
const _uniRadioGroupElement = { value: "RADIO-GROUP" };
const _sfc_main$h = /* @__PURE__ */ defineVaporComponent({
...{
name: "radio-group",
// @ts-ignore
rootElement: {
class: /* @__PURE__ */ initUniElementType(UniRadioGroupElement, "radio-group")
}
},
__name: "radio-group",
props: {
name: { default: "", type: String }
},
emits: ["change"],
setup(__props, { emit: __emit }) {
class UniCustomEvent3 {
constructor(type, detail) {
this.detail = detail;
}
}
class UniRadioGroupChangeEvent extends UniCustomEvent3 {
constructor(value) {
super("change", { value });
}
}
const emit2 = __emit;
const props2 = __props;
const selectedValue = ref(null);
const initialValue = ref(null);
function setSelectedValue(val) {
if (selectedValue.value == val) {
return;
}
selectedValue.value = val;
}
function change(val) {
setSelectedValue(val);
emit2("change", new UniRadioGroupChangeEvent(val));
}
function handleKeydown(event) {
const direction2 = event.key === "ArrowUp" || event.key === "ArrowLeft" ? -1 : event.key === "ArrowDown" || event.key === "ArrowRight" ? 1 : 0;
if (direction2 === 0 || event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey) {
return;
}
const target = event.target;
const group = event.currentTarget;
if (!(target instanceof HTMLElement) || !(group instanceof HTMLElement) || !target.matches('[role="radio"]') || target.closest('[role="radiogroup"]') !== group) {
return;
}
const radios = Array.from(group.querySelectorAll('[role="radio"]')).filter(
(radio) => radio.getAttribute("aria-disabled") !== "true" && radio.closest('[role="radiogroup"]') === group
);
const index2 = radios.indexOf(target);
if (index2 < 0) {
return;
}
event.preventDefault();
const next2 = radios[(index2 + direction2 + radios.length) % radios.length];
if (next2 !== target) {
next2.focus();
next2.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
}
}
const ctx = {
selectedValue,
change,
setSelectedValue
};
provide(RADIO_GROUP_KEY, ctx);
const formCtx = inject(FORM_KEY, null);
onMounted(() => {
initialValue.value = selectedValue.value;
if (formCtx && props2.name) {
formCtx.registerField({
name: props2.name,
getValue: () => toStringOrEmpty(selectedValue.value),
reset: () => {
selectedValue.value = initialValue.value;
emit2("change", new UniRadioGroupChangeEvent(toStringOrEmpty(initialValue.value)));
}
});
}
});
onUnmounted(() => {
if (formCtx && props2.name) {
formCtx.unregisterField(props2.name);
}
});
const n0 = t0$h();
initUniElement(n0, _uniRadioGroupElement);
setInsertionState(n0);
createSlot();
on$1(n0, "keydown", handleKeydown);
return n0;
}
});
let UniCustomEvent$1 = class UniCustomEvent {
constructor(type, detail) {
this.detail = detail;
}
};
class UniSliderChangeEvent extends UniCustomEvent$1 {
constructor(value) {
super("change", { value });
}
}
const _UniSliderElement = class _UniSliderElement extends UniViewElement {
constructor() {
super(...arguments);
this.tagName = "SLIDER";
this.nodeName = "SLIDER";
}
get value() {
var _a;
return (_a = this.vm) == null ? void 0 : _a.getCurrentValue();
}
set value(val) {
var _a;
if (this.value === val) {
return;
}
(_a = this.vm) == null ? void 0 : _a.renderVisuals(val);
}
};
_UniSliderElement.__uniElement = { vm: true };
let UniSliderElement = _UniSliderElement;
const t0$g = template('<span uni-text style="width: 35px;color: #888;font-size: 14px;align-self: center;margin-left: 5px;white-space: nowrap;"> ');
const t1$a = template("<div uni-slider uni-view class=container><div uni-view class=slider-track><div uni-view><div uni-view></div></div><div uni-view><div uni-view role=slider aria-orientation=horizontal></div></div></div>", 1);
const _uniSliderElement = { value: "SLIDER" };
const TOUCH_THRESHOLD = 4;
const _sfc_main$g = /* @__PURE__ */ defineVaporComponent({
...{
name: "slider",
externalClasses: ["track-class", "track-active-class", "thumb-class"],
rootElement: {
name: "uni-slider-element",
class: /* @__PURE__ */ initUniElementType(UniSliderElement, "slider")
}
},
__name: "slider",
props: {
name: { default: "", type: String },
min: { default: 0, type: Number },
max: { default: 100, type: Number },
step: { default: 1, type: Number },
value: { default: 0, type: Number },
disabled: { type: Boolean, default: false },
showValue: { type: Boolean, default: false },
activeColor: { default: "", type: null },
activeBackgroundColor: { default: "", type: null },
backgroundColor: { default: "", type: null },
blockSize: { default: null, type: [Number, null] },
blockColor: { default: "", type: null },
foreColor: { default: "", type: null },
trackClass: { default: "", type: null },
trackActiveClass: { default: "", type: null },
thumbClass: { default: "", type: null }
},
emits: ["change", "changing"],
setup(__props, { expose: __expose, emit: __emit }) {
const emit2 = __emit;
const attrs2 = useAttrs$1();
const id2 = attrs2.id ?? "";
let unregisterLabelTarget = null;
const props2 = __props;
const containerRef = ref(null);
const backgroundRef = ref(null);
const fillRef = ref(null);
const handleRef = ref(null);
const thumbRef = ref(null);
function setColor(element, color) {
if (element == null)
return;
if (color.length > 0) {
element.style.setProperty("background-color", color);
} else {
element.style.removeProperty("background-color");
}
}
watchEffect(() => {
setColor(backgroundRef.value, props2.backgroundColor);
setColor(fillRef.value, props2.activeBackgroundColor.length > 0 ? props2.activeBackgroundColor : props2.activeColor);
setColor(thumbRef.value, props2.foreColor.length > 0 ? props2.foreColor : props2.blockColor);
const blockSize = props2.blockSize;
const thumbEl = thumbRef.value;
if (thumbEl != null) {
if (blockSize != null && !isNaN(blockSize)) {
const size = Math.min(Math.max(blockSize, 12), 28);
thumbEl.style.setProperty("width", size + "px");
thumbEl.style.setProperty("height", size + "px");
thumbEl.style.setProperty("border-radius", size / 2 + "px");
} else {
thumbEl.style.removeProperty("width");
thumbEl.style.removeProperty("height");
thumbEl.style.removeProperty("border-radius");
}
}
});
const initialValue = props2.value;
const currentValue = ref(props2.value);
const isDragging = ref(false);
let trackWidth = 0;
let trackLeft = 0;
let rafId = 0;
let ticking = false;
let cachedDecimalPlaces = -1;
let cachedStep = props2.step;
let lastValue = 0;
const thumbTranslateX = ref(0);
const trackActiveScaleX = ref(0);
const effectiveMax = computed(() => {
const min = Number.isFinite(props2.min) ? props2.min : 0;
const max = Number.isFinite(props2.max) ? props2.max : min;
const step = props2.step;
const range = max - min;
if (!Number.isFinite(step) || step <= 0 || range <= 0)
return min;
return min + Math.floor(range / step) * step;
});
let _activeStatus = 0;
let touchStartX = 0;
let touchStartY = 0;
let activePointerId = -1;
let pointerTarget = null;
let pointerClientX = 0;
let pointerStartFocus = null;
function releasePointerCapture() {
const target = pointerTarget;
const pointerId = activePointerId;
activePointerId = -1;
pointerTarget = null;
pointerStartFocus = null;
if (target != null && target.hasPointerCapture(pointerId)) {
target.releasePointerCapture(pointerId);
}
}
function resetInteractionState() {
if (rafId != 0) {
cancelAnimationFrame(rafId);
rafId = 0;
}
ticking = false;
isDragging.value = false;
lastValue = currentValue.value;
releasePointerCapture();
}
function lerp(start, end, t12) {
const clampedT = Math.max(0, Math.min(1, t12));
return start * (1 - clampedT) + end * clampedT;
}
function getDecimalPlaces(num) {
if (num == 0)
return 0;
if (cachedStep !== num || cachedDecimalPlaces == -1) {
const str = num.toString();
const decimalIndex = str.indexOf(".");
if (decimalIndex == -1)
cachedDecimalPlaces = 0;
cachedDecimalPlaces = str.length - decimalIndex - 1;
}
return cachedDecimalPlaces;
}
function applyStepPrecision(value) {
let result = value;
if (props2.step > 0) {
result = Math.round(result / props2.step) * props2.step;
const decimalPlaces = getDecimalPlaces(props2.step);
if (decimalPlaces > 0) {
result = parseFloat(result.toFixed(decimalPlaces));
}
}
return result;
}
function applyVisualPosition(percentage, fillScale) {
thumbTranslateX.value = percentage * 100;
trackActiveScaleX.value = fillScale;
}
function renderVisuals(newValue) {
const min = Number.isFinite(props2.min) ? props2.min : 0;
const max = Number.isFinite(effectiveMax.value) ? effectiveMax.value : min;
const clampedValue = Number.isFinite(newValue) ? Math.max(min, Math.min(newValue, max)) : min;
currentValue.value = clampedValue;
const range = max - min;
const percentage = range > 0 ? (clampedValue - min) / range : 0;
const fillScale = percentage - 1e-3;
applyVisualPosition(percentage, fillScale);
}
function calculateValue(clientX) {
if (trackWidth <= 0) {
return currentValue.value;
}
const containerWidth = trackWidth;
const containerLeft = trackLeft;
const min = Number.isFinite(props2.min) ? props2.min : 0;
const max = Number.isFinite(props2.max) ? props2.max : min;
if (max <= min)
return min;
let currentX = clientX - containerLeft;
currentX = Math.max(0, Math.min(currentX, containerWidth));
const ratio = currentX / containerWidth;
let newValue = lerp(min, max, ratio);
newValue = applyStepPrecision(newValue);
newValue = Math.max(min, Math.min(newValue, effectiveMax.value));
return newValue;
}
function focusThumb() {
if (props2.disabled)
return;
const element = thumbRef.value;
if (element != null && element.ownerDocument.activeElement !== element)
element.focus({ preventScroll: true });
}
function handleThumbClick(e2) {
if (e2.detail == 0)
focusThumb();
}
function finishPointerInteraction(clientX) {
if (props2.disabled) {
resetInteractionState();
return;
}
if (_activeStatus != -1) {
const element = thumbRef.value;
if (element != null && element.ownerDocument.activeElement === pointerStartFocus)
focusThumb();
renderVisuals(calculateValue(clientX));
}
const value = currentValue.value;
const changed = lastValue !== value;
resetInteractionState();
if (changed)
emit2("change", new UniSliderChangeEvent(value));
}
function handlePointerMove(e2) {
if (e2.pointerId != activePointerId || props2.disabled == true) {
return;
}
if (e2.pointerType == "mouse" && (e2.buttons & 1) == 0) {
finishPointerInteraction(e2.clientX);
return;
}
if (_activeStatus == 0) {
const deltaX = Math.abs(e2.clientX - touchStartX);
const deltaY = Math.abs(e2.clientY - touchStartY);
if (deltaX <= TOUCH_THRESHOLD && deltaY <= TOUCH_THRESHOLD)
return;
_activeStatus = deltaX > deltaY ? 1 : -1;
}
if (_activeStatus != 1)
return;
if (e2.cancelable) {
e2.preventDefault();
}
e2.stopPropagation();
pointerClientX = e2.clientX;
if (ticking == false) {
ticking = true;
const pointerId = activePointerId;
const frameId = requestAnimationFrame(() => {
if (rafId != frameId)
return;
rafId = 0;
ticking = false;
if (activePointerId != pointerId || props2.disabled)
return;
const newValue = calculateValue(pointerClientX);
if (newValue === currentValue.value)
return;
renderVisuals(newValue);
emit2("changing", new UniSliderChangeEvent(currentValue.value));
});
rafId = frameId;
}
}
function handlePointerDown(e2) {
if (props2.disabled == true || activePointerId != -1 || !e2.isPrimary || e2.button != 0) {
return;
}
lastValue = currentValue.value;
isDragging.value = true;
touchStartX = e2.clientX;
touchStartY = e2.clientY;
_activeStatus = e2.pointerType == "mouse" ? 1 : 0;
activePointerId = e2.pointerId;
const thumbEl = thumbRef.value;
pointerStartFocus = (thumbEl == null ? void 0 : thumbEl.ownerDocument.activeElement) ?? null;
pointerTarget = e2.currentTarget;
pointerTarget.setPointerCapture(e2.pointerId);
const containerEl = containerRef.value;
if (containerEl != null) {
const rect = containerEl.getBoundingClientRect();
trackLeft = rect.left;
trackWidth = rect.width;
}
if (e2.pointerType == "mouse") {
e2.preventDefault();
focusThumb();
renderVisuals(calculateValue(e2.clientX));
}
}
function handlePointerUp(e2) {
if (e2.pointerId != activePointerId || e2.button != 0) {
return;
}
finishPointerInteraction(e2.clientX);
}
function handlePointerCancel(e2) {
if (e2.pointerId == activePointerId)
resetInteractionState();
}
const sliderKeys = ["ArrowLeft", "ArrowDown", "ArrowRight", "ArrowUp", "Home", "End", "PageUp", "PageDown"];
const pressedSliderKeys = /* @__PURE__ */ new Set();
function handleThumbBlur() {
pressedSliderKeys.clear();
resetInteractionState();
}
function getKeyboardDecimalPlaces(value) {
const parts = value.toString().split("e");
const fraction = parts[0].split(".")[1] ?? "";
return Math.max(0, fraction.length - Number(parts[1] ?? "0"));
}
function ownsKeyboardEvent(e2) {
const element = thumbRef.value;
return !props2.disabled && element != null && e2.target === element && e2.currentTarget === element && element.ownerDocument.activeElement === element && !e2.defaultPrevented && !e2.isComposing && !e2.altKey && !e2.ctrlKey && !e2.metaKey && sliderKeys.includes(e2.key);
}
function handleKeyUp(e2) {
const handled = pressedSliderKeys.delete(e2.key);
const element = thumbRef.value;
if (handled && element != null && e2.target === element && e2.currentTarget === element)
e2.stopPropagation();
}
function handleKeyDown(e2) {
if (!ownsKeyboardEvent(e2))
return;
pressedSliderKeys.add(e2.key);
e2.preventDefault();
e2.stopPropagation();
if (isDragging.value || !Number.isFinite(props2.step) || props2.step <= 0)
return;
const min = Number.isFinite(props2.min) ? props2.min : 0;
let newValue = currentValue.value;
if (e2.key == "ArrowLeft" || e2.key == "ArrowDown") {
newValue -= props2.step;
} else if (e2.key == "ArrowRight" || e2.key == "ArrowUp") {
newValue += props2.step;
} else if (e2.key == "PageUp") {
newValue += props2.step * 10;
} else if (e2.key == "PageDown") {
newValue -= props2.step * 10;
} else if (e2.key == "Home") {
newValue = min;
} else if (e2.key == "End") {
newValue = effectiveMax.value;
}
newValue = min + Math.round((newValue - min) / props2.step) * props2.step;
const precision = Math.min(100, Math.max(getKeyboardDecimalPlaces(min), getKeyboardDecimalPlaces(props2.step)));
newValue = parseFloat(newValue.toFixed(precision));
newValue = Math.max(min, Math.min(newValue, effectiveMax.value));
if (newValue === currentValue.value)
return;
renderVisuals(newValue);
emit2("change", new UniSliderChangeEvent(currentValue.value));
}
function handleResize() {
trackWidth = 0;
trackLeft = 0;
renderVisuals(currentValue.value);
}
renderVisuals(currentValue.value);
onMounted(() => {
nextTick(() => {
watch(() => {
return props2.value;
}, (newValue) => {
if (isDragging.value)
return;
renderVisuals(newValue);
});
watch([
() => props2.min,
() => props2.max
], () => {
renderVisuals(currentValue.value);
});
watch(() => {
return props2.step;
}, () => {
renderVisuals(currentValue.value);
});
watch(() => props2.showValue, () => {
nextTick(() => setTimeout(handleResize, 10));
});
watch(() => props2.disabled, (disabled) => {
if (disabled) {
resetInteractionState();
const element = thumbRef.value;
if (element != null && element.ownerDocument.activeElement === element)
element.blur();
}
});
});
const formCtx = inject(FORM_KEY, null);
if (formCtx != null && props2.name.length > 0) {
formCtx.registerField({
name: props2.name,
getValue: () => currentValue.value,
reset: () => {
currentValue.value = initialValue;
renderVisuals(initialValue);
}
});
}
const labelCtx = inject(LABEL_KEY, null);
const target = {
id: id2.length > 0 ? id2 : props2.name,
activate: (event) => {
const element = thumbRef.value;
if (element != null)
dispatchLabelClick(element, event);
},
getDisabled: () => props2.disabled
};
if (labelCtx != null) {
labelCtx.register(target);
}
if (id2.length > 0) {
unregisterLabelTarget = registerLabelTarget(id2, target);
}
window.addEventListener("resize", handleResize);
});
onUnmounted(() => {
const formCtx = inject(FORM_KEY, null);
if (formCtx != null && props2.name.length > 0) {
formCtx.unregisterField(props2.name);
}
const labelCtx = inject(LABEL_KEY, null);
if (labelCtx != null) {
if (id2.length > 0) {
labelCtx.unregister(id2);
} else if (props2.name.length > 0) {
labelCtx.unregister(props2.name);
}
}
unregisterLabelTarget == null ? void 0 : unregisterLabelTarget();
unregisterLabelTarget = null;
resetInteractionState();
});
onBeforeUnmount(() => {
resetInteractionState();
window.removeEventListener("resize", handleResize);
});
__expose({
renderVisuals,
getCurrentValue: () => currentValue.value
});
const n0 = t1$a();
const n5 = child(n0);
const n2 = child(n5);
const n1 = child(n2);
const n4 = next(n2);
const n3 = child(n4);
initUniElement(n0, _uniSliderElement);
setStaticTemplateRef(n1, fillRef, null, "fillRef");
setStaticTemplateRef(n2, backgroundRef, null, "backgroundRef");
on$1(n3, "keydown", handleKeyDown);
on$1(n3, "keyup", handleKeyUp);
on$1(n3, "blur", handleThumbBlur);
on$1(n3, "click", handleThumbClick);
setStaticTemplateRef(n3, thumbRef, null, "thumbRef");
setStaticTemplateRef(n4, handleRef, null, "handleRef");
on$1(n5, "pointerdown", handlePointerDown);
on$1(n5, "pointermove", handlePointerMove);
on$1(n5, "pointerup", handlePointerUp);
on$1(n5, "pointercancel", handlePointerCancel);
on$1(n5, "lostpointercapture", handlePointerCancel);
setStaticTemplateRef(n5, containerRef, null, "containerRef");
renderEffect(() => {
const _props = props2;
const _thumbTranslateX = unref(thumbTranslateX);
const _props_disabled = _props.disabled;
setClass(n2, ["slider-track-bg", _props.trackClass]);
setClass(n1, ["slider-track-fill", _props.trackActiveClass]);
setStyle(n1, { transform: `scaleX(${unref(trackActiveScaleX)})` });
setStyle(n4, ["overflow: visible; align-self: flex-start;z-index: 2;", { width: "100%", transform: `translateX(${_thumbTranslateX}%)` }]);
setProp(n3, "tabindex", _props_disabled ? -1 : 0);
setAttr(n3, "aria-disabled", _props_disabled);
setAttr(n3, "aria-valuenow", unref(currentValue));
setAttr(n3, "aria-valuemin", Number.isFinite(_props.min) ? _props.min : 0);
setAttr(n3, "aria-valuemax", unref(effectiveMax));
setClass(n3, ["slider-handle", _props.thumbClass]);
setStyle(n3, { transform: `translateX(-${_thumbTranslateX}%)` });
});
setInsertionState(n0, 1);
createIf(() => props2.showValue, () => {
const n8 = t0$g();
const x8 = txt(n8);
renderEffect(() => setText(x8, normalizeUniText(toDisplayString(unref(currentValue)))));
return n8;
});
return n0;
}
});
const t0$f = template('<div uni-sticky-header uni-view class=uni-sticky-header style="position: sticky; top: 0; width: 100%; z-index: 1">', 1);
const _uniStickyHeaderElement = { value: "STICKY-HEADER" };
const _sfc_main$f = /* @__PURE__ */ defineVaporComponent({
...{
name: "sticky-header",
rootElement: {
class: /* @__PURE__ */ initUniElementType(UniStickyHeaderElement, "sticky-header")
}
},
__name: "sticky-header",
setup(__props) {
const element = ref(null);
const { section, updateHeaderSize } = inject("__uni_recycle_section");
const observer = new UniResizeObserver((entries2) => {
if (element.value && element.value.isConnected) {
updateHeaderSize(entries2[entries2.length - 1].borderBoxSize[0].blockSize);
}
});
onMounted(() => {
section.headerElement = element.value;
updateHeaderSize(element.value.getBoundingClientRect().height);
observer.observe(element.value);
});
onBeforeUnmount(() => {
observer.disconnect();
section.headerElement = null;
updateHeaderSize(0);
});
const n0 = t0$f();
initUniElement(n0, _uniStickyHeaderElement);
setInsertionState(n0);
createSlot();
setStaticTemplateRef(n0, element, null, "element");
return n0;
}
});
const t0$e = template('<div uni-sticky-section uni-view class=uni-sticky-section style="position: relative; overflow: visible"><!><div uni-view style="width: 1px; flex-shrink: 0;">', 1);
const _uniStickySectionElement = { value: "STICKY-SECTION" };
const _sfc_main$e = /* @__PURE__ */ defineVaporComponent({
...{
name: "sticky-section",
rootElement: {
class: /* @__PURE__ */ initUniElementType(UniStickySectionElement, "sticky-section")
}
},
__name: "sticky-section",
props: {
preload: { type: Boolean, default: false }
},
setup(__props, { expose: __expose }) {
const props2 = __props;
const instance2 = getCurrentInstance();
const sectionId = instance2.uid;
const listView = inject("__uni_recycle_list");
const element = ref(null);
const placeholderElement = ref(null);
const renderRange = ref([0, 0]);
const store = new RecycleListItemDataStore();
const idKeyMap = /* @__PURE__ */ new Map();
let keys = [];
let listIds = [];
let hasSyncedDefaultItemSize = false;
const section = {
element: null,
headerElement: null,
headerSize: 0,
placeholderSize: 0,
offsetTop: 0,
resolveKeyById: (id2) => idKeyMap.get(id2),
getItemOffset,
onScrollContextUpdate,
applyDefaultItemSize
};
listView.sectionMap.set(sectionId, section);
provide("__uni_recycle_view_instance", instance2);
provide("__uni_recycle_section_id", sectionId);
provide("__uni_recycle_section", { section, updateHeaderSize });
provide("__uni_recycle_container", {
store,
updateItemSize,
getItemOffset
});
function updateIdKeyMap() {
if (listIds.length !== keys.length)
return;
idKeyMap.clear();
listIds.forEach((id2, index2) => {
if (id2 && keys[index2])
idKeyMap.set(id2, keys[index2]);
});
}
function updateList(newList) {
keys = newList;
store.updateKeyList(newList);
updateIdKeyMap();
updatePlaceholderSize();
}
function updateListIds(ids) {
listIds = ids;
updateIdKeyMap();
listView.queueLayout();
}
function updateRenderInfo(start, length) {
store.updateItemOffset(section.headerSize);
if (renderRange.value[0] !== start || renderRange.value[1] !== length) {
renderRange.value = [start, length];
}
}
function updatePlaceholderSize() {
section.placeholderSize = section.headerSize + store.contentSize;
if (placeholderElement.value)
placeholderElement.value.style.height = `${store.contentSize}px`;
listView.queueLayout();
}
function updateHeaderSize(height) {
if (section.headerSize === height)
return;
section.headerSize = height;
updatePlaceholderSize();
}
function applyDefaultItemSize(height) {
hasSyncedDefaultItemSize = true;
store.defaultItemSize = height;
store.rebuildItemOffsetsFrom(0);
updatePlaceholderSize();
}
function updateItemSize(key, height) {
const item = store.keyItemMap.get(key);
if (!item || item.size === height)
return;
const wasUnknown = item.size < 0;
item.size = height;
if (!hasSyncedDefaultItemSize && wasUnknown && height > 0) {
listView.syncDefaultItemSize(height);
} else {
store.rebuildItemOffsetsFrom(item.index + 1);
updatePlaceholderSize();
}
}
function getItemOffset(key) {
const item = store.keyItemMap.get(key);
return item ? item.offset + section.headerSize : -1;
}
function onScrollContextUpdate(context) {
if (!section.element || context.containerSize === 0)
return;
const top = context.headerSize + section.offsetTop;
const bottom = top + section.placeholderSize;
if (!keys.length || !props2.preload && (bottom < context.renderStartOffset || top > context.renderEndOffset)) {
updateRenderInfo(0, 0);
return;
}
let min = Math.max(0, context.renderStartOffset - top - section.headerSize);
let max = Math.max(0, context.renderEndOffset - top - section.headerSize);
if (props2.preload) {
const contentHeight = store.contentSize;
min = Math.min(min, contentHeight);
max = Math.min(max, contentHeight);
let remaining = Math.min(contentHeight, context.containerSize) - (max - min);
if (remaining > 0) {
const prepend = Math.min(remaining, min);
min -= prepend;
remaining -= prepend;
max = Math.min(contentHeight, max + remaining);
}
}
if (max <= min)
updateRenderInfo(0, 0);
else
updateRenderInfo(...store.getRenderRange(min, max));
}
onMounted(() => {
section.element = element.value;
updatePlaceholderSize();
});
watch(
() => props2.preload,
() => listView.queueLayout()
);
onBeforeUnmount(() => {
listView.sectionMap.delete(sectionId);
store.itemInstanceMap.clear();
listView.queueLayout();
});
__expose({ renderRange, updateList, updateListIds, updateRenderInfo });
const n0 = t0$e();
const n3 = child(n0);
const n2 = next(n3);
initUniElement(n0, _uniStickySectionElement);
setInsertionState(n0, n3);
createSlot();
setStaticTemplateRef(n2, placeholderElement, null, "placeholderElement");
setStaticTemplateRef(n0, element, null, "element");
return n0;
}
});
class UniCustomEvent2 {
constructor(type, detail) {
this.type = type;
this.detail = detail;
}
}
class UniSwiperChangeEvent extends UniCustomEvent2 {
constructor(current, source, currentItemId) {
const detail = { current, source };
if (currentItemId != null) {
detail.currentItemId = currentItemId;
}
super("change", detail);
}
}
class UniSwiperTransitionEvent extends UniCustomEvent2 {
constructor(dx, dy) {
super("transition", { dx, dy });
}
}
class UniSwiperAnimationFinishEvent extends UniCustomEvent2 {
constructor(current, source, currentItemId) {
const detail = { current, source };
if (currentItemId != null) {
detail.currentItemId = currentItemId;
}
super("animationfinish", detail);
}
}
function parsePxRpx(margin) {
if (margin.length == 0) {
return 0;
}
if (margin.endsWith("px")) {
return parseFloat(margin);
}
if (margin.endsWith("rpx")) {
return parseFloat(margin) * (750 / uni.getWindowInfo().windowWidth);
}
return 0;
}
const _UniSwiperElement = class _UniSwiperElement extends UniViewElement {
};
_UniSwiperElement.__uniElement = {};
let UniSwiperElement = _UniSwiperElement;
const t0$d = template("<div uni-view>");
const t1$9 = template("<div uni-swiper uni-view class=uni-swiper-wrapper><div uni-view></div><div uni-view>", 1);
const _uniSwiperElement = { value: "SWIPER" };
const DIRECTION_LOCK_THRESHOLD = 5;
const _sfc_main$d = /* @__PURE__ */ defineVaporComponent({
...{
name: "swiper",
rootElement: {
class: /* @__PURE__ */ initUniElementType(UniSwiperElement, "swiper")
},
externalClasses: ["indicator-class", "indicator-active-class"]
},
__name: "swiper",
props: {
vertical: { type: [Boolean, String], default: false },
current: { type: Number },
circular: { type: [Boolean, String], default: false },
autoplay: { type: [Boolean, String], default: false },
interval: { default: 3e3, type: Number },
duration: { default: 500, type: Number },
easingFunction: { default: "default", type: String },
previousMargin: { default: "0px", type: String },
nextMargin: { default: "0px", type: String },
disableTouch: { type: [Boolean, String], default: false },
disableBounce: { type: [Boolean, String], default: false },
indicatorDots: { type: [Boolean, String], default: false },
indicatorClass: { default: "", type: null },
indicatorActiveClass: { default: "", type: null },
indicatorStyle: { default: "", type: String },
indicatorActiveStyle: { default: "", type: String },
autoHeight: { type: [Boolean, String], default: false },
currentItemId: { type: String }
},
emits: ["change", "transition", "animationfinish"],
setup(__props, { emit: __emit }) {
const props2 = __props;
const emit2 = __emit;
const wrapper = ref(null);
const currentIndex = ref(0);
const sliderCount = ref(0);
const animating = ref(false);
const autoPlayTimer = ref(0);
let resizeObserver = null;
let translate_value = 0;
let touchStartX = 0, touchStartY = 0, touchStartTime = 0, dragging = false, touchMoving = false, activeTouchId = -1, touchStartTranslate = 0, gestureStartTranslate = 0, prevMargin = parsePxRpx(props2.previousMargin), nextMargin = parsePxRpx(props2.nextMargin), sliderItemSize = 0, firstSliderPosition = "start", lastSliderPosition = "end", maxTranslate = 0, minTranslate = 0, initHasFixedHeight = false, initd = false, animationFrameId = 0, animationStartTranslate = 0, animationTargetTranslate = 0, lastAnimationTranslate = 0, animationStartTime = 0, animationSource = "", sequenceStartTranslate = 0, touchDirectionLocked = false, touchDirection = "", needInitAfterAnimate = false, touchInterruptedAnimation = false, lastSliderCount = 0, lastSliderItemSize = 0, destroyFlag = false;
const slots = useSlots();
const hasCustomIndicator = computed(() => {
return slots["indicator"] != null;
});
function updateContainerTransform() {
if (destroyFlag)
return;
if (swiperContainer == null)
return;
const offset = translate_value + prevMargin;
if (props2.vertical) {
swiperContainer.style.setProperty("transform", `translateY(${offset}px)`);
} else {
swiperContainer.style.setProperty("transform", `translateX(${offset}px)`);
}
}
function setItemTransform(item, offset) {
if (destroyFlag)
return;
if (props2.vertical) {
item.style.setProperty("transform", `translateY(${offset}px)`);
} else {
item.style.setProperty("transform", `translateX(${offset}px)`);
}
}
function updateItemPositions() {
if (sliders == null)
return;
for (let i = 0; i < sliders.length; i++) {
const item = sliders[i];
const baseOffset = i * sliderItemSize;
setItemTransform(item, baseOffset);
}
firstSliderPosition = "start";
lastSliderPosition = "end";
}
const isMarginAndMultipleSliders = computed(() => {
return (prevMargin > 0 || nextMargin > 0) && sliderCount.value > 2;
});
let sliders = null;
let swiperContainer = null;
const getSliders = () => {
const wrapperEl = wrapper.value;
if (wrapperEl == null)
return null;
const container = wrapperEl.querySelector(".uni-swiper-container");
if (container == null)
return null;
swiperContainer = container;
const sliders2 = container.children;
if (sliders2 == null || sliders2.length == 0)
return null;
return sliders2;
};
const mergeStyle = (isActive) => {
let style = props2.indicatorStyle;
if (isActive && props2.indicatorActiveStyle.length > 0) {
style = style.length > 0 ? style + "; " + props2.indicatorActiveStyle : props2.indicatorActiveStyle;
}
return style;
};
function findTouchByIdentifier(touches, identifier) {
for (let i = 0; i < touches.length; i++) {
const touch = touches[i];
if (touch.identifier == identifier) {
return touch;
}
}
return null;
}
function getStartTouch(e2) {
if (e2.changedTouches.length > 0) {
return e2.changedTouches[0];
}
if (e2.touches.length > 0) {
return e2.touches[0];
}
return null;
}
function getActiveTouch(e2) {
if (activeTouchId < 0) {
return null;
}
let touch = findTouchByIdentifier(e2.changedTouches, activeTouchId);
if (touch != null) {
return touch;
}
return findTouchByIdentifier(e2.touches, activeTouchId);
}
function handoffActiveTouch(touch) {
activeTouchId = touch.identifier;
touchStartX = touch.pageX;
touchStartY = touch.pageY;
touchStartTranslate = translate_value;
}
function stopAnimationFrame() {
if (animationFrameId > 0) {
cancelAnimationFrame(animationFrameId);
animationFrameId = 0;
}
}
function getEasingProgress(progress) {
if (props2.easingFunction === "linear") {
return progress;
}
return 1 - Math.pow(1 - progress, 2);
}
function dispatchTransitionEvent(offset) {
const accumulatedDx = props2.vertical ? 0 : -offset;
const accumulatedDy = props2.vertical ? -offset : 0;
emit2("transition", new UniSwiperTransitionEvent(accumulatedDx, accumulatedDy));
}
function getInterruptedTranslate() {
if (!isSupportCircular()) {
return lastAnimationTranslate;
}
const stableMinTranslate = -(sliderCount.value - 1) * sliderItemSize;
if (lastAnimationTranslate <= 0 && lastAnimationTranslate >= stableMinTranslate) {
return lastAnimationTranslate;
}
return -(currentIndex.value * sliderItemSize);
}
function animateSlide() {
if (destroyFlag) {
animating.value = false;
stopAnimationFrame();
return;
}
if (!animating.value) {
stopAnimationFrame();
return;
}
const now = Date.now();
const elapsed = now - animationStartTime;
let timeProgress = elapsed / props2.duration;
if (timeProgress >= 1) {
timeProgress = 1;
translate_value = animationTargetTranslate;
lastAnimationTranslate = animationTargetTranslate;
updateContainerTransform();
dispatchTransitionEvent(animationTargetTranslate - sequenceStartTranslate);
emit2("animationfinish", new UniSwiperAnimationFinishEvent(currentIndex.value, animationSource, getItemIdByIndex(currentIndex.value)));
animating.value = false;
stopAnimationFrame();
resetSlidersPosition();
if (needInitAfterAnimate) {
init2();
}
nextTick(() => {
if (initd && !destroyFlag) {
init2();
}
});
sequenceStartTranslate = translate_value;
animationSource = "";
return;
}
const easedProgress = getEasingProgress(timeProgress);
const currentAnimationTranslate = animationStartTranslate + (animationTargetTranslate - animationStartTranslate) * easedProgress;
translate_value = currentAnimationTranslate;
lastAnimationTranslate = currentAnimationTranslate;
updateContainerTransform();
const totalTranslateChange = currentAnimationTranslate - sequenceStartTranslate;
dispatchTransitionEvent(totalTranslateChange);
animationFrameId = requestAnimationFrame(animateSlide);
}
function isStartToEndSlide(targetIndex, direction2) {
return currentIndex.value == 0 && targetIndex == sliderCount.value - 1 && direction2 == -1;
}
function isEndToStartSlide(targetIndex, direction2) {
return currentIndex.value == sliderCount.value - 1 && targetIndex == 0 && direction2 == 1;
}
function isSupportCircular() {
return props2.circular && (sliderCount.value > 2 || sliderCount.value == 2 && prevMargin == 0 && nextMargin == 0);
}
let resetSlidersPosition = () => {
};
function adjustSliderPositionWhenNoMargin(targetIndex, direction2) {
if (!isSupportCircular())
return;
if (sliders == null)
return;
const totalSize = sliderCount.value * sliderItemSize;
if (totalSize == 0)
return;
const currentTranslate = translate_value;
const rightBound = -(sliderCount.value - 1) * sliderItemSize;
const leftBound = 0;
const visualIndex = Math.round(-currentTranslate / sliderItemSize);
let needItem0AtEnd = false;
if (currentTranslate < rightBound) {
needItem0AtEnd = true;
} else if (isEndToStartSlide(targetIndex, direction2)) {
needItem0AtEnd = true;
} else if (visualIndex == sliderCount.value - 1 && targetIndex == 0 && direction2 == 1) {
needItem0AtEnd = true;
}
let needItemLastAtStart = false;
if (currentTranslate > leftBound) {
needItemLastAtStart = true;
} else if (isStartToEndSlide(targetIndex, direction2)) {
needItemLastAtStart = true;
} else if (visualIndex == 0 && targetIndex == sliderCount.value - 1 && direction2 == -1) {
needItemLastAtStart = true;
}
if (needItem0AtEnd) {
if (firstSliderPosition != "end") {
const firstSlider = sliders[0];
if (firstSlider != null) {
setItemTransform(firstSlider, totalSize);
}
firstSliderPosition = "end";
}
} else {
if (firstSliderPosition == "end") {
const firstSlider = sliders[0];
if (firstSlider != null) {
setItemTransform(firstSlider, 0);
}
firstSliderPosition = "start";
}
}
if (needItemLastAtStart) {
if (lastSliderPosition != "start") {
const lastSlider = sliders[sliders.length - 1];
if (lastSlider != null) {
setItemTransform(lastSlider, -sliderItemSize);
}
lastSliderPosition = "start";
}
} else {
if (lastSliderPosition == "start") {
const lastSlider = sliders[sliders.length - 1];
if (lastSlider != null) {
setItemTransform(lastSlider, (sliders.length - 1) * sliderItemSize);
}
lastSliderPosition = "end";
}
}
}
function adjustSliderPositionWhenHasMargin(targetIndex, direction2) {
if (!isSupportCircular())
return;
if (sliders == null)
return;
const totalSize = sliderCount.value * sliderItemSize;
if (totalSize == 0)
return;
const currentTranslate = translate_value;
const visualIndex = Math.round(-currentTranslate / sliderItemSize);
const rightBound = -(sliderCount.value - 1) * sliderItemSize;
const leftBound = 0;
let needItem0AtEnd = false;
if (currentTranslate < rightBound) {
needItem0AtEnd = true;
} else if (targetIndex != null && isEndToStartSlide(targetIndex, direction2)) {
needItem0AtEnd = true;
} else if (visualIndex == sliderCount.value - 1 && targetIndex == 0 && direction2 == 1) {
needItem0AtEnd = true;
} else if (direction2 == null && targetIndex == sliderCount.value - 1) {
needItem0AtEnd = true;
}
let needItemLastAtStart = false;
if (currentTranslate > leftBound) {
needItemLastAtStart = true;
} else if (targetIndex != null && isStartToEndSlide(targetIndex, direction2)) {
needItemLastAtStart = true;
} else if (visualIndex == 0 && targetIndex == sliderCount.value - 1 && direction2 == -1) {
needItemLastAtStart = true;
} else if (direction2 == null && targetIndex == 0) {
needItemLastAtStart = true;
}
if (needItem0AtEnd) {
if (firstSliderPosition != "end") {
const firstSlider = sliders[0];
if (firstSlider != null) {
setItemTransform(firstSlider, totalSize);
}
firstSliderPosition = "end";
}
} else {
if (firstSliderPosition == "end") {
const firstSlider = sliders[0];
if (firstSlider != null) {
setItemTransform(firstSlider, 0);
}
firstSliderPosition = "start";
}
}
if (needItemLastAtStart) {
if (lastSliderPosition != "start") {
const lastSlider = sliders[sliders.length - 1];
if (lastSlider != null) {
setItemTransform(lastSlider, -sliderItemSize);
}
lastSliderPosition = "start";
}
} else {
if (lastSliderPosition == "start") {
const lastSlider = sliders[sliders.length - 1];
if (lastSlider != null) {
setItemTransform(lastSlider, (sliders.length - 1) * sliderItemSize);
}
lastSliderPosition = "end";
}
}
}
function adjustSliderPosition(targetIndex, direction2) {
if (!isSupportCircular())
return;
if (sliders == null)
return;
if (isMarginAndMultipleSliders.value) {
adjustSliderPositionWhenHasMargin(targetIndex, direction2);
} else {
adjustSliderPositionWhenNoMargin(targetIndex, direction2);
}
}
function resetSlidersPositionWhenHasMargin() {
if (!isSupportCircular())
return;
if (sliders == null)
return;
if (currentIndex.value == 0) {
if (firstSliderPosition != "start") {
translate_value = 0;
updateContainerTransform();
if (sliders[0] != null) {
setItemTransform(sliders[0], 0);
}
firstSliderPosition = "start";
}
if (lastSliderPosition != "end") {
if (sliders[sliders.length - 1] != null) {
setItemTransform(sliders[sliders.length - 1], (sliders.length - 1) * sliderItemSize);
}
lastSliderPosition = "end";
}
adjustSliderPosition(currentIndex.value, null);
return;
}
if (currentIndex.value == sliderCount.value - 1) {
if (firstSliderPosition != "start") {
if (sliders[0] != null) {
setItemTransform(sliders[0], 0);
}
firstSliderPosition = "start";
}
if (lastSliderPosition != "end") {
if (sliders[sliders.length - 1] != null) {
setItemTransform(sliders[sliders.length - 1], (sliders.length - 1) * sliderItemSize);
}
lastSliderPosition = "end";
}
translate_value = -(sliderCount.value - 1) * sliderItemSize;
updateContainerTransform();
adjustSliderPosition(currentIndex.value, null);
return;
}
if (lastSliderPosition != "end" && firstSliderPosition != "start") {
adjustSliderPosition(currentIndex.value, null);
}
}
function resetSlidersPositionWhenNoMargin() {
if (!isSupportCircular())
return;
const totalSize = sliderCount.value * sliderItemSize;
if (totalSize == 0)
return;
if (translate_value <= -totalSize + 1) {
translate_value += totalSize;
updateContainerTransform();
updateItemPositions();
firstSliderPosition = "start";
lastSliderPosition = "end";
} else if (translate_value >= 1) {
translate_value -= totalSize;
updateContainerTransform();
updateItemPositions();
firstSliderPosition = "start";
lastSliderPosition = "end";
}
}
resetSlidersPosition = () => {
if (sliders == null)
return;
if (isMarginAndMultipleSliders.value) {
resetSlidersPositionWhenHasMargin();
} else {
resetSlidersPositionWhenNoMargin();
}
};
function getItemIdByIndex(index2) {
var _a;
if (sliders == null)
return null;
return (_a = sliders[index2]) == null ? void 0 : _a.itemId;
}
function slideTo(targetIndex, source, direction2) {
if (destroyFlag)
return;
if (targetIndex < 0 || targetIndex >= sliderCount.value)
return;
if (animating.value || dragging) {
animating.value = false;
stopAnimationFrame();
dragging = false;
touchMoving = false;
touchDirectionLocked = false;
touchDirection = "";
touchInterruptedAnimation = false;
if (isSupportCircular()) {
updateItemPositions();
firstSliderPosition = "start";
lastSliderPosition = "end";
}
translate_value = getInterruptedTranslate();
updateContainerTransform();
}
stopAnimationFrame();
const oldTranslate = translate_value;
adjustSliderPosition(targetIndex, direction2);
const translateDelta = translate_value - oldTranslate;
sequenceStartTranslate += translateDelta;
animationStartTranslate = translate_value;
lastAnimationTranslate = animationStartTranslate;
animationStartTime = Date.now();
animationSource = source;
if (props2.circular && isStartToEndSlide(targetIndex, direction2)) {
animationTargetTranslate = 1 * sliderItemSize;
} else if (props2.circular && isEndToStartSlide(targetIndex, direction2)) {
animationTargetTranslate = sliderCount.value * sliderItemSize * -1;
} else {
animationTargetTranslate = targetIndex * sliderItemSize * -1;
}
if (targetIndex != currentIndex.value) {
currentIndex.value = targetIndex;
emit2("change", new UniSwiperChangeEvent(targetIndex, source, getItemIdByIndex(targetIndex)));
}
animating.value = true;
animationFrameId = requestAnimationFrame(animateSlide);
}
function startAutoPlay() {
if (!props2.autoplay || sliderCount.value <= 1)
return;
autoPlayTimer.value = setInterval(() => {
if (destroyFlag) {
stopAutoPlay();
return;
}
const next2 = currentIndex.value == sliderCount.value - 1 ? 0 : currentIndex.value + 1;
slideTo(next2, "autoplay", 1);
}, props2.interval);
}
function stopAutoPlay() {
if (autoPlayTimer.value > 0) {
clearInterval(autoPlayTimer.value);
autoPlayTimer.value = 0;
}
}
const handleIndicatorClick = (index2) => {
const direction2 = getSlideDirection(index2);
slideTo(index2, "click", direction2);
};
function updateWrapperHeight(index2) {
if (sliders == null)
return;
const currentSlider = sliders[index2];
if (currentSlider == null)
return;
const sliderContent = currentSlider.querySelector(".uni-swiper-item-content");
if (sliderContent) {
wrapper.value.style.setProperty("height", `${sliderContent.offsetHeight}px`);
}
}
function initSliders() {
sliders = getSliders();
sliderCount.value = sliders ? sliders.length : 0;
}
function updateMinTranslate() {
minTranslate = -(sliderCount.value - 1) * sliderItemSize;
}
function getTouchMoveMaxTranslate() {
if (isSupportCircular() && lastSliderPosition == "start") {
return sliderItemSize;
}
return maxTranslate;
}
function getTouchMoveMinTranslate() {
if (isSupportCircular() && firstSliderPosition == "end") {
return -(sliderCount.value * sliderItemSize);
}
return minTranslate;
}
function fixIndex(index2) {
if (index2 < 0) {
return props2.circular ? sliderCount.value - 1 : 0;
} else if (index2 >= sliderCount.value) {
return props2.circular ? 0 : sliderCount.value - 1;
}
return index2;
}
function getSlideDirection(targetIndex) {
const count = sliderCount.value;
const current = currentIndex.value;
if (count <= 1 || targetIndex == current) {
return 1;
}
if (!props2.circular) {
return targetIndex > current ? 1 : -1;
}
const forward = (targetIndex - current + count) % count;
const backward = (current - targetIndex + count) % count;
return forward <= backward ? 1 : -1;
}
function calculateSliderContainerSize() {
const wrapperEl = wrapper.value;
let containerWidth = wrapperEl.offsetWidth;
let containerHeight = wrapperEl.offsetHeight;
if (containerWidth <= 0 || containerHeight <= 0) {
const rect = wrapperEl.getBoundingClientRect();
if (containerWidth <= 0 && rect.width > 0) {
containerWidth = rect.width;
}
if (containerHeight <= 0 && rect.height > 0) {
containerHeight = rect.height;
}
}
if (containerWidth <= 0) {
const wrapperWidth = wrapperEl.style.getPropertyValue("width");
if (wrapperWidth.endsWith("px") || wrapperWidth.endsWith("rpx")) {
const parsedWidth = parsePxRpx(wrapperWidth);
if (parsedWidth > 0) {
containerWidth = parsedWidth;
}
}
}
if (containerHeight <= 0) {
const wrapperHeight = wrapperEl.style.getPropertyValue("height");
if (wrapperHeight.endsWith("px") || wrapperHeight.endsWith("rpx")) {
const parsedHeight = parsePxRpx(wrapperHeight);
if (parsedHeight > 0) {
containerHeight = parsedHeight;
}
}
}
return {
containerWidth,
containerHeight
};
}
function calculateSliderItemSize(hasFixedHeight, containerWidth, containerHeight) {
if (props2.vertical) {
if (hasFixedHeight && containerHeight > 0) {
sliderItemSize = containerHeight - prevMargin - nextMargin;
} else {
sliderItemSize = 0;
}
} else {
sliderItemSize = containerWidth - prevMargin - nextMargin;
if (sliderItemSize <= 0) {
sliderItemSize = containerWidth;
}
}
if (sliderItemSize < 0) {
sliderItemSize = 0;
}
}
function updateContainerSize(containerWidth, containerHeight, hasFixedHeight) {
if (sliders == null)
return;
const container = wrapper.value.querySelector(".uni-swiper-container");
if (props2.vertical) {
if (containerWidth > 0) {
container.style.setProperty("width", containerWidth + "px");
}
if (sliderItemSize > 0) {
const totalSize = sliderItemSize * sliders.length;
container.style.setProperty("height", totalSize + "px");
}
} else {
const totalSize = sliderItemSize * sliders.length;
container.style.setProperty("width", totalSize + "px");
if (hasFixedHeight) {
container.style.setProperty("height", "100%");
}
}
}
function updateSlidersSize(containerWidth, sliderItemSize2, hasFixedHeight) {
let sliderWidth = "", sliderHeight = "";
if (props2.vertical) {
if (containerWidth > 0) {
sliderWidth = containerWidth + "px";
}
if (sliderItemSize2 > 0) {
sliderHeight = sliderItemSize2 + "px";
}
} else {
if (sliderItemSize2 > 0) {
sliderWidth = sliderItemSize2 + "px";
} else if (containerWidth > 0) {
sliderWidth = containerWidth + "px";
}
if (hasFixedHeight) {
sliderHeight = "100%";
}
}
if (sliders == null)
return;
for (let i = 0; i < sliders.length; i++) {
const item = sliders[i];
if (sliderWidth.length > 0) {
item.style.setProperty("width", sliderWidth);
}
if (sliderHeight.length > 0) {
item.style.setProperty("height", sliderHeight);
}
item.style.setProperty("visibility", "visible");
}
const savedFirstPos = firstSliderPosition;
const savedLastPos = lastSliderPosition;
updateItemPositions();
if (isSupportCircular() && sliderCount.value > 0) {
if (savedFirstPos == "end") {
const firstSlider = sliders[0];
const totalSize = sliderCount.value * sliderItemSize2;
setItemTransform(firstSlider, totalSize);
firstSliderPosition = "end";
}
if (savedLastPos == "start") {
const lastSlider = sliders[sliders.length - 1];
setItemTransform(lastSlider, -sliderItemSize2);
lastSliderPosition = "start";
}
}
}
function updateWrapperOverflow() {
if (prevMargin > 0 || nextMargin > 0) {
if (props2.vertical) {
wrapper.value.style.setProperty("overflow-x", "hidden");
wrapper.value.style.setProperty("overflow-y", "visible");
} else {
wrapper.value.style.setProperty("overflow-x", "visible");
wrapper.value.style.setProperty("overflow-y", "hidden");
}
}
}
function init2() {
stopAutoPlay();
needInitAfterAnimate = false;
if (wrapper == null || destroyFlag)
return;
let { containerWidth, containerHeight } = calculateSliderContainerSize();
const isFirstInit = !initd;
if (isFirstInit) {
initd = true;
const wrapperHeight = wrapper.value.style.getPropertyValue("height");
if (wrapperHeight.length > 0 && wrapperHeight !== "auto") {
initHasFixedHeight = true;
if (containerHeight <= 0) {
containerHeight = parsePxRpx(wrapperHeight);
}
}
if (!initHasFixedHeight && containerHeight <= 0) {
containerHeight = 0;
}
}
initSliders();
if (sliders == null)
return;
calculateSliderItemSize(initHasFixedHeight, containerWidth, containerHeight);
updateContainerSize(containerWidth, containerHeight, initHasFixedHeight);
updateSlidersSize(containerWidth, sliderItemSize, initHasFixedHeight);
updateWrapperOverflow();
const sliderStructureChanged = sliderCount.value != lastSliderCount || sliderItemSize != lastSliderItemSize;
lastSliderCount = sliderCount.value;
lastSliderItemSize = sliderItemSize;
if (isFirstInit) {
if (props2.current != void 0) {
currentIndex.value = props2.current > 0 && props2.current < sliderCount.value ? props2.current : 0;
} else if (props2.currentItemId != void 0) {
const targetIndex = getItemIndexByItemId(props2.currentItemId);
if (targetIndex != null) {
currentIndex.value = targetIndex;
}
}
} else {
if (currentIndex.value >= sliderCount.value) {
currentIndex.value = sliderCount.value - 1;
}
}
if (animating.value || dragging) {
if (sliderStructureChanged) {
animating.value = false;
stopAnimationFrame();
dragging = false;
touchMoving = false;
touchInterruptedAnimation = false;
updateItemPositions();
firstSliderPosition = "start";
lastSliderPosition = "end";
if (currentIndex.value >= sliderCount.value) {
currentIndex.value = Math.max(sliderCount.value - 1, 0);
}
translate_value = -(currentIndex.value * sliderItemSize);
updateContainerTransform();
sequenceStartTranslate = translate_value;
animationSource = "";
needInitAfterAnimate = false;
updateMinTranslate();
updateWrapperHeight(currentIndex.value);
} else {
needInitAfterAnimate = true;
updateMinTranslate();
updateWrapperHeight(currentIndex.value);
return;
}
}
if (currentIndex.value != 0) {
translate_value = -(currentIndex.value * sliderItemSize);
} else {
translate_value = 0;
}
updateContainerTransform();
adjustSliderPosition(currentIndex.value, null);
sequenceStartTranslate = translate_value;
updateMinTranslate();
updateWrapperHeight(currentIndex.value);
startAutoPlay();
}
const onTouchStart = (e2) => {
if (destroyFlag)
return;
if (props2.disableTouch)
return;
e2.stopPropagation();
const startTouch = getStartTouch(e2);
if (startTouch == null)
return;
if (dragging && activeTouchId >= 0 && findTouchByIdentifier(e2.touches, activeTouchId) != null) {
return;
}
stopAutoPlay();
const wasAnimating = animating.value;
touchInterruptedAnimation = wasAnimating;
if (animating.value) {
animating.value = false;
stopAnimationFrame();
if (isSupportCircular()) {
updateItemPositions();
firstSliderPosition = "start";
lastSliderPosition = "end";
}
translate_value = getInterruptedTranslate();
updateContainerTransform();
}
const oldTranslate = translate_value;
resetSlidersPosition();
const translateDelta = translate_value - oldTranslate;
handoffActiveTouch(startTouch);
touchStartTime = Date.now();
gestureStartTranslate = translate_value;
dragging = true;
touchMoving = false;
touchDirectionLocked = false;
touchDirection = "";
if (!wasAnimating) {
sequenceStartTranslate = translate_value;
startTouch.pageX;
startTouch.pageY;
} else {
sequenceStartTranslate += translateDelta;
}
};
const onTouchMove = (e2) => {
if (destroyFlag)
return;
if (props2.disableTouch)
return;
e2.stopPropagation();
if (!dragging)
return;
const t12 = getActiveTouch(e2);
if (t12 == null)
return;
touchMoving = true;
const dx = t12.pageX - touchStartX;
const dy = t12.pageY - touchStartY;
const delta = props2.vertical ? dy : dx;
const currentTranslate = touchStartTranslate + delta;
const overallDelta = currentTranslate - touchStartTranslate;
const overallDirection = overallDelta > 0 ? -1 : 1;
const absDx = Math.abs(dx);
const absDy = Math.abs(dy);
if (!touchDirectionLocked) {
const totalDistance = Math.sqrt(dx * dx + dy * dy);
if (totalDistance >= DIRECTION_LOCK_THRESHOLD) {
const angle = Math.atan2(absDy, absDx) * 180 / Math.PI;
if (!props2.vertical) {
if (angle < 30) {
touchDirection = "horizontal";
} else if (angle > 45) {
touchDirection = "vertical";
} else {
touchDirection = "vertical";
}
} else {
if (angle > 60) {
touchDirection = "vertical";
} else if (angle < 45) {
touchDirection = "horizontal";
} else {
touchDirection = "horizontal";
}
}
touchDirectionLocked = true;
}
}
if (touchDirectionLocked) {
if (!props2.vertical) {
if (touchDirection === "horizontal") {
e2.preventDefault();
} else {
return;
}
} else {
if (touchDirection === "vertical") {
const canSwipe = isSupportCircular() || delta > 0 && currentIndex.value > 0 || delta < 0 && currentIndex.value < sliderCount.value - 1;
if (!canSwipe) {
return;
}
} else {
return;
}
}
} else {
return;
}
if (isSupportCircular()) {
const visualIndex = Math.round(-touchStartTranslate / sliderItemSize);
const targetIndex = fixIndex(visualIndex + overallDirection);
adjustSliderPosition(targetIndex, overallDirection);
}
const touchMoveMaxTranslate = getTouchMoveMaxTranslate();
const touchMoveMinTranslate = getTouchMoveMinTranslate();
const atBoundary = !props2.circular && props2.disableBounce && sliderCount.value > 0 && (currentTranslate > maxTranslate && delta > 0 || currentTranslate < minTranslate && delta < 0);
if (!atBoundary) {
e2.preventDefault();
}
if (delta != 0) {
const totalTranslateChange = currentTranslate - sequenceStartTranslate;
dispatchTransitionEvent(totalTranslateChange);
}
if (props2.disableBounce) {
if (currentTranslate > touchMoveMaxTranslate) {
translate_value = touchMoveMaxTranslate;
updateContainerTransform();
return;
}
if (currentTranslate < touchMoveMinTranslate) {
translate_value = touchMoveMinTranslate;
updateContainerTransform();
return;
}
} else {
if (currentTranslate > touchMoveMaxTranslate) {
const overScroll = currentTranslate - touchMoveMaxTranslate;
translate_value = touchMoveMaxTranslate + overScroll * 0.3;
updateContainerTransform();
return;
}
if (currentTranslate < touchMoveMinTranslate) {
const overScroll = currentTranslate - touchMoveMinTranslate;
translate_value = touchMoveMinTranslate + overScroll * 0.3;
updateContainerTransform();
return;
}
}
translate_value = currentTranslate;
updateContainerTransform();
};
const onTouchEnd = (e2) => {
if (destroyFlag)
return;
if (props2.disableTouch)
return;
e2.stopPropagation();
if (!dragging)
return;
const activeChangedTouch = activeTouchId >= 0 ? findTouchByIdentifier(e2.changedTouches, activeTouchId) : null;
if (activeChangedTouch == null) {
return;
}
if (e2.touches.length > 0) {
handoffActiveTouch(e2.touches[0]);
return;
}
dragging = false;
activeTouchId = -1;
if (!touchMoving) {
if (touchInterruptedAnimation) {
slideTo(currentIndex.value, "touch", 0);
}
touchMoving = false;
startAutoPlay();
return;
}
touchMoving = false;
if (!touchDirectionLocked) {
if (touchInterruptedAnimation) {
slideTo(currentIndex.value, "touch", 0);
}
startAutoPlay();
return;
}
const isDirectionMatched = !props2.vertical && touchDirection === "horizontal" || props2.vertical && touchDirection === "vertical";
if (!isDirectionMatched) {
if (touchInterruptedAnimation) {
slideTo(currentIndex.value, "touch", 0);
}
startAutoPlay();
return;
}
const dt = Date.now() - touchStartTime;
const totalDelta = translate_value - gestureStartTranslate;
const abs = Math.abs(totalDelta);
const source = "touch";
const direction2 = totalDelta < 0 ? 1 : totalDelta > 0 ? -1 : 0;
const shouldChange = dt < 300 && abs > 30 || abs > 100;
if (!shouldChange) {
slideTo(currentIndex.value, source, direction2);
return;
}
let nextIndex = currentIndex.value;
if (isSupportCircular()) {
if (totalDelta > 0) {
nextIndex = (currentIndex.value - 1 + sliderCount.value) % sliderCount.value;
} else if (totalDelta < 0) {
nextIndex = (currentIndex.value + 1) % sliderCount.value;
}
} else {
if (!props2.disableBounce && (translate_value > maxTranslate || translate_value < minTranslate)) {
if (translate_value > maxTranslate) {
nextIndex = 0;
} else if (translate_value < minTranslate) {
nextIndex = sliderCount.value - 1;
}
} else {
if (totalDelta > 0 && currentIndex.value > 0) {
nextIndex = currentIndex.value - 1;
} else if (totalDelta < 0 && currentIndex.value < sliderCount.value - 1) {
nextIndex = currentIndex.value + 1;
}
}
}
slideTo(nextIndex, source, direction2);
startAutoPlay();
};
const handleSwiperItemMounted = () => {
if (initd && !destroyFlag) {
init2();
}
nextTick(() => {
if (initd && !destroyFlag) {
init2();
}
});
};
const handleSwiperItemUnMounted = () => {
nextTick(() => {
if (initd && !destroyFlag) {
init2();
}
});
};
provide("handleSwiperItemMounted", handleSwiperItemMounted);
provide("handleSwiperItemUnMounted", handleSwiperItemUnMounted);
provide("autoHeight", props2.autoHeight);
function getItemIndexByItemId(itemId) {
const list2 = sliders;
if (list2 == null)
return null;
let res = null;
for (let i = 0; i < list2.length; i++) {
if (list2[i].itemId == itemId) {
res = i;
break;
}
}
return res;
}
onMounted(() => {
destroyFlag = false;
watch(() => props2.current, (newVal) => {
if (newVal == currentIndex.value || newVal < 0 || newVal >= sliderCount.value)
return;
const direction2 = getSlideDirection(newVal);
slideTo(newVal, "prop", direction2);
});
watch(() => props2.currentItemId, (newVal) => {
if (props2.current != void 0)
return;
const targetIndex = getItemIndexByItemId(newVal);
if (targetIndex != null) {
currentIndex.value = targetIndex;
}
const direction2 = getSlideDirection(currentIndex.value);
slideTo(currentIndex.value, "prop", direction2);
});
watch(currentIndex, (newVal) => {
updateWrapperHeight(newVal);
});
watch(() => props2.autoplay, (newVal) => {
newVal ? startAutoPlay() : stopAutoPlay();
});
watch(() => props2.vertical, (newVal) => {
init2();
});
init2();
if (resizeObserver == null) {
resizeObserver = new UniResizeObserver((entries2) => {
init2();
});
resizeObserver.observe(wrapper.value);
}
});
onBeforeUnmount(() => {
destroyFlag = true;
stopAutoPlay();
stopAnimationFrame();
if (resizeObserver != null) {
resizeObserver.disconnect(wrapper);
}
});
const n0 = t1$9();
const n2 = child(n0);
const n9 = next(n2);
initUniElement(n0, _uniSwiperElement);
renderEffect(() => setClass(n2, ["uni-swiper-container", __props.vertical ? "uni-swiper-container_vertical" : "uni-swiper-container_horizontal"]));
setInsertionState(n2);
createSlot();
renderEffect(() => setClass(n9, [
"uni-swiper-indicator",
__props.vertical ? "uni-swiper-indicator_vertical" : "uni-swiper-indicator_horizontal"
]));
setInsertionState(n9);
createSlot("indicator");
setInsertionState(n9, 1);
createIf(() => __props.indicatorDots && !unref(hasCustomIndicator), () => {
const n6 = createFor(
() => unref(sliderCount),
(_for_item0) => {
const n8 = t0$d();
on$1(n8, "touchstart", (e2) => {
e2.stopPropagation();
});
on$1(n8, "touchmove", (e2) => {
e2.stopPropagation();
e2.preventDefault();
});
on$1(n8, "touchend", (e2) => {
e2.stopPropagation();
});
on$1(n8, "touchcancel", (e2) => {
e2.stopPropagation();
});
on$1(n8, "click", () => handleIndicatorClick(_for_item0.value - 1));
renderEffect(() => {
const _currentIndex = unref(currentIndex);
const _i = _for_item0.value;
setClass(n8, ["uni-swiper-indicator-item", [
__props.indicatorClass,
{ active: _currentIndex == _i - 1 },
{ [__props.indicatorActiveClass]: _currentIndex == _i - 1 }
]]);
setStyle(n8, mergeStyle(_currentIndex == _i - 1));
});
return n8;
},
(i) => i,
8
/* IS_SINGLE_NODE */
);
return n6;
});
on$1(n0, "touchstart", onTouchStart);
on$1(n0, "touchmove", onTouchMove);
on$1(n0, "touchend", onTouchEnd);
on$1(n0, "touchcancel", onTouchEnd);
setStaticTemplateRef(n0, wrapper, null, "wrapper");
return n0;
}
});
const _UniSwiperItemElement = class _UniSwiperItemElement extends UniViewElement {
constructor() {
super(...arguments);
this.itemId = null;
}
};
_UniSwiperItemElement.__uniElement = { init() {
Object.defineProperty(this, "itemId", { value: null, writable: true, enumerable: true, configurable: true });
} };
let UniSwiperItemElement = _UniSwiperItemElement;
const t0$c = template("<div uni-view class=uni-swiper-item-content>");
const t1$8 = template('<div uni-swiper-item uni-view class=uni-swiper-item style="position: absolute; visibility: hidden;">', 1);
const _uniSwiperItemElement = { value: "SWIPER-ITEM" };
const _sfc_main$c = /* @__PURE__ */ defineVaporComponent({
...{
name: "swiper-item",
rootElement: {
class: /* @__PURE__ */ initUniElementType(UniSwiperItemElement, "swiper-item")
}
},
__name: "swiper-item",
props: {
itemId: { default: null, type: String }
},
setup(__props) {
const swiperItem = ref(null);
const props2 = __props;
const autoHeight = inject("autoHeight", false);
const handleMounted = inject("handleSwiperItemMounted");
const handleUnMounted = inject("handleSwiperItemUnMounted");
onMounted(() => {
swiperItem.value.itemId = props2.itemId;
handleMounted();
});
onUnmounted(() => {
nextTick(() => {
handleUnMounted();
});
});
const n0 = t1$8();
initUniElement(n0, _uniSwiperItemElement);
setInsertionState(n0);
createIf(
() => unref(autoHeight),
() => {
const n4 = t0$c();
setInsertionState(n4);
createSlot();
return n4;
},
() => {
const n6 = createSlot();
return n6;
},
261
/* TRUE_SINGLE_ROOT, FALSE_SINGLE_ROOT, KEYED_INDEX_0 */
);
setStaticTemplateRef(n0, swiperItem, null, "swiperItem");
return n0;
}
});
const _UniSwitchElement = class _UniSwitchElement extends UniViewElement {
constructor() {
super(...arguments);
this.tagName = "SWITCH";
this.nodeName = "SWITCH";
this._checked = false;
}
get checked() {
var _a;
return ((_a = this.vm) == null ? void 0 : _a.getSwitchChecked()) ?? this._checked;
}
set checked(val) {
var _a;
this._checked = val;
(_a = this.vm) == null ? void 0 : _a.setSwitchChecked(val);
}
};
_UniSwitchElement.__uniElement = { vm: true, init() {
Object.defineProperty(this, "_checked", { value: false, writable: true, enumerable: true, configurable: true });
} };
let UniSwitchElement = _UniSwitchElement;
const t0$b = template("<div uni-switch uni-view role=switch><div uni-view>", 1);
const _uniSwitchElement = { value: "SWITCH" };
const _sfc_main$b = /* @__PURE__ */ defineVaporComponent({
...{
name: "switch",
// @ts-ignore
rootElement: {
class: /* @__PURE__ */ initUniElementType(UniSwitchElement, "switch")
},
externalClasses: ["thumb-class", "thumb-active-class", "switch-active-class"]
},
__name: "switch",
props: {
color: { default: "", type: String },
disabled: { type: Boolean, default: false },
checked: { type: Boolean, default: false },
name: { default: "", type: String },
thumbClass: { default: "", type: null },
thumbActiveClass: { default: "", type: null },
switchActiveClass: { default: "", type: null }
},
emits: ["change"],
setup(__props, { expose: __expose, emit: __emit }) {
var _a;
const props2 = __props;
const { handleKeydown, handleKeyup, handleBlur } = createSpaceKeyHandlers(() => props2.disabled);
const attrs2 = useAttrs$1();
const id2 = attrs2.id;
const proxy = (_a = getCurrentInstance()) == null ? void 0 : _a.proxy;
class UniCustomEvent3 {
constructor(type, detail) {
this.detail = detail;
}
}
class UniSwitchChangeEvent extends UniCustomEvent3 {
constructor(value) {
super("change", { value });
}
}
const emit2 = __emit;
const formCtx = inject(FORM_KEY, null);
const labelCtx = inject(LABEL_KEY, null);
let unregisterLabelTarget = null;
const isChecked = ref(props2.checked);
const activeStyle = computed(() => {
if (isChecked.value && props2.color) {
return { "background-color": props2.color };
}
return {};
});
const initialChecked = ref(false);
const enableTransition = ref(false);
const setChecked = (checked) => {
isChecked.value = checked;
};
watch(() => props2.checked, (value) => {
setChecked(value);
});
onMounted(() => {
initialChecked.value = props2.checked;
if (formCtx && props2.name) {
formCtx.registerField({
name: props2.name,
getValue: () => isChecked.value,
reset: () => {
setChecked(initialChecked.value);
}
});
}
const target = {
id: id2 || props2.name,
activate: (event) => {
const element = proxy == null ? void 0 : proxy.$el;
if (element != null) {
dispatchLabelClick(element, event);
}
},
getDisabled: () => props2.disabled
};
if (labelCtx != null) {
labelCtx.register(target);
}
if (id2 != null && id2.length > 0) {
unregisterLabelTarget = registerLabelTarget(id2, target);
}
enableTransition.value = true;
});
onUnmounted(() => {
if (formCtx && props2.name) {
formCtx.unregisterField(props2.name);
}
if (labelCtx != null) {
labelCtx.unregister(id2 || props2.name);
}
unregisterLabelTarget == null ? void 0 : unregisterLabelTarget();
unregisterLabelTarget = null;
});
const handleTap = () => {
if (props2.disabled) {
return;
}
setChecked(!isChecked.value);
emit2("change", new UniSwitchChangeEvent(isChecked.value));
};
__expose({
getSwitchChecked: () => {
return isChecked.value;
},
setSwitchChecked: (checked) => {
setChecked(checked);
}
});
const n0 = t0$b();
const n1 = child(n0);
initUniElement(n0, _uniSwitchElement);
on$1(n0, "keydown", (e2) => unref(handleKeydown)(e2));
on$1(n0, "keyup", (e2) => unref(handleKeyup)(e2));
on$1(n0, "blur", (e2) => unref(handleBlur)(e2));
on$1(n0, "click", withModifiers(handleTap, ["stop"]));
renderEffect(() => {
const _classes = unref(classes);
const _enableTransition = unref(enableTransition);
const _disabled = __props.disabled;
const _isChecked = unref(isChecked);
setClass(n0, ["uni-switch", _classes(
[_enableTransition, "transition-enabled"],
[_disabled, "uni-switch-disabled"],
[_isChecked, "uni-switch-active"],
[_isChecked, __props.switchActiveClass]
)]);
setStyle(n0, unref(activeStyle));
setProp(n0, "tabindex", _disabled ? -1 : 0);
setAttr(n0, "aria-checked", _isChecked);
setAttr(n0, "aria-disabled", _disabled);
setClass(n1, ["uni-switch-thumb", _classes(
[_enableTransition, "thumb-transition-enabled"],
[_isChecked, "uni-switch-active-thumb"],
[_isChecked, __props.thumbActiveClass, __props.thumbClass]
)]);
});
return n0;
}
});
const t0$a = template('<div uni-view style="position: relative; overflow-anchor: none"><!><div uni-view style="width: 1px; flex-shrink: 0;"></div></div>');
const _uniWaterflowElement = { value: "WATERFLOW" };
const _sfc_main$a = /* @__PURE__ */ defineVaporComponent({
...{
name: "waterflow",
rootElement: {
class: /* @__PURE__ */ initUniElementType(UniWaterflowElement, "waterflow")
}
},
__name: "waterflow",
props: {
crossAxisCount: { type: [Number, String], default: 2 },
mainAxisGap: { type: [Number, String], default: 0 },
crossAxisGap: { type: [Number, String], default: 0 },
maxCrossAxisExtent: { type: [Number, String], default: 0 },
scrollIntoView: { type: String, default: "" }
},
setup(__props, { expose: __expose }) {
const props2 = __props;
const attrs2 = useAttrs$1();
const realCrossAxisCount = computed(
() => parseInt(String(props2.crossAxisCount))
);
const realMainAxisGap = computed(() => parseFloat(String(props2.mainAxisGap)));
const realCrossAxisGap = computed(() => parseFloat(String(props2.crossAxisGap)));
const realMaxCrossAxisExtent = computed(
() => parseFloat(String(props2.maxCrossAxisExtent))
);
const scrollElement = ref(null);
const placeholderElement = ref(null);
const renderRange = ref([0, 0]);
let list2 = [];
let keyItemMap = /* @__PURE__ */ new Map();
const itemInstanceMap = /* @__PURE__ */ new Map();
const idKeyMap = /* @__PURE__ */ new Map();
let listIds = [];
let size = 0;
let containerCrossAxisSize = 0;
let itemCrossAxisSize = 0;
let layoutCrossAxisCount = 2;
let placeholderSize = 0;
let scrollOffset = 0;
let cachedSizeStart = 200;
let queued = false;
let destroyed = false;
let pendingScrollId = props2.scrollIntoView;
let scrollingToItemKey;
let scrollingToItemOffset = -1;
let scrollingToItemTimestamp = 0;
let scrollEndTimer;
provide("__uni_recycle_view_instance", getCurrentInstance());
provide("__uni_recycle_state_map", /* @__PURE__ */ new Map());
provide("__uni_recycle_waterflow", {
itemInstanceMap,
updateItemSize,
getItemOffset,
getItemCrossAxisSize: () => itemCrossAxisSize
});
function updateIdKeyMap() {
if (listIds.length !== list2.length)
return;
idKeyMap.clear();
listIds.forEach((id2, index2) => {
if (id2 && list2[index2].key)
idKeyMap.set(id2, list2[index2].key);
});
}
function updateList(keys) {
const oldItems = keyItemMap;
keyItemMap = /* @__PURE__ */ new Map();
list2 = keys.map((key, index2) => {
const instance2 = itemInstanceMap.get(key);
const item = oldItems.get(key) || {
key,
index: index2,
size: instance2 ? instance2.size : -1,
offsetX: 0,
offsetY: 0,
maxEndOffset: 0
};
item.index = index2;
keyItemMap.set(key, item);
return item;
});
rebuildItemOffsetsFrom(0);
updateIdKeyMap();
queueLayout();
}
function updateListIds(ids) {
listIds = ids;
updateIdKeyMap();
queueLayout();
}
function updateRenderInfo(start, length) {
if (renderRange.value[0] !== start || renderRange.value[1] !== length) {
renderRange.value = [start, length];
}
}
function realItemSize(item) {
return item.size < 0 ? 150 : item.size;
}
function rebuildItemOffsetsFrom(start) {
const columns = new Array(layoutCrossAxisCount).fill(0);
const mainGap = realMainAxisGap.value;
const crossGap = realCrossAxisGap.value;
for (let i = 0; i < start; i++) {
const item = list2[i];
const column = itemCrossAxisSize + crossGap > 0 ? Math.min(
layoutCrossAxisCount - 1,
Math.round(item.offsetX / (itemCrossAxisSize + crossGap))
) : 0;
columns[column] = Math.max(
columns[column],
item.offsetY + realItemSize(item) + mainGap
);
}
let maxEnd = start > 0 ? list2[start - 1].maxEndOffset : 0;
for (let i = start; i < list2.length; i++) {
const item = list2[i];
let column = 0;
for (let c = 1; c < columns.length; c++) {
if (columns[c] < columns[column])
column = c;
}
item.offsetX = column * (itemCrossAxisSize + crossGap);
item.offsetY = columns[column];
const end = item.offsetY + realItemSize(item);
item.maxEndOffset = maxEnd = Math.max(maxEnd, end);
columns[column] = end + mainGap;
}
placeholderSize = Math.max(0, Math.max(...columns) - mainGap);
}
function updateCrossAxisMetrics() {
const gap = realCrossAxisGap.value;
const extent = realMaxCrossAxisExtent.value;
layoutCrossAxisCount = extent > 0 && containerCrossAxisSize > 0 ? Math.max(1, Math.ceil(containerCrossAxisSize / (extent + gap))) : Math.max(1, realCrossAxisCount.value);
const width = Math.max(
0,
(containerCrossAxisSize - gap * (layoutCrossAxisCount - 1)) / layoutCrossAxisCount
);
if (width !== itemCrossAxisSize) {
itemCrossAxisSize = width;
list2.forEach((item) => {
item.size = -1;
});
itemInstanceMap.forEach((item) => item.updateItemCrossAxisSize(width));
}
rebuildItemOffsetsFrom(0);
queueLayout();
}
function updateItemSize(key, height) {
const item = keyItemMap.get(key);
if (!item || item.size === height)
return;
item.size = height;
rebuildItemOffsetsFrom(item.index);
queueLayout();
}
function getItemOffset(key) {
const item = keyItemMap.get(key);
return item ? [item.offsetX, item.offsetY] : [-1, -1];
}
function queueLayout() {
if (queued || destroyed)
return;
queued = true;
nextTick(() => {
queued = false;
if (!destroyed && scrollElement.value)
updateRenderList();
});
}
function updateRenderList() {
if (placeholderElement.value)
placeholderElement.value.style.height = `${placeholderSize}px`;
if (pendingScrollId) {
const key = idKeyMap.get(pendingScrollId);
if (key !== void 0) {
pendingScrollId = "";
scrollingToItemKey = key;
scrollingToItemOffset = -1;
scrollingToItemTimestamp = Date.now();
cachedSizeStart = 0;
}
}
if (scrollingToItemKey !== void 0) {
const item = keyItemMap.get(scrollingToItemKey);
if (item && item.offsetY !== scrollingToItemOffset) {
scrollingToItemOffset = item.offsetY;
const animation2 = attrs2["scroll-with-animation"];
const animated = (animation2 === "" || animation2 === true || animation2 === "true") && Date.now() - scrollingToItemTimestamp < 300;
scrollElement.value.scrollTo({
top: item.offsetY,
behavior: animated ? "smooth" : "instant"
});
if (!animated)
scrollOffset = scrollElement.value.scrollTop;
}
}
itemInstanceMap.forEach((instance2, key) => {
const item = keyItemMap.get(key);
if (item)
instance2.updateItemOffset(item.offsetX, item.offsetY);
});
const min = Math.max(0, scrollOffset - cachedSizeStart + 0.2);
const max = scrollOffset + size + 200 - 0.2;
let low = 0;
let high = list2.length;
while (low < high) {
const mid = low + high >>> 1;
if (list2[mid].maxEndOffset < min)
low = mid + 1;
else
high = mid;
}
const start = low;
high = list2.length;
while (low < high) {
const mid = low + high >>> 1;
if (list2[mid].offsetY <= max)
low = mid + 1;
else
high = mid;
}
updateRenderInfo(start, low - start);
}
function onScroll() {
scrollOffset = Math.max(0, scrollElement.value.scrollTop);
updateRenderList();
clearTimeout(scrollEndTimer);
scrollEndTimer = setTimeout(onScrollEnd, 150);
}
function onScrollEnd() {
clearTimeout(scrollEndTimer);
updateRenderList();
scrollingToItemKey = void 0;
cachedSizeStart = 200;
}
const observer = new ResizeObserver((entries2) => {
const entry = entries2[entries2.length - 1];
size = entry.contentRect.height;
if (containerCrossAxisSize !== entry.contentRect.width) {
containerCrossAxisSize = entry.contentRect.width;
updateCrossAxisMetrics();
} else
queueLayout();
});
onMounted(() => {
const element = scrollElement.value;
const style = getComputedStyle(element);
size = element.clientHeight - parseFloat(style.paddingTop) - parseFloat(style.paddingBottom);
containerCrossAxisSize = element.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight);
scrollOffset = element.scrollTop;
updateCrossAxisMetrics();
observer.observe(element);
});
watch(
[
realCrossAxisCount,
realMainAxisGap,
realCrossAxisGap,
realMaxCrossAxisExtent
],
updateCrossAxisMetrics
);
watch(
() => props2.scrollIntoView,
(id2) => {
pendingScrollId = id2;
scrollingToItemKey = void 0;
queueLayout();
}
);
onBeforeUnmount(() => {
destroyed = true;
clearTimeout(scrollEndTimer);
observer.disconnect();
itemInstanceMap.clear();
});
__expose({ renderRange, updateList, updateListIds, updateRenderInfo });
const n7 = withComponentId("2edab972", () => createComponent$1(__syscom_1, {
onScroll: () => onScroll,
onScrollend: () => onScrollEnd
}, {
"refresher": extend$1(() => {
const n4 = createSlot(
"refresher",
null,
null,
4
/* FORWARDED */
);
return n4;
}, {
_: 1
/* NON_STABLE */
}),
"default": () => {
const n3 = t0$a();
const n2 = child(n3);
const n1 = next(n2);
setInsertionState(n3, n2);
createSlot();
setStaticTemplateRef(n1, placeholderElement, null, "placeholderElement");
const n6 = createSlot("load-more");
return [n3, n6];
}
}, true));
setStaticTemplateRef(n7, scrollElement, null, "scrollElement");
const _uniWaterflowRoot = getBlockFirstNode(n7);
if (_uniWaterflowRoot && _uniWaterflowRoot.nodeType === 1) {
_uniWaterflowRoot.setAttribute("uni-waterflow", "");
initUniElement(_uniWaterflowRoot, _uniWaterflowElement);
}
return n7;
}
});
const _t0$7 = template('<text class="uni-video-icon uni-video-toast-icon">', false, 1);
const _t1$2 = template("<div><!><div class=uni-video-toast-draw></div>");
const _t2$1 = template('<div class=uni-video-container><video></video><div class="uni-video-bar uni-video-bar-full"><div class=uni-video-controls><div></div><div class=uni-video-current-time> </div><div class=uni-video-progress-container><div><div class=uni-video-progress-buffered></div><div class=uni-video-progress-played></div><div><div class=uni-video-inner></div></div></div></div><div class=uni-video-duration> </div></div><div></div><div></div></div><div style="z-index: 0;" class=uni-video-danmu></div> <div class=uni-video-loading></div><div><div class=uni-video-toast-title><span class=uni-video-toast-title-current-time> </span> </div></div><div class=uni-video-slots> ', 1);
const _t3$1 = template('<div class=uni-video-cover><div class="uni-video-cover-play-button uni-video-icon"></div>', 1);
const _t4$1 = template('<text class="uni-video-icon uni-video-toast-icon">', 1, 1);
function formatTime(val) {
val = val > 0 && val < Infinity ? val : 0;
const h = Math.floor(val / 3600);
const m = Math.floor(val % 3600 / 60);
const s = Math.floor(val % 3600 % 60);
const hStr = (h < 10 ? "0" : "") + h;
const mStr = (m < 10 ? "0" : "") + m;
const sStr = (s < 10 ? "0" : "") + s;
let str = mStr + ":" + sStr;
if (hStr !== "00") {
str = hStr + ":" + str;
}
return str;
}
function useGesture(props2, videoState, videoRef, fullscreenState) {
const state = reactive({
seeking: false,
gestureType: "none",
volumeOld: 0,
volumeNew: 0,
currentTimeOld: 0,
currentTimeNew: 0,
toastThin: false
});
const touchStartOrigin = {
x: 0,
y: 0
};
let changeToastThinTimer = null;
const changeToastThin = () => {
if (state.gestureType !== "none" && changeToastThinTimer != null)
return;
changeToastThinTimer = setTimeout(() => {
state.toastThin = true;
}, 500);
};
let showToastTimer = void 0;
function changeShowToast() {
if (showToastTimer != void 0)
return;
showToastTimer = setTimeout(() => {
state.toastThin = false;
showToastTimer = void 0;
}, 1e3);
}
function clearChangeShowToast() {
clearTimeout(showToastTimer);
showToastTimer = void 0;
}
function onTouchstart(event) {
const toucher = event.targetTouches[0];
touchStartOrigin.x = toucher.pageX;
touchStartOrigin.y = toucher.pageY;
state.gestureType = "none";
state.volumeOld = 0;
if (fullscreenState.fullscreen) {
event.stopPropagation();
}
}
function onTouchmove(event) {
function stop() {
if (fullscreenState.fullscreen) {
event.stopPropagation();
}
event.preventDefault();
}
if (fullscreenState.fullscreen) {
stop();
}
const gestureType = state.gestureType;
if (gestureType === "stop") {
return;
}
const toucher = event.targetTouches[0];
const pageX = toucher.pageX;
const pageY = toucher.pageY;
const origin = touchStartOrigin;
const video = videoRef.value;
if (gestureType === "progress") {
changeProgress(pageX - origin.x);
state.seeking = true;
} else if (gestureType === "volume") {
changeVolume(pageY - origin.y);
}
if (gestureType !== "none") {
stop();
return;
}
if (Math.abs(pageX - origin.x) > Math.abs(pageY - origin.y)) {
if (!props2.enableProgressGesture) {
state.gestureType = "stop";
return;
}
state.gestureType = "progress";
state.currentTimeOld = state.currentTimeNew = video.currentTime;
if (!fullscreenState.fullscreen) {
stop();
}
} else {
if (!props2.pageGesture && !props2.vslideGesture) {
state.gestureType = "stop";
return;
}
changeToastThin();
state.gestureType = "volume";
state.volumeOld = video.volume;
if (!fullscreenState.fullscreen) {
stop();
}
}
}
function onTouchend(event) {
const video = videoRef.value;
if (state.gestureType !== "none" && state.gestureType !== "stop") {
if (fullscreenState.fullscreen) {
event.stopPropagation();
}
event.preventDefault();
}
if (state.gestureType === "progress" && state.currentTimeOld !== state.currentTimeNew) {
video.currentTime = state.currentTimeNew;
}
state.gestureType = "none";
}
function changeProgress(x) {
const duration = videoState.currentDuration;
let currentTimeNew = x / 600 * duration + state.currentTimeOld;
if (currentTimeNew < 0) {
currentTimeNew = 0;
} else if (currentTimeNew > duration) {
currentTimeNew = duration;
}
state.currentTimeNew = currentTimeNew;
}
function changeVolume(y) {
const video = videoRef.value;
const valueOld = state.volumeOld;
let value;
if (typeof valueOld === "number") {
value = valueOld - y / 200;
if (value < 0) {
value = 0;
} else if (value > 1) {
value = 1;
}
clearChangeShowToast();
changeShowToast();
video.volume = value;
state.volumeNew = value;
}
}
return {
state,
onTouchstart,
onTouchmove,
onTouchend
};
}
function useFullscreen(trigger, containerRef, videoRef, userActionState, rootRef) {
const state = reactive({ fullscreen: false });
const isSafari = /^Apple/.test(navigator.vendor);
function onFullscreenChange($event, webkit) {
if (webkit && document.fullscreenEnabled) {
return;
}
emitFullscreenChange(!!(document.fullscreenElement || document.webkitFullscreenElement));
}
function emitFullscreenChange(val) {
state.fullscreen = val;
trigger("fullscreenchange", {}, {
fullScreen: val,
direction: "vertical"
});
}
function toggleFullscreen(val) {
const root = rootRef.value;
const container = containerRef.value;
const video = videoRef.value;
let mockFullScreen;
if (val) {
if ((document.fullscreenEnabled || document.webkitFullscreenEnabled) && (!isSafari || userActionState.userAction)) {
container[document.fullscreenEnabled ? "requestFullscreen" : "webkitRequestFullscreen"]();
} else if (video.webkitEnterFullScreen) {
video.webkitEnterFullScreen();
} else {
mockFullScreen = true;
container.remove();
container.classList.add("uni-video-type-fullscreen");
document.body.appendChild(container);
}
} else {
if (document.fullscreenEnabled || document.webkitFullscreenEnabled) {
if (document.fullscreenElement) {
document.exitFullscreen();
} else if (document.webkitFullscreenElement) {
document.webkitExitFullscreen();
}
} else if (video.webkitExitFullScreen) {
video.webkitExitFullScreen();
} else {
mockFullScreen = true;
container.remove();
container.classList.remove("uni-video-type-fullscreen");
root.appendChild(container);
}
}
if (mockFullScreen) {
emitFullscreenChange(val);
}
}
function requestFullScreen() {
toggleFullscreen(true);
}
function exitFullScreen() {
toggleFullscreen(false);
}
onBeforeUnmount(exitFullScreen);
return {
state,
onFullscreenChange,
emitFullscreenChange,
toggleFullscreen,
requestFullScreen,
exitFullScreen
};
}
function useVideo(props2, attrs2, trigger) {
const videoRef = ref(null);
const src = computed(() => getRealPath(props2.src));
const muted = computed(() => props2.muted === "true" || props2.muted === true);
const state = reactive({
start: false,
src,
playing: false,
currentTime: 0,
duration: 0,
currentDuration: 0,
progress: 0,
buffered: 0,
muted,
pauseUpdatingCurrentTime: false
});
watch(() => src.value, () => {
state.playing = false;
state.currentTime = 0;
});
watch(() => state.buffered, (buffered) => {
trigger("progress", {}, { buffered });
});
watch(() => muted.value, (muted2) => {
const video = videoRef.value;
video.muted = muted2;
});
watch([() => state.duration, () => props2.duration], () => {
let _duration = Number(props2.duration);
isNaN(_duration) && (_duration = 0);
state.currentDuration = _duration > 0 ? _duration : state.duration;
});
function onDurationChange({ target }) {
state.duration = target.duration;
}
function onLoadedMetadata($event) {
const initialTime = Number(props2.initialTime) || 0;
const video = $event.target;
if (initialTime > 0) {
video.currentTime = initialTime;
}
trigger("loadedmetadata", $event, {
width: video.videoWidth,
height: video.videoHeight,
duration: video.duration
});
onProgress($event);
}
function onProgress($event) {
const video = $event.target;
const buffered = video.buffered;
if (buffered.length) {
state.buffered = buffered.end(buffered.length - 1) / video.duration * 100;
}
}
function onWaiting($event) {
trigger("waiting", $event, {});
}
function onVideoError($event) {
state.playing = false;
trigger("error", $event, {});
}
function onPlay($event) {
state.start = true;
state.playing = true;
trigger("play", $event, {});
}
function onPause($event) {
state.playing = false;
trigger("pause", $event, {});
}
function onEnded($event) {
state.playing = false;
trigger("ended", $event, {});
}
function onTimeUpdate($event) {
const video = $event.target;
if (!state.pauseUpdatingCurrentTime) {
state.currentTime = video.currentTime;
}
const currentTime = video.currentTime;
trigger("timeupdate", $event, {
currentTime,
duration: video.duration
});
}
function toggle() {
const video = videoRef.value;
if (state.playing) {
video.pause();
} else {
video.play();
}
}
function play() {
const video = videoRef.value;
state.start = true;
video.play();
}
function pause() {
const video = videoRef.value;
video.pause();
}
function seek(position) {
const video = videoRef.value;
position = Number(position);
if (typeof position === "number" && !isNaN(position)) {
video.currentTime = position;
}
}
function stop() {
seek(0);
pause();
}
function playbackRate(rate) {
const video = videoRef.value;
video.playbackRate = rate;
}
return {
videoRef,
state,
play,
pause,
stop,
seek,
playbackRate,
toggle,
onDurationChange,
onLoadedMetadata,
onProgress,
onWaiting,
onVideoError,
onPlay,
onPause,
onEnded,
onTimeUpdate
};
}
function useControls(props2, videoState, seek, seeking) {
const progressRef = ref(null);
const ballRef = ref(null);
const centerPlayBtnShow = computed(() => props2.showCenterPlayBtn && !videoState.start);
const controlsVisible = ref(true);
const controlsShow = computed(() => !centerPlayBtnShow.value && props2.controls && controlsVisible.value);
const state = reactive({
seeking: false,
touching: false,
controlsTouching: false,
centerPlayBtnShow,
controlsShow,
controlsVisible
});
function clickProgress(event) {
const $progress = progressRef.value;
let element = event.target;
let x = event.offsetX;
while (element && element !== $progress) {
x += element.offsetLeft;
element = element.parentNode;
}
const w = $progress.offsetWidth;
let progress = 0;
if (x >= 0 && x <= w) {
progress = x / w;
seek(videoState.currentDuration * progress);
}
}
function toggleControls() {
state.controlsVisible = !state.controlsVisible;
}
let hideTiming;
function autoHideStart() {
hideTiming = setTimeout(() => {
state.controlsVisible = false;
}, 3e3);
}
function autoHideEnd() {
if (hideTiming) {
clearTimeout(hideTiming);
hideTiming = null;
}
}
onBeforeUnmount(() => {
if (hideTiming) {
clearTimeout(hideTiming);
}
});
watch(() => state.controlsShow && videoState.playing && !state.controlsTouching, (val) => {
if (val) {
autoHideStart();
} else {
autoHideEnd();
}
});
onMounted(() => {
const passiveOptions2 = passive(false);
let originX;
let originY;
let moveOnce = true;
let originProgress;
const ball = ballRef.value;
function touchmove2(event) {
const toucher = event.targetTouches[0];
const pageX = toucher.pageX;
const pageY = toucher.pageY;
if (moveOnce && Math.abs(pageX - originX) < Math.abs(pageY - originY)) {
touchend(event);
return;
}
moveOnce = false;
const progressEl = progressRef.value;
const w = progressEl.offsetWidth;
let progress = originProgress + (pageX - originX) / w * 100;
if (progress < 0) {
progress = 0;
} else if (progress > 100) {
progress = 100;
}
videoState.progress = progress;
seeking == null ? void 0 : seeking(videoState.currentDuration * progress / 100);
state.seeking = true;
event.preventDefault();
event.stopPropagation();
}
function touchend(event) {
state.controlsTouching = false;
if (state.touching) {
ball.removeEventListener("touchmove", touchmove2, passiveOptions2);
if (!moveOnce) {
event.preventDefault();
event.stopPropagation();
seek(videoState.currentDuration * videoState.progress / 100);
}
state.touching = false;
}
}
ball.addEventListener("touchstart", (event) => {
state.controlsTouching = true;
const toucher = event.targetTouches[0];
originX = toucher.pageX;
originY = toucher.pageY;
originProgress = videoState.progress;
moveOnce = true;
state.touching = true;
ball.addEventListener("touchmove", touchmove2, passiveOptions2);
});
ball.addEventListener("touchend", touchend);
ball.addEventListener("touchcancel", touchend);
});
return {
state,
progressRef,
ballRef,
clickProgress,
toggleControls,
autoHideStart,
autoHideEnd
};
}
function useDanmu(props2, videoState) {
const danmuRef = ref(null);
const state = reactive({ enable: Boolean(props2.enableDanmu) });
let danmuIndex = {
time: 0,
index: -1
};
const danmuList = isArray(props2.danmuList) ? JSON.parse(JSON.stringify(props2.danmuList)) : [];
danmuList.sort(function(a, b) {
return (a.time || 0) - (b.time || 0);
});
function toggleDanmu() {
state.enable = !state.enable;
}
function updateDanmu(event) {
const video = event.target;
const currentTime = video.currentTime;
const oldDanmuIndex = danmuIndex;
const newDanmuIndex = {
time: currentTime,
index: oldDanmuIndex.index
};
if (currentTime > oldDanmuIndex.time) {
for (let index2 = oldDanmuIndex.index + 1; index2 < danmuList.length; index2++) {
const element = danmuList[index2];
if (currentTime >= (element.time || 0)) {
newDanmuIndex.index = index2;
if (videoState.playing && state.enable) {
playDanmu(element);
}
} else {
break;
}
}
} else if (currentTime < oldDanmuIndex.time) {
for (let index2 = oldDanmuIndex.index - 1; index2 > -1; index2--) {
const element = danmuList[index2];
if (currentTime <= (element.time || 0)) {
newDanmuIndex.index = index2 - 1;
} else {
break;
}
}
}
danmuIndex = newDanmuIndex;
}
function playDanmu(danmu) {
const p2 = document.createElement("p");
p2.className = "uni-video-danmu-item";
p2.innerText = danmu.text;
let style = `bottom: ${Math.random() * 100}%;color: ${danmu.color};`;
p2.setAttribute("style", style);
const danmuEl = danmuRef.value;
danmuEl.appendChild(p2);
setTimeout(function() {
style += "left: 0;-webkit-transform: translateX(-100%);transform: translateX(-100%);";
p2.setAttribute("style", style);
setTimeout(function() {
p2.remove();
}, 4e3);
}, 17);
}
function sendDanmu(danmu) {
danmuList.splice(danmuIndex.index + 1, 0, {
text: String(danmu.text),
color: danmu.color,
time: videoState.currentTime || 0
});
}
return {
state,
danmuRef,
updateDanmu,
toggleDanmu,
sendDanmu
};
}
function useContext(play, pause, stop, seek, sendDanmu, playbackRate, requestFullScreen, exitFullScreen) {
const methods = {
play,
stop,
pause,
seek,
sendDanmu,
playbackRate,
requestFullScreen,
exitFullScreen
};
const id2 = useContextInfo();
useSubscribe((type, data) => {
let options;
switch (type) {
case "seek":
options = data.position;
break;
case "sendDanmu":
options = data;
break;
case "playbackRate":
options = data.rate;
break;
}
if (type in methods) {
methods[type](options);
}
}, id2, true);
}
function useProgressing(videoState, gestureState, controlsState, autoHideEnd, autoHideStart) {
const progressing = computed(() => gestureState.gestureType === "progress" || controlsState.touching);
watch(progressing, (val) => {
videoState.pauseUpdatingCurrentTime = val;
controlsState.controlsTouching = val;
if (gestureState.gestureType === "progress" && val) {
controlsState.controlsVisible = val;
}
});
watch([() => videoState.currentTime, () => videoState.currentDuration], () => {
if (videoState.currentDuration > 0) {
videoState.progress = videoState.currentTime / videoState.currentDuration * 100;
} else {
videoState.progress = 0;
}
videoState.progress > 100 && (videoState.progress = 100);
}, { immediate: true });
watch(() => gestureState.currentTimeNew, (currentTimeNew) => {
videoState.currentTime = currentTimeNew;
});
return progressing;
}
const videoProps = {
id: {
type: String,
default: ""
},
src: {
type: String,
default: ""
},
duration: {
type: [Number, String],
default: ""
},
controls: {
type: [Boolean, String],
default: true
},
danmuList: {
type: Array,
default() {
return [];
}
},
danmuBtn: {
type: [Boolean, String],
default: false
},
enableDanmu: {
type: [Boolean, String],
default: false
},
autoplay: {
type: [Boolean, String],
default: false
},
loop: {
type: [Boolean, String],
default: false
},
muted: {
type: [Boolean, String],
default: false
},
objectFit: {
type: String,
default: "contain"
},
poster: {
type: String,
default: ""
},
direction: {
type: [String, Number],
default: ""
},
showProgress: {
type: Boolean,
default: true
},
initialTime: {
type: [String, Number],
default: 0
},
showFullscreenBtn: {
type: [Boolean, String],
default: true
},
pageGesture: {
type: [Boolean, String],
default: false
},
vslideGesture: {
type: [Boolean, String],
default: false
},
enableProgressGesture: {
type: [Boolean, String],
default: true
},
showPlayBtn: {
type: [Boolean, String],
default: true
},
showCenterPlayBtn: {
type: [Boolean, String],
default: true
}
};
const videoEmits = [
"fullscreenchange",
"progress",
"loadedmetadata",
"waiting",
"error",
"play",
"pause",
"ended",
"timeupdate"
];
function useVideoComponent(props2, { emit: emit2, attrs: attrs2, slots }) {
const rootRef = ref(null);
const containerRef = ref(null);
const trigger = useCustomEvent(rootRef, emit2);
const { state: userActionState } = useUserAction();
const { $attrs: videoAttrs } = useAttrs({ excludeListeners: true });
initI18nVideoMsgsOnce();
const { videoRef, state: videoState, play, pause, stop, seek, playbackRate, toggle, onDurationChange, onLoadedMetadata, onProgress, onWaiting, onVideoError, onPlay, onPause, onEnded, onTimeUpdate } = useVideo(props2, attrs2, trigger);
const { state: danmuState, danmuRef, updateDanmu, toggleDanmu, sendDanmu } = useDanmu(props2, videoState);
const { state: fullscreenState, onFullscreenChange, emitFullscreenChange, toggleFullscreen, requestFullScreen, exitFullScreen } = useFullscreen(trigger, containerRef, videoRef, userActionState, rootRef);
const { state: gestureState, onTouchstart, onTouchend, onTouchmove } = useGesture(props2, videoState, videoRef, fullscreenState);
const { state: controlsState, progressRef, ballRef, clickProgress, toggleControls, autoHideEnd, autoHideStart } = useControls(props2, videoState, seek, (currentTimeNew) => {
gestureState.currentTimeNew = currentTimeNew;
});
useContext(play, pause, stop, seek, sendDanmu, playbackRate, requestFullScreen, exitFullScreen);
const progressing = useProgressing(videoState, gestureState, controlsState);
return {
rootRef,
toggleControls,
methods: {
play,
pause,
stop,
seek,
sendDanmu,
playbackRate,
requestFullScreen,
exitFullScreen
},
render: () => {
return (() => {
const _setTemplateRef = createTemplateRefSetter();
const _n0 = _t2$1();
const _n1 = child(_n0);
const _n2 = next(_n1);
let _p0 = child(_n2);
const _n3 = child(_p0);
const _n4 = next(_n3);
const _n5 = next(_n4);
const _n9 = child(_n5);
const _n6 = child(_n9);
const _n7 = next(_n6);
const _n8 = next(_n7);
const _n10 = next(_n5);
const _n11 = next(_p0);
const _n12 = next(_n11);
const _n13 = next(_n2);
const _n14 = next(_n13, true);
const _n27 = next(_n14);
const _n30 = next(_n27);
const _n28 = child(child(_n30));
const _n29 = next(_n28, true);
const _n31 = next(_n30);
on$1(_n0, "touchstart", onTouchstart);
on$1(_n0, "touchend", onTouchend);
on$1(_n0, "touchmove", onTouchmove);
on$1(
_n0,
// @ts-expect-error
"fullscreenchange",
withModifiers(onFullscreenChange, ["stop"])
);
on$1(_n0, "webkitfullscreenchange", withModifiers(($event) => onFullscreenChange($event, true), ["stop"]));
on$1(_n1, "durationchange", onDurationChange);
on$1(_n1, "loadedmetadata", onLoadedMetadata);
on$1(_n1, "progress", onProgress);
on$1(_n1, "waiting", onWaiting);
on$1(_n1, "error", onVideoError);
on$1(_n1, "play", onPlay);
on$1(_n1, "pause", onPause);
on$1(_n1, "ended", onEnded);
on$1(_n1, "timeupdate", (event) => {
onTimeUpdate(event);
updateDanmu(event);
});
on$1(_n1, "webkitbeginfullscreen", () => emitFullscreenChange(true));
on$1(_n1, "x5videoenterfullscreen", () => emitFullscreenChange(true));
on$1(_n1, "webkitendfullscreen", () => emitFullscreenChange(false));
on$1(_n1, "x5videoexitfullscreen", () => emitFullscreenChange(false));
applyVShow(_n2, () => controlsState.controlsShow);
on$1(_n2, "click", withModifiers(() => {
}, ["stop"]));
applyVShow(_n3, () => props2.showPlayBtn);
on$1(_n3, "click", withModifiers(toggle, ["stop"]));
applyVShow(_n4, () => props2.showProgress);
const _x4 = txt(_n4);
setNodes(_x4, () => formatTime(videoState.currentTime));
on$1(_n5, "click", withModifiers(clickProgress, ["stop"]));
applyVShow(_n5, () => props2.showProgress);
applyVShow(_n10, () => props2.showProgress);
const _x10 = txt(_n10);
setNodes(_x10, () => formatTime(videoState.currentDuration));
applyVShow(_n11, () => props2.danmuBtn);
on$1(_n11, "click", withModifiers(toggleDanmu, ["stop"]));
applyVShow(_n12, () => props2.showFullscreenBtn);
on$1(_n12, "click", withModifiers(() => toggleFullscreen(!fullscreenState.fullscreen), ["stop"]));
applyVShow(_n13, () => videoState.start && danmuState.enable);
setNodes(_n14, () => controlsState.centerPlayBtnShow && (() => {
const _n02 = _t3$1();
const _n16 = child(_n02);
on$1(_n02, "click", withModifiers(() => {
}, ["stop"]));
on$1(_n16, "click", withModifiers(play, ["stop"]));
return _n02;
})());
renderEffect(() => {
setDynamicProps(_n1, [
{
style: { "object-fit": props2.objectFit },
muted: !!props2.muted,
loop: !!props2.loop,
src: videoState.src,
poster: props2.poster,
autoplay: !!props2.autoplay
},
videoAttrs.value,
{
class: {
"uni-video-video": true,
"uni-video-video-fullscreen": fullscreenState.fullscreen
},
"webkit-playsinline": true,
playsinline: true
}
]);
_setTemplateRef(_n1, videoRef);
setClassName(_n3, 1 | 2 | (!videoState.playing ? 4 : 0) | (videoState.playing ? 8 : 0), [
" uni-video-icon",
" uni-video-control-button",
" uni-video-control-button-play",
" uni-video-control-button-pause"
]);
setClassName(_n9, 1 | (progressing.value ? 2 : 0), [" uni-video-progress", " uni-video-progress-progressing"]);
setStyle(_n6, {
width: videoState.buffered - videoState.progress + "%",
left: videoState.progress + "%"
});
setStyle(_n7, { width: videoState.progress + "%" });
setStyle(_n8, { left: videoState.progress + "%" });
setClassName(_n8, 1 | (progressing.value ? 2 : 0), [" uni-video-ball", " uni-video-ball-progressing"]);
_setTemplateRef(_n8, ballRef);
_setTemplateRef(_n5, progressRef);
setClassName(_n11, 1 | 2 | (danmuState.enable ? 4 : 0), [
" uni-video-icon",
" uni-video-danmu-button",
" uni-video-danmu-button-active"
]);
setClassName(_n12, 1 | 2 | (fullscreenState.fullscreen ? 4 : 0), [
" uni-video-icon",
" uni-video-fullscreen",
" uni-video-type-fullscreen"
]);
_setTemplateRef(_n13, danmuRef);
});
setInsertionState(_n27);
createIf(() => gestureState.gestureType === "volume", () => {
const _n24 = _t1$2();
const _n23 = child(_n24);
const _n22 = next(_n23);
renderEffect(() => setClassName(_n24, 1 | (gestureState.toastThin ? 2 : 0), [" uni-video-toast-container", " uni-video-toast-container-thin"]));
setInsertionState(_n24, _n23);
createIf(() => !gestureState.toastThin && gestureState.volumeNew > 0 && gestureState.gestureType === "volume", () => {
const _n19 = _t0$7();
return _n19;
}, () => {
const _n21 = createNodes(() => !gestureState.toastThin && (() => {
const _n02 = _t4$1();
return _n02;
})());
return _n21;
}, 265);
setStyle(_n24, { marginTop: `5px` });
renderEffect(() => setStyle(_n22, { width: `${gestureState.volumeNew * 100}%` }));
return _n24;
}, () => {
const _n26 = createNodes(null);
return _n26;
}, 521);
const _x28 = txt(_n28);
setNodes(_x28, () => formatTime(gestureState.currentTimeNew));
setNodes(_n29, " / ", () => formatTime(videoState.currentDuration));
const _x31 = txt(_n31);
setNodes(_x31, () => slots.default && slots.default());
renderEffect(() => {
setClassName(_n30, 1 | (progressing.value ? 2 : 0), [" uni-video-toast", " uni-video-toast-progress"]);
_setTemplateRef(_n0, containerRef);
});
return _n0;
})();
}
};
}
const _t0$6 = template("<div uni-video uni-view>", 1);
class UniVideoElement extends UniViewElement {
static [Symbol.hasInstance](value) {
return this === UniVideoElement && value instanceof UniViewElement && value.hasAttribute("uni-video") || Function.prototype[Symbol.hasInstance].call(this, value);
}
}
const uniTagName$3 = { value: "VIDEO" };
const indexVapor$2 = /* @__PURE__ */ defineBuiltInComponent({
name: "Video",
props: videoProps,
emits: videoEmits,
rootElement: {
name: "uni-video",
class: UniVideoElement
},
setup(props2, context) {
const { rootRef, toggleControls, methods, render } = useVideoComponent(props2, context);
const root = (() => {
const _setTemplateRef = createTemplateRefSetter();
const _n0 = _t0$6();
on$1(_n0, "click", toggleControls);
renderEffect(() => {
setProp(_n0, "id", props2.id);
_setTemplateRef(_n0, rootRef);
});
return _n0;
})();
setInsertionState(root);
insert(render(), root);
Object.assign(root, methods);
Object.defineProperty(root, "uniTagName", uniTagName$3);
return root;
}
});
const onWebInvokeAppService = ({ name, arg }) => {
if (name === "postMessage")
;
else {
switch (name) {
case "navigateTo":
uni.navigateTo(arg);
break;
case "navigateBack":
uni.navigateBack(arg);
break;
case "switchTab":
uni.switchTab(arg);
break;
case "reLaunch":
uni.reLaunch(arg);
break;
case "redirectTo":
uni.redirectTo(arg);
break;
}
}
};
const Invoke = /* @__PURE__ */ once(
() => UniServiceJSBridge.on(ON_WEB_INVOKE_APP_SERVICE, onWebInvokeAppService)
);
const webViewProps = {
src: {
type: String,
default: ""
}
};
function useWebView(props2, emit2) {
Invoke();
const rootRef = ref(null);
const iframeRef = ref(null);
const { $attrs, $excludeAttrs, $listeners } = useAttrs({
excludeListeners: true
});
const trigger = useCustomEvent(rootRef, emit2);
const renderIframe = () => {
const iframe = document.createElement("iframe");
iframe.onload = function(event) {
trigger("load", event, { src: props2.src, url: props2.src });
};
watchEffect(() => {
for (const key in $attrs.value) {
if (hasOwn($attrs.value, key)) {
const attr2 = $attrs.value[key];
iframe[key] = attr2;
}
}
});
watchEffect(() => {
iframe.src = getRealPath(props2.src);
});
iframeRef.value = iframe;
};
renderIframe();
onMounted(() => {
var _a;
(_a = rootRef.value) == null ? void 0 : _a.appendChild(iframeRef.value);
});
return { rootRef, $listeners, $excludeAttrs };
}
const _t0$5 = template("<div>", 1);
class UniWebViewElement extends UniViewElement {
static [Symbol.hasInstance](value) {
return this === UniWebViewElement && value instanceof UniViewElement && value.hasAttribute("uni-web-view") || Function.prototype[Symbol.hasInstance].call(this, value);
}
}
const uniTagName$2 = { value: "WEB-VIEW" };
const indexVapor$1 = /* @__PURE__ */ defineBuiltInComponent({
inheritAttrs: false,
name: "WebView",
props: webViewProps,
emits: ["load"],
rootElement: {
name: "uni-web-view",
class: UniWebViewElement
},
setup(props2, { emit: emit2 }) {
const { rootRef, $listeners, $excludeAttrs } = useWebView(props2, emit2);
const root = (() => {
const _setTemplateRef = createTemplateRefSetter();
const _n0 = _t0$5();
renderEffect(() => {
setDynamicProps(_n0, [
{
"uni-web-view": "",
"uni-view": "",
class: "uni-webview"
},
$listeners.value,
$excludeAttrs.value
]);
_setTemplateRef(_n0, rootRef);
});
return _n0;
})();
Object.defineProperty(root, "uniTagName", uniTagName$2);
return root;
}
});
let index$6 = 0;
function getJSONP(url, options, success, error) {
var js = document.createElement("script");
var callbackKey = options.callback || "callback";
var callbackName = "__uni_jsonp_callback_" + index$6++;
var timeout = options.timeout || 3e4;
var timing;
function end() {
clearTimeout(timing);
delete window[callbackName];
js.remove();
}
window[callbackName] = (res) => {
if (isFunction(success)) {
success(res);
}
end();
};
js.onerror = () => {
if (isFunction(error)) {
error();
}
end();
};
timing = setTimeout(function() {
if (isFunction(error)) {
error();
}
end();
}, timeout);
js.src = url + (url.indexOf("?") >= 0 ? "&" : "?") + callbackKey + "=" + callbackName;
document.body.appendChild(js);
}
function createCallout(maps2) {
function onAdd() {
const div = this.div;
const panes = this.getPanes();
panes.floatPane.appendChild(div);
}
function onRemove() {
const parentNode = this.div.parentNode;
if (parentNode) {
parentNode.removeChild(this.div);
}
}
function createAMapText() {
const option = this.option;
this.Text = new maps2.Text({
text: option.content,
anchor: "bottom-center",
// 设置文本标记锚点
offset: new maps2.Pixel(0, option.offsetY - 16),
style: {
padding: (option.padding || 8) + "px",
"line-height": (option.fontSize || 14) + "px",
"border-radius": (option.borderRadius || 0) + "px",
"border-color": `${option.bgColor || "#fff"} transparent transparent`,
"background-color": option.bgColor || "#fff",
"box-shadow": "0 2px 6px 0 rgba(114, 124, 245, .5)",
"text-align": "center",
"font-size": (option.fontSize || 14) + "px",
color: option.color || "#000"
},
position: option.position
});
const event = maps2.event || maps2.Event;
event.addListener(this.Text, "click", () => {
this.callback();
});
this.Text.setMap(option.map);
}
function createBMapText() {
}
function removeAMapText() {
if (this.Text) {
this.option.map.remove(this.Text);
}
}
function removeBMapText() {
if (this.Text) {
this.option.map.remove(this.Text);
}
}
class Callout {
constructor(option = {}, callback) {
this.createAMapText = createAMapText;
this.removeAMapText = removeAMapText;
this.createBMapText = createBMapText;
this.removeBMapText = removeBMapText;
this.onAdd = onAdd;
this.construct = onAdd;
this.onRemove = onRemove;
this.destroy = onRemove;
this.option = option || {};
const visible = this.visible = this.alwaysVisible = option.display === "ALWAYS";
if (getIsAMap()) {
this.callback = callback;
if (this.visible) {
this.createAMapText();
}
} else if (getIsBMap()) {
if (this.visible) {
this.createBMapText();
}
} else {
const map = option.map;
this.position = option.position;
this.index = 1;
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(callback) {
this.div.onclick = callback;
}
get onclick() {
return this.div.onclick;
}
setOption(option) {
this.option = option;
if (option.display === "ALWAYS") {
this.alwaysVisible = this.visible = true;
} else {
this.alwaysVisible = false;
}
if (getIsAMap()) {
if (this.visible) {
this.createAMapText();
}
} else if (getIsBMap()) {
if (this.visible) {
this.createBMapText();
}
} else {
this.setPosition(option.position);
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";
}
}
if (!getIsAMap() && !getIsBMap()) {
const overlay = new (maps2.OverlayView || maps2.Overlay)();
Callout.prototype.setMap = overlay.setMap;
Callout.prototype.getMap = overlay.getMap;
Callout.prototype.getPanes = overlay.getPanes;
Callout.prototype.getProjection = overlay.getProjection;
Callout.prototype.map_changed = overlay.map_changed;
Callout.prototype.set = overlay.set;
Callout.prototype.get = overlay.get;
Callout.prototype.setOptions = overlay.setValues;
Callout.prototype.bindTo = overlay.bindTo;
Callout.prototype.bindsTo = overlay.bindsTo;
Callout.prototype.notify = overlay.notify;
Callout.prototype.setValues = overlay.setValues;
Callout.prototype.unbind = overlay.unbind;
Callout.prototype.unbindAll = overlay.unbindAll;
Callout.prototype.addListener = overlay.addListener;
}
return Callout;
}
let maps;
const callbacksMap = {};
const GOOGLE_MAP_CALLBACKNAME = "__map_callback__";
function loadMaps(libraries, callback) {
const mapInfo = getMapInfo();
if (!mapInfo.key) {
console.error("Map key not configured.");
return;
}
const callbacks2 = callbacksMap[mapInfo.type] = callbacksMap[mapInfo.type] || [];
if (maps) {
callback(maps);
} else if (window[mapInfo.type] && window[mapInfo.type].maps) {
maps = getIsAMap() || getIsBMap() ? window[mapInfo.type] : window[mapInfo.type].maps;
maps.Callout = maps.Callout || createCallout(maps);
callback(maps);
} else if (callbacks2.length) {
callbacks2.push(callback);
} else {
callbacks2.push(callback);
const globalExt = window;
const callbackName = GOOGLE_MAP_CALLBACKNAME + mapInfo.type;
globalExt[callbackName] = function() {
delete globalExt[callbackName];
maps = getIsAMap() || getIsBMap() ? window[mapInfo.type] : window[mapInfo.type].maps;
maps.Callout = createCallout(maps);
callbacks2.forEach((callback2) => callback2(maps));
callbacks2.length = 0;
};
if (getIsAMap()) {
handleAMapSecurityPolicy(mapInfo);
}
const script = document.createElement("script");
let src = getScriptBaseUrl(mapInfo.type);
if (mapInfo.type === MapType.QQ) {
libraries.push("geometry");
}
if (libraries.length) {
src += `libraries=${libraries.join("%2C")}&`;
}
if (mapInfo.type === MapType.BMAP) {
script.src = `${src}ak=${mapInfo.key}&callback=${callbackName}`;
} else {
script.src = `${src}key=${mapInfo.key}&callback=${callbackName}`;
}
script.onerror = function() {
console.error("Map load failed.");
};
document.body.appendChild(script);
}
}
const getScriptBaseUrl = (mapType) => {
const urlMap = {
qq: "https://map.qq.com/api/js?v=2.exp&",
google: "https://maps.googleapis.com/maps/api/js?",
AMap: "https://webapi.amap.com/maps?v=2.0&",
BMapGL: "https://api.map.baidu.com/api?type=webgl&v=1.0&"
};
return urlMap[mapType];
};
function handleAMapSecurityPolicy(mapInfo) {
window._AMapSecurityConfig = {
securityJsCode: mapInfo.securityJsCode || "",
serviceHost: mapInfo.serviceHost || ""
};
}
const ICON_PATH_ORIGIN = "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 MapType = /* @__PURE__ */ ((MapType2) => {
MapType2["QQ"] = "qq";
MapType2["GOOGLE"] = "google";
MapType2["AMAP"] = "AMap";
MapType2["BMAP"] = "BMapGL";
MapType2["UNKNOWN"] = "";
return MapType2;
})(MapType || {});
function getMapInfo() {
if (__uniConfig.bMapKey) {
return {
type: "BMapGL",
key: __uniConfig.bMapKey
};
}
if (__uniConfig.qqMapKey) {
return {
type: "qq",
key: __uniConfig.qqMapKey
};
}
if (__uniConfig.googleMapKey) {
return {
type: "google",
key: __uniConfig.googleMapKey
};
}
if (__uniConfig.aMapKey) {
return {
type: "AMap",
key: __uniConfig.aMapKey,
securityJsCode: __uniConfig.aMapSecurityJsCode,
serviceHost: __uniConfig.aMapServiceHost
};
}
return {
type: "",
key: ""
};
}
let IS_AMAP = false;
let hasGetIsAMap = false;
const getIsAMap = () => {
if (hasGetIsAMap) {
return IS_AMAP;
} else {
hasGetIsAMap = true;
return IS_AMAP = getMapInfo().type === "AMap";
}
};
const getIsBMap = () => {
return getMapInfo().type === "BMapGL";
};
function translateCoordinateSystem(type, coords, skip) {
const mapInfo = getMapInfo();
const wgs84Map = [
"google"
/* GOOGLE */
];
if (type && type.toUpperCase() === "WGS84" || wgs84Map.includes(mapInfo.type) || skip) {
return Promise.resolve(coords);
}
if (mapInfo.type === "qq") {
return new Promise((resolve) => {
getJSONP(
`https://apis.map.qq.com/ws/coord/v1/translate?type=1&locations=${coords.latitude},${coords.longitude}&key=${mapInfo.key}&output=jsonp`,
{
callback: "callback"
},
(res) => {
if ("locations" in res && res.locations.length) {
const { lng, lat } = res.locations[0];
resolve({
longitude: lng,
latitude: lat,
altitude: coords.altitude,
accuracy: coords.accuracy,
altitudeAccuracy: coords.altitudeAccuracy,
heading: coords.heading,
speed: coords.speed
});
} else {
resolve(coords);
}
},
() => resolve(coords)
);
});
}
if (mapInfo.type === "AMap") {
return new Promise((resolve) => {
loadMaps([], () => {
window.AMap.convertFrom(
[coords.longitude, coords.latitude],
"gps",
(_, res) => {
if (res.info === "ok" && res.locations.length) {
const { lat, lng } = res.locations[0];
resolve({
longitude: lng,
latitude: lat,
altitude: coords.altitude,
accuracy: coords.accuracy,
altitudeAccuracy: coords.altitudeAccuracy,
heading: coords.heading,
speed: coords.speed
});
} else {
resolve(coords);
}
}
);
});
});
}
return Promise.reject(
new Error(
"translate coordinate system faild, map provider not configured or not supported"
)
);
}
const props$5 = {
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: ""
}
};
function useMarkerLabelStyle(id2) {
const className = "uni-map-marker-label-" + id2;
const styleEl = document.createElement("style");
styleEl.id = className;
document.head.appendChild(styleEl);
onUnmounted(() => {
styleEl.remove();
});
return function updateMarkerLabelStyle(style) {
const newStyle = Object.assign({}, style, {
position: "absolute",
top: "70px",
borderStyle: "solid"
});
const div = document.createElement("div");
Object.keys(newStyle).forEach((key) => {
div.style[key] = newStyle[key] || "";
});
styleEl.innerText = `.${className}{${div.getAttribute("style")}}`;
return className;
};
}
const MapMarker = /* @__PURE__ */ defineSystemComponent({
name: "MapMarker",
props: props$5,
setup(props2) {
const id2 = String(!isNaN(Number(props2.id)) ? props2.id : "");
const onMapReady = inject("onMapReady");
const updateMarkerLabelStyle = useMarkerLabelStyle(id2);
let marker;
function removeMarker() {
if (marker) {
if (marker.label && "setMap" in marker.label) {
marker.label.setMap(null);
}
if (marker.callout) {
removeMarkerCallout(marker.callout);
}
marker.setMap(null);
}
}
function removeMarkerCallout(callout) {
if (getIsAMap()) {
callout.removeAMapText();
} else {
callout.setMap(null);
}
}
onMapReady((map, maps2, trigger) => {
function updateMarker(option) {
const title = option.title;
let position;
if (getIsAMap()) {
position = new maps2.LngLat(option.longitude, option.latitude);
} else if (getIsBMap()) {
position = new maps2.Point(option.longitude, option.latitude);
} else {
position = new maps2.LatLng(option.latitude, option.longitude);
}
const img = new Image();
let imgHeight = 0;
img.onload = () => {
const anchor = option.anchor || {};
let icon;
let w;
let h;
let top;
let x = typeof anchor.x === "number" ? anchor.x : 0.5;
let y = typeof anchor.y === "number" ? anchor.y : 1;
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;
}
imgHeight = h;
top = h - (h - y * h);
if ("MarkerImage" in maps2) {
icon = new maps2.MarkerImage(img.src, null, null, new maps2.Point(x * w, y * h), new maps2.Size(w, h));
} else if ("Icon" in maps2) {
icon = new maps2.Icon({
image: img.src,
size: new maps2.Size(w, h),
imageSize: new maps2.Size(w, h),
imageOffset: new maps2.Pixel(x * w, y * h)
});
} else {
icon = {
url: img.src,
anchor: new maps2.Point(x, y),
size: new maps2.Size(w, h)
};
}
if (getIsBMap()) {
marker = new maps2.Marker(new maps2.Point(position.lng, position.lat));
map.addOverlay(marker);
} else {
marker.setPosition(position);
marker.setIcon(icon);
}
if ("setRotation" in marker) {
marker.setRotation(option.rotate || 0);
}
const labelOpt = option.label || {};
if ("label" in marker) {
marker.label.setMap(null);
delete marker.label;
}
let label;
if (labelOpt.content) {
const labelStyle = {
borderColor: labelOpt.borderColor,
borderWidth: (Number(labelOpt.borderWidth) || 0) + "px",
padding: (Number(labelOpt.padding) || 0) + "px",
borderRadius: (Number(labelOpt.borderRadius) || 0) + "px",
backgroundColor: labelOpt.bgColor,
color: labelOpt.color,
fontSize: (labelOpt.fontSize || 14) + "px",
lineHeight: (labelOpt.fontSize || 14) + "px",
marginLeft: (Number(labelOpt.anchorX || labelOpt.x) || 0) + "px",
marginTop: (Number(labelOpt.anchorY || labelOpt.y) || 0) + "px"
};
if ("Label" in maps2) {
label = new maps2.Label({
position,
map,
clickable: false,
content: labelOpt.content,
style: labelStyle
});
marker.label = label;
} else if ("setLabel" in marker) {
if (getIsAMap()) {
const content = `<div style="
margin-left:${labelStyle.marginLeft};
margin-top:${labelStyle.marginTop};
padding:${labelStyle.padding};
background-color:${labelStyle.backgroundColor};
border-radius:${labelStyle.borderRadius};
line-height:${labelStyle.lineHeight};
color:${labelStyle.color};
font-size:${labelStyle.fontSize};
">
${labelOpt.content}
<div>`;
marker.setLabel({
content,
direction: "bottom-right"
});
} else {
const className = updateMarkerLabelStyle(labelStyle);
marker.setLabel({
text: labelOpt.content,
color: labelStyle.color,
fontSize: labelStyle.fontSize,
className
});
}
}
}
const calloutOpt = option.callout || {};
let callout = marker.callout;
let calloutStyle;
if (calloutOpt.content || title) {
if (getIsAMap() && calloutOpt.content) {
calloutOpt.content = calloutOpt.content.replaceAll("\n", "<br/>");
}
const boxShadow = "0px 0px 3px 1px rgba(0,0,0,0.5)";
let offsetY = -imgHeight / 2;
if (option.width || option.height) {
offsetY += 14 - imgHeight / 2;
}
calloutStyle = calloutOpt.content ? {
position,
map,
top,
// handle AMap callout offset
offsetY,
content: calloutOpt.content,
color: calloutOpt.color,
fontSize: calloutOpt.fontSize,
borderRadius: calloutOpt.borderRadius,
bgColor: calloutOpt.bgColor,
padding: calloutOpt.padding,
boxShadow: calloutOpt.boxShadow || boxShadow,
display: calloutOpt.display
} : {
position,
map,
top,
// handle AMap callout offset
offsetY,
content: title,
boxShadow
};
if (callout) {
callout.setOption(calloutStyle);
} else {
if (getIsAMap()) {
const callback = () => {
if (id2 !== "") {
trigger("callouttap", {}, { markerId: Number(id2) });
}
};
callout = marker.callout = new maps2.Callout(calloutStyle, callback);
} 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();
};
if (getMapInfo().type === MapType.GOOGLE) {
callout.div.ontouchstart = function($event) {
$event.stopPropagation();
};
callout.div.onpointerdown = function($event) {
$event.stopPropagation();
};
}
}
}
} else {
if (callout) {
removeMarkerCallout(callout);
delete marker.callout;
}
}
};
if (option.iconPath) {
img.src = getRealPath(option.iconPath);
} else {
console.error("Marker.iconPath is required.");
}
}
function addMarker(props3) {
if (!getIsBMap()) {
marker = new maps2.Marker({
map,
flat: true,
autoRotation: false
});
}
updateMarker(props3);
const MapsEvent = maps2.event || maps2.Event;
if (getIsBMap())
;
else {
MapsEvent.addListener(marker, "click", () => {
const callout = marker.callout;
if (callout && !callout.alwaysVisible) {
if (getIsAMap()) {
callout.visible = !callout.visible;
if (callout.visible) {
marker.callout.createAMapText();
} else {
marker.callout.removeAMapText();
}
} else {
callout.set("visible", !callout.visible);
if (callout.visible) {
const div = callout.div;
const parent = div.parentNode;
parent.removeChild(div);
parent.appendChild(div);
}
}
}
if (id2) {
trigger("markertap", {}, {
markerId: Number(id2),
latitude: props3.latitude,
longitude: props3.longitude
});
}
});
}
}
addMarker(props2);
watch(props2, updateMarker);
});
if (id2) {
const addMapChidlContext = inject("addMapChidlContext");
const removeMapChidlContext = 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;
let rotation = 0;
if ("getRotation" in marker) {
rotation = marker.getRotation();
}
const a = marker.getPosition();
const b = new maps2.LatLng(destination.latitude, destination.longitude);
const distance = maps2.geometry.spherical.computeDistanceBetween(a, b) / 1e3;
const time = (typeof duration === "number" ? duration : 1e3) / (1e3 * 60 * 60);
const speed = distance / time;
const MapsEvent = maps2.event || maps2.Event;
const movingEvent = MapsEvent.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 = MapsEvent.addListener(marker, "moveend", () => {
event.remove();
movingEvent.remove();
marker.lastPosition = a;
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 (isFunction(cb)) {
cb();
}
});
let lastRtate = 0;
if (autoRotate) {
if (marker.lastPosition) {
lastRtate = maps2.geometry.spherical.computeHeading(marker.lastPosition, a);
}
rotate = maps2.geometry.spherical.computeHeading(a, b) - lastRtate;
}
if ("setRotation" in marker) {
marker.setRotation(rotation + rotate);
}
if ("moveTo" in marker) {
marker.moveTo(b, speed);
} else {
marker.setPosition(b);
MapsEvent.trigger(marker, "moveend", {});
}
});
}
};
addMapChidlContext(context);
onUnmounted(() => removeMapChidlContext(context));
}
onUnmounted(removeMarker);
return [];
}
});
const props$4 = {
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: ""
}
};
const MapPolyline = /* @__PURE__ */ defineSystemComponent({
name: "MapPolyline",
props: props$4,
setup(props2) {
const onMapReady = 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) => {
let pointPosition;
if (getIsAMap()) {
pointPosition = [point.longitude, point.latitude];
} else if (getIsBMap()) {
pointPosition = new maps2.Point(point.longitude, point.latitude);
} else {
pointPosition = new maps2.LatLng(point.latitude, point.longitude);
}
path.push(pointPosition);
});
const strokeWeight = Number(option.width) || 1;
const { r: sr, g: sg, b: sb, a: sa } = hexToRgba(option.color);
const { r: br, g: bg, b: bb, a: ba } = hexToRgba(option.borderColor);
const polylineOptions = {
map,
clickable: false,
path,
strokeWeight,
strokeColor: option.color || void 0,
strokeDashStyle: option.dottedLine ? "dash" : "solid"
};
const borderWidth = Number(option.borderWidth) || 0;
const polylineBorderOptions = {
map,
clickable: false,
path,
strokeWeight: strokeWeight + borderWidth * 2,
strokeColor: option.borderColor || void 0,
strokeDashStyle: option.dottedLine ? "dash" : "solid"
};
if ("Color" in maps2) {
polylineOptions.strokeColor = new maps2.Color(sr, sg, sb, sa);
polylineBorderOptions.strokeColor = new maps2.Color(br, bg, bb, ba);
} else {
polylineOptions.strokeColor = `rgb(${sr}, ${sg}, ${sb})`;
polylineOptions.strokeOpacity = sa;
polylineBorderOptions.strokeColor = `rgb(${br}, ${bg}, ${bb})`;
polylineBorderOptions.strokeOpacity = ba;
}
if (borderWidth) {
polylineBorder = new maps2.Polyline(polylineBorderOptions);
}
if (getIsBMap()) {
polyline = new maps2.Polyline(polylineOptions.path, polylineOptions);
map.addOverlay(polyline);
} else {
polyline = new maps2.Polyline(polylineOptions);
}
}
addPolyline(props2);
watch(props2, updatePolyline);
});
onUnmounted(removePolyline);
return [];
}
});
const props$3 = {
latitude: {
type: [Number, String],
require: true
},
longitude: {
type: [Number, String],
require: true
},
color: {
type: String,
default: "#000000"
},
fillColor: {
type: String,
default: "#00000000"
},
radius: {
type: [Number, String],
require: true
},
strokeWidth: {
type: [Number, String],
default: ""
},
level: {
type: String,
default: ""
}
};
const MapCircle = /* @__PURE__ */ defineSystemComponent({
name: "MapCircle",
props: props$3,
setup(props2) {
const onMapReady = 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 = getIsAMap() || getIsBMap() ? [option.longitude, option.latitude] : new maps2.LatLng(option.latitude, option.longitude);
const circleOptions = {
map,
center,
clickable: false,
radius: option.radius,
strokeWeight: Number(option.strokeWidth) || 1,
strokeDashStyle: "solid"
};
if (getIsBMap()) {
circleOptions.strokeColor = option.color;
circleOptions.fillColor = option.fillColor || "#000";
circleOptions.fillOpacity = 1;
} else {
const { r: fr, g: fg, b: fb, a: fa } = hexToRgba(option.fillColor);
const { r: sr, g: sg, b: sb, a: sa } = hexToRgba(option.color);
if ("Color" in maps2) {
circleOptions.fillColor = new maps2.Color(fr, fg, fb, fa);
circleOptions.strokeColor = new maps2.Color(sr, sg, sb, sa);
} else {
circleOptions.fillColor = `rgb(${fr}, ${fg}, ${fb})`;
circleOptions.fillOpacity = fa;
circleOptions.strokeColor = `rgb(${sr}, ${sg}, ${sb})`;
circleOptions.strokeOpacity = sa;
}
}
if (getIsBMap()) {
let pt = new maps2.Point(
// @ts-expect-error
circleOptions.center[0],
// @ts-expect-error
circleOptions.center[1]
);
circle = new maps2.Circle(pt, circleOptions.radius, circleOptions);
map.addOverlay(circle);
} else {
circle = new maps2.Circle(circleOptions);
if (getIsAMap()) {
map.add(circle);
}
}
}
addCircle(props2);
watch(props2, updateCircle);
});
onUnmounted(removeCircle);
return [];
}
});
const _t0$4 = template("<div class=uni-map-control><img class=uni-map-control-icon>", 1);
const props$2 = {
id: {
type: [Number, String],
default: ""
},
position: {
type: Object,
required: true
},
iconPath: {
type: String,
required: true
},
clickable: {
type: [Boolean, String],
default: ""
},
trigger: {
type: Function,
required: true
}
};
const MapControl = /* @__PURE__ */ defineSystemComponent({
name: "MapControl",
props: props$2,
setup(props2) {
const imgPath = computed(() => getRealPath(props2.iconPath));
const positionStyle = computed(() => {
let positionStyle2 = `top:${props2.position.top || 0}px;left:${props2.position.left || 0}px;`;
if (props2.position.width) {
positionStyle2 += `width:${props2.position.width}px;`;
}
if (props2.position.height) {
positionStyle2 += `height:${props2.position.height}px;`;
}
return positionStyle2;
});
const handleClick = ($event) => {
if (props2.clickable) {
props2.trigger("controltap", $event, { controlId: props2.id });
}
};
return () => {
return (() => {
const _n1 = _t0$4();
const _n0 = child(_n1);
on$1(_n0, "click", handleClick);
renderEffect(() => {
setProp(_n0, "src", imgPath.value);
setStyle(_n0, positionStyle.value);
});
return _n1;
})();
};
}
});
const request = /* @__PURE__ */ defineTaskApi(
API_REQUEST,
({
url,
data,
header = {},
method,
dataType: dataType2,
responseType,
enableChunked,
withCredentials,
timeout = __uniConfig.networkTimeout.request,
// @ts-expect-error 内部isUTS参数
isUTS
}, { resolve, reject }) => {
{
timeout = timeout == null ? __uniConfig.networkTimeout.request : timeout;
}
let body = null;
const contentType = normalizeContentType(header);
if (method !== "GET") {
if (isString(data) || 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 (hasOwn(data, key)) {
bodyArray.push(
encodeURIComponent(key) + "=" + encodeURIComponent(data[key])
);
}
}
body = bodyArray.join("&");
} else {
body = data.toString();
}
}
}
let requestTask;
if (!enableChunked) {
const xhr = new XMLHttpRequest();
requestTask = new RequestTask(xhr);
xhr.open(method, url);
for (const key in header) {
if (hasOwn(header, key)) {
xhr.setRequestHeader(key, header[key]);
}
}
const timer = setTimeout(function() {
xhr.onload = xhr.onabort = xhr.onerror = null;
requestTask.abort();
reject("timeout", { errCode: 5 });
}, timeout);
xhr.responseType = responseType;
xhr.onload = function() {
clearTimeout(timer);
const statusCode = xhr.status;
let res = responseType === "text" ? xhr.responseText : xhr.response;
if (responseType === "text") {
res = parseResponseText(res, responseType, dataType2, isUTS);
}
resolve({
data: res,
statusCode,
header: parseHeaders(xhr.getAllResponseHeaders()),
cookies: []
});
};
xhr.onabort = function() {
clearTimeout(timer);
reject("abort", { errCode: 600003 });
};
xhr.onerror = function() {
clearTimeout(timer);
reject(void 0, { errCode: 5 });
};
xhr.withCredentials = withCredentials;
xhr.send(body);
} else {
if (typeof window.fetch === void 0 || typeof window.AbortController === void 0) {
throw new Error(
"fetch or AbortController is not supported in this environment"
);
}
const controller = new AbortController();
const signal = controller.signal;
requestTask = new RequestTask(controller);
const fetchOptions = {
method,
headers: header,
body,
signal,
credentials: withCredentials ? "include" : "same-origin"
};
const timer = setTimeout(function() {
requestTask.abort();
reject("timeout", { errCode: 5 });
}, timeout);
fetchOptions.signal.addEventListener("abort", function() {
clearTimeout(timer);
reject("abort", { errCode: 600003 });
});
window.fetch(url, fetchOptions).then(
(response) => {
const statusCode = response.status;
const header2 = response.headers;
const body2 = response.body;
const headerObj = {};
header2.forEach((value, key) => {
headerObj[key] = value;
});
const cookies = cookiesParse(headerObj);
requestTask._emitter.emit("headersReceived", {
header: headerObj,
statusCode,
cookies
});
if (!body2) {
resolve({
data: "",
statusCode,
header: headerObj,
cookies
});
return;
}
const reader = body2.getReader();
const bodyBuffers = [];
const streamReaderRead = () => {
reader.read().then(({ done, value }) => {
if (done) {
const result = concatArrayBuffers(bodyBuffers);
let res = responseType === "text" ? new TextDecoder().decode(result) : result;
if (responseType === "text") {
res = parseResponseText(res, responseType, dataType2, isUTS);
}
resolve({
data: res,
statusCode,
header: headerObj,
cookies
});
return;
}
const chunk = value;
bodyBuffers.push(chunk);
requestTask._emitter.emit("chunkReceived", {
data: chunk
});
streamReaderRead();
});
};
streamReaderRead();
},
(error) => {
reject(error, { errCode: 5 });
}
);
}
return requestTask;
},
RequestProtocol,
RequestOptions
);
const cookiesParse = (header) => {
let cookiesStr = header["Set-Cookie"] || header["set-cookie"];
let cookiesArr = [];
if (!cookiesStr) {
return [];
}
if (cookiesStr[0] === "[" && cookiesStr[cookiesStr.length - 1] === "]") {
cookiesStr = cookiesStr.slice(1, -1);
}
const handleCookiesArr = cookiesStr.split(";");
for (let i = 0; i < handleCookiesArr.length; i++) {
if (handleCookiesArr[i].indexOf("Expires=") !== -1 || handleCookiesArr[i].indexOf("expires=") !== -1) {
cookiesArr.push(handleCookiesArr[i].replace(",", ""));
} else {
cookiesArr.push(handleCookiesArr[i]);
}
}
cookiesArr = cookiesArr.join(";").split(",");
return cookiesArr;
};
function concatArrayBuffers(buffers) {
const totalLength = buffers.reduce((acc, buf) => acc + buf.byteLength, 0);
const result = new Uint8Array(totalLength);
let offset = 0;
for (const buffer of buffers) {
result.set(new Uint8Array(buffer), offset);
offset += buffer.byteLength;
}
return result.buffer;
}
function normalizeContentType(header) {
const name = Object.keys(header).find(
(name2) => name2.toLowerCase() === "content-type"
);
if (!name) {
return;
}
const contentType = header[name];
if (!contentType) {
return "string";
}
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(controller) {
this._requestOnChunkReceiveCallbackId = 0;
this._requestOnChunkReceiveCallbacks = /* @__PURE__ */ new Map();
this._requestOnHeadersReceiveCallbackId = 0;
this._requestOnHeadersReceiveCallbacks = /* @__PURE__ */ new Map();
this._emitter = new Emitter();
this._controller = controller;
}
abort() {
if (this._controller) {
this._controller.abort();
delete this._controller;
}
}
onHeadersReceived(callback) {
this._emitter.on("headersReceived", callback);
this._requestOnHeadersReceiveCallbackId++;
this._requestOnHeadersReceiveCallbacks.set(
this._requestOnHeadersReceiveCallbackId,
callback
);
return this._requestOnHeadersReceiveCallbackId;
}
offHeadersReceived(callback) {
if (callback == null) {
this._emitter.off("headersReceived");
return;
}
if (typeof callback === "function") {
this._requestOnHeadersReceiveCallbacks.forEach((cb, id2) => {
if (cb === callback) {
this._requestOnHeadersReceiveCallbacks.delete(id2);
this._emitter.off("headersReceived", callback);
}
});
return;
}
const callbackFn = this._requestOnHeadersReceiveCallbacks.get(callback);
if (!callbackFn) {
return;
}
this._requestOnHeadersReceiveCallbacks.delete(callback);
this._emitter.off("headersReceived", callbackFn);
}
onChunkReceived(callback) {
this._emitter.on("chunkReceived", callback);
this._requestOnChunkReceiveCallbackId++;
this._requestOnChunkReceiveCallbacks.set(
this._requestOnChunkReceiveCallbackId,
callback
);
return this._requestOnChunkReceiveCallbackId;
}
offChunkReceived(callback) {
if (callback == null) {
this._emitter.off("chunkReceived");
return;
}
if (typeof callback === "function") {
this._requestOnChunkReceiveCallbacks.forEach((cb, id2) => {
if (cb === callback) {
this._requestOnChunkReceiveCallbacks.delete(id2);
this._emitter.off("chunkReceived", callback);
}
});
return;
}
const callbackFn = this._requestOnChunkReceiveCallbacks.get(callback);
if (!callbackFn) {
return;
}
this._requestOnChunkReceiveCallbacks.delete(callback);
this._emitter.off("chunkReceived", callbackFn);
}
}
function parseHeaders(headers) {
const headersObject = {};
headers.split(LINEFEED).forEach((header) => {
const find = header.match(/(\S+\s*):\s*(.*)/);
if (!find || find.length !== 3) {
return;
}
headersObject[find[1]] = find[2];
});
return headersObject;
}
function parseResponseText(responseText, responseType, dataType2, isUTS) {
let res = responseText;
if (responseType === "text" && dataType2 === "json") {
try {
if (isUTS) {
res = UTS.JSON.parse(res) || res;
} else {
res = JSON.parse(res);
}
} catch (error) {
}
}
return res;
}
const getLocation = /* @__PURE__ */ defineAsyncApi(
API_GET_LOCATION,
({ type, altitude, highAccuracyExpireTime, isHighAccuracy }, { resolve, reject }) => {
const mapInfo = getMapInfo();
new Promise((resolve2, reject2) => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(res) => resolve2({ coords: res.coords }),
reject2,
{
enableHighAccuracy: isHighAccuracy || altitude,
timeout: highAccuracyExpireTime || 1e3 * 100
}
);
} else {
reject2(new Error("device nonsupport geolocation"));
}
}).catch((error) => {
return new Promise(
(resolve2, reject2) => {
if (mapInfo.type === MapType.QQ) {
getJSONP(
`https://apis.map.qq.com/ws/location/v1/ip?output=jsonp&key=${mapInfo.key}`,
{
callback: "callback"
},
(res) => {
if ("result" in res && res.result.location) {
const location2 = res.result.location;
resolve2({
coords: {
latitude: location2.lat,
longitude: location2.lng
},
skip: true
});
} else {
reject2(new Error(res.message || JSON.stringify(res)));
}
},
() => reject2(new Error("network error"))
);
} else if (mapInfo.type === MapType.GOOGLE) {
request({
method: "POST",
url: `https://www.googleapis.com/geolocation/v1/geolocate?key=${mapInfo.key}`,
success(res) {
const data = res.data;
if ("location" in data) {
resolve2({
coords: {
latitude: data.location.lat,
longitude: data.location.lng,
accuracy: data.accuracy
},
skip: true
});
} else {
reject2(
new Error(
data.error && data.error.message || JSON.stringify(res)
)
);
}
},
fail() {
reject2(new Error("network error"));
}
});
} else if (mapInfo.type === MapType.AMAP) {
loadMaps([], () => {
window.AMap.plugin("AMap.Geolocation", () => {
const geolocation = new window.AMap.Geolocation({
enableHighAccuracy: true,
timeout: 1e4
});
geolocation.getCurrentPosition(
(status, data) => {
if (status === "complete") {
resolve2({
coords: {
latitude: data.position.lat,
longitude: data.position.lng,
accuracy: data.accuracy
},
skip: true
});
} else {
reject2(new Error(data.message));
}
}
);
});
});
} else {
reject2(error);
}
}
);
}).then(({ coords, skip }) => {
translateCoordinateSystem(type, coords, skip).then((coords2) => {
resolve({
latitude: coords2.latitude,
longitude: coords2.longitude,
accuracy: coords2.accuracy,
speed: coords2.altitude || 0,
altitude: coords2.altitude || 0,
verticalAccuracy: coords2.altitudeAccuracy || 0,
// 无专门水平精度,使用位置精度替代
horizontalAccuracy: coords2.accuracy || 0
});
}).catch((error) => {
reject(error.message);
});
}).catch((error) => {
reject(error.message || JSON.stringify(error));
});
},
GetLocationProtocol,
GetLocationOptions
);
let listener$1 = null;
const onCompassChange = /* @__PURE__ */ defineOnApi(
API_ON_COMPASS,
() => {
startCompass();
}
);
const offCompassChange = /* @__PURE__ */ defineOffApi(
API_OFF_COMPASS,
() => {
stopCompass();
}
);
const startCompass = /* @__PURE__ */ defineAsyncApi(
API_START_COMPASS,
(_, { resolve, reject }) => {
if (!window.DeviceOrientationEvent) {
reject();
return;
}
function addEventListener() {
listener$1 = function(event) {
const direction2 = 360 - (event.alpha !== null ? event.alpha : 360);
UniServiceJSBridge.invokeOnCallback(API_ON_COMPASS, {
direction: direction2
});
};
window.addEventListener("deviceorientation", listener$1, false);
}
if (!listener$1) {
if (DeviceOrientationEvent.requestPermission) {
DeviceOrientationEvent.requestPermission().then((res) => {
if (res === "granted") {
addEventListener();
resolve();
} else {
reject(`${res}`);
}
}).catch((error) => {
reject(`${error}`);
});
return;
}
addEventListener();
}
resolve();
}
);
const stopCompass = /* @__PURE__ */ defineAsyncApi(
API_STOP_COMPASS,
(_, { resolve }) => {
if (listener$1) {
window.removeEventListener("deviceorientation", listener$1, false);
listener$1 = null;
}
resolve();
}
);
const CONTEXT_ID = "MAP_LOCATION";
const MapLocation = /* @__PURE__ */ defineSystemComponent({
name: "MapLocation",
setup() {
const state = reactive({
latitude: 0,
longitude: 0,
rotate: 0
});
{
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);
}
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));
}
return () => {
return state.latitude ? (() => {
const _n0 = createComponent(MapMarker, {
anchor: {
x: 0.5,
y: 0.5
},
width: "44",
height: "44",
iconPath: () => ICON_PATH_ORIGIN,
$: [() => state]
}, null, true);
return _n0;
})() : null;
};
}
});
const props$1 = {
// 边框虚线,腾讯地图支持,google 高德 地图不支持,默认值为[0, 0] 为实线,非 [0, 0] 为虚线,H5 端无法像微信小程序一样控制虚线的间隔像素大小
dashArray: {
type: Array,
default: () => [0, 0]
},
// 经纬度数组,[{latitude: 0, longitude: 0}]
points: {
type: Array,
required: true
},
// 描边的宽度
strokeWidth: {
type: Number,
default: 1
},
// 描边的颜色,十六进制
strokeColor: {
type: String,
default: "#000000"
},
// 填充颜色,十六进制
fillColor: {
type: String,
default: "#00000000"
},
// 设置多边形 Z 轴数值
zIndex: {
type: Number,
default: 0
}
};
const MapPolygon = /* @__PURE__ */ defineSystemComponent({
name: "MapPolygon",
props: props$1,
setup(props2) {
let polygonIns;
const onMapReady = inject("onMapReady");
onMapReady((map, maps2, trigger) => {
function drawPolygon() {
const { points, strokeWidth, strokeColor, dashArray, fillColor, zIndex } = props2;
const path = points.map((item) => {
const { latitude, longitude } = item;
if (getIsAMap()) {
return [longitude, latitude];
} else if (getIsBMap()) {
return new maps2.Point(longitude, latitude);
} else {
return new maps2.LatLng(latitude, longitude);
}
});
const { r: fcR, g: fcG, b: fcB, a: fcA } = hexToRgba(fillColor);
const { r: scR, g: scG, b: scB, a: scA } = hexToRgba(strokeColor);
const polygonOptions = {
//多边形是否可点击。
clickable: true,
//鼠标在多边形内的光标样式。
cursor: "crosshair",
//多边形是否可编辑。
editable: false,
// 地图实例,即要显示多边形的地图
// @ts-expect-error
map,
// 区域填充色
fillColor: "",
//多边形的路径,以经纬度坐标数组构成。
path,
// 区域边框
strokeColor: "",
//多边形的边框样式。实线是solid,虚线是dash。
strokeDashStyle: dashArray.some((item) => item > 0) ? "dash" : "solid",
//多边形的边框线宽。
strokeWeight: strokeWidth,
//多边形是否可见。
visible: true,
//多边形的zIndex值。
zIndex
};
if (maps2.Color) {
polygonOptions.fillColor = new maps2.Color(fcR, fcG, fcB, fcA);
polygonOptions.strokeColor = new maps2.Color(scR, scG, scB, scA);
} else {
polygonOptions.fillColor = `rgb(${fcR}, ${fcG}, ${fcB})`;
polygonOptions.fillOpacity = fcA;
polygonOptions.strokeColor = `rgb(${scR}, ${scG}, ${scB})`;
polygonOptions.strokeOpacity = scA;
}
if (polygonIns) {
polygonIns.setOptions(polygonOptions);
return;
}
if (getIsBMap()) {
polygonIns = new maps2.Polygon(polygonOptions.path, polygonOptions);
map.addOverlay(polygonIns);
} else {
polygonIns = new maps2.Polygon(polygonOptions);
}
}
drawPolygon();
watch(props2, drawPolygon);
});
onUnmounted(() => {
polygonIns == null ? void 0 : polygonIns.setMap(null);
});
return [];
}
});
const mapProps = {
id: {
type: String,
default: ""
},
latitude: {
type: [String, Number],
default: 0
},
longitude: {
type: [String, Number],
default: 0
},
scale: {
type: [String, Number],
default: 16
},
markers: {
type: Array,
default() {
return [];
}
},
includePoints: {
type: Array,
default() {
return [];
}
},
polyline: {
type: Array,
default() {
return [];
}
},
circles: {
type: Array,
default() {
return [];
}
},
controls: {
type: Array,
default() {
return [];
}
},
showLocation: {
type: [Boolean, String],
default: false
},
libraries: {
type: Array,
default() {
return [];
}
},
polygons: {
type: Array,
default: () => []
}
};
function getPoints(points) {
const newPoints = [];
if (isArray(points)) {
points.forEach((point) => {
if (point && point.latitude && point.longitude) {
newPoints.push({
latitude: point.latitude,
longitude: point.longitude
});
}
});
}
return newPoints;
}
function getAMapPosition(maps2, latitude, longitude) {
return new maps2.LngLat(longitude, latitude);
}
function getBMapPosition(maps2, latitude, longitude) {
return new maps2.Point(longitude, latitude);
}
function getGoogleOrQQMapPosition(maps2, latitude, longitude) {
return new maps2.LatLng(latitude, longitude);
}
function getMapPosition(maps2, latitude, longitude) {
if (getIsBMap()) {
return getBMapPosition(maps2, latitude, longitude);
} else if (getIsAMap()) {
return getAMapPosition(maps2, latitude, longitude);
} else {
return getGoogleOrQQMapPosition(
maps2,
latitude,
longitude
);
}
}
function getLat(latLng) {
if ("getLat" in latLng) {
return latLng.getLat();
} else {
if (getIsBMap()) {
return latLng.lat;
}
return latLng.lat();
}
}
function getLng(latLng) {
if ("getLng" in latLng) {
return latLng.getLng();
} else {
if (getIsBMap()) {
return latLng.lng;
}
return latLng.lng();
}
}
function useMap(props2, rootRef, emit2) {
const trigger = useCustomEvent(rootRef, emit2);
const mapRef = ref(null);
let maps2;
let map;
const state = reactive({
latitude: Number(props2.latitude),
longitude: Number(props2.longitude),
includePoints: getPoints(props2.includePoints)
});
const onMapReadyCallbacks = [];
let isMapReady;
function onMapReady(callback) {
if (isMapReady) {
callback(map, maps2, trigger);
} else {
onMapReadyCallbacks.push(callback);
}
}
function emitMapReady() {
isMapReady = true;
onMapReadyCallbacks.forEach((callback) => callback(map, maps2, trigger));
onMapReadyCallbacks.length = 0;
}
let isBoundsReady;
const onBoundsReadyCallbacks = [];
function onBoundsReady(callback) {
if (isBoundsReady) {
callback();
} else {
onMapReadyCallbacks.push(callback);
}
}
const contexts = {};
function addMapChidlContext(context) {
contexts[context.id] = context;
}
function removeMapChidlContext(context) {
delete contexts[context.id];
}
watch(
[() => props2.latitude, () => props2.longitude],
([latitudeVlaue, longitudeVlaue]) => {
const latitude = Number(latitudeVlaue);
const longitude = Number(longitudeVlaue);
if (latitude !== state.latitude || longitude !== state.longitude) {
state.latitude = latitude;
state.longitude = longitude;
if (map) {
const centerPosition = getMapPosition(
maps2,
state.latitude,
state.longitude
);
map.setCenter(centerPosition);
}
}
}
);
watch(
() => props2.includePoints,
(points) => {
state.includePoints = getPoints(points);
if (isBoundsReady) {
updateBounds();
}
},
{
deep: true
}
);
function emitBoundsReady() {
isBoundsReady = true;
onBoundsReadyCallbacks.forEach((callback) => callback());
onBoundsReadyCallbacks.length = 0;
}
function getMapInfo2() {
const center = map.getCenter();
return {
scale: map.getZoom(),
centerLocation: {
latitude: getLat(center),
longitude: getLng(center)
}
};
}
function updateCenter() {
const centerPosition = getMapPosition(maps2, state.latitude, state.longitude);
map.setCenter(centerPosition);
}
function updateBounds() {
if (getIsAMap()) {
const points = [];
state.includePoints.forEach((point) => {
points.push([point.longitude, point.latitude]);
});
const bounds = new maps2.Bounds(...points);
map.setBounds(bounds);
} else if (getIsBMap())
;
else {
const bounds = new maps2.LatLngBounds();
state.includePoints.forEach(({ latitude, longitude }) => {
const latLng = new maps2.LatLng(
latitude,
longitude
);
bounds.extend(latLng);
});
map.fitBounds(bounds);
}
}
function initMap() {
const mapEl = mapRef.value;
const center = getMapPosition(maps2, state.latitude, state.longitude);
const event = maps2.event || maps2.Event;
const map2 = new maps2.Map(mapEl, {
center,
zoom: Number(props2.scale),
// scrollwheel: false,
disableDoubleClickZoom: true,
mapTypeControl: false,
zoomControl: false,
scaleControl: false,
panControl: false,
fullscreenControl: false,
streetViewControl: false,
keyboardShortcuts: false,
minZoom: 5,
maxZoom: 18,
draggable: true
});
if (getIsBMap()) {
map2.centerAndZoom(center, Number(props2.scale));
map2.enableScrollWheelZoom();
map2._printLog && map2._printLog("uniapp");
}
watch(
() => props2.scale,
(scale) => {
map2.setZoom(Number(scale) || 16);
}
);
onBoundsReady(() => {
if (state.includePoints.length) {
updateBounds();
updateCenter();
}
});
if (getIsBMap()) {
map2.addEventListener("click", () => {
trigger("tap", {}, {});
trigger("click", {}, {});
});
map2.addEventListener("dragstart", () => {
trigger("regionchange", {}, {
type: "begin",
causedBy: "gesture"
});
});
map2.addEventListener("dragend", () => {
trigger(
"regionchange",
{},
extend(
{
type: "end",
causedBy: "drag"
},
getMapInfo2()
)
);
});
} else {
const boundsChangedEvent = event.addListener(
map2,
"bounds_changed",
() => {
boundsChangedEvent.remove();
emitBoundsReady();
}
);
event.addListener(map2, "complete", () => {
emitBoundsReady();
});
event.addListener(map2, "click", () => {
trigger("tap", {}, {});
trigger("click", {}, {});
});
event.addListener(map2, "dragstart", () => {
trigger("regionchange", {}, {
type: "begin",
causedBy: "gesture"
});
});
event.addListener(map2, "dragend", () => {
trigger(
"regionchange",
{},
extend(
{
type: "end",
causedBy: "drag"
},
getMapInfo2()
)
);
});
const zoomChangedCallback = () => {
emit2("update:scale", map2.getZoom());
trigger(
"regionchange",
{},
extend(
{
type: "end",
causedBy: "scale"
},
getMapInfo2()
)
);
};
event.addListener(map2, "zoom_changed", zoomChangedCallback);
event.addListener(map2, "zoomend", zoomChangedCallback);
event.addListener(map2, "center_changed", () => {
const center2 = map2.getCenter();
const latitude = getLat(center2);
const longitude = getLng(center2);
emit2("update:latitude", latitude);
emit2("update:longitude", longitude);
});
}
return map2;
}
try {
const id2 = useContextInfo();
useSubscribe(
(type, data = {}) => {
switch (type) {
case "getCenterLocation":
onMapReady(() => {
const center = map.getCenter();
callOptions(data, {
latitude: getLat(center),
longitude: getLng(center),
errMsg: `${type}:ok`
});
});
break;
case "moveToLocation":
{
let latitude = Number(data.latitude);
let longitude = Number(data.longitude);
if (!latitude || !longitude) {
const context = contexts[CONTEXT_ID];
if (context) {
latitude = context.state.latitude;
longitude = context.state.longitude;
}
}
if (latitude && longitude) {
state.latitude = latitude;
state.longitude = longitude;
if (map) {
const centerPosition = getMapPosition(
maps2,
latitude,
longitude
);
map.setCenter(centerPosition);
}
onMapReady(() => {
callOptions(data, `${type}:ok`);
});
} else {
callOptions(data, `${type}:fail`);
}
}
break;
case "translateMarker":
onMapReady(() => {
const context = contexts[data.markerId];
if (context) {
try {
context.translate(data);
} catch (error) {
callOptions(data, `${type}:fail ${error.message}`);
}
callOptions(data, `${type}:ok`);
} else {
callOptions(data, `${type}:fail not found`);
}
});
break;
case "includePoints":
state.includePoints = getPoints(data.includePoints);
if (isBoundsReady || getIsAMap()) {
updateBounds();
}
onBoundsReady(() => {
callOptions(data, `${type}:ok`);
});
break;
case "getRegion":
onBoundsReady(() => {
const latLngBounds = map.getBounds();
const southwest = latLngBounds.getSouthWest();
const northeast = latLngBounds.getNorthEast();
callOptions(data, {
southwest: {
latitude: getLat(southwest),
longitude: getLng(southwest)
},
northeast: {
latitude: getLat(northeast),
longitude: getLng(northeast)
},
errMsg: `${type}:ok`
});
});
break;
case "getScale":
onMapReady(() => {
callOptions(data, {
scale: map.getZoom(),
errMsg: `${type}:ok`
});
});
break;
}
},
id2,
true
);
} catch (error) {
}
onMounted(() => {
loadMaps(props2.libraries, (result) => {
maps2 = result;
map = initMap();
emitMapReady();
trigger("updated", {}, {});
});
});
provide("onMapReady", onMapReady);
provide("addMapChidlContext", addMapChidlContext);
provide("removeMapChidlContext", removeMapChidlContext);
return {
state,
mapRef,
trigger
};
}
const mapEmits = [
"markertap",
"labeltap",
"callouttap",
"controltap",
"regionchange",
"tap",
"click",
"updated",
"update:scale",
"update:latitude",
"update:longitude"
];
const _t0$3 = template('<div uni-map uni-view><div style="width: 100%; height: 100%; position: relative; overflow: hidden"></div> <div style="position: absolute;top: 0;width: 100%;height: 100%;overflow: hidden;pointer-events: none;"> ', 1);
class UniMapElement extends UniViewElement {
static [Symbol.hasInstance](value) {
return this === UniMapElement && value instanceof UniViewElement && value.hasAttribute("uni-map") || Function.prototype[Symbol.hasInstance].call(this, value);
}
}
const uniTagName$1 = { value: "MAP" };
const __syscom_0 = /* @__PURE__ */ defineBuiltInComponent({
name: "Map",
props: mapProps,
emits: mapEmits,
rootElement: {
name: "uni-map",
class: UniMapElement
},
setup(props2, { emit: emit2, slots }) {
const rootRef = ref(null);
const { mapRef, trigger } = useMap(props2, rootRef, emit2);
const root = (() => {
const _setTemplateRef = createTemplateRefSetter();
const _n3 = _t0$3();
const _n0 = child(_n3);
const _n1 = next(_n0, true);
const _n2 = next(_n1);
setNodes(_n1, () => props2.markers.map((item) => (() => {
const _n02 = createKeyedFragment(() => item.id, () => {
const _n22 = createComponent(MapMarker, { $: [() => item] }, null, true);
return _n22;
});
return _n02;
})()), () => props2.polyline.map((item) => (() => {
const _n02 = createComponent(MapPolyline, { $: [() => item] }, null, true);
return _n02;
})()), () => props2.circles.map((item) => (() => {
const _n02 = createComponent(MapCircle, { $: [() => item] }, null, true);
return _n02;
})()), () => props2.controls.map((item) => (() => {
const _n02 = createComponent(MapControl, { $: [() => item, { trigger: () => trigger }] }, null, true);
return _n02;
})()), () => props2.showLocation && (() => {
const _n02 = createComponent(MapLocation, null, null, true);
return _n02;
})(), () => props2.polygons.map((item) => (() => {
const _n02 = createComponent(MapPolygon, { $: [() => item] }, null, true);
return _n02;
})()));
const _x2 = txt(_n2);
setNodes(_x2, () => slots.default && slots.default());
renderEffect(() => {
setProp(_n3, "id", props2.id);
_setTemplateRef(_n0, mapRef);
_setTemplateRef(_n3, rootRef);
});
return _n3;
})();
Object.defineProperty(root, "uniTagName", uniTagName$1);
return root;
}
});
const _AdConfig = class _AdConfig {
constructor() {
this._adConfig = null;
this._isLoading = false;
this._callbacks = [];
this._configLast = 0;
}
static get instance() {
if (!_AdConfig._instance) {
_AdConfig._instance = new _AdConfig();
_AdConfig._instance._init();
}
return _AdConfig._instance;
}
get adConfig() {
return this._adConfig;
}
get isExpired() {
if (this._adConfig == null) {
return true;
}
if (!this._configLast) {
return true;
}
return Math.abs(Date.now() - this._configLast) > _AdConfig.CACHE_TIME;
}
_init() {
var config = this._getConfig();
if (config === null || !config.last) {
return;
}
if (Math.abs(Date.now() - config.last) <= _AdConfig.CACHE_TIME) {
this._adConfig = config.data;
this._configLast = config.last;
}
}
get(adpid, success, fail) {
_AdConfig.IC++;
if (this._adConfig != null) {
this._doCallback(adpid, success, fail);
if (this.isExpired) {
this._loadAdConfig(adpid);
}
return;
}
this._callbacks.push({
adpid,
success,
fail
});
this._loadAdConfig(adpid);
}
_doCallback(adpid, success, fail) {
_AdConfig.IS++;
var { a, b } = this._adConfig;
const adData = a[adpid];
if (adData) {
success(b, Array.isArray(adData) ? adData : [adData]);
} else {
fail(_AdConfig.ERROR_INVALID_ADPID);
}
}
_loadAdConfig(adpid) {
if (this._isLoading === true) {
return;
}
this._isLoading = true;
const appid = typeof __uniConfig !== "undefined" ? __uniConfig.appId ?? "" : "";
uni.request({
url: _AdConfig.URL,
method: "GET",
timeout: 8e3,
data: {
d: location.hostname,
a: adpid,
appid
},
dataType: "json",
success: (res) => {
const rd = res.data;
if (rd.ret === 0) {
const data = rd.data;
this._adConfig = data;
this._configLast = Date.now();
this._setConfig(data);
this._callbacks.forEach(({ adpid: adpid2, success, fail }) => {
this._doCallback(adpid2, success, fail);
});
} else {
this._callbacks.forEach((i) => {
i.fail({ errCode: rd.ret, errMsg: rd.msg });
});
}
this._callbacks = [];
},
fail: (err) => {
this._callbacks.forEach((i) => {
i.fail(err);
});
this._callbacks = [];
},
complete: (c) => {
this._isLoading = false;
}
});
}
_getConfig() {
if (!navigator.cookieEnabled || !window.localStorage) {
return null;
}
var data = localStorage.getItem(_AdConfig.KEY);
return data ? JSON.parse(data) : null;
}
_setConfig(data) {
if (!navigator.cookieEnabled || !window.localStorage) {
return null;
}
localStorage.setItem(
_AdConfig.KEY,
JSON.stringify({
last: Date.now(),
data
})
);
}
};
_AdConfig.IC = 0;
_AdConfig.IS = 0;
_AdConfig.URL = "https://hac1.dcloud.net.cn/ah5v2";
_AdConfig.KEY = "uni_app_ad_config";
_AdConfig.CACHE_TIME = 1e3 * 60 * 10;
_AdConfig.ERROR_INVALID_ADPID = {
"-5002": "invalid adpid"
};
let AdConfig = _AdConfig;
const _AdReport = class _AdReport {
static get instance() {
if (!_AdReport._instance) {
_AdReport._instance = new _AdReport();
}
return _AdReport._instance;
}
constructor() {
var config = this._getConfig();
if (config && config.guid) {
this._guid = config.guid;
return;
}
this._guid = this._newGUID();
this._setConfig(this._guid);
}
get(data) {
this._process(
Object.assign(data, {
d: location.hostname,
i: this._guid
})
);
}
_process(data) {
uni.request({
url: _AdReport.URL,
method: "GET",
data,
dataType: "json",
success: () => {
}
});
}
_newGUID() {
let guid = "";
const format = "xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx";
for (let i = 0; i < format.length; i++) {
if (format[i] === "x") {
guid += (Math.random() * 16 | 0).toString(16);
} else {
guid += format[i];
}
}
return guid.toUpperCase();
}
_getConfig() {
if (!navigator.cookieEnabled || !window.localStorage) {
return null;
}
var data = localStorage.getItem(_AdReport.KEY);
return data ? JSON.parse(data) : null;
}
_setConfig(guid) {
if (!navigator.cookieEnabled || !window.localStorage) {
return null;
}
localStorage.setItem(
_AdReport.KEY,
JSON.stringify({
last: Date.now(),
guid
})
);
}
};
_AdReport.URL = "https://has1.dcloud.net.cn/ahl";
_AdReport.KEY = "uni_app_ad_guid";
let AdReport = _AdReport;
class AdScript {
static get instance() {
if (!AdScript._instance) {
AdScript._instance = new AdScript();
}
return AdScript._instance;
}
constructor() {
this._callback = {};
this._cache = {};
}
load(data, success, fail) {
const provider = data.provider;
if (this._cache[provider] === void 0) {
this.loadScript(data);
}
if (this._cache[provider] === 1) {
success();
} else {
if (!this._callback[provider]) {
this._callback[provider] = [];
}
this._callback[provider].push({
success,
fail
});
}
}
loadScript(data) {
const provider = data.provider;
this._cache[provider] = 0;
const domid = "uniad_provider" + provider;
const adScriptDom = document.getElementById(domid);
const src = adScriptDom && adScriptDom.getAttribute("src");
if (src) {
this._cache[provider] = 1;
return;
}
var ads = document.createElement("script");
ads.setAttribute("id", domid);
const script = data.script;
for (const var1 in script) {
ads.setAttribute(var1, script[var1]);
}
ads.onload = () => {
this._cache[provider] = 1;
this._callback[provider].forEach(({ success }) => {
success();
});
this._callback[provider].length = 0;
};
ads.onerror = (err) => {
this._cache[provider] = void 0;
this._callback[provider].forEach(({ fail }) => {
fail(err);
});
this._callback[provider].length = 0;
};
document.body.append(ads);
}
}
const CHECK_RENDER_DELAY = 1e3;
const CHECK_RENDER_RETRY = 5;
const AD_PROVIDER = {
GDT: "2",
TUIA: "10035"
};
class AdRender {
constructor(props2, trigger, rootRef, options) {
this._pi = 0;
this._pl = [];
this._b = {};
this._checkTimerCount = 0;
this._currentChannel = null;
this._tuiaData = null;
this._checkTimer = null;
this._adpid = props2.adpid;
this._adpidWidescreen = props2.adpidWidescreen;
this._widescreenWidth = props2.widescreenWidth;
this._trigger = trigger;
this._rootRef = rootRef;
this._currentAdpid = this._adpid;
this._hasCustomTuiaMaterial = options.hasCustomTuiaMaterial;
this._setCustomTuiaVisible = options.setCustomTuiaVisible;
}
renderTuiaFromCustomMaterial() {
if (!this._tuiaData) {
return;
}
this._renderTuia(this._tuiaData);
}
get isWidescreen() {
return this._rootRef.value && this._rootRef.value.clientWidth > this._widescreenWidth;
}
load(adpid) {
this._currentAdpid = adpid || (this.isWidescreen ? this._adpidWidescreen : this._adpid);
this._reset();
AdConfig.instance.get(
this._currentAdpid,
(b, a) => {
this._b = b;
this._pl = a;
this._renderAd();
},
(err) => {
this._trigger("error", {}, err);
}
);
}
dispose() {
this._clearCheckTimer();
if (this._rootRef.value) {
this._rootRef.value.innerHTML = "";
}
}
_renderAd() {
if (this._pi > this._pl.length - 1) {
return;
}
const data = this._pl[this._pi];
if (!data) {
this._renderNext();
return;
}
const providerId = String(data.a1);
const providerConfig = this._b[providerId];
if (!providerConfig) {
this._renderNext();
return;
}
const script = providerConfig.script || providerConfig.s;
this._currentChannel = providerId;
const id2 = this._randomId();
this._createView(id2);
if (providerId === AD_PROVIDER.GDT) {
window.TencentGDT = window.TencentGDT || [];
AdScript.instance.load(
{ provider: providerId, script },
() => {
this._renderGdt(id2, data);
},
(err) => {
this._trigger("error", {}, err);
this._renderNext();
}
);
return;
}
if (providerId === AD_PROVIDER.TUIA) {
AdScript.instance.load(
{ provider: providerId, script },
() => {
this._renderTuiaMaterial(id2, data);
},
(err) => {
this._trigger("error", {}, err);
this._renderNext();
}
);
return;
}
this._renderNext();
}
_createView(id2) {
if (!this._rootRef.value) {
return null;
}
var adView = document.createElement("div");
adView.setAttribute("id", id2);
adView.setAttribute("class", id2);
this._rootRef.value.innerHTML = "";
this._rootRef.value.append(adView);
return adView;
}
_renderGdt(id2, data) {
window.TencentGDT.push({
placement_id: data.a3,
app_id: data.a2,
type: "native",
count: 1,
onComplete: (res) => {
if (res && res.constructor === Array && res.length > 0) {
window.TencentGDT.NATIVE.renderAd(res[0], id2);
this._trigger("load", {}, {});
} else {
this._trigger(
"error",
{},
res || { errMsg: "No advertisement" }
);
this._renderNext();
}
}
});
this._startCheckTimer();
}
_renderTuiaMaterial(id2, data) {
const adView = document.getElementById(id2);
if (!adView) {
this._trigger("error", {}, { errMsg: "Invalid ad container" });
this._renderNext();
return;
}
this._tuiaData = data;
if (this._hasCustomTuiaMaterial()) {
adView.innerHTML = "";
let resolved = false;
this._setCustomTuiaVisible(true, (hasContent2) => {
if (resolved)
return;
resolved = true;
if (hasContent2) {
this.report(40, this._currentChannel || void 0);
this._trigger("load", {}, {});
} else {
this._renderTuiaDefaultMaterial(adView, data);
}
});
return;
}
this._renderTuiaDefaultMaterial(adView, data);
}
_renderTuiaDefaultMaterial(adView, data) {
this._setCustomTuiaVisible(false);
const materialSrc = this._getRandomTuiaMaterial(data == null ? void 0 : data.imgs, data == null ? void 0 : data.img);
if (!materialSrc) {
this._trigger("error", {}, {
errMsg: "Invalid tuia material imgs/img"
});
this._renderNext();
return;
}
const img = document.createElement("img");
img.src = materialSrc;
img.onerror = () => {
this._trigger("error", {}, { errMsg: "Tuia material load fail" });
this._renderNext();
};
img.alt = "ad";
img.setAttribute("draggable", "false");
img.style.width = "100%";
img.style.height = "auto";
img.style.display = "block";
img.style.cursor = "pointer";
img.onclick = () => {
this._renderTuia(data);
};
adView.innerHTML = "";
adView.append(img);
this.report(40, this._currentChannel || void 0);
this._trigger("load", {}, {});
}
_getRandomTuiaMaterial(imgs, img) {
if (Array.isArray(imgs)) {
const list2 = imgs.filter((item) => typeof item === "string" && item);
if (list2.length) {
const index2 = Math.floor(Math.random() * list2.length);
return list2[index2];
}
}
if (typeof img === "string") {
return img;
}
return "";
}
_renderTuia(data) {
this._setCustomTuiaVisible(false);
const tuia = window.TuiaSDKLite;
if (!tuia || typeof tuia.execute !== "function") {
this._trigger("error", {}, { errMsg: "Invalid TuiaSDKLite" });
this._renderNext();
return;
}
tuia.execute({
data: {
pid: data.a3,
fail_message: "ad load fail",
product_name: document.title || location.hostname
},
success: (res) => {
this._trigger("load", {}, res || {});
},
fail: (err) => {
this._trigger(
"error",
{},
err || { errMsg: "TuiaSDKLite execute fail" }
);
this._renderNext();
}
});
}
_renderAdView(provider, data) {
var randomId = this._randomId();
var adView = document.createElement("div");
adView.setAttribute("class", randomId);
this._rootRef.value.innerHTML = "";
this._rootRef.value.append(adView);
const scriptPath = provider.s || provider.script;
if (!scriptPath || typeof scriptPath !== "string") {
this._trigger("error", {}, { errMsg: "Invalid provider script" });
this._renderNext();
return;
}
try {
let bindThis = window;
const fn = scriptPath.split(".").reduce((total, currentValue) => {
bindThis = total;
return total[currentValue];
}, window);
fn.bind(bindThis)(data.a2, randomId, 2);
} catch (err) {
this._trigger("error", {}, err);
this._renderNext();
return;
}
this._startCheckTimer();
}
_renderNext() {
if (this._pi >= this._pl.length - 1) {
return;
}
this._pi++;
this._renderAd();
}
_checkRender() {
if (!this._rootRef.value) {
return false;
}
var hasContent2 = this._rootRef.value.children.length > 0 && this._rootRef.value.clientHeight > 40;
if (hasContent2) {
this.report(40, this._currentChannel || void 0);
}
return hasContent2;
}
_startCheckTimer() {
this._clearCheckTimer();
this._checkTimer = setInterval(() => {
this._checkTimerCount++;
if (this._checkTimerCount >= CHECK_RENDER_RETRY) {
this._clearCheckTimer();
this._renderNext();
return;
}
if (this._checkRender()) {
this._clearCheckTimer();
}
}, CHECK_RENDER_DELAY);
}
_clearCheckTimer() {
this._checkTimerCount = 0;
if (this._checkTimer != null) {
window.clearInterval(this._checkTimer);
this._checkTimer = null;
}
}
report(type, currentChannel) {
const compilerVersion = typeof __uniConfig !== "undefined" ? __uniConfig.compilerVersion ?? "" : "";
const reportData = {
h: compilerVersion,
a: this._currentAdpid,
at: type
};
if (currentChannel) {
reportData.t = currentChannel;
}
AdReport.instance.get(reportData);
}
_randomId() {
var result = "";
for (let i = 0; i < 4; i++) {
result += (65536 * (1 + Math.random()) | 0).toString(16).substring(1);
}
return "_u" + result;
}
_reset() {
this._b = {};
this._pl = [];
this._pi = 0;
this._tuiaData = null;
this._setCustomTuiaVisible(false);
this._clearCheckTimer();
if (this._rootRef.value) {
this._rootRef.value.innerHTML = "";
}
}
}
const DEFAULT_WIDESCREEN_WIDTH = 750;
const adProps = {
adpid: {
type: String,
default: ""
},
adpidWidescreen: {
type: String,
default: ""
},
widescreenWidth: {
type: Number,
default: DEFAULT_WIDESCREEN_WIDTH
}
};
function useAd(props2, emit2, hasCustomTuiaMaterial) {
const rootRef = ref(null);
const customTuiaVisible = ref(
false
);
const { $excludeAttrs, $listeners } = useAttrs({
excludeListeners: true
});
const trigger = useCustomEvent(rootRef, emit2);
const ad = new AdRender(props2, trigger, rootRef, {
hasCustomTuiaMaterial,
setCustomTuiaVisible: (visible, onRendered) => {
customTuiaVisible.value = visible ? onRendered : false;
}
});
watch(
() => props2.adpid,
(val) => {
ad.load(val);
}
);
watch(
() => props2.adpidWidescreen,
(val) => {
ad.load(val);
}
);
onMounted(() => {
const compilerVersion = typeof __uniConfig !== "undefined" ? __uniConfig.compilerVersion ?? "" : "";
ad.load(null);
AdReport.instance.get({
h: compilerVersion,
a: props2.adpid,
at: -3,
ic: AdConfig.IC,
is: AdConfig.IS
});
});
onBeforeUnmount(() => {
ad.dispose();
});
return { rootRef, customTuiaVisible, $excludeAttrs, $listeners, ad };
}
const _t0$2 = template("<div class=uni-ad-custom-material> ");
const _t1$1 = template("<div><div class=uni-ad-container></div>", 1);
const uniTagName = { value: "AD" };
const indexVapor = /* @__PURE__ */ defineBuiltInComponent({
inheritAttrs: false,
name: "Ad",
props: adProps,
setup(props2, { emit: emit2, slots }) {
const { rootRef, customTuiaVisible, $excludeAttrs, $listeners, ad } = useAd(
props2,
emit2,
// Vapor 插槽会直接创建节点,只判断是否声明,不为探测而提前执行插槽。
() => Boolean(slots.default)
);
let pendingMaterial;
const confirmMaterial = () => {
const pending = pendingMaterial;
pendingMaterial = void 0;
if (pending && rootRef.value && customTuiaVisible.value === pending.onRendered) {
pending.onRendered(pending.hasContent);
}
};
const renderCustomMaterial = () => {
var _a;
const onRendered = customTuiaVisible.value;
if (typeof onRendered !== "function")
return null;
const content = (_a = slots.default) == null ? void 0 : _a.call(slots);
pendingMaterial = {
onRendered,
hasContent: Boolean(content) && (!Array.isArray(content) || content.length > 0)
};
queuePostFlushCb(confirmMaterial);
return content;
};
const root = (() => {
const _setTemplateRef = createTemplateRefSetter();
const _n6 = _t1$1();
const _n0 = child(_n6);
on$1(_n0, "click", () => ad.report(41));
renderEffect(() => {
setDynamicProps(_n6, [
{
"uni-ad": "",
"uni-view": ""
},
$listeners.value,
$excludeAttrs.value,
{
adpid: props2.adpid,
adpidWidescreen: props2.adpidWidescreen,
widescreenWidth: props2.widescreenWidth
}
]);
_setTemplateRef(_n0, rootRef);
});
setInsertionState(_n6, 1);
createIf(() => customTuiaVisible.value, () => {
const _n3 = _t0$2();
on$1(_n3, "click", () => ad.renderTuiaFromCustomMaterial());
const _x3 = txt(_n3);
setNodes(_x3, () => renderCustomMaterial());
return _n3;
}, () => {
const _n5 = createNodes(null);
return _n5;
}, 265);
return _n6;
})();
Object.defineProperty(root, "uniTagName", uniTagName);
return root;
}
});
const index$5 = /* @__PURE__ */ defineUnsupportedComponent("ad-content-page");
const index$4 = /* @__PURE__ */ defineUnsupportedComponent("ad-draw");
const index$3 = /* @__PURE__ */ defineUnsupportedComponent("camera");
const index$2 = /* @__PURE__ */ defineUnsupportedComponent("live-player");
const index$1 = /* @__PURE__ */ defineUnsupportedComponent("live-pusher");
function injectLifecycleHook(name, hook, publicThis, instance2) {
if (isFunction(hook)) {
injectHook(name, hook.bind(publicThis), instance2);
}
}
function initHooks(options, instance2, publicThis) {
const mpType = options.mpType || publicThis.$mpType;
if (!mpType || mpType === "component" || // instance.renderer 标识页面是否作为组件渲染
mpType === "page" && instance2.renderer === "component") {
return;
}
Object.keys(options).forEach((name) => {
if (isUniLifecycleHook(name, options[name], false)) {
const hooks = options[name];
if (isArray(hooks)) {
hooks.forEach(
(hook) => injectLifecycleHook(name, hook, publicThis, instance2)
);
} else {
injectLifecycleHook(name, hooks, publicThis, instance2);
}
}
});
if (mpType === "page") {
instance2.__isVisible = true;
try {
let query;
query = instance2.__pageQuery;
const scriptLang = instance2.type.__scriptLang;
const isUTS = !scriptLang || scriptLang === "uts";
if (true) {
query = isUTS ? new UTSJSONObject(decodedQuery(query)) : decodedQuery(query);
}
if (false)
;
invokeHook(publicThis, ON_LOAD, query);
if (!instance2.vapor) {
delete instance2.attrs.__pageQuery;
}
const $basePage = true ? publicThis.$basePage : publicThis.$page;
if (true) {
if (($basePage == null ? void 0 : $basePage.openType) !== "preloadPage") {
if (isDialogPageInstance(getPageInstanceByChild(instance2))) {
invokeNewDialogPageHook(publicThis.$page, ON_SHOW);
} else {
invokeHook(publicThis, ON_SHOW);
}
}
}
} catch (e2) {
console.error(e2.message + LINEFEED + e2.stack);
}
}
}
function set(target, key, val) {
return target[key] = val;
}
function $callMethod(method, ...args) {
const fn = this[method];
if (fn) {
return fn(...args);
}
console.error(`method ${method} not found`);
return null;
}
function createErrorHandler(app) {
const userErrorHandler = app.config.errorHandler;
return function errorHandler(err, instance2, info) {
if (userErrorHandler) {
userErrorHandler(err, instance2, info);
}
const appInstance = app._instance;
if (!appInstance || !appInstance.proxy) {
throw err;
}
if (appInstance[ON_ERROR]) {
{
invokeHook(appInstance.proxy, ON_ERROR, err);
}
} else {
logError(err, info, instance2 == null ? void 0 : instance2.$, false);
}
};
}
function mergeAsArray(to, from) {
return to ? [...new Set([].concat(to, from))] : from;
}
function initOptionMergeStrategies(optionMergeStrategies) {
UniLifecycleHooks.forEach((name) => {
optionMergeStrategies[name] = mergeAsArray;
});
}
let realAtob;
const b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
const b64re = /^(?:[A-Za-z\d+/]{4})*?(?:[A-Za-z\d+/]{2}(?:==)?|[A-Za-z\d+/]{3}=?)?$/;
if (typeof atob !== "function") {
realAtob = function(str) {
str = String(str).replace(/[\t\n\f\r ]+/g, "");
if (!b64re.test(str)) {
throw new Error(
"Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded."
);
}
str += "==".slice(2 - (str.length & 3));
var bitmap;
var result = "";
var r1;
var r2;
var i = 0;
for (; i < str.length; ) {
bitmap = b64.indexOf(str.charAt(i++)) << 18 | b64.indexOf(str.charAt(i++)) << 12 | (r1 = b64.indexOf(str.charAt(i++))) << 6 | (r2 = b64.indexOf(str.charAt(i++)));
result += r1 === 64 ? String.fromCharCode(bitmap >> 16 & 255) : r2 === 64 ? String.fromCharCode(bitmap >> 16 & 255, bitmap >> 8 & 255) : String.fromCharCode(
bitmap >> 16 & 255,
bitmap >> 8 & 255,
bitmap & 255
);
}
return result;
};
} else {
realAtob = atob;
}
function b64DecodeUnicode(str) {
return decodeURIComponent(
realAtob(str).split("").map(function(c) {
return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
}).join("")
);
}
function getCurrentUserInfo() {
const token = uni.getStorageSync("uni_id_token") || "";
const tokenArr = token.split(".");
if (!token || tokenArr.length !== 3) {
return {
uid: null,
role: [],
permission: [],
tokenExpired: 0
};
}
let userInfo;
try {
userInfo = JSON.parse(b64DecodeUnicode(tokenArr[1]));
} catch (error) {
throw new Error("获取当前用户信息出错,详细错误信息为:" + error.message);
}
userInfo.tokenExpired = userInfo.exp * 1e3;
delete userInfo.exp;
delete userInfo.iat;
return userInfo;
}
function uniIdMixin(globalProperties) {
globalProperties.uniIDHasRole = function(roleId) {
const { role } = getCurrentUserInfo();
return role.indexOf(roleId) > -1;
};
globalProperties.uniIDHasPermission = function(permissionId) {
const { permission } = getCurrentUserInfo();
return this.uniIDHasRole("admin") || permission.indexOf(permissionId) > -1;
};
globalProperties.uniIDTokenValid = function() {
const { tokenExpired } = getCurrentUserInfo();
return tokenExpired > Date.now();
};
}
function initApp(app) {
const appConfig = app.config;
appConfig.errorHandler = invokeCreateErrorHandler(app, createErrorHandler);
initOptionMergeStrategies(appConfig.optionMergeStrategies);
const globalProperties = appConfig.globalProperties;
{
if (__UNI_FEATURE_UNI_CLOUD__) {
uniIdMixin(globalProperties);
}
}
{
globalProperties.$set = set;
globalProperties.$callMethod = $callMethod;
}
setUniPageHooksInitializer(initVaporPageHooks);
{
invokeCreateVueAppHook(app);
}
}
function initVaporPageHooks(instance2) {
const page = instance2;
initHooks(page.type, page, page.proxy);
}
function initRouter(app) {
const router2 = createRouter(createRouterOptions());
setRouterInstance(router2);
initWebAppRouteListener(router2, {
onRouteConfirmed: cleanupWebAppRoute,
onMissingRoute: handleBeforeEntryPageRoutes
});
router2.beforeEach((to, from) => {
if (to && from && to.meta.isTabBar && from.meta.isTabBar) {
saveTabBarScrollPosition(from.meta.tabBarIndex);
}
});
app.router = router2;
app.use(router2);
}
let positionStore = /* @__PURE__ */ Object.create(null);
function getTabBarScrollPosition(id2) {
return positionStore[id2];
}
function saveTabBarScrollPosition(id2) {
if (typeof window !== "undefined") {
positionStore[id2] = {
left: window.pageXOffset,
top: window.pageYOffset
};
}
}
const scrollBehavior = (to, from, savedPosition) => {
if (savedPosition) {
return savedPosition;
} else {
if (to && from && to.meta.isTabBar && from.meta.isTabBar) {
const position = getTabBarScrollPosition(to.meta.tabBarIndex);
if (position) {
return position;
}
}
return {
left: 0,
top: 0
};
}
};
function createRouterOptions() {
return {
history: initHistory(),
strict: !!__uniConfig.router.strict,
routes: __uniRoutes,
scrollBehavior
};
}
function removeCurrentPages(delta = 1) {
const keys = getCurrentBasePages();
const start = keys.length - 1;
const end = start - delta;
for (let i = start; i > end; i--) {
const page = getPage$BasePage(keys[i]);
removePage(normalizeRouteKey(page.path, page.id), false);
}
}
function cleanupWebAppRoute(transaction) {
switch (transaction.openType) {
case API_REDIRECT_TO:
removeLastPage();
break;
case API_RE_LAUNCH:
removeAllPages();
break;
case API_SWITCH_TAB:
removeNonTabBarPages(transaction.pageId);
break;
case API_NAVIGATE_BACK:
removeCurrentPages(transaction.delta || 1);
break;
}
}
function initHistory() {
let { routerBase } = __uniConfig.router;
if (routerBase === "/") {
routerBase = "";
}
const history2 = __UNI_FEATURE_ROUTER_MODE__ === "history" ? createWebHistory(routerBase) : createWebHashHistory(routerBase);
history2.listen((to, _from, info) => {
setWebAppRouteHistoryDirection(to, info.direction, info.delta);
});
return history2;
}
const index = {
install(app) {
setRealPathResolver(getRealPath);
setNativeEventNormalizer(normalizeVaporNativeEvent);
initApp(app);
initViewPlugin(app);
initServicePlugin(app);
if (!app.config.warnHandler) {
app.config.warnHandler = warnHandler;
}
if (__UNI_FEATURE_PAGES__) {
initRouter(app);
}
}
};
function warnHandler(msg, instance2, trace) {
if (instance2) {
const internalInstance = "$" in instance2 ? instance2.$ : instance2;
const name = internalInstance.type.name;
if ("PageMetaHead" === name) {
return;
}
const parent = internalInstance.parent;
if (parent && parent.type.name === "PageMeta") {
return;
}
}
const warnArgs = [`[Vue warn]: ${msg}`];
if (trace.length) {
warnArgs.push(`
`, trace);
}
console.warn(...warnArgs);
}
const UniViewJSBridge$1 = /* @__PURE__ */ extend(ViewJSBridge, {
publishHandler(event, args, pageId) {
UniServiceJSBridge.subscribeHandler(event, args, pageId);
}
});
const initInnerAudioContextEventOnce = /* @__PURE__ */ once(() => {
innerAudioContextEventNames.forEach((eventName) => {
InnerAudioContext.prototype[eventName] = function(callback) {
if (isFunction(callback)) {
this._events[eventName].push(callback);
}
};
});
innerAudioContextOffEventNames.forEach((eventName) => {
InnerAudioContext.prototype[eventName] = function(callback) {
var handle = this._events[eventName.replace("off", "on")];
var index2 = handle.indexOf(callback);
if (index2 >= 0) {
handle.splice(index2, 1);
}
};
});
});
class InnerAudioContext {
/**
* 音频上下文初始化
*/
constructor() {
this._src = "";
var audio = this._audio = new Audio();
this._stoping = false;
const propertys = [
"src",
"autoplay",
"loop",
"duration",
"currentTime",
"paused",
"volume"
];
propertys.forEach((property) => {
Object.defineProperty(this, property, {
set: property === "src" ? (src) => {
audio.src = getRealPath(src);
this._src = src;
return src;
} : (val) => {
audio[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", {
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 stopEventNames = ["canplay", "pause", "seeking", "seeked", "timeUpdate"];
var eventNames = stopEventNames.concat([
"play",
"ended",
"error",
"waiting"
]);
eventNames.forEach((eventName) => {
audio.addEventListener(
eventName.toLowerCase(),
() => {
if (this._stoping && stopEventNames.indexOf(eventName) >= 0) {
return;
}
const EventName = `on${eventName.slice(0, 1).toUpperCase()}${eventName.slice(1)}`;
this._events[EventName].forEach((callback) => {
callback();
});
},
false
);
});
initInnerAudioContextEventOnce();
}
/**
* 播放
*/
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((callback) => {
callback();
});
}
/**
* 跳转到
* @param {number} position
*/
seek(position) {
this._stoping = false;
position = Number(position);
if (typeof position === "number" && !isNaN(position)) {
this._audio.currentTime = position;
}
}
/**
* 销毁
*/
destroy() {
this.stop();
}
}
const createInnerAudioContext = /* @__PURE__ */ defineSyncApi(
API_CREATE_INNER_AUDIO_CONTEXT,
() => {
return new InnerAudioContext();
}
);
const makePhoneCall = /* @__PURE__ */ defineAsyncApi(
API_MAKE_PHONE_CALL,
({ phoneNumber }, { resolve }) => {
window.location.href = `tel:${phoneNumber}`;
return resolve();
},
MakePhoneCallProtocol
);
const UUID_KEY = "__DC_STAT_UUID";
const storage = navigator.cookieEnabled && (window.localStorage || window.sessionStorage) || {};
let deviceId;
function deviceId$1() {
deviceId = deviceId || storage[UUID_KEY];
if (!deviceId) {
deviceId = Date.now() + "" + Math.floor(Math.random() * 1e7);
try {
storage[UUID_KEY] = deviceId;
} catch (error) {
}
}
return deviceId;
}
const getWindowInfo = /* @__PURE__ */ defineSyncApi(
"getWindowInfo",
() => {
const pixelRatio = window.devicePixelRatio;
const screenFix = getScreenFix();
const landscape = isLandscape(screenFix);
const screenWidth = getScreenWidth(screenFix, landscape);
const screenHeight = getScreenHeight(screenFix, landscape);
const windowWidth = getWindowWidth();
let windowHeight = window.innerHeight;
const statusBarHeight = safeAreaInsets$1.top;
const safeArea = {
left: safeAreaInsets$1.left,
right: windowWidth - safeAreaInsets$1.right,
top: safeAreaInsets$1.top,
bottom: windowHeight - safeAreaInsets$1.bottom,
width: windowWidth - safeAreaInsets$1.left - safeAreaInsets$1.right,
height: windowHeight - safeAreaInsets$1.top - safeAreaInsets$1.bottom
};
const { top: windowTop, bottom: windowBottom } = getWindowOffset();
windowHeight -= windowTop;
windowHeight -= windowBottom;
return {
windowTop,
windowBottom,
windowWidth,
windowHeight,
pixelRatio,
screenWidth,
screenHeight,
statusBarHeight,
safeArea,
safeAreaInsets: {
top: safeAreaInsets$1.top,
right: safeAreaInsets$1.right,
bottom: safeAreaInsets$1.bottom,
left: safeAreaInsets$1.left
},
screenTop: screenHeight - windowHeight
};
}
);
let browserInfo;
let _initBrowserInfo = true;
function initBrowserInfo() {
if (!_initBrowserInfo)
return;
browserInfo = getBrowserInfo();
}
const getDeviceInfo = /* @__PURE__ */ defineSyncApi(
"getDeviceInfo",
() => {
initBrowserInfo();
const {
deviceBrand,
deviceModel,
brand,
model,
platform,
system,
deviceOrientation,
deviceType,
osname,
osversion
} = browserInfo;
return extend({
brand,
deviceBrand,
deviceModel,
devicePixelRatio: window.devicePixelRatio,
deviceId: deviceId$1(),
deviceOrientation,
deviceType,
model,
osName: osname ? osname.toLowerCase() : void 0,
osVersion: osversion,
platform,
system
});
}
);
const getAppBaseInfo = /* @__PURE__ */ defineSyncApi(
"getAppBaseInfo",
() => {
initBrowserInfo();
const { theme, language, browserName, browserVersion } = browserInfo;
return extend(
{
appId: __uniConfig.appId,
appName: __uniConfig.appName,
appVersion: __uniConfig.appVersion,
appVersionCode: __uniConfig.appVersionCode,
appLanguage: getLocale ? getLocale() : language,
enableDebug: false,
hostSDKVersion: void 0,
hostPackageName: void 0,
hostFontSizeSetting: void 0,
hostName: browserName,
hostVersion: browserVersion,
hostTheme: theme,
hostLanguage: language,
isUniAppX: true,
language,
SDKVersion: "",
theme,
uniPlatform: "web",
uniCompileVersion: __uniConfig.compilerVersion,
uniCompilerVersion: __uniConfig.compilerVersion,
uniRuntimeVersion: __uniConfig.compilerVersion,
version: ""
},
{
uniCompilerVersionCode: parseFloat(__uniConfig.compilerVersion),
uniRuntimeVersionCode: parseFloat(__uniConfig.compilerVersion),
uniRuntimeVersion: __uniConfig.compilerVersion
}
);
}
);
const getSystemInfoSync = /* @__PURE__ */ defineSyncApi(
"getSystemInfoSync",
() => {
_initBrowserInfo = true;
initBrowserInfo();
_initBrowserInfo = false;
const windowInfo = getWindowInfo();
const deviceInfo = getDeviceInfo();
const appBaseInfo = getAppBaseInfo();
_initBrowserInfo = true;
const { ua: ua2, browserName, browserVersion, osname, osversion } = browserInfo;
const systemInfo = extend(
windowInfo,
deviceInfo,
appBaseInfo,
{
browserName,
browserVersion,
fontSizeSetting: void 0,
osName: osname.toLowerCase(),
osVersion: osversion,
osLanguage: void 0,
osTheme: void 0,
ua: ua2,
uniPlatform: "web",
uniCompileVersion: __uniConfig.compilerVersion,
uniRuntimeVersion: __uniConfig.compilerVersion
}
);
delete systemInfo.screenTop;
delete systemInfo.enableDebug;
return systemInfo;
}
);
const getSystemInfo = /* @__PURE__ */ defineAsyncApi(
"getSystemInfo",
(_args, { resolve }) => {
return resolve(getSystemInfoSync());
}
);
const API_ON_NETWORK_STATUS_CHANGE = "onNetworkStatusChange";
const NONE = "none";
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 = /* @__PURE__ */ 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 = /* @__PURE__ */ defineOffApi("offNetworkStatusChange", () => {
const connection = getConnection();
if (connection) {
connection.removeEventListener("change", networkListener);
} else {
window.removeEventListener("offline", networkListener);
window.removeEventListener("online", networkListener);
}
});
const getNetworkType = /* @__PURE__ */ defineAsyncApi(
"getNetworkType",
(_args, { resolve }) => {
const connection = getConnection();
let networkType = "unknown";
if (connection) {
const effectiveType = connection.effectiveType;
networkType = connection.type;
if (networkType === "cellular" && effectiveType) {
networkType = effectiveType.replace("slow-", "");
} else if ((!networkType || networkType === NONE) && effectiveType) {
networkType = effectiveType;
} else if (![NONE, "wifi"].includes(networkType)) {
networkType = "unknown";
}
} else if (navigator.onLine === false) {
networkType = NONE;
}
return resolve({ networkType });
}
);
let listener = null;
const onAccelerometerChange = /* @__PURE__ */ defineOnApi(API_ON_ACCELEROMETER, () => {
startAccelerometer();
});
const offAccelerometerChange = /* @__PURE__ */ defineOffApi(API_OFF_ACCELEROMETER, () => {
stopAccelerometer();
});
const startAccelerometer = /* @__PURE__ */ defineAsyncApi(
API_START_ACCELEROMETER,
(_, { resolve, reject }) => {
if (!window.DeviceMotionEvent) {
reject();
return;
}
function addEventListener() {
listener = 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, false);
}
if (!listener) {
if (DeviceMotionEvent.requestPermission) {
DeviceMotionEvent.requestPermission().then((res) => {
if (res === "granted") {
addEventListener();
resolve();
} else {
reject(`${res}`);
}
}).catch((error) => {
reject(`${error}`);
});
return;
}
addEventListener();
}
resolve();
}
);
const stopAccelerometer = /* @__PURE__ */ defineAsyncApi(
API_STOP_ACCELEROMETER,
(_, { resolve }) => {
if (listener) {
window.removeEventListener("devicemotion", listener, false);
listener = null;
}
resolve();
}
);
const _isSupport = !!window.navigator.vibrate;
const vibrateShort = /* @__PURE__ */ defineAsyncApi(
API_VIBRATE_SHORT,
(args, { resolve, reject }) => {
if (_isSupport && window.navigator.vibrate(15)) {
resolve();
} else {
reject("vibrateShort:fail");
}
}
);
const vibrateLong = /* @__PURE__ */ defineAsyncApi(
API_VIBRATE_LONG,
(args, { resolve, reject }) => {
if (_isSupport && window.navigator.vibrate(400)) {
resolve();
} else {
reject("vibrateLong:fail");
}
}
);
const getClipboardData = /* @__PURE__ */ defineAsyncApi(
API_GET_CLIPBOARD_DATA,
async (_, { resolve, reject }) => {
initI18nGetClipboardDataMsgsOnce();
const { t: t12 } = useI18n();
try {
const data = await navigator.clipboard.readText();
resolve({ data });
} catch (error) {
_getClipboardData(resolve, () => {
reject(`${error} ${t12("uni.getClipboardData.fail")}`);
});
}
}
);
const setClipboardData = /* @__PURE__ */ defineAsyncApi(
API_SET_CLIPBOARD_DATA,
async ({ data }, { resolve, reject }) => {
try {
await navigator.clipboard.writeText(data);
resolve();
} catch (error) {
_setClipboardData(data, resolve, reject);
}
},
SetClipboardDataProtocol,
SetClipboardDataOptions
);
function _getClipboardData(resolve, reject) {
const pasteText = document.getElementById("#clipboard");
const data = pasteText ? pasteText.value : void 0;
if (data) {
resolve({ data });
} else {
reject();
}
}
function _setClipboardData(data, resolve, reject) {
const pasteText = document.getElementById("#clipboard");
pasteText && pasteText.remove();
const textarea = document.createElement("textarea");
textarea.setAttribute("inputmode", "none");
textarea.id = "#clipboard";
textarea.style.position = "fixed";
textarea.style.top = "-9999px";
textarea.style.zIndex = "-9999";
document.body.appendChild(textarea);
textarea.value = data;
textarea.select();
textarea.setSelectionRange(0, textarea.value.length);
const result = document.execCommand("Copy", false);
textarea.blur();
if (result) {
resolve();
} else {
reject();
}
}
const themeChangeCallBack = (res) => {
UniServiceJSBridge.invokeOnCallback(ON_THEME_CHANGE, res);
};
const onThemeChange = /* @__PURE__ */ defineOnApi(
ON_THEME_CHANGE,
() => {
UniServiceJSBridge.on(ON_THEME_CHANGE, themeChangeCallBack);
}
);
const offThemeChange = /* @__PURE__ */ defineOffApi(
OFF_THEME_CHANGE,
() => {
UniServiceJSBridge.off(ON_THEME_CHANGE, themeChangeCallBack);
}
);
const THEME_CALLBACK = [];
const onHostThemeChange = /* @__PURE__ */ defineSyncApi(
ON_HOST_THEME_CHANGE,
(callback) => {
const onHostThemeChangeCallback = (res) => {
callback({ hostTheme: res.theme });
};
const index2 = THEME_CALLBACK.push([callback, onHostThemeChangeCallback]) - 1;
UniServiceJSBridge.on(ON_THEME_CHANGE, onHostThemeChangeCallback);
return index2;
}
);
const offHostThemeChange = /* @__PURE__ */ defineSyncApi(
OFF_HOST_THEME_CHANGE,
(callbackId) => {
if (isFunction(callbackId)) {
callbackId = THEME_CALLBACK.findIndex(
([callback]) => callback === callbackId
);
}
if (callbackId > -1) {
const arr = THEME_CALLBACK.splice(callbackId, 1)[0];
isArray(arr) && UniServiceJSBridge.off(ON_THEME_CHANGE, arr[1]);
}
}
);
const STORAGE_KEYS = "uni-storage-keys";
function parseValue(value, isUTS) {
const types = ["object", "string", "number", "boolean", "undefined"];
try {
const object = isString(value) ? 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) {
if (type === "object" && isUTS) {
return UTS.JSON.parse(JSON.stringify(object.data));
}
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 setStorageSync = /* @__PURE__ */ 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 = /* @__PURE__ */ defineAsyncApi(
API_SET_STORAGE,
({ key, data }, { resolve, reject }) => {
try {
setStorageSync(key, data);
resolve();
} catch (error) {
reject(error.message);
}
},
SetStorageProtocol
);
function getStorageOrigin(key, isUTS) {
const value = localStorage && localStorage.getItem(key);
if (!isString(value)) {
throw new Error("data not found");
}
let data = value;
try {
const object = JSON.parse(value);
const result = parseValue(object, isUTS);
if (result !== void 0) {
data = result;
}
} catch (error) {
}
return data;
}
const getStorageSync = /* @__PURE__ */ defineSyncApi(
API_GET_STORAGE_SYNC,
// @ts-expect-error 内部isUTS参数
(key, isUTS) => {
try {
return getStorageOrigin(key, isUTS);
} catch (error) {
return "";
}
},
GetStorageSyncProtocol
);
const getStorage = /* @__PURE__ */ defineAsyncApi(
API_GET_STORAGE,
// @ts-expect-error 内部isUTS参数
({ key, isUTS }, { resolve, reject }) => {
try {
const data = getStorageOrigin(key, isUTS);
resolve({
data
});
} catch (error) {
reject(error.message);
}
},
GetStorageProtocol
);
const removeStorageSync = /* @__PURE__ */ defineSyncApi(
API_REMOVE_STORAGE,
(key) => {
if (localStorage) {
localStorage.removeItem(key);
}
},
RemoveStorageSyncProtocol
);
const removeStorage = /* @__PURE__ */ defineAsyncApi(
API_REMOVE_STORAGE,
({ key }, { resolve }) => {
removeStorageSync(key);
resolve();
},
RemoveStorageProtocol
);
const clearStorageSync = /* @__PURE__ */ defineSyncApi(
"clearStorageSync",
() => {
if (localStorage) {
localStorage.clear();
}
}
);
const clearStorage = /* @__PURE__ */ defineAsyncApi(
"clearStorage",
(_, { resolve }) => {
clearStorageSync();
resolve();
}
);
const getStorageInfoSync = /* @__PURE__ */ 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 = /* @__PURE__ */ defineAsyncApi(
"getStorageInfo",
(_, { resolve }) => {
resolve(getStorageInfoSync());
}
);
const getFileInfo = /* @__PURE__ */ defineAsyncApi(
API_GET_FILE_INFO,
({ filePath }, { resolve, reject }) => {
urlToFile(filePath).then((res) => {
resolve({
size: res.size
});
}).catch((err) => {
reject(String(err));
});
},
GetFileInfoProtocol,
GetFileInfoOptions
);
const openDocument = /* @__PURE__ */ defineAsyncApi(
API_OPEN_DOCUMENT,
({ filePath }, { resolve }) => {
window.open(filePath);
return resolve();
},
OpenDocumentProtocol,
OpenDocumentOptions
);
const hideKeyboard = /* @__PURE__ */ 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 = /* @__PURE__ */ 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
});
};
img.onerror = function() {
reject();
};
img.src = src;
},
GetImageInfoProtocol,
GetImageInfoOptions
);
const getVideoInfo = /* @__PURE__ */ 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: Math.ceil((file ? file.size : 0) / 1024),
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 = {
/**
* 关于图片常见的MIME类型
*/
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"
},
/**
* 关于视频常见的MIME类型
*/
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
}) {
addInteractListener();
const inputEl = document.createElement("input");
inputEl.type = "file";
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 = /* @__PURE__ */ defineAsyncApi(
API_CHOOSE_FILE,
({
// sizeType,
count,
sourceType,
type,
extension
}, { resolve, reject }) => {
initI18nChooseFileMsgsOnce();
const { t: t12 } = useI18n();
if (fileInput) {
document.body.removeChild(fileInput);
fileInput = null;
}
fileInput = _createInput({
count,
sourceType,
type,
extension
});
document.body.appendChild(fileInput);
fileInput.addEventListener("cancel", () => {
reject("chooseFile:fail cancel");
});
fileInput.addEventListener("change", function(event) {
const eventTarget = event.target;
const tempFiles = [];
if (eventTarget && eventTarget.files) {
const fileCount = eventTarget.files.length;
for (let i = 0; i < fileCount; i++) {
const file = eventTarget.files[i];
let filePath;
Object.defineProperty(file, "path", {
get() {
filePath = filePath || fileToUrl(file);
return filePath;
}
});
if (i < count)
tempFiles.push(file);
}
}
const res = {
get tempFilePaths() {
return tempFiles.map(({ path }) => path);
},
tempFiles
};
resolve(res);
});
fileInput.click();
if (!getInteractStatus()) {
console.warn(t12("uni.chooseFile.notUserActivation"));
}
},
ChooseFileProtocol,
ChooseFileOptions
);
let imageInput = null;
const chooseImage = /* @__PURE__ */ defineAsyncApi(
API_CHOOSE_IMAGE,
({
count,
// sizeType,
sourceType,
extension
}, { resolve, reject }) => {
initI18nChooseFileMsgsOnce();
const { t: t12 } = useI18n();
if (imageInput) {
document.body.removeChild(imageInput);
imageInput = null;
}
imageInput = _createInput({
count,
sourceType,
extension,
type: "image"
});
document.body.appendChild(imageInput);
imageInput.addEventListener("cancel", () => {
reject("chooseImage:fail cancel");
});
imageInput.addEventListener("change", function(event) {
const eventTarget = event.target;
const tempFiles = [];
if (eventTarget && eventTarget.files) {
const fileCount = eventTarget.files.length;
for (let i = 0; i < fileCount; i++) {
const file = eventTarget.files[i];
let filePath;
Object.defineProperty(file, "path", {
get() {
filePath = filePath || fileToUrl(file);
return filePath;
}
});
if (i < count)
tempFiles.push(file);
}
}
const res = {
get tempFilePaths() {
return tempFiles.map(({ path }) => path);
},
tempFiles
};
resolve(res);
});
imageInput.click();
if (!getInteractStatus()) {
console.warn(t12("uni.chooseFile.notUserActivation"));
}
},
ChooseImageProtocol,
ChooseImageOptions
);
let videoInput = null;
const chooseVideo = /* @__PURE__ */ defineAsyncApi(
API_CHOOSE_VIDEO,
({ sourceType, extension }, { resolve, reject }) => {
initI18nChooseFileMsgsOnce();
const { t: t12 } = useI18n();
if (videoInput) {
document.body.removeChild(videoInput);
videoInput = null;
}
videoInput = _createInput({
sourceType,
extension,
type: "video"
});
document.body.appendChild(videoInput);
videoInput.addEventListener("cancel", () => {
reject("chooseVideo:fail cancel");
});
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;
}
});
const video = document.createElement("video");
if (video.onloadedmetadata !== void 0) {
const filePath2 = fileToUrl(file);
video.onloadedmetadata = function() {
revokeObjectURL(filePath2);
resolve(
extend(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();
if (!getInteractStatus()) {
console.warn(t12("uni.chooseFile.notUserActivation"));
}
},
ChooseVideoProtocol,
ChooseVideoOptions
);
class DownloadTask {
constructor(xhr) {
this._callbacks = [];
this._xhr = xhr;
}
/**
* 监听下载进度
* @param {Function} callback 回调
*/
onProgressUpdate(callback) {
if (!isFunction(callback)) {
return;
}
this._callbacks.push(callback);
}
offProgressUpdate(callback) {
const index2 = this._callbacks.indexOf(callback);
if (index2 >= 0) {
this._callbacks.splice(index2, 1);
}
}
/**
* 停止任务
*/
abort() {
if (this._xhr) {
this._xhr.abort();
delete this._xhr;
}
}
onHeadersReceived(callback) {
throw new Error("Method not implemented.");
}
offHeadersReceived(callback) {
throw new Error("Method not implemented.");
}
}
const downloadFile = /* @__PURE__ */ defineTaskApi(
API_DOWNLOAD_FILE,
({ url, header = {}, timeout = __uniConfig.networkTimeout.downloadFile }, { resolve, reject }) => {
{
timeout = timeout == null ? __uniConfig.networkTimeout.downloadFile : timeout;
}
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];
}
}
blob.name = filename || getFileName(url);
resolve({
statusCode,
tempFilePath: fileToUrl(blob)
});
};
xhr.onabort = function() {
clearTimeout(timer);
reject("abort", { errCode: 600003 });
};
xhr.onerror = function() {
clearTimeout(timer);
reject("", { errCode: 602001 });
};
xhr.onprogress = function(event) {
downloadTask._callbacks.forEach((callback) => {
var totalBytesWritten = event.loaded;
var totalBytesExpectedToWrite = event.total;
var progress = Math.round(
totalBytesWritten / totalBytesExpectedToWrite * 100
);
callback({
progress,
totalBytesWritten,
totalBytesExpectedToWrite
});
});
};
xhr.send();
timer = setTimeout(function() {
xhr.onprogress = xhr.onload = xhr.onabort = xhr.onerror = null;
downloadTask.abort();
reject("timeout", { errCode: 5 });
}, timeout);
return downloadTask;
},
DownloadFileProtocol,
DownloadFileOptions
);
class UploadTask {
constructor(xhr) {
this._callbacks = [];
this._xhr = xhr;
}
/**
* 监听上传进度
* @param callback 回调
*/
onProgressUpdate(callback) {
if (!isFunction(callback)) {
return;
}
this._callbacks.push(callback);
}
offProgressUpdate(callback) {
const index2 = this._callbacks.indexOf(callback);
if (index2 >= 0) {
this._callbacks.splice(index2, 1);
}
}
/**
* 中断上传任务
*/
abort() {
this._isAbort = true;
if (this._xhr) {
this._xhr.abort();
delete this._xhr;
}
}
onHeadersReceived(callback) {
throw new Error("Method not implemented.");
}
offHeadersReceived(callback) {
throw new Error("Method not implemented.");
}
}
const uploadFile = /* @__PURE__ */ defineTaskApi(
API_UPLOAD_FILE,
({
url,
file,
filePath,
name,
files: files2,
header = {},
formData = {},
timeout = __uniConfig.networkTimeout.uploadFile
}, { resolve, reject }) => {
{
timeout = timeout == null ? __uniConfig.networkTimeout.uploadFile : timeout;
}
var uploadTask = new UploadTask();
if (!isArray(files2) || !files2.length) {
if (!filePath) {
reject("file error");
}
files2 = [
{
name,
file,
uri: filePath
}
];
}
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((callback) => {
var totalBytesSent = event.loaded;
var totalBytesExpectedToSend = event.total;
var progress = Math.round(
totalBytesSent / totalBytesExpectedToSend * 100
);
callback({
progress,
totalBytesSent,
totalBytesExpectedToSend
});
});
};
xhr.onerror = function() {
clearTimeout(timer);
reject("", { errCode: 602001 });
};
xhr.onabort = function() {
clearTimeout(timer);
reject("abort", { errCode: 600003 });
};
xhr.onload = function() {
clearTimeout(timer);
const statusCode = xhr.status;
const responseHeaders = xhr.getAllResponseHeaders();
const header2 = responseHeaders ? responseHeaders.trim().split(/[\r\n]+/).reduce((acc, line) => {
const parts = line.split(": ");
const header3 = parts.shift();
const value = parts.join(": ");
acc[header3] = value;
return acc;
}, {}) : {};
resolve({
statusCode,
data: xhr.responseText || xhr.response,
header: header2
});
};
if (!uploadTask._isAbort) {
timer = setTimeout(function() {
xhr.upload.onprogress = xhr.onload = xhr.onabort = xhr.onerror = null;
uploadTask.abort();
reject("timeout", { errCode: 5 });
}, timeout);
xhr.send(form);
uploadTask._xhr = xhr;
} else {
reject("abort", { errCode: 600003 });
}
}
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 {
/**
* 构造函数
* @param {string} url
* @param {Array} protocols
*/
constructor(url, protocols, callback) {
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 { data, code, reason } = event;
const res = name === "message" ? { data } : name === "close" ? { code, reason } : {};
this._callbacks[name].forEach((callback2) => {
try {
callback2(res);
} catch (e2) {
console.error(
`thirdScriptError
${e2};at socketTask.on${capitalize(
name
)} callback function
`,
e2
);
}
});
if (this === socketTasks[0] && globalEvent[name]) {
UniServiceJSBridge.invokeOnCallback(globalEvent[name], res);
}
if (name === "error" || name === "close") {
const index2 = socketTasks.indexOf(this);
if (index2 >= 0) {
socketTasks.splice(index2, 1);
}
}
});
});
const propertys = [
"CLOSED",
"CLOSING",
"CONNECTING",
"OPEN",
"readyState"
];
propertys.forEach((property) => {
Object.defineProperty(this, property, {
get() {
return webSocket[property];
}
});
});
} catch (e2) {
error = e2;
}
callback && callback(error, this);
}
/**
* 发送
* @param {any} data
*/
send(options) {
const data = (options || {}).data;
const ws = this._webSocket;
try {
if (ws.readyState !== ws.OPEN) {
callOptions(options, {
errMsg: `sendSocketMessage:fail SocketTask.readyState is not OPEN`,
errCode: 10002
});
throw new Error("SocketTask.readyState is not OPEN");
}
ws.send(data);
callOptions(options, "sendSocketMessage:ok");
} catch (error) {
callOptions(options, {
errMsg: `sendSocketMessage:fail ${error}`,
errCode: 602001
});
}
}
/**
* 关闭
* @param {number} code
* @param {string} reason
*/
close(options = {}) {
const ws = this._webSocket;
try {
const code = options.code || 1e3;
const reason = options.reason;
if (isString(reason)) {
ws.close(code, reason);
} else {
ws.close(code);
}
callOptions(options, "closeSocket:ok");
} catch (error) {
callOptions(options, `closeSocket:fail ${error}`);
}
}
onOpen(callback) {
this._callbacks.open.push(callback);
}
onMessage(callback) {
this._callbacks.message.push(callback);
}
onError(callback) {
this._callbacks.error.push(callback);
}
onClose(callback) {
this._callbacks.close.push(callback);
}
}
const connectSocket = /* @__PURE__ */ defineTaskApi(
API_CONNECT_SOCKET,
({ url, protocols }, { resolve, reject }) => {
return new SocketTask(
url,
protocols,
(error, socketTask) => {
if (error) {
reject(error.toString(), {
errCode: 600009
});
return;
}
socketTasks.push(socketTask);
resolve();
}
);
},
ConnectSocketProtocol,
ConnectSocketOptions
);
function callSocketTask(socketTask, method, option, resolve, reject) {
const fn = socketTask[method];
if (isFunction(fn)) {
fn.call(
socketTask,
extend({}, option, {
success() {
resolve();
},
fail({ errMsg }) {
reject(errMsg.replace("sendSocketMessage:fail ", ""));
},
complete: void 0
})
);
}
}
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);
} else {
reject("WebSocket is not connected");
}
},
SendSocketMessageProtocol
);
const closeSocket = /* @__PURE__ */ defineAsyncApi(
API_CLOSE_SOCKET,
(options, { resolve, reject }) => {
const socketTask = socketTasks[0];
if (socketTask) {
callSocketTask(socketTask, "close", options, resolve, reject);
} else {
reject("WebSocket is not connected");
}
},
CloseSocketProtocol
);
function on(event) {
const api2 = `onSocket${capitalize(event)}`;
return /* @__PURE__ */ 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");
let started = false;
let watchId = 0;
const startLocationUpdate = /* @__PURE__ */ defineAsyncApi(
API_START_LOCATION_UPDATE,
(options, { resolve, reject }) => {
if (!navigator.geolocation) {
reject();
return;
}
watchId = watchId || navigator.geolocation.watchPosition(
(res) => {
started = true;
translateCoordinateSystem(options == null ? void 0 : options.type, res.coords).then((coords) => {
UniServiceJSBridge.invokeOnCallback(
API_ON_LOCATION_CHANGE,
coords
);
resolve();
}).catch((error) => {
UniServiceJSBridge.invokeOnCallback(
API_ON_LOCATION_CHANGE_ERROR,
{ errMsg: `onLocationChange:fail ${error.message}` }
);
});
},
(error) => {
if (!started) {
reject(error.message);
started = true;
}
UniServiceJSBridge.invokeOnCallback(API_ON_LOCATION_CHANGE_ERROR, {
errMsg: `onLocationChange:fail ${error.message}`
});
}
);
setTimeout(resolve, 100);
},
StartLocationUpdateProtocol,
StartLocationUpdateOptions
);
const stopLocationUpdate = /* @__PURE__ */ defineAsyncApi(
API_STOP_LOCATION_UPDATE,
(_, { resolve }) => {
if (watchId) {
navigator.geolocation.clearWatch(watchId);
started = false;
watchId = 0;
}
resolve();
}
);
const onLocationChange = /* @__PURE__ */ defineOnApi(
API_ON_LOCATION_CHANGE,
() => {
}
);
const offLocationChange = /* @__PURE__ */ defineOffApi(
API_OFF_LOCATION_CHANGE,
() => {
}
);
const onLocationChangeError = /* @__PURE__ */ defineOnApi(
API_ON_LOCATION_CHANGE_ERROR,
() => {
}
);
const offLocationChangeError = /* @__PURE__ */ defineOffApi(
API_OFF_LOCATION_CHANGE_ERROR,
() => {
}
);
const navigateBack = /* @__PURE__ */ defineAsyncApi(
API_NAVIGATE_BACK,
(args, { resolve, reject }) => {
let canBack = true;
if (invokeHook(ON_BACK_PRESS, {
from: args.from || "navigateBack"
}) === true) {
canBack = false;
}
{
const currentPage = getCurrentPage();
if (currentPage) {
const dialogPages = currentPage.getDialogPages();
if (dialogPages.length > 0) {
const dialogPage = dialogPages[dialogPages.length - 1];
if (invokeHook(dialogPage.vm, ON_BACK_PRESS, {
from: args.from || "navigateBack"
}) === true) {
canBack = false;
}
}
}
}
if (!canBack) {
return reject(ON_BACK_PRESS);
}
let router2;
router2 = getRouterInstance();
router2.go(-args.delta);
return resolve();
},
NavigateBackProtocol,
NavigateBackOptions
);
const navigateTo = /* @__PURE__ */ defineAsyncApi(
API_NAVIGATE_TO,
// @ts-expect-error
({ url, events, isAutomatedTesting }, { resolve, reject }) => {
if (!entryPageState.handledBeforeEntryPageRoutes) {
navigateToPagesBeforeEntryPages.push({
args: { type: API_NAVIGATE_TO, url, events, isAutomatedTesting },
resolve,
reject
});
return;
}
return navigate({ type: API_NAVIGATE_TO, url, events, isAutomatedTesting }).then(resolve).catch(reject);
},
NavigateToProtocol,
NavigateToOptions
);
const preloadPage = /* @__PURE__ */ defineAsyncApi(
API_PRELOAD_PAGE,
({ url }, { resolve, reject }) => {
const path = url.split("?")[0];
const route = getRouteOptions(path);
if (!route) {
reject(`${url}`);
return;
}
route.loader && route.loader().then(() => {
resolve({
url,
errMsg: "preloadPage:ok"
});
}).catch((err) => {
reject(`${url} ${String(err)}`);
});
},
PreloadPageProtocol
);
const _t0$1 = template('<i class="uni-toast__icon uni-loading">', 3);
function createToastIcon$1(icon) {
switch (icon) {
case "success":
case "error": {
const element = createSvgIconVNode(icon === "success" ? ICON_PATH_SUCCESS_NO_CIRCLE : ICON_PATH_WARN, "#fff", 36);
element.setAttribute("class", "uni-toast__icon");
return element;
}
case "loading":
return (() => {
const _n0 = _t0$1();
return _n0;
})();
default:
return null;
}
}
const KEY_MAPS = {
esc: ["Esc", "Escape"],
// tab: ['Tab'],
enter: ["Enter"]
// space: [' ', 'Spacebar'],
// up: ['Up', 'ArrowUp'],
// left: ['Left', 'ArrowLeft'],
// right: ['Right', 'ArrowRight'],
// down: ['Down', 'ArrowDown'],
// delete: ['Backspace', 'Delete', 'Del'],
};
const KEYS = Object.keys(KEY_MAPS);
function useKeyboard() {
const key = ref("");
const disable = 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;
}
nextTick(() => key.value = "");
};
onMounted(() => {
document.addEventListener("keyup", onKeyup);
});
onBeforeUnmount(() => {
document.removeEventListener("keyup", onKeyup);
});
return {
key,
disable
};
}
function createRootApp(component, rootState, callback) {
rootState.onClose = (...args) => (rootState.visible = false, callback.apply(null, args));
return createVaporApp(component, {
$: [() => rootState]
});
}
function ensureRoot(id2) {
let rootEl = document.getElementById(id2);
if (!rootEl) {
rootEl = document.createElement("div");
rootEl.id = id2;
document.body.append(rootEl);
}
return rootEl;
}
function usePopup(props2, {
onEsc,
onEnter
}) {
const visible = ref(props2.visible);
const { key, disable } = useKeyboard();
watch(
() => props2.visible,
(value) => visible.value = value
);
watch(
() => visible.value,
(value) => disable.value = !value
);
watchEffect(() => {
const { value } = key;
if (value === "esc") {
onEsc && onEsc();
} else if (value === "enter") {
onEnter && onEnter();
}
});
return visible;
}
const _t0 = template('<div class=uni-mask style="background: transparent;">');
const _t1 = template("<div><p class=uni-simple-toast__text> ");
const _t2 = template("<img>");
const _t3 = template("<p class=uni-toast__content> ");
const _t4 = template("<div class=uni-toast>");
const ToastTransition = VaporTransition;
const defineToast = defineSystemComponent;
const createToastIcon = createToastIcon$1;
const props = {
title: {
type: String,
default: ""
},
icon: {
default: "success",
validator(value) {
return SHOW_TOAST_ICON.indexOf(value) !== -1;
}
},
image: {
type: String,
default: ""
},
duration: {
type: Number,
default: 1500
},
position: { type: String },
mask: {
type: Boolean,
default: false
},
visible: { type: Boolean }
};
const ToastIconClassName = "uni-toast__icon";
const Toast = /* @__PURE__ */ defineToast({
name: "Toast",
props,
setup(props2) {
initI18nShowToastMsgsOnce();
initI18nShowLoadingMsgsOnce();
const Icon = computed(() => createToastIcon(props2.icon));
const visible = usePopup(props2, {});
return () => {
return (() => {
const _n22 = createComponent(ToastTransition, { name: "uni-fade" }, () => {
const _n0 = createPlainElement("uni-toast", { "data-duration": () => props2.duration }, extend$1(() => {
const _n1 = createIf(() => props2.mask && !props2.position, () => {
const _n3 = _t0();
on$1(_n3, "touchmove", onEventPrevent);
return _n3;
}, () => {
const _n5 = createNodes("");
return _n5;
}, 393);
const _n6 = createIf(() => !!props2.position || !props2.image && !Icon.value, () => {
const _n9 = _t1();
const _n8 = child(_n9);
const _x8 = txt(_n8);
setNodes(_x8, () => props2.title);
renderEffect(() => setClass(_n9, ["uni-sample-toast", props2.position ? `uni-toast--${props2.position}` : ""]));
return _n9;
}, () => {
const _n21 = _t4();
setInsertionState(_n21);
createIf(() => props2.image, () => {
const _n13 = _t2();
renderEffect(() => {
setProp(_n13, "src", props2.image);
setClass(_n13, ToastIconClassName);
});
return _n13;
}, () => {
const _n15 = createNodes(() => Icon.value);
return _n15;
}, 777);
setInsertionState(_n21, 1);
createIf(() => props2.title, () => {
const _n18 = _t3();
const _x18 = txt(_n18);
setNodes(_x18, () => props2.title);
return _n18;
}, () => {
const _n20 = createNodes("");
return _n20;
}, 1033);
return _n21;
}, 645);
return [_n1, _n6];
}, { _: 1 }));
applyVShow(_n0, () => visible.value);
return _n0;
}, true);
return _n22;
})();
};
}
});
const pageToast = { type: "", token: 0 };
const appToast = { type: "", token: 0 };
const scope = /* @__PURE__ */ effectScope();
function resetToastTimeout(controller) {
clearTimeout(controller.timeoutId);
if (controller.type !== "onShowToast") {
return;
}
controller.timeoutId = setTimeout(
() => hidePopup("onHideToast", controller),
controller.state.duration
);
}
function watchVisible(controller) {
scope.run(() => {
watch(
() => controller.state.visible,
(visible) => {
if (visible) {
resetToastTimeout(controller);
} else {
clearTimeout(controller.timeoutId);
}
}
);
});
}
function createToast(controller, args, type, pageId) {
var _a;
clearTimeout(controller.timeoutId);
clearTimeout(controller.showTimerId);
controller.type = type;
controller.pageId = pageId;
controller.token++;
if (!controller.state) {
controller.state = reactive(extend({}, args, { visible: false }));
nextTick(() => {
watchVisible(controller);
if (controller === pageToast) {
UniServiceJSBridge.on(
"onHidePopup",
() => hidePopup("onHidePopup", pageToast)
);
}
createRootApp(Toast, controller.state, () => {
}).mount(
ensureRoot(controller === pageToast ? "u-a-t" : "u-a-at")
);
});
} else {
extend(controller.state, args);
}
const token = controller.token;
controller.showTimerId = setTimeout(() => {
if (token === controller.token) {
controller.state.visible = true;
}
}, 10);
if ((_a = controller.state) == null ? void 0 : _a.visible) {
resetToastTimeout(controller);
}
}
const showToast = /* @__PURE__ */ defineAsyncApi(
API_SHOW_TOAST,
(args, { resolve, reject }) => {
if (args.position !== void 0 && !["top", "center", "bottom"].includes(args.position)) {
args.position = "center";
}
const controller = args.position === void 0 ? pageToast : appToast;
createToast(
controller,
args,
"onShowToast",
controller === pageToast ? getCurrentPageId() : void 0
);
resolve();
},
ShowToastProtocol,
ShowToastOptions
);
const hideToast = /* @__PURE__ */ defineAsyncApi(
API_HIDE_TOAST,
(args, { resolve, reject }) => {
hidePopup("onHideToast", pageToast);
if (args == null ? void 0 : args.allType) {
hidePopup("onHideToast", appToast);
}
resolve();
},
HideToastProtocol,
HideToastOptions
);
function hidePopup(type, controller) {
const { t: t12 } = useI18n();
if (!controller.type) {
return;
}
let warnMsg = "";
if (type === "onHideToast" && controller.type !== "onShowToast") {
warnMsg = t12("uni.showToast.unpaired");
} else if (type === "onHideLoading" && controller.type !== "onShowLoading") {
warnMsg = t12("uni.showLoading.unpaired");
}
if (warnMsg) {
return console.warn(warnMsg);
}
controller.type = "";
controller.pageId = void 0;
clearTimeout(controller.timeoutId);
clearTimeout(controller.showTimerId);
const token = ++controller.token;
setTimeout(() => {
if (token === controller.token) {
controller.state.visible = false;
}
}, 10);
}
onPageUnload((pageId) => {
if (pageToast.pageId === pageId && pageToast.type === "onShowToast") {
hidePopup("onHideToast", pageToast);
}
});
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: animation2 } = args;
const { duration, timingFunc } = animation2;
if (frontColor) {
navigationBar.titleColor = frontColor === "#000000" ? "#000000" : "#ffffff";
}
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 = /* @__PURE__ */ defineAsyncApi(
API_SET_NAVIGATION_BAR_COLOR,
(args, { resolve, reject }) => {
setNavigationBar(
getCurrentPageMeta(),
API_SET_NAVIGATION_BAR_COLOR,
args,
resolve,
reject
);
},
SetNavigationBarColorProtocol,
SetNavigationBarColorOptions
);
const showNavigationBarLoading = /* @__PURE__ */ defineAsyncApi(
API_SHOW_NAVIGATION_BAR_LOADING,
(args, { resolve, reject }) => {
setNavigationBar(
getCurrentPageMeta(),
API_SHOW_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 = /* @__PURE__ */ defineAsyncApi(
API_SET_NAVIGATION_BAR_TITLE,
(args, { resolve, reject }) => {
setNavigationBar(
getCurrentPageMeta(),
API_SET_NAVIGATION_BAR_TITLE,
args,
resolve,
reject
);
},
SetNavigationBarTitleProtocol
);
const pageScrollTo = /* @__PURE__ */ defineAsyncApi(
API_PAGE_SCROLL_TO,
({ scrollTop, selector, duration }, { resolve }) => {
scrollTo(selector || scrollTop || 0, duration, true);
resolve();
},
PageScrollToProtocol,
PageScrollToOptions
);
const startPullDownRefresh = /* @__PURE__ */ defineAsyncApi(
API_START_PULL_DOWN_REFRESH,
(_args, { resolve }) => {
UniServiceJSBridge.invokeViewMethod(
API_START_PULL_DOWN_REFRESH,
{},
getCurrentPageId()
);
resolve();
}
);
const stopPullDownRefresh = /* @__PURE__ */ defineAsyncApi(
API_STOP_PULL_DOWN_REFRESH,
(_args, { resolve }) => {
UniServiceJSBridge.invokeViewMethod(
API_STOP_PULL_DOWN_REFRESH,
{},
getCurrentPageId()
);
resolve();
}
);
const setTabBarItemProps = [
"text",
"iconPath",
"iconfont",
"selectedIconPath",
"visible"
];
const setTabBarStyleProps = [
"color",
"selectedColor",
"backgroundColor",
"borderStyle",
"borderColor",
"midButton"
];
const setTabBarBadgeProps = ["badge", "redDot"];
function setProperties(item, props2, propsData) {
props2.forEach(function(name) {
if (hasOwn(propsData, name)) {
item[name] = propsData[name];
}
});
}
function setTabBar(type, args, resolve, reject) {
var _a;
let isTabBar = false;
const pages = getCurrentBasePages();
if (pages.length) {
if (getPage$BasePage(pages[pages.length - 1]).meta.isTabBar) {
isTabBar = true;
}
}
if (!isTabBar) {
return reject(`not TabBar page`);
}
const { index: index2 } = args;
if (typeof index2 === "number") {
const tabBarListLength = (_a = __uniConfig == null ? void 0 : __uniConfig.tabBar) == null ? void 0 : _a.list.length;
if (!tabBarListLength || index2 >= tabBarListLength) {
return reject(`tabbar item not found`);
}
}
const tabBar = useTabBar();
switch (type) {
case API_SHOW_TAB_BAR:
tabBar.shown = true;
break;
case API_HIDE_TAB_BAR:
tabBar.shown = false;
break;
case API_SET_TAB_BAR_ITEM:
const tabBarItem = tabBar.list[index2];
const oldPagePath = tabBarItem.pagePath;
setProperties(tabBarItem, setTabBarItemProps, args);
const { pagePath } = args;
if (pagePath) {
const newPagePath = addLeadingSlash(pagePath);
if (newPagePath !== oldPagePath) {
normalizeTabBarRoute(index2, oldPagePath, newPagePath);
}
}
break;
case API_SET_TAB_BAR_STYLE:
setProperties(tabBar, setTabBarStyleProps, args);
break;
case API_SHOW_TAB_BAR_RED_DOT:
setProperties(tabBar.list[index2], setTabBarBadgeProps, {
badge: "",
redDot: true
});
break;
case API_SET_TAB_BAR_BADGE:
setProperties(tabBar.list[index2], setTabBarBadgeProps, {
badge: args.text,
redDot: true
});
break;
case API_HIDE_TAB_BAR_RED_DOT:
case API_REMOVE_TAB_BAR_BADGE:
setProperties(tabBar.list[index2], setTabBarBadgeProps, {
badge: "",
redDot: false
});
break;
}
resolve();
}
const setTabBarItem = /* @__PURE__ */ defineAsyncApi(
API_SET_TAB_BAR_ITEM,
(args, { resolve, reject }) => {
setTabBar(API_SET_TAB_BAR_ITEM, args, resolve, reject);
},
SetTabBarItemProtocol,
SetTabBarItemOptions
);
const setTabBarStyle = /* @__PURE__ */ defineAsyncApi(
API_SET_TAB_BAR_STYLE,
(args, { resolve, reject }) => {
setTabBar(API_SET_TAB_BAR_STYLE, args, resolve, reject);
},
SetTabBarStyleProtocol,
SetTabBarStyleOptions
);
const hideTabBar = /* @__PURE__ */ defineAsyncApi(
API_HIDE_TAB_BAR,
(args, { resolve, reject }) => {
setTabBar(API_HIDE_TAB_BAR, args ? args : {}, resolve, reject);
},
HideTabBarProtocol
);
const showTabBar = /* @__PURE__ */ defineAsyncApi(
API_SHOW_TAB_BAR,
(args, { resolve, reject }) => {
setTabBar(API_SHOW_TAB_BAR, args ? args : {}, resolve, reject);
},
ShowTabBarProtocol
);
const hideTabBarRedDot = /* @__PURE__ */ defineAsyncApi(
API_HIDE_TAB_BAR_RED_DOT,
(args, { resolve, reject }) => {
setTabBar(API_HIDE_TAB_BAR_RED_DOT, args, resolve, reject);
},
HideTabBarRedDotProtocol,
HideTabBarRedDotOptions
);
const showTabBarRedDot = /* @__PURE__ */ defineAsyncApi(
API_SHOW_TAB_BAR_RED_DOT,
(args, { resolve, reject }) => {
setTabBar(API_SHOW_TAB_BAR_RED_DOT, args, resolve, reject);
},
ShowTabBarRedDotProtocol,
ShowTabBarRedDotOptions
);
const removeTabBarBadge = /* @__PURE__ */ defineAsyncApi(
API_REMOVE_TAB_BAR_BADGE,
(args, { resolve, reject }) => {
setTabBar(API_REMOVE_TAB_BAR_BADGE, args, resolve, reject);
},
RemoveTabBarBadgeProtocol,
RemoveTabBarBadgeOptions
);
const setTabBarBadge = /* @__PURE__ */ defineAsyncApi(
API_SET_TAB_BAR_BADGE,
(args, { resolve, reject }) => {
setTabBar(API_SET_TAB_BAR_BADGE, args, resolve, reject);
},
SetTabBarBadgeProtocol,
SetTabBarBadgeOptions
);
const showTopWindow = /* @__PURE__ */ defineAsyncApi(
"showTopWindow",
(_, { resolve, reject }) => {
const state = getLayoutState();
if (!state) {
reject();
return;
}
state.apiShowTopWindow = true;
nextTick(resolve);
}
);
const hideTopWindow = /* @__PURE__ */ defineAsyncApi(
"hideTopWindow",
(_, { resolve, reject }) => {
const state = getLayoutState();
if (!state) {
reject();
return;
}
state.apiShowTopWindow = false;
nextTick(resolve);
}
);
const showLeftWindow = /* @__PURE__ */ defineAsyncApi(
"showLeftWindow",
(_, { resolve, reject }) => {
const state = getLayoutState();
if (!state) {
reject();
return;
}
state.apiShowLeftWindow = true;
nextTick(resolve);
}
);
const hideLeftWindow = /* @__PURE__ */ defineAsyncApi(
"hideLeftWindow",
(_, { resolve, reject }) => {
const state = getLayoutState();
if (!state) {
reject();
return;
}
state.apiShowLeftWindow = false;
nextTick(resolve);
}
);
const showRightWindow = /* @__PURE__ */ defineAsyncApi(
"showRightWindow",
(_, { resolve, reject }) => {
const state = getLayoutState();
if (!state) {
reject();
return;
}
state.apiShowRightWindow = true;
nextTick(resolve);
}
);
const hideRightWindow = /* @__PURE__ */ defineAsyncApi(
"hideRightWindow",
(_, { resolve, reject }) => {
const state = getLayoutState();
if (!state) {
reject();
return;
}
state.apiShowRightWindow = false;
nextTick(resolve);
}
);
const getTopWindowStyle = /* @__PURE__ */ defineSyncApi(
"getTopWindowStyle",
() => {
const state = getLayoutState();
return extend({}, state && state.topWindowStyle);
}
);
const setTopWindowStyle = /* @__PURE__ */ defineSyncApi(
"setTopWindowStyle",
(style) => {
const state = getLayoutState();
if (state) {
state.topWindowStyle = style;
}
}
);
const getLeftWindowStyle = /* @__PURE__ */ defineSyncApi(
"getLeftWindowStyle",
() => {
const state = getLayoutState();
return extend({}, state && state.leftWindowStyle);
}
);
const setLeftWindowStyle = /* @__PURE__ */ defineSyncApi(
"setLeftWindowStyle",
(style) => {
const state = getLayoutState();
if (state) {
state.leftWindowStyle = style;
}
}
);
const getRightWindowStyle = /* @__PURE__ */ defineSyncApi("getRightWindowStyle", () => {
const state = getLayoutState();
return extend({}, state && state.rightWindowStyle);
});
const setRightWindowStyle = /* @__PURE__ */ defineSyncApi("setRightWindowStyle", (style) => {
const state = getLayoutState();
if (state) {
state.rightWindowStyle = style;
}
});
const getElementById = /* @__PURE__ */ defineSyncApi(
"getElementById",
(id2) => {
const uniPageBody = document.querySelector("uni-page-body");
return uniPageBody ? uniPageBody.querySelector(`#${id2}`) : null;
}
);
const getFacialRecognitionMetaInfo = /* @__PURE__ */ defineSyncApi(
"getFacialRecognitionMetaInfo",
() => {
if (Object.getPrototypeOf(window) !== Window.prototype) {
console.error(
"getFacialRecognitionMetaInfo:fail window对象原型被篡改,可能存在劫持"
);
return "";
}
if (window.window !== window || window.self !== window) {
console.error(
"getFacialRecognitionMetaInfo:fail window对象属性引用异常,可能被劫持"
);
return "";
}
if (Object.prototype.toString.call(window) !== "[object Window]" && Object.prototype.toString.call(window) !== "[object DOMWindow]") {
console.error(
"getFacialRecognitionMetaInfo:fail window对象类型标识异常,可能被劫持"
);
return "";
}
if (isFunction(window.getMetaInfo)) {
return window.getMetaInfo();
} else {
console.error(
"getFacialRecognitionMetaInfo:fail window对象缺少getMetaInfo方法,请参考文档引用:https://doc.dcloud.net.cn/uniCloud/frv/dev.html#window-get-meta-info"
);
return "";
}
}
);
let keepScreenOn = false;
let wakeLockSentinel = null;
let wakeLockRequest = null;
let visibilityChangeListenerAdded = false;
function getWakeLockManager() {
const currentNavigator = navigator;
if (currentNavigator.wakeLock != null) {
return currentNavigator.wakeLock;
}
return null;
}
function getUnsupportedMessage() {
return `method 'uni.${API_SET_KEEP_SCREEN_ON}' not supported`;
}
function getErrorMessage(error) {
return error == null ? void 0 : `${error}`;
}
function onWakeLockRelease(event) {
const sentinel = event.target;
if (sentinel) {
sentinel.removeEventListener("release", onWakeLockRelease);
}
if (wakeLockSentinel === sentinel) {
wakeLockSentinel = null;
}
}
function requestWakeLock() {
const wakeLockManager = getWakeLockManager();
if (wakeLockManager == null) {
return Promise.reject(getUnsupportedMessage());
}
if (wakeLockSentinel && !wakeLockSentinel.released) {
return Promise.resolve(wakeLockSentinel);
}
if (wakeLockRequest) {
return wakeLockRequest;
}
wakeLockRequest = wakeLockManager.request("screen").then((sentinel) => {
wakeLockSentinel = sentinel;
sentinel.addEventListener("release", onWakeLockRelease);
return sentinel;
}).finally(() => {
wakeLockRequest = null;
});
return wakeLockRequest;
}
async function releaseWakeLock() {
if (wakeLockRequest) {
await wakeLockRequest.catch(() => null);
}
const sentinel = wakeLockSentinel;
wakeLockSentinel = null;
if (sentinel == null) {
return;
}
sentinel.removeEventListener("release", onWakeLockRelease);
if (!sentinel.released) {
await sentinel.release();
}
}
function onVisibilityChange() {
if (document.visibilityState === "visible" && keepScreenOn) {
requestWakeLock().catch(() => {
});
}
}
function addVisibilityChangeListener() {
if (!visibilityChangeListenerAdded) {
document.addEventListener("visibilitychange", onVisibilityChange);
visibilityChangeListenerAdded = true;
}
}
function removeVisibilityChangeListener() {
if (visibilityChangeListenerAdded) {
document.removeEventListener("visibilitychange", onVisibilityChange);
visibilityChangeListenerAdded = false;
}
}
const setKeepScreenOn = /* @__PURE__ */ defineAsyncApi(
API_SET_KEEP_SCREEN_ON,
({ keepScreenOn: value }, { resolve, reject }) => {
keepScreenOn = !!value;
if (keepScreenOn) {
addVisibilityChangeListener();
requestWakeLock().then(() => {
resolve();
}).catch((error) => {
keepScreenOn = false;
removeVisibilityChangeListener();
reject(getErrorMessage(error));
});
} else {
removeVisibilityChangeListener();
releaseWakeLock().then(resolve).catch((error) => {
reject(getErrorMessage(error));
});
}
}
);
const saveImageToPhotosAlbum = /* @__PURE__ */ defineAsyncApi(
API_SAVE_IMAGE_TO_PHOTOS_ALBUM,
createUnsupportedAsyncApi(API_SAVE_IMAGE_TO_PHOTOS_ALBUM)
);
const API_GET_RECORDER_MANAGER = "getRecorderManager";
const getRecorderManager = /* @__PURE__ */ defineSyncApi(
API_GET_RECORDER_MANAGER,
createUnsupportedSyncApi(API_GET_RECORDER_MANAGER)
);
const saveVideoToPhotosAlbum = /* @__PURE__ */ defineAsyncApi(
API_SAVE_VIDEO_TO_PHOTOS_ALBUM,
createUnsupportedAsyncApi(API_SAVE_VIDEO_TO_PHOTOS_ALBUM)
);
const API_CREATE_CAMERA_CONTEXT = "createCameraContext";
const createCameraContext = /* @__PURE__ */ defineSyncApi(
API_CREATE_CAMERA_CONTEXT,
createUnsupportedSyncApi(API_CREATE_CAMERA_CONTEXT)
);
const API_CREATE_LIVE_PLAYER_CONTEXT = "createLivePlayerContext";
const createLivePlayerContext = /* @__PURE__ */ defineSyncApi(
API_CREATE_LIVE_PLAYER_CONTEXT,
createUnsupportedSyncApi(API_CREATE_LIVE_PLAYER_CONTEXT)
);
const API_SAVE_FILE = "saveFile";
const saveFile = /* @__PURE__ */ defineAsyncApi(
API_SAVE_FILE,
createUnsupportedAsyncApi(API_SAVE_FILE)
);
const API_GET_SAVED_FILE_LIST = "getSavedFileList";
const getSavedFileList = /* @__PURE__ */ defineAsyncApi(
API_GET_SAVED_FILE_LIST,
createUnsupportedAsyncApi(API_GET_SAVED_FILE_LIST)
);
const API_GET_SAVED_FILE_INFO = "getSavedFileInfo";
const getSavedFileInfo = /* @__PURE__ */ defineAsyncApi(
API_GET_SAVED_FILE_INFO,
createUnsupportedAsyncApi(API_GET_SAVED_FILE_INFO)
);
const API_REMOVE_SAVED_FILE = "removeSavedFile";
const removeSavedFile = /* @__PURE__ */ defineAsyncApi(
API_REMOVE_SAVED_FILE,
createUnsupportedAsyncApi(API_REMOVE_SAVED_FILE)
);
const API_ON_MEMORY_WARNING = "onMemoryWarning";
const onMemoryWarning = /* @__PURE__ */ defineOnApi(
API_ON_MEMORY_WARNING,
createUnsupportedOnApi(API_ON_MEMORY_WARNING)
);
const API_ON_GYROSCOPE_CHANGE = "onGyroscopeChange";
const onGyroscopeChange = /* @__PURE__ */ defineOnApi(
API_ON_GYROSCOPE_CHANGE,
createUnsupportedOnApi(API_ON_GYROSCOPE_CHANGE)
);
const API_START_GYROSCOPE = "startGyroscope";
const startGyroscope = /* @__PURE__ */ defineAsyncApi(
API_START_GYROSCOPE,
createUnsupportedAsyncApi(API_START_GYROSCOPE)
);
const API_STOP_GYROSCOPE = "stopGyroscope";
const stopGyroscope = /* @__PURE__ */ defineAsyncApi(
API_STOP_GYROSCOPE,
createUnsupportedAsyncApi(API_STOP_GYROSCOPE)
);
const API_SCAN_CODE = "scanCode";
const scanCode = /* @__PURE__ */ defineAsyncApi(
API_SCAN_CODE,
createUnsupportedAsyncApi(API_SCAN_CODE)
);
const API_SET_SCREEN_BRIGHTNESS = "setScreenBrightness";
const setScreenBrightness = /* @__PURE__ */ defineAsyncApi(
API_SET_SCREEN_BRIGHTNESS,
createUnsupportedAsyncApi(API_SET_SCREEN_BRIGHTNESS)
);
const API_GET_SCREEN_BRIGHTNESS = "getScreenBrightness";
const getScreenBrightness = /* @__PURE__ */ defineAsyncApi(
API_GET_SCREEN_BRIGHTNESS,
createUnsupportedAsyncApi(API_GET_SCREEN_BRIGHTNESS)
);
const API_ON_USER_CAPTURE_SCREEN = "onUserCaptureScreen";
const onUserCaptureScreen = /* @__PURE__ */ defineOnApi(
API_ON_USER_CAPTURE_SCREEN,
createUnsupportedOnApi(API_ON_USER_CAPTURE_SCREEN)
);
const API_ADD_PHONE_CONTACT = "addPhoneContact";
const addPhoneContact = /* @__PURE__ */ defineAsyncApi(
API_ADD_PHONE_CONTACT,
createUnsupportedAsyncApi(API_ADD_PHONE_CONTACT)
);
const API_LOGIN = "login";
const login = /* @__PURE__ */ defineAsyncApi(
API_LOGIN,
createUnsupportedAsyncApi(API_LOGIN)
);
const API_GET_PROVIDER = "getProvider";
const getProvider = /* @__PURE__ */ defineAsyncApi(
API_GET_PROVIDER,
createUnsupportedAsyncApi(API_GET_PROVIDER)
);
class CanvasImage extends Image {
constructor() {
super();
this._src = "";
}
get src() {
return this._src;
}
set src(value) {
this._src = value;
super.src = getRealPath(value);
}
}
class CanvasContextImpl {
constructor(element) {
this._element = element;
}
getContext(type) {
return this._element.getContext(type);
}
toBlob(callback, type, quality) {
this._element.toBlob(callback, type, quality);
}
toDataURL(type, encoderOptions) {
return this._element.toDataURL(type, encoderOptions);
}
// @ts-expect-error TODO 类型不匹配?
createImage() {
return new CanvasImage();
}
createPath2D() {
return new Path2D();
}
requestAnimationFrame(callback) {
return window.requestAnimationFrame(callback);
}
cancelAnimationFrame(taskId) {
window.cancelAnimationFrame(taskId);
}
}
const createCanvasContextAsync = function(options) {
nextTick(() => {
const pages = getCurrentBasePages();
const currentPage = options.component ?? pages[pages.length - 1];
requestComponentInfo(
currentPage,
[
{
component: currentPage,
selector: "#" + options.id,
single: true,
fields: {
node: true
}
}
],
(result) => {
var _a, _b, _c;
if (result.length > 0) {
const canvas = result[0].node;
(_a = options.success) == null ? void 0 : _a.call(options, new CanvasContextImpl(canvas));
} else {
const uniError = new UniError(
"uni-createCanvasContextAsync",
-1,
"canvas id invalid."
);
(_b = options.fail) == null ? void 0 : _b.call(options, uniError);
}
(_c = options.complete) == null ? void 0 : _c.call(options);
}
);
});
};
const ERR_SUBJECT = "uni-createEditorContextAsync";
const createEditorContextAsync = function(options) {
nextTick(() => {
const pages = getCurrentBasePages();
const currentPage = options.component ?? pages[pages.length - 1];
requestComponentInfo(
currentPage,
[
{
component: currentPage,
selector: "#" + options.id,
single: true,
fields: {
context: true
}
}
],
(result) => {
var _a, _b, _c, _d;
if (result.length > 0) {
const contextInfo = result[0].contextInfo;
const id2 = contextInfo == null ? void 0 : contextInfo.id;
const page = contextInfo == null ? void 0 : contextInfo.page;
if (id2 != null && page != null) {
(_a = options.success) == null ? void 0 : _a.call(options, new EditorContext(id2, page));
} else {
const uniError = new UniError(
ERR_SUBJECT,
-2,
"Editor context information not found."
);
(_b = options.fail) == null ? void 0 : _b.call(options, uniError);
}
} else {
const uniError = new UniError(
ERR_SUBJECT,
-1,
"Editor id or component invalid."
);
(_c = options.fail) == null ? void 0 : _c.call(options, uniError);
}
(_d = options.complete) == null ? void 0 : _d.call(options);
}
);
});
};
const POPUP_WIDTH = 300;
const POPUP_EDGE = 6;
function getPickerPopupStyle(popover, windowWidth, windowHeight, contentHeight) {
const availableWidth = Math.max(0, windowWidth - POPUP_EDGE * 2);
const availableHeight = Math.max(0, windowHeight - POPUP_EDGE * 2);
const width = Math.min(POPUP_WIDTH, availableWidth);
let height = Math.min(Math.max(0, contentHeight), availableHeight);
let left = (windowWidth - width) / 2;
let top = (windowHeight - height) / 2;
if (popover != null) {
left = Math.max(POPUP_EDGE, Math.min(windowWidth - width - POPUP_EDGE, popover.left));
const spaceAbove = Math.max(0, popover.top - POPUP_EDGE * 2);
const spaceBelow = Math.max(0, windowHeight - popover.top - popover.height - POPUP_EDGE * 2);
const above = spaceBelow < height && spaceAbove > spaceBelow;
height = Math.min(height, above ? spaceAbove : spaceBelow);
top = above ? popover.top - height - POPUP_EDGE : popover.top + popover.height + POPUP_EDGE;
top = Math.max(POPUP_EDGE, Math.min(windowHeight - height - POPUP_EDGE, top));
}
return {
content: {
left: `${left}px`,
top: `${top}px`,
right: "auto",
bottom: "auto",
width: `${width}px`,
height: `${height}px`
}
};
}
const t0$9 = template("<span uni-text data-v-212d40c7> ");
const t1$7 = template("<div uni-view data-v-212d40c7><span uni-text data-v-212d40c7> </span><span uni-text data-v-212d40c7 class=uni-picker__header-btn-ok> </div>");
const t2$6 = template("<div uni-view data-v-212d40c7 class=uni-picker__view>");
const t3$3 = template("<div uni-view data-v-212d40c7><div uni-view data-v-212d40c7></div><div uni-view data-v-212d40c7>", 1);
const _sfc_main$9 = /* @__PURE__ */ defineVaporComponent({
__name: "picker",
setup(__props) {
const show = ref(false);
const readyEventName = ref("");
const optionsEventName = ref("");
const cancelEventName = ref("");
const selectorChangeEventName = ref("");
const multiSelectorChangeEventName = ref("");
const timeChangeEventName = ref("");
const columnChangeEventName = ref("");
const mode = ref("selector");
const range = ref([]);
const rangeKey = ref("");
const value = ref([]);
const eventValue = ref([]);
const prevMultiValue = ref([]);
const selected = reactive({
year: (/* @__PURE__ */ new Date()).getFullYear(),
month: (/* @__PURE__ */ new Date()).getMonth() + 1,
day: (/* @__PURE__ */ new Date()).getDate()
});
const years = ref([]);
const months = ref(Array.from({ length: 12 }, (_, i) => i + 1));
const days = ref([]);
const hours = ref([]);
const minutes = ref([]);
const fields = ref("day");
const start = ref([]);
const end = ref([]);
const yearRange = ref([]);
const monthRange = ref([]);
const dayRange = ref([]);
const timer = ref(0);
const theme = ref("light");
const maskTopStyle = ref("background-image: linear-gradient(to bottom, rgba(255,255,255,1), rgba(255, 255, 255, 0));");
const maskBottomStyle = ref("background-image: linear-gradient(to bottom, rgba(255,255,255,0), rgba(255, 255, 255, 1));");
const i18nText = {
"en": {
"cancel": "Cancel",
"confirm": "OK",
"year": "",
"month": "",
"day": "",
"months": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"]
},
"es": {
"cancel": "Cancelar",
"confirm": "Aceptar",
"year": "",
"month": "",
"day": "",
"months": ["Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic"]
},
"fr": {
"cancel": "Annuler",
"confirm": "Valider",
"year": "",
"month": "",
"day": "",
"months": ["Jan", "Fév", "Mar", "Avr", "Mai", "Juin", "Juil", "Aoû", "Sep", "Oct", "Nov", "Déc"]
},
"zh-Hans": {
"cancel": "取消",
"confirm": "确定",
"year": "年",
"month": "月",
"day": "日",
"months": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]
},
"zh-Hant": {
"cancel": "取消",
"confirm": "確定",
"year": "年",
"month": "月",
"day": "日",
"months": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]
}
};
const language = ref("zh-Hans");
const instance2 = getCurrentInstance();
const popover = ref(null);
const selectorType = ref("select");
const windowWidth = ref(0);
const windowHeight = ref(0);
const containerRef = ref(null);
const selectRef = ref(null);
let layoutFrame = null;
let closing = false;
const isDesktop = computed(() => windowWidth.value >= 500 && windowHeight.value >= 500);
const isSelect = computed(() => isDesktop.value && mode.value == "selector" && selectorType.value == "select");
const popupStyle = computed(() => {
if (!isDesktop.value)
return { content: {} };
const contentHeight = isSelect.value ? Math.min(300, range.value.length * 34 + 12) : 300;
return getPickerPopupStyle(popover.value, windowWidth.value, windowHeight.value, contentHeight);
});
const updateLayout = () => {
windowWidth.value = window.innerWidth;
windowHeight.value = window.innerHeight;
uni.$emit(`${optionsEventName.value}_layout`);
};
const scheduleLayout = () => {
if (layoutFrame != null)
return;
layoutFrame = window.requestAnimationFrame(() => {
layoutFrame = null;
updateLayout();
});
};
const handleScroll = (event) => {
var _a;
if (event.target instanceof Node && ((_a = containerRef.value) == null ? void 0 : _a.contains(event.target)))
return;
scheduleLayout();
};
const selectItem = (index2) => {
eventValue.value = [index2];
confirm();
};
watch(isSelect, (select) => {
if (!select)
value.value = eventValue.value.slice();
});
watch(() => [isSelect.value, eventValue.value[0], range.value.length, show.value], () => {
if (isSelect.value && show.value) {
nextTick(() => {
var _a;
return (_a = selectRef.value) == null ? void 0 : _a.scrollTo(0, Math.max(0, eventValue.value[0] ?? 0) * 34);
});
}
});
const selectedDate = computed(() => {
const { year, month, day } = selected;
switch (fields.value) {
case "year":
return `${year}`;
case "month":
return `${year}-${formatSingle(month)}`;
case "day":
return `${year}-${formatSingle(month)}-${formatSingle(day)}`;
default:
return `${year}-${formatSingle(month)}-${formatSingle(day)}`;
}
});
const indicatorStyle = computed(() => {
const color = theme.value == "dark" ? "rgba(255,255,255,0.05)" : "#F5F5F5";
return `height:50px;background:rgba(255,255,255,0);border-top:1px ${color} solid;border-bottom:1px ${color} solid;`;
});
const cancelText = computed(() => {
return i18nHandle("cancel", "取消");
});
const confirmText = computed(() => {
return i18nHandle("confirm", "确定");
});
const yearText = computed(() => {
return i18nHandle("year", "年");
});
const monthText = computed(() => {
return i18nHandle("month", "月");
});
const dayText = computed(() => {
return i18nHandle("day", "日");
});
const monthsText = computed(() => {
let monthsList = months.value;
let i18months = i18nHandle("months", i18nText["zh-Hans"]["months"]);
let arr = [];
monthsList.forEach((v2) => {
let index2 = v2 - 1;
arr.push(i18months[index2].toString().padStart(2, "0"));
});
return arr;
});
const switchTheme = (themeValue) => {
if (themeValue == "light") {
maskTopStyle.value = "background-image: linear-gradient(to bottom, rgba(255,255,255,1), rgba(255, 255, 255, 0));";
maskBottomStyle.value = "background-image: linear-gradient(to bottom, rgba(255,255,255,0), rgba(255, 255, 255, 1));";
} else {
maskTopStyle.value = "background-image: linear-gradient(to bottom, rgba(35, 35, 35, 1), rgba(35, 35, 35, 0));";
maskBottomStyle.value = "background-image: linear-gradient(to bottom, rgba(35, 35, 35, 0), rgba(35, 35, 35, 1));";
}
};
const confirm = () => {
if (closing)
return;
const val = eventValue.value;
const modeValue = mode.value;
switch (modeValue) {
case "selector":
uni.$emit(selectorChangeEventName.value, val[0]);
break;
case "multiSelector":
uni.$emit(multiSelectorChangeEventName.value, val);
break;
case "time":
const h = hours.value[val[0]];
const m = minutes.value[val[1]];
uni.$emit(timeChangeEventName.value, `${h}:${m}`);
break;
case "date":
uni.$emit(timeChangeEventName.value, selectedDate.value);
break;
}
closeDialog();
};
const close = () => {
if (closing)
return;
uni.$emit(cancelEventName.value);
closeDialog();
};
const closeDialog = () => {
closing = true;
show.value = false;
clearTimeout(timer.value);
timer.value = setTimeout(() => {
var _a;
const dialogPages = (_a = instance2 == null ? void 0 : instance2.proxy) == null ? void 0 : _a.$page;
uni.closeDialogPage({
dialogPage: dialogPages
});
}, 250);
};
const handleChange = (e2) => {
const val = e2.detail.value;
if (mode.value == "date") {
let yIdx = val[0];
let mIdx = val[1] ?? 0;
let dIdx = val[2] ?? 0;
yIdx = Math.max(yearRange.value[0], Math.min(yearRange.value[1], yIdx));
const currentYear = years.value[yIdx];
let sy = parseInt(start.value[0]);
let sm = parseInt(start.value[1]);
let ey = parseInt(end.value[0]);
let em = parseInt(end.value[1]);
if (currentYear == sy || currentYear == ey) {
let newMonths = getMonths(currentYear);
if (months.value.length !== newMonths.length) {
calculateRanges();
const originalMonth = months.value[mIdx];
mIdx = newMonths.findIndex((month) => month === originalMonth);
mIdx = Math.max(0, mIdx);
months.value = newMonths;
}
} else {
if (months.value.length != 12) {
const nowMonth = months.value[mIdx];
months.value = getMonths(currentYear);
calculateRanges();
mIdx = nowMonth - 1;
}
}
mIdx = Math.max(0, Math.min(mIdx, months.value.length - 1));
const monthsValue = months.value[mIdx];
if (currentYear == sy && monthsValue == sm || currentYear == ey && monthsValue == em) {
let newDays = getDays(currentYear, monthsValue);
if (days.value.length != newDays.length) {
calculateRanges();
let dayIdx = newDays.length - 1;
if (currentYear == sy && monthsValue == sm) {
dIdx = Math.max(0, dIdx - dayIdx);
}
if (currentYear == ey && monthsValue == em) {
dIdx = Math.max(0, dayIdx);
}
days.value = newDays;
}
} else {
const nowDay = days.value[dIdx];
days.value = getDays(currentYear, monthsValue);
calculateRanges();
dIdx = days.value.findIndex((day) => day === nowDay);
dIdx = Math.max(0, dIdx);
}
if (dIdx >= days.value.length) {
dIdx = 0;
}
selected.year = years.value[yIdx];
selected.month = months.value[mIdx];
selected.day = days.value[dIdx];
const indices = fields.value == "year" ? [yIdx] : fields.value == "month" ? [yIdx, mIdx] : [yIdx, mIdx, dIdx];
value.value = indices;
eventValue.value = indices.slice();
} else if (mode.value == "time") {
let h_idx = val[0];
let m_idx = val[1];
let h = parseInt(hours.value[h_idx]);
let m = parseInt(minutes.value[m_idx]);
let sh = parseInt(start.value[0]);
let eh = parseInt(end.value[0]);
const adjusted = adjustTime(h, m);
h = adjusted.h;
m = adjusted.m;
const hStr = h.toString().padStart(2, "0");
const mStr = m.toString().padStart(2, "0");
const newHIdx = hours.value.findIndex((e22) => e22 == hStr);
let newMIdx = minutes.value.findIndex((e22) => e22 == mStr);
if (h == sh || h == eh) {
const newMinutes = getMinutes(h);
if (minutes.value.length !== newMinutes.length) {
const originalMinute = minutes.value[newMIdx];
newMIdx = newMinutes.findIndex((m2) => m2 === originalMinute);
newMIdx = Math.max(0, newMIdx);
minutes.value = newMinutes;
}
} else {
if (minutes.value.length != 60) {
const nowMinutes = minutes.value[newMIdx];
minutes.value = getMinutes(h);
newMIdx = parseInt(nowMinutes);
}
}
const indices = [newHIdx, newMIdx];
value.value = indices;
eventValue.value = indices.slice();
} else if (mode.value == "multiSelector") {
const newValue = val;
const oldValue = prevMultiValue.value;
newValue.forEach((v2, column) => {
if (oldValue[column] !== v2) {
uni.$emit(columnChangeEventName.value, column, v2);
}
});
prevMultiValue.value = [...newValue];
eventValue.value = [...newValue];
} else {
eventValue.value = val;
}
};
const calculateRanges = () => {
const startYear = parseInt(start.value[0]);
const endYear = parseInt(end.value[0]);
yearRange.value = [
years.value.findIndex((y) => y >= startYear),
years.value.findIndex((y) => y >= endYear)
];
const startMonth = parseInt(start.value[1]);
const endMonth = parseInt(end.value[1]);
monthRange.value = [startMonth - 1, endMonth - 1];
const startDay = parseInt(start.value[2]);
const endDay = parseInt(end.value[2]);
dayRange.value = [startDay - 1, endDay - 1];
};
const getYears = () => {
const startYear = parseInt(start.value[0] || "1970");
const endYear = parseInt(end.value[0] || "2099");
return Array.from({ length: endYear - startYear + 1 }, (_, i) => startYear + i);
};
const getMonths = (year) => {
let startMonth = 1;
let endMonth = 12;
if (year == parseInt(start.value[0])) {
startMonth = parseInt(start.value[1]) ?? 1;
}
if (year == parseInt(end.value[0])) {
endMonth = parseInt(end.value[1]) ?? 12;
}
return Array.from({ length: endMonth - startMonth + 1 }, (_, i) => startMonth + i);
};
const getDays = (currentYear, currentMonth) => {
let startDay = 1;
let endDay = new Date(currentYear, currentMonth, 0).getDate();
if (currentYear == parseInt(start.value[0]) && currentMonth == parseInt(start.value[1])) {
startDay = parseInt(start.value[2]) || 1;
}
if (currentYear == parseInt(end.value[0]) && currentMonth == parseInt(end.value[1])) {
endDay = Math.min(endDay, parseInt(end.value[2]) || endDay);
}
return Array.from({ length: endDay - startDay + 1 }, (_, i) => startDay + i);
};
const updateDateColumns = () => {
years.value = getYears();
months.value = getMonths(selected.year);
days.value = getDays(selected.year, selected.month);
};
const getHours = () => {
const sH = parseInt(start.value[0] || "1");
const eH = parseInt(end.value[0] || "12");
return Array.from({ length: eH - sH + 1 }, (_, i) => String(sH + i).padStart(2, "0"));
};
const getMinutes = (hour) => {
let startMinute = 0;
let endMinute = 59;
if (hour == parseInt(start.value[0])) {
startMinute = parseInt(start.value[1]) ?? 1;
}
if (hour == parseInt(end.value[0])) {
endMinute = parseInt(end.value[1]) ?? 12;
}
return Array.from({ length: endMinute - startMinute + 1 }, (_, i) => String(startMinute + i).padStart(2, "0"));
};
const updateTimeColumns = (hour) => {
hours.value = getHours();
let minuteHour = hour;
if (minuteHour == null || isNaN(minuteHour)) {
minuteHour = parseInt(hours.value[0] || "00");
}
minutes.value = getMinutes(minuteHour);
};
const adjustTime = (h, m) => {
var _a, _b;
if (!((_a = start.value) == null ? void 0 : _a.length) || !((_b = end.value) == null ? void 0 : _b.length))
return { h, m };
const startHour = parseInt(start.value[0]);
const startMinute = parseInt(start.value[1]);
const endHour = parseInt(end.value[0]);
const endMinute = parseInt(end.value[1]);
const current = h * 60 + m;
const startTotal = startHour * 60 + startMinute;
const endTotal = endHour * 60 + endMinute;
if (current < startTotal) {
return { h: startHour, m: startMinute };
} else if (current > endTotal) {
return { h: endHour, m: endMinute };
} else {
if (h == startHour && m < startMinute)
return { h, m: startMinute };
if (h == endHour && m > endMinute)
return { h, m: endMinute };
return { h, m };
}
};
const initTimeValue = (timeValue) => {
let h = parseInt(timeValue[0]);
let m = parseInt(timeValue[1]);
const adjusted = adjustTime(h, m);
const hStr = adjusted.h.toString().padStart(2, "0");
const mStr = adjusted.m.toString().padStart(2, "0");
return [
hours.value.findIndex((e2) => e2 == hStr),
minutes.value.findIndex((e2) => e2 == mStr)
];
};
const formatSingle = (num) => {
return num.toString().padStart(2, "0");
};
const i18nHandle = (key, defaultVal) => {
if (language.value.startsWith("en")) {
return i18nText["en"][key];
}
if (language.value.startsWith("es")) {
return i18nText["es"][key];
}
if (language.value.startsWith("fr")) {
return i18nText["fr"][key];
}
if (language.value.startsWith("zh-Hans")) {
return i18nText["zh-Hans"][key];
}
if (language.value.startsWith("zh-Hant")) {
return i18nText["zh-Hant"][key];
}
return defaultVal;
};
const initLanguageAndTheme = () => {
const appBaseInfo = uni.getAppBaseInfo();
language.value = uni.getLocale();
theme.value = appBaseInfo.hostTheme == "dark" ? "dark" : "light";
};
onLoad((options) => {
readyEventName.value = options["readyEventName"];
optionsEventName.value = options["optionsEventName"];
cancelEventName.value = options["cancelEventName"];
selectorChangeEventName.value = options["selectorChangeEventName"];
multiSelectorChangeEventName.value = options["multiSelectorChangeEventName"];
timeChangeEventName.value = options["timeChangeEventName"];
columnChangeEventName.value = options["columnChangeEventName"];
uni.$on(optionsEventName.value, (data) => {
if (data["layoutOnly"] == true) {
popover.value = data["popover"];
return;
}
if (data["selectorType"] != null) {
selectorType.value = data["selectorType"];
popover.value = data["popover"];
}
if (data["mode"] != null) {
mode.value = data["mode"];
}
if (data["range"] != null) {
range.value = data["range"];
}
if (data["rangeKey"] != null) {
rangeKey.value = data["rangeKey"];
}
if (data["selectorValue"] != null) {
value.value = [data["selectorValue"]];
}
if (data["multiSelectorValue"] != null) {
value.value.length = 0;
const multiSelectorValue = data["multiSelectorValue"];
const len = range.value.length;
let arr = Array.from({ length: len }, () => 0);
arr.forEach((_, index2) => {
let val = multiSelectorValue[index2] ?? 0;
value.value.push(val);
});
prevMultiValue.value = value.value.slice();
}
if (data["timeValue"] != null) {
const timeVal = data["timeValue"];
start.value = data["start"];
end.value = data["end"];
const timeHour = parseInt(timeVal[0]);
const timeMinute = parseInt(timeVal[1]);
const adjusted = adjustTime(timeHour, timeMinute);
updateTimeColumns(adjusted.h);
value.value = initTimeValue(timeVal);
}
if (data["dateValue"] != null) {
const dateValue = data["dateValue"];
const year = dateValue[0];
const month = dateValue[1];
const day = dateValue[2];
fields.value = data["fields"];
start.value = data["start"] ?? ["1970", "01", "01"];
end.value = data["end"] ?? ["2099", "12", "31"];
selected.year = parseInt(year) ?? (/* @__PURE__ */ new Date()).getFullYear();
selected.month = parseInt(month) ?? 1;
selected.day = parseInt(day) ?? 1;
selected.year = Math.max(
parseInt(start.value[0]),
Math.min(parseInt(end.value[0]), selected.year)
);
selected.month = Math.max(1, Math.min(12, selected.month));
selected.day = Math.max(1, Math.min(
new Date(selected.year, selected.month, 0).getDate(),
selected.day
));
updateDateColumns();
const yIdx = years.value.findIndex((y) => y == selected.year);
const mIdx = months.value.findIndex((m) => m == selected.month);
const dIdx = days.value.findIndex((d) => d == selected.day);
switch (fields.value) {
case "year":
value.value = [yIdx];
break;
case "month":
value.value = [yIdx, mIdx];
break;
case "day":
value.value = [yIdx, mIdx, dIdx];
break;
}
}
eventValue.value = value.value;
calculateRanges();
});
updateLayout();
window.addEventListener("resize", scheduleLayout);
document.addEventListener("scroll", handleScroll, true);
uni.$emit(readyEventName.value);
initLanguageAndTheme();
switchTheme(theme.value);
uni.onHostThemeChange((res) => {
theme.value = res.hostTheme == "dark" ? "dark" : "light";
switchTheme(theme.value);
});
});
onReady(() => {
show.value = true;
});
onUnload(() => {
window.removeEventListener("resize", scheduleLayout);
document.removeEventListener("scroll", handleScroll, true);
if (layoutFrame != null) {
window.cancelAnimationFrame(layoutFrame);
layoutFrame = null;
}
uni.$off(optionsEventName.value, null);
if (timer.value) {
clearTimeout(timer.value);
}
});
initUniPageHooks();
const _component_scroll_view = __syscom_1;
const _component_picker_view_column = _sfc_main$k;
const _component_picker_view = _sfc_main$l;
const n56 = t3$3();
const n0 = child(n56);
const n55 = next(n0);
on$1(n0, "click", close);
renderEffect(() => {
const _theme = unref(theme);
const _isDesktop = unref(isDesktop);
const _show = unref(show);
setClass(n56, ["uni-picker__container", ["uni-picker-theme--" + _theme, { "uni-picker__container--desktop": _isDesktop }]]);
setClassName(n0, (_show ? 1 : 0) | (_theme == "dark" ? 2 : 0), [" picker__ani-show", " picker__mask--dark"], "uni-picker__mask");
setClass(n55, ["uni-picker__inner-box", [_show ? "picker__ani-box-show" : "", "inner-box--" + _theme, { "uni-picker__inner-box--desktop": _isDesktop }]]);
setStyle(n55, unref(popupStyle).content);
});
setInsertionState(n55);
createIf(
() => unref(isSelect),
() => {
const n6 = withComponentId("3e32089c", () => createComponentWithFallback(_component_scroll_view, {
class: "uni-picker__select",
direction: "vertical",
"show-scrollbar": true
}, extend$1(() => {
const n3 = createFor(
() => unref(range),
(_for_item0, _for_key0) => {
const n5 = t0$9();
const x5 = txt(n5);
on$1(n5, "click", () => selectItem(_for_key0.value));
renderEffect(() => {
const _rangeKey = unref(rangeKey);
const _item = _for_item0.value;
setClassName(n5, unref(eventValue)[0] == _for_key0.value ? 1 : 0, " uni-picker__select-item--selected", "uni-picker__select-item");
setText(x5, normalizeUniText(toDisplayString(_rangeKey ? _item[_rangeKey] : _item)));
});
return n5;
},
(item, selectorIdx) => selectorIdx,
40
/* IS_SINGLE_NODE, SLOT_ROOT */
);
return n3;
}, {
_: 1
/* NON_STABLE */
})));
setStaticTemplateRef(n6, selectRef, null, "selectRef");
return n6;
},
() => {
const n10 = t1$7();
const n8 = child(n10);
const n9 = next(n8);
const n54 = t2$6();
const x8 = txt(n8);
on$1(n8, "click", close);
const x9 = txt(n9);
on$1(n9, "click", confirm);
on$1(n10, "click", withModifiers(() => {
}, ["stop"]));
renderEffect(() => {
const _theme = unref(theme);
setClass(n10, ["uni-picker__header-btn", ["header-btn--" + _theme]]);
setClass(n8, ["uni-picker__header-btn-cancel", ["header-btn-cannel--" + _theme]]);
setText(x8, normalizeUniText(toDisplayString(unref(cancelText))));
setText(x9, normalizeUniText(toDisplayString(unref(confirmText))));
});
setInsertionState(n54);
withComponentId("3bf71206", () => createComponentWithFallback(_component_picker_view, {
style: { "flex": "1" },
onChange: () => handleChange,
"mask-top-style": () => unref(maskTopStyle),
"mask-bottom-style": () => unref(maskBottomStyle),
indicatorStyle: () => unref(indicatorStyle),
value: () => unref(value)
}, extend$1(() => {
const n11 = createIf(
() => unref(mode) == "selector",
() => {
const n16 = withComponentId("3bf719c2", () => createComponentWithFallback(_component_picker_view_column, null, extend$1(() => {
const n13 = createFor(
() => unref(range),
(_for_item0, _for_key0) => {
const n15 = t0$9();
const x15 = txt(n15);
renderEffect(() => {
const _rangeKey = unref(rangeKey);
const _item = _for_item0.value;
setClass(n15, ["uni-picker__view-item", ["view-item--" + unref(theme)]]);
setText(x15, normalizeUniText(toDisplayString(_rangeKey ? _item[_rangeKey] : _item)));
});
return n15;
},
(item, selectorIdx) => selectorIdx,
40
/* IS_SINGLE_NODE, SLOT_ROOT */
);
return n13;
}, {
_: 1
/* NON_STABLE */
})));
return n16;
},
null,
129
/* TRUE_SINGLE_ROOT, SLOT_ROOT */
);
const n17 = createIf(
() => unref(mode) == "multiSelector",
() => {
const n19 = createFor(
() => unref(range),
(_for_item0, _for_key0) => {
const n24 = withComponentId("3bf728cb-" + _for_key0.value, () => createComponentWithFallback(_component_picker_view_column, null, extend$1(() => {
const n21 = createFor(
() => _for_item0.value,
(_for_item1, _for_key1) => {
const n23 = t0$9();
const x23 = txt(n23);
renderEffect(() => {
const _rangeKey = unref(rangeKey);
const _column = _for_item1.value;
setClass(n23, ["uni-picker__view-item", ["view-item--" + unref(theme)]]);
setText(x23, normalizeUniText(toDisplayString(_rangeKey ? _column[_rangeKey] : _column)));
});
return n23;
},
(column, colIdx) => colIdx,
40
/* IS_SINGLE_NODE, SLOT_ROOT */
);
return n21;
}, {
_: 1
/* NON_STABLE */
})));
return n24;
},
(item, multiIdx) => multiIdx,
34
/* IS_COMPONENT, SLOT_ROOT */
);
return n19;
},
null,
129
/* TRUE_SINGLE_ROOT, SLOT_ROOT */
);
const n25 = createIf(
() => unref(mode) == "time",
() => {
const n30 = withComponentId("3bf7837a", () => createComponentWithFallback(_component_picker_view_column, null, extend$1(() => {
const n27 = createFor(
() => unref(hours),
(_for_item0, _for_key0) => {
const n29 = t0$9();
const x29 = txt(n29);
renderEffect(() => {
setClass(n29, ["uni-picker__view-item", ["view-item--" + unref(theme)]]);
setText(x29, normalizeUniText(toDisplayString(_for_item0.value)));
});
return n29;
},
(h, hIdx) => h,
40
/* IS_SINGLE_NODE, SLOT_ROOT */
);
return n27;
}, {
_: 1
/* NON_STABLE */
})));
const n34 = withComponentId("3bf78ac3", () => createComponentWithFallback(_component_picker_view_column, null, extend$1(() => {
const n31 = createFor(
() => unref(minutes),
(_for_item0, _for_key0) => {
const n33 = t0$9();
const x33 = txt(n33);
renderEffect(() => {
setClass(n33, ["uni-picker__view-item", ["view-item--" + unref(theme)]]);
setText(x33, normalizeUniText(toDisplayString(_for_item0.value)));
});
return n33;
},
(m, mIdx) => m,
40
/* IS_SINGLE_NODE, SLOT_ROOT */
);
return n31;
}, {
_: 1
/* NON_STABLE */
})));
return [n30, n34];
},
null,
130
/* TRUE_MULTI_ROOT, SLOT_ROOT */
);
const n35 = createIf(
() => unref(mode) == "date",
() => {
const n40 = withComponentId("3bf7954e", () => createComponentWithFallback(_component_picker_view_column, null, extend$1(() => {
const n37 = createFor(
() => unref(years),
(_for_item0) => {
const n39 = t0$9();
const x39 = txt(n39);
renderEffect(() => {
setClass(n39, ["uni-picker__view-item", ["view-item--" + unref(theme)]]);
setText(x39, normalizeUniText(toDisplayString(_for_item0.value) + toDisplayString(unref(yearText))));
});
return n39;
},
(year) => year,
40
/* IS_SINGLE_NODE, SLOT_ROOT */
);
return n37;
}, {
_: 1
/* NON_STABLE */
})));
const n41 = createIf(() => unref(fields) != "year", () => {
const n46 = withComponentId("3bf79ccf", () => createComponentWithFallback(_component_picker_view_column, null, extend$1(() => {
const n43 = createFor(
() => unref(monthsText),
(_for_item0) => {
const n45 = t0$9();
const x45 = txt(n45);
renderEffect(() => {
setClass(n45, ["uni-picker__view-item", ["view-item--" + unref(theme)]]);
setText(x45, normalizeUniText(toDisplayString(formatSingle(_for_item0.value)) + toDisplayString(unref(monthText))));
});
return n45;
},
(month) => month,
40
/* IS_SINGLE_NODE, SLOT_ROOT */
);
return n43;
}, {
_: 1
/* NON_STABLE */
})));
return n46;
});
const n47 = createIf(() => unref(fields) == "day", () => {
const n52 = withComponentId("3bf7f3bd", () => createComponentWithFallback(_component_picker_view_column, null, extend$1(() => {
const n49 = createFor(
() => unref(days),
(_for_item0) => {
const n51 = t0$9();
const x51 = txt(n51);
renderEffect(() => {
setClass(n51, ["uni-picker__view-item", ["view-item--" + unref(theme)]]);
setText(x51, normalizeUniText(toDisplayString(formatSingle(_for_item0.value)) + toDisplayString(unref(dayText))));
});
return n51;
},
(day) => day,
40
/* IS_SINGLE_NODE, SLOT_ROOT */
);
return n49;
}, {
_: 1
/* NON_STABLE */
})));
return n52;
});
return [n40, n41, n47];
},
null,
130
/* TRUE_MULTI_ROOT, SLOT_ROOT */
);
return [n11, n17, n25, n35];
}, {
_: 1
/* NON_STABLE */
})));
return [n10, n54];
},
265
/* TRUE_SINGLE_ROOT, FALSE_MULTI_ROOT, KEYED_INDEX_0 */
);
setStaticTemplateRef(n56, containerRef, null, "containerRef");
return n56;
}
});
const _style_0$9 = "\n.uni-picker__container {\n flex: 1;\n}\n.uni-picker__mask {\n flex: 1;\n background-color: rgba(0, 0, 0, .3);\n opacity: 0;\n transition-property: opacity;\n transition-duration: 0.3s;\n}\n.picker__mask--dark {\n background-color: rgba(0, 0, 0, .6);\n}\n.picker__ani-show {\n opacity: 1;\n}\n.uni-picker__inner-box {\n position: absolute;\n bottom: 0;\n left: 0;\n right: 0;\n height: 300px;\n transform: translateY(100%);\n transition-property: transform;\n transition-duration: 0.2s;\n}\n.picker__ani-box-show {\n transform: translateY(0%);\n}\n.uni-picker__header-btn {\n flex-direction: row;\n justify-content: space-between;\n border-bottom: 1px #f7f7f7 solid;\n}\n.uni-picker__header-btn-cancel {\n font-size: 14px;\n padding: 15px;\n background-color: transparent;\n}\n.uni-picker__header-btn-ok {\n font-size: 14px;\n padding: 15px;\n color: #007aff;\n}\n.uni-picker__view {\n position: relative;\n flex: 1;\n}\n.uni-picker__view-item {\n width: 100%;\n text-align: center;\n height: 50px;\n line-height: 50px;\n}\n.inner-box--light {\n background-color: #fff;\n}\n.header-btn-cannel--light {\n color: #000;\n}\n.inner-box--dark {\n background-color: #232323;\n}\n.header-btn-cannel--dark {\n color: rgba(255, 255, 255, .8);\n}\n.view-item--dark {\n color: rgba(255, 255, 255, .8);\n}\n.header-btn--dark {\n border-color: rgba(255, 255, 255, .05);\n}\n.uni-picker__mask {\n /* 建立滚动容器,通过 CSS 阻止遮罩上的滚动传递到背景页面。 */\n overflow: auto;\n overscroll-behavior: none;\n touch-action: none;\n}\n.uni-picker__container--desktop .uni-picker__mask {\n background-color: transparent;\n}\n.uni-picker__inner-box--desktop {\n transform: none;\n opacity: 0;\n border-radius: 5px;\n box-shadow: 0 0 20px 5px rgba(0, 0, 0, .3);\n transition-property: opacity;\n}\n.uni-picker__inner-box--desktop.picker__ani-box-show {\n transform: none;\n opacity: 1;\n}\n.uni-picker__inner-box--desktop .uni-picker__header-btn {\n flex-shrink: 0;\n}\n.uni-picker__inner-box--desktop .uni-picker__view {\n min-height: 0;\n overflow: hidden;\n border-radius: 0 0 5px 5px;\n}\n.uni-picker__select {\n height: 100%;\n box-sizing: border-box;\n padding: 6px 0;\n border-radius: 5px;\n overscroll-behavior: contain;\n}\n.uni-picker__select .uni-scroll-view {\n overscroll-behavior: contain;\n}\n.uni-picker__select-item {\n flex-shrink: 0;\n height: 34px;\n line-height: 34px;\n padding: 0 10px;\n text-align: center;\n color: #555;\n white-space: nowrap;\n text-overflow: ellipsis;\n overflow: hidden;\n cursor: pointer;\n}\n.uni-picker__select-item:hover {\n background-color: #f6f6f6;\n}\n.uni-picker-theme--dark .uni-picker__select-item {\n color: rgba(255, 255, 255, .8);\n}\n.uni-picker-theme--dark .uni-picker__select-item:hover {\n background-color: rgba(255, 255, 255, .1);\n}\n.uni-picker__select-item.uni-picker__select-item--selected {\n color: #007aff;\n}\n\n";
const _export_sfc = (sfc, props2) => {
const target = sfc.__vccOpts || sfc;
for (const [key, val] of props2) {
target[key] = val;
}
return target;
};
const UniPickerPage = /* @__PURE__ */ _export_sfc(_sfc_main$9, [["styles", [_style_0$9]]]);
const openDialogPage = (options) => {
var _a, _b, _c;
if (!options.url) {
triggerFailCallback(options, "url is required");
return null;
}
let { path, query } = parseUrl(options.url);
path = normalizeRoute(path);
if (path === "uni:picker") {
registerSystemRoute(path, UniPickerPage);
}
const normalizeUrl = createNormalizeUrl("navigateTo");
const errMsg = normalizeUrl(options.url, {});
if (errMsg) {
triggerFailCallback(options, errMsg);
return null;
}
const targetRoute = __uniRoutes.find((route) => {
return route.path === path || `/${route.meta.route}` === path;
});
const dialogPage = markRaw(
new UniDialogPageImpl({
route: removeLeadingSlash(path),
// 忽略类型,不同环境UTSJSONObject表示不同类型。此处直接传普通object即可,获取options时再进行处理
options: query,
$component: targetRoute.component,
getParentPage: () => null,
$disableEscBack: options.disableEscBack,
$triggerParentHide: !!options.triggerParentHide
})
);
let parentPage = options.parentPage;
const currentPages = getCurrentPages();
if (parentPage) {
if (currentPages.indexOf(parentPage) === -1) {
triggerFailCallback(options, "parentPage is not a valid page");
return null;
}
}
if (!isSystemDialogPage(dialogPage)) {
if (!currentPages.length) {
homeDialogPages.push(dialogPage);
} else {
if (!parentPage) {
parentPage = currentPages[currentPages.length - 1];
}
dialogPageTriggerPrevDialogPageLifeCycle(parentPage, ON_HIDE);
dialogPage.getParentPage = () => parentPage;
parentPage.getDialogPages().push(dialogPage);
}
} else {
let targetSystemDialogPages = [];
if (!currentPages.length) {
targetSystemDialogPages = homeSystemDialogPages;
} else {
if (!parentPage) {
parentPage = currentPages[currentPages.length - 1];
}
dialogPageTriggerPrevDialogPageLifeCycle(parentPage, ON_HIDE);
dialogPage.getParentPage = () => parentPage;
targetSystemDialogPages = (_a = parentPage.vm.$pageLayoutInstance) == null ? void 0 : _a.$systemDialogPages.value;
}
targetSystemDialogPages.push(dialogPage);
if (isSystemActionSheetDialogPage(dialogPage)) {
closePreSystemDialogPage(
targetSystemDialogPages,
SYSTEM_DIALOG_ACTION_SHEET_PAGE_PATH$1,
(preSystemDialogPage) => {
if (!preSystemDialogPage.$disableEscBack) {
decrementEscBackPageNum();
}
}
);
}
}
if (!dialogPage.$disableEscBack) {
incrementEscBackPageNum();
}
const successOptions = {
errMsg: "openDialogPage:ok"
};
(_b = options.success) == null ? void 0 : _b.call(options, successOptions);
(_c = options.complete) == null ? void 0 : _c.call(options, successOptions);
return dialogPage;
};
function triggerFailCallback(options, errMsg) {
var _a, _b;
const failOptions = new UniError(
"uni-openDialogPage",
4,
`openDialogPage: fail, ${errMsg}`
);
(_a = options.fail) == null ? void 0 : _a.call(options, failOptions);
(_b = options.complete) == null ? void 0 : _b.call(options, failOptions);
}
const t0$8 = template("<div uni-view data-v-212d40c7><span uni-text data-v-212d40c7 class=uni-action-sheet_dialog__title__text> </div>");
const t1$6 = template("<div uni-view data-v-212d40c7 class=divider>", 2);
const t2$5 = template("<div uni-view data-v-212d40c7 class=divider>");
const t3$2 = template("<div uni-view data-v-212d40c7><span uni-text data-v-212d40c7 class=uni-action-sheet_dialog__cell__text> ");
const t4$2 = template("<div uni-view data-v-212d40c7 class=uni-action-sheet_dialog__safe-area>");
const t5$1 = template("<div uni-view data-v-212d40c7>");
const t6$1 = template("<div uni-view data-v-212d40c7><div uni-view data-v-212d40c7></div><div uni-view data-v-212d40c7><div uni-view data-v-212d40c7><!><div uni-view data-v-212d40c7></div></div><div uni-view data-v-212d40c7><span uni-text data-v-212d40c7 class=uni-action-sheet_dialog__action__text> </div>", 1);
const _sfc_main$8 = /* @__PURE__ */ defineVaporComponent({
__name: "actionSheet",
setup(__props) {
const pageInstance = getCurrentInstance().proxy;
const uniPageInstance = pageInstance.$page;
const show = ref(false);
const isClosing = ref(false);
const maskAnimationClass = computed(() => {
if (isClosing.value) {
return "uni-action-sheet_dialog__mask__hide";
}
return show.value ? "uni-action-sheet_dialog__mask__show" : "";
});
const containerAnimationClass = computed(() => {
const classes2 = [];
if (isClosing.value) {
classes2.push("uni-action-sheet_dialog__hide");
} else if (show.value) {
classes2.push("uni-action-sheet_dialog__show");
}
if (isLandscape2.value) {
classes2.push("uni-action-sheet_landscape__mode");
}
return classes2.join(" ");
});
const i18nCancelText = reactive({
en: "Cancel",
es: "Cancelar",
fr: "Annuler",
zhHans: "取消",
zhHant: "取消"
});
const readyEventName = ref("");
const optionsEventName = ref("");
const successEventName = ref("");
const failEventName = ref("");
const title = ref(null);
const itemList = ref([]);
const optionCancelText = ref(null);
const titleColor = ref(null);
const itemColor = ref(null);
const cancelColor = ref(null);
const backgroundColor = ref(null);
const language = ref("zhHans");
const isLandscape2 = ref(false);
const bottomNavigationHeight = ref(0);
const menuItemClicked = ref(false);
const cancelButtonClicked = ref(false);
const windowWidth = ref(0);
const windowHeight = ref(0);
const popover = reactive({});
const fixSize = () => {
const windowInfo = uni.getWindowInfo();
windowWidth.value = windowInfo.windowWidth;
windowHeight.value = windowInfo.windowHeight + (windowInfo.windowTop || 0);
};
const getCloseAnimationDelay = () => {
return 180;
};
const closeActionSheet = () => {
if (isClosing.value) {
return;
}
isClosing.value = true;
show.value = false;
setTimeout(() => {
uni.closeDialogPage({
dialogPage: uniPageInstance
});
}, getCloseAnimationDelay());
};
const handleMenuItemClick = (tapIndex) => {
menuItemClicked.value = true;
closeActionSheet();
uni.$emit(successEventName.value, tapIndex);
};
const handleCancel = () => {
cancelButtonClicked.value = true;
closeActionSheet();
uni.$emit(failEventName.value, {});
};
onLoad((options) => {
readyEventName.value = options["readyEventName"];
optionsEventName.value = options["optionsEventName"];
successEventName.value = options["successEventName"];
failEventName.value = options["failEventName"];
uni.$on(optionsEventName.value, (data) => {
itemList.value = data["itemList"];
if (data["title"] != null) {
title.value = data["title"];
}
if (data["cancelText"] != null) {
optionCancelText.value = data["cancelText"];
}
if (data["titleColor"] != null) {
titleColor.value = data["titleColor"];
}
if (data["itemColor"] != null) {
itemColor.value = data["itemColor"];
}
if (data["cancelColor"] != null) {
cancelColor.value = data["cancelColor"];
}
if (data["backgroundColor"] != null) {
backgroundColor.value = data["backgroundColor"];
}
if (data["popover"] != null) {
popover.value = data["popover"];
}
});
uni.$emit(readyEventName.value, {});
const deviceInfo = uni.getDeviceInfo();
const appInfo = uni.getAppBaseInfo();
if (appInfo.appLanguage != null) {
language.value = appInfo.appLanguage;
} else if (deviceInfo.osLanguage != null) {
language.value = deviceInfo.osLanguage;
}
fixSize();
window.addEventListener("resize", fixSize);
const locale = uni.getLocale();
language.value = locale;
uni.onLocaleChange((res) => {
if (res.locale) {
language.value = res.locale;
}
});
isLandscape2.value = deviceInfo.deviceOrientation == "landscape";
});
const isWidescreen = computed(() => {
return windowHeight.value >= 500 && windowWidth.value >= 500;
});
const containerStyle = computed(() => {
if (Object.keys(popover).length == 0) {
return {};
}
const res = {
transform: "none !important"
};
const top = popover.top;
const left = popover.left;
const width = popover.width;
const height = popover.height;
const center = left + width / 2;
const contentLeft = Math.max(0, center - 300 / 2);
res["left"] = `${contentLeft}px`;
const vcl = windowHeight.value / 2;
if (top + height - vcl > vcl - top) {
res["top"] = "auto";
res["bottom"] = `${windowHeight.value - top + 6}px`;
} else {
res["top"] = `${top + height + 6}px`;
}
return res;
});
const triangleStyle = computed(() => {
if (Object.keys(popover).length == 0) {
return {};
}
const res = {};
const top = popover.top;
const left = popover.left;
const width = popover.width;
const height = popover.height;
const center = left + width / 2;
const contentLeft = Math.max(0, center - 300 / 2);
let triangleLeft = Math.max(12, center - contentLeft);
triangleLeft = Math.min(300 - 12, triangleLeft);
res["left"] = `${triangleLeft}px`;
const vcl = windowHeight.value / 2;
if (top + height - vcl > vcl - top) {
res["bottom"] = "-6px";
res["border-width"] = "6px 6px 0 6px";
if (backgroundColor.value != null) {
res["border-color"] = `${backgroundColor.value} transparent transparent transparent`;
}
} else {
res["top"] = "-6px";
res["border-width"] = "0 6px 6px 6px";
if (backgroundColor.value != null) {
res["border-color"] = `transparent transparent ${backgroundColor.value} transparent`;
}
}
return res;
});
const triangleClass = computed(() => {
if (Object.keys(popover).length == 0) {
return "";
}
return triangleStyle.value["bottom"] != null ? "uni-action-sheet_dialog__triangle--bottom" : "uni-action-sheet_dialog__triangle--top";
});
const cancelText = computed(() => {
if (optionCancelText.value != null) {
const res = optionCancelText.value;
return res;
}
if (language.value.startsWith("en")) {
return i18nCancelText["en"];
}
if (language.value.startsWith("es")) {
return i18nCancelText["es"];
}
if (language.value.startsWith("fr")) {
return i18nCancelText["fr"];
}
if (language.value.startsWith("zhHans")) {
return i18nCancelText["zhHans"];
}
if (language.value.startsWith("zhHant")) {
return i18nCancelText["zhHant"];
}
return "取消";
});
onReady(() => {
bottomNavigationHeight.value = uniPageInstance.safeAreaInsets.bottom;
requestAnimationFrame(() => {
requestAnimationFrame(() => {
if (!isClosing.value) {
show.value = true;
}
});
});
});
onResize((_) => {
const deviceInfo = uni.getDeviceInfo();
isLandscape2.value = deviceInfo.deviceOrientation == "landscape";
});
onBeforeUnmount(() => {
if (!menuItemClicked.value && !cancelButtonClicked.value) {
uni.$emit(failEventName.value, {});
}
uni.$off(optionsEventName.value, null);
uni.$off(readyEventName.value, null);
uni.$off(successEventName.value, null);
uni.$off(failEventName.value, null);
window.removeEventListener("resize", fixSize);
});
initUniPageHooks();
const n25 = t6$1();
const n0 = child(n25);
const n24 = next(n0);
const n15 = child(n24);
const n14 = child(n15);
const n13 = next(n14);
const n17 = next(n15);
const n16 = child(n17);
on$1(n0, "click", handleCancel);
renderEffect(() => {
const _backgroundColor = backgroundColor.value;
setClass(n0, ["uni-action-sheet_dialog__mask", maskAnimationClass.value]);
setStyle(n24, isWidescreen.value ? containerStyle.value : {});
setClass(n24, ["uni-action-sheet_dialog__container", containerAnimationClass.value]);
setStyle(n15, _backgroundColor != null ? { backgroundColor: _backgroundColor } : {});
setClassName(n15, isLandscape2.value ? 1 : 0, " uni-action-sheet_landscape__mode", "uni-action-sheet_dialog__menu");
});
setInsertionState(n15, n14);
createIf(
() => title.value,
() => {
const n4 = t0$8();
const n3 = child(n4);
const n5 = t1$6();
const x3 = txt(n3);
renderEffect(() => {
const _titleColor = titleColor.value;
setClassName(n4, isLandscape2.value ? 1 : 0, " uni-action-sheet_landscape__mode", "uni-action-sheet_dialog__title border-b");
setStyle(n3, _titleColor != null ? { color: _titleColor } : {});
setText(x3, normalizeUniText(toDisplayString(title.value)));
});
return [n4, n5];
},
null,
2
/* TRUE_MULTI_ROOT */
);
renderEffect(() => setClassName(n13, isLandscape2.value ? 1 : 0, " uni-action-sheet_landscape__mode", "uni-action-sheet_dialog__cell__container"));
setInsertionState(n13);
createFor(
() => itemList.value,
(_for_item0, _for_key0) => {
const n8 = createIf(
() => _for_key0.value !== 0,
() => {
const n10 = t2$5();
return n10;
},
null,
10
/* TRUE_MULTI_ROOT, FALSE_MULTI_ROOT */
);
const n12 = t3$2();
const n11 = child(n12);
const x11 = txt(n11);
on$1(n12, "click", () => handleMenuItemClick(_for_key0.value));
setHover(n12, "uni-action-sheet_dialog__hover", false, 50, 400, "");
renderEffect(() => {
const _itemColor = itemColor.value;
setClassName(n12, (isLandscape2.value ? 1 : 0) | (_for_key0.value !== 0 ? 2 : 0), [" uni-action-sheet_landscape__mode", " border-t"], "uni-action-sheet_dialog__cell");
setStyle(n11, _itemColor != null ? { color: _itemColor } : {});
setText(x11, normalizeUniText(toDisplayString(_for_item0.value)));
});
return [n8, n12];
},
(item, index2) => index2,
65
/* FAST_REMOVE, WRAPPED_ROWS */
);
const x16 = txt(n16);
on$1(n17, "click", handleCancel);
setHover(n17, "uni-action-sheet_dialog__hover", false, 50, 400, "");
renderEffect(() => {
const _backgroundColor = backgroundColor.value;
const _cancelColor = cancelColor.value;
setStyle(n17, _backgroundColor != null ? { backgroundColor: _backgroundColor } : {});
setClassName(n17, isLandscape2.value ? 1 : 0, " uni-action-sheet_landscape__mode", "uni-action-sheet_dialog__action");
setStyle(n16, _cancelColor != null ? { color: _cancelColor } : {});
setText(x16, normalizeUniText(toDisplayString(cancelText.value)));
});
setInsertionState(n24, 2);
createIf(() => !isLandscape2.value, () => {
const n20 = t4$2();
renderEffect(() => {
const _backgroundColor = backgroundColor.value;
const _bottomNavigationHeight = bottomNavigationHeight.value;
setStyle(n20, _backgroundColor != null ? { height: `${_bottomNavigationHeight}px`, backgroundColor: _backgroundColor } : { height: `${_bottomNavigationHeight}px` });
});
return n20;
});
setInsertionState(n24, 3);
createIf(() => isWidescreen.value && Object.keys(popover).length > 0, () => {
const n23 = t5$1();
renderEffect(() => {
setStyle(n23, triangleStyle.value);
setClass(n23, ["uni-action-sheet_dialog__triangle", triangleClass.value]);
});
return n23;
});
return n25;
}
});
const _style_0$8 = "\n.uni-action-sheet_dialog__mask {\n position: fixed;\n z-index: 999;\n top: 0;\n right: 0;\n left: 0;\n bottom: 0;\n opacity: 0;\n background-color: rgba(0, 0, 0, 0.6);\n}\n.uni-action-sheet_dialog__mask__hide {\n animation: uni-action-sheet-mask-fade-out 0.15s ease-in forwards;\n}\n.uni-action-sheet_dialog__mask__show {\n animation: uni-action-sheet-mask-fade-in 0.15s ease-out forwards;\n}\n.uni-action-sheet_dialog__container {\n position: fixed;\n width: 100%;\n left: 0;\n bottom: 0;\n z-index: 999;\n transform: translate(0, 100%);\n\n\n\n\n background-color: #f7f7f7;\n border-top-left-radius: 12px;\n border-top-right-radius: 12px;\n}\n.uni-action-sheet_dialog__menu {\n border-top-left-radius: 12px;\n border-top-right-radius: 12px;\n overflow: hidden;\n}\n.uni-action-sheet_dialog__container.uni-action-sheet_dialog__show {\n animation: uni-action-sheet-slide-in 0.15s ease-out forwards;\n}\n.uni-action-sheet_dialog__container.uni-action-sheet_dialog__hide {\n animation: uni-action-sheet-slide-out 0.15s ease-in forwards;\n}\n.uni-action-sheet_dialog__title,\n .uni-action-sheet_dialog__cell,\n .uni-action-sheet_dialog__action {\n padding: 16px;\n}\n.uni-action-sheet_dialog__title__text,\n .uni-action-sheet_dialog__cell__text,\n .uni-action-sheet_dialog__action__text {\n line-height: 1.4;\n text-align: center;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n.uni-action-sheet_dialog__action {\n margin-top: 8px;\n}\n.uni-action-sheet_dialog__title__text {\n color: #666666;\n}\n.uni-action-sheet_dialog__cell__text,\n .uni-action-sheet_dialog__action__text {\n color: #000000;\n}\n.uni-action-sheet_dialog__menu,\n .uni-action-sheet_dialog__action,\n .uni-action-sheet_dialog__safe-area {\n background-color: #ffffff;\n}\n.uni-action-sheet_dialog__cell__container {\n max-height: 330px;\n\n display: block;\n overflow-y: auto;\n scrollbar-width: none;\n}\n.uni-action-sheet_dialog__hover {\n background-color: #efefef;\n}\n.divider{\n height: 1px;\n background-color: #e5e5e5;\n transform: scaleY(0.5);\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n /* landscape mode */\n.uni-action-sheet_dialog__container.uni-action-sheet_landscape__mode {\n width: 300px;\n position: fixed;\n left: 50%;\n right: auto;\n top: 50%;\n bottom: auto;\n z-index: 999;\n transform: translate(-50%, -50%);\n border-top-left-radius: 5px;\n border-top-right-radius: 5px;\n border-bottom-left-radius: 5px;\n border-bottom-right-radius: 5px;\n\n animation: none;\n}\n.uni-action-sheet_dialog__menu.uni-action-sheet_landscape__mode {\n border-top-left-radius: 5px;\n border-top-right-radius: 5px;\n border-bottom-left-radius: 5px;\n border-bottom-right-radius: 5px;\n box-shadow: 0 0 20px 5px rgba(0, 0, 0, 0.3);\n}\n.uni-action-sheet_dialog__action.uni-action-sheet_landscape__mode {\n display: none;\n}\n.uni-action-sheet_dialog__cell__container.uni-action-sheet_landscape__mode {\n max-height: 260px;\n}\n.uni-action-sheet_dialog__title.uni-action-sheet_landscape__mode,\n .uni-action-sheet_dialog__cell.uni-action-sheet_landscape__mode,\n .uni-action-sheet_dialog__action.uni-action-sheet_landscape__mode {\n padding: 10px 6px;\n}\n.uni-action-sheet_dialog__menu {\n display: block;\n}\n.uni-action-sheet_dialog__title,\n .uni-action-sheet_dialog__cell,\n .uni-action-sheet_dialog__action {\n display: block;\n text-align: center;\n line-height: 1.4;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n.uni-action-sheet_dialog__cell,\n .uni-action-sheet_dialog__action {\n cursor: pointer;\n}\n.uni-action-sheet_dialog__triangle {\n position: absolute;\n width: 0;\n height: 0;\n margin-left: -6px;\n border-style: solid;\n}\n.uni-action-sheet_dialog__triangle--bottom {\n border-color: #fcfcfd transparent transparent transparent;\n}\n.uni-action-sheet_dialog__triangle--top {\n border-color: transparent transparent #fcfcfd transparent;\n}\n\n /* web wide screen */\n@media screen and (min-width: 500px) and (min-height: 500px) {\n.uni-action-sheet_dialog__mask {\n background: none;\n}\n.uni-action-sheet_dialog__container {\n width: 300px;\n position: fixed;\n left: 50%;\n right: auto;\n top: 50%;\n bottom: auto;\n z-index: 999;\n border-radius: 5px;\n transform: translate(-50%, -50%);\n box-shadow: 0 0 20px 5px rgba(0, 0, 0, 0.3);\n}\n.uni-action-sheet_dialog__container.uni-action-sheet_dialog__show,\n .uni-action-sheet_dialog__container.uni-action-sheet_dialog__hide {\n transform: translate(-50%, -50%);\n animation: none;\n}\n.uni-action-sheet_dialog__show {\n transform: translate(-50%, -50%) !important;\n}\n.uni-action-sheet_dialog__menu {\n border-radius: 5px;\n}\n.uni-action-sheet_dialog__cell__container {\n max-height: 260px;\n}\n.uni-action-sheet_dialog__action {\n display: none;\n}\n.uni-action-sheet_dialog__title {\n font-size: 15px;\n}\n.uni-action-sheet_dialog__title,\n .uni-action-sheet_dialog__cell,\n .uni-action-sheet_dialog__action {\n padding: 10px 6px;\n}\n}\n@media (prefers-color-scheme: dark) {\n.uni-action-sheet_dialog__container {\n background-color: #1D1E1E;\n}\n.uni-action-sheet_dialog__menu,\n .uni-action-sheet_dialog__action,\n .uni-action-sheet_dialog__safe-area {\n background-color: #2C2C2C;\n}\n.uni-action-sheet_dialog__title__text {\n color: #999999;\n}\n.uni-action-sheet_dialog__cell__text,\n .uni-action-sheet_dialog__action__text {\n color: #ffffff;\n}\n.uni-action-sheet_dialog__hover {\n background-color: #414141;\n}\n.divider {\n background-color: #2F3131;\n}\n.uni-action-sheet_dialog__triangle--bottom {\n border-color: #2C2C2C transparent transparent transparent;\n}\n.uni-action-sheet_dialog__triangle--top {\n border-color: transparent transparent #2C2C2C transparent;\n}\n}\n@keyframes uni-action-sheet-mask-fade-in {\nfrom {\n opacity: 0;\n}\nto {\n opacity: 1;\n}\n}\n@keyframes uni-action-sheet-mask-fade-out {\nfrom {\n opacity: 1;\n}\nto {\n opacity: 0;\n}\n}\n@keyframes uni-action-sheet-slide-in {\nfrom {\n transform: translate(0, 100%);\n}\nto {\n transform: translate(0, 0);\n}\n}\n@keyframes uni-action-sheet-slide-out {\nfrom {\n transform: translate(0, 0);\n}\nto {\n transform: translate(0, 100%);\n}\n}\n\n";
const UniActionSheetPage = /* @__PURE__ */ _export_sfc(_sfc_main$8, [["styles", [_style_0$8]]]);
class ShowActionSheetSuccessImpl {
constructor(tapIndex, errMsg = "showActionSheet:ok") {
this.errMsg = errMsg;
this.tapIndex = tapIndex;
}
}
class ShowActionSheetFailImpl extends UniError {
constructor(errMsg = "showActionSheet:fail cancel", errCode = 4) {
super();
this.errMsg = errMsg;
this.errCode = errCode;
}
}
const showActionSheet$1 = (options) => {
const uuid = `${Date.now()}${Math.floor(Math.random() * 1e7)}`;
const baseEventName = `uni_action_sheet_${uuid}`;
const readyEventName = `${baseEventName}_ready`;
const optionsEventName = `${baseEventName}_options`;
const successEventName = `${baseEventName}_success`;
const failEventName = `${baseEventName}_fail`;
uni.$on(readyEventName, () => {
uni.$emit(optionsEventName, JSON.parse(JSON.stringify(options)));
});
uni.$on(successEventName, (index2) => {
var _a, _b;
const res = new ShowActionSheetSuccessImpl(index2);
(_a = options.success) == null ? void 0 : _a.call(options, res);
(_b = options.complete) == null ? void 0 : _b.call(options, res);
});
uni.$on(failEventName, () => {
var _a, _b;
const res = new ShowActionSheetFailImpl();
(_a = options.fail) == null ? void 0 : _a.call(options, res);
(_b = options.complete) == null ? void 0 : _b.call(options, res);
});
uni.openDialogPage({
url: `uni:actionSheet?readyEventName=${readyEventName}&optionsEventName=${optionsEventName}&successEventName=${successEventName}&failEventName=${failEventName}`,
animationType: "none",
fail(err) {
var _a, _b;
const res = new ShowActionSheetFailImpl(`showActionSheet failed, ${err.errMsg}`);
(_a = options.fail) == null ? void 0 : _a.call(options, res);
(_b = options.complete) == null ? void 0 : _b.call(options, res);
uni.$off(readyEventName);
uni.$off(successEventName);
uni.$off(failEventName);
}
});
};
const SYSTEM_DIALOG_ACTION_SHEET_PAGE_PATH = "uni:actionSheet";
const hideActionSheet$1 = () => {
const pages = getCurrentPages();
const currentPage = pages[pages.length - 1];
if (currentPage == null)
return;
const systemDialogPages = currentPage.$getSystemDialogPages();
systemDialogPages.forEach((page) => {
if (page.route.startsWith(SYSTEM_DIALOG_ACTION_SHEET_PAGE_PATH)) {
uni.closeDialogPage({
dialogPage: page
});
}
});
};
const registerActionSheetOnce = /* @__PURE__ */ once(() => {
registerSystemRoute("uni:actionSheet", UniActionSheetPage);
});
const hideActionSheet = () => {
registerActionSheetOnce();
hideActionSheet$1();
};
const showActionSheet = /* @__PURE__ */ defineAsyncApi(
API_SHOW_ACTION_SHEET,
(args, { resolve, reject }) => {
registerActionSheetOnce();
showActionSheet$1(
/* @__PURE__ */ extend(
{
success: (res) => {
resolve(res);
},
fail: (err) => {
reject(err);
}
},
args
)
);
}
);
const t0$7 = template("<span uni-text data-v-212d40c7 class=uni-choose-location-poi-search-cancel> ");
const t1$5 = template("<div uni-view data-v-212d40c7 class=uni-choose-location-poi-search-error><span uni-text data-v-212d40c7> ");
const t2$4 = template("<div uni-view data-v-212d40c7 class=uni-choose-location-poi-search-loading><span uni-text data-v-212d40c7> ");
const t3$1 = template("<div uni-view data-v-212d40c7 class=uni-choose-location-poi-search-loading>");
const t4$1 = template('<span uni-text data-v-212d40c7 class="uni-choose-location-icons uni-choose-location-poi-item-selected-icon"> ');
const t5 = template("<div uni-view data-v-212d40c7><div uni-view data-v-212d40c7><div uni-view data-v-212d40c7><span uni-text data-v-212d40c7> </div><div uni-view data-v-212d40c7><span uni-text data-v-212d40c7> </div></div><!><div uni-view data-v-212d40c7></div>");
const t6 = template("<div uni-view data-v-212d40c7><div uni-view data-v-212d40c7><div uni-view data-v-212d40c7><span uni-text data-v-212d40c7> </div>");
const t7 = template('<div uni-view data-v-212d40c7><div uni-view data-v-212d40c7><!><div uni-view data-v-212d40c7 class=uni-choose-location-map-target><span uni-text data-v-212d40c7 class="uni-choose-location-icons uni-choose-location-map-target-icon"> </div><div uni-view data-v-212d40c7><span uni-text data-v-212d40c7> </div></div><div uni-view data-v-212d40c7 class=uni-choose-location-nav><div uni-view data-v-212d40c7><span uni-text data-v-212d40c7 class="uni-choose-location-nav-text uni-choose-location-nav-back-text"> </div><div uni-view data-v-212d40c7><span uni-text data-v-212d40c7 class="uni-choose-location-nav-text uni-choose-location-nav-confirm-text"> </div></div>', 1);
const _sfc_main$7 = /* @__PURE__ */ defineVaporComponent({
__name: "chooseLocation",
setup(__props) {
const defaultPoi = {
latitude: 39.908823,
longitude: 116.39747
};
const languageData = {
"en": {
"ok": "ok",
"cancel": "cancel",
"locationLoading": "positioning...",
"search": "Search location"
},
"zh-Hans": {
"ok": "确定",
"cancel": "取消",
"locationLoading": "获取定位中...",
"search": "搜索地点"
},
"zh-Hant": {
"ok": "確定",
"cancel": "取消",
"locationLoading": "獲取定位中...",
"search": "蒐索地點"
}
};
const currentInstance = getCurrentInstance().proxy;
const uniPage = currentInstance.$page;
const readyEventName = ref("");
const optionsEventName = ref("");
const successEventName = ref("");
const failEventName = ref("");
const mapId = ref(`UniMap1_${(Math.random() * 1e6).toString(36)}`);
const isFocus = ref(false);
const latitude = ref(0);
const longitude = ref(0);
const locationComplete = ref(false);
const locationLoading = ref(false);
const chooseLocationOptions = reactive({});
const pageIndex = ref(1);
const pageSize = ref(20);
const pois = ref([]);
const selected = ref(-1);
const searchValue = ref("");
const safeArea = reactive({
top: 0,
bottom: 0,
left: 0,
right: 0
});
const icon = reactive({
target: "",
success: "",
position: "",
search: ""
});
ref(0);
const searchLoading = ref(false);
const language = ref("zh-Hans");
const scrollTop = ref(0);
const isLandscape2 = ref(false);
const theme = ref("light");
const searchValueChangeTimer = ref(-1);
const lastPoi = reactive({
latitude: null,
longitude: null,
selected: -1,
pois: [],
scrollTop: 0
});
const errMsg = ref("");
const callUniMapCoErr = ref(false);
const useUniCloud = ref(true);
const mapHeight = ref(350);
const timeoutTimers = ref([]);
const mapTargetRef = ref(null);
const scrollRef = ref(null);
const checkUniCloud = () => {
if (typeof uniCloud == "undefined" || typeof uniCloud.config == "undefined" || uniCloud.config.spaceId == "") {
errMsg.value = "uni.chooseLocation 依赖 uniCloud 的 uni-map-common 插件,请先关联服务空间,并安装 uni-map-common 插件,插件地址:https://ext.dcloud.net.cn/plugin?id=13872";
useUniCloud.value = false;
console.error(errMsg.value);
}
};
const initPageOptions = (options) => {
readyEventName.value = options["readyEventName"];
optionsEventName.value = options["optionsEventName"];
successEventName.value = options["successEventName"];
failEventName.value = options["failEventName"];
uni.$on(optionsEventName.value, (data) => {
if (data["latitude"] != null) {
chooseLocationOptions.latitude = data["latitude"];
}
if (data["longitude"] != null) {
chooseLocationOptions.longitude = data["longitude"];
}
if (data["keyword"] != null) {
let keyword = data["keyword"];
chooseLocationOptions.keyword = keyword;
searchValue.value = keyword;
} else {
chooseLocationOptions.keyword = "";
}
if (data["payload"] != null) {
chooseLocationOptions.payload = data["payload"];
}
});
uni.$emit(readyEventName.value, {});
};
const callUniMapCo = (action, data) => {
let promise = new Promise((resolve, reject) => {
if (useUniCloud.value == false) {
reject(errMsg.value);
return;
}
errMsg.value = "";
const uniMapCo = uniCloud.importObject("uni-map-co", {
customUI: true
});
let chooseLocationData = {
action,
data
};
if (chooseLocationOptions.payload != null) {
chooseLocationData["payload"] = chooseLocationOptions.payload;
}
uniMapCo.chooseLocation(chooseLocationData).then((res) => {
resolve(res);
}).catch((err) => {
if (err instanceof UniCloudError) {
const cloudError = err;
const errCode = cloudError.errCode;
const errorMsg = cloudError.errMsg;
const errSubject = cloudError.errSubject;
if (errorMsg.indexOf("在云端不存在") > -1 || errorMsg.indexOf("未匹配") > -1) {
errMsg.value = "uni.chooseLocation 依赖 uniCloud 的 uni-map-common 插件,请安装 uni-map-common 插件,插件地址:https://ext.dcloud.net.cn/plugin?id=13872";
console.error(errMsg.value);
} else {
errMsg.value = errorMsg;
console.error("获取POI信息失败," + JSON.stringify({ errCode, errMsg: errorMsg, errSubject }));
}
}
reject(err);
});
});
promise.then((res) => {
callUniMapCoErr.value = false;
}).catch((err) => {
callUniMapCoErr.value = true;
});
return promise;
};
const calcDirection = (poi1, poi2) => {
const toRadians = (angle2) => angle2 * (Math.PI / 180);
const toDegrees = (angle2) => angle2 * (180 / Math.PI);
const lat1 = toRadians(poi1.latitude);
const lon1 = toRadians(poi1.longitude);
const lat2 = toRadians(poi2.latitude);
const lon2 = toRadians(poi2.longitude);
const dLon = lon2 - lon1;
const y = Math.sin(dLon) * Math.cos(lat2);
const x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon);
const angleRadians = Math.atan2(y, x);
let angle = toDegrees(angleRadians);
angle = (angle + 360) % 360;
if (angle < 22.5 || angle >= 337.5) {
return "北";
} else if (angle >= 22.5 && angle < 67.5) {
return "东北";
} else if (angle >= 67.5 && angle < 112.5) {
return "东";
} else if (angle >= 112.5 && angle < 157.5) {
return "东南";
} else if (angle >= 157.5 && angle < 202.5) {
return "南";
} else if (angle >= 202.5 && angle < 247.5) {
return "西南";
} else if (angle >= 247.5 && angle < 292.5) {
return "西";
} else {
return "西北";
}
};
const distanceHandle = (distance) => {
if (distance < 1e3) {
return distance + "m";
} else {
return parseFloat((distance / 1e3).toFixed(2)) + "km";
}
};
const safeSetTimeout = (callback, delay) => {
let timerId = -1;
timerId = setTimeout(() => {
callback();
const index2 = timeoutTimers.value.indexOf(timerId);
if (index2 > -1) {
timeoutTimers.value.splice(index2, 1);
}
}, delay);
timeoutTimers.value.push(timerId);
return timerId;
};
const updateScrollTop = (scrollTopValue) => {
safeSetTimeout(() => {
scrollTop.value = scrollTopValue;
}, 10);
};
const poiHandle = (poisData) => {
let list2 = poisData.map((item, index22) => {
const location2 = item["location"];
let distance = item["distance"];
let lat = location2["lat"];
let lng = location2["lng"];
if (distance == 0) {
lat = latitude.value;
lng = longitude.value;
}
return {
title: item["title"],
address: item["address"],
distance,
distanceStr: distanceHandle(distance),
location: {
latitude: lat,
longitude: lng
}
};
});
let index2 = pageIndex.value;
if (index2 == 1) {
pois.value = list2;
updateScrollTop(0);
} else {
pois.value = pois.value.concat(list2);
}
};
const getPoi = (type) => {
let searchVal = searchValue.value;
let lat = latitude.value;
let lng = longitude.value;
let index2 = pageIndex.value;
let size = pageSize.value;
if (["searchValueChange"].indexOf(type) == -1) {
searchLoading.value = true;
}
if (searchVal != "" && searchVal.length > 0) {
callUniMapCo("search", {
keyword: searchVal,
location: {
lat,
lng
},
radius: 5e3,
auto_extend: 1,
orderby: "weight",
page_index: index2,
page_size: size
}).then((res) => {
var _a, _b;
let poisData;
const data = (_b = (_a = res["result"]) == null ? void 0 : _a["result"]) == null ? void 0 : _b["data"];
poisData = Array.isArray(data) ? data : null;
poiHandle(poisData);
searchLoading.value = false;
}).catch((err) => {
searchLoading.value = false;
});
} else {
callUniMapCo("location2address", {
location: `${lat},${lng}`,
get_poi: 1,
poi_options: {
radius: 3e3,
policy: index2 == 1 ? 3 : 4,
roadlevel: 1,
homeorcorp: 1,
page_index: index2,
page_size: size
}
}).then((res) => {
var _a, _b;
let poisData;
const data = (_b = (_a = res["result"]) == null ? void 0 : _a["result"]) == null ? void 0 : _b["pois"];
poisData = Array.isArray(data) ? data : null;
poiHandle(poisData);
if (pois.value.length > 0 && index2 == 1) {
let poi = pois.value[0];
if (poi.distance > 0) {
let poi1 = poi.location;
let poi2 = {
latitude: latitude.value,
longitude: longitude.value
};
let distance = poi.distance;
let direction2 = calcDirection(poi1, poi2);
if (poi.address.indexOf("米") == -1) {
let suffix = `向${direction2}${distance}米`;
let newPoi = {
title: `${poi.title}${suffix}`,
address: `${poi.address}${suffix}`,
distance: 0,
distanceStr: distanceHandle(distance),
location: poi2
};
pois.value.unshift(newPoi);
}
}
searchLoading.value = false;
if (selected.value == -1) {
safeSetTimeout(() => {
selected.value = 0;
}, 20);
lastPoi.latitude = latitude.value;
lastPoi.longitude = longitude.value;
lastPoi.selected = selected.value;
lastPoi.pois = pois.value;
}
}
}).catch((err) => {
searchLoading.value = false;
});
}
};
const getLocation2 = () => {
if (chooseLocationOptions.latitude != null && chooseLocationOptions.longitude != null) {
latitude.value = chooseLocationOptions.latitude;
longitude.value = chooseLocationOptions.longitude;
locationComplete.value = true;
getPoi("getLocation");
} else {
locationLoading.value = true;
uni.getLocation({
type: "gcj02",
success: (res) => {
latitude.value = res.latitude;
longitude.value = res.longitude;
locationComplete.value = true;
locationLoading.value = false;
getPoi("getLocation");
},
fail: (err) => {
console.error("getLocationErr: ", err);
latitude.value = defaultPoi.latitude;
longitude.value = defaultPoi.longitude;
locationComplete.value = true;
locationLoading.value = false;
getPoi("getLocation");
}
});
}
};
const getSafeAreaInsets2 = () => {
const info = uni.getWindowInfo();
safeArea.top = info.safeAreaInsets.top;
safeArea.bottom = info.safeAreaInsets.bottom;
safeArea.left = info.safeAreaInsets.left;
safeArea.right = info.safeAreaInsets.right;
};
const getMapContext = () => {
return uni.createMapContext(mapId.value, currentInstance);
};
const regionchange = (e2) => {
let causedBy = e2.causedBy;
if (!causedBy) {
causedBy = e2.detail.causedBy;
}
if (e2.type !== "end" || causedBy != "drag" || locationComplete.value == false) {
return;
}
const mapContext = getMapContext();
if (mapContext != null) {
mapContext.getCenterLocation({
success: (res) => {
let latitudeDiff = Math.abs(res.latitude - latitude.value);
let longitudeDiff = Math.abs(res.longitude - longitude.value);
if (latitudeDiff > 1e-6 || longitudeDiff > 1e-6) {
latitude.value = parseFloat(res.latitude.toFixed(6));
longitude.value = parseFloat(res.longitude.toFixed(6));
searchValue.value = "";
selected.value = -1;
pageIndex.value = 1;
getPoi("regionchange");
const element = mapTargetRef.value;
if (element != null) {
const duration = 250;
element.style.setProperty("transition-duration", `${duration}ms`);
element.style.setProperty("transform", "translateY(0px)");
element.style.setProperty("transform", "translateY(-15px)");
safeSetTimeout(() => {
element.style.setProperty("transform", "translateY(0px)");
}, duration);
}
}
}
});
}
};
const clearSearchValueChangeTimer = () => {
if (searchValueChangeTimer.value != -1) {
clearTimeout(searchValueChangeTimer.value);
searchValueChangeTimer.value = -1;
}
};
const clearAllTimeoutTimers = () => {
timeoutTimers.value.forEach((timer) => {
if (timer != -1) {
clearTimeout(timer);
}
});
timeoutTimers.value = [];
};
const poiSearch = (type) => {
clearSearchValueChangeTimer();
pageIndex.value = 1;
selected.value = -1;
getPoi(type);
};
const searchValueChange = (e2) => {
clearSearchValueChangeTimer();
searchValueChangeTimer.value = setTimeout(() => {
poiSearch("searchValueChange");
}, 200);
};
const cancelSearch = () => {
isFocus.value = false;
searchValue.value = "";
if (lastPoi.latitude != null) {
latitude.value = lastPoi.latitude;
}
if (lastPoi.longitude != null) {
longitude.value = lastPoi.longitude;
}
if (lastPoi.pois.length - 1 > lastPoi.selected) {
pois.value = lastPoi.pois;
selected.value = lastPoi.selected;
updateScrollTop(lastPoi.scrollTop);
} else {
poiSearch("cancelSearch");
}
};
const selectPoi = (item, index2) => {
isFocus.value = false;
selected.value = index2;
latitude.value = item.location.latitude;
longitude.value = item.location.longitude;
if (searchValue.value == chooseLocationOptions.keyword) {
lastPoi.latitude = latitude.value;
lastPoi.longitude = longitude.value;
lastPoi.selected = selected.value;
lastPoi.pois = pois.value;
const scrollElement = scrollRef.value;
if (scrollElement != null) {
const scrollTopVal = scrollElement.scrollTop;
lastPoi.scrollTop = scrollTopVal;
scrollTop.value = scrollTopVal;
}
}
};
const scrolltolower = () => {
pageIndex.value++;
getPoi("scrolltolower");
};
const mapReset = () => {
isFocus.value = false;
pageIndex.value = 1;
selected.value = -1;
getLocation2();
};
const closeDialogPage2 = () => {
uni.closeDialogPage({
dialogPage: uniPage
});
};
const back = () => {
uni.$emit(failEventName.value, 1);
closeDialogPage2();
};
const confirm = () => {
if (selected.value < 0) {
if (callUniMapCoErr.value) {
uni.$emit(successEventName.value, {
name: "",
address: "",
latitude: parseFloat(latitude.value.toFixed(6)),
longitude: parseFloat(longitude.value.toFixed(6))
});
closeDialogPage2();
}
return;
}
let item = pois.value[selected.value];
let res = {
name: item.title,
address: item.address,
latitude: item.location.latitude,
longitude: item.location.longitude
};
uni.$emit(successEventName.value, res);
closeDialogPage2();
};
const getSystemInfo2 = () => {
const info = uni.getWindowInfo();
safeArea.top = info.safeAreaInsets.top;
safeArea.bottom = info.safeAreaInsets.bottom;
safeArea.left = info.safeAreaInsets.left;
safeArea.right = info.safeAreaInsets.right;
let screenHeight = info.screenHeight;
mapHeight.value = (screenHeight - safeArea.top - safeArea.bottom) * 0.6;
const systemInfo = uni.getSystemInfoSync();
const appLanguage = systemInfo.appLanguage;
language.value = appLanguage;
const osTheme = systemInfo.osTheme;
const appTheme = systemInfo.appTheme;
if (appTheme != null && appTheme != "auto") {
theme.value = appTheme;
} else if (osTheme != null) {
theme.value = osTheme;
}
isLandscape2.value = systemInfo.windowWidth >= 900 ? true : false;
const hostTheme = systemInfo.hostTheme;
if (hostTheme != null) {
theme.value = hostTheme;
}
const locale = uni.getLocale();
language.value = locale;
};
const languageCom = computed(() => {
const textInfo = languageData[language.value] != null ? languageData[language.value] : languageData["zh-Hans"];
return textInfo;
});
const darkClassCom = computed(() => {
return theme.value == "dark" ? "uni-choose-location-dark" : "uni-choose-location-light";
});
const landscapeClassCom = computed(() => {
return isLandscape2.value ? "uni-choose-location-landscape" : "uni-choose-location-vertical";
});
const mapBoxStyleCom = computed(() => {
let list2 = [];
if (!useUniCloud.value) {
list2.push(`flex: 1;`);
}
if (!isLandscape2.value) {
let top = isFocus.value ? (300 - mapHeight.value) / 2 : 0;
list2.push(`transform:translateY(${top}px);`);
list2.push(`height:${mapHeight.value}px;`);
}
return list2.join("");
});
const poiBoxStyleCom = computed(() => {
let list2 = [];
if (!isLandscape2.value) {
let top = isFocus.value ? 300 : mapHeight.value;
list2.push(`top:${top}px;`);
}
return list2.join("");
});
const resetStyleCom = computed(() => {
let list2 = [];
if (!isLandscape2.value) {
let bottom = isFocus.value ? (mapHeight.value - 300) / 2 + 300 - mapHeight.value : 0;
list2.push(`transform:translateY(${bottom}px);`);
}
return list2.join("");
});
onLoad((options) => {
checkUniCloud();
initPageOptions(options);
getSystemInfo2();
getLocation2();
});
onReady(() => {
getSafeAreaInsets2();
});
onUnload(() => {
uni.$off(optionsEventName.value, null);
uni.$off(readyEventName.value, null);
uni.$off(successEventName.value, null);
uni.$off(failEventName.value, null);
clearSearchValueChangeTimer();
clearAllTimeoutTimers();
});
onResize(() => {
getSystemInfo2();
});
initUniPageHooks();
const _component_input = __syscom_0$2;
const _component_loading = _sfc_main$C;
const _component_scroll_view = __syscom_1;
const n51 = t7();
const n6 = child(n51);
const n5 = child(n6);
const n2 = next(n5);
const n1 = child(n2);
const n4 = next(n2);
const n3 = child(n4);
const n11 = next(n6);
const n8 = child(n11);
const n7 = child(n8);
const n10 = next(n8);
const n9 = child(n10);
renderEffect(() => {
setClass(n51, ["uni-choose-location", darkClassCom.value]);
setClass(n6, ["uni-choose-location-map-box", [landscapeClassCom.value]]);
setStyle(n6, mapBoxStyleCom.value);
});
setInsertionState(n6, n5);
withComponentId("67643bf8", () => createComponent$1(__syscom_0, {
class: "uni-choose-location-map",
id: () => mapId.value,
latitude: () => latitude.value,
longitude: () => longitude.value,
"layer-style": () => theme.value == "dark" ? "2" : "1",
"show-compass": false,
"enable-zoom": true,
"enable-scroll": true,
"enable-rotate": false,
"enable-poi": true,
"show-location": true,
onRegionchange: () => regionchange
}));
const x1 = txt(n1);
setStaticTemplateRef(n2, mapTargetRef, null, "mapTargetRef");
const x3 = txt(n3);
on$1(n4, "click", mapReset);
const x7 = txt(n7);
on$1(n7, "click", back);
const x9 = txt(n9);
on$1(n10, "click", confirm);
renderEffect(() => {
const _icon = icon;
const _landscapeClassCom = landscapeClassCom.value;
const _darkClassCom = darkClassCom.value;
const _safeArea = safeArea;
const _languageCom = languageCom.value;
const _safeArea_top = _safeArea.top;
const _safeArea_top_0_top_safeArea_top_px = _safeArea_top > 0 ? "top: " + _safeArea_top + "px;" : "";
setText(x1, normalizeUniText(toDisplayString(_icon.target)));
setClass(n4, ["uni-choose-location-map-reset", [_landscapeClassCom, _darkClassCom]]);
setStyle(n4, resetStyleCom.value);
setClass(n3, ["uni-choose-location-icons uni-choose-location-map-reset-icon", [_darkClassCom]]);
setText(x3, normalizeUniText(toDisplayString(_icon.position)));
setStyle(n11, "height:" + (60 + _safeArea_top) + "px;");
setClass(n8, ["uni-choose-location-nav-btn uni-choose-location-nav-back-btn", [_landscapeClassCom]]);
setStyle(n8, _safeArea_top_0_top_safeArea_top_px);
setText(x7, normalizeUniText(toDisplayString(_languageCom["cancel"])));
setClass(n10, ["uni-choose-location-nav-btn uni-choose-location-nav-confirm-btn", [_landscapeClassCom, selected.value < 0 && !callUniMapCoErr.value ? "disable" : "active"]]);
setStyle(n10, _safeArea_top_0_top_safeArea_top_px);
setText(x9, normalizeUniText(toDisplayString(_languageCom["ok"])));
});
setInsertionState(n51, 2);
createIf(() => useUniCloud.value, () => {
const n50 = t6();
const n20 = child(n50);
const n16 = child(n20);
const n14 = child(n16);
const x14 = txt(n14);
renderEffect(() => {
const _darkClassCom = darkClassCom.value;
const __darkClassCom = [_darkClassCom];
setClass(n50, ["uni-choose-location-poi", [landscapeClassCom.value, _darkClassCom]]);
setStyle(n50, poiBoxStyleCom.value);
setClass(n20, ["uni-choose-location-poi-search", __darkClassCom]);
setClass(n16, ["uni-choose-location-poi-search-box", __darkClassCom]);
setClass(n14, ["uni-choose-location-icons uni-choose-location-search-icon", __darkClassCom]);
setText(x14, normalizeUniText(toDisplayString(icon.search)));
});
setInsertionState(n16, 1);
const _on_focus = () => isFocus.value = true;
const _on_confirm = () => poiSearch("poiSearch");
withComponentId("f5b8b00e", () => createComponentWithFallback(_component_input, {
modelValue: () => searchValue.value,
"onUpdate:modelValue": () => (_value) => searchValue.value = _value,
type: "text",
placeholder: () => languageCom.value["search"],
class: () => ["uni-choose-location-poi-search-input uni-choose-location-icons", [darkClassCom.value]],
onFocus: () => _on_focus,
onConfirm: () => _on_confirm,
onInput: () => searchValueChange
}));
setInsertionState(n20, 1);
createIf(() => isFocus.value || searchValue.value != "", () => {
const n19 = t0$7();
const x19 = txt(n19);
on$1(n19, "click", cancelSearch);
renderEffect(() => setText(x19, normalizeUniText(toDisplayString(languageCom.value["cancel"]))));
return n19;
});
setInsertionState(n50, 1);
const n49 = withComponentId("f5b890fe", () => createComponentWithFallback(_component_scroll_view, {
"scroll-with-animation": false,
direction: "vertical",
"scroll-top": () => scrollTop.value,
"lower-threshold": 50,
onScrolltolower: () => scrolltolower,
class: "uni-choose-location-poi-list"
}, extend$1(() => {
const n21 = createIf(
() => errMsg.value != "",
() => {
const n24 = t1$5();
const n23 = child(n24);
const x23 = txt(n23);
renderEffect(() => {
setClass(n23, ["uni-choose-location-poi-search-error-text", [darkClassCom.value]]);
setText(x23, normalizeUniText(toDisplayString(errMsg.value)));
});
return n24;
},
() => createIf(
() => locationLoading.value,
() => {
const n27 = t2$4();
const n26 = child(n27);
const x26 = txt(n26);
renderEffect(() => {
setClass(n26, ["uni-choose-location-poi-search-loading-text", [darkClassCom.value]]);
setText(x26, normalizeUniText(toDisplayString(languageCom.value["locationLoading"])));
});
return n27;
},
() => createIf(
() => searchLoading.value && pageIndex.value == 1,
() => {
const n31 = t3$1();
setInsertionState(n31);
withComponentId("f5b7b83c", () => createComponentWithFallback(_component_loading, { class: () => ["uni-choose-location-poi-search-loading-item", [darkClassCom.value]] }));
return n31;
},
() => {
const n34 = createFor(
() => pois.value,
(_for_item0, _for_key0) => {
const n43 = t5();
let p0 = child(n43);
let p1 = child(p0);
const n36 = child(p1);
const n37 = child(p1 = next(p1));
const n42 = next(p0);
const n41 = next(n42);
const x36 = txt(n36);
const x37 = txt(n37);
renderEffect(() => {
const _item = _for_item0.value;
const __darkClassCom = [darkClassCom.value];
setClass(n43, ["uni-choose-location-poi-item", [landscapeClassCom.value]]);
setClass(n36, ["uni-choose-location-poi-item-title-text", __darkClassCom]);
setText(x36, normalizeUniText(toDisplayString(_item.title)));
setClass(n37, ["uni-choose-location-poi-item-detail-text", __darkClassCom]);
setText(x37, normalizeUniText(toDisplayString(_item.distance > 0 ? _item.distanceStr + " | " : "") + toDisplayString(_item.address)));
});
setInsertionState(n43, n42);
createIf(() => selected.value == _for_key0.value, () => {
const n40 = t4$1();
const x40 = txt(n40);
renderEffect(() => setText(x40, normalizeUniText(toDisplayString(icon.success))));
return n40;
});
on$1(n43, "click", () => selectPoi(_for_item0.value, _for_key0.value));
renderEffect(() => setClass(n41, ["uni-choose-location-poi-item-after", [darkClassCom.value]]));
return n43;
},
(item, index2) => index2,
40
/* IS_SINGLE_NODE, SLOT_ROOT */
);
return n34;
},
1157
/* TRUE_SINGLE_ROOT, FALSE_SINGLE_ROOT, SLOT_ROOT, KEYED_INDEX_3 */
),
909
/* TRUE_SINGLE_ROOT, FALSE_ELSE_IF, SLOT_ROOT, KEYED_INDEX_2 */
),
653
/* TRUE_SINGLE_ROOT, FALSE_ELSE_IF, SLOT_ROOT, KEYED_INDEX_1 */
);
const n45 = createIf(
() => searchLoading.value && pageIndex.value > 1,
() => {
const n48 = t3$1();
setInsertionState(n48);
withComponentId("f5b6cdd6", () => createComponentWithFallback(_component_loading, { class: () => ["uni-choose-location-poi-search-loading-item", [darkClassCom.value]] }));
return n48;
},
null,
129
/* TRUE_SINGLE_ROOT, SLOT_ROOT */
);
return [n21, n45];
}, {
_: 1
/* NON_STABLE */
})));
setStaticTemplateRef(n49, scrollRef, null, "scrollRef");
return n50;
});
return n51;
}
});
const _style_0$7 = `
@font-face {
font-family: UniChooseLocationFontFamily;
src: url('data:font/woff2;base64,d09GMgABAAAAAATwAAsAAAAAChQAAAShAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHFQGYACDMgqFNIUSATYCJAMUCwwABCAFhksHUhsiCVFUTqJkPyRJN0gphHle0lZmMBAqAAAAACgAAIiH//b73z4zc+93q6a4V/FQzLtZglKIP5I8UgKLeB8SMovh3zOTpqneQCeFfEh7gtLN7WB9gv9gMAH77adpO+DnpyLMUNYCq5HdpxxQ+u7nCtpM74f7Ga98H3DxbOWYFZTF84GP+6qtUvzaDpDP9R7gGaZ7Vuv0ZQQ6rTPgHJ1vv+DhZi0JHnG5k0GRHzetruHK1igDSGiX19J9i3gHoaQ3nAt4m7x9/LU52kmqzD3JycuzDv4bcesQQv4nAco/RBMCrk6okLF8Yrq4P2y5aZRFliE6u0JnDoLVz9olqdnUJDaznm/8/w8ILk3W6f3DI8mKIGqupJtwB8XlxnEDConmDIVM84xCobXBeyySitZ3ogM/iUuAm94mCVkeOKJ7D5lMKIyTqyiCCjOMj09iWXyIppMJKi60atVK9ySrB+TGWDbCMFGKImk6LTEncdiVJCYoT9NGxakQuXL3ahiezKJ0UXT1hjUAjGBiKhxZE1sF2RoLc8GaVetWikS9XCFrGirK3QWPucxi1C4OnzI3uj9yILaP3JtDHo+djJyIHkvjkCvtMhhhGAsDRwTimKYIIolzVOFG2kVYlvmTKCr/vFMSFhD8wMi40WXRbmGQOCw4PH5ubahnQs/4wQmDm8i+ob4J/eMHEHdfv7YHDPsff7YffeXtcru7Vrs7uzyrOz2eztWerk43ZFw8l3fvZ6K3IHlx2+bZJWGivKy0YtW6tvnQntGFaJkqXZGSokhTlvOk4J3pLZCW8dKVKQpFijIdLZOB98g9IEPLlWnEkK4qQ2Wi9/2J8nI0TTVflYaWS7e+474HRetFIx9AtB7NFAexQAAL4pm8deBt/3ed6zJ4cbgfwwN4EM1cC651aAbeFPnDuRnoWvDPdBeszUSD/a+E+cVxzbYBF5YuLt1duuNsYh+XPHlsstxVUt3MDXFN3AJus0NYn9BjtMkdP8k2wWqdYJu03WfGzJxZVsa72+6+R30Cb+zA8U775DjYPnGSAwpOsFgmBGDr+MkmeXAE+H9t9ApRQBD5W/q+CJFnUH6yiEVGU5CHP67f8WFD/P321H1tBwW02lv/Er6c8+OQWnJ+StJ0Yc+yYpG0dFUHJmHlc8/oFZf5wVT8dhyD7u3GNgQqTGHK5iIkbVYhmyJHFVwcVLrcgNqURui0ZNnBXYacAkSUDsy6DBC2+wpJbyxBtj12oQruDlRG472o7sJ9hE7n4+PxusymE5NMtVCHuScsaTkp/yTynezEMPe05bYWy2m+fr/zOtpw+iBdQp0HG213/VDua9OieAYuiC8oUT6exXV7/V4vCgszR1xejEJgrM7sqJXnYpHdGMMKux7kOY8jTGSkJkgH5TpBJVosUREivne2JgzGemSLia2RWJTNRfPnapEVnHxYBK0I48j6Nihyf5CsH5wNJDYDvhvUQpJ2VfMG7VRnT3tXTygYFGYswl2YSPAiDFV3L3NISzwrVoR2xjDqVSiVPN96WXxLuX+Zuu7xqkiRo0QVtfoBl77wZVF8jGOp02W+TfpA9jbfSnny2WU1AAAAAA==') format('woff2');
}
.uni-choose-location-icons {
font-family: "UniChooseLocationFontFamily";
font-size: 16px;
font-style: normal;
}
.uni-choose-location {
position: relative;
left: 0;
top: 0;
width: 100%;
height: 100%;
background: #f8f8f8;
z-index: 999;
}
.uni-choose-location-map-box {
position: relative;
width: 100%;
height: 350px;
}
.uni-choose-location-map-box.uni-choose-location-vertical {
transition-property: transform;
transition-duration: 0.25s;
transition-timing-function: ease-out;
}
.uni-choose-location-map {
width: 100%;
height: 100%;
}
.uni-choose-location-map-target {
position: absolute;
left: 50%;
bottom: 50%;
width: 50px;
height: 50px;
margin-left: -25px;
transition-property: transform;
transition-duration: 0.25s;
transition-timing-function: ease-out;
}
.uni-choose-location-map-target-icon {
font-size: 50px;
color: #f0493e;
}
/* #1aad19; #f0493e; #007aff;*/
.uni-choose-location-map-reset {
position: absolute;
left: 20px;
bottom: 40px;
width: 40px;
height: 40px;
box-sizing: border-box;
background-color: #fff;
border-radius: 20px;
pointer-events: auto;
box-shadow: 0px 0px 20px 2px rgba(0, 0, 0, .3);
z-index: 9;
display: flex;
justify-content: center;
align-items: center;
}
.uni-choose-location-map-reset.uni-choose-location-vertical {
transition-property: transform;
transition-duration: 0.25s;
transition-timing-function: ease-out;
}
.uni-choose-location-map-reset-icon {
font-size: 26px;
text-align: center;
line-height: 40px;
}
.uni-choose-location-nav {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 60px;
background-color: rgba(0, 0, 0, 0);
background-image: linear-gradient(to bottom, rgba(0, 0, 0, .6), rgba(0, 0, 0, 0));
}
.uni-choose-location-nav-btn {
position: absolute;
top: 5px;
left: 5px;
width: 64px;
height: 44px;
padding: 5px;
}
.uni-choose-location-nav-btn.uni-choose-location-nav-confirm-btn {
left: auto;
right: 5px;
}
.uni-choose-location-nav-confirm-text {
background-color: #007aff;
border-radius: 5px;
}
.uni-choose-location-nav-btn.uni-choose-location-nav-confirm-btn.disable {
opacity: 0.4;
}
.uni-choose-location-nav-back-text {
color: #fff;
}
.uni-choose-location-nav-text {
padding: 8px 0px;
font-size: 14px;
text-align: center;
letter-spacing: 0.1em;
color: #fff;
}
.uni-choose-location-poi {
position: absolute;
top: 350px;
width: 100%;
bottom: 0;
background-color: #fff;
z-index: 10
}
.uni-choose-location-poi.uni-choose-location-vertical {
transition-property: top;
transition-duration: 0.25s;
transition-timing-function: ease-out;
}
.uni-choose-location-poi-search {
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
height: 50px;
padding: 8px;
background-color: #fff;
}
.uni-choose-location-poi-search-box {
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
height: 32px;
flex: 1;
border-radius: 5px;
padding: 0 15px;
background-color: #ededed;
}
.uni-choose-location-poi-search-input {
flex: 1;
height: 100%;
border-radius: 5px;
padding: 0 5px;
background: #ededed;
}
.uni-choose-location-poi-search-cancel {
margin-left: 5px;
color: #007aff;
font-size: 15px;
text-align: center;
}
.uni-choose-location-poi-list {
flex: 1;
}
.uni-choose-location-poi-search-loading {
display: flex;
align-items: center;
padding: 10px 0px;
}
.uni-choose-location-poi-search-loading-text {
color: #191919;
}
.uni-choose-location-poi-search-error {
display: flex;
align-items: center;
padding: 10px;
}
.uni-choose-location-poi-search-error-text {
color: #191919;
font-size: 14px;
}
.uni-choose-location-poi-item {
position: relative;
padding: 15px 10px;
padding-right: 40px;
}
.uni-choose-location-poi-item-title-text {
font-size: 14px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
color: #191919;
}
.uni-choose-location-poi-item-detail-text {
font-size: 12px;
margin-top: 5px;
color: #b2b2b2;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.uni-choose-location-poi-item-selected-icon {
position: absolute;
top: 50%;
right: 10px;
width: 26px;
height: 26px;
margin-top: -13px;
color: #007aff;
font-size: 24px;
}
.uni-choose-location-poi-item-after {
position: absolute;
height: 1px;
left: 10px;
bottom: 0px;
right: 10px;
width: auto;
border-bottom: 1px solid #f8f8f8;
}
.uni-choose-location-search-icon {
color: #808080;
padding-left: 5px;
}
.uni-choose-location-poi-search-loading-item {
width: 28px;
height: 28px;
border-color: #D0D0D0;
}
/* 横屏样式开始 */
.uni-choose-location-map-box.uni-choose-location-landscape {
height: 100%;
}
.uni-choose-location-poi.uni-choose-location-landscape {
position: absolute;
top: 80px;
right: 25px;
width: 300px;
bottom: 20px;
max-height: 600px;
box-shadow: 0px 0px 20px 2px rgba(0, 0, 0, .3);
border-radius: 5px;
}
.uni-choose-location-map-reset.uni-choose-location-landscape {
left: 40px;
bottom: 40px;
}
.uni-choose-location-poi-item.uni-choose-location-landscape {
padding: 10px;
}
.uni-choose-location-nav-btn.uni-choose-location-landscape {
top: 10px;
left: 20px;
}
.uni-choose-location-nav-btn.uni-choose-location-nav-confirm-btn.uni-choose-location-landscape {
left: auto;
right: 20px;
}
/* 横屏样式结束 */
/* 暗黑模式样式开始 */
.uni-choose-location-dark.uni-choose-location-map-reset {
background-color: #111111;
box-shadow: 0px 0px 5px 1px rgba(0, 0, 0, .3);
}
.uni-choose-location-dark.uni-choose-location-poi-search-box {
background-color: #111111;
}
.uni-choose-location-dark.uni-choose-location-search-icon {
color: #d1d1d1;
}
.uni-choose-location-dark.uni-choose-location-poi-search-loading-text {
color: #d1d1d1;
}
.uni-choose-location-dark.uni-choose-location-poi-search {
background-color: #181818
}
.uni-choose-location-dark.uni-choose-location-poi-search-input {
background: #111111;
color: #d1d1d1;
}
.uni-choose-location-dark.uni-choose-location-poi-item-title-text {
color: #d1d1d1;
}
.uni-choose-location-dark.uni-choose-location-poi-item-detail-text {
color: #595959;
}
.uni-choose-location-dark.uni-choose-location-poi {
background-color: #181818
}
.uni-choose-location-dark.uni-choose-location-poi-item-after {
border-bottom: 1px solid #1e1e1e;
}
.uni-choose-location-dark.uni-choose-location-map-reset-icon {
color: #d1d1d1;
}
.uni-choose-location-dark.uni-choose-location-poi-search-error-text {
color: #d1d1d1;
}
.uni-choose-location-dark.uni-choose-location-poi-search-loading-item {
border-color: #d1d1d1;
}
/* 暗黑模式样式结束 */
`;
const UniChooseLocationPage = /* @__PURE__ */ _export_sfc(_sfc_main$7, [["styles", [_style_0$7]]]);
class ChooseLocationFailImpl extends UniError {
constructor(errMsg = "chooseLocation:fail cancel", errCode = 1) {
super();
this.errCode = errCode;
this.errMsg = errMsg;
}
}
const chooseLocation$1 = (options) => {
const uuid = `${Date.now()}${Math.floor(Math.random() * 1e7)}`;
const baseEventName = `uni_choose_location_${uuid}`;
const readyEventName = `${baseEventName}_ready`;
const optionsEventName = `${baseEventName}_options`;
const successEventName = `${baseEventName}_success`;
const failEventName = `${baseEventName}_fail`;
uni.$on(readyEventName, () => {
uni.$emit(optionsEventName, JSON.parse(JSON.stringify(options)));
});
uni.$on(successEventName, (result) => {
var _a, _b;
(_a = options.success) == null ? void 0 : _a.call(options, result);
(_b = options.complete) == null ? void 0 : _b.call(options, result);
});
uni.$on(failEventName, () => {
var _a, _b;
(_a = options.fail) == null ? void 0 : _a.call(options, new ChooseLocationFailImpl());
(_b = options.complete) == null ? void 0 : _b.call(options, new ChooseLocationFailImpl());
});
uni.openDialogPage({
url: `uni:chooseLocation?readyEventName=${readyEventName}&optionsEventName=${optionsEventName}&successEventName=${successEventName}&failEventName=${failEventName}`,
triggerParentHide: true,
fail(err) {
var _a, _b;
(_a = options.fail) == null ? void 0 : _a.call(options, new ChooseLocationFailImpl(`chooseLocation:fail ${err.errMsg}`, 4));
(_b = options.complete) == null ? void 0 : _b.call(options, new ChooseLocationFailImpl(`chooseLocation:fail ${err.errMsg}`, 4));
uni.$off(readyEventName);
uni.$off(successEventName);
uni.$off(failEventName);
}
});
};
const registerChooseLocationOnce = /* @__PURE__ */ once(() => {
registerSystemRoute("uni:chooseLocation", UniChooseLocationPage);
});
const chooseLocation = /* @__PURE__ */ defineAsyncApi(
API_CHOOSE_LOCATION,
(args, { resolve, reject }) => {
registerChooseLocationOnce();
chooseLocation$1(
/* @__PURE__ */ extend(
{
success: (res) => {
resolve(res);
},
fail: (err) => {
reject(err);
}
},
args
)
);
}
);
const t0$6 = template("<span uni-text data-v-212d40c7 class=uni-modal-dialog__title> ");
const t1$4 = template("<span uni-text data-v-212d40c7 class=uni-modal-dialog__message> ");
const t2$3 = template('<div uni-view data-v-212d40c7 class="uni-modal-dialog__action uni-modal-dialog__action--cancel"><span uni-text data-v-212d40c7 class=uni-modal-dialog__action-text> ');
const t3 = template("<div uni-view data-v-212d40c7 class=uni-modal-dialog__split>", 2);
const t4 = template('<div uni-view data-v-212d40c7><div uni-view data-v-212d40c7><div uni-view data-v-212d40c7 class=uni-modal-dialog__inner><div uni-view data-v-212d40c7 class=uni-modal-dialog__title__container></div><div uni-view data-v-212d40c7></div><div uni-view data-v-212d40c7 class=uni-modal-dialog__divider></div><div uni-view data-v-212d40c7 class=uni-modal-dialog__actions><!><!><div uni-view data-v-212d40c7 class="uni-modal-dialog__action uni-modal-dialog__action--confirm"><span uni-text data-v-212d40c7 class="uni-modal-dialog__action-text uni-modal-dialog__action-text--confirm"> ', 1);
const _sfc_main$6 = /* @__PURE__ */ defineVaporComponent({
__name: "uniModal",
setup(__props) {
const language = ref("zh-Hans");
const i18nCancelText = {
en: "Cancel",
es: "Cancelar",
fr: "Annuler",
"zh-Hans": "取消",
"zh-Hant": "取消"
};
const i18nConfirmText = {
en: "OK",
es: "Confirmar",
fr: "Confirmer",
"zh-Hans": "确定",
"zh-Hant": "確定"
};
const readyEventName = ref("");
const optionsEventName = ref("");
const successEventName = ref("");
const failEventName = ref("");
const title = ref("");
const content = ref("");
const showCancel = ref(true);
const editable = ref(false);
const placeholderText = ref(null);
const inputConfirmText = ref(null);
const inputCancelText = ref(null);
const inputBottom = ref("0px");
const maxScrollHeight = ref("192px");
const inputCancelColor = ref(null);
const inputConfirmColor = ref(null);
const showAnim = ref(false);
const isClosing = ref(false);
const maskAnimationClass = computed(() => {
if (isClosing.value) {
return "uni-modal-mask--hide";
}
return showAnim.value ? "uni-modal-mask--show" : "";
});
const dialogAnimationClass = computed(() => {
if (isClosing.value) {
return "uni-modal-dialog--hide";
}
return showAnim.value ? "uni-modal-dialog--show" : "";
});
const isAutoHeight = ref(true);
const hasTitle = computed(() => {
return title.value != "";
});
const instance2 = getCurrentInstance();
const cancelText = computed(() => {
if (inputCancelText.value != null) {
return inputCancelText.value;
}
if (language.value.startsWith("en")) {
return i18nCancelText["en"];
}
if (language.value.startsWith("es")) {
return i18nCancelText["es"];
}
if (language.value.startsWith("fr")) {
return i18nCancelText["fr"];
}
if (language.value.startsWith("zh-Hans")) {
return i18nCancelText["zh-Hans"];
}
if (language.value.startsWith("zh-Hant")) {
return i18nCancelText["zh-Hant"];
}
return "取消";
});
const confirmText = computed(() => {
if (inputConfirmText.value != null) {
return inputConfirmText.value;
}
if (language.value.startsWith("en")) {
return i18nConfirmText["en"];
}
if (language.value.startsWith("es")) {
return i18nConfirmText["es"];
}
if (language.value.startsWith("fr")) {
return i18nConfirmText["fr"];
}
if (language.value.startsWith("zh-Hans")) {
return i18nConfirmText["zh-Hans"];
}
if (language.value.startsWith("zh-Hant")) {
return i18nConfirmText["zh-Hant"];
}
return "确定";
});
const onInputBlur = (e2) => {
setTimeout(() => {
inputBottom.value = "0px";
}, 220);
};
const onInputKeyboardChange = (e2) => {
const keyBoardHeight = e2.detail.height;
if (keyBoardHeight > 0) {
inputBottom.value = `${keyBoardHeight / 2}px`;
}
};
const isValidColor = (inputColor) => {
const hexColorRegex = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;
if (inputColor == null) {
return false;
}
return hexColorRegex.test(inputColor);
};
const cancelColorStyle = computed(() => {
return isValidColor(inputCancelColor.value) ? { color: inputCancelColor.value } : {};
});
const confirmColorStyle = computed(() => {
return isValidColor(inputConfirmColor.value) ? { color: inputConfirmColor.value } : {};
});
const getCloseAnimationDelay = () => {
return 180;
};
const closeModal = () => {
if (isClosing.value) {
return;
}
isClosing.value = true;
showAnim.value = false;
setTimeout(() => {
var _a;
uni.closeDialogPage({
dialogPage: (_a = instance2 == null ? void 0 : instance2.proxy) == null ? void 0 : _a.$page
});
}, getCloseAnimationDelay());
};
const handleCancel = () => {
closeModal();
const ret = {
cancel: true,
confirm: false
};
uni.$emit(successEventName.value, JSON.stringify(ret));
};
const handleSure = () => {
closeModal();
const ret = {
cancel: false,
confirm: true,
content: editable.value ? content.value : null
};
uni.$emit(successEventName.value, JSON.stringify(ret));
};
onReady(() => {
requestAnimationFrame(() => {
requestAnimationFrame(() => {
if (!isClosing.value) {
showAnim.value = true;
}
});
});
});
onLoad((options) => {
const deviceInfo = uni.getDeviceInfo();
const windowInfo = uni.getWindowInfo();
maxScrollHeight.value = `${Math.floor(windowInfo.screenHeight * 0.55)}px`;
const appBaseInfo = uni.getAppBaseInfo();
if (appBaseInfo.appLanguage != null) {
language.value = appBaseInfo.appLanguage;
} else if (deviceInfo.osLanguage != null) {
language.value = deviceInfo.osLanguage;
}
const locale = uni.getLocale();
language.value = locale;
uni.onLocaleChange((res) => {
if (res.locale) {
language.value = res.locale;
}
});
readyEventName.value = options["readyEventName"];
optionsEventName.value = options["optionsEventName"];
successEventName.value = options["successEventName"];
failEventName.value = options["failEventName"];
uni.$on(optionsEventName.value, (data) => {
if (data["title"] != null) {
title.value = data["title"];
}
if (data["content"] != null) {
content.value = data["content"];
}
if (data["showCancel"] != null) {
showCancel.value = data["showCancel"];
}
if (data["editable"] != null) {
editable.value = data["editable"];
}
if (data["placeholderText"] != null) {
placeholderText.value = data["placeholderText"];
}
if (data["confirmText"] != null) {
inputConfirmText.value = data["confirmText"];
}
if (data["cancelText"] != null) {
inputCancelText.value = data["cancelText"];
}
if (data["confirmColor"] != null) {
inputConfirmColor.value = data["confirmColor"];
}
if (data["cancelColor"] != null) {
inputCancelColor.value = data["cancelColor"];
}
});
uni.$emit(readyEventName.value, {});
});
onUnload(() => {
uni.$off(optionsEventName.value, null);
uni.$off(readyEventName.value, null);
uni.$off(successEventName.value, null);
uni.$off(failEventName.value, null);
});
onBackPress((_) => {
const ret = {
cancel: false,
confirm: false
};
uni.$emit(successEventName.value, JSON.stringify(ret));
return false;
});
initUniPageHooks();
const _component_textarea = __syscom_0$1;
const _component_scroll_view = __syscom_1;
const n24 = t4();
const n23 = child(n24);
let p0 = child(n23);
const n3 = child(p0);
const n10 = next(n3);
const n21 = nthChild(p0, 3);
const n20 = child(n21);
const n22 = next(n20);
const n19 = next(n22);
const n18 = child(n19);
renderEffect(() => {
setClass(n24, ["uni-modal-mask", maskAnimationClass.value]);
setClass(n23, ["uni-modal-dialog", dialogAnimationClass.value]);
setStyle(n23, { bottom: inputBottom.value });
});
setInsertionState(n3);
createIf(() => hasTitle.value, () => {
const n2 = t0$6();
const x2 = txt(n2);
renderEffect(() => setText(x2, normalizeUniText(toDisplayString(title.value))));
return n2;
});
renderEffect(() => setClassName(n10, !hasTitle.value ? 1 : 0, " no-title", "uni-modal-dialog__body"));
setInsertionState(n10);
createIf(
() => editable.value,
() => {
const n6 = withComponentId("876dd6da", () => createComponentWithFallback(_component_textarea, {
modelValue: () => content.value,
"onUpdate:modelValue": () => (_value) => content.value = _value,
class: "uni-modal-dialog__textarea",
"placeholder-class": "uni-modal-dialog__textarea-placeholder",
focus: true,
"adjust-position": false,
onBlur: () => onInputBlur,
onKeyboardheightchange: () => onInputKeyboardChange,
"auto-height": () => isAutoHeight.value,
placeholder: () => placeholderText.value
}));
return n6;
},
() => createIf(() => content.value.length > 0, () => {
const n9 = withComponentId("876dbf60", () => createComponentWithFallback(_component_scroll_view, {
class: "uni-modal-dialog__scroll",
"show-scrollbar": false,
bounces: false,
style: () => ({ maxHeight: maxScrollHeight.value })
}, () => {
const n8 = t1$4();
const x8 = txt(n8);
renderEffect(() => setText(x8, normalizeUniText(toDisplayString(content.value))));
return n8;
}));
return n9;
}),
525
/* TRUE_SINGLE_ROOT, FALSE_ELSE_IF, KEYED_INDEX_1 */
);
setInsertionState(n21, n20);
createIf(() => showCancel.value, () => {
const n14 = t2$3();
const n13 = child(n14);
const x13 = txt(n13);
on$1(n14, "click", handleCancel);
setHover(n14, "uni-modal-dialog__action--hover", false, 50, 400, "uni-modal-dialog__action uni-modal-dialog__action--cancel");
renderEffect(() => {
setStyle(n13, cancelColorStyle.value);
setText(x13, normalizeUniText(toDisplayString(cancelText.value)));
});
return n14;
});
setInsertionState(n21, n22);
createIf(
() => showCancel.value,
() => {
const n17 = t3();
return n17;
},
null,
33
/* TRUE_SINGLE_ROOT, TRUE_NO_SCOPE */
);
const x18 = txt(n18);
on$1(n19, "click", handleSure);
setHover(n19, "uni-modal-dialog__action--hover", false, 50, 400, "uni-modal-dialog__action uni-modal-dialog__action--confirm");
renderEffect(() => {
setStyle(n18, confirmColorStyle.value);
setText(x18, normalizeUniText(toDisplayString(confirmText.value)));
});
return n24;
}
});
const _style_0$6 = "\n /**\n * 透明背景\n */\n.uni-modal-mask {\n display: flex;\n height: 100%;\n width: 100%;\n justify-content: center;\n align-items: center;\n background-color: rgba(0, 0, 0, 0.55);\n\n\n\n\n opacity: 0;\n}\n.uni-modal-mask--hide {\n animation: uni-modal-mask-fade-out 0.15s ease-in forwards;\n}\n.uni-modal-mask--show {\n animation: uni-modal-mask-fade-in 0.15s ease-out forwards;\n}\n@keyframes uni-modal-mask-fade-in {\nfrom {\n opacity: 0;\n}\nto {\n opacity: 1;\n}\n}\n@keyframes uni-modal-mask-fade-out {\nfrom {\n opacity: 1;\n}\nto {\n opacity: 0;\n}\n}\n\n\n /**\n * 居中的内容展示区域\n */\n.uni-modal-dialog {\n width: 80%;\n max-width: 90%;\n max-height: 90%;\n background-color: #ffffff;\n box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);\n border-radius: 16px;\n opacity: 0;\n transform: scale(0.9);\n}\n@media screen and (min-width: 768px) {\n.uni-modal-dialog {\n max-width: 556px;\n}\n}\n.uni-modal-dialog--show {\n animation: uni-modal-dialog-scale-in 0.15s ease-out forwards;\n}\n.uni-modal-dialog--hide {\n animation: uni-modal-dialog-scale-out 0.15s ease-in forwards;\n}\n@keyframes uni-modal-dialog-scale-in {\nfrom {\n opacity: 0;\n transform: scale(0.9);\n}\nto {\n opacity: 1;\n transform: scale(1);\n}\n}\n@keyframes uni-modal-dialog-scale-out {\nfrom {\n opacity: 1;\n transform: scale(1);\n}\nto {\n opacity: 0;\n transform: scale(0.9);\n}\n}\n.uni-modal-dialog__inner {\n width: 100%;\n height: 100%;\n background-color: #ffffff;\n border-radius: 8px;\n}\n.uni-modal-dialog__title__container {\n padding: 33px 24px 18px;\n}\n.uni-modal-dialog__title {\n font-size: 17px;\n font-weight: 600;\n text-align: center;\n text-overflow: ellipsis;\n\n\n\n line-height: 22px;\n\n display: -webkit-box;\n -webkit-line-clamp: 2;\n -webkit-box-orient: vertical;\n overflow: hidden;\n}\n.uni-modal-dialog__body {\n justify-content: center;\n align-items: center;\n padding: 0 22px;\n margin-bottom: 13px;\n}\n.uni-modal-dialog__body.no-title {\n margin-top: -10px;\n margin-bottom: 20px;\n}\n.uni-modal-dialog__scroll {\n max-height: 192px;\n margin: 2px;\n width: 100%;\n}\n.uni-modal-dialog__message {\n font-size: 17px;\n font-weight: normal;\n text-align: center;\n color: #7f7f7f;\n line-height: 1.5em;\n width: 100%;\n padding-bottom: 10px;\n}\n.uni-modal-dialog__textarea {\n font-size: 17px;\n background-color: #f6f6f6;\n color: #000000;\n width: 96%;\n padding: 5px;\n margin-top: 2px;\n margin-bottom: 7px;\n max-height: 192px;\n\n word-break: break-word;\n}\n.uni-modal-dialog__textarea-placeholder {\n color: #808080;\n}\n.uni-modal-dialog__divider {\n width: 100%;\n height: 1px;\n transform: scaleY(0.5);\n background-color: #e3e3e3;\n}\n.uni-modal-dialog__actions {\n display: flex;\n width: 100%;\n height: 56px;\n flex-direction: row;\n overflow: hidden;\n}\n.uni-modal-dialog__action {\n width: 50%;\n justify-content: center;\n flex-grow: 1;\n}\n.uni-modal-dialog__action--cancel{\n padding: 0 4px 0 10px;\n}\n.uni-modal-dialog__action--confirm{\n padding: 0 10px 0 4px;\n}\n.uni-modal-dialog__action--hover {\n background-color: #efefef;\n}\n.uni-modal-dialog__action-text {\n color: #000000;\n letter-spacing: 1px;\n font-size: 17px;\n text-align: center;\n\n\n\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n font-weight: 600;\n}\n.uni-modal-dialog__action-text--confirm {\n color: #4A5E86;\n}\n.uni-modal-dialog__split {\n width: 1px;\n height: 100%;\n transform: scaleX(0.5);\n background-color: #e3e3e3;\n}\n.uni-textarea-wrapper {\n min-height: 18px !important;\n}\n@media (prefers-color-scheme: dark) {\n.uni-modal-dialog,\n .uni-modal-dialog__inner {\n background-color: #272727;\n}\n.uni-modal-dialog__title {\n color: #cfcfcf;\n}\n.uni-modal-dialog__textarea {\n background-color: #3d3d3d;\n color: #cfcfcf;\n}\n.uni-modal-dialog__divider,\n .uni-modal-dialog__split {\n background-color: #303030;\n}\n.uni-modal-dialog__action--hover {\n background-color: #414141;\n}\n.uni-modal-dialog__action-text {\n color: #a5a5a5;\n}\n.uni-modal-dialog__action-text--confirm {\n color: #7388a2;\n}\n}\n\n";
const UniModalPage = /* @__PURE__ */ _export_sfc(_sfc_main$6, [["styles", [_style_0$6]]]);
class ShowModalSuccessImpl {
constructor(cancel, confirm, content = null, errMsg = "showModal:ok") {
this.errMsg = errMsg;
this.content = content;
this.cancel = cancel;
this.confirm = confirm;
}
}
class ShowModalFailImpl extends UniError {
constructor(errMsg = "showModal:fail cancel", errCode = 4) {
super();
this.errMsg = errMsg;
this.errCode = errCode;
}
}
class HideModalSuccessImpl {
constructor(errMsg = "hideModal:ok") {
this.errMsg = errMsg;
}
}
class HideModalFailImpl extends UniError {
constructor(errMsg = "hideModal:fail cancel", errCode = 4) {
super();
this.errMsg = errMsg;
this.errCode = errCode;
}
}
const showModal$1 = (options) => {
var _a, _b;
const uuid = `${Date.now()}${Math.floor(Math.random() * 1e7)}`;
const baseEventName = `uni_modal_${uuid}`;
const readyEventName = `${baseEventName}_ready`;
const optionsEventName = `${baseEventName}_options`;
const successEventName = `${baseEventName}_success`;
const failEventName = `${baseEventName}_fail`;
uni.$on(readyEventName, () => {
uni.$emit(optionsEventName, options != null ? JSON.parse(JSON.stringify(options)) : {});
});
uni.$on(successEventName, (inputParamStr) => {
var _a2, _b2;
const inputParam = JSON.parse(inputParamStr);
const res2 = new ShowModalSuccessImpl(
inputParam["cancel"],
inputParam["confirm"],
inputParam["content"]
);
(_a2 = options == null ? void 0 : options.success) == null ? void 0 : _a2.call(options, res2);
(_b2 = options == null ? void 0 : options.complete) == null ? void 0 : _b2.call(options, res2);
});
uni.$on(failEventName, () => {
var _a2, _b2;
const res2 = new ShowModalFailImpl();
(_a2 = options == null ? void 0 : options.fail) == null ? void 0 : _a2.call(options, res2);
(_b2 = options == null ? void 0 : options.complete) == null ? void 0 : _b2.call(options, res2);
});
const openRet = uni.openDialogPage({
url: `uni:uniModal?readyEventName=${readyEventName}&optionsEventName=${optionsEventName}&successEventName=${successEventName}&failEventName=${failEventName}`,
animationType: "none",
fail(err) {
var _a2, _b2;
const res2 = new ShowModalFailImpl(`showModal failed, ${err.errMsg}`);
(_a2 = options == null ? void 0 : options.fail) == null ? void 0 : _a2.call(options, res2);
(_b2 = options == null ? void 0 : options.complete) == null ? void 0 : _b2.call(options, res2);
uni.$off(readyEventName);
uni.$off(successEventName);
uni.$off(failEventName);
}
});
if (openRet != null) {
return openRet;
}
const res = new ShowModalFailImpl();
(_a = options == null ? void 0 : options.fail) == null ? void 0 : _a.call(options, res);
(_b = options == null ? void 0 : options.complete) == null ? void 0 : _b.call(options, res);
return null;
};
const SYSTEM_DIALOG_MODAL_PAGE_PATH = "uni:uniModal";
const hideModal$1 = (options) => {
var _a, _b, _c, _d;
const pages = getCurrentPages();
const currentPage = pages[pages.length - 1];
if (currentPage == null) {
const res2 = new HideModalFailImpl();
(_a = options == null ? void 0 : options.fail) == null ? void 0 : _a.call(options, res2);
(_b = options == null ? void 0 : options.complete) == null ? void 0 : _b.call(options, res2);
return;
}
const systemDialogPages = currentPage.$getSystemDialogPages();
const modalPage = options == null ? void 0 : options.modalPage;
for (let i = systemDialogPages.length - 1; i >= 0; i--) {
const page = systemDialogPages[i];
if (!page.route.startsWith(SYSTEM_DIALOG_MODAL_PAGE_PATH)) {
continue;
}
if (modalPage == null) {
uni.closeDialogPage({
dialogPage: page
});
} else {
if (modalPage === page) {
uni.closeDialogPage({
dialogPage: page
});
break;
}
}
}
const res = new HideModalSuccessImpl();
(_c = options == null ? void 0 : options.success) == null ? void 0 : _c.call(options, res);
(_d = options == null ? void 0 : options.complete) == null ? void 0 : _d.call(options, res);
};
const API_HIDE_MODAL = "hideModal";
const registerModalOnce = /* @__PURE__ */ once(() => {
registerSystemRoute("uni:uniModal", UniModalPage);
});
const hideModal = /* @__PURE__ */ defineAsyncApi(
API_HIDE_MODAL,
(args, { resolve, reject }) => {
registerModalOnce();
hideModal$1(
/* @__PURE__ */ extend(
{
success: (res) => {
resolve(res);
},
fail: (err) => {
reject(err);
}
},
args
)
);
}
);
const showModal = /* @__PURE__ */ defineAsyncApi(
API_SHOW_MODAL,
(args, { resolve, reject }) => {
registerModalOnce();
return showModal$1(
extend(
{
success: (res) => {
resolve(res);
},
fail: (err) => {
reject(err);
}
},
args
)
);
}
);
const t0$5 = template("<span uni-text data-v-212d40c7 class=uni-loading-dialog__title> ");
const t1$3 = template("<div uni-view data-v-212d40c7><div uni-view data-v-212d40c7>", 1);
const _sfc_main$5 = /* @__PURE__ */ defineVaporComponent({
__name: "showLoading",
setup(__props) {
const readyEventName = ref("");
const optionsEventName = ref("");
const successEventName = ref("");
const failEventName = ref("");
const title = ref("");
const showAnim = ref(false);
const iosSpinner = ref(true);
onReady(() => {
setTimeout(() => {
showAnim.value = true;
}, 10);
});
onLoad((options) => {
readyEventName.value = options["readyEventName"];
optionsEventName.value = options["optionsEventName"];
successEventName.value = options["successEventName"];
failEventName.value = options["failEventName"];
uni.$on(optionsEventName.value, (data) => {
if (data["title"] != null) {
title.value = data["title"];
}
if (data["iosSpinner"] != null) {
iosSpinner.value = data["iosSpinner"];
}
});
uni.$emit(readyEventName.value, {});
uni.$emit(successEventName.value, "");
});
onUnload(() => {
uni.$off(optionsEventName.value, null);
uni.$off(readyEventName.value, null);
uni.$off(successEventName.value, null);
uni.$off(failEventName.value, null);
});
initUniPageHooks();
const n5 = t1$3();
const n4 = child(n5);
renderEffect(() => {
const _showAnim = showAnim.value;
setClassName(n5, _showAnim ? 1 : 0, " uni-loading-mask--show", "uni-loading-mask");
setClassName(n4, _showAnim ? 1 : 0, " uni-loading-dialog--show", "uni-loading-dialog");
});
setInsertionState(n4);
withComponentId("9a8ccad6", () => createComponent$1(_sfc_main$C, {
class: "uni-loading-dialog__spinner",
"ios-spinner": () => iosSpinner.value
}));
setInsertionState(n4, 1);
createIf(() => title.value, () => {
const n3 = t0$5();
const x3 = txt(n3);
renderEffect(() => setText(x3, normalizeUniText(toDisplayString(title.value))));
return n3;
});
return n5;
}
});
const _style_0$5 = "\n /**\n * 透明背景\n */\n.uni-loading-mask {\n display: flex;\n height: 100%;\n width: 100%;\n justify-content: center;\n align-items: center;\n background-color: rgba(0, 0, 0, 0);\n transition-duration: 0.1s;\n transition-property: opacity;\n opacity: 0;\n}\n.uni-loading-mask--show {\n opacity: 1;\n}\n\n /**\n * 居中的内容展示区域\n */\n.uni-loading-dialog {\n display: flex;\n justify-content: center;\n align-items: center;\n min-width: 136px;\n\n\n\n\n max-width: 80%;\n\n height: 136px;\n padding: 10px;\n background-color: rgba(76, 76, 76, 0.95);\n box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);\n border-radius: 10px;\n opacity: 0;\n transform: scale(0.9);\n transition-duration: 0.1s;\n transition-property: opacity, transform;\n}\n.uni-loading-dialog.uni-loading-dialog--show {\n opacity: 1;\n transform: scale(1);\n}\n.uni-loading-dialog__spinner {\n width: 36px;\n height: 36px;\n border-color: white;\n}\n.uni-loading-dialog__title {\n margin-top: 14px;\n color: white;\n font-size: 16px;\n lines: 1;\n text-align: center;\n text-overflow: ellipsis;\n\n display: -webkit-box;\n -webkit-line-clamp: 1;\n -webkit-box-orient: vertical;\n overflow: hidden;\n}\n";
const UniLoadingPage = /* @__PURE__ */ _export_sfc(_sfc_main$5, [["styles", [_style_0$5]]]);
class ShowLoadingSuccessImpl {
constructor(errMsg = "showLoading:ok") {
this.errMsg = errMsg;
}
}
class ShowLoadingFailImpl extends UniError {
constructor(errMsg = "showLoading:fail cancel", errCode = 4) {
super();
this.errMsg = errMsg;
this.errCode = errCode;
}
}
class HideLoadingSuccessImpl {
constructor(errMsg = "hideLoading:ok") {
this.errMsg = errMsg;
}
}
class HideLoadingFailImpl extends UniError {
constructor(errMsg = "hideLoading:fail cancel", errCode = 4) {
super();
this.errMsg = errMsg;
this.errCode = errCode;
}
}
const showLoading$1 = (options) => {
var _a, _b;
const uuid = `${Date.now()}${Math.floor(Math.random() * 1e7)}`;
const baseEventName = `uni_loading_${uuid}`;
const readyEventName = `${baseEventName}_ready`;
const optionsEventName = `${baseEventName}_options`;
const successEventName = `${baseEventName}_success`;
const failEventName = `${baseEventName}_fail`;
uni.$on(readyEventName, () => {
uni.$emit(optionsEventName, options != null ? JSON.parse(JSON.stringify(options)) : {});
});
uni.$on(successEventName, (_) => {
var _a2, _b2;
const res2 = new ShowLoadingSuccessImpl();
(_a2 = options == null ? void 0 : options.success) == null ? void 0 : _a2.call(options, res2);
(_b2 = options == null ? void 0 : options.complete) == null ? void 0 : _b2.call(options, res2);
});
uni.$on(failEventName, () => {
var _a2, _b2;
const res2 = new ShowLoadingFailImpl();
(_a2 = options == null ? void 0 : options.fail) == null ? void 0 : _a2.call(options, res2);
(_b2 = options == null ? void 0 : options.complete) == null ? void 0 : _b2.call(options, res2);
});
const openRet = uni.openDialogPage({
url: `uni:showLoading?readyEventName=${readyEventName}&optionsEventName=${optionsEventName}&successEventName=${successEventName}&failEventName=${failEventName}`,
animationType: "none",
fail(err) {
var _a2, _b2;
const res2 = new ShowLoadingFailImpl(`showLoading failed, ${err.errMsg}`);
(_a2 = options == null ? void 0 : options.fail) == null ? void 0 : _a2.call(options, res2);
(_b2 = options == null ? void 0 : options.complete) == null ? void 0 : _b2.call(options, res2);
uni.$off(readyEventName);
uni.$off(successEventName);
uni.$off(failEventName);
}
});
if (openRet != null) {
return openRet;
}
const res = new ShowLoadingFailImpl();
(_a = options == null ? void 0 : options.fail) == null ? void 0 : _a.call(options, res);
(_b = options == null ? void 0 : options.complete) == null ? void 0 : _b.call(options, res);
return null;
};
const SYSTEM_DIALOG_LOADING_PAGE_PATH = "uni:showLoading";
const hideLoading$1 = (options) => {
var _a, _b, _c, _d;
const pages = getCurrentPages();
const currentPage = pages[pages.length - 1];
if (currentPage == null) {
const res2 = new HideLoadingFailImpl();
(_a = options == null ? void 0 : options.fail) == null ? void 0 : _a.call(options, res2);
(_b = options == null ? void 0 : options.complete) == null ? void 0 : _b.call(options, res2);
return;
}
const loadingPage = options == null ? void 0 : options.loadingPage;
const systemDialogPages = currentPage.$getSystemDialogPages();
for (let i = systemDialogPages.length - 1; i >= 0; i--) {
const page = systemDialogPages[i];
if (!page.route.startsWith(SYSTEM_DIALOG_LOADING_PAGE_PATH)) {
continue;
}
if (loadingPage == null) {
uni.closeDialogPage({
dialogPage: page
});
} else {
if (loadingPage === page) {
uni.closeDialogPage({
dialogPage: page
});
break;
}
}
}
const res = new HideLoadingSuccessImpl();
(_c = options == null ? void 0 : options.success) == null ? void 0 : _c.call(options, res);
(_d = options == null ? void 0 : options.complete) == null ? void 0 : _d.call(options, res);
};
const API_HIDE_LOADING = "hideLoading";
const registerLoadingOnce = /* @__PURE__ */ once(() => {
registerSystemRoute("uni:showLoading", UniLoadingPage);
});
const hideLoading = /* @__PURE__ */ defineAsyncApi(
API_HIDE_LOADING,
(args, { resolve, reject }) => {
registerLoadingOnce();
hideLoading$1(
/* @__PURE__ */ extend(
{
success: (res) => {
resolve(res);
},
fail: (err) => {
reject(err);
}
},
args
)
);
}
);
const showLoading = /* @__PURE__ */ defineAsyncApi(
API_SHOW_LOADING,
(args, { resolve, reject }) => {
registerLoadingOnce();
return showLoading$1(
extend(
{
success: (res) => {
resolve(res);
},
fail: (err) => {
reject(err);
}
},
args
)
);
}
);
class Friction {
// 构造函数,初始化物体的质量(m)、摩擦力大小(f,这里假设是牛顿单位的力,但乘以1000可能是为了转换为某种特定单位)
constructor(mass, frictionForce) {
this.endPosition = null;
this.lastTimeElapsed = null;
this.totalTimeToStop = 0;
this.mass = mass;
this.frictionForce = 1e3 * frictionForce;
this.startTime = 0;
this.velocity = { x: 0, y: 0 };
this.acceleration = { x: 0, y: 0 };
this.startPosition = { x: 0, y: 0 };
this.endPosition = null;
this.lastTimeElapsed = null;
}
// 设置物体的速度
setVelocity(x, y) {
const speed = Math.sqrt(x * x + y * y);
this.velocity = { x, y };
this.acceleration = {
x: -this.frictionForce * x / speed,
y: -this.frictionForce * y / speed
};
this.totalTimeToStop = Math.abs(x / this.acceleration.x);
if (Number.isNaN(this.totalTimeToStop)) {
this.totalTimeToStop = Math.abs(y / this.acceleration.y);
}
if (Number.isNaN(this.totalTimeToStop)) {
this.totalTimeToStop = 0;
}
this.startTime = Date.now();
this.lastTimeElapsed = null;
}
// 设置物体的起始位置
setStartPosition(x, y) {
this.startPosition = { x, y };
}
// 设置物体的结束位置
setEndPosition(x, y) {
this.endPosition = { x, y };
}
// 计算并返回物体在时间 t 时的位置
positionAtTime(t12) {
if (t12 == null) {
t12 = (Date.now() - this.startTime) / 1e3;
}
if (t12 > this.totalTimeToStop) {
t12 = this.totalTimeToStop;
this.lastTimeElapsed = t12;
}
var x = this.velocity.x * t12 + 0.5 * this.acceleration.x * t12 * t12 + this.startPosition.x;
var y = this.velocity.y * t12 + 0.5 * this.acceleration.y * t12 * t12 + this.startPosition.y;
if (this.acceleration.x > 0 && x < this.endPosition.x || this.acceleration.x < 0 && x > this.endPosition.x) {
x = this.endPosition.x;
}
if (this.acceleration.y > 0 && y < this.endPosition.y || this.acceleration.y < 0 && y > this.endPosition.y) {
y = this.endPosition.y;
}
return { x, y };
}
// 计算并返回物体在时间 t 时的速度
velocityAtTime(t12) {
if (t12 == null) {
t12 = (Date.now() - this.startTime) / 1e3;
}
if (t12 > this.totalTimeToStop) {
t12 = this.totalTimeToStop;
}
return {
dx: this.velocity.x + this.acceleration.x * t12,
dy: this.velocity.y + this.acceleration.y * t12
};
}
// 计算物体停止前的位移量(这里的方法名可能不准确,因为 delta 通常表示变化量)
// 注意:这个方法可能是错误的,因为它基于一个不准确的加速度公式
displacement() {
var tx = -1.5 * Math.pow(this.velocity.x, 2) / this.acceleration.x;
if (Number.isNaN(tx)) {
tx = 0;
}
var ty = -1.5 * Math.pow(this.velocity.y, 2) / this.acceleration.y;
if (Number.isNaN(ty)) {
ty = 0;
}
return {
x: tx,
y: ty
};
}
// 计算物体停止所需的时间(这个方法实际上是多余的,因为已经在 setVelocity 中计算过了)
timeToStop() {
return -this.velocity.x / this.acceleration.x;
}
// 检查物体是否已经停止或到达结束位置
isDone() {
const currentPosition = this.positionAtTime(null);
return currentPosition.x === this.endPosition.x && currentPosition.y === this.endPosition.y || this.lastTimeElapsed === this.totalTimeToStop;
}
// 重新配置物体的质量和摩擦力大小
reconfigure(mass, frictionForce) {
this.mass = mass;
this.frictionForce = 1e3 * frictionForce;
}
}
const t0$4 = template("<div uni-view class=uni-preview-image-loading>");
const t1$2 = template('<div uni-view style="align-items: center;justify-content: center;position: absolute;top: 0;bottom: 0;left: 0;right: 0;"><img uni-image mode=aspectFit style="width: 70px;height: 70px;" draggable=false>');
const t2$2 = template("<div uni-view style=flex:1; class=uni-preview-image-item-background><img uni-image class=uni-preview-image-item draggable=false><div uni-view class=uni-preview-image-patch></div>", 1);
const DEFAULT_DISTANCE = 4;
const FAST_SLIDE_LENGTH = 10;
const SCALE_BOUNDARY_BUFFER = 2;
const MIN_SCALE = 1;
const MAX_SCALE = 3;
const ANIMATION_DURATION = 200;
const _sfc_main$4 = /* @__PURE__ */ defineVaporComponent({
__name: "uni-previewImageItem",
props: {
src: {
type: String,
default: ""
},
index: {
type: Number,
default: -1
},
longPressAction: {
type: Object
},
tips: {
type: Object
},
reset: {
type: Boolean,
default: false
},
resetOnSrcChange: {
type: Boolean,
default: false
}
},
setup(__props) {
const props2 = __props;
const imageView = ref(null);
const mask = ref(null);
const imageMode = ref("aspectFit");
const lastTouchEndTime = ref(0);
const srcPath = ref("");
const screenWidth = ref(0);
const screenHeight = ref(0);
const scaleSize = ref(1);
const lastSlideTouch = ref(null);
const lastTouchPointerTime = ref(0);
const imageTop = ref(0);
const imageMarginTop = ref(0);
const imageLeft = ref(0);
const withAnimation = ref(false);
const imageHeight = ref(0);
const historyX = ref([0, 0]);
const historyY = ref([0, 0]);
const historyT = ref([0, 0]);
const _friction = ref(new Friction(1, 2));
const requestId = ref(-1);
const needExecLongPress = ref(false);
const downPoint = ref(null);
const longPressActionTimeoutId = ref(-1);
const inScaleMode = ref(false);
const scaleGestureActive = ref(false);
const scaleGestureInProgress = ref(false);
const delegateMoveToParent = ref(false);
const inDoubleTapMode = ref(false);
const startTimestamp = ref(0);
const clickTimeoutId = ref(-1);
const transformOrigin = ref([0, 0]);
const loadingFinished = ref(false);
const devicePixelRatio = ref(0);
const loadError = ref(false);
const language = ref("zh-Hans");
const isPreviewImaqeClosed = ref(false);
const swiperTouchDisabled = ref(false);
const ignoreClickUntil = ref(0);
const inScaleBounceBack = ref(false);
const bounceTransitionUntil = ref(0);
const instance2 = getCurrentInstance().proxy;
const getSrcLocalPath = (url) => {
srcPath.value = url;
};
const resetImageState = () => {
var _a, _b, _c, _d;
cancelAnimationFrame(requestId.value);
clearTimeout(clickTimeoutId.value);
clearTimeout(longPressActionTimeoutId.value);
loadingFinished.value = false;
loadError.value = false;
imageMode.value = "aspectFit";
scaleSize.value = 1;
imageTop.value = 0;
imageMarginTop.value = 0;
imageLeft.value = 0;
imageHeight.value = 0;
withAnimation.value = false;
historyX.value = [0, 0];
historyY.value = [0, 0];
historyT.value = [0, 0];
lastSlideTouch.value = null;
needExecLongPress.value = false;
downPoint.value = null;
inScaleMode.value = false;
scaleGestureActive.value = false;
scaleGestureInProgress.value = false;
delegateMoveToParent.value = false;
inDoubleTapMode.value = false;
transformOrigin.value = [0, 0];
inScaleBounceBack.value = false;
bounceTransitionUntil.value = 0;
if (swiperTouchDisabled.value) {
swiperTouchDisabled.value = false;
uni.$emit("__UNIPREVIEWIMAGE", false);
}
(_a = imageView.value) == null ? void 0 : _a.style.setProperty("height", "100%");
(_b = imageView.value) == null ? void 0 : _b.style.setProperty("transition-duration", "0ms");
(_c = imageView.value) == null ? void 0 : _c.style.setProperty("transform-origin", "0px 0px");
(_d = imageView.value) == null ? void 0 : _d.style.setProperty("transform", "translate(0px,0px) scale(1)");
};
watch(() => props2.src, (newValue, oldValue) => {
if (props2.resetOnSrcChange) {
resetImageState();
}
if (newValue != "") {
getSrcLocalPath(newValue);
} else {
srcPath.value = "";
loadingFinished.value = true;
loadError.value = true;
}
}, { immediate: true });
onMounted(() => {
var dpr = uni.getDeviceInfo({ filter: ["devicePixelRatio"] }).devicePixelRatio;
if (dpr == null) {
devicePixelRatio.value = 1;
} else {
devicePixelRatio.value = dpr;
}
const systemInfo = uni.getSystemInfoSync();
language.value = systemInfo.appLanguage;
language.value = uni.getLocale();
});
const previewImageError = (e2) => {
var _a;
(_a = mask.value) == null ? void 0 : _a.style.setProperty("point-events", "none");
loadingFinished.value = true;
loadError.value = true;
};
const onLongPressAction = () => {
var longPressAction = props2.longPressAction;
if (longPressAction != null && longPressAction.itemList.length > 0) {
uni.showActionSheet({
itemList: longPressAction.itemList,
itemColor: longPressAction.itemColor,
success: (e2) => {
var _a;
(_a = longPressAction.success) == null ? void 0 : _a.call(longPressAction, { tapIndex: e2.tapIndex, index: props2.index });
uni.$emit("__UNIPREVIEWLONGPRESS", { type: "success", tapIndex: e2.tapIndex, index: props2.index });
},
fail() {
var _a;
(_a = longPressAction.fail) == null ? void 0 : _a.call(longPressAction, new UniError("uni-previewImage", 1101001, "user cancel"));
uni.$emit("__UNIPREVIEWLONGPRESS", { type: "fail", tapIndex: -1, index: -1 });
}
});
}
};
const preventDefaultScall = (e2) => {
e2 == null ? void 0 : e2.preventDefault();
e2 == null ? void 0 : e2.stopPropagation();
};
const setSwiperTouchDisabled = (disabled) => {
if (swiperTouchDisabled.value == disabled) {
return;
}
swiperTouchDisabled.value = disabled;
uni.$emit("__UNIPREVIEWIMAGE", disabled);
};
const markScaleGesture = () => {
ignoreClickUntil.value = Date.now() + 450;
};
const shouldIgnoreClick = () => {
return Date.now() < ignoreClickUntil.value;
};
const setScaleKeepingViewportCenter = (targetScale) => {
if (scaleSize.value <= 0 || screenWidth.value <= 0 || screenHeight.value <= 0) {
scaleSize.value = targetScale;
return;
}
var ratio = targetScale / scaleSize.value;
var centerX = screenWidth.value / 2;
var centerY = screenHeight.value / 2;
imageLeft.value = centerX - transformOrigin.value[0] - (centerX - imageLeft.value - transformOrigin.value[0]) * ratio;
imageTop.value = centerY - transformOrigin.value[1] - (centerY - imageTop.value - transformOrigin.value[1]) * ratio;
scaleSize.value = targetScale;
};
const protectBounceTransition = () => {
bounceTransitionUntil.value = Date.now() + ANIMATION_DURATION;
};
const onInterceptTouchEvent = (e2) => {
if (inScaleMode.value || scaleGestureActive.value) {
setSwiperTouchDisabled(true);
preventDefaultScall(e2);
return;
}
clearTimeout(clickTimeoutId.value);
};
const shouldDelegateMoveToParent = (slideX, slideY) => {
if (scaleSize.value <= 1 || screenWidth.value <= 0) {
return false;
}
if (Math.abs(slideX) <= Math.abs(slideY)) {
return false;
}
var maxLeft = transformOrigin.value[0] * (scaleSize.value - 1);
var minLeft = screenWidth.value - (transformOrigin.value[0] + (screenWidth.value - transformOrigin.value[0]) * scaleSize.value);
return imageLeft.value >= maxLeft && slideX > 0 || imageLeft.value <= minLeft && slideX < 0;
};
const isAtHorizontalBoundary = () => {
if (scaleSize.value <= 1 || screenWidth.value <= 0) {
return false;
}
var maxLeft = transformOrigin.value[0] * (scaleSize.value - 1);
var minLeft = screenWidth.value - (transformOrigin.value[0] + (screenWidth.value - transformOrigin.value[0]) * scaleSize.value);
return imageLeft.value >= maxLeft || imageLeft.value <= minLeft;
};
const delegateCurrentMoveToParent = (e2, currentSlideTouch) => {
inScaleMode.value = false;
scaleGestureActive.value = false;
scaleGestureInProgress.value = false;
delegateMoveToParent.value = true;
setSwiperTouchDisabled(false);
needExecLongPress.value = false;
clearTimeout(longPressActionTimeoutId.value);
lastSlideTouch.value = e2.touches;
downPoint.value = { x: currentSlideTouch.clientX, y: currentSlideTouch.clientY };
historyX.value = [imageLeft.value, imageLeft.value];
historyY.value = [imageTop.value, imageTop.value];
historyT.value = [e2.timeStamp, e2.timeStamp];
onInterceptTouchEvent(e2);
};
const caculatorTransformOrigin = (e2) => {
var originalCenterX;
var originalCenterY;
if (e2 != null) {
if (e2.touches.length >= 2) {
var point1 = e2.touches[0];
var point2 = e2.touches[1];
originalCenterX = (point1.clientX + point2.clientX) / 2;
originalCenterY = (point1.clientY + point2.clientY) / 2;
if (scaleSize.value * imageHeight.value < screenHeight.value) {
originalCenterY = screenHeight.value / 2;
}
if (imageHeight.value > screenHeight.value && scaleSize.value >= 1) {
originalCenterY = originalCenterY - imageTop.value / scaleSize.value;
}
var oldTransformOrigin = [transformOrigin.value[0], transformOrigin.value[1]];
transformOrigin.value = [originalCenterX, originalCenterY];
if (oldTransformOrigin[0] != 0 && oldTransformOrigin[1] != 1) {
imageLeft.value = imageLeft.value + (scaleSize.value - 1) * (originalCenterX - oldTransformOrigin[0]);
imageTop.value = imageTop.value + (scaleSize.value - 1) * (originalCenterY - oldTransformOrigin[1]);
}
} else if (e2.type == "touchend") {
if (inDoubleTapMode.value && scaleSize.value == 2 && lastSlideTouch.value != null && lastSlideTouch.value.length == 1) {
originalCenterX = lastSlideTouch.value[0].clientX;
originalCenterY = lastSlideTouch.value[0].clientY;
if (scaleSize.value * imageHeight.value < screenHeight.value) {
originalCenterY = screenHeight.value / 2;
}
if (imageHeight.value > screenHeight.value) {
originalCenterY = originalCenterY - imageTop.value;
}
transformOrigin.value = [originalCenterX, originalCenterY];
}
}
}
};
const updateStyle2 = (e2, xDistance, yDistance) => {
var _a, _b, _c;
caculatorTransformOrigin(e2);
if (1 < scaleSize.value) {
var minLeft = screenWidth.value - (transformOrigin.value[0] + (screenWidth.value - transformOrigin.value[0]) * scaleSize.value);
var maxLeft = transformOrigin.value[0] * (scaleSize.value - 1);
if (imageLeft.value > maxLeft) {
imageLeft.value = maxLeft;
onInterceptTouchEvent(e2);
} else if (imageLeft.value < minLeft) {
imageLeft.value = minLeft;
onInterceptTouchEvent(e2);
} else {
preventDefaultScall(e2);
}
} else {
imageLeft.value = 0;
onInterceptTouchEvent(e2);
}
var imageContentTop = imageMarginTop.value > 0 ? imageMarginTop.value : 0;
var imageContentBottom = imageContentTop + imageHeight.value;
var scaledContentHeight = imageHeight.value * scaleSize.value;
if (scaleSize.value <= 1 && imageHeight.value > screenHeight.value) {
var minTop = screenHeight.value - imageHeight.value;
if (imageTop.value > 0) {
imageTop.value = 0;
} else if (imageTop.value < minTop) {
imageTop.value = minTop;
}
if (!Number.isNaN(yDistance) && Math.abs(yDistance - downPoint.value.y) > DEFAULT_DISTANCE) {
preventDefaultScall(e2);
}
} else if (screenHeight.value + SCALE_BOUNDARY_BUFFER < scaledContentHeight) {
var scaledTopWithoutTranslate = transformOrigin.value[1] + (imageContentTop - transformOrigin.value[1]) * scaleSize.value;
var scaledBottomWithoutTranslate = transformOrigin.value[1] + (imageContentBottom - transformOrigin.value[1]) * scaleSize.value;
var visualTop = scaledTopWithoutTranslate + imageTop.value;
var visualBottom = scaledBottomWithoutTranslate + imageTop.value;
if (visualBottom < screenHeight.value) {
imageTop.value = imageTop.value + (screenHeight.value - visualBottom);
} else if (visualTop > 0 && !inScaleBounceBack.value) {
imageTop.value = imageTop.value - visualTop;
}
if (!Number.isNaN(yDistance) && Math.abs(yDistance - downPoint.value.y) > DEFAULT_DISTANCE) {
preventDefaultScall(e2);
}
} else {
if (!inScaleMode.value) {
var scaledTopWithoutTranslate = transformOrigin.value[1] + (imageContentTop - transformOrigin.value[1]) * scaleSize.value;
var centeredTop = (screenHeight.value - scaledContentHeight) / 2;
imageTop.value = centeredTop - scaledTopWithoutTranslate;
if (!Number.isNaN(yDistance) && Math.abs(yDistance - downPoint.value.y) > DEFAULT_DISTANCE) {
preventDefaultScall(e2);
}
} else {
preventDefaultScall(e2);
}
}
var shouldAnimate = withAnimation.value || Date.now() < bounceTransitionUntil.value;
(_a = imageView.value) == null ? void 0 : _a.style.setProperty("transition-duration", shouldAnimate ? ANIMATION_DURATION + "ms" : "0ms");
(_b = imageView.value) == null ? void 0 : _b.style.setProperty("transform-origin", transformOrigin.value[0] + "px " + transformOrigin.value[1] + "px");
(_c = imageView.value) == null ? void 0 : _c.style.setProperty("transform", "translate(" + imageLeft.value + "px," + imageTop.value + "px) scale(" + scaleSize.value + ")");
};
watch(() => props2.reset, (newValue, oldValue) => {
if (newValue != oldValue) {
if (imageView.value != null && (scaleSize.value != 1 || imageLeft.value != 0 || imageTop.value != 0)) {
scaleSize.value = 1;
imageLeft.value = 0;
imageTop.value = 0;
withAnimation.value = false;
updateStyle2(null, NaN, NaN);
}
}
}, { immediate: true });
function doTransform(callback) {
requestId.value = requestAnimationFrame(() => {
callback();
if (!_friction.value.isDone())
doTransform(callback);
});
}
function closePreviewImage2() {
isPreviewImaqeClosed.value = true;
uni.$emit("__UNIPREVIEWIMAGECLOSE");
}
const handleStart = (e2) => {
if (isPreviewImaqeClosed.value)
return;
inScaleMode.value = false;
scaleGestureActive.value = false;
scaleGestureInProgress.value = false;
delegateMoveToParent.value = false;
bounceTransitionUntil.value = 0;
if (e2.touches.length >= 2) {
inScaleMode.value = true;
scaleGestureActive.value = true;
scaleGestureInProgress.value = true;
markScaleGesture();
setSwiperTouchDisabled(true);
} else {
setSwiperTouchDisabled(scaleSize.value > 1 && !isAtHorizontalBoundary());
}
withAnimation.value = false;
cancelAnimationFrame(requestId.value);
clearTimeout(clickTimeoutId.value);
lastSlideTouch.value = e2.touches;
historyX.value = [0, 0];
historyY.value = [0, 0];
historyT.value = [0, 0];
downPoint.value = { x: e2.touches[0].clientX, y: e2.touches[0].clientY };
inDoubleTapMode.value = false;
startTimestamp.value = e2.timeStamp;
e2.preventDefault();
needExecLongPress.value = e2.touches.length < 2;
if (needExecLongPress.value) {
longPressActionTimeoutId.value = setTimeout(() => {
if (needExecLongPress.value) {
onLongPressAction();
}
}, 350);
}
};
const handleMove = (e2) => {
if (isPreviewImaqeClosed.value)
return;
if (e2.touches.length == 1) {
var currentSlideTouch = e2.touches[0];
if (delegateMoveToParent.value) {
needExecLongPress.value = false;
clearTimeout(longPressActionTimeoutId.value);
lastSlideTouch.value = e2.touches;
downPoint.value = { x: currentSlideTouch.clientX, y: currentSlideTouch.clientY };
historyX.value = [imageLeft.value, imageLeft.value];
historyY.value = [imageTop.value, imageTop.value];
historyT.value = [e2.timeStamp, e2.timeStamp];
onInterceptTouchEvent(e2);
return;
}
if (lastSlideTouch.value != null && lastSlideTouch.value.length != 1) {
lastSlideTouch.value = e2.touches;
downPoint.value = { x: currentSlideTouch.clientX, y: currentSlideTouch.clientY };
historyX.value = [imageLeft.value, imageLeft.value];
historyY.value = [imageTop.value, imageTop.value];
historyT.value = [e2.timeStamp, e2.timeStamp];
if (scaleSize.value > 1 || inScaleMode.value || scaleGestureActive.value) {
preventDefaultScall(e2);
} else {
onInterceptTouchEvent(e2);
}
return;
}
if (lastSlideTouch.value != null) {
var slideX = currentSlideTouch.clientX - lastSlideTouch.value[0].clientX;
var slideY = currentSlideTouch.clientY - lastSlideTouch.value[0].clientY;
if (shouldDelegateMoveToParent(slideX, slideY)) {
delegateCurrentMoveToParent(e2, currentSlideTouch);
return;
}
var downX = Math.abs(currentSlideTouch.clientX - downPoint.value.x);
var downY = Math.abs(currentSlideTouch.clientY - downPoint.value.y);
if (downX > DEFAULT_DISTANCE || downY > DEFAULT_DISTANCE) {
needExecLongPress.value = false;
clearTimeout(longPressActionTimeoutId.value);
var handledByImage = false;
if (scaleSize.value > 1) {
setSwiperTouchDisabled(true);
imageLeft.value = imageLeft.value + slideX;
imageTop.value = imageTop.value + slideY;
updateStyle2(e2, currentSlideTouch.clientX, currentSlideTouch.clientY);
handledByImage = true;
} else if (imageHeight.value > screenHeight.value && downY > downX) {
setSwiperTouchDisabled(true);
imageTop.value = imageTop.value + slideY;
updateStyle2(e2, currentSlideTouch.clientX, currentSlideTouch.clientY);
preventDefaultScall(e2);
handledByImage = true;
} else {
setSwiperTouchDisabled(false);
onInterceptTouchEvent(e2);
}
if (handledByImage) {
historyX.value.shift();
historyX.value.push(imageLeft.value);
historyY.value.shift();
historyY.value.push(imageTop.value);
historyT.value.shift();
historyT.value.push(e2.timeStamp);
}
lastSlideTouch.value = e2.touches;
needExecLongPress.value = false;
} else {
needExecLongPress.value = true;
}
} else {
lastSlideTouch.value = e2.touches;
}
} else if (e2.touches.length >= 2) {
inScaleMode.value = true;
scaleGestureActive.value = true;
scaleGestureInProgress.value = true;
setSwiperTouchDisabled(true);
markScaleGesture();
needExecLongPress.value = false;
clearTimeout(longPressActionTimeoutId.value);
var currentFirstTouch = e2.touches[0];
var currentSecondTouch = e2.touches[1];
var currentXSlideLength = currentFirstTouch.clientX - currentSecondTouch.clientX;
var currentYSlideLength = currentFirstTouch.clientY - currentSecondTouch.clientY;
var currentLongSideLength = Math.sqrt(currentXSlideLength * currentXSlideLength + currentYSlideLength * currentYSlideLength);
if (lastSlideTouch.value != null && lastSlideTouch.value.length >= 2) {
var lastFirstTouch = lastSlideTouch.value[0];
var lastSecondTouch = lastSlideTouch.value[1];
var lastXSlideLength = lastFirstTouch.clientX - lastSecondTouch.clientX;
var lastYSlideLength = lastFirstTouch.clientY - lastSecondTouch.clientY;
var lastLongSideLength = Math.sqrt(lastXSlideLength * lastXSlideLength + lastYSlideLength * lastYSlideLength);
if (currentLongSideLength != lastLongSideLength) {
scaleSize.value = scaleSize.value * (currentLongSideLength / lastLongSideLength);
updateStyle2(e2, NaN, NaN);
}
}
preventDefaultScall(e2);
needExecLongPress.value = false;
lastSlideTouch.value = e2.touches;
}
};
const handleEnd = (e2) => {
if (isPreviewImaqeClosed.value)
return;
const wasScaleMode = inScaleMode.value || scaleGestureActive.value || scaleGestureInProgress.value;
if (wasScaleMode) {
markScaleGesture();
}
inScaleMode.value = false;
needExecLongPress.value = false;
clearTimeout(longPressActionTimeoutId.value);
var current = Date.now();
if (wasScaleMode) {
if (scaleSize.value > MAX_SCALE) {
withAnimation.value = true;
protectBounceTransition();
setScaleKeepingViewportCenter(MAX_SCALE);
inScaleBounceBack.value = true;
updateStyle2(e2, NaN, NaN);
inScaleBounceBack.value = false;
} else if (scaleSize.value < MIN_SCALE) {
withAnimation.value = true;
protectBounceTransition();
setScaleKeepingViewportCenter(MIN_SCALE);
imageLeft.value = 0;
imageTop.value = 0;
inScaleBounceBack.value = true;
updateStyle2(e2, NaN, NaN);
inScaleBounceBack.value = false;
} else {
withAnimation.value = false;
updateStyle2(e2, NaN, NaN);
}
lastTouchEndTime.value = current;
lastSlideTouch.value = null;
scaleGestureActive.value = false;
if (e2.touches.length == 0) {
scaleGestureInProgress.value = false;
}
delegateMoveToParent.value = false;
setSwiperTouchDisabled(false);
return;
}
if (historyY.value[0] == 0 && historyY.value[1] == 0 && historyX.value[0] == 0 && historyX.value[1] == 0) {
withAnimation.value = true;
if (current - lastTouchEndTime.value < 350) {
if (lastSlideTouch.value != null && lastSlideTouch.value.length > 0) {
var downX = Math.abs(lastSlideTouch.value[0].clientX - downPoint.value.x);
var downY = Math.abs(lastSlideTouch.value[0].clientY - downPoint.value.y);
if (downX > FAST_SLIDE_LENGTH || downY > FAST_SLIDE_LENGTH) {
lastSlideTouch.value = null;
scaleGestureActive.value = false;
delegateMoveToParent.value = false;
setSwiperTouchDisabled(false);
return;
}
}
if (scaleSize.value > 1) {
scaleSize.value = 1;
imageLeft.value = 0;
updateStyle2(e2, NaN, NaN);
} else if (scaleSize.value == 1) {
scaleSize.value = 2;
inDoubleTapMode.value = true;
updateStyle2(e2, NaN, NaN);
}
} else if (e2.touches.length == 0) {
if (lastSlideTouch.value != null && lastSlideTouch.value.length == 1 && e2.timeStamp - startTimestamp.value < 160) {
var downX = Math.abs(lastSlideTouch.value[0].clientX - downPoint.value.x);
var downY = Math.abs(lastSlideTouch.value[0].clientY - downPoint.value.y);
if (downX < FAST_SLIDE_LENGTH && downY < FAST_SLIDE_LENGTH && !shouldIgnoreClick()) {
clickTimeoutId.value = setTimeout(() => {
closePreviewImage2();
}, 200);
}
}
lastTouchEndTime.value = current;
}
} else {
var deltaTime = historyT.value[1] - historyT.value[0];
var xv = 0;
var yv = 0;
if (deltaTime > 0) {
xv = 1e3 * (historyX.value[1] - historyX.value[0]) / deltaTime;
yv = 1e3 * (historyY.value[1] - historyY.value[0]) / deltaTime;
}
if (!Number.isFinite(xv)) {
xv = 0;
}
if (!Number.isFinite(yv)) {
yv = 0;
}
_friction.value.setVelocity(xv, yv);
_friction.value.setStartPosition(imageLeft.value, imageTop.value);
const x0 = _friction.value.displacement().x;
const y0 = _friction.value.displacement().y;
var x = imageLeft.value;
if (!Number.isNaN(x0))
x = x0 + imageLeft.value;
var y = imageTop.value;
if (!Number.isNaN(y0))
y = y0 + imageTop.value;
_friction.value.setEndPosition(x, y);
doTransform(() => {
var p2 = _friction.value.positionAtTime(null);
if (Number.isNaN(p2.x) && Number.isNaN(p2.y)) {
cancelAnimationFrame(requestId.value);
}
if (!Number.isNaN(p2.x))
imageLeft.value = p2.x;
if (!Number.isNaN(p2.y))
imageTop.value = p2.y;
updateStyle2(e2, NaN, NaN);
});
}
lastSlideTouch.value = null;
scaleGestureActive.value = false;
if (e2.touches.length == 0) {
scaleGestureInProgress.value = false;
}
delegateMoveToParent.value = false;
setSwiperTouchDisabled(false);
};
const handleCancel = (e2) => {
handleEnd(e2);
clearTimeout(clickTimeoutId.value);
inScaleMode.value = false;
scaleGestureActive.value = false;
scaleGestureInProgress.value = false;
delegateMoveToParent.value = false;
setSwiperTouchDisabled(false);
};
const toPreviewEvent = (e2) => {
const points = [];
for (var i = 0; i < e2.touches.length; i++) {
const touch = e2.touches[i];
points.push({ clientX: touch.clientX, clientY: touch.clientY });
}
const event = {
type: e2.type,
timeStamp: e2.timeStamp,
touches: points,
preventDefault: () => {
e2.preventDefault();
},
stopPropagation: () => {
e2.stopPropagation();
}
};
return event;
};
const onstart = (e2) => {
lastTouchPointerTime.value = Date.now();
handleStart(toPreviewEvent(e2));
};
const onmove = (e2) => {
lastTouchPointerTime.value = Date.now();
handleMove(toPreviewEvent(e2));
};
const onend = (e2) => {
lastTouchPointerTime.value = Date.now();
handleEnd(toPreviewEvent(e2));
};
const oncancel = (e2) => {
lastTouchPointerTime.value = Date.now();
handleCancel(toPreviewEvent(e2));
};
const mousePressed = ref(false);
const isSimulatedMouseEvent = () => {
return Date.now() - lastTouchPointerTime.value < 600;
};
const toPreviewEventFromMouse = (e2, type) => {
const points = [];
if (type != "touchend") {
points.push({ clientX: e2.clientX, clientY: e2.clientY });
}
const event = {
type,
timeStamp: e2.timeStamp,
touches: points,
preventDefault: () => {
e2.preventDefault();
},
stopPropagation: () => {
e2.stopPropagation();
}
};
return event;
};
const onMouseStart = (e2) => {
if (isSimulatedMouseEvent())
return;
mousePressed.value = true;
handleStart(toPreviewEventFromMouse(e2, "touchstart"));
};
const onMouseMove = (e2) => {
if (!mousePressed.value)
return;
if (isSimulatedMouseEvent())
return;
handleMove(toPreviewEventFromMouse(e2, "touchmove"));
};
const onMouseEnd = (e2) => {
mousePressed.value = false;
if (isSimulatedMouseEvent())
return;
handleEnd(toPreviewEventFromMouse(e2, "touchend"));
};
const caculatorImageSize = (imgWidth, imgHeight) => {
var _a, _b;
var scaleImageSize = imgHeight / (imgWidth / screenWidth.value);
if (scaleImageSize > screenHeight.value) {
imageHeight.value = scaleImageSize;
imageMode.value = "aspectFill";
(_a = imageView.value) == null ? void 0 : _a.style.setProperty("height", scaleImageSize + "px");
} else {
imageMode.value = "aspectFit";
(_b = imageView.value) == null ? void 0 : _b.style.setProperty("height", "100%");
}
imageMarginTop.value = (screenHeight.value - scaleImageSize) / 2;
imageHeight.value = scaleImageSize;
};
const onImageLoad = (e2) => {
var _a;
(_a = mask.value) == null ? void 0 : _a.style.setProperty("point-events", "none");
uni.createSelectorQuery().in(instance2).select(".uni-preview-image-patch").boundingClientRect().exec((ret) => {
if (ret.length == 1) {
var rect = mask.value.getBoundingClientRect();
screenHeight.value = rect.height;
screenWidth.value = rect.width;
if (devicePixelRatio.value == 0) {
var dpr = uni.getDeviceInfo({ filter: ["devicePixelRatio"] }).devicePixelRatio;
if (dpr == null) {
devicePixelRatio.value = 1;
} else {
devicePixelRatio.value = dpr;
}
}
caculatorImageSize(e2.detail.width / devicePixelRatio.value, e2.detail.height / devicePixelRatio.value);
}
});
loadingFinished.value = true;
};
const reloadImage = (e2) => {
var _a;
if (srcPath.value == "") {
loadingFinished.value = false;
loadError.value = false;
setTimeout(() => {
loadError.value = true;
loadingFinished.value = true;
}, 1e3);
e2.stopPropagation();
return;
}
(_a = mask.value) == null ? void 0 : _a.style.setProperty("point-events", "none");
loadingFinished.value = false;
loadError.value = false;
var tempPath = srcPath.value + "";
srcPath.value = "";
setTimeout(() => {
srcPath.value = tempPath;
}, 100);
e2.stopPropagation();
};
const _component_loading = _sfc_main$C;
const n10 = t2$2();
const n0 = child(n10);
const n1 = next(n0);
on$1(n0, "error", withImageEventDetail(previewImageError, "error"));
on$1(n0, "load", withImageEventDetail(onImageLoad, "load"));
setStaticTemplateRef(n0, imageView, null, "imageView");
on$1(n1, "touchstart", onstart);
on$1(n1, "touchmove", onmove);
on$1(n1, "touchend", onend);
on$1(n1, "touchcancel", oncancel);
on$1(n1, "mousedown", onMouseStart);
on$1(n1, "mousemove", onMouseMove);
on$1(n1, "mouseup", onMouseEnd);
setStaticTemplateRef(n1, mask, null, "mask");
renderEffect(() => {
setImageMode(n0, imageMode.value);
setImageSrc(n0, srcPath.value);
});
setInsertionState(n10, 2);
createIf(() => !loadingFinished.value, () => {
const n5 = t0$4();
setInsertionState(n5);
withComponentId("9ba1ca88", () => createComponentWithFallback(_component_loading, { style: { "margin": "auto", "width": "54px", "height": "54px", "border-color": "#d3d3d3" } }));
return n5;
});
setInsertionState(n10, 3);
createIf(() => loadError.value, () => {
const n9 = t1$2();
const n8 = child(n9);
on$1(n8, "click", reloadImage);
setImageSrc(n8, "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJAAAACQCAMAAADQmBKKAAAAilBMVEUAAAD////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////2N2iNAAAALXRSTlMAf/kN/BOp7IxPBsMz9NzMRi0h4L7Q5pFjnhfVmIN3WUo6W6NUPrVtJ0yhcR84ApfrAAADTElEQVR42u3b3XaiMBSG4V1CABFBhFr/f1q1Tmf2/d/eHJoYrNJvu1a6Vp7zzrwthAAJFARBEARBEARBEPxmqtiuk3bZTJmnzbJN1ttC0SNeSJ76k71yhyrbqbs9LF4zG8Z8U9TO1Pc9wkG7JOI7Rh/jb3pkg96X/JBqcKtHNGhW8sOW284eyaD9K/cyrN0ewSA9577iTDk9YkGDlH+gOVo9ckH5G/9MvHF7mGCTin/spK978KAiZUA5sXvwoPGIO8XVfDM4TxZEi0k92HzdGoTTwuzBg7ZR5//yNlDOQDysUu4wOlo9DPbE7Ihuzg354RSzI2a5oHHk/sLZgr5xnrs/IhdUjNyrnb47KJOnBU3SrvngvnH5nKC8Ylv0iVxJ8aDrf7Us6GGHVD5owLZW9TrcpXSQTtmS5NTLohIOmrNlRX2pRjRoz5aEenth0SB7ampzrAcPmtnjS4E9eJA1RqIC7MGD3tn0ifbgQUtrvkB78KCddcBqtAcPStiQoT14kIrM+x8t28PomM/gHjxoaJ5BC7QHD1IxX3zAPXjQHzaM4R48KDOfd8R7GJtX38R7GDuFBnAPHlTwRazFexiaWCvywNoImpMHzIlsQx4YWue0B8xRX5MHGiNoQh5IjSBNHoiMoJw84F2Qd4fMu5Pau2Hv3YXRu6nDu8nVu9sP5wYNpmNz4MK3sLiD9dQA3+TjVnxxIvgxCDflixeSfVCEX+4cCX2Ulr2wpUT4ywbQv8i+sOGvY0AZO6MWfWEF0SPziOX4UecMHfPOVQR/6QmoYzacyQC/FoYHCLdkwV+c97dh045M+NJCf3UE/KnhxReXbhi46qPLU668ZeAMghfwXAkDo1V+iZO+2LImBL4InCdsKXMC4MvkumVLfCQAvpGgKNm2IQC81YI+I7adCABvRqmHfKXRBAC36+gs4ivpmQDYhqbFeuT+yJ4AyJYvOnZtJo6AORXZFKfGqyl3GDn5z942qCf14O/qNeZOKXS85DdWNjUB5LeetppA+OZc4AHh6duXkdNZfoM3rxQBxLfAV8j0Lv+RQHkggPxnFDMCSH9oEid7Akh/inOaaQKIfqwUV28HRTD8c660aYYf6/e9oiAIgiAIgiAIguAX+w9i21DdU9TtnwAAAABJRU5ErkJggg==");
on$1(n9, "click", closePreviewImage2);
return n9;
});
return n10;
}
});
const _style_0$4 = "\n.uni-preview-image-item {\n width: 100%;\n height: 100%;\n transition-property: transform;\n transition-duration: 0ms;\n}\n.uni-preview-image-patch {\n width: 100%;\n height: 100%;\n background-color: transparent;\n position: absolute;\n}\n.uni-preview-image-loading {\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n pointer-events: none;\n}\n.uni-preview-image-item-background {\n background-color: black;\n overflow: hidden;\n}\n.uni-preview-image-tips-retry {\n color: blue;\n font-size: 18px;\n margin-top: 16px;\n text-decoration-line: underline;\n}\n.uni-preview-image-tips-error {\n font-size: 18px;\n color: red;\n}\n";
const UniPreviewImageItem = /* @__PURE__ */ _export_sfc(_sfc_main$4, [["styles", [_style_0$4]]]);
const t0$3 = template("<div uni-view data-v-212d40c7 class=uni-preview-image-number-indicator-layout><span uni-text data-v-212d40c7 class=uni-preview-image-number-indicator> ");
const t1$1 = template("<div uni-view data-v-212d40c7>");
const t2$1 = template("<div uni-view data-v-212d40c7 class=uni-preview-image-default-indicator-layout>");
const _sfc_main$3 = /* @__PURE__ */ defineVaporComponent({
__name: "previewImage",
__multiRoot: true,
setup(__props) {
const urls = ref(null);
const current = ref(0);
const swiperCurrent = ref(1);
const swiperCircular = ref(false);
const swiperItems = ref(new Array());
let lastItemIndex = 1;
const resetCurrent = ref(0);
const loop = ref(false);
const disableTouch = ref(false);
const numberIndicator = ref("");
const indicatorIndex = ref(0);
const indicator = ref("number");
const longPressAction = ref(null);
const tips = ref(null);
const normalizePreviewIndex = (index2, len) => {
if (len <= 0) {
return 0;
}
if (index2 < 0) {
return 0;
}
if (index2 >= len) {
return len - 1;
}
return index2;
};
const getPreviewIndex = (index2) => {
if (urls.value == null) {
return 0;
}
const len = urls.value.length;
if (len <= 0) {
return 0;
}
if (loop.value) {
var realIndex = index2;
while (realIndex < 0) {
realIndex += len;
}
while (realIndex >= len) {
realIndex -= len;
}
return realIndex;
}
return normalizePreviewIndex(index2, len);
};
const createSwiperItem = (slot, index2) => {
const list2 = urls.value;
if (list2 == null || list2.length == 0) {
return { slot, index: -1, src: "" };
}
const realIndex = getPreviewIndex(index2);
return { slot, index: realIndex, src: list2[realIndex] };
};
const updateIndicator = (index2) => {
var _a;
numberIndicator.value = index2 + 1 + " / " + ((_a = urls.value) == null ? void 0 : _a.length);
indicatorIndex.value = index2;
};
const shouldRenderItem = (index2) => {
if (index2 < 0) {
return false;
}
if (loop.value) {
return true;
}
const list2 = urls.value;
if (list2 == null || list2.length <= 3) {
return true;
}
return Math.abs(index2 - current.value) <= 2;
};
const updateSwiperCircular = () => {
const list2 = urls.value;
if (list2 == null || list2.length <= 1) {
swiperCircular.value = false;
return;
}
swiperCircular.value = loop.value;
};
const updateLoopSwiperItems = (realIndex, targetSlot) => {
const items = new Array();
const prevSlot = (targetSlot - 1 + 3) % 3;
const nextSlot = (targetSlot + 1) % 3;
for (let i = 0; i < 3; i++) {
var itemIndex = realIndex;
if (i == prevSlot) {
itemIndex = realIndex - 1;
} else if (i == nextSlot) {
itemIndex = realIndex + 1;
}
items.push(createSwiperItem(i, itemIndex));
}
swiperItems.value = items;
swiperCurrent.value = targetSlot;
lastItemIndex = targetSlot;
};
const updateNonLoopSwiperItems = (realIndex) => {
const list2 = urls.value;
const items = new Array();
if (list2 == null || list2.length == 0) {
swiperItems.value = items;
swiperCurrent.value = 0;
lastItemIndex = 0;
return;
}
for (let i = 0; i < list2.length; i++) {
items.push(createSwiperItem(i, i));
}
swiperItems.value = items;
swiperCurrent.value = realIndex;
lastItemIndex = realIndex;
};
function initSwiperItems() {
const list2 = urls.value;
const items = new Array();
if (list2 == null || list2.length == 0) {
swiperItems.value = items;
swiperCurrent.value = 0;
lastItemIndex = 0;
return;
}
const len = list2.length;
current.value = normalizePreviewIndex(current.value, len);
if (len == 1) {
items.push(createSwiperItem(0, current.value));
swiperItems.value = items;
swiperCurrent.value = 0;
lastItemIndex = 0;
return;
}
if (loop.value) {
updateLoopSwiperItems(current.value, 1);
updateSwiperCircular();
return;
}
updateNonLoopSwiperItems(current.value);
updateSwiperCircular();
}
function switchToPreviewIndex(targetIndex, targetSlot) {
const list2 = urls.value;
if (list2 == null || list2.length == 0) {
return;
}
const len = list2.length;
if (len == 1) {
current.value = 0;
swiperCurrent.value = 0;
lastItemIndex = 0;
updateIndicator(0);
return;
}
const realIndex = getPreviewIndex(targetIndex);
current.value = realIndex;
updateLoopSwiperItems(realIndex, targetSlot);
updateSwiperCircular();
updateIndicator(realIndex);
}
const pageInstance = getCurrentInstance().proxy;
const uniPageInstance = pageInstance.$page;
onUnload(() => {
uni.$off("__UNIPREVIEWIMAGE");
uni.$off("__UNIPREVIEWIMAGECLOSE");
uni.$off("__UNIPREVIEWLONGPRESS");
uni.$off("__CLOSEPREVIEWIMAGE");
});
const __onPreviewLoadCallback = (result) => {
urls.value = result["urls"];
if (result["current"] != null) {
var c = result["current"];
if (typeof c == "number") {
var d = c;
if (d < 0 || d >= urls.value.length)
d = 0;
current.value = d;
} else if (typeof c == "string") {
var index2 = urls.value.indexOf(c);
if (index2 < 0) {
index2 = 0;
}
current.value = index2;
}
indicatorIndex.value = current.value;
resetCurrent.value = current.value;
}
if (result["indicator"] != null) {
indicator.value = result["indicator"];
}
if (result["longPressActions"] != null) {
longPressAction.value = {
itemList: result["longPressActions"]["itemList"],
itemColor: result["longPressActions"]["itemColor"]
};
}
if (result["loop"] != null) {
loop.value = result["loop"];
}
initSwiperItems();
updateIndicator(current.value);
};
const onPreviewImageChanged = (e2) => {
const itemIndex = e2.detail.current;
swiperCurrent.value = itemIndex;
if (!loop.value) {
current.value = itemIndex;
lastItemIndex = itemIndex;
updateSwiperCircular();
updateIndicator(itemIndex);
return;
}
if (itemIndex == lastItemIndex) {
return;
}
const item = swiperItems.value[itemIndex];
if (item == null || item.index < 0) {
return;
}
switchToPreviewIndex(item.index, itemIndex);
};
function onPreviewImageFinish(e2) {
resetCurrent.value = current.value;
}
const setDisableTouch = (isDisable) => {
disableTouch.value = isDisable;
};
const closePreviewPage = () => {
uni.closeDialogPage({
dialogPage: uniPageInstance,
animationType: "fade-out"
});
};
onLoad(() => {
uni.$once("__onPreviewLoadCallback", __onPreviewLoadCallback);
uni.$emit("__onPreviewLoad", null);
uni.$on("__UNIPREVIEWIMAGE", setDisableTouch);
uni.$on("__UNIPREVIEWIMAGECLOSE", closePreviewPage);
uni.$on("__CLOSEPREVIEWIMAGE", () => {
closePreviewPage();
});
});
onBackPress((options) => {
return false;
});
initUniPageHooks();
const _component_swiper_item = _sfc_main$c;
const n8 = withComponentId("c275e6b6", () => createComponent$1(_sfc_main$d, {
class: "uni-preview-image-swiper",
style: { "flex": "1", "background-color": "black" },
"indicator-dots": false,
circular: () => unref(swiperCircular),
current: () => unref(swiperCurrent),
onChange: () => onPreviewImageChanged,
onAnimationfinish: () => onPreviewImageFinish,
"disable-touch": () => unref(disableTouch)
}, extend$1(() => {
const n0 = createIf(
() => unref(urls) != null,
() => {
const n2 = createFor(
() => unref(swiperItems),
(_for_item0) => {
const n7 = withComponentId("01b46b7d-" + _for_item0.value.slot, () => createComponentWithFallback(_component_swiper_item, { class: "uni-preview-image-swiper-item" }, extend$1(() => {
const n4 = createIf(
() => shouldRenderItem(_for_item0.value.index),
() => {
const n6 = withComponentId("01b46f7d-" + _for_item0.value.slot, () => createComponent$1(
UniPreviewImageItem,
{
index: () => _for_item0.value.index,
src: () => _for_item0.value.src,
longPressAction: () => unref(longPressAction),
tips: () => unref(tips),
reset: () => _for_item0.value.index == unref(resetCurrent),
resetOnSrcChange: true
},
null,
2
/* SLOT */
));
return n6;
},
null,
129
/* TRUE_SINGLE_ROOT, SLOT_ROOT */
);
return n4;
}, {
_: 1
/* NON_STABLE */
})));
return n7;
},
(item) => item.slot,
34
/* IS_COMPONENT, SLOT_ROOT */
);
return n2;
},
null,
129
/* TRUE_SINGLE_ROOT, SLOT_ROOT */
);
return n0;
}, {
_: 1
/* NON_STABLE */
})));
const n9 = createIf(() => unref(indicator) == "number", () => {
const n12 = t0$3();
const n11 = child(n12);
const x11 = txt(n11);
renderEffect(() => setText(x11, normalizeUniText(toDisplayString(unref(numberIndicator)))));
return n12;
});
const n13 = createIf(() => unref(indicator) == "default", () => {
const n18 = t2$1();
setInsertionState(n18);
createFor(
() => unref(urls).length,
(_for_item0) => {
const n17 = t1$1();
renderEffect(() => setClass(n17, ["uni-preview-image-default-indicator", unref(indicatorIndex) + 1 == _for_item0.value ? "uni-preview-image-default-indicator-active" : "uni-preview-image-default-indicator-default"]));
return n17;
},
void 0,
9
/* FAST_REMOVE, IS_SINGLE_NODE */
);
applyVShow(n18, () => unref(urls) != null);
return n18;
});
return [n8, n9, n13];
}
});
const _style_0$3 = "\n.uni-preview-image-swiper {\n overflow: hidden;\n}\n.uni-preview-image-swiper-item {\n background-color: black;\n overflow: hidden;\n}\n.uni-preview-image-default-indicator {\n width: 9px;\n height: 9px;\n border-style: solid;\n border-radius: 9px;\n margin: 2px 3px;\n border-width: .1px;\n border-color: #AAAAAA;\n}\n.uni-preview-image-default-indicator-default {\n background-color: #AAAAAA;\n}\n.uni-preview-image-default-indicator-active {\n background-color: #ffffff;\n}\n.uni-preview-image-default-indicator-layout {\n bottom: var(--uni-safe-area-inset-bottom);\n margin-bottom: 8px;\n flex-direction: row;\n position: absolute;\n left: 0px;\n right: 0px;\n justify-content: center;\n}\n.uni-preview-image-number-indicator-layout {\n position: absolute;\n left: 0;\n right: 0;\n top: var(--uni-safe-area-inset-top);\n margin-top: 8px;\n}\n.uni-preview-image-number-indicator {\n color: white;\n font-size: 16px;\n margin: auto;\n padding: 8px 20px;\n background-color: rgba(0, 0, 0, .3);\n line-height: 1;\n border-radius: 32px;\n}\n\n";
const UniPreviewImagePage = /* @__PURE__ */ _export_sfc(_sfc_main$3, [["styles", [_style_0$3]]]);
const t0$2 = template("<div uni-view class=uni-preview-image-number-indicator-layout><span uni-text class=uni-preview-image-number-indicator> ");
const t1 = template("<div uni-view>");
const t2 = template("<div uni-view class=uni-preview-image-default-indicator-layout>");
const _sfc_main$2 = /* @__PURE__ */ defineVaporComponent({
__name: "uni-previewImageNonVapor",
props: {
urls: {
type: Array,
default: null
},
current: {
type: Number,
default: 0
},
resetCurrent: {
type: Number,
default: 0
},
loop: {
type: Boolean,
default: false
},
disableTouch: {
type: Boolean,
default: false
},
numberIndicator: {
type: String,
default: ""
},
indicatorIndex: {
type: Number,
default: 0
},
indicator: {
type: String,
default: "number"
},
longPressAction: {
type: Object
},
tips: {
type: Object
}
},
emits: ["previewImageChanged", "previewImageFinish"],
__multiRoot: true,
setup(__props, { emit: __emit }) {
const props2 = __props;
const emit2 = __emit;
const shouldRender = (index2) => {
var _a;
const len = (_a = props2.urls) == null ? void 0 : _a.length;
if (len == null) {
return false;
}
if (len <= 3) {
return true;
}
const c = props2.current;
if (index2 == c) {
return true;
}
if (props2.loop) {
const prev = c == 0 ? len - 1 : c - 1;
const next2 = c == len - 1 ? 0 : c + 1;
const prev2 = prev == 0 ? len - 1 : prev - 1;
const next22 = next2 == len - 1 ? 0 : next2 + 1;
if (index2 == prev || index2 == next2 || index2 == prev2 || index2 == next22) {
return true;
}
} else if (Math.abs(index2 - c) <= 2) {
return true;
}
return false;
};
const handlePreviewImageChanged = (e2) => {
emit2("previewImageChanged", e2);
};
const handlePreviewImageFinish = (e2) => {
emit2("previewImageFinish", e2);
};
const _component_swiper_item = _sfc_main$c;
const n8 = withComponentId("782d2844", () => createComponent$1(_sfc_main$d, {
class: "uni-preview-image-swiper",
style: { "flex": "1", "background-color": "black" },
"indicator-dots": false,
circular: () => props2.loop,
current: () => props2.current,
onChange: () => handlePreviewImageChanged,
onAnimationfinish: () => handlePreviewImageFinish,
"disable-touch": () => props2.disableTouch
}, extend$1(() => {
const n0 = createIf(
() => props2.urls != null,
() => {
const n2 = createFor(
() => props2.urls,
(_for_item0, _for_key0) => {
const n7 = withComponentId("6f3de455", () => createComponentWithFallback(_component_swiper_item, { class: "uni-preview-image-swiper-item" }, extend$1(() => {
const n4 = createIf(
() => shouldRender(_for_key0.value),
() => {
const n6 = withComponentId("6f3deadc", () => createComponent$1(
UniPreviewImageItem,
{
index: () => _for_key0.value,
src: () => _for_item0.value,
longPressAction: () => props2.longPressAction,
tips: () => props2.tips,
reset: () => _for_key0.value == props2.resetCurrent
},
null,
2
/* SLOT */
));
return n6;
},
null,
129
/* TRUE_SINGLE_ROOT, SLOT_ROOT */
);
return n4;
}, {
_: 1
/* NON_STABLE */
})));
return n7;
},
void 0,
34
/* IS_COMPONENT, SLOT_ROOT */
);
return n2;
},
null,
129
/* TRUE_SINGLE_ROOT, SLOT_ROOT */
);
return n0;
}, {
_: 1
/* NON_STABLE */
})));
const n9 = createIf(() => props2.indicator == "number", () => {
const n12 = t0$2();
const n11 = child(n12);
const x11 = txt(n11);
renderEffect(() => setText(x11, normalizeUniText(toDisplayString(props2.numberIndicator))));
return n12;
});
const n13 = createIf(() => props2.indicator == "default", () => {
const n18 = t2();
setInsertionState(n18);
createFor(
() => props2.urls.length,
(_for_item0) => {
const n17 = t1();
renderEffect(() => setClass(n17, ["uni-preview-image-default-indicator", props2.indicatorIndex + 1 == _for_item0.value ? "uni-preview-image-default-indicator-active" : "uni-preview-image-default-indicator-default"]));
return n17;
},
void 0,
9
/* FAST_REMOVE, IS_SINGLE_NODE */
);
applyVShow(n18, () => props2.urls != null);
return n18;
});
return [n8, n9, n13];
}
});
const _style_0$2 = "\n.uni-preview-image-swiper {\n overflow: hidden;\n}\n.uni-preview-image-swiper-item {\n background-color: black;\n overflow: hidden;\n}\n.uni-preview-image-default-indicator {\n width: 9px;\n height: 9px;\n border-style: solid;\n border-radius: 9px;\n margin: 2px 3px;\n border-width: .1px;\n border-color: #AAAAAA;\n}\n.uni-preview-image-default-indicator-default {\n background-color: #AAAAAA;\n}\n.uni-preview-image-default-indicator-active {\n background-color: #ffffff;\n}\n.uni-preview-image-default-indicator-layout {\n bottom: var(--uni-safe-area-inset-bottom);\n margin-bottom: 8px;\n flex-direction: row;\n position: absolute;\n left: 0px;\n right: 0px;\n justify-content: center;\n}\n.uni-preview-image-number-indicator-layout {\n position: absolute;\n left: 0;\n right: 0;\n top: var(--uni-safe-area-inset-top);\n margin-top: 8px;\n}\n.uni-preview-image-number-indicator {\n color: white;\n font-size: 16px;\n margin: auto;\n padding: 8px 20px;\n background-color: rgba(0, 0, 0, .3);\n line-height: 1;\n border-radius: 32px;\n}\n";
const UniPreviewImageNonVapor = /* @__PURE__ */ _export_sfc(_sfc_main$2, [["styles", [_style_0$2]]]);
const UniErrorPreviewImage = "uni-previewImage";
const PreviewImageUniErrors = /* @__PURE__ */ new Map([
/**
* 用户取消
*/
[1101001, "user cancel"],
/**
* urls至少包含一张图片地址
*/
[1001, "fail parameter error: parameter.urls should have at least 1 item"],
/**
* 文件不存在
*/
[1101003, "file not find"],
/**
* 图片加载失败
*/
[1101004, "Failed to load resource"],
/**
* 未获取权限
*/
[1101005, "No Permission"],
/**
* 其他错误
*/
[1101010, "unexpect error:please check previewImage.uvue is in pages.json"]
]);
class PreviewImageErrorImpl extends UniError {
constructor(errCode, uniErrorSubject) {
super();
this.errSubject = uniErrorSubject;
this.errCode = errCode;
this.errMsg = PreviewImageUniErrors.get(errCode) ?? "";
}
}
function __previewImage(option) {
var _a, _b;
if (option.urls.length == 0) {
let error = new PreviewImageErrorImpl(1001, UniErrorPreviewImage);
(_a = option.fail) == null ? void 0 : _a.call(option, error);
(_b = option.complete) == null ? void 0 : _b.call(option, error);
return;
}
uni.$once("__onPreviewLoad", () => {
var object = {
current: option.current,
urls: option.urls,
indicator: option.indicator,
loop: option.loop
};
if (option.longPressActions != null) {
object.longPressActions = {
itemList: option.longPressActions.itemList,
itemColor: option.longPressActions.itemColor
};
}
uni.$emit("__onPreviewLoadCallback", object);
});
uni.$on("__UNIPREVIEWLONGPRESS", (value) => {
var _a2, _b2, _c, _d, _e, _f, _g, _h;
if (option.longPressActions != null) {
var type = value["type"];
var tapIndex = value["tapIndex"];
var index2 = value["index"];
if (type == "success") {
var success = { tapIndex, index: index2 };
(_b2 = (_a2 = option.longPressActions) == null ? void 0 : _a2.success) == null ? void 0 : _b2.call(_a2, success);
(_d = (_c = option.longPressActions) == null ? void 0 : _c.complete) == null ? void 0 : _d.call(_c, success);
} else {
var fail = new PreviewImageErrorImpl(1101001, UniErrorPreviewImage);
(_f = (_e = option.longPressActions) == null ? void 0 : _e.fail) == null ? void 0 : _f.call(_e, fail);
(_h = (_g = option.longPressActions) == null ? void 0 : _g.complete) == null ? void 0 : _h.call(_g, fail);
}
}
});
uni.openDialogPage({
url: "uni:previewImage",
animationType: "fade-in",
success(_) {
var _a2, _b2;
let success = { errMsg: "ok", "errSubject": UniErrorPreviewImage };
(_a2 = option.success) == null ? void 0 : _a2.call(option, success);
(_b2 = option.complete) == null ? void 0 : _b2.call(option, success);
},
fail(_) {
var _a2, _b2;
let error = new PreviewImageErrorImpl(1101010, UniErrorPreviewImage);
(_a2 = option.fail) == null ? void 0 : _a2.call(option, error);
(_b2 = option.complete) == null ? void 0 : _b2.call(option, error);
}
});
}
function __closePreviewImage(option) {
var _a, _b;
uni.$emit("__CLOSEPREVIEWIMAGE", null);
let callback = {
errMsg: "ok"
};
(_a = option.success) == null ? void 0 : _a.call(option, callback);
(_b = option.complete) == null ? void 0 : _b.call(option, callback);
}
const previewImage$1 = (option) => {
__previewImage(option);
};
const closePreviewImage$1 = (option) => {
__closePreviewImage(option);
};
function mergeComponentStyles(page, components) {
const styles = isArray(page.styles) ? [...page.styles] : [];
components.forEach((component) => {
if (isArray(component.styles)) {
styles.push(...component.styles);
}
});
page.styles = styles;
}
const registerPreviewImageOnce = /* @__PURE__ */ once(() => {
mergeComponentStyles(
UniPreviewImagePage,
[UniPreviewImageNonVapor, UniPreviewImageItem]
);
registerSystemRoute("uni:previewImage", UniPreviewImagePage);
});
const closePreviewImage = () => {
registerPreviewImageOnce();
closePreviewImage$1();
};
const previewImage = /* @__PURE__ */ defineAsyncApi(
API_PREVIEW_IMAGE,
(args, { resolve, reject }) => {
registerPreviewImageOnce();
previewImage$1(
/* @__PURE__ */ extend(
{
success: (res) => {
resolve(res);
},
fail: (err) => {
reject(err);
}
},
args
)
);
}
);
const t0$1 = template("<div uni-view class=back-circle>", 1);
const _sfc_main$1 = /* @__PURE__ */ defineVaporComponent({
__name: "uni-back-arrow-circle",
props: {
autoBack: { type: Boolean, default: false }
},
emits: ["click"],
setup(__props, { emit: __emit }) {
const props2 = __props;
const emit2 = __emit;
const handleClick = () => {
emit2("click");
if (props2.autoBack) {
uni.navigateBack({});
}
};
const n0 = t0$1();
on$1(n0, "click", handleClick);
return n0;
}
});
const _style_0$1 = "\n.back-circle {\n width: 28px;\n height: 28px;\n border-radius: 14px;\n background-color: rgba(220, 220, 220, 0.3);\n justify-content: center;\n align-items: center;\n margin: 6px;\n padding-left: 4px;\n}\n\n /* 通过根节点上的 CSS 变量定制箭头颜色和线宽。 */\n.back-circle::after,\n\n .back-arrow {\n width: 12px;\n height: 12px;\n transform: rotate(45deg);\n border-left: var(--back-arrow-width, 2px) solid var(--back-arrow-color, #000000);\n border-bottom: var(--back-arrow-width, 2px) solid var(--back-arrow-color, #000000);\n}\n.back-circle::after {\n content: '';\n box-sizing: border-box;\n}\n@media (prefers-color-scheme: dark) {\n.back-circle {\n background-color: rgba(80, 80, 80, 0.45);\n}\n.back-circle::after,\n\n .back-arrow {\n border-left-color: var(--back-arrow-color, #ffffff);\n border-bottom-color: var(--back-arrow-color, #ffffff);\n}\n}\n";
const UniBackArrowCircle = /* @__PURE__ */ _export_sfc(_sfc_main$1, [["styles", [_style_0$1]]]);
const targetPath = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAAAXNSR0IArs4c6QAABGtJREFUeF7tm0tPFEEQx7uHd8DAXsTEg8sNSSBixOgBWKImCx8Aglx2P4EeuQE3bsZPsMsBkS/AYoxhgYMmGB9EAzf2YoSLQJDIc1prZ5fXzky/agYSexJCNlMz0/Xr6n9V9/RQEuKxGY9FiWUnLEJvMWZHnUfTKCEsR6mVg1+2TScis9lsWM2iQT+o6DRlZETiWTlKaTYMGIEBAMcpPU4RQmMSjpeYUkrTQYIIBMBmX9eoZI9zGTFKxiIzC6NcQ0kDVABYve7jQ44xqycym83rBcaBBsBx3p4jhBTEDaN5rvdAhYAGYKu3c053vEsgyzVkFpok7D1NUQCE7LyTPClN18/MJ3UhaANQFbzKJ70nbbc3fhJ7Yz3/J3NgCKM2gK3eLibaaHC66mmCWI03XC85Wv5MDt+9IfBfEIa2HmgB2O7rTjHGEjwA5W138o6Xt7XzTPPnAcCfF+NCEHSHgjKAguqv8TwC52vHX/LMXM8DhIO3Gd61EAVJ1fJZA0BnglKa8mudjvPF++4kB7iRoKMFygBElP9aatpzvPO6tXgetGB3+BkHAss2ZBZ7RO951k4DgL/4VQ8lSdUQVx6E2rw/mSZ7k77BplwXKAHYjPPDv35mXsg5ESMQxd3h576mhRJZehodCABIcxD+mAdPCxhjycjsYlr2mWoAOLM9zPAvOsTLCKpCqASAl/+DAMDTAdV6QAkAr/y9DAChRsCVBBCqBnCyAEYBdFHMoBY4Wv7iqXHhiqCz+OFbBmMUQWeLIcgCfgdjVpPKSpGSBkBDeLNATB3gCSC0pyGzoOSL0kUOAP8VIKgFYBLkNfUVzddQCvN6XzUDQBuUAWzGY7HCGqCnLxhRwBv78HDVKlALgEgUgI0OBF7x45BXnwhpAxCZExQhVDyOSw0HkZ53el+tBC6GrfIQgBvIvAeA1FjxKJ5fFfLTBVgA2X+V5q4BYPS+dgScQvBPiRdFAmCUt7YTer3x5NTxt68ya4FO8CumvrPt0YqA4o1Eh4Ko8ovY6QgfOoB8JATwPtALhO64DwRAWBAwnUfRgIu9VBgOsBcA+x2h1uqvVzShaEApBGcnCN4rcr1c76cpgQA4FcdY1LLYiMjLE7dGFjZHjKlMckSENJAh4Pbg/DYZchyzLKubAyMH+4UYpfNBbIZwhSxKCtPOfUktuDC/tCHg9WA3ADozOp3OCVQDDAAPAiYCXF6rmyGAtOVFVg+MBsgSw7A3GmA0oHRvkRFBI4I4Gx9lNcpkAVliGPYmC5gsYLJAyRZbkwZNGjRpEOUDCNksZeoAWWIY9v91HTD1oDl6t7b+fWNl1bnPRjYO9tc/7W4/HPywivZJnEhnhT4EXne0pFrr6hI3q6vPte/H3h75/nsn27+0orTtXcTZK/FeYLrj9lpNWVm0xrLOtefX4SH8zg0sraB8DicKJPQImL7fMvpvX4vrh9SUsGT/0qr0jm9RZ69EBEAjpu41x8ooHWGFN8iM0Cxj9sTgx1Xp/f46zsO1fwF2PaBfXH1iLwAAAABJRU5ErkJggg==";
const t0 = template('<div uni-view data-v-212d40c7 class=uni-open-location><div uni-view data-v-212d40c7 class=uni-open-location-map-box><!><div uni-view data-v-212d40c7><span uni-text data-v-212d40c7> </div></div><div uni-view data-v-212d40c7 class=uni-open-location-nav><div uni-view data-v-212d40c7></div></div><div uni-view data-v-212d40c7><div uni-view data-v-212d40c7 class=uni-open-location-address><span uni-text data-v-212d40c7> </span><span uni-text data-v-212d40c7> </div><div uni-view data-v-212d40c7 class=uni-open-location-footer-icon-btns><div uni-view data-v-212d40c7 class=uni-open-location-footer-icon-btns-item><div uni-view data-v-212d40c7><span uni-text data-v-212d40c7 class="uni-open-location-icons uni-open-location-navigation"> </div><span uni-text data-v-212d40c7> ', 1);
const _sfc_main = /* @__PURE__ */ defineVaporComponent({
__name: "openLocation",
setup(__props) {
const languageData = {
en: {
navigation: "navigation"
},
"zh-Hans": {
navigation: "导航"
},
"zh-Hant": {
navigation: "導航"
}
};
const currentInstance = getCurrentInstance().proxy;
const uniPage = currentInstance.$page;
const id1 = `UniMap1_${(Math.random() * 1e6).toString(36)}`;
const readyEventName = ref("");
const optionsEventName = ref("");
const successEventName = ref("");
const failEventName = ref("");
const openLocationOptions = ref({
latitude: 0,
longitude: 0,
scale: 18,
name: "",
address: ""
});
const safeArea = ref({
top: 0,
bottom: 0,
left: 0,
right: 0
});
const icon = ref({
position: "",
navigation: ""
});
const language = ref("zh-Hans");
const isLandscape2 = ref(false);
const theme = ref("light");
const mapId = ref(id1);
const latitude = ref(0);
const longitude = ref(0);
const markers = ref([]);
const languageCom = computed(() => {
const textInfo = languageData[language.value] != null ? languageData[language.value] : languageData["zh-Hans"];
return textInfo;
});
const darkClassCom = computed(() => {
return theme.value == "dark" ? "uni-open-location-dark" : "uni-open-location-light";
});
const landscapeClassCom = computed(() => {
return isLandscape2.value ? "uni-open-location-landscape" : "";
});
const initPageOptions = (options) => {
readyEventName.value = options["readyEventName"];
optionsEventName.value = options["optionsEventName"];
successEventName.value = options["successEventName"];
failEventName.value = options["failEventName"];
uni.$on(optionsEventName.value, (data) => {
console.log("data: ", JSON.stringify(data));
if (data["latitude"] != null) {
openLocationOptions.value.latitude = data["latitude"];
latitude.value = openLocationOptions.value.latitude;
}
if (data["longitude"] != null) {
openLocationOptions.value.longitude = data["longitude"];
longitude.value = openLocationOptions.value.longitude;
}
if (data["scale"] != null) {
openLocationOptions.value.scale = data["scale"];
}
if (data["name"] != null) {
openLocationOptions.value.name = data["name"];
}
if (data["address"] != null) {
openLocationOptions.value.address = data["address"];
}
setTimeout(() => {
markers.value = [
{
id: 1,
latitude: openLocationOptions.value.latitude,
longitude: openLocationOptions.value.longitude,
iconPath: targetPath,
width: 50,
height: 50
}
];
}, 300);
uni.$emit(successEventName.value, {});
});
uni.$emit(readyEventName.value, {});
};
const getSystemInfo2 = () => {
const info = uni.getWindowInfo();
safeArea.value.top = info.safeAreaInsets.top;
safeArea.value.bottom = info.safeAreaInsets.bottom;
safeArea.value.left = info.safeAreaInsets.left;
safeArea.value.right = info.safeAreaInsets.right;
const systemInfo = uni.getSystemInfoSync();
const appLanguage = systemInfo.appLanguage;
language.value = appLanguage;
const osTheme = systemInfo.osTheme;
const appTheme = systemInfo.appTheme;
if (appTheme != null && appTheme != "auto") {
theme.value = appTheme;
} else if (osTheme != null) {
theme.value = osTheme;
}
isLandscape2.value = systemInfo.deviceOrientation == "landscape";
const hostTheme = systemInfo.hostTheme;
if (hostTheme != null) {
theme.value = hostTheme;
}
const locale = uni.getLocale();
language.value = locale;
uni.onLocaleChange((res) => {
if (res.locale) {
language.value = res.locale;
}
});
uni.onThemeChange((res) => {
theme.value = res.theme;
});
};
const closeDialogPage2 = () => {
uni.closeDialogPage({
dialogPage: uniPage
});
};
const back = () => {
closeDialogPage2();
};
const getMapContext = () => {
return uni.createMapContext(mapId.value, currentInstance);
};
const moveToLocation = () => {
const mapContext = getMapContext();
if (mapContext != null) {
mapContext.moveToLocation({});
}
};
const mapReset = () => {
moveToLocation();
};
const navigation = () => {
uni.getAppBaseInfo();
const src = "webapp.baidu.openAPIdemo";
const list2 = ["腾讯地图", "高德地图", "百度地图"];
uni.showActionSheet({
itemList: list2,
success: (res) => {
let index2 = res.tapIndex;
if (index2 >= 0) {
let item = list2[index2];
try {
let url = "";
if (item == "腾讯地图") {
url = `https://apis.map.qq.com/uri/v1/marker?marker=coord:${openLocationOptions.value.latitude},${openLocationOptions.value.longitude};title:${openLocationOptions.value.name};addr:${openLocationOptions.value.address}&referer=1`;
} else if (item == "高德地图") {
url = `https://uri.amap.com/navigation?to=${openLocationOptions.value.longitude},${openLocationOptions.value.latitude},${openLocationOptions.value.name},${openLocationOptions.value.address}&mode=car&policy=0&src=mypage&coordinate=gaode&callnative=1`;
} else if (item == "百度地图") {
url = `https://api.map.baidu.com/marker?coord_type=gcj02&location=${openLocationOptions.value.latitude},${openLocationOptions.value.longitude}&title=${openLocationOptions.value.name}&content=${openLocationOptions.value.address}&output=html&src=${src}`;
} else if (item == "苹果地图") {
} else if (item == "华为地图") {
}
if (url != "") {
window.open(url);
}
} catch (err) {
console.error(err);
}
}
}
});
};
onLoad((options) => {
initPageOptions(options);
getSystemInfo2();
});
onUnload(() => {
uni.$off(optionsEventName.value, null);
uni.$off(readyEventName.value, null);
uni.$off(successEventName.value, null);
uni.$off(failEventName.value, null);
});
onResize(() => {
const systemInfo = uni.getSystemInfoSync();
isLandscape2.value = systemInfo.deviceOrientation == "landscape";
});
initUniPageHooks();
const n15 = t0();
const n4 = child(n15);
const n3 = child(n4);
const n2 = next(n3);
const n1 = child(n2);
const n7 = next(n4);
const n6 = child(n7);
const n14 = next(n7);
let p0 = child(n14);
const n8 = child(p0);
const n9 = next(n8);
const n13 = child(p0 = next(p0));
const n11 = child(n13);
const n10 = child(n11);
const n12 = next(n11);
setInsertionState(n4, n3);
withComponentId("777d2cb6", () => createComponent$1(__syscom_0, {
class: "uni-open-location-map",
id: () => unref(mapId),
latitude: () => unref(latitude),
longitude: () => unref(longitude),
scale: () => unref(openLocationOptions).scale,
markers: () => unref(markers),
"layer-style": () => unref(theme) == "dark" ? "2" : "1",
"show-compass": false,
"enable-zoom": true,
"enable-scroll": true,
"enable-rotate": false,
"enable-poi": true,
"show-location": true
}));
const x1 = txt(n1);
on$1(n2, "click", mapReset);
renderEffect(() => {
const _safeArea = unref(safeArea);
const _safeArea_top = _safeArea.top;
const __darkClassCom = [unref(darkClassCom)];
setClass(n2, ["uni-open-location-map-reset", __darkClassCom]);
setClass(n1, ["uni-open-location-icons uni-open-location-map-reset-icon", __darkClassCom]);
setText(x1, normalizeUniText(toDisplayString(unref(icon).position)));
setStyle(n7, "height:" + (60 + _safeArea_top) + "px;");
setClass(n6, ["uni-open-location-nav-btn uni-open-location-nav-back-btn", [unref(landscapeClassCom)]]);
setStyle(n6, _safeArea_top > 0 ? "top: " + _safeArea_top + "px;" : "");
});
setInsertionState(n6);
withComponentId("782862e0", () => createComponent$1(UniBackArrowCircle, {
class: () => ["uni-open-location-back-circle", [unref(darkClassCom)]],
"auto-back": false,
onClick: () => back
}));
const x8 = txt(n8);
const x9 = txt(n9);
const x10 = txt(n10);
const x12 = txt(n12);
on$1(n13, "click", navigation);
renderEffect(() => {
const _openLocationOptions = unref(openLocationOptions);
const __darkClassCom = [unref(darkClassCom)];
setClass(n14, ["uni-open-location-footer", __darkClassCom]);
setClass(n8, ["uni-open-location-name-text", __darkClassCom]);
setText(x8, normalizeUniText(toDisplayString(_openLocationOptions.name)));
setClass(n9, ["uni-open-location-address-text", __darkClassCom]);
setText(x9, normalizeUniText(toDisplayString(_openLocationOptions.address)));
setClass(n11, ["uni-open-location-footer-icon-box", __darkClassCom]);
setText(x10, normalizeUniText(toDisplayString(unref(icon).navigation)));
setClass(n12, ["uni-open-location-footer-btn-text", __darkClassCom]);
setText(x12, normalizeUniText(toDisplayString(unref(languageCom)["navigation"])));
});
return n15;
}
});
const _style_0 = "\n@font-face {\n font-family: UniOpenLocationFontFamily;\n \n\n src: url('data:font/woff2;base64,d09GMgABAAAAAAOIAAsAAAAACFwAAAM8AAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHFQGYACDBgqCZIJlATYCJAMMCwgABCAFhjMHOxuSBxEVnDPIfhy4sdOwnpu/XCQX6p+Dh3+9r/uQzJ9kYYxdEdgKdrWnlztI1VYMAN93akFQAGXB0t7c9LK+HdVDfoq6/rif/Ot8oLt7tnb7q6CgqKRqsPmA51Fls4lOkwYkU1Cv3gUoo65BABYuBCEjoqKTGVZd0FzLJDRWvYA0XlRXlBXg0JTolniBA4GJTtWIDRggV8o7wPrw8eIrbsIBEkNhrRJfGlnMhQ8hH5JU//9+UM/w6xDQ7hIwAAUs2Zha5LZr0lGxZwkKq06mWbiJRiAntf//H/J0hbnlP54EYWLFDgFgAZXKi+K7NAj4kMSlcq5fC6YWQwtwjhFjxgiU9vBw7qovyOi6l2xz0r/l2DYhHqRyWqu27d5u2w/TOMXA9tVb4X5KrL19684tltXIB8l+yCr+FALO5yRHjvL43QtXnRo4vfpk/wnvt/wO9F/R44//zFKjyifbKyPDK8u72nS3f4R8t92rzGzvDC+vDO9so8rD/qle2B5GtXcWwJLtU2V4WD/HUj2rjSyf1j5ZRrX7gR/6p122y+p4A2uXkesatzw2dnmcS6650/4+9oe1M8eMd4lZ7hLrEmfk7iCmnUaOS1kS47XMMXbY/0Ke2ztyjbjm6ctjXOPbI8bdWXx38fPFz8jH6qn6FPC/X6MGfth3WLXr6fH/4QG/HLYG4KPj8p1QgOnAcScaAb9Hng3W1LoVlK7juUkIQNFwly4JWLYK/kciwCheDFeMhl0gmJjjK5A4sQQUE3FHNBENBjYlYDKRerBYzMrZNqM5j0JoZ2Ae1wkI3PgOkmFiOijcxFJEE3lgME5slJh1xHGwSBWPl7OZJ33L94rRsNB0JZ4lO2e4/WZ+L8gvMo/Gku/Ik9ndmDhev+CPcdS2wipNf9Ct0Bh1ddvuv0eGrqP9dvK9mSOnkojuhhiFisoBs9WrWdk1jau7ST1LqvaK0bDQdCWeJTufYr+T+L0gv8iMy7hNcQf83ndj4nj9gj/GUYeWGI79g26tzU1d3U4hu4e40+S8kMO3k+/NHDmVRLwTYhQq9Z0OmK1eB7jKrrFrOVRWX7Ui/cIGwMIaqoQUSmicikdZx+xDMXvuM7iqAA==') format('woff2');\n}\n.uni-open-location-icons {\n font-family: 'UniOpenLocationFontFamily';\n font-size: 16px;\n font-style: normal;\n}\n.uni-open-location {\n position: relative;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n background: #f8f8f8;\n z-index: 999;\n display: flex;\n flex-direction: column;\n}\n.uni-open-location-map-box {\n width: 100%;\n flex: 1;\n}\n.uni-open-location-map {\n width: 100%;\n height: 100%;\n}\n.uni-open-location-map-reset {\n position: absolute;\n left: 20px;\n bottom: 40px;\n width: 40px;\n height: 40px;\n box-sizing: border-box;\n background-color: #ffffff;\n border-radius: 20px;\n pointer-events: auto;\n box-shadow: 0px 0px 20px 2px rgba(0, 0, 0, 0.3);\n z-index: 9;\n display: flex;\n justify-content: center;\n align-items: center;\n}\n.uni-open-location-map-reset-icon {\n font-size: 26px;\n text-align: center;\n line-height: 40px;\n}\n.uni-open-location-nav {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 60px;\n background-color: rgba(0, 0, 0, 0);\n background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.3), rgba(0, 0, 0, 0));\n}\n.uni-open-location-nav-btn {\n position: absolute;\n top: 5px;\n left: 5px;\n width: 44px;\n height: 44px;\n display: flex;\n justify-content: center;\n align-items: center;\n}\n.uni-open-location-back-circle {\n --back-arrow-color: #cacbc6;\n --back-arrow-width: 2px;\n background-color: #ffffff;\n}\n.uni-open-location-footer {\n height: 150px;\n border-radius: 10px 10px 0px 0px;\n overflow: hidden;\n background-color: #ffffff;\n display: flex;\n flex-direction: row;\n align-items: center;\n justify-content: space-between;\n padding: 0px 20px;\n}\n.uni-open-location-address {\n display: flex;\n flex-direction: column;\n flex: 1;\n}\n.uni-open-location-name-text {\n font-size: 18px;\n font-weight: bold;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n.uni-open-location-address-text {\n font-size: 16px;\n margin-top: 10px;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n.uni-open-location-footer-icon-btns {\n width: 100px;\n display: flex;\n flex-direction: row;\n justify-content: flex-end;\n}\n.uni-open-location-footer-icon-btns-item {\n display: flex;\n flex-direction: column;\n align-items: center;\n}\n.uni-open-location-footer-icon-box {\n background-color: #f8f8f8;\n width: 40px;\n height: 40px;\n border-radius: 6px;\n display: flex;\n justify-content: center;\n align-items: center;\n margin-bottom: 6px;\n}\n.uni-open-location-navigation.uni-open-location-icons {\n color: #007aff;\n font-size: 24px;\n}\n.uni-open-location-footer-btn-text {\n font-size: 12px;\n text-align: center;\n}\n.uni-open-location-dark.uni-open-location-back-circle {\n --back-arrow-color: #000000;\n}\n.uni-open-location-dark.uni-open-location-map-reset {\n background-color: #111111;\n}\n.uni-open-location-dark.uni-open-location-map-reset-icon {\n color: #d1d1d1;\n}\n.uni-open-location-dark.uni-open-location-footer {\n background-color: #181818;\n}\n.uni-open-location-dark.uni-open-location-name-text {\n color: #fafafa;\n}\n.uni-open-location-dark.uni-open-location-address-text {\n color: #fafafa;\n}\n.uni-open-location-dark.uni-open-location-footer-icon-box {\n background-color: #393939;\n}\n.uni-open-location-dark.uni-open-location-footer-btn-text {\n color: #909090;\n}\n";
const UniOpenLocationPage = /* @__PURE__ */ _export_sfc(_sfc_main, [["styles", [_style_0]]]);
class OpenLocationSuccessImpl {
constructor(errMsg = "openLocation:ok") {
this.errMsg = errMsg;
}
}
const UniErrorSubject = "uni-openLocation";
const UniErrors = /* @__PURE__ */ new Map([
/**
* 框架内部错误
*/
[4, "internal error"]
]);
class OpenLocationFailImpl extends UniError {
constructor(errCode) {
super();
this.errSubject = UniErrorSubject;
this.errCode = errCode;
this.errMsg = UniErrors.get(errCode) ?? "";
}
}
const openLocation$1 = function(options) {
const uuid = `${Date.now()}${Math.floor(Math.random() * 1e7)}`;
const baseEventName = `uni_open_location_${uuid}`;
const readyEventName = `${baseEventName}_ready`;
const optionsEventName = `${baseEventName}_options`;
const successEventName = `${baseEventName}_success`;
const failEventName = `${baseEventName}_fail`;
uni.$on(readyEventName, () => {
uni.$emit(optionsEventName, JSON.parse(JSON.stringify(options)));
});
uni.$on(successEventName, () => {
var _a, _b;
const res = new OpenLocationSuccessImpl();
(_a = options.success) == null ? void 0 : _a.call(options, res);
(_b = options.complete) == null ? void 0 : _b.call(options, res);
});
uni.$on(failEventName, (errCode) => {
var _a, _b;
const res = new OpenLocationFailImpl(errCode);
(_a = options.fail) == null ? void 0 : _a.call(options, res);
(_b = options.complete) == null ? void 0 : _b.call(options, res);
});
uni.openDialogPage({
url: `uni:openLocation?readyEventName=${readyEventName}&optionsEventName=${optionsEventName}&successEventName=${successEventName}&failEventName=${failEventName}`,
triggerParentHide: true,
fail(err) {
var _a, _b;
const res = new OpenLocationFailImpl(4);
(_a = options.fail) == null ? void 0 : _a.call(options, res);
(_b = options.complete) == null ? void 0 : _b.call(options, res);
uni.$off(readyEventName);
uni.$off(successEventName);
uni.$off(failEventName);
}
});
};
const registerOpenLocationOnce = /* @__PURE__ */ once(() => {
registerSystemRoute("uni:openLocation", UniOpenLocationPage);
});
const openLocation = /* @__PURE__ */ defineAsyncApi(
API_OPEN_LOCATION,
(args, { resolve, reject }) => {
registerOpenLocationOnce();
openLocation$1(
extend({}, args, {
success: (res) => resolve(res),
fail: (err) => reject(err.errMsg, err)
})
);
},
OpenLocationProtocol,
OpenLocationOptions
);
const API_CREATE_WORKER = "createWorker";
const MESSAGE_EVENT = "__UNI_WEB_WORKER_MESSAGE";
const ERROR_EVENT = "__UNI_WEB_WORKER_ERROR";
let id = 0;
const createWorker = /* @__PURE__ */ defineSyncApi(
API_CREATE_WORKER,
(url) => {
const MESSAGE_EVENT_NAME = `${MESSAGE_EVENT}_${id}`;
const ERROR_EVENT_NAME = `${ERROR_EVENT}_${id}`;
id++;
const threadWorker = new Worker(
getRealPath(url.startsWith("/") ? url : "/" + url),
{
type: "module"
}
);
threadWorker.onmessage = (event) => {
$emit(MESSAGE_EVENT_NAME, event.data);
};
threadWorker.onmessageerror = (error) => {
$emit(ERROR_EVENT_NAME, error.data);
};
threadWorker.onerror = (error) => {
$emit(
ERROR_EVENT_NAME,
`${error.message} in ${error.filename}(${error.lineno}:${error.colno})`
);
};
class WorkerImpl {
constructor() {
this._threadWorker = threadWorker;
}
onMessage(listener2) {
$on(MESSAGE_EVENT_NAME, listener2);
}
onError(listener2) {
$on(ERROR_EVENT_NAME, listener2);
}
postMessage(message, options = null) {
this._threadWorker.postMessage(
message,
(options == null ? void 0 : options.transfer) ?? void 0
);
}
terminate() {
$off(MESSAGE_EVENT_NAME);
$off(ERROR_EVENT_NAME);
this._threadWorker.terminate();
}
}
return new WorkerImpl();
}
);
const uasmCache = /* @__PURE__ */ new Map();
function loadUasm(module) {
const descriptor = module;
if (!descriptor || typeof descriptor.id !== "string" || typeof descriptor.loader !== "function") {
return Promise.reject(new Error("uni.loadUasm 参数未经过编译处理"));
}
let promise = uasmCache.get(descriptor.id);
if (!promise) {
promise = descriptor.loader().then((loaded) => {
if (typeof loaded.default !== "function") {
throw new Error(`uasm 插件[${descriptor.id}]的默认导出必须是函数`);
}
return loaded.default();
});
uasmCache.set(descriptor.id, promise);
promise.catch(() => {
if (uasmCache.get(descriptor.id) === promise) {
uasmCache.delete(descriptor.id);
}
});
}
return promise;
}
window.UniResizeObserver = window.ResizeObserver;
const api = /* @__PURE__ */ Object.defineProperty({
__proto__: null,
$emit,
$off,
$on,
$once,
__f__,
addInterceptor,
addPhoneContact,
arrayBufferToBase64,
base64ToArrayBuffer,
canIUse,
canvasGetImageData,
canvasPutImageData,
canvasToTempFilePath,
chooseFile,
chooseImage,
chooseLocation,
chooseVideo,
clearStorage,
clearStorageSync,
closeDialogPage,
closePreviewImage,
closeSocket,
connectSocket,
createAnimation,
createCameraContext,
createCanvasContext,
createCanvasContextAsync,
createEditorContextAsync,
createInnerAudioContext,
createIntersectionObserver,
createLivePlayerContext,
createMapContext,
createMediaQueryObserver,
createSelectorQuery,
createVideoContext,
createWorker,
cssBackdropFilter,
cssConstant,
cssEnv,
cssVar,
downloadFile,
getAppBaseInfo,
getClipboardData,
getDeviceInfo,
getElementById,
getEnterOptionsSync,
getFacialRecognitionMetaInfo,
getFileInfo,
getImageInfo,
getLaunchOptionsSync,
getLeftWindowStyle,
getLocale,
getLocation,
getNetworkType,
getProvider,
getPushClientId,
getRecorderManager,
getRightWindowStyle,
getSavedFileInfo,
getSavedFileList,
getScreenBrightness,
getSelectedTextRange,
getStorage,
getStorageInfo,
getStorageInfoSync,
getStorageSync,
getSystemInfo,
getSystemInfoSync,
getTabBarPageId,
getTopWindowStyle,
getVideoInfo,
getWindowInfo,
hideActionSheet,
hideKeyboard,
hideLeftWindow,
hideLoading,
hideModal,
hideNavigationBarLoading,
hideRightWindow,
hideTabBar,
hideTabBarRedDot,
hideToast,
hideTopWindow,
interceptors,
invokePushCallback,
loadFontFace,
loadUasm,
login,
makePhoneCall,
navigateBack,
navigateTo,
offAccelerometerChange,
offAppHide,
offAppRoute,
offAppShow,
offBeforeAppRoute,
offCompassChange,
offError,
offHostThemeChange,
offLocationChange,
offLocationChangeError,
offNetworkStatusChange,
offPageNotFound,
offPushMessage,
offThemeChange,
offUnhandledRejection,
offWindowResize,
onAccelerometerChange,
onAppHide,
onAppRoute,
onAppShow,
onBeforeAppRoute,
onCompassChange,
onCreateVueApp,
onError,
onGyroscopeChange,
onHostThemeChange,
onLocaleChange,
onLocationChange,
onLocationChangeError,
onMemoryWarning,
onNetworkStatusChange,
onPageNotFound,
onPushMessage,
onSocketClose,
onSocketError,
onSocketMessage,
onSocketOpen,
onTabBarMidButtonTap,
onThemeChange,
onUnhandledRejection,
onUserCaptureScreen,
onWindowResize,
openDialogPage,
openDocument,
openLocation,
pageScrollTo,
preloadPage,
previewImage,
reLaunch,
redirectTo,
removeAllPages,
removeInterceptor,
removeLastPage,
removeNonTabBarPages,
removeSavedFile,
removeStorage,
removeStorageSync,
removeTabBarBadge,
request,
rewriteRoute,
rpx2px: upx2px,
saveFile,
saveImageToPhotosAlbum,
saveVideoToPhotosAlbum,
scanCode,
sendSocketMessage,
setClipboardData,
setKeepScreenOn,
setLeftWindowStyle,
setLocale,
setNavigationBarColor,
setNavigationBarTitle,
setPageMeta,
setRightWindowStyle,
setScreenBrightness,
setStorage,
setStorageSync,
setTabBarBadge,
setTabBarItem,
setTabBarStyle,
setTopWindowStyle,
showActionSheet,
showLeftWindow,
showLoading,
showModal,
showNavigationBarLoading,
showRightWindow,
showTabBar,
showTabBarRedDot,
showToast,
showTopWindow,
startAccelerometer,
startCompass,
startGyroscope,
startLocationUpdate,
startPullDownRefresh,
stopAccelerometer,
stopCompass,
stopGyroscope,
stopLocationUpdate,
stopPullDownRefresh,
switchTab,
uploadFile,
upx2px,
vibrateLong,
vibrateShort
}, Symbol.toStringTag, { value: "Module" });
const uni$1 = api;
const UniServiceJSBridge$1 = /* @__PURE__ */ extend(ServiceJSBridge, {
publishHandler(event, args, pageId) {
UniViewJSBridge.subscribeHandler(event, args, pageId);
}
});
{
installWebVaporElements(window);
}
export {
$emit,
$off,
$on,
$once,
indexVapor as Ad,
index$5 as AdContentPage,
index$4 as AdDraw,
_sfc_main$D as AsyncErrorComponent,
_sfc_main$E as AsyncLoadingComponent,
_sfc_main$x as Button,
index$3 as Camera,
indexVapor$8 as Canvas,
_sfc_main$w as Checkbox,
_sfc_main$v as CheckboxGroup,
indexVapor$7 as Editor,
_sfc_main$u as FlowItem,
_sfc_main$t as Form,
indexVapor$6 as Icon,
__syscom_0$2 as Input,
_sfc_main$s as Label,
_sfc_main$F as LayoutComponent,
_sfc_main$r as ListItem,
_sfc_main$q as ListView,
index$2 as LivePlayer,
index$1 as LivePusher,
_sfc_main$C as Loading,
__syscom_0 as Map,
_sfc_main$p as MatchMedia,
indexVapor$5 as MovableArea,
indexVapor$4 as MovableView,
_sfc_main$o as Navigator,
_sfc_main$y as PageComponent,
_sfc_main$n as PageContainer,
_sfc_main$m as Picker,
_sfc_main$l as PickerView,
_sfc_main$k as PickerViewColumn,
_sfc_main$j as Progress,
_sfc_main$i as Radio,
_sfc_main$h as RadioGroup,
ResizeSensor,
indexVapor$3 as RichText,
__syscom_1 as ScrollView,
_sfc_main$g as Slider,
_sfc_main$f as StickyHeader,
_sfc_main$e as StickySection,
_sfc_main$d as Swiper,
_sfc_main$c as SwiperItem,
_sfc_main$b as Switch,
__syscom_0$1 as Textarea,
UTS2 as UTS,
UTSJSONObject2 as UTSJSONObject,
UTSValueIterable2 as UTSValueIterable,
UniButtonElement,
UniButtonElement as UniButtonElementImpl,
UniCanvasElement,
UniCanvasElement as UniCanvasElementImpl,
UniCheckboxElement,
UniCheckboxElement as UniCheckboxElementImpl,
UniCheckboxGroupElement,
UniCheckboxGroupElement as UniCheckboxGroupElementImpl,
UniEditorElement,
UniEditorElement as UniEditorElementImpl,
UniElement2 as UniElement,
UniElement2 as UniElementImpl,
UniError2 as UniError,
UniFormElement,
UniFormElement as UniFormElementImpl,
UniIconElement,
UniIconElement as UniIconElementImpl,
UniImageElement,
UniImageElement as UniImageElementImpl,
UniInputElement,
UniInputElement as UniInputElementImpl,
UniLabelElement,
UniLabelElement as UniLabelElementImpl,
UniLoadingElement,
UniLoadingElement as UniLoadingElementImpl,
UniMapElement,
UniMatchMediaElement,
UniMatchMediaElement as UniMatchMediaElementImpl,
UniMovableAreaElement,
UniMovableAreaElement as UniMovableAreaElementImpl,
UniMovableViewElement,
UniMovableViewElement as UniMovableViewElementImpl,
UniNavigatorElement,
UniNavigatorElement as UniNavigatorElementImpl,
UniPageContainerElement,
UniPageContainerElement as UniPageContainerElementImpl,
UniPickerElement,
UniPickerElement as UniPickerElementImpl,
UniPickerViewColumnElement,
UniPickerViewColumnElement as UniPickerViewColumnElementImpl,
UniPickerViewElement,
UniPickerViewElement as UniPickerViewElementImpl,
UniProgressElement,
UniProgressElement as UniProgressElementImpl,
UniRadioElement,
UniRadioElement as UniRadioElementImpl,
UniRadioGroupElement,
UniRadioGroupElement as UniRadioGroupElementImpl,
UniRichTextElement,
UniRichTextElement as UniRichTextElementImpl,
UniScrollViewElement,
UniScrollViewElement as UniScrollViewElementImpl,
UniServiceJSBridge$1 as UniServiceJSBridge,
UniSliderElement,
UniSliderElement as UniSliderElementImpl,
UniSwiperElement,
UniSwiperElement as UniSwiperElementImpl,
UniSwiperItemElement,
UniSwiperItemElement as UniSwiperItemElementImpl,
UniSwitchElement,
UniSwitchElement as UniSwitchElementImpl,
UniTextElement,
UniTextElement as UniTextElementImpl,
UniTextareaElement,
UniTextareaElement as UniTextareaElementImpl,
UniVideoElement,
UniViewElement,
UniViewElement as UniViewElementImpl,
UniViewJSBridge$1 as UniViewJSBridge,
UniWebViewElement,
indexVapor$2 as Video,
_sfc_main$a as Waterflow,
indexVapor$1 as WebView,
__f__,
addInterceptor,
addPhoneContact,
arrayBufferToBase64,
base64ToArrayBuffer,
canIUse,
canvasGetImageData,
canvasPutImageData,
canvasToTempFilePath,
chooseFile,
chooseImage,
chooseLocation,
chooseVideo,
clearStorage,
clearStorageSync,
closeDialogPage,
closePreviewImage,
closeSocket,
connectSocket,
createAnimation,
createCameraContext,
createCanvasContext,
createCanvasContextAsync,
createEditorContextAsync,
createInnerAudioContext,
createIntersectionObserver,
createLivePlayerContext,
createMapContext,
createMediaQueryObserver,
createSelectorQuery,
createVaporPageRouteComponent,
createVideoContext,
createWorker,
cssBackdropFilter,
cssConstant,
cssEnv,
cssVar,
downloadFile,
getApp$1 as getApp,
getAppBaseInfo,
getClipboardData,
getCurrentPages$1 as getCurrentPages,
getDeviceInfo,
getElementById,
getEnterOptionsSync,
getFacialRecognitionMetaInfo,
getFileInfo,
getImageInfo,
getLaunchOptionsSync,
getLeftWindowStyle,
getLocale,
getLocation,
getNetworkType,
getProvider,
getPushClientId,
getRealPath,
getRecorderManager,
getRightWindowStyle,
getSavedFileInfo,
getSavedFileList,
getScreenBrightness,
getSelectedTextRange,
getStorage,
getStorageInfo,
getStorageInfoSync,
getStorageSync,
getSystemInfo,
getSystemInfoSync,
getTabBarPageId,
getTopWindowStyle,
getVideoInfo,
getWindowInfo,
hideActionSheet,
hideKeyboard,
hideLeftWindow,
hideLoading,
hideModal,
hideNavigationBarLoading,
hideRightWindow,
hideTabBar,
hideTabBarRedDot,
hideToast,
hideTopWindow,
interceptors,
invokePushCallback,
loadFontFace,
loadUasm,
login,
makePhoneCall,
navigateBack,
navigateTo,
offAccelerometerChange,
offAppHide,
offAppRoute,
offAppShow,
offBeforeAppRoute,
offCompassChange,
offError,
offHostThemeChange,
offLocationChange,
offLocationChangeError,
offNetworkStatusChange,
offPageNotFound,
offPushMessage,
offThemeChange,
offUnhandledRejection,
offWindowResize,
onAccelerometerChange,
onAppHide,
onAppRoute,
onAppShow,
onBeforeAppRoute,
onCompassChange,
onCreateVueApp2 as onCreateVueApp,
onError,
onGyroscopeChange,
onHostThemeChange,
onLocaleChange,
onLocationChange,
onLocationChangeError,
onMemoryWarning,
onNetworkStatusChange,
onPageNotFound,
onPushMessage,
onSocketClose,
onSocketError,
onSocketMessage,
onSocketOpen,
onTabBarMidButtonTap,
onThemeChange,
onUnhandledRejection,
onUserCaptureScreen,
onWindowResize,
openDialogPage,
openDocument,
openLocation,
pageScrollTo,
index as plugin,
preloadPage,
previewImage,
reLaunch,
redirectTo,
removeAllPages,
removeInterceptor,
removeLastPage,
removeNonTabBarPages,
removeSavedFile,
removeStorage,
removeStorageSync,
removeTabBarBadge,
request,
rewriteRoute,
upx2px as rpx2px,
saveFile,
saveImageToPhotosAlbum,
saveVideoToPhotosAlbum,
scanCode,
sendSocketMessage,
setClipboardData,
setKeepScreenOn,
setLeftWindowStyle,
setLocale,
setNavigationBarColor,
setNavigationBarTitle,
setPageMeta,
setRightWindowStyle,
setScreenBrightness,
setStorage,
setStorageSync,
setTabBarBadge,
setTabBarItem,
setTabBarStyle,
setTopWindowStyle,
setupApp,
setupPage,
setupWindow,
showActionSheet,
showLeftWindow,
showLoading,
showModal,
showNavigationBarLoading,
showRightWindow,
showTabBar,
showTabBarRedDot,
showToast,
showTopWindow,
startAccelerometer,
startCompass,
startGyroscope,
startLocationUpdate,
startPullDownRefresh,
stopAccelerometer,
stopCompass,
stopGyroscope,
stopLocationUpdate,
stopPullDownRefresh,
switchTab,
uni$1 as uni,
uploadFile,
upx2px,
useI18n,
useTabBar,
vibrateLong,
vibrateShort
};