37 Commits
Author SHA1 Message Date
frost-zx 2345ee9dcc chore(网址导航): 更新导航链接列表(#17 #18 #19) 2026-11-30 14:44:12 +08:00
frost-zx 8504af5f24 feat(工具箱): 添加新工具
- 待办事项
- Base64 字符串编码 / 解码
- URL 编码 / 解码
- 文本结构转换
- 转换 HTML 实体
- CSV 编辑
- frp 配置文件生成
- Minecraft UUID 转换
- Minecraft 区块位置计算
- 生成 Dynmap renderdata
2026-11-30 14:30:50 +08:00
frost-zx 760a457410 feat(工具箱/MSU2 USB 小屏幕控制): 增加“音频可视化 - 3” 2026-05-21 23:41:36 +08:00
frost-zx 58116ff311 fix(工具箱/MSU2 USB 小屏幕控制): 优化 renderAudioSpectrum 的算法 2026-05-21 23:40:54 +08:00
frost-zx b2d715a1b1 feat(工具箱/MSU2 USB 小屏幕控制): 支持设置屏幕亮度 2026-03-14 13:43:14 +08:00
frost-zx f31020d31c feat(工具箱/MSU2 USB 小屏幕控制): 支持设置屏幕捕获帧率,自动获取画布大小作为屏幕捕获分辨率 2026-03-13 22:29:59 +08:00
frost-zx 7e5100fc5c fix(工具箱/MSU2 USB 小屏幕控制): 修正 onBeforeUnmount 调用 2026-03-09 15:01:17 +08:00
frost-zx 9ca0619373 feat(工具箱/MSU2 USB 小屏幕控制): 添加屏幕捕获功能 2026-03-09 14:41:20 +08:00
frost-zx 02237e3e30 fix(app): 统一 gap 样式,移除无效的属性 2026-03-09 08:18:59 +08:00
frost-zx 2d805cf02d feat(工具箱/MSU2 USB 小屏幕控制): 完善功能
- 添加旧算法
- 支持设置显示方向
- 支持配置渲染间隔和发送间隔
2026-02-24 23:40:03 +08:00
frost-zx 266a1764be chore: 更新 package.json,“scripts”添加“dev-host”项 2026-02-22 22:40:02 +08:00
frost-zx 52d154e1a3 chore(工具箱/工作时间可视化): 调整界面文本,与其他模块统一 2026-02-22 17:44:15 +08:00
frost-zx 7deefc8ea3 feat(工具箱): 添加“MSU2 USB 小屏幕控制”工具 2026-02-22 17:43:22 +08:00
frost-zx 31b6a6ce2d chore: 安装 @types/w3c-web-serial 2026-02-22 17:42:37 +08:00
frost-zx 7b76410df8 chore: 更新 package.json,添加“license”项 2026-02-21 22:07:17 +08:00
frost-zx c836302f99 feat(工具箱): 添加“PNG 转 ICO 图标”工具 2026-01-26 00:11:38 +08:00
frost-zx ecadb6ce2a docs: 添加 project_rules.md 2026-01-26 00:11:06 +08:00
frost-zx 1ff42aa911 fix(工具箱/执行 JavaScript): 优化界面样式 2026-01-03 23:41:12 +08:00
frost-zx a666679ebd feat(工具箱): 添加“生成批量下载链接”工具 2026-01-03 23:40:47 +08:00
frost-zx 6cbbbe8541 chore(工具箱/保持亮屏): 调整界面样式,与其他模块统一 2026-01-03 19:43:22 +08:00
frost-zx dcd46b9afe fix(工具箱): 优化文本内容 2026-01-03 19:23:10 +08:00
frost-zx 13ed3a8fe4 refactor(工具箱): 优化逻辑,提取 MonacoEnvironment 配置 2026-01-03 19:04:10 +08:00
frost-zx 69e64fb08c feat(工具箱): 添加“执行 JavaScript”工具 2026-01-03 18:55:31 +08:00
frost-zx e6c35d25a5 feat(工具箱): 添加“UUID 生成器”工具 2026-01-03 17:22:32 +08:00
frost-zx 26947ee678 chore(工具箱): 调整工具项顺序 2026-01-03 17:07:45 +08:00
frost-zx fe8f1606fa feat(工具箱): 添加“计时器”工具 2025-12-30 19:12:22 +08:00
frost-zx b8113725bf feat(工具箱): 添加“文本编辑器”工具 2025-12-21 23:07:26 +08:00
frost-zx 66e1170c58 chore(app): 隐藏“MINECRAFT 联动控制”模块 2025-11-30 19:24:42 +08:00
frost-zx 359acb41d1 chore: 更新版本信息(V3.1.6) 2025-10-26 22:33:42 +08:00
frost-zx 6883e54a1b feat(工具箱): 添加“JSON 编辑器”工具 2025-10-26 22:31:46 +08:00
frost-zx 84273c3689 chore(app): 安装 monaco-editor 2025-10-26 22:23:20 +08:00
frost-zx 383280031c feat(工具箱): 添加“工作时间可视化”工具 2025-06-16 00:08:31 +08:00
frost-zx bca8602a3a refactor(app): 调整本地储存 key 命名 2025-06-15 18:44:29 +08:00
frost-zx 04c76dc347 docs: 更新 README 2025-06-14 20:55:31 +08:00
frost-zx d75232e5e0 feat(工具箱): 添加工具信息和工具更新日志显示 2025-06-04 23:38:16 +08:00
frost-zx ca27b2bbcc chore: 更新 package.json,添加 packageManager 配置项 2025-06-01 22:52:55 +08:00
frost-zx 6486a90812 chore: 更新依赖项的版本 2025-06-01 19:59:23 +08:00
55 changed files with 13904 additions and 1415 deletions
+3
View File
@@ -0,0 +1,3 @@
1. 项目采用 Vite + Vue 3 + Naive UI 组件库开发,图标库使用 Material Design Icons(@mdi/font)。
2. 项目使用 pnpm 作为包管理器。
3. 项目开发服务已启动,首页访问地址是 http://localhost:9000/,不需要重复启动。
+7
View File
@@ -1,5 +1,12 @@
# 更新日志 # 更新日志
## [3.1.6] - 2025-10-26
### Added
- `工具箱` 添加工具信息和工具更新日志显示。
- `工具箱` 添加“JSON 编辑器”工具。
## [3.1.5] - 2025-04-06 ## [3.1.5] - 2025-04-06
### Added ### Added
+9 -1
View File
@@ -2,7 +2,15 @@
## 简介 ## 简介
一个多功能的网址导航,绿色无广告。 一个使用 Vue 3 开发的网站导航和工具箱,绿色无广告。
![](./screenshots/image_01.png)
![](./screenshots/image_02.png)
![](./screenshots/image_03.png)
![](./screenshots/image_04.png)
## 使用方法 ## 使用方法
+4 -1
View File
@@ -7,7 +7,10 @@
"paths": { "paths": {
"@/*": ["./src/*"], "@/*": ["./src/*"],
"@package-json": ["./package.json"], "@package-json": ["./package.json"],
} },
"types": [
"@types/w3c-web-serial"
]
}, },
"exclude": [], "exclude": [],
"include": [ "include": [
+3 -1
View File
@@ -6,7 +6,9 @@
"noEmit": true, "noEmit": true,
"module": "ESNext", "module": "ESNext",
"moduleResolution": "Bundler", "moduleResolution": "Bundler",
"types": ["node"] "types": [
"@types/node"
]
}, },
"exclude": [], "exclude": [],
"include": [ "include": [
+23 -18
View File
@@ -1,41 +1,46 @@
{ {
"name": "frost-navigation", "name": "frost-navigation",
"description": "Frost Navigation", "description": "Frost Navigation",
"version": "3.1.5", "version": "3.1.6",
"license": "GPL-3.0-only",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
"dev-host": "vite dev --host 0.0.0.0",
"build": "vite build", "build": "vite build",
"preview": "vite preview", "preview": "vite preview",
"lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs --fix --ignore-path .gitignore" "lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs --fix --ignore-path .gitignore"
}, },
"packageManager": "pnpm@10.11.0",
"dependencies": { "dependencies": {
"@frost-utils/javascript": "^2.1.3", "@frost-utils/javascript": "^2.1.3",
"@mdi/font": "^7.4.47", "@mdi/font": "^7.4.47",
"@vueuse/core": "^12.5.0", "@vueuse/core": "^13.3.0",
"axios": "^1.7.9", "axios": "^1.9.0",
"dayjs": "^1.11.13", "dayjs": "^1.11.13",
"highlight.js": "^11.11.1", "highlight.js": "^11.11.1",
"lunisolar": "^2.5.1", "lunisolar": "^2.5.2",
"mathjs": "^14.2.0", "mathjs": "^14.5.2",
"monaco-editor": "^0.54.0",
"naive-ui": "^2.41.0", "naive-ui": "^2.41.0",
"radash": "^12.1.0", "radash": "^12.1.0",
"uuid": "^11.0.5", "uuid": "^11.1.0",
"vue": "^3.5.13", "vue": "^3.5.16",
"vue-router": "^4.5.0", "vue-router": "^4.5.1",
"zxing-wasm": "^2.0.1" "zxing-wasm": "^2.1.2"
}, },
"devDependencies": { "devDependencies": {
"@tsconfig/node20": "^20.1.4", "@tsconfig/node20": "^20.1.5",
"@types/node": "^20.17.16", "@types/node": "^20.17.57",
"@types/uuid": "^10.0.0", "@types/uuid": "^10.0.0",
"@vitejs/plugin-legacy": "^6.0.0", "@types/w3c-web-serial": "^1.0.8",
"@vitejs/plugin-vue": "^5.2.1", "@vitejs/plugin-legacy": "^6.1.1",
"@vitejs/plugin-vue-jsx": "^4.1.1", "@vitejs/plugin-vue": "^5.2.4",
"@vitejs/plugin-vue-jsx": "~4.1.2",
"@vue/tsconfig": "^0.7.0", "@vue/tsconfig": "^0.7.0",
"eslint": "^9.19.0", "eslint": "^9.28.0",
"eslint-plugin-vue": "^9.32.0", "eslint-plugin-vue": "^9.33.0",
"less": "^4.2.2", "less": "^4.3.0",
"vite": "^6.0.11" "vite": "^6.3.5"
} }
} }
+1319 -1224
View File
File diff suppressed because it is too large Load Diff
+3
View File
@@ -0,0 +1,3 @@
onlyBuiltDependencies:
- core-js
- esbuild
+24 -1
View File
@@ -1,4 +1,4 @@
window['NAV_LINK_DATE'] = '2025-02-03'; window['NAV_LINK_DATE'] = '2026-11-30';
window['NAV_LINK_LIST'] = [ window['NAV_LINK_LIST'] = [
{ {
@@ -69,6 +69,12 @@ window['NAV_LINK_LIST'] = [
date: '2021-02-08', date: '2021-02-08',
url: 'https://ctext.org/zhs', url: 'https://ctext.org/zhs',
}, },
{
title: '资料星球',
date: '2026-11-30',
desc: '中文学习与创作资料目录。可以按主题和关键词查找,打开条目查看说明,部分资料提供目录预览。',
url: 'https://resources.packscena.com/',
},
], ],
}, },
{ {
@@ -458,6 +464,12 @@ window['NAV_LINK_LIST'] = [
{ {
title: '开发', title: '开发',
children: [ children: [
{
title: 'agent-qa',
date: '2026-11-30',
desc: '自然语言 Web、Android 与 iOS 测试工具,结合运行证据、memidex 持久记忆与经验证的自我改进。',
url: 'https://vostride.com',
},
{ {
title: '前端', title: '前端',
children: [ children: [
@@ -1205,6 +1217,17 @@ window['NAV_LINK_LIST'] = [
title: '工具', title: '工具',
icon: 'mdi mdi-hammer-wrench', icon: 'mdi mdi-hammer-wrench',
children: [ children: [
{
title: 'AI',
children: [
{
title: 'Whizi',
date: '2026-11-30',
desc: '一个订阅使用 GPT、Claude、Gemini、Grok、DeepSeek 等 280+ 个 AI 模型,对话中可随时切换模型。',
url: 'https://whizi.io/',
}
]
},
{ {
title: '编辑', title: '编辑',
children: [ children: [
+1 -1
View File
@@ -1,2 +1,2 @@
zxing_full.wasm zxing_full.wasm
zxing-wasm v2.0.1 zxing-wasm v2.1.2
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

+11 -1
View File
@@ -122,7 +122,8 @@ function initCssVars() {
'--color-green': 'var(--color-success)', '--color-green': 'var(--color-success)',
'--color-blue': 'var(--color-info)', '--color-blue': 'var(--color-info)',
'--color-orange': 'var(--color-warning)', '--color-orange': 'var(--color-warning)',
// 滚动条大小 // 元素大小
'--dialog-content-max-height': 'calc(100vh - 160px)',
'--scrollbar-size': '8px', '--scrollbar-size': '8px',
}; };
@@ -265,6 +266,11 @@ html {
// -- Naive UI -- // -- Naive UI --
.n-dialog-content--with-max-height {
max-height: var(--dialog-content-max-height);
overflow-y: auto;
}
.n-drawer--right-placement { .n-drawer--right-placement {
.n-drawer-body { .n-drawer-body {
height: 0; height: 0;
@@ -275,4 +281,8 @@ html {
line-height: 1; line-height: 1;
} }
} }
.n-flex {
gap: 10px !important;
}
</style> </style>
+5 -5
View File
@@ -3,19 +3,19 @@
import { useLocalStorage } from '@vueuse/core'; import { useLocalStorage } from '@vueuse/core';
/** 本地储存 key 前缀 */ /** 本地储存 key 前缀 */
const PREFIX = 'frost-navigation/'; export const KEY_PREFIX = 'frost-navigation/';
/** NavView 模块 */ /** NavView 模块 */
export const storeNavView = { export const storeNavView = {
/** 导航链接侧边栏折叠状态 */ /** 导航链接侧边栏折叠状态 */
isAsideCollapsed: useLocalStorage(PREFIX + 'nav-view/is-aside-collapsed', false), isAsideCollapsed: useLocalStorage(KEY_PREFIX + 'nav-view/isAsideCollapsed', false),
/** 导航链接当前选中分类 */ /** 导航链接当前选中分类 */
currentCategory: useLocalStorage(PREFIX + 'nav-view/current-category', ''), currentCategory: useLocalStorage(KEY_PREFIX + 'nav-view/currentCategory', ''),
/** 导航链接搜索类型 */ /** 导航链接搜索类型 */
searchType: useLocalStorage(PREFIX + 'nav-view/search-type', 'all'), searchType: useLocalStorage(KEY_PREFIX + 'nav-view/searchType', 'all'),
}; };
@@ -23,6 +23,6 @@ export const storeNavView = {
export const storeSearchView = { export const storeSearchView = {
/** 当前使用的搜索引擎名称 */ /** 当前使用的搜索引擎名称 */
searchEngineName: useLocalStorage(PREFIX + 'search-view/search-engine-name', '必应'), searchEngineName: useLocalStorage(KEY_PREFIX + 'search-view/searchEngineName', '必应'),
}; };
+21
View File
@@ -0,0 +1,21 @@
import editorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker';
import jsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker';
import tsWorker from 'monaco-editor/esm/vs/language/typescript/ts.worker?worker';
/** 初始化 MonacoEnvironment */
export function initMonacoEnvironment() {
if (!self.MonacoEnvironment) {
// 配置编辑器环境(Service Worker 等)
self.MonacoEnvironment = {
getWorker(workerId, label) {
if (label === 'javascript' || label === 'typescript') {
return new tsWorker();
} else if (label === 'json') {
return new jsonWorker();
} else {
return new editorWorker();
}
},
};
}
}
+207
View File
@@ -0,0 +1,207 @@
/** PNG 转 ICO 图标,支持生成多尺寸 ICO */
class PNGtoICOConverter {
/**
* @description 将 PNG 图像转换为 ICO 格式
* @param {File|Blob|string} source PNG 文件、Blob 或 DataURL
* @param {number[]} sizes 需要生成的尺寸数组,默认 `[32, 128, 256]`
* @returns {Promise<Blob>} ICO 文件的 Blob 对象
*/
static async convert(source, sizes = [32, 128, 256]) {
try {
// 1. 加载 PNG 图像
let pngBlob = await this._preparePNG(source);
let imageBitmap = await createImageBitmap(pngBlob);
// 2. 创建各尺寸的图像
let imageDatas = await this._createMultiSizeImages(imageBitmap, sizes);
// 3. 生成 ICO 文件
let icoBlob = await this._generateICO(imageDatas);
return icoBlob;
} catch (error) {
throw new Error(`PNG 转 ICO 失败: ${error.message}`);
}
}
/**
* @description 准备 PNG 源数据
* @private
*/
static async _preparePNG(source) {
if (source instanceof File || source instanceof Blob) {
return source;
}
if (typeof source === 'string') {
if (source.startsWith('data:image/png')) {
const response = await fetch(source);
return await response.blob();
} else {
throw new Error('不支持的数据格式,仅支持 PNG 文件、Blob 或 DataURL');
}
}
throw new Error('无效的输入类型');
}
/**
* @description 创建多尺寸图像数据
* @private
*/
static async _createMultiSizeImages(imageBitmap, sizes) {
let results = [];
for (let size of sizes) {
// 按尺寸创建 Canvas
let canvas = document.createElement('canvas');
canvas.width = size;
canvas.height = size;
let ctx = canvas.getContext('2d');
// 设置高质量缩放
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';
// 绘制缩放后的图像
ctx.drawImage(imageBitmap, 0, 0, size, size);
// 获取 PNG 数据
let pngBlob = await new Promise(resolve => {
canvas.toBlob(resolve, 'image/png');
});
let arrayBuffer = await pngBlob.arrayBuffer();
results.push({
size,
width: size,
height: size,
data: new Uint8Array(arrayBuffer),
pngSize: arrayBuffer.byteLength
});
}
return results;
}
/**
* @description 生成 ICO 文件
* @private
*/
static async _generateICO(imageDatas) {
// ICO 文件结构:
// 1. ICONDIR 头 (6 字节)
// 2. ICONDIRENTRY 数组 (每个 16 字节)
// 3. PNG 数据
let numImages = imageDatas.length;
// 计算总大小
let totalSize = 6; // ICONDIR 头
totalSize += numImages * 16; // ICONDIRENTRY 数组
totalSize += imageDatas.reduce((sum, img) => sum + img.pngSize, 0);
// 创建 ArrayBuffer
let buffer = new ArrayBuffer(totalSize);
let view = new DataView(buffer);
let offset = 0;
// 1. 写入 ICONDIR 头
view.setUint16(offset, 0, true); // Reserved (0)
offset += 2;
view.setUint16(offset, 1, true); // Type (1 for ICO)
offset += 2;
view.setUint16(offset, numImages, true); // Number of images
offset += 2;
// 2. 写入 ICONDIRENTRY 数组
let dataOffset = 6 + (numImages * 16);
for (let img of imageDatas) {
// 宽度和高度 (0 表示 256 像素)
view.setUint8(offset, img.width === 256 ? 0 : img.width);
offset += 1;
view.setUint8(offset, img.height === 256 ? 0 : img.height);
offset += 1;
view.setUint8(offset, 0); // Color palette (0 for no palette)
offset += 1;
view.setUint8(offset, 0); // Reserved
offset += 1;
view.setUint16(offset, 1, true); // Color planes
offset += 2;
view.setUint16(offset, 32, true); // Bits per pixel
offset += 2;
view.setUint32(offset, img.pngSize, true); // PNG data size
offset += 4;
view.setUint32(offset, dataOffset, true); // PNG data offset
offset += 4;
dataOffset += img.pngSize;
}
// 3. 写入 PNG 数据
for (let img of imageDatas) {
let uint8View = new Uint8Array(buffer, offset, img.pngSize);
uint8View.set(img.data);
offset += img.pngSize;
}
return new Blob([buffer], { type: 'image/x-icon' });
}
/**
* @description 下载 ICO 文件
* @param {Blob} icoBlob ICO 文件的 Blob 对象
* @param {string} filename 下载的文件名
*/
static download(icoBlob, filename = 'icon.ico') {
let url = URL.createObjectURL(icoBlob);
let a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
}
/**
* @description 将 PNG 转换为 ICO 并下载
* @param {File|Blob|string} source PNG 文件、Blob 或 DataURL
* @param {number[]} sizes 需要生成的尺寸数组
* @param {string} filename 下载的文件名
*/
export async function convertPNGtoICO(source, sizes, filename) {
try {
let blob = await PNGtoICOConverter.convert(source, sizes);
PNGtoICOConverter.download(blob, filename);
return { blob: blob, error: '', success: true };
} catch (error) {
console.error('转换失败:', error);
return { blob: null, error: error.message, success: false };
}
}
+50
View File
@@ -0,0 +1,50 @@
/** 工具更新日志 */
export const CHANGE_LOGS = {
'todo-list': [
'[1] - 2026-11-18\n初始版本。\n支持选择本地文件夹读写数据(JSON 格式),数据版本升级前自动备份原文件;文件夹不可用时回退到浏览器本地存储,并支持 JSON 导入导出与外部修改冲突处理;\n支持待办分类的创建、重命名、删除与按分类筛选(数据版本 2 起使用,旧数据自动归入“默认”分类);\n界面基于 Naive UI 统一卡片、统计、标签、按钮与字体层级,危险操作按钮使用红色系配色;待办列表按 420px 最小卡片宽度自动填充列数,窄屏自动降为单列。',
],
'base64-encode-decode': [
'[1] - 2026-11-17\n初始版本。\n支持文本与 Base64 互转;\n支持 URL 安全字符集与按行批量处理。',
],
'calc-minecraft-chunk-location': [
'[1] - 2026-11-17\n初始版本。\n支持方块坐标与区块坐标互算,并显示区域文件、区块序号与头部记录位置。',
],
'convert-html-entities': [
'[1] - 2026-11-17\n初始版本。\n支持 HTML5 / XML 实体的编码与解码,编码支持普通与深度模式。',
],
'convert-text-structure': [
'[1] - 2026-11-17\n初始版本。\n支持倒序(左右、上下)与横竖互换(半角、全角)。',
],
'csv-editor': [
'[1] - 2026-11-17\n初始版本。\n支持导入 / 导出 CSV 文件、粘贴解析、单元格编辑、行列增删,并自动识别分隔符。',
],
'frp-config-generator': [
'[1] - 2026-11-17\n初始版本。\n支持生成 frpc / frps 的 TOML 与 INI 配置;\n支持 tcp、udp、http、https、stcp、xtcp 代理类型。',
],
'generate-minecraft-dynmap-renderdata': [
'[1] - 2026-11-17\n初始版本。\n支持生成 Dynmap 的 patchblock、texture、block 配置,并提供撤销、合并与本地记录功能。',
],
'json-formatter': [
'[2] - 2025-02-07\n优化“输出内容”显示样式,解决内容较多时行号显示不全的问题。',
'[1] - 2025-02-04\n初始版本。',
],
'keep-screen-on': [
'[3] - 2026-01-03\n调整界面样式,与其他模块统一。',
'[2] - 2024-10-13\n优化界面样式,背景添加圆角。',
'[1] - 2024-10-11\n初始版本。',
],
'minecraft-uuid-converter': [
'[1] - 2026-11-17\n初始版本。\n支持十六进制、UUID Most / Least 与整型数组之间的相互转换,并可随机生成 UUID V4。',
],
'msu2-usb-monitor-controller': [
'[2] - 2026-02-24\n完善功能:添加旧算法;支持设置显示方向;支持配置渲染间隔和发送间隔。',
'[1] - 2026-02-21\n初始版本。',
],
'qrcode-reader-and-generator': [
'[2] - 2025-02-23\n支持生成二维码。\n支持解析剪贴板中的二维码图片。\n优化解析功能,在二维码所在位置添加矩形标记。',
'[1] - 2025-02-21\n初始版本。',
],
'url-encode-decode': [
'[1] - 2026-11-17\n初始版本。\n支持 encodeURIComponent / encodeURI 及对应解码方式。',
],
};
+146 -53
View File
@@ -1,5 +1,7 @@
// 工具箱 // 工具箱
import { CHANGE_LOGS } from './toolbox-changelogs';
const MODULES = import.meta.glob('../../views/ToolboxView/**/*.vue'); const MODULES = import.meta.glob('../../views/ToolboxView/**/*.vue');
/** /**
@@ -47,10 +49,22 @@ export const toolList = [
title: 'Base64 字符串编码 / 解码', title: 'Base64 字符串编码 / 解码',
iconClass: 'mdi mdi-swap-horizontal', iconClass: 'mdi mdi-swap-horizontal',
desc: '处理 Base64 编码的字符串。', desc: '处理 Base64 编码的字符串。',
createdAt: '', createdAt: '2026-11-17',
updatedAt: '', updatedAt: '2026-11-17',
version: '0', version: '1',
enabled: false, enabled: true,
changelogs: CHANGE_LOGS['base64-encode-decode'],
},
{
id: 'png-to-ico',
component: 'Conversion/PngToIco',
title: 'PNG 转 ICO 图标',
iconClass: 'mdi mdi-image-outline',
desc: '将 PNG 图片转换为 ICO 图标。',
createdAt: '2026-01-26',
updatedAt: '2026-01-26',
version: '1',
enabled: true,
}, },
{ {
id: 'convert-timestamp', id: 'convert-timestamp',
@@ -69,10 +83,11 @@ export const toolList = [
title: 'URL 编码 / 解码', title: 'URL 编码 / 解码',
iconClass: 'mdi mdi-swap-horizontal', iconClass: 'mdi mdi-swap-horizontal',
desc: '处理 URL 编码的字符串。', desc: '处理 URL 编码的字符串。',
createdAt: '', createdAt: '2026-11-17',
updatedAt: '', updatedAt: '2026-11-17',
version: '0', version: '1',
enabled: false, enabled: true,
changelogs: CHANGE_LOGS['url-encode-decode'],
}, },
{ {
id: 'qrcode-reader-and-generator', id: 'qrcode-reader-and-generator',
@@ -84,6 +99,7 @@ export const toolList = [
updatedAt: '2025-02-23', updatedAt: '2025-02-23',
version: '2', version: '2',
enabled: true, enabled: true,
changelogs: CHANGE_LOGS['qrcode-reader-and-generator'],
}, },
{ {
id: 'convert-text-structure', id: 'convert-text-structure',
@@ -91,21 +107,23 @@ export const toolList = [
title: '文本结构转换', title: '文本结构转换',
iconClass: 'mdi mdi-swap-horizontal', iconClass: 'mdi mdi-swap-horizontal',
desc: '倒序、横竖互换等', desc: '倒序、横竖互换等',
createdAt: '', createdAt: '2026-11-17',
updatedAt: '', updatedAt: '2026-11-17',
version: '0', version: '1',
enabled: false, enabled: true,
changelogs: CHANGE_LOGS['convert-text-structure'],
}, },
{ {
id: 'convert-html-entities', id: 'convert-html-entities',
component: 'Conversion/ConvertHtmlEntities', component: 'Conversion/ConvertHtmlEntities',
title: '转换 HTML 实体', title: '转换 HTML 实体',
iconClass: 'mdi mdi-swap-horizontal', iconClass: 'mdi mdi-swap-horizontal',
desc: '', desc: '编码 / 解码 HTML、XML 实体。',
createdAt: '', createdAt: '2026-11-17',
updatedAt: '', updatedAt: '2026-11-17',
version: '0', version: '1',
enabled: false, enabled: true,
changelogs: CHANGE_LOGS['convert-html-entities'],
}, },
] ]
}, },
@@ -120,10 +138,22 @@ export const toolList = [
title: 'CSV 编辑', title: 'CSV 编辑',
iconClass: 'mdi mdi-table-edit', iconClass: 'mdi mdi-table-edit',
desc: '查看或编辑 CSV 文件', desc: '查看或编辑 CSV 文件',
createdAt: '', createdAt: '2026-11-17',
updatedAt: '', updatedAt: '2026-11-17',
version: '0', version: '1',
enabled: false, enabled: true,
changelogs: CHANGE_LOGS['csv-editor'],
},
{
id: 'json-editor',
component: 'Edit/JsonEditor',
title: 'JSON 编辑器',
iconClass: 'mdi mdi-code-json',
desc: '基于 Monaco Editor 实现的 JSON 编辑器。',
createdAt: '2025-10-26',
updatedAt: '2025-10-26',
version: '1',
enabled: true,
}, },
{ {
id: 'json-formatter', id: 'json-formatter',
@@ -135,6 +165,18 @@ export const toolList = [
updatedAt: '2025-02-07', updatedAt: '2025-02-07',
version: '2', version: '2',
enabled: true, enabled: true,
changelogs: CHANGE_LOGS['json-formatter'],
},
{
id: 'text-editor',
component: 'Edit/TextEditor',
title: '文本编辑器',
iconClass: 'mdi mdi-text-long',
desc: '基于 Monaco Editor 实现的文本编辑器。',
createdAt: '2025-12-21',
updatedAt: '2025-12-21',
version: '1',
enabled: true,
}, },
], ],
}, },
@@ -149,21 +191,22 @@ export const toolList = [
title: 'frp 配置文件生成', title: 'frp 配置文件生成',
iconClass: 'mdi mdi-file-cog-outline', iconClass: 'mdi mdi-file-cog-outline',
desc: '生成用于 frpc、frps 的配置文件。', desc: '生成用于 frpc、frps 的配置文件。',
createdAt: '', createdAt: '2026-11-17',
updatedAt: '', updatedAt: '2026-11-17',
version: '0', version: '1',
enabled: false, enabled: true,
changelogs: CHANGE_LOGS['frp-config-generator'],
}, },
{ {
id: 'frp-config-generator', id: 'uuid-generator',
component: 'Generator/UuidGenerator', component: 'Generator/UuidGenerator',
title: 'UUID 生成器', title: 'UUID 生成器',
iconClass: 'mdi mdi-identifier', iconClass: 'mdi mdi-identifier',
desc: '生成 UUID 列表。', desc: '生成 UUID 列表。',
createdAt: '', createdAt: '2026-01-03',
updatedAt: '', updatedAt: '2026-01-03',
version: '0', version: '1',
enabled: false, enabled: true,
}, },
{ {
id: 'generate-urls', id: 'generate-urls',
@@ -171,10 +214,10 @@ export const toolList = [
title: '生成批量下载链接', title: '生成批量下载链接',
iconClass: 'mdi mdi-link-variant', iconClass: 'mdi mdi-link-variant',
desc: '根据设置,生成有一定规律的用于批量下载的链接。', desc: '根据设置,生成有一定规律的用于批量下载的链接。',
createdAt: '', createdAt: '2026-01-03',
updatedAt: '', updatedAt: '2026-01-03',
version: '0', version: '1',
enabled: false, enabled: true,
}, },
{ {
id: 'generate-random-string', id: 'generate-random-string',
@@ -200,10 +243,11 @@ export const toolList = [
title: 'Minecraft UUID 转换', title: 'Minecraft UUID 转换',
iconClass: 'mdi mdi-identifier', iconClass: 'mdi mdi-identifier',
desc: '随机生成或转换 Minecraft 的 UUID。', desc: '随机生成或转换 Minecraft 的 UUID。',
createdAt: '', createdAt: '2026-11-17',
updatedAt: '', updatedAt: '2026-11-17',
version: '0', version: '1',
enabled: false, enabled: true,
changelogs: CHANGE_LOGS['minecraft-uuid-converter'],
}, },
{ {
id: 'minecraft-chat-history-reader', id: 'minecraft-chat-history-reader',
@@ -221,11 +265,12 @@ export const toolList = [
component: 'Minecraft/CalcChunkLocation', component: 'Minecraft/CalcChunkLocation',
title: 'Minecraft 区块位置计算', title: 'Minecraft 区块位置计算',
iconClass: 'mdi mdi-calculator-variant-outline', iconClass: 'mdi mdi-calculator-variant-outline',
desc: '', desc: '根据方块坐标计算所属区块、区域文件位置等信息。',
createdAt: '', createdAt: '2026-11-17',
updatedAt: '', updatedAt: '2026-11-17',
version: '0', version: '1',
enabled: false, enabled: true,
changelogs: CHANGE_LOGS['calc-minecraft-chunk-location'],
}, },
{ {
id: 'generate-minecraft-dynmap-renderdata', id: 'generate-minecraft-dynmap-renderdata',
@@ -233,10 +278,11 @@ export const toolList = [
title: '生成 Dynmap renderdata', title: '生成 Dynmap renderdata',
iconClass: 'mdi mdi-file-outline', iconClass: 'mdi mdi-file-outline',
desc: '生成用于 Minecraft Dynmap 插件或模组的 renderdata 数据。', desc: '生成用于 Minecraft Dynmap 插件或模组的 renderdata 数据。',
createdAt: '', createdAt: '2026-11-17',
updatedAt: '', updatedAt: '2026-11-17',
version: '0', version: '1',
enabled: false, enabled: true,
changelogs: CHANGE_LOGS['generate-minecraft-dynmap-renderdata'],
}, },
] ]
}, },
@@ -263,6 +309,18 @@ export const toolList = [
title: '其他', title: '其他',
enabled: true, enabled: true,
items: [ items: [
{
id: 'todo-list',
component: 'Other/TodoList/TodoList',
title: '待办事项',
iconClass: 'mdi mdi-format-list-checks',
desc: '管理待办事项与待办分类,数据以 JSON 格式保存在所选的本地文件夹中。',
createdAt: '2026-11-17',
updatedAt: '2026-11-18',
version: '1',
enabled: true,
changelogs: CHANGE_LOGS['todo-list'],
},
{ {
id: 'keep-screen-on', id: 'keep-screen-on',
component: 'Other/KeepScreenOn', component: 'Other/KeepScreenOn',
@@ -270,8 +328,31 @@ export const toolList = [
iconClass: 'mdi mdi-monitor', iconClass: 'mdi mdi-monitor',
desc: '保持屏幕开启,不息屏,不休眠。', desc: '保持屏幕开启,不息屏,不休眠。',
createdAt: '2024-10-11', createdAt: '2024-10-11',
updatedAt: '2024-10-13', updatedAt: '2026-01-03',
version: '2', version: '3',
enabled: true,
changelogs: CHANGE_LOGS['keep-screen-on'],
},
{
id: 'visualized-working-hours',
component: 'Other/VisualizedWorkingHours/VisualizedWorkingHours',
title: '工作时间可视化',
iconClass: 'mdi mdi-clock-digital',
desc: '用趣味化的方式呈现工作收益与时间进度,让薪资进度和下班期待看得见。',
createdAt: '',
updatedAt: '',
version: '0',
enabled: false,
},
{
id: 'timer-tool',
component: 'Other/TimerTool',
title: '计时器',
iconClass: 'mdi mdi-timer-outline',
desc: '正计时、倒计时工具。',
createdAt: '2025-12-29',
updatedAt: '2025-12-29',
version: '1',
enabled: true, enabled: true,
}, },
{ {
@@ -291,10 +372,22 @@ export const toolList = [
title: '执行 JavaScript', title: '执行 JavaScript',
iconClass: 'mdi mdi-code-braces', iconClass: 'mdi mdi-code-braces',
desc: '执行简单的 JavaScript 代码片段。', desc: '执行简单的 JavaScript 代码片段。',
createdAt: '', createdAt: '2026-01-03',
updatedAt: '', updatedAt: '2026-01-03',
version: '0', version: '1',
enabled: false, enabled: true,
},
{
id: 'msu2-usb-monitor-controller',
component: 'Other/Msu2UsbMonitorController/Msu2UsbMonitorController',
title: 'MSU2 USB 小屏幕控制',
iconClass: 'mdi mdi-usb',
desc: 'MSU2 USB 小屏幕控制工具,参考了原 Python 程序的代码。',
createdAt: '2026-02-21',
updatedAt: '2026-02-24',
version: '2',
enabled: true,
changelogs: CHANGE_LOGS['msu2-usb-monitor-controller'],
}, },
{ {
id: 'genshin-impact-clock', id: 'genshin-impact-clock',
+2 -2
View File
@@ -1,6 +1,6 @@
// 模块显示配置 // 模块显示配置
import { IS_DEV } from './env'; // import { IS_DEV } from './env';
/** 启用模块 */ /** 启用模块 */
export const ABOUT_MODULE_ENABLED = true; export const ABOUT_MODULE_ENABLED = true;
@@ -9,7 +9,7 @@ export const ABOUT_MODULE_ENABLED = true;
export const ABOUT_MODULE_TITLE = '关于'; export const ABOUT_MODULE_TITLE = '关于';
/** 启用模块 */ /** 启用模块 */
export const MC_CTRL_MODULE_ENABLED = IS_DEV; export const MC_CTRL_MODULE_ENABLED = false;
/** 模块标题 */ /** 模块标题 */
export const MC_CTRL_MODULE_TITLE = 'MINECRAFT 联动控制'; export const MC_CTRL_MODULE_TITLE = 'MINECRAFT 联动控制';
@@ -1,8 +1,8 @@
<template> <template>
<div class="tool-detail-page"> <div class="tool-detail-page">
<!-- 参数 --> <!-- 配置参数 -->
<n-card size="small" title="参数"> <n-card size="small" title="配置参数">
<n-form <n-form
class="form-no-feedback" class="form-no-feedback"
label-align="right" label-align="right"
@@ -1,9 +1,318 @@
<template> <template>
<div class="tool-detail-page"></div> <div class="tool-detail-page">
<!-- 转换设置 -->
<n-card size="small" title="转换设置">
<n-form
class="form-no-feedback"
label-align="right"
label-placement="left"
label-width="auto"
>
<n-form-item label="转换模式:">
<n-select
v-model:value="setting.mode"
:options="[
{ label: '文本 -> Base64', value: 'encode' },
{ label: 'Base64 -> 文本', value: 'decode' },
]"
/>
</n-form-item>
<n-form-item label="选项:">
<n-flex>
<n-checkbox
v-model:checked="setting.urlSafe"
>URL 安全(使用 -、_ 替换 +、/,并移除填充符 =)</n-checkbox>
</n-flex>
</n-form-item>
<n-form-item label="选项:">
<n-flex>
<n-checkbox
v-model:checked="setting.byLine"
>按行独立处理(每行分别编码 / 解码)</n-checkbox>
</n-flex>
</n-form-item>
</n-form>
</n-card>
<!-- 操作 -->
<n-card size="small" title="操作">
<n-flex>
<n-button
type="primary"
@click="handleConvert"
>{{ setting.mode === 'encode' ? '编码' : '解码' }}</n-button>
<n-button
:disabled="!outputText"
@click="handleSwap"
>交换输入输出</n-button>
<n-button
type="primary"
:disabled="!outputText"
@click="handleCopy"
>复制结果</n-button>
<n-button
type="error"
:disabled="!inputText && !outputText"
@click="handleClear"
>清空</n-button>
</n-flex>
</n-card>
<!-- 输入内容 -->
<n-card size="small" title="输入内容">
<template #header-extra>{{ inputText.length }} 字符</template>
<n-input
v-model:value="inputText"
class="monospace-input"
:placeholder="inputPlaceholder"
type="textarea"
:rows="8"
:autosize="false"
></n-input>
</n-card>
<!-- 输出内容 -->
<n-card size="small" title="输出内容">
<template #header-extra>{{ outputText.length }} 字符</template>
<n-input
v-model:value="outputText"
class="monospace-input"
:placeholder="outputPlaceholder"
type="textarea"
:rows="8"
:readonly="true"
:autosize="false"
></n-input>
</n-card>
</div>
</template> </template>
<script setup> <script setup>
import {
NButton, NCard, NCheckbox, NFlex,
NForm, NFormItem, NInput, NSelect,
} from 'naive-ui';
import {
computed, reactive, ref,
} from 'vue';
import {
$message,
} from '@/assets/js/naive-ui';
import {
useClipboard,
} from '@vueuse/core';
/** 剪贴板 */
const clipboard = useClipboard({
legacy: true,
read: false,
});
/** 设置项 */
const setting = reactive({
/** 是否按行独立处理 */
byLine: false,
/** 转换模式(encode - 编码,decode - 解码) */
mode: 'encode',
/** 是否启用 URL 安全模式 */
urlSafe: false,
});
/** 输入内容 */
const inputText = ref('');
/** 输出内容 */
const outputText = ref('');
/** 输入框占位文本 */
const inputPlaceholder = computed(() => {
return (setting.mode === 'encode' ? '请输入需要编码的文本' : '请输入需要解码的 Base64 字符串');
});
/** 输出框占位文本 */
const outputPlaceholder = computed(() => {
return (setting.mode === 'encode' ? '编码结果将显示在这里' : '解码结果将显示在这里');
});
/**
* @description 将字符串转换为 Base64
* @param {string} text 原文本
* @param {boolean} urlSafe 是否为 URL 安全模式
* @returns {string} Base64 字符串
*/
function encodeBase64(text, urlSafe = false) {
let bytes = new TextEncoder().encode(text);
let binary = '';
let chunkSize = 0x8000;
// 分块处理,防止内容较多时参数过多导致异常
for (let i = 0; i < bytes.length; i += chunkSize) {
binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));
}
let result = btoa(binary);
// URL 安全模式:替换字符并移除填充符
if (urlSafe) {
result = result.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');
}
return result;
}
/**
* @description 将 Base64 字符串解码为文本
* @param {string} text Base64 字符串
* @returns {string} 解码后的文本
*/
function decodeBase64(text) {
let base64 = text.trim();
// 兼容 URL 安全模式,并补齐填充符
base64 = base64.replace(/-/g, '+').replace(/_/g, '/');
let remainder = base64.length % 4;
if (remainder > 0) {
base64 += '='.repeat(4 - remainder);
}
let binary = atob(base64);
let bytes = Uint8Array.from(binary, (char) => {
return char.charCodeAt(0);
});
return new TextDecoder().decode(bytes);
}
/**
* @description 处理单行内容
* @param {string} line 单行文本
* @returns {string} 转换结果
*/
function convertLine(line) {
return (setting.mode === 'encode'
? encodeBase64(line, setting.urlSafe)
: decodeBase64(line));
}
/** 处理转换 */
function handleConvert() {
if (!inputText.value) {
$message.warning('请输入需要转换的内容');
return;
}
let source = inputText.value;
let result = '';
let errorLines = [];
if (setting.byLine) {
let lines = source.split('\n');
let results = [];
lines.forEach((line, index) => {
// 空行直接保留,便于与原文对照
if (!line) {
results.push('');
return;
}
try {
results.push(convertLine(line));
} catch (error) {
console.warn(`第 ${index + 1} 行转换失败:`, error);
errorLines.push(index + 1);
results.push('');
}
});
result = results.join('\n');
} else {
try {
result = convertLine(source);
} catch (error) {
console.warn('转换失败:', error);
$message.error('转换失败:内容格式不正确');
return;
}
}
outputText.value = result;
if (errorLines.length > 0) {
$message.error(`转换完成,但有 ${errorLines.length} 行失败(第 ${errorLines.slice(0, 5).join('、')} 行)`);
} else {
$message.success('转换成功');
}
}
/** 交换输入与输出内容 */
function handleSwap() {
let temp = inputText.value;
inputText.value = outputText.value;
outputText.value = temp;
setting.mode = (setting.mode === 'encode' ? 'decode' : 'encode');
}
/** 复制结果 */
function handleCopy() {
if (!clipboard.isSupported) {
$message.error('复制失败:当前浏览器不支持该操作');
return Promise.resolve();
}
return clipboard.copy(outputText.value).then(() => {
$message.success('复制成功');
}).catch((error) => {
console.error('复制失败:');
console.error(error);
$message.error('复制失败:异常');
});
}
/** 清空内容 */
function handleClear() {
inputText.value = '';
outputText.value = '';
}
</script> </script>
<style lang="less" scoped> <style lang="less" scoped>
.monospace-input {
font-family: monospace;
}
:deep(.n-input) {
max-width: 64em;
}
</style> </style>
@@ -1,9 +1,388 @@
<template> <template>
<div class="tool-detail-page"></div> <div class="tool-detail-page">
<!-- 转换设置 -->
<n-card size="small" title="转换设置">
<n-form
class="form-no-feedback"
label-align="right"
label-placement="left"
label-width="auto"
>
<n-form-item label="转换模式:">
<n-select
v-model:value="setting.mode"
:options="[
{ label: '编码(文本 -> 实体)', value: 'encode' },
{ label: '解码(实体 -> 文本)', value: 'decode' },
]"
/>
</n-form-item>
<n-form-item label="实体级别:">
<n-select
v-model:value="setting.level"
:options="[
{ label: 'HTML5', value: 'html5' },
{ label: 'XML', value: 'xml' },
]"
/>
</n-form-item>
<n-form-item
v-show="setting.mode === 'encode'"
label="编码深度:"
>
<n-select
v-model:value="setting.depth"
:options="[
{ label: '普通(仅转义特殊字符)', value: 'normal' },
{ label: '深度(额外转换非 ASCII 字符)', value: 'deep' },
]"
/>
</n-form-item>
</n-form>
</n-card>
<!-- 操作 -->
<n-card size="small" title="操作">
<n-flex>
<n-button
type="primary"
@click="handleConvert"
>{{ setting.mode === 'encode' ? '编码' : '解码' }}</n-button>
<n-button
:disabled="!outputText"
@click="handleSwap"
>交换输入输出</n-button>
<n-button
type="primary"
:disabled="!outputText"
@click="handleCopy"
>复制结果</n-button>
<n-button
type="error"
:disabled="!inputText && !outputText"
@click="handleClear"
>清空</n-button>
</n-flex>
</n-card>
<!-- 输入内容 -->
<n-card size="small" title="输入内容">
<template #header-extra>{{ inputText.length }} 字符</template>
<n-input
v-model:value="inputText"
class="monospace-input"
:placeholder="inputPlaceholder"
type="textarea"
:rows="8"
:autosize="false"
></n-input>
</n-card>
<!-- 输出内容 -->
<n-card size="small" title="输出内容">
<template #header-extra>{{ outputText.length }} 字符</template>
<n-input
v-model:value="outputText"
class="monospace-input"
:placeholder="outputPlaceholder"
type="textarea"
:rows="8"
:readonly="true"
:autosize="false"
></n-input>
</n-card>
<!-- 说明 -->
<n-card size="small" title="说明">
<div class="tip-text">
<p>“普通”模式仅转义 <code>&amp;</code>、<code>&lt;</code>、<code>&gt;</code>、<code>"</code>、<code>'</code> 5 个特殊字符。</p>
<p>“深度”模式会在此基础上,将非 ASCII 字符转换为数字实体(如 <code>&amp;#20013;</code>)。</p>
<p>HTML5 级别解码时支持全部 HTML 命名实体;XML 级别仅支持 XML 预定义的 5 个命名实体及数字实体。</p>
</div>
</n-card>
</div>
</template> </template>
<script setup> <script setup>
import {
NButton, NCard, NFlex,
NForm, NFormItem, NInput, NSelect,
} from 'naive-ui';
import {
computed, reactive, ref,
} from 'vue';
import {
$message,
} from '@/assets/js/naive-ui';
import {
useClipboard,
} from '@vueuse/core';
/** 剪贴板 */
const clipboard = useClipboard({
legacy: true,
read: false,
});
/** XML 预定义命名实体 */
const XML_NAMED_ENTITIES = {
amp: '&',
apos: '\'',
gt: '>',
lt: '<',
quot: '"',
};
/** 设置项 */
const setting = reactive({
/** 编码深度(normal - 普通,deep - 深度) */
depth: 'normal',
/** 实体级别(html5 - HTML5,xml - XML) */
level: 'html5',
/** 转换模式(encode - 编码,decode - 解码) */
mode: 'encode',
});
/** 输入内容 */
const inputText = ref('');
/** 输出内容 */
const outputText = ref('');
/** 输入框占位文本 */
const inputPlaceholder = computed(() => {
return (setting.mode === 'encode' ? '请输入需要编码的文本' : '请输入需要解码的 HTML 实体字符串');
});
/** 输出框占位文本 */
const outputPlaceholder = computed(() => {
return (setting.mode === 'encode' ? '编码结果将显示在这里' : '解码结果将显示在这里');
});
/**
* @description 转义特殊字符
* @param {string} char 单个字符
* @param {string} level 实体级别(html5、xml)
* @returns {string} 转义结果
*/
function escapeSpecialChar(char, level) {
switch (char) {
case '&':
return '&amp;';
case '<':
return '&lt;';
case '>':
return '&gt;';
case '"':
return '&quot;';
case '\'':
return (level === 'xml' ? '&apos;' : '&#39;');
default:
return null;
}
}
/**
* @description 编码 HTML / XML 实体
* @param {string} text 原文本
* @param {string} level 实体级别(html5、xml)
* @param {boolean} isDeep 是否为深度编码
* @returns {string} 编码后的文本
*/
function encodeEntities(text, level = 'html5', isDeep = false) {
let result = '';
// 按 Unicode 码点遍历,保证代理对(如 Emoji)能被正确处理
for (let char of text) {
let escaped = escapeSpecialChar(char, level);
if (escaped) {
result += escaped;
continue;
}
let code = char.codePointAt(0);
// 深度模式:将非 ASCII 字符转换为数字实体
if (isDeep && code > 127) {
result += `&#${code};`;
continue;
}
result += char;
}
return result;
}
/**
* @description 解码数字实体
* @param {string} text 原文本
* @returns {string} 解码后的文本
*/
function decodeNumericEntities(text) {
return text.replace(/&#(x[0-9a-fA-F]+|[0-9]+);/g, (match, content) => {
let code = (content[0] === 'x' || content[0] === 'X'
? parseInt(content.slice(1), 16)
: parseInt(content, 10));
// 排除无效码点
if (!Number.isFinite(code) || code < 0 || code > 0x10FFFF) {
return match;
}
try {
return String.fromCodePoint(code);
} catch (error) {
console.warn('解码数字实体失败:', match, error);
return match;
}
});
}
/**
* @description 解码 HTML5 实体(借助浏览器的 HTML 解析能力,支持全部命名实体)
* @param {string} text 原文本
* @returns {string} 解码后的文本
*/
function decodeHtml5Entities(text) {
let textarea = document.createElement('textarea');
// 注:textarea 的 innerHTML 按 RCDATA 解析,不会生成实际节点,仅做实体解码
textarea.innerHTML = text;
return textarea.value;
}
/**
* @description 解码 XML 实体(仅支持预定义的 5 个命名实体及数字实体)
* @param {string} text 原文本
* @returns {string} 解码后的文本
*/
function decodeXmlEntities(text) {
return text.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|[a-zA-Z][a-zA-Z0-9]*);/g, (match, content) => {
// 数字实体
if (content[0] === '#') {
return decodeNumericEntities(match);
}
// 命名实体
let value = XML_NAMED_ENTITIES[content];
return (value === undefined ? match : value);
});
}
/** 处理转换 */
function handleConvert() {
if (!inputText.value) {
$message.warning('请输入需要转换的内容');
return;
}
let result = '';
if (setting.mode === 'encode') {
result = encodeEntities(inputText.value, setting.level, setting.depth === 'deep');
} else if (setting.level === 'html5') {
result = decodeHtml5Entities(inputText.value);
} else {
result = decodeXmlEntities(inputText.value);
}
outputText.value = result;
$message.success('转换成功');
}
/** 交换输入与输出内容 */
function handleSwap() {
let temp = inputText.value;
inputText.value = outputText.value;
outputText.value = temp;
setting.mode = (setting.mode === 'encode' ? 'decode' : 'encode');
}
/** 复制结果 */
function handleCopy() {
if (!clipboard.isSupported) {
$message.error('复制失败:当前浏览器不支持该操作');
return Promise.resolve();
}
return clipboard.copy(outputText.value).then(() => {
$message.success('复制成功');
}).catch((error) => {
console.error('复制失败:');
console.error(error);
$message.error('复制失败:异常');
});
}
/** 清空内容 */
function handleClear() {
inputText.value = '';
outputText.value = '';
}
</script> </script>
<style lang="less" scoped> <style lang="less" scoped>
.monospace-input {
font-family: monospace;
}
.tip-text {
color: #666;
font-size: 14px;
line-height: 1.8;
p {
margin: 0;
}
code {
padding: 0 4px;
border-radius: 2px;
background-color: #F5F5F5;
font-family: monospace;
}
}
:deep(.n-input) {
max-width: 64em;
}
</style> </style>
@@ -1,9 +1,272 @@
<template> <template>
<div class="tool-detail-page"></div> <div class="tool-detail-page">
<!-- 转换设置 -->
<n-card size="small" title="转换设置">
<n-form
class="form-no-feedback"
label-align="right"
label-placement="left"
label-width="auto"
>
<n-form-item label="转换模式:">
<n-select
v-model:value="mode"
:options="modeOptions"
/>
</n-form-item>
<n-form-item label="说明:">
<div class="tip-text">{{ modeDescription }}</div>
</n-form-item>
</n-form>
</n-card>
<!-- 操作 -->
<n-card size="small" title="操作">
<n-flex>
<n-button
type="primary"
@click="handleConvert"
>转换</n-button>
<n-button
:disabled="!outputText"
@click="handleCopy"
>复制结果</n-button>
<n-button
type="error"
:disabled="!inputText && !outputText"
@click="handleClear"
>清空</n-button>
</n-flex>
</n-card>
<!-- 输入内容 -->
<n-card size="small" title="输入内容">
<template #header-extra>{{ inputLineCount }} 行 / {{ inputText.length }} 字符</template>
<n-input
v-model:value="inputText"
class="monospace-input"
placeholder="请输入需要转换的文本"
type="textarea"
:rows="10"
:autosize="false"
></n-input>
</n-card>
<!-- 输出内容 -->
<n-card size="small" title="转换结果">
<template #header-extra>{{ outputLineCount }} 行 / {{ outputText.length }} 字符</template>
<n-input
v-model:value="outputText"
class="monospace-input"
placeholder="转换结果将显示在这里"
type="textarea"
:rows="10"
:readonly="true"
:autosize="false"
></n-input>
</n-card>
</div>
</template> </template>
<script setup> <script setup>
import {
NButton, NCard, NFlex,
NForm, NFormItem, NInput, NSelect,
} from 'naive-ui';
import {
computed, ref,
} from 'vue';
import {
$message,
} from '@/assets/js/naive-ui';
import {
useClipboard,
} from '@vueuse/core';
/** 剪贴板 */
const clipboard = useClipboard({
legacy: true,
read: false,
});
/** 转换模式选项 */
const modeOptions = [
{ label: '倒序(左右)', value: 'reverse-h' },
{ label: '倒序(上下)', value: 'reverse-v' },
{ label: '横竖互换(半角,1 空格)', value: 'horizon-vertical-normal' },
{ label: '横竖互换(全角,2 空格)', value: 'horizon-vertical-full' },
];
/** 当前转换模式 */
const mode = ref('reverse-h');
/** 输入内容 */
const inputText = ref('');
/** 转换结果 */
const outputText = ref('');
/** 输入内容行数 */
const inputLineCount = computed(() => {
return (inputText.value ? inputText.value.split('\n').length : 0);
});
/** 输出内容行数 */
const outputLineCount = computed(() => {
return (outputText.value ? outputText.value.split('\n').length : 0);
});
/** 当前模式说明 */
const modeDescription = computed(() => {
return (modeOptions.find((item) => {
return item.value === mode.value;
})?.label || '');
});
/**
* @description 倒序(横向)
* @param {string} text 原文本
* @returns {string} 转换后的文本
*/
function convertReverseHorizontal(text) {
return text.split('\n').map((line) => {
return line.split('').reverse().join('');
}).join('\n');
}
/**
* @description 倒序(竖向)
* @param {string} text 原文本
* @returns {string} 转换后的文本
*/
function convertReverseVertical(text) {
return text.split('\n').reverse().join('\n');
}
/**
* @description 横竖互换
* @param {string} text 原文本
* @param {boolean} isFullAngle 是否使用全角空格
* @returns {string} 转换后的文本
*/
function convertHorizontalVertical(text, isFullAngle = false) {
// 空格字符:全角时为 2 个半角空格,半角时为 1 个空格
let spaceChar = (isFullAngle ? ' ' : ' ');
// 空格 Unicode:&emsp; / &nbsp;
let spaceUnicode = (isFullAngle ? '\u2003' : '\u2002');
let spaceRegChar = new RegExp(spaceChar, 'g');
let spaceRegUnicode = new RegExp(spaceUnicode, 'g');
let inputs = text.split('\n');
// 统一空格字符,并记录每一行的长度
inputs = inputs.map((row) => {
return row.replace(spaceRegChar, spaceUnicode);
});
let inputLens = inputs.map((row) => {
return row.length;
});
let inputLenMax = (inputs.length > 0 ? Math.max(...inputLens) : 0);
// 创建与最长行等长的空行
let outputs = [];
for (let i = 0; i < inputLenMax; i++) {
outputs.push([]);
}
// 行列互换(不足的位置使用空格补齐)
inputs.forEach((row, rowIndex) => {
for (let i = 0; i < inputLenMax; i++) {
let char = (row.charAt(i) || spaceUnicode);
outputs[i][rowIndex] = char;
}
});
// 合并行内容,并还原空格字符
return outputs.map((row) => {
return row.join('').replace(spaceRegUnicode, spaceChar);
}).join('\n');
}
/** 处理转换 */
function handleConvert() {
if (!inputText.value) {
$message.warning('请输入需要转换的内容');
return;
}
switch (mode.value) {
case 'reverse-h':
outputText.value = convertReverseHorizontal(inputText.value);
break;
case 'reverse-v':
outputText.value = convertReverseVertical(inputText.value);
break;
case 'horizon-vertical-normal':
outputText.value = convertHorizontalVertical(inputText.value, false);
break;
case 'horizon-vertical-full':
outputText.value = convertHorizontalVertical(inputText.value, true);
break;
default:
$message.warning('未知的转换模式');
return;
}
$message.success('转换成功');
}
/** 复制结果 */
function handleCopy() {
if (!clipboard.isSupported) {
$message.error('复制失败:当前浏览器不支持该操作');
return Promise.resolve();
}
return clipboard.copy(outputText.value).then(() => {
$message.success('复制成功');
}).catch((error) => {
console.error('复制失败:');
console.error(error);
$message.error('复制失败:异常');
});
}
/** 清空内容 */
function handleClear() {
inputText.value = '';
outputText.value = '';
}
</script> </script>
<style lang="less" scoped> <style lang="less" scoped>
.monospace-input {
font-family: monospace;
}
.tip-text {
color: #666;
font-size: 14px;
}
:deep(.n-input) {
max-width: 64em;
}
</style> </style>
@@ -1,8 +1,8 @@
<template> <template>
<div class="tool-detail-page"> <div class="tool-detail-page">
<!-- 控制 --> <!-- 操作 -->
<n-card size="small" title="控制"> <n-card size="small" title="操作">
<n-form <n-form
class="form-no-feedback form-data" class="form-no-feedback form-data"
label-align="right" label-align="right"
@@ -80,8 +80,8 @@
</n-form> </n-form>
</n-card> </n-card>
<!-- 转换 --> <!-- 结果 -->
<n-card size="small" title="转换"> <n-card size="small" title="结果">
<n-form <n-form
class="form-no-feedback form-data" class="form-no-feedback form-data"
label-align="right" label-align="right"
@@ -0,0 +1,216 @@
<template>
<div class="tool-detail-page">
<!-- 文件选择 -->
<n-card size="small" title="文件选择">
<div class="file-description">
<p>支持格式:PNG、JPEG、GIF、BMP</p>
<p>建议图片大小:小于 8MB</p>
<p>建议图片比例:1:1(正方形)</p>
</div>
<n-upload
:max="1"
:on-before-upload="handleFileSelect"
:on-error="handleFileError"
:on-remove="handleFileRemove"
:show-file-list="false">
<n-button type="primary">选择文件</n-button>
</n-upload>
<div class="file-status">
<span>已选择文件:</span>
<span v-if="formInfo.selectedFile">{{ formInfo.selectedFile.name }}</span>
<span v-else>无</span>
</div>
</n-card>
<!-- 分辨率配置 -->
<n-card size="small" title="分辨率配置">
<div class="section-description">
<p>一个 ICO 文件可以存储多种分辨率的图像。</p>
</div>
<div class="selection-items">
<p class="senection-item">
<n-checkbox
v-model:checked="formInfo.sizes[16]"
>16px</n-checkbox>
</p>
<p class="senection-item">
<n-checkbox
v-model:checked="formInfo.sizes[32]"
>32px</n-checkbox>
</p>
<p class="senection-item">
<n-checkbox
v-model:checked="formInfo.sizes[48]"
>48px</n-checkbox>
</p>
<p class="senection-item">
<n-checkbox
v-model:checked="formInfo.sizes[64]"
>64px</n-checkbox>
</p>
<p class="senection-item">
<n-checkbox
v-model:checked="formInfo.sizes[128]"
>128px</n-checkbox>
</p>
<p class="senection-item">
<n-checkbox
v-model:checked="formInfo.sizes[256]"
>256px(仅 32 位深度支持)</n-checkbox>
</p>
</div>
</n-card>
<!-- 位深度配置 -->
<n-card size="small" title="位深度配置">
<n-radio-group v-model:value="formInfo.bitDepth">
<p>
<n-radio :value="8">8 位(256 色,调色板)</n-radio>
</p>
<p>
<n-radio :value="32">32 位(1670 万色 & 透明度)</n-radio>
</p>
</n-radio-group>
</n-card>
<!-- 操作 -->
<n-card size="small" title="操作">
<n-flex>
<n-button
size="large"
type="primary"
@click="handleConvert"
>转换为 ICO 图标</n-button>
</n-flex>
</n-card>
</div>
</template>
<script setup>
import {
NButton, NCard, NFlex, NForm, NFormItem,
NCheckbox, NRadio, NRadioGroup, NUpload,
} from 'naive-ui';
import {
reactive,
} from 'vue';
import {
$message, $notification,
} from '@/assets/js/naive-ui';
import {
convertPNGtoICO,
} from '@/assets/js/png-to-ico';
/** 数据 */
const formInfo = reactive({
/** 选择的文件 */
selectedFile: null,
/** 选择的分辨率 */
sizes: {
16: true,
32: true,
48: true,
64: false,
128: false,
256: false
},
/** 选择的位深度 */
bitDepth: 32,
});
/** 文件上传错误时的处理 */
function handleFileError() {
$message.error('文件上传失败,请重试');
}
/** 文件选择时的处理 */
function handleFileSelect(uploadData) {
formInfo.selectedFile = uploadData?.file?.file;
// 返回 false 阻止自动上传(只需要获取文件对象)
return false;
}
/** 文件移除时的处理 */
function handleFileRemove() {
formInfo.selectedFile = null;
}
/** 转换按钮点击处理 */
function handleConvert() {
if (!formInfo.selectedFile) {
$message.warning('请先选择文件');
return;
}
// 检查是否选择了至少一个分辨率
let selectedSizes = Object.keys(formInfo.sizes).filter((size) => {
return formInfo.sizes[size];
}).map((value) => {
return Number(value);
});
if (selectedSizes.length === 0) {
$message.warning('请至少选择一个分辨率');
return;
}
// 检查如果选择了 256 像素,是否位深度为 32 位
if (formInfo.sizes[256] && formInfo.bitDepth !== 32) {
$message.warning('256px 分辨率仅支持 32 位深度');
return;
}
convertPNGtoICO(
formInfo.selectedFile,
selectedSizes,
'icon.ico'
).then((result) => {
console.log('转换结果', result);
if (result.success) {
$message.success('文件转换成功');
} else {
$message.error('文件转换失败');
}
});
}
</script>
<style lang="less" scoped>
.file-description {
margin-bottom: 12px;
color: #666;
font-size: 14px;
line-height: 1.4;
}
.file-status {
margin-top: 12px;
font-size: 14px;
color: #666;
}
.section-description {
margin-bottom: 16px;
color: #666;
font-size: 14px;
line-height: 1.4;
}
:deep(.n-form-item) {
margin-bottom: 8px;
}
</style>
@@ -1,9 +1,244 @@
<template> <template>
<div class="tool-detail-page"></div> <div class="tool-detail-page">
<!-- 转换设置 -->
<n-card size="small" title="转换设置">
<n-form
class="form-no-feedback"
label-align="right"
label-placement="left"
label-width="auto"
>
<n-form-item label="转换模式:">
<n-select
v-model:value="setting.mode"
:options="[
{ label: '编码', value: 'encode' },
{ label: '解码', value: 'decode' },
]"
/>
</n-form-item>
<n-form-item label="处理范围:">
<n-select
v-model:value="setting.scope"
:options="[
{ label: 'URL 组件(参数值等)', value: 'component' },
{ label: '完整 URL', value: 'uri' },
]"
/>
</n-form-item>
<n-form-item label="说明:">
<div class="tip-text">
<p v-if="setting.scope === 'component'">使用 encodeURIComponent / decodeURIComponent,会编码 <code>:/?#[]@!$&amp;'()*+,;=</code> 等字符,适合处理 URL 参数值。</p>
<p v-else>使用 encodeURI / decodeURI,会保留 <code>:/?#[]@!$&amp;'()*+,;=</code> 等 URL 结构字符,适合处理完整链接。</p>
</div>
</n-form-item>
</n-form>
</n-card>
<!-- 操作 -->
<n-card size="small" title="操作">
<n-flex>
<n-button
type="primary"
@click="handleConvert"
>{{ setting.mode === 'encode' ? '编码' : '解码' }}</n-button>
<n-button
:disabled="!outputText"
@click="handleSwap"
>交换输入输出</n-button>
<n-button
type="primary"
:disabled="!outputText"
@click="handleCopy"
>复制结果</n-button>
<n-button
type="error"
:disabled="!inputText && !outputText"
@click="handleClear"
>清空</n-button>
</n-flex>
</n-card>
<!-- 输入内容 -->
<n-card size="small" title="输入内容">
<template #header-extra>{{ inputText.length }} 字符</template>
<n-input
v-model:value="inputText"
class="monospace-input"
:placeholder="inputPlaceholder"
type="textarea"
:rows="6"
:autosize="false"
></n-input>
</n-card>
<!-- 输出内容 -->
<n-card size="small" title="输出内容">
<template #header-extra>{{ outputText.length }} 字符</template>
<n-input
v-model:value="outputText"
class="monospace-input"
:placeholder="outputPlaceholder"
type="textarea"
:rows="6"
:readonly="true"
:autosize="false"
></n-input>
</n-card>
</div>
</template> </template>
<script setup> <script setup>
import {
NButton, NCard, NFlex,
NForm, NFormItem, NInput, NSelect,
} from 'naive-ui';
import {
computed, reactive, ref,
} from 'vue';
import {
$message,
} from '@/assets/js/naive-ui';
import {
useClipboard,
} from '@vueuse/core';
/** 剪贴板 */
const clipboard = useClipboard({
legacy: true,
read: false,
});
/** 设置项 */
const setting = reactive({
/** 转换模式(encode - 编码,decode - 解码) */
mode: 'encode',
/** 处理范围(component - URL 组件,uri - 完整 URL) */
scope: 'component',
});
/** 输入内容 */
const inputText = ref('');
/** 输出内容 */
const outputText = ref('');
/** 输入框占位文本 */
const inputPlaceholder = computed(() => {
return (setting.mode === 'encode' ? '请输入需要编码的文本或链接' : '请输入需要解码的字符串');
});
/** 输出框占位文本 */
const outputPlaceholder = computed(() => {
return (setting.mode === 'encode' ? '编码结果将显示在这里' : '解码结果将显示在这里');
});
/** 处理转换 */
function handleConvert() {
if (!inputText.value) {
$message.warning('请输入需要转换的内容');
return;
}
try {
let result = '';
let isComponent = (setting.scope === 'component');
let isEncode = (setting.mode === 'encode');
if (isEncode) {
result = (isComponent
? encodeURIComponent(inputText.value)
: encodeURI(inputText.value));
} else {
result = (isComponent
? decodeURIComponent(inputText.value)
: decodeURI(inputText.value));
}
outputText.value = result;
$message.success('转换成功');
} catch (error) {
console.warn('转换失败:');
console.warn(error);
$message.error(`转换失败:${error.message || '内容格式不正确'}`);
}
}
/** 交换输入与输出内容 */
function handleSwap() {
let temp = inputText.value;
inputText.value = outputText.value;
outputText.value = temp;
setting.mode = (setting.mode === 'encode' ? 'decode' : 'encode');
}
/** 复制结果 */
function handleCopy() {
if (!clipboard.isSupported) {
$message.error('复制失败:当前浏览器不支持该操作');
return Promise.resolve();
}
return clipboard.copy(outputText.value).then(() => {
$message.success('复制成功');
}).catch((error) => {
console.error('复制失败:');
console.error(error);
$message.error('复制失败:异常');
});
}
/** 清空内容 */
function handleClear() {
inputText.value = '';
outputText.value = '';
}
</script> </script>
<style lang="less" scoped> <style lang="less" scoped>
.monospace-input {
font-family: monospace;
}
.tip-text {
color: #666;
font-size: 14px;
line-height: 1.6;
p {
margin: 0;
}
code {
padding: 0 4px;
border-radius: 2px;
background-color: #F5F5F5;
font-family: monospace;
}
}
:deep(.n-input) {
max-width: 64em;
}
</style> </style>
+770 -1
View File
@@ -1,9 +1,778 @@
<template> <template>
<div class="tool-detail-page"></div> <div class="tool-detail-page">
<!-- 文件操作 -->
<n-card size="small" title="文件">
<n-flex>
<n-upload
accept=".csv,.txt"
:max="1"
:show-file-list="false"
:on-before-upload="handleImportFile"
>
<n-button type="success">导入 CSV 文件</n-button>
</n-upload>
<n-button
type="primary"
:disabled="!hasData"
@click="handleExport"
>导出 CSV</n-button>
<n-button
type="primary"
:disabled="!hasData"
@click="handleCopyCsv"
>复制 CSV</n-button>
<n-button
type="error"
:disabled="!hasData"
@click="handleClearData"
>清空数据</n-button>
<n-button
@click="handleReset"
>重置表格</n-button>
</n-flex>
<div class="tip-text">导入文件时会自动识别分隔符(逗号、分号、制表符);导出的文件带 UTF-8 BOM,便于 Excel 正确识别中文。</div>
</n-card>
<!-- 配置 -->
<n-card size="small" title="配置">
<n-flex align="center">
<div class="config-item">
<div class="config-item__label">分隔符:</div>
<n-select
v-model:value="data.delimiter"
:options="delimiterOptions"
class="config-item__select"
/>
</div>
<div class="config-item">
<div class="config-item__label">首行作为表头:</div>
<n-switch v-model:value="data.hasHeader" />
</div>
<div class="config-item">
<div class="config-item__label">表格大小:</div>
<n-tag type="info">{{ rowCount }} 行 × {{ columnCount }} 列</n-tag>
</div>
</n-flex>
<div class="paste-area">
<n-input
v-model:value="data.pasteText"
class="paste-input"
placeholder="也可以在此粘贴 CSV 文本,然后点击“解析粘贴内容”"
type="textarea"
:rows="4"
></n-input>
<n-flex class="paste-actions">
<n-button
type="success"
:disabled="!data.pasteText"
@click="handleParsePaste"
>解析粘贴内容</n-button>
<n-button
type="error"
:disabled="!data.pasteText"
@click="data.pasteText = ''"
>清空粘贴内容</n-button>
</n-flex>
</div>
</n-card>
<!-- 编辑区 -->
<n-card size="small" title="编辑区">
<template #header-extra>
<span class="header-extra-text">{{ rowCount }} 行 × {{ columnCount }} 列</span>
</template>
<n-flex class="edit-actions">
<n-button
size="small"
type="success"
@click="addRow"
>添加行</n-button>
<n-button
size="small"
type="success"
@click="addColumn"
>添加列</n-button>
<n-button
size="small"
type="warning"
:disabled="columnCount <= 1"
@click="removeLastColumn"
>删除末列</n-button>
<n-button
size="small"
type="warning"
:disabled="rowCount <= 1"
@click="removeLastRow"
>删除末行</n-button>
</n-flex>
<div class="table-wrapper">
<table class="csv-table">
<thead>
<tr>
<th class="row-index-cell">#</th>
<th
v-for="colIndex in columnCount"
:key="`col-${colIndex}`"
:class="{ 'is-header': data.hasHeader }"
>
<div class="column-header">
<span>{{ getColumnLabel(colIndex - 1) }}</span>
<span
v-if="columnCount > 1"
class="mdi mdi-close-circle-outline column-remove"
title="删除该列"
@click="removeColumn(colIndex - 1)"
></span>
</div>
</th>
</tr>
</thead>
<tbody>
<tr
v-for="(row, rowIndex) in data.rows"
:key="`row-${rowIndex}`"
>
<td class="row-index-cell">
<div class="row-index">
<span>{{ rowIndex + 1 }}</span>
<span
v-if="rowCount > 1"
class="mdi mdi-close-circle-outline row-remove"
title="删除该行"
@click="removeRow(rowIndex)"
></span>
</div>
</td>
<td
v-for="colIndex in columnCount"
:key="`cell-${rowIndex}-${colIndex}`"
:class="{ 'is-header': data.hasHeader && rowIndex === 0 }"
>
<n-input
v-model:value="row[colIndex - 1]"
class="cell-input"
size="tiny"
:bordered="false"
placeholder=""
></n-input>
</td>
</tr>
</tbody>
</table>
</div>
<div class="tip-text">提示:单元格内容包含分隔符、双引号或换行时,导出会自动使用双引号包裹并转义。</div>
</n-card>
</div>
</template> </template>
<script setup> <script setup>
import {
NButton, NCard, NFlex,
NInput, NSelect, NSwitch, NTag, NUpload,
} from 'naive-ui';
import {
computed, reactive,
} from 'vue';
import {
$dialog, $message,
} from '@/assets/js/naive-ui';
import {
useClipboard,
} from '@vueuse/core';
/** 剪贴板 */
const clipboard = useClipboard({
legacy: true,
read: false,
});
/** 支持的最大单元格数量(防止数据过大导致界面卡顿) */
const MAX_CELLS = 10000;
/** 初始行数 */
const INIT_ROWS = 5;
/** 初始列数 */
const INIT_COLS = 5;
/** 分隔符选项 */
const delimiterOptions = [
{ label: '逗号(,)', value: ',' },
{ label: '分号(;)', value: ';' },
{ label: '制表符(Tab)', value: '\t' },
{ label: '竖线(|)', value: '|' },
];
/** 数据 */
const data = reactive({
/** 分隔符 */
delimiter: ',',
/** 是否将首行作为表头 */
hasHeader: true,
/** 粘贴内容 */
pasteText: '',
/** 表格数据(行 × 列) */
rows: createEmptyRows(INIT_ROWS, INIT_COLS),
});
/** 行数 */
const rowCount = computed(() => {
return data.rows.length;
});
/** 列数 */
const columnCount = computed(() => {
return (data.rows[0] ? data.rows[0].length : 0);
});
/** 是否包含内容 */
const hasData = computed(() => {
return data.rows.some((row) => {
return row.some((cell) => {
return Boolean(cell);
});
});
});
/**
* @description 创建空的表格数据
* @param {number} rows 行数
* @param {number} cols 列数
* @returns {string[][]} 表格数据
*/
function createEmptyRows(rows = 5, cols = 5) {
return Array.from({ length: rows }, () => {
return Array.from({ length: cols }, () => '');
});
}
/**
* @description 获取列名称(A、B、...、Z、AA、AB、...)
* @param {number} index 列下标(从 0 开始)
* @returns {string} 列名称
*/
function getColumnLabel(index = 0) {
let label = '';
let n = index + 1;
while (n > 0) {
let remainder = (n - 1) % 26;
label = String.fromCharCode(65 + remainder) + label;
n = Math.floor((n - 1) / 26);
}
return label;
}
/**
* @description 补齐每行的列数,保证表格为矩形
* @param {string[][]} rows 表格数据
* @returns {string[][]} 处理后的表格数据
*/
function normalizeRows(rows) {
let maxCols = rows.reduce((max, row) => {
return Math.max(max, row.length);
}, 1);
return rows.map((row) => {
let newRow = row.slice(0, maxCols);
while (newRow.length < maxCols) {
newRow.push('');
}
return newRow;
});
}
/**
* @description 识别 CSV 文本使用的分隔符
* @param {string} text CSV 文本
* @returns {string} 分隔符
*/
function detectDelimiter(text = '') {
let candidates = [',', ';', '\t', '|'];
let firstLine = '';
let inQuotes = false;
// 取第一行(引号内的换行不算)
for (let i = 0; i < text.length; i++) {
let char = text[i];
if (char === '"') {
inQuotes = !inQuotes;
} else if ((char === '\n' || char === '\r') && !inQuotes) {
break;
} else if (!inQuotes) {
firstLine += char;
}
}
let counts = candidates.map((delimiter) => {
let count = 0;
let isInQuotes = false;
for (let i = 0; i < firstLine.length; i++) {
let char = firstLine[i];
if (char === '"') {
isInQuotes = !isInQuotes;
} else if (char === delimiter && !isInQuotes) {
count++;
}
}
return { delimiter, count };
});
counts.sort((a, b) => {
return b.count - a.count;
});
return (counts[0].count > 0 ? counts[0].delimiter : ',');
}
/**
* @description 解析 CSV 文本
* @param {string} text CSV 文本
* @param {string} delimiter 分隔符
* @returns {string[][]} 表格数据
*/
function parseCsv(text = '', delimiter = ',') {
let rows = [];
let row = [];
let field = '';
let inQuotes = false;
for (let i = 0; i < text.length; i++) {
let char = text[i];
if (inQuotes) {
if (char === '"') {
// 连续的双引号视为转义的双引号
if (text[i + 1] === '"') {
field += '"';
i++;
} else {
inQuotes = false;
}
} else {
field += char;
}
continue;
}
if (char === '"') {
inQuotes = true;
} else if (char === delimiter) {
row.push(field);
field = '';
} else if (char === '\r') {
// 兼容 \r\n 与单独的 \r
if (text[i + 1] !== '\n') {
row.push(field);
rows.push(row);
row = [];
field = '';
}
} else if (char === '\n') {
row.push(field);
rows.push(row);
row = [];
field = '';
} else {
field += char;
}
}
// 处理最后一段内容
if (field || row.length > 0) {
row.push(field);
rows.push(row);
}
// 移除末尾完全为空的行
while (rows.length > 1) {
let lastRow = rows[rows.length - 1];
if (lastRow.length === 1 && lastRow[0] === '') {
rows.pop();
} else {
break;
}
}
return (rows.length > 0 ? normalizeRows(rows) : createEmptyRows(1, 1));
}
/**
* @description 将表格数据转换为 CSV 文本
* @param {string[][]} rows 表格数据
* @param {string} delimiter 分隔符
* @returns {string} CSV 文本
*/
function stringifyCsv(rows, delimiter = ',') {
return rows.map((row) => {
return row.map((cell) => {
let value = (cell ?? '');
// 包含引号、分隔符或换行时使用双引号包裹
if (value.includes('"') || value.includes(delimiter) || /[\r\n]/.test(value)) {
return '"' + value.replace(/"/g, '""') + '"';
}
return value;
}).join(delimiter);
}).join('\r\n');
}
/**
* @description 载入 CSV 文本
* @param {string} text CSV 文本
*/
function loadCsvText(text = '') {
if (!text.trim()) {
$message.warning('内容为空');
return false;
}
let delimiter = detectDelimiter(text);
let rows = parseCsv(text, delimiter);
// 限制数据量,防止界面卡顿
if (rows.length * (rows[0]?.length || 0) > MAX_CELLS) {
$message.error(`数据量过大(最多支持 ${MAX_CELLS} 个单元格)`);
return false;
}
data.delimiter = delimiter;
data.rows = rows;
return true;
}
/** 处理导入文件 */
function handleImportFile(uploadData) {
let file = uploadData?.file?.file;
if (!file) {
return false;
}
file.text().then((text) => {
if (loadCsvText(text)) {
$message.success(`已导入文件:${file.name}`);
}
}).catch((error) => {
console.error('读取文件失败:');
console.error(error);
$message.error('读取文件失败');
});
// 返回 false 阻止自动上传(只需要读取文件内容)
return false;
}
/** 处理解析粘贴内容 */
function handleParsePaste() {
if (loadCsvText(data.pasteText)) {
$message.success('解析成功');
data.pasteText = '';
}
}
/** 处理导出 CSV */
function handleExport() {
let text = stringifyCsv(data.rows, data.delimiter);
// 添加 BOM,便于 Excel 正确识别 UTF-8 编码
let blob = new Blob(['\ufeff' + text], { type: 'text/csv;charset=utf-8' });
let url = URL.createObjectURL(blob);
let link = document.createElement('a');
link.href = url;
link.download = 'data.csv';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
setTimeout(() => {
URL.revokeObjectURL(url);
}, 1000);
$message.success('已导出文件');
}
/** 处理复制 CSV */
function handleCopyCsv() {
if (!clipboard.isSupported) {
$message.error('复制失败:当前浏览器不支持该操作');
return Promise.resolve();
}
return clipboard.copy(stringifyCsv(data.rows, data.delimiter)).then(() => {
$message.success('复制成功');
}).catch((error) => {
console.error('复制失败:');
console.error(error);
$message.error('复制失败:异常');
});
}
/** 添加行 */
function addRow() {
data.rows.push(Array.from({ length: columnCount.value }, () => ''));
}
/** 添加列 */
function addColumn() {
data.rows.forEach((row) => {
row.push('');
});
}
/** 删除末行 */
function removeLastRow() {
if (data.rows.length <= 1) {
return;
}
data.rows.pop();
}
/** 删除末列 */
function removeLastColumn() {
if (columnCount.value <= 1) {
return;
}
data.rows.forEach((row) => {
row.pop();
});
}
/**
* @description 删除指定行
* @param {number} rowIndex 行下标
*/
function removeRow(rowIndex = 0) {
if (data.rows.length <= 1) {
return;
}
data.rows.splice(rowIndex, 1);
}
/**
* @description 删除指定列
* @param {number} colIndex 列下标
*/
function removeColumn(colIndex = 0) {
if (columnCount.value <= 1) {
return;
}
data.rows.forEach((row) => {
row.splice(colIndex, 1);
});
}
/** 清空数据(保留表格大小) */
function handleClearData() {
$dialog.warning({
title: '确认',
content: '是否清空表格中的所有数据?',
positiveText: '确定',
negativeText: '取消',
onPositiveClick: () => {
data.rows.forEach((row) => {
row.fill('');
});
$message.success('已清空数据');
},
});
}
/** 重置表格 */
function handleReset() {
$dialog.warning({
title: '确认',
content: '是否重置为初始状态(5 行 × 5 列)?',
positiveText: '确定',
negativeText: '取消',
onPositiveClick: () => {
data.rows = createEmptyRows(INIT_ROWS, INIT_COLS);
data.pasteText = '';
$message.success('已重置');
},
});
}
</script> </script>
<style lang="less" scoped> <style lang="less" scoped>
.config-item {
display: flex;
align-items: center;
.config-item__label {
flex-shrink: 0;
}
.config-item__select {
width: 160px;
}
& + .config-item {
margin-left: 24px;
}
}
.paste-area {
margin-top: 16px;
.paste-input {
max-width: 100%;
font-family: monospace;
}
.paste-actions {
margin-top: 8px;
}
}
.edit-actions {
margin-bottom: 12px;
}
.table-wrapper {
max-height: 480px;
overflow: auto;
border: 1px solid #E5E5E5;
border-radius: 4px;
.csv-table {
width: max-content;
min-width: 100%;
border-collapse: separate;
border-spacing: 0;
font-size: 14px;
th, td {
padding: 0;
border-right: 1px solid #EEE;
border-bottom: 1px solid #EEE;
}
thead th {
position: sticky;
top: 0;
z-index: 2;
background-color: #F8F9FA;
&.is-header {
background-color: #EAF4FE;
}
}
tbody td.is-header {
background-color: #F7FBFF;
font-weight: bold;
}
.row-index-cell {
position: sticky;
left: 0;
z-index: 1;
width: 56px;
min-width: 56px;
background-color: #F8F9FA;
text-align: center;
color: #999;
font-family: monospace;
}
thead .row-index-cell {
z-index: 3;
}
.row-index, .column-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 4px 8px;
min-width: 120px;
height: 28px;
}
.column-header {
font-weight: bold;
}
.column-remove, .row-remove {
margin-left: 4px;
cursor: pointer;
opacity: 0.5;
transition: opacity 0.2s;
&:hover {
opacity: 1;
color: #E34D59;
}
}
.cell-input {
min-width: 120px;
:deep(.n-input__input-el) {
padding: 0 8px;
height: 28px;
font-family: monospace;
}
}
}
}
.tip-text {
margin-top: 12px;
color: #999;
font-size: 13px;
line-height: 1.6;
}
.header-extra-text {
color: #999;
font-size: 13px;
}
</style> </style>
+137
View File
@@ -0,0 +1,137 @@
<template>
<div class="tool-detail-page">
<n-card size="small" title="编辑器">
<div ref="editorContainer" class="editor-container"></div>
</n-card>
</div>
</template>
<script setup>
import {
NCard,
} from 'naive-ui';
import {
ref, shallowRef,
onBeforeUnmount, onMounted,
} from 'vue';
import {
initMonacoEnvironment,
} from '@/assets/js/monaco-editor';
import * as monaco from 'monaco-editor';
/** 模块名称 */
const PREFIX = '[JsonEditor]';
/**
* @desc 编辑器实例(注:内部不能为响应式,防止出现部分操作会导致界面卡死等异常)
* @type {VueRef<monaco.editor.IStandaloneCodeEditor>}
*/
const editorInstance = shallowRef(null);
/** @type {VueRef<HTMLElement>} */
const editorContainer = ref(null);
/** 防抖定时器 */
const resizeTimer = ref(null);
/** 处理窗口大小变化 */
function handleWindowResize() {
clearTimeout(resizeTimer.value);
resizeTimer.value = setTimeout(() => {
if (editorInstance.value) {
editorInstance.value.layout();
}
}, 200);
}
/** 初始化编辑器 */
function initEditor() {
console.log(PREFIX, 'initEditor');
let container = editorContainer.value;
let editor = null;
let valueStr = '';
if (!container) {
console.error(PREFIX, '初始化失败:元素不存在');
return;
}
editor = monaco.editor.create(container, {
autoDetectHighContrast: false,
automaticLayout: false,
contextmenu: true,
find: {
cursorMoveOnType: false,
},
fontFamily: 'monospace',
fontSize: 14,
language: 'json',
minimap: {
enabled: true,
renderCharacters: false,
},
mouseWheelScrollSensitivity: 2,
stickyScroll: {
enabled: false,
},
tabSize: 2,
theme: 'vs',
value: valueStr,
});
// 注:
// 若使用自定义字体,且字体的加载时间比编辑器加载时间长,
// 需要在字体加载完成后调用 monaco.editor.remeasureFonts(),
// 防止光标位置异常。
editorInstance.value = editor;
}
/** 销毁编辑器 */
function resetEditor() {
console.log(PREFIX, 'resetEditor');
try {
if (editorInstance.value) {
editorInstance.value.getModel().dispose()
editorInstance.value.dispose();
editorInstance.value = null;
}
return true;
} catch (error) {
console.error(PREFIX, '销毁失败:');
console.error(error);
return false;
}
}
onMounted(() => {
initMonacoEnvironment();
initEditor();
window.addEventListener('resize', handleWindowResize);
});
onBeforeUnmount(() => {
resetEditor();
window.removeEventListener('resize', handleWindowResize);
});
</script>
<style lang="less" scoped>
.n-card, .editor-container {
width: 100%;
height: 100%;
}
.editor-container {
outline: 1px solid var(--n-border-color);
}
</style>
+2 -2
View File
@@ -1,8 +1,8 @@
<template> <template>
<div class="tool-detail-page"> <div class="tool-detail-page">
<!-- 设置 --> <!-- 配置参数 -->
<n-card size="small" title="设置"> <n-card size="small" title="配置参数">
<n-flex> <n-flex>
<!-- 缩进空格 --> <!-- 缩进空格 -->
<div class="config-item"> <div class="config-item">
+245
View File
@@ -0,0 +1,245 @@
<template>
<div class="tool-detail-page">
<!-- 操作 -->
<n-card size="small" title="操作">
<n-flex>
<n-flex align="center">
<span>文件格式:</span>
<n-select
v-model:value="textEncoding"
:options="[
{ label: 'GBK', value: 'gbk' },
{ label: 'UTF-8', value: 'utf-8' },
]"
style="width: 160px;"
/>
</n-flex>
<n-button
type="primary"
@click="handleOpenFile"
>打开文件</n-button>
<n-button
type="error"
@click="handleClearContent"
>清空内容</n-button>
</n-flex>
</n-card>
<n-card size="small" title="编辑器">
<div ref="editorContainer" class="editor-container"></div>
</n-card>
</div>
</template>
<script setup>
import {
NButton, NCard, NFlex, NSelect,
} from 'naive-ui';
import {
ref, shallowRef,
onBeforeUnmount, onMounted,
} from 'vue';
import {
useFileDialog,
} from '@vueuse/core';
import {
initMonacoEnvironment,
} from '@/assets/js/monaco-editor';
import {
$dialog, $message,
} from '@/assets/js/naive-ui';
import * as monaco from 'monaco-editor';
/** 模块名称 */
const PREFIX = '[TextEditor]';
const {
onChange: fileOnChange,
open: fileOpen,
reset: fileReset,
} = useFileDialog({
accept: '*',
directory: false,
multiple: false,
});
/**
* @desc 编辑器实例(注:内部不能为响应式,防止出现部分操作会导致界面卡死等异常)
* @type {VueRef<monaco.editor.IStandaloneCodeEditor>}
*/
const editorInstance = shallowRef(null);
/** @type {VueRef<HTMLElement>} */
const editorContainer = ref(null);
/** 防抖定时器 */
const resizeTimer = ref(null);
/** 文件编码 */
const textEncoding = ref('utf-8');
/** 处理清空内容操作 */
function handleClearContent() {
$dialog.create({
content: '确定要清空编辑器内容吗?',
negativeText: '取消',
positiveText: '确定',
title: '确认',
type: 'default',
onPositiveClick: () => {
updateEditorContent('');
},
});
}
/** 处理打开文件操作 */
function handleOpenFile() {
fileReset();
fileOpen();
}
/** 处理窗口大小变化 */
function handleWindowResize() {
clearTimeout(resizeTimer.value);
resizeTimer.value = setTimeout(() => {
if (editorInstance.value) {
editorInstance.value.layout();
}
}, 200);
}
/** 初始化编辑器 */
function initEditor() {
console.log(PREFIX, 'initEditor');
let container = editorContainer.value;
let editor = null;
let valueStr = '';
if (!container) {
console.error(PREFIX, '初始化失败:元素不存在');
return;
}
editor = monaco.editor.create(container, {
autoDetectHighContrast: false,
automaticLayout: false,
contextmenu: true,
find: {
cursorMoveOnType: false,
},
fontFamily: 'monospace',
fontSize: 14,
language: 'plaintext',
minimap: {
enabled: true,
renderCharacters: false,
},
mouseWheelScrollSensitivity: 2,
stickyScroll: {
enabled: false,
},
tabSize: 2,
theme: 'vs',
value: valueStr,
});
// 注:
// 若使用自定义字体,且字体的加载时间比编辑器加载时间长,
// 需要在字体加载完成后调用 monaco.editor.remeasureFonts(),
// 防止光标位置异常。
editorInstance.value = editor;
}
/** 销毁编辑器 */
function resetEditor() {
console.log(PREFIX, 'resetEditor');
try {
if (editorInstance.value) {
editorInstance.value.getModel().dispose()
editorInstance.value.dispose();
editorInstance.value = null;
}
return true;
} catch (error) {
console.error(PREFIX, '销毁失败:');
console.error(error);
return false;
}
}
/** 更新编辑器内容 */
function updateEditorContent(text = '') {
if (editorInstance.value) {
editorInstance.value.setValue(text);
}
}
fileOnChange((files) => {
let file = files ? files[0] : null;
file && file.arrayBuffer().then((buffer) => {
try {
let decoder = new TextDecoder(textEncoding.value);
let text = decoder.decode(buffer);
updateEditorContent(text);
} catch (error) {
console.error('解码失败:');
console.error(error);
$message.error('打开文件失败:解码失败');
}
}).catch((error) => {
console.error('打开文件失败:');
console.error(error);
$message.error('打开文件失败:读取失败');
});
});
onMounted(() => {
initMonacoEnvironment();
initEditor();
window.addEventListener('resize', handleWindowResize);
});
onBeforeUnmount(() => {
resetEditor();
window.removeEventListener('resize', handleWindowResize);
});
</script>
<style lang="less" scoped>
.n-card:nth-child(1) {
height: auto;
}
.n-card:nth-child(2) {
height: 100%;
}
.n-card, .editor-container {
width: 100%;
}
.editor-container {
height: 100%;
outline: 1px solid var(--n-border-color);
}
</style>
@@ -1,9 +1,951 @@
<template> <template>
<div class="tool-detail-page"></div> <div class="tool-detail-page">
<!-- 基础配置 -->
<n-card size="small" title="基础配置">
<n-form
class="form-no-feedback"
label-align="right"
label-placement="left"
label-width="auto"
>
<n-form-item label="配置类型:">
<n-radio-group v-model:value="data.mode">
<n-radio value="frpc">frpc(客户端)</n-radio>
<n-radio value="frps">frps(服务端)</n-radio>
</n-radio-group>
</n-form-item>
<n-form-item label="文件格式:">
<n-select
v-model:value="data.format"
class="config-select"
:options="[
{ label: 'TOML(frp v0.52 及更高版本)', value: 'toml' },
{ label: 'INI(旧版本)', value: 'ini' },
]"
/>
</n-form-item>
<n-form-item
v-show="data.mode === 'frpc'"
label="服务端地址:"
>
<n-input
v-model:value="data.serverAddr"
class="config-input"
placeholder="例如:127.0.0.1 或 frp.example.com"
></n-input>
</n-form-item>
<n-form-item
v-show="data.mode === 'frpc'"
label="服务端端口:"
>
<n-input-number
v-model:value="data.serverPort"
class="config-input"
:min="1"
:max="65535"
:precision="0"
:step="1"
></n-input-number>
</n-form-item>
<n-form-item label="认证令牌:">
<n-input
v-model:value="data.token"
class="config-input"
placeholder="留空则不生成认证配置"
></n-input>
</n-form-item>
<n-form-item label="日志级别:">
<n-select
v-model:value="data.logLevel"
class="config-select"
:options="[
{ label: 'trace', value: 'trace' },
{ label: 'debug', value: 'debug' },
{ label: 'info', value: 'info' },
{ label: 'warn', value: 'warn' },
{ label: 'error', value: 'error' },
]"
/>
</n-form-item>
</n-form>
</n-card>
<!-- 服务端配置 -->
<n-card
v-show="data.mode === 'frps'"
size="small"
title="服务端配置"
>
<n-form
class="form-no-feedback"
label-align="right"
label-placement="left"
label-width="auto"
>
<n-form-item label="绑定端口:">
<n-input-number
v-model:value="data.frps.bindPort"
class="config-input"
:min="1"
:max="65535"
:precision="0"
:step="1"
></n-input-number>
</n-form-item>
<n-form-item label="HTTP 端口:">
<n-input-number
v-model:value="data.frps.vhostHTTPPort"
class="config-input"
placeholder="留空则不启用"
:min="1"
:max="65535"
:precision="0"
:step="1"
clearable
></n-input-number>
</n-form-item>
<n-form-item label="HTTPS 端口:">
<n-input-number
v-model:value="data.frps.vhostHTTPSPort"
class="config-input"
placeholder="留空则不启用"
:min="1"
:max="65535"
:precision="0"
:step="1"
clearable
></n-input-number>
</n-form-item>
<n-form-item label="子域名根域:">
<n-input
v-model:value="data.frps.subdomainHost"
class="config-input"
placeholder="例如:example.com"
></n-input>
</n-form-item>
</n-form>
<n-divider />
<n-form
class="form-no-feedback"
label-align="right"
label-placement="left"
label-width="auto"
>
<n-form-item label="管理面板地址:">
<n-input
v-model:value="data.frps.webServerAddr"
class="config-input"
placeholder="留空则不生成管理面板配置"
></n-input>
</n-form-item>
<n-form-item label="管理面板端口:">
<n-input-number
v-model:value="data.frps.webServerPort"
class="config-input"
:min="1"
:max="65535"
:precision="0"
:step="1"
clearable
></n-input-number>
</n-form-item>
<n-form-item label="管理面板用户:">
<n-input
v-model:value="data.frps.webServerUser"
class="config-input"
placeholder="留空则不生成"
></n-input>
</n-form-item>
<n-form-item label="管理面板密码:">
<n-input
v-model:value="data.frps.webServerPassword"
class="config-input"
placeholder="留空则不生成"
type="password"
show-password-on="click"
></n-input>
</n-form-item>
</n-form>
</n-card>
<!-- 代理配置 -->
<n-card
v-show="data.mode === 'frpc'"
size="small"
title="代理配置"
>
<template #header-extra>
<n-button
size="small"
type="success"
@click="addProxy"
>添加代理</n-button>
</template>
<div
v-for="(proxy, index) in data.proxies"
:key="proxy.id"
class="proxy-item"
>
<div class="proxy-header">
<span class="proxy-index">#{{ index + 1 }}</span>
<n-input
v-model:value="proxy.name"
class="proxy-name"
size="small"
placeholder="代理名称,例如 web"
></n-input>
<n-select
v-model:value="proxy.type"
class="proxy-type"
size="small"
:options="proxyTypeOptions"
/>
<n-button
size="small"
type="error"
:disabled="data.proxies.length <= 1"
@click="removeProxy(index)"
>删除</n-button>
</div>
<n-form
class="form-no-feedback proxy-form"
label-align="right"
label-placement="left"
label-width="auto"
>
<n-form-item label="本地地址:">
<n-input
v-model:value="proxy.localIP"
class="config-input"
size="small"
placeholder="例如:127.0.0.1"
></n-input>
</n-form-item>
<n-form-item label="本地端口:">
<n-input-number
v-model:value="proxy.localPort"
class="config-input"
size="small"
:min="1"
:max="65535"
:precision="0"
:step="1"
></n-input-number>
</n-form-item>
<n-form-item
v-if="isPortProxy(proxy.type)"
label="远程端口:"
>
<n-input-number
v-model:value="proxy.remotePort"
class="config-input"
size="small"
:min="1"
:max="65535"
:precision="0"
:step="1"
></n-input-number>
</n-form-item>
<n-form-item
v-if="isDomainProxy(proxy.type)"
label="自定义域名:"
>
<n-input
v-model:value="proxy.customDomains"
class="config-input config-input--wide"
size="small"
placeholder="多个域名使用逗号分隔,例如:www.example.com, example.com"
></n-input>
</n-form-item>
<n-form-item
v-if="isDomainProxy(proxy.type)"
label="子域名:"
>
<n-input
v-model:value="proxy.subdomain"
class="config-input"
size="small"
placeholder="例如:demo(需服务端配置子域名根域)"
></n-input>
</n-form-item>
<n-form-item
v-if="isSecretProxy(proxy.type)"
label="密钥:"
>
<n-input
v-model:value="proxy.secretKey"
class="config-input"
size="small"
placeholder="stcp / xtcp 的访问密钥"
></n-input>
</n-form-item>
</n-form>
</div>
<div
v-if="data.proxies.length === 0"
class="empty-tips"
>暂无代理配置,请点击“添加代理”。</div>
</n-card>
<!-- 操作 -->
<n-card size="small" title="操作">
<n-flex>
<n-button
type="primary"
@click="handleGenerate"
>生成配置</n-button>
<n-button
type="primary"
:disabled="!result"
@click="handleCopy"
>复制结果</n-button>
<n-button
:disabled="!result"
@click="handleDownload"
>下载配置文件</n-button>
<n-button
type="error"
:disabled="!result"
@click="result = ''"
>清空结果</n-button>
</n-flex>
</n-card>
<!-- 生成结果 -->
<n-card size="small" title="生成结果">
<template #header-extra>{{ resultFileName }}</template>
<n-input
v-model:value="result"
class="result-input"
placeholder="生成的配置内容将显示在这里"
type="textarea"
:rows="16"
:readonly="true"
></n-input>
</n-card>
<!-- 说明 -->
<n-card size="small" title="说明">
<div class="tip-text">
<p>TOML 格式适用于 frp v0.52 及更高版本,INI 格式适用于旧版本,两者请勿混用。</p>
<p>frpc 的“服务端地址 / 端口”对应服务端的外网地址与 <code>bindPort</code> 端口。</p>
<p>HTTP / HTTPS 代理需要服务端配置对应的 <code>vhostHTTPPort</code> / <code>vhostHTTPSPort</code> 端口,并正确设置域名解析。</p>
</div>
</n-card>
</div>
</template> </template>
<script setup> <script setup>
import {
NButton, NCard, NDivider, NFlex,
NForm, NFormItem, NInput, NInputNumber,
NRadio, NRadioGroup, NSelect,
} from 'naive-ui';
import {
computed, reactive, ref,
} from 'vue';
import {
$message,
} from '@/assets/js/naive-ui';
import {
useClipboard,
} from '@vueuse/core';
import {
getUuidV4,
} from '@/assets/js/utils';
/** 剪贴板 */
const clipboard = useClipboard({
legacy: true,
read: false,
});
/** 代理类型选项 */
const proxyTypeOptions = [
{ label: 'TCP', value: 'tcp' },
{ label: 'UDP', value: 'udp' },
{ label: 'HTTP', value: 'http' },
{ label: 'HTTPS', value: 'https' },
{ label: 'STCP', value: 'stcp' },
{ label: 'XTCP', value: 'xtcp' },
];
/** 数据 */
const data = reactive({
/** 文件格式(toml、ini) */
format: 'toml',
/** 服务端配置 */
frps: {
bindPort: 7000,
subdomainHost: '',
vhostHTTPPort: null,
vhostHTTPSPort: null,
webServerAddr: '0.0.0.0',
webServerPassword: '',
webServerPort: 7500,
webServerUser: '',
},
/** 日志级别 */
logLevel: 'info',
/** 配置类型(frpc、frps) */
mode: 'frpc',
/** 代理列表 */
proxies: [],
/** 服务端地址 */
serverAddr: '127.0.0.1',
/** 服务端端口 */
serverPort: 7000,
/** 认证令牌 */
token: '',
});
/** 生成结果 */
const result = ref('');
/** 结果文件名 */
const resultFileName = computed(() => {
let ext = (data.format === 'ini' ? 'ini' : 'toml');
return `${data.mode}.${ext}`;
});
/** 添加默认代理 */
function addProxy() {
data.proxies.push({
customDomains: '',
id: getUuidV4(),
localIP: '127.0.0.1',
localPort: (data.proxies.length === 0 ? 80 : 8080),
name: (data.proxies.length === 0 ? 'web' : `proxy-${data.proxies.length + 1}`),
remotePort: 6000,
secretKey: '',
subdomain: '',
type: 'tcp',
});
}
/**
* @description 删除指定代理
* @param {number} index 代理下标
*/
function removeProxy(index = 0) {
data.proxies.splice(index, 1);
}
/**
* @description 是否为端口类型代理
* @param {string} type 代理类型
* @returns {boolean} 结果
*/
function isPortProxy(type = '') {
return (type === 'tcp' || type === 'udp');
}
/**
* @description 是否为域名类型代理
* @param {string} type 代理类型
* @returns {boolean} 结果
*/
function isDomainProxy(type = '') {
return (type === 'http' || type === 'https');
}
/**
* @description 是否为密钥类型代理
* @param {string} type 代理类型
* @returns {boolean} 结果
*/
function isSecretProxy(type = '') {
return (type === 'stcp' || type === 'xtcp');
}
/**
* @description 判断数值是否有效
* @param {number|null} value 数值
* @returns {boolean} 结果
*/
function isValidNumber(value) {
return (typeof value === 'number' && Number.isFinite(value) && value > 0);
}
/**
* @description 生成 TOML 字符串值
* @param {string} value 原值
* @returns {string} TOML 字符串
*/
function tomlString(value = '') {
return JSON.stringify(String(value));
}
/**
* @description 将域名文本拆分为数组
* @param {string} text 域名文本
* @returns {string[]} 域名列表
*/
function splitDomains(text = '') {
return text.split(/[\s,,]+/).map((item) => {
return item.trim();
}).filter((item) => {
return Boolean(item);
});
}
/** 校验配置内容 */
function validateConfig() {
if (data.mode === 'frpc') {
if (!data.serverAddr.trim()) {
$message.warning('请填写服务端地址');
return false;
}
if (!isValidNumber(data.serverPort)) {
$message.warning('请填写有效的服务端端口');
return false;
}
if (data.proxies.length === 0) {
$message.warning('请至少添加一个代理');
return false;
}
let names = new Set();
for (let proxy of data.proxies) {
if (!proxy.name.trim()) {
$message.warning('请填写代理名称');
return false;
}
if (names.has(proxy.name.trim())) {
$message.warning(`代理名称重复:${proxy.name}`);
return false;
}
names.add(proxy.name.trim());
if (!isValidNumber(proxy.localPort)) {
$message.warning(`代理“${proxy.name}”的本地端口无效`);
return false;
}
if (isPortProxy(proxy.type) && !isValidNumber(proxy.remotePort)) {
$message.warning(`代理“${proxy.name}”的远程端口无效`);
return false;
}
if (isDomainProxy(proxy.type)
&& splitDomains(proxy.customDomains).length === 0
&& !proxy.subdomain.trim()) {
$message.warning(`代理“${proxy.name}”需要填写自定义域名或子域名`);
return false;
}
}
} else {
if (!isValidNumber(data.frps.bindPort)) {
$message.warning('请填写有效的绑定端口');
return false;
}
if (data.frps.webServerAddr.trim() && !isValidNumber(data.frps.webServerPort)) {
$message.warning('请填写有效的管理面板端口');
return false;
}
}
return true;
}
/**
* @description 生成 frpc 的 TOML 配置
* @returns {string} 配置内容
*/
function generateFrpcToml() {
let lines = [];
lines.push(`serverAddr = ${tomlString(data.serverAddr.trim())}`);
lines.push(`serverPort = ${data.serverPort}`);
if (data.logLevel) {
lines.push('');
lines.push(`log.level = ${tomlString(data.logLevel)}`);
}
if (data.token.trim()) {
lines.push('');
lines.push('auth.method = "token"');
lines.push(`auth.token = ${tomlString(data.token.trim())}`);
}
data.proxies.forEach((proxy) => {
lines.push('');
lines.push('[[proxies]]');
lines.push(`name = ${tomlString(proxy.name.trim())}`);
lines.push(`type = ${tomlString(proxy.type)}`);
lines.push(`localIP = ${tomlString(proxy.localIP.trim() || '127.0.0.1')}`);
lines.push(`localPort = ${proxy.localPort}`);
if (isPortProxy(proxy.type)) {
lines.push(`remotePort = ${proxy.remotePort}`);
}
if (isDomainProxy(proxy.type)) {
let domains = splitDomains(proxy.customDomains);
if (domains.length > 0) {
lines.push(`customDomains = [${domains.map(tomlString).join(', ')}]`);
}
if (proxy.subdomain.trim()) {
lines.push(`subdomain = ${tomlString(proxy.subdomain.trim())}`);
}
}
if (isSecretProxy(proxy.type) && proxy.secretKey.trim()) {
lines.push(`secretKey = ${tomlString(proxy.secretKey.trim())}`);
}
});
return lines.join('\n');
}
/**
* @description 生成 frps 的 TOML 配置
* @returns {string} 配置内容
*/
function generateFrpsToml() {
let lines = [];
lines.push(`bindPort = ${data.frps.bindPort}`);
if (isValidNumber(data.frps.vhostHTTPPort)) {
lines.push(`vhostHTTPPort = ${data.frps.vhostHTTPPort}`);
}
if (isValidNumber(data.frps.vhostHTTPSPort)) {
lines.push(`vhostHTTPSPort = ${data.frps.vhostHTTPSPort}`);
}
if (data.frps.subdomainHost.trim()) {
lines.push(`subdomainHost = ${tomlString(data.frps.subdomainHost.trim())}`);
}
if (data.logLevel) {
lines.push('');
lines.push(`log.level = ${tomlString(data.logLevel)}`);
}
if (data.token.trim()) {
lines.push('');
lines.push('auth.method = "token"');
lines.push(`auth.token = ${tomlString(data.token.trim())}`);
}
if (data.frps.webServerAddr.trim() && isValidNumber(data.frps.webServerPort)) {
lines.push('');
lines.push(`webServer.addr = ${tomlString(data.frps.webServerAddr.trim())}`);
lines.push(`webServer.port = ${data.frps.webServerPort}`);
if (data.frps.webServerUser.trim()) {
lines.push(`webServer.user = ${tomlString(data.frps.webServerUser.trim())}`);
}
if (data.frps.webServerPassword.trim()) {
lines.push(`webServer.password = ${tomlString(data.frps.webServerPassword.trim())}`);
}
}
return lines.join('\n');
}
/**
* @description 生成 frpc 的 INI 配置
* @returns {string} 配置内容
*/
function generateFrpcIni() {
let lines = [];
lines.push('[common]');
lines.push(`server_addr = ${data.serverAddr.trim()}`);
lines.push(`server_port = ${data.serverPort}`);
if (data.logLevel) {
lines.push(`log_level = ${data.logLevel}`);
}
if (data.token.trim()) {
lines.push(`token = ${data.token.trim()}`);
}
data.proxies.forEach((proxy) => {
lines.push('');
lines.push(`[${proxy.name.trim()}]`);
lines.push(`type = ${proxy.type}`);
lines.push(`local_ip = ${proxy.localIP.trim() || '127.0.0.1'}`);
lines.push(`local_port = ${proxy.localPort}`);
if (isPortProxy(proxy.type)) {
lines.push(`remote_port = ${proxy.remotePort}`);
}
if (isDomainProxy(proxy.type)) {
let domains = splitDomains(proxy.customDomains);
if (domains.length > 0) {
lines.push(`custom_domains = ${domains.join(',')}`);
}
if (proxy.subdomain.trim()) {
lines.push(`subdomain = ${proxy.subdomain.trim()}`);
}
}
if (isSecretProxy(proxy.type) && proxy.secretKey.trim()) {
lines.push(`sk = ${proxy.secretKey.trim()}`);
}
});
return lines.join('\n');
}
/**
* @description 生成 frps 的 INI 配置
* @returns {string} 配置内容
*/
function generateFrpsIni() {
let lines = [];
lines.push('[common]');
lines.push(`bind_port = ${data.frps.bindPort}`);
if (isValidNumber(data.frps.vhostHTTPPort)) {
lines.push(`vhost_http_port = ${data.frps.vhostHTTPPort}`);
}
if (isValidNumber(data.frps.vhostHTTPSPort)) {
lines.push(`vhost_https_port = ${data.frps.vhostHTTPSPort}`);
}
if (data.frps.subdomainHost.trim()) {
lines.push(`subdomain_host = ${data.frps.subdomainHost.trim()}`);
}
if (data.logLevel) {
lines.push(`log_level = ${data.logLevel}`);
}
if (data.token.trim()) {
lines.push(`token = ${data.token.trim()}`);
}
if (data.frps.webServerAddr.trim() && isValidNumber(data.frps.webServerPort)) {
lines.push(`dashboard_addr = ${data.frps.webServerAddr.trim()}`);
lines.push(`dashboard_port = ${data.frps.webServerPort}`);
if (data.frps.webServerUser.trim()) {
lines.push(`dashboard_user = ${data.frps.webServerUser.trim()}`);
}
if (data.frps.webServerPassword.trim()) {
lines.push(`dashboard_pwd = ${data.frps.webServerPassword.trim()}`);
}
}
return lines.join('\n');
}
/** 处理生成配置 */
function handleGenerate() {
if (!validateConfig()) {
return;
}
let isToml = (data.format === 'toml');
if (data.mode === 'frpc') {
result.value = (isToml ? generateFrpcToml() : generateFrpcIni());
} else {
result.value = (isToml ? generateFrpsToml() : generateFrpsIni());
}
$message.success('配置生成成功');
}
/** 复制结果 */
function handleCopy() {
if (!clipboard.isSupported) {
$message.error('复制失败:当前浏览器不支持该操作');
return Promise.resolve();
}
return clipboard.copy(result.value).then(() => {
$message.success('复制成功');
}).catch((error) => {
console.error('复制失败:');
console.error(error);
$message.error('复制失败:异常');
});
}
/** 下载结果 */
function handleDownload() {
let blob = new Blob([result.value], { type: 'text/plain;charset=utf-8' });
let url = URL.createObjectURL(blob);
let link = document.createElement('a');
link.href = url;
link.download = resultFileName.value;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
setTimeout(() => {
URL.revokeObjectURL(url);
}, 1000);
$message.success('已开始下载');
}
/** 初始添加一个代理 */
addProxy();
</script> </script>
<style lang="less" scoped> <style lang="less" scoped>
.config-input {
width: 260px;
}
.config-input--wide {
width: 420px;
}
.config-select {
width: 260px;
}
.proxy-item {
padding: 12px;
border: 1px solid #EEE;
border-radius: 4px;
background-color: #FAFAFA;
& + .proxy-item {
margin-top: 12px;
}
}
.proxy-header {
display: flex;
align-items: center;
margin-bottom: 12px;
.proxy-index {
flex-shrink: 0;
margin-right: 8px;
color: #999;
font-family: monospace;
}
.proxy-name {
width: 220px;
}
.proxy-type {
margin: 0 8px;
width: 120px;
}
}
.proxy-form {
:deep(.n-form-item) {
margin-bottom: 8px;
}
}
.empty-tips {
padding: 16px;
text-align: center;
color: #999;
}
.result-input {
font-family: monospace;
}
.tip-text {
color: #666;
font-size: 14px;
line-height: 1.8;
p {
margin: 0;
}
code {
padding: 0 4px;
border-radius: 2px;
background-color: #F5F5F5;
font-family: monospace;
}
}
</style> </style>
@@ -1,8 +1,8 @@
<template> <template>
<div class="tool-detail-page"> <div class="tool-detail-page">
<!-- 配置选项 --> <!-- 配置参数 -->
<n-card size="small" title="配置选项"> <n-card size="small" title="配置参数">
<n-form <n-form
class="form-no-feedback" class="form-no-feedback"
label-align="right" label-align="right"
@@ -1,9 +1,488 @@
<template> <template>
<div class="tool-detail-page"></div> <div class="tool-detail-page">
<!-- 链接模板 -->
<n-card size="small" title="链接模板">
<n-form
class="form-no-feedback"
label-align="right"
label-placement="left"
label-width="auto"
>
<n-form-item label="链接模板:">
<n-input
v-model:value="linkBase"
placeholder="使用 {n} 表示变量,例如:https://example.com/file_{n}.jpg"
clearable
></n-input>
</n-form-item>
</n-form>
</n-card>
<!-- 配置参数 -->
<n-card size="small" title="参数配置">
<n-radio-group v-model:value="mode">
<!-- 等差数列 -->
<div class="mode-item">
<n-flex vertical>
<n-radio value="as">等差数列</n-radio>
<n-form
class="form-no-feedback"
label-align="right"
label-placement="left"
label-width="auto"
>
<n-flex>
<n-form-item label="首项:">
<n-input-number
v-model:value="modes.as.first"
:min="0"
:step="1"
></n-input-number>
</n-form-item>
<n-form-item label="公差:">
<n-input-number
v-model:value="modes.as.diff"
:min="1"
:step="1"
></n-input-number>
</n-form-item>
<n-form-item label="项数:">
<n-input-number
v-model:value="modes.as.count"
:min="1"
:max="1000"
:step="1"
></n-input-number>
</n-form-item>
</n-flex>
<n-flex>
<n-form-item label="选项:">
<n-checkbox
v-model:checked="modes.as.zero"
>补零</n-checkbox>
</n-form-item>
<n-form-item>
<n-checkbox
v-model:checked="modes.as.reverse"
>倒序</n-checkbox>
</n-form-item>
</n-flex>
</n-form>
</n-flex>
</div>
<!-- 等比数列 -->
<div class="mode-item">
<n-flex vertical>
<n-radio value="ps">等比数列</n-radio>
<n-form
class="form-no-feedback"
label-align="right"
label-placement="left"
label-width="auto"
>
<n-flex>
<n-form-item label="首项:">
<n-input-number
v-model:value="modes.ps.first"
:min="1"
:step="1"
></n-input-number>
</n-form-item>
<n-form-item label="公比:">
<n-input-number
v-model:value="modes.ps.diff"
:min="2"
:step="1"
></n-input-number>
</n-form-item>
<n-form-item label="项数:">
<n-input-number
v-model:value="modes.ps.count"
:min="1"
:max="1000"
:step="1"
></n-input-number>
</n-form-item>
</n-flex>
<n-flex>
<n-form-item label="选项:">
<n-checkbox
v-model:checked="modes.ps.zero"
>补零</n-checkbox>
</n-form-item>
<n-form-item>
<n-checkbox
v-model:checked="modes.ps.reverse"
>倒序</n-checkbox>
</n-form-item>
</n-flex>
</n-form>
</n-flex>
</div>
<!-- 字母变化 -->
<div class="mode-item">
<n-flex vertical>
<n-radio value="lc">字母变化</n-radio>
<n-form
class="form-no-feedback"
label-align="right"
label-placement="left"
label-width="auto"
>
<n-flex align-items="center">
<n-form-item label="从:">
<n-input
v-model:value="modes.lc.start"
:maxlength="1"
placeholder="a"
></n-input>
</n-form-item>
<n-form-item label="到:">
<n-input
v-model:value="modes.lc.end"
:maxlength="1"
placeholder="z"
></n-input>
</n-form-item>
<n-form-item>
<n-checkbox
v-model:checked="modes.lc.reverse"
>倒序</n-checkbox>
</n-form-item>
</n-flex>
</n-form>
</n-flex>
</div>
</n-radio-group>
</n-card>
<!-- 操作 -->
<n-card size="small" title="操作">
<n-flex>
<n-button
type="primary"
@click="handleGenerate"
>生成链接</n-button>
<n-button
type="primary"
:disabled="!linkResult"
@click="handleCopy"
>复制结果</n-button>
<n-button
@click="handleClear"
>清空结果</n-button>
</n-flex>
</n-card>
<!-- 生成结果 -->
<n-card size="small" title="生成结果">
<n-form
class="form-no-feedback"
label-align="right"
label-placement="left"
label-width="auto"
>
<n-form-item>
<n-input
v-model:value="linkResult"
placeholder="生成的链接将显示在这里"
type="textarea"
:readonly="true"
:rows="10"
></n-input>
</n-form-item>
</n-form>
</n-card>
</div>
</template> </template>
<script setup> <script setup>
import {
NButton, NCard, NCheckbox, NFlex,
NForm, NFormItem, NInput, NInputNumber,
NRadio, NRadioGroup,
} from 'naive-ui';
import {
reactive, ref,
} from 'vue';
import {
$message,
} from '@/assets/js/naive-ui';
import {
useClipboard,
} from '@vueuse/core';
// 链接模板
const linkBase = ref('');
// 生成结果
const linkResult = ref('');
// 正则,匹配链接变量
const linkRegExp = /\{n\}/g;
// 当前模式
const mode = ref('as');
// 模式配置
const modes = reactive({
// 等差数列(Arithmetic Sequence)
as: {
first: 0,
diff: 1,
count: 10,
zero: false,
reverse: false,
},
// 等比数列(Proportional Sequence)
ps: {
first: 1,
diff: 2,
count: 10,
zero: false,
reverse: false,
},
// 字母变化(Letter Change)
lc: {
start: 'a',
end: 'z',
reverse: false,
},
});
// 剪贴板功能
const clipboard = useClipboard({
legacy: true,
read: false,
});
/** 处理生成链接 */
function handleGenerate() {
if (!linkBase.value) {
$message.warning('请输入链接模板');
return;
}
switch (mode.value) {
case 'as':
linkResult.value = generateSeq('as');
break;
case 'ps':
linkResult.value = generateSeq('ps');
break;
case 'lc':
linkResult.value = generateLetter();
break;
default:
break;
}
}
/**
* @description 生成数列
* @param {string} type 类型(as - 等差数列,ps - 等比数列)
*/
function generateSeq(type) {
let linkBaseVal = linkBase.value;
if (!linkBaseVal) {
return '';
}
let data = modes[type];
if (!data) {
return '';
}
let nFirst = data.first;
let nCount = data.count;
let nDiff = data.diff;
let nResult = {
digits: 0, // 最大位数
numbers: [], // 生成的数值
};
let links = [];
// 等差数列公式
let expAS = (i) => {
return (nFirst + (i - 1) * nDiff);
};
// 等比数列公式
let expPS = (i) => {
return (nFirst * Math.pow(nDiff, (i - 1)));
};
// 实际使用的公式
let exp = (type === 'as' ? expAS : expPS);
// 生成数值
for (let i = 1; i <= nCount; i++) {
// 等差数列 / 等比数列
let n = exp(i);
let digits = Math.abs(n).toString().length;
(digits > nResult.digits) && (nResult.digits = digits);
nResult.numbers.push(n);
}
// 补零
if (data.zero) {
let digits = nResult.digits;
let base = Math.pow(10, digits);
let numbers = nResult.numbers;
for (let i = 0; i < numbers.length; i++) {
let n = numbers[i];
if (n >= 0) {
numbers[i] = (n / base).toFixed(digits).substr(2);
} else {
numbers[i] = '-' + (n / base).toFixed(digits).substr(3);
}
}
}
// 倒序
if (data.reverse) {
nResult.numbers.reverse();
}
// 生成链接
nResult.numbers.forEach((n) => {
links.push(linkBaseVal.replace(linkRegExp, n));
});
return links.join('\n');
}
/**
* @description 生成字母变化链接
* @returns {string} 生成结果
*/
function generateLetter() {
let linkBaseVal = linkBase.value;
if (!linkBaseVal) {
return '';
}
let data = modes.lc;
// 编码数值
let cStart = data.start.charCodeAt(0);
let cEnd = data.end.charCodeAt(0);
let chars = [];
let links = [];
// 生成字母
if (cStart >= 65 && cStart <= 122 && cEnd >= 65 && cEnd <= 122) {
if (cStart < cEnd) {
for (let i = cStart; i <= cEnd; i++) {
// 跳过符号 [ \ ] ^ _ `
if (i >= 91 && i <= 96) {
continue;
}
chars.push(String.fromCharCode(i));
}
} else if (cStart > cEnd) {
$message.warning('字母先后顺序有误。注意:大写字母需要在前。');
return '';
} else if (cStart === cEnd) {
$message.warning('仅有 1 条链接,无需生成。');
return '';
} else {
$message.error('未知错误。');
return '';
}
} else {
$message.warning('输入有误,请检查字母范围。');
return '';
}
// 倒序
if (data.reverse) {
chars.reverse();
}
// 生成链接
chars.forEach((c) => {
links.push(linkBaseVal.replace(linkRegExp, c));
});
return links.join('\n');
}
/** 处理复制结果 */
function handleCopy() {
if (clipboard.isSupported) {
return clipboard.copy(linkResult.value).then(() => {
$message.success('复制成功');
}).catch((error) => {
console.error('复制失败:');
console.error(error);
$message.error('复制失败:异常');
});
} else {
$message.error('复制失败:当前浏览器不支持该操作');
return Promise.resolve();
}
}
/** 处理清空结果 */
function handleClear() {
linkResult.value = '';
}
</script> </script>
<style lang="less" scoped> <style lang="less" scoped>
.tool-detail-page {
:deep(.n-input-number) {
width: 8em;
}
:deep(.n-input) {
max-width: 48em;
}
:deep(.n-input--textarea) {
max-width: 48em;
font-family: monospace;
}
.mode-item {
padding: 12px 0;
border-bottom: 1px solid #eee;
&:last-child {
border-bottom: none;
}
:deep(.n-form) {
margin-left: 2em;
}
}
}
</style> </style>
@@ -1,9 +1,153 @@
<template> <template>
<div class="tool-detail-page"></div> <div class="tool-detail-page">
<!-- 配置参数 -->
<n-card size="small" title="配置参数">
<n-form
class="form-no-feedback"
label-align="right"
label-placement="left"
label-width="auto"
>
<n-form-item label="生成数量:">
<n-input-number
v-model:value="info.count"
:min="1"
:max="1000"
:step="1"
></n-input-number>
</n-form-item>
<n-form-item label="选项:">
<n-flex>
<n-checkbox
v-model:checked="info.options.withSplit"
>是否包含分隔符“-”</n-checkbox>
</n-flex>
</n-form-item>
</n-form>
</n-card>
<!-- 操作 -->
<n-card size="small" title="操作">
<n-flex>
<n-button
type="primary"
@click="handleGenerate"
>生成 UUID V4</n-button>
<n-button
type="primary"
:disabled="!info.result"
@click="handleCopy"
>复制结果</n-button>
</n-flex>
</n-card>
<!-- 结果 -->
<n-card size="small" title="结果">
<n-form
class="form-no-feedback"
label-align="right"
label-placement="left"
label-width="auto"
>
<n-form-item>
<n-input
v-model:value="info.result"
placeholder="生成的 UUID 将显示在这里"
type="textarea"
:readonly="true"
:rows="8"
></n-input>
</n-form-item>
</n-form>
</n-card>
</div>
</template> </template>
<script setup> <script setup>
import {
NButton, NCard, NCheckbox,
NFlex, NForm, NFormItem,
NInput, NInputNumber,
} from 'naive-ui';
import {
reactive,
} from 'vue';
import {
$message,
} from '@/assets/js/naive-ui';
import {
useClipboard,
} from '@vueuse/core';
import {
getUuidV4,
} from '@/assets/js/utils';
const clipboard = useClipboard({
legacy: true,
read: false,
});
const info = reactive({
count: 1,
options: {
withSplit: true,
},
result: '',
});
/** 处理复制操作 */
function handleCopy() {
if (clipboard.isSupported) {
return clipboard.copy(info.result).then(() => {
$message.success('复制成功');
}).catch((error) => {
console.error('复制失败:');
console.error(error);
$message.error('复制失败:异常');
});
} else {
$message.error('复制失败:当前浏览器不支持该操作');
return Promise.resolve();
}
}
/** 处理生成操作 */
function handleGenerate() {
let count = info.count;
let opt = info.options;
let results = [];
for (let i = 0; i < count; i++) {
let uuid = getUuidV4(!opt.withSplit);
results.push(uuid);
}
info.result = results.join('\n');
}
</script> </script>
<style lang="less" scoped> <style lang="less" scoped>
.tool-detail-page {
:deep(.n-input-number) {
width: 8em;
}
:deep(.n-input--textarea) {
max-width: 48em;
font-family: monospace;
}
}
</style> </style>
@@ -1,9 +1,329 @@
<template> <template>
<div class="tool-detail-page"></div> <div class="tool-detail-page">
<!-- 方块坐标 -> 区块信息 -->
<n-card size="small" title="方块坐标 → 区块信息">
<n-form
class="form-no-feedback"
label-align="right"
label-placement="left"
label-width="auto"
>
<n-form-item label="方块坐标:">
<n-flex align="center">
<span class="coord-label">X</span>
<n-input-number
v-model:value="blockCoord.x"
class="coord-input"
:min="-30000000"
:max="30000000"
:precision="0"
:step="1"
:show-button="false"
></n-input-number>
<span class="coord-label">Z</span>
<n-input-number
v-model:value="blockCoord.z"
class="coord-input"
:min="-30000000"
:max="30000000"
:precision="0"
:step="1"
:show-button="false"
></n-input-number>
</n-flex>
</n-form-item>
</n-form>
<n-divider />
<div class="result-list">
<div class="result-row">
<div class="result-label">区块坐标:</div>
<div class="result-value">{{ blockResult.chunkX }}, {{ blockResult.chunkZ }}</div>
</div>
<div class="result-row">
<div class="result-label">区块内坐标:</div>
<div class="result-value">{{ blockResult.localX }}, {{ blockResult.localZ }}</div>
</div>
<div class="result-row">
<div class="result-label">区块范围:</div>
<div class="result-value">
X:{{ blockResult.minX }} ~ {{ blockResult.maxX }},Z:{{ blockResult.minZ }} ~ {{ blockResult.maxZ }}
</div>
</div>
<div class="result-row">
<div class="result-label">区域文件:</div>
<div class="result-value">{{ blockResult.regionFileName }}</div>
</div>
<div class="result-row">
<div class="result-label">区域内区块坐标:</div>
<div class="result-value">{{ blockResult.regionBlockX }}, {{ blockResult.regionBlockZ }}</div>
</div>
<div class="result-row">
<div class="result-label">区块序号(区域内):</div>
<div class="result-value">{{ blockResult.index }}</div>
</div>
<div class="result-row">
<div class="result-label">头部记录位置:</div>
<div class="result-value">{{ blockResult.headerOffset }} 字节</div>
</div>
<div class="result-row">
<div class="result-label">时间戳记录位置:</div>
<div class="result-value">{{ blockResult.timestampOffset }} 字节</div>
</div>
</div>
</n-card>
<!-- 区块坐标 -> 方块范围 -->
<n-card size="small" title="区块坐标 → 方块范围">
<n-form
class="form-no-feedback"
label-align="right"
label-placement="left"
label-width="auto"
>
<n-form-item label="区块坐标:">
<n-flex align="center">
<span class="coord-label">X</span>
<n-input-number
v-model:value="chunkCoord.x"
class="coord-input"
:min="-1875000"
:max="1875000"
:precision="0"
:step="1"
:show-button="false"
></n-input-number>
<span class="coord-label">Z</span>
<n-input-number
v-model:value="chunkCoord.z"
class="coord-input"
:min="-1875000"
:max="1875000"
:precision="0"
:step="1"
:show-button="false"
></n-input-number>
</n-flex>
</n-form-item>
</n-form>
<n-divider />
<div class="result-list">
<div class="result-row">
<div class="result-label">方块坐标范围:</div>
<div class="result-value">
X:{{ chunkResult.minX }} ~ {{ chunkResult.maxX }},Z:{{ chunkResult.minZ }} ~ {{ chunkResult.maxZ }}
</div>
</div>
<div class="result-row">
<div class="result-label">起始方块坐标:</div>
<div class="result-value">{{ chunkResult.minX }}, {{ chunkResult.minZ }}</div>
</div>
<div class="result-row">
<div class="result-label">区域文件:</div>
<div class="result-value">{{ chunkResult.regionFileName }}</div>
</div>
<div class="result-row">
<div class="result-label">区域内区块坐标:</div>
<div class="result-value">{{ chunkResult.regionBlockX }}, {{ chunkResult.regionBlockZ }}</div>
</div>
<div class="result-row">
<div class="result-label">区块序号(区域内):</div>
<div class="result-value">{{ chunkResult.index }}</div>
</div>
</div>
</n-card>
<!-- 说明 -->
<n-card size="small" title="说明">
<div class="tip-text">
<p>1 个区块为 16 × 16 个方块,区块坐标 = 方块坐标除以 16 后向下取整。</p>
<p>1 个区域文件(<code>r.X.Z.mca</code>)包含 32 × 32 个区块,区域坐标 = 区块坐标除以 32 后向下取整。</p>
<p>区域内区块序号 = 区域内 X + 区域内 Z × 32;头部记录位置 = 4 + 序号 × 4,时间戳记录位置 = 4096 + 序号 × 4(均为字节)。</p>
<p>Y 坐标(高度)不影响区块坐标,因此无需填写。</p>
</div>
</n-card>
</div>
</template> </template>
<script setup> <script setup>
import {
NCard, NDivider, NFlex,
NForm, NFormItem, NInputNumber,
} from 'naive-ui';
import {
computed, reactive,
} from 'vue';
/** 方块坐标 */
const blockCoord = reactive({
x: 0,
z: 0,
});
/** 区块坐标 */
const chunkCoord = reactive({
x: 0,
z: 0,
});
/**
* @description 向下取整除法
* @param {number} value 被除数
* @param {number} divisor 除数
* @returns {number} 结果
*/
function floorDiv(value, divisor) {
return Math.floor(value / divisor);
}
/**
* @description 取模(结果始终为非负数)
* @param {number} value 被除数
* @param {number} divisor 除数
* @returns {number} 结果
*/
function floorMod(value, divisor) {
return ((value % divisor) + divisor) % divisor;
}
/**
* @description 将输入值转换为有效数值
* @param {number|null} value 输入值
* @param {number} fallback 默认值
* @returns {number} 结果
*/
function toNumber(value, fallback = 0) {
return (typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : fallback);
}
/**
* @description 根据区域坐标生成区域文件名
* @param {number} regionX 区域 X 坐标
* @param {number} regionZ 区域 Z 坐标
* @returns {string} 文件名
*/
function getRegionFileName(regionX, regionZ) {
return `r.${regionX}.${regionZ}.mca`;
}
/** 方块坐标计算结果 */
const blockResult = computed(() => {
let x = toNumber(blockCoord.x);
let z = toNumber(blockCoord.z);
let chunkX = floorDiv(x, 16);
let chunkZ = floorDiv(z, 16);
let localX = floorMod(x, 16);
let localZ = floorMod(z, 16);
let regionX = floorDiv(chunkX, 32);
let regionZ = floorDiv(chunkZ, 32);
let regionBlockX = floorMod(chunkX, 32);
let regionBlockZ = floorMod(chunkZ, 32);
let index = regionBlockX + regionBlockZ * 32;
return {
chunkX,
chunkZ,
headerOffset: 4 + index * 4,
index,
localX,
localZ,
maxX: chunkX * 16 + 15,
maxZ: chunkZ * 16 + 15,
minX: chunkX * 16,
minZ: chunkZ * 16,
regionBlockX,
regionBlockZ,
regionFileName: getRegionFileName(regionX, regionZ),
timestampOffset: 4096 + index * 4,
};
});
/** 区块坐标计算结果 */
const chunkResult = computed(() => {
let chunkX = toNumber(chunkCoord.x);
let chunkZ = toNumber(chunkCoord.z);
let regionX = floorDiv(chunkX, 32);
let regionZ = floorDiv(chunkZ, 32);
let regionBlockX = floorMod(chunkX, 32);
let regionBlockZ = floorMod(chunkZ, 32);
return {
index: regionBlockX + regionBlockZ * 32,
maxX: chunkX * 16 + 15,
maxZ: chunkZ * 16 + 15,
minX: chunkX * 16,
minZ: chunkZ * 16,
regionBlockX,
regionBlockZ,
regionFileName: getRegionFileName(regionX, regionZ),
};
});
</script> </script>
<style lang="less" scoped> <style lang="less" scoped>
.coord-label {
flex-shrink: 0;
color: #666;
font-family: monospace;
}
.coord-input {
width: 140px;
}
.result-list {
.result-row {
display: flex;
align-items: center;
padding: 6px 0;
font-size: 14px;
.result-label {
flex-shrink: 0;
width: 10em;
text-align: right;
color: #666;
}
.result-value {
margin-left: 12px;
font-family: monospace;
user-select: text;
}
}
}
.tip-text {
color: #666;
font-size: 14px;
line-height: 1.8;
p {
margin: 0;
}
code {
padding: 0 4px;
border-radius: 2px;
background-color: #F5F5F5;
font-family: monospace;
}
}
</style> </style>
@@ -7,8 +7,8 @@
<n-p>若内容出现乱码,请尝试更改“文件编码”后重新打开文件。</n-p> <n-p>若内容出现乱码,请尝试更改“文件编码”后重新打开文件。</n-p>
</n-card> </n-card>
<!-- 设置 --> <!-- 配置参数 -->
<n-card size="small" title="设置"> <n-card size="small" title="配置参数">
<n-flex> <n-flex>
<!-- 文件编码 --> <!-- 文件编码 -->
<div class="config-item"> <div class="config-item">
@@ -1,9 +1,679 @@
<template> <template>
<div class="tool-detail-page"></div> <div class="tool-detail-page">
<!-- 说明 -->
<n-card size="small" title="说明">
<div class="tip-text">
<p>目前仅支持普通方块。</p>
<p>已测试游戏版本:Minecraft 1.12.2。</p>
<p>生成的 <code>patchblock</code>、<code>texture</code> 内容会追加到对应文件中,请按 Dynmap 的模型 / 纹理配置格式使用。</p>
</div>
</n-card>
<!-- 参数 -->
<n-card size="small" title="参数">
<n-form
class="form-no-feedback"
label-align="right"
label-placement="left"
label-width="auto"
>
<n-form-item label="Mod ID:">
<n-input
v-model:value="inputs.modID"
class="param-input"
placeholder="例如:example"
></n-input>
</n-form-item>
<n-form-item label="注释:">
<n-input
v-model:value="inputs.comment"
class="param-input"
placeholder="可选,添加在每条记录上方"
></n-input>
</n-form-item>
<n-form-item label="方块 ID:">
<n-input
v-model:value="inputs.blockID"
class="param-input"
placeholder="例:stone(不带命名空间)"
></n-input>
</n-form-item>
<n-form-item label="子方块:">
<n-input
v-model:value="inputs.blockSubset"
class="param-input param-input--short"
placeholder="0 ~ 15,默认 0,可使用 *"
></n-input>
</n-form-item>
<n-form-item label="透明方块:">
<n-checkbox v-model:checked="inputs.isTransparent" />
</n-form-item>
<n-form-item label="纹理 ID:">
<n-input
v-model:value="inputs.textureID"
class="param-input"
placeholder="默认与 Mod ID 相同"
></n-input>
</n-form-item>
<n-form-item label="纹理文件路径:">
<n-input
v-model:value="inputs.textureFilePath"
class="param-input param-input--wide"
placeholder="例:assets/minecraft/textures/blocks/stone.png"
></n-input>
</n-form-item>
</n-form>
</n-card>
<!-- 操作 -->
<n-card size="small" title="操作">
<n-flex class="action-row">
<n-button
type="success"
@click="addBlock"
>添加方块</n-button>
<n-button
type="warning"
@click="historyCtrl('undo')"
>撤销操作</n-button>
<n-button
type="warning"
@click="historyCtrl('redo')"
>还原操作</n-button>
</n-flex>
<n-flex class="action-row">
<n-button
type="danger"
@click="clearResult"
>清除结果</n-button>
<n-button
type="primary"
@click="mergeResult"
>合并结果</n-button>
<n-button
type="danger"
@click="clearMerged"
>清除合并</n-button>
</n-flex>
<n-flex class="action-row">
<n-button
type="success"
@click="saveResult"
>记录结果</n-button>
<n-button
type="primary"
@click="loadSaves"
>载入记录</n-button>
<n-button
type="danger"
@click="clearSaves"
>清除记录</n-button>
</n-flex>
</n-card>
<!-- 生成结果 -->
<n-card size="small" title="生成结果">
<div class="output-block">
<div class="output-title">{{ modPrefix }}-models.txt - modname</div>
<n-input
v-model:value="outputs.modID"
class="monospace-input"
placeholder="Mod 名称"
:readonly="true"
></n-input>
</div>
<div class="output-block">
<div class="output-title">{{ modPrefix }}-models.txt - patch</div>
<n-input
v-model:value="outputs.modelsPatch"
class="monospace-input"
type="textarea"
:rows="8"
:readonly="true"
></n-input>
</div>
<div class="output-block is-part">
<div class="output-title">{{ modPrefix }}-models.txt - patchblock</div>
<n-input
v-model:value="outputs.modelsPatchBlock"
class="monospace-input"
type="textarea"
placeholder="生成的 patchblock 内容"
:rows="8"
></n-input>
</div>
<div class="output-block is-part">
<div class="output-title">{{ modPrefix }}-texture.txt - texture</div>
<n-input
v-model:value="outputs.textureTexture"
class="monospace-input"
type="textarea"
placeholder="生成的 texture 内容"
:rows="8"
></n-input>
</div>
<div class="output-block is-part">
<div class="output-title">{{ modPrefix }}-texture.txt - block</div>
<n-input
v-model:value="outputs.textureBlock"
class="monospace-input"
type="textarea"
placeholder="生成的 block 内容"
:rows="8"
></n-input>
</div>
<div class="output-block is-merged">
<div class="output-title">
<span>合并:{{ modPrefix }}-models.txt</span>
<n-button
size="tiny"
:disabled="!outputs.mergedModels"
@click="handleCopy(outputs.mergedModels)"
>复制</n-button>
</div>
<n-input
v-model:value="outputs.mergedModels"
class="monospace-input"
type="textarea"
:rows="10"
:readonly="true"
></n-input>
</div>
<div class="output-block is-merged">
<div class="output-title">
<span>合并:{{ modPrefix }}-texture.txt</span>
<n-button
size="tiny"
:disabled="!outputs.mergedTexture"
@click="handleCopy(outputs.mergedTexture)"
>复制</n-button>
</div>
<n-input
v-model:value="outputs.mergedTexture"
class="monospace-input"
type="textarea"
:rows="10"
:readonly="true"
></n-input>
</div>
</n-card>
</div>
</template> </template>
<script setup> <script setup>
import {
NButton, NCard, NCheckbox, NFlex,
NForm, NFormItem, NInput,
} from 'naive-ui';
import {
computed, reactive, ref,
} from 'vue';
import {
$dialog, $message,
} from '@/assets/js/naive-ui';
import {
useClipboard,
} from '@vueuse/core';
/** 本地储存 key 前缀 */
const STORAGE_KEY_PREFIX = 'frost-navigation/toolbox/dynmap-renderdata/';
/** 历史记录最大数量 */
const HISTORY_MAX = 20;
/** 剪贴板 */
const clipboard = useClipboard({
legacy: true,
read: false,
});
/** 静态数据 */
const datas = {
/** 正方体 6 个面的 patch */
modelsPatch1: 'patch:id=patch0,Ox=0.0,Oy=0.0,Oz=0.0,Ux=1.0,Uy=0.0,Uz=0.0,Vx=0.0,Vy=0.0,Vz=1.0,Umin=0.0,Umax=1.0,Vmin=0.0,Vmax=1.0,VmaxAtUMax=1.0,VminAtUMax=0.0,visibility=top\npatch:id=patch1,Ox=0.0,Oy=1.0,Oz=1.0,Ux=1.0,Uy=1.0,Uz=1.0,Vx=0.0,Vy=1.0,Vz=0.0,Umin=0.0,Umax=1.0,Vmin=0.0,Vmax=1.0,VmaxAtUMax=1.0,VminAtUMax=0.0,visibility=top\npatch:id=patch2,Ox=1.0,Oy=0.0,Oz=0.0,Ux=0.0,Uy=0.0,Uz=0.0,Vx=1.0,Vy=1.0,Vz=0.0,Umin=0.0,Umax=1.0,Vmin=0.0,Vmax=1.0,VmaxAtUMax=1.0,VminAtUMax=0.0,visibility=top\npatch:id=patch3,Ox=0.0,Oy=0.0,Oz=1.0,Ux=1.0,Uy=0.0,Uz=1.0,Vx=0.0,Vy=1.0,Vz=1.0,Umin=0.0,Umax=1.0,Vmin=0.0,Vmax=1.0,VmaxAtUMax=1.0,VminAtUMax=0.0,visibility=top\npatch:id=patch4,Ox=0.0,Oy=0.0,Oz=0.0,Ux=0.0,Uy=0.0,Uz=1.0,Vx=0.0,Vy=1.0,Vz=0.0,Umin=0.0,Umax=1.0,Vmin=0.0,Vmax=1.0,VmaxAtUMax=1.0,VminAtUMax=0.0,visibility=top\npatch:id=patch5,Ox=1.0,Oy=0.0,Oz=1.0,Ux=1.0,Uy=0.0,Uz=0.0,Vx=1.0,Vy=1.0,Vz=1.0,Umin=0.0,Umax=1.0,Vmin=0.0,Vmax=1.0,VmaxAtUMax=1.0,VminAtUMax=0.0,visibility=top',
/** 正方体 6 个面的 patch 映射 */
modelsPatch2: ',patch0=patch0,patch1=patch1,patch2=patch2,patch3=patch3,patch4=patch4,patch5=patch5',
};
/** 输入参数 */
const inputs = reactive({
blockID: '',
blockSubset: '',
comment: '',
isTransparent: false,
modID: '',
textureFilePath: '',
textureID: '',
});
/** 输出结果 */
const outputs = reactive({
mergedModels: '',
mergedTexture: '',
modID: '',
modelsPatch: '',
modelsPatchBlock: '',
textureBlock: '',
textureTexture: '',
});
/** 历史记录列表 */
const historyList = ref([]);
/** 历史记录下标 */
const historyIndex = ref(0);
/** Mod 前缀(用于标题显示) */
const modPrefix = computed(() => {
return (inputs.modID || '*');
});
/**
* @description 初始化数据
*/
function initDatas() {
outputs.modelsPatch = datas.modelsPatch1;
}
/**
* @description 确认对话框
* @param {string} msg 提示内容
* @param {Function} fnConfirm 确认后进行的操作
*/
function confirmDialog(msg = '', fnConfirm = null) {
$dialog.warning({
title: '确认',
content: (msg || '确定要进行此操作?'),
positiveText: '确定',
negativeText: '取消',
onPositiveClick: () => {
if (fnConfirm) {
fnConfirm();
}
},
});
}
/**
* @description 历史记录操作
* @param {string} type 类型(record、redo、undo)
*/
function historyCtrl(type = 'record') {
let list = historyList.value;
let index = historyIndex.value;
if (type === 'record') {
// 下标不在末尾时,先删除后方内容
if (index < list.length - 1) {
list.splice(index + 1, list.length - (index + 1));
}
// 数量超出限制时,先删除最早的内容
if (list.length >= HISTORY_MAX) {
list.splice(0, list.length - HISTORY_MAX + 1);
}
// 添加记录
list.push(JSON.parse(JSON.stringify(outputs)));
historyIndex.value = list.length - 1;
} else if (type === 'redo') {
let item = list[index + 1];
if (item) {
Object.assign(outputs, JSON.parse(JSON.stringify(item)));
historyIndex.value = index + 1;
} else {
$message.warning('没有可以还原的内容');
}
} else if (type === 'undo') {
let item = list[index - 1];
if (item) {
Object.assign(outputs, JSON.parse(JSON.stringify(item)));
historyIndex.value = index - 1;
} else {
$message.warning('没有可以撤销的内容');
}
}
}
/** 同步 Mod ID */
function syncModID() {
inputs.modID = inputs.modID.toLowerCase();
outputs.modID = (inputs.modID ? `modname:${inputs.modID}` : '');
}
/**
* @description 获取注释前缀
* @param {string} content 原内容(用于判断是否需要换行)
* @returns {string} 注释内容
*/
function getComment(content = '') {
let prefix = (content ? '\n' : '');
if (inputs.comment) {
return `${prefix}# ${inputs.comment}\n`;
}
return prefix;
}
/**
* @description 获取子方块数值
* @returns {string} 子方块数值
*/
function getBlockSubset() {
return (inputs.blockSubset || '0');
}
/**
* @description 获取纹理 ID
* @returns {string} 纹理 ID
*/
function getTextureID() {
return (inputs.textureID || inputs.modID);
}
/** 添加方块 */
function addBlock() {
let requiredKeys = ['blockID', 'modID', 'textureFilePath'];
for (let key of requiredKeys) {
if (!inputs[key]) {
$message.warning('内容未填写完整');
return;
}
}
// 校验子方块格式
if (inputs.blockSubset && !/^(\*|[0-9]|1[0-5])$/.test(inputs.blockSubset)) {
$message.warning('子方块取值范围为 0 ~ 15,或使用 *');
return;
}
syncModID();
let subset = getBlockSubset();
let textureID = getTextureID();
let modID = inputs.modID;
let blockID = inputs.blockID;
// 处理:models.txt - patchblock
let str = outputs.modelsPatchBlock;
str += getComment(str);
str += 'patchblock:id=%';
str += blockID;
str += ',data=';
str += subset;
str += datas.modelsPatch2;
outputs.modelsPatchBlock = str;
// 处理:texture.txt - texture
str = outputs.textureTexture;
str += getComment(str);
str += 'texture:id=';
str += textureID;
str += ',filename=';
str += inputs.textureFilePath;
str += ',xcount=1,ycount=1';
outputs.textureTexture = str;
// 处理:texture.txt - block
str = outputs.textureBlock;
str += getComment(str);
str += 'block:id=%';
str += blockID;
str += ',data=';
str += subset;
str += ',allfaces=0:';
str += textureID;
str += ',stdrot=true';
if (inputs.isTransparent) {
str += ',transparency=TRANSPARENT';
}
outputs.textureBlock = str;
// 记录
historyCtrl('record');
$message.success(`已添加方块:${modID}:${blockID}`);
}
/** 清除结果 */
function clearResult() {
confirmDialog('是否清除生成结果?', () => {
for (let key in outputs) {
outputs[key] = '';
}
initDatas();
historyCtrl('record');
$message.success('已清除');
});
}
/** 合并结果 */
function mergeResult() {
let modelsKeys = ['modID', 'modelsPatch', 'modelsPatchBlock'];
let textureKeys = ['modID', 'textureTexture', 'textureBlock'];
clearMerged();
syncModID();
if (!outputs.modID) {
$message.warning('Mod ID 为空');
return;
}
modelsKeys.forEach((key, index) => {
let prefix = (index === 0 ? '' : '\n\n');
outputs.mergedModels += (prefix + outputs[key]);
});
textureKeys.forEach((key, index) => {
let prefix = (index === 0 ? '' : '\n\n');
outputs.mergedTexture += (prefix + outputs[key]);
});
$message.success('合并完成');
}
/** 清除合并结果 */
function clearMerged() {
outputs.mergedModels = '';
outputs.mergedTexture = '';
}
/** 记录结果 */
function saveResult() {
confirmDialog('是否记录生成结果到本地储存?', () => {
for (let key in outputs) {
localStorage.setItem((STORAGE_KEY_PREFIX + key), outputs[key]);
}
$message.success('已记录');
});
}
/** 载入记录 */
function loadSaves() {
confirmDialog('是否加载本地记录?', () => {
let records = {};
for (let key in outputs) {
let value = localStorage.getItem(STORAGE_KEY_PREFIX + key);
if (value !== null) {
records[key] = value;
}
}
if (Object.keys(records).length === 0) {
$message.warning('没有记录');
return;
}
Object.assign(outputs, records);
historyCtrl('record');
$message.success('已加载');
});
}
/** 清除记录 */
function clearSaves() {
confirmDialog('是否清除本地记录?', () => {
for (let key in outputs) {
localStorage.removeItem(STORAGE_KEY_PREFIX + key);
}
$message.success('已清除');
});
}
/**
* @description 复制文本
* @param {string} text 文本内容
*/
function handleCopy(text = '') {
if (!text) {
return;
}
if (!clipboard.isSupported) {
$message.error('复制失败:当前浏览器不支持该操作');
return;
}
clipboard.copy(text).then(() => {
$message.success('复制成功');
}).catch((error) => {
console.error('复制失败:');
console.error(error);
$message.error('复制失败:异常');
});
}
/** 初始化 */
initDatas();
historyCtrl('record');
</script> </script>
<style lang="less" scoped> <style lang="less" scoped>
.param-input {
width: 260px;
}
.param-input--short {
width: 160px;
}
.param-input--wide {
width: 420px;
}
.action-row {
& + .action-row {
margin-top: 8px;
}
}
.output-block {
& + .output-block {
margin-top: 16px;
}
.output-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 6px;
color: #666;
font-size: 14px;
}
&.is-part :deep(.n-input__border),
&.is-part :deep(.n-input__state-border) {
border-color: #FF5722;
}
&.is-merged :deep(.n-input__border),
&.is-merged :deep(.n-input__state-border) {
border-color: #4CAF50;
}
}
.monospace-input {
font-family: monospace;
}
.tip-text {
color: #666;
font-size: 14px;
line-height: 1.8;
p {
margin: 0;
}
code {
padding: 0 4px;
border-radius: 2px;
background-color: #F5F5F5;
font-family: monospace;
}
}
</style> </style>
@@ -1,9 +1,544 @@
<template> <template>
<div class="tool-detail-page"></div> <div class="tool-detail-page">
<!-- 操作 -->
<n-card size="small" title="操作">
<n-flex align="center">
<n-button
type="primary"
@click="handleRandom"
>随机生成 UUID</n-button>
<n-tag type="info">使用浏览器加密安全随机数生成 UUID V4</n-tag>
</n-flex>
</n-card>
<!-- 转换表单 -->
<n-card size="small" title="转换">
<div class="convert-list">
<!-- 十六进制 -->
<div class="convert-row">
<div class="row-label">Hexadecimal:</div>
<div class="row-content">
<n-input
v-model:value="data.hex"
class="hex-input"
:status="hexValid ? undefined : 'error'"
placeholder="00000000-0000-0000-0000-000000000000"
@update:value="handleHexChange"
></n-input>
</div>
<div class="row-actions">
<n-button
size="small"
type="success"
@click="handleCopy('hex')"
>复制</n-button>
</div>
</div>
<!-- 高低位 -->
<div class="convert-row">
<div class="row-label">UUID Most:</div>
<div class="row-content">
<n-input
v-model:value="data.most"
class="half-input"
:status="halvesValid ? undefined : 'error'"
placeholder="0"
@update:value="handleHalvesChange"
>
<template #suffix>L</template>
</n-input>
</div>
<div class="row-actions">
<n-button
size="small"
type="success"
@click="handleCopy('halves')"
>复制</n-button>
</div>
</div>
<div class="convert-row">
<div class="row-label">UUID Least:</div>
<div class="row-content">
<n-input
v-model:value="data.least"
class="half-input"
:status="halvesValid ? undefined : 'error'"
placeholder="0"
@update:value="handleHalvesChange"
>
<template #suffix>L</template>
</n-input>
</div>
<div class="row-actions"></div>
</div>
<!-- 整型数组 -->
<div class="convert-row convert-row--array">
<div class="row-label">UUID(整型数组):</div>
<div class="row-content array-content">
<span class="array-symbol">[I;&nbsp;</span>
<template
v-for="(_, index) in data.array"
:key="`array-${index}`"
>
<n-input-number
v-model:value="data.array[index]"
class="array-input"
:show-button="false"
:min="-2147483648"
:max="2147483647"
:precision="0"
:status="arrayValid ? undefined : 'error'"
@update:value="handleArrayChange"
></n-input-number>
<span
v-if="index < data.array.length - 1"
class="array-symbol"
>, </span>
</template>
<span class="array-symbol">]</span>
</div>
<div class="row-actions">
<n-button
size="small"
type="success"
@click="handleCopy('array')"
>复制</n-button>
</div>
</div>
</div>
</n-card>
<!-- 说明 -->
<n-card size="small" title="说明">
<div class="tip-text">
<p>可以在任意一栏中修改内容,其余两栏会自动同步;输入无效时对应输入框会显示为错误状态。</p>
<p>十六进制支持带分隔符(<code>xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx</code>)或 32 位连续形式。</p>
<p>整型数组格式常用于命令(如 <code>/tp @s [I; ...]</code>)及 NBT 数据。</p>
<p>
<span>资料参考:</span>
<n-a
href="https://minecraft.fandom.com/zh/wiki/通用唯一识别码"
target="_blank"
>Minecraft Wiki - 通用唯一识别码</n-a>
</p>
<p>
<span>算法参考:</span>
<n-a
href="https://github.com/AjaxGb/mc-uuid-converter"
target="_blank"
>AjaxGb / mc-uuid-converter</n-a>
</p>
</div>
</n-card>
</div>
</template> </template>
<script setup> <script setup>
import {
NButton, NCard, NFlex,
NInput, NInputNumber, NTag, NA,
} from 'naive-ui';
import {
computed, reactive,
} from 'vue';
import {
$message,
} from '@/assets/js/naive-ui';
import {
useClipboard,
} from '@vueuse/core';
/** 剪贴板 */
const clipboard = useClipboard({
legacy: true,
read: false,
});
/** 64 位整数的取值范围 */
const INT64_MIN = -(1n << 63n);
const INT64_MAX = (1n << 63n) - 1n;
/** UUID 字节缓冲区 */
const uuidBytes = new Uint8Array(16);
/** UUID 数据视图(用于读写 64 位整数) */
const uuidView = new DataView(uuidBytes.buffer);
/** 数据 */
const data = reactive({
/** 整型数组(4 个 int32) */
array: [0, 0, 0, 0],
/** 十六进制字符串 */
hex: '00000000-0000-0000-0000-000000000000',
/** UUID Least(有符号 64 位整数) */
least: '0',
/** UUID Most(有符号 64 位整数) */
most: '0',
});
/** 十六进制是否有效 */
const hexValid = computed(() => {
return parseHexText(data.hex) !== null;
});
/** 高低位是否有效 */
const halvesValid = computed(() => {
return (parseInt64Text(data.most) !== null && parseInt64Text(data.least) !== null);
});
/** 整型数组是否有效 */
const arrayValid = computed(() => {
return data.array.every((value) => {
return (typeof value === 'number' && Number.isInteger(value)
&& value >= -2147483648 && value <= 2147483647);
});
});
/**
* @description 将十六进制文本解析为 32 位长度的字符串
* @param {string} text 十六进制文本
* @returns {string|null} 解析结果,无效时返回 null
*/
function parseHexText(text = '') {
let hex = String(text).trim();
if (!hex) {
return null;
}
if (hex.includes('-')) {
let groups = hex.split('-');
let groupSizes = [8, 4, 4, 4, 12];
if (groups.length !== groupSizes.length) {
return null;
}
for (let i = 0; i < groups.length; i++) {
let group = groups[i];
if (!/^[0-9a-fA-F]*$/.test(group) || group.length > groupSizes[i]) {
return null;
}
}
hex = groups.map((group, index) => {
return group.padStart(groupSizes[index], '0');
}).join('');
} else {
if (!/^[0-9a-fA-F]{1,32}$/.test(hex)) {
return null;
}
hex = hex.padStart(32, '0');
}
return hex;
}
/**
* @description 将文本解析为有符号 64 位整数
* @param {string|number} text 文本
* @returns {bigint|null} 解析结果,无效时返回 null
*/
function parseInt64Text(text = '') {
let value = String(text).trim();
if (!/^[-+]?\d+$/.test(value)) {
return null;
}
try {
let big = window.BigInt(value);
if (big < INT64_MIN || big > INT64_MAX) {
return null;
}
return big;
} catch (error) {
console.warn('解析 64 位整数失败:', error);
return null;
}
}
/** 从缓冲区同步全部字段 */
function syncFromBuffer() {
let high = uuidView.getBigUint64(0, false).toString(16).padStart(16, '0');
let low = uuidView.getBigUint64(8, false).toString(16).padStart(16, '0');
let hex = high + low;
data.hex = [
hex.slice(0, 8),
hex.slice(8, 12),
hex.slice(12, 16),
hex.slice(16, 20),
hex.slice(20, 32),
].join('-');
data.most = String(uuidView.getBigInt64(0, false));
data.least = String(uuidView.getBigInt64(8, false));
data.array = [
uuidView.getInt32(0, false),
uuidView.getInt32(4, false),
uuidView.getInt32(8, false),
uuidView.getInt32(12, false),
];
}
/** 处理十六进制输入 */
function handleHexChange() {
let hex = parseHexText(data.hex);
if (hex === null) {
return;
}
uuidView.setBigUint64(0, window.BigInt('0x' + hex.slice(0, 16)), false);
uuidView.setBigUint64(8, window.BigInt('0x' + hex.slice(16)), false);
let most = String(uuidView.getBigInt64(0, false));
let least = String(uuidView.getBigInt64(8, false));
data.most = most;
data.least = least;
data.array = [
uuidView.getInt32(0, false),
uuidView.getInt32(4, false),
uuidView.getInt32(8, false),
uuidView.getInt32(12, false),
];
}
/** 处理高低位输入 */
function handleHalvesChange() {
let most = parseInt64Text(data.most);
let least = parseInt64Text(data.least);
if (most === null || least === null) {
return;
}
uuidView.setBigInt64(0, most, false);
uuidView.setBigInt64(8, least, false);
syncFromBufferExceptHalves();
}
/**
* @description 从缓冲区同步除高低位以外的字段
*/
function syncFromBufferExceptHalves() {
let high = uuidView.getBigUint64(0, false).toString(16).padStart(16, '0');
let low = uuidView.getBigUint64(8, false).toString(16).padStart(16, '0');
let hex = high + low;
data.hex = [
hex.slice(0, 8),
hex.slice(8, 12),
hex.slice(12, 16),
hex.slice(16, 20),
hex.slice(20, 32),
].join('-');
data.array = [
uuidView.getInt32(0, false),
uuidView.getInt32(4, false),
uuidView.getInt32(8, false),
uuidView.getInt32(12, false),
];
}
/** 处理整型数组输入 */
function handleArrayChange() {
if (!arrayValid.value) {
return;
}
data.array.forEach((value, index) => {
uuidView.setInt32(index * 4, value, false);
});
let high = uuidView.getBigUint64(0, false).toString(16).padStart(16, '0');
let low = uuidView.getBigUint64(8, false).toString(16).padStart(16, '0');
let hex = high + low;
data.hex = [
hex.slice(0, 8),
hex.slice(8, 12),
hex.slice(12, 16),
hex.slice(16, 20),
hex.slice(20, 32),
].join('-');
data.most = String(uuidView.getBigInt64(0, false));
data.least = String(uuidView.getBigInt64(8, false));
}
/** 处理随机生成 */
function handleRandom() {
window.crypto.getRandomValues(uuidBytes);
// 设置版本为 4(随机)
uuidBytes[6] = (uuidBytes[6] & 0x0F) | (4 << 4);
// 设置变体为 1(Leach–Salz)
uuidBytes[8] = (uuidBytes[8] & 0x3F) | 0x80;
syncFromBuffer();
$message.success('已生成新的 UUID');
}
/**
* @description 复制指定内容
* @param {string} type 类型(hex、halves、array)
*/
function handleCopy(type = 'hex') {
let text = '';
if (type === 'hex') {
text = data.hex;
} else if (type === 'halves') {
text = `UUID Most: ${data.most}L, UUID Least: ${data.least}L`;
} else if (type === 'array') {
text = `[I; ${data.array.join(', ')}]`;
}
if (!text) {
return;
}
if (!clipboard.isSupported) {
$message.error('复制失败:当前浏览器不支持该操作');
return;
}
clipboard.copy(text).then(() => {
$message.success('复制成功');
}).catch((error) => {
console.error('复制失败:');
console.error(error);
$message.error('复制失败:异常');
});
}
</script> </script>
<style lang="less" scoped> <style lang="less" scoped>
.convert-list {
overflow-x: auto;
}
.convert-row {
display: flex;
align-items: center;
padding: 10px 0;
border-bottom: 1px solid #F0F0F0;
&:last-child {
border-bottom: none;
}
.row-label {
flex-shrink: 0;
width: 10em;
text-align: right;
color: #666;
font-family: monospace;
}
.row-content {
display: flex;
align-items: center;
flex-grow: 1;
margin: 0 12px;
min-width: 0;
}
.row-actions {
flex-shrink: 0;
width: 64px;
text-align: right;
}
.hex-input {
width: 360px;
font-family: monospace;
}
.half-input {
width: 220px;
font-family: monospace;
}
}
.convert-row--array {
.array-content {
flex-wrap: nowrap;
}
.array-symbol {
flex-shrink: 0;
font-family: monospace;
}
.array-input {
width: 150px;
:deep(.n-input__input-el) {
text-align: right;
font-family: monospace;
}
}
}
.tip-text {
color: #666;
font-size: 14px;
line-height: 1.8;
p {
margin: 0;
}
code {
padding: 0 4px;
border-radius: 2px;
background-color: #F5F5F5;
font-family: monospace;
}
}
</style> </style>
@@ -1,8 +1,8 @@
<template> <template>
<div class="tool-detail-page"> <div class="tool-detail-page">
<!-- 注意 --> <!-- 注意事项 -->
<n-card size="small" title="注意"> <n-card size="small" title="注意事项">
<n-p>由于浏览器限制,通过 HTTPS 访问网站时只能连接带 SSL 的 WebSocket(WSS)。</n-p> <n-p>由于浏览器限制,通过 HTTPS 访问网站时只能连接带 SSL 的 WebSocket(WSS)。</n-p>
<n-p>若需要连接不带 SSL 的 WebSocket(WS),建议下载到本地后使用。</n-p> <n-p>若需要连接不带 SSL 的 WebSocket(WS),建议下载到本地后使用。</n-p>
</n-card> </n-card>
@@ -73,8 +73,8 @@
</n-flex> </n-flex>
</n-card> </n-card>
<!-- 日志 --> <!-- 日志内容 -->
<n-card size="small" title="日志"> <n-card size="small" title="日志内容">
<div <div
ref="logsContentRef" ref="logsContentRef"
class="logs-content" class="logs-content"
@@ -107,8 +107,8 @@
</div> </div>
</n-card> </n-card>
<!-- 设置 --> <!-- 配置参数 -->
<n-card size="small" title="设置"> <n-card size="small" title="配置参数">
<n-form <n-form
class="form-no-feedback" class="form-no-feedback"
label-align="left" label-align="left"
+28 -29
View File
@@ -13,10 +13,16 @@
}" }"
@click="isFaded = false" @click="isFaded = false"
> >
<div class="controls"> <!-- 配置参数 -->
<n-card size="small" title="配置参数">
<div class="title">开关 / Switch</div> <n-form
class="form-no-feedback"
label-align="left"
label-placement="left"
label-width="auto"
>
<n-form-item label="开关 / Switch">
<n-switch <n-switch
:value="wakeLock.isActive.value" :value="wakeLock.isActive.value"
size="medium" size="medium"
@@ -26,9 +32,9 @@
<template #checked>开启</template> <template #checked>开启</template>
<template #unchecked>关闭</template> <template #unchecked>关闭</template>
</n-switch> </n-switch>
</n-form-item>
<div class="title">背景颜色 / Background Color</div> <n-form-item label="背景颜色 / Background Color">
<n-color-picker <n-color-picker
v-model:value="bgColor" v-model:value="bgColor"
size="medium" size="medium"
@@ -42,14 +48,13 @@
'#FFFFFF', '#FFFFFF',
]" ]"
/> />
</n-form-item>
<div <n-form-item
v-show="fullscreen.isSupported" v-show="fullscreen.isSupported"
class="title" label="切换全屏 / Toggle Fullscreen"
>切换全屏 / Toggle Fullscreen</div> >
<n-switch <n-switch
v-show="fullscreen.isSupported"
size="medium" size="medium"
:round="false" :round="false"
:value="fullscreen.isFullscreen.value" :value="fullscreen.isFullscreen.value"
@@ -58,9 +63,9 @@
<template #checked>开启</template> <template #checked>开启</template>
<template #unchecked>关闭</template> <template #unchecked>关闭</template>
</n-switch> </n-switch>
</n-form-item>
<div class="title">隐藏界面 / Hide UI</div> <n-form-item label="隐藏界面 / Hide UI">
<n-switch <n-switch
v-model:value="isFaded" v-model:value="isFaded"
size="medium" size="medium"
@@ -70,14 +75,16 @@
<template #checked>隐藏</template> <template #checked>隐藏</template>
<template #unchecked>显示</template> <template #unchecked>显示</template>
</n-switch> </n-switch>
</n-form-item>
</div> </n-form>
</n-card>
</div> </div>
</template> </template>
<script setup> <script setup>
import { import {
NColorPicker, NSwitch, NCard, NColorPicker, NForm, NFormItem, NSwitch,
} from 'naive-ui'; } from 'naive-ui';
import { import {
@@ -178,7 +185,6 @@ onBeforeUnmount(() => {
<style lang="less" scoped> <style lang="less" scoped>
.tool-detail-page { .tool-detail-page {
display: flex;
background-color: inherit; background-color: inherit;
transition: all 0.25s; transition: all 0.25s;
user-select: none; user-select: none;
@@ -190,26 +196,19 @@ onBeforeUnmount(() => {
&.is-on { &.is-on {
background-color: var(--bg-color); background-color: var(--bg-color);
&.is-dark-color { &.is-dark-color * {
color: #FFF; color: #FFF;
} }
}
> * { :deep(.n-card) {
transition: opacity 0.25s; border-color: transparent;
}
} }
} }
.controls { :deep(.n-card) {
margin: auto; background-color: transparent;
padding-bottom: 48px; transition: all 0.25s;
text-align: center;
}
.title {
margin-top: 48px;
margin-bottom: 16px;
font-size: 24px;
} }
:deep(.n-color-picker) { :deep(.n-color-picker) {
@@ -1,8 +1,8 @@
<template> <template>
<div class="tool-detail-page"> <div class="tool-detail-page">
<!-- 设置 --> <!-- 配置参数 -->
<n-card size="small" title="设置"> <n-card size="small" title="配置参数">
<n-form <n-form
class="form-no-feedback config-inputs" class="form-no-feedback config-inputs"
label-align="left" label-align="left"
+328 -1
View File
@@ -1,9 +1,336 @@
<template> <template>
<div class="tool-detail-page"></div> <div class="tool-detail-page">
<!-- 操作 -->
<n-card class="actions" size="small" title="操作">
<n-flex>
<n-button
type="primary"
@click="handleRunCode"
>执行代码</n-button>
<n-button
type="error"
@click="handleClearContent"
>清空内容</n-button>
<n-button
type="default"
@click="handleClearOutput"
>清空输出</n-button>
</n-flex>
</n-card>
<!-- 代码和结果 -->
<div class="code-and-result">
<!-- 编辑器 -->
<n-card size="small" title="编辑器">
<div ref="editorContainer" class="editor-container"></div>
</n-card>
<!-- 执行结果 -->
<n-card size="small" title="执行结果">
<n-scrollbar class="output-container">
<pre class="output-content">{{ outputContent }}</pre>
</n-scrollbar>
</n-card>
</div>
</div>
</template> </template>
<script setup> <script setup>
import {
NButton, NCard, NFlex, NScrollbar,
} from 'naive-ui';
import {
ref, shallowRef,
onBeforeUnmount, onMounted,
} from 'vue';
import {
initMonacoEnvironment,
} from '@/assets/js/monaco-editor';
import {
$dialog, $message,
} from '@/assets/js/naive-ui';
import * as monaco from 'monaco-editor';
/** 模块名称 */
const PREFIX = '[RunJavaScript]';
/**
* @desc 编辑器实例(注:内部不能为响应式,防止出现部分操作会导致界面卡死等异常)
* @type {VueRef<monaco.editor.IStandaloneCodeEditor>}
*/
const editorInstance = shallowRef(null);
/** @type {VueRef<HTMLElement>} */
const editorContainer = ref(null);
/** 防抖定时器 */
const resizeTimer = ref(null);
/** 输出内容 */
const outputContent = ref('');
/** 处理清空内容操作 */
function handleClearContent() {
$dialog.create({
content: '确定要清空编辑器内容吗?',
negativeText: '取消',
positiveText: '确定',
title: '确认',
type: 'default',
onPositiveClick: () => {
updateEditorContent('');
},
});
}
/** 处理清空输出操作 */
function handleClearOutput() {
outputContent.value = '';
}
/** 处理执行代码操作 */
function handleRunCode() {
let code = editorInstance.value?.getValue() || '';
if (!code.trim()) {
$message.warning('请先输入要执行的 JavaScript 代码');
return;
}
outputContent.value += '> 开始执行...\n';
// 创建控制台重定向
let originalConsole = {
log: console.log,
error: console.error,
warn: console.warn,
info: console.info,
};
// 重定向控制台输出到结果区域
console.log = (...args) => {
originalConsole.log(...args);
outputContent.value += '[LOG] ' + formatConsoleArgs(args) + '\n';
};
console.error = (...args) => {
originalConsole.error(...args);
outputContent.value += '[ERROR] ' + formatConsoleArgs(args) + '\n';
};
console.warn = (...args) => {
originalConsole.warn(...args);
outputContent.value += '[WARN] ' + formatConsoleArgs(args) + '\n';
};
console.info = (...args) => {
originalConsole.info(...args);
outputContent.value += '[INFO] ' + formatConsoleArgs(args) + '\n';
};
try {
// 执行代码
let result = eval(code);
// 如果有返回值且不是 undefined,输出结果
if (result !== undefined) {
outputContent.value += '返回值: ' + JSON.stringify(result, null, 2) + '\n';
}
outputContent.value += '> 执行完成' + '\n';
} catch (error) {
outputContent.value += '错误: ' + error.message + '\n';
} finally {
// 恢复原控制台
Object.assign(console, originalConsole);
}
}
/** 格式化控制台参数 */
function formatConsoleArgs(args) {
return args.map(arg => {
if (typeof arg === 'object') {
return JSON.stringify(arg, null, 2);
} else {
return String(arg);
}
}).join(' ');
}
/** 处理窗口大小变化 */
function handleWindowResize() {
clearTimeout(resizeTimer.value);
resizeTimer.value = setTimeout(() => {
if (editorInstance.value) {
editorInstance.value.layout();
}
}, 200);
}
/** 初始化编辑器 */
function initEditor() {
console.log(PREFIX, 'initEditor');
let container = editorContainer.value;
let editor = null;
let valueStr = `// 在这里输入 JavaScript 代码\nconsole.log('Hello, World!');`;
if (!container) {
console.error(PREFIX, '初始化失败:元素不存在');
return;
}
editor = monaco.editor.create(container, {
autoDetectHighContrast: false,
automaticLayout: false,
contextmenu: true,
find: {
cursorMoveOnType: false,
},
fontFamily: 'monospace',
fontSize: 14,
language: 'javascript',
minimap: {
enabled: true,
renderCharacters: false,
},
mouseWheelScrollSensitivity: 2,
stickyScroll: {
enabled: false,
},
tabSize: 2,
theme: 'vs',
value: valueStr,
});
editorInstance.value = editor;
}
/** 销毁编辑器 */
function resetEditor() {
console.log(PREFIX, 'resetEditor');
try {
if (editorInstance.value) {
editorInstance.value.getModel().dispose()
editorInstance.value.dispose();
editorInstance.value = null;
}
return true;
} catch (error) {
console.error(PREFIX, '销毁失败:');
console.error(error);
return false;
}
}
/** 更新编辑器内容 */
function updateEditorContent(text = '') {
if (editorInstance.value) {
editorInstance.value.setValue(text);
}
}
onMounted(() => {
initMonacoEnvironment();
initEditor();
window.addEventListener('resize', handleWindowResize);
});
onBeforeUnmount(() => {
resetEditor();
window.removeEventListener('resize', handleWindowResize);
});
</script> </script>
<style lang="less" scoped> <style lang="less" scoped>
.tool-detail-page {
display: flex;
flex-direction: column;
container-type: inline-size;
}
.actions {
height: auto;
}
.code-and-result {
display: flex;
flex-direction: row;
flex-grow: 1;
gap: 20px;
margin-top: 20px;
height: 0;
.n-card {
width: 0;
height: 100%;
}
:deep(.n-card__content) {
height: 0;
}
.n-card:first-child {
flex-grow: 1.5;
}
.n-card:last-child {
flex-grow: 1;
}
}
@container (max-width: 640px) {
.code-and-result {
display: block;
.n-card {
width: 100%;
height: 100%;
}
.n-card:last-child {
margin-top: 20px;
}
}
}
.editor-container {
width: 100%;
height: 100%;
outline: 1px solid var(--n-border-color);
}
.output-container {
width: 100%;
height: 100%;
}
.output-content {
margin: 0;
padding: 8px;
background-color: #F5F5F5;
border-radius: 4px;
line-height: 1.5;
font-family: monospace;
font-size: 14px;
color: #252525;
white-space: pre-wrap;
}
</style> </style>
+416
View File
@@ -0,0 +1,416 @@
<template>
<div class="tool-detail-page">
<!-- 计时器 -->
<n-card size="small" title="计时器">
<div class="timer-display">
<span class="time-main">{{ formatTimeMain(data.timeDisplay) }}</span>
<span class="time-milliseconds">{{ formatTimeMilliseconds(data.timeDisplay) }}</span>
</div>
</n-card>
<!-- 操作 -->
<n-card size="small" title="操作">
<n-flex justify="center">
<n-button
type="success"
:disabled="data.isRunning"
@click="startTimer"
>开始</n-button>
<n-button
type="warning"
:disabled="!data.isRunning"
@click="pauseTimer"
>暂停</n-button>
<n-button
type="error"
@click="resetTimer"
>重置</n-button>
<n-button
type="primary"
@click="recordTime"
>记录</n-button>
</n-flex>
</n-card>
<!-- 配置参数 -->
<n-card size="small" title="配置参数">
<n-form
class="form-no-feedback"
label-align="left"
label-placement="top"
label-width="auto"
>
<!-- 计时模式 -->
<n-form-item label="计时模式">
<n-radio-group v-model:value="data.timerMode">
<n-radio-button label="正计时" :value="'countUp'" />
<n-radio-button label="倒计时" :value="'countDown'" />
</n-radio-group>
</n-form-item>
<!-- 倒计时时间设置 -->
<n-form-item label="倒计时设置" v-if="data.timerMode === 'countDown'">
<n-input-group>
<n-input-number
v-model:value="data.countDownTime.hours"
:min="0"
:max="99"
:precision="0"
:step="1"
></n-input-number>
<span class="time-separator">时</span>
<n-input-number
v-model:value="data.countDownTime.minutes"
:min="0"
:max="59"
:precision="0"
:step="1"
></n-input-number>
<span class="time-separator">分</span>
<n-input-number
v-model:value="data.countDownTime.seconds"
:min="0"
:max="59"
:precision="0"
:step="1"
></n-input-number>
<span class="time-separator">秒</span>
</n-input-group>
</n-form-item>
</n-form>
</n-card>
<!-- 时间记录 -->
<n-card size="small" title="时间记录">
<div class="records-content">
<div
v-if="data.records.length === 0"
class="no-records"
>暂无记录</div>
<div
v-for="(record, index) in data.records"
:key="record.id"
class="record-item"
>
<span class="record-index">{{ index + 1 }}</span>
<span class="record-time">{{ formatTime(record.time) }}</span>
<span class="record-timestamp">{{ formatDateTime(record.timestamp) }}</span>
</div>
</div>
<n-button
type="error"
size="small"
class="clear-records-btn"
@click="clearRecords"
>清空记录</n-button>
</n-card>
</div>
</template>
<script setup>
import {
NButton, NCard, NFlex, NForm, NFormItem, NInputGroup, NInputNumber, NRadioButton, NRadioGroup,
} from 'naive-ui';
import {
reactive, onBeforeUnmount, watch,
} from 'vue';
import {
getCommonDateTime,
} from '@frost-utils/javascript/common/index';
import {
$dialog, $notification,
} from '@/assets/js/naive-ui';
/** 数据 */
const data = reactive({
/** 计时器模式:countUp(正计时), countDown(倒计时) */
timerMode: 'countUp',
/** 是否正在运行 */
isRunning: false,
/** 当前显示时间(毫秒) */
timeDisplay: 0,
/** 倒计时时间设置 */
countDownTime: {
hours: 0,
minutes: 5,
seconds: 0
},
/** 计时器ID */
timerID: null,
/** 开始时间戳 */
startTime: 0,
/** 已运行时间 */
elapsedTime: 0,
/** 时间记录 */
records: [],
/** 记录ID */
recordID: 0,
});
/** 格式化时间显示(主时间部分:HH:MM:SS) */
function formatTimeMain(milliseconds) {
let totalSeconds = Math.floor(milliseconds / 1000);
let hours = Math.floor(totalSeconds / 3600);
let minutes = Math.floor((totalSeconds % 3600) / 60);
let seconds = totalSeconds % 60;
return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}
/** 格式化时间显示(毫秒部分:.SSS) */
function formatTimeMilliseconds(milliseconds) {
let ms = milliseconds % 1000;
return `.${ms.toString().padStart(3, '0')}`;
}
/** 格式化完整时间显示(用于记录和提示) */
function formatTime(milliseconds) {
return `${formatTimeMain(milliseconds)}${formatTimeMilliseconds(milliseconds)}`;
}
/** 格式化日期时间 */
function formatDateTime(timestamp) {
return getCommonDateTime(timestamp);
}
/** 开始计时器 */
function startTimer() {
if (data.timerMode === 'countUp') {
// 正计时模式
data.startTime = Date.now() - data.elapsedTime;
data.timerID = setInterval(() => {
data.elapsedTime = Date.now() - data.startTime;
data.timeDisplay = data.elapsedTime;
}, 10); // 每10毫秒更新一次,提高毫秒显示精度
} else {
// 倒计时模式
if (data.timeDisplay === 0) {
// 如果是首次开始或重置后开始,设置倒计时时间
const { hours, minutes, seconds } = data.countDownTime;
data.timeDisplay = (hours * 3600 + minutes * 60 + seconds) * 1000;
}
data.startTime = Date.now() + data.timeDisplay;
data.timerID = setInterval(() => {
data.timeDisplay = Math.max(0, data.startTime - Date.now());
data.elapsedTime = (data.startTime - data.timeDisplay) - data.startTime + data.timeDisplay;
// 倒计时结束
if (data.timeDisplay === 0) {
pauseTimer();
notify({
message: '倒计时结束!',
type: 'success',
title: '提示'
});
}
}, 10); // 每10毫秒更新一次,提高毫秒显示精度
}
data.isRunning = true;
}
/** 暂停计时器 */
function pauseTimer() {
if (data.timerID) {
clearInterval(data.timerID);
data.timerID = null;
data.isRunning = false;
}
}
/** 重置计时器 */
function resetTimer() {
pauseTimer();
data.elapsedTime = 0;
data.timeDisplay = 0;
}
/** 记录时间 */
function recordTime() {
data.recordID += 1;
data.records.push({
id: data.recordID,
time: data.timeDisplay,
timestamp: Date.now()
});
notify({
message: `已记录时间: ${formatTime(data.timeDisplay)}`,
type: 'info',
title: '记录成功'
});
}
/** 清空记录 */
function clearRecords() {
$dialog.create({
content: '确定要清空所有时间记录吗?',
negativeText: '取消',
positiveText: '确定',
title: '确认',
type: 'default',
onPositiveClick: () => {
data.records = [];
data.recordID = 0;
},
});
}
/**
* @description 提示信息
* @param {object} options
* @param {number} options.duration
* @param {string} options.message
* @param {string} options.title
* @param {string} options.type
*/
function notify(options) {
let {
duration = 3000,
message = '',
title = '提示',
type = 'info',
} = options;
return $notification.create({
content: message,
duration: duration,
title: title,
type: type,
});
}
/** 监听计时模式切换 */
watch(
() => data.timerMode,
() => {
// 切换模式时重置计时器
resetTimer();
}
);
/** 监听倒计时时间设置变化 */
watch(
() => [data.countDownTime.hours, data.countDownTime.minutes, data.countDownTime.seconds],
() => {
// 只有在倒计时模式且计时器未运行时,才更新显示时间
if (data.timerMode === 'countDown' && !data.isRunning && data.timeDisplay === 0) {
const { hours, minutes, seconds } = data.countDownTime;
data.timeDisplay = (hours * 3600 + minutes * 60 + seconds) * 1000;
}
},
{ deep: true }
);
onBeforeUnmount(() => {
if (data.timerID) {
clearInterval(data.timerID);
}
});
</script>
<style lang="less" scoped>
.timer-display {
font-size: 48px;
font-weight: bold;
text-align: center;
padding: 20px 0;
color: #2196F3;
font-family: 'Courier New', monospace;
display: flex;
align-items: baseline;
justify-content: center;
gap: 4px;
.time-main {
font-size: 48px;
}
.time-milliseconds {
font-size: 32px;
color: #666;
margin-left: 2px;
}
}
.time-separator {
display: flex;
align-items: center;
justify-content: center;
padding: 0 8px;
font-size: 16px;
color: #666;
}
.records-content {
padding: 8px 16px;
border: 1px solid #F0F0F0;
border-radius: 4px;
background-color: #FFF;
line-height: 1.6;
max-height: 200px;
overflow-y: auto;
margin-bottom: 12px;
.record-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 4px 0;
border-bottom: 1px dashed #F0F0F0;
&:last-child {
border-bottom: none;
}
}
.record-index {
width: 30px;
color: #999;
}
.record-time {
flex: 1;
text-align: center;
font-weight: bold;
color: #2196F3;
font-family: 'Courier New', monospace;
}
.record-timestamp {
color: #999;
font-size: 12px;
}
.no-records {
text-align: center;
color: #999;
padding: 20px 0;
}
}
.clear-records-btn {
display: block;
margin-left: auto;
}
</style>
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,797 @@
// 待办事项数据模型
//
// 数据文件(todo-data.json)结构(版本 2):
// {
// "type": "frost-navigation/todo-list",
// "schemaVersion": 2,
// "updatedAt": "2026-11-17T08:00:00.000Z",
// "categories": [
// {
// "id": "…",
// "name": "默认",
// "color": "#0894FA",
// "createdAt": "…"
// }
// ],
// "tasks": [
// {
// "id": "…",
// "title": "…",
// "note": "…",
// "done": false,
// "priority": "normal",
// "tags": ["…"],
// "dueDate": "2026-11-18",
// "categoryId": "…",
// "createdAt": "…",
// "updatedAt": "…",
// "completedAt": null
// }
// ]
// }
//
// 版本升级约定:
// 1. 数据结构发生变化时,将 CURRENT_DATA_VERSION 加 1;
// 2. 在 MIGRATIONS 中新增“从旧版本升级到下一版本”的函数(键为旧版本号);
// 3. 迁移函数只负责结构转换,不依赖组件和浏览器 API,便于单独测试;
// 4. 打开旧版本数据时,由调用方在写入升级后的数据前原样备份原文件(见 todo-storage.js)。
//
// 版本 0 为历史格式:没有 schemaVersion 字段,内容可能是任务数组或 { tasks: [] },
// 且任务字段命名不统一(text / content、completed / isDone、deadline 等)。
// 版本 1 为引入待办分类前的格式:只有 tasks,没有 categories,任务也没有 categoryId。
// 版本 2 新增 categories(待办分类),任务通过 categoryId 关联分类。
import { v4 as uuidV4 } from 'uuid';
/** 数据类型标识 */
export const DATA_TYPE = 'frost-navigation/todo-list';
/** 数据文件名 */
export const DATA_FILE_NAME = 'todo-data.json';
/** 当前数据版本 */
export const CURRENT_DATA_VERSION = 2;
/** 默认分类 ID(旧版本数据升级时使用的分类) */
export const DEFAULT_CATEGORY_ID = 'default';
/** 默认分类名称 */
export const DEFAULT_CATEGORY_NAME = '默认';
/** 分类可选颜色 */
export const CATEGORY_COLORS = [
'#0894FA',
'#00A870',
'#ED7B2F',
'#E34D59',
'#14B8A6',
'#F59E0B',
'#2F54EB',
'#8C8C8C',
];
/** 分类名称最大长度 */
const MAX_CATEGORY_NAME_LENGTH = 20;
/** 优先级 */
export const PRIORITY_VALUES = ['high', 'normal', 'low'];
/** 优先级选项(用于界面下拉框) */
export const PRIORITY_OPTIONS = [
{ label: '高', value: 'high' },
{ label: '普通', value: 'normal' },
{ label: '低', value: 'low' },
];
/** 优先级名称 */
const PRIORITY_LABELS = {
high: '高',
normal: '普通',
low: '低',
};
/** 旧数据中可能出现的优先级写法 */
const PRIORITY_ALIASES = {
'高': 'high',
'中': 'normal',
'普通': 'normal',
'低': 'low',
};
/** 单条待办最多保存的标签数量 */
const MAX_TAGS = 10;
/** 标签最大长度 */
const MAX_TAG_LENGTH = 24;
/** 标题最大长度 */
const MAX_TITLE_LENGTH = 200;
/** 备注最大长度 */
const MAX_NOTE_LENGTH = 2000;
/** 是否为普通对象 */
function isPlainObject(value) {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
/** 从对象中按优先级取出第一个有值的字段 */
function pickDefined(source, keys) {
if (!isPlainObject(source)) return undefined;
for (let i = 0; i < keys.length; i += 1) {
const value = source[keys[i]];
if (value !== undefined && value !== null) {
return value;
}
}
return undefined;
}
/** 将时间值转换为 ISO 字符串 */
function toIsoTime(value) {
if (value === undefined || value === null || value === '') {
return null;
}
if (typeof value === 'number' && Number.isFinite(value)) {
// 兼容以秒为单位的时间戳(10 位数)
const timestamp = value > 1e11 ? value : value * 1000;
const date = new Date(timestamp);
return Number.isNaN(date.getTime()) ? null : date.toISOString();
}
if (typeof value === 'string') {
const text = value.trim();
if (!text) {
return null;
}
if (/^\d+$/.test(text)) {
return toIsoTime(Number(text));
}
const date = new Date(text);
return Number.isNaN(date.getTime()) ? null : date.toISOString();
}
return null;
}
/** 将日期对象格式化为 YYYY-MM-DD */
function formatDate(date) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
/** 将日期值规范化为 YYYY-MM-DD(无效值返回空字符串) */
function normalizeDateString(value) {
if (value === undefined || value === null || value === '') {
return '';
}
if (value instanceof Date) {
return Number.isNaN(value.getTime()) ? '' : formatDate(value);
}
if (typeof value === 'number' && Number.isFinite(value)) {
const timestamp = value > 1e11 ? value : value * 1000;
const date = new Date(timestamp);
return Number.isNaN(date.getTime()) ? '' : formatDate(date);
}
const text = String(value).trim();
if (!text) {
return '';
}
const match = text.match(/^(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})$/);
if (!match) {
return '';
}
const year = Number(match[1]);
const month = Number(match[2]);
const day = Number(match[3]);
if (month < 1 || month > 12 || day < 1 || day > 31) {
return '';
}
const date = new Date(year, month - 1, day);
// 排除 2 月 30 日之类的非法日期
if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) {
return '';
}
return `${match[1]}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
}
/** 规范化标题 */
function normalizeTitle(value) {
if (value === undefined || value === null) {
return '';
}
return String(value).replace(/\s+/g, ' ').trim().slice(0, MAX_TITLE_LENGTH);
}
/** 规范化备注 */
function normalizeNote(value) {
if (value === undefined || value === null) {
return '';
}
return String(value).replace(/\r\n/g, '\n').trim().slice(0, MAX_NOTE_LENGTH);
}
/** 规范化优先级 */
function normalizePriority(value) {
if (typeof value === 'number' && Number.isFinite(value)) {
if (value >= 3) return 'high';
if (value <= 1) return 'low';
return 'normal';
}
if (typeof value === 'string') {
const text = value.trim().toLowerCase();
if (PRIORITY_VALUES.includes(text)) {
return text;
}
if (PRIORITY_ALIASES[text]) {
return PRIORITY_ALIASES[text];
}
}
return 'normal';
}
/** 规范化标签 */
function normalizeTags(value) {
let list = [];
if (Array.isArray(value)) {
list = value;
} else if (typeof value === 'string') {
list = value.split(/[,,、;;]+/);
}
const result = [];
for (let i = 0; i < list.length; i += 1) {
const item = list[i];
if (typeof item !== 'string' && typeof item !== 'number') {
continue;
}
const tag = String(item).trim().slice(0, MAX_TAG_LENGTH);
if (!tag || result.includes(tag)) {
continue;
}
result.push(tag);
if (result.length >= MAX_TAGS) {
break;
}
}
return result;
}
/** 规范化分类名称 */
function normalizeCategoryName(value) {
if (value === undefined || value === null) {
return '';
}
return String(value).replace(/\s+/g, ' ').trim().slice(0, MAX_CATEGORY_NAME_LENGTH);
}
/** 规范化分类颜色(仅支持十六进制颜色,无法识别时使用第一个预设颜色) */
function normalizeCategoryColor(value) {
if (typeof value !== 'string') {
return CATEGORY_COLORS[0];
}
const text = value.trim();
if (/^#[0-9A-Fa-f]{6}$/.test(text)) {
return text.toUpperCase();
}
if (/^#[0-9A-Fa-f]{3}$/.test(text)) {
const hex = text.slice(1).split('').map((char) => char + char).join('');
return `#${hex.toUpperCase()}`;
}
return CATEGORY_COLORS[0];
}
/**
* @description 创建一条新的分类数据
* @param {object} input 初始字段
* @returns {{ id: string, name: string, color: string, createdAt: string }}
*/
export function createCategory(input = {}) {
const name = normalizeCategoryName(input.name);
return {
id: typeof input.id === 'string' && input.id.trim() ? input.id.trim().slice(0, 64) : uuidV4(),
name: name || DEFAULT_CATEGORY_NAME,
color: normalizeCategoryColor(input.color),
createdAt: toIsoTime(input.createdAt) ?? new Date().toISOString(),
};
}
/**
* @description 规范化单条分类数据
* @param {any} raw 原始数据
* @param {number} index 在列表中的位置(用于生成兜底名称)
* @returns {object | null} 规范化后的分类
*/
function normalizeCategory(raw, index = 0) {
if (typeof raw === 'string') {
const name = normalizeCategoryName(raw);
return name ? createCategory({ name }) : null;
}
if (!isPlainObject(raw)) {
return null;
}
const name = normalizeCategoryName(pickDefined(raw, ['name', 'title', 'label']))
|| `分类 ${index + 1}`;
return createCategory({
id: pickDefined(raw, ['id', 'uuid', 'key']),
name,
color: pickDefined(raw, ['color', 'colour']),
createdAt: pickDefined(raw, ['createdAt', 'createTime', 'createdTime']),
});
}
/** 规范化分类列表,并保证至少存在一个分类 */
function normalizeCategories(list) {
if (!Array.isArray(list)) {
return [createCategory({ id: DEFAULT_CATEGORY_ID, name: DEFAULT_CATEGORY_NAME })];
}
const result = [];
const usedIds = new Set();
for (let i = 0; i < list.length; i += 1) {
const category = normalizeCategory(list[i], i);
if (!category) {
continue;
}
if (usedIds.has(category.id)) {
category.id = uuidV4();
}
usedIds.add(category.id);
result.push(category);
}
if (result.length === 0) {
result.push(createCategory({ id: DEFAULT_CATEGORY_ID, name: DEFAULT_CATEGORY_NAME }));
}
return result;
}
/** 获取优先级名称 */
export function getPriorityLabel(priority) {
return PRIORITY_LABELS[priority] ?? '普通';
}
/**
* @description 规范化单条待办数据(兼容旧字段命名)
* @param {any} raw 原始数据
* @param {string[]} validCategoryIds 有效分类 ID 列表
* @returns {object | null} 规范化后的待办,无法识别时返回 null
*/
export function normalizeTask(raw, validCategoryIds = []) {
if (typeof raw === 'string') {
raw = { title: raw };
}
if (!isPlainObject(raw)) {
return null;
}
const title = normalizeTitle(pickDefined(raw, ['title', 'text', 'content', 'name']));
if (!title) {
return null;
}
const doneValue = pickDefined(raw, ['done', 'completed', 'isDone', 'checked', 'finished']);
const done = doneValue === true
|| doneValue === 'true'
|| doneValue === 1
|| raw.status === 'done'
|| raw.status === 'completed';
const now = new Date().toISOString();
const createdAt = toIsoTime(pickDefined(raw, ['createdAt', 'createTime', 'createdTime', 'created'])) ?? now;
const updatedAt = toIsoTime(pickDefined(raw, ['updatedAt', 'updateTime', 'updatedTime', 'modifiedAt'])) ?? createdAt;
const completedAt = done
? (toIsoTime(pickDefined(raw, ['completedAt', 'doneAt', 'finishedAt'])) ?? updatedAt)
: null;
const providedId = pickDefined(raw, ['id', 'uuid', 'key']);
const id = typeof providedId === 'string' && providedId.trim()
? providedId.trim().slice(0, 64)
: uuidV4();
const providedCategoryId = pickDefined(raw, ['categoryId', 'category', 'listId']);
const categoryId = typeof providedCategoryId === 'string' && validCategoryIds.includes(providedCategoryId)
? providedCategoryId
: (validCategoryIds[0] ?? '');
return {
id,
title,
note: normalizeNote(pickDefined(raw, ['note', 'notes', 'desc', 'description', 'remark'])),
done,
priority: normalizePriority(pickDefined(raw, ['priority', 'level'])),
tags: normalizeTags(pickDefined(raw, ['tags', 'labels', 'tag'])),
dueDate: normalizeDateString(pickDefined(raw, ['dueDate', 'deadline', 'due', 'dueTime', 'endDate'])),
categoryId,
createdAt,
updatedAt,
completedAt,
};
}
/** 规范化待办列表,并处理重复 ID */
function normalizeTasks(list, validCategoryIds = []) {
if (!Array.isArray(list)) {
return [];
}
const result = [];
const usedIds = new Set();
for (let i = 0; i < list.length; i += 1) {
const task = normalizeTask(list[i], validCategoryIds);
if (!task) {
continue;
}
if (usedIds.has(task.id)) {
task.id = uuidV4();
}
usedIds.add(task.id);
result.push(task);
}
return result;
}
/**
* @description 创建一条新的待办数据
* @param {object} input 初始字段
* @param {string[]} validCategoryIds 有效分类 ID 列表
*/
export function createTask(input = {}, validCategoryIds = []) {
const now = new Date().toISOString();
const categoryId = typeof input.categoryId === 'string' && validCategoryIds.includes(input.categoryId)
? input.categoryId
: (validCategoryIds[0] ?? '');
return {
id: typeof input.id === 'string' && input.id.trim() ? input.id.trim() : uuidV4(),
title: normalizeTitle(input.title),
note: normalizeNote(input.note),
done: false,
priority: normalizePriority(input.priority),
tags: normalizeTags(input.tags),
dueDate: normalizeDateString(input.dueDate),
categoryId,
createdAt: now,
updatedAt: now,
completedAt: null,
};
}
/**
* @description 根据当前待办列表构建待写入文件的数据对象
* @param {object[]} tasks 待办列表
* @param {object[]} categories 分类列表
*/
export function buildTodoData(tasks = [], categories = []) {
const normalizedCategories = normalizeCategories(categories);
const categoryIds = normalizedCategories.map((category) => category.id);
return {
type: DATA_TYPE,
schemaVersion: CURRENT_DATA_VERSION,
updatedAt: new Date().toISOString(),
categories: normalizedCategories,
tasks: normalizeTasks(tasks, categoryIds),
};
}
/**
* @description 序列化为数据文件内容(2 空格缩进,末尾保留换行)
* @param {object} data 数据对象
*/
export function stringifyTodoData(data) {
return `${JSON.stringify(data, null, 2)}\n`;
}
/**
* 版本 0 升级到版本 1
* 旧格式可能是任务数组,也可能是包含 tasks 字段的对象,任务字段由 normalizeTask 统一处理。
*/
function migrateVersion0ToVersion1(source) {
if (Array.isArray(source)) {
return { tasks: source };
}
if (isPlainObject(source) && Array.isArray(source.tasks)) {
return { tasks: source.tasks };
}
return { tasks: [] };
}
/** 版本迁移函数表:键为起始版本,值为升级到下一版本的函数 */
const MIGRATIONS = {
0: migrateVersion0ToVersion1,
1: migrateVersion1ToVersion2,
};
/**
* 版本 1 升级到版本 2:新增待办分类
* 旧数据中没有分类,统一归入“默认”分类,避免升级后待办无所属分类。
*/
function migrateVersion1ToVersion2(source) {
const sourceObject = isPlainObject(source) ? source : {};
const tasks = Array.isArray(sourceObject.tasks) ? sourceObject.tasks : [];
const categories = Array.isArray(sourceObject.categories) ? sourceObject.categories : [];
// 数据中已带有分类时直接保留(兼容手工调整过的数据)
if (categories.length > 0) {
return { ...sourceObject, tasks, categories };
}
return {
tasks: tasks.map((task) => (
isPlainObject(task)
? { ...task, categoryId: task.categoryId ?? DEFAULT_CATEGORY_ID }
: task
)),
categories: [
{
id: DEFAULT_CATEGORY_ID,
name: DEFAULT_CATEGORY_NAME,
color: CATEGORY_COLORS[0],
createdAt: new Date().toISOString(),
},
],
};
}
/**
* 判断解析后的 JSON 是否可识别为待办事项数据。
* 用于避免把文件夹中同名但不相关的 JSON 文件当作旧版本数据升级后覆盖。
*/
function isRecognizableTodoData(raw) {
if (Array.isArray(raw)) {
return true;
}
if (!isPlainObject(raw)) {
return false;
}
// 声明了类型时必须是本工具的数据
if (raw.type !== undefined) {
return raw.type === DATA_TYPE;
}
// 没有类型时,至少应具备待办数据结构(兼容旧格式)
if (Array.isArray(raw.tasks)) {
return true;
}
return raw.schemaVersion !== undefined || raw.dataVersion !== undefined;
}
/** 读取数据中的版本号(无法识别时按版本 0 处理) */
function getSourceVersion(raw) {
if (Array.isArray(raw)) {
return 0;
}
if (!isPlainObject(raw)) {
return null;
}
const value = pickDefined(raw, ['schemaVersion', 'dataVersion', 'version']);
if (value === undefined) {
return 0;
}
if (typeof value === 'string' && /^\d+$/.test(value.trim())) {
return Number(value.trim());
}
if (typeof value === 'number' && Number.isInteger(value) && value >= 0) {
return value;
}
// 无法识别版本时按最旧的格式尝试升级
return 0;
}
/**
* @description 将任意(旧)版本的数据升级到当前版本
* @param {any} raw 已解析的 JSON 数据
* @returns {{
* ok: boolean,
* error?: string,
* data?: object,
* fromVersion?: number,
* toVersion?: number,
* migrated?: boolean,
* isFutureVersion?: boolean,
* }} 升级结果
*/
export function migrateTodoData(raw) {
if (!isRecognizableTodoData(raw)) {
return { ok: false, error: '无法识别的数据文件(不是待办事项数据)' };
}
const fromVersion = getSourceVersion(raw);
if (fromVersion === null) {
return { ok: false, error: '无法识别的数据格式,应为 JSON 对象或任务数组' };
}
const now = new Date().toISOString();
// 数据版本高于当前版本:仅以只读方式展示,避免写入时丢失新版本中的字段
if (fromVersion > CURRENT_DATA_VERSION) {
const source = Array.isArray(raw) ? { tasks: raw } : raw;
const categories = normalizeCategories(source?.categories);
const categoryIds = categories.map((category) => category.id);
return {
ok: true,
data: {
type: typeof source?.type === 'string' ? source.type : DATA_TYPE,
schemaVersion: fromVersion,
updatedAt: toIsoTime(source?.updatedAt) ?? now,
categories,
tasks: normalizeTasks(source?.tasks, categoryIds),
},
fromVersion,
toVersion: fromVersion,
migrated: false,
isFutureVersion: true,
};
}
let payload = raw;
for (let version = fromVersion; version < CURRENT_DATA_VERSION; version += 1) {
const migrate = MIGRATIONS[version];
if (typeof migrate !== 'function') {
return { ok: false, error: `缺少数据版本 ${version} 升级到 ${version + 1} 的迁移逻辑` };
}
payload = migrate(payload);
}
const source = Array.isArray(payload)
? { tasks: payload }
: (isPlainObject(payload) ? payload : {});
if (!Array.isArray(source.tasks)) {
return { ok: false, error: '数据文件缺少有效的任务列表(tasks 数组)' };
}
if (source.categories !== undefined && !Array.isArray(source.categories)) {
return { ok: false, error: '数据文件中的分类列表(categories)格式无效' };
}
const categories = normalizeCategories(source.categories);
const categoryIds = categories.map((category) => category.id);
const data = {
type: DATA_TYPE,
schemaVersion: CURRENT_DATA_VERSION,
updatedAt: toIsoTime(source.updatedAt) ?? now,
categories,
tasks: normalizeTasks(source.tasks, categoryIds),
};
return {
ok: true,
data,
fromVersion,
toVersion: CURRENT_DATA_VERSION,
migrated: fromVersion !== CURRENT_DATA_VERSION,
isFutureVersion: false,
};
}
/**
* @description 解析数据文件内容并升级到当前版本
* @param {string} text 文件内容
*/
export function parseTodoDataText(text = '') {
const content = String(text ?? '').replace(/^\uFEFF/, '').trim();
if (!content) {
return { ok: false, error: '数据内容为空' };
}
let parsed = null;
try {
parsed = JSON.parse(content);
} catch (error) {
return { ok: false, error: `数据不是有效的 JSON(${error.message})` };
}
return migrateTodoData(parsed);
}
@@ -0,0 +1,315 @@
// 待办事项存储
//
// 优先使用 File System Access API 直接读写用户选择的本地文件夹中的 todo-data.json;
// 目录句柄保存在 IndexedDB 中,下次打开页面时可直接复用(浏览器可能要求重新授权)。
// 浏览器不支持该 API 时,退化为浏览器本地存储(localStorage)临时保存。
import { DATA_FILE_NAME } from './todo-data.js';
/** IndexedDB 数据库名称 */
const IDB_NAME = 'frost-navigation';
/** IndexedDB 数据库版本 */
const IDB_VERSION = 1;
/** 存放文件句柄的对象仓库 */
const IDB_STORE_NAME = 'file-handles';
/** 目录句柄的存储键 */
const IDB_DIRECTORY_KEY = 'todo-list/directory';
/** 浏览器本地存储的 key(兜底模式) */
export const LOCAL_DATA_KEY = 'frost-navigation/todo-list/data';
/** 是否支持选择本地文件夹 */
export function isFolderAccessSupported() {
return typeof window !== 'undefined' && typeof window.showDirectoryPicker === 'function';
}
/** 打开选择文件夹对话框(需由用户操作触发) */
export async function pickTodoDirectory() {
if (!isFolderAccessSupported()) {
throw new Error('当前浏览器不支持访问本地文件夹');
}
return window.showDirectoryPicker({
id: 'frost-navigation-todo-list',
mode: 'readwrite',
});
}
/** 打开 IndexedDB */
function openHandleDatabase() {
return new Promise((resolve, reject) => {
if (typeof indexedDB === 'undefined') {
reject(new Error('当前环境不支持 IndexedDB'));
return;
}
const request = indexedDB.open(IDB_NAME, IDB_VERSION);
request.onupgradeneeded = () => {
const database = request.result;
if (!database.objectStoreNames.contains(IDB_STORE_NAME)) {
database.createObjectStore(IDB_STORE_NAME);
}
};
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error ?? new Error('打开 IndexedDB 失败'));
});
}
/** 在句柄仓库中执行一次事务 */
async function runHandleTransaction(mode, executor) {
const database = await openHandleDatabase();
try {
return await new Promise((resolve, reject) => {
const transaction = database.transaction(IDB_STORE_NAME, mode);
const store = transaction.objectStore(IDB_STORE_NAME);
const request = executor(store);
transaction.oncomplete = () => resolve(request ? request.result : undefined);
transaction.onerror = () => reject(transaction.error ?? new Error('IndexedDB 事务失败'));
transaction.onabort = () => reject(transaction.error ?? new Error('IndexedDB 事务被中止'));
});
} finally {
database.close();
}
}
/** 读取上次使用的目录句柄 */
export async function getSavedDirectoryHandle() {
try {
return (await runHandleTransaction('readonly', (store) => store.get(IDB_DIRECTORY_KEY))) ?? null;
} catch (error) {
console.error('[TodoStorage] 读取目录句柄失败:', error);
return null;
}
}
/** 保存目录句柄,便于下次直接复用 */
export async function saveDirectoryHandle(handle) {
await runHandleTransaction('readwrite', (store) => store.put(handle, IDB_DIRECTORY_KEY));
}
/** 清除已保存的目录句柄 */
export async function clearSavedDirectoryHandle() {
try {
await runHandleTransaction('readwrite', (store) => store.delete(IDB_DIRECTORY_KEY));
} catch (error) {
console.error('[TodoStorage] 清除目录句柄失败:', error);
}
}
/** 查询目录的读写权限 */
export async function queryDirectoryPermission(handle) {
if (!handle || typeof handle.queryPermission !== 'function') {
return 'granted';
}
try {
return await handle.queryPermission({ mode: 'readwrite' });
} catch (error) {
console.error('[TodoStorage] 查询文件夹权限失败:', error);
return 'denied';
}
}
/** 请求目录的读写权限(需由用户操作触发) */
export async function requestDirectoryPermission(handle) {
if (!handle || typeof handle.requestPermission !== 'function') {
return 'granted';
}
try {
return await handle.requestPermission({ mode: 'readwrite' });
} catch (error) {
console.error('[TodoStorage] 请求文件夹权限失败:', error);
return 'denied';
}
}
/**
* @description 读取数据文件
* @param {FileSystemDirectoryHandle} dirHandle 目录句柄
* @returns {Promise<{ exists: boolean, text: string, lastModified: number }>}
*/
export async function readTodoDataFile(dirHandle) {
try {
const fileHandle = await dirHandle.getFileHandle(DATA_FILE_NAME);
const file = await fileHandle.getFile();
return {
exists: true,
text: await file.text(),
lastModified: file.lastModified,
};
} catch (error) {
// 文件不存在时返回空结果,由调用方决定是否创建
if (error?.name === 'NotFoundError') {
return { exists: false, text: '', lastModified: 0 };
}
throw error;
}
}
/**
* @description 写入数据文件
* @param {FileSystemDirectoryHandle} dirHandle 目录句柄
* @param {string} text 文件内容
* @returns {Promise<{ lastModified: number }>}
*/
export async function writeTodoDataFile(dirHandle, text) {
const fileHandle = await dirHandle.getFileHandle(DATA_FILE_NAME, { create: true });
const writable = await fileHandle.createWritable();
try {
await writable.write(text);
await writable.close();
} catch (error) {
try {
await writable.abort();
} catch {
// 忽略中止异常,保留原始错误
}
throw error;
}
const file = await fileHandle.getFile();
return { lastModified: file.lastModified };
}
/** 生成用于备份文件名的本地时间字符串 */
function formatBackupTimestamp(date = new Date()) {
const pad = (value, length = 2) => String(value).padStart(length, '0');
const datePart = `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}`;
const timePart = `${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`;
const msPart = pad(date.getMilliseconds(), 3);
return `${datePart}-${timePart}-${msPart}`;
}
/**
* @description 备份当前数据文件(用于数据升级前保留原始内容)
* @param {FileSystemDirectoryHandle} dirHandle 目录句柄
* @param {string} text 原始文件内容
* @returns {Promise<string>} 备份文件名
*/
export async function backupTodoDataFile(dirHandle, text) {
const name = `todo-data.backup-${formatBackupTimestamp()}.json`;
const fileHandle = await dirHandle.getFileHandle(name, { create: true });
const writable = await fileHandle.createWritable();
try {
await writable.write(text);
await writable.close();
} catch (error) {
try {
await writable.abort();
} catch {
// 忽略中止异常,保留原始错误
}
throw error;
}
return name;
}
/** 读取浏览器本地存储中的待办数据 */
export function readLocalTodoData() {
try {
return window.localStorage.getItem(LOCAL_DATA_KEY) ?? '';
} catch (error) {
console.error('[TodoStorage] 读取浏览器本地存储失败:', error);
return '';
}
}
/** 浏览器本地存储备份键(升级数据前保存原始内容) */
export const LOCAL_BACKUP_KEY = 'frost-navigation/todo-list/data.backup';
/**
* @description 备份浏览器本地存储中的原始数据(只保留最近一次)
* @param {string} text 原始内容
* @returns {boolean} 是否备份成功
*/
export function backupLocalTodoData(text) {
if (!text) {
return false;
}
try {
window.localStorage.setItem(LOCAL_BACKUP_KEY, text);
return true;
} catch (error) {
console.error('[TodoStorage] 备份浏览器本地存储失败:', error);
return false;
}
}
/** 写入浏览器本地存储,返回是否成功 */
export function writeLocalTodoData(text) {
try {
window.localStorage.setItem(LOCAL_DATA_KEY, text);
return true;
} catch (error) {
console.error('[TodoStorage] 写入浏览器本地存储失败:', error);
return false;
}
}
/** 清除浏览器本地存储中的待办数据 */
export function clearLocalTodoData() {
try {
window.localStorage.removeItem(LOCAL_DATA_KEY);
} catch (error) {
console.error('[TodoStorage] 清除浏览器本地存储失败:', error);
}
}
/**
* @description 下载文本文件
* @param {string} filename 文件名
* @param {string} text 文件内容
*/
export function downloadTextFile(filename, text) {
const blob = new Blob([text], { type: 'application/json;charset=utf-8' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename;
document.body.appendChild(link);
link.click();
link.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
@@ -0,0 +1,243 @@
<template>
<div class="tool-detail-page">
<!-- 配置参数 -->
<n-card size="small" style="--color: #2196F3;">
<template #header>
<div class="card-title">
<span class="card-title__icon mdi mdi-cog-outline"></span>
<span class="card-title__label">配置参数</span>
</div>
</template>
<n-form
class="form-no-feedback config-inputs"
label-align="right"
label-placement="left"
label-width="auto"
>
<n-form-item label="日薪">
<n-input-number
v-model:value="configData.dailyWage.value"
:min="0"
:max="99999999"
:precision="2"
:step="1"
></n-input-number>
</n-form-item>
<n-form-item label="收入币种">
<n-input
v-model:value="configData.currencyOfIncome.value"
placeholder="用于显示,例如:¥"
type="text"
:maxlength="8"
></n-input>
</n-form-item>
<n-form-item label="工作时间">
<n-input-group>
<n-time-picker
v-model:formatted-value="configData.workTimeStart.value"
format="HH:mm"
/>
<n-time-picker
v-model:formatted-value="configData.workTimeStop.value"
format="HH:mm"
/>
</n-input-group>
</n-form-item>
</n-form>
</n-card>
<!-- 实时进度 -->
<n-card size="small" style="--color: #F44336;">
<template #header>
<div class="card-title">
<span class="card-title__icon mdi mdi-chart-line"></span>
<span class="card-title__label">实时进度</span>
</div>
</template>
<div class="progress-item">
<div class="progress-item__row">
<span>本月已赚</span>
<span>1000 ¥</span>
</div>
<div class="progress-item__row">
<n-progress
color="var(--color)"
type="line"
:height="16"
:percentage="35"
:processing="true"
:show-indicator="false"
/>
</div>
<div class="progress-item__row">
<span>35%</span>
<span>剩余 20.5 天</span>
</div>
</div>
<div class="progress-item">
<div class="progress-item__row">
<span>今日已赚</span>
<span>100 ¥</span>
</div>
<div class="progress-item__row">
<n-progress
color="var(--color)"
type="line"
:height="16"
:percentage="60"
:processing="true"
:show-indicator="false"
/>
</div>
<div class="progress-item__row">
<span>60%</span>
<span>剩余 5.6 小时</span>
</div>
</div>
</n-card>
<!-- 下班冲刺 -->
<n-card size="small" style="--color: #4CAF50;">
<template #header>
<div class="card-title">
<span class="card-title__icon mdi mdi-clock-outline"></span>
<span class="card-title__label">下班冲刺</span>
</div>
</template>
<div class="time-info">
<div class="time-info__row">
<span>距离下班还剩</span>
</div>
<div class="time-info__row">
<span>05:30:20</span>
</div>
<div class="time-info__row">
<span>漫长的一天才过一半,加油吧!</span>
</div>
</div>
</n-card>
<!-- 获得成就 -->
<!-- <n-card size="small" style="--color: #FF9800;">
<template #header>
<div class="card-title">
<span class="card-title__icon mdi mdi-trophy-outline"></span>
<span class="card-title__label">获得成就</span>
</div>
</template>
</n-card> -->
</div>
</template>
<script setup>
import {
NButton, NCard, NForm, NFormItem,
NInput, NInputGroup, NInputNumber,
NProgress, NTimePicker,
} from 'naive-ui';
import {
onBeforeMount,
} from 'vue';
import {
configData, initData,
} from './data';
onBeforeMount(() => {
initData();
});
</script>
<style lang="less" scoped>
.card-title > span {
vertical-align: middle;
}
.card-title__icon {
color: var(--color, #252525);
font-size: 1.2em;
}
.card-title__label {
margin-left: 0.5em;
}
.config-inputs {
.n-form-item {
max-width: 480px;
}
:deep(.n-form-item-blank) > * {
width: 100%;
}
:deep(.n-input-group) > * {
flex-grow: 1;
width: 0;
}
}
.progress-item :not(:first-child) {
margin-top: 12px;
}
.progress-item__row {
display: flex;
align-items: center;
justify-content: space-between;
&:not(:first-child) {
margin-top: 4px;
}
&:first-child, &:last-child {
color: #505050;
}
&:first-child span:last-child {
color: var(--color);
font-size: 1.2em;
font-weight: bold;
}
&:last-child {
font-size: 0.8em;
}
}
.time-info {
padding: 16px 0;
background-color: var(--color-action);
}
.time-info__row {
text-align: center;
&:first-child, &:last-child {
color: #505050;
}
&:nth-child(1) {
font-size: 1em;
}
&:nth-child(2) {
font-size: 2em;
}
&:nth-child(3) {
font-size: 0.8em;
}
}
</style>
@@ -0,0 +1,50 @@
import { useLocalStorage } from '@vueuse/core';
import { KEY_PREFIX } from '@/assets/js/local-storage';
/** 模块名称 */
const STORAGE_PREFIX = KEY_PREFIX + 'visualized-working-hours/';
/** 配置参数 */
export const configData = {
/** 收入币种 */
currencyOfIncome: useLocalStorage(STORAGE_PREFIX + 'currencyOfIncome', ''),
/** 日薪 */
dailyWage: useLocalStorage(STORAGE_PREFIX + 'dailyWage', 100),
/** 午休时长 */
lunchBreakDuration: useLocalStorage(STORAGE_PREFIX + 'lunchBreakDuration', 1),
/** 工作开始时间 */
workTimeStart: useLocalStorage(STORAGE_PREFIX + 'workTimeStart', ''),
/** 工作结束时间 */
workTimeStop: useLocalStorage(STORAGE_PREFIX + 'workTimeStop', ''),
};
/** 初始化数据 */
export function initData() {
let {
currencyOfIncome,
workTimeStart,
workTimeStop,
} = configData;
let timeRegExp = new RegExp(/^\d{2}:\d{2}$/);
if (!currencyOfIncome.value) {
currencyOfIncome.value = '¥';
}
if (!workTimeStart.value.match(timeRegExp)) {
workTimeStart.value = '09:00';
}
if (!workTimeStop.value.match(timeRegExp)) {
workTimeStop.value = '18:00';
}
}
+102 -6
View File
@@ -5,7 +5,7 @@
<!-- 返回上一级 --> <!-- 返回上一级 -->
<n-button <n-button
v-show="isToolDetail" v-show="isToolDetail"
class="back-button" class="header-button"
:text="true" :text="true"
@click="handleCloseTool" @click="handleCloseTool"
> >
@@ -18,10 +18,20 @@
<!-- 占位 --> <!-- 占位 -->
<div class="placeholder"></div> <div class="placeholder"></div>
<!-- 查看信息 -->
<n-button
v-show="isToolDetail"
class="header-button"
:text="true"
@click="showToolItemInfo"
>
<span class="mdi mdi-information-slab-circle-outline"></span>
</n-button>
<!-- 新窗口打开 --> <!-- 新窗口打开 -->
<n-button <n-button
v-show="isToolDetail" v-show="isToolDetail"
class="back-button" class="header-button"
:text="true" :text="true"
@click="handleOpenNewWindow" @click="handleOpenNewWindow"
> >
@@ -89,17 +99,47 @@
<router-view></router-view> <router-view></router-view>
</div> </div>
<!-- 工具信息 -->
<n-modal
v-model:show="toolInfo.show"
content-class="n-dialog-content--with-max-height"
preset="dialog"
title="工具信息"
:show-icon="false"
>
<template v-if="true">
<n-h4>版本信息</n-h4>
<n-ul>
<n-li>创建日期:{{ toolInfo.dateCreated }}</n-li>
<n-li>更新日期:{{ toolInfo.dateUpdated }}</n-li>
<n-li>当前版本:{{ toolInfo.currVersion }}</n-li>
</n-ul>
</template>
<template v-if="toolInfo.changelogs.length > 0">
<n-h4>更新日志</n-h4>
<n-ul>
<n-li
v-for="(text, index) in toolInfo.changelogs"
:key="index"
class="changelogs-row"
>{{ text }}</n-li>
</n-ul>
</template>
</n-modal>
</div> </div>
</div> </div>
</template> </template>
<script setup> <script setup>
import { import {
NButton, NCollapse, NCollapseItem, NEllipsis, NTooltip, NButton, NCollapse, NCollapseItem,
NEllipsis, NModal, NTooltip,
NH4, NUl, NLi,
} from 'naive-ui'; } from 'naive-ui';
import { import {
computed, computed, reactive,
} from 'vue'; } from 'vue';
import { import {
@@ -112,7 +152,7 @@ import {
/** 是否为工具页面 */ /** 是否为工具页面 */
const isToolDetail = computed(() => { const isToolDetail = computed(() => {
return route.meta.isToolDetail; return Boolean(route.meta.isToolDetail);
}); });
/** 路由 */ /** 路由 */
@@ -126,6 +166,15 @@ const routeTitle = computed(() => {
return route.meta.title; return route.meta.title;
}); });
/** 工具信息 */
const toolInfo = reactive({
changelogs: [],
currVersion: '',
dateCreated: '',
dateUpdated: '',
show: false,
});
/** 关闭工具 */ /** 关闭工具 */
function handleCloseTool() { function handleCloseTool() {
return router.push({ return router.push({
@@ -154,10 +203,53 @@ function handleOpenTool(data) {
name: `Toolbox/${data.component}`, name: `Toolbox/${data.component}`,
}); });
} }
/** 查看当前工具信息 */
function showToolItemInfo() {
let routePath = route.path;
let toolIdMatch = routePath.match(/\/([^/]*)$/);
let toolIdStr = toolIdMatch ? toolIdMatch[1] : null;
let toolItem = null;
if (toolIdStr) {
for (let i = 0; i < toolList.length; i++) {
let category = toolList[i];
let list = category.items;
if (!category.enabled || !list) {
continue;
}
for (let j = 0; j < list.length; j++) {
let item = list[j];
if (item.id === toolIdStr) {
toolItem = item;
break;
}
}
if (toolItem) {
break;
}
}
}
if (toolItem) {
toolInfo.changelogs = toolItem.changelogs || [];
toolInfo.currVersion = toolItem.version || '';
toolInfo.dateCreated = toolItem.createdAt || '';
toolInfo.dateUpdated = toolItem.updatedAt || '';
toolInfo.show = true;
}
}
</script> </script>
<style lang="less" scoped> <style lang="less" scoped>
.back-button { .header-button {
margin-right: 0.5em; margin-right: 0.5em;
font-size: 24px; font-size: 24px;
} }
@@ -243,4 +335,8 @@ function handleOpenTool(data) {
} }
} }
} }
.changelogs-row {
white-space: pre-wrap;
}
</style> </style>
+2
View File
@@ -65,6 +65,8 @@ declare global {
version: string; version: string;
/** 是否启用 */ /** 是否启用 */
enabled: boolean; enabled: boolean;
/** 更新日志 */
changelogs: string[];
} }
// window // window
+8
View File
@@ -20,6 +20,13 @@ export default defineConfig({
}, },
}, },
envPrefix: 'V_ENV_', envPrefix: 'V_ENV_',
optimizeDeps: {
include: [
// 预构建 Monaco Editor Worker
'monaco-editor/esm/vs/editor/editor.worker',
'monaco-editor/esm/vs/language/json/json.worker',
],
},
plugins: [ plugins: [
legacy({ legacy({
polyfills: false, polyfills: false,
@@ -37,6 +44,7 @@ export default defineConfig({
}, },
}, },
server: { server: {
allowedHosts: true,
port: 9000, port: 9000,
}, },
}); });