2 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
15 changed files with 8077 additions and 48 deletions
+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'] = [
{
@@ -69,6 +69,12 @@ window['NAV_LINK_LIST'] = [
date: '2021-02-08',
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: '开发',
children: [
{
title: 'agent-qa',
date: '2026-11-30',
desc: '自然语言 Web、Android 与 iOS 测试工具,结合运行证据、memidex 持久记忆与经验证的自我改进。',
url: 'https://vostride.com',
},
{
title: '前端',
children: [
@@ -1205,6 +1217,17 @@ window['NAV_LINK_LIST'] = [
title: '工具',
icon: 'mdi mdi-hammer-wrench',
children: [
{
title: 'AI',
children: [
{
title: 'Whizi',
date: '2026-11-30',
desc: '一个订阅使用 GPT、Claude、Gemini、Grok、DeepSeek 等 280+ 个 AI 模型,对话中可随时切换模型。',
url: 'https://whizi.io/',
}
]
},
{
title: '编辑',
children: [
+30
View File
@@ -1,5 +1,29 @@
/** 工具更新日志 */
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初始版本。',
@@ -9,6 +33,9 @@ export const CHANGE_LOGS = {
'[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初始版本。',
@@ -17,4 +44,7 @@ export const CHANGE_LOGS = {
'[2] - 2025-02-23\n支持生成二维码。\n支持解析剪贴板中的二维码图片。\n优化解析功能,在二维码所在位置添加矩形标记。',
'[1] - 2025-02-21\n初始版本。',
],
'url-encode-decode': [
'[1] - 2026-11-17\n初始版本。\n支持 encodeURIComponent / encodeURI 及对应解码方式。',
],
};
+59 -38
View File
@@ -49,10 +49,11 @@ export const toolList = [
title: 'Base64 字符串编码 / 解码',
iconClass: 'mdi mdi-swap-horizontal',
desc: '处理 Base64 编码的字符串。',
createdAt: '',
updatedAt: '',
version: '0',
enabled: false,
createdAt: '2026-11-17',
updatedAt: '2026-11-17',
version: '1',
enabled: true,
changelogs: CHANGE_LOGS['base64-encode-decode'],
},
{
id: 'png-to-ico',
@@ -82,10 +83,11 @@ export const toolList = [
title: 'URL 编码 / 解码',
iconClass: 'mdi mdi-swap-horizontal',
desc: '处理 URL 编码的字符串。',
createdAt: '',
updatedAt: '',
version: '0',
enabled: false,
createdAt: '2026-11-17',
updatedAt: '2026-11-17',
version: '1',
enabled: true,
changelogs: CHANGE_LOGS['url-encode-decode'],
},
{
id: 'qrcode-reader-and-generator',
@@ -105,21 +107,23 @@ export const toolList = [
title: '文本结构转换',
iconClass: 'mdi mdi-swap-horizontal',
desc: '倒序、横竖互换等',
createdAt: '',
updatedAt: '',
version: '0',
enabled: false,
createdAt: '2026-11-17',
updatedAt: '2026-11-17',
version: '1',
enabled: true,
changelogs: CHANGE_LOGS['convert-text-structure'],
},
{
id: 'convert-html-entities',
component: 'Conversion/ConvertHtmlEntities',
title: '转换 HTML 实体',
iconClass: 'mdi mdi-swap-horizontal',
desc: '',
createdAt: '',
updatedAt: '',
version: '0',
enabled: false,
desc: '编码 / 解码 HTML、XML 实体。',
createdAt: '2026-11-17',
updatedAt: '2026-11-17',
version: '1',
enabled: true,
changelogs: CHANGE_LOGS['convert-html-entities'],
},
]
},
@@ -134,10 +138,11 @@ export const toolList = [
title: 'CSV 编辑',
iconClass: 'mdi mdi-table-edit',
desc: '查看或编辑 CSV 文件',
createdAt: '',
updatedAt: '',
version: '0',
enabled: false,
createdAt: '2026-11-17',
updatedAt: '2026-11-17',
version: '1',
enabled: true,
changelogs: CHANGE_LOGS['csv-editor'],
},
{
id: 'json-editor',
@@ -186,10 +191,11 @@ export const toolList = [
title: 'frp 配置文件生成',
iconClass: 'mdi mdi-file-cog-outline',
desc: '生成用于 frpc、frps 的配置文件。',
createdAt: '',
updatedAt: '',
version: '0',
enabled: false,
createdAt: '2026-11-17',
updatedAt: '2026-11-17',
version: '1',
enabled: true,
changelogs: CHANGE_LOGS['frp-config-generator'],
},
{
id: 'uuid-generator',
@@ -237,10 +243,11 @@ export const toolList = [
title: 'Minecraft UUID 转换',
iconClass: 'mdi mdi-identifier',
desc: '随机生成或转换 Minecraft 的 UUID。',
createdAt: '',
updatedAt: '',
version: '0',
enabled: false,
createdAt: '2026-11-17',
updatedAt: '2026-11-17',
version: '1',
enabled: true,
changelogs: CHANGE_LOGS['minecraft-uuid-converter'],
},
{
id: 'minecraft-chat-history-reader',
@@ -258,11 +265,12 @@ export const toolList = [
component: 'Minecraft/CalcChunkLocation',
title: 'Minecraft 区块位置计算',
iconClass: 'mdi mdi-calculator-variant-outline',
desc: '',
createdAt: '',
updatedAt: '',
version: '0',
enabled: false,
desc: '根据方块坐标计算所属区块、区域文件位置等信息。',
createdAt: '2026-11-17',
updatedAt: '2026-11-17',
version: '1',
enabled: true,
changelogs: CHANGE_LOGS['calc-minecraft-chunk-location'],
},
{
id: 'generate-minecraft-dynmap-renderdata',
@@ -270,10 +278,11 @@ export const toolList = [
title: '生成 Dynmap renderdata',
iconClass: 'mdi mdi-file-outline',
desc: '生成用于 Minecraft Dynmap 插件或模组的 renderdata 数据。',
createdAt: '',
updatedAt: '',
version: '0',
enabled: false,
createdAt: '2026-11-17',
updatedAt: '2026-11-17',
version: '1',
enabled: true,
changelogs: CHANGE_LOGS['generate-minecraft-dynmap-renderdata'],
},
]
},
@@ -300,6 +309,18 @@ export const toolList = [
title: '其他',
enabled: true,
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',
component: 'Other/KeepScreenOn',
@@ -1,9 +1,318 @@
<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>
<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>
<style lang="less" scoped>
.monospace-input {
font-family: monospace;
}
:deep(.n-input) {
max-width: 64em;
}
</style>
@@ -1,9 +1,388 @@
<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>
<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>
<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>
@@ -1,9 +1,272 @@
<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>
<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>
<style lang="less" scoped>
.monospace-input {
font-family: monospace;
}
.tip-text {
color: #666;
font-size: 14px;
}
:deep(.n-input) {
max-width: 64em;
}
</style>
@@ -1,9 +1,244 @@
<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>
<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>
<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>
+770 -1
View File
@@ -1,9 +1,778 @@
<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>
<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>
<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>
@@ -1,9 +1,951 @@
<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>
<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>
<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>
@@ -1,9 +1,329 @@
<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>
<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>
<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>
@@ -1,9 +1,679 @@
<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>
<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>
<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>
@@ -1,9 +1,544 @@
<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>
<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>
<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>
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);
}