调整,音乐模块

This commit is contained in:
zhongluofeng
2026-09-12 11:05:26 +08:00
parent 27ad5d89a5
commit d702ed0d31
71 changed files with 13647 additions and 387 deletions
+115
View File
@@ -241,6 +241,21 @@ export const commands = {
downloaderInspect: (input: string) => __TAURI_INVOKE<TorrentInfo>("downloader_inspect", { input }),
/** 磁力任务:元数据解析成功后,用户勾选文件并确认开始下载 */
downloaderSelectBtFiles: (id: string, onlyFiles: number[]) => __TAURI_INVOKE<null>("downloader_select_bt_files", { id, onlyFiles }),
/**
* 查询环境状态(Python / musicdl / FFmpeg / 桥接进程),设置页「环境检查」面板调用。
* 异步命令:子进程探测在阻塞线程池执行,避免冻结主线程/UI。
*/
musicEnvStatus: () => __TAURI_INVOKE<MusicEnvStatus>("music_env_status"),
/** 安装便携 Python + musicdl(幂等),全程推送 music-runtime-install-progress 事件 */
musicInstallRuntime: () => __TAURI_INVOKE<MusicEnvStatus>("music_install_runtime"),
/** 取消便携运行时安装/下载 */
musicCancelRuntimeInstall: () => __TAURI_INVOKE<null>("music_cancel_runtime_install"),
/** 停止桥接进程 */
musicStopBridge: () => __TAURI_INVOKE<null>("music_stop_bridge"),
/** 读取音乐模块设置 */
musicGetSettings: () => __TAURI_INVOKE<MusicSettings>("music_get_settings"),
/** 保存音乐模块设置(立即生效) */
musicSaveSettings: (settings: MusicSettings) => __TAURI_INVOKE<null>("music_save_settings", { settings }),
/** 禁用指定窗口(按 label 查找)的显示/隐藏过渡动画,消除覆盖层出现/消失时的缩放动画 */
screenshotDisableTransitions: (label: string) => __TAURI_INVOKE<null>("screenshot_disable_transitions", { label }),
/** 一次 IPC 完成指定窗口的显示与聚焦(截图覆盖层显示关键路径,减少串行往返) */
@@ -305,6 +320,20 @@ export const commands = {
width: number,
height: number,
} | null, auto: boolean) => __TAURI_INVOKE<null>("screenshot_scroll_start", { hwnd, region, auto }),
/**
* 滚动模式遮罩挖孔:在截图覆盖层窗口上挖出选区带的真孔(region = None 时复位整窗)。
*
* Chromium 系浏览器(Edge/Chrome)的窗口遮挡检测会把被完全覆盖的窗口标记为
* occluded 并暂停渲染——滚动截图时覆盖层铺满全屏,网页"看起来完全不滚动"。
* 挖孔后目标窗口仅部分被覆盖,恢复渲染与滚轮响应(详见 capture::set_scroll_hole)。
* 进入滚动模式时带选区调用,会话结束/新一轮截图开始时必须传 None 复位。
*/
screenshotSetScrollHole: (region: {
x: number,
y: number,
width: number,
height: number,
} | null) => __TAURI_INVOKE<null>("screenshot_set_scroll_hole", { region }),
/** 将 PNG base64 写入系统剪贴板(转 CF_DIB */
screenshotCopyImage: (pngBase64: string) => __TAURI_INVOKE<null>("screenshot_copy_image", { pngBase64 }),
/** 将 PNG base64 写入文件 */
@@ -522,6 +551,24 @@ export type ExtractResult = {
error: string,
};
/** 一条飞牛音乐连接(持久化在 `MusicSettings`)。 */
export type FeiniuConnection = {
id: string,
name: string,
/** "lan" | "frp" | "fnconnect"fnconnect 预留) */
kind: string,
/** 服务器地址(http://192.168.x.x:5666 或 https://域名) */
baseUrl: string,
username: string,
token: string,
deviceId: string,
accessCode: string,
/** https 遇到自签证书时忽略校验 */
insecure: boolean,
/** fnconnect 连接的 fnId(如 fnos.net/<id> 或裸 id */
fnId?: string,
};
export type FileEntry = {
name: string,
path: string,
@@ -564,6 +611,74 @@ export type KernelUpdateInfo = {
hasUpdate: boolean,
};
/** 环境状态(返回前端,设置页「环境检查」面板展示) */
export type MusicEnvStatus = {
/** 系统 Python 版本(如 "3.14.5"),无则 None */
python: string | null,
/** python 来源:"system" | "bundled" | "none" */
pythonSource: string,
/** 便携 Python 可执行文件路径(未安装则 None) */
bundledPython: string | null,
/** musicdl 是否可导入 */
musicdlInstalled: boolean,
/** musicdl 版本 */
musicdlVersion: string | null,
/** FFmpeg 是否可用(部分音源需要,非必需) */
ffmpeg: string | null,
/** 桥接进程是否在运行 */
bridgeRunning: boolean,
/** 运行时目录({app_data_dir}/music */
runtimeDir: string,
};
/** 音乐模块设置(settings.json 持久化;变更即时生效) */
export type MusicSettings = {
/** 下载保存目录 */
savedir: string,
/** 搜索源(musicdl 客户端名,如 NeteaseMusicClient */
sources: string[],
/** 下载时同步保存歌词 */
lyricDownload: boolean,
/** 下载时同步保存封面 */
coverDownload: boolean,
/** 搜索/下载请求是否走代理模块(mihomo mixed 端口) */
useProxy: boolean,
/** 最大并发下载数 */
maxConcurrent: number,
/** 下载引擎:"musicdl" | "rust"P2 生效) */
downloadEngine: string,
/** 下载时是否弹窗选择音质(默认关;开启后点下载弹出所选歌曲档位并集选择) */
selectQualityOnDownload: boolean,
/** 下载时默认音质:"" 表示最高;否则为搜索音质档位 label(如 "无损"、"320K" */
defaultDownloadQuality: string,
/** 飞牛音乐(NAS)连接:服务器地址(如 http://192.168.1.10:5666,空=未配置) */
feiniuBaseUrl?: string,
/** 飞牛音乐登录 token(登录成功后保存) */
feiniuToken?: string,
/** 飞牛音乐登录账号(展示 + 重新登录回填用) */
feiniuUsername?: string,
/** 飞牛音乐设备 ID(32 位 hex,登录签名用,一次生成复用) */
feiniuDeviceId?: string,
/** 飞牛音乐访问安全码(可选;仅需访问码的库才填,LAN 通常为空) */
feiniuAccessCode?: string,
/** 飞牛音乐连接列表(多连接:本地 / frp / 预留 fnconnect */
feiniuConnections?: FeiniuConnection[],
/** 当前激活连接的 id */
feiniuActiveId?: string,
/** 本地曲库扫描目录(默认含音乐下载 savedir) */
feiniuLocalDirs?: string[],
/** 播放缓存开关 */
feiniuCacheEnabled?: boolean,
/** 缓存上限(GB */
feiniuCacheMaxGb?: number,
/** 播放模式:"stream" 直连流式 | "cache" 缓存后播放 */
feiniuPlayMode?: string,
/** 飞牛曲库目标目录(NAS 绝对路径,如 vol1/1000/Music;上传到飞牛用) */
feiniuLibraryNasPath?: string,
/** 下载完成后自动上传到飞牛曲库 */
feiniuAutoUpload?: boolean,
};
/** 进程信息(返回给前端) */
export type ProcessInfo = {
id: string,
+157
View File
@@ -0,0 +1,157 @@
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { ArrowLeft, Search } from '@lucide/vue'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Separator } from '@/components/ui/separator'
import { useSearchStore } from '@/stores/searchStore'
import { registerAllTools, TOOLS_META } from './tools'
import {
getAllTools, getTool, searchTools,
CATEGORY_ORDER, CATEGORY_LABEL, type DevTool
} from './registry'
const searchStore = useSearchStore()
registerAllTools()
const allTools = getAllTools()
// ===== 列表视图:搜索 + 分类筛选 =====
const query = ref('')
const category = ref<'all' | DevTool['category']>('all')
const filteredTools = computed(() => {
const list = searchTools(query.value)
if (category.value === 'all') return list
return list.filter(t => t.category === category.value)
})
interface ToolGroup {
category: DevTool['category']
label: string
tools: DevTool[]
}
const groupedTools = computed<ToolGroup[]>(() => {
if (category.value !== 'all') {
return [{
category: category.value as DevTool['category'],
label: CATEGORY_LABEL[category.value as DevTool['category']],
tools: filteredTools.value
}]
}
const groups: ToolGroup[] = []
for (const cat of CATEGORY_ORDER) {
const tools = filteredTools.value.filter(t => t.category === cat)
if (tools.length > 0) groups.push({ category: cat, label: CATEGORY_LABEL[cat], tools })
}
return groups
})
// ===== 详情视图 =====
const selectedId = ref<string | null>(null)
const selectedTool = computed<DevTool | null>(() => {
if (!selectedId.value) return null
return getTool(selectedId.value) ?? null
})
function openTool(id: string) {
selectedId.value = id
}
// ===== 全局搜索跳转:工具索引 → 打开对应工具 =====
onMounted(() => {
const actions = new Map<number, () => void>()
TOOLS_META.forEach((t, i) => {
actions.set(i, () => openTool(t.id))
})
searchStore.registerActions('devtools', actions)
})
watch(selectedId, () => {
query.value = ''
})
</script>
<template>
<div class="h-full p-6 overflow-hidden flex flex-col">
<!-- 列表视图 -->
<template v-if="!selectedTool">
<div class="flex items-center gap-3 mb-4 shrink-0 flex-wrap">
<div class="relative flex-1 min-w-[180px] max-w-xs">
<Search class="absolute left-2.5 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
<Input v-model="query" placeholder="搜索工具..." class="h-8 pl-8 text-sm" />
</div>
<Button
v-for="cat in (['all', ...CATEGORY_ORDER] as const)"
:key="cat"
size="sm"
variant="ghost"
class="h-7 px-2.5 text-xs"
:class="category === cat ? 'bg-secondary text-foreground' : 'text-muted-foreground'"
@click="category = cat as typeof category"
>
{{ cat === 'all' ? '全部' : CATEGORY_LABEL[cat as DevTool['category']] }}
</Button>
<span class="text-xs text-muted-foreground ml-auto">{{ (category === 'all' ? allTools : filteredTools).length }} 个工具</span>
</div>
<ScrollArea class="flex-1 min-h-0 -mr-3 pr-3">
<div v-if="filteredTools.length === 0" class="h-full flex items-center justify-center text-muted-foreground text-sm">
没有找到匹配的工具
</div>
<!-- 按分类分组 -->
<div v-for="group in groupedTools" :key="group.category" class="mb-5">
<div class="flex items-center gap-2 mb-2">
<span class="text-xs font-medium text-muted-foreground">{{ group.label }}</span>
<Separator class="flex-1" />
</div>
<div class="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-3">
<Card
v-for="tool in group.tools"
:key="tool.id"
class="cursor-pointer transition-all hover:border-primary/50 hover:shadow-sm !py-0 !gap-0"
@click="openTool(tool.id)"
>
<CardContent class="p-4 flex flex-col gap-2">
<div class="size-9 rounded-lg bg-primary/10 text-primary flex items-center justify-center">
<component :is="tool.icon" class="size-5" />
</div>
<div class="flex flex-col gap-0.5">
<span class="text-sm font-medium leading-tight">{{ tool.name }}</span>
<span class="text-xs text-muted-foreground leading-snug line-clamp-2">{{ tool.description }}</span>
</div>
</CardContent>
</Card>
</div>
</div>
</ScrollArea>
</template>
<!-- 工具详情视图 -->
<template v-else>
<div class="flex items-center gap-3 mb-4 shrink-0">
<Button size="sm" variant="ghost" class="gap-1 h-8" @click="selectedId = null">
<ArrowLeft class="size-4" />
返回
</Button>
<div class="size-8 rounded-lg bg-primary/10 text-primary flex items-center justify-center">
<component :is="selectedTool.icon" class="size-4" />
</div>
<div class="flex flex-col">
<span class="text-sm font-medium leading-tight">{{ selectedTool.name }}</span>
<span class="text-xs text-muted-foreground leading-snug">{{ selectedTool.description }}</span>
</div>
</div>
<ScrollArea class="flex-1 min-h-0 -mr-3 pr-3">
<div class="max-w-3xl px-1 pb-6">
<component :is="selectedTool.component" />
</div>
</ScrollArea>
</template>
</div>
</template>
@@ -0,0 +1,75 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { Check, Copy } from '@lucide/vue'
import { Textarea } from '@/components/ui/textarea'
import { Button } from '@/components/ui/button'
const props = withDefaults(
defineProps<{
text: string
editable?: boolean
placeholder?: string
label?: string
minHeight?: string
}>(),
{ editable: false, placeholder: '结果...', label: '结果', minHeight: '120px' }
)
const emit = defineEmits<{
(e: 'update:text', v: string): void
(e: 'copy', text: string): void
}>()
const copied = ref(false)
let copyTimer: number
const lineCount = computed(() => (props.text ? props.text.split('\n').length : 0))
const charCount = computed(() => props.text.length)
const copy = async () => {
try {
await navigator.clipboard.writeText(props.text)
emit('copy', props.text)
copied.value = true
window.clearTimeout(copyTimer)
copyTimer = window.setTimeout(() => (copied.value = false), 1500)
} catch {
/* 复制失败静默 */
}
}
const onInput = (v: string | number) => {
if (props.editable) emit('update:text', String(v))
}
</script>
<template>
<div class="flex flex-col gap-1.5">
<div class="flex items-center justify-between">
<span class="text-xs font-medium">{{ label }}</span>
<div class="flex items-center gap-2 text-[11px] text-muted-foreground">
<span>{{ lineCount }} </span>
<span>{{ charCount }} 字符</span>
<Button
v-if="!editable"
size="icon"
variant="ghost"
class="size-6"
:title="copied ? '已复制' : '复制'"
@click="copy"
>
<Check v-if="copied" class="size-3.5 text-green-500" />
<Copy v-else class="size-3.5" />
</Button>
</div>
</div>
<Textarea
:model-value="props.text"
:readonly="!editable"
:placeholder="placeholder"
:style="{ minHeight }"
class="font-mono text-xs leading-relaxed resize-y"
@update:model-value="onInput"
/>
</div>
</template>
@@ -0,0 +1,40 @@
<script setup lang="ts">
export interface SegmentedOption {
value: string
label: string
}
defineProps<{
options: SegmentedOption[]
modelValue: string
label?: string
size?: 'xs' | 'sm'
}>()
const emit = defineEmits<{
(e: 'update:modelValue', v: string): void
}>()
</script>
<template>
<div class="flex items-center gap-2 shrink-0">
<span v-if="label" class="text-sm text-muted-foreground">{{ label }}</span>
<div class="inline-flex rounded-md border border-border bg-muted/40 p-1">
<button
v-for="o in options"
:key="o.value"
type="button"
class="rounded px-3 font-medium transition-colors cursor-pointer"
:class="[
size === 'sm' ? 'py-1.5 text-sm' : 'py-1 text-sm',
modelValue === o.value
? 'bg-background text-foreground shadow-sm'
: 'text-muted-foreground hover:text-foreground'
]"
@click="emit('update:modelValue', o.value)"
>
{{ o.label }}
</button>
</div>
</div>
</template>
+27
View File
@@ -0,0 +1,27 @@
import type { ModuleConfig } from '@/types/module'
import type { SearchIndexItem } from '@/stores/searchIndex'
import { TOOLS_META } from './tools'
/** 开发者工具模块:聚合大量轻量文本/编码/转换工具 */
const searchItems: SearchIndexItem[] = TOOLS_META.map((t) => ({
title: t.name,
description: t.description,
keywords: [t.name, ...t.keywords]
}))
export const moduleConfig: ModuleConfig = {
id: 'devtools',
name: '开发者工具',
icon: 'devtools',
description: 'JSON / Base64 / 时间戳 / 正则 / 颜色 / Cron / 密码等 20 个常用开发工具',
category: 'tool',
defaultEnabled: true,
loader: () => import('./DevToolsModule.vue'),
searchItems,
lifecycle: {
onEnable: async () => {},
onDisable: async () => {}
},
order: 60
}
+59
View File
@@ -0,0 +1,59 @@
import type { Component } from 'vue'
export type DevToolCategory = 'encoding' | 'transform' | 'text' | 'generate' | 'reference'
export interface DevTool {
id: string
name: string
description: string
category: DevToolCategory
keywords: string[]
icon: Component
component: Component
}
/** 分类展示顺序 */
export const CATEGORY_ORDER: DevToolCategory[] = ['transform', 'encoding', 'text', 'generate', 'reference']
export const CATEGORY_LABEL: Record<DevToolCategory, string> = {
transform: '转换',
encoding: '编码',
text: '文本',
generate: '生成',
reference: '速查'
}
const allTools: DevTool[] = []
const registry = new Map<string, DevTool>()
export function registerTool(tool: DevTool): void {
if (registry.has(tool.id)) return
registry.set(tool.id, tool)
allTools.push(tool)
}
export function getTool(id: string): DevTool | undefined {
return registry.get(id)
}
export function getAllTools(): DevTool[] {
return [...allTools]
}
export function getToolsByCategory(): Record<DevToolCategory, DevTool[]> {
const result = {} as Record<DevToolCategory, DevTool[]>
for (const cat of CATEGORY_ORDER) result[cat] = []
for (const tool of allTools) {
result[tool.category].push(tool)
}
return result
}
export function searchTools(query: string): DevTool[] {
if (!query.trim()) return allTools
const q = query.trim().toLowerCase()
return allTools.filter(t =>
t.name.toLowerCase().includes(q) ||
t.description.toLowerCase().includes(q) ||
t.keywords.some(k => k.toLowerCase().includes(q))
)
}
+166
View File
@@ -0,0 +1,166 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { ArrowDownUp, Upload } from '@lucide/vue'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { Button } from '@/components/ui/button'
import Segmented from '../components/Segmented.vue'
import ResultArea from '../components/ResultArea.vue'
type Tab = 'convert' | 'file'
const tab = ref<Tab>('convert')
const mode = ref<'encode' | 'decode'>('encode')
const input = ref('')
const error = ref('')
function encode(s: string): string {
const bytes = new TextEncoder().encode(s)
let bin = ''
for (const b of bytes) bin += String.fromCharCode(b)
return btoa(bin)
}
function decode(s: string): string {
const cleaned = s.replace(/[\r\n\s]/g, '')
const bin = atob(cleaned)
const bytes = Uint8Array.from(bin, ch => ch.charCodeAt(0))
return new TextDecoder().decode(bytes)
}
const output = computed(() => {
error.value = ''
const v = input.value
if (!v) return ''
try {
return mode.value === 'encode' ? encode(v) : decode(v)
} catch (e) {
error.value = '解码失败:' + String(e)
return ''
}
})
const swap = () => {
if (output.value) {
input.value = output.value
mode.value = mode.value === 'encode' ? 'decode' : 'encode'
}
}
// ===== 文件转 Base64 =====
const file = ref<File | null>(null)
const fileInput = ref<HTMLInputElement | null>(null)
const fileBase64 = ref('')
const fileError = ref('')
const fileLoading = ref(false)
const FILE_SIZE_LIMIT = 64 * 1024 * 1024 // 64MB 保护上限(Base64 展示本身就很占内存)
function formatSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
return `${(bytes / 1024 / 1024).toFixed(1)} MB`
}
const mime = computed(() => file.value?.type || 'application/octet-stream')
async function onFileChange(e: Event) {
const el = e.target as HTMLInputElement
const f = el.files?.[0] ?? null
fileError.value = ''
fileBase64.value = ''
file.value = f
if (!f) return
if (f.size > FILE_SIZE_LIMIT) {
fileError.value = `文件过大(${formatSize(f.size)}),请使用 64MB 以内的文件`
return
}
fileLoading.value = true
try {
const buf = await f.arrayBuffer()
const bytes = new Uint8Array(buf)
let bin = ''
const CHUNK = 0x8000
for (let i = 0; i < bytes.length; i += CHUNK) {
bin += String.fromCharCode(...bytes.subarray(i, i + CHUNK))
}
fileBase64.value = btoa(bin)
} catch (e) {
fileError.value = '读取失败:' + String(e)
} finally {
fileLoading.value = false
}
}
function clearFile() {
file.value = null
fileBase64.value = ''
fileError.value = ''
if (fileInput.value) fileInput.value.value = ''
}
const dataUrl = computed(() =>
fileBase64.value ? `data:${mime.value};base64,${fileBase64.value}` : ''
)
</script>
<template>
<div class="flex flex-col gap-4">
<Segmented
v-model="tab"
:options="[
{ value: 'convert', label: '文本互转' },
{ value: 'file', label: '文件转 Base64' }
]"
/>
<!-- 文本互转 -->
<template v-if="tab === 'convert'">
<div class="flex items-center justify-between flex-wrap gap-2">
<Segmented
v-model="mode"
label="操作"
:options="[
{ value: 'encode', label: '编码' },
{ value: 'decode', label: '解码' }
]"
/>
<Button size="sm" variant="outline" class="h-8 text-sm gap-1" :disabled="!output" @click="swap">
<ArrowDownUp class="size-3.5" />
结果回填
</Button>
</div>
<div class="flex flex-col gap-1.5">
<Label class="text-xs">{{ mode === 'encode' ? '原文' : 'Base64 字符串' }}</Label>
<Textarea v-model="input" placeholder="在此输入..." class="min-h-[120px] font-mono text-xs resize-y" />
</div>
<ResultArea :text="output" placeholder="结果" />
<p v-if="error" class="text-xs text-destructive">{{ error }}</p>
</template>
<!-- 文件转 Base64 -->
<template v-else>
<div class="flex items-center gap-2 flex-wrap">
<Button size="sm" variant="outline" class="h-8 text-sm gap-1.5" @click="fileInput?.click()">
<Upload class="size-3.5" />
选择文件
</Button>
<input ref="fileInput" type="file" class="hidden" @change="onFileChange" />
<template v-if="file">
<span class="text-xs font-mono text-muted-foreground">{{ file.name }}{{ formatSize(file.size) }}{{ mime }}</span>
<Button size="sm" variant="ghost" class="h-7 text-xs" @click="clearFile">移除</Button>
</template>
</div>
<p v-if="fileError" class="text-xs text-destructive">{{ fileError }}</p>
<template v-if="fileBase64">
<ResultArea :text="fileBase64" label="Base64" placeholder="Base64" minHeight="100px" />
<ResultArea :text="dataUrl" label="Data URL" placeholder="Data URL" minHeight="100px" />
<p class="text-xs text-muted-foreground">Base64 体积约为原文件的 4/3{{ formatSize(fileBase64.length) }}</p>
</template>
<p v-else-if="!fileLoading" class="text-xs text-muted-foreground">选择文件后自动生成 Base64 Data URL</p>
<p v-else class="text-xs text-muted-foreground">读取中...</p>
</template>
</div>
</template>
+87
View File
@@ -0,0 +1,87 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import Segmented from '../components/Segmented.vue'
import ResultArea from '../components/ResultArea.vue'
type CaseMode =
| 'camel' | 'pascal' | 'snake' | 'kebab'
| 'upper' | 'lower' | 'title'
| 'spaceToDash' | 'trimLines' | 'collapseSpace'
const modes: { value: CaseMode; label: string }[] = [
{ value: 'camel', label: 'camelCase' },
{ value: 'pascal', label: 'PascalCase' },
{ value: 'snake', label: 'snake_case' },
{ value: 'kebab', label: 'kebab-case' },
{ value: 'upper', label: '全大写' },
{ value: 'lower', label: '全小写' },
{ value: 'title', label: '标题式' },
{ value: 'spaceToDash', label: '空格转下划线' },
{ value: 'collapseSpace', label: '合并空行空白' },
{ value: 'trimLines', label: '每行去首尾空格' }
]
const mode = ref<CaseMode>('camel')
const input = ref('')
function toWords(s: string): string[] {
// 拆分 camelCase / snake_case / kebab-case / 空格,得到词
return s
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
.replace(/[_\-\s]+/g, ' ')
.trim()
.split(' ')
.filter(Boolean)
}
const output = computed(() => {
const v = input.value
if (!v) return ''
switch (mode.value) {
case 'upper':
return v.toUpperCase()
case 'lower':
return v.toLowerCase()
case 'title':
return v.replace(/\b\w/g, ch => ch.toUpperCase())
case 'spaceToDash':
return v.replace(/\s+/g, '_')
case 'collapseSpace':
return v.split(/\n+/).map(l => l.trim()).filter(Boolean).join('\n')
case 'trimLines':
return v.split('\n').map(l => l.trim()).join('\n')
case 'camel': // fallthrough
case 'pascal':
case 'snake':
case 'kebab':
break
}
const words = toWords(v).filter(Boolean)
if (words.length === 0) return ''
if (mode.value === 'camel') {
return words[0].toLowerCase() + words.slice(1).map(w => cap(w)).join('')
}
if (mode.value === 'pascal') {
return words.map(cap).join('')
}
const sep = mode.value === 'snake' ? '_' : '-'
return words.map(w => w.toLowerCase()).join(sep)
})
function cap(w: string): string {
return w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()
}
</script>
<template>
<div class="flex flex-col gap-4">
<Segmented v-model="mode" :options="modes" />
<div class="flex flex-col gap-1.5">
<Label class="text-xs">原文</Label>
<Textarea v-model="input" placeholder="在此输入..." class="min-h-[140px] font-mono text-xs resize-y" />
</div>
<ResultArea :text="output" placeholder="结果" />
</div>
</template>
@@ -0,0 +1,129 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
const input = ref('')
const showFrequency = ref(true)
function utf8Bytes(s: string): number {
return new TextEncoder().encode(s).length
}
/** 统计词:中文按字、英文按单词 */
function countWords(s: string): number {
const cjk = (s.match(/[\u4e00-\u9fff\u3400-\u4dbf]/g) ?? []).length
const latin = (s.match(/[a-zA-Z0-9]+(?:[-'][a-zA-Z0-9]+)*/g) ?? []).length
return cjk + latin
}
interface Stats {
chars: number
charsNoSpace: number
bytes: number
words: number
lines: number
nonEmptyLines: number
sentences: number
paragraphs: number
}
const stats = computed<Stats>(() => {
const v = input.value
const lines = v === '' ? 0 : v.split('\n').length
const nonEmpty = v.split('\n').filter(l => l.trim()).length
// 句子:以 。!?.!?;; 结尾的段落片段
const sentences = (v.match(/[^。!?!?\n]+[。!?!?]?/g) ?? []).filter(s => s.trim()).length
const paragraphs = v.split(/\n\s*\n/).filter(p => p.trim()).length
return {
chars: v.length,
charsNoSpace: v.replace(/\s/g, '').length,
bytes: utf8Bytes(v),
words: countWords(v),
lines,
nonEmptyLines: nonEmpty,
sentences,
paragraphs
}
})
const FIELDS: Array<{ key: keyof Stats; label: string }> = [
{ key: 'chars', label: '字符数' },
{ key: 'charsNoSpace', label: '字符数(不含空白)' },
{ key: 'bytes', label: '字节数(UTF-8' },
{ key: 'words', label: '词数(中文按字/英文按词)' },
{ key: 'lines', label: '行数' },
{ key: 'nonEmptyLines', label: '非空行数' },
{ key: 'sentences', label: '句子数' },
{ key: 'paragraphs', label: '段落数(空行分隔)' }
]
/** 高频字符 / 高频词 top 10 */
const topChars = computed(() => {
if (!showFrequency.value || !input.value) return []
const map = new Map<string, number>()
for (const ch of input.value) {
if (/\s/.test(ch)) continue
map.set(ch, (map.get(ch) ?? 0) + 1)
}
return [...map.entries()].sort((a, b) => b[1] - a[1]).slice(0, 10)
})
const topWords = computed(() => {
if (!showFrequency.value || !input.value) return []
const tokens = input.value.match(/[\u4e00-\u9fff]|[a-zA-Z0-9]+(?:[-'][a-zA-Z0-9]+)*/g) ?? []
const map = new Map<string, number>()
for (const t of tokens) {
map.set(t, (map.get(t) ?? 0) + 1)
}
return [...map.entries()].sort((a, b) => b[1] - a[1]).slice(0, 10)
})
</script>
<template>
<div class="flex flex-col gap-4">
<div class="flex flex-col gap-1.5">
<div class="flex items-center justify-between">
<Label class="text-xs">文本</Label>
<label class="flex items-center gap-2 text-xs text-muted-foreground cursor-pointer">
显示高频统计
<Switch v-model="showFrequency" />
</label>
</div>
<Textarea v-model="input" placeholder="粘贴或输入文本,实时统计..." class="min-h-[160px] font-mono text-xs resize-y" />
</div>
<div class="rounded-md border border-border divide-y divide-border text-xs">
<div v-for="f in FIELDS" :key="f.key" class="flex justify-between px-3 py-1.5">
<span class="text-muted-foreground">{{ f.label }}</span>
<span class="font-mono">{{ stats[f.key].toLocaleString() }}</span>
</div>
</div>
<template v-if="showFrequency && input">
<div class="grid grid-cols-2 gap-3">
<div class="flex flex-col gap-1.5">
<Label class="text-xs">高频字符 Top 10</Label>
<div class="rounded-md border border-border divide-y divide-border text-xs">
<div v-for="([ch, n], i) in topChars" :key="i" class="flex justify-between px-3 py-1">
<span class="font-mono w-8 text-center rounded bg-muted">{{ ch }}</span>
<span class="font-mono text-muted-foreground">{{ n }} </span>
</div>
<div v-if="topChars.length === 0" class="px-3 py-2 text-muted-foreground">无内容</div>
</div>
</div>
<div class="flex flex-col gap-1.5">
<Label class="text-xs">高频词 Top 10</Label>
<div class="rounded-md border border-border divide-y divide-border text-xs">
<div v-for="([w, n], i) in topWords" :key="i" class="flex justify-between px-3 py-1">
<span class="font-mono">{{ w }}</span>
<span class="font-mono text-muted-foreground">{{ n }} </span>
</div>
<div v-if="topWords.length === 0" class="px-3 py-2 text-muted-foreground">无内容</div>
</div>
</div>
</div>
</template>
</div>
</template>
+211
View File
@@ -0,0 +1,211 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import ResultArea from '../components/ResultArea.vue'
const input = ref('#3b82f6')
const alpha = ref(1)
interface Rgb {
r: number
g: number
b: number
}
function clampByte(v: number): number {
return Math.min(255, Math.max(0, Math.round(v)))
}
function parseColor(s: string): Rgb | null {
const v = s.trim().toLowerCase()
if (!v) return null
// #rgb / #rgba / #rrggbb / #rrggbbaa
const hex = v.match(/^#?([0-9a-f]{3,8})$/)
if (hex) {
const h = hex[1]
if (h.length === 3 || h.length === 4) {
const [r, g, b] = [h[0], h[1], h[2]].map(c => parseInt(c + c, 16))
return { r, g, b }
}
if (h.length === 6 || h.length === 8) {
return {
r: parseInt(h.slice(0, 2), 16),
g: parseInt(h.slice(2, 4), 16),
b: parseInt(h.slice(4, 6), 16)
}
}
return null
}
// rgb() / rgba()
const rgb = v.match(/^rgba?\(\s*(\d{1,3})[\s,]+(\d{1,3})[\s,]+(\d{1,3})/)
if (rgb) {
return { r: clampByte(Number(rgb[1])), g: clampByte(Number(rgb[2])), b: clampByte(Number(rgb[3])) }
}
// hsl() / hsla()
const hsl = v.match(/^hsla?\(\s*(\d{1,3}(?:\.\d+)?)\s*[,\s]\s*(\d{1,3})%\s*[,\s]\s*(\d{1,3})%/)
if (hsl) {
return hslToRgb(Number(hsl[1]), Number(hsl[2]) / 100, Number(hsl[3]) / 100)
}
return null
}
function hslToRgb(h: number, s: number, l: number): Rgb {
h = ((h % 360) + 360) % 360
const c = (1 - Math.abs(2 * l - 1)) * s
const x = c * (1 - Math.abs(((h / 60) % 2) - 1))
const m = l - c / 2
let r = 0, g = 0, b = 0
if (h < 60) { r = c; g = x }
else if (h < 120) { r = x; g = c }
else if (h < 180) { g = c; b = x }
else if (h < 240) { g = x; b = c }
else if (h < 300) { r = x; b = c }
else { r = c; b = x }
return { r: clampByte((r + m) * 255), g: clampByte((g + m) * 255), b: clampByte((b + m) * 255) }
}
function rgbToHsl({ r, g, b }: Rgb): { h: number; s: number; l: number } {
const rn = r / 255, gn = g / 255, bn = b / 255
const max = Math.max(rn, gn, bn)
const min = Math.min(rn, gn, bn)
const l = (max + min) / 2
let h = 0
let s = 0
if (max !== min) {
const d = max - min
s = l > 0.5 ? d / (2 - max - min) : d / (max + min)
if (max === rn) h = ((gn - bn) / d + (gn < bn ? 6 : 0)) * 60
else if (max === gn) h = ((bn - rn) / d + 2) * 60
else h = ((rn - gn) / d + 4) * 60
}
return { h: Math.round(h), s: Math.round(s * 100), l: Math.round(l * 100) }
}
function rgbToHsv({ r, g, b }: Rgb): { h: number; s: number; v: number } {
const rn = r / 255, gn = g / 255, bn = b / 255
const max = Math.max(rn, gn, bn)
const min = Math.min(rn, gn, bn)
const d = max - min
let h = 0
if (d !== 0) {
if (max === rn) h = (((gn - bn) / d) % 6) * 60
else if (max === gn) h = ((bn - rn) / d + 2) * 60
else h = ((rn - gn) / d + 4) * 60
}
h = Math.round(((h % 360) + 360) % 360)
return { h, s: Math.round((max === 0 ? 0 : d / max) * 100), v: Math.round(max * 100) }
}
function toHex({ r, g, b }: Rgb): string {
return '#' + [r, g, b].map(x => x.toString(16).padStart(2, '0')).join('')
}
const rgb = computed<Rgb | null>(() => parseColor(input.value))
const alphaInput = computed(() => {
const a = Math.min(1, Math.max(0, alpha.value))
return Math.round(a * 255)
.toString(16)
.padStart(2, '0')
})
const formats = computed(() => {
const c = rgb.value
if (!c) return null
const hsl = rgbToHsl(c)
const hsv = rgbToHsv(c)
return {
hex: toHex(c),
hexA: `${toHex(c)}${alphaInput.value}`,
rgb: `rgb(${c.r}, ${c.g}, ${c.b})`,
rgba: `rgba(${c.r}, ${c.g}, ${c.b}, ${alpha.value})`,
hsl: `hsl(${hsl.h}, ${hsl.s}%, ${hsl.l}%)`,
hsla: `hsla(${hsl.h}, ${hsl.s}%, ${hsl.l}%, ${alpha.value})`,
hsv: `hsv(${hsv.h}, ${hsv.s}%, ${hsv.v}%)`,
cmyk: rgbToCmyk(c)
}
})
function rgbToCmyk({ r, g, b }: Rgb): string {
const rn = r / 255, gn = g / 255, bn = b / 255
const k = 1 - Math.max(rn, gn, bn)
if (k === 1) return 'cmyk(0%, 0%, 0%, 100%)'
const c = (1 - rn - k) / (1 - k)
const m = (1 - gn - k) / (1 - k)
const y = (1 - bn - k) / (1 - k)
const p = (x: number) => Math.round(x * 100)
return `cmyk(${p(c)}%, ${p(m)}%, ${p(y)}%, ${p(k)}%)`
}
// 亮度判断(W3C 公式),用于预览色上的文字颜色
const previewTextLight = computed(() => {
const c = rgb.value
if (!c) return true
return (c.r * 0.299 + c.g * 0.587 + c.b * 0.114) < 140
})
// 明暗梯度
const shades = computed(() => {
const c = rgb.value
if (!c) return []
const hsl = rgbToHsl(c)
return [-60, -40, -20, 0, 20, 40, 60].map(delta => {
const l = Math.min(96, Math.max(4, hsl.l + delta))
const rgb2 = hslToRgb(hsl.h, hsl.s / 100, l / 100)
return { label: delta === 0 ? `${l}%` : `${l}%`, color: toHex(rgb2) }
})
})
</script>
<template>
<div class="flex flex-col gap-4">
<div class="flex items-end gap-3 flex-wrap">
<div class="flex flex-col gap-1.5 flex-1 min-w-[200px]">
<Label class="text-xs">颜色支持 #hex / rgb() / hsl()</Label>
<Input v-model="input" placeholder="#3b82f6 或 rgb(59,130,246) 或 hsl(217,91%,60%)" class="font-mono text-sm" />
</div>
<div class="flex flex-col gap-1.5">
<Label class="text-xs">透明度 {{ alpha.toFixed(2) }}</Label>
<input v-model.number="alpha" type="range" min="0" max="1" step="0.01" class="w-40 accent-primary" />
</div>
</div>
<template v-if="formats && rgb">
<!-- 预览 -->
<div
class="rounded-md border border-border h-20 flex items-center justify-center font-mono text-sm"
:style="{ backgroundColor: `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${alpha})`, color: previewTextLight ? '#ffffff' : '#000000' }"
>
{{ formats.hex }} {{ alpha < 1 ? `(透明度 ${alpha.toFixed(2)}` : '' }}
</div>
<ResultArea :text="formats.hex" label="HEX" placeholder="HEX" minHeight="60px" />
<ResultArea v-if="alpha < 1" :text="formats.hexA" label="HEX + Alpha" placeholder="HEX" minHeight="60px" />
<ResultArea :text="formats.rgb" label="RGB" placeholder="RGB" minHeight="60px" />
<ResultArea v-if="alpha < 1" :text="formats.rgba" label="RGBA" placeholder="RGBA" minHeight="60px" />
<ResultArea :text="formats.hsl" label="HSL" placeholder="HSL" minHeight="60px" />
<ResultArea v-if="alpha < 1" :text="formats.hsla" label="HSLA" placeholder="HSLA" minHeight="60px" />
<ResultArea :text="formats.hsv" label="HSV" placeholder="HSV" minHeight="60px" />
<ResultArea :text="formats.cmyk" label="CMYK" placeholder="CMYK" minHeight="60px" />
<!-- 明暗梯度 -->
<div class="flex flex-col gap-1.5">
<Label class="text-xs">明暗梯度</Label>
<div class="flex rounded-md overflow-hidden border border-border h-10">
<div
v-for="(s, i) in shades"
:key="i"
class="flex-1 flex items-center justify-center text-[10px] font-mono cursor-pointer"
:style="{ backgroundColor: s.color, color: i < 3 ? '#fff' : '#000' }"
:title="s.color"
@click="input = s.color"
>
{{ s.label }}
</div>
</div>
</div>
</template>
<p v-else-if="input" class="text-xs text-destructive">无法识别的颜色格式支持 #hex / rgb() / rgba() / hsl() / hsla()</p>
</div>
</template>
+228
View File
@@ -0,0 +1,228 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import ResultArea from '../components/ResultArea.vue'
const expr = ref('*/5 * * * *')
interface FieldMatcher {
/** 该字段是否为非通配(受限) */
restricted: boolean
match(v: number): boolean
}
function parseField(field: string, min: number, max: number): FieldMatcher {
const values = new Set<number>()
let restricted = false
for (const part of field.split(',')) {
const [rangePart, stepPart] = part.split('/')
const step = stepPart ? Number(stepPart) : 1
if (!Number.isFinite(step) || step < 1) throw new Error(`非法步长:${part}`)
let lo: number
let hi: number
if (rangePart === '*') {
if (!stepPart) {
// 纯通配:匹配任意值(不受限)
return { restricted: false, match: () => true }
}
lo = min
hi = max
} else if (rangePart.includes('-')) {
const [a, b] = rangePart.split('-').map(Number)
if (!Number.isFinite(a) || !Number.isFinite(b) || a < min || b > max || a > b) {
throw new Error(`非法范围:${part}(应在 ${min}-${max} 内)`)
}
lo = a
hi = b
} else {
const n = Number(rangePart)
if (!Number.isFinite(n) || n < min || n > max) {
throw new Error(`非法值:${part}(应在 ${min}-${max} 内)`)
}
lo = n
hi = n
}
restricted = true
for (let v = lo; v <= hi; v += step) values.add(v)
}
if (values.size === 0) throw new Error(`空字段:${field}`)
return { restricted, match: v => values.has(v) }
}
const FIELD_NAMES = ['分钟', '小时', '日', '月', '星期'] as const
// 星期允许 0-7(0 与 7 均为周日)
const FIELD_RANGES: Array<[number, number]> = [[0, 59], [0, 23], [1, 31], [1, 12], [0, 7]]
const DOW_NAMES = ['日', '一', '二', '三', '四', '五', '六']
/** 支持英文别名(星期/月份)与中文星期 */
function normalizeExpr(s: string): string {
const DOW_MAP: Record<string, string> = {
sun: '0', mon: '1', tue: '2', wed: '3', thu: '4', fri: '5', sat: '6',
'日': '0', '一': '1', '二': '2', '三': '3', '四': '4', '五': '5', '六': '6'
}
const MON_MAP: Record<string, string> = {
jan: '1', feb: '2', mar: '3', apr: '4', may: '5', jun: '6',
jul: '7', aug: '8', sep: '9', oct: '10', nov: '11', dec: '12'
}
let out = s.trim().toLowerCase()
for (const [k, v] of Object.entries(MON_MAP)) {
out = out.split(k).join(v)
}
for (const [k, v] of Object.entries(DOW_MAP)) {
out = out.split(k).join(v)
}
return out
}
interface CronParsed {
minute: FieldMatcher
hour: FieldMatcher
dom: FieldMatcher
month: FieldMatcher
dow: FieldMatcher
domRestricted: boolean
dowRestricted: boolean
}
function parseCron(s: string): CronParsed {
const parts = normalizeExpr(s).split(/\s+/)
if (parts.length !== 5) {
throw new Error(`应为 5 个字段(分 时 日 月 周),当前 ${parts.length}`)
}
const [minute, hour, dom, month, dowRaw] = parts.map((p, i) => parseField(p, FIELD_RANGES[i][0], FIELD_RANGES[i][1]))
// cron 标准允许星期用 0-7,其中 0 与 7 均为周日
const dow: FieldMatcher = {
restricted: dowRaw.restricted,
match: v => dowRaw.match(v) || (v === 0 && dowRaw.match(7))
}
return {
minute, hour, dom, month, dow,
domRestricted: dom.restricted,
dowRestricted: dow.restricted
}
}
/** 标准 cron 语义:日 与 星期 都受限时,任一匹配即可 */
function matches(p: CronParsed, d: Date): boolean {
if (!p.minute.match(d.getMinutes())) return false
if (!p.hour.match(d.getHours())) return false
if (!p.month.match(d.getMonth() + 1)) return false
const domOk = p.dom.match(d.getDate())
const dowOk = p.dow.match(d.getDay())
if (p.domRestricted && p.dowRestricted) return domOk || dowOk
return domOk && dowOk
}
function nextRuns(p: CronParsed, from: Date, n: number): Date[] {
const out: Date[] = []
const t = new Date(from.getTime())
t.setSeconds(0, 0)
t.setMinutes(t.getMinutes() + 1)
// 最多向前扫描 5 年(处理 2 月 29 日等罕见窗口)
const limit = new Date(from.getTime() + 5 * 365.25 * 24 * 3600 * 1000)
while (out.length < n && t < limit) {
if (matches(p, t)) out.push(new Date(t.getTime()))
t.setMinutes(t.getMinutes() + 1)
}
return out
}
const pad = (x: number) => String(x).padStart(2, '0')
function fmt(d: Date): string {
const week = `${DOW_NAMES[d.getDay()]}`
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())} ${week}`
}
const parsed = computed<{ runs: string[]; fields: string[] } | null>(() => {
const s = expr.value.trim()
if (!s) return null
try {
const p = parseCron(s)
const runs = nextRuns(p, new Date(), 6)
const fields = s.split(/\s+/)
return { runs: runs.map(fmt), fields }
} catch {
return null
}
})
const error = computed(() => {
const s = expr.value.trim()
if (!s) return ''
try {
parseCron(s)
return ''
} catch (e) {
return String(e instanceof Error ? e.message : e)
}
})
/** 人类可读的字段说明 */
const fieldDesc = computed<string[]>(() => {
const s = expr.value.trim()
if (!s || error.value) return []
const fields = normalizeExpr(s).split(/\s+/)
return fields.map((f, i) => {
if (f === '*') return `${FIELD_NAMES[i]}:任意`
return `${FIELD_NAMES[i]}${f}`
})
})
const EXAMPLES = [
{ expr: '*/5 * * * *', desc: '每 5 分钟' },
{ expr: '0 * * * *', desc: '每小时整点' },
{ expr: '30 9 * * 1-5', desc: '工作日 9:30' },
{ expr: '0 0 1 * *', desc: '每月 1 日零点' },
{ expr: '0 12 */2 * *', desc: '每 2 天的 12:00' }
]
</script>
<template>
<div class="flex flex-col gap-4">
<div class="flex flex-col gap-1.5">
<Label class="text-xs">Cron 表达式 支持英文/中文星期与英文月份</Label>
<Input v-model="expr" placeholder="*/5 * * * *" class="font-mono text-sm" :class="{ 'border-destructive': !!error }" />
<div class="flex items-center gap-2 flex-wrap">
<button
v-for="ex in EXAMPLES"
:key="ex.expr"
type="button"
class="text-xs px-2 py-0.5 rounded border border-border text-muted-foreground hover:text-foreground cursor-pointer transition-colors"
@click="expr = ex.expr"
>
{{ ex.desc }}
</button>
</div>
</div>
<p v-if="error" class="text-xs text-destructive">{{ error }}</p>
<template v-if="parsed">
<div class="flex flex-col gap-1.5">
<Label class="text-xs">字段拆解</Label>
<div class="rounded-md border border-border divide-y divide-border text-xs">
<div v-for="(f, i) in parsed.fields" :key="i" class="flex gap-3 px-3 py-1.5">
<span class="w-12 shrink-0 text-muted-foreground">{{ FIELD_NAMES[i] }}</span>
<span class="font-mono">{{ f }}</span>
<span class="ml-auto text-muted-foreground">{{ fieldDesc[i]?.split('')[1] ?? '' }}</span>
</div>
</div>
</div>
<div class="flex flex-col gap-1.5">
<Label class="text-xs">接下来 6 次执行时间</Label>
<div class="rounded-md border border-border divide-y divide-border text-xs font-mono">
<div v-for="(r, i) in parsed.runs" :key="i" class="px-3 py-1.5 flex gap-3">
<span class="text-muted-foreground w-4">+{{ i + 1 }}</span>
<span>{{ r }}</span>
</div>
<div v-if="parsed.runs.length === 0" class="px-3 py-2 text-muted-foreground">5 年内无执行时间表达式可能过严 2 30 </div>
</div>
</div>
<ResultArea :text="parsed.runs.join('\n')" label="执行时间列表(可复制)" placeholder="执行时间" />
</template>
<p v-else-if="!expr" class="text-xs text-muted-foreground">输入 5 段式 cron 表达式自动计算接下来 6 次执行时间</p>
</div>
</template>
+146
View File
@@ -0,0 +1,146 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import ResultArea from '../components/ResultArea.vue'
const oldText = ref('')
const newText = ref('')
type Op = 'equal' | 'del' | 'add'
interface DiffLine {
op: Op
oldLine: string
line: string
newLine: string
}
// LCS DP 为 O(n·m),行数过大会卡死 UI;超过上限停止计算并提示
const MAX_LINES = 3000
// 先裁剪公共前缀/后缀,LCS 只算中间差异部分(典型场景提速明显)
function diffLines(a: string[], b: string[]): DiffLine[] {
const out: DiffLine[] = []
let start = 0
while (start < a.length && start < b.length && a[start] === b[start]) {
out.push({ op: 'equal', oldLine: a[start], line: a[start], newLine: b[start] })
start++
}
let endA = a.length, endB = b.length
while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {
endA--
endB--
}
const mid = lcsDiff(a.slice(start, endA), b.slice(start, endB))
// 后缀公共部分:a[endA..] 与 b[endB..] 逐行配对
const suffix: DiffLine[] = []
for (let i = a.length - 1; i >= endA; i--) {
const j = endB + (i - endA)
suffix.unshift({ op: 'equal', oldLine: a[i], line: a[i], newLine: b[j] })
}
return [...out, ...mid, ...suffix]
}
function lcsDiff(a: string[], b: string[]): DiffLine[] {
const n = a.length
const m = b.length
if (n === 0) return b.map(line => ({ op: 'add' as const, oldLine: '', line, newLine: '' }))
if (m === 0) return a.map(line => ({ op: 'del' as const, oldLine: line, line, newLine: '' }))
// LCS DP
const dp: number[][] = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0))
for (let i = n - 1; i >= 0; i--) {
for (let j = m - 1; j >= 0; j--) {
dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1])
}
}
const out: DiffLine[] = []
let i = 0
let j = 0
while (i < n && j < m) {
if (a[i] === b[j]) {
out.push({ op: 'equal', oldLine: a[i], line: a[i], newLine: b[j] })
i++
j++
} else if (dp[i + 1][j] >= dp[i][j + 1]) {
out.push({ op: 'del', oldLine: a[i], line: a[i], newLine: '' })
i++
} else {
out.push({ op: 'add', oldLine: '', line: b[j], newLine: b[j] })
j++
}
}
while (i < n) {
out.push({ op: 'del', oldLine: a[i], line: a[i], newLine: '' })
i++
}
while (j < m) {
out.push({ op: 'add', oldLine: '', line: b[j], newLine: b[j] })
j++
}
return out
}
const tooLarge = computed(() =>
oldText.value.split('\n').length > MAX_LINES || newText.value.split('\n').length > MAX_LINES
)
const lines = computed(() => {
if (tooLarge.value) return []
return diffLines(oldText.value.split('\n'), newText.value.split('\n'))
})
const stats = computed(() => {
let adds = 0
let dels = 0
for (const l of lines.value) {
if (l.op === 'add') adds++
else if (l.op === 'del') dels++
}
return { adds, dels }
})
const unifiedText = computed(() => {
if (lines.value.length === 0) return ''
return lines.value
.map(l => (l.op === 'add' ? '+' : l.op === 'del' ? '-' : ' ') + l.line)
.join('\n')
})
</script>
<template>
<div class="flex flex-col gap-4">
<div class="grid grid-cols-2 gap-3">
<div class="flex flex-col gap-1.5">
<Label class="text-xs text-red-500">旧文本删除 {{ stats.dels }} </Label>
<Textarea v-model="oldText" placeholder="旧文本..." class="min-h-[140px] font-mono text-xs resize-y" />
</div>
<div class="flex flex-col gap-1.5">
<Label class="text-xs text-green-500">新文本新增 {{ stats.adds }} </Label>
<Textarea v-model="newText" placeholder="新文本..." class="min-h-[140px] font-mono text-xs resize-y" />
</div>
</div>
<div class="flex flex-col gap-1.5">
<Label class="text-xs">差异预览</Label>
<div class="rounded-md border border-border max-h-64 overflow-auto font-mono text-xs leading-relaxed">
<div v-if="tooLarge" class="p-3 text-destructive">文本超过 {{ MAX_LINES }} 差异计算已停止LCS 算法复杂度 O(n·m)请缩减输入</div>
<div v-else-if="lines.length === 0 || (oldText === '' && newText === '')" class="p-3 text-muted-foreground">输入两边文本查看差异</div>
<div
v-for="(l, i) in lines"
:key="i"
class="flex whitespace-pre px-2 py-0.5"
:class="{
'bg-red-500/10 text-red-600 dark:text-red-400': l.op === 'del',
'bg-green-500/10 text-green-600 dark:text-green-400': l.op === 'add',
'text-muted-foreground': l.op === 'equal'
}"
>
<span class="w-5 shrink-0 select-none">{{ l.op === 'add' ? '+' : l.op === 'del' ? '-' : ' ' }}</span>
<span class="break-all">{{ l.line }}</span>
</div>
</div>
</div>
<ResultArea :text="unifiedText" label="统一格式(可复制)" placeholder="unified diff" />
</div>
</template>
+64
View File
@@ -0,0 +1,64 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import Segmented from '../components/Segmented.vue'
import ResultArea from '../components/ResultArea.vue'
type Eol = 'CRLF' | 'LF' | 'CR'
const target = ref<Eol>('LF')
const input = ref('')
const detectEol = computed<Eol | 'mixed' | 'none'>(() => {
const v = input.value
if (!v) return 'none'
// 注意:\r\n 中的 \n 也会命中 /\n/,必须用负向后顾排除 CRLF 中的 LF
const hasCrlf = v.includes('\r\n')
const hasLfOnly = /(?<!\r)\n/.test(v)
const hasCrOnly = /\r(?!\n)/.test(v)
if (!hasCrlf && !hasLfOnly && !hasCrOnly) return 'none'
if (hasCrlf && !hasLfOnly && !hasCrOnly) return 'CRLF'
if (!hasCrlf && hasLfOnly && !hasCrOnly) return 'LF'
if (!hasCrlf && !hasLfOnly && hasCrOnly) return 'CR'
return 'mixed'
})
const detectLabel: Record<string, string> = {
CRLF: 'CRLFWindows',
LF: 'LFUnix / macOS',
CR: 'CR(旧 Mac',
mixed: '混合',
none: '未检测到换行符'
}
const output = computed(() => {
const v = input.value
if (!v) return ''
const sep = target.value === 'CRLF' ? '\r\n' : target.value === 'LF' ? '\n' : '\r'
return v.replace(/\r\n|\r|\n/g, sep)
})
</script>
<template>
<div class="flex flex-col gap-4">
<Segmented
v-model="target"
label="目标行尾符"
:options="[
{ value: 'CRLF', label: 'CRLF (\\r\\n)' },
{ value: 'LF', label: 'LF (\\n)' },
{ value: 'CR', label: 'CR (\\r)' }
]"
/>
<p class="text-xs text-muted-foreground">当前检测<span class="font-medium">{{ detectLabel[detectEol] }}</span></p>
<div class="flex flex-col gap-1.5">
<Label class="text-xs">原文</Label>
<Textarea v-model="input" placeholder="在此输入..." class="min-h-[160px] font-mono text-xs resize-y" />
</div>
<ResultArea :text="output" placeholder="结果" />
</div>
</template>
+103
View File
@@ -0,0 +1,103 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { ArrowDownUp } from '@lucide/vue'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { Button } from '@/components/ui/button'
import Segmented from '../components/Segmented.vue'
import ResultArea from '../components/ResultArea.vue'
const type = ref<'html' | 'json'>('html')
const mode = ref<'encode' | 'decode'>('encode')
const input = ref('')
function htmlEncode(s: string): string {
return s
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;')
}
function htmlDecode(s: string): string {
return s
.replace(/&amp;/g, '&')
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&quot;/g, '"')
.replace(/&#39;|&#x27;/g, "'")
.replace(/&nbsp;|&#160;/g, ' ')
}
function jsonEncode(s: string): string {
return JSON.stringify(s).slice(1, -1)
}
function jsonDecode(s: string): string {
// 粘贴的原文可能含真实换行等控制字符,直接拼进 JSON 字符串会解析失败;
// 仅转义控制字符(已转义的反斜杠序列不受影响,其中的控制字符不是裸的)
const escaped = s.replace(/[\u0000-\u001f]/g, c => {
const map: Record<string, string> = { '\n': '\\n', '\r': '\\r', '\t': '\\t', '\b': '\\b', '\f': '\\f' }
return map[c] ?? '\\u' + c.charCodeAt(0).toString(16).padStart(4, '0')
})
return JSON.parse('"' + escaped + '"')
}
const output = computed(() => {
const v = input.value
if (!v) return { text: '', error: '' }
try {
if (type.value === 'html') {
return { text: mode.value === 'encode' ? htmlEncode(v) : htmlDecode(v), error: '' }
}
return { text: mode.value === 'encode' ? jsonEncode(v) : jsonDecode(v), error: '' }
} catch (e) {
return { text: '', error: '转换失败:' + String(e) }
}
})
const swap = () => {
if (output.value.text) {
input.value = output.value.text
mode.value = mode.value === 'encode' ? 'decode' : 'encode'
}
}
</script>
<template>
<div class="flex flex-col gap-4">
<div class="flex items-center justify-between flex-wrap gap-3">
<div class="flex items-center gap-3 flex-wrap">
<Segmented
v-model="type"
label="类型"
:options="[
{ value: 'html', label: 'HTML' },
{ value: 'json', label: 'JSON 字符串' }
]"
/>
<Segmented
v-model="mode"
label="操作"
:options="[
{ value: 'encode', label: '转义' },
{ value: 'decode', label: '反转义' }
]"
/>
</div>
<Button size="sm" variant="outline" class="h-8 text-sm gap-1" :disabled="!output.text" @click="swap">
<ArrowDownUp class="size-3.5" />
结果回填
</Button>
</div>
<div class="flex flex-col gap-1.5">
<Label class="text-xs">原文 / 已转义文本</Label>
<Textarea v-model="input" placeholder="在此输入..." class="min-h-[120px] font-mono text-xs resize-y" />
</div>
<ResultArea :text="output.text" placeholder="结果" />
<p v-if="output.error" class="text-xs text-destructive">{{ output.error }}</p>
</div>
</template>
+249
View File
@@ -0,0 +1,249 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { Upload } from '@lucide/vue'
import { Textarea } from '@/components/ui/textarea'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import Segmented from '../components/Segmented.vue'
import ResultArea from '../components/ResultArea.vue'
type HashAlgo = 'MD5' | 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512'
type Source = 'text' | 'file'
const algos: { value: HashAlgo; label: string }[] = [
{ value: 'MD5', label: 'MD5' },
{ value: 'SHA-1', label: 'SHA-1' },
{ value: 'SHA-256', label: 'SHA-256' },
{ value: 'SHA-384', label: 'SHA-384' },
{ value: 'SHA-512', label: 'SHA-512' }
]
const algo = ref<HashAlgo>('SHA-256')
const source = ref<Source>('text')
const uppercase = ref(false)
const useHmac = ref(false)
const hmacKey = ref('')
const input = ref('')
const output = ref('')
const loading = ref(false)
const error = ref('')
// ===== 文件 =====
const file = ref<File | null>(null)
const fileInput = ref<HTMLInputElement | null>(null)
const fileError = ref('')
const FILE_SIZE_LIMIT = 512 * 1024 * 1024 // 512MB 保护上限
function formatSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
if (bytes < 1024 * 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(1)} MB`
return `${(bytes / 1024 / 1024 / 1024).toFixed(2)} GB`
}
async function onFileChange(e: Event) {
const el = e.target as HTMLInputElement
fileError.value = ''
file.value = el.files?.[0] ?? null
await compute()
}
function clearFile() {
file.value = null
if (fileInput.value) fileInput.value.value = ''
void compute()
}
// ===== MD5WebCrypto 不支持,自行实现)=====
function md5(input: Uint8Array): string {
const S = [
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21
]
const K = new Uint32Array(64)
for (let i = 0; i < 64; i++) K[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296)
const len = input.length
const bitLenLo = (len * 8) >>> 0
const bitLenHi = Math.floor(len / 536870912) // len*8 / 2^32
const paddedLen = (((len + 8) >> 6) + 1) * 64
const msg = new Uint8Array(paddedLen)
msg.set(input)
msg[len] = 0x80
const dv = new DataView(msg.buffer)
dv.setUint32(paddedLen - 8, bitLenLo, true)
dv.setUint32(paddedLen - 4, bitLenHi, true)
let a0 = 0x67452301
let b0 = 0xefcdab89
let c0 = 0x98badcfe
let d0 = 0x10325476
const M = new Uint32Array(16)
for (let off = 0; off < paddedLen; off += 64) {
for (let i = 0; i < 16; i++) M[i] = dv.getUint32(off + i * 4, true)
let A = a0, B = b0, C = c0, D = d0
for (let i = 0; i < 64; i++) {
let F: number
let g: number
if (i < 16) { F = (B & C) | (~B & D); g = i }
else if (i < 32) { F = (D & B) | (~D & C); g = (5 * i + 1) % 16 }
else if (i < 48) { F = B ^ C ^ D; g = (3 * i + 5) % 16 }
else { F = C ^ (B | ~D); g = (7 * i) % 16 }
F = (F + A + K[i] + M[g]) >>> 0
A = D
D = C
C = B
B = (B + ((F << S[i]) | (F >>> (32 - S[i])))) >>> 0
}
a0 = (a0 + A) >>> 0
b0 = (b0 + B) >>> 0
c0 = (c0 + C) >>> 0
d0 = (d0 + D) >>> 0
}
const out = new Uint8Array(16)
const odv = new DataView(out.buffer)
odv.setUint32(0, a0, true)
odv.setUint32(4, b0, true)
odv.setUint32(8, c0, true)
odv.setUint32(12, d0, true)
return Array.from(out, b => b.toString(16).padStart(2, '0')).join('')
}
function toHex(buf: ArrayBuffer): string {
return Array.from(new Uint8Array(buf), b => b.toString(16).padStart(2, '0')).join('')
}
async function compute() {
error.value = ''
fileError.value = ''
output.value = ''
if (source.value === 'text') {
const text = input.value
if (!text) return
loading.value = true
try {
const data = new TextEncoder().encode(text)
output.value = await digest(algo.value, data)
} catch (e) {
error.value = '计算失败:' + String(e)
} finally {
loading.value = false
}
} else {
const f = file.value
if (!f) return
if (f.size > FILE_SIZE_LIMIT) {
fileError.value = `文件过大(${formatSize(f.size)}),请使用 512MB 以内的文件`
return
}
loading.value = true
try {
const data = new Uint8Array(await f.arrayBuffer())
output.value = await digest(algo.value, data)
} catch (e) {
error.value = '计算失败:' + String(e)
} finally {
loading.value = false
}
}
}
async function digest(algorithm: HashAlgo, data: Uint8Array): Promise<string> {
let hex: string
if (algorithm === 'MD5') {
hex = md5(data)
} else {
hex = toHex(await crypto.subtle.digest(algorithm, data))
}
if (useHmac.value) {
if (algorithm === 'MD5') {
throw new Error('HMAC 不支持 MD5,请选择 SHA 系列算法')
}
const enc = new TextEncoder()
const key = await crypto.subtle.importKey(
'raw', enc.encode(hmacKey.value),
{ name: 'HMAC', hash: { name: algorithm } },
false, ['sign']
)
hex = toHex(await crypto.subtle.sign('HMAC', key, data))
}
return hex
}
const displayOutput = computed(() =>
uppercase.value ? output.value.toUpperCase() : output.value
)
// 输入、算法、选项、文件变化时自动重算
watch([input, algo, source, uppercase, useHmac, hmacKey], () => {
void compute()
})
// 首次挂载如有初始值则计算(通常为空)
void compute()
</script>
<template>
<div class="flex flex-col gap-4">
<div class="flex items-center gap-3 flex-wrap">
<Segmented
v-model="source"
:options="[
{ value: 'text', label: '文本' },
{ value: 'file', label: '文件' }
]"
/>
<Segmented v-model="algo" label="算法" :options="algos" />
<label class="flex items-center gap-2 text-xs text-muted-foreground cursor-pointer">
大写
<Switch v-model="uppercase" />
</label>
</div>
<div v-if="algo === 'MD5'" class="text-xs text-muted-foreground">
MD5 SHA-1 已不推荐用于安全场景仅用于兼容旧系统或校验比对
</div>
<!-- HMAC -->
<div class="flex flex-col gap-2 rounded-md border border-border p-3">
<label class="flex items-center gap-2 text-xs cursor-pointer w-fit">
<Switch v-model="useHmac" />
<span class="font-medium">HMAC密钥签名</span>
</label>
<div v-if="useHmac" class="flex flex-col gap-1.5">
<Label class="text-xs">密钥</Label>
<Input v-model="hmacKey" placeholder="HMAC 密钥(仅支持 SHA 系列)" class="font-mono text-sm" />
</div>
</div>
<!-- 文本输入 -->
<div v-if="source === 'text'" class="flex flex-col gap-1.5">
<Label class="text-xs">原文文本</Label>
<Textarea v-model="input" placeholder="在此输入文本..." class="min-h-[120px] font-mono text-xs resize-y" />
</div>
<!-- 文件输入 -->
<div v-else class="flex flex-col gap-2">
<Label class="text-xs">选择文件</Label>
<div class="flex items-center gap-2 flex-wrap">
<Button size="sm" variant="outline" class="h-8 text-sm gap-1.5" @click="fileInput?.click()">
<Upload class="size-3.5" />
选择文件
</Button>
<input ref="fileInput" type="file" class="hidden" @change="onFileChange" />
<template v-if="file">
<span class="text-xs font-mono text-muted-foreground">{{ file.name }}{{ formatSize(file.size) }}</span>
<Button size="sm" variant="ghost" class="h-7 text-xs" @click="clearFile">移除</Button>
</template>
</div>
<p v-if="fileError" class="text-xs text-destructive">{{ fileError }}</p>
</div>
<ResultArea :text="loading ? '计算中...' : displayOutput" :label="useHmac ? 'HMAC 摘要(十六进制)' : '摘要(十六进制)'" placeholder="摘要" />
<p v-if="error" class="text-xs text-destructive">{{ error }}</p>
</div>
</template>
@@ -0,0 +1,195 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import Segmented from '../components/Segmented.vue'
type Tab = 'status' | 'mime'
const tab = ref<Tab>('status')
const query = ref('')
interface StatusDef {
code: number
name: string
desc: string
}
const STATUSES: StatusDef[] = [
// 1xx
{ code: 100, name: 'Continue', desc: '客户端应继续请求,常用于 Expect: 100-continue 大文件上传前探测' },
{ code: 101, name: 'Switching Protocols', desc: '服务器同意切换协议(如升级 WebSocket' },
{ code: 102, name: 'Processing', desc: '服务器已收到请求,仍在处理(WebDAV)' },
{ code: 103, name: 'Early Hints', desc: '预加载提示,主响应前先返回 Link 头' },
// 2xx
{ code: 200, name: 'OK', desc: '请求成功' },
{ code: 201, name: 'Created', desc: '请求成功并创建了新资源(POST 之后常见)' },
{ code: 202, name: 'Accepted', desc: '请求已受理,但尚未处理完成(异步任务)' },
{ code: 204, name: 'No Content', desc: '成功但无返回体(DELETE / PUT 常见)' },
{ code: 206, name: 'Partial Content', desc: '范围请求成功(断点续传 / 视频拖动)' },
// 3xx
{ code: 301, name: 'Moved Permanently', desc: '永久重定向,搜索引擎更新链接(GET 保持、POST 可能转 GET' },
{ code: 302, name: 'Found', desc: '临时重定向,浏览器可能将 POST 改为 GET' },
{ code: 303, name: 'See Other', desc: '临时重定向,强制使用 GET 访问新地址' },
{ code: 304, name: 'Not Modified', desc: '缓存有效(协商缓存命中,无返回体)' },
{ code: 307, name: 'Temporary Redirect', desc: '临时重定向,严格保持原请求方法与体' },
{ code: 308, name: 'Permanent Redirect', desc: '永久重定向,严格保持原请求方法与体' },
// 4xx
{ code: 400, name: 'Bad Request', desc: '请求语法错误 / 参数校验失败' },
{ code: 401, name: 'Unauthorized', desc: '未认证(缺少或无效的凭证,应带 WWW-Authenticate 头)' },
{ code: 402, name: 'Payment Required', desc: '要求付费(保留状态码,实际很少使用)' },
{ code: 403, name: 'Forbidden', desc: '已认证但无权限访问该资源' },
{ code: 404, name: 'Not Found', desc: '资源不存在' },
{ code: 405, name: 'Method Not Allowed', desc: '方法不被允许(应返回 Allow 头)' },
{ code: 406, name: 'Not Acceptable', desc: '请求的 Accept 头无法满足内容协商' },
{ code: 408, name: 'Request Timeout', desc: '客户端请求超时' },
{ code: 409, name: 'Conflict', desc: '请求与当前资源状态冲突(并发编辑 / 版本冲突)' },
{ code: 410, name: 'Gone', desc: '资源已永久消失(区别于 404' },
{ code: 412, name: 'Precondition Failed', desc: '前置条件失败(If-Match / If-None-Match 校验不过)' },
{ code: 413, name: 'Content Too Large', desc: '请求体超过服务器限制' },
{ code: 415, name: 'Unsupported Media Type', desc: 'Content-Type 不支持' },
{ code: 418, name: "I'm a teapot", desc: '愚人节彩蛋:我是茶壶' },
{ code: 422, name: 'Unprocessable Content', desc: '语义正确但校验失败(表单校验常用)' },
{ code: 425, name: 'Too Early', desc: '过早重放(防重放攻击)' },
{ code: 428, name: 'Precondition Required', desc: '要求带条件请求头(防丢失更新)' },
{ code: 429, name: 'Too Many Requests', desc: '请求频率超限(限流,应带 Retry-After 头)' },
{ code: 431, name: 'Request Header Fields Too Large', desc: '请求头过大(Cookie 太多常见)' },
{ code: 451, name: 'Unavailable For Legal Reasons', desc: '因法律原因不可提供(审查)' },
// 5xx
{ code: 500, name: 'Internal Server Error', desc: '服务器内部错误(后端异常兜底)' },
{ code: 501, name: 'Not Implemented', desc: '服务器不支持该功能' },
{ code: 502, name: 'Bad Gateway', desc: '网关收到上游无效响应(后端挂了 / 崩溃)' },
{ code: 503, name: 'Service Unavailable', desc: '服务不可用(过载 / 维护中,可带 Retry-After' },
{ code: 504, name: 'Gateway Timeout', desc: '网关等待上游超时(后端太慢)' },
{ code: 505, name: 'HTTP Version Not Supported', desc: 'HTTP 版本不支持' },
{ code: 507, name: 'Insufficient Storage', desc: '存储不足(WebDAV' },
{ code: 508, name: 'Loop Detected', desc: '检测到无限循环(WebDAV' },
{ code: 511, name: 'Network Authentication Required', desc: '需要网络认证(公共 Wi-Fi 门户)' }
]
interface MimeDef {
mime: string
ext: string
desc: string
}
const MIMES: MimeDef[] = [
{ mime: 'text/html', ext: '.html .htm', desc: 'HTML 文档' },
{ mime: 'text/plain', ext: '.txt', desc: '纯文本' },
{ mime: 'text/css', ext: '.css', desc: '样式表' },
{ mime: 'text/javascript', ext: '.js .mjs', desc: 'JavaScript(旧写法 application/javascript' },
{ mime: 'application/json', ext: '.json', desc: 'JSON 数据(API 最常用)' },
{ mime: 'application/xml', ext: '.xml', desc: 'XML 数据' },
{ mime: 'application/yaml', ext: '.yaml .yml', desc: 'YAML 配置' },
{ mime: 'application/toml', ext: '.toml', desc: 'TOML 配置' },
{ mime: 'text/csv', ext: '.csv', desc: '逗号分隔表格' },
{ mime: 'text/markdown', ext: '.md', desc: 'Markdown 文档' },
{ mime: 'image/jpeg', ext: '.jpg .jpeg', desc: 'JPEG 图片(有损压缩)' },
{ mime: 'image/png', ext: '.png', desc: 'PNG 图片(无损,支持透明)' },
{ mime: 'image/gif', ext: '.gif', desc: 'GIF 动图' },
{ mime: 'image/webp', ext: '.webp', desc: 'WebP 图片(现代格式,体积小)' },
{ mime: 'image/svg+xml', ext: '.svg', desc: 'SVG 矢量图' },
{ mime: 'image/avif', ext: '.avif', desc: 'AVIF 图片(新一代压缩)' },
{ mime: 'image/x-icon', ext: '.ico', desc: '网站图标' },
{ mime: 'audio/mpeg', ext: '.mp3', desc: 'MP3 音频' },
{ mime: 'audio/ogg', ext: '.ogg', desc: 'OGG 音频' },
{ mime: 'audio/wav', ext: '.wav', desc: 'WAV 无损音频' },
{ mime: 'video/mp4', ext: '.mp4', desc: 'MP4 视频' },
{ mime: 'video/webm', ext: '.webm', desc: 'WebM 视频' },
{ mime: 'video/x-matroska', ext: '.mkv', desc: 'MKV 视频' },
{ mime: 'application/pdf', ext: '.pdf', desc: 'PDF 文档' },
{ mime: 'application/zip', ext: '.zip', desc: 'ZIP 压缩包' },
{ mime: 'application/x-7z-compressed', ext: '.7z', desc: '7z 压缩包' },
{ mime: 'application/x-rar-compressed', ext: '.rar', desc: 'RAR 压缩包' },
{ mime: 'application/gzip', ext: '.gz', desc: 'GZip 压缩' },
{ mime: 'application/x-tar', ext: '.tar', desc: 'TAR 归档' },
{ mime: 'application/octet-stream', ext: '(默认)', desc: '未知二进制(浏览器会下载)' },
{ mime: 'application/wasm', ext: '.wasm', desc: 'WebAssembly 模块' },
{ mime: 'font/woff', ext: '.woff', desc: 'Web 字体(压缩)' },
{ mime: 'font/woff2', ext: '.woff2', desc: 'Web 字体(现代格式)' },
{ mime: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', ext: '.docx', desc: 'Word 文档' },
{ mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', ext: '.xlsx', desc: 'Excel 表格' },
{ mime: 'application/vnd.openxmlformats-officedocument.presentationml.presentation', ext: '.pptx', desc: 'PPT 演示文稿' },
{ mime: 'application/msword', ext: '.doc', desc: 'Word 旧格式' },
{ mime: 'application/vnd.ms-excel', ext: '.xls', desc: 'Excel 旧格式' },
{ mime: 'multipart/form-data', ext: '(表单)', desc: '文件上传表单(带 boundary' },
{ mime: 'application/x-www-form-urlencoded', ext: '(表单)', desc: 'URL 编码表单(默认)' },
{ mime: 'application/grpc', ext: 'RPC', desc: 'gRPC 请求(配合 proto' }
]
const STATUS_CLASS: Record<string, string> = {
'1xx': 'bg-sky-500/10 text-sky-600 dark:text-sky-400 border-sky-500/30',
'2xx': 'bg-green-500/10 text-green-600 dark:text-green-400 border-green-500/30',
'3xx': 'bg-blue-500/10 text-blue-600 dark:text-blue-400 border-blue-500/30',
'4xx': 'bg-amber-500/10 text-amber-600 dark:text-amber-400 border-amber-500/30',
'5xx': 'bg-red-500/10 text-red-600 dark:text-red-400 border-red-500/30'
}
const statusGroups = computed(() => {
const q = query.value.trim().toLowerCase()
const filtered = q
? STATUSES.filter(s => String(s.code).includes(q) || s.name.toLowerCase().includes(q) || s.desc.toLowerCase().includes(q))
: STATUSES
const groups: Array<{ label: string; class: string; items: StatusDef[] }> = []
for (const [label, cls] of Object.entries(STATUS_CLASS)) {
const items = filtered.filter(s => String(s.code).startsWith(label[0]))
if (items.length > 0) groups.push({ label: `${label} ${label === '1xx' ? '信息' : label === '2xx' ? '成功' : label === '3xx' ? '重定向' : label === '4xx' ? '客户端错误' : '服务器错误'}`, class: cls, items })
}
return groups
})
const filteredMimes = computed(() => {
const q = query.value.trim().toLowerCase()
if (!q) return MIMES
return MIMES.filter(m => m.mime.includes(q) || m.ext.includes(q) || m.desc.toLowerCase().includes(q))
})
</script>
<template>
<div class="flex flex-col gap-4">
<div class="flex items-center gap-3 flex-wrap">
<Segmented
v-model="tab"
:options="[
{ value: 'status', label: 'HTTP 状态码' },
{ value: 'mime', label: 'MIME 类型' }
]"
/>
<div class="relative flex-1 min-w-[160px] max-w-xs">
<Input v-model="query" placeholder="搜索…" class="h-8 text-sm" />
</div>
<span class="text-xs text-muted-foreground ml-auto">
{{ tab === 'status' ? `${STATUSES.length} 个状态码` : `${MIMES.length} 个常用类型` }}
</span>
</div>
<!-- 状态码 -->
<template v-if="tab === 'status'">
<div v-for="group in statusGroups" :key="group.label" class="flex flex-col gap-2">
<span class="text-xs font-medium text-muted-foreground">{{ group.label }}</span>
<div class="rounded-md border border-border divide-y divide-border text-xs">
<div v-for="s in group.items" :key="s.code" class="flex items-start gap-3 px-3 py-2">
<Badge variant="outline" :class="['py-0 shrink-0 font-mono', group.class]">{{ s.code }}</Badge>
<div class="flex flex-col gap-0.5 min-w-0">
<span class="font-medium">{{ s.name }}</span>
<span class="text-muted-foreground leading-snug">{{ s.desc }}</span>
</div>
</div>
</div>
</div>
<p v-if="statusGroups.length === 0" class="text-xs text-muted-foreground">没有匹配的状态码</p>
</template>
<!-- MIME -->
<template v-else>
<div class="rounded-md border border-border divide-y divide-border text-xs">
<div v-for="m in filteredMimes" :key="m.mime" class="flex items-start gap-3 px-3 py-2">
<span class="font-mono text-primary break-all w-64 shrink-0">{{ m.mime }}</span>
<span class="font-mono text-muted-foreground w-20 shrink-0">{{ m.ext }}</span>
<span class="text-muted-foreground min-w-0">{{ m.desc }}</span>
</div>
<div v-if="filteredMimes.length === 0" class="px-3 py-2 text-muted-foreground">没有匹配的 MIME 类型</div>
</div>
</template>
</div>
</template>
+189
View File
@@ -0,0 +1,189 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import Segmented from '../components/Segmented.vue'
import ResultArea from '../components/ResultArea.vue'
type Tab = 'cidr' | 'convert'
const tab = ref<Tab>('cidr')
// ===== CIDR 计算 =====
const cidrInput = ref('192.168.1.0/24')
function parseIPv4(s: string): bigint | null {
const parts = s.trim().split('.')
if (parts.length !== 4) return null
let n = 0n
for (const p of parts) {
if (!/^\d{1,3}$/.test(p)) return null
const v = Number(p)
if (v > 255) return null
n = (n << 8n) | BigInt(v)
}
return n
}
function ipToString(n: bigint): string {
return [24n, 16n, 8n, 0n].map(shift => String((n >> shift) & 0xffn)).join('.')
}
const cidr = computed(() => {
const s = cidrInput.value.trim()
if (!s) return null
const [ipPart, maskPart] = s.split('/')
const ip = parseIPv4(ipPart)
if (ip === null) return { error: 'IPv4 地址格式不正确' }
let prefix: number
if (maskPart === undefined) {
prefix = 24
} else {
prefix = Number(maskPart)
if (!Number.isInteger(prefix) || prefix < 0 || prefix > 32) {
return { error: '前缀长度应在 0-32 之间' }
}
}
const mask = prefix === 0 ? 0n : (0xffffffffn << BigInt(32 - prefix)) & 0xffffffffn
const network = ip & mask
const broadcast = network | (~mask & 0xffffffffn)
const total = 1n << BigInt(32 - prefix)
// 主机数:/31 无主机位(点对点),/32 单主机
const hosts = prefix >= 31 ? total : total - 2n
const firstHost = prefix >= 31 ? network : network + 1n
const lastHost = prefix >= 31 ? broadcast : broadcast - 1n
const wildcard = ~mask & 0xffffffffn
// 私有地址判断
const privateNote =
(ip >> 24n) === 10n ? 'A 类私有(10.0.0.0/8'
: (ip >> 20n) === 0xac1n ? 'B 类私有(172.16.0.0/12'
: (ip >> 16n) === 0xc0a8n ? 'C 类私有(192.168.0.0/16'
: (ip >> 28n) === 14n ? '环回/保留(240.0.0.0/4'
: ip === 0n ? '未指定地址'
: (ip >> 24n) === 127n ? '环回地址(127.0.0.0/8'
: (ip >> 24n) === 169n && (ip >> 16n) === 0xa9fen ? '链路本地(169.254.0.0/16'
: '公网地址'
return {
error: '',
network: ipToString(network),
broadcast: ipToString(broadcast),
mask: ipToString(mask),
wildcard: ipToString(wildcard),
firstHost: ipToString(firstHost),
lastHost: ipToString(lastHost),
hosts: hosts.toLocaleString(),
total: total.toLocaleString(),
prefix,
isAligned: (ip & mask) === network,
ipIsNetwork: ip === network,
privateNote,
binaryMask: ipToString(mask).split('.').map(p => Number(p).toString(2).padStart(8, '0')).join('.')
}
})
// ===== IP ↔ 整数互转 =====
const convertInput = ref('192.168.1.1')
const converted = computed(() => {
const s = convertInput.value.trim()
if (!s) return null
const ip = parseIPv4(s)
if (ip !== null) {
return {
dec: ip.toString(),
hex: '0x' + ip.toString(16).padStart(8, '0').toUpperCase(),
oct: ip.toString(8),
bin: ip.toString(2).padStart(32, '0').replace(/(.{8})(?=.)/g, '$1 '),
binaryMask: ''
}
}
// 尝试十进制整数
if (/^\d+$/.test(s)) {
const n = BigInt(s)
if (n <= 0xffffffffn) {
return { dec: s, hex: '0x' + n.toString(16).padStart(8, '0').toUpperCase(), oct: n.toString(8), bin: n.toString(2).padStart(32, '0').replace(/(.{8})(?=.)/g, '$1 '), binaryMask: '' }
}
}
return null
})
</script>
<template>
<div class="flex flex-col gap-4">
<Segmented
v-model="tab"
:options="[
{ value: 'cidr', label: 'CIDR 子网计算' },
{ value: 'convert', label: 'IP ↔ 整数' }
]"
/>
<!-- CIDR -->
<template v-if="tab === 'cidr'">
<div class="flex flex-col gap-1.5">
<Label class="text-xs">IPv4 地址 / 前缀 192.168.1.100/26</Label>
<Input v-model="cidrInput" placeholder="192.168.1.0/24" class="font-mono text-sm" />
</div>
<template v-if="cidr">
<p v-if="cidr.error" class="text-xs text-destructive">{{ cidr.error }}</p>
<template v-else>
<p v-if="!cidr.ipIsNetwork" class="text-xs text-amber-600 dark:text-amber-400">
注意输入地址不是该子网的网络地址已按网络 {{ cidr.network }}/{{ cidr.prefix }} 计算
</p>
<div class="rounded-md border border-border divide-y divide-border text-xs">
<div class="flex gap-3 px-3 py-1.5">
<span class="w-24 shrink-0 text-muted-foreground">网络地址</span>
<span class="font-mono">{{ cidr.network }}/{{ cidr.prefix }}</span>
</div>
<div class="flex gap-3 px-3 py-1.5">
<span class="w-24 shrink-0 text-muted-foreground">子网掩码</span>
<span class="font-mono">{{ cidr.mask }}</span>
</div>
<div class="flex gap-3 px-3 py-1.5">
<span class="w-24 shrink-0 text-muted-foreground">掩码二进制</span>
<span class="font-mono break-all">{{ cidr.binaryMask }}</span>
</div>
<div class="flex gap-3 px-3 py-1.5">
<span class="w-24 shrink-0 text-muted-foreground">反掩码</span>
<span class="font-mono">{{ cidr.wildcard }}</span>
</div>
<div class="flex gap-3 px-3 py-1.5">
<span class="w-24 shrink-0 text-muted-foreground">广播地址</span>
<span class="font-mono">{{ cidr.broadcast }}</span>
</div>
<div class="flex gap-3 px-3 py-1.5">
<span class="w-24 shrink-0 text-muted-foreground">可用主机范围</span>
<span class="font-mono">{{ cidr.firstHost }} ~ {{ cidr.lastHost }}</span>
</div>
<div class="flex gap-3 px-3 py-1.5">
<span class="w-24 shrink-0 text-muted-foreground">可用主机数</span>
<span class="font-mono">{{ cidr.hosts }}地址总数 {{ cidr.total }}</span>
</div>
<div class="flex gap-3 px-3 py-1.5">
<span class="w-24 shrink-0 text-muted-foreground">地址类型</span>
<span>{{ cidr.privateNote }}</span>
</div>
</div>
</template>
</template>
<p v-else class="text-xs text-muted-foreground">输入 IPv4 地址与 CIDR 前缀自动计算子网信息</p>
</template>
<!-- IP 整数 -->
<template v-else>
<div class="flex flex-col gap-1.5">
<Label class="text-xs">IP 地址或无符号整数</Label>
<Input v-model="convertInput" placeholder="192.168.1.1 或 3232235777" class="font-mono text-sm" />
</div>
<template v-if="converted">
<ResultArea :text="converted.dec" label="十进制整数" placeholder="十进制" minHeight="60px" />
<ResultArea :text="converted.hex" label="十六进制" placeholder="十六进制" minHeight="60px" />
<ResultArea :text="converted.oct" label="八进制" placeholder="八进制" minHeight="60px" />
<ResultArea :text="converted.bin" label="二进制" placeholder="二进制" minHeight="60px" />
</template>
<p v-else-if="convertInput" class="text-xs text-destructive">无法识别的输入支持 IPv4 地址或 0-4294967295 整数</p>
</template>
</div>
</template>
+96
View File
@@ -0,0 +1,96 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import Segmented from '../components/Segmented.vue'
import ResultArea from '../components/ResultArea.vue'
const mode = ref<'format' | 'minify'>('format')
const indent = ref('2')
const sortKeys = ref(false)
const input = ref('')
const result = computed<{ text: string; error: string }>(() => {
const v = input.value.trim()
if (!v) return { text: '', error: '' }
try {
const parsed = JSON.parse(v)
if (mode.value === 'minify') {
return { text: JSON.stringify(parsed), error: '' }
}
return { text: JSON.stringify(parsed, normalizeReplacer(sortKeys.value), Number(indent.value)), error: '' }
} catch (e) {
return { text: '', error: 'JSON 解析失败:' + String(e) }
}
})
const output = computed(() => result.value.text)
const error = computed(() => result.value.error)
const isValid = computed<boolean | null>(() => {
if (!input.value.trim()) return null
try {
JSON.parse(input.value)
return true
} catch {
return false
}
})
/** 深浅不一:sortKeys 时按 key 排序输出 */
function normalizeReplacer(sort: boolean): (this: unknown, key: string, value: unknown) => unknown {
if (!sort) return undefined as never
return function (this: unknown, _key: string, value: unknown) {
if (Array.isArray(value)) return value
if (value && typeof value === 'object') {
const obj = value as Record<string, unknown>
const sorted: Record<string, unknown> = {}
Object.keys(obj)
.sort()
.forEach(k => { sorted[k] = obj[k] })
return sorted
}
return value
}
}
</script>
<template>
<div class="flex flex-col gap-4">
<div class="flex items-center justify-between flex-wrap gap-3">
<div class="flex items-center gap-3 flex-wrap">
<Segmented
v-model="mode"
:options="[
{ value: 'format', label: '美化' },
{ value: 'minify', label: '压缩' }
]"
/>
<Segmented
v-model="indent"
label="缩进"
:options="[
{ value: '2', label: '2' },
{ value: '4', label: '4' },
{ value: '8', label: '8' }
]"
/>
<label class="flex items-center gap-1.5 text-xs text-muted-foreground cursor-pointer">
<input v-model="sortKeys" type="checkbox" class="accent-primary size-3.5" />
键排序
</label>
</div>
</div>
<div class="flex flex-col gap-1.5">
<Label class="text-xs">原始 JSON</Label>
<Textarea v-model="input" placeholder='输入 JSON,如 {"a":1,"b":[true,null]}' class="min-h-[160px] font-mono text-xs resize-y" />
</div>
<div v-if="isValid !== false" class="flex items-center gap-2 text-xs">
<span v-if="isValid === true" class="text-green-600 dark:text-green-400"> 合法 JSON</span>
</div>
<ResultArea :text="output" placeholder="结果" />
<p v-if="error" class="text-xs text-destructive break-all">{{ error }}</p>
</div>
</template>
+131
View File
@@ -0,0 +1,131 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { Badge } from '@/components/ui/badge'
import ResultArea from '../components/ResultArea.vue'
const token = ref('')
const error = ref('')
function base64UrlDecode(s: string): string {
const cleaned = s.replace(/-/g, '+').replace(/_/g, '/')
const pad = cleaned.length % 4
const normalized = pad ? cleaned + '='.repeat(4 - pad) : cleaned
const bin = atob(normalized)
const bytes = Uint8Array.from(bin, ch => ch.charCodeAt(0))
return new TextDecoder().decode(bytes)
}
interface TimeClaim {
name: string
value: string
local: string
status: 'ok' | 'expired' | 'not-yet' | 'unknown'
}
const parsed = computed<{
header: string
payload: string
signature: string
timeClaims: TimeClaim[]
} | null>(() => {
error.value = ''
const t = token.value.trim()
if (!t) return null
const parts = t.split('.')
if (parts.length < 2) {
error.value = 'JWT 格式不正确(应为 header.payload.signature'
return null
}
try {
const header = formatJson(base64UrlDecode(parts[0]))
const payload = formatJson(base64UrlDecode(parts[1]))
const signature = parts[2] ?? ''
return { header, payload, signature, timeClaims: parseTimeClaims(payload) }
} catch (e) {
error.value = '解码失败:' + String(e)
return null
}
})
function formatJson(s: string): string {
let pretty = s
try {
pretty = JSON.stringify(JSON.parse(s), null, 2)
} catch {
/* 非 JSON(如已损毁),原样展示 */
}
return pretty
}
/** 解读 iat / nbf / exp 等时间声明(秒级时间戳) */
function parseTimeClaims(payload: string): TimeClaim[] {
let obj: unknown
try {
obj = JSON.parse(payload)
} catch {
return []
}
if (!obj || typeof obj !== 'object') return []
const p = obj as Record<string, unknown>
const claims: TimeClaim[] = []
const now = Math.floor(Date.now() / 1000)
const NAMES: Record<string, string> = { iat: 'iat(签发时间)', nbf: 'nbf(生效时间)', exp: 'exp(过期时间)' }
const pad = (x: number) => String(x).padStart(2, '0')
for (const key of ['iat', 'nbf', 'exp']) {
const v = p[key]
if (typeof v !== 'number' || !Number.isFinite(v)) continue
const d = new Date(v * 1000)
if (Number.isNaN(d.getTime())) continue
const local = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
let status: TimeClaim['status'] = 'ok'
if (key === 'exp' && v < now) status = 'expired'
else if (key === 'nbf' && v > now) status = 'not-yet'
else if (key === 'iat' && v > now + 60) status = 'unknown'
claims.push({ name: NAMES[key], value: String(v), local, status })
}
return claims
}
const STATUS_BADGE: Record<TimeClaim['status'], { label: string; class: string } | null> = {
ok: null,
expired: { label: '已过期', class: 'bg-red-500/10 text-red-600 dark:text-red-400 border-red-500/30' },
'not-yet': { label: '尚未生效', class: 'bg-amber-500/10 text-amber-600 dark:text-amber-400 border-amber-500/30' },
unknown: { label: '签发时间在未来(时钟偏差?)', class: 'bg-amber-500/10 text-amber-600 dark:text-amber-400 border-amber-500/30' }
}
</script>
<template>
<div class="flex flex-col gap-4">
<div class="flex flex-col gap-1.5">
<Label class="text-xs">JWT Token</Label>
<Textarea
v-model="token"
placeholder="eyJhbGciOi...header.payload.signature"
class="min-h-[70px] font-mono text-xs resize-y break-all"
/>
</div>
<template v-if="parsed">
<ResultArea :text="parsed.header" label="Header" placeholder="Header" />
<ResultArea :text="parsed.payload" label="Payload(载荷)" placeholder="Payload" />
<ResultArea :text="parsed.signature" label="Signature(签名)" placeholder="Signature" />
<div v-if="parsed.timeClaims.length > 0" class="flex flex-col gap-1.5">
<Label class="text-xs">时间声明解读</Label>
<div class="rounded-md border border-border divide-y divide-border text-xs">
<div v-for="c in parsed.timeClaims" :key="c.name" class="flex items-center gap-3 px-3 py-2 flex-wrap">
<span class="font-mono text-muted-foreground">{{ c.name }}</span>
<span class="font-mono">{{ c.local }}</span>
<Badge v-if="STATUS_BADGE[c.status]" variant="outline" :class="['py-0 text-[10px] ml-auto', STATUS_BADGE[c.status]!.class]">
{{ STATUS_BADGE[c.status]!.label }}
</Badge>
</div>
</div>
</div>
</template>
<p v-else-if="!token" class="text-xs text-muted-foreground">在左侧粘贴 JWT下方将自动解析 Header Payload</p>
<p v-else class="text-xs text-destructive">{{ error }}</p>
</div>
</template>
@@ -0,0 +1,165 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { Copy, RefreshCw } from '@lucide/vue'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Button } from '@/components/ui/button'
import { Switch } from '@/components/ui/switch'
import { Textarea } from '@/components/ui/textarea'
const CHARSETS = {
lower: 'abcdefghijklmnopqrstuvwxyz',
upper: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
digits: '0123456789',
symbols: '!@#$%^&*_-+=?',
// 易混淆字符:l/1/I、O/0、等等
ambiguous: 'Il1O0o`\'"|'
}
const length = ref('16')
const count = ref('5')
const useLower = ref(true)
const useUpper = ref(true)
const useDigits = ref(true)
const useSymbols = ref(false)
const excludeAmbiguous = ref(true)
const passwords = ref<string[]>([])
const error = ref('')
const lengthNum = computed(() => {
const n = Math.floor(Number(length.value))
if (!Number.isFinite(n)) return 16
return Math.min(Math.max(n || 0, 4), 128)
})
const countNum = computed(() => {
const n = Math.floor(Number(count.value))
if (!Number.isFinite(n)) return 5
return Math.min(Math.max(n || 0, 1), 100)
})
const charset = computed(() => {
let s = ''
if (useLower.value) s += CHARSETS.lower
if (useUpper.value) s += CHARSETS.upper
if (useDigits.value) s += CHARSETS.digits
if (useSymbols.value) s += CHARSETS.symbols
if (excludeAmbiguous.value) {
for (const c of CHARSETS.ambiguous) s = s.split(c).join('')
}
return s
})
/** 用 crypto.getRandomValues 生成无偏随机整数 [0, max) */
function randomInt(max: number): number {
// 拒绝采样消除模偏差
const limit = Math.floor(0x100000000 / max) * max
const buf = new Uint32Array(1)
let v: number
do {
crypto.getRandomValues(buf)
v = buf[0]
} while (v >= limit)
return v % max
}
/** 熵估算:log2(charsetSize^length) = length * log2(size) */
const entropy = computed(() => {
const size = charset.value.length
if (size === 0) return 0
return Math.round(lengthNum.value * Math.log2(size))
})
const strength = computed(() => {
const e = entropy.value
if (e >= 128) return { label: '极强(128+ bit', class: 'text-green-600 dark:text-green-400' }
if (e >= 80) return { label: '强(80-127 bit', class: 'text-green-600 dark:text-green-400' }
if (e >= 60) return { label: '中等(60-79 bit', class: 'text-amber-600 dark:text-amber-400' }
return { label: '弱(<60 bit', class: 'text-red-600 dark:text-red-400' }
})
function generate() {
error.value = ''
if (charset.value.length === 0) {
error.value = '请至少选择一种字符集'
passwords.value = []
return
}
const list: string[] = []
for (let i = 0; i < countNum.value; i++) {
let pw = ''
for (let j = 0; j < lengthNum.value; j++) {
pw += charset.value[randomInt(charset.value.length)]
}
list.push(pw)
}
passwords.value = list
}
const allText = computed(() => passwords.value.join('\n'))
function copyAll() {
void navigator.clipboard.writeText(allText.value)
}
onMounted(generate)
</script>
<template>
<div class="flex flex-col gap-4">
<div class="flex items-center gap-6 flex-wrap">
<div class="flex flex-col gap-1.5">
<Label class="text-xs">长度4-128</Label>
<Input v-model="length" type="number" min="4" max="128" class="w-24 font-mono text-sm" />
</div>
<div class="flex flex-col gap-1.5">
<Label class="text-xs">数量1-100</Label>
<Input v-model="count" type="number" min="1" max="100" class="w-24 font-mono text-sm" />
</div>
<Button size="sm" class="gap-1 self-end" @click="generate">
<RefreshCw class="size-3.5" />
重新生成
</Button>
</div>
<div class="flex items-center gap-4 flex-wrap">
<label class="flex items-center gap-2 text-xs cursor-pointer">
<Switch v-model="useLower" /> 小写 a-z
</label>
<label class="flex items-center gap-2 text-xs cursor-pointer">
<Switch v-model="useUpper" /> 大写 A-Z
</label>
<label class="flex items-center gap-2 text-xs cursor-pointer">
<Switch v-model="useDigits" /> 数字 0-9
</label>
<label class="flex items-center gap-2 text-xs cursor-pointer">
<Switch v-model="useSymbols" /> 符号 !@#$%
</label>
<label class="flex items-center gap-2 text-xs cursor-pointer">
<Switch v-model="excludeAmbiguous" /> 排除易混淆字符
</label>
</div>
<p v-if="error" class="text-xs text-destructive">{{ error }}</p>
<template v-if="passwords.length">
<div class="flex flex-col gap-1.5">
<div class="flex items-center justify-between">
<Label class="text-xs">生成结果</Label>
<span class="text-xs" :class="strength.class">熵约 {{ entropy }} bit · {{ strength.label }}</span>
</div>
<Textarea
readonly
:model-value="allText"
class="min-h-[120px] font-mono text-xs resize-y"
/>
</div>
<Button size="sm" variant="outline" class="gap-1 w-fit" @click="copyAll">
<Copy class="size-3.5" />
复制全部{{ passwords.length }}
</Button>
</template>
</div>
</template>
+192
View File
@@ -0,0 +1,192 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { Textarea } from '@/components/ui/textarea'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Badge } from '@/components/ui/badge'
import ResultArea from '../components/ResultArea.vue'
const pattern = ref('')
const testText = ref('')
const flags = ref({ g: true, i: false, m: false, s: false, u: false })
interface MatchInfo {
index: number
full: string
groups: string[]
groupsLabel: string
}
const raw = computed<{ matches: MatchInfo[]; error: string }>(() => {
if (!pattern.value) return { matches: [], error: '' }
// 防卡 UI:同步 exec 无超时保护,超长文本截断测试(灾难性回溯正则仍可能慢,限制输入规模是主要防线)
const MAX_TEXT = 200_000
const text = testText.value.length > MAX_TEXT ? testText.value.slice(0, MAX_TEXT) : testText.value
const truncated = testText.value.length > MAX_TEXT
let fl = ''
const f = flags.value
if (f.g) fl += 'g'
if (f.i) fl += 'i'
if (f.m) fl += 'm'
if (f.s) fl += 's'
if (f.u) fl += 'u'
try {
const re = new RegExp(pattern.value, fl)
const list: MatchInfo[] = []
let m: RegExpExecArray | null
let guard = 0
while ((m = re.exec(text)) !== null) {
const groups = m.slice(1)
list.push({
index: m.index,
full: m[0],
groups,
groupsLabel: groups && groups.length > 0
? groups.map((g, i) => `$${i + 1}=${g === undefined ? '∅' : g}`).join(', ')
: ''
})
if (!f.g) break
if (list.length >= 5000) break // 匹配数上限,防止大文本 + 极宽正则刷爆列表
if (m[0] === '') {
if (++guard > 100000) break
re.lastIndex++
}
}
if (list.length >= 5000) {
const extra = truncated ? `(文本超过 ${MAX_TEXT} 字符,仅测试前 ${MAX_TEXT} 字符)` : ''
return { matches: list, error: `匹配数已达 5000 上限,已停止${extra}` }
}
return { matches: list, error: '' }
} catch (e) {
return { matches: [], error: '正则语法错误:' + String(e) }
}
})
const matches = computed(() => raw.value.matches)
const error = computed(() => raw.value.error)
const isValidPattern = computed(() => {
if (!pattern.value) return null
try {
new RegExp(pattern.value, flags.value.g ? 'g' : '')
return true
} catch {
return false
}
})
const matchesText = computed(() => {
if (matches.value.length === 0) return ''
return matches.value
.map((m, i) => `[${i}] @${m.index}: ${m.full}` + (m.groupsLabel ? ` (${m.groupsLabel})` : ''))
.join('\n')
})
const flagDefs = [
{ key: 'g' as const, label: 'g', title: '全局' },
{ key: 'i' as const, label: 'i', title: '忽略大小写' },
{ key: 'm' as const, label: 'm', title: '多行' },
{ key: 's' as const, label: 's', title: '点匹配换行' },
{ key: 'u' as const, label: 'u', title: 'Unicode' }
]
// ===== 替换预览 =====
const showReplace = ref(false)
const replacement = ref('')
const replaceError = computed(() => {
if (!showReplace.value || !pattern.value) return ''
try {
new RegExp(pattern.value, flags.value.g ? 'g' : '')
return ''
} catch (e) {
return '正则语法错误:' + String(e)
}
})
const replacedText = computed<{ text: string; count: number }>(() => {
if (!showReplace.value || !pattern.value || !testText.value) return { text: '', count: 0 }
const text = testText.value.length > 200_000 ? testText.value.slice(0, 200_000) : testText.value
try {
const fl = (flags.value.g ? 'g' : '') + (flags.value.i ? 'i' : '') + (flags.value.m ? 'm' : '') + (flags.value.s ? 's' : '') + (flags.value.u ? 'u' : '')
const re = new RegExp(pattern.value, fl)
const all = (text.match(new RegExp(pattern.value, fl.includes('g') ? fl : fl + 'g')) ?? []).length
return { text: text.replace(re, replacement.value), count: flags.value.g ? all : Math.min(all, 1) }
} catch {
return { text: '', count: 0 }
}
})
</script>
<template>
<div class="flex flex-col gap-4">
<div class="flex flex-col gap-1.5">
<Label class="text-xs">正则表达式</Label>
<div class="flex items-center gap-2">
<span class="text-muted-foreground font-mono text-sm">/</span>
<Input v-model="pattern" placeholder="如 \b\w+@\w+\.\w+\b" class="font-mono text-sm flex-1" :class="{ 'border-destructive': isValidPattern === false }" />
<span class="text-muted-foreground font-mono text-sm">/</span>
</div>
<div class="flex items-center gap-1 flex-wrap">
<button
v-for="fd in flagDefs"
:key="fd.key"
type="button"
class="h-6 px-2 rounded font-mono text-xs border transition-colors cursor-pointer"
:class="flags[fd.key] ? 'border-primary text-primary bg-primary/10' : 'border-border text-muted-foreground hover:text-foreground'"
:title="fd.title"
@click="flags[fd.key] = !flags[fd.key]"
>
{{ fd.label }}
</button>
<span v-if="matches.length" class="ml-auto text-xs text-muted-foreground">匹配 {{ matches.length }} </span>
<span v-else-if="pattern && testText && !error" class="ml-auto text-xs text-muted-foreground">无匹配</span>
</div>
</div>
<div class="flex flex-col gap-1.5">
<Label class="text-xs">测试文本</Label>
<Textarea v-model="testText" placeholder="在此输入文本..." class="min-h-[120px] font-mono text-xs resize-y" />
</div>
<div class="flex flex-col gap-1.5">
<Label class="text-xs">匹配结果</Label>
<div class="rounded-md border border-border max-h-56 overflow-y-auto divide-y divide-border">
<div v-if="matches.length === 0 && !error" class="p-3 text-xs text-muted-foreground">输入正则与文本查看匹配</div>
<div v-for="(m, i) in matches" :key="i" class="flex items-start gap-2 p-2 text-xs font-mono">
<Badge variant="outline" class="shrink-0 py-0 px-1.5 text-[10px]">@{{ m.index }}</Badge>
<span class="break-all min-w-0">{{ m.full }}</span>
<span v-if="m.groupsLabel" class="text-muted-foreground break-all ml-auto pl-2">{{ m.groupsLabel }}</span>
</div>
</div>
</div>
<ResultArea :text="matchesText" label="匹配列表(可复制)" placeholder="匹配列表" />
<!-- 替换预览 -->
<div class="rounded-md border border-border">
<button
type="button"
class="w-full flex items-center justify-between px-3 py-2 text-xs font-medium cursor-pointer hover:bg-muted/40 transition-colors"
@click="showReplace = !showReplace"
>
<span>替换预览支持 $1$&lt;name&gt; 引用分组</span>
<span class="text-muted-foreground">{{ showReplace ? '收起' : '展开' }}</span>
</button>
<div v-if="showReplace" class="flex flex-col gap-3 p-3 border-t border-border">
<div class="flex flex-col gap-1.5">
<Label class="text-xs">替换为</Label>
<Input v-model="replacement" placeholder="如 [$1](留空则删除匹配内容)" class="font-mono text-sm" />
</div>
<ResultArea
v-if="replacedText.text"
:text="replacedText.text"
:label="`替换结果(已替换 ${replacedText.count} 处)`"
placeholder="替换结果"
/>
<p v-else-if="replacement" class="text-xs text-muted-foreground">替换后无内容或无匹配</p>
<p v-if="replaceError" class="text-xs text-destructive">{{ replaceError }}</p>
</div>
</div>
<p v-if="error" class="text-xs text-destructive">{{ error }}</p>
</div>
</template>
@@ -0,0 +1,82 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { Textarea } from '@/components/ui/textarea'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import ResultArea from '../components/ResultArea.vue'
const input = ref('')
const find = ref('')
const replacement = ref('')
const useRegex = ref(false)
const caseInsensitive = ref(false)
const multiline = ref(false)
const result = computed<{ text: string; count: number; error: string }>(() => {
const v = input.value
if (!v || !find.value) return { text: '', count: 0, error: '' }
try {
let re: RegExp
let replacementText: string
if (useRegex.value) {
const flags = 'g' + (caseInsensitive.value ? 'i' : '') + (multiline.value ? 'm' : '')
re = new RegExp(find.value, flags)
// 正则模式:原生支持 $1、$<name> 等引用
replacementText = replacement.value
} else {
// 纯文本模式:查找与替换都按字面处理,需转义正则元字符与替换串中的 $
const esc = find.value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
re = new RegExp(esc, 'g' + (caseInsensitive.value ? 'i' : ''))
replacementText = replacement.value.replace(/\$/g, '$$$$')
}
const count = (v.match(re) ?? []).length
return { text: v.replace(re, replacementText), count, error: '' }
} catch (e) {
return { text: '', count: 0, error: '正则语法错误:' + String(e) }
}
})
</script>
<template>
<div class="flex flex-col gap-4">
<div class="flex flex-col gap-1.5">
<Label class="text-xs">原文</Label>
<Textarea v-model="input" placeholder="在此输入文本..." class="min-h-[140px] font-mono text-xs resize-y" />
</div>
<div class="grid grid-cols-2 gap-3">
<div class="flex flex-col gap-1.5">
<Label class="text-xs">查找</Label>
<Input v-model="find" :placeholder="useRegex ? '正则表达式' : '纯文本'" class="font-mono text-sm" />
</div>
<div class="flex flex-col gap-1.5">
<Label class="text-xs">替换为留空删除匹配</Label>
<Input v-model="replacement" :placeholder="useRegex ? '支持 $1、$<name>' : '纯文本'" class="font-mono text-sm" />
</div>
</div>
<div class="flex items-center gap-4 flex-wrap">
<label class="flex items-center gap-2 text-xs cursor-pointer">
<Switch v-model="useRegex" /> 正则模式
</label>
<label class="flex items-center gap-2 text-xs cursor-pointer">
<Switch v-model="caseInsensitive" /> 忽略大小写
</label>
<label class="flex items-center gap-2 text-xs cursor-pointer" :class="{ 'opacity-50': !useRegex }">
<Switch v-model="multiline" :disabled="!useRegex" /> 多行模式^$ 匹配行首尾
</label>
</div>
<p v-if="result.error" class="text-xs text-destructive">{{ result.error }}</p>
<ResultArea
v-if="result.text"
:text="result.text"
:label="`替换结果(已替换 ${result.count} 处)`"
placeholder="替换结果"
/>
<p v-else-if="input && find" class="text-xs text-muted-foreground">无匹配或替换后为空</p>
<p v-else class="text-xs text-muted-foreground">输入原文与查找内容实时预览替换结果</p>
</div>
</template>
@@ -0,0 +1,138 @@
<script setup lang="ts">
import { computed, onUnmounted, ref } from 'vue'
import { Clock } from '@lucide/vue'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Button } from '@/components/ui/button'
import { Separator } from '@/components/ui/separator'
import Segmented from '../components/Segmented.vue'
import ResultArea from '../components/ResultArea.vue'
type Unit = 'auto' | 's' | 'ms'
const unit = ref<Unit>('auto')
const numberInput = ref('')
const dateInput = ref('')
const toNumber = (v: string): number | null => {
const n = Number(v.trim())
return Number.isFinite(n) ? n : null
}
/** 自动识别:13 位(>1e11)视为毫秒,10 位(>1e8)视为秒,其他按数值范围推断 */
function resolveUnit(n: number): 's' | 'ms' {
if (unit.value !== 'auto') return unit.value
if (Math.abs(n) >= 1e11) return 'ms'
return 's'
}
const unixToDate = (n: number, u: 's' | 'ms'): Date =>
new Date(u === 's' ? n * 1000 : n)
const formatLocal = (d: Date): string => {
const pad = (x: number) => String(x).padStart(2, '0')
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
}
const formatUtc = (d: Date): string => {
const pad = (x: number) => String(x).padStart(2, '0')
return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())} ${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}:${pad(d.getUTCSeconds())} UTC`
}
const fromNumber = computed<{ local: string; utc: string; iso: string; ts: string; unitUsed: 's' | 'ms' } | null>(() => {
const n = toNumber(numberInput.value)
if (n === null) return null
const u = resolveUnit(n)
const d = unixToDate(n, u)
if (Number.isNaN(d.getTime())) return null
return {
local: formatLocal(d),
utc: formatUtc(d),
iso: d.toISOString(),
ts: String(n),
unitUsed: u
}
})
const fromDate = computed<string>(() => {
if (!dateInput.value) return ''
const d = new Date(dateInput.value)
if (Number.isNaN(d.getTime())) return ''
// 日期输入统一同时给出秒与毫秒
return `${Math.floor(d.getTime() / 1000)}(秒)\n${d.getTime()}(毫秒)`
})
// ===== 当前时间戳 =====
const nowTick = ref(0)
const timer = window.setInterval(() => (nowTick.value++), 1000)
onUnmounted(() => window.clearInterval(timer))
const now = computed(() => {
void nowTick.value
const d = new Date()
return {
s: String(Math.floor(d.getTime() / 1000)),
ms: String(d.getTime()),
local: formatLocal(d)
}
})
function copy(text: string) {
void navigator.clipboard.writeText(text)
}
</script>
<template>
<div class="flex flex-col gap-4">
<Segmented
v-model="unit"
label="单位"
:options="[
{ value: 'auto', label: '自动' },
{ value: 's', label: '秒' },
{ value: 'ms', label: '毫秒' }
]"
/>
<!-- 时间戳 时间 -->
<div class="flex flex-col gap-3">
<div class="flex flex-col gap-1.5">
<Label class="text-xs">Unix 时间戳 日期时间</Label>
<Input v-model="numberInput" placeholder="例如 1757419200 或 1757419200000" class="font-mono text-sm" />
</div>
<template v-if="fromNumber">
<ResultArea :text="fromNumber.local" label="本地时间" placeholder="本地时间" />
<ResultArea :text="fromNumber.utc" label="UTC 时间" placeholder="UTC 时间" />
<ResultArea :text="fromNumber.iso" label="ISO 8601" placeholder="ISO 8601" />
<p class="text-xs text-muted-foreground">已识别为{{ fromNumber.unitUsed === 's' ? '秒级' : '毫秒级' }}时间戳</p>
</template>
<p v-else-if="numberInput" class="text-xs text-destructive">请输入有效的数字时间戳</p>
</div>
<Separator />
<!-- 时间 时间戳 -->
<div class="flex flex-col gap-1.5">
<Label class="text-xs">日期时间 Unix 时间戳</Label>
<Input v-model="dateInput" type="datetime-local" class="font-mono text-sm" />
<ResultArea v-if="fromDate" :text="fromDate" label="结果" placeholder="结果" />
</div>
<Separator />
<!-- 当前时间戳 -->
<div class="flex flex-col gap-2">
<Label class="text-xs">当前时间{{ now.local }}</Label>
<div class="flex items-center gap-2 flex-wrap">
<Button size="sm" variant="outline" class="h-8 font-mono text-xs gap-1.5" @click="copy(now.s)">
<Clock class="size-3.5" />
{{ now.s }}点击复制
</Button>
<Button size="sm" variant="outline" class="h-8 font-mono text-xs gap-1.5" @click="copy(now.ms)">
<Clock class="size-3.5" />
{{ now.ms }}毫秒点击复制
</Button>
</div>
</div>
</div>
</template>
+187
View File
@@ -0,0 +1,187 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { ArrowDownUp } from '@lucide/vue'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { Button } from '@/components/ui/button'
import { Switch } from '@/components/ui/switch'
import Segmented from '../components/Segmented.vue'
import ResultArea from '../components/ResultArea.vue'
type Tab = 'convert' | 'parse'
const tab = ref<Tab>('convert')
const mode = ref<'encode' | 'decode'>('encode')
const usePlus = ref(false)
const input = ref('')
// ===== 编解码 =====
const output = computed<{ text: string; error: string }>(() => {
const v = input.value
if (!v) return { text: '', error: '' }
if (mode.value === 'encode') {
const enc = encodeURIComponent(v)
return { text: usePlus.value ? enc.replace(/%20/g, '+') : enc, error: '' }
}
// decode:先处理 + 与 %20 两种形式
const normalized = usePlus.value ? v.replace(/\+/g, ' ') : v
try {
return { text: decodeURIComponent(normalized), error: '' }
} catch (e) {
return { text: '', error: '解码失败(存在非法百分号序列):' + String(e) }
}
})
const swap = () => {
if (output.value.text) {
input.value = output.value.text
mode.value = mode.value === 'encode' ? 'decode' : 'encode'
}
}
// ===== URL 解析 =====
const parseInput = ref('https://user:pass@example.com:8080/path/to/page?a=1&b=hello%20world&c=3#section')
interface ParsedUrl {
href: string
protocol: string
username: string
password: string
host: string
hostname: string
port: string
pathname: string
search: string
hash: string
origin: string
params: Array<[string, string]>
paramError: string
}
const parsedUrl = computed<{ url: ParsedUrl | null; error: string }>(() => {
const v = parseInput.value.trim()
if (!v) return { url: null, error: '' }
let u: URL
try {
u = new URL(v)
} catch {
// 无协议时尝试补 http:// 再解析
try {
u = new URL('http://' + v)
} catch (e) {
return { url: null, error: 'URL 解析失败:' + String(e) }
}
}
const params: Array<[string, string]> = []
let paramError = ''
try {
u.searchParams.forEach((value, key) => params.push([key, value]))
} catch (e) {
paramError = String(e)
}
return {
url: {
href: u.href,
protocol: u.protocol,
username: u.username,
password: u.password,
host: u.host,
hostname: u.hostname,
port: u.port,
pathname: u.pathname,
search: u.search,
hash: u.hash,
origin: u.origin,
params,
paramError
},
error: ''
}
})
const FIELDS: Array<{ key: keyof ParsedUrl; label: string }> = [
{ key: 'protocol', label: '协议' },
{ key: 'username', label: '用户名' },
{ key: 'password', label: '密码' },
{ key: 'hostname', label: '主机名' },
{ key: 'port', label: '端口' },
{ key: 'pathname', label: '路径' },
{ key: 'search', label: '查询串' },
{ key: 'hash', label: '锚点' },
{ key: 'origin', label: 'Origin' }
]
</script>
<template>
<div class="flex flex-col gap-4">
<Segmented
v-model="tab"
:options="[
{ value: 'convert', label: '编解码' },
{ value: 'parse', label: 'URL 解析' }
]"
/>
<!-- 编解码 -->
<template v-if="tab === 'convert'">
<div class="flex items-center justify-between flex-wrap gap-3">
<Segmented
v-model="mode"
label="操作"
:options="[
{ value: 'encode', label: '编码' },
{ value: 'decode', label: '解码' }
]"
/>
<label class="flex items-center gap-2 text-xs text-muted-foreground cursor-pointer">
空格用
<Switch v-model="usePlus" />
<span class="font-mono">{{ usePlus ? '+(表单)' : '%20' }}</span>
</label>
<Button size="sm" variant="outline" class="h-8 text-sm gap-1" :disabled="!output.text" @click="swap">
<ArrowDownUp class="size-3.5" />
结果回填
</Button>
</div>
<div class="flex flex-col gap-1.5">
<Label class="text-xs">{{ mode === 'encode' ? '待编码文本' : '待解码字符串' }}</Label>
<Textarea v-model="input" placeholder="在此输入..." class="min-h-[120px] font-mono text-xs resize-y" />
</div>
<ResultArea :text="output.text" placeholder="结果" />
<p v-if="output.error" class="text-xs text-destructive">{{ output.error }}</p>
</template>
<!-- URL 解析 -->
<template v-else>
<div class="flex flex-col gap-1.5">
<Label class="text-xs">URL</Label>
<Textarea v-model="parseInput" placeholder="https://example.com/path?a=1#hash" class="min-h-[70px] font-mono text-xs resize-y" />
</div>
<template v-if="parsedUrl.url">
<div class="rounded-md border border-border divide-y divide-border text-xs">
<div v-for="f in FIELDS" :key="f.key" class="flex gap-3 px-3 py-1.5">
<span class="w-16 shrink-0 text-muted-foreground">{{ f.label }}</span>
<span class="font-mono break-all">{{ (parsedUrl.url[f.key] as string) || '—' }}</span>
</div>
</div>
<div v-if="parsedUrl.url.params.length > 0" class="flex flex-col gap-1.5">
<Label class="text-xs">查询参数{{ parsedUrl.url.params.length }} </Label>
<div class="rounded-md border border-border divide-y divide-border text-xs">
<div v-for="([k, v], i) in parsedUrl.url.params" :key="i" class="flex gap-3 px-3 py-1.5">
<span class="font-mono text-primary break-all">{{ k }}</span>
<span class="font-mono break-all">{{ v }}</span>
</div>
</div>
</div>
<p v-if="parsedUrl.url.paramError" class="text-xs text-destructive">{{ parsedUrl.url.paramError }}</p>
<p v-else-if="parsedUrl.url.params.length === 0" class="text-xs text-muted-foreground">无查询参数</p>
</template>
<p v-else-if="!parseInput" class="text-xs text-muted-foreground">输入 URL 查看解析结果</p>
<p v-else class="text-xs text-destructive">{{ parsedUrl.error }}</p>
</template>
</div>
</template>
+121
View File
@@ -0,0 +1,121 @@
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { RefreshCw, Copy } from '@lucide/vue'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Button } from '@/components/ui/button'
import { Switch } from '@/components/ui/switch'
import Segmented from '../components/Segmented.vue'
import ResultArea from '../components/ResultArea.vue'
const count = ref('5')
const version = ref<'v4' | 'v7'>('v4')
const uppercase = ref(false)
const noDashes = ref(false)
// 原始随机 UUID 与格式化后的展示
const baseUuids = ref<string[]>([])
const batchCount = computed(() => {
const n = Math.floor(Number(count.value))
if (!Number.isFinite(n)) return 5
return Math.min(Math.max(n || 0, 1), 100)
})
function formatUuid(u: string): string {
let out = uppercase.value ? u.toUpperCase() : u
if (noDashes.value) out = out.replace(/-/g, '')
return out
}
const uuids = computed(() => baseUuids.value.map(formatUuid))
/** UUID v4:纯随机 */
function uuidv4(): string {
return crypto.randomUUID()
}
/** UUID v7:毫秒时间戳前缀(48 bit)+ 随机,时间有序、适合数据库索引 */
function uuidv7(): string {
const ts = BigInt(Date.now())
const b = crypto.getRandomValues(new Uint8Array(16))
b[0] = Number((ts >> 40n) & 0xffn)
b[1] = Number((ts >> 32n) & 0xffn)
b[2] = Number((ts >> 24n) & 0xffn)
b[3] = Number((ts >> 16n) & 0xffn)
b[4] = Number((ts >> 8n) & 0xffn)
b[5] = Number(ts & 0xffn)
b[6] = (b[6] & 0x0f) | 0x70 // version 7
b[8] = (b[8] & 0x3f) | 0x80 // variant 10xx
const hex = Array.from(b, x => x.toString(16).padStart(2, '0')).join('')
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
}
function generate() {
const gen = version.value === 'v4' ? uuidv4 : uuidv7
baseUuids.value = Array.from({ length: batchCount.value }, gen)
}
const allText = computed(() => uuids.value.join('\n'))
function copyAll() {
try {
void navigator.clipboard.writeText(allText.value)
} catch {
/* ignore */
}
}
// 切换版本时立即重新生成
watch(version, generate)
onMounted(generate)
</script>
<template>
<div class="flex flex-col gap-4">
<div class="flex items-center justify-between flex-wrap gap-3">
<div class="flex items-center gap-4 flex-wrap">
<div class="flex flex-col gap-1.5">
<Label class="text-xs">生成数量1-100</Label>
<Input v-model="count" type="number" min="1" max="100" class="w-24 font-mono text-sm" />
</div>
<div class="flex flex-col gap-1.5">
<Label class="text-xs">版本</Label>
<div class="flex items-center gap-2">
<Segmented
v-model="version"
:options="[
{ value: 'v4', label: 'v4 随机' },
{ value: 'v7', label: 'v7 时间有序' }
]"
/>
</div>
</div>
</div>
<div class="flex items-center gap-4">
<label class="flex items-center gap-2 text-xs text-muted-foreground cursor-pointer">
大写
<Switch v-model="uppercase" />
</label>
<label class="flex items-center gap-2 text-xs text-muted-foreground cursor-pointer">
去除连字符
<Switch v-model="noDashes" />
</label>
<Button size="sm" class="gap-1" @click="generate">
<RefreshCw class="size-3.5" />
重新生成
</Button>
</div>
</div>
<ResultArea :text="allText" label="UUID 列表" placeholder="点击重新生成" />
<div class="flex items-center gap-2">
<Button size="sm" variant="outline" class="gap-1" :disabled="!allText" @click="copyAll">
<Copy class="size-3.5" />
复制全部{{ uuids.length }}
</Button>
<span class="text-xs text-muted-foreground">{{ version === 'v4' ? 'UUID v4(纯随机)' : 'UUID v7(毫秒时间戳前缀,适合数据库主键索引)' }}</span>
</div>
</div>
</template>
@@ -0,0 +1,77 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import Segmented from '../../components/Segmented.vue'
import ResultArea from '../../components/ResultArea.vue'
type Radix = '2' | '8' | '10' | '16'
const bases: { value: Radix; label: string }[] = [
{ value: '2', label: '二进制(2)' },
{ value: '8', label: '八进制(8)' },
{ value: '10', label: '十进制(10)' },
{ value: '16', label: '十六进制(16)' }
]
const from = ref<Radix>('10')
const to = ref<Radix>('16')
const input = ref('')
const error = ref('')
const RADIX_MAP: Record<Radix, number> = { '2': 2, '8': 8, '10': 10, '16': 16 }
/** 按进制精确解析为 BigInt(大数字不丢精度),非法输入抛错 */
function parseBigInt(s: string, radix: number): bigint {
const digits = '0123456789abcdef'
const trimmed = s.trim().toLowerCase()
const negative = trimmed.startsWith('-')
const body = trimmed.replace(/^[+-]/, '')
if (!body) throw new Error('empty')
let n = 0n
for (const ch of body) {
const d = digits.indexOf(ch)
if (d === -1 || d >= radix) throw new Error('invalid digit')
n = n * BigInt(radix) + BigInt(d)
}
return negative ? -n : n
}
const result = computed(() => {
error.value = ''
const v = input.value.trim()
if (!v) return { dec: null, output: '', outputUppercase: '' }
try {
const parsed = parseBigInt(v, RADIX_MAP[from.value])
const out = parsed.toString(RADIX_MAP[to.value])
return {
dec: parsed,
output: out,
outputUppercase: to.value === '16' ? out.toUpperCase() : out
}
} catch {
error.value = '输入不合法,请确认数字与当前进制匹配(如十六进制仅含 0-9a-f)'
return { dec: null, output: '', outputUppercase: '' }
}
})
</script>
<template>
<div class="flex flex-col gap-4">
<div class="flex items-center gap-3 flex-wrap">
<Segmented v-model="from" label="从" :options="bases" />
<span class="text-xs text-muted-foreground"></span>
<Segmented v-model="to" label="到" :options="bases" />
</div>
<div class="flex flex-col gap-1.5">
<Label class="text-xs">输入{{ from === '2' ? '二进制' : from === '8' ? '八进制' : from === '10' ? '十进制' : '十六进制' }}</Label>
<Input v-model="input" placeholder="输入数字" class="font-mono text-sm" />
</div>
<ResultArea :text="result.output" label="结果" placeholder="结果" />
<ResultArea v-if="to === '16' && result.outputUppercase !== result.output" :text="result.outputUppercase" label="大写形式" placeholder="大写形式" />
<div v-if="result.dec !== null" class="text-xs text-muted-foreground">十进制值{{ result.dec.toString() }}</div>
<p v-if="error" class="text-xs text-destructive">{{ error }}</p>
</div>
</template>
+171
View File
@@ -0,0 +1,171 @@
import type { Component } from 'vue'
import { defineAsyncComponent } from 'vue'
import {
FileJson, Binary, Link, Clock, MoveHorizontal, Fingerprint,
Wand2, KeyRound, CaseSensitive, Hash, Code, GitCompare, Shield,
Palette, Lock, CalendarClock, Network, Sigma, Replace, Globe
} from '@lucide/vue'
import { registerTool, type DevTool } from '../registry'
/** 工具元数据(与组件解耦,供模块配置生成搜索项) */
export const TOOLS_META: Array<Omit<DevTool, 'component' | 'icon'>> = [
{
id: 'json', name: 'JSON 格式化', category: 'transform',
description: '格式化 / 压缩 / 校验,支持键排序',
keywords: ['json', '格式化', '美化', '压缩', '校验', '排序']
},
{
id: 'timestamp', name: '时间戳转换', category: 'transform',
description: 'Unix 时间戳与日期时间互转,自动识别秒 / 毫秒',
keywords: ['时间戳', 'timestamp', 'unix', '日期', '时间', '转换', '现在']
},
{
id: 'base', name: '进制转换', category: 'transform',
description: '二进制 / 八进制 / 十进制 / 十六进制互转',
keywords: ['进制', '二进制', '十六进制', 'hex', 'bin', 'oct', 'dec', 'base']
},
{
id: 'color', name: '颜色转换器', category: 'transform',
description: 'HEX / RGB / HSL / HSV / CMYK 互转,明暗梯度',
keywords: ['颜色', 'color', 'hex', 'rgb', 'hsl', 'hsv', 'cmyk', '调色', '取色']
},
{
id: 'ip', name: 'IP / CIDR 计算', category: 'transform',
description: '子网划分、掩码换算、IP 与整数互转',
keywords: ['ip', 'cidr', '子网', '掩码', '网段', '广播', '网络', 'subnet', 'mask']
},
{
id: 'cron', name: 'Cron 表达式', category: 'transform',
description: '解析 Cron 表达式,预览接下来 6 次执行时间',
keywords: ['cron', 'crontab', '定时', '计划任务', '表达式', 'schedule']
},
{
id: 'base64', name: 'Base64 转换', category: 'encoding',
description: '文本与 Base64 互转(支持中文),文件转 Base64 / Data URL',
keywords: ['base64', '编码', '解码', 'encode', 'decode', 'dataurl', '文件']
},
{
id: 'url', name: 'URL 编解码', category: 'encoding',
description: 'URL 编码 / 解码,URL 结构解析',
keywords: ['url', 'encode', 'decode', '编码', '解码', '链接', '解析', '参数', 'query']
},
{
id: 'jwt', name: 'JWT 解码', category: 'encoding',
description: '本地解析 JWT 的 Header 与 Payload,含过期时间提示',
keywords: ['jwt', 'token', '解码', 'header', 'payload', '过期', 'exp']
},
{
id: 'escape', name: '转义 / 反转义', category: 'encoding',
description: 'HTML 实体与 JSON 字符串转义、反转义',
keywords: ['转义', '反转义', 'html', 'entity', 'json', 'escape']
},
{
id: 'case', name: '大小写 / 命名转换', category: 'text',
description: 'camel / Pascal / snake / kebab 等命名转换',
keywords: ['大小写', '命名', 'camel', 'snake', 'kebab', 'pascal', '转换']
},
{
id: 'regex', name: '正则测试', category: 'text',
description: '在线测试正则表达式,实时匹配、分组查看与替换预览',
keywords: ['正则', 'regex', '匹配', 'test', 're', '替换']
},
{
id: 'diff', name: '文本对比', category: 'text',
description: '两段文本逐行差异对比',
keywords: ['对比', '差异', 'diff', '比较', 'compare']
},
{
id: 'eol', name: '行尾符转换', category: 'text',
description: 'CRLF / LF / CR 行尾符统一',
keywords: ['行尾', '换行', 'crlf', 'lf', 'cr', 'eol', '转行']
},
{
id: 'replace', name: '批量查找替换', category: 'text',
description: '纯文本 / 正则批量替换,支持分组引用',
keywords: ['替换', '查找', 'replace', '批量', '正则替换']
},
{
id: 'charcount', name: '字符统计', category: 'text',
description: '字符 / 字节 / 词数 / 行数统计与高频分析',
keywords: ['统计', '字数', '字符数', '词频', 'count', 'words', '字节数']
},
{
id: 'uuid', name: 'UUID 生成', category: 'generate',
description: '批量生成 UUID v4 / v7,支持大写与去连字符',
keywords: ['uuid', 'guid', '生成', '随机', 'id', 'v4', 'v7']
},
{
id: 'hash', name: '哈希计算', category: 'generate',
description: 'MD5 / SHA-1 / SHA-256 / SHA-384 / SHA-512 与 HMAC,支持文件',
keywords: ['哈希', 'hash', 'sha', '摘要', 'md5', 'hmac', '文件', '校验']
},
{
id: 'password', name: '密码生成', category: 'generate',
description: '随机密码批量生成,字符集可选,附熵值评估',
keywords: ['密码', 'password', '随机', '生成', '安全', 'entropy']
},
{
id: 'httpstatus', name: 'HTTP 速查', category: 'reference',
description: 'HTTP 状态码与常用 MIME 类型速查',
keywords: ['http', '状态码', 'status', 'mime', 'content-type', '速查', '429', '404']
}
]
/** 图标映射(按工具 id */
const TOOL_ICONS: Record<string, Component> = {
json: FileJson,
timestamp: Clock,
base: Hash,
color: Palette,
ip: Network,
cron: CalendarClock,
base64: Binary,
url: Link,
jwt: KeyRound,
escape: Code,
case: CaseSensitive,
regex: Wand2,
diff: GitCompare,
eol: MoveHorizontal,
replace: Replace,
charcount: Sigma,
uuid: Fingerprint,
hash: Shield,
password: Lock,
httpstatus: Globe
}
// 工具组件(懒加载路径映射)
const TOOL_COMPONENTS: Record<string, () => Promise<{ default: Component }>> = {
json: () => import('./JsonTools.vue'),
timestamp: () => import('./TimestampTools.vue'),
base: () => import('./base/BaseTools.vue'),
color: () => import('./ColorTools.vue'),
ip: () => import('./IpTools.vue'),
cron: () => import('./CronTools.vue'),
base64: () => import('./Base64Tools.vue'),
url: () => import('./UrlTools.vue'),
jwt: () => import('./JwtTools.vue'),
escape: () => import('./EscapeTools.vue'),
case: () => import('./CaseTools.vue'),
regex: () => import('./RegexTools.vue'),
diff: () => import('./DiffTools.vue'),
eol: () => import('./EolTools.vue'),
replace: () => import('./ReplaceTools.vue'),
charcount: () => import('./CharCountTools.vue'),
uuid: () => import('./UuidTools.vue'),
hash: () => import('./HashTools.vue'),
password: () => import('./PasswordTools.vue'),
httpstatus: () => import('./HttpStatusTools.vue')
}
/** 将所有工具注册进注册表(幂等) */
export function registerAllTools(): void {
for (const meta of TOOLS_META) {
registerTool({
...meta,
icon: TOOL_ICONS[meta.id],
component: defineAsyncComponent(TOOL_COMPONENTS[meta.id])
})
}
}
+6 -2
View File
@@ -6,7 +6,9 @@ import {
Camera,
Activity,
Download,
Command
Command,
Wrench,
Music
} from '@lucide/vue'
/**
@@ -23,7 +25,9 @@ export const moduleIconMap: Record<string, Component> = {
screenshot: Camera,
monitor: Activity,
downloader: Download,
quickpanel: Command
quickpanel: Command,
devtools: Wrench,
music: Music
}
/** 获取模块图标组件,未找到时回退到 Settings 图标 */
+5 -1
View File
@@ -8,7 +8,9 @@ import { moduleConfig as screenshot } from './screenshot'
import { moduleConfig as monitor } from './monitor'
import { moduleConfig as downloader } from './downloader'
import { moduleConfig as quickpanel } from './quickpanel'
import { moduleConfig as devtools } from './devtools'
import { moduleConfig as settings } from './settings'
import { moduleConfig as music } from './music'
const allModules: ModuleConfig[] = [
proxy,
@@ -17,7 +19,9 @@ const allModules: ModuleConfig[] = [
monitor,
downloader,
quickpanel,
settings
devtools,
settings,
music
]
// 启动时注册所有模块
+1
View File
@@ -279,6 +279,7 @@ function fmtFixedValue(v: number | null, item: OsdItem): string {
case 'temperature':
return padNum(Math.round(v).toString(), 3) // 0-150 → 3 字符
case 'power':
return padNum(v.toFixed(2), 6) // 12.34 / 123.45 → 6 字符(支持三位数功耗)
case 'voltage':
return padNum(v.toFixed(2), 5) // 12.34 → 5 字符
case 'clock':
File diff suppressed because it is too large Load Diff
+70
View File
@@ -0,0 +1,70 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { ChevronDown } from '@lucide/vue'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { Label } from '@/components/ui/label'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { ScrollArea } from '@/components/ui/scroll-area'
import { sourceName } from './sources'
const props = defineProps<{
modelValue: string[]
/** 可选源(客户端名)列表 */
options: string[]
}>()
const emit = defineEmits<{ 'update:model-value': [string[]] }>()
const open = ref(false)
const checked = computed(() => new Set(props.modelValue))
const toggle = (code: string) => {
const next = new Set(checked.value)
if (next.has(code)) next.delete(code)
else next.add(code)
emit('update:model-value', [...next])
}
const label = computed(() => {
if (props.modelValue.length === 0) return '未选择'
if (props.modelValue.length === 1) return sourceName(props.modelValue[0])
return `已选 ${props.modelValue.length} 个源`
})
</script>
<template>
<Popover v-model:open="open">
<PopoverTrigger as-child>
<Button variant="outline" class="justify-between font-normal" size="sm">
<span class="truncate">{{ label }}</span>
<ChevronDown class="size-3.5 opacity-50 shrink-0" />
</Button>
</PopoverTrigger>
<PopoverContent class="w-64 p-2" align="start">
<!-- ScrollArea viewport h-full 需要 root 有确定高度才滚动max-h 不生效用固定 h-72 -->
<ScrollArea class="h-72">
<div class="space-y-0.5 pr-2">
<label
v-for="code in options"
:key="code"
class="flex items-center gap-2 rounded-md px-2 py-1.5 cursor-pointer hover:bg-muted/50"
>
<Checkbox
:model-value="checked.has(code)"
@update:model-value="toggle(code)"
/>
<Label class="text-sm cursor-pointer truncate">{{ sourceName(code) }}</Label>
</label>
<p v-if="options.length === 0" class="px-2 py-3 text-xs text-muted-foreground">
未获取到可用源请先安装环境
</p>
</div>
</ScrollArea>
<div class="mt-1 border-t pt-1.5 px-1 flex items-center justify-between">
<span class="text-xs text-muted-foreground">{{ options.length }} 个可选源</span>
<span class="text-xs text-muted-foreground">已选 {{ props.modelValue.length }}</span>
</div>
</PopoverContent>
</Popover>
</template>
@@ -0,0 +1,269 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { toast } from 'vue-sonner'
import { FolderOpen, Loader2, Music2, Plus, RefreshCw, Trash2 } from '@lucide/vue'
import { useFeiniuStore, type Playlist } from '@/stores/feiniuStore'
import TrackItem from './TrackItem.vue'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Empty } from '@/components/ui/empty'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
const store = useFeiniuStore()
type SubTab = 'feiniu' | 'local' | 'playlists'
const subTab = ref<SubTab>('feiniu')
// 未登录(无激活连接且未登录)
const needsLogin = computed(() => !store.config.loggedIn && !store.activeConn)
const keywordInput = ref('')
let searchTimer: ReturnType<typeof setTimeout> | undefined
function onSearchInput() {
clearTimeout(searchTimer)
searchTimer = setTimeout(() => {
store.loadTracks(1).catch((e) => toast.error(String(e)))
}, 400)
}
function refreshFeiniu() {
store.loadTracks(store.page).catch((e) => toast.error(String(e)))
}
function refreshLocal() {
store.scanLocal().catch((e) => toast.error(String(e)))
}
function playAll() {
const list =
subTab.value === 'feiniu' ? store.tracks : subTab.value === 'local' ? store.localTracks : []
if (list.length) store.playQueue(list, 0)
}
// ===== 歌单 =====
const playlistName = ref('')
const createOpen = ref(false)
const activePlaylistId = ref('')
const activePlaylist = computed<Playlist | null>(
() => store.playlists.find((p) => p.id === activePlaylistId.value) || null
)
function createPlaylist() {
if (!playlistName.value.trim()) {
toast.error('请输入歌单名称')
return
}
const id = store.createPlaylist(playlistName.value.trim())
activePlaylistId.value = id
playlistName.value = ''
createOpen.value = false
}
onMounted(async () => {
await store.init()
if (store.config.loggedIn) {
store.loadTracks(1).catch(() => {})
}
})
</script>
<template>
<ScrollArea class="h-full pr-3">
<div class="flex flex-col gap-4 px-1 pt-1 pb-4 min-w-0">
<!-- 未登录态引导配置连接 -->
<div v-if="needsLogin" class="flex flex-col items-center gap-3 py-16 text-center">
<Music2 class="size-10 text-muted-foreground" />
<p class="text-sm text-muted-foreground">
还没有可用的飞牛音乐连接请到设置 飞牛音乐连接添加并登录
<br />
或先到发现音乐下载歌曲到本地曲库
</p>
</div>
<template v-else>
<!-- 页头 + 子导航 -->
<div class="flex flex-col gap-3">
<div class="flex items-center justify-between">
<div class="flex items-center gap-1 rounded-lg border bg-card p-1">
<button
type="button"
class="rounded-md px-3 py-1 text-sm transition-colors"
:class="subTab === 'feiniu' ? 'bg-primary text-primary-foreground' : 'text-muted-foreground hover:text-foreground'"
@click="subTab = 'feiniu'"
>
飞牛曲库
</button>
<button
type="button"
class="rounded-md px-3 py-1 text-sm transition-colors"
:class="subTab === 'local' ? 'bg-primary text-primary-foreground' : 'text-muted-foreground hover:text-foreground'"
@click="subTab = 'local'"
>
本地曲库
</button>
<button
type="button"
class="rounded-md px-3 py-1 text-sm transition-colors"
:class="subTab === 'playlists' ? 'bg-primary text-primary-foreground' : 'text-muted-foreground hover:text-foreground'"
@click="subTab = 'playlists'"
>
我的歌单
</button>
</div>
<Button v-if="store.config.loggedIn" variant="outline" size="sm" @click="playAll">
播放全部
</Button>
</div>
</div>
<!-- ===== 飞牛曲库 ===== -->
<template v-if="subTab === 'feiniu'">
<div class="flex items-center gap-2">
<div class="flex-1">
<Input v-model="keywordInput" placeholder="搜索飞牛曲库(歌名 / 歌手)" @input="onSearchInput" @keydown.enter="onSearchInput" />
</div>
<Button variant="outline" size="icon" :disabled="store.loading" @click="refreshFeiniu">
<RefreshCw :class="store.loading ? 'size-4 animate-spin' : 'size-4'" />
</Button>
</div>
<div class="flex flex-col gap-1.5">
<div v-if="store.loading" class="flex items-center justify-center gap-2 py-10 text-sm text-muted-foreground">
<Loader2 class="size-4 animate-spin" /> 加载曲库
</div>
<Empty v-else-if="!store.tracks.length" class="min-h-40">
<Music2 class="size-10 text-muted-foreground" />
<p class="text-sm text-muted-foreground">
{{ store.config.loggedIn ? '曲库为空或未匹配到结果' : '请先在设置中登录飞牛音乐连接' }}
</p>
</Empty>
<template v-else>
<TrackItem
v-for="(t, i) in store.tracks"
:key="t.guid || i"
:item="t"
:active="store.current?.guid === t.guid"
@dblclick="store.playQueue(store.tracks, i)"
/>
</template>
</div>
</template>
<!-- ===== 本地曲库 ===== -->
<template v-else-if="subTab === 'local'">
<div class="flex items-center gap-2">
<Button variant="outline" size="sm" :disabled="store.localScanBusy" @click="refreshLocal">
<Loader2 v-if="store.localScanBusy" class="size-4 animate-spin" />
<FolderOpen v-else class="size-4" />
扫描本地
</Button>
<span class="text-xs text-muted-foreground">{{ store.localTracks.length }} 目录音乐下载目录 + 自定义</span>
</div>
<div class="flex flex-col gap-1.5">
<Empty v-if="!store.localTracks.length && !store.localScanBusy" class="min-h-40">
<FolderOpen class="size-10 text-muted-foreground" />
<p class="text-sm text-muted-foreground">暂无本地音乐点击扫描本地或先到发现音乐下载</p>
</Empty>
<template v-else>
<TrackItem
v-for="(t, i) in store.localTracks"
:key="t.guid || i"
:item="t"
:active="store.current?.guid === t.guid"
@dblclick="store.playQueue(store.localTracks, i)"
/>
</template>
</div>
</template>
<!-- ===== 我的歌单 ===== -->
<template v-else>
<div class="flex items-center gap-2">
<Button variant="outline" size="sm" @click="createOpen = true">
<Plus class="size-4" /> 新建歌单
</Button>
</div>
<!-- 歌单列表 + 详情 -->
<div class="grid grid-cols-1 gap-4 md:grid-cols-[220px_1fr]">
<div class="flex flex-col gap-1 rounded-lg border bg-card p-2">
<button
v-for="p in store.playlists"
:key="p.id"
type="button"
class="flex items-center justify-between rounded-md px-3 py-2 text-sm transition-colors"
:class="activePlaylistId === p.id ? 'bg-primary/10 text-foreground' : 'text-muted-foreground hover:bg-muted/40'"
@click="activePlaylistId = p.id"
>
<span class="truncate">{{ p.name }}</span>
<span class="text-xs">{{ p.items.length }}</span>
</button>
<Empty v-if="!store.playlists.length" class="min-h-32">
<p class="text-sm text-muted-foreground">还没有歌单</p>
</Empty>
</div>
<div class="flex flex-col gap-2">
<div v-if="activePlaylist" class="flex items-center justify-between">
<div>
<div class="text-base font-semibold">{{ activePlaylist.name }}</div>
<div class="text-xs text-muted-foreground">{{ activePlaylist.items.length }} </div>
</div>
<div class="flex items-center gap-2">
<Button variant="outline" size="sm" :disabled="!activePlaylist.items.length" @click="store.playQueue(activePlaylist.items, 0)">
播放全部
</Button>
<Button
variant="ghost"
size="icon"
class="size-8 text-destructive"
@click="store.deletePlaylist(activePlaylist.id); activePlaylistId = ''"
>
<Trash2 class="size-4" />
</Button>
</div>
</div>
<div v-if="activePlaylist" class="flex flex-col gap-1.5">
<TrackItem
v-for="(t, i) in activePlaylist.items"
:key="`${t.source}-${t.guid}-${i}`"
:item="t"
:active="store.current?.guid === t.guid"
/>
<div class="mt-1 flex justify-end">
<Button
variant="ghost"
size="sm"
class="text-xs text-muted-foreground"
@click="store.removeFromPlaylist(activePlaylist.id, activePlaylist.items.length - 1)"
>
移除最后一首
</Button>
</div>
</div>
<Empty v-else class="min-h-40">
<p class="text-sm text-muted-foreground">选择左侧歌单查看内容</p>
</Empty>
</div>
</div>
</template>
</template>
</div>
</ScrollArea>
<!-- 新建歌单弹窗 -->
<Dialog v-model:open="createOpen">
<DialogContent class="sm:max-w-sm">
<DialogHeader>
<DialogTitle>新建歌单</DialogTitle>
<DialogDescription>歌单保存在本机可混合飞牛 NAS 与本地曲目</DialogDescription>
</DialogHeader>
<Input v-model="playlistName" placeholder="歌单名称" @keydown.enter="createPlaylist" />
<DialogFooter>
<Button variant="outline" @click="createOpen = false">取消</Button>
<Button @click="createPlaylist">创建</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</template>
+142
View File
@@ -0,0 +1,142 @@
<script setup lang="ts">
import { computed } from 'vue'
import { ListMusic, Maximize2, Music2, Pause, Play, Repeat, Repeat1, Shuffle, SkipBack, SkipForward, Volume2 } from '@lucide/vue'
import { useFeiniuStore } from '@/stores/feiniuStore'
import { Slider } from '@/components/ui/slider'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
const store = useFeiniuStore()
const coverUrl = computed(() => {
const t = store.current
if (t?.source === 'feiniu' && t.coverId && store.mediaPrefix) {
return `${store.mediaPrefix}/cover?coverId=${encodeURIComponent(t.coverId)}&size=96`
}
return ''
})
function onProgress(v: number[] | undefined) {
store.seek(((v?.[0] ?? 0) / 100) * store.duration)
}
function onVolume(v: number[] | undefined) {
store.setVolume((v?.[0] ?? 0) / 100)
}
const modeIcon = computed(() => {
if (store.playMode === 'loopOne') return Repeat1
if (store.playMode === 'shuffle') return Shuffle
return Repeat
})
</script>
<template>
<div
class="flex items-center gap-3 border-t bg-background/80 px-4 py-2.5 backdrop-blur"
data-slot="player-bar"
>
<!-- 封面 + 信息点击开 Now-Playing -->
<button
type="button"
class="flex min-w-0 items-center gap-3 text-left"
@click="store.nowPlayingOpen = true"
>
<img
v-if="coverUrl"
:src="coverUrl"
class="size-11 shrink-0 rounded-md object-cover shadow"
alt=""
@error="($event.target as HTMLImageElement).style.display = 'none'"
/>
<div v-else class="flex size-11 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground">
<Music2 class="size-5" />
</div>
<div class="min-w-0 max-w-44">
<div class="truncate text-sm font-medium">{{ store.current?.title || '未播放' }}</div>
<div class="truncate text-xs text-muted-foreground">{{ store.current?.artistNames || '选择一首歌曲开始播放' }}</div>
</div>
</button>
<!-- 控制区 -->
<div class="flex flex-1 flex-col items-center gap-1">
<div class="flex items-center gap-3">
<Tooltip>
<TooltipTrigger as-child>
<button type="button" class="text-muted-foreground transition-colors hover:text-foreground" @click="store.togglePlayMode()">
<component :is="modeIcon" class="size-4" />
</button>
</TooltipTrigger>
<TooltipContent>
{{ store.playMode === 'loopAll' ? '列表循环' : store.playMode === 'loopOne' ? '单曲循环' : '随机播放' }}
</TooltipContent>
</Tooltip>
<button type="button" class="text-muted-foreground transition-colors hover:text-foreground" @click="store.prev()">
<SkipBack class="size-5" />
</button>
<button
type="button"
class="flex size-10 items-center justify-center rounded-full bg-primary text-primary-foreground transition-opacity hover:opacity-90"
:disabled="!store.current"
@click="store.toggle()"
>
<Pause v-if="store.playing" class="size-5" />
<Play v-else class="size-5 translate-x-[1px]" />
</button>
<button type="button" class="text-muted-foreground transition-colors hover:text-foreground" @click="store.next()">
<SkipForward class="size-5" />
</button>
<button
type="button"
class="relative text-muted-foreground transition-colors hover:text-foreground"
@click="store.queueVisible = !store.queueVisible"
>
<ListMusic class="size-4" />
<span
v-if="store.queue.length"
class="absolute -right-1.5 -top-1 flex size-3.5 items-center justify-center rounded-full bg-primary text-[8px] font-medium text-primary-foreground"
>
{{ store.queue.length }}
</span>
</button>
</div>
<div class="flex w-full max-w-lg items-center gap-2">
<span class="w-10 text-right text-[10px] tabular-nums text-muted-foreground">{{ store.fmtDuration(store.position) }}</span>
<Slider
:model-value="[store.progress]"
class="flex-1"
:max="100"
:step="0.5"
@update:model-value="onProgress"
/>
<span class="w-10 text-[10px] tabular-nums text-muted-foreground">{{ store.fmtDuration(store.duration) }}</span>
</div>
</div>
<!-- 音量 + 歌词 + 最大化 -->
<div class="flex items-center gap-2">
<Volume2 class="size-4 text-muted-foreground" />
<Slider
:model-value="[store.volume * 100]"
class="w-20"
:max="100"
:step="1"
@update:model-value="onVolume"
/>
<button
type="button"
class="text-muted-foreground transition-colors hover:text-foreground"
:class="{ 'text-primary': store.lyricVisible }"
@click="store.lyricVisible = !store.lyricVisible"
>
</button>
<button
type="button"
class="text-muted-foreground transition-colors hover:text-foreground"
@click="store.nowPlayingOpen = true"
>
<Maximize2 class="size-4" />
</button>
</div>
</div>
</template>
+176
View File
@@ -0,0 +1,176 @@
<script setup lang="ts">
import { computed, ref, watchEffect } from 'vue'
import { ListMusic, Music2, Pause, Play, Repeat, Repeat1, Shuffle, SkipBack, SkipForward, X } from '@lucide/vue'
import { useFeiniuStore } from '@/stores/feiniuStore'
import { Slider } from '@/components/ui/slider'
import { Dialog, DialogContent, DialogClose } from '@/components/ui/dialog'
import { ScrollArea } from '@/components/ui/scroll-area'
const store = useFeiniuStore()
const coverUrl = computed(() => {
const t = store.current
if (t?.source === 'feiniu' && t.coverId && store.mediaPrefix) {
return `${store.mediaPrefix}/cover?coverId=${encodeURIComponent(t.coverId)}&size=400`
}
return ''
})
const currentLineIdx = computed(() => store.currentLine())
function onProgress(v: number[] | undefined) {
store.seek(((v?.[0] ?? 0) / 100) * store.duration)
}
const modeIcon = computed(() => {
if (store.playMode === 'loopOne') return Repeat1
if (store.playMode === 'shuffle') return Shuffle
return Repeat
})
// 歌词滚动跟随
const lyricScrollEl = ref<HTMLElement | null>(null)
watchEffect(() => {
const idx = currentLineIdx.value
if (idx < 0 || !lyricScrollEl.value) return
const nodes = lyricScrollEl.value.querySelectorAll<HTMLElement>('[data-line]')
const node = nodes[idx]
if (node) node.scrollIntoView({ block: 'center', behavior: 'smooth' })
})
</script>
<template>
<Dialog v-model:open="store.nowPlayingOpen">
<DialogContent
class="max-w-4xl overflow-hidden border-0 p-0 sm:max-w-5xl"
:show-close-button="false"
>
<div class="relative flex min-h-[70vh] flex-col">
<!-- 背景渐变 -->
<div class="pointer-events-none absolute inset-0">
<img v-if="coverUrl" :src="coverUrl" class="h-full w-full scale-110 object-cover blur-2xl opacity-30" alt="" />
<div class="absolute inset-0 bg-gradient-to-b from-background/60 via-background/85 to-background" />
</div>
<div class="relative flex min-h-0 flex-1">
<!-- 封面 + 控制 -->
<div class="flex w-1/2 flex-col items-center justify-center gap-5 p-8">
<img
v-if="coverUrl"
:src="coverUrl"
class="size-64 rounded-xl object-cover shadow-2xl ring-1 ring-border"
alt=""
/>
<div v-else class="flex size-64 items-center justify-center rounded-xl bg-muted/40 text-muted-foreground shadow-2xl">
<Music2 class="size-20" />
</div>
<div class="text-center">
<div class="truncate text-2xl font-semibold">{{ store.current?.title || '未播放' }}</div>
<div class="mt-1 truncate text-sm text-muted-foreground">
{{ store.current?.artistNames || '—' }}<template v-if="store.current?.album"> · {{ store.current.album }}</template>
</div>
</div>
<div class="flex w-full max-w-sm flex-col gap-2">
<Slider
:model-value="[store.progress]"
:max="100"
:step="0.5"
@update:model-value="onProgress"
/>
<div class="flex justify-between text-[11px] tabular-nums text-muted-foreground">
<span>{{ store.fmtDuration(store.position) }}</span>
<span>{{ store.fmtDuration(store.duration) }}</span>
</div>
<div class="mt-1 flex items-center justify-center gap-6">
<button type="button" class="text-muted-foreground hover:text-foreground" @click="store.togglePlayMode()">
<component :is="modeIcon" class="size-5" />
</button>
<button type="button" class="text-muted-foreground hover:text-foreground" @click="store.prev()">
<SkipBack class="size-7" />
</button>
<button
type="button"
class="flex size-16 items-center justify-center rounded-full bg-primary text-primary-foreground transition-opacity hover:opacity-90"
:disabled="!store.current"
@click="store.toggle()"
>
<Pause v-if="store.playing" class="size-8" />
<Play v-else class="size-8 translate-x-[1px]" />
</button>
<button type="button" class="text-muted-foreground hover:text-foreground" @click="store.next()">
<SkipForward class="size-7" />
</button>
<button type="button" class="text-muted-foreground hover:text-foreground" @click="store.queueVisible = true">
<ListMusic class="size-5" />
</button>
</div>
</div>
</div>
<!-- 歌词 / 队列 -->
<div class="flex w-1/2 flex-col border-l border-white/10 p-6">
<div class="mb-3 flex items-center justify-between">
<button
type="button"
class="text-sm"
:class="!store.queueVisible ? 'font-semibold text-foreground' : 'text-muted-foreground'"
@click="store.queueVisible = false"
>
歌词
</button>
<button
type="button"
class="text-sm"
:class="store.queueVisible ? 'font-semibold text-foreground' : 'text-muted-foreground'"
@click="store.queueVisible = true"
>
队列{{ store.queue.length }}
</button>
</div>
<ScrollArea class="min-h-0 flex-1 pr-3">
<div v-if="!store.queueVisible" ref="lyricScrollEl" class="flex flex-col gap-1 py-2">
<p v-if="!store.lyricLines.length" class="text-sm text-muted-foreground/60">
{{ store.current?.source === 'local' ? '本地文件无歌词' : '暂无歌词' }}
</p>
<p
v-for="(line, idx) in store.lyricLines"
:key="idx"
data-line
class="cursor-pointer py-1 text-[15px] leading-7 transition-colors"
:class="idx === currentLineIdx ? 'font-medium text-foreground' : 'text-muted-foreground/60'"
@click="store.seek(line.t)"
>
{{ line.text }}
</p>
</div>
<div v-else class="flex flex-col gap-1.5 py-1">
<p v-if="!store.queue.length" class="text-sm text-muted-foreground/60">队列为空</p>
<button
v-for="(q, i) in store.queue"
:key="i"
type="button"
class="flex items-center gap-3 rounded-md px-2 py-1.5 text-left transition-colors"
:class="i === store.queueIndex ? 'bg-primary/10' : 'hover:bg-muted/40'"
@click="store.queueIndex = i; store.playItem(q)"
>
<span class="w-5 text-right text-xs tabular-nums text-muted-foreground">{{ i + 1 }}</span>
<div class="min-w-0 flex-1">
<div class="truncate text-sm" :class="i === store.queueIndex ? 'font-medium' : ''">{{ q.title }}</div>
<div class="truncate text-xs text-muted-foreground">{{ q.artistNames }}</div>
</div>
</button>
</div>
</ScrollArea>
</div>
</div>
<DialogClose as-child>
<button type="button" class="absolute right-4 top-4 z-10 rounded-md p-1.5 text-muted-foreground hover:bg-muted/40 hover:text-foreground">
<X class="size-5" />
</button>
</DialogClose>
</div>
</DialogContent>
</Dialog>
</template>
+120
View File
@@ -0,0 +1,120 @@
<script setup lang="ts">
import { computed } from 'vue'
import { toast } from 'vue-sonner'
import { Cloud, Music2, MoreHorizontal, Play, Plus } from '@lucide/vue'
import type { PlayableItem } from '@/stores/feiniuStore'
import { useFeiniuStore } from '@/stores/feiniuStore'
import { Button } from '@/components/ui/button'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuTrigger
} from '@/components/ui/dropdown-menu'
const props = defineProps<{
item: PlayableItem
active?: boolean
}>()
const store = useFeiniuStore()
const coverUrl = computed(() => {
if (props.item.source === 'feiniu' && props.item.coverId && store.mediaPrefix) {
return `${store.mediaPrefix}/cover?coverId=${encodeURIComponent(props.item.coverId)}&size=64`
}
return ''
})
const durationText = computed(() => store.fmtDuration(props.item.durationMs ? props.item.durationMs / 1000 : undefined))
function addToPlaylist(playlistId: string) {
store.addToPlaylist(playlistId, [props.item])
toast.success('已加入歌单')
}
async function uploadToFeiniu() {
try {
await store.uploadLocalTrack(props.item)
toast.success('已上传到飞牛曲库')
} catch (e) {
toast.error(String(e))
}
}
</script>
<template>
<div
class="group flex items-center gap-3 rounded-lg border px-3 py-2 transition-colors"
:class="active ? 'border-primary bg-primary/10' : 'border-border hover:bg-muted/40'"
>
<img
v-if="coverUrl"
:src="coverUrl"
class="size-10 shrink-0 rounded-md object-cover"
alt=""
loading="lazy"
@error="($event.target as HTMLImageElement).style.display = 'none'"
/>
<div v-else class="flex size-10 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground">
<Music2 class="size-4" />
</div>
<button
type="button"
class="flex size-10 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground opacity-0 transition-opacity group-hover:opacity-100"
:disabled="store.playing && store.current?.guid === item.guid"
@click="store.playItem(item)"
>
<Play class="size-4 translate-x-[1px]" />
</button>
<div class="min-w-0 flex-1">
<div class="truncate text-sm font-medium">{{ item.title }}</div>
<div class="truncate text-xs text-muted-foreground">
{{ item.artistNames }}<template v-if="item.artistNames && item.album"> · </template>{{ item.album }}
<span v-if="item.source === 'local'" class="ml-1 rounded bg-muted px-1 text-[10px]">本地</span>
</div>
</div>
<span class="shrink-0 text-xs tabular-nums text-muted-foreground">{{ durationText }}</span>
<DropdownMenu>
<DropdownMenuTrigger as-child>
<Button size="icon" variant="ghost" class="size-8">
<MoreHorizontal class="size-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" class="w-48">
<DropdownMenuLabel>{{ item.title }}</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem @click="store.playItem(item)">
<Play class="size-4" /> 播放
</DropdownMenuItem>
<DropdownMenuItem
v-if="item.source === 'local' && store.fnosLoggedIn && store.libraryNasPath"
:disabled="store.uploading"
@click="uploadToFeiniu"
>
<Cloud class="size-4" /> 上传到飞牛曲库
</DropdownMenuItem>
<DropdownMenuSub>
<DropdownMenuSubTrigger>
<Plus class="size-4" /> 加入歌单
</DropdownMenuSubTrigger>
<DropdownMenuSubContent class="w-48 max-h-64 overflow-y-auto">
<DropdownMenuItem v-if="store.playlists.length === 0" disabled>还没有歌单</DropdownMenuItem>
<DropdownMenuItem v-for="p in store.playlists" :key="p.id" @click="addToPlaylist(p.id)">
{{ p.name }}
</DropdownMenuItem>
</DropdownMenuSubContent>
</DropdownMenuSub>
</DropdownMenuContent>
</DropdownMenu>
</div>
</template>
@@ -0,0 +1,83 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { toast } from 'vue-sonner'
import { HardDriveDownload, Trash2 } from '@lucide/vue'
import { useFeiniuStore } from '@/stores/feiniuStore'
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
const store = useFeiniuStore()
const cacheMax = ref(5)
const cacheEnabled = ref(false)
onMounted(async () => {
await store.init()
cacheMode.value = store.cacheMode
cacheMax.value = 5
})
// 本地持久化缓存设置(后端 cache_fetch 用 settings.feiniu_cache_max_gb;这里给个默认)
const cacheMode = ref<'stream' | 'cache'>(store.cacheMode)
function setMode(v: unknown) {
const mode = v === 'cache' ? 'cache' : 'stream'
cacheMode.value = mode
store.setCacheMode(mode)
toast.success(mode === 'cache' ? '已开启缓存后播放' : '已切换为直连流式播放')
}
function setEnabled(v: boolean) {
cacheEnabled.value = v
if (!v) store.setCacheMode('stream')
}
async function clearAll() {
await store.clearCache()
toast.success('缓存已清空')
}
</script>
<template>
<div class="space-y-4">
<div class="flex items-center justify-between">
<div>
<div class="flex items-center gap-2">
<HardDriveDownload class="size-4 text-muted-foreground" />
<Label class="font-medium">播放缓存</Label>
</div>
<p class="mt-1 text-xs text-muted-foreground">
缓存后播放 NAS 音频缓存到本机{{ store.cacheStatus.usedMb }} MB / {{ store.cacheStatus.count }}
超出上限自动按 LRU 淘汰直连流式则每次在线拉取
</p>
</div>
<Switch v-model:model-value="cacheEnabled" @update:model-value="setEnabled" />
</div>
<template v-if="cacheEnabled">
<div class="flex items-center justify-between">
<Label class="text-muted-foreground">播放模式</Label>
<Select :model-value="cacheMode" @update:model-value="setMode">
<SelectTrigger class="w-44">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="stream">直连流式</SelectItem>
<SelectItem value="cache">缓存后播放</SelectItem>
</SelectContent>
</Select>
</div>
<div class="flex items-center justify-between">
<Label class="text-muted-foreground">当前占用</Label>
<span class="text-sm tabular-nums">{{ store.cacheStatus.usedMb }} MB{{ store.cacheStatus.count }} </span>
</div>
<Button variant="outline" size="sm" class="text-destructive" @click="clearAll">
<Trash2 class="size-4" /> 清空缓存
</Button>
</template>
</div>
</template>
@@ -0,0 +1,257 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { toast } from 'vue-sonner'
import { Check, Cloud, Loader2, Pencil, Plus, Power, Trash2 } from '@lucide/vue'
import { useFeiniuStore, type FeiniuConnection } from '@/stores/feiniuStore'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { Badge } from '@/components/ui/badge'
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle
} from '@/components/ui/dialog'
const store = useFeiniuStore()
const editing = ref<Partial<FeiniuConnection> | null>(null)
const editOpen = ref(false)
const password = ref('')
const testing = ref(false)
const fnosPassword = ref('')
const fnosFormOpen = ref(false)
/** 目标 fnOS 登录连接 */
const fnosTarget = ref<FeiniuConnection | null>(null)
function newForm() {
editing.value = { name: '', kind: 'lan', baseUrl: '', username: '', accessCode: '', insecure: false, fnId: '' }
password.value = ''
editOpen.value = true
}
function editForm(c: FeiniuConnection) {
editing.value = { ...c }
password.value = ''
editOpen.value = true
}
function openFnosLogin(c: FeiniuConnection) {
fnosTarget.value = c
fnosPassword.value = ''
fnosFormOpen.value = true
}
async function save() {
if (!editing.value) return
if (!editing.value.name?.trim() || !editing.value.baseUrl?.trim()) {
toast.error('请填写名称与服务器地址')
return
}
try {
const id = await store.saveConnection({
id: editing.value.id || '',
name: editing.value.name.trim(),
kind: editing.value.kind || 'lan',
baseUrl: editing.value.baseUrl.trim(),
username: editing.value.username || '',
accessCode: editing.value.accessCode || '',
insecure: !!editing.value.insecure,
fnId: editing.value.fnId || ''
})
if (password.value) {
await store.login(id, editing.value.username || '', password.value)
}
editOpen.value = false
toast.success('已保存')
} catch (e) {
toast.error(String(e))
}
}
async function test(c: FeiniuConnection) {
if (!password.value) {
toast.error('请输入密码再测试')
return
}
testing.value = true
try {
await store.testConnection(c.id, c.username, password.value)
toast.success('连接成功')
} catch (e) {
toast.error(String(e))
} finally {
testing.value = false
}
}
async function activate(c: FeiniuConnection) {
await store.activateConnection(c.id)
toast.success('已切换为激活连接')
}
async function logout(c: FeiniuConnection) {
await store.logout(c.id)
toast.success('已登出')
}
async function remove(c: FeiniuConnection) {
await store.deleteConnection(c.id)
toast.success('已删除')
}
async function fnosLogin() {
if (!fnosTarget.value) return
if (!fnosPassword.value) {
toast.error('请输入 NAS 密码')
return
}
try {
await store.fnosLogin(fnosTarget.value.username, fnosPassword.value)
fnosFormOpen.value = false
toast.success('NAS 文件服务已连接')
} catch (e) {
toast.error(String(e))
}
}
function kindLabel(k: string) {
return k === 'lan' ? '局域网' : k === 'frp' ? 'frp 域名' : 'FnConnect'
}
onMounted(() => store.refreshConnections())
</script>
<template>
<div class="space-y-3">
<div class="flex items-center justify-between">
<Label class="text-muted-foreground">飞牛音乐连接</Label>
<Button variant="outline" size="sm" @click="newForm">
<Plus class="size-4" /> 新建
</Button>
</div>
<div class="flex flex-col gap-2">
<div
v-for="c in store.connections"
:key="c.id"
class="flex items-center gap-3 rounded-lg border bg-card px-3 py-2"
>
<div class="min-w-0 flex-1">
<div class="flex items-center gap-2">
<span class="truncate text-sm font-medium">{{ c.name }}</span>
<Badge variant="secondary" class="text-[10px]">{{ kindLabel(c.kind) }}</Badge>
<Badge v-if="store.activeId === c.id" variant="default" class="text-[10px]">激活</Badge>
</div>
<div class="truncate text-xs text-muted-foreground">
{{ c.baseUrl }}<template v-if="c.username"> · {{ c.username }}</template>
</div>
</div>
<div class="flex shrink-0 items-center gap-1">
<span v-if="c.loggedIn" class="mr-1 flex items-center gap-1 text-xs text-emerald-600">
<Check class="size-3.5" /> 已登录
</span>
<Button v-if="store.activeId !== c.id" variant="ghost" size="icon" class="size-8" @click="activate(c)">
<Power class="size-4" />
</Button>
<Button v-if="store.activeId === c.id && !store.fnosLoggedIn" variant="ghost" size="icon" class="size-8" :title="`连接 NAS 文件服务(${c.username}`" @click="openFnosLogin(c)">
<Cloud class="size-4" />
</Button>
<Button variant="ghost" size="icon" class="size-8" @click="editForm(c)">
<Pencil class="size-4" />
</Button>
<Button v-if="c.loggedIn" variant="ghost" size="icon" class="size-8" @click="logout(c)">
<Power class="size-4" />
</Button>
<Button variant="ghost" size="icon" class="size-8 text-destructive" @click="remove(c)">
<Trash2 class="size-4" />
</Button>
</div>
</div>
<p v-if="!store.connections.length" class="text-xs text-muted-foreground">
还没有连接新建一个并填写 NAS 地址局域网 http://192.168.x.x:5666frp 域名或 FnConnect fnId
</p>
</div>
<Dialog v-model:open="editOpen">
<DialogContent class="sm:max-w-md">
<DialogHeader>
<DialogTitle>{{ editing?.id ? '编辑连接' : '新建连接' }}</DialogTitle>
</DialogHeader>
<div class="flex flex-col gap-3">
<div class="space-y-1.5">
<Label>名称</Label>
<Input v-model="editing!.name" placeholder="如:家里 NAS / frp 远程 / FnConnect" />
</div>
<div class="space-y-1.5">
<Label>类型</Label>
<div class="flex gap-2">
<Button
v-for="k in (['lan', 'frp', 'fnconnect'] as const)"
:key="k"
type="button"
size="sm"
:variant="editing!.kind === k ? 'default' : 'outline'"
@click="editing!.kind = k"
>
{{ kindLabel(k) }}
</Button>
</div>
</div>
<div v-if="editing!.kind === 'fnconnect'" class="space-y-1.5">
<Label>FnConnect fnIdfnos.net/xxx 或裸 id</Label>
<Input v-model="editing!.fnId" placeholder="fnos.net/zy2060537" />
<p class="text-xs text-muted-foreground">
保存后点登录会自动解析到可达地址服务器地址会回填
</p>
</div>
<div v-else class="space-y-1.5">
<Label>服务器地址</Label>
<Input v-model="editing!.baseUrl" placeholder="http://192.168.1.10:5666 或 https://xxx.xxx.com" />
</div>
<div class="space-y-1.5">
<Label>账号</Label>
<Input v-model="editing!.username" placeholder="飞牛音乐账号" />
</div>
<div class="space-y-1.5">
<Label>密码{{ password ? '' : '(留空则保留已存 token' }}</Label>
<Input v-model="password" type="password" placeholder="登录密码" />
</div>
<div class="flex items-center justify-between">
<Label class="text-muted-foreground">忽略 HTTPS 证书校验自签证书时勾选</Label>
<Switch v-model:model-value="editing!.insecure" />
</div>
</div>
<DialogFooter class="gap-2">
<Button variant="outline" :disabled="testing" @click="test(editing as unknown as FeiniuConnection)">
<Loader2 v-if="testing" class="size-4 animate-spin" /> 测试
</Button>
<Button @click="save">保存</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<!-- fnOS 文件服务登录上传到飞牛用 -->
<Dialog v-model:open="fnosFormOpen">
<DialogContent class="sm:max-w-sm">
<DialogHeader>
<DialogTitle>连接 NAS 文件服务</DialogTitle>
</DialogHeader>
<p class="text-xs text-muted-foreground">
账号{{ fnosTarget?.username }}连接后即可把本地音乐上传到飞牛曲库目录从曲库删除音乐
</p>
<div class="space-y-1.5">
<Label>NAS 密码</Label>
<Input v-model="fnosPassword" type="password" placeholder="NAS 登录密码" @keydown.enter="fnosLogin" />
</div>
<DialogFooter>
<Button variant="outline" @click="fnosFormOpen = false">取消</Button>
<Button @click="fnosLogin">连接</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
</template>
+47
View File
@@ -0,0 +1,47 @@
import type { ModuleConfig } from '@/types/module'
import type { SearchIndexItem } from '@/stores/searchIndex'
const searchItems: SearchIndexItem[] = [
{
title: '我的音乐',
description: '飞牛 NAS 曲库 / 本地曲库 / 自定义歌单与内嵌播放器',
keywords: ['音乐', 'music', '飞牛', 'NAS', '曲库', '歌单', '播放', '本地'],
tab: 'mymusic'
},
{
title: '发现音乐',
description: '多平台搜索歌曲并下载(本地 / 飞牛曲库)',
keywords: ['发现音乐', '搜索', '下载', '聚合', '在线', '网易云', 'qq', '酷狗'],
tab: 'discover'
},
{
title: '音乐设置',
description: '飞牛连接、播放缓存、下载目录与 Python 环境检查',
keywords: ['音乐设置', '飞牛连接', '缓存', '下载目录', '环境', 'python', 'musicdl'],
tab: 'settings'
}
]
export const moduleConfig: ModuleConfig = {
id: 'music',
name: '音乐',
icon: 'music',
description: '飞牛音乐客户端(NAS 曲库 + 本地曲库 + 发现添加)',
category: 'media',
defaultEnabled: true,
loader: () => import('./MusicModule.vue'),
searchItems,
lifecycle: {
onEnable: async () => {
// 桥接进程按需拉起(首次搜索/环境检测时自动启动),此处无需预启动
},
onDisable: () => {
// 禁用模块时停止桥接进程,释放 Python 进程
// 直接 invoke 避免模块 index.ts 导入 store 造成循环依赖
import('@tauri-apps/api/core')
.then(({ invoke }) => invoke('music_stop_bridge'))
.catch(() => {})
}
},
order: 55
}
+81
View File
@@ -0,0 +1,81 @@
/**
* 音乐源(musicdl MusicClient 名)→ 中文展示名映射。
* 未收录的源回退显示原始客户端名。
*/
export const SOURCE_NAMES: Record<string, string> = {
NeteaseMusicClient: '网易云',
QQMusicClient: 'QQ音乐',
KugouMusicClient: '酷狗',
KuwoMusicClient: '酷我',
MiguMusicClient: '咪咕',
QianqianMusicClient: '千千',
BilibiliMusicClient: 'B站音乐',
SodaMusicClient: '汽水音乐',
StreetVoiceMusicClient: '街声',
FiveSingMusicClient: '5SING',
BodianMusicClient: '波点音乐',
JooxMusicClient: 'JOOX',
MyFreeMP3MusicClient: 'MyFreeMP3',
XiaoBaiMusicClient: '小白音乐',
JBSouMusicClient: '煎饼搜',
TuneHubMusicClient: 'TuneHub',
MituMusicClient: '米兔音乐',
GequbaoMusicClient: '歌曲宝',
GequhaiMusicClient: '歌曲海',
KkwsMusicClient: '开开无损',
LivePOOMusicClient: '力音',
LiziYYMusicClient: '梨子音乐',
MGMP3MusicClient: '木瓜音乐',
SgogoMusicClient: '搜歌网',
TwoT58MusicClient: '爱听音乐',
XiagebaMusicClient: '下歌吧',
YinyuedaoMusicClient: '音乐岛',
ZhuolinMusicClient: '音乐解析',
FiveSongMusicClient: '5Song',
HTQYYMusicClient: '好听轻音乐',
ITingWaMusicClient: '听蛙纯音乐',
XimalayaMusicClient: '喜马拉雅',
QingtingMusicClient: '蜻蜓FM',
LizhiMusicClient: '荔枝FM',
LRTSMusicClient: '懒人听书',
AppleMusicClient: '苹果音乐',
ITunesMusicClient: '苹果播客',
DeezerMusicClient: 'Deezer',
QobuzMusicClient: 'Qobuz',
TIDALMusicClient: 'TIDAL',
SpotifyMusicClient: 'Spotify',
SoundCloudMusicClient: 'SoundCloud',
YouTubeMusicClient: '油管音乐',
SunoMusicClient: 'Suno',
MOOVMusicClient: '摩音符',
JamendoMusicClient: '简音乐',
FMAMusicClient: 'FMA',
JioSaavnMusicClient: 'JioSaavn',
OpenGameArtMusicClient: '开源游戏素材',
WikimediaCommonsMusicClient: '维基共享',
AudiusMusicClient: 'Audius',
CCMixterMusicClient: 'ccMixter'
}
export function sourceName(code: string): string {
return SOURCE_NAMES[code] ?? code.replace(/MusicClient$/, '')
}
/** 搜索页/设置页展示的常用源(中文平台为主,与已注册源求交后展示) */
export const PICKER_SOURCES: string[] = [
'NeteaseMusicClient',
'QQMusicClient',
'KugouMusicClient',
'KuwoMusicClient',
'MiguMusicClient',
'QianqianMusicClient',
'BilibiliMusicClient',
'SodaMusicClient',
'StreetVoiceMusicClient',
'FiveSingMusicClient',
'BodianMusicClient',
'MyFreeMP3MusicClient',
'XiaoBaiMusicClient',
'JBSouMusicClient',
'TuneHubMusicClient'
]
+532 -136
View File
@@ -1,6 +1,5 @@
<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import type { Component } from 'vue'
import { getCurrentWindow, currentMonitor } from '@tauri-apps/api/window'
import { LogicalSize } from '@tauri-apps/api/dpi'
import { emit, listen, type UnlistenFn } from '@tauri-apps/api/event'
@@ -11,7 +10,6 @@ import { commands } from '@/lib/bindings'
import { save } from '@tauri-apps/plugin-dialog'
import { toast } from 'vue-sonner'
import {
Square, Circle, MoveUpRight, ListOrdered, Pencil, Type, Grid3x3, Highlighter,
Eraser, Undo2, Redo2, Trash2, Copy, Save, X, Image as ImageIcon,
} from '@lucide/vue'
import { Button } from '@/components/ui/button'
@@ -20,43 +18,21 @@ import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover
import { Slider } from '@/components/ui/slider'
import { ScrollBar } from '@/components/ui/scroll-area'
import { ScrollAreaCorner, ScrollAreaRoot, ScrollAreaViewport } from 'reka-ui'
import { TOOL_KEYS, type CaptureData } from './types'
import {
TOOLS, TOOL_KEYS, COLORS, BLOCK_SIZES, ALPHAS, HANDLES,
type ToolType, type Annotation, type DrawableAnnotation, type Point,
type RectAnno, type EllipseAnno, type ArrowAnno, type PenAnno, type TextAnno,
type MosaicAnno, type HighlightAnno, type NumberAnno, type HandleDir,
type CaptureData,
} from './types'
import {
annoHasColor, annoHasLineWidth, annoBBox, hitTestAnno, hitTestTextZone,
isAnnoResizable, cloneAnno, applyMove, applyResize, drawSelectionBox,
} from './annotations'
// ===== 标注数据结构 =====
type ToolType = 'rect' | 'ellipse' | 'arrow' | 'number' | 'pen' | 'text' | 'mosaic' | 'highlight'
// ===== 标注类型(types.ts 共享,与覆盖层一致) =====
interface Point { x: number; y: number }
interface RectAnno { type: 'rect'; x1: number; y1: number; x2: number; y2: number; color: string; lineWidth: number }
interface EllipseAnno { type: 'ellipse'; x1: number; y1: number; x2: number; y2: number; color: string; lineWidth: number }
interface ArrowAnno { type: 'arrow'; x1: number; y1: number; x2: number; y2: number; color: string; lineWidth: number }
interface NumberAnno { type: 'number'; x: number; y: number; n: number; color: string; fontSize: number }
interface PenAnno { type: 'pen'; points: Point[]; color: string; lineWidth: number }
interface TextAnno { type: 'text'; x: number; y: number; text: string; color: string; fontSize: number }
interface MosaicAnno { type: 'mosaic'; x1: number; y1: number; x2: number; y2: number; blockSize: number }
interface HighlightAnno { type: 'highlight'; x1: number; y1: number; x2: number; y2: number; color: string; alpha: number }
type Annotation = RectAnno | EllipseAnno | ArrowAnno | NumberAnno | PenAnno | TextAnno | MosaicAnno | HighlightAnno
/** 可拖拽绘制的标注(不含文字/序号,文字与序号通过点击放置) */
type DrawableAnnotation = RectAnno | EllipseAnno | ArrowAnno | PenAnno | MosaicAnno | HighlightAnno
// ===== 工具与选项(与普通截图编辑栏一致) =====
const TOOLS: { value: ToolType; icon: Component; label: string }[] = [
{ value: 'rect', icon: Square, label: '矩形' },
{ value: 'ellipse', icon: Circle, label: '椭圆' },
{ value: 'arrow', icon: MoveUpRight, label: '箭头' },
{ value: 'number', icon: ListOrdered, label: '序号' },
{ value: 'pen', icon: Pencil, label: '画笔' },
{ value: 'text', icon: Type, label: '文字' },
{ value: 'mosaic', icon: Grid3x3, label: '马赛克' },
{ value: 'highlight', icon: Highlighter, label: '高亮' },
]
/** 与普通截图一致的颜色预设 */
const COLORS = ['#ef4444', '#f97316', '#eab308', '#22c55e', '#3b82f6', '#a855f7', '#000000', '#ffffff'] as const
const BLOCK_SIZES = [8, 10, 14] as const
const ALPHAS = [0.2, 0.4, 0.6] as const
// ===== 工具与选项(types.ts 共享 TOOLS/COLORS 等,与普通截图编辑栏一致) =====
// ===== 状态 =====
const canvasRef = ref<HTMLCanvasElement | null>(null)
@@ -89,6 +65,19 @@ let loadUnlisten: UnlistenFn | null = null
/** 马赛克结果缓存:标注参数不变时跳过重复像素化(长图上拖动其他标注不再卡顿) */
let mosaicCache: { key: string; canvas: HTMLCanvasElement } | null = null
/** Canvas 分层:静态层缓存底图 + 已提交标注,动态层只画 draft + 选中框 + 裁剪遮罩。
* 拖拽/调整标注时每帧只需 drawImage(静态层) + 少量动态元素,长图(数万像素高)不卡顿。 */
let staticCanvas: HTMLCanvasElement | null = null
let staticDirty = true
// 标注选中 / 拖拽 / 调整大小状态(与覆盖层一致)
const selectedAnnoIdx = ref(-1)
const draggingAnno = ref(false)
const resizingAnno = ref(false)
const annoResizeDir = ref<HandleDir | null>(null)
const annoDragStart = ref<{ p: Point; orig: Annotation } | null>(null)
const annoResizeStart = ref<{ p: Point; orig: Annotation } | null>(null)
// ===== 上下边界裁剪(长图场景,如滚动截图) =====
/** 保留区上边界(像素,相对图片顶部) */
const trimTop = ref(0)
@@ -97,32 +86,157 @@ const trimBottom = ref(0)
/** 正在拖动的裁剪手柄 */
const trimming = ref<'top' | 'bottom' | null>(null)
// 文字输入浮层
// 文字输入浮层textarea 支持多行)
const textInputPos = ref<Point | null>(null)
const textInputValue = ref('')
const textInputEl = ref<HTMLInputElement | null>(null)
const textInputEl = ref<HTMLTextAreaElement | null>(null)
/** 编辑已有文字标注时的索引(-1 = 新建) */
const editingTextAnnoIdx = ref(-1)
const fontSizePx = computed(() => currentLineWidth.value * 3 + 14)
const canUndo = computed(() => annotations.value.length > 0)
const canRedo = computed(() => redoStack.value.length > 0)
// ===== 画布重绘 =====
/** 颜色控件:双用途——选中标注时反映并修改其颜色,否则设置新标注默认色 */
const effectiveColor = computed<string>({
get() {
const i = selectedAnnoIdx.value
if (i >= 0 && i < annotations.value.length) {
const a = annotations.value[i]
if (annoHasColor(a)) return (a as { color: string }).color
}
return currentColor.value
},
set(v: string) {
currentColor.value = v
const i = selectedAnnoIdx.value
if (i >= 0 && i < annotations.value.length) {
const a = annotations.value[i]
if (annoHasColor(a)) {
(a as { color: string }).color = v
markDirtyRedraw()
}
}
},
})
/** 粗细控件:双用途——选中标注时反映并修改其 lineWidth,否则设置新标注默认粗细 */
const effectiveLineWidth = computed<number>({
get() {
const i = selectedAnnoIdx.value
if (i >= 0 && i < annotations.value.length) {
const a = annotations.value[i]
if (annoHasLineWidth(a)) return (a as { lineWidth: number }).lineWidth
}
return currentLineWidth.value
},
set(v: number) {
currentLineWidth.value = v
const i = selectedAnnoIdx.value
if (i >= 0 && i < annotations.value.length) {
const a = annotations.value[i]
if (annoHasLineWidth(a)) {
(a as { lineWidth: number }).lineWidth = v
markDirtyRedraw()
}
}
},
})
/** 控件是否可用(颜色/粗细),选中不支持该属性的标注时禁用 */
const colorEnabled = computed(() => {
const i = selectedAnnoIdx.value
if (i < 0 || i >= annotations.value.length) return true
return annoHasColor(annotations.value[i])
})
const lineWidthEnabled = computed(() => {
const i = selectedAnnoIdx.value
if (i < 0 || i >= annotations.value.length) return true
return annoHasLineWidth(annotations.value[i])
})
/** 选中标注的 bounding box(画布 1:1 物理坐标,用于手柄定位) */
const selectedAnnoBBox = computed(() => {
const i = selectedAnnoIdx.value
if (i < 0 || i >= annotations.value.length) return null
return annoBBox(annotations.value[i])
})
/** 选中标注是否可调整大小(pen/text/number 仅支持移动) */
const selectedAnnoResizable = computed(() => {
const i = selectedAnnoIdx.value
if (i < 0 || i >= annotations.value.length) return false
return isAnnoResizable(annotations.value[i])
})
/** 文字输入浮层样式(编辑已有文字时用原标注颜色和字号) */
const textInputStyle = computed(() => {
const p = textInputPos.value
if (!p) return {}
const ei = editingTextAnnoIdx.value
const anno = ei >= 0 ? annotations.value[ei] : null
const color = anno && anno.type === 'text' ? anno.color : currentColor.value
const fs = anno && anno.type === 'text' ? anno.fontSize : fontSizePx.value
return {
left: p.x + 'px',
top: p.y + 'px',
color,
fontSize: fs + 'px',
}
})
// ===== 画布重绘(静态层 + 动态层) =====
/** rAF 节流重绘:鼠标移动事件频率远高于 60fps,合并到下一帧统一重绘 */
let redrawRaf = 0
function scheduleRedraw() {
if (!redrawRaf) {
redrawRaf = requestAnimationFrame(() => {
redrawRaf = 0
redraw()
})
}
}
/** 标记静态层脏 + rAF 节流重绘(annotations 增删/修改后调用) */
function markDirtyRedraw() {
staticDirty = true
scheduleRedraw()
}
/** 重绘静态层(底图 + 已提交标注缓存)。annotations 增删/修改时标记脏。 */
function redrawStatic() {
const img = baseImage.value
if (!img) return
const canvas = canvasRef.value
if (!canvas) return
if (!staticCanvas) staticCanvas = document.createElement('canvas')
if (staticCanvas.width !== canvas.width || staticCanvas.height !== canvas.height) {
staticCanvas.width = canvas.width
staticCanvas.height = canvas.height
}
const sctx = staticCanvas.getContext('2d')
if (!sctx) return
sctx.clearRect(0, 0, staticCanvas.width, staticCanvas.height)
// 底图画在静态层:拖动标注时底图零成本复用
sctx.drawImage(img, 0, 0)
for (let i = 0; i < annotations.value.length; i++) {
// 正在编辑的文字标注由 textarea 显示,跳过绘制避免重影
if (i === editingTextAnnoIdx.value) continue
drawAnnotation(sctx, annotations.value[i])
}
staticDirty = false
}
function redraw() {
const canvas = canvasRef.value
const img = baseImage.value
if (!canvas || !img) return
const ctx = canvas.getContext('2d')
if (!ctx) return
if (staticDirty) redrawStatic()
ctx.clearRect(0, 0, canvas.width, canvas.height)
// 白色背景填充透明区
ctx.fillStyle = '#ffffff'
ctx.fillRect(0, 0, canvas.width, canvas.height)
// 底图
ctx.drawImage(img, 0, 0)
// 已提交标注
for (const anno of annotations.value) {
drawAnnotation(ctx, anno)
}
// 静态层合成(O(1) drawImage,跳过遍历所有标注)
if (staticCanvas) ctx.drawImage(staticCanvas, 0, 0)
// 进行中的草稿
if (draft.value) {
if (draft.value.type === 'mosaic') {
@@ -139,6 +253,11 @@ function redraw() {
if (top > 0) ctx.fillRect(0, 0, canvas.width, top)
if (bottom < canvas.height) ctx.fillRect(0, bottom, canvas.width, canvas.height - bottom)
}
// 选中标注:绘制虚线边框(手柄用 CSS DOM 定位,便于点击)
const si = selectedAnnoIdx.value
if (si >= 0 && si < annotations.value.length) {
drawSelectionBox(ctx, annoBBox(annotations.value[si]))
}
}
function drawAnnotation(ctx: CanvasRenderingContext2D, anno: Annotation) {
@@ -230,7 +349,10 @@ function drawText(ctx: CanvasRenderingContext2D, a: TextAnno) {
ctx.font = `${a.fontSize}px sans-serif`
ctx.fillStyle = a.color
ctx.textBaseline = 'top'
ctx.fillText(a.text, a.x, a.y)
const lines = a.text.split('\n')
lines.forEach((line, i) => {
ctx.fillText(line, a.x, a.y + i * a.fontSize)
})
}
function drawHighlight(ctx: CanvasRenderingContext2D, a: HighlightAnno) {
@@ -240,36 +362,54 @@ function drawHighlight(ctx: CanvasRenderingContext2D, a: HighlightAnno) {
ctx.globalAlpha = 1
}
/** 对区域做像素化(马赛克):取块平均色填回。
* 缓存:同一标注参数(位置/尺寸/块大小)重复 redraw 时直接 drawImage 复用,
* 避免长图上每次重绘都重新 getImageData + 像素化。 */
/** 马赛克 tmp 画布(复用,避免拖拽中反复创建) */
let mosaicTmp: HTMLCanvasElement | null = null
function getMosaicTmp(): HTMLCanvasElement {
if (!mosaicTmp) mosaicTmp = document.createElement('canvas')
return mosaicTmp
}
/**
* 马赛克:从**底图**取区域像素做块平均(与覆盖层一致)。
* 从底图而非画布取:画布上已绘制的其他标注不会被二次像素化;
* 且缓存命中时拖动其他标注零像素化开销(长图不卡顿)。
*/
function applyMosaic(ctx: CanvasRenderingContext2D, a: MosaicAnno) {
const canvas = ctx.canvas
const img = baseImage.value
if (!img) return
const block = Math.max(1, a.blockSize)
const sx = Math.max(0, Math.floor(Math.min(a.x1, a.x2)))
const sy = Math.max(0, Math.floor(Math.min(a.y1, a.y2)))
const sw = Math.min(canvas.width - sx, Math.floor(Math.abs(a.x2 - a.x1)))
const sh = Math.min(canvas.height - sy, Math.floor(Math.abs(a.y2 - a.y1)))
if (sw <= 0 || sh <= 0) return
const cacheKey = `${sx},${sy},${sw},${sh},${block}`
const x1 = Math.min(a.x1, a.x2)
const y1 = Math.min(a.y1, a.y2)
const w = Math.abs(a.x2 - a.x1)
const h = Math.abs(a.y2 - a.y1)
if (w < 1 || h < 1) return
const cw = Math.min(Math.ceil(w), img.naturalWidth - Math.floor(x1))
const ch = Math.min(Math.ceil(h), img.naturalHeight - Math.floor(y1))
if (cw < 1 || ch < 1) return
const cacheKey = `${a.x1},${a.y1},${a.x2},${a.y2},${block}`
if (mosaicCache?.key === cacheKey) {
ctx.drawImage(mosaicCache.canvas, sx, sy)
ctx.drawImage(mosaicCache.canvas, Math.floor(x1), Math.floor(y1))
return
}
const imageData = ctx.getImageData(sx, sy, sw, sh)
const tmp = getMosaicTmp()
tmp.width = cw
tmp.height = ch
const tctx = tmp.getContext('2d')
if (!tctx) return
tctx.drawImage(img, Math.floor(x1), Math.floor(y1), cw, ch, 0, 0, cw, ch)
const imageData = tctx.getImageData(0, 0, cw, ch)
const data = imageData.data
for (let by = 0; by < sh; by += block) {
for (let bx = 0; bx < sw; bx += block) {
let r = 0, g = 0, b = 0, alpha = 0, count = 0
const maxJ = Math.min(by + block, sh)
const maxI = Math.min(bx + block, sw)
for (let by = 0; by < ch; by += block) {
for (let bx = 0; bx < cw; bx += block) {
let r = 0, g = 0, b = 0, count = 0
const maxJ = Math.min(by + block, ch)
const maxI = Math.min(bx + block, cw)
for (let j = by; j < maxJ; j++) {
for (let i = bx; i < maxI; i++) {
const idx = (j * sw + i) * 4
const idx = (j * cw + i) * 4
r += data[idx]
g += data[idx + 1]
b += data[idx + 2]
alpha += data[idx + 3]
count++
}
}
@@ -277,25 +417,25 @@ function applyMosaic(ctx: CanvasRenderingContext2D, a: MosaicAnno) {
r = Math.round(r / count)
g = Math.round(g / count)
b = Math.round(b / count)
alpha = Math.round(alpha / count)
for (let j = by; j < maxJ; j++) {
for (let i = bx; i < maxI; i++) {
const idx = (j * sw + i) * 4
const idx = (j * cw + i) * 4
data[idx] = r
data[idx + 1] = g
data[idx + 2] = b
data[idx + 3] = alpha
data[idx + 3] = 255
}
}
}
}
ctx.putImageData(imageData, sx, sy)
// 缓存像素化结果(undo/redo/清空/新图加载时失效)
tctx.putImageData(imageData, 0, 0)
// 缓存结果(undo/redo/清空/新图加载时失效)
const cached = document.createElement('canvas')
cached.width = sw
cached.height = sh
cached.getContext('2d')?.putImageData(imageData, 0, 0)
cached.width = cw
cached.height = ch
cached.getContext('2d')?.drawImage(tmp, 0, 0)
mosaicCache = { key: cacheKey, canvas: cached }
ctx.drawImage(cached, Math.floor(x1), Math.floor(y1))
}
/** 马赛克拖拽中的虚线框预览(避免每帧像素化开销) */
@@ -307,23 +447,88 @@ function drawMosaicDraft(ctx: CanvasRenderingContext2D, a: MosaicAnno) {
ctx.setLineDash([])
}
// ===== 鼠标交互 =====
// ===== 鼠标交互(与覆盖层一致:选中 / 拖拽 / 调整大小 / 绘制) =====
function getPoint(e: MouseEvent): Point {
const canvas = canvasRef.value!
const rect = canvas.getBoundingClientRect()
const scaleX = canvas.width / rect.width
const scaleY = canvas.height / rect.height
return { x: (e.clientX - rect.left) * scaleX, y: (e.clientY - rect.top) * scaleY }
return {
x: Math.min(canvas.width, Math.max(0, (e.clientX - rect.left) * scaleX)),
y: Math.min(canvas.height, Math.max(0, (e.clientY - rect.top) * scaleY)),
}
}
/** 标注手柄位置(画布 1:1,物理坐标 = CSS 偏移) */
function annoHandleStyle(dir: HandleDir) {
const bb = selectedAnnoBBox.value
if (!bb) return { display: 'none' }
let cx = 0
let cy = 0
switch (dir) {
case 'nw': cx = bb.x; cy = bb.y; break
case 'n': cx = bb.x + bb.w / 2; cy = bb.y; break
case 'ne': cx = bb.x + bb.w; cy = bb.y; break
case 'e': cx = bb.x + bb.w; cy = bb.y + bb.h / 2; break
case 'se': cx = bb.x + bb.w; cy = bb.y + bb.h; break
case 's': cx = bb.x + bb.w / 2; cy = bb.y + bb.h; break
case 'sw': cx = bb.x; cy = bb.y + bb.h; break
case 'w': cx = bb.x; cy = bb.y + bb.h / 2; break
}
return { left: cx + 'px', top: cy + 'px' }
}
/** 标注手柄按下:进入调整大小模式 */
function onAnnoHandleMouseDown(dir: HandleDir, e: MouseEvent) {
if (selectedAnnoIdx.value < 0) return
e.preventDefault()
e.stopPropagation()
const p = getPoint(e)
const cur = annotations.value[selectedAnnoIdx.value]
if (!cur) return
resizingAnno.value = true
annoResizeDir.value = dir
annoResizeStart.value = { p: { ...p }, orig: cloneAnno(cur) }
}
function onMouseDown(e: MouseEvent) {
if (!baseImage.value || !loaded.value) return
const p = getPoint(e)
// 文字工具:阻止 mousedown 默认行为,防止浏览器抢占焦点导致 textarea 立即失焦
if (currentTool.value === 'text') {
startTextInput(p)
e.preventDefault()
}
const p = getPoint(e)
// 点击已有标注 → 选中并进入拖拽模式
const idx = hitTestAnno(annotations.value, p)
if (idx >= 0) {
// 先提交未完成的文字输入(点击别处放置/选中时,旧输入框提交)
if (textInputPos.value) commitText()
// 文字工具 + 点击文字标注:内容区→编辑,边框区→移动
if (currentTool.value === 'text' && annotations.value[idx].type === 'text') {
const zone = hitTestTextZone(annotations.value[idx] as TextAnno, p)
if (zone === 'core') {
openTextInput(p, idx)
return
}
// border → 选中并拖拽(移动),继续往下走
}
selectedAnnoIdx.value = idx
draggingAnno.value = true
annoDragStart.value = { p: { ...p }, orig: cloneAnno(annotations.value[idx]) }
markDirtyRedraw()
return
}
// 序号:点击即放置(自增),不进入拖拽
// 点击空白处 → 取消选中,开始绘制新标注
selectedAnnoIdx.value = -1
beginDraft(p)
}
function beginDraft(p: Point) {
if (currentTool.value === 'text') {
openTextInput(p)
return
}
// 序号:点击即放置(自增),不进入拖拽;放置后自动选中便于移动
if (currentTool.value === 'number') {
annotations.value.push({
type: 'number',
@@ -335,45 +540,61 @@ function onMouseDown(e: MouseEvent) {
})
numberSeq.value++
redoStack.value = []
redraw()
selectedAnnoIdx.value = annotations.value.length - 1
markDirtyRedraw()
return
}
isDrawing.value = true
const color = currentColor.value
const lw = currentLineWidth.value
switch (currentTool.value) {
case 'rect':
draft.value = { type: 'rect', x1: p.x, y1: p.y, x2: p.x, y2: p.y, color: currentColor.value, lineWidth: currentLineWidth.value }
draft.value = { type: 'rect', x1: p.x, y1: p.y, x2: p.x, y2: p.y, color, lineWidth: lw }
break
case 'ellipse':
draft.value = { type: 'ellipse', x1: p.x, y1: p.y, x2: p.x, y2: p.y, color: currentColor.value, lineWidth: currentLineWidth.value }
draft.value = { type: 'ellipse', x1: p.x, y1: p.y, x2: p.x, y2: p.y, color, lineWidth: lw }
break
case 'arrow':
draft.value = { type: 'arrow', x1: p.x, y1: p.y, x2: p.x, y2: p.y, color: currentColor.value, lineWidth: currentLineWidth.value }
draft.value = { type: 'arrow', x1: p.x, y1: p.y, x2: p.x, y2: p.y, color, lineWidth: lw }
break
case 'pen':
draft.value = { type: 'pen', points: [p], color: currentColor.value, lineWidth: currentLineWidth.value }
draft.value = { type: 'pen', points: [p], color, lineWidth: lw }
break
case 'mosaic':
draft.value = { type: 'mosaic', x1: p.x, y1: p.y, x2: p.x, y2: p.y, blockSize: blockSize.value }
break
case 'highlight':
draft.value = { type: 'highlight', x1: p.x, y1: p.y, x2: p.x, y2: p.y, color: currentColor.value, alpha: highlightAlpha.value }
draft.value = { type: 'highlight', x1: p.x, y1: p.y, x2: p.x, y2: p.y, color, alpha: highlightAlpha.value }
break
}
redraw()
}
// ===== 画布重绘(rAF 节流) =====
/** 连续鼠标移动时每帧最多重绘一次,避免 mousemove 高频事件(每帧多次)触发多次全量重绘 */
let redrawRaf = 0
function scheduleRedraw() {
if (redrawRaf) return
redrawRaf = requestAnimationFrame(() => {
redrawRaf = 0
redraw()
})
scheduleRedraw()
}
function onMouseMove(e: MouseEvent) {
if (resizingAnno.value && annoResizeStart.value) {
// 调整选中标注大小
const p = getPoint(e)
const dx = p.x - annoResizeStart.value.p.x
const dy = p.y - annoResizeStart.value.p.y
const cur = annotations.value[selectedAnnoIdx.value]
if (cur && annoResizeDir.value) {
applyResize(cur, annoResizeStart.value.orig, annoResizeDir.value, dx, dy)
markDirtyRedraw()
}
return
}
if (draggingAnno.value && annoDragStart.value) {
// 移动选中标注
const p = getPoint(e)
const dx = p.x - annoDragStart.value.p.x
const dy = p.y - annoDragStart.value.p.y
const cur = annotations.value[selectedAnnoIdx.value]
if (cur) {
applyMove(cur, annoDragStart.value.orig, dx, dy)
markDirtyRedraw()
}
return
}
if (!isDrawing.value || !draft.value) return
const p = getPoint(e)
const d = draft.value
@@ -387,6 +608,19 @@ function onMouseMove(e: MouseEvent) {
}
function onMouseUp() {
if (resizingAnno.value) {
// 调整大小结束
resizingAnno.value = false
annoResizeDir.value = null
annoResizeStart.value = null
return
}
if (draggingAnno.value) {
// 拖拽结束(点击未移动时保持选中)
draggingAnno.value = false
annoDragStart.value = null
return
}
if (!isDrawing.value || !draft.value) return
const d = draft.value
// 过滤无效(空)标注
@@ -399,10 +633,14 @@ function onMouseUp() {
if (valid) {
annotations.value.push(d)
redoStack.value = []
// 自动选中新创建的标注,便于立即调整位置和大小
selectedAnnoIdx.value = annotations.value.length - 1
} else {
selectedAnnoIdx.value = -1
}
draft.value = null
isDrawing.value = false
redraw()
markDirtyRedraw()
}
// ===== 上下边界裁剪拖拽 =====
@@ -422,7 +660,7 @@ function onTrimMove(e: MouseEvent) {
} else {
trimBottom.value = Math.max(trimTop.value + 10, Math.min(Math.round(p.y), h))
}
redraw()
scheduleRedraw()
}
function onTrimUp() {
@@ -431,11 +669,30 @@ function onTrimUp() {
window.removeEventListener('mouseup', onTrimUp)
}
// ===== 文字输入 =====
function startTextInput(p: Point) {
textInputPos.value = { x: p.x, y: p.y }
// ===== 文字输入(textarea 多行,与覆盖层一致) =====
function openTextInput(p: Point, editIdx: number = -1) {
// 先提交当前未完成的文字(点击别处放置新文字时,旧输入框会失焦)
commitText()
if (editIdx >= 0 && editIdx < annotations.value.length) {
const anno = annotations.value[editIdx]
if (anno && anno.type === 'text') {
editingTextAnnoIdx.value = editIdx
textInputPos.value = { x: anno.x, y: anno.y }
textInputValue.value = anno.text
markDirtyRedraw() // 隐藏原文字,由 textarea 显示
nextTick(() => {
textInputEl.value?.focus()
autoResizeTextarea()
})
return
}
}
textInputPos.value = p
textInputValue.value = ''
nextTick(() => textInputEl.value?.focus())
nextTick(() => {
textInputEl.value?.focus()
autoResizeTextarea()
})
}
function commitText() {
@@ -444,6 +701,26 @@ function commitText() {
textInputPos.value = null
const value = textInputValue.value.trim()
textInputValue.value = ''
const editIdx = editingTextAnnoIdx.value
editingTextAnnoIdx.value = -1
// 编辑已有文字标注
if (editIdx >= 0 && editIdx < annotations.value.length) {
const anno = annotations.value[editIdx]
if (anno && anno.type === 'text') {
if (value) {
anno.text = value
selectedAnnoIdx.value = editIdx
} else {
// 空文字 → 删除
annotations.value.splice(editIdx, 1)
selectedAnnoIdx.value = -1
redoStack.value = []
}
markDirtyRedraw()
}
return
}
// 新建文字标注
if (value) {
annotations.value.push({
type: 'text',
@@ -454,13 +731,37 @@ function commitText() {
fontSize: fontSizePx.value,
})
redoStack.value = []
redraw()
// 自动选中新创建的文字
selectedAnnoIdx.value = annotations.value.length - 1
markDirtyRedraw()
}
}
function cancelText() {
textInputPos.value = null
textInputValue.value = ''
editingTextAnnoIdx.value = -1
markDirtyRedraw() // 恢复显示原文字标注
}
/** 自动调整 textarea 高度以适应内容 */
function autoResizeTextarea() {
const el = textInputEl.value
if (!el) return
el.style.height = 'auto'
el.style.height = el.scrollHeight + 'px'
}
// ===== 删除选中标注 =====
function deleteSelectedAnno() {
const i = selectedAnnoIdx.value
if (i < 0 || i >= annotations.value.length) return
const a = annotations.value[i]
if (a.type === 'number') numberSeq.value = Math.max(1, numberSeq.value - 1)
annotations.value.splice(i, 1)
selectedAnnoIdx.value = -1
redoStack.value = []
markDirtyRedraw()
}
// ===== 撤销 / 重做 / 清空 =====
@@ -470,8 +771,10 @@ function undo() {
redoStack.value.push(last)
// 撤销序号标注后回退序号,避免后续新增序号跳号
if (last.type === 'number') numberSeq.value = Math.max(1, numberSeq.value - 1)
// 撤销后选中可能失效,重置
if (selectedAnnoIdx.value >= annotations.value.length) selectedAnnoIdx.value = -1
mosaicCache = null
redraw()
markDirtyRedraw()
}
function redo() {
@@ -479,16 +782,18 @@ function redo() {
const a = redoStack.value.pop()!
annotations.value.push(a)
if (a.type === 'number') numberSeq.value = a.n + 1
selectedAnnoIdx.value = -1
mosaicCache = null
redraw()
markDirtyRedraw()
}
function clearAll() {
annotations.value = []
redoStack.value = []
numberSeq.value = 1
selectedAnnoIdx.value = -1
mosaicCache = null
redraw()
markDirtyRedraw()
}
// ===== 导出 =====
@@ -589,7 +894,16 @@ async function closeWindow() {
isDrawing.value = false
annotations.value = []
redoStack.value = []
selectedAnnoIdx.value = -1
draggingAnno.value = false
resizingAnno.value = false
annoDragStart.value = null
annoResizeStart.value = null
editingTextAnnoIdx.value = -1
textInputPos.value = null
mosaicCache = null
mosaicTmp = null
staticDirty = true
if (objectUrl) {
URL.revokeObjectURL(objectUrl)
objectUrl = ''
@@ -623,10 +937,10 @@ function onStorageChange(e: StorageEvent) {
if (e.key === STORAGE_KEYS.appSettings) applyTheme()
}
/** 自定义颜色选择:更新 customColor 并设为当前颜色 */
/** 自定义颜色选择:更新 customColor 并设为当前颜色/选中标注颜色 */
function onCustomColorPick(color: string) {
customColor.value = color
currentColor.value = color
effectiveColor.value = color
}
/**
@@ -657,6 +971,17 @@ function onKeyDown(e: KeyboardEvent) {
// 输入控件(文字标注 / 取色器 / 滑杆)聚焦时不响应快捷键
const t = e.target as HTMLElement | null
if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return
// 文字输入浮层激活时:Ctrl+Enter 提交,Esc 取消(普通 Enter 留给 textarea 换行)
if (textInputPos.value) {
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
e.preventDefault()
commitText()
} else if (e.key === 'Escape') {
e.stopPropagation()
cancelText()
}
return
}
const k = e.key.toLowerCase()
const mod = e.ctrlKey || e.metaKey
if (mod && !e.shiftKey && k === 'z') {
@@ -679,6 +1004,12 @@ function onKeyDown(e: KeyboardEvent) {
void saveToFile()
return
}
// Delete/Backspace 删除选中的标注
if ((e.key === 'Delete' || e.key === 'Backspace') && selectedAnnoIdx.value >= 0) {
e.preventDefault()
deleteSelectedAnno()
return
}
if (k === 'enter') {
e.preventDefault()
void copyAndClose()
@@ -686,7 +1017,13 @@ function onKeyDown(e: KeyboardEvent) {
}
if (k === 'escape') {
e.preventDefault()
void closeWindow()
// 选中状态下 Esc 先取消选中,再次按才关闭窗口(与覆盖层一致)
if (selectedAnnoIdx.value >= 0) {
selectedAnnoIdx.value = -1
markDirtyRedraw()
} else {
void closeWindow()
}
return
}
if (!mod && !e.altKey) {
@@ -723,6 +1060,14 @@ async function loadPendingImage() {
isDrawing.value = false
numberSeq.value = 1
mosaicCache = null
staticDirty = true
selectedAnnoIdx.value = -1
draggingAnno.value = false
resizingAnno.value = false
annoDragStart.value = null
annoResizeStart.value = null
editingTextAnnoIdx.value = -1
textInputPos.value = null
loadError.value = false
trimTop.value = 0
trimBottom.value = img.naturalHeight
@@ -825,13 +1170,15 @@ onUnmounted(() => {
<div class="h-6 w-px bg-border" />
<!-- 颜色当前色 badge + 弹层自定义取色 + 默认色板与普通截图一致 -->
<!-- 颜色当前色 badge + 弹层双用途选中标注时修改其颜色与普通截图一致 -->
<Popover v-model:open="colorPickerOpen">
<PopoverTrigger as-child>
<button
class="color-badge"
:style="{ '--swatch-color': currentColor }"
:aria-label="'当前颜色 ' + currentColor"
:class="{ disabled: !colorEnabled }"
:style="{ '--swatch-color': effectiveColor }"
:aria-label="'当前颜色 ' + effectiveColor"
:disabled="!colorEnabled"
/>
</PopoverTrigger>
<PopoverContent class="w-auto p-3" align="start">
@@ -847,9 +1194,9 @@ onUnmounted(() => {
<TooltipTrigger as-child>
<button
class="color-swatch-mini"
:class="{ active: currentColor === c }"
:class="{ active: effectiveColor === c }"
:style="{ backgroundColor: c }"
@click="currentColor = c"
@click="effectiveColor = c"
/>
</TooltipTrigger>
<TooltipContent>{{ c }}</TooltipContent>
@@ -859,24 +1206,25 @@ onUnmounted(() => {
</PopoverContent>
</Popover>
<!-- 粗细 badge + 弹层Slider与普通截图一致 -->
<!-- 粗细 badge + 弹层双用途选中标注时修改其粗细与普通截图一致 -->
<Popover v-model:open="widthPickerOpen">
<PopoverTrigger as-child>
<button class="width-badge">{{ currentLineWidth }}</button>
<button class="width-badge" :class="{ disabled: !lineWidthEnabled }" :disabled="!lineWidthEnabled">{{ effectiveLineWidth }}</button>
</PopoverTrigger>
<PopoverContent class="w-auto p-3" align="start">
<div class="width-popover">
<div class="width-popover-header">
<span>粗细</span>
<span class="width-popover-value">{{ currentLineWidth }}</span>
<span class="width-popover-value">{{ effectiveLineWidth }}</span>
</div>
<Slider
:model-value="[currentLineWidth]"
:model-value="[effectiveLineWidth]"
:min="1"
:max="16"
:step="1"
:disabled="!lineWidthEnabled"
class="width-slider"
@update:model-value="(v: number[] | undefined) => { if (v && v.length) currentLineWidth = v[0] }"
@update:model-value="(v: number[] | undefined) => { if (v && v.length) effectiveLineWidth = v[0] }"
/>
</div>
</PopoverContent>
@@ -1009,7 +1357,7 @@ onUnmounted(() => {
<canvas
ref="canvasRef"
class="block max-w-none select-none"
:style="{ cursor: currentTool === 'text' ? 'text' : 'crosshair' }"
:style="{ cursor: draggingAnno || resizingAnno ? 'move' : currentTool === 'text' ? 'text' : 'crosshair' }"
@mousedown="onMouseDown"
/>
<!-- 上下边界裁剪手柄(拖动调整保留区,导出按此裁切) -->
@@ -1027,25 +1375,31 @@ onUnmounted(() => {
>
<span class="trim-grip">下 {{ Math.round(trimBottom) }}</span>
</div>
<input
<!-- 选中标注的调整手柄(画布 1:1,物理坐标直接定位;pen/text/number 仅移动不显示) -->
<template v-if="selectedAnnoIdx >= 0 && selectedAnnoResizable">
<div
v-for="dir in HANDLES"
:key="'anno-h-' + dir"
class="anno-handle"
:class="'handle-' + dir"
:style="annoHandleStyle(dir)"
@mousedown.stop.prevent="onAnnoHandleMouseDown(dir, $event)"
/>
</template>
<!-- 文字输入浮层:textarea 支持多行,Ctrl+Enter 提交 / Esc 取消 / blur 提交 -->
<textarea
v-if="textInputPos"
id="screenshot-editor-text-input"
ref="textInputEl"
v-model="textInputValue"
class="absolute z-10 bg-transparent outline-none"
:style="{
left: textInputPos.x + 'px',
top: textInputPos.y + 'px',
color: currentColor,
fontSize: fontSizePx + 'px',
fontFamily: 'sans-serif',
lineHeight: '1',
padding: '0 2px',
border: '1px dashed ' + currentColor,
}"
placeholder="输入文字"
@keydown.enter.prevent="commitText"
@keydown.esc.prevent="cancelText"
class="absolute z-10 bg-transparent outline-none resize-none overflow-hidden"
:style="textInputStyle"
placeholder="输入文字 (Ctrl+Enter 完成)"
rows="1"
@keydown.enter.ctrl.prevent="commitText"
@keydown.esc.stop.prevent="cancelText"
@blur="commitText"
@input="autoResizeTextarea"
/>
</div>
</div>
@@ -1074,6 +1428,48 @@ onUnmounted(() => {
</template>
<style scoped>
/* 文字输入浮层:textarea 多行(与覆盖层 .text-input 一致) */
#screenshot-editor-text-input {
position: absolute;
z-index: 10;
background: transparent;
outline: none;
border: 1px dashed currentColor;
font-family: sans-serif;
line-height: 1;
padding: 0 2px;
min-width: 20px;
resize: none;
overflow: hidden;
white-space: pre;
word-break: keep-all;
box-sizing: border-box;
height: auto;
}
/* 标注调整手柄(与覆盖层 .handle 一致;画布 1:1,物理坐标直接定位) */
.anno-handle {
position: absolute;
width: 9px;
height: 9px;
background: #fff;
border: 2px solid #3b82f6;
border-radius: 2px;
transform: translate(-50%, -50%);
z-index: 15;
}
.handle-nw, .handle-se { cursor: nwse-resize; }
.handle-ne, .handle-sw { cursor: nesw-resize; }
.handle-n, .handle-s { cursor: ns-resize; }
.handle-e, .handle-w { cursor: ew-resize; }
/* badge 禁用态(选中不支持该属性的标注时) */
.color-badge.disabled, .width-badge.disabled {
opacity: 0.4;
cursor: not-allowed;
}
.color-badge.disabled:hover { transform: none; }
/* 上下边界裁剪手柄:跨画布宽度的可拖拽蓝线 + 居中数值标签 */
.trim-bar {
position: absolute;
+22 -227
View File
@@ -20,6 +20,10 @@ import {
type MosaicAnno, type HighlightAnno, type NumberAnno,
type ScreenshotBeginPayload,
} from './types'
import {
annoHasColor, annoHasLineWidth, annoBBox, hitTestAnno, hitTestTextZone,
isAnnoResizable, cloneAnno, applyMove, applyResize, drawSelectionBox,
} from './annotations'
// ===== 窗口 / 底图 =====
const win = getCurrentWindow()
@@ -129,7 +133,6 @@ const resizingAnno = ref(false)
const annoResizeDir = ref<HandleDir | null>(null)
const annoDragStart = ref<{ p: Point; orig: Annotation } | null>(null)
const annoResizeStart = ref<{ p: Point; orig: Annotation } | null>(null)
let measureCtx: CanvasRenderingContext2D | null = null
/** Canvas 分层:静态层缓存已提交标注,动态层只画 draft + 选中框。
* 绘制 draft(画笔/矩形等)时 annotations 不变,只需 drawImage(静态层) + draftO(1) 合成。 */
@@ -208,18 +211,9 @@ const canUndo = computed(() => annotations.value.length > 0)
const canRedo = computed(() => redoStack.value.length > 0)
const fontSizePx = computed(() => currentLineWidth.value * 3 + 14)
/** 选中标注是否有可变颜色属性 */
function annoHasColor(a: Annotation): boolean {
return a.type !== 'mosaic'
}
/** 选中标注是否有粗细概念(lineWidth) */
function annoHasLineWidth(a: Annotation): boolean {
return a.type === 'rect' || a.type === 'ellipse' || a.type === 'arrow' || a.type === 'pen'
}
/** 选中标注是否有可变颜色属性 / 粗细概念:见 annotations.ts 共享实现 */
/**
* 颜色控件:双用途——选中标注时反映并修改其颜色,否则设置新标注默认色
*/
/** 颜色控件:双用途——选中标注时反映并修改其颜色,否则设置新标注默认色 */
const effectiveColor = computed<string>({
get() {
const i = selectedAnnoIdx.value
@@ -819,7 +813,7 @@ function onRegionMouseDown(e: MouseEvent) {
}
const p = canvasPoint(e)
// 点击已有标注 → 选中并进入拖拽模式
const idx = hitTestAnno(p)
const idx = hitTestAnno(annotations.value, p)
if (idx >= 0) {
// 先提交未完成的文字输入(点击别处放置/选中时,旧输入框提交)
if (textInputPos.value) commitText()
@@ -1333,220 +1327,8 @@ function drawMosaicDraft(ctx: CanvasRenderingContext2D, a: MosaicAnno) {
}
// ===== 标注选中 / 编辑 =====
/** 获取文字测量用的 canvas 上下文(惰性创建一次复用) */
function getMeasureCtx(): CanvasRenderingContext2D | null {
if (!measureCtx) {
const c = document.createElement('canvas')
measureCtx = c.getContext('2d')
}
return measureCtx
}
/** 估算文字宽高(用 ctx.measureText 测宽,多行取最宽行,高 = 行数 × fontSize
* 结果缓存:相同 text+fontSize 的测量结果不变,避免 hitTest / annoBBox 重复调用开销 */
const measureCache = new Map<string, { w: number; h: number }>()
function measureText(text: string, fontSize: number): { w: number; h: number } {
const key = `${fontSize}\0${text}`
const cached = measureCache.get(key)
if (cached) return cached
const ctx = getMeasureCtx()
const lines = text.split('\n')
let result: { w: number; h: number }
if (!ctx) {
const maxLen = Math.max(1, ...lines.map(l => l.length))
result = { w: fontSize * maxLen * 0.6, h: fontSize * lines.length }
} else {
ctx.font = `${fontSize}px sans-serif`
let maxW = 0
for (const line of lines) {
const m = ctx.measureText(line)
if (m.width > maxW) maxW = m.width
}
result = { w: Math.ceil(maxW), h: fontSize * lines.length }
}
measureCache.set(key, result)
return result
}
/** 标注 bounding box(物理像素坐标) */
function annoBBox(anno: Annotation): { x: number; y: number; w: number; h: number } {
switch (anno.type) {
case 'rect':
case 'ellipse':
case 'mosaic':
case 'highlight':
case 'arrow': {
const x = Math.min(anno.x1, anno.x2)
const y = Math.min(anno.y1, anno.y2)
return { x, y, w: Math.abs(anno.x2 - anno.x1), h: Math.abs(anno.y2 - anno.y1) }
}
case 'pen': {
if (anno.points.length === 0) return { x: 0, y: 0, w: 0, h: 0 }
let minX = Infinity
let minY = Infinity
let maxX = -Infinity
let maxY = -Infinity
for (const pt of anno.points) {
if (pt.x < minX) minX = pt.x
if (pt.y < minY) minY = pt.y
if (pt.x > maxX) maxX = pt.x
if (pt.y > maxY) maxY = pt.y
}
return { x: minX, y: minY, w: maxX - minX, h: maxY - minY }
}
case 'text': {
const { w, h } = measureText(anno.text, anno.fontSize)
return { x: anno.x, y: anno.y, w, h }
}
case 'number': {
const r = anno.fontSize / 2
return { x: anno.x - r, y: anno.y - r, w: anno.fontSize, h: anno.fontSize }
}
}
}
/** 点到线段的距离 */
function distToSegment(p: Point, a: Point, b: Point): number {
const dx = b.x - a.x
const dy = b.y - a.y
const len2 = dx * dx + dy * dy
if (len2 === 0) return Math.hypot(p.x - a.x, p.y - a.y)
let t = ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2
t = Math.max(0, Math.min(1, t))
const cx = a.x + t * dx
const cy = a.y + t * dy
return Math.hypot(p.x - cx, p.y - cy)
}
/** 文字标注区域检测:core=文字内容区(编辑),border=边框区(移动)null=未命中 */
function hitTestTextZone(anno: TextAnno, p: Point): 'core' | 'border' | null {
const { w, h } = measureText(anno.text, anno.fontSize)
const x1 = anno.x, y1 = anno.y
const x2 = anno.x + w, y2 = anno.y + h
const pad = 8
if (p.x < x1 - pad || p.x > x2 + pad || p.y < y1 - pad || p.y > y2 + pad) return null
if (p.x >= x1 && p.x <= x2 && p.y >= y1 && p.y <= y2) return 'core'
return 'border'
}
/** 点击测试单个标注 */
function hitTestSingle(anno: Annotation, p: Point): boolean {
switch (anno.type) {
case 'rect':
case 'ellipse':
case 'mosaic':
case 'highlight': {
const x1 = Math.min(anno.x1, anno.x2)
const y1 = Math.min(anno.y1, anno.y2)
const x2 = Math.max(anno.x1, anno.x2)
const y2 = Math.max(anno.y1, anno.y2)
const pad = Math.max(4, anno.type === 'rect' || anno.type === 'ellipse' ? anno.lineWidth : 2)
return p.x >= x1 - pad && p.x <= x2 + pad && p.y >= y1 - pad && p.y <= y2 + pad
}
case 'arrow':
return distToSegment(p, { x: anno.x1, y: anno.y1 }, { x: anno.x2, y: anno.y2 }) <= Math.max(6, anno.lineWidth)
case 'pen': {
for (let i = 1; i < anno.points.length; i++) {
if (distToSegment(p, anno.points[i - 1], anno.points[i]) <= Math.max(6, anno.lineWidth)) return true
}
return false
}
case 'text': {
return hitTestTextZone(anno, p) !== null
}
case 'number': {
const r = anno.fontSize / 2
const dx = p.x - anno.x
const dy = p.y - anno.y
return dx * dx + dy * dy <= r * r
}
}
}
/** 点击测试:返回命中的标注索引(-1 未命中),从后往前测试(后画的在上层) */
function hitTestAnno(p: Point): number {
for (let i = annotations.value.length - 1; i >= 0; i--) {
if (hitTestSingle(annotations.value[i], p)) return i
}
return -1
}
/** 标注是否可调整大小(pen/text/number 仅支持移动) */
function isAnnoResizable(anno: Annotation): boolean {
return anno.type === 'rect' || anno.type === 'ellipse' || anno.type === 'arrow' || anno.type === 'mosaic' || anno.type === 'highlight'
}
/** 深拷贝标注(用于拖拽/调整大小时保存原始快照) */
function cloneAnno(a: Annotation): Annotation {
if (a.type === 'pen') return { ...a, points: a.points.map(pt => ({ ...pt })) }
return { ...a }
}
/** 移动标注:基于原始快照 + 偏移量更新目标标注坐标 */
function applyMove(target: Annotation, orig: Annotation, dx: number, dy: number) {
switch (target.type) {
case 'rect':
case 'ellipse':
case 'arrow':
case 'mosaic':
case 'highlight': {
const o = orig as typeof target
target.x1 = o.x1 + dx
target.y1 = o.y1 + dy
target.x2 = o.x2 + dx
target.y2 = o.y2 + dy
break
}
case 'pen': {
const o = orig as typeof target
target.points = o.points.map(pt => ({ x: pt.x + dx, y: pt.y + dy }))
break
}
case 'text':
case 'number': {
const o = orig as typeof target
target.x = o.x + dx
target.y = o.y + dy
break
}
}
}
/** 调整标注大小:根据手柄方向更新对应坐标(仅对可调整大小的标注有效) */
function applyResize(target: Annotation, orig: Annotation, dir: HandleDir, dx: number, dy: number) {
switch (target.type) {
case 'rect':
case 'ellipse':
case 'arrow':
case 'mosaic':
case 'highlight': {
const o = orig as typeof target
let x1 = o.x1
let y1 = o.y1
let x2 = o.x2
let y2 = o.y2
if (dir.includes('e')) x2 = o.x2 + dx
if (dir.includes('s')) y2 = o.y2 + dy
if (dir.includes('w')) x1 = o.x1 + dx
if (dir.includes('n')) y1 = o.y1 + dy
target.x1 = x1
target.y1 = y1
target.x2 = x2
target.y2 = y2
break
}
}
}
/** 绘制选中标注的虚线边框 */
function drawSelectionBox(ctx: CanvasRenderingContext2D, bb: { x: number; y: number; w: number; h: number }) {
const pad = 2
ctx.strokeStyle = '#3b82f6'
ctx.lineWidth = 1
ctx.setLineDash([4, 4])
ctx.strokeRect(bb.x - pad, bb.y - pad, bb.w + pad * 2, bb.h + pad * 2)
ctx.setLineDash([])
}
// 几何 / 命中 / 变换纯函数已抽到 annotations.ts,与编辑器共用,
// 保证两处对同一标注数据的选中、拖拽、调整大小行为一致。
// ===== 标注交互 =====
function beginDraft(e: MouseEvent) {
@@ -1952,10 +1734,19 @@ async function startScroll() {
width: Math.round(sp.w),
height: Math.round(sp.h),
}
// 覆盖层挖孔(先于会话启动):Chromium 系浏览器(Edge/Chrome)的遮挡检测会把
// 被完全覆盖的窗口标记为 occluded 并暂停渲染(页面冻结、抓帧静止)。在选区带处
// 挖出真孔,目标窗口仅部分被覆盖即可恢复渲染,滚轮与拼接恢复正常。
// 先挖孔再启动,保证会话首帧与滚轮都发生在解除遮挡之后。
await commands.screenshotSetScrollHole(region).catch((e) => {
console.error('[screenshot] 覆盖层挖孔失败', e)
})
try {
await commands.screenshotScrollStart(hwnd, region, true)
} catch (e) {
console.error('[screenshot] 滚动截图启动失败', e)
// 启动失败:回滚挖孔,避免残留空洞
void commands.screenshotSetScrollHole(null).catch(() => {})
showScrollToast(String(e))
return
}
@@ -1970,6 +1761,8 @@ async function startScroll() {
function exitScrollMode() {
scrollMode.value = false
scrollProgress.value = null
// 复位覆盖层挖孔(区域在窗口上持续有效,不复位会残留空洞)
void commands.screenshotSetScrollHole(null).catch(() => {})
}
/** 取消滚动会话并退出滚动模式(会话线程回滚窗口、丢弃画布) */
@@ -2102,6 +1895,8 @@ async function beginCapture(payload?: ScreenshotBeginPayload) {
scrollProgress.value = null
// 新截图打断进行中的滚动会话 → 取消后台会话(避免残留占用)
if (wasScrolling) void commands.screenshotScrollCancel().catch(() => {})
// 复位覆盖层挖孔(无条件:异常路径也可能残留窗口区域,这里兜底清理)
void commands.screenshotSetScrollHole(null).catch(() => {})
winHighlight.value = null
currentHwnd.value = 0
sel.value = { x: 0, y: 0, w: 0, h: 0 }
+242
View File
@@ -0,0 +1,242 @@
/**
* 标注几何 / 命中测试 / 变换共享纯函数。
* 覆盖层(ScreenshotOverlay)与编辑器(ScreenshotEditor)共用,
* 保证两处对同一标注数据的选中、拖拽、调整大小行为严格一致。
*/
import type { Annotation, HandleDir, Point, TextAnno } from './types'
// ===== 文字测量 =====
/** 离屏测量上下文(惰性创建,供 measureText 使用) */
let measureCtx: CanvasRenderingContext2D | null = null
function getMeasureCtx(): CanvasRenderingContext2D | null {
if (!measureCtx) {
const c = document.createElement('canvas')
c.width = 0
c.height = 0
measureCtx = c.getContext('2d')
}
return measureCtx
}
/** 估算文字宽高(ctx.measureText 测宽,多行取最宽行,高 = 行数 × fontSize)。
* 结果缓存:相同 text+fontSize 的测量结果不变,避免 hitTest / annoBBox 重复调用开销 */
const measureCache = new Map<string, { w: number; h: number }>()
export function measureText(text: string, fontSize: number): { w: number; h: number } {
const key = `${fontSize}\0${text}`
const cached = measureCache.get(key)
if (cached) return cached
const ctx = getMeasureCtx()
const lines = text.split('\n')
let result: { w: number; h: number }
if (!ctx) {
const maxLen = Math.max(1, ...lines.map(l => l.length))
result = { w: fontSize * maxLen * 0.6, h: fontSize * lines.length }
} else {
ctx.font = `${fontSize}px sans-serif`
let maxW = 0
for (const line of lines) {
const m = ctx.measureText(line)
if (m.width > maxW) maxW = m.width
}
result = { w: Math.ceil(maxW), h: fontSize * lines.length }
}
measureCache.set(key, result)
return result
}
// ===== 几何 =====
/** 标注 bounding box(画布物理像素坐标) */
export function annoBBox(anno: Annotation): { x: number; y: number; w: number; h: number } {
switch (anno.type) {
case 'rect':
case 'ellipse':
case 'mosaic':
case 'highlight':
case 'arrow': {
const x = Math.min(anno.x1, anno.x2)
const y = Math.min(anno.y1, anno.y2)
return { x, y, w: Math.abs(anno.x2 - anno.x1), h: Math.abs(anno.y2 - anno.y1) }
}
case 'pen': {
if (anno.points.length === 0) return { x: 0, y: 0, w: 0, h: 0 }
let minX = Infinity
let minY = Infinity
let maxX = -Infinity
let maxY = -Infinity
for (const pt of anno.points) {
if (pt.x < minX) minX = pt.x
if (pt.y < minY) minY = pt.y
if (pt.x > maxX) maxX = pt.x
if (pt.y > maxY) maxY = pt.y
}
return { x: minX, y: minY, w: maxX - minX, h: maxY - minY }
}
case 'text': {
const { w, h } = measureText(anno.text, anno.fontSize)
return { x: anno.x, y: anno.y, w, h }
}
case 'number': {
const r = anno.fontSize / 2
return { x: anno.x - r, y: anno.y - r, w: anno.fontSize, h: anno.fontSize }
}
}
}
/** 点到线段的距离 */
export function distToSegment(p: Point, a: Point, b: Point): number {
const dx = b.x - a.x
const dy = b.y - a.y
const len2 = dx * dx + dy * dy
if (len2 === 0) return Math.hypot(p.x - a.x, p.y - a.y)
let t = ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2
t = Math.max(0, Math.min(1, t))
const cx = a.x + t * dx
const cy = a.y + t * dy
return Math.hypot(p.x - cx, p.y - cy)
}
// ===== 命中测试 =====
/** 文字标注区域检测:core=文字内容区(编辑),border=边框区(移动)null=未命中 */
export function hitTestTextZone(anno: TextAnno, p: Point): 'core' | 'border' | null {
const { w, h } = measureText(anno.text, anno.fontSize)
const x1 = anno.x, y1 = anno.y
const x2 = anno.x + w, y2 = anno.y + h
const pad = 8
if (p.x < x1 - pad || p.x > x2 + pad || p.y < y1 - pad || p.y > y2 + pad) return null
if (p.x >= x1 && p.x <= x2 && p.y >= y1 && p.y <= y2) return 'core'
return 'border'
}
/** 点击测试单个标注 */
export function hitTestSingle(anno: Annotation, p: Point): boolean {
switch (anno.type) {
case 'rect':
case 'ellipse':
case 'mosaic':
case 'highlight': {
const x1 = Math.min(anno.x1, anno.x2)
const y1 = Math.min(anno.y1, anno.y2)
const x2 = Math.max(anno.x1, anno.x2)
const y2 = Math.max(anno.y1, anno.y2)
const pad = Math.max(4, anno.type === 'rect' || anno.type === 'ellipse' ? anno.lineWidth : 2)
return p.x >= x1 - pad && p.x <= x2 + pad && p.y >= y1 - pad && p.y <= y2 + pad
}
case 'arrow':
return distToSegment(p, { x: anno.x1, y: anno.y1 }, { x: anno.x2, y: anno.y2 }) <= Math.max(6, anno.lineWidth)
case 'pen': {
for (let i = 1; i < anno.points.length; i++) {
if (distToSegment(p, anno.points[i - 1], anno.points[i]) <= Math.max(6, anno.lineWidth)) return true
}
return false
}
case 'text': {
return hitTestTextZone(anno, p) !== null
}
case 'number': {
const r = anno.fontSize / 2
const dx = p.x - anno.x
const dy = p.y - anno.y
return dx * dx + dy * dy <= r * r
}
}
}
/** 点击测试:返回命中的标注索引(-1 未命中),从后往前测试(后画的在上层) */
export function hitTestAnno(annotations: Annotation[], p: Point): number {
for (let i = annotations.length - 1; i >= 0; i--) {
if (hitTestSingle(annotations[i], p)) return i
}
return -1
}
/** 标注是否可调整大小(pen/text/number 仅支持移动) */
export function isAnnoResizable(anno: Annotation): boolean {
return anno.type === 'rect' || anno.type === 'ellipse' || anno.type === 'arrow' || anno.type === 'mosaic' || anno.type === 'highlight'
}
/** 选中标注是否有可变颜色属性 */
export function annoHasColor(anno: Annotation): boolean {
return anno.type !== 'mosaic'
}
/** 选中标注是否有粗细概念(lineWidth) */
export function annoHasLineWidth(anno: Annotation): boolean {
return anno.type === 'rect' || anno.type === 'ellipse' || anno.type === 'arrow' || anno.type === 'pen'
}
// ===== 变换 =====
/** 深拷贝标注(用于拖拽/调整大小时保存原始快照) */
export function cloneAnno(a: Annotation): Annotation {
if (a.type === 'pen') return { ...a, points: a.points.map(pt => ({ ...pt })) }
return { ...a }
}
/** 移动标注:基于原始快照 + 偏移量更新目标标注坐标 */
export function applyMove(target: Annotation, orig: Annotation, dx: number, dy: number) {
switch (target.type) {
case 'rect':
case 'ellipse':
case 'arrow':
case 'mosaic':
case 'highlight': {
const o = orig as typeof target
target.x1 = o.x1 + dx
target.y1 = o.y1 + dy
target.x2 = o.x2 + dx
target.y2 = o.y2 + dy
break
}
case 'pen': {
const o = orig as typeof target
target.points = o.points.map(pt => ({ x: pt.x + dx, y: pt.y + dy }))
break
}
case 'text':
case 'number': {
const o = orig as typeof target
target.x = o.x + dx
target.y = o.y + dy
break
}
}
}
/** 调整标注大小:根据手柄方向更新对应坐标(仅对可调整大小的标注有效) */
export function applyResize(target: Annotation, orig: Annotation, dir: HandleDir, dx: number, dy: number) {
switch (target.type) {
case 'rect':
case 'ellipse':
case 'arrow':
case 'mosaic':
case 'highlight': {
const o = orig as typeof target
let x1 = o.x1
let y1 = o.y1
let x2 = o.x2
let y2 = o.y2
if (dir.includes('e')) x2 = o.x2 + dx
if (dir.includes('s')) y2 = o.y2 + dy
if (dir.includes('w')) x1 = o.x1 + dx
if (dir.includes('n')) y1 = o.y1 + dy
target.x1 = x1
target.y1 = y1
target.x2 = x2
target.y2 = y2
break
}
}
}
/** 绘制选中标注的虚线边框 */
export function drawSelectionBox(ctx: CanvasRenderingContext2D, bb: { x: number; y: number; w: number; h: number }) {
const pad = 2
ctx.strokeStyle = '#3b82f6'
ctx.lineWidth = 1
ctx.setLineDash([4, 4])
ctx.strokeRect(bb.x - pad, bb.y - pad, bb.w + pad * 2, bb.h + pad * 2)
ctx.setLineDash([])
}
+799
View File
@@ -0,0 +1,799 @@
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { invoke } from '@tauri-apps/api/core'
import { createLogger } from '@/lib/logger'
const logger = createLogger('feiniu')
/** 可播条目(飞牛 NAS 或本地文件),是播放器/歌单的统一数据模型 */
export interface PlayableItem {
source: 'feiniu' | 'local'
/** feiniu 源:track guidlocal 源:文件路径 */
guid?: string
title: string
artistNames: string
album?: string
durationMs?: number
coverId?: string
/** local 源文件大小(字节) */
size?: number
/** local 源所在目录 */
dir?: string
}
export interface FeiniuConnection {
id: string
name: string
kind: 'lan' | 'frp' | 'fnconnect'
baseUrl: string
username: string
loggedIn: boolean
accessCode: string
insecure: boolean
fnId?: string
}
export interface Playlist {
id: string
name: string
items: PlayableItem[]
}
export type PlayMode = 'loopAll' | 'loopOne' | 'shuffle'
interface LrcLine {
t: number
text: string
}
const PLAYERS_KEY = 'thing.music.playlists'
const QUEUE_KEY = 'thing.music.queue'
const VOL_KEY = 'thing.music.volume'
function uid(): string {
return `p${Date.now().toString(36)}${Math.random().toString(36).slice(2, 7)}`
}
export const useFeiniuStore = defineStore('feiniu', () => {
// ===== 连接 =====
const connections = ref<FeiniuConnection[]>([])
const activeId = ref('')
const config = ref<{ baseUrl: string; username: string; loggedIn: boolean }>({
baseUrl: '',
username: '',
loggedIn: false
})
const mediaPrefix = ref('')
const connecting = ref(false)
// 缓存播放模式('stream' 直连 | 'cache' 缓存后播放)
const cacheMode = ref<'stream' | 'cache'>('stream')
const cacheStatus = ref<{ count: number; usedMb: number }>({ count: 0, usedMb: 0 })
// fnOS 文件服务(P6:上传到飞牛)
const fnosLoggedIn = ref(false)
const libraryNasPath = ref('')
const autoUpload = ref(false)
const uploading = ref(false)
const activeConn = computed(() => connections.value.find((c) => c.id === activeId.value) || null)
// ===== 曲库(飞牛 + 本地) =====
const tracks = ref<PlayableItem[]>([])
const page = ref(1)
const total = ref(0)
const loading = ref(false)
const keyword = ref('')
const localTracks = ref<PlayableItem[]>([])
const localScanBusy = ref(false)
// ===== 歌单 =====
const playlists = ref<Playlist[]>([])
// ===== 播放器内核 =====
const queue = ref<PlayableItem[]>([])
const queueIndex = ref(-1)
const playMode = ref<PlayMode>('loopAll')
const volume = ref(0.8)
const current = computed(() => queue.value[queueIndex.value] ?? null)
const playing = ref(false)
const loadingPlay = ref(false)
const position = ref(0)
const duration = ref(0)
const lyricLines = ref<LrcLine[]>([])
const lyricVisible = ref(false)
const queueVisible = ref(false)
const nowPlayingOpen = ref(false)
let lyricRaw = ''
let audioEl: HTMLAudioElement | null = null
function ensureAudio(): HTMLAudioElement {
if (!audioEl) {
const a = new Audio()
a.preload = 'auto'
a.volume = volume.value
a.addEventListener('loadedmetadata', () => (duration.value = a.duration || 0))
a.addEventListener('timeupdate', () => (position.value = a.currentTime))
a.addEventListener('play', () => (playing.value = true))
a.addEventListener('pause', () => (playing.value = false))
a.addEventListener('ended', () => onEnded())
a.addEventListener('error', () => {
loadingPlay.value = false
playing.value = false
})
audioEl = a
}
return audioEl
}
// ===== 初始化 & 连接 =====
async function init() {
try {
const r = await invoke<{ activeId: string; list: FeiniuConnection[] }>('feiniu_list_connections')
connections.value = r?.list || []
activeId.value = r?.activeId || ''
const c = await invoke<{ baseUrl: string; username: string; loggedIn: boolean }>('feiniu_get_config')
config.value = c
if (c?.loggedIn) await refreshMediaPrefix()
} catch (e) {
logger.error(`初始化失败: ${e}`)
}
loadPlaylists()
restoreQueue()
try {
volume.value = Number(localStorage.getItem(VOL_KEY)) || 0.8
const cm = localStorage.getItem('thing.music.cachemode')
if (cm === 'cache' || cm === 'stream') cacheMode.value = cm
} catch {
/* ignore */
}
await ensureCacheStatus()
try {
libraryNasPath.value = localStorage.getItem('thing.music.feiniu.naspath') || ''
autoUpload.value = localStorage.getItem('thing.music.feiniu.autoupload') === '1'
} catch {
/* ignore */
}
await refreshFnosStatus()
}
async function refreshFnosStatus() {
if (!activeId.value) {
fnosLoggedIn.value = false
return
}
try {
const r = await invoke<{ loggedIn: boolean }>('feiniu_fnos_status', { connectionId: activeId.value })
fnosLoggedIn.value = !!r?.loggedIn
} catch {
fnosLoggedIn.value = false
}
}
async function fnosLogin(username: string, password: string) {
if (!activeId.value) throw new Error('请先激活一个连接')
await invoke('feiniu_fnos_login', { connectionId: activeId.value, username, password })
fnosLoggedIn.value = true
}
function fnosLogout() {
if (activeId.value) invoke('feiniu_fnos_logout', { connectionId: activeId.value }).catch(() => {})
fnosLoggedIn.value = false
}
function setLibraryNasPath(v: string) {
libraryNasPath.value = v
try {
localStorage.setItem('thing.music.feiniu.naspath', v)
} catch {
/* ignore */
}
}
function setAutoUpload(v: boolean) {
autoUpload.value = v
try {
localStorage.setItem('thing.music.feiniu.autoupload', v ? '1' : '0')
} catch {
/* ignore */
}
}
/** 上传单个本地文件到飞牛曲库目录(激活连接)。 */
async function uploadToFeiniu(localPath: string, fileName: string): Promise<void> {
if (!fnosLoggedIn.value) throw new Error('请先登录 NAS 文件服务')
const base = libraryNasPath.value.replace(/[\\/]+$/, '')
const nasPath = base ? `${base}/${fileName}` : fileName
uploading.value = true
try {
await invoke('feiniu_fnos_upload', { localPath, nasPath })
} finally {
uploading.value = false
}
}
/** 上传一个本地曲目(自动取文件名)到飞牛曲库。 */
async function uploadLocalTrack(item: PlayableItem): Promise<void> {
if (!item.guid) throw new Error('缺少本地文件路径')
const name = item.guid.split(/[\\/]/).pop() || 'music.bin'
await uploadToFeiniu(item.guid, name)
}
/** 把最近 N 分钟内新出现的本地音频批量上传到飞牛曲库。返回 { total, ok }。 */
async function uploadRecentToFeiniu(minutes = 10): Promise<{ total: number; ok: number }> {
if (!fnosLoggedIn.value) throw new Error('请先连接 NAS 文件服务(设置 → 飞牛连接)')
if (!libraryNasPath.value) throw new Error('请先填写飞牛曲库目录(设置 → 上传到飞牛)')
const r = await invoke<{ items: any[] }>('feiniu_scan_local')
const now = Date.now() / 1000
const recent = (r?.items || []).filter((f) => now - (f.mtim || 0) <= minutes * 60)
let ok = 0
uploading.value = true
try {
for (const f of recent) {
const path = String(f.path)
const name = path.split(/[\\/]/).pop() || 'music.bin'
try {
await uploadToFeiniu(path, name)
ok++
} catch {
/* 单文件失败继续 */
}
}
} finally {
uploading.value = false
}
return { total: recent.length, ok }
}
/** 删除 NAS 上的文件(激活连接)。 */
async function deleteFromFeiniu(nasPath: string): Promise<void> {
await invoke('feiniu_fnos_delete', { nasPath })
}
/** FnConnect:解析 fnId 得到可达 base_url。 */
async function resolveFnConnect(fnId: string): Promise<{ baseUrl: string; relay: boolean }> {
return invoke('feiniu_fnconnect_resolve', { fnId })
}
async function ensureCacheStatus() {
try {
const r = await invoke<{ count: number; usedMb: number }>('feiniu_cache_status')
cacheStatus.value = { count: r?.count ?? 0, usedMb: r?.usedMb ?? 0 }
} catch {
/* ignore */
}
}
function setCacheMode(mode: 'stream' | 'cache') {
cacheMode.value = mode
try {
localStorage.setItem('thing.music.cachemode', mode)
} catch {
/* ignore */
}
if (mode === 'stream') clearPlayback()
}
async function clearCache() {
await invoke('feiniu_cache_clear')
await ensureCacheStatus()
clearPlayback()
}
async function refreshConnections() {
try {
const r = await invoke<{ activeId: string; list: FeiniuConnection[] }>('feiniu_list_connections')
connections.value = r?.list || []
activeId.value = r?.activeId || ''
await refreshFnosStatus()
const c = await invoke<{ baseUrl: string; username: string; loggedIn: boolean }>('feiniu_get_config')
config.value = c
} catch (e) {
logger.error(String(e))
}
}
async function saveConnection(conn: Partial<FeiniuConnection> & { name: string; baseUrl: string; kind: string }): Promise<string> {
const r = await invoke<{ ok: boolean }>('feiniu_save_connection', {
connection: {
id: conn.id || '',
name: conn.name,
kind: conn.kind,
baseUrl: conn.baseUrl,
username: conn.username || '',
token: '',
deviceId: '',
accessCode: conn.accessCode || '',
insecure: conn.insecure || false,
fnId: conn.fnId || ''
}
})
void r
await refreshConnections()
return connections.value.find((c) => c.baseUrl === conn.baseUrl && c.name === conn.name)?.id || ''
}
async function deleteConnection(id: string) {
await invoke('feiniu_delete_connection', { id })
await refreshConnections()
}
async function activateConnection(id: string) {
await invoke('feiniu_activate_connection', { id })
await refreshConnections()
if (config.value.loggedIn) await refreshMediaPrefix()
await refreshFnosStatus()
}
async function login(connectionId: string, username: string, password: string) {
connecting.value = true
try {
const r = await invoke<{ mediaPrefix: string }>('feiniu_login', {
connectionId,
username,
password
})
await refreshConnections()
config.value = { baseUrl: activeConn.value?.baseUrl || '', username, loggedIn: true }
if (r?.mediaPrefix) mediaPrefix.value = r.mediaPrefix
await loadTracks(1)
} catch (e) {
logger.error(String(e))
throw e
} finally {
connecting.value = false
}
}
async function logout(connectionId: string) {
try {
await invoke('feiniu_logout', { connectionId })
} catch {
/* ignore */
}
await refreshConnections()
config.value.loggedIn = false
mediaPrefix.value = ''
tracks.value = []
clearPlayback()
}
async function testConnection(id: string, username: string, password: string): Promise<boolean> {
const r = await invoke<{ ok: boolean }>('feiniu_test_connection', { connectionId: id, username, password })
return !!r?.ok
}
async function refreshMediaPrefix() {
try {
const r = await invoke<{ mediaPrefix: string }>('feiniu_media_prefix')
mediaPrefix.value = r?.mediaPrefix || ''
} catch (e) {
logger.error(String(e))
}
}
// ===== 飞牛曲库 =====
async function loadTracks(p: number = 1): Promise<void> {
loading.value = true
try {
const data = await invoke<any>('feiniu_list_tracks', {
page: p,
size: 50,
keyword: keyword.value.trim() || null
})
const list = Array.isArray(data) ? data : data?.list || data?.items || data?.tracks || []
tracks.value = (list as any[]).map((t) => normalizeTrack(t))
total.value = data?.total ?? data?.count ?? list.length
page.value = p
} catch (e) {
logger.error(String(e))
throw e
} finally {
loading.value = false
}
}
function normalizeTrack(t: any): PlayableItem {
const artists = Array.isArray(t.artists) ? t.artists : []
const album = typeof t.album === 'string' ? t.album : t.album?.name || t.albumName || ''
return {
source: 'feiniu',
guid: t.guid || t.trackGuid || t.id,
title: t.title || t.name || '未知标题',
durationMs: t.durationMs ?? t.duration ?? undefined,
coverId: t.coverId || undefined,
album,
artistNames:
artists.map((a: { name?: string }) => a.name).filter(Boolean).join(' / ') ||
t.artist ||
t.singers ||
''
}
}
// ===== 本地曲库 =====
async function scanLocal() {
localScanBusy.value = true
try {
const data = await invoke<{ items: any[] }>('feiniu_scan_local')
localTracks.value = (data?.items || []).map((f) => ({
source: 'local' as const,
guid: f.path,
title: f.title || f.name || '未知',
artistNames: '',
durationMs: undefined,
size: f.size,
dir: f.dir
}))
} catch (e) {
logger.error(String(e))
throw e
} finally {
localScanBusy.value = false
}
}
// ===== 歌单 =====
function loadPlaylists() {
try {
const raw = localStorage.getItem(PLAYERS_KEY)
if (!raw) return
playlists.value = JSON.parse(raw)
} catch {
playlists.value = []
}
}
function persistPlaylists() {
try {
localStorage.setItem(PLAYERS_KEY, JSON.stringify(playlists.value))
} catch {
/* ignore */
}
}
function createPlaylist(name: string): string {
const id = uid()
playlists.value.push({ id, name, items: [] })
persistPlaylists()
return id
}
function renamePlaylist(id: string, name: string) {
const p = playlists.value.find((p) => p.id === id)
if (p) {
p.name = name
persistPlaylists()
}
}
function deletePlaylist(id: string) {
playlists.value = playlists.value.filter((p) => p.id !== id)
persistPlaylists()
}
function addToPlaylist(playlistId: string, items: PlayableItem[]) {
const p = playlists.value.find((p) => p.id === playlistId)
if (!p) return
for (const it of items) {
const dup = p.items.some((x) => x.guid === it.guid && x.source === it.source)
if (!dup) p.items.push({ ...it })
}
persistPlaylists()
}
function removeFromPlaylist(playlistId: string, index: number) {
const p = playlists.value.find((p) => p.id === playlistId)
if (p) {
p.items.splice(index, 1)
persistPlaylists()
}
}
function moveInPlaylist(playlistId: string, from: number, to: number) {
const p = playlists.value.find((p) => p.id === playlistId)
if (!p || from < 0 || to < 0 || from >= p.items.length || to >= p.items.length) return
const [it] = p.items.splice(from, 1)
p.items.splice(to, 0, it)
persistPlaylists()
}
// ===== 播放器 =====
function playQueue(items: PlayableItem[], startIndex = 0) {
queue.value = items.map((i) => ({ ...i }))
queueIndex.value = Math.min(Math.max(startIndex, 0), items.length - 1)
playCurrent()
}
function playItem(item: PlayableItem) {
// 若已在队列中,跳转到它;否则作为新队列播放
const i = queue.value.findIndex((q) => q.guid === item.guid && q.source === item.source)
if (i >= 0) {
queueIndex.value = i
playCurrent()
} else {
queue.value = [{ ...item }]
queueIndex.value = 0
playCurrent()
}
}
function playCurrent() {
const t = current.value
if (!t) return
if (t.source === 'feiniu') loadLyric(t.guid)
else lyricLines.value = []
const a = ensureAudio()
a.pause()
if (t.source === 'feiniu' && cacheMode.value === 'cache') {
playCached(t, a)
return
}
a.src =
t.source === 'feiniu'
? `${mediaPrefix.value}/stream?guid=${encodeURIComponent(t.guid || '')}`
: `file://${(t.guid || '').replace(/\\/g, '/')}`
a.currentTime = 0
startPlayback(a)
}
async function playCached(t: PlayableItem, a: HTMLAudioElement) {
loadingPlay.value = true
try {
const r = await invoke<{ path: string | null }>('feiniu_cache_fetch', { guid: t.guid || '' })
if (r?.path) {
a.src = `file://${(r.path as string).replace(/\\/g, '/')}`
a.currentTime = 0
startPlayback(a)
return
}
} catch {
/* fall through to stream */
}
// 缓存失败(未登录/网络)→ 回退直连流
a.src = `${mediaPrefix.value}/stream?guid=${encodeURIComponent(t.guid || '')}`
a.currentTime = 0
startPlayback(a)
}
function startPlayback(a: HTMLAudioElement) {
loadingPlay.value = true
a.play()
.then(() => {
loadingPlay.value = false
persistQueue()
})
.catch(() => {
loadingPlay.value = false
persistQueue()
})
}
function toggle() {
const a = ensureAudio()
if (a.paused) a.play().catch(() => {})
else a.pause()
}
function next(manual = true) {
const n = queue.value.length
if (n === 0) return
if (manual && playMode.value === 'shuffle') {
let idx = queueIndex.value
while (idx === queueIndex.value && n > 1) idx = Math.floor(Math.random() * n)
queueIndex.value = idx
} else if (queueIndex.value < n - 1) {
queueIndex.value++
} else if (playMode.value !== 'loopOne') {
queueIndex.value = 0
} else {
// loopOne 且已到末尾:保持当前
queueIndex.value = 0
}
playCurrent()
}
function onEnded() {
if (playMode.value === 'loopOne') {
const a = ensureAudio()
a.currentTime = 0
a.play().catch(() => {})
return
}
next(false)
}
function prev() {
const a = ensureAudio()
if (a.currentTime > 3) {
a.currentTime = 0
return
}
if (queueIndex.value > 0) queueIndex.value--
else queueIndex.value = 0
playCurrent()
}
function seek(sec: number) {
const a = ensureAudio()
a.currentTime = Math.max(0, sec)
position.value = a.currentTime
}
function setVolume(v: number) {
volume.value = v
const a = ensureAudio()
a.volume = v
try {
localStorage.setItem(VOL_KEY, String(v))
} catch {
/* ignore */
}
}
function togglePlayMode() {
playMode.value = playMode.value === 'loopAll' ? 'loopOne' : playMode.value === 'loopOne' ? 'shuffle' : 'loopAll'
}
function clearPlayback() {
queue.value = []
queueIndex.value = -1
lyricLines.value = []
position.value = 0
duration.value = 0
playing.value = false
if (audioEl) {
audioEl.pause()
audioEl.removeAttribute('src')
audioEl.load()
}
}
function restoreQueue() {
try {
const raw = localStorage.getItem(QUEUE_KEY)
if (!raw) return
const s = JSON.parse(raw)
if (!s?.queue || !Array.isArray(s.queue)) return
queue.value = s.queue
queueIndex.value = typeof s.index === 'number' ? s.index : -1
} catch {
/* ignore */
}
}
function persistQueue() {
try {
localStorage.setItem(QUEUE_KEY, JSON.stringify({ queue: queue.value, index: queueIndex.value }))
} catch {
/* ignore */
}
}
function fmtDuration(sec?: number): string {
if (sec == null || !isFinite(sec)) return '--:--'
const s = Math.floor(sec)
const m = Math.floor(s / 60)
const r = s % 60
return `${String(m).padStart(2, '0')}:${String(r).padStart(2, '0')}`
}
async function loadLyric(guid?: string) {
lyricLines.value = []
if (!guid) return
try {
const r = await invoke<{ lyric: string }>('feiniu_lyric', { guid })
const text = r?.lyric || ''
if (text === lyricRaw) return
lyricRaw = text
lyricLines.value = parseLrc(text)
} catch (e) {
logger.error(String(e))
}
}
function parseLrc(text: string): LrcLine[] {
const lines: LrcLine[] = []
const lineRe = /\[(\d{1,2}):(\d{1,2})(?:[.:](\d{1,3}))?]/g
const parts = text.split(/\r?\n/)
for (const part of parts) {
const timestamps: number[] = []
let src = part
let m: RegExpExecArray | null
while ((m = lineRe.exec(part))) {
const mm = Number(m[1])
const ss = Number(m[2])
const frac = m[3] ? Number(m[3].padEnd(3, '0')) / 1000 : 0
timestamps.push(mm * 60 + ss + frac)
src = part.slice(lineRe.lastIndex)
}
const content = src.replace(/^\[[^\]]*]\s*/, '').trim()
if (!content) continue
for (const t of timestamps) lines.push({ t, text: content })
}
lines.sort((a, b) => a.t - b.t)
return lines
}
function currentLine(): number {
let idx = -1
for (let k = 0; k < lyricLines.value.length; k++) {
if (lyricLines.value[k].t <= position.value) idx = k
else break
}
return idx
}
const progress = computed(() => (duration.value > 0 ? (position.value / duration.value) * 100 : 0))
return {
connections,
activeId,
activeConn,
config,
mediaPrefix,
connecting,
cacheMode,
cacheStatus,
tracks,
page,
total,
loading,
keyword,
localTracks,
localScanBusy,
playlists,
queue,
queueIndex,
playMode,
volume,
current,
playing,
loadingPlay,
position,
duration,
lyricLines,
lyricVisible,
queueVisible,
nowPlayingOpen,
progress,
init,
refreshConnections,
saveConnection,
deleteConnection,
activateConnection,
login,
logout,
testConnection,
refreshMediaPrefix,
loadTracks,
scanLocal,
ensureCacheStatus,
setCacheMode,
clearCache,
fnosLoggedIn,
libraryNasPath,
autoUpload,
uploading,
refreshFnosStatus,
fnosLogin,
fnosLogout,
setLibraryNasPath,
setAutoUpload,
uploadToFeiniu,
uploadLocalTrack,
uploadRecentToFeiniu,
deleteFromFeiniu,
resolveFnConnect,
createPlaylist,
renamePlaylist,
deletePlaylist,
addToPlaylist,
removeFromPlaylist,
moveInPlaylist,
playQueue,
playItem,
toggle,
next,
prev,
seek,
setVolume,
togglePlayMode,
clearPlayback,
persistQueue,
fmtDuration,
currentLine
}
})
+595
View File
@@ -0,0 +1,595 @@
import { defineStore } from 'pinia'
import { computed, ref, watch } from 'vue'
import { invoke } from '@tauri-apps/api/core'
import { listen, type UnlistenFn } from '@tauri-apps/api/event'
import { commands, type MusicEnvStatus, type MusicSettings } from '@/lib/bindings'
import { useProxyStore } from '@/stores/proxyStore'
import { createLogger } from '@/lib/logger'
/** 搜索结果中的单曲(与 bridge.py song_to_dict 字段对应) */
export interface MusicSong {
songName: string | null
singers: string | null
album: string | null
duration: string | null
durationS: number | null
fileSize: string | null
fileSizeBytes: number | null
ext: string | null
source: string | null
rootSource: string | null
downloadUrl: string | null
valid: boolean
coverUrl: string | null
bitrate: number | null
/** 下载所需:save_path 命名用 */
identifier?: string | null
/** 默认下载请求头(rust 引擎直传下载器模块用) */
defaultDownloadHeaders?: Record<string, string> | null
defaultDownloadCookies?: Record<string, string> | null
/** 懒解析:官方搜索 API 的原始结果(resolve/下载前解析真实链接用) */
rawSearch?: Record<string, unknown> | null
/** 音质提示:true=具备无损(ext 或官方音质字段推断),null=未知;懒解析歌 ext/fileSize 为空时筛选依据 */
lossless?: boolean | null
/** 全音质档位(搜索阶段多档展示:label/ext/bitrate/sizeBytes/size/lossless);懒解析歌为数组,急切解析/无数据为 null */
qualities?: MusicQuality[] | null
}
/** 单个音质档位(musicdl 官方接口搜索阶段批量取回的格式+大小+无损) */
export interface MusicQuality {
label: string | null
ext: string | null
bitrate: number | null
sizeBytes: number | null
size: string | null
lossless: boolean | null
}
/** 桥接下载事件(bridge.py 事件行,经 Rust 原样转发) */
export interface MusicDownloadEvent {
event: string
taskId?: string
type?: 'start' | 'progress' | 'done' | 'error' | 'cancelled' | 'finished' | 'resolving' | 'bridge-stopped'
key?: string
songName?: string
singers?: string
ext?: string
/** 实际解析出的音质档位(start 事件回传,如 "无损"/"320K" */
quality?: string
downloaded?: number
total?: number
done?: number
message?: string
}
/** 任务内单曲状态(key = "{source}|{idx}" */
export interface MusicDownloadSongState {
key: string
songName: string
singers: string
status: 'queued' | 'resolving' | 'downloading' | 'done' | 'error' | 'cancelled'
downloaded: number
total: number
message?: string
/** 实际解析出的音质档位(start 事件回传);请求档位(如 "最高")在任务级 task.quality */
quality?: string
}
/** 音乐下载任务(musicdl 引擎) */
export interface MusicDownloadTask {
taskId: string
engine: 'musicdl' | 'rust'
status: 'downloading' | 'cancelling' | 'done' | 'error' | 'cancelled' | 'interrupted'
doneCount: number
songs: MusicDownloadSongState[]
/** 完整歌曲数据(localStorage 持久化,用于"重新下载" */
songsData: MusicSong[]
/** 下载目录(打开文件夹用) */
savedir?: string
/** 本次下载的目标音质 label("" 表示最高),用于任务标题展示 */
quality?: string
errorMessage?: string
createdAt: number
}
/** 运行时安装进度事件负载(事件类型非 specta 生成范围,本地定义) */
export interface MusicInstallProgress {
stage: string
percent: number
downloadedBytes: number
totalBytes: number | null
message: string
}
/** 搜索返回(bridge search 结果结构) */
export interface MusicSearchPayload {
results: Record<string, MusicSong[]>
total: number
sources: string[]
}
/** 桥接 ping 返回 */
export interface MusicPingPayload {
version: string
python: string
}
const logger = createLogger('music')
export const useMusicStore = defineStore('music', () => {
const settings = ref<MusicSettings | null>(null)
const env = ref<MusicEnvStatus | null>(null)
/** musicdl 已注册的全部搜索源(客户端名) */
const availableSources = ref<string[]>([])
// 搜索状态
const searching = ref(false)
const searchError = ref('')
const results = ref<Record<string, MusicSong[]>>({})
const resultTotal = ref(0)
/** 已执行过一次搜索/歌单解析(用于空结果时展示"未找到"而非初始引导空态) */
const searched = ref(false)
// 运行时安装状态
const installing = ref(false)
const installProgress = ref<MusicInstallProgress | null>(null)
const installError = ref('')
let progressUnlisten: UnlistenFn | null = null
async function init() {
restoreTasks()
await Promise.all([loadSettings(), refreshEnv()])
}
async function loadSettings() {
settings.value = await commands.musicGetSettings()
}
/** 保存设置(调用方先修改 settings 再调用;前端用 400ms debounce */
async function saveSettings() {
if (!settings.value) return
await commands.musicSaveSettings(settings.value)
}
async function refreshEnv() {
env.value = await commands.musicEnvStatus()
}
async function loadSources() {
try {
const v = (await invoke('music_get_sources')) as { sources: string[] }
availableSources.value = v.sources ?? []
} catch (e) {
logger.error(`加载音乐源失败: ${e}`)
availableSources.value = []
}
}
async function pingBridge(): Promise<MusicPingPayload> {
return (await invoke('music_ping')) as MusicPingPayload
}
async function search(keyword: string, sources: string[]) {
searching.value = true
searchError.value = ''
try {
const v = (await invoke('music_search', { keyword, sources })) as MusicSearchPayload
results.value = v.results ?? {}
resultTotal.value = v.total ?? 0
searched.value = true
} catch (e) {
searchError.value = typeof e === 'string' ? e : JSON.stringify(e)
throw e
} finally {
searching.value = false
}
}
// ===== 歌单解析 =====
const parsing = ref(false)
const parseError = ref('')
/** 解析歌单链接,结果以首个歌曲来源为键写入 results(与搜索共用展示/下载) */
async function parsePlaylist(url: string, sources: string[]) {
parsing.value = true
parseError.value = ''
try {
const v = (await invoke('music_parse_playlist', { url, sources })) as {
songs: MusicSong[]
count: number
}
const count = v.count ?? 0
searched.value = true
if (count > 0) {
const srcKey = v.songs[0]?.source ?? 'playlist'
results.value = { [srcKey]: v.songs }
resultTotal.value = count
} else {
results.value = {}
resultTotal.value = 0
}
return count
} catch (e) {
parseError.value = typeof e === 'string' ? e : JSON.stringify(e)
throw e
} finally {
parsing.value = false
}
}
// ===== 下载任务 =====
const tasks = ref<MusicDownloadTask[]>([])
let downloadUnlisten: UnlistenFn | null = null
// 任务历史持久化(localStorage,应用重启后保留记录;恢复时不尝试续传)
const TASKS_KEY = 'thing.music.tasks'
const MAX_TASKS = 30
let persistTimer: ReturnType<typeof setTimeout> | null = null
function persistTasks() {
try {
localStorage.setItem(TASKS_KEY, JSON.stringify(tasks.value.slice(0, MAX_TASKS)))
} catch {
// localStorage 不可用/超限时静默降级(仅影响历史记录)
}
}
function restoreTasks() {
try {
const raw = localStorage.getItem(TASKS_KEY)
if (!raw) return
const arr = JSON.parse(raw) as MusicDownloadTask[]
if (!Array.isArray(arr)) return
for (const t of arr) {
// 重启后桥接已无下载状态:残留的"下载中"统一标记为中断;
// "取消中"表明用户已请求取消,落定为已取消
if (t.status === 'downloading') t.status = 'interrupted'
else if (t.status === 'cancelling') t.status = 'cancelled'
if (!Array.isArray(t.songs)) t.songs = []
if (!Array.isArray(t.songsData)) t.songsData = []
}
tasks.value = arr.slice(0, MAX_TASKS)
} catch {
// 数据损坏则丢弃历史
}
}
// 仅在结构性变化(任务增删 / 任务状态 / 完成数)时持久化:
// 用轻量签名代替深度 watch,避免下载进度事件(每 300ms 修改 downloaded
// 触发 30 个任务(含 songsData)的全量 JSON 序列化
const tasksSignature = computed(
() => tasks.value.map((t) => `${t.taskId}:${t.status}:${t.doneCount}`).join('|')
)
watch(
tasksSignature,
() => {
if (persistTimer) clearTimeout(persistTimer)
persistTimer = setTimeout(persistTasks, 400)
}
)
async function ensureDownloadListener() {
if (downloadUnlisten) return
downloadUnlisten = await listen<MusicDownloadEvent>('music-download-event', (e) => {
handleDownloadEvent(e.payload)
})
}
function handleDownloadEvent(ev: MusicDownloadEvent) {
if (ev.type === 'bridge-stopped') {
// 桥接进程被停止:活动任务标记为中断;取消中的任务落定为已取消
for (const t of tasks.value) {
if (t.status === 'downloading') t.status = 'interrupted'
else if (t.status === 'cancelling') t.status = 'cancelled'
}
return
}
if (!ev.taskId) return
const task = tasks.value.find((t) => t.taskId === ev.taskId)
if (!task) return
const type = ev.type
if (type === 'resolving') {
// 懒解析:下载 worker 正在解析真实下载链接(第三方 API + 官方音质阶梯)
const st = task.songs.find((s) => s.key === ev.key)
if (st) {
st.status = 'resolving'
st.songName = ev.songName ?? st.songName
st.singers = ev.singers ?? st.singers
}
if (task.status !== 'cancelling') task.status = 'downloading'
} else if (type === 'start') {
const st = task.songs.find((s) => s.key === ev.key)
if (st) {
st.status = 'downloading'
st.songName = ev.songName ?? st.songName
st.singers = ev.singers ?? st.singers
st.total = ev.total ?? st.total
st.quality = ev.quality ?? st.quality
}
// 取消请求后桥接仍可能推送在途歌曲的 start 事件,不覆盖「取消中」状态
if (task.status !== 'cancelling') task.status = 'downloading'
} else if (type === 'progress') {
const st = task.songs.find((s) => s.key === ev.key)
if (st) {
st.downloaded = ev.downloaded ?? 0
st.total = ev.total ?? st.total
}
} else if (type === 'done') {
const st = task.songs.find((s) => s.key === ev.key)
if (st) {
st.status = 'done'
st.downloaded = st.total || st.downloaded
}
task.doneCount++
} else if (type === 'error') {
const st = task.songs.find((s) => s.key === ev.key)
if (st) {
st.status = 'error'
st.message = ev.message
} else if (ev.key === undefined) {
// 任务级错误(worker 初始化失败/监督线程异常):桥接不会再发 finished,
// 此处直接落定最终状态,避免任务永久停留在「下载中」
task.errorMessage = ev.message
task.status = task.status === 'cancelling' ? 'cancelled' : 'error'
}
} else if (type === 'cancelled') {
const st = task.songs.find((s) => s.key === ev.key)
if (st) st.status = 'cancelled'
} else if (type === 'finished') {
const anyError = task.songs.some((s) => s.status === 'error')
const anyCancelled = task.songs.some((s) => s.status === 'cancelled')
task.status = anyError ? 'error' : anyCancelled ? 'cancelled' : 'done'
}
}
/** 清洗文件名中的 Windows 非法字符(\ / : * ? " < > | 及控制字符),并去掉结尾空格/点 */
function sanitizeFilename(name: string): string {
return (
name
.replace(/[\\/:*?"<>|\x00-\x1f]/g, '')
.replace(/\s+/g, ' ')
.trim()
.replace(/[. ]+$/, '') || 'music'
)
}
/** 懒解析:解析单首歌曲的真实下载链接(试听前调用),成功后原地更新
* 搜索结果并返回带链接的最新歌曲对象;失败返回 null */
async function resolveSong(source: string, index: number): Promise<MusicSong | null> {
const song = results.value[source]?.[index]
if (!song) return null
if (song.downloadUrl) return song
if (!song.rawSearch) return null
const v = (await invoke('music_resolve', { song })) as {
songs: (MusicSong | null)[]
}
const resolved = v.songs?.[0]
if (!resolved?.downloadUrl) return null
// 原地更新(索引未变,key 稳定);保留 rawSearch 供后续重新解析
if (results.value[source]?.[index] === song) {
results.value[source][index] = { ...song, ...resolved }
}
return resolved
}
/** 启动下载。engine='rust' 时交给下载器模块(任务在其列表中管理),返回跳过的无链接歌曲数;
* 否则走 musicdl 桥接,返回 0 */
async function startDownload(
songs: MusicSong[],
opts: {
savedir: string
lyric: boolean
cover: boolean
proxyUrl: string
engine: string
maxConcurrent: number
/** 目标音质 label"" 表示最高);解析下载时按「≤所选最优档」封顶 */
quality?: string
}
): Promise<number> {
if (songs.length === 0) return 0
await ensureDownloadListener()
const quality = opts.quality ?? ''
if (opts.engine === 'rust') {
// 懒解析歌曲先批量解析出真实链接(桥接内并行),再交给下载器模块
const lazy = songs.filter((s) => !s.downloadUrl && s.rawSearch)
if (lazy.length > 0) {
try {
const v = (await invoke('music_resolve', { songs: lazy, quality })) as {
songs: (MusicSong | null)[]
}
// 返回与输入顺序对齐,失败位为 null
v.songs?.forEach((r, i) => {
if (r && lazy[i]) Object.assign(lazy[i], r)
})
} catch (e) {
logger.error(`批量解析下载链接失败: ${e}`)
}
}
let skipped = 0
for (const song of songs) {
if (!song.downloadUrl) {
skipped++
continue
}
const ext = (song.ext ?? '').replace(/[\\/:*?"<>|\x00-\x1f]/g, '')
const raw = `${song.songName ?? 'music'}${ext ? '.' + ext : ''}`
try {
await commands.downloaderAddTask(
song.downloadUrl,
sanitizeFilename(raw),
opts.savedir,
song.defaultDownloadHeaders ?? null,
true,
null
)
} catch (e) {
logger.error(`下载失败 ${song.songName}: ${e}`)
throw e
}
}
return skipped
}
const taskId = crypto.randomUUID()
const task: MusicDownloadTask = {
taskId,
engine: 'musicdl',
status: 'downloading',
doneCount: 0,
createdAt: Date.now(),
songsData: songs,
savedir: opts.savedir,
quality,
songs: songs.map((s, idx) => ({
key: `${s.source ?? ''}|${idx}`,
songName: s.songName ?? '',
singers: s.singers ?? '',
status: 'queued' as const,
downloaded: 0,
total: s.fileSizeBytes ?? 0
}))
}
tasks.value.unshift(task)
if (tasks.value.length > 30) tasks.value.length = 30
try {
await invoke('music_download', {
taskId,
// 有 rawSearch 时丢弃搜索阶段的 downloadUrl(CDN 链接有时效,
// 交给桥接在下载 worker 里重新解析,顺带修复"隔夜链接过期"问题)
songs: songs.map((s) => (s.rawSearch ? { ...s, downloadUrl: null } : s)),
savedir: opts.savedir,
lyric: opts.lyric,
cover: opts.cover,
proxyUrl: opts.proxyUrl,
maxConcurrent: opts.maxConcurrent,
quality
})
} catch (e) {
task.status = 'error'
task.errorMessage = String(e)
throw e
}
return 0
}
async function cancelDownload(taskId: string) {
const task = tasks.value.find((t) => t.taskId === taskId)
if (!task || (task.status !== 'downloading' && task.status !== 'cancelling')) return
// 队列级取消:当前歌曲会完成,其余标记取消;最终状态由 finished 事件落定,
// 此处先置「取消中」防止用户在剩余歌曲停止前误点「重新下载」产生重复任务
task.status = 'cancelling'
try {
await invoke('music_download_cancel', { taskId })
} catch {
// 桥接不可用(进程已死,无后台下载)→ 直接落定为已取消,避免卡在取消中
if (task.status === 'cancelling') task.status = 'cancelled'
}
}
function removeTask(taskId: string) {
// 下载中/取消中的任务先请求队列级取消,防止移除后后台仍在下载
const task = tasks.value.find((t) => t.taskId === taskId)
if (task && (task.status === 'downloading' || task.status === 'cancelling')) {
invoke('music_download_cancel', { taskId }).catch(() => {})
}
tasks.value = tasks.value.filter((t) => t.taskId !== taskId)
}
/** 重新下载:用任务内保存的完整歌曲数据重新发起(error/cancelled/interrupted 状态可用) */
async function redownloadTask(taskId: string) {
const task = tasks.value.find((t) => t.taskId === taskId)
if (
!task ||
task.status === 'downloading' ||
task.status === 'cancelling' ||
task.songsData.length === 0
) {
return
}
const s = settings.value
if (!s) return
// 代理 URL:惰性读取代理模块设置(避免 store 初始化时跨 store 依赖)
let proxy = ''
if (s.useProxy) {
const port = useProxyStore().settings?.mixedPort
proxy = port ? `http://127.0.0.1:${port}` : ''
}
await startDownload(task.songsData, {
savedir: s.savedir,
lyric: s.lyricDownload,
cover: s.coverDownload,
proxyUrl: proxy,
engine: s.downloadEngine,
maxConcurrent: s.maxConcurrent,
quality: s.defaultDownloadQuality ?? ''
})
}
async function installRuntime() {
if (installing.value) return
installing.value = true
installError.value = ''
installProgress.value = null
if (!progressUnlisten) {
progressUnlisten = await listen<MusicInstallProgress>(
'music-runtime-install-progress',
(e) => {
installProgress.value = e.payload
}
)
}
try {
env.value = await commands.musicInstallRuntime()
} catch (e) {
// 保留失败原因供设置页面板展示;进度停在最后事件值,需清掉避免误导
installError.value = typeof e === 'string' ? e : JSON.stringify(e)
throw e
} finally {
installing.value = false
if (progressUnlisten) {
progressUnlisten()
progressUnlisten = null
}
}
}
function cancelInstall() {
commands.musicCancelRuntimeInstall().catch(() => {})
}
async function stopBridge() {
await commands.musicStopBridge()
}
return {
settings,
env,
availableSources,
searching,
searchError,
searched,
parsing,
parseError,
results,
resultTotal,
installing,
installProgress,
installError,
tasks,
init,
loadSettings,
saveSettings,
refreshEnv,
loadSources,
pingBridge,
search,
parsePlaylist,
resolveSong,
startDownload,
cancelDownload,
removeTask,
redownloadTask,
installRuntime,
cancelInstall,
stopBridge
}
})