509 lines
16 KiB
Vue
509 lines
16 KiB
Vue
<script setup>
|
|
import {
|
|
ref,
|
|
onMounted,
|
|
onBeforeMount,
|
|
onBeforeUnmount,
|
|
onBeforeUpdate
|
|
} from 'vue';
|
|
import {
|
|
onLoad,
|
|
onLaunch,
|
|
onShow,
|
|
onError
|
|
} from '@dcloudio/uni-app';
|
|
import {
|
|
ShoproInit
|
|
} from './sheep';
|
|
|
|
const SCHEME_TAG = '[Scheme]';
|
|
const HOME_PATH = '/pages/index/index';
|
|
const SCHEME_PROTOCOL = 'yougou://';
|
|
|
|
const schemeState = {
|
|
lastScheme: '',
|
|
lastHandleAt: 0,
|
|
launching: false,
|
|
schemeHandledInLaunch: false,
|
|
};
|
|
|
|
const isSameSchemeDebounce = (scheme) => {
|
|
const now = Date.now();
|
|
const same = schemeState.lastScheme === scheme && now - schemeState.lastHandleAt < 800;
|
|
schemeState.lastScheme = scheme;
|
|
schemeState.lastHandleAt = now;
|
|
return same;
|
|
};
|
|
|
|
const parseSchemeQuery = (query = {}) => {
|
|
try {
|
|
const result = {};
|
|
Object.keys(query || {}).forEach((k) => {
|
|
const v = query[k];
|
|
if (v === undefined || v === null) return;
|
|
if (typeof v === 'string' && v.length > 512) {
|
|
result[k] = v.slice(0, 512);
|
|
return;
|
|
}
|
|
result[k] = v;
|
|
});
|
|
return result;
|
|
} catch (e) {
|
|
console.warn(SCHEME_TAG, 'parseSchemeQuery error', e);
|
|
return {};
|
|
}
|
|
};
|
|
|
|
const resolveTargetPath = (scheme = '', query = {}) => {
|
|
try {
|
|
const url = String(scheme || '').trim();
|
|
if (!url) return { path: HOME_PATH, query: parseSchemeQuery(query) };
|
|
const withoutProtocol = url.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//, '');
|
|
if (!withoutProtocol) return { path: HOME_PATH, query: parseSchemeQuery(query) };
|
|
const [pathRaw = '', queryRaw = ''] = withoutProtocol.split('?');
|
|
const cleanPath = pathRaw.replace(/^\/+/, '/').trim();
|
|
const path = cleanPath.startsWith('/pages/') ? cleanPath : HOME_PATH;
|
|
const merged = { ...parseSchemeQuery(query) };
|
|
if (queryRaw) {
|
|
queryRaw.split('&').forEach((pair) => {
|
|
const [k, v] = pair.split('=');
|
|
if (!k) return;
|
|
try { merged[decodeURIComponent(k)] = v === undefined ? '' : decodeURIComponent(v); } catch (_) {}
|
|
});
|
|
}
|
|
return { path, query: merged };
|
|
} catch (e) {
|
|
console.warn(SCHEME_TAG, 'resolveTargetPath error, fallback to home', e);
|
|
return { path: HOME_PATH, query: parseSchemeQuery(query) };
|
|
}
|
|
};
|
|
|
|
const buildUrl = (path, query) => {
|
|
try {
|
|
const q = query || {};
|
|
const keys = Object.keys(q).filter((k) => q[k] !== undefined && q[k] !== null && q[k] !== '');
|
|
if (!keys.length) return path;
|
|
const qs = keys
|
|
.map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(String(q[k]))}`)
|
|
.join('&');
|
|
return `${path}${path.includes('?') ? '&' : '?'}${qs}`;
|
|
} catch (e) {
|
|
return path;
|
|
}
|
|
};
|
|
|
|
const safeReLaunch = (path, query, source) => {
|
|
const finalUrl = buildUrl(path, query);
|
|
console.log(SCHEME_TAG, `${source} → reLaunch`, finalUrl);
|
|
try {
|
|
uni.reLaunch({
|
|
url: finalUrl,
|
|
fail: (err) => {
|
|
console.warn(SCHEME_TAG, 'reLaunch fail, fallback to switchTab/home', err);
|
|
if (path === HOME_PATH) {
|
|
try {
|
|
uni.switchTab({
|
|
url: HOME_PATH,
|
|
fail: (err2) => {
|
|
console.warn(SCHEME_TAG, 'switchTab also fail', err2);
|
|
uni.navigateTo({ url: HOME_PATH, fail: () => {} });
|
|
},
|
|
});
|
|
} catch (e) {
|
|
console.warn(SCHEME_TAG, 'switchTab catch', e);
|
|
}
|
|
} else {
|
|
uni.navigateTo({ url: finalUrl, fail: () => uni.reLaunch({ url: HOME_PATH }) });
|
|
}
|
|
},
|
|
});
|
|
} catch (e) {
|
|
console.error(SCHEME_TAG, 'safeReLaunch catch error', e);
|
|
try { uni.reLaunch({ url: HOME_PATH }); } catch (_) {}
|
|
}
|
|
};
|
|
|
|
const isSchemeTrigger = (options) => {
|
|
if (!options) return false;
|
|
if (String(options?.path || '').toLowerCase() === 'scheme') return true;
|
|
const scheme = String(options?.scheme || options?.argv?.scheme || '');
|
|
if (scheme.startsWith(SCHEME_PROTOCOL)) return true;
|
|
const referrer = String(options?.referrer || '');
|
|
if (referrer.startsWith(SCHEME_PROTOCOL)) return true;
|
|
return false;
|
|
};
|
|
|
|
const handleSchemeByOptions = (options, source) => {
|
|
const scheme = String(options?.scheme || options?.argv?.scheme || options?.referrer || '');
|
|
if (isSameSchemeDebounce(scheme)) {
|
|
console.log(SCHEME_TAG, `${source} 防抖跳过`, scheme);
|
|
return;
|
|
}
|
|
console.log(SCHEME_TAG, `${source} 触发`, options);
|
|
const query = { ...(options?.query || {}), ...(options?.argv?.query || {}) };
|
|
const { path, query: resolvedQuery } = resolveTargetPath(scheme, query);
|
|
safeReLaunch(path, resolvedQuery, source);
|
|
};
|
|
|
|
let schemeEventListenerRegistered = false;
|
|
const registerSchemeEventListener = () => {
|
|
if (schemeEventListenerRegistered) return;
|
|
if (typeof plus === 'undefined' || !plus?.globalEvent) return;
|
|
try {
|
|
plus.globalEvent.addEventListener('newintent', (e) => {
|
|
const intent = e?.intent || e;
|
|
let scheme = '';
|
|
let query = {};
|
|
try {
|
|
if (typeof plus?.runtime?.arguments === 'function' || typeof plus?.runtime?.arguments !== 'undefined') {
|
|
const args = plus.runtime.arguments;
|
|
if (args && typeof args === 'object') {
|
|
scheme = String(args.scheme || args.url || args.action || '');
|
|
query = args.query || {};
|
|
} else if (typeof args === 'string') {
|
|
scheme = args;
|
|
}
|
|
}
|
|
if (!scheme && intent?.data) {
|
|
const data = String(intent.data || '');
|
|
scheme = data;
|
|
const i = data.indexOf('?');
|
|
if (i > -1) {
|
|
data.slice(i + 1).split('&').forEach((pair) => {
|
|
const [k, v] = pair.split('=');
|
|
if (!k) return;
|
|
try { query[decodeURIComponent(k)] = v === undefined ? '' : decodeURIComponent(v); } catch (_) {}
|
|
});
|
|
}
|
|
}
|
|
if (!scheme && intent?.extras) {
|
|
scheme = String(intent.extras.scheme || intent.extras.url || intent.extras['android.intent.extra.TEXT'] || '');
|
|
}
|
|
} catch (err) {
|
|
console.warn(SCHEME_TAG, 'newintent parse error', err);
|
|
}
|
|
if (!scheme) return;
|
|
if (isSameSchemeDebounce(scheme)) {
|
|
console.log(SCHEME_TAG, 'newintent 防抖跳过', scheme);
|
|
return;
|
|
}
|
|
console.log(SCHEME_TAG, 'newintent(plus.globalEvent) 触发', { scheme, query, intent });
|
|
const { path, query: resolvedQuery } = resolveTargetPath(scheme, query);
|
|
safeReLaunch(path, resolvedQuery, 'newintent后台唤起');
|
|
});
|
|
schemeEventListenerRegistered = true;
|
|
console.log(SCHEME_TAG, 'plus.globalEvent newintent 监听已注册');
|
|
} catch (e) {
|
|
console.warn(SCHEME_TAG, 'registerSchemeEventListener catch', e);
|
|
}
|
|
};
|
|
|
|
const registerSchemeRuntimeArguments = () => {
|
|
if (typeof plus === 'undefined' || !plus?.runtime) return;
|
|
try {
|
|
const args = plus.runtime.arguments;
|
|
let scheme = '';
|
|
let query = {};
|
|
if (args && typeof args === 'object') {
|
|
scheme = String(args.scheme || args.url || '');
|
|
query = args.query || {};
|
|
} else if (typeof args === 'string' && args) {
|
|
scheme = args;
|
|
}
|
|
if (!scheme) return;
|
|
if (isSameSchemeDebounce(scheme)) {
|
|
console.log(SCHEME_TAG, 'runtime.arguments 防抖跳过', scheme);
|
|
return;
|
|
}
|
|
console.log(SCHEME_TAG, 'plus.runtime.arguments 读取', { scheme, query });
|
|
const { path, query: resolvedQuery } = resolveTargetPath(scheme, query);
|
|
safeReLaunch(path, resolvedQuery, 'plus.runtime.arguments冷启动');
|
|
} catch (e) {
|
|
console.warn(SCHEME_TAG, 'registerSchemeRuntimeArguments catch', e);
|
|
}
|
|
};
|
|
|
|
let globalData = ref({
|
|
statusBarHeight: 0, // 状态导航栏高度
|
|
navHeight: 0, // 总体高度
|
|
navigationBarHeight: 0, // 导航栏高度(标题栏高度)
|
|
windowHeight: 0,
|
|
});
|
|
const socket = () => {
|
|
let url = 'ws://192.168.101.229:48080/aishop/ws';
|
|
let socketTask = uni.connectSocket({
|
|
url: url,
|
|
success(res) {
|
|
console.log('连接成功', res);
|
|
},
|
|
fail() {},
|
|
});
|
|
socketTask.onOpen((res) => {
|
|
console.log('WebSocket 连接已打开');
|
|
});
|
|
socketTask.onMessage((res) => {
|
|
console.log('收到服务器消息', res);
|
|
});
|
|
socketTask.onClose((res) => {
|
|
console.log('WebSocket 已关闭!');
|
|
});
|
|
socketTask.onError((res) => {
|
|
console.log('WebSocket 错误!', res);
|
|
});
|
|
};
|
|
|
|
const parseTitleToProgress = (title) => {
|
|
const text = String(title || '');
|
|
const percentMatch = text.match(/(\d{1,3})%/);
|
|
const percent = percentMatch ? Number(percentMatch[1]) : null;
|
|
const cleanText = text.replace(/\s*\d{1,3}%\s*$/, '').trim() || text;
|
|
const normalizedPercent =
|
|
percent !== null && Number.isFinite(percent) ?
|
|
Math.max(0, Math.min(100, percent)) :
|
|
text.includes('安装') && !text.includes('下载') ? 100 : null;
|
|
return {
|
|
percent: normalizedPercent,
|
|
text: cleanText
|
|
};
|
|
};
|
|
|
|
const shouldUseUpdateOverlay = (title) => {
|
|
const text = String(title || '');
|
|
if (!text) return false;
|
|
if (/下载|安装|更新/.test(text) && (/%/.test(text) || /下载中|安装中|正在下载|正在安装|正在更新/.test(text))) {
|
|
return true;
|
|
}
|
|
return false;
|
|
};
|
|
|
|
const ensureLoadingPatched = () => {
|
|
if (!uni || uni.__updateLoadingPatched) return;
|
|
const originalShowLoading = uni.showLoading;
|
|
const originalHideLoading = uni.hideLoading;
|
|
if (typeof originalShowLoading !== 'function' || typeof originalHideLoading !== 'function') {
|
|
uni.__updateLoadingPatched = true;
|
|
return;
|
|
}
|
|
|
|
const HOT_UPDATE_PROGRESS_EVENT = '__hot_update_progress__';
|
|
const canEmit = () => typeof uni !== 'undefined' && typeof uni.$emit === 'function';
|
|
const emitProgress = (payload) => {
|
|
if (!canEmit()) return false;
|
|
uni.__hotUpdatePendingProgress = payload;
|
|
uni.$emit(HOT_UPDATE_PROGRESS_EVENT, payload);
|
|
return true;
|
|
};
|
|
|
|
if (!uni.__updateToastPatched && typeof uni.showToast === 'function') {
|
|
const originalShowToast = uni.showToast;
|
|
uni.showToast = (options = {}) => {
|
|
const title =
|
|
typeof options === 'string' ? options : (options?.title ?? '');
|
|
if ((uni.__hotUpdateInFlight || uni.__hotUpdatePendingProgress || uni.__updateProgressShown) && shouldUseUpdateOverlay(title)) {
|
|
return;
|
|
}
|
|
return originalShowToast.call(uni, options);
|
|
};
|
|
uni.__updateToastPatched = true;
|
|
}
|
|
|
|
uni.showLoading = (options = {}) => {
|
|
const title = options?.title ?? '';
|
|
if (shouldUseUpdateOverlay(title) && (uni.__hotUpdateInFlight || uni.__hotUpdatePendingProgress || canEmit())) {
|
|
const parsed = parseTitleToProgress(title);
|
|
if (!uni.__updateProgressShown && canEmit()) {
|
|
uni.__updateProgressShown = true;
|
|
emitProgress({
|
|
type: 'show',
|
|
text: parsed.text || '下载中...'
|
|
});
|
|
}
|
|
if (parsed.percent !== null && canEmit()) {
|
|
emitProgress({
|
|
type: 'set',
|
|
percent: parsed.percent,
|
|
text: parsed.text || ''
|
|
});
|
|
}
|
|
return;
|
|
}
|
|
return originalShowLoading.call(uni, options);
|
|
};
|
|
|
|
uni.hideLoading = () => {
|
|
if (uni.__updateProgressShown && canEmit()) {
|
|
uni.__updateProgressShown = false;
|
|
emitProgress({
|
|
type: 'hide'
|
|
});
|
|
return;
|
|
}
|
|
return originalHideLoading.call(uni);
|
|
};
|
|
|
|
uni.__updateLoadingPatched = true;
|
|
};
|
|
|
|
const waitForPlusRuntime = ({
|
|
timeoutMs = 5000,
|
|
intervalMs = 50
|
|
} = {}) =>
|
|
new Promise((resolve) => {
|
|
const ready = () => typeof plus !== 'undefined' && !!plus?.runtime;
|
|
if (ready()) {
|
|
resolve(true);
|
|
return;
|
|
}
|
|
const startedAt = Date.now();
|
|
const timer = setInterval(() => {
|
|
if (ready()) {
|
|
clearInterval(timer);
|
|
resolve(true);
|
|
return;
|
|
}
|
|
if (Date.now() - startedAt >= timeoutMs) {
|
|
clearInterval(timer);
|
|
resolve(false);
|
|
}
|
|
}, intervalMs);
|
|
});
|
|
|
|
const ensureGlobalHotUpdateChecked = async () => {
|
|
if (uni.__globalHotUpdateCheckedInApp) return;
|
|
uni.__globalHotUpdateCheckedInApp = true;
|
|
const ok = await waitForPlusRuntime();
|
|
if (!ok) return;
|
|
if (typeof uni.__globalHotUpdateCheck === 'function') {
|
|
await uni.__globalHotUpdateCheck({
|
|
force: true,
|
|
source: 'app'
|
|
});
|
|
}
|
|
};
|
|
onMounted(() => {
|
|
// #ifdef APP-PLUS
|
|
// plus.nativeUI.setUIStyle('dark');
|
|
// #endif
|
|
// #ifdef H5
|
|
// 以下是H5端的代码
|
|
// document.body.classList.remove('dark', 'light', 'auto');
|
|
// document.body.classList.add('dark');
|
|
// #endif
|
|
// 初始化全局数据
|
|
globalData.value = {
|
|
...globalData.value,
|
|
...uni.getStorageSync('globalData'),
|
|
};
|
|
|
|
globalData.value.statusBarHeight = uni.getSystemInfoSync()?.statusBarHeight;
|
|
globalData.value.windowHeight = uni.getSystemInfoSync()?.windowHeight;
|
|
|
|
ensureLoadingPatched();
|
|
ensureGlobalHotUpdateChecked();
|
|
// socket()
|
|
});
|
|
onLaunch((options = {}) => {
|
|
try {
|
|
uni.hideTabBar({
|
|
fail: () => {},
|
|
});
|
|
} catch (e) {}
|
|
// globalData.value.statusBarHeight = uni.getSystemInfoSync()?.statusBarHeight;
|
|
// globalData.value.windowHeight = uni.getSystemInfoSync()?.windowHeight;
|
|
// 获取微信胶囊的位置信息 width,height,top,right,left,bottom
|
|
let custom = {
|
|
top: 0,
|
|
height: 0,
|
|
};
|
|
// #ifdef MP-WEIXIN
|
|
|
|
custom = wx.getMenuButtonBoundingClientRect();
|
|
// #endif
|
|
// 导航栏高度(标题栏高度) = 胶囊高度 + (顶部距离 - 状态栏高度) * 2
|
|
globalData.value.navigationBarHeight =
|
|
custom.height + (custom.top - uni.getSystemInfoSync()?.statusBarHeight) * 2;
|
|
globalData.value.navHeight =
|
|
globalData.value.navigationBarHeight + uni.getSystemInfoSync()?.statusBarHeight;
|
|
uni.setStorageSync('globalData', globalData.value);
|
|
// 加载Shopro底层依赖
|
|
ShoproInit();
|
|
|
|
console.log(SCHEME_TAG, 'onLaunch', options);
|
|
schemeState.launching = true;
|
|
schemeState.schemeHandledInLaunch = false;
|
|
// #ifdef APP-PLUS
|
|
const boot = () => {
|
|
registerSchemeEventListener();
|
|
const optionsHit = isSchemeTrigger(options);
|
|
if (optionsHit) {
|
|
schemeState.schemeHandledInLaunch = true;
|
|
handleSchemeByOptions(options, 'onLaunch冷启动scheme');
|
|
} else {
|
|
registerSchemeRuntimeArguments();
|
|
}
|
|
};
|
|
if (typeof plus === 'undefined' || !plus?.runtime) {
|
|
const start = Date.now();
|
|
const t = setInterval(() => {
|
|
if (typeof plus !== 'undefined' && plus?.runtime) {
|
|
clearInterval(t);
|
|
boot();
|
|
} else if (Date.now() - start > 4000) {
|
|
clearInterval(t);
|
|
boot();
|
|
}
|
|
}, 50);
|
|
} else {
|
|
boot();
|
|
}
|
|
setTimeout(() => { schemeState.launching = false; }, 1500);
|
|
// #endif
|
|
});
|
|
|
|
onShow((options = {}) => {
|
|
try {
|
|
uni.hideTabBar({
|
|
fail: () => {},
|
|
});
|
|
} catch (e) {}
|
|
// #ifdef APP-PLUS
|
|
if (
|
|
!schemeState.launching &&
|
|
!schemeState.schemeHandledInLaunch &&
|
|
isSchemeTrigger(options)
|
|
) {
|
|
handleSchemeByOptions(options, 'onShow兜底scheme');
|
|
}
|
|
schemeState.schemeHandledInLaunch = false;
|
|
// 获取剪贴板
|
|
uni.getClipboardData({
|
|
success: (res) => {},
|
|
});
|
|
// #endif
|
|
});
|
|
if (typeof uni.onTabBarMidButtonTap === 'function') {
|
|
uni.onTabBarMidButtonTap(() => {
|
|
uni.navigateTo({
|
|
url: '/pages/home/seed',
|
|
});
|
|
});
|
|
}
|
|
</script>
|
|
|
|
<style lang="scss">
|
|
@import '@/sheep/scss/index.scss';
|
|
|
|
.uni-tabbar-border {
|
|
background-color: transparent !important;
|
|
/* 移除背景色 */
|
|
height: 0 !important;
|
|
/* 隐藏边框元素 */
|
|
border: none !important;
|
|
/* 确保无边框 */
|
|
}
|
|
|
|
.uni-app--showtopwindow uni-page-head {
|
|
display: none;
|
|
}
|
|
</style>
|