Commit bddcd94a by 岑成威

feat(devTools): 添加调试工具和页面统计功能

- 新增调试工具,支持 Vue2+Vue3 的跨平台调试
- 实现页面访问统计功能,记录访问次数和停留时长
- 引入多种日志上报机制,包括错误和运行日志
- 增强调试工具的界面和交互体验,支持气泡标签和拖动功能
- 更新文档以说明调试工具的使用和配置方法
1 parent 38e37589
Showing 97 changed files with 5001 additions and 0 deletions
......@@ -12,6 +12,7 @@ export default {
// #ifdef APP
const sys = uni.getSystemInfoSync();
console.log(`[App] 当前分辨率:${ sys.screenWidth } x ${ sys.screenHeight}`);
// globalStyle.pageOrientation=auto 允许旋转;手机在下方仍 lock 竖屏,Pad unlock FULL_SENSOR
applyScreenOrientationLock();
// #endif
console.log("App Launch");
......@@ -24,6 +25,10 @@ export default {
},
onShow () {
console.log("App Show");
// #ifdef APP
// 与 onLaunch 一致:手机每次回到前台再锁竖屏(auto 下易被系统/框架改回可旋转)
applyScreenOrientationLock();
// #endif
},
onHide () {
console.log("App Hide");
......
......@@ -9,6 +9,9 @@ import { computed, onMounted, onUnmounted, type Ref } from 'vue'
import { useLayout } from '@/composables/useLayout'
import { cssClassRef, updateResolutionConfig, useResolutionConfig } from '@/services/adapter'
import { layoutService } from '@/services/LayoutService.uts'
// #ifdef APP
import { reassertHandsetPortraitIfNeeded } from '@/utils/apply-orientation-lock.uts'
// #endif
const layout = useLayout()
const rawCssVars = (layout as UTSJSONObject)['cssVars'] as Ref<UTSJSONObject> | null
......@@ -45,6 +48,9 @@ function syncLayoutRootResolution(): void {
}
lastLayoutW = w
lastLayoutH = h
// #ifdef APP
reassertHandsetPortraitIfNeeded()
// #endif
layoutService.refreshScreenInfo()
updateResolutionConfig()
}
......
......@@ -6,6 +6,12 @@
- **缩放**:同模式下不同分辨率等比缩放,避免拉伸
- **计算**:App 启动时算一次,缓存供全局使用
## 屏幕方向(App)
- **`pages.json`**:已在 `globalStyle` 设置 **`pageOrientation": "auto"`**(Android 4.13+ 起生效)。若保持默认 `portrait`,仅调 `FULL_SENSOR` 往往仍无法横屏,因 **uni-app x 页面层**按竖屏约束。
- **本工程策略**:`App.onLaunch` / **`App.onShow`**:`applyScreenOrientationLock()`。**小屏手持机**:**非 `layoutService.isPadLikeDevice()`** 且长边 **&lt; 1024**(不依赖 `deviceType===phone`,避免厂商未上报导致从不锁屏)→ Android 使用 **`SENSOR_PORTRAIT`** + 多次补锁;**`LayoutRoot`** 在窗口 **宽>高** 时再调 `reassertHandsetPortraitIfNeeded()`。**Pad/大屏**:`unlockOrientation`(`FULL_SENSOR`)+ 延迟再 unlock。
- 布局分档(portrait / pad / desktop)仍由 `layoutService` 在 init 时根据 `getDeviceInfo` + 尺寸兜底计算,与上述「是否锁屏」独立。控制台 `[orientation-diag]`、`[orientation-lock]`、`[plus-screen]` 可排查。
## 使用方式
### 1. 页面使用布局变量
......
# UniDevTools - 调试工具
支持 Vue2+Vue3 的跨平台调试工具
> 文档&安装教程 https://dev.api0.cn/
当前版本:v3.8
更新日期:2025.5.5
let config = {
status: true, //调试工具总开关
route: "/devTools/page/index", // 调试页面的路由,不建议更改
bubble: { //调试弹窗气泡设置
status: true, // 气泡标签是否显示,生产环境建议关闭
text: "DevTools", // 气泡上展示的文字
color: "#ffffff", // 气泡文字颜色
bgColor: "rgba(250, 53, 52,0.7)", // 气泡背景颜色
},
// 注意: 以下配置不建议更改
pageStatistics: {// 页面统计开关
status: true, // 统计状态开关
size: 1024 * 100, // 缓存上限,单位byte
dayOnlineRowMax: 30, // 活跃数据缓存天数
},
console: { //console日志配置
status: true, //功能总开关
isOutput: true, //打印的日志是否对外输出到浏览器调试界面,建议在生产环境时关闭
cache: {
status: true, //是否启用本地缓存
size: 512 * 1024, //缓存上限,单位byte
rowSize: 1024 * 4,//单条记录缓存上限,单位byte
},
},
uniBus: { // uni event bus 监听设置
status: true,
cache: {
status: true,
size: 1024 * 512, // bus调用日志上限 byte
rowSize: 1024 * 10,
countMaxSize: 1024 * 10, // bus统计上限 byte
},
},
error: { //报错拦截配置
status: true,
cache: {
status: true,
size: 512 * 1024,
rowSize: 1024 * 4,
},
},
network: { //请求拦截配置
status: true,
cache: {
status: true,
size: 512 * 1024,
rowSize: 1024 * 4,
},
},
logs: { //运行日志
status: true,
cache: {
status: true,
size: 512 * 1024,
rowSize: 1024 * 4,
},
},
};
export default config;
\ No newline at end of file
<template>
<view
v-if="isMp && options && options.status && options.bubble.status"
class="mpDevBubble"
:style="{
left: `${tagConfig.x}px`,
top: `${tagConfig.y}px`,
'background-color': options.bubble.bgColor,
'box-shadow': `0px 0px 6px ${options.bubble.bgColor}`,
}"
@touchstart.stop="touchstart"
@touchmove.stop="touchmove"
@touchend.stop="touchend"
>
<text
class="mpDevBubbleText"
:style="{
color: options.bubble.color,
'font-size': '20rpx',
}"
>
{{ options.bubble.text }}
</text>
</view>
</template>
<script>
import devOptions from "../libs/devOptions";
let options = devOptions.getOptions();
let sysInfo = uni.getSystemInfoSync();
let tagConfig = uni.getStorageSync("devTools_tagConfig");
if (!tagConfig) {
tagConfig = {};
}
tagConfig = Object.assign(
{
x: sysInfo.screenWidth - 150,
y: sysInfo.screenHeight - 240,
},
tagConfig
);
// 拖动范围限制
let dragLimit = {
min: { x: 0, y: 0 },
max: {
x: sysInfo.screenWidth - 70,
y: sysInfo.screenHeight - 24,
},
};
tagConfig.x = Math.min(Math.max(tagConfig.x, dragLimit.min.x), dragLimit.max.x);
tagConfig.y = Math.min(Math.max(tagConfig.y, dragLimit.min.y), dragLimit.max.y);
let isTouch = false;
let touchStartPoint = {
clientX: 0,
clientY: 0,
tagX: tagConfig.x,
tagY: tagConfig.y,
hasMove: false,
};
let isMp = false;
// #ifdef MP
isMp = true;
// #endif
export default {
data() {
return {
isMp,
/**
* 标签参数
*/
options,
/**
* 标签坐标信息配置
*/
tagConfig,
};
},
mounted() {
// console.log("调试开始zzzzzzzzzzzzzzzz");
},
methods: {
touchstart(e) {
if (isTouch) return;
if (e.preventDefault) {
e.preventDefault();
}
let clientX = e.touches[0].clientX;
let clientY = e.touches[0].clientY;
touchStartPoint.clientX = clientX;
touchStartPoint.clientY = clientY;
touchStartPoint.tagX = tagConfig.x;
touchStartPoint.tagY = tagConfig.y;
touchStartPoint.hasMove = false;
isTouch = true;
},
touchmove(e) {
if (!isTouch) return;
if (e.preventDefault) {
e.preventDefault();
}
let clientX = e.touches[0].clientX;
let clientY = e.touches[0].clientY;
touchStartPoint.hasMove = true;
let offsetX = touchStartPoint.clientX - clientX;
let offsetY = touchStartPoint.clientY - clientY;
let tx = touchStartPoint.tagX - offsetX;
let ty = touchStartPoint.tagY - offsetY;
tx = Math.min(Math.max(tx, dragLimit.min.x), dragLimit.max.x);
ty = Math.min(Math.max(ty, dragLimit.min.y), dragLimit.max.y);
tagConfig.x = tx;
tagConfig.y = ty;
this.tagConfig.x = tx;
this.tagConfig.y = ty;
},
touchend(e) {
if (!isTouch) return;
if (e.preventDefault) {
e.preventDefault();
}
isTouch = false;
uni.setStorageSync("devTools_tagConfig", tagConfig);
if (!touchStartPoint.hasMove) {
let pages = getCurrentPages();
let route = options.route.substring(1, options.route.length - 2);
if (pages[pages.length - 1].route == route) {
// 已经处于debug页面,不响应点击事件
return;
}
this.$devTools.show();
}
},
},
};
</script>
<style lang="scss" scoped>
.mpDevBubble {
box-sizing: border-box;
position: fixed;
z-index: 9999999;
width: 70px;
height: 24px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 4px;
border-radius: 6px;
font-size: 10px;
}
</style>
/**
*! 创建h5页面上拖动的气泡标签
*/
function createH5Bubble(options, devTools) {
let tagConfig = localStorage.getItem("devTools_tagConfig");
if (!tagConfig) {
tagConfig = {}
} else {
tagConfig = JSON.parse(tagConfig)
}
tagConfig = Object.assign({
show: options.bubble.status,
x: window.innerWidth - 90,
y: window.innerHeight - 90,
}, tagConfig);
tagConfig.show = options.bubble.status;
// 拖动范围限制
let dragLimit = {
min: { x: 0, y: 0, },
max: {
x: window.innerWidth - 70,
y: window.innerHeight - 24,
}
}
tagConfig.x = Math.min(Math.max(tagConfig.x, dragLimit.min.x), dragLimit.max.x)
tagConfig.y = Math.min(Math.max(tagConfig.y, dragLimit.min.y), dragLimit.max.y)
let tag = document.createElement("div");
tag.style = `
box-sizing: border-box;
position: fixed;
z-index: 9999999;
left: ${tagConfig.x}px;
top: ${tagConfig.y}px;
width: 70px;
height: 24px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 4px;
border-radius: 6px;
background-color: ${options.bubble.bgColor};
color: ${options.bubble.color};
font-size: 10px;
cursor: grab;
box-shadow: 0px 0px 6px ${options.bubble.bgColor};
backdrop-filter: blur(1px);
`;
tag.innerHTML = options.bubble.text;
tag.setAttribute("id", "debugTag")
if (tagConfig.show) {
document.body.appendChild(tag)
}
/**
* 标签单击事件
*/
function tagClick() {
let pages = getCurrentPages()
let route = options.route.substring(1, options.route.length - 2);
if (pages[pages.length - 1].route == route) {
// 已经处于debug页面,不响应点击事件
return;
}
devTools.show()
}
let isTouch = false;
let touchStartPoint = {
clientX: 0,
clientY: 0,
tagX: tagConfig.x,
tagY: tagConfig.y,
hasMove: false,
}
function touchStart(e) {
if (isTouch) return;
if (e.preventDefault) {
e.preventDefault()
}
let clientX = e.clientX ? e.clientX : e.targetTouches[0].clientX;
let clientY = e.clientX ? e.clientY : e.targetTouches[0].clientY;
touchStartPoint.clientX = clientX;
touchStartPoint.clientY = clientY;
touchStartPoint.tagX = tagConfig.x;
touchStartPoint.tagY = tagConfig.y;
touchStartPoint.hasMove = false;
isTouch = true;
}
function touchMove(e) {
if (!isTouch) return;
if (e.preventDefault) {
e.preventDefault()
}
let clientX = e.clientX ? e.clientX : e.targetTouches[0].clientX;
let clientY = e.clientX ? e.clientY : e.targetTouches[0].clientY;
touchStartPoint.hasMove = true;
let offsetX = touchStartPoint.clientX - clientX;
let offsetY = touchStartPoint.clientY - clientY;
let tx = touchStartPoint.tagX - offsetX;
let ty = touchStartPoint.tagY - offsetY;
tx = Math.min(Math.max(tx, dragLimit.min.x), dragLimit.max.x)
ty = Math.min(Math.max(ty, dragLimit.min.y), dragLimit.max.y)
tag.style.left = `${tx}px`;
tag.style.top = `${ty}px`;
tagConfig.x = tx;
tagConfig.y = ty;
}
function touchEnd(e) {
if (!isTouch) return;
if (e.preventDefault) {
e.preventDefault()
}
isTouch = false;
localStorage.setItem("devTools_tagConfig", JSON.stringify(tagConfig))
if (!touchStartPoint.hasMove) {
tagClick()
}
}
tag.addEventListener("touchstart", touchStart)
tag.addEventListener("touchmove", touchMove)
tag.addEventListener("touchend", touchEnd)
tag.addEventListener("mousedown", touchStart)
document.addEventListener("mousemove", touchMove)
document.addEventListener("mouseup", touchEnd)
localStorage.setItem("devTools_tagConfig", JSON.stringify(tagConfig))
}
export default createH5Bubble;
\ No newline at end of file
import devOptions from "./devOptions"
/**
* dev工具缓存管理
*/
export default {
/**
* 存储的键开始名称
*/
cacheKey: "devTools_v3_",
options: null,
/**
* 临时缓存对象
*/
tempCache: {
errorReport: [],
logReport: [],
console: [],
request: [],
uniBus: [],
},
/**
* 临时数据存放
*/
tempData: {},
/**
* 向缓存内写入数据
*/
set(key, value) {
try {
if (['errorReport', 'logReport', 'console', 'request', 'uniBus'].indexOf(key) != -1) {
let setting = this.getLongListSetting(key)
if (!setting.status) return;
if (!setting.cache.status) {
// !不使用缓存
this.tempCache[key] = value;
return;
}
}
key = `${this.cacheKey}${key}`
// #ifdef APP-NVUE
let pages = getCurrentPages()
if (pages[pages.length - 1].route == "devTools/page/index") {
// devtools 页面直接走设置缓存
return uni.setStorageSync(key, value);
}
// #endif
this.tempData[key] = value;
} catch (error) {
console.log("devCache.set error", error);
}
},
/**
* 同步读取缓存数据
*/
get(key) {
try {
if (['errorReport', 'logReport', 'console', 'request', 'uniBus'].indexOf(key) != -1) {
let setting = this.getLongListSetting(key)
if (!setting.status) return [];
if (!setting.cache.status) {
// !不使用缓存
return this.tempCache[key];
}
}
key = `${this.cacheKey}${key}`
// #ifdef APP-NVUE
let pages = getCurrentPages()
if (pages[pages.length - 1].route == "devTools/page/index") {
// devtools 页面直接走设置缓存
return uni.getStorageSync(key);
}
// #endif
if (this.tempData.hasOwnProperty(key)) {
return this.tempData[key];
} else {
let value = uni.getStorageSync(key);
this.tempData[key] = value;
return value;
}
} catch (error) {
console.log("devCache.get error", error);
return "";
}
},
getLongListSetting(key) {
let optionsKey = {
errorReport: 'error',
logReport: 'logs',
console: 'console',
request: 'network',
uniBus: 'uniBus',
}
if (this.options) return this.options[optionsKey[key]];
this.options = devOptions.getOptions()
return this.options[optionsKey[key]];
},
/**
* 同步本地缓存
*/
syncLocalCache() {
let that = this;
setTimeout(() => {
try {
let waitSetKeys = Object.keys(that.tempData);
for (let i = 0; i < waitSetKeys.length; i++) {
const key = waitSetKeys[i];
uni.setStorage({
key,
data: that.tempData[key],
success() {
// console.log("set " + key + " success,length=" + that.tempData[key].length);
delete that.tempData[key];
}
});
}
} catch (error) {
console.log("devCache error: ", error);
}
setTimeout(() => {
that.syncLocalCache();
}, 500);
}, Math.round(Math.random() * 3 * 1000) + 2000);
},
}
import devCache from "./devCache";
/**
* 设置各端大小 kb
*/
const defSize = (h5, app, mp) => {
let r = 0;
// #ifdef H5
r = h5;
// #endif
// #ifdef MP
r = mp;
// #endif
// #ifdef APP-PLUS || APP-NVUE
r = app;
// #endif
return Math.ceil(r * 1024);
}
/**
* 获取配置
*/
export default {
/**
* 配置缓存key
*/
cacheKey: "options_v8",
/**
* 默认配置项
*/
defaultOptions: {
version: 3.81,
status: false, //调试工具总开关
route: "/devTools/page/index", // 调试页面的路由,不建议更改
bubble: { //调试弹窗气泡设置
status: false, // 气泡标签是否显示,生产环境建议关闭
text: "调试工具", // 气泡上展示的文字
color: "#ffffff", // 气泡文字颜色
bgColor: "rgba(250, 53, 52,0.7)", // 气泡背景颜色
},
console: {
status: true, // 开关
isOutput: true, //打印的日志是否对外输出到浏览器调试界面,建议在生产环境时开启
cache: {
status: true, //是否启用console缓存
size: defSize(512, 1024 * 2, 512),
rowSize: defSize(5.12, 20, 10),
},
},
error: {
status: true,
cache: {
status: true,
size: defSize(512, 1024 * 2, 512),
rowSize: defSize(5.12, 20, 10),
},
},
network: {
status: true,
cache: {
status: true,
size: defSize(512, 1024 * 2, 512),
rowSize: defSize(5.12, 20, 10),
},
},
logs: {
status: true,
cache: {
status: true,
size: defSize(512, 1024 * 2, 512),
rowSize: defSize(0.4, 0.4, 0.4),
},
},
// 页面统计开关
pageStatistics: {
status: true, // 统计状态开关
size: defSize(200, 1024 * 2, 512),
// #ifdef H5
dayOnlineRowMax: 30, // 日活跃时间的保存条数
// #endif
// #ifdef APP-PLUS || APP-NVUE
dayOnlineRowMax: 90, // 日活跃时间的保存条数
// #endif
// #ifdef MP-WEIXIN
dayOnlineRowMax: 60, // 日活跃时间的保存条数
// #endif
},
// uni event bus 监听设置
uniBus: {
status: true,
cache: {
status: true,
size: defSize(512, 1024 * 2, 512),
rowSize: defSize(5.12, 20, 10),
countMaxSize: defSize(512, 1024 * 2, 512), // bus统计上限 kb
},
},
},
/**
* 获取配置信息
*/
getOptions() {
try {
let options = devCache.get(this.cacheKey)
if (!options) {
return {
status: false, //默认关闭调试工具
}
}
let r = String(options.route)
// ! 增加 devRoute 参数
options.devRoute = r.substring(1, r.length)
return options;
} catch (error) {
console.log("devOptions.getOptions error: ", error);
return {
status: false, //默认关闭调试工具
}
}
},
/**
* 保存配置项
*/
setOptions(options) {
try {
if (!options) {
options = this.defaultOptions;
}
if (options.status) {
if (
!options.route
|| typeof options.route != "string"
|| options.route.indexOf("/") != 0
) {
return this.outputError(`devTools 调试工具配置出错: [route] 参数配置错误!`)
}
}
let data = deepMerge(this.defaultOptions, options)
devCache.set(this.cacheKey, data)
} catch (error) {
console.log("devOptions.setOptions error: ", error);
}
},
/**
* 弹出错误信息
*/
outputError(msg) {
console.log('%c' + msg, `
padding: 4px;
background-color: red;
color: #fff;
font-size: 15px;
`)
},
}
/**
* 深度合并对象
*/
function deepMerge(target, ...sources) {
try {
if (!sources.length) return target; // 如果没有源对象则直接返回目标对象
const source = sources[0];
for (let key in source) {
if (source.hasOwnProperty(key)) {
if (typeof source[key] === 'object' && typeof target[key] !== undefined) {
target[key] = deepMerge({}, target[key], source[key]); // 若属性值为对象类型且目标对象已存在该属性,则递归调用deepMerge函数进行合并
} else {
target[key] = source[key]; // 否则将源对象的属性赋值到目标对象上
}
}
}
return deepMerge(target, ...sources.slice(1)); // 处理完第一个源对象后再次调用deepMerge函数处理其他源对象
} catch (error) {
console.log("deepMerge error", error);
return {}
}
}
\ No newline at end of file
/**
* 绘制调试工具
*/
/**
* 入口文件
*/
function init(options, devTools) {
let sysInfo = uni.getSystemInfoSync()
let tagConfig = uni.getStorageSync("devTools_tagConfig");
if (!tagConfig) {
tagConfig = {}
}
tagConfig = Object.assign({
show: options.bubble.status,
x: sysInfo.screenWidth - 90,
y: sysInfo.screenHeight - 90,
}, tagConfig)
tagConfig.show = options.bubble.status;
// 拖动范围限制
let dragLimit = {
min: { x: 0, y: 0, },
max: {
x: sysInfo.screenWidth - 70,
y: sysInfo.screenHeight - 24,
}
}
let view = new plus.nativeObj.View('debugTag', {
top: tagConfig.y + 'px',
left: tagConfig.x + 'px',
height: '24px',
width: '70px',
backgroundColor: options.bubble.bgColor,
});
view.drawText(options.bubble.text, {}, {
size: '12px',
color: options.bubble.color,
weight: 'bold'
});
if (tagConfig.show) {
view.show();
}
let isTouch = false;
let touchStart = {
l: 0,
t: 0,
x: 0,
y: 0,
time: 0,
hasMove: false,
}
view.addEventListener("touchstart", (e) => {
isTouch = true;
touchStart.l = e.clientX;
touchStart.t = e.clientY;
touchStart.time = new Date().getTime();
touchStart.hasMove = false;
})
view.addEventListener("touchmove", (e) => {
if (!isTouch) return;
if (!touchStart.hasMove) {
touchStart.hasMove = true;
}
let x = e.screenX - touchStart.l;
let y = e.screenY - touchStart.t;
x = Math.min(Math.max(x, dragLimit.min.x), dragLimit.max.x)
y = Math.min(Math.max(y, dragLimit.min.y), dragLimit.max.y)
view.setStyle({
top: y + 'px',
left: x + 'px',
})
touchStart.x = x;
touchStart.y = y;
})
view.addEventListener("touchend", (e) => {
isTouch = false;
if (
!touchStart.hasMove
|| touchStart.time > (new Date().getTime() - 300)
) {// 单击事件
let pages = getCurrentPages()
let route = options.route.substring(1, options.route.length - 2);
if (pages[pages.length - 1].route == route) {
// 已经处于debug页面,不响应点击事件
return;
}
devTools.show()
} else { //拖拽结束事件
tagConfig.x = touchStart.x;
tagConfig.y = touchStart.y;
uni.setStorageSync("devTools_tagConfig", tagConfig)
}
})
uni.setStorageSync("devTools_tagConfig", tagConfig)
}
export default init;
\ No newline at end of file
import devCache from "./devCache";
import devOptions from "./devOptions";
import jsonCompress from "./jsonCompress";
/**
* ! vue报错捕获
*/
/**
* * vue错误日志上报
* @param {'ve'|'vw'|'oe'|'n'} type 错误类型
*/
function errorReport(msg, trace, type = "n") {
try {
if (!msg) return false;
if (msg instanceof Error) {
msg = msg.message;
}
let options = devOptions.getOptions()
if (!options.error.status) return;
let page = "未知";
try {
let pages = getCurrentPages()
let item = pages[pages.length - 1];
if (item && item.route) {
page = item.route;
}
} catch (error) { }
let logs = devCache.get("errorReport");
if (!logs) logs = [];
if (logs.length >= options.error.cache.rowMax) {
logs = logs.splice(0, options.error.cache.rowMax)
}
msg = String(msg)
msg = jsonCompress.compressObject(msg, options.error.cache.rowSize / 2)
trace = String(trace)
trace = jsonCompress.compressObject(trace, options.error.cache.rowSize / 2)
logs.unshift({
t: new Date().getTime(),
m: msg,
tr: trace,
p: page,
type,
});
console.error("__ignoreReport__", msg, trace)
logs = jsonCompress.compressArray(logs, "end", options.error.cache.size)
devCache.set("errorReport", logs)
} catch (error) {
console.log("errorReport error: ", error);
}
}
export default errorReport;
\ No newline at end of file
import devCache from "./devCache";
import devOptions from "./devOptions";
import jsonCompress from "./jsonCompress";
/**
* ! 运行日志提交工具
*/
/**
* 日志上报
*/
function logReport(msg) {
try {
if (!msg) return false;
let options = devOptions.getOptions()
if (!options.status) {
console.error("日志上报失败!dev工具未启用 msg:" + msg);
return;
}
if (!options.logs.status) {
console.error("日志上报失败!dev logs未启用 msg:" + msg);
return;
}
try {
let pages = getCurrentPages()
if (pages[pages.length - 1].route == options.devRoute) {
// 不记录调试工具报出的日志
return false;
}
} catch (error) { }
if (typeof msg == "object") {
try {
msg = JSON.stringify(msg)
} catch (error) {
msg = "logReport:error"
}
}
let log = {
t: new Date().getTime(),
m: "",
}
let logSize = jsonCompress.calculateStringByteSize(log)
msg = String(msg);
msg = jsonCompress.compressObject(msg, options.logs.cache.rowSize - logSize)
log.m = msg;
let logs = devCache.get("logReport");
if (!logs) logs = [];
logs.unshift(log);
logs = jsonCompress.compressArray(logs, "end", options.logs.cache.size)
devCache.set("logReport", logs)
} catch (error) {
console.log("logReport error", error);
}
}
export default logReport;
\ No newline at end of file
import devCache from "./devCache"
export default {
pageRouteMap: [],
pageRouteKeyMap: {},
/**
* 安装路径分析插件
*/
install() {
let allRoutes = this.getAllRoutes();
let pageRouteKeyMap = devCache.get("pageRouteKeyMap")
if (!pageRouteKeyMap || typeof pageRouteKeyMap != "object") {
pageRouteKeyMap = {}
}
let lastNo = 0;
Object.keys(pageRouteKeyMap).forEach((key) => {
let item = Number(pageRouteKeyMap[key])
if (item > lastNo) {
lastNo = item;
}
})
allRoutes.forEach(item => {
if (!pageRouteKeyMap[item.path]) {
pageRouteKeyMap[item.path] = lastNo + 1;
lastNo = lastNo + 1;
}
})
devCache.set("pageRouteKeyMap", pageRouteKeyMap)
this.pageRouteKeyMap = pageRouteKeyMap;
let pageRouteMap = devCache.get("pageRouteMap");
if (!pageRouteMap || typeof pageRouteMap != "object") {
pageRouteMap = {}
}
Object.keys(pageRouteMap).forEach((key) => {
try {
let n = Number(pageRouteMap[key]);
if (!Number.isInteger(n) || n < 0) {
pageRouteMap[key] = 1;
}
} catch (error) { }
})
this.pageRouteMap = pageRouteMap;
this.saveData()
},
/**
* 获取APP注册的所有路由
* @returns {{path: string}[]} 返回路由列表
*/
getAllRoutes() {
let pages = [];
// #ifdef H5 || APP-PLUS
try {
__uniRoutes.map((item) => {
let path = item.alias ? item.alias : item.path;
pages.push({ path })
});
} catch (error) {
pages = [];
}
// #endif
// #ifdef MP-WEIXIN
try {
let wxPages = __wxConfig.pages;
wxPages.map((item) => {
pages.push({
path: "/" + item,
})
});
} catch (error) {
pages = [];
}
// #endif
return pages;
},
/**
* 写入路由列表
*/
pushPageRouteMap(list = []) {
if (!list || list.length == 0) {
list = getCurrentPages()
}
let key = ""
list.forEach((item) => {
let path = item.route.indexOf("/") == 0 ? item.route : "/" + item.route;
let keyItem = this.pageRouteKeyMap[path];
if (!keyItem) {
keyItem = path;
}
if (key == "") {
key = keyItem + ""
} else {
key = key + "," + keyItem
}
})
if (this.pageRouteMap[key]) {
this.pageRouteMap[key] = this.pageRouteMap[key] + 1;
} else {
this.pageRouteMap[key] = 1;
}
},
/**
* 保存路由缓存
*/
saveData() {
let that = this;
setTimeout(() => {
devCache.set("pageRouteMap", that.pageRouteMap)
setTimeout(() => {
that.saveData()
}, 500);
}, Math.round(Math.random() * 3 * 1000) + 2000);
},
}
\ No newline at end of file
/**
* !页面统计:访问次数、停留时长
*/
import devCache from "./devCache"
import devOptions from "./devOptions";
import jsonCompress from "./jsonCompress";
import { timeFormat } from "./timeFormat";
/**
* 页面注销时提交
*/
function pageStatisticsReport(
route, activeTime,
) {
try {
if (!route) return false;
let options = devOptions.getOptions()
if (!options.pageStatistics.status) return; //! 配置文件关闭页面统计
let logs = devCache.get("pageCount");
if (!logs) logs = [];
let pageIndex = logs.findIndex(x => x.route == route)
if (pageIndex == -1) {
logs.push({
route,
activeTimeCount: activeTime,
})
} else {
logs[pageIndex].activeTimeCount = activeTime + logs[pageIndex].activeTimeCount;
}
logs = jsonCompress.compressArray(logs, "end", options.pageStatistics.size)
devCache.set("pageCount", logs)
let now = new Date().getTime();
let date = timeFormat(now, "yyyy-mm-dd");
let dayOnline = devCache.get("dayOnline");
if (!dayOnline) dayOnline = [];
let i = dayOnline.findIndex(x => x.date == date);
if (i == -1) {
dayOnline.unshift({
date,
activeTimeCount: activeTime,
page: [
{
r: route,
t: activeTime,
}
]
})
} else {
dayOnline[i].activeTimeCount = dayOnline[i].activeTimeCount + activeTime;
let pi = dayOnline[i].page.findIndex(x => x.r == route);
if (pi == -1) {
dayOnline[i].page.push({
r: route,
t: activeTime,
})
} else {
dayOnline[i].page[pi].t = dayOnline[i].page[pi].t + activeTime;
}
}
if (dayOnline.length > options.pageStatistics.dayOnlineRowMax) {
dayOnline = dayOnline.splice(0, options.pageStatistics.dayOnlineRowMax)
}
dayOnline = jsonCompress.compressArray(dayOnline, "end", options.pageStatistics.size)
devCache.set("dayOnline", dayOnline)
} catch (error) {
console.log("pageStatistics error", error);
}
}
export default pageStatisticsReport;
\ No newline at end of file
// padStart 的 polyfill,因为某些机型或情况,还无法支持es7的padStart,比如电脑版的微信小程序
// 所以这里做一个兼容polyfill的兼容处理
try {
if (!String.prototype.padStart) {
// 为了方便表示这里 fillString 用了ES6 的默认参数,不影响理解
String.prototype.padStart = function (maxLength, fillString = ' ') {
if (Object.prototype.toString.call(fillString) !== "[object String]") throw new TypeError(
'fillString must be String')
let str = this
// 返回 String(str) 这里是为了使返回的值是字符串字面量,在控制台中更符合直觉
if (str.length >= maxLength) return String(str)
let fillLength = maxLength - str.length,
times = Math.ceil(fillLength / fillString.length)
while (times >>= 1) {
fillString += fillString
if (times === 1) {
fillString += fillString
}
}
return fillString.slice(0, fillLength) + str;
}
}
} catch (error) {
console.log("timeFormat fillString error", error);
}
// 其他更多是格式化有如下:
// yyyy:mm:dd|yyyy:mm|yyyy年mm月dd日|yyyy年mm月dd日 hh时MM分等,可自定义组合
export function timeFormat(dateTime = null, fmt = 'yyyy-mm-dd hh:MM:ss') {
try {
// 如果为null,则格式化当前时间
if (!dateTime) dateTime = Number(new Date());
// 如果dateTime长度为10或者13,则为秒和毫秒的时间戳,如果超过13位,则为其他的时间格式
if (dateTime.toString().length == 10) dateTime *= 1000;
let date = new Date(dateTime);
let ret;
let opt = {
"y+": date.getFullYear().toString(), // 年
"m+": (date.getMonth() + 1).toString(), // 月
"d+": date.getDate().toString(), // 日
"h+": date.getHours().toString(), // 时
"M+": date.getMinutes().toString(), // 分
"s+": date.getSeconds().toString() // 秒
// 有其他格式化字符需求可以继续添加,必须转化成字符串
};
for (let k in opt) {
ret = new RegExp("(" + k + ")").exec(fmt);
if (ret) {
fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
};
};
return fmt;
} catch (error) {
console.log("timeFormat error", error);
return "unknown error"
}
}
export function timeFromNow(timestamp) {
try {
const now = new Date().getTime();
let diff = timestamp - now;
// 确定是过去还是未来
const suffix = diff > 0 ? "后" : "前";
diff = Math.abs(diff);
// 计算时间差异
const seconds = Math.floor(diff / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
const months = Math.floor(days / 30);
const years = Math.floor(days / 365);
// 根据时间差异返回相应的字符串
if (seconds < 60) {
return `${seconds}秒${suffix}`;
} else if (minutes < 60) {
return `${minutes}分钟${suffix}`;
} else if (hours < 24) {
return `${hours}小时${suffix}`;
} else if (days < 30) {
return `${days}天${suffix}`;
} else if (months < 12) {
return `${months}个月${suffix}`;
} else {
return `${years}年${suffix}`;
}
} catch (error) {
console.log("timeFromNow error", error);
}
}
\ No newline at end of file
import devCache from "../libs/devCache";
import console from "./console";
import request from "./request";
import storage from "./storage";
import uniBus from "./uniBus";
import uniListen from "./uniListen";
/**
* dev调试工具初始化
*/
export default function devToolsProxyInstall(options) {
try {
if (options.network && options.network.status) {
request.install()
}
if (options.console && options.console.status) {
console.install()
}
if (options.logs && options.logs.status) {
uniListen.install()
}
storage.install()
if (options.uniBus && options.uniBus.status) {
uniBus.install()
}
devCache.syncLocalCache();
} catch (error) {
console.log("devToolsProxyInstall error", error);
}
}
\ No newline at end of file
import devCache from "../libs/devCache";
import devOptions from "../libs/devOptions";
import jsonCompress from "../libs/jsonCompress";
export default {
/**
* 请求日志示例
*/
ajaxLogData: {
id: 0, //请求id
type: 0, // 0发起请求中 1请求成功 2请求失败
sendTime: 0, //发送请求的时间
responseTime: 0, //响应时间
useTime: 0, //请求总耗时
url: "", //请求地址
header: "", //请求头
method: "get", //请求方式
data: "", //请求参数
responseBody: "", //响应主体
responseHeader: "", //响应头
responseStatus: "", //响应编码
responseMsg: "", //响应报错信息
},
options: null,
/**
* 请求的数据列表
*/
ajaxData: [],
/**
* 挂载请求拦截器
*/
install() {
let that = this;
try {
this.options = devOptions.getOptions()
if (!this.options.network.status) return;
this.ajaxData = devCache.get("request");
if (!this.ajaxData) this.ajaxData = [];
this.syncReqData(); //同步缓存
uni.addInterceptor('request', {
/**
* 入参
*/
invoke(args) {
try {
args._id_ = new Date().getTime() + '_' + Number(Math.random().toString().replace("0.", ""));
let copyData = JSON.parse(JSON.stringify(that.ajaxLogData))
copyData.id = args._id_;
copyData.sendTime = new Date().getTime();
copyData.url = that.dataCopy(args.url);
copyData.header = that.dataCopy(args.header);
if (!args.method) {
copyData.method = "get"
} else {
copyData.method = that.dataCopy(args.method);
}
let cSize = jsonCompress.calculateStringByteSize(copyData)
if (cSize > that.options.network.cache.rowSize) {
copyData = jsonCompress.compressObject(copyData, that.options.network.cache.rowSize)
} else {
let data = jsonCompress.compressObject(args.data, that.options.network.cache.rowSize - cSize)
try {
data = JSON.parse(data)
} catch (error) { }
copyData.data = data;
}
that.ajaxData.unshift(copyData)
} catch (error) {
console.error("request拦截器invoke出错", error)
}
},
success(response, request) {
return new Promise(async (yes, err) => {
//! 延迟请求返回,模拟弱网环境
let speedLimit = uni.getStorageSync("devtools_uniResLimitType");
if (speedLimit) {
let delayDuration = {
"2g": [30, 60],
"3g-": [10, 30],
"3g": [3, 10],
"4g": [0.5, 3],
}
let sleepParam = delayDuration[speedLimit];
if (sleepParam) {
let sleepTime = rNum(sleepParam[0], sleepParam[1]);
await sleep(sleepTime * 1000)
response.errMsg = response.errMsg + ` | [devtools模拟弱网延迟:${sleepTime}s]`
}
}
// ! 随机响应失败概率
let resTimeout = uni.getStorageSync("devtools_uniResTimeout");
let isFail = false
if (resTimeout && resTimeout > 1) {
let targetPro = Number(resTimeout);
let randPro = rNum(0, 100);
if (randPro < targetPro) {
// 命中失败
response.statusCode = rNum(400, 600); //生成随机400 ~ 600之间的状态码
response.errMsg = response.errMsg + ` | [devtools随机超时报错,当前命中的概率阶层为:${targetPro}%,生成的随机数为:${randPro}]`
response.data = "[devTools]模拟请求失败结果!"
isFail = true
}
}
// ! 记录响应内容
try {
let item = that.ajaxData.find(x => x.id == request._id_);
if (!item) return;
item.responseBodySize = jsonCompress.calculateStringByteSize(response.data);
item.responseMsg = response.errMsg;
item.responseStatus = response.statusCode;
item.responseHeader = response.header;
item.type = 1;
item.responseTime = new Date().getTime();
item.useTime = ((item.responseTime - item.sendTime) / 1000).toFixed(3);
let size = jsonCompress.calculateStringByteSize(item)
if (size > that.options.network.cache.rowSize) {
item.responseBody = "[内容太长已截断多余部分]"
let data = jsonCompress.compressObject(item, that.options.network.cache.rowSize)
that.ajaxData[that.ajaxData.findIndex(x => x.id == request._id_)] = data;
} else {
let json = response.data;
try {
json = JSON.parse(JSON.stringify(json))
} catch (error) { }
item.responseBody = jsonCompress.compressObject(json, that.options.network.cache.rowSize - size)
}
} catch (error) {
console.error("request拦截器success出错", error)
}
if (isFail) {
err(response.data)
} else {
yes(response)
}
})
},
fail(err, request) {
try {
let item = that.ajaxData.find(x => x.id == request._id_);
if (!item) return;
item.type = 2;
item.responseTime = new Date().getTime();
item.useTime = ((item.responseTime - item.sendTime) / 1000).toFixed(3);
item.responseMsg = err.errMsg;
} catch (error) {
console.error("request拦截器fail出错", error)
}
},
complete(res) {
}
})
// ! 删除指定请求记录
uni.$on("devTools_delNetworkItemById", (id) => {
let i = this.ajaxData.findIndex(x => x.id == id)
if (i != -1) {
this.ajaxData.splice(i, 1)
}
this.saveData()
})
// ! 清空请求记录
uni.$on("devTools_delNetworkAll", () => {
this.ajaxData = []
this.saveData()
})
} catch (error) {
console.log("request.install error", error);
}
},
/**
* 同步请求信息到缓存数据中
*/
syncReqData() {
let that = this;
setTimeout(() => {
try {
that.saveData()
} catch (error) {
console.log("request.syncReqData", error);
}
that.syncReqData()
}, 4000);
},
/**
* 保存数据到缓存中
*/
saveData() {
let that = this;
that.ajaxData = jsonCompress.compressArray(that.ajaxData, that.options.network.cache.size)
devCache.set("request", that.ajaxData)
},
/**
* 复制对象
*/
dataCopy(data) {
try {
if (typeof data == "object") {
return JSON.parse(JSON.stringify([data]))[0]
} else {
return data;
}
} catch (error) {
console.log("request.dataCopy", error);
return ""
}
}
}
/**
* 随机生成n~m的数,支持两位小数
*/
function rNum(n, m) {
return Number((Math.random() * (m - n) + n).toFixed(2));
}
/**
* 休眠指定时长
*/
function sleep(t) {
return new Promise((y) => {
setTimeout(y, t);
})
}
\ No newline at end of file
import devCache from "../libs/devCache";
export default {
/**
* 挂载缓存监听
*/
install() {
try {
// #ifdef MP
let that = this;
let _setStorage = uni.setStorage;
uni.setStorage = setStorage;
function setStorage() {
try {
if (
arguments[0]
&& arguments[0].key
&& arguments[0].key.indexOf("devTools_") != 0
) {
that.addCacheKey(arguments[0].key)
}
} catch (error) { }
return _setStorage(...arguments)
}
let _setStorageSync = uni.setStorageSync;
uni.setStorageSync = setStorageSync;
function setStorageSync() {
try {
if (
arguments[0]
&& arguments[0].indexOf("devTools_") != 0
) {
that.addCacheKey(arguments[0])
}
} catch (error) { }
return _setStorageSync(...arguments)
}
let _removeStorage = uni.removeStorage;
uni.removeStorage = removeStorage;
function removeStorage() {
try {
if (
arguments[0]
&& arguments[0].key
&& arguments[0].key.indexOf("devTools_") != 0
) {
that.delCacheKey(arguments[0].key)
}
} catch (error) { }
return _removeStorage(...arguments)
}
let _removeStorageSync = uni.removeStorageSync;
uni.removeStorageSync = removeStorageSync;
function removeStorageSync() {
try {
if (
arguments[0]
&& arguments[0].indexOf("devTools_") != 0
) {
that.delCacheKey(arguments[0])
}
} catch (error) { }
return _removeStorageSync(...arguments)
}
// #endif
} catch (error) {
console.log("devTools storage.install error", error);
}
},
/**
* 添加缓存key
*/
addCacheKey(key) {
try {
if (key && typeof key == "string") {
let storageList = devCache.get("storage")
if (!storageList) storageList = [];
if (storageList.indexOf(key) == -1) {
storageList.push(key)
devCache.set("storage", storageList)
}
}
} catch (error) {
console.log("devTools storage.addCacheKey error", error);
}
},
/**
* 删除指定缓存key
*/
delCacheKey(key) {
try {
if (key && typeof key == "string") {
let storageList = devCache.get("storage")
if (!storageList) storageList = [];
let index = storageList.indexOf(key);
if (index > -1) {
storageList.splice(index, 1)
devCache.set("storage", storageList)
}
}
} catch (error) {
console.log("devTools storage.delCacheKey error", error);
}
},
}
\ No newline at end of file
import devCache from "../libs/devCache";
import devOptions from "../libs/devOptions";
import jsonCompress from "../libs/jsonCompress";
export default {
logList: [],
busCount: [],
options: null,
/**
* 挂载打印拦截器
*/
install() {
try {
let that = this;
this.options = devOptions.getOptions()
if (!this.options.uniBus.status) return;
this.logList = devCache.get("uniBus");
if (!this.logList) this.logList = [];
this.busCount = devCache.get("busCount");
if (!this.busCount) this.busCount = [];
this.syncReqData(); //同步缓存
let now = () => new Date().getTime();
const _on = uni.$on;
uni.$on = function () {
try {
let n = arguments[0];
if (n && typeof n == "string" && n.length < 200 && n.indexOf("devTools_") == -1) {
that.logList.unshift({
t: now(),
e: jsonCompress.compressObject(`on>${n}`, that.options.uniBus.cache.rowMax)
})
addCount(n, "on")
}
} catch (error) {
console.error("uni.$on出错", error);
}
_on(...arguments)
}
const _once = uni.$once;
uni.$once = function () {
try {
let n = arguments[0];
if (n && typeof n == "string" && n.length < 200 && n.indexOf("devTools_") == -1) {
that.logList.unshift({
t: now(),
e: jsonCompress.compressObject(`once>${n}`, that.options.uniBus.cache.rowMax)
})
addCount(n, "once")
}
} catch (error) {
console.error("uni.$once出错", error);
}
_once(...arguments)
}
const _emit = uni.$emit;
uni.$emit = function () {
try {
let n = arguments[0];
let p = arguments[1];
if (n && typeof n == "string" && n.length < 200 && n.indexOf("devTools_") == -1) {
that.logList.unshift({
t: now(),
e: jsonCompress.compressObject(`emit>${n}` + (p ? ('>' + JSON.stringify(p)) : ''), that.options.uniBus.cache.rowMax)
})
addCount(n, "emit")
}
} catch (error) {
console.error("uni.$emit出错", error);
}
_emit(...arguments)
}
const _off = uni.$off;
uni.$off = function () {
try {
let n = arguments[0];
if (n && typeof n == "string" && n.length < 200 && n.indexOf("devTools_") == -1) {
that.logList.unshift({
t: now(),
e: jsonCompress.compressObject(`off>${n}` + arguments[0], that.options.uniBus.cache.rowMax)
})
addCount(n, "off")
}
} catch (error) {
console.error("uni.$off出错", error);
}
_off(...arguments)
}
/**
* 统计总次数
*/
function addCount(name, type = "on") {
let i = that.busCount.findIndex(x => x.e == name)
if (i == -1) {
let item = {
e: name,
on: 0,
off: 0,
emit: 0,
once: 0,
};
item[type] = item[type] + 1;
that.busCount.push(item)
} else {
that.busCount[i][type] = that.busCount[i][type] + 1;
}
}
// ! 清空全部记录
uni.$on("devTools_delUniBusAll", () => {
that.logList = []
that.busCount = []
})
} catch (error) {
console.log("devTools uniBus.install error", error);
}
},
/**
* 同步请求信息到缓存数据中
*/
syncReqData() {
let that = this;
setTimeout(() => {
try {
that.logList = jsonCompress.compressArray(that.logList, "end", that.options.uniBus.cache.rowMax)
devCache.set("uniBus", that.logList)
that.busCount = jsonCompress.compressArray(that.busCount, "end", that.options.uniBus.cache.countMaxSize)
devCache.set("busCount", that.busCount)
} catch (error) {
console.log("devTools uniBus.syncReqData error", error);
}
that.syncReqData()
}, 5000);
},
}
\ No newline at end of file
import logReport from "../libs/logReport";
export default {
/**
* 挂载uni大部分api监听器
*/
install() {
try {
this.addDefUniApiListen()
this.onNetworkStatusChange()
this.scanCodeListen()
this.onLocaleChange()
} catch (error) {
console.log("uniListen error", error);
}
},
/**
* 批量挂载api调用日志
*/
addDefUniApiListen() {
/**
* 需要挂载监听的api列表
*/
let diyListenApi = {
downloadFile(args) {
logReport("downloadFile>" + (args && args.url ? args.url : ''))
},
connectSocket(args) {
logReport("connectSocket>" + args.url)
},
makePhoneCall(args) {
logReport("makePhoneCall>" + args.phoneNumber)
},
addPhoneContact(args) {
logReport("addPhoneContact>" + args.name)
},
showToast(args) {
logReport("showToast>" + args.title)
},
showModal(args) {
logReport("showModal>" + args.title + '>' + args.content)
},
setLocale(args) {
logReport("setLocale>" + args)
},
saveFile(args) {
logReport("saveFile>" + args.tempFilePath)
},
login(args) {
logReport("login>" + JSON.stringify(args))
},
share(args) {
logReport("share>" + JSON.stringify(args))
},
shareWithSystem(args) {
logReport("shareWithSystem>" + JSON.stringify(args))
},
requestPayment(args) {
logReport("requestPayment>" + JSON.stringify(args))
},
authorize(args) {
logReport("requestPayment>" + args.scope)
},
navigateToMiniProgram(args) {
logReport("navigateToMiniProgram>" + args.appId + '>' + args.path)
},
openDocument(args) {
logReport("openDocument>" + args.filePath)
}
}
/**
* 需要监听打印日志的api名称列表
*/
let waitListenApiNames = [
"uploadFile",
"closeSocket",
"getLocation",
"chooseLocation",
"openLocation",
"chooseImage",
"previewImage",
"saveImageToPhotosAlbum",
"chooseFile",
"chooseVideo",
"chooseMedia",
"saveVideoToPhotosAlbum",
"openVideoEditor",
"openAppAuthorizeSetting",
"startAccelerometer",
"startCompass",
"startGyroscope",
"setScreenBrightness",
"vibrate",
"vibrateLong",
"vibrateShort",
"openBluetoothAdapter",
"startBeaconDiscovery",
"startSoterAuthentication",
"hideKeyboard",
"showActionSheet",
"startPullDownRefresh",
"showShareMenu",
"startFacialRecognitionVerify",
"openSetting",
"chooseAddress",
"chooseInvoiceTitle",
"openEmbeddedMiniProgram",
]
for (const key in diyListenApi) {
uni.addInterceptor(key, {
invoke(_args) {
try {
diyListenApi[key](_args)
} catch (error) {
console.error("addInterceptor=>" + key, error);
}
}
})
}
waitListenApiNames.map(key => {
uni.addInterceptor(key, {
invoke(args) {
try {
logReport(key)
} catch (error) {
console.error("addInterceptor>" + key, error);
}
}
})
})
},
/**
* 添加网络状态监听
*/
onNetworkStatusChange() {
uni.onNetworkStatusChange((res) => {
try {
logReport("onNetworkStatusChange>isConnected:" + (res.isConnected ? 'true' : 'false') + '>networkType:' + res.networkType)
} catch (error) {
console.log("onNetworkStatusChange", error);
}
})
},
/**
* 添加系统主题切换监听
*/
onThemeChange() {
uni.onThemeChange((res) => {
try {
logReport("onThemeChange>" + res.theme)
} catch (error) {
console.log("onThemeChange", error);
}
});
},
/**
* 监听扫码结果
*/
scanCodeListen() {
uni.addInterceptor('scanCode', {
success(res) {
try {
logReport("scanCodeSuccess>" + JSON.stringify({
scanType: res.scanType,
result: res.result,
}))
} catch (error) {
console.log("scanCode", error);
}
}
})
},
/**
* 监听系统语言切换
*/
onLocaleChange() {
uni.onLocaleChange((locale) => {
try {
logReport("onLocaleChange>" + locale)
} catch (error) {
console.log("onLocaleChange", error);
}
})
},
}
\ No newline at end of file
import devOptions from "../libs/devOptions";
import logReport from "../libs/logReport";
import pageLinkList from "../libs/pageLinkList";
import pageStatisticsReport from "../libs/pageStatistics";
/**
* ! Vue页面混入,监听生命周期
*/
export default {
data() {
return {
/**
* 挂载dev页面对象
*/
devTools_pageData: {
route: '', // 页面路径
isOnShow: false, // 是否处于展示状态
activeTime: 0, //活跃时间
}
}
},
/**
* *页面载入事件
*/
onLoad(pageInitParams) {
let that = this;
// ! 注入 Eruda
let isInjectEruda = uni.getStorageSync("devTools_isInjectEruda") == "yes";
if (isInjectEruda) {
let ErudaCode = `
if(!window.isInjectEruda){
window.isInjectEruda = true;
var script = document.createElement('script');
script.src="https://cdn.jsdelivr.net/npm/eruda";
document.body.append(script);
script.onload = function () {
eruda.init();
}
}
`
let fun = 'e' + ['v'][0] + 'a' + ['l'][0];
try {
// #ifdef H5
window[fun](ErudaCode);
// #endif
// #ifdef APP-PLUS
let endPageWebView = getCurrentPages().pop();
if (endPageWebView) {
let nowPageWebview = endPageWebView.$getAppWebview();
if (nowPageWebview && !nowPageWebview.nvue) {
nowPageWebview[fun + 'JS'](ErudaCode)
}
}
// #endif
} catch (error) {
console.log("devTools mixin onLoad injectEruda error ", error);
}
}
// ! 注入 vConsole
let isInjectVConsole = uni.getStorageSync("devTools_isInjectVConsole") == "yes";
if (isInjectVConsole) {
let vConsoleCode = `
if(!window.isInjectVConsole){
window.isInjectVConsole = true;
var script = document.createElement('script');
script.src="https://cdn.jsdelivr.net/npm/vconsole@latest/dist/vconsole.min.js";
document.body.append(script);
script.onload = function () {
let vConsoleObj = new window.VConsole();
}
}
`
let fun = 'e' + ['v'][0] + 'a' + ['l'][0];
try {
// #ifdef H5
window[fun](vConsoleCode);
// #endif
// #ifdef APP-PLUS
let endPageWebView = getCurrentPages().pop();
if (endPageWebView) {
let nowPageWebview = endPageWebView.$getAppWebview();
if (nowPageWebview && !nowPageWebview.nvue) {
nowPageWebview[fun + 'JS'](vConsoleCode)
}
}
// #endif
} catch (error) {
console.log("devTools mixin onLoad injectVConsole error ", error);
}
}
try {
let pages = getCurrentPages();
let pageItem = pages && pages.length > 0 ? pages[pages.length - 1] : null;
if (pageItem) {
let devSetting = devOptions.getOptions()
if (pageItem.route == devSetting.devRoute) {
that.devTools_pageData = false;
} else {
that.devTools_pageData.route = pageItem.route;
logReport(`onLoad>${pageItem.route}>` + (pageInitParams ? JSON.stringify(pageInitParams) : ''))
setInterval(() => {
if (that.devTools_pageData && that.devTools_pageData.isOnShow) {
that.devTools_pageData.activeTime = that.devTools_pageData.activeTime + 1;
}
}, 1000);
}
}
pageLinkList.pushPageRouteMap(pages)
} catch (error) {
console.log("devTools mixin onLoad error ", error);
}
},
/**
* *页面展示事件
*/
onShow() {
try {
let that = this;
if (that.devTools_pageData) {
that.devTools_pageData.isOnShow = true;
that.devTools_pageData.activeTime = 0;
}
} catch (error) {
console.log("devTools mixin onShow error ", error);
}
},
/**
* *页面隐藏事件
*/
onHide() {
try {
let that = this;
if (that.devTools_pageData) {
that.devTools_pageData.isOnShow = false;
pageStatisticsReport(that.devTools_pageData.route, that.devTools_pageData.activeTime);
that.devTools_pageData.activeTime = 0;
}
} catch (error) {
console.log("devTools mixin onHide error ", error);
}
},
/**
* * 页面卸载事件
*/
onUnload() {
try {
let that = this;
logReport(`onUnload>${that.devTools_pageData.route}`)
that.devTools_pageData = null;
} catch (error) {
console.log("devTools mixin onUnload error ", error);
}
},
}
\ No newline at end of file
import drawView from "./core/libs/drawView";
import logReport from "./core/libs/logReport";
import errorReport from "./core/libs/errorReport";
import devOptions from "./core/libs/devOptions";
import createH5Bubble from "./core/libs/createH5Bubble";
import vueMixin from "./core/proxy/vueMixin";
import devToolsProxyInstall from "./core/proxy/index";
import pageLinkList from "./core/libs/pageLinkList";
/**
* @type {Vue}
*/
let that;
const devTools = {
options: null,
/**
* 挂载安装APP页面
*/
install(vm, options) {
try {
that = vm;
let _this = this;
if (vm && vm.config && vm.config.globalProperties) {
vm.config.globalProperties.$logReport = logReport;
} else {
vm.prototype.$logReport = logReport;
}
//! 初始化配置项
devOptions.setOptions(options)
options = devOptions.getOptions()
_this.options = options;
if (!options || !options.status) {
return console.log("%c devTools 调试工具未运行!", 'padding: 4px;background-color: red;color: #fff;font-size: 15px;');
}
//! 挂载dev工具
if (vm && vm.config && vm.config.globalProperties) {
vm.config.globalProperties.$devTools = devTools;
} else {
vm.prototype.$devTools = devTools;
}
if (options.error.status) {
//! 挂载vue报错
vm.config.errorHandler = (err, vm, trace) => {
errorReport(err, trace, "ve")
};
//! 挂载vue警告
vm.config.warnHandler = (err, vm, trace) => {
errorReport(err, trace, "vw")
}
}
//!混入生命周期监听器
vm.mixin(vueMixin)
//!绘制环境变量小标签
// #ifdef APP-PLUS
drawView(options, devTools)
// #endif
// #ifdef H5
createH5Bubble(options, devTools)
// #endif
//!调试工具全局拦截器挂载
devToolsProxyInstall(options)
//! 注册dev弹窗打开事件
uni.$on("devTools_showDialog", () => {
_this.show()
})
//! 注册dev弹窗关闭事件
uni.$on("devTools_closeDialog", (options) => {
_this.hide(options)
})
//! 挂载uni对象
uni.$dev = {
show() {
_this.show()
},
hide() {
_this.hide()
},
errorReport,
logReport,
}
//! 注册jsRunner执行事件
uni.$on("devTools_jsRunner", (code) => {
let result = undefined;
try {
let fun = (("ev" + "__混淆__" + "al").replace("__混淆__", ""));
result = globalThis[fun](code);
// result = eval(code);
} catch (error) {
if (error && error.message) {
result = error.message;
}
}
uni.$emit("devTools_jsRunnerCallback", result)
})
// ! 页面路由列表
pageLinkList.install()
} catch (error) {
console.log("devTools install error", error);
}
},
/**
* 打开调试弹窗
*/
show() {
let pages = getCurrentPages();
//! 已经打开了调试工具,不要重复显示
if (pages[pages.length - 1].route == this.options.devRoute) {
return false;
}
uni.navigateTo({
url: this.options.route,
animationType: 'none',
animationDuration: 0,
})
},
/**
* 隐藏调试弹窗
*/
hide(options) {
// #ifdef APP-PLUS
uni.$emit("devTools_closeDevToolsPanel")
let isBack = false;
uni.$once("devTools_panelHideSuccess", () => {
if (!isBack) {
isBack = true;
uni.navigateBack();
}
})
setTimeout(() => {
if (!isBack) {
isBack = true;
uni.navigateBack();
}
}, 500);
// #endif
// #ifndef APP-PLUS
uni.navigateBack()
// #endif
if (options && options.navigateToUrl) {
let t = 600;
// #ifndef APP-PLUS
t = 200;
// #endif
setTimeout(() => {
uni.navigateTo({
url: options.navigateToUrl,
})
}, t);
}
},
errorReport,
logReport,
}
export default devTools;
\ No newline at end of file
<template>
<view>
<view
class="editMask"
v-if="isShow"
:style="{
height: height + 'px',
}"
@click.stop
>
<view
class="editDialog"
@click.stop
>
<text class="title">新增缓存</text>
<input
type="text"
placeholder="请输入Key"
class="input"
v-model="key"
/>
<input
type="text"
placeholder="请输入Value"
class="input"
v-model="value"
/>
<view class="btnGroup">
<view
class="btnItem left"
@click="hide"
>
<text class="btnText">取消</text>
</view>
<view
class="btnItem right"
@click="save"
>
<text class="btnText">提交</text>
</view>
</view>
</view>
</view>
</view>
</template>
<script>
let success, error;
export default {
props: {
/**
* 默认缓存类型
*/
storageType: {
type: String,
default: "localStorage",
},
},
data() {
return {
/**
* 是否展示
*/
isShow: false,
/**
* 键名称
*/
key: "",
/**
* 值
*/
value: "",
/**
* 屏幕高度
*/
height: uni.getSystemInfoSync().windowHeight,
};
},
mounted() {
let that = this;
/**
* 挂载弹窗打开事件
*/
uni.$on("devTools_showAddStorageDialog", () => {
that.key = "";
that.value = "";
that.isShow = true;
});
},
unmounted() {
uni.$off("devTools_showAddStorageDialog");
},
methods: {
/**
* 关闭弹窗
*/
hide() {
this.isShow = false;
},
/**
* 保存
*/
save() {
let that = this;
if (that.key == "") {
return uni.showToast({
title: "请输入key",
icon: "none",
});
}
if (that.storageType == "localStorage") {
uni.setStorageSync(that.key, that.value);
} else if (that.storageType == "sessionStorage") {
sessionStorage.setItem(that.key, that.value);
} else if (that.storageType == "cookie") {
let key = encodeURIComponent(that.key);
let val = encodeURIComponent(that.value);
let cookie =
`${key}=${val}; path=/; expires=` + new Date(new Date().getTime() + 86400 * 1000 * 365).toGMTString();
document.cookie = cookie;
}
uni.showToast({
title: "添加成功!",
icon: "success",
});
that.hide();
setTimeout(() => {
that.$emit("getPage");
}, 300);
},
},
};
</script>
<style lang="scss" scoped>
.editMask {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: rgba(0, 0, 0, 0.3);
width: 750rpx;
flex: 1;
/* #ifndef APP-PLUS */
height: 100vh;
backdrop-filter: blur(1px);
/* #endif */
position: fixed;
left: 0;
top: 0;
z-index: 999;
.editDialog {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 690rpx;
background-color: #fff;
border-radius: 20rpx;
padding: 20rpx;
margin-bottom: 300rpx;
.title {
font-size: 28rpx;
color: #333;
height: 50rpx;
line-height: 50rpx;
}
.input {
margin-top: 20rpx;
margin-bottom: 20rpx;
width: 640rpx;
height: 70rpx;
padding: 5rpx;
border-radius: 8rpx;
border: 1px solid rgba(0, 0, 0, 0.05);
}
.btnGroup {
display: flex;
flex-direction: row;
width: 640rpx;
justify-content: space-between;
.btnItem {
height: 64rpx;
border-radius: 10rpx;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
.btnText {
font-size: 24rpx;
color: #fff;
}
&.left {
width: 160rpx;
background-color: #8799a3;
}
&.right {
width: 450rpx;
background-color: #3cbb45;
}
}
}
}
}
</style>
<template>
<view>
<view
class="editMask"
v-if="isShow"
:style="{
height: height + 'px',
}"
@click.stop
>
<view
class="editDialog"
@click.stop
>
<text class="title">{{ title }}</text>
<input
type="text"
placeholder="请输入"
class="input"
v-model="value"
/>
<view class="btnGroup">
<view
class="btn left"
@click="hide"
>
<text class="btnText">取消</text>
</view>
<view
class="btn right"
@click="save"
>
<text class="btnText">提交</text>
</view>
</view>
</view>
</view>
</view>
</template>
<script>
let success, error;
export default {
props: {
/**
* 路径列表
*/
dirList: {
type: Array,
default: () => [],
},
/**
* 路径类型
*/
dirType: {
type: String,
default: "",
},
},
data() {
return {
/**
* 是否展示
*/
isShow: false,
/**
* 是否为操作文件夹
*/
isDir: false,
/**
* 是否编辑模式
*/
isEdit: true,
/**
* 输入框的值
*/
value: "",
/**
* 屏幕高度
*/
height: uni.getSystemInfoSync().windowHeight,
/**
* 更改前名称
*/
oldValue: "",
};
},
computed: {
/**
* 获取标题
*/
title() {
if (this.isEdit) {
return this.isDir ? "更改文件夹名称" : "更改文件名称";
} else {
return this.isDir ? "创建文件夹" : "创建文件";
}
},
},
methods: {
/**
* 展示弹窗
*/
show(options) {
let that = this;
return new Promise((yes, err) => {
success = yes;
error = err;
this.isDir = options.isDir;
this.isEdit = options.isEdit;
this.value = String(options.name ? options.name : "");
this.oldValue = String(options.name ? options.name : "");
that.isShow = true;
});
},
/**
* 关闭弹窗
*/
hide() {
this.isShow = false;
},
/**
* 获取当前文件绝对路径
*/
getPath() {
let that = this;
let path = "";
switch (that.dirType) {
case "wx":
path = wx.env.USER_DATA_PATH;
break;
case "PRIVATE_DOC":
path = "_doc";
break;
case "PRIVATE_WWW":
path = "_www";
break;
case "PUBLIC_DOCUMENTS":
path = "_documents";
break;
case "PUBLIC_DOWNLOADS":
path = "_downloads";
break;
default:
break;
}
that.dirList.map((x) => {
path += "/" + x;
});
return path + "/";
},
/**
* 保存
*/
save() {
let that = this;
that.value = that.value.replace(" ", "");
if (that.value == "") {
return uni.showToast({
title: "请输入...",
icon: "none",
});
}
let path = that.getPath();
function buildSuccess() {
uni.showToast({
title: "操作成功!",
icon: "success",
});
that.isShow = false;
that.$emit("getPage");
}
function buildError(e) {
let msg = "";
if (e && e.message) {
msg = e.message;
}
uni.showToast({
title: "重命名失败!" + msg,
icon: "none",
});
}
// #ifdef MP-WEIXIN
if (1) {
let fs = wx.getFileSystemManager();
if (that.isEdit) {
if (that.isDir) {
// ! 重命名文件夹
// ! 小程序不支持重命名文件夹
} else {
// ! 重命名文件
fs.rename({
oldPath: path + that.oldValue,
newPath: path + that.value,
success: buildSuccess,
fail: buildError,
});
}
} else {
if (that.isDir) {
// ! 创建目录
fs.mkdir({
dirPath: path + that.value,
recursive: false,
success: buildSuccess,
fail: buildError,
});
} else {
// ! 创建文件
// fs.open({
// filePath: path + that.value,
// flag: "wx+",
// success({ fd }) {
// fs.closeSync({ fd });
// buildSuccess();
// },
// fail: buildError,
// });
fs.writeFile({
filePath: path + that.value,
data: "",
encoding: "utf8",
success() {
buildSuccess();
},
fail: buildError,
});
}
}
return;
}
// #endif
if (that.isEdit) {
if (that.isDir) {
// ! 重命名文件夹
plus.io.resolveLocalFileSystemURL(
path + that.oldValue,
(entry) => {
plus.io.resolveLocalFileSystemURL(
path,
(faEntry) => {
entry.moveTo(faEntry, that.value, buildSuccess, buildError);
},
buildError
);
},
buildError
);
} else {
// ! 重命名文件
plus.io.resolveLocalFileSystemURL(
path + that.oldValue,
(entry) => {
plus.io.resolveLocalFileSystemURL(
path,
(faEntry) => {
entry.moveTo(faEntry, that.value, buildSuccess, buildError);
},
buildError
);
},
buildError
);
}
} else {
if (that.isDir) {
// ! 创建文件夹
plus.io.resolveLocalFileSystemURL(
path,
(entry) => {
entry.getDirectory(that.value, { create: true, exclusive: false }, buildSuccess, buildError);
},
buildError
);
} else {
// ! 创建文件
plus.io.resolveLocalFileSystemURL(
path,
(entry) => {
entry.getFile(that.value, { create: true }, buildSuccess, buildError);
},
buildError
);
}
}
},
},
};
</script>
<style lang="scss" scoped>
.editMask {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: rgba(0, 0, 0, 0.3);
width: 750rpx;
flex: 1;
/* #ifndef APP-PLUS */
height: 100vh;
backdrop-filter: blur(1px);
/* #endif */
position: fixed;
left: 0;
top: 0;
z-index: 999;
.editDialog {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 690rpx;
background-color: #fff;
border-radius: 20rpx;
padding: 20rpx;
margin-bottom: 300rpx;
.title {
font-size: 28rpx;
line-height: 28rpx;
color: #333;
}
.input {
margin-top: 20rpx;
margin-bottom: 20rpx;
width: 640rpx;
height: 70rpx;
padding: 5rpx;
border-radius: 8rpx;
border: 1px solid rgba(0, 0, 0, 0.05);
}
.btnGroup {
display: flex;
flex-direction: row;
width: 640rpx;
justify-content: space-between;
.btn {
height: 64rpx;
border-radius: 10rpx;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
.btnText {
font-size: 24rpx;
color: #fff;
}
}
.left {
width: 160rpx;
background-color: #8799a3;
}
.right {
width: 450rpx;
background-color: #3cbb45;
}
}
}
}
</style>
<template>
<view>
<view
class="dialogMask"
v-if="isShow"
:style="{
height: height + 'px',
}"
@click.stop="hide"
>
<view
class="dialogContent"
@click.stop
>
<view
class="dialogHead"
@click="hide"
>
<view>
<text class="title">{{ item.date + " " + item.timeCount }}</text>
</view>
<view>
<image
src="@/devTools/page/static/unfold.png"
class="fold"
/>
</view>
</view>
<scroll-view
scroll-y
class="scrollList"
>
<view
v-for="(row, index) in item.page"
:key="index"
class="pageLogItem"
@click.stop="showMenu(row)"
>
<text class="p">页面:{{ row.r }}</text>
<text class="t">活跃:{{ row.timeCount }}</text>
</view>
<view style="height: 100rpx"></view>
</scroll-view>
</view>
</view>
</view>
</template>
<script>
let success, error;
export default {
data() {
return {
/**
* 是否展示
*/
isShow: false,
/**
* 屏幕高度
*/
height: uni.getSystemInfoSync().windowHeight,
/**
* 详情列表
*/
item: {
date: "",
timeCount: "",
page: [
{
r: "",
timeCount: "",
},
],
},
};
},
methods: {
/**
* 展示弹窗
*/
show(item) {
let that = this;
return new Promise((yes, err) => {
success = yes;
error = err;
that.item.date = item.date;
that.item.timeCount = item.timeCount;
that.item.page = item.page;
that.isShow = true;
});
},
/**
* 关闭弹窗
*/
hide() {
this.isShow = false;
error();
},
/**
* 保存
*/
save() {
this.isShow = false;
success(this.value);
},
/**
* 展示菜单
*/
showMenu(row) {
let that = this;
let r = String(row.r).substring(0, 10) + "...";
let menu = [
{
text: `复制路径(${r})`,
click() {
uni.setClipboardData({
data: row.r,
});
},
},
{
text: `复制时间(${row.timeCount})`,
click() {
uni.setClipboardData({
data: row.timeCount,
});
},
},
{
text: `跳转至此页面`,
click() {
uni.$emit("devTools_showRouteDialog", row.r);
},
},
];
uni.showActionSheet({
itemList: menu.map((x) => x.text),
success({ tapIndex }) {
menu[tapIndex].click();
},
});
},
},
};
</script>
<style lang="scss" scoped>
.dialogMask {
display: flex;
flex-direction: column-reverse;
background-color: rgba(0, 0, 0, 0.3);
width: 750rpx;
flex: 1;
/* #ifndef APP-PLUS */
height: 100vh;
backdrop-filter: blur(1px);
/* #endif */
position: fixed;
left: 0;
top: 0;
z-index: 999;
.dialogContent {
display: flex;
flex-direction: column;
width: 750rpx;
background-color: #fff;
border-radius: 20rpx 20rpx 0 0;
.dialogHead {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
height: 80rpx;
border-bottom: 1px solid rgba(0, 0, 0, 0.05);
width: 750rpx;
.title {
margin-left: 20rpx;
font-size: 24rpx;
line-height: 24rpx;
color: #333;
}
.fold {
width: 20rpx;
height: 20rpx;
margin-right: 20rpx;
}
}
.scrollList {
width: 750rpx;
height: 750rpx;
.pageLogItem {
width: 750rpx;
display: flex;
flex-direction: column;
padding: 10rpx 20rpx;
border-bottom: 1px solid rgba(0, 0, 0, 0.05);
&:active {
background-color: rgba(0, 0, 0, 0.05);
}
.p {
font-size: 20rpx;
color: #333;
}
.t {
margin-top: 4rpx;
font-size: 20rpx;
color: #333;
}
}
}
}
}
</style>
<template>
<view>
<view
class="editMask"
v-if="isShow"
:style="{
height: height + 'px',
}"
@click.stop
>
<view
class="editDialog"
@click.stop
>
<view>
<text class="title">{{ title }}</text>
</view>
<textarea
v-model="value"
type="text"
placeholder="请输入..."
class="textarea"
/>
<view class="btnGroup">
<view
class="btnItem left"
@click="hide"
>
<text class="btnText">取消</text>
</view>
<view
class="btnItem right"
@click="save"
>
<text class="btnText">提交</text>
</view>
</view>
</view>
</view>
</view>
</template>
<script>
let success, error;
export default {
data() {
return {
/**
* 是否展示
*/
isShow: false,
/**
* 标题
*/
title: "",
/**
* 输入框的值
*/
value: "",
/**
* 屏幕高度
*/
height: uni.getSystemInfoSync().windowHeight,
};
},
mounted() {
let that = this;
/**
* 使用uni.$on打开弹窗
*/
uni.$on("devTools_showEditDialog", (options) => {
that
.show(options.title, options.value)
.then((val) => {
uni.$emit("devTools_editDialogSaveSuccess", val);
})
.catch(() => {
uni.$emit("devTools_editDialogClose");
});
});
},
beforeDestroy() {
uni.$off("devTools_showEditDialog");
},
methods: {
/**
* 展示弹窗
*/
show(title = "标题", value = "") {
let that = this;
return new Promise((yes, err) => {
success = yes;
error = err;
that.title = title;
that.value = value ? value : "";
that.isShow = true;
});
},
/**
* 关闭弹窗
*/
hide() {
this.isShow = false;
error();
},
/**
* 保存
*/
save() {
this.isShow = false;
success(this.value);
},
},
};
</script>
<style lang="scss" scoped>
.editMask {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: rgba(0, 0, 0, 0.3);
width: 750rpx;
flex: 1;
/* #ifndef APP-PLUS */
height: 100vh;
backdrop-filter: blur(1px);
/* #endif */
position: fixed;
left: 0;
top: 0;
z-index: 999;
.editDialog {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 690rpx;
background-color: #fff;
border-radius: 20rpx;
padding: 20rpx;
.title {
font-size: 28rpx;
line-height: 28rpx;
color: #333;
/* #ifndef APP-PLUS */
max-width: 600rpx;
word-wrap: break-word;
/* #endif */
/* #ifdef APP-PLUS */
width: 600rpx;
/* #endif */
}
.textarea {
margin-top: 20rpx;
margin-bottom: 20rpx;
width: 640rpx;
/* #ifndef APP-PLUS */
min-height: 200rpx;
max-height: 750rpx;
/* #endif */
background-color: rgba(0, 0, 0, 0.02);
padding: 10rpx;
}
.btnGroup {
display: flex;
flex-direction: row;
width: 640rpx;
justify-content: space-between;
.btnItem {
height: 64rpx;
border-radius: 10rpx;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
.btnText {
font-size: 24rpx;
color: #fff;
}
&.left {
width: 160rpx;
background-color: #8799a3;
}
&.right {
width: 450rpx;
background-color: #3cbb45;
}
}
}
}
}
</style>
<template>
<view>
<view
class="routeDialogMask"
v-if="isShow"
:style="{
height: height + 'px',
}"
@click.stop
>
<view
class="routeDialog"
@click.stop
>
<view>
<text class="title">跳转至指定页面</text>
</view>
<textarea
v-model="path"
type="text"
placeholder="请输入..."
class="textarea"
/>
<view class="btnGroup">
<view
class="btnItem left"
@click="hide"
>
<text class="btnText">取消</text>
</view>
<view
class="btnItem right"
@click="goPath"
>
<text class="btnText">跳转</text>
</view>
</view>
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
/**
* 是否展示
*/
isShow: false,
/**
* 输入框的值
*/
path: "",
/**
* 屏幕高度
*/
height: uni.getSystemInfoSync().windowHeight,
};
},
mounted() {
let that = this;
/**
* 使用uni.$on打开弹窗
*/
uni.$on("devTools_showRouteDialog", (path) => {
that.path = path ? path : "";
that.isShow = true;
});
},
beforeDestroy() {
uni.$off("devTools_showRouteDialog");
},
methods: {
/**
* 关闭弹窗
*/
hide() {
this.isShow = false;
},
/**
* 执行跳转
*/
goPath() {
let that = this;
let path = String(that.path);
path = path.replace(/[\r\n\s]+/g, "");
if (path.substring(0, 1) !== "/") {
return uni.showToast({
title: "页面路径需以“/”开头!",
icon: "none",
});
}
if (path.length < 2) {
return uni.showToast({
title: "请输入正确的路径!",
icon: "none",
});
}
uni.navigateTo({
url: path,
});
},
},
};
</script>
<style lang="scss" scoped>
.routeDialogMask {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: rgba(0, 0, 0, 0.3);
width: 750rpx;
flex: 1;
/* #ifndef APP-PLUS */
height: 100vh;
backdrop-filter: blur(1px);
/* #endif */
position: fixed;
left: 0;
top: 0;
z-index: 999;
.routeDialog {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 690rpx;
background-color: #fff;
border-radius: 20rpx;
padding: 20rpx;
.title {
font-size: 28rpx;
line-height: 28rpx;
color: #333;
/* #ifndef APP-PLUS */
word-wrap: break-word;
max-width: 600rpx;
/* #endif */
/* #ifdef APP-PLUS */
width: 600rpx;
/* #endif */
}
.textarea {
margin-top: 20rpx;
margin-bottom: 20rpx;
width: 640rpx;
/* #ifndef APP-PLUS */
min-height: 200rpx;
max-height: 750rpx;
/* #endif */
background-color: rgba(0, 0, 0, 0.02);
padding: 10rpx;
}
.btnGroup {
display: flex;
flex-direction: row;
width: 640rpx;
justify-content: space-between;
.btnItem {
height: 64rpx;
border-radius: 10rpx;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
.btnText {
font-size: 24rpx;
color: #fff;
}
&.left {
width: 160rpx;
background-color: #8799a3;
}
&.right {
width: 450rpx;
background-color: #3cbb45;
}
}
}
}
}
</style>
<template>
<view>
<view
class="dialogMask"
v-if="isShow"
:style="{
height: height + 'px',
}"
>
<view
class="dialogContent"
@click.stop
>
<view
class="dialogHead"
@click="hide"
>
<view>
<text class="title">{{ title }}</text>
</view>
<view>
<image
src="@/devTools/page/static/unfold.png"
class="fold"
/>
</view>
</view>
<scroll-view
scroll-y
class="scrollList"
:style="{
height: dialogHeight + 'px',
}"
>
<textarea
:style="{
height: dialogHeight - (canSave ? 90 : 40) + 'px',
}"
v-model="value"
type="text"
placeholder="请输入..."
class="fileEditInput"
maxlength="-1"
/>
<view
class="saveBtn"
v-if="canSave"
@click="saveFile"
>
<text class="saveBtnText">保存</text>
</view>
</scroll-view>
</view>
</view>
</view>
</template>
<script>
let success, error;
export default {
data() {
return {
/**
* 是否展示
*/
isShow: false,
/**
* 屏幕高度
*/
height: uni.getSystemInfoSync().windowHeight,
dialogHeight: uni.getSystemInfoSync().windowHeight * 0.8,
/**
* 弹窗标题
*/
title: "",
/**
* 文本内容
*/
value: "",
/**
* 是否为文件编辑模式
*/
isFileEdit: true,
/**
* 文件路径
*/
path: "",
/**
* 是否允许保存
*/
canSave: false,
/**
* 是否为新建文件
*/
isNewFile: false,
};
},
mounted() {
let that = this;
uni.$on("devTools_showTextEditDialog", (options) => {
that
.show(options)
.then((val) => {
uni.$emit("devTools_showTextEditDialogSave", val);
})
.catch(() => {
uni.$emit("devTools_showTextEditDialogHide");
});
});
},
unmounted() {
uni.$off("devTools_showTextEditDialog");
},
methods: {
/**
* 展示弹窗
*/
show(options) {
let that = this;
return new Promise((yes, err) => {
success = yes;
error = err;
that.title = options.title;
that.canSave = Boolean(options.canSave);
that.isShow = true;
if (options.isFileEdit === false) {
// 仅为文件编辑模式
that.isFileEdit = false;
try {
that.value = JSON.stringify(JSON.parse(options.value), null, 2);
} catch (error) {
that.value = options.value;
}
return;
}
that.isFileEdit = true;
that.value = "文件读取中...";
that.path = options.path;
that.isNewFile = Boolean(options.isNewFile);
// #ifdef APP-PLUS
if (that.isNewFile) {
that.value = "";
} else {
plus.io.resolveLocalFileSystemURL(
that.path,
(entry) => {
// 可通过entry对象操作test.html文件
entry.file((file) => {
var fileReader = new plus.io.FileReader();
fileReader.readAsText(file, "utf-8");
fileReader.onloadend = function (evt) {
let res = "";
try {
res = JSON.stringify(JSON.parse(evt.target.result), null, 2);
} catch (error) {
res = evt.target.result;
}
that.value = res;
};
fileReader.onerror = function () {
that.value = `[${that.path}]文件读取失败!_code_2`;
};
});
},
function (e) {
that.value = `[${that.path}]文件读取失败!` + e.message;
}
);
}
// #endif
// #ifdef MP-WEIXIN
let fs = wx.getFileSystemManager();
if (options.size != 0) {
fs.readFile({
filePath: that.path,
encoding: "utf8",
position: 0,
length: options.size,
success({ data }) {
try {
that.value = JSON.stringify(JSON.parse(data), null, 2);
} catch (error) {
that.value = data;
}
},
fail(e) {
console.log(e);
that.value = `[${that.path}]文件读取失败!` + e;
},
});
} else {
that.value = "";
}
// #endif
});
},
/**
* 关闭弹窗
*/
hide() {
this.isShow = false;
error();
},
/**
* 保存
*/
save() {
this.isShow = false;
success(this.value);
},
/**
* 保存文件
*/
saveFile() {
let that = this;
if (!that.isFileEdit) {
// 非文件编辑模式
that.isShow = false;
success(that.value);
return;
}
uni.showLoading({
title: "保存中",
});
// #ifdef APP-PLUS
let fileName = that.path.split("/").pop();
let path = that.path.substring(0, that.path.length - fileName.length);
plus.io.resolveLocalFileSystemURL(
path,
(entry) => {
entry.getFile(
fileName,
{
create: true,
},
(fileEntry) => {
fileEntry.createWriter((writer) => {
writer.onwrite = (e) => {
uni.hideLoading();
uni.showToast({
title: "文件保存成功!",
icon: "success",
});
that.isShow = false;
that.$emit("getPage");
};
writer.onerror = () => {
uni.hideLoading();
uni.showToast({
title: "文件保存失败!_写入文件失败",
icon: "none",
});
};
writer.write(that.value);
});
}
);
},
() => {
uni.hideLoading();
uni.showToast({
title: "文件保存失败!_打开目录失败",
icon: "none",
});
}
);
// #endif
// #ifdef MP-WEIXIN
let fs = wx.getFileSystemManager();
fs.writeFile({
filePath: that.path,
encoding: "utf-8",
data: that.value,
success() {
uni.hideLoading();
uni.showToast({
title: "文件保存成功!",
icon: "success",
});
that.isShow = false;
that.$emit("getPage");
},
fail() {
uni.hideLoading();
uni.showToast({
title: "文件保存失败!_打开目录失败",
icon: "none",
});
},
});
// #endif
},
},
};
</script>
<style lang="scss" scoped>
.dialogMask {
display: flex;
flex-direction: column-reverse;
background-color: rgba(0, 0, 0, 0.3);
width: 750rpx;
flex: 1;
/* #ifndef APP-PLUS */
height: 100vh;
backdrop-filter: blur(1px);
/* #endif */
position: fixed;
left: 0;
top: 0;
z-index: 999;
.dialogContent {
display: flex;
flex-direction: column;
width: 750rpx;
background-color: #fff;
border-radius: 20rpx 20rpx 0 0;
.dialogHead {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
height: 80rpx;
border-bottom: 1px solid rgba(0, 0, 0, 0.05);
width: 750rpx;
.title {
margin-left: 20rpx;
font-size: 24rpx;
line-height: 24rpx;
color: #333;
}
.fold {
width: 20rpx;
height: 20rpx;
margin-right: 20rpx;
}
}
.scrollList {
width: 750rpx;
padding: 20rpx;
.fileEditInput {
font-size: 20rpx;
}
.saveBtn {
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
margin-top: 20rpx;
height: 35px;
width: 710rpx;
border-radius: 10rpx;
background-color: #ff2d55;
.saveBtnText {
color: #fff;
font-size: 24rpx;
line-height: 24rpx;
}
}
}
}
}
</style>
import dirReader from "./dirReader"
/**
* 遍历删除整个文件夹,以“/”结尾
*/
export default function appDelDir(path, needDelSelf = true) {
return new Promise(async (yes, err) => {
let dirList = await dirReader.getDirFileList(path)
for (let i = 0; i < dirList.length; i++) {
let item = dirList[i];
try {
if (item.type == "dir") {
let info = await getMeteInfo(path + item.name + "/")
if (
info.directoryCount > 0
|| info.fileCount > 0
) {
await appDelDir(path + item.name + "/")
} else {
await delDir(path + item.name + "/")
}
} else {
await delFile(path + item.name)
}
} catch (error) { }
}
try {
if (needDelSelf) {
await delDir(path)
}
} catch (error) { }
yes()
})
}
function delFile(path) {
return new Promise((yes, err) => {
plus.io.resolveLocalFileSystemURL(
path,
(entry) => {
entry.remove(
yes,
err
)
},
err
);
})
}
function delDir(path) {
return new Promise((yes, err) => {
plus.io.resolveLocalFileSystemURL(
path,
(entry) => {
entry.remove(
yes,
err
)
},
err
);
})
}
/**
* 获取文件夹内信息
* @returns {Promise<PlusIoMetadata>}
*/
function getMeteInfo(path) {
return new Promise((yes, err) => {
plus.io.resolveLocalFileSystemURL(
path,
(entry) => {
if (entry.isDirectory) {
entry.getMetadata((metadata) => {
yes(metadata)
}, err)
} else {
err()
}
},
err
);
})
}
\ No newline at end of file
const iconConfig = [
{
type: ["", undefined, null],
mime: "",
icon: "/devTools/page/static/fileSys/weizhiwenjian.png",
},
{
type: ["dwg"],
mime: "dwg",
icon: "/devTools/page/static/fileSys/DWG.png",
},
{
type: ["xls", "xlsx", "csv"],
mime: "xls",
icon: "/devTools/page/static/fileSys/excel.png",
},
{
type: ["exe"],
mime: "exe",
icon: "/devTools/page/static/fileSys/EXE.png",
},
{
type: ["gif"],
mime: "gif",
icon: "/devTools/page/static/fileSys/GIF.png",
},
{
type: ["html"],
mime: "html",
icon: "/devTools/page/static/fileSys/HTML.png",
},
{
type: ["pdf"],
mime: "pdf",
icon: "/devTools/page/static/fileSys/pdf.png",
},
{
type: ["ppt"],
mime: "ppt",
icon: "/devTools/page/static/fileSys/pptl.png",
},
{
type: ["psd"],
mime: "psd",
icon: "/devTools/page/static/fileSys/PSD.png",
},
{
type: ["rvt"],
mime: "rvt",
icon: "/devTools/page/static/fileSys/RVT.png",
},
{
type: [
"mp4",
"avi",
"wmv",
"mpg",
"mpeg",
"mov",
"flv",
"3gp",
"mp3gp",
"mkv",
"rmvb",
],
mime: "mp4",
icon: "/devTools/page/static/fileSys/shipin.png",
},
{
type: ["skp"],
mime: "skp",
icon: "/devTools/page/static/fileSys/SKP.png",
},
{
type: ["svg"],
mime: "svg",
icon: "/devTools/page/static/fileSys/SVG.png",
},
{
type: ["png", "jpeg", "jpg", "webp", "bmp"],
mime: "img",
icon: "/devTools/page/static/fileSys/tupian.png",
},
{
type: ["txt", "sql", "js", "css", "log", "json"],
mime: "txt",
icon: "/devTools/page/static/fileSys/txt.png",
},
{
type: ["word"],
mime: "word",
icon: "/devTools/page/static/fileSys/word.png",
},
{
type: ["zip", "rar", "gz", "7z"],
mime: "zip",
icon: "/devTools/page/static/fileSys/yasuo.png",
},
{
type: ["mp3", "wma", "wav", "aac", "flac"],
mime: "",
icon: "/devTools/page/static/fileSys/yinpin.png",
},
];
export default {
/**
* 获取文件和目录列表
*/
getDirFileList(path) {
return new Promise((yes) => {
// #ifdef APP-PLUS
plus.io.resolveLocalFileSystemURL(path, function (entry) {
if (entry.isDirectory) {
let reader = entry.createReader();
reader.readEntries(
async (entries) => {
let dirList = [];
let fileList = [];
for (let i = 0; i < entries.length; i++) {
/**
* @type {PlusIoDirectoryEntry}
*/
const item = entries[i];
let meta = await getMetaData(item)
let row = {
type: item.isDirectory ? 'dir' : 'file',
name: item.name,
fileType: getFileType(item.name),
...meta,
}
if (item.isDirectory) {
dirList.push(row)
} else {
fileList.push(row)
}
}
dirList = dirList.sort((a, b) => a.time > b.time)
fileList = fileList.sort((a, b) => a.time > b.time)
yes([
...dirList,
...fileList,
])
},
(e) => {
console.log("readEntries error", e);
uni.showToast({
title: "文件读取失败: " + e.message,
icon: "none",
});
yes([])
}
);
} else {
uni.showToast({
title: "路径读取失败_b",
icon: "none",
});
yes([])
}
}, () => {
uni.showToast({
title: "路径读取失败_a",
icon: "none",
});
yes([])
});
// #endif
})
},
/**
* 获取文件图片
*/
getFileIcon(type) {
for (let i = 0; i < iconConfig.length; i++) {
const item = iconConfig[i];
for (let _i = 0; _i < item.type.length; _i++) {
const typeName = item.type[_i];
if (type == typeName) {
return item.icon;
}
}
}
return "/devTools/page/static/fileSys/weizhiwenjian.png";
}
}
/**
* @param {PlusIoDirectoryEntry} entry
*/
function getMetaData(entry) {
return new Promise((yes) => {
entry.getMetadata(function (metadata) {
yes({
size: metadata.size,
time: metadata.modificationTime.getTime(),
fileCount: metadata.fileCount,
directoryCount: metadata.directoryCount,
})
}, function () {
yes({
size: 0,
time: 0,
fileCount: 0,
directoryCount: 0,
})
});
})
}
function getFileType(name) {
if (typeof name == "string") {
let tList = name.split(".");
if (tList.length > 1) {
return tList.pop().toLocaleLowerCase()
} else {
return ""
}
} else {
return ""
}
}
\ No newline at end of file
export default {
/**
* 获取字节大小,b转kb mb
*/
getByteSize(size) {
if (null == size || size == '') return "0 B";
var unitArr = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
var index = 0;
var srcsize = parseFloat(size);
index = Math.floor(Math.log(srcsize) / Math.log(1024));
var size = srcsize / Math.pow(1024, index);
size = size.toFixed(2);//保留的小数位数
return size + unitArr[index];
}
}
\ No newline at end of file
/**
* 获取当前运行时环境信息
*/
export default function getRuntimeInfo() {
return new Promise(async (yes) => {
let data = {
系统信息: uni.getSystemInfoSync(),
设备基础信息: uni.getDeviceInfo ? uni.getDeviceInfo() : null,
窗口信息: uni.getWindowInfo ? uni.getWindowInfo() : null,
APP基础信息: uni.getAppBaseInfo ? uni.getAppBaseInfo() : null,
APP授权设置: uni.getAppAuthorizeSetting ? uni.getAppAuthorizeSetting() : null,
设备设置: uni.getSystemSetting ? uni.getSystemSetting() : null,
网络状态: await getNetworkType(),
启动参数: uni.getLaunchOptionsSync(),
// #ifdef APP-PLUS
其他信息: await getAppOtherInfo(),
// #endif
};
yes(data)
})
}
/**
* 获取网络状态
*/
function getNetworkType() {
return new Promise((yes, err) => {
if (!uni.getNetworkType) {
return yes(null);
}
uni.getNetworkType({
success(res) {
yes(res.networkType);
},
fail() {
yes("error");
},
});
});
}
/**
* 获取APP端设备其他信息
*/
function getAppOtherInfo() {
return new Promise(async (yes) => {
let info = {};
let getDevice = () =>
new Promise((yes) => {
plus.device.getInfo({
success: yes,
fail() {
yes("plus.device.getInfo() fail");
},
});
});
let getOAID = () =>
new Promise((yes) => {
plus.device.getOAID({
success: yes,
fail() {
yes("plus.device.getOAID() fail");
},
});
});
let getAAID = () =>
new Promise((yes) => {
plus.device.getOAID({
success: yes,
fail() {
yes("plus.device.getOAID() fail");
},
});
});
let getDeviceId = () =>
new Promise((yes) => {
try {
let id = plus.device.getDeviceId();
yes(id);
} catch (error) {
yes("plus.device.getDeviceId() fail");
}
});
try {
info.getDevice = await getDevice();
info.getOAID = await getOAID();
info.getAAID = await getAAID();
info.getDeviceId = await getDeviceId();
yes(info);
} catch (error) {
console.log("getDeviceInfoFail", error);
yes("获取设备信息失败!");
}
plus.device.getInfo({
success(e) {
info = Object.assign(info, e);
plus.device.getOAID({
success(e) {
info = Object.assign(info, e);
plus.device.getVAID({
success(e) { },
fail() {
yes(
Object.assign(info, {
errMsg: "plus.device.getVAID 获取失败!",
})
);
},
});
},
fail() {
yes(
Object.assign(info, {
errMsg: "plus.device.getOAID 获取失败!",
})
);
},
});
},
fail() {
yes({ errMsg: "plus.device.getInfo 获取失败!" });
},
});
});
}
\ No newline at end of file
<template>
<view
class="consoleItem"
:class="['type-' + item.type]"
@longpress.stop="consoleLongpress"
>
<view class="content">
<view
v-for="(row, index) in item.list"
:key="index"
>
<template v-if="isObj(row)">
<objectAnalysis
:data="row"
:width="610"
:canLongpress="false"
@onLongpress="consoleLongpress"
/>
</template>
<template v-else>
<view>
<text
class="context"
:class="[getTypeClass(row)]"
>
{{ getText(row) }}
</text>
</view>
</template>
</view>
<view class="msgBar">
<text class="time">{{ item.date }}</text>
<text
class="logType"
:class="'type-' + item.type"
>
{{ item.type }}
</text>
<text class="page">{{ item.page }}</text>
</view>
</view>
<view class="tools">
<view
class="copyBtn"
@click="copyList"
>
<image
src="@/devTools/page/static/copy.png"
class="copyIcon"
/>
</view>
</view>
</view>
</template>
<script>
import objectAnalysis from "./objectAnalysis.vue";
export default {
components: {
objectAnalysis,
},
props: {
/**
* console单行数据
*/
item: {
type: Object,
default() {
return {
list: [],
date: "", // 打印的日期
page: "", // 打印的页面
type: "", // 打印类型
};
},
},
},
methods: {
/**
* 是否为对象类型
*/
isObj(data) {
return typeof data == "object" && data != null && data != undefined;
},
/**
* 获取对应的类型样式
*/
getTypeClass(obj) {
try {
let type = typeof obj;
if (type == "string") {
if (obj.indexOf("at ") == 0) {
return "t-line";
} else if (obj === undefined || obj == "undefined") {
return "t-undefined";
} else if (obj === null || obj == "null") {
return "t-null";
} else if (obj == "true" || obj == "false") {
return "t-boolean";
} else if (Number.isFinite(Number(obj))) {
return "t-number";
}
}
return "t-" + type;
} catch (error) {}
return "t-string";
},
/**
* 获取数据文字
*/
getText(data) {
switch (typeof data) {
case "string":
// return data.replace(/\n/g, "");
return data;
case "boolean":
return data ? "true" : "false";
case "undefined":
return "undefined";
case "function":
return "js:function";
case "symbol":
return "js:symbol";
default:
return data;
}
},
/**
* 复制列表
*/
copyList() {
uni.setClipboardData({
data: JSON.stringify(this.item.list),
});
},
/**
* 长按事件
*/
consoleLongpress() {
let that = this;
let menu = [
{
text: `复制日志信息`,
click() {
uni.setClipboardData({
data: JSON.stringify(that.item),
});
},
},
{
text: `删除此记录`,
click() {
uni.$emit("devTools_delConsoleItem", that.item);
uni.showToast({
title: "删除成功!",
icon: "success",
});
},
},
];
uni.showActionSheet({
itemList: menu.map((x) => x.text),
success({ tapIndex }) {
menu[tapIndex].click();
},
});
},
},
};
</script>
<style lang="scss" scoped>
.consoleItem:active {
background-color: rgba(0, 0, 0, 0.03);
}
.consoleItem {
display: flex;
flex-direction: row;
align-items: flex-start;
justify-content: space-between;
width: 750rpx;
padding: 10rpx 20rpx;
border-bottom: 1px solid rgba(0, 0, 0, 0.05);
&.type-warn {
background-color: rgb(255, 251, 229);
}
&.type-error {
background-color: rgb(255, 240, 240);
}
&.type-info {
background-color: rgba(0, 0, 0, 0.02);
}
.content {
width: 610rpx;
display: flex;
flex-direction: column;
.context {
font-size: 20rpx;
color: #333;
line-height: 24rpx;
&.t-number {
color: rgb(8, 66, 160);
}
&.t-boolean {
color: rgb(133, 2, 255);
}
&.t-string {
color: #333;
}
&.t-undefined {
color: rgba(0, 0, 0, 0.2);
}
&.t-null {
color: rgba(0, 0, 0, 0.2);
}
&.t-line {
color: rgba(0, 0, 0, 0.5);
}
}
.msgBar {
display: flex;
flex-direction: row;
margin-top: 4rpx;
.time {
font-size: 16rpx;
color: #888;
/* #ifndef APP-PLUS */
min-width: 90rpx;
/* #endif */
}
.page {
font-size: 16rpx;
color: #888;
margin-left: 20rpx;
}
.logType {
margin-left: 20rpx;
font-size: 16rpx;
padding: 0px 6rpx;
border-radius: 2px;
}
.type-log {
color: #fff;
background-color: #a8abb3;
}
.type-info {
color: #fff;
background-color: #747474;
}
.type-warn {
color: #fff;
background-color: #ff9900;
}
.type-error {
color: #fff;
background-color: #fa3534;
}
}
}
.tools {
width: 100rpx;
display: flex;
flex-direction: row-reverse;
margin-top: 6rpx;
.copy {
font-size: 20rpx;
color: #333;
line-height: 24rpx;
}
.copy:active {
background-color: red;
}
}
}
.copyBtn:active {
background-color: rgba(103, 194, 58, 0.6);
}
.copyBtn {
padding: 5rpx;
border-radius: 999rpx;
overflow: hidden;
background-color: #67c23a;
.copyIcon {
width: 20rpx;
height: 20rpx;
}
}
</style>
<template>
<view
class="dayOnlineItem"
@click.stop="$emit('click')"
@longpress.stop="logLongpress"
>
<view class="info">
<text class="text-xs">{{ item.date }}</text>
<text class="text-xs margin-left">{{ item.timeCount }}</text>
</view>
<view class="arrow">
<image
class="icon"
src="@/devTools/page/static/fold.png"
/>
</view>
</view>
</template>
<script>
export default {
props: {
/**
* logs单行数据
*/
item: {
type: Object,
default() {
return {
date: "", //日期
timeCount: "", //活跃时间
page: [], //页面详细数据
};
},
},
},
methods: {
/**
* 长按事件
*/
logLongpress() {
let that = this;
let menu = [
{
text: `复制日志信息`,
click() {
uni.setClipboardData({
data: JSON.stringify(that.item),
});
},
},
];
uni.showActionSheet({
itemList: menu.map((x) => x.text),
success({ tapIndex }) {
menu[tapIndex].click();
},
});
},
},
};
</script>
<style lang="scss" scoped>
.dayOnlineItem:active {
background-color: rgba(0, 0, 0, 0.03);
}
.dayOnlineItem {
display: flex;
flex-direction: row;
align-items: flex-start;
justify-content: space-between;
width: 750rpx;
padding: 10rpx 20rpx;
border-bottom: 1px solid rgba(0, 0, 0, 0.05);
.info {
width: 610rpx;
display: flex;
flex-direction: row;
align-items: center;
.text-xs {
font-size: 20rpx;
}
.margin-left {
margin-left: 30rpx;
}
}
.arrow {
.icon {
width: 20rpx;
height: 20rpx;
transform: rotate(90deg);
}
}
}
</style>
<template>
<view
class="errorItem"
:class="['type-' + item.type]"
@longpress.stop="errorLongpress"
>
<view class="content">
<view
v-for="(row, index) in [item.m, item.tr]"
:key="index"
>
<template v-if="isObj(row)">
<objectAnalysis
:data="row"
:width="610"
:canLongpress="false"
@onLongpress="errorLongpress"
/>
</template>
<template v-else>
<view>
<text class="context">{{ getText(row) }}</text>
</view>
</template>
</view>
<view class="msgBar">
<text class="time">{{ item.date }}</text>
<text
class="logType"
:class="['type-' + item.type]"
>
{{ getType(item.type) }}
</text>
<text class="page">{{ item.p }}</text>
</view>
</view>
<view class="tools">
<view
class="copyBtn"
@click="copyList"
>
<image
src="@/devTools/page/static/copy.png"
class="copyIcon"
/>
</view>
</view>
</view>
</template>
<script>
import devCache from "../../../core/libs/devCache";
import objectAnalysis from "./objectAnalysis.vue";
export default {
components: {
objectAnalysis,
},
props: {
/**
* console单行数据
*/
item: {
type: Object,
default() {
return {
m: "",
tr: "",
date: "", // 打印的日期
p: "", // 打印的页面
type: "", // 打印类型
};
},
},
},
methods: {
/**
* 是否为对象类型
*/
isObj(data) {
return typeof data == "object";
},
/**
* 获取数据文字
*/
getText(data) {
switch (typeof data) {
case "string":
return data;
case "boolean":
return data ? "true" : "false";
case "undefined":
return "undefined";
case "function":
return "js:function";
case "symbol":
return "js:symbol";
default:
return data;
}
},
/**
* 复制列表
*/
copyList() {
let that = this;
uni.setClipboardData({
data: JSON.stringify([that.item.m, that.item.tr]),
});
},
/**
* 获取类型
*/
getType(type) {
let t = {
ve: "vue error",
vw: "vue warn",
oe: "App.vue onError",
n: "unknown",
};
return t[type];
},
/**
* 长按事件
*/
errorLongpress() {
let that = this;
let menu = [
{
text: `复制日志信息`,
click() {
uni.setClipboardData({
data: JSON.stringify(that.item),
});
},
},
{
text: `删除此记录`,
click() {
uni.$emit("devTools_delError", that.item);
let logs = devCache.get("errorReport");
if (!logs) logs = [];
let i = logs.findIndex(
(x) =>
x.type == that.item.type &&
x.t == that.item.t &&
x.m == that.item.m &&
x.tr == that.item.tr &&
x.p == that.item.p
);
if (i != -1) {
logs.splice(i, 1);
devCache.set("errorReport", logs);
}
uni.showToast({
title: "删除成功!",
icon: "success",
});
},
},
];
uni.showActionSheet({
itemList: menu.map((x) => x.text),
success({ tapIndex }) {
menu[tapIndex].click();
},
});
},
},
};
</script>
<style lang="scss" scoped>
.errorItem:active {
background-color: rgba(0, 0, 0, 0.03);
}
.errorItem {
display: flex;
flex-direction: row;
align-items: flex-start;
justify-content: space-between;
width: 750rpx;
padding: 10rpx 20rpx;
border-bottom: 1px solid rgba(0, 0, 0, 0.05);
&.type-vw {
background-color: rgb(255, 251, 229);
}
&.type-ve {
background-color: rgb(255, 240, 240);
}
&.type-oe {
background-color: rgb(255, 240, 240);
}
.content {
width: 670rpx;
display: flex;
flex-direction: column;
.context {
font-size: 20rpx;
color: #333;
line-height: 24rpx;
}
.msgBar {
display: flex;
flex-direction: row;
flex-wrap: wrap;
.time {
font-size: 16rpx;
color: #888;
/* #ifndef APP-PLUS */
min-width: 90rpx;
/* #endif */
}
.page {
font-size: 16rpx;
color: #888;
margin-left: 20rpx;
lines: 1;
overflow: hidden;
/* #ifndef APP-PLUS */
max-width: 450rpx;
white-space: nowrap;
/* #endif */
/* #ifdef APP-PLUS */
width: 450rpx;
/* #endif */
text-overflow: ellipsis;
}
.logType {
margin-left: 20rpx;
font-size: 16rpx;
padding: 0px 6rpx;
border-radius: 2px;
}
.type-ve {
color: #fff;
background-color: #fd0add;
}
.type-n {
color: #fff;
background-color: #82848a;
}
.type-vw {
color: #fff;
background-color: #ff9900;
}
.type-oe {
color: #fff;
background-color: #ff0000;
}
}
}
.tools {
width: 40rpx;
display: flex;
flex-direction: row-reverse;
margin-top: 6rpx;
.copy {
font-size: 20rpx;
color: #333;
line-height: 24rpx;
}
.copy:active {
background-color: red;
}
}
}
.copyBtn:active {
background-color: rgba(103, 194, 58, 0.6);
}
.copyBtn {
padding: 5rpx;
border-radius: 999rpx;
overflow: hidden;
background-color: #67c23a;
.copyIcon {
width: 20rpx;
height: 20rpx;
}
}
</style>
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!