From 5f11b43b1245410d3d998ca246326a32720e9e2e Mon Sep 17 00:00:00 2001 From: DCloud_LXH <283700113@qq.com> Date: Wed, 29 Sep 2021 14:43:48 +0800 Subject: [PATCH] feat: support dynamic tabbarItem hidden --- package.json | 2 +- packages/shims-uni-app.d.ts | 1 + .../uni-app-plus/dist/uni-app-service.es.js | 165 +- .../uni-app-plus/src/service/api/ui/tabBar.ts | 4 +- .../src/service/framework/app/tabBar.ts | 20 +- packages/uni-cli-shared/src/json/pages.ts | 41 +- packages/uni-h5/dist/uni-h5.cjs.js | 34 +- packages/uni-h5/dist/uni-h5.es.js | 40 +- .../framework/components/layout/tabBar.tsx | 57 +- packages/uni-h5/src/service/api/ui/tabBar.ts | 6 +- packages/uni-stat/dist/uni-stat.cjs.js | 1888 ++++++++--------- packages/uni-stat/dist/uni-stat.es.js | 1888 ++++++++--------- yarn.lock | 8 +- 13 files changed, 2121 insertions(+), 2033 deletions(-) diff --git a/package.json b/package.json index dca1ebe61..88cb559a2 100644 --- a/package.json +++ b/package.json @@ -42,7 +42,7 @@ }, "devDependencies": { "@babel/preset-env": "^7.14.7", - "@dcloudio/types": "2.5.8", + "@dcloudio/types": "2.5.9", "@jest/types": "^27.0.2", "@microsoft/api-extractor": "^7.13.2", "@rollup/plugin-alias": "^3.1.1", diff --git a/packages/shims-uni-app.d.ts b/packages/shims-uni-app.d.ts index 557c614b4..ee998aa38 100644 --- a/packages/shims-uni-app.d.ts +++ b/packages/shims-uni-app.d.ts @@ -255,6 +255,7 @@ declare namespace UniApp { selectedIconPath?: string redDot?: boolean badge?: string + visible?: boolean } interface TabBarNormalItemOptions extends TabBarItemBaseOptions { diff --git a/packages/uni-app-plus/dist/uni-app-service.es.js b/packages/uni-app-plus/dist/uni-app-service.es.js index 7040d0f3b..ae1af0b07 100644 --- a/packages/uni-app-plus/dist/uni-app-service.es.js +++ b/packages/uni-app-plus/dist/uni-app-service.es.js @@ -10,79 +10,79 @@ const __uniRoutes = instanceContext.__uniRoutes; var serviceContext = (function (vue) { 'use strict'; - /* - * base64-arraybuffer - * https://github.com/niklasvh/base64-arraybuffer - * - * Copyright (c) 2012 Niklas von Hertzen - * Licensed under the MIT license. - */ - - var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - - // Use a lookup table to find the index. - var lookup = /*#__PURE__*/ (function () { - const lookup = new Uint8Array(256); - for (var i = 0; i < chars.length; i++) { - lookup[chars.charCodeAt(i)] = i; - } - return lookup - })(); - - function encode$3(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$1(base64) { - var bufferLength = base64.length * 0.75, - len = base64.length, - i, - p = 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[p++] = (encoded1 << 2) | (encoded2 >> 4); - bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); - bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); - } - - return arraybuffer + /* + * base64-arraybuffer + * https://github.com/niklasvh/base64-arraybuffer + * + * Copyright (c) 2012 Niklas von Hertzen + * Licensed under the MIT license. + */ + + var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + + // Use a lookup table to find the index. + var lookup = /*#__PURE__*/ (function () { + const lookup = new Uint8Array(256); + for (var i = 0; i < chars.length; i++) { + lookup[chars.charCodeAt(i)] = i; + } + return lookup + })(); + + function encode$3(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$1(base64) { + var bufferLength = base64.length * 0.75, + len = base64.length, + i, + p = 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[p++] = (encoded1 << 2) | (encoded2 >> 4); + bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); + bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); + } + + return arraybuffer } /** @@ -6163,7 +6163,7 @@ var serviceContext = (function (vue) { /** * 动态设置 tabBar 某一项的内容 */ - function setTabBarItem$1(index, text, iconPath, selectedIconPath) { + function setTabBarItem$1(index, text, iconPath, selectedIconPath, visible) { const item = { index, }; @@ -6176,7 +6176,18 @@ var serviceContext = (function (vue) { if (selectedIconPath) { item.selectedIconPath = getRealPath(selectedIconPath); } - tabBar && tabBar.setTabBarItem(item); + if (visible !== undefined) { + item.visible = config.list[index].visible = visible; + delete item.index; + const tabbarItems = config.list.map((item) => ({ + visible: item.visible, + })); + tabbarItems[index] = item; + tabBar && tabBar.setTabBarItems({ list: tabbarItems }); + } + else { + tabBar && tabBar.setTabBarItem(item); + } } /** * 动态设置 tabBar 的整体样式 @@ -9301,8 +9312,8 @@ var serviceContext = (function (vue) { tabBar$1.setTabBarBadge('text', index, text); resolve(); }, SetTabBarBadgeProtocol, SetTabBarBadgeOptions); - const setTabBarItem = defineAsyncApi(API_SET_TAB_BAR_ITEM, ({ index, text, iconPath, selectedIconPath, pagePath }, { resolve, reject }) => { - tabBar$1.setTabBarItem(index, text, iconPath, selectedIconPath); + const setTabBarItem = defineAsyncApi(API_SET_TAB_BAR_ITEM, ({ index, text, iconPath, selectedIconPath, pagePath, visible }, { resolve, reject }) => { + tabBar$1.setTabBarItem(index, text, iconPath, selectedIconPath, visible); const route = pagePath && __uniRoutes.find(({ path }) => path === pagePath); if (route) { const meta = route.meta; diff --git a/packages/uni-app-plus/src/service/api/ui/tabBar.ts b/packages/uni-app-plus/src/service/api/ui/tabBar.ts index 2329db1ba..df71307ec 100644 --- a/packages/uni-app-plus/src/service/api/ui/tabBar.ts +++ b/packages/uni-app-plus/src/service/api/ui/tabBar.ts @@ -47,10 +47,10 @@ export const setTabBarBadge = defineAsyncApi( export const setTabBarItem = defineAsyncApi( API_SET_TAB_BAR_ITEM, ( - { index, text, iconPath, selectedIconPath, pagePath }, + { index, text, iconPath, selectedIconPath, pagePath, visible }, { resolve, reject } ) => { - tabBar.setTabBarItem(index, text, iconPath, selectedIconPath) + tabBar.setTabBarItem(index, text, iconPath, selectedIconPath, visible) const route = pagePath && __uniRoutes.find(({ path }) => path === pagePath) if (route) { const meta = route.meta diff --git a/packages/uni-app-plus/src/service/framework/app/tabBar.ts b/packages/uni-app-plus/src/service/framework/app/tabBar.ts index 86256e652..baa2f85d1 100644 --- a/packages/uni-app-plus/src/service/framework/app/tabBar.ts +++ b/packages/uni-app-plus/src/service/framework/app/tabBar.ts @@ -52,9 +52,11 @@ function setTabBarItem( index: number, text?: string, iconPath?: string, - selectedIconPath?: string + selectedIconPath?: string, + visible?: boolean ) { - const item: Record = { + type TabBarItem = Record + const item: TabBarItem = { index, } if (text !== undefined) { @@ -66,7 +68,19 @@ function setTabBarItem( if (selectedIconPath) { item.selectedIconPath = getRealPath(selectedIconPath) } - tabBar && tabBar.setTabBarItem(item) + if (visible !== undefined) { + item.visible = config.list[index].visible = visible + delete item.index + + const tabbarItems = config.list.map((item) => ({ + visible: item.visible, + })) + tabbarItems[index] = item + + tabBar && tabBar.setTabBarItems({ list: tabbarItems }) + } else { + tabBar && tabBar.setTabBarItem(item) + } } /** * 动态设置 tabBar 的整体样式 diff --git a/packages/uni-cli-shared/src/json/pages.ts b/packages/uni-cli-shared/src/json/pages.ts index e356d6944..1d73f7d9c 100644 --- a/packages/uni-cli-shared/src/json/pages.ts +++ b/packages/uni-cli-shared/src/json/pages.ts @@ -54,7 +54,7 @@ export function normalizePagesJson(jsonStr: string, platform: UniApp.PLATFORM) { ) // tabBar if (pagesJson.tabBar) { - const tabBar = normalizeTabBar(pagesJson.tabBar!) + const tabBar = normalizeTabBar(pagesJson.tabBar!, platform) if (tabBar) { pagesJson.tabBar = tabBar } else { @@ -289,29 +289,34 @@ const DEFAULT_TAB_BAR: Partial = { height: TABBAR_HEIGHT + 'px', } -function normalizeTabBar(tabBar: UniApp.TabBarOptions) { +function normalizeTabBar( + tabBar: UniApp.TabBarOptions, + platform: UniApp.PLATFORM +) { const { list, midButton } = tabBar if (!list || !list.length) { return } tabBar = extend({}, DEFAULT_TAB_BAR, tabBar) - const len = list.length - if (len % 2 === 0 && isPlainObject(midButton)) { - list.splice( - Math.floor(len / 2), - 0, - extend( - { - type: 'midButton', - width: '50px', - height: '50px', - iconWidth: '24px', - }, - midButton + if (platform === 'h5') { + const len = list.length + if (len % 2 === 0 && isPlainObject(midButton)) { + list.splice( + Math.floor(len / 2), + 0, + extend( + { + type: 'midButton', + width: '50px', + height: '50px', + iconWidth: '24px', + }, + midButton + ) ) - ) - } else { - delete tabBar.midButton + } else { + delete tabBar.midButton + } } list.forEach((item) => { if (item.iconPath) { diff --git a/packages/uni-h5/dist/uni-h5.cjs.js b/packages/uni-h5/dist/uni-h5.cjs.js index 637cdfd59..121c3cf03 100644 --- a/packages/uni-h5/dist/uni-h5.cjs.js +++ b/packages/uni-h5/dist/uni-h5.cjs.js @@ -9744,16 +9744,18 @@ const UniServiceJSBridge$1 = /* @__PURE__ */ shared.extend(ServiceJSBridge, { var TabBar = /* @__PURE__ */ defineSystemComponent({ name: "TabBar", setup() { + const visibleList = vue.ref([]); const tabBar2 = useTabBar(); + useVisibleList(tabBar2, visibleList); useTabBarCssVar(tabBar2); - const onSwitchTab = useSwitchTab(vueRouter.useRoute(), tabBar2); + const onSwitchTab = useSwitchTab(vueRouter.useRoute(), tabBar2, visibleList); const { style, borderStyle, placeholderStyle } = useTabBarStyle(tabBar2); return () => { - const tabBarItemsTsx = createTabBarItemsTsx(tabBar2, onSwitchTab); + const tabBarItemsTsx = createTabBarItemsTsx(tabBar2, onSwitchTab, visibleList); return vue.createVNode("uni-tabbar", { "class": "uni-tabbar-" + tabBar2.position }, [vue.createVNode("div", { @@ -9776,15 +9778,26 @@ function useTabBarCssVar(tabBar2) { }); }); } -function useSwitchTab(route, tabBar2) { +function useVisibleList(tabBar2, visibleList) { + function setVisibleList() { + let tempList = []; + tempList = tabBar2.list.filter((item) => item.visible !== false); + if (__UNI_FEATURE_TABBAR_MIDBUTTON__) { + tempList = tempList.filter((item) => !isMidButton(item)); + if (tempList.length % 2 === 0) { + tempList.splice(Math.floor(tempList.length / 2), 0, tabBar2.list[Math.floor(tabBar2.list.length / 2)]); + } + } + visibleList.value = tempList; + } + vue.watchEffect(setVisibleList); +} +function useSwitchTab(route, tabBar2, visibleList) { vue.watchEffect(() => { const meta = route.meta; if (meta.isTabBar) { const pagePath = meta.route; - const index2 = tabBar2.list.findIndex((item) => item.pagePath === pagePath); - if (index2 === -1) { - return; - } + const index2 = visibleList.value.findIndex((item) => item.pagePath === pagePath); tabBar2.selectedIndex = index2; } }); @@ -9867,14 +9880,13 @@ function useTabBarStyle(tabBar2) { function isMidButton(item) { return item.type === "midButton"; } -function createTabBarItemsTsx(tabBar2, onSwitchTab) { +function createTabBarItemsTsx(tabBar2, onSwitchTab, visibleList) { const { - list, selectedIndex, selectedColor, color } = tabBar2; - return list.map((item, index2) => { + return visibleList.value.map((item, index2) => { const selected = selectedIndex === index2; const textColor = selected ? selectedColor : color; const iconPath = (selected ? item.selectedIconPath || item.iconPath : item.iconPath) || ""; @@ -9958,7 +9970,7 @@ function createTabBarMidButtonTsx(color, iconPath, midButton, tabBar2, index2, o iconWidth } = midButton; return vue.createVNode("div", { - "key": index2, + "key": "midButton", "class": "uni-tabbar__item", "style": { flex: "0 0 " + width, diff --git a/packages/uni-h5/dist/uni-h5.es.js b/packages/uni-h5/dist/uni-h5.es.js index 554856647..8e93286cc 100644 --- a/packages/uni-h5/dist/uni-h5.es.js +++ b/packages/uni-h5/dist/uni-h5.es.js @@ -18549,7 +18549,7 @@ const stopPullDownRefresh = /* @__PURE__ */ defineAsyncApi(API_STOP_PULL_DOWN_RE UniServiceJSBridge.invokeViewMethod(API_STOP_PULL_DOWN_REFRESH, {}, getCurrentPageId()); resolve(); }); -const setTabBarItemProps = ["text", "iconPath", "selectedIconPath"]; +const setTabBarItemProps = ["text", "iconPath", "selectedIconPath", "visible"]; const setTabBarStyleProps = [ "color", "selectedColor", @@ -18629,10 +18629,10 @@ const setTabBarStyle = /* @__PURE__ */ defineAsyncApi(API_SET_TAB_BAR_STYLE, (ar setTabBar(API_SET_TAB_BAR_STYLE, args, resolve); }, SetTabBarStyleProtocol, SetTabBarStyleOptions); const hideTabBar = /* @__PURE__ */ defineAsyncApi(API_HIDE_TAB_BAR, (args, { resolve }) => { - setTabBar(API_HIDE_TAB_BAR, args, resolve); + setTabBar(API_HIDE_TAB_BAR, args ? args : {}, resolve); }, HideTabBarProtocol); const showTabBar = /* @__PURE__ */ defineAsyncApi(API_SHOW_TAB_BAR, (args, { resolve }) => { - setTabBar(API_SHOW_TAB_BAR, args, resolve); + setTabBar(API_SHOW_TAB_BAR, args ? args : {}, resolve); }, ShowTabBarProtocol); const hideTabBarRedDot = /* @__PURE__ */ defineAsyncApi(API_HIDE_TAB_BAR_RED_DOT, (args, { resolve }) => { setTabBar(API_HIDE_TAB_BAR_RED_DOT, args, resolve); @@ -18649,16 +18649,18 @@ const setTabBarBadge = /* @__PURE__ */ defineAsyncApi(API_SET_TAB_BAR_BADGE, (ar var TabBar = /* @__PURE__ */ defineSystemComponent({ name: "TabBar", setup() { + const visibleList = ref([]); const tabBar2 = useTabBar(); + useVisibleList(tabBar2, visibleList); useTabBarCssVar(tabBar2); - const onSwitchTab = useSwitchTab(useRoute(), tabBar2); + const onSwitchTab = useSwitchTab(useRoute(), tabBar2, visibleList); const { style, borderStyle, placeholderStyle } = useTabBarStyle(tabBar2); return () => { - const tabBarItemsTsx = createTabBarItemsTsx(tabBar2, onSwitchTab); + const tabBarItemsTsx = createTabBarItemsTsx(tabBar2, onSwitchTab, visibleList); return createVNode("uni-tabbar", { "class": "uni-tabbar-" + tabBar2.position }, [createVNode("div", { @@ -18681,15 +18683,26 @@ function useTabBarCssVar(tabBar2) { }); }); } -function useSwitchTab(route, tabBar2) { +function useVisibleList(tabBar2, visibleList) { + function setVisibleList() { + let tempList = []; + tempList = tabBar2.list.filter((item) => item.visible !== false); + if (__UNI_FEATURE_TABBAR_MIDBUTTON__) { + tempList = tempList.filter((item) => !isMidButton(item)); + if (tempList.length % 2 === 0) { + tempList.splice(Math.floor(tempList.length / 2), 0, tabBar2.list[Math.floor(tabBar2.list.length / 2)]); + } + } + visibleList.value = tempList; + } + watchEffect(setVisibleList); +} +function useSwitchTab(route, tabBar2, visibleList) { watchEffect(() => { const meta = route.meta; if (meta.isTabBar) { const pagePath = meta.route; - const index2 = tabBar2.list.findIndex((item) => item.pagePath === pagePath); - if (index2 === -1) { - return; - } + const index2 = visibleList.value.findIndex((item) => item.pagePath === pagePath); tabBar2.selectedIndex = index2; } }); @@ -18772,14 +18785,13 @@ function useTabBarStyle(tabBar2) { function isMidButton(item) { return item.type === "midButton"; } -function createTabBarItemsTsx(tabBar2, onSwitchTab) { +function createTabBarItemsTsx(tabBar2, onSwitchTab, visibleList) { const { - list: list2, selectedIndex, selectedColor, color } = tabBar2; - return list2.map((item, index2) => { + return visibleList.value.map((item, index2) => { const selected = selectedIndex === index2; const textColor = selected ? selectedColor : color; const iconPath = (selected ? item.selectedIconPath || item.iconPath : item.iconPath) || ""; @@ -18863,7 +18875,7 @@ function createTabBarMidButtonTsx(color, iconPath, midButton, tabBar2, index2, o iconWidth } = midButton; return createVNode("div", { - "key": index2, + "key": "midButton", "class": "uni-tabbar__item", "style": { flex: "0 0 " + width, diff --git a/packages/uni-h5/src/framework/components/layout/tabBar.tsx b/packages/uni-h5/src/framework/components/layout/tabBar.tsx index 646ed3d33..df1b5b21a 100644 --- a/packages/uni-h5/src/framework/components/layout/tabBar.tsx +++ b/packages/uni-h5/src/framework/components/layout/tabBar.tsx @@ -1,4 +1,4 @@ -import { watch, watchEffect, computed } from 'vue' +import { watch, watchEffect, computed, ref, Ref } from 'vue' import { RouteLocationNormalizedLoaded, useRoute } from 'vue-router' import { invokeHook, updatePageCssVar } from '@dcloudio/uni-core' import { @@ -14,12 +14,18 @@ import { normalizeWindowBottom } from '../../../helpers/cssVar' export default /*#__PURE__*/ defineSystemComponent({ name: 'TabBar', setup() { + const visibleList = ref([]) const tabBar = useTabBar()! + useVisibleList(tabBar, visibleList) useTabBarCssVar(tabBar) - const onSwitchTab = useSwitchTab(useRoute(), tabBar) + const onSwitchTab = useSwitchTab(useRoute(), tabBar, visibleList) const { style, borderStyle, placeholderStyle } = useTabBarStyle(tabBar) return () => { - const tabBarItemsTsx = createTabBarItemsTsx(tabBar, onSwitchTab) + const tabBarItemsTsx = createTabBarItemsTsx( + tabBar, + onSwitchTab, + visibleList + ) return (
@@ -46,18 +52,44 @@ function useTabBarCssVar(tabBar: UniApp.TabBarOptions) { ) } +function useVisibleList( + tabBar: UniApp.TabBarOptions, + visibleList: Ref +) { + function setVisibleList() { + let tempList = [] + tempList = tabBar.list.filter((item) => item.visible !== false) + + if (__UNI_FEATURE_TABBAR_MIDBUTTON__) { + tempList = tempList.filter((item) => !isMidButton(item)) + + if (tempList.length % 2 === 0) { + tempList.splice( + Math.floor(tempList.length / 2), + 0, + tabBar.list[Math.floor(tabBar.list.length / 2)] + ) + } + } + + visibleList.value = tempList + } + + watchEffect(setVisibleList) +} + function useSwitchTab( route: RouteLocationNormalizedLoaded, - tabBar: UniApp.TabBarOptions + tabBar: UniApp.TabBarOptions, + visibleList: Ref ) { watchEffect(() => { const meta = route.meta if (meta.isTabBar) { const pagePath = meta.route - const index = tabBar.list.findIndex((item) => item.pagePath === pagePath) - if (index === -1) { - return - } + const index = visibleList.value.findIndex( + (item) => item.pagePath === pagePath + ) tabBar.selectedIndex = index } }) @@ -141,10 +173,11 @@ function isMidButton(item: unknown): item is UniApp.TabBarMidButtonOptions { function createTabBarItemsTsx( tabBar: UniApp.TabBarOptions, - onSwitchTab: OnSwtichTab + onSwitchTab: OnSwtichTab, + visibleList: Ref ) { - const { list, selectedIndex, selectedColor, color } = tabBar - return list.map((item, index) => { + const { selectedIndex, selectedColor, color } = tabBar + return visibleList.value.map((item, index) => { const selected = selectedIndex === index const textColor = selected ? selectedColor : color const iconPath = @@ -267,7 +300,7 @@ function createTabBarMidButtonTsx( const { width, height, backgroundImage, iconWidth } = midButton return (
( export const hideTabBar = defineAsyncApi( API_HIDE_TAB_BAR, (args, { resolve }) => { - setTabBar(API_HIDE_TAB_BAR, args, resolve) + setTabBar(API_HIDE_TAB_BAR, args ? args : {}, resolve) }, HideTabBarProtocol ) @@ -152,7 +152,7 @@ export const hideTabBar = defineAsyncApi( export const showTabBar = defineAsyncApi( API_SHOW_TAB_BAR, (args, { resolve }) => { - setTabBar(API_SHOW_TAB_BAR, args, resolve) + setTabBar(API_SHOW_TAB_BAR, args ? args : {}, resolve) }, ShowTabBarProtocol ) diff --git a/packages/uni-stat/dist/uni-stat.cjs.js b/packages/uni-stat/dist/uni-stat.cjs.js index 12e609c13..062692177 100644 --- a/packages/uni-stat/dist/uni-stat.cjs.js +++ b/packages/uni-stat/dist/uni-stat.cjs.js @@ -10,952 +10,952 @@ const APP_PVER_TIME = 300; const OPERATING_TIME = 10; const DIFF_TIME = 60 * 1000 * 60 * 24; -const statConfig$1 = { - appid: process.env.UNI_APP_ID, +const statConfig$1 = { + appid: process.env.UNI_APP_ID, +}; +const UUID_KEY = '__DC_STAT_UUID'; +const UUID_VALUE = '__DC_UUID_VALUE'; + +function getUuid() { + let uuid = ''; + if (getPlatformName() === 'n') { + try { + uuid = plus.runtime.getDCloudId(); + } catch (e) { + uuid = ''; + } + return uuid + } + + try { + uuid = uni.getStorageSync(UUID_KEY); + } catch (e) { + uuid = UUID_VALUE; + } + + if (!uuid) { + uuid = Date.now() + '' + Math.floor(Math.random() * 1e7); + try { + uni.setStorageSync(UUID_KEY, uuid); + } catch (e) { + uni.setStorageSync(UUID_KEY, UUID_VALUE); + } + } + return uuid +} + +const getSgin = (statData) => { + let arr = Object.keys(statData); + let sortArr = arr.sort(); + let sgin = {}; + let sginStr = ''; + for (var i in sortArr) { + sgin[sortArr[i]] = statData[sortArr[i]]; + sginStr += sortArr[i] + '=' + statData[sortArr[i]] + '&'; + } + // const options = sginStr.substr(0, sginStr.length - 1) + // sginStr = sginStr.substr(0, sginStr.length - 1) + '&key=' + STAT_KEY; + // const si = crypto.createHash('md5').update(sginStr).digest('hex'); + return { + sign: '', + options: sginStr.substr(0, sginStr.length - 1), + } +}; + +const getSplicing = (data) => { + let str = ''; + for (var i in data) { + str += i + '=' + data[i] + '&'; + } + return str.substr(0, str.length - 1) +}; + +const getTime = () => { + return parseInt(new Date().getTime() / 1000) +}; + +const getPlatformName = () => { + const aliArr = ['y', 'a', 'p', 'mp-ali']; + const platformList = { + 'app-plus': 'n', + h5: 'h5', + 'mp-weixin': 'wx', + [aliArr.reverse().join('')]: 'ali', + 'mp-baidu': 'bd', + 'mp-toutiao': 'tt', + 'mp-qq': 'qq', + 'quickapp-native': 'qn', + 'mp-kuaishou': 'ks', + }; + return platformList[process.env.VUE_APP_PLATFORM] +}; + +const getPackName = () => { + let packName = ''; + if (getPlatformName() === 'wx' || getPlatformName() === 'qq') { + // 兼容微信小程序低版本基础库 + if (uni.canIUse('getAccountInfoSync')) { + packName = uni.getAccountInfoSync().miniProgram.appId || ''; + } + } + return packName +}; + +const getVersion = () => { + return getPlatformName() === 'n' ? plus.runtime.version : '' +}; + +const getChannel = () => { + const platformName = getPlatformName(); + let channel = ''; + if (platformName === 'n') { + channel = plus.runtime.channel; + } + return channel +}; + +const getScene = (options) => { + const platformName = getPlatformName(); + let scene = ''; + if (options) { + return options + } + if (platformName === 'wx') { + scene = uni.getLaunchOptionsSync().scene; + } + return scene +}; +const First__Visit__Time__KEY = 'First__Visit__Time'; +const Last__Visit__Time__KEY = 'Last__Visit__Time'; + +const getFirstVisitTime = () => { + const timeStorge = uni.getStorageSync(First__Visit__Time__KEY); + let time = 0; + if (timeStorge) { + time = timeStorge; + } else { + time = getTime(); + uni.setStorageSync(First__Visit__Time__KEY, time); + uni.removeStorageSync(Last__Visit__Time__KEY); + } + return time +}; + +const getLastVisitTime = () => { + const timeStorge = uni.getStorageSync(Last__Visit__Time__KEY); + let time = 0; + if (timeStorge) { + time = timeStorge; + } else { + time = ''; + } + uni.setStorageSync(Last__Visit__Time__KEY, getTime()); + return time +}; + +const PAGE_RESIDENCE_TIME = '__page__residence__time'; +let First_Page_residence_time = 0; +let Last_Page_residence_time = 0; + +const setPageResidenceTime = () => { + First_Page_residence_time = getTime(); + if (getPlatformName() === 'n') { + uni.setStorageSync(PAGE_RESIDENCE_TIME, getTime()); + } + return First_Page_residence_time +}; + +const getPageResidenceTime = () => { + Last_Page_residence_time = getTime(); + if (getPlatformName() === 'n') { + First_Page_residence_time = uni.getStorageSync(PAGE_RESIDENCE_TIME); + } + return Last_Page_residence_time - First_Page_residence_time +}; +const TOTAL__VISIT__COUNT = 'Total__Visit__Count'; +const getTotalVisitCount = () => { + const timeStorge = uni.getStorageSync(TOTAL__VISIT__COUNT); + let count = 1; + if (timeStorge) { + count = timeStorge; + count++; + } + uni.setStorageSync(TOTAL__VISIT__COUNT, count); + return count +}; + +const GetEncodeURIComponentOptions = (statData) => { + let data = {}; + for (let prop in statData) { + data[prop] = encodeURIComponent(statData[prop]); + } + return data +}; + +let Set__First__Time = 0; +let Set__Last__Time = 0; + +const getFirstTime = () => { + let time = new Date().getTime(); + Set__First__Time = time; + Set__Last__Time = 0; + return time +}; + +const getLastTime = () => { + let time = new Date().getTime(); + Set__Last__Time = time; + return time +}; + +const getResidenceTime = (type) => { + let residenceTime = 0; + if (Set__First__Time !== 0) { + residenceTime = Set__Last__Time - Set__First__Time; + } + + residenceTime = parseInt(residenceTime / 1000); + residenceTime = residenceTime < 1 ? 1 : residenceTime; + if (type === 'app') { + let overtime = residenceTime > APP_PVER_TIME ? true : false; + return { + residenceTime, + overtime, + } + } + if (type === 'page') { + let overtime = residenceTime > PAGE_PVER_TIME ? true : false; + return { + residenceTime, + overtime, + } + } + + return { + residenceTime, + } +}; + +const getRoute = () => { + var pages = getCurrentPages(); + var page = pages[pages.length - 1]; + if (!page) return '' + // TODO 需要确认如果不用 $vm ,其他平台会不会出错 + let _self = page.$vm; + + if (getPlatformName() === 'bd') { + return _self.$mp && _self.$mp.page.is + } else { + return _self.route || (_self.$scope && _self.$scope.route) + } +}; + +const getPageRoute = (_this) => { + let pageVm = _this.self; + let page = pageVm.$page || pageVm.$scope.$page; + return page.fullPath === '/' ? page.route : page.fullPath +}; + +const getPageTypes = (self) => { + if ( + self.$mpType === 'page' || + (self.$mp && self.$mp.mpType === 'page') || + self.$options.mpType === 'page' + ) { + return true + } + return false +}; + +const calibration = (eventName, options) => { + // login 、 share 、pay_success 、pay_fail 、register 、title + if (!eventName) { + console.error(`uni.report 缺少 [eventName] 参数`); + return true + } + if (typeof eventName !== 'string') { + console.error(`uni.report [eventName] 参数类型错误,只能为 String 类型`); + return true + } + if (eventName.length > 255) { + console.error(`uni.report [eventName] 参数长度不能大于 255`); + return true + } + + if (typeof options !== 'string' && typeof options !== 'object') { + console.error( + `uni.report [options] 参数类型错误,只能为 String 或 Object 类型` + ); + return true + } + + if (typeof options === 'string' && options.length > 255) { + console.error(`uni.report [options] 参数长度不能大于 255`); + return true + } + + if (eventName === 'title' && typeof options !== 'string') { + console.error( + 'uni.report [eventName] 参数为 title 时,[options] 参数只能为 String 类型' + ); + return true + } +}; + +const Report_Data_Time = 'Report_Data_Time'; +const Report_Status = 'Report_Status'; +const isReportData = () => { + return new Promise((resolve, reject) => { + let start_time = ''; + let end_time = new Date().getTime(); + let diff_time = DIFF_TIME; + let report_status = 1; + try { + start_time = uni.getStorageSync(Report_Data_Time); + report_status = uni.getStorageSync(Report_Status); + } catch (e) { + start_time = ''; + report_status = 1; + } + + if (report_status === '') { + requestData(({ enable }) => { + uni.setStorageSync(Report_Data_Time, end_time); + uni.setStorageSync(Report_Status, enable); + if (enable === 1) { + resolve(); + } + }); + return + } + + if (report_status === 1) { + resolve(); + } + + if (!start_time) { + uni.setStorageSync(Report_Data_Time, end_time); + start_time = end_time; + } + + if (end_time - start_time > diff_time) { + requestData(({ enable }) => { + uni.setStorageSync(Report_Data_Time, end_time); + uni.setStorageSync(Report_Status, enable); + }); + } + }) +}; + +const requestData = (done) => { + let formData = { + usv: STAT_VERSION, + conf: JSON.stringify({ + ak: statConfig$1.appid, + }), + }; + uni.request({ + url: STAT_URL, + method: 'GET', + data: formData, + success: (res) => { + const { data } = res; + if (data.ret === 0) { + typeof done === 'function' && + done({ + enable: data.enable, + }); + } + }, + fail: (e) => { + let report_status_code = 1; + try { + report_status_code = uni.getStorageSync(Report_Status); + } catch (e) { + report_status_code = 1; + } + if (report_status_code === '') { + report_status_code = 1; + } + typeof done === 'function' && + done({ + enable: report_status_code, + }); + }, + }); }; -const UUID_KEY = '__DC_STAT_UUID'; -const UUID_VALUE = '__DC_UUID_VALUE'; -function getUuid() { - let uuid = ''; - if (getPlatformName() === 'n') { - try { - uuid = plus.runtime.getDCloudId(); - } catch (e) { - uuid = ''; - } - return uuid - } - - try { - uuid = uni.getStorageSync(UUID_KEY); - } catch (e) { - uuid = UUID_VALUE; - } - - if (!uuid) { - uuid = Date.now() + '' + Math.floor(Math.random() * 1e7); - try { - uni.setStorageSync(UUID_KEY, uuid); - } catch (e) { - uni.setStorageSync(UUID_KEY, UUID_VALUE); - } - } - return uuid -} - -const getSgin = (statData) => { - let arr = Object.keys(statData); - let sortArr = arr.sort(); - let sgin = {}; - let sginStr = ''; - for (var i in sortArr) { - sgin[sortArr[i]] = statData[sortArr[i]]; - sginStr += sortArr[i] + '=' + statData[sortArr[i]] + '&'; - } - // const options = sginStr.substr(0, sginStr.length - 1) - // sginStr = sginStr.substr(0, sginStr.length - 1) + '&key=' + STAT_KEY; - // const si = crypto.createHash('md5').update(sginStr).digest('hex'); - return { - sign: '', - options: sginStr.substr(0, sginStr.length - 1), - } -}; - -const getSplicing = (data) => { - let str = ''; - for (var i in data) { - str += i + '=' + data[i] + '&'; - } - return str.substr(0, str.length - 1) -}; - -const getTime = () => { - return parseInt(new Date().getTime() / 1000) -}; - -const getPlatformName = () => { - const aliArr = ['y', 'a', 'p', 'mp-ali']; - const platformList = { - 'app-plus': 'n', - h5: 'h5', - 'mp-weixin': 'wx', - [aliArr.reverse().join('')]: 'ali', - 'mp-baidu': 'bd', - 'mp-toutiao': 'tt', - 'mp-qq': 'qq', - 'quickapp-native': 'qn', - 'mp-kuaishou': 'ks', - }; - return platformList[process.env.VUE_APP_PLATFORM] -}; - -const getPackName = () => { - let packName = ''; - if (getPlatformName() === 'wx' || getPlatformName() === 'qq') { - // 兼容微信小程序低版本基础库 - if (uni.canIUse('getAccountInfoSync')) { - packName = uni.getAccountInfoSync().miniProgram.appId || ''; - } - } - return packName -}; - -const getVersion = () => { - return getPlatformName() === 'n' ? plus.runtime.version : '' -}; - -const getChannel = () => { - const platformName = getPlatformName(); - let channel = ''; - if (platformName === 'n') { - channel = plus.runtime.channel; - } - return channel -}; - -const getScene = (options) => { - const platformName = getPlatformName(); - let scene = ''; - if (options) { - return options - } - if (platformName === 'wx') { - scene = uni.getLaunchOptionsSync().scene; - } - return scene -}; -const First__Visit__Time__KEY = 'First__Visit__Time'; -const Last__Visit__Time__KEY = 'Last__Visit__Time'; - -const getFirstVisitTime = () => { - const timeStorge = uni.getStorageSync(First__Visit__Time__KEY); - let time = 0; - if (timeStorge) { - time = timeStorge; - } else { - time = getTime(); - uni.setStorageSync(First__Visit__Time__KEY, time); - uni.removeStorageSync(Last__Visit__Time__KEY); - } - return time -}; - -const getLastVisitTime = () => { - const timeStorge = uni.getStorageSync(Last__Visit__Time__KEY); - let time = 0; - if (timeStorge) { - time = timeStorge; - } else { - time = ''; - } - uni.setStorageSync(Last__Visit__Time__KEY, getTime()); - return time -}; - -const PAGE_RESIDENCE_TIME = '__page__residence__time'; -let First_Page_residence_time = 0; -let Last_Page_residence_time = 0; - -const setPageResidenceTime = () => { - First_Page_residence_time = getTime(); - if (getPlatformName() === 'n') { - uni.setStorageSync(PAGE_RESIDENCE_TIME, getTime()); - } - return First_Page_residence_time -}; - -const getPageResidenceTime = () => { - Last_Page_residence_time = getTime(); - if (getPlatformName() === 'n') { - First_Page_residence_time = uni.getStorageSync(PAGE_RESIDENCE_TIME); - } - return Last_Page_residence_time - First_Page_residence_time -}; -const TOTAL__VISIT__COUNT = 'Total__Visit__Count'; -const getTotalVisitCount = () => { - const timeStorge = uni.getStorageSync(TOTAL__VISIT__COUNT); - let count = 1; - if (timeStorge) { - count = timeStorge; - count++; - } - uni.setStorageSync(TOTAL__VISIT__COUNT, count); - return count -}; - -const GetEncodeURIComponentOptions = (statData) => { - let data = {}; - for (let prop in statData) { - data[prop] = encodeURIComponent(statData[prop]); - } - return data -}; - -let Set__First__Time = 0; -let Set__Last__Time = 0; - -const getFirstTime = () => { - let time = new Date().getTime(); - Set__First__Time = time; - Set__Last__Time = 0; - return time -}; - -const getLastTime = () => { - let time = new Date().getTime(); - Set__Last__Time = time; - return time -}; - -const getResidenceTime = (type) => { - let residenceTime = 0; - if (Set__First__Time !== 0) { - residenceTime = Set__Last__Time - Set__First__Time; - } - - residenceTime = parseInt(residenceTime / 1000); - residenceTime = residenceTime < 1 ? 1 : residenceTime; - if (type === 'app') { - let overtime = residenceTime > APP_PVER_TIME ? true : false; - return { - residenceTime, - overtime, - } - } - if (type === 'page') { - let overtime = residenceTime > PAGE_PVER_TIME ? true : false; - return { - residenceTime, - overtime, - } - } - - return { - residenceTime, - } -}; - -const getRoute = () => { - var pages = getCurrentPages(); - var page = pages[pages.length - 1]; - if (!page) return '' - // TODO 需要确认如果不用 $vm ,其他平台会不会出错 - let _self = page.$vm; - - if (getPlatformName() === 'bd') { - return _self.$mp && _self.$mp.page.is - } else { - return _self.route || (_self.$scope && _self.$scope.route) - } -}; - -const getPageRoute = (_this) => { - let pageVm = _this.self; - let page = pageVm.$page || pageVm.$scope.$page; - return page.fullPath === '/' ? page.route : page.fullPath -}; - -const getPageTypes = (self) => { - if ( - self.$mpType === 'page' || - (self.$mp && self.$mp.mpType === 'page') || - self.$options.mpType === 'page' - ) { - return true - } - return false -}; - -const calibration = (eventName, options) => { - // login 、 share 、pay_success 、pay_fail 、register 、title - if (!eventName) { - console.error(`uni.report 缺少 [eventName] 参数`); - return true - } - if (typeof eventName !== 'string') { - console.error(`uni.report [eventName] 参数类型错误,只能为 String 类型`); - return true - } - if (eventName.length > 255) { - console.error(`uni.report [eventName] 参数长度不能大于 255`); - return true - } - - if (typeof options !== 'string' && typeof options !== 'object') { - console.error( - `uni.report [options] 参数类型错误,只能为 String 或 Object 类型` - ); - return true - } - - if (typeof options === 'string' && options.length > 255) { - console.error(`uni.report [options] 参数长度不能大于 255`); - return true - } - - if (eventName === 'title' && typeof options !== 'string') { - console.error( - 'uni.report [eventName] 参数为 title 时,[options] 参数只能为 String 类型' - ); - return true - } -}; - -const Report_Data_Time = 'Report_Data_Time'; -const Report_Status = 'Report_Status'; -const isReportData = () => { - return new Promise((resolve, reject) => { - let start_time = ''; - let end_time = new Date().getTime(); - let diff_time = DIFF_TIME; - let report_status = 1; - try { - start_time = uni.getStorageSync(Report_Data_Time); - report_status = uni.getStorageSync(Report_Status); - } catch (e) { - start_time = ''; - report_status = 1; - } - - if (report_status === '') { - requestData(({ enable }) => { - uni.setStorageSync(Report_Data_Time, end_time); - uni.setStorageSync(Report_Status, enable); - if (enable === 1) { - resolve(); - } - }); - return - } - - if (report_status === 1) { - resolve(); - } - - if (!start_time) { - uni.setStorageSync(Report_Data_Time, end_time); - start_time = end_time; - } - - if (end_time - start_time > diff_time) { - requestData(({ enable }) => { - uni.setStorageSync(Report_Data_Time, end_time); - uni.setStorageSync(Report_Status, enable); - }); - } - }) -}; - -const requestData = (done) => { - let formData = { - usv: STAT_VERSION, - conf: JSON.stringify({ - ak: statConfig$1.appid, - }), - }; - uni.request({ - url: STAT_URL, - method: 'GET', - data: formData, - success: (res) => { - const { data } = res; - if (data.ret === 0) { - typeof done === 'function' && - done({ - enable: data.enable, - }); - } - }, - fail: (e) => { - let report_status_code = 1; - try { - report_status_code = uni.getStorageSync(Report_Status); - } catch (e) { - report_status_code = 1; - } - if (report_status_code === '') { - report_status_code = 1; - } - typeof done === 'function' && - done({ - enable: report_status_code, - }); - }, - }); -}; - -let titleJsons = {}; -// #ifdef MP -let pagesTitle = require('uni-pages?{"type":"style"}').default; -pagesTitle = pagesTitle.pages; -for (let i in pagesTitle) { - titleJsons[i] = pagesTitle[i].navigationBarTitleText || ''; -} -// #endif -// #ifndef MP -titleJsons = process.env.UNI_STAT_TITLE_JSON; -// #endif - -const statConfig = { - appid: process.env.UNI_APP_ID, -}; -const resultOptions = uni.getSystemInfoSync(); - -class Util { - constructor() { - this.self = ''; - this._retry = 0; - this._platform = ''; - this._query = {}; - this._navigationBarTitle = { - config: '', - page: '', - report: '', - lt: '', - }; - this._operatingTime = 0; - this._reportingRequestData = { - 1: [], - 11: [], - }; - this.__prevent_triggering = false; - - this.__licationHide = false; - this.__licationShow = false; - this._lastPageRoute = ''; - this.statData = { - uuid: getUuid(), - ut: getPlatformName(), - mpn: getPackName(), - ak: statConfig.appid, - usv: STAT_VERSION, - v: getVersion(), - ch: getChannel(), - cn: '', - pn: '', - ct: '', - t: getTime(), - tt: '', - p: resultOptions.platform === 'android' ? 'a' : 'i', - brand: resultOptions.brand || '', - md: resultOptions.model, - sv: resultOptions.system.replace(/(Android|iOS)\s/, ''), - mpsdk: resultOptions.SDKVersion || '', - mpv: resultOptions.version || '', - lang: resultOptions.language, - pr: resultOptions.pixelRatio, - ww: resultOptions.windowWidth, - wh: resultOptions.windowHeight, - sw: resultOptions.screenWidth, - sh: resultOptions.screenHeight, - }; - // 注册拦截器 - let registerInterceptor = - typeof uni.addInterceptor === 'function' && - process.env.NODE_ENV !== 'development'; - if (registerInterceptor) { - this.addInterceptorInit(); - this.interceptLogin(); - this.interceptShare(true); - this.interceptRequestPayment(); - } - } - - addInterceptorInit() { - let self = this; - uni.addInterceptor('setNavigationBarTitle', { - invoke(args) { - self._navigationBarTitle.page = args.title; - }, - }); - } - - interceptLogin() { - let self = this; - uni.addInterceptor('login', { - complete() { - self._login(); - }, - }); - } - - interceptShare(type) { - let self = this; - if (!type) { - self._share(); - return - } - uni.addInterceptor('share', { - success() { - self._share(); - }, - fail() { - self._share(); - }, - }); - } - - interceptRequestPayment() { - let self = this; - uni.addInterceptor('requestPayment', { - success() { - self._payment('pay_success'); - }, - fail() { - self._payment('pay_fail'); - }, - }); - } - - getIsReportData() { - return isReportData() - } - - _applicationShow() { - if (this.__licationHide) { - getLastTime(); - const time = getResidenceTime('app'); - if (time.overtime) { - let options = { - path: this._lastPageRoute, - scene: this.statData.sc, - }; - this._sendReportRequest(options); - } - this.__licationHide = false; - } - } - - _applicationHide(self, type) { - this.__licationHide = true; - getLastTime(); - const time = getResidenceTime(); - getFirstTime(); - const route = getPageRoute(this); - this._sendHideRequest( - { - urlref: route, - urlref_ts: time.residenceTime, - }, - type - ); - } - - _pageShow() { - const route = getPageRoute(this); - const routepath = getRoute(); - this._navigationBarTitle.config = - (titleJsons && titleJsons[routepath]) || ''; - if (this.__licationShow) { - getFirstTime(); - this.__licationShow = false; - this._lastPageRoute = route; - return - } - - getLastTime(); - const time = getResidenceTime('page'); - // 停留时间 - if (time.overtime) { - let options = { - path: route, - scene: this.statData.sc, - }; - this._sendReportRequest(options); - } - getFirstTime(); - } - - _pageHide() { - if (!this.__licationHide) { - getLastTime(); - const time = getResidenceTime('page'); - let route = getPageRoute(this); - if (!this._lastPageRoute) { - this._lastPageRoute = route; - } - this._sendPageRequest({ - url: route, - urlref: this._lastPageRoute, - urlref_ts: time.residenceTime, - }); - this._lastPageRoute = route; - this._navigationBarTitle = { - config: '', - page: '', - report: '', - lt: '', - }; - return - } - } - - _login() { - this._sendEventRequest( - { - key: 'login', - }, - 0 - ); - } - - _share() { - this._sendEventRequest( - { - key: 'share', - }, - 0 - ); - } - _payment(key) { - this._sendEventRequest( - { - key, - }, - 0 - ); - } - _sendReportRequest(options) { - this._navigationBarTitle.lt = '1'; - this._navigationBarTitle.config = - (titleJsons && titleJsons[options.path]) || ''; - let query = - options.query && JSON.stringify(options.query) !== '{}' - ? '?' + JSON.stringify(options.query) - : ''; - this.statData.lt = '1'; - this.statData.url = options.path + query || ''; - this.statData.t = getTime(); - this.statData.sc = getScene(options.scene); - this.statData.fvts = getFirstVisitTime(); - this.statData.lvts = getLastVisitTime(); - this.statData.tvc = getTotalVisitCount(); - if (getPlatformName() === 'n') { - this.getProperty(); - } else { - this.getNetworkInfo(); - } - } - - _sendPageRequest(opt) { - let { url, urlref, urlref_ts } = opt; - this._navigationBarTitle.lt = '11'; - let options = { - ak: this.statData.ak, - uuid: this.statData.uuid, - lt: '11', - ut: this.statData.ut, - url, - tt: this.statData.tt, - urlref, - urlref_ts, - ch: this.statData.ch, - usv: this.statData.usv, - t: getTime(), - p: this.statData.p, - }; - this.request(options); - } - - _sendHideRequest(opt, type) { - let { urlref, urlref_ts } = opt; - let options = { - ak: this.statData.ak, - uuid: this.statData.uuid, - lt: '3', - ut: this.statData.ut, - urlref, - urlref_ts, - ch: this.statData.ch, - usv: this.statData.usv, - t: getTime(), - p: this.statData.p, - }; - this.request(options, type); - } - _sendEventRequest({ key = '', value = '' } = {}) { - const route = this._lastPageRoute; - let options = { - ak: this.statData.ak, - uuid: this.statData.uuid, - lt: '21', - ut: this.statData.ut, - url: route, - ch: this.statData.ch, - e_n: key, - e_v: typeof value === 'object' ? JSON.stringify(value) : value.toString(), - usv: this.statData.usv, - t: getTime(), - p: this.statData.p, - }; - this.request(options); - } - - getNetworkInfo() { - uni.getNetworkType({ - success: (result) => { - this.statData.net = result.networkType; - this.getLocation(); - }, - }); - } - - getProperty() { - plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => { - this.statData.v = wgtinfo.version || ''; - this.getNetworkInfo(); - }); - } - - getLocation() { - { - this.statData.lat = 0; - this.statData.lng = 0; - this.request(this.statData); - } - } - - request(data, type) { - let time = getTime(); - const title = this._navigationBarTitle; - data.ttn = title.page; - data.ttpj = title.config; - data.ttc = title.report; - let requestData = this._reportingRequestData; - if (getPlatformName() === 'n') { - requestData = uni.getStorageSync('__UNI__STAT__DATA') || {}; - } - if (!requestData[data.lt]) { - requestData[data.lt] = []; - } - requestData[data.lt].push(data); - if (getPlatformName() === 'n') { - uni.setStorageSync('__UNI__STAT__DATA', requestData); - } - if (getPageResidenceTime() < OPERATING_TIME && !type) { - return - } - let uniStatData = this._reportingRequestData; - if (getPlatformName() === 'n') { - uniStatData = uni.getStorageSync('__UNI__STAT__DATA'); - } - // 时间超过,重新获取时间戳 - setPageResidenceTime(); - let firstArr = []; - let contentArr = []; - let lastArr = []; - - for (let i in uniStatData) { - const rd = uniStatData[i]; - rd.forEach((elm) => { - const newData = getSplicing(elm); - if (i === 0) { - firstArr.push(newData); - } else if (i === 3) { - lastArr.push(newData); - } else { - contentArr.push(newData); - } - }); - } - - firstArr.push(...contentArr, ...lastArr); - let optionsData = { - usv: STAT_VERSION, //统计 SDK 版本号 - t: time, //发送请求时的时间戮 - requests: JSON.stringify(firstArr), - }; - - this._reportingRequestData = {}; - if (getPlatformName() === 'n') { - uni.removeStorageSync('__UNI__STAT__DATA'); - } - - if (data.ut === 'h5') { - this.imageRequest(optionsData); - return - } - - if (getPlatformName() === 'n' && this.statData.p === 'a') { - setTimeout(() => { - this._sendRequest(optionsData); - }, 200); - return - } - this._sendRequest(optionsData); - } - _sendRequest(optionsData) { - this.getIsReportData().then(() => { - uni.request({ - url: STAT_URL, - method: 'POST', - data: optionsData, - success: () => {}, - fail: (e) => { - if (++this._retry < 3) { - setTimeout(() => { - this._sendRequest(optionsData); - }, 1000); - } - }, - }); - }); - } - /** - * h5 请求 - */ - imageRequest(data) { - this.getIsReportData().then(() => { - let image = new Image(); - let options = getSgin(GetEncodeURIComponentOptions(data)).options; - image.src = STAT_H5_URL + '?' + options; - }); - } - - sendEvent(key, value) { - // 校验 type 参数 - if (calibration(key, value)) return - - if (key === 'title') { - this._navigationBarTitle.report = value; - return - } - this._sendEventRequest( - { - key, - value: typeof value === 'object' ? JSON.stringify(value) : value, - }, - 1 - ); - } -} - -class Stat extends Util { - static getInstance() { - if (!this.instance) { - this.instance = new Stat(); - } - return this.instance - } - constructor() { - super(); - this.instance = null; - } - - report(options, self) { - // TODO 需要确认如果不用 $vm ,其他平台会不会出错 - setPageResidenceTime(); - this.__licationShow = true; - this._sendReportRequest(options, true); - } - - load(options, self) { - this.self = self; - this._query = options; - } - - show(self) { - this.self = self; - if (getPageTypes(self)) { - this._pageShow(self); - } else { - this._applicationShow(self); - } - } - ready(self) {} - hide(self) { - this.self = self; - if (getPageTypes(self)) { - this._pageHide(self); - } else { - this._applicationHide(self, true); - } - } - error(em) { - if (this._platform === 'devtools') { - if (process.env.NODE_ENV === 'development') { - console.info('当前运行环境为开发者工具,不上报数据。'); - } - } - let emVal = ''; - if (!em.message) { - emVal = JSON.stringify(em); - } else { - emVal = em.stack; - } - let options = { - ak: this.statData.ak, - uuid: this.statData.uuid, - lt: '31', - ut: this.statData.ut, - ch: this.statData.ch, - mpsdk: this.statData.mpsdk, - mpv: this.statData.mpv, - v: this.statData.v, - em: emVal, - usv: this.statData.usv, - t: getTime(), - p: this.statData.p, - }; - this.request(options); - } -} +let titleJsons = {}; +// #ifdef MP +let pagesTitle = require('uni-pages?{"type":"style"}').default; +pagesTitle = pagesTitle.pages; +for (let i in pagesTitle) { + titleJsons[i] = pagesTitle[i].navigationBarTitleText || ''; +} +// #endif +// #ifndef MP +titleJsons = process.env.UNI_STAT_TITLE_JSON; +// #endif + +const statConfig = { + appid: process.env.UNI_APP_ID, +}; +const resultOptions = uni.getSystemInfoSync(); + +class Util { + constructor() { + this.self = ''; + this._retry = 0; + this._platform = ''; + this._query = {}; + this._navigationBarTitle = { + config: '', + page: '', + report: '', + lt: '', + }; + this._operatingTime = 0; + this._reportingRequestData = { + 1: [], + 11: [], + }; + this.__prevent_triggering = false; + + this.__licationHide = false; + this.__licationShow = false; + this._lastPageRoute = ''; + this.statData = { + uuid: getUuid(), + ut: getPlatformName(), + mpn: getPackName(), + ak: statConfig.appid, + usv: STAT_VERSION, + v: getVersion(), + ch: getChannel(), + cn: '', + pn: '', + ct: '', + t: getTime(), + tt: '', + p: resultOptions.platform === 'android' ? 'a' : 'i', + brand: resultOptions.brand || '', + md: resultOptions.model, + sv: resultOptions.system.replace(/(Android|iOS)\s/, ''), + mpsdk: resultOptions.SDKVersion || '', + mpv: resultOptions.version || '', + lang: resultOptions.language, + pr: resultOptions.pixelRatio, + ww: resultOptions.windowWidth, + wh: resultOptions.windowHeight, + sw: resultOptions.screenWidth, + sh: resultOptions.screenHeight, + }; + // 注册拦截器 + let registerInterceptor = + typeof uni.addInterceptor === 'function' && + process.env.NODE_ENV !== 'development'; + if (registerInterceptor) { + this.addInterceptorInit(); + this.interceptLogin(); + this.interceptShare(true); + this.interceptRequestPayment(); + } + } + + addInterceptorInit() { + let self = this; + uni.addInterceptor('setNavigationBarTitle', { + invoke(args) { + self._navigationBarTitle.page = args.title; + }, + }); + } + + interceptLogin() { + let self = this; + uni.addInterceptor('login', { + complete() { + self._login(); + }, + }); + } + + interceptShare(type) { + let self = this; + if (!type) { + self._share(); + return + } + uni.addInterceptor('share', { + success() { + self._share(); + }, + fail() { + self._share(); + }, + }); + } + + interceptRequestPayment() { + let self = this; + uni.addInterceptor('requestPayment', { + success() { + self._payment('pay_success'); + }, + fail() { + self._payment('pay_fail'); + }, + }); + } + + getIsReportData() { + return isReportData() + } + + _applicationShow() { + if (this.__licationHide) { + getLastTime(); + const time = getResidenceTime('app'); + if (time.overtime) { + let options = { + path: this._lastPageRoute, + scene: this.statData.sc, + }; + this._sendReportRequest(options); + } + this.__licationHide = false; + } + } + + _applicationHide(self, type) { + this.__licationHide = true; + getLastTime(); + const time = getResidenceTime(); + getFirstTime(); + const route = getPageRoute(this); + this._sendHideRequest( + { + urlref: route, + urlref_ts: time.residenceTime, + }, + type + ); + } + + _pageShow() { + const route = getPageRoute(this); + const routepath = getRoute(); + this._navigationBarTitle.config = + (titleJsons && titleJsons[routepath]) || ''; + if (this.__licationShow) { + getFirstTime(); + this.__licationShow = false; + this._lastPageRoute = route; + return + } + + getLastTime(); + const time = getResidenceTime('page'); + // 停留时间 + if (time.overtime) { + let options = { + path: route, + scene: this.statData.sc, + }; + this._sendReportRequest(options); + } + getFirstTime(); + } + + _pageHide() { + if (!this.__licationHide) { + getLastTime(); + const time = getResidenceTime('page'); + let route = getPageRoute(this); + if (!this._lastPageRoute) { + this._lastPageRoute = route; + } + this._sendPageRequest({ + url: route, + urlref: this._lastPageRoute, + urlref_ts: time.residenceTime, + }); + this._lastPageRoute = route; + this._navigationBarTitle = { + config: '', + page: '', + report: '', + lt: '', + }; + return + } + } + + _login() { + this._sendEventRequest( + { + key: 'login', + }, + 0 + ); + } + + _share() { + this._sendEventRequest( + { + key: 'share', + }, + 0 + ); + } + _payment(key) { + this._sendEventRequest( + { + key, + }, + 0 + ); + } + _sendReportRequest(options) { + this._navigationBarTitle.lt = '1'; + this._navigationBarTitle.config = + (titleJsons && titleJsons[options.path]) || ''; + let query = + options.query && JSON.stringify(options.query) !== '{}' + ? '?' + JSON.stringify(options.query) + : ''; + this.statData.lt = '1'; + this.statData.url = options.path + query || ''; + this.statData.t = getTime(); + this.statData.sc = getScene(options.scene); + this.statData.fvts = getFirstVisitTime(); + this.statData.lvts = getLastVisitTime(); + this.statData.tvc = getTotalVisitCount(); + if (getPlatformName() === 'n') { + this.getProperty(); + } else { + this.getNetworkInfo(); + } + } + + _sendPageRequest(opt) { + let { url, urlref, urlref_ts } = opt; + this._navigationBarTitle.lt = '11'; + let options = { + ak: this.statData.ak, + uuid: this.statData.uuid, + lt: '11', + ut: this.statData.ut, + url, + tt: this.statData.tt, + urlref, + urlref_ts, + ch: this.statData.ch, + usv: this.statData.usv, + t: getTime(), + p: this.statData.p, + }; + this.request(options); + } + + _sendHideRequest(opt, type) { + let { urlref, urlref_ts } = opt; + let options = { + ak: this.statData.ak, + uuid: this.statData.uuid, + lt: '3', + ut: this.statData.ut, + urlref, + urlref_ts, + ch: this.statData.ch, + usv: this.statData.usv, + t: getTime(), + p: this.statData.p, + }; + this.request(options, type); + } + _sendEventRequest({ key = '', value = '' } = {}) { + const route = this._lastPageRoute; + let options = { + ak: this.statData.ak, + uuid: this.statData.uuid, + lt: '21', + ut: this.statData.ut, + url: route, + ch: this.statData.ch, + e_n: key, + e_v: typeof value === 'object' ? JSON.stringify(value) : value.toString(), + usv: this.statData.usv, + t: getTime(), + p: this.statData.p, + }; + this.request(options); + } + + getNetworkInfo() { + uni.getNetworkType({ + success: (result) => { + this.statData.net = result.networkType; + this.getLocation(); + }, + }); + } + + getProperty() { + plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => { + this.statData.v = wgtinfo.version || ''; + this.getNetworkInfo(); + }); + } + + getLocation() { + { + this.statData.lat = 0; + this.statData.lng = 0; + this.request(this.statData); + } + } + + request(data, type) { + let time = getTime(); + const title = this._navigationBarTitle; + data.ttn = title.page; + data.ttpj = title.config; + data.ttc = title.report; + let requestData = this._reportingRequestData; + if (getPlatformName() === 'n') { + requestData = uni.getStorageSync('__UNI__STAT__DATA') || {}; + } + if (!requestData[data.lt]) { + requestData[data.lt] = []; + } + requestData[data.lt].push(data); + if (getPlatformName() === 'n') { + uni.setStorageSync('__UNI__STAT__DATA', requestData); + } + if (getPageResidenceTime() < OPERATING_TIME && !type) { + return + } + let uniStatData = this._reportingRequestData; + if (getPlatformName() === 'n') { + uniStatData = uni.getStorageSync('__UNI__STAT__DATA'); + } + // 时间超过,重新获取时间戳 + setPageResidenceTime(); + let firstArr = []; + let contentArr = []; + let lastArr = []; + + for (let i in uniStatData) { + const rd = uniStatData[i]; + rd.forEach((elm) => { + const newData = getSplicing(elm); + if (i === 0) { + firstArr.push(newData); + } else if (i === 3) { + lastArr.push(newData); + } else { + contentArr.push(newData); + } + }); + } + + firstArr.push(...contentArr, ...lastArr); + let optionsData = { + usv: STAT_VERSION, //统计 SDK 版本号 + t: time, //发送请求时的时间戮 + requests: JSON.stringify(firstArr), + }; + + this._reportingRequestData = {}; + if (getPlatformName() === 'n') { + uni.removeStorageSync('__UNI__STAT__DATA'); + } + + if (data.ut === 'h5') { + this.imageRequest(optionsData); + return + } + + if (getPlatformName() === 'n' && this.statData.p === 'a') { + setTimeout(() => { + this._sendRequest(optionsData); + }, 200); + return + } + this._sendRequest(optionsData); + } + _sendRequest(optionsData) { + this.getIsReportData().then(() => { + uni.request({ + url: STAT_URL, + method: 'POST', + data: optionsData, + success: () => {}, + fail: (e) => { + if (++this._retry < 3) { + setTimeout(() => { + this._sendRequest(optionsData); + }, 1000); + } + }, + }); + }); + } + /** + * h5 请求 + */ + imageRequest(data) { + this.getIsReportData().then(() => { + let image = new Image(); + let options = getSgin(GetEncodeURIComponentOptions(data)).options; + image.src = STAT_H5_URL + '?' + options; + }); + } + + sendEvent(key, value) { + // 校验 type 参数 + if (calibration(key, value)) return + + if (key === 'title') { + this._navigationBarTitle.report = value; + return + } + this._sendEventRequest( + { + key, + value: typeof value === 'object' ? JSON.stringify(value) : value, + }, + 1 + ); + } +} + +class Stat extends Util { + static getInstance() { + if (!this.instance) { + this.instance = new Stat(); + } + return this.instance + } + constructor() { + super(); + this.instance = null; + } + + report(options, self) { + // TODO 需要确认如果不用 $vm ,其他平台会不会出错 + setPageResidenceTime(); + this.__licationShow = true; + this._sendReportRequest(options, true); + } + + load(options, self) { + this.self = self; + this._query = options; + } + + show(self) { + this.self = self; + if (getPageTypes(self)) { + this._pageShow(self); + } else { + this._applicationShow(self); + } + } + ready(self) {} + hide(self) { + this.self = self; + if (getPageTypes(self)) { + this._pageHide(self); + } else { + this._applicationHide(self, true); + } + } + error(em) { + if (this._platform === 'devtools') { + if (process.env.NODE_ENV === 'development') { + console.info('当前运行环境为开发者工具,不上报数据。'); + } + } + let emVal = ''; + if (!em.message) { + emVal = JSON.stringify(em); + } else { + emVal = em.stack; + } + let options = { + ak: this.statData.ak, + uuid: this.statData.uuid, + lt: '31', + ut: this.statData.ut, + ch: this.statData.ch, + mpsdk: this.statData.mpsdk, + mpv: this.statData.mpv, + v: this.statData.v, + em: emVal, + usv: this.statData.usv, + t: getTime(), + p: this.statData.p, + }; + this.request(options); + } +} var Stat$1 = Stat; -const stat = Stat$1.getInstance(); -let isHide = false; -const lifecycle = { - onLaunch(options) { - stat.report(options, this); - }, - onReady() { - stat.ready(this); - }, - onLoad(options) { - stat.load(options, this); - // 重写分享,获取分享上报事件 - if (this.$scope && this.$scope.onShareAppMessage) { - let oldShareAppMessage = this.$scope.onShareAppMessage; - this.$scope.onShareAppMessage = function (options) { - stat.interceptShare(false); - return oldShareAppMessage.call(this, options) - }; - } - }, - onShow() { - isHide = false; - stat.show(this); - }, - onHide() { - isHide = true; - stat.hide(this); - }, - onUnload() { - if (isHide) { - isHide = false; - return - } - stat.hide(this); - }, - onError(e) { - stat.error(e); - }, -}; - -function main() { - if (process.env.NODE_ENV === 'development') { - uni.report = function (type, options) {}; - } else { - uni.onAppLaunch((options) => { - stat.report(options); - // 小程序平台此时也无法获取getApp,统一在options中传递一个app对象 - options.app.$vm.$.appContext.app.mixin(lifecycle); - uni.report = function (type, options) { - stat.sendEvent(type, options); - }; - }); - } -} - +const stat = Stat$1.getInstance(); +let isHide = false; +const lifecycle = { + onLaunch(options) { + stat.report(options, this); + }, + onReady() { + stat.ready(this); + }, + onLoad(options) { + stat.load(options, this); + // 重写分享,获取分享上报事件 + if (this.$scope && this.$scope.onShareAppMessage) { + let oldShareAppMessage = this.$scope.onShareAppMessage; + this.$scope.onShareAppMessage = function (options) { + stat.interceptShare(false); + return oldShareAppMessage.call(this, options) + }; + } + }, + onShow() { + isHide = false; + stat.show(this); + }, + onHide() { + isHide = true; + stat.hide(this); + }, + onUnload() { + if (isHide) { + isHide = false; + return + } + stat.hide(this); + }, + onError(e) { + stat.error(e); + }, +}; + +function main() { + if (process.env.NODE_ENV === 'development') { + uni.report = function (type, options) {}; + } else { + uni.onAppLaunch((options) => { + stat.report(options); + // 小程序平台此时也无法获取getApp,统一在options中传递一个app对象 + options.app.$vm.$.appContext.app.mixin(lifecycle); + uni.report = function (type, options) { + stat.sendEvent(type, options); + }; + }); + } +} + main(); diff --git a/packages/uni-stat/dist/uni-stat.es.js b/packages/uni-stat/dist/uni-stat.es.js index ae3e78e2d..a67be9175 100644 --- a/packages/uni-stat/dist/uni-stat.es.js +++ b/packages/uni-stat/dist/uni-stat.es.js @@ -8,952 +8,952 @@ const APP_PVER_TIME = 300; const OPERATING_TIME = 10; const DIFF_TIME = 60 * 1000 * 60 * 24; -const statConfig$1 = { - appid: process.env.UNI_APP_ID, +const statConfig$1 = { + appid: process.env.UNI_APP_ID, +}; +const UUID_KEY = '__DC_STAT_UUID'; +const UUID_VALUE = '__DC_UUID_VALUE'; + +function getUuid() { + let uuid = ''; + if (getPlatformName() === 'n') { + try { + uuid = plus.runtime.getDCloudId(); + } catch (e) { + uuid = ''; + } + return uuid + } + + try { + uuid = uni.getStorageSync(UUID_KEY); + } catch (e) { + uuid = UUID_VALUE; + } + + if (!uuid) { + uuid = Date.now() + '' + Math.floor(Math.random() * 1e7); + try { + uni.setStorageSync(UUID_KEY, uuid); + } catch (e) { + uni.setStorageSync(UUID_KEY, UUID_VALUE); + } + } + return uuid +} + +const getSgin = (statData) => { + let arr = Object.keys(statData); + let sortArr = arr.sort(); + let sgin = {}; + let sginStr = ''; + for (var i in sortArr) { + sgin[sortArr[i]] = statData[sortArr[i]]; + sginStr += sortArr[i] + '=' + statData[sortArr[i]] + '&'; + } + // const options = sginStr.substr(0, sginStr.length - 1) + // sginStr = sginStr.substr(0, sginStr.length - 1) + '&key=' + STAT_KEY; + // const si = crypto.createHash('md5').update(sginStr).digest('hex'); + return { + sign: '', + options: sginStr.substr(0, sginStr.length - 1), + } +}; + +const getSplicing = (data) => { + let str = ''; + for (var i in data) { + str += i + '=' + data[i] + '&'; + } + return str.substr(0, str.length - 1) +}; + +const getTime = () => { + return parseInt(new Date().getTime() / 1000) +}; + +const getPlatformName = () => { + const aliArr = ['y', 'a', 'p', 'mp-ali']; + const platformList = { + 'app-plus': 'n', + h5: 'h5', + 'mp-weixin': 'wx', + [aliArr.reverse().join('')]: 'ali', + 'mp-baidu': 'bd', + 'mp-toutiao': 'tt', + 'mp-qq': 'qq', + 'quickapp-native': 'qn', + 'mp-kuaishou': 'ks', + }; + return platformList[process.env.VUE_APP_PLATFORM] +}; + +const getPackName = () => { + let packName = ''; + if (getPlatformName() === 'wx' || getPlatformName() === 'qq') { + // 兼容微信小程序低版本基础库 + if (uni.canIUse('getAccountInfoSync')) { + packName = uni.getAccountInfoSync().miniProgram.appId || ''; + } + } + return packName +}; + +const getVersion = () => { + return getPlatformName() === 'n' ? plus.runtime.version : '' +}; + +const getChannel = () => { + const platformName = getPlatformName(); + let channel = ''; + if (platformName === 'n') { + channel = plus.runtime.channel; + } + return channel +}; + +const getScene = (options) => { + const platformName = getPlatformName(); + let scene = ''; + if (options) { + return options + } + if (platformName === 'wx') { + scene = uni.getLaunchOptionsSync().scene; + } + return scene +}; +const First__Visit__Time__KEY = 'First__Visit__Time'; +const Last__Visit__Time__KEY = 'Last__Visit__Time'; + +const getFirstVisitTime = () => { + const timeStorge = uni.getStorageSync(First__Visit__Time__KEY); + let time = 0; + if (timeStorge) { + time = timeStorge; + } else { + time = getTime(); + uni.setStorageSync(First__Visit__Time__KEY, time); + uni.removeStorageSync(Last__Visit__Time__KEY); + } + return time +}; + +const getLastVisitTime = () => { + const timeStorge = uni.getStorageSync(Last__Visit__Time__KEY); + let time = 0; + if (timeStorge) { + time = timeStorge; + } else { + time = ''; + } + uni.setStorageSync(Last__Visit__Time__KEY, getTime()); + return time +}; + +const PAGE_RESIDENCE_TIME = '__page__residence__time'; +let First_Page_residence_time = 0; +let Last_Page_residence_time = 0; + +const setPageResidenceTime = () => { + First_Page_residence_time = getTime(); + if (getPlatformName() === 'n') { + uni.setStorageSync(PAGE_RESIDENCE_TIME, getTime()); + } + return First_Page_residence_time +}; + +const getPageResidenceTime = () => { + Last_Page_residence_time = getTime(); + if (getPlatformName() === 'n') { + First_Page_residence_time = uni.getStorageSync(PAGE_RESIDENCE_TIME); + } + return Last_Page_residence_time - First_Page_residence_time +}; +const TOTAL__VISIT__COUNT = 'Total__Visit__Count'; +const getTotalVisitCount = () => { + const timeStorge = uni.getStorageSync(TOTAL__VISIT__COUNT); + let count = 1; + if (timeStorge) { + count = timeStorge; + count++; + } + uni.setStorageSync(TOTAL__VISIT__COUNT, count); + return count +}; + +const GetEncodeURIComponentOptions = (statData) => { + let data = {}; + for (let prop in statData) { + data[prop] = encodeURIComponent(statData[prop]); + } + return data +}; + +let Set__First__Time = 0; +let Set__Last__Time = 0; + +const getFirstTime = () => { + let time = new Date().getTime(); + Set__First__Time = time; + Set__Last__Time = 0; + return time +}; + +const getLastTime = () => { + let time = new Date().getTime(); + Set__Last__Time = time; + return time +}; + +const getResidenceTime = (type) => { + let residenceTime = 0; + if (Set__First__Time !== 0) { + residenceTime = Set__Last__Time - Set__First__Time; + } + + residenceTime = parseInt(residenceTime / 1000); + residenceTime = residenceTime < 1 ? 1 : residenceTime; + if (type === 'app') { + let overtime = residenceTime > APP_PVER_TIME ? true : false; + return { + residenceTime, + overtime, + } + } + if (type === 'page') { + let overtime = residenceTime > PAGE_PVER_TIME ? true : false; + return { + residenceTime, + overtime, + } + } + + return { + residenceTime, + } +}; + +const getRoute = () => { + var pages = getCurrentPages(); + var page = pages[pages.length - 1]; + if (!page) return '' + // TODO 需要确认如果不用 $vm ,其他平台会不会出错 + let _self = page.$vm; + + if (getPlatformName() === 'bd') { + return _self.$mp && _self.$mp.page.is + } else { + return _self.route || (_self.$scope && _self.$scope.route) + } +}; + +const getPageRoute = (_this) => { + let pageVm = _this.self; + let page = pageVm.$page || pageVm.$scope.$page; + return page.fullPath === '/' ? page.route : page.fullPath +}; + +const getPageTypes = (self) => { + if ( + self.$mpType === 'page' || + (self.$mp && self.$mp.mpType === 'page') || + self.$options.mpType === 'page' + ) { + return true + } + return false +}; + +const calibration = (eventName, options) => { + // login 、 share 、pay_success 、pay_fail 、register 、title + if (!eventName) { + console.error(`uni.report 缺少 [eventName] 参数`); + return true + } + if (typeof eventName !== 'string') { + console.error(`uni.report [eventName] 参数类型错误,只能为 String 类型`); + return true + } + if (eventName.length > 255) { + console.error(`uni.report [eventName] 参数长度不能大于 255`); + return true + } + + if (typeof options !== 'string' && typeof options !== 'object') { + console.error( + `uni.report [options] 参数类型错误,只能为 String 或 Object 类型` + ); + return true + } + + if (typeof options === 'string' && options.length > 255) { + console.error(`uni.report [options] 参数长度不能大于 255`); + return true + } + + if (eventName === 'title' && typeof options !== 'string') { + console.error( + 'uni.report [eventName] 参数为 title 时,[options] 参数只能为 String 类型' + ); + return true + } +}; + +const Report_Data_Time = 'Report_Data_Time'; +const Report_Status = 'Report_Status'; +const isReportData = () => { + return new Promise((resolve, reject) => { + let start_time = ''; + let end_time = new Date().getTime(); + let diff_time = DIFF_TIME; + let report_status = 1; + try { + start_time = uni.getStorageSync(Report_Data_Time); + report_status = uni.getStorageSync(Report_Status); + } catch (e) { + start_time = ''; + report_status = 1; + } + + if (report_status === '') { + requestData(({ enable }) => { + uni.setStorageSync(Report_Data_Time, end_time); + uni.setStorageSync(Report_Status, enable); + if (enable === 1) { + resolve(); + } + }); + return + } + + if (report_status === 1) { + resolve(); + } + + if (!start_time) { + uni.setStorageSync(Report_Data_Time, end_time); + start_time = end_time; + } + + if (end_time - start_time > diff_time) { + requestData(({ enable }) => { + uni.setStorageSync(Report_Data_Time, end_time); + uni.setStorageSync(Report_Status, enable); + }); + } + }) +}; + +const requestData = (done) => { + let formData = { + usv: STAT_VERSION, + conf: JSON.stringify({ + ak: statConfig$1.appid, + }), + }; + uni.request({ + url: STAT_URL, + method: 'GET', + data: formData, + success: (res) => { + const { data } = res; + if (data.ret === 0) { + typeof done === 'function' && + done({ + enable: data.enable, + }); + } + }, + fail: (e) => { + let report_status_code = 1; + try { + report_status_code = uni.getStorageSync(Report_Status); + } catch (e) { + report_status_code = 1; + } + if (report_status_code === '') { + report_status_code = 1; + } + typeof done === 'function' && + done({ + enable: report_status_code, + }); + }, + }); }; -const UUID_KEY = '__DC_STAT_UUID'; -const UUID_VALUE = '__DC_UUID_VALUE'; -function getUuid() { - let uuid = ''; - if (getPlatformName() === 'n') { - try { - uuid = plus.runtime.getDCloudId(); - } catch (e) { - uuid = ''; - } - return uuid - } - - try { - uuid = uni.getStorageSync(UUID_KEY); - } catch (e) { - uuid = UUID_VALUE; - } - - if (!uuid) { - uuid = Date.now() + '' + Math.floor(Math.random() * 1e7); - try { - uni.setStorageSync(UUID_KEY, uuid); - } catch (e) { - uni.setStorageSync(UUID_KEY, UUID_VALUE); - } - } - return uuid -} - -const getSgin = (statData) => { - let arr = Object.keys(statData); - let sortArr = arr.sort(); - let sgin = {}; - let sginStr = ''; - for (var i in sortArr) { - sgin[sortArr[i]] = statData[sortArr[i]]; - sginStr += sortArr[i] + '=' + statData[sortArr[i]] + '&'; - } - // const options = sginStr.substr(0, sginStr.length - 1) - // sginStr = sginStr.substr(0, sginStr.length - 1) + '&key=' + STAT_KEY; - // const si = crypto.createHash('md5').update(sginStr).digest('hex'); - return { - sign: '', - options: sginStr.substr(0, sginStr.length - 1), - } -}; - -const getSplicing = (data) => { - let str = ''; - for (var i in data) { - str += i + '=' + data[i] + '&'; - } - return str.substr(0, str.length - 1) -}; - -const getTime = () => { - return parseInt(new Date().getTime() / 1000) -}; - -const getPlatformName = () => { - const aliArr = ['y', 'a', 'p', 'mp-ali']; - const platformList = { - 'app-plus': 'n', - h5: 'h5', - 'mp-weixin': 'wx', - [aliArr.reverse().join('')]: 'ali', - 'mp-baidu': 'bd', - 'mp-toutiao': 'tt', - 'mp-qq': 'qq', - 'quickapp-native': 'qn', - 'mp-kuaishou': 'ks', - }; - return platformList[process.env.VUE_APP_PLATFORM] -}; - -const getPackName = () => { - let packName = ''; - if (getPlatformName() === 'wx' || getPlatformName() === 'qq') { - // 兼容微信小程序低版本基础库 - if (uni.canIUse('getAccountInfoSync')) { - packName = uni.getAccountInfoSync().miniProgram.appId || ''; - } - } - return packName -}; - -const getVersion = () => { - return getPlatformName() === 'n' ? plus.runtime.version : '' -}; - -const getChannel = () => { - const platformName = getPlatformName(); - let channel = ''; - if (platformName === 'n') { - channel = plus.runtime.channel; - } - return channel -}; - -const getScene = (options) => { - const platformName = getPlatformName(); - let scene = ''; - if (options) { - return options - } - if (platformName === 'wx') { - scene = uni.getLaunchOptionsSync().scene; - } - return scene -}; -const First__Visit__Time__KEY = 'First__Visit__Time'; -const Last__Visit__Time__KEY = 'Last__Visit__Time'; - -const getFirstVisitTime = () => { - const timeStorge = uni.getStorageSync(First__Visit__Time__KEY); - let time = 0; - if (timeStorge) { - time = timeStorge; - } else { - time = getTime(); - uni.setStorageSync(First__Visit__Time__KEY, time); - uni.removeStorageSync(Last__Visit__Time__KEY); - } - return time -}; - -const getLastVisitTime = () => { - const timeStorge = uni.getStorageSync(Last__Visit__Time__KEY); - let time = 0; - if (timeStorge) { - time = timeStorge; - } else { - time = ''; - } - uni.setStorageSync(Last__Visit__Time__KEY, getTime()); - return time -}; - -const PAGE_RESIDENCE_TIME = '__page__residence__time'; -let First_Page_residence_time = 0; -let Last_Page_residence_time = 0; - -const setPageResidenceTime = () => { - First_Page_residence_time = getTime(); - if (getPlatformName() === 'n') { - uni.setStorageSync(PAGE_RESIDENCE_TIME, getTime()); - } - return First_Page_residence_time -}; - -const getPageResidenceTime = () => { - Last_Page_residence_time = getTime(); - if (getPlatformName() === 'n') { - First_Page_residence_time = uni.getStorageSync(PAGE_RESIDENCE_TIME); - } - return Last_Page_residence_time - First_Page_residence_time -}; -const TOTAL__VISIT__COUNT = 'Total__Visit__Count'; -const getTotalVisitCount = () => { - const timeStorge = uni.getStorageSync(TOTAL__VISIT__COUNT); - let count = 1; - if (timeStorge) { - count = timeStorge; - count++; - } - uni.setStorageSync(TOTAL__VISIT__COUNT, count); - return count -}; - -const GetEncodeURIComponentOptions = (statData) => { - let data = {}; - for (let prop in statData) { - data[prop] = encodeURIComponent(statData[prop]); - } - return data -}; - -let Set__First__Time = 0; -let Set__Last__Time = 0; - -const getFirstTime = () => { - let time = new Date().getTime(); - Set__First__Time = time; - Set__Last__Time = 0; - return time -}; - -const getLastTime = () => { - let time = new Date().getTime(); - Set__Last__Time = time; - return time -}; - -const getResidenceTime = (type) => { - let residenceTime = 0; - if (Set__First__Time !== 0) { - residenceTime = Set__Last__Time - Set__First__Time; - } - - residenceTime = parseInt(residenceTime / 1000); - residenceTime = residenceTime < 1 ? 1 : residenceTime; - if (type === 'app') { - let overtime = residenceTime > APP_PVER_TIME ? true : false; - return { - residenceTime, - overtime, - } - } - if (type === 'page') { - let overtime = residenceTime > PAGE_PVER_TIME ? true : false; - return { - residenceTime, - overtime, - } - } - - return { - residenceTime, - } -}; - -const getRoute = () => { - var pages = getCurrentPages(); - var page = pages[pages.length - 1]; - if (!page) return '' - // TODO 需要确认如果不用 $vm ,其他平台会不会出错 - let _self = page.$vm; - - if (getPlatformName() === 'bd') { - return _self.$mp && _self.$mp.page.is - } else { - return _self.route || (_self.$scope && _self.$scope.route) - } -}; - -const getPageRoute = (_this) => { - let pageVm = _this.self; - let page = pageVm.$page || pageVm.$scope.$page; - return page.fullPath === '/' ? page.route : page.fullPath -}; - -const getPageTypes = (self) => { - if ( - self.$mpType === 'page' || - (self.$mp && self.$mp.mpType === 'page') || - self.$options.mpType === 'page' - ) { - return true - } - return false -}; - -const calibration = (eventName, options) => { - // login 、 share 、pay_success 、pay_fail 、register 、title - if (!eventName) { - console.error(`uni.report 缺少 [eventName] 参数`); - return true - } - if (typeof eventName !== 'string') { - console.error(`uni.report [eventName] 参数类型错误,只能为 String 类型`); - return true - } - if (eventName.length > 255) { - console.error(`uni.report [eventName] 参数长度不能大于 255`); - return true - } - - if (typeof options !== 'string' && typeof options !== 'object') { - console.error( - `uni.report [options] 参数类型错误,只能为 String 或 Object 类型` - ); - return true - } - - if (typeof options === 'string' && options.length > 255) { - console.error(`uni.report [options] 参数长度不能大于 255`); - return true - } - - if (eventName === 'title' && typeof options !== 'string') { - console.error( - 'uni.report [eventName] 参数为 title 时,[options] 参数只能为 String 类型' - ); - return true - } -}; - -const Report_Data_Time = 'Report_Data_Time'; -const Report_Status = 'Report_Status'; -const isReportData = () => { - return new Promise((resolve, reject) => { - let start_time = ''; - let end_time = new Date().getTime(); - let diff_time = DIFF_TIME; - let report_status = 1; - try { - start_time = uni.getStorageSync(Report_Data_Time); - report_status = uni.getStorageSync(Report_Status); - } catch (e) { - start_time = ''; - report_status = 1; - } - - if (report_status === '') { - requestData(({ enable }) => { - uni.setStorageSync(Report_Data_Time, end_time); - uni.setStorageSync(Report_Status, enable); - if (enable === 1) { - resolve(); - } - }); - return - } - - if (report_status === 1) { - resolve(); - } - - if (!start_time) { - uni.setStorageSync(Report_Data_Time, end_time); - start_time = end_time; - } - - if (end_time - start_time > diff_time) { - requestData(({ enable }) => { - uni.setStorageSync(Report_Data_Time, end_time); - uni.setStorageSync(Report_Status, enable); - }); - } - }) -}; - -const requestData = (done) => { - let formData = { - usv: STAT_VERSION, - conf: JSON.stringify({ - ak: statConfig$1.appid, - }), - }; - uni.request({ - url: STAT_URL, - method: 'GET', - data: formData, - success: (res) => { - const { data } = res; - if (data.ret === 0) { - typeof done === 'function' && - done({ - enable: data.enable, - }); - } - }, - fail: (e) => { - let report_status_code = 1; - try { - report_status_code = uni.getStorageSync(Report_Status); - } catch (e) { - report_status_code = 1; - } - if (report_status_code === '') { - report_status_code = 1; - } - typeof done === 'function' && - done({ - enable: report_status_code, - }); - }, - }); -}; - -let titleJsons = {}; -// #ifdef MP -let pagesTitle = require('uni-pages?{"type":"style"}').default; -pagesTitle = pagesTitle.pages; -for (let i in pagesTitle) { - titleJsons[i] = pagesTitle[i].navigationBarTitleText || ''; -} -// #endif -// #ifndef MP -titleJsons = process.env.UNI_STAT_TITLE_JSON; -// #endif - -const statConfig = { - appid: process.env.UNI_APP_ID, -}; -const resultOptions = uni.getSystemInfoSync(); - -class Util { - constructor() { - this.self = ''; - this._retry = 0; - this._platform = ''; - this._query = {}; - this._navigationBarTitle = { - config: '', - page: '', - report: '', - lt: '', - }; - this._operatingTime = 0; - this._reportingRequestData = { - 1: [], - 11: [], - }; - this.__prevent_triggering = false; - - this.__licationHide = false; - this.__licationShow = false; - this._lastPageRoute = ''; - this.statData = { - uuid: getUuid(), - ut: getPlatformName(), - mpn: getPackName(), - ak: statConfig.appid, - usv: STAT_VERSION, - v: getVersion(), - ch: getChannel(), - cn: '', - pn: '', - ct: '', - t: getTime(), - tt: '', - p: resultOptions.platform === 'android' ? 'a' : 'i', - brand: resultOptions.brand || '', - md: resultOptions.model, - sv: resultOptions.system.replace(/(Android|iOS)\s/, ''), - mpsdk: resultOptions.SDKVersion || '', - mpv: resultOptions.version || '', - lang: resultOptions.language, - pr: resultOptions.pixelRatio, - ww: resultOptions.windowWidth, - wh: resultOptions.windowHeight, - sw: resultOptions.screenWidth, - sh: resultOptions.screenHeight, - }; - // 注册拦截器 - let registerInterceptor = - typeof uni.addInterceptor === 'function' && - process.env.NODE_ENV !== 'development'; - if (registerInterceptor) { - this.addInterceptorInit(); - this.interceptLogin(); - this.interceptShare(true); - this.interceptRequestPayment(); - } - } - - addInterceptorInit() { - let self = this; - uni.addInterceptor('setNavigationBarTitle', { - invoke(args) { - self._navigationBarTitle.page = args.title; - }, - }); - } - - interceptLogin() { - let self = this; - uni.addInterceptor('login', { - complete() { - self._login(); - }, - }); - } - - interceptShare(type) { - let self = this; - if (!type) { - self._share(); - return - } - uni.addInterceptor('share', { - success() { - self._share(); - }, - fail() { - self._share(); - }, - }); - } - - interceptRequestPayment() { - let self = this; - uni.addInterceptor('requestPayment', { - success() { - self._payment('pay_success'); - }, - fail() { - self._payment('pay_fail'); - }, - }); - } - - getIsReportData() { - return isReportData() - } - - _applicationShow() { - if (this.__licationHide) { - getLastTime(); - const time = getResidenceTime('app'); - if (time.overtime) { - let options = { - path: this._lastPageRoute, - scene: this.statData.sc, - }; - this._sendReportRequest(options); - } - this.__licationHide = false; - } - } - - _applicationHide(self, type) { - this.__licationHide = true; - getLastTime(); - const time = getResidenceTime(); - getFirstTime(); - const route = getPageRoute(this); - this._sendHideRequest( - { - urlref: route, - urlref_ts: time.residenceTime, - }, - type - ); - } - - _pageShow() { - const route = getPageRoute(this); - const routepath = getRoute(); - this._navigationBarTitle.config = - (titleJsons && titleJsons[routepath]) || ''; - if (this.__licationShow) { - getFirstTime(); - this.__licationShow = false; - this._lastPageRoute = route; - return - } - - getLastTime(); - const time = getResidenceTime('page'); - // 停留时间 - if (time.overtime) { - let options = { - path: route, - scene: this.statData.sc, - }; - this._sendReportRequest(options); - } - getFirstTime(); - } - - _pageHide() { - if (!this.__licationHide) { - getLastTime(); - const time = getResidenceTime('page'); - let route = getPageRoute(this); - if (!this._lastPageRoute) { - this._lastPageRoute = route; - } - this._sendPageRequest({ - url: route, - urlref: this._lastPageRoute, - urlref_ts: time.residenceTime, - }); - this._lastPageRoute = route; - this._navigationBarTitle = { - config: '', - page: '', - report: '', - lt: '', - }; - return - } - } - - _login() { - this._sendEventRequest( - { - key: 'login', - }, - 0 - ); - } - - _share() { - this._sendEventRequest( - { - key: 'share', - }, - 0 - ); - } - _payment(key) { - this._sendEventRequest( - { - key, - }, - 0 - ); - } - _sendReportRequest(options) { - this._navigationBarTitle.lt = '1'; - this._navigationBarTitle.config = - (titleJsons && titleJsons[options.path]) || ''; - let query = - options.query && JSON.stringify(options.query) !== '{}' - ? '?' + JSON.stringify(options.query) - : ''; - this.statData.lt = '1'; - this.statData.url = options.path + query || ''; - this.statData.t = getTime(); - this.statData.sc = getScene(options.scene); - this.statData.fvts = getFirstVisitTime(); - this.statData.lvts = getLastVisitTime(); - this.statData.tvc = getTotalVisitCount(); - if (getPlatformName() === 'n') { - this.getProperty(); - } else { - this.getNetworkInfo(); - } - } - - _sendPageRequest(opt) { - let { url, urlref, urlref_ts } = opt; - this._navigationBarTitle.lt = '11'; - let options = { - ak: this.statData.ak, - uuid: this.statData.uuid, - lt: '11', - ut: this.statData.ut, - url, - tt: this.statData.tt, - urlref, - urlref_ts, - ch: this.statData.ch, - usv: this.statData.usv, - t: getTime(), - p: this.statData.p, - }; - this.request(options); - } - - _sendHideRequest(opt, type) { - let { urlref, urlref_ts } = opt; - let options = { - ak: this.statData.ak, - uuid: this.statData.uuid, - lt: '3', - ut: this.statData.ut, - urlref, - urlref_ts, - ch: this.statData.ch, - usv: this.statData.usv, - t: getTime(), - p: this.statData.p, - }; - this.request(options, type); - } - _sendEventRequest({ key = '', value = '' } = {}) { - const route = this._lastPageRoute; - let options = { - ak: this.statData.ak, - uuid: this.statData.uuid, - lt: '21', - ut: this.statData.ut, - url: route, - ch: this.statData.ch, - e_n: key, - e_v: typeof value === 'object' ? JSON.stringify(value) : value.toString(), - usv: this.statData.usv, - t: getTime(), - p: this.statData.p, - }; - this.request(options); - } - - getNetworkInfo() { - uni.getNetworkType({ - success: (result) => { - this.statData.net = result.networkType; - this.getLocation(); - }, - }); - } - - getProperty() { - plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => { - this.statData.v = wgtinfo.version || ''; - this.getNetworkInfo(); - }); - } - - getLocation() { - { - this.statData.lat = 0; - this.statData.lng = 0; - this.request(this.statData); - } - } - - request(data, type) { - let time = getTime(); - const title = this._navigationBarTitle; - data.ttn = title.page; - data.ttpj = title.config; - data.ttc = title.report; - let requestData = this._reportingRequestData; - if (getPlatformName() === 'n') { - requestData = uni.getStorageSync('__UNI__STAT__DATA') || {}; - } - if (!requestData[data.lt]) { - requestData[data.lt] = []; - } - requestData[data.lt].push(data); - if (getPlatformName() === 'n') { - uni.setStorageSync('__UNI__STAT__DATA', requestData); - } - if (getPageResidenceTime() < OPERATING_TIME && !type) { - return - } - let uniStatData = this._reportingRequestData; - if (getPlatformName() === 'n') { - uniStatData = uni.getStorageSync('__UNI__STAT__DATA'); - } - // 时间超过,重新获取时间戳 - setPageResidenceTime(); - let firstArr = []; - let contentArr = []; - let lastArr = []; - - for (let i in uniStatData) { - const rd = uniStatData[i]; - rd.forEach((elm) => { - const newData = getSplicing(elm); - if (i === 0) { - firstArr.push(newData); - } else if (i === 3) { - lastArr.push(newData); - } else { - contentArr.push(newData); - } - }); - } - - firstArr.push(...contentArr, ...lastArr); - let optionsData = { - usv: STAT_VERSION, //统计 SDK 版本号 - t: time, //发送请求时的时间戮 - requests: JSON.stringify(firstArr), - }; - - this._reportingRequestData = {}; - if (getPlatformName() === 'n') { - uni.removeStorageSync('__UNI__STAT__DATA'); - } - - if (data.ut === 'h5') { - this.imageRequest(optionsData); - return - } - - if (getPlatformName() === 'n' && this.statData.p === 'a') { - setTimeout(() => { - this._sendRequest(optionsData); - }, 200); - return - } - this._sendRequest(optionsData); - } - _sendRequest(optionsData) { - this.getIsReportData().then(() => { - uni.request({ - url: STAT_URL, - method: 'POST', - data: optionsData, - success: () => {}, - fail: (e) => { - if (++this._retry < 3) { - setTimeout(() => { - this._sendRequest(optionsData); - }, 1000); - } - }, - }); - }); - } - /** - * h5 请求 - */ - imageRequest(data) { - this.getIsReportData().then(() => { - let image = new Image(); - let options = getSgin(GetEncodeURIComponentOptions(data)).options; - image.src = STAT_H5_URL + '?' + options; - }); - } - - sendEvent(key, value) { - // 校验 type 参数 - if (calibration(key, value)) return - - if (key === 'title') { - this._navigationBarTitle.report = value; - return - } - this._sendEventRequest( - { - key, - value: typeof value === 'object' ? JSON.stringify(value) : value, - }, - 1 - ); - } -} - -class Stat extends Util { - static getInstance() { - if (!this.instance) { - this.instance = new Stat(); - } - return this.instance - } - constructor() { - super(); - this.instance = null; - } - - report(options, self) { - // TODO 需要确认如果不用 $vm ,其他平台会不会出错 - setPageResidenceTime(); - this.__licationShow = true; - this._sendReportRequest(options, true); - } - - load(options, self) { - this.self = self; - this._query = options; - } - - show(self) { - this.self = self; - if (getPageTypes(self)) { - this._pageShow(self); - } else { - this._applicationShow(self); - } - } - ready(self) {} - hide(self) { - this.self = self; - if (getPageTypes(self)) { - this._pageHide(self); - } else { - this._applicationHide(self, true); - } - } - error(em) { - if (this._platform === 'devtools') { - if (process.env.NODE_ENV === 'development') { - console.info('当前运行环境为开发者工具,不上报数据。'); - } - } - let emVal = ''; - if (!em.message) { - emVal = JSON.stringify(em); - } else { - emVal = em.stack; - } - let options = { - ak: this.statData.ak, - uuid: this.statData.uuid, - lt: '31', - ut: this.statData.ut, - ch: this.statData.ch, - mpsdk: this.statData.mpsdk, - mpv: this.statData.mpv, - v: this.statData.v, - em: emVal, - usv: this.statData.usv, - t: getTime(), - p: this.statData.p, - }; - this.request(options); - } -} +let titleJsons = {}; +// #ifdef MP +let pagesTitle = require('uni-pages?{"type":"style"}').default; +pagesTitle = pagesTitle.pages; +for (let i in pagesTitle) { + titleJsons[i] = pagesTitle[i].navigationBarTitleText || ''; +} +// #endif +// #ifndef MP +titleJsons = process.env.UNI_STAT_TITLE_JSON; +// #endif + +const statConfig = { + appid: process.env.UNI_APP_ID, +}; +const resultOptions = uni.getSystemInfoSync(); + +class Util { + constructor() { + this.self = ''; + this._retry = 0; + this._platform = ''; + this._query = {}; + this._navigationBarTitle = { + config: '', + page: '', + report: '', + lt: '', + }; + this._operatingTime = 0; + this._reportingRequestData = { + 1: [], + 11: [], + }; + this.__prevent_triggering = false; + + this.__licationHide = false; + this.__licationShow = false; + this._lastPageRoute = ''; + this.statData = { + uuid: getUuid(), + ut: getPlatformName(), + mpn: getPackName(), + ak: statConfig.appid, + usv: STAT_VERSION, + v: getVersion(), + ch: getChannel(), + cn: '', + pn: '', + ct: '', + t: getTime(), + tt: '', + p: resultOptions.platform === 'android' ? 'a' : 'i', + brand: resultOptions.brand || '', + md: resultOptions.model, + sv: resultOptions.system.replace(/(Android|iOS)\s/, ''), + mpsdk: resultOptions.SDKVersion || '', + mpv: resultOptions.version || '', + lang: resultOptions.language, + pr: resultOptions.pixelRatio, + ww: resultOptions.windowWidth, + wh: resultOptions.windowHeight, + sw: resultOptions.screenWidth, + sh: resultOptions.screenHeight, + }; + // 注册拦截器 + let registerInterceptor = + typeof uni.addInterceptor === 'function' && + process.env.NODE_ENV !== 'development'; + if (registerInterceptor) { + this.addInterceptorInit(); + this.interceptLogin(); + this.interceptShare(true); + this.interceptRequestPayment(); + } + } + + addInterceptorInit() { + let self = this; + uni.addInterceptor('setNavigationBarTitle', { + invoke(args) { + self._navigationBarTitle.page = args.title; + }, + }); + } + + interceptLogin() { + let self = this; + uni.addInterceptor('login', { + complete() { + self._login(); + }, + }); + } + + interceptShare(type) { + let self = this; + if (!type) { + self._share(); + return + } + uni.addInterceptor('share', { + success() { + self._share(); + }, + fail() { + self._share(); + }, + }); + } + + interceptRequestPayment() { + let self = this; + uni.addInterceptor('requestPayment', { + success() { + self._payment('pay_success'); + }, + fail() { + self._payment('pay_fail'); + }, + }); + } + + getIsReportData() { + return isReportData() + } + + _applicationShow() { + if (this.__licationHide) { + getLastTime(); + const time = getResidenceTime('app'); + if (time.overtime) { + let options = { + path: this._lastPageRoute, + scene: this.statData.sc, + }; + this._sendReportRequest(options); + } + this.__licationHide = false; + } + } + + _applicationHide(self, type) { + this.__licationHide = true; + getLastTime(); + const time = getResidenceTime(); + getFirstTime(); + const route = getPageRoute(this); + this._sendHideRequest( + { + urlref: route, + urlref_ts: time.residenceTime, + }, + type + ); + } + + _pageShow() { + const route = getPageRoute(this); + const routepath = getRoute(); + this._navigationBarTitle.config = + (titleJsons && titleJsons[routepath]) || ''; + if (this.__licationShow) { + getFirstTime(); + this.__licationShow = false; + this._lastPageRoute = route; + return + } + + getLastTime(); + const time = getResidenceTime('page'); + // 停留时间 + if (time.overtime) { + let options = { + path: route, + scene: this.statData.sc, + }; + this._sendReportRequest(options); + } + getFirstTime(); + } + + _pageHide() { + if (!this.__licationHide) { + getLastTime(); + const time = getResidenceTime('page'); + let route = getPageRoute(this); + if (!this._lastPageRoute) { + this._lastPageRoute = route; + } + this._sendPageRequest({ + url: route, + urlref: this._lastPageRoute, + urlref_ts: time.residenceTime, + }); + this._lastPageRoute = route; + this._navigationBarTitle = { + config: '', + page: '', + report: '', + lt: '', + }; + return + } + } + + _login() { + this._sendEventRequest( + { + key: 'login', + }, + 0 + ); + } + + _share() { + this._sendEventRequest( + { + key: 'share', + }, + 0 + ); + } + _payment(key) { + this._sendEventRequest( + { + key, + }, + 0 + ); + } + _sendReportRequest(options) { + this._navigationBarTitle.lt = '1'; + this._navigationBarTitle.config = + (titleJsons && titleJsons[options.path]) || ''; + let query = + options.query && JSON.stringify(options.query) !== '{}' + ? '?' + JSON.stringify(options.query) + : ''; + this.statData.lt = '1'; + this.statData.url = options.path + query || ''; + this.statData.t = getTime(); + this.statData.sc = getScene(options.scene); + this.statData.fvts = getFirstVisitTime(); + this.statData.lvts = getLastVisitTime(); + this.statData.tvc = getTotalVisitCount(); + if (getPlatformName() === 'n') { + this.getProperty(); + } else { + this.getNetworkInfo(); + } + } + + _sendPageRequest(opt) { + let { url, urlref, urlref_ts } = opt; + this._navigationBarTitle.lt = '11'; + let options = { + ak: this.statData.ak, + uuid: this.statData.uuid, + lt: '11', + ut: this.statData.ut, + url, + tt: this.statData.tt, + urlref, + urlref_ts, + ch: this.statData.ch, + usv: this.statData.usv, + t: getTime(), + p: this.statData.p, + }; + this.request(options); + } + + _sendHideRequest(opt, type) { + let { urlref, urlref_ts } = opt; + let options = { + ak: this.statData.ak, + uuid: this.statData.uuid, + lt: '3', + ut: this.statData.ut, + urlref, + urlref_ts, + ch: this.statData.ch, + usv: this.statData.usv, + t: getTime(), + p: this.statData.p, + }; + this.request(options, type); + } + _sendEventRequest({ key = '', value = '' } = {}) { + const route = this._lastPageRoute; + let options = { + ak: this.statData.ak, + uuid: this.statData.uuid, + lt: '21', + ut: this.statData.ut, + url: route, + ch: this.statData.ch, + e_n: key, + e_v: typeof value === 'object' ? JSON.stringify(value) : value.toString(), + usv: this.statData.usv, + t: getTime(), + p: this.statData.p, + }; + this.request(options); + } + + getNetworkInfo() { + uni.getNetworkType({ + success: (result) => { + this.statData.net = result.networkType; + this.getLocation(); + }, + }); + } + + getProperty() { + plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => { + this.statData.v = wgtinfo.version || ''; + this.getNetworkInfo(); + }); + } + + getLocation() { + { + this.statData.lat = 0; + this.statData.lng = 0; + this.request(this.statData); + } + } + + request(data, type) { + let time = getTime(); + const title = this._navigationBarTitle; + data.ttn = title.page; + data.ttpj = title.config; + data.ttc = title.report; + let requestData = this._reportingRequestData; + if (getPlatformName() === 'n') { + requestData = uni.getStorageSync('__UNI__STAT__DATA') || {}; + } + if (!requestData[data.lt]) { + requestData[data.lt] = []; + } + requestData[data.lt].push(data); + if (getPlatformName() === 'n') { + uni.setStorageSync('__UNI__STAT__DATA', requestData); + } + if (getPageResidenceTime() < OPERATING_TIME && !type) { + return + } + let uniStatData = this._reportingRequestData; + if (getPlatformName() === 'n') { + uniStatData = uni.getStorageSync('__UNI__STAT__DATA'); + } + // 时间超过,重新获取时间戳 + setPageResidenceTime(); + let firstArr = []; + let contentArr = []; + let lastArr = []; + + for (let i in uniStatData) { + const rd = uniStatData[i]; + rd.forEach((elm) => { + const newData = getSplicing(elm); + if (i === 0) { + firstArr.push(newData); + } else if (i === 3) { + lastArr.push(newData); + } else { + contentArr.push(newData); + } + }); + } + + firstArr.push(...contentArr, ...lastArr); + let optionsData = { + usv: STAT_VERSION, //统计 SDK 版本号 + t: time, //发送请求时的时间戮 + requests: JSON.stringify(firstArr), + }; + + this._reportingRequestData = {}; + if (getPlatformName() === 'n') { + uni.removeStorageSync('__UNI__STAT__DATA'); + } + + if (data.ut === 'h5') { + this.imageRequest(optionsData); + return + } + + if (getPlatformName() === 'n' && this.statData.p === 'a') { + setTimeout(() => { + this._sendRequest(optionsData); + }, 200); + return + } + this._sendRequest(optionsData); + } + _sendRequest(optionsData) { + this.getIsReportData().then(() => { + uni.request({ + url: STAT_URL, + method: 'POST', + data: optionsData, + success: () => {}, + fail: (e) => { + if (++this._retry < 3) { + setTimeout(() => { + this._sendRequest(optionsData); + }, 1000); + } + }, + }); + }); + } + /** + * h5 请求 + */ + imageRequest(data) { + this.getIsReportData().then(() => { + let image = new Image(); + let options = getSgin(GetEncodeURIComponentOptions(data)).options; + image.src = STAT_H5_URL + '?' + options; + }); + } + + sendEvent(key, value) { + // 校验 type 参数 + if (calibration(key, value)) return + + if (key === 'title') { + this._navigationBarTitle.report = value; + return + } + this._sendEventRequest( + { + key, + value: typeof value === 'object' ? JSON.stringify(value) : value, + }, + 1 + ); + } +} + +class Stat extends Util { + static getInstance() { + if (!this.instance) { + this.instance = new Stat(); + } + return this.instance + } + constructor() { + super(); + this.instance = null; + } + + report(options, self) { + // TODO 需要确认如果不用 $vm ,其他平台会不会出错 + setPageResidenceTime(); + this.__licationShow = true; + this._sendReportRequest(options, true); + } + + load(options, self) { + this.self = self; + this._query = options; + } + + show(self) { + this.self = self; + if (getPageTypes(self)) { + this._pageShow(self); + } else { + this._applicationShow(self); + } + } + ready(self) {} + hide(self) { + this.self = self; + if (getPageTypes(self)) { + this._pageHide(self); + } else { + this._applicationHide(self, true); + } + } + error(em) { + if (this._platform === 'devtools') { + if (process.env.NODE_ENV === 'development') { + console.info('当前运行环境为开发者工具,不上报数据。'); + } + } + let emVal = ''; + if (!em.message) { + emVal = JSON.stringify(em); + } else { + emVal = em.stack; + } + let options = { + ak: this.statData.ak, + uuid: this.statData.uuid, + lt: '31', + ut: this.statData.ut, + ch: this.statData.ch, + mpsdk: this.statData.mpsdk, + mpv: this.statData.mpv, + v: this.statData.v, + em: emVal, + usv: this.statData.usv, + t: getTime(), + p: this.statData.p, + }; + this.request(options); + } +} var Stat$1 = Stat; -const stat = Stat$1.getInstance(); -let isHide = false; -const lifecycle = { - onLaunch(options) { - stat.report(options, this); - }, - onReady() { - stat.ready(this); - }, - onLoad(options) { - stat.load(options, this); - // 重写分享,获取分享上报事件 - if (this.$scope && this.$scope.onShareAppMessage) { - let oldShareAppMessage = this.$scope.onShareAppMessage; - this.$scope.onShareAppMessage = function (options) { - stat.interceptShare(false); - return oldShareAppMessage.call(this, options) - }; - } - }, - onShow() { - isHide = false; - stat.show(this); - }, - onHide() { - isHide = true; - stat.hide(this); - }, - onUnload() { - if (isHide) { - isHide = false; - return - } - stat.hide(this); - }, - onError(e) { - stat.error(e); - }, -}; - -function main() { - if (process.env.NODE_ENV === 'development') { - uni.report = function (type, options) {}; - } else { - uni.onAppLaunch((options) => { - stat.report(options); - // 小程序平台此时也无法获取getApp,统一在options中传递一个app对象 - options.app.$vm.$.appContext.app.mixin(lifecycle); - uni.report = function (type, options) { - stat.sendEvent(type, options); - }; - }); - } -} - +const stat = Stat$1.getInstance(); +let isHide = false; +const lifecycle = { + onLaunch(options) { + stat.report(options, this); + }, + onReady() { + stat.ready(this); + }, + onLoad(options) { + stat.load(options, this); + // 重写分享,获取分享上报事件 + if (this.$scope && this.$scope.onShareAppMessage) { + let oldShareAppMessage = this.$scope.onShareAppMessage; + this.$scope.onShareAppMessage = function (options) { + stat.interceptShare(false); + return oldShareAppMessage.call(this, options) + }; + } + }, + onShow() { + isHide = false; + stat.show(this); + }, + onHide() { + isHide = true; + stat.hide(this); + }, + onUnload() { + if (isHide) { + isHide = false; + return + } + stat.hide(this); + }, + onError(e) { + stat.error(e); + }, +}; + +function main() { + if (process.env.NODE_ENV === 'development') { + uni.report = function (type, options) {}; + } else { + uni.onAppLaunch((options) => { + stat.report(options); + // 小程序平台此时也无法获取getApp,统一在options中传递一个app对象 + options.app.$vm.$.appContext.app.mixin(lifecycle); + uni.report = function (type, options) { + stat.sendEvent(type, options); + }; + }); + } +} + main(); diff --git a/yarn.lock b/yarn.lock index 7a6afc9bd..0be4e6911 100644 --- a/yarn.lock +++ b/yarn.lock @@ -922,10 +922,10 @@ resolved "https://registry.yarnpkg.com/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz#75a2e8b51cb758a7553d6804a5932d7aace75c39" integrity sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw== -"@dcloudio/types@2.5.8": - version "2.5.8" - resolved "https://registry.yarnpkg.com/@dcloudio/types/-/types-2.5.8.tgz#3aee4b179bb4c13877309dc0fe1ba4ca1ff7d3b0" - integrity sha512-H/6I+Ui2F/g/juepMrx3wx2jfOFI8sRlKlAxOMycR2o75/ghVIhJU6GW9hU1DYNActGsM5UhcdpZYLL0qXkr4Q== +"@dcloudio/types@2.5.9": + version "2.5.9" + resolved "https://registry.yarnpkg.com/@dcloudio/types/-/types-2.5.9.tgz#06365a3406b02006c76870474314e5c20f24137e" + integrity sha512-dLyZChtY7oZ+34MgWBCU/qAJufszn1XvVN9GXL5Yk2wk/s3vl4kbrB2YDG0pVCUn7cDPmmyRoknp38x/vSAKpQ== "@eslint/eslintrc@^0.4.3": version "0.4.3" -- GitLab