修复: 文件预览误报脏标记与编辑丢失等一批缺陷
- 脏标记行尾归一(含裸\r),CRLF 文件打开不再误报未保存 - 防抖回灌校验发起文件+flushEmit,杜绝串文件与丢尾 - F5/tab淘汰/读失败/草稿/重命名/保存刷新六处状态一致性修复 - GBK 文件按原编码回写(接口零改动),保存不再悄悄转 UTF-8 - .sh 系高亮根修(StreamLanguage 导入源错),面包屑长名截断 - CSV 大文件门豁免+表头贴顶;空标题滤除与 iframe 边距去除 - BGM 播放器增强收编(拖拽seek/音量/连播/快捷键/路径导航折叠) - 版本 0.5.3,CHANGELOG 同步
This commit is contained in:
1 parent
e5e8054916
commit
bce14a0480
26 files changed
+989
-117
No files matched your search
@@ -13,3 +13,4 @@ docs/08-用户指南/u-desk-site/
|
||||
temp/
|
||||
frontend/temp/
|
||||
build/publish/*.exe
|
||||
out/
|
||||
@@ -1,5 +1,44 @@
|
||||
# 更新日志
|
||||
|
||||
## [0.5.3] - 2026-11-22
|
||||
|
||||
### 修复 🐛
|
||||
- **打开文件误报"未保存"**: 打开带 CRLF/混合行尾的源码文件,未编辑即显示变更标记的问题(行尾归一比较,覆盖 \r\n 与裸 \r)
|
||||
- **编辑内容丢失两连**: 输入后 150ms 内切文件/切标签页,尾部按键静默丢失;同窗口内 Ctrl+S 保存的是滞后内容
|
||||
- **串文件事故隐患**: 快速切换文件时旧文件内容可能被回灌到新文件编辑器(防抖回灌增加发起文件校验)
|
||||
- **F5 静默覆盖修改**: 编辑中按 F5 重载不再直接覆盖,有未保存修改时先弹确认
|
||||
- **第 11 个标签页挤掉脏标签**: 标签页满时优先淘汰无修改的标签,不再静默丢弃未保存内容
|
||||
- **GBK 文件保存即转码**: 中文 ANSI/批处理等 GBK 文件保存后不再被悄悄转成 UTF-8(按原编码回写)
|
||||
- **重命名后标签页指向旧路径**: 重命名文件后标签与会话恢复同步指向新路径
|
||||
- **读文件失败残留旧内容**: 读取失败时清空编辑区,不再显示上一个文件的内容
|
||||
- **.sh/.bash 无语法高亮**: 语言加载器 StreamLanguage 导入源错误导致 shell 系高亮自迁移起一直失效
|
||||
- **面包屑长目录名撑破地址栏**: 超长目录名截断显示(悬停看全名),不再换行撑成两行
|
||||
- **CSV 预览**: 大 CSV 不再被大文件门拦截(表格预览自带分批渲染);表头贴顶显示去除顶部间隙
|
||||
- **草稿防丢**: 打开带草稿的文件不再误删草稿备份;读取失败清空残留
|
||||
- **保存后列表即时刷新**: 保存成功后文件列表的修改时间/大小同步更新
|
||||
|
||||
### 优化 🚀
|
||||
- **预览区顶部空白**: Markdown 空标题不再渲染成空白条;HTML 预览去除 iframe 默认边距
|
||||
- **音频优先识别**: ogg/webm 归类为音频而非视频;.dat 文本数据文件不再盲判为二进制
|
||||
|
||||
## [0.5.2] - 2026-11-14
|
||||
|
||||
### 新增 ✨
|
||||
- **在线音乐即点即播**: 点击云端存储的音乐边下边播不再等整首下载完,进度条随意拖动;目录支持"▶ 连播"一键排队循环播放;云端目录可一键批量加入播放列表(上限 50 首)
|
||||
|
||||
### 优化 🚀
|
||||
- **背景音乐播放手感全面升级**: 进度条支持拖拽定位(拖动中实时跳转,不再只能点击),悬停显示时间气泡
|
||||
- **音量可调**: 新增音量按钮与悬浮滑块,0-100 档位记忆,一键静音,切歌后音量不丢失
|
||||
- **切歌即时反馈**: 远程曲目解析地址期间标题区显示加载动效,不再出现"点了没反应"的空窗
|
||||
- **播放列表可拖拽排序**: 列表项拖动重排并自动保存,顺序调整即时生效
|
||||
- **列表信息更完整**: 每首显示时长,正在播放的曲目以跳动音柱标识
|
||||
- **快捷键支持**: 空格播放/暂停、左右方向键快退快进 5 秒(输入框内不触发)
|
||||
|
||||
### 修复 🐛
|
||||
- **关闭 BGM 行为澄清**: 点 ✕ 仅隐藏播放条、音乐继续播放(可经 📻 按钮重新唤出);📻 按钮第三击才彻底停止并清空播放状态
|
||||
- **全局热键失效**: Ctrl+Shift+B 按下播放条不弹出(事件链断裂)已修复
|
||||
- **文件预览内容陈旧**: 文件修改后预览仍显示旧内容、刷新也无效的问题(预览响应彻底禁用浏览器缓存;远程文件元信息获取失败时不再使用可能过期的本地缓存副本)
|
||||
|
||||
## [0.5.1] - 2026-10-24
|
||||
|
||||
### 新增 ✨
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
{
|
||||
"version": "0.5.0",
|
||||
"download_url": "https://c.1216.top/download/u-desk-0.5.0.exe",
|
||||
"changelog": "### 新增 ✨\n- **预览导出 PDF**: HTML/Markdown 预览一键导出为 PDF,成功后自动打开所在文件夹并选中文件\n- **剪贴板粘贴文件**: 资源管理器复制的文件/文件夹可直接粘贴进文件列表(本机=复制,SFTP=上传)\n- **收藏展示名自定义**: 收藏项可自定义显示名称,收藏列表默认展开\n- **服务器右键菜单**: 服务器列表支持右键菜单,连接/管理操作直达\n- **一键全连**: 服务器管理菜单新增\"一键全连\",并发连接全部服务器\n\n### 优化 🚀\n- **收藏置顶项**: 置顶背景加深为清晰浅蓝,一眼区分置顶与普通收藏\n- **收藏栏宽度可调**: 拖拽调整侧边栏收藏区宽度并记忆\n\n### 修复 🐛\n- **窗口内容收窄**: 切换服务器/目录时偶发的内容区收窄卡住不再出现,自动恢复满宽\n- **Markdown 导出**: file URL 转义修正,含空格/特殊字符路径导出正常\n- **PDF 导出稳定性**: 浏览器探测补全,导出失败立即提示不再无响应",
|
||||
"version": "0.5.1",
|
||||
"download_url": "https://c.1216.top/download/u-desk-0.5.1.exe",
|
||||
"changelog": "### 新增 ✨\n- **粘贴截图为文件**: 文件列表直接 Ctrl+V 粘贴剪贴板截图,自动保存为图片并提示落盘位置(修复\"粘贴没反应\")\n- **PDF 导出目录设置**: 设置面板新增「导出设置」,可自定义 PDF 保存位置\n\n### 优化 🚀\n- **打开大文档更快**: Markdown 组件按需加载+空闲预热,大文件从数秒级降到即时\n- **编辑更流畅**: 边写边渲染防抖,长文档打字不卡顿\n- **操作防连点**: 连接/保存/下载防重复,误触不再产生重复任务\n- **超时保护**: 连接 9 秒超时提示,SFTP 掉线快速报错,快捷方式解析 10 秒超时\n- **日志更干净**: 静态资源请求不再刷屏\n\n### 修复 🐛\n- **目录图标不显示**: 字段错位导致恒不显示的问题\n- **设置保存丢字段**: 部分配置保存后字段丢失\n- **删除大目录冻结界面**: 不再冻结整个窗口\n- **SFTP 连接窗口期错位**: 拨号期不再错误回退本机目录,跨盘路径自动回根\n- **PDF 导出文案**: 成功提示展示实际落盘路径",
|
||||
"force_update": false,
|
||||
"release_date": "2026-10-01",
|
||||
"file_size": 8324096,
|
||||
"sha256": "26422786300ea1d0b7100295893b11aaf9bfb61078180745f12b5d09e019878d"
|
||||
"release_date": "2026-10-24",
|
||||
"file_size": 8288256,
|
||||
"sha256": "16f85c4798e810ed574fdb7caff72c65525af85a832e287085d3b4b1dbe0a161"
|
||||
}
|
||||
@@ -1,6 +1,15 @@
|
||||
{
|
||||
"updated_at": "2026-10-01T20:30:00+08:00",
|
||||
"updated_at": "2026-10-24T05:52:41.379+08:00",
|
||||
"versions": [
|
||||
{
|
||||
"version": "0.5.1",
|
||||
"download_url": "https://c.1216.top/download/u-desk-0.5.1.exe",
|
||||
"changelog": "### 新增 ✨\n- **粘贴截图为文件**: 文件列表直接 Ctrl+V 粘贴剪贴板截图,自动保存为图片并提示落盘位置(修复\"粘贴没反应\")\n- **PDF 导出目录设置**: 设置面板新增「导出设置」,可自定义 PDF 保存位置\n\n### 优化 🚀\n- **打开大文档更快**: Markdown 组件按需加载+空闲预热,大文件从数秒级降到即时\n- **编辑更流畅**: 边写边渲染防抖,长文档打字不卡顿\n- **操作防连点**: 连接/保存/下载防重复,误触不再产生重复任务\n- **超时保护**: 连接 9 秒超时提示,SFTP 掉线快速报错,快捷方式解析 10 秒超时\n- **日志更干净**: 静态资源请求不再刷屏\n\n### 修复 🐛\n- **目录图标不显示**: 字段错位导致恒不显示的问题\n- **设置保存丢字段**: 部分配置保存后字段丢失\n- **删除大目录冻结界面**: 不再冻结整个窗口\n- **SFTP 连接窗口期错位**: 拨号期不再错误回退本机目录,跨盘路径自动回根\n- **PDF 导出文案**: 成功提示展示实际落盘路径",
|
||||
"force_update": false,
|
||||
"release_date": "2026-10-24",
|
||||
"file_size": 8288256,
|
||||
"sha256": "16f85c4798e810ed574fdb7caff72c65525af85a832e287085d3b4b1dbe0a161"
|
||||
},
|
||||
{
|
||||
"version": "0.5.0",
|
||||
"release_date": "2026-10-01",
|
||||
|
||||
+1
-1
Submodule docs/08-用户指南/u-desk-site updated: 15016c01b7...3bf3fbdf66.
@@ -69,14 +69,30 @@ const languageCompartment = new Compartment()
|
||||
// ==================== 防抖处理 ====================
|
||||
|
||||
let emitTimeout = null
|
||||
let pendingValue = null
|
||||
let pendingPath = ''
|
||||
const debouncedEmit = (value) => {
|
||||
if (emitTimeout) {
|
||||
clearTimeout(emitTimeout)
|
||||
}
|
||||
pendingValue = value
|
||||
pendingPath = props.filePath || ''
|
||||
emitTimeout = setTimeout(() => {
|
||||
emitTimeout = null
|
||||
emit('update:modelValue', value)
|
||||
}, 150)
|
||||
}
|
||||
// 立即冲刷待发的内容变更;期间已切换文件则丢弃,防止串写到新文件
|
||||
const flushEmit = () => {
|
||||
if (!emitTimeout) return
|
||||
clearTimeout(emitTimeout)
|
||||
emitTimeout = null
|
||||
if (pendingPath === (props.filePath || '')) {
|
||||
emit('update:modelValue', pendingValue)
|
||||
}
|
||||
pendingValue = null
|
||||
pendingPath = ''
|
||||
}
|
||||
|
||||
// 获取当前主题扩展
|
||||
const getThemeExtension = () => {
|
||||
@@ -281,6 +297,7 @@ watch(() => themeStore.isDark, () => {
|
||||
watch(() => props.fileExtension, () => {
|
||||
initLanguage()
|
||||
})
|
||||
defineExpose({ flushEmit })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
|
||||
@@ -58,7 +58,8 @@ const onProgress = (event: unknown) => {
|
||||
// 构造 viewer iframe src
|
||||
const buildViewerSrc = async (filePath: string): Promise<string> => {
|
||||
// 1. .drawio 原文 URL(本地/远程自适应;远程先下载到 temp 再走 localfs)
|
||||
const xmlUrl = await resolveFileUrl(filePath)
|
||||
// 显式 stream=false:viewer iframe 需要同源可 fetch 的 URL,OSS 签名直链跨域不适用
|
||||
const xmlUrl = await resolveFileUrl(filePath, false)
|
||||
if (!xmlUrl) throw new Error('无法解析文件 URL(远程下载可能失败)')
|
||||
|
||||
// 2. viewer base = 本地文件服务器(与 /drawio-viewer/ 路由及原文同源)
|
||||
|
||||
@@ -12,17 +12,30 @@
|
||||
<div class="bgm-bar" ref="bgmBarEl">
|
||||
<span class="bgm-icon">📻</span>
|
||||
<template v-if="src">
|
||||
<button class="bgm-btn" @click="playPrev" title="上一首">⏮</button>
|
||||
<button class="bgm-btn" @click="togglePlay">{{ playing ? '⏸' : '▶' }}</button>
|
||||
<button class="bgm-btn" @click="playNext" title="下一首">⏭</button>
|
||||
<a-tooltip content="上一首"><button class="bgm-btn" @click="playPrev">⏮</button></a-tooltip>
|
||||
<a-tooltip :content="playing ? '暂停' : '播放'"><button class="bgm-btn" @click="togglePlay">{{ playing ? '⏸' : '▶' }}</button></a-tooltip>
|
||||
<a-tooltip content="下一首"><button class="bgm-btn" @click="playNext">⏭</button></a-tooltip>
|
||||
<span class="bgm-time">{{ currentFmt }} / {{ durationFmt }}</span>
|
||||
<div class="bgm-progress" @click="seek">
|
||||
<div
|
||||
class="bgm-progress"
|
||||
:class="{ dragging: dragging }"
|
||||
@pointerdown="onSeekDown"
|
||||
@pointermove="onSeekHover"
|
||||
@pointerup="onSeekUp"
|
||||
@pointercancel="onSeekUp"
|
||||
@pointerleave="hoverTime = null"
|
||||
>
|
||||
<div class="bgm-progress-filled" :style="{ width: progress + '%' }"></div>
|
||||
<div v-if="hoverTime !== null" class="bgm-progress-tip" :style="{ left: hoverPercent + '%' }">
|
||||
{{ formatTime(hoverTime) }}
|
||||
</div>
|
||||
<span class="bgm-title">{{ title }}</span>
|
||||
<button class="bgm-btn" @click="cyclePlayMode" :title="playModeLabel">{{ playModeIcon }}</button>
|
||||
</div>
|
||||
<span class="bgm-title" :class="{ 'bgm-title-loading': switching }">
|
||||
<span v-if="switching" class="bgm-spinner"></span>{{ title }}
|
||||
</span>
|
||||
<a-tooltip :content="playModeLabel"><button class="bgm-btn" @click="cyclePlayMode">{{ playModeIcon }}</button></a-tooltip>
|
||||
<button v-if="lyrics.length" class="bgm-btn bgm-btn-text" @click="lyricsOpen = !lyricsOpen"
|
||||
:title="lyricsOpen ? '收起歌词' : '展开歌词'" :style="{ color: lyricsOpen ? 'rgb(var(--primary-6))' : undefined }">词</button>
|
||||
:style="{ color: lyricsOpen ? 'rgb(var(--primary-6))' : undefined }">词</button>
|
||||
</template>
|
||||
<template v-else>
|
||||
<button class="bgm-btn" disabled>⏮</button>
|
||||
@@ -33,19 +46,50 @@
|
||||
<div class="bgm-progress-filled" style="width:0%"></div>
|
||||
</div>
|
||||
<span class="bgm-title bgm-title-idle">暂无播放音乐</span>
|
||||
<button class="bgm-btn" disabled title="播放模式">🔁</button>
|
||||
<button class="bgm-btn" disabled>🔁</button>
|
||||
</template>
|
||||
<button class="bgm-btn" @click="playlistOpen = !playlistOpen" title="播放列表">🎵</button>
|
||||
<button class="bgm-btn bgm-btn-close" @click="emit('stop')" title="关闭 BGM">✕</button>
|
||||
<div class="bgm-volume" @pointerenter="volumeEnter" @pointerleave="volumeLeave">
|
||||
<button class="bgm-btn" @click="toggleMute" @pointerenter="volumeEnter">
|
||||
{{ muted || volume === 0 ? '🔇' : volume < 50 ? '🔉' : '🔊' }}
|
||||
</button>
|
||||
<div class="bgm-volume-slider" :class="{ open: volumeOpen }"
|
||||
@pointerenter="volumeEnter" @pointerleave="volumeLeave">
|
||||
<span class="bgm-volume-value">{{ muted ? '静音' : volume + '%' }}</span>
|
||||
<input
|
||||
type="range" min="0" max="100" step="1" orient="vertical"
|
||||
:value="muted ? 0 : volume"
|
||||
:style="{ '--fill': (muted ? 0 : volume) + '%' }"
|
||||
@input="onVolumeInput"
|
||||
class="bgm-volume-range"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<a-tooltip content="播放列表"><button class="bgm-btn" @click="playlistOpen = !playlistOpen">🎵</button></a-tooltip>
|
||||
<a-tooltip content="隐藏 BGM(音乐继续播放)"><button class="bgm-btn bgm-btn-close" @click="closeBgm">✕</button></a-tooltip>
|
||||
<div v-if="playlistOpen" class="bgm-playlist">
|
||||
<div class="bgm-playlist-header">播放列表</div>
|
||||
<div v-for="(track, idx) in playlist" :key="track.path"
|
||||
class="bgm-playlist-item"
|
||||
:class="{ active: track.path === currentPath || (!currentPath && track.path === lastPlayedPath) }"
|
||||
:class="{
|
||||
active: track.path === currentPath || (!currentPath && track.path === lastPlayedPath),
|
||||
dragging: dragIdx === idx,
|
||||
'drag-over': dragOverIdx === idx && dragIdx !== idx
|
||||
}"
|
||||
draggable="true"
|
||||
@dragstart="onDragStart(idx, $event)"
|
||||
@dragover.prevent="onDragOver(idx)"
|
||||
@dragleave="onDragLeave(idx)"
|
||||
@drop.prevent="onDrop(idx)"
|
||||
@dragend="onDragEnd"
|
||||
@click="playTrack(track)"
|
||||
>
|
||||
<span class="bgm-pl-indicator">
|
||||
<span v-if="isPlayingTrack(track)" class="bgm-eq"><i></i><i></i><i></i></span>
|
||||
<span v-else class="bgm-pl-index">{{ idx + 1 }}</span>
|
||||
</span>
|
||||
<span class="bgm-pl-name">{{ track.name }}</span>
|
||||
<span class="bgm-pl-remove" @click.stop="removeTrack(idx)">✕</span>
|
||||
<span v-if="track.duration" class="bgm-pl-dur">{{ formatTime(track.duration) }}</span>
|
||||
<a-tooltip content="从列表移除"><span class="bgm-pl-remove" @click.stop="removeTrack(idx)">✕</span></a-tooltip>
|
||||
</div>
|
||||
<div v-if="playlist.length === 0" class="bgm-playlist-empty">暂无记录</div>
|
||||
</div>
|
||||
@@ -65,7 +109,7 @@
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
export interface BgmTrack { name: string; path: string; url: string; profileId?: string }
|
||||
export interface BgmTrack { name: string; path: string; url: string; profileId?: string; duration?: number }
|
||||
</script>
|
||||
|
||||
<script setup lang="ts">
|
||||
@@ -98,6 +142,9 @@ const lyricsOpen = ref(false)
|
||||
const currentLyricIdx = ref(-1)
|
||||
const lyricsWrapRef = ref<HTMLElement | null>(null)
|
||||
const playingPath = ref('')
|
||||
// 切歌加载态:父组件解析 URL 期间置 true(playFrom 时清除)
|
||||
const switching = ref(false)
|
||||
watch(() => props.src, () => { switching.value = false })
|
||||
|
||||
// 播放模式
|
||||
type PlayMode = 'single' | 'sequential' | 'random' | 'loop'
|
||||
@@ -137,7 +184,8 @@ const restorePlaylist = async (resolver?: (path: string) => Promise<string | und
|
||||
const entries = await BgmGetPlaylist()
|
||||
if (!entries?.length) return
|
||||
if (resolver) {
|
||||
const results = await Promise.all(entries.map(e => resolver(e.path)))
|
||||
// 并发重签;单条失败置空被下方 filter 静默跳过,不阻塞整列表
|
||||
const results = await Promise.all(entries.map(e => resolver(e.path).catch(() => '')))
|
||||
playlist.value = entries
|
||||
.map((e, i) => ({ name: e.name, path: e.path, url: results[i] || '' }))
|
||||
.filter((_, i) => results[i])
|
||||
@@ -159,6 +207,11 @@ const _restoreLastPlayed = () => {
|
||||
if (!track) return
|
||||
lastPlayedPath.value = saved
|
||||
playingPath.value = saved
|
||||
// 上次 BGM 开启中 → 自动恢复播放(url 为空走父组件解析链路,含自动建连)
|
||||
if (localStorage.getItem('desk:bgmActive') === 'true') {
|
||||
playingPath.value = ''
|
||||
playTrack(track)
|
||||
}
|
||||
}
|
||||
restorePlaylist().then(_restoreLastPlayed)
|
||||
|
||||
@@ -189,6 +242,51 @@ const removeTrack = (idx: number) => {
|
||||
savePlaylist()
|
||||
}
|
||||
|
||||
// ---------- 播放列表拖拽排序 ----------
|
||||
const dragIdx = ref(-1)
|
||||
const dragOverIdx = ref(-1)
|
||||
|
||||
const onDragStart = (idx: number, e: DragEvent) => {
|
||||
dragIdx.value = idx
|
||||
dragOverIdx.value = -1
|
||||
if (e.dataTransfer) {
|
||||
e.dataTransfer.effectAllowed = 'move'
|
||||
e.dataTransfer.setData('text/plain', String(idx))
|
||||
}
|
||||
}
|
||||
|
||||
const onDragOver = (idx: number) => {
|
||||
if (dragIdx.value === -1) return
|
||||
dragOverIdx.value = idx
|
||||
}
|
||||
|
||||
const onDragLeave = (idx: number) => {
|
||||
if (dragOverIdx.value === idx) dragOverIdx.value = -1
|
||||
}
|
||||
|
||||
const onDrop = (idx: number) => {
|
||||
const from = dragIdx.value
|
||||
dragIdx.value = -1
|
||||
dragOverIdx.value = -1
|
||||
if (from === -1 || from === idx) return
|
||||
const list = playlist.value.slice()
|
||||
const [moved] = list.splice(from, 1)
|
||||
list.splice(idx, 0, moved)
|
||||
playlist.value = list
|
||||
savePlaylist()
|
||||
}
|
||||
|
||||
const onDragEnd = () => {
|
||||
dragIdx.value = -1
|
||||
dragOverIdx.value = -1
|
||||
}
|
||||
|
||||
// 当前是否正在播放该曲目(用于列表动效指示)
|
||||
const isPlayingTrack = (track: BgmTrack): boolean => {
|
||||
if (!playing.value) return false
|
||||
return track.path === playingPath.value || track.url === props.src
|
||||
}
|
||||
|
||||
// 时间格式化
|
||||
const formatTime = (s: number): string => {
|
||||
if (!s || !isFinite(s)) return '0:00'
|
||||
@@ -223,6 +321,11 @@ const onTimeUpdate = () => {
|
||||
if (audioRef.value) {
|
||||
currentTime.value = audioRef.value.currentTime
|
||||
duration.value = audioRef.value.duration || 0
|
||||
// 记录当前曲目时长,供播放列表展示
|
||||
if (duration.value && playingPath.value) {
|
||||
const t = playlist.value.find(x => x.path === playingPath.value)
|
||||
if (t && t.duration !== duration.value) t.duration = duration.value
|
||||
}
|
||||
syncLyrics(currentTime.value)
|
||||
}
|
||||
}
|
||||
@@ -248,6 +351,103 @@ const seek = (e: MouseEvent) => {
|
||||
audioRef.value.currentTime = ratio * duration.value
|
||||
}
|
||||
|
||||
// ---------- 进度条拖拽 + 悬停时间气泡 ----------
|
||||
const dragging = ref(false)
|
||||
const hoverTime = ref<number | null>(null)
|
||||
const hoverPercent = computed(() => duration.value ? Math.min((hoverTime.value ?? 0) / duration.value * 100, 100) : 0)
|
||||
|
||||
const ratioAt = (el: HTMLElement, clientX: number): number => {
|
||||
const rect = el.getBoundingClientRect()
|
||||
return Math.max(0, Math.min(1, (clientX - rect.left) / rect.width))
|
||||
}
|
||||
|
||||
const onSeekDown = (e: PointerEvent) => {
|
||||
if (!audioRef.value || !duration.value) return
|
||||
const bar = e.currentTarget as HTMLElement
|
||||
dragging.value = true
|
||||
bar.setPointerCapture?.(e.pointerId)
|
||||
audioRef.value.currentTime = ratioAt(bar, e.clientX) * duration.value
|
||||
}
|
||||
|
||||
const onSeekHover = (e: PointerEvent) => {
|
||||
if (!duration.value) return
|
||||
const bar = e.currentTarget as HTMLElement
|
||||
const ratio = ratioAt(bar, e.clientX)
|
||||
hoverTime.value = ratio * duration.value
|
||||
if (dragging.value && audioRef.value) audioRef.value.currentTime = ratio * duration.value
|
||||
}
|
||||
|
||||
const onSeekUp = (e: PointerEvent) => {
|
||||
if (!dragging.value) return
|
||||
dragging.value = false
|
||||
const bar = e.currentTarget as HTMLElement
|
||||
bar.releasePointerCapture?.(e.pointerId)
|
||||
}
|
||||
|
||||
// ---------- 音量(localStorage 记忆) ----------
|
||||
const VOLUME_KEY = 'desk:bgmVolume'
|
||||
const _initVolume = (): number => {
|
||||
const v = Number(localStorage.getItem(VOLUME_KEY))
|
||||
return isFinite(v) && v >= 0 && v <= 100 ? v : 80
|
||||
}
|
||||
const volume = ref(_initVolume())
|
||||
const muted = ref(false)
|
||||
const volumeOpen = ref(false)
|
||||
// 桥接延迟关闭:鼠标从按钮移向滑块途经空隙时 pointerleave 先触发,延迟关防「中途消失」
|
||||
let volumeCloseTimer: ReturnType<typeof setTimeout> | undefined
|
||||
const volumeEnter = () => {
|
||||
clearTimeout(volumeCloseTimer)
|
||||
volumeOpen.value = true
|
||||
}
|
||||
const volumeLeave = () => {
|
||||
clearTimeout(volumeCloseTimer)
|
||||
volumeCloseTimer = setTimeout(() => { volumeOpen.value = false }, 150)
|
||||
}
|
||||
|
||||
const applyVolume = () => {
|
||||
if (audioRef.value) audioRef.value.volume = muted.value ? 0 : volume.value / 100
|
||||
}
|
||||
|
||||
const onVolumeInput = (e: Event) => {
|
||||
volume.value = Number((e.target as HTMLInputElement).value)
|
||||
if (volume.value > 0) muted.value = false
|
||||
localStorage.setItem(VOLUME_KEY, String(volume.value))
|
||||
applyVolume()
|
||||
}
|
||||
|
||||
const toggleMute = () => {
|
||||
muted.value = !muted.value
|
||||
applyVolume()
|
||||
}
|
||||
|
||||
watch(volume, applyVolume)
|
||||
watch(muted, applyVolume)
|
||||
|
||||
// ---------- 快捷键(焦点在输入框时不响应) ----------
|
||||
const isTypingTarget = (t: EventTarget | null): boolean => {
|
||||
const el = t as HTMLElement | null
|
||||
if (!el) return false
|
||||
const tag = el.tagName
|
||||
return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || el.isContentEditable
|
||||
}
|
||||
|
||||
const onKeydown = (e: KeyboardEvent) => {
|
||||
if (!props.src || isTypingTarget(e.target)) return
|
||||
if (e.ctrlKey || e.altKey || e.metaKey) return
|
||||
const a = audioRef.value
|
||||
if (!a) return
|
||||
if (e.code === 'Space') {
|
||||
e.preventDefault()
|
||||
togglePlay()
|
||||
} else if (e.code === 'ArrowRight') {
|
||||
e.preventDefault()
|
||||
a.currentTime = Math.min((a.currentTime || 0) + 5, duration.value || Infinity)
|
||||
} else if (e.code === 'ArrowLeft') {
|
||||
e.preventDefault()
|
||||
a.currentTime = Math.max((a.currentTime || 0) - 5, 0)
|
||||
}
|
||||
}
|
||||
|
||||
const playTrack = (track: BgmTrack) => {
|
||||
playlistOpen.value = false
|
||||
lastPlayedPath.value = ''
|
||||
@@ -308,24 +508,24 @@ const playNext = () => {
|
||||
const onEnded = () => {
|
||||
const mode = playMode.value
|
||||
if (mode === 'single') {
|
||||
emit('stop')
|
||||
haltAtStart()
|
||||
return
|
||||
}
|
||||
// 只有一首歌时,loop 直接重播,其他模式停止
|
||||
// 只有一首歌时,loop 直接重播,其他模式停在原地
|
||||
if (playlist.value.length <= 1) {
|
||||
if (mode === 'loop') {
|
||||
nextTick(() => {
|
||||
if (audioRef.value) { audioRef.value.currentTime = 0; audioRef.value.play().catch(() => {}) }
|
||||
})
|
||||
} else {
|
||||
emit('stop')
|
||||
haltAtStart()
|
||||
}
|
||||
return
|
||||
}
|
||||
const idx = curIdx()
|
||||
// sequential: 到末尾停止
|
||||
// sequential: 到末尾停在最后一首
|
||||
if (mode === 'sequential' && idx === playlist.value.length - 1) {
|
||||
emit('stop')
|
||||
haltAtStart()
|
||||
return
|
||||
}
|
||||
const nextIdx = getNextIdx()
|
||||
@@ -333,6 +533,12 @@ const onEnded = () => {
|
||||
pendingTimer.value = setTimeout(() => playTrack(playlist.value[nextIdx]), NEXT_TRACK_DELAY)
|
||||
}
|
||||
|
||||
// 播完/失败时原地暂停并回零:工具条保留、bgmActive 不变,下次启动可恢复;仅手动 ✕ 真正关闭
|
||||
const haltAtStart = () => {
|
||||
playing.value = false
|
||||
if (audioRef.value) audioRef.value.currentTime = 0
|
||||
}
|
||||
|
||||
// 播放失败自动跳到下一首(不删除,下次重试下载)
|
||||
const _failedUrls = new Set<string>()
|
||||
const onAudioError = () => {
|
||||
@@ -340,7 +546,11 @@ const onAudioError = () => {
|
||||
_failedUrls.add(props.src)
|
||||
console.warn('[BgmBar] 播放失败,跳过:', props.src)
|
||||
const len = playlist.value.length
|
||||
if (len <= 1) { emit('stop'); return }
|
||||
if (len <= 1) {
|
||||
haltAtStart()
|
||||
Message.error('BGM 播放失败,请检查文件连接')
|
||||
return
|
||||
}
|
||||
// 最多尝试 len 次,避免无限循环
|
||||
for (let attempt = 0; attempt < len; attempt++) {
|
||||
const nextIdx = getNextIdx()
|
||||
@@ -351,7 +561,8 @@ const onAudioError = () => {
|
||||
return
|
||||
}
|
||||
}
|
||||
emit('stop')
|
||||
haltAtStart()
|
||||
Message.error('BGM 播放列表全部失败,请检查连接后重试')
|
||||
}
|
||||
|
||||
watch(() => props.src, (url) => {
|
||||
@@ -367,14 +578,36 @@ watch(() => props.src, (url) => {
|
||||
|
||||
function playFrom(currentTime?: number) {
|
||||
console.debug('[BgmBar] playFrom, src:', props.src, 'time:', currentTime)
|
||||
switching.value = false
|
||||
nextTick(() => {
|
||||
if (audioRef.value) {
|
||||
applyVolume()
|
||||
if (currentTime !== undefined) audioRef.value.currentTime = currentTime
|
||||
audioRef.value.play().catch(() => {})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// 父组件切歌前调用:置加载态(URL 解析可能耗时)
|
||||
function markSwitching() {
|
||||
switching.value = true
|
||||
}
|
||||
|
||||
// 切歌失败时由父组件调用:解除加载态并提示(避免 spinner 卡死、失败无反馈)
|
||||
function markSwitchFailed(reason: string) {
|
||||
switching.value = false
|
||||
Message.error(`播放失败: ${reason}`)
|
||||
}
|
||||
|
||||
// 关闭 BGM 条:仅隐藏 UI,音乐继续播放(经父组件 📻 BGM 按钮可重新显示)
|
||||
function closeBgm() {
|
||||
// 取消排队的自动切歌,避免隐藏后切歌链路把条再次拉起
|
||||
clearTimeout(pendingTimer.value)
|
||||
playlistOpen.value = false
|
||||
lyricsOpen.value = false
|
||||
emit('stop')
|
||||
}
|
||||
|
||||
function getAudioElement() {
|
||||
return audioRef.value
|
||||
}
|
||||
@@ -386,6 +619,7 @@ onUnmounted(() => {
|
||||
audioRef.value.src = ''
|
||||
}
|
||||
document.removeEventListener('click', handleClickOutside)
|
||||
window.removeEventListener('keydown', onKeydown)
|
||||
})
|
||||
|
||||
const handleClickOutside = (e: MouseEvent) => {
|
||||
@@ -395,11 +629,16 @@ const handleClickOutside = (e: MouseEvent) => {
|
||||
}
|
||||
onMounted(() => {
|
||||
document.addEventListener('click', handleClickOutside)
|
||||
window.addEventListener('keydown', onKeydown)
|
||||
// 防止浏览器恢复媒体会话导致自动播放
|
||||
if (audioRef.value) audioRef.value.pause()
|
||||
})
|
||||
|
||||
defineExpose({ playFrom, getAudioElement, addToPlaylist, addBatch, restorePlaylist })
|
||||
function setPlayMode(mode: PlayMode) {
|
||||
if (VALID_MODES.has(mode)) playMode.value = mode
|
||||
}
|
||||
|
||||
defineExpose({ playFrom, getAudioElement, addToPlaylist, addBatch, restorePlaylist, setPlayMode, markSwitching, markSwitchFailed })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
@@ -492,12 +731,143 @@ defineExpose({ playFrom, getAudioElement, addToPlaylist, addBatch, restorePlayli
|
||||
cursor: pointer;
|
||||
min-width: 80px;
|
||||
transition: height 0.15s;
|
||||
position: relative;
|
||||
touch-action: none;
|
||||
}
|
||||
|
||||
.bgm-progress:hover {
|
||||
.bgm-progress:hover,
|
||||
.bgm-progress.dragging {
|
||||
height: 6px;
|
||||
}
|
||||
|
||||
.bgm-progress.dragging {
|
||||
cursor: grabbing;
|
||||
}
|
||||
|
||||
.bgm-progress-tip {
|
||||
position: absolute;
|
||||
bottom: 100%;
|
||||
transform: translateX(-50%);
|
||||
margin-bottom: 6px;
|
||||
padding: 1px 5px;
|
||||
font-size: 10px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
color: #fff;
|
||||
background: rgba(0, 0, 0, 0.75);
|
||||
border-radius: 3px;
|
||||
pointer-events: none;
|
||||
white-space: nowrap;
|
||||
z-index: 5;
|
||||
}
|
||||
|
||||
/* 音量 */
|
||||
.bgm-volume {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.bgm-volume-slider {
|
||||
position: absolute;
|
||||
/* 抬离按钮 6px:贴死显下沉,间隙由 150ms 桥接延迟兜底 */
|
||||
bottom: calc(100% + 6px);
|
||||
left: 50%;
|
||||
transform: translateX(-50%) translateY(6px);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 8px 6px 6px;
|
||||
background: var(--color-bg-popup);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 -4px 14px rgba(0, 0, 0, 0.14);
|
||||
z-index: 20;
|
||||
opacity: 0;
|
||||
visibility: hidden;
|
||||
pointer-events: none;
|
||||
transition: opacity 0.15s ease, transform 0.15s ease, visibility 0.15s;
|
||||
}
|
||||
|
||||
.bgm-volume-slider.open {
|
||||
opacity: 1;
|
||||
visibility: visible;
|
||||
pointer-events: auto;
|
||||
transform: translateX(-50%) translateY(0);
|
||||
}
|
||||
|
||||
.bgm-volume-value {
|
||||
font-size: 10px;
|
||||
color: var(--color-text-2);
|
||||
font-variant-numeric: tabular-nums;
|
||||
line-height: 1;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* 竖向滑杆:底部为 0,顶部为 100(writing-mode + direction 控制方向);自定义轨道+拇指,--fill 驱动已填充渐变 */
|
||||
.bgm-volume-range {
|
||||
writing-mode: vertical-lr;
|
||||
direction: rtl;
|
||||
width: 16px;
|
||||
height: 88px;
|
||||
appearance: none;
|
||||
-webkit-appearance: none;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.bgm-volume-range::-webkit-slider-runnable-track {
|
||||
width: 4px;
|
||||
border-radius: 2px;
|
||||
background: linear-gradient(
|
||||
to top,
|
||||
rgb(var(--primary-6)) 0,
|
||||
rgb(var(--primary-6)) var(--fill, 0%),
|
||||
var(--color-fill-3) var(--fill, 0%),
|
||||
var(--color-fill-3) 100%
|
||||
);
|
||||
}
|
||||
|
||||
.bgm-volume-range::-webkit-slider-thumb {
|
||||
appearance: none;
|
||||
-webkit-appearance: none;
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
margin-left: -4px;
|
||||
border-radius: 50%;
|
||||
background: rgb(var(--primary-6));
|
||||
border: 2px solid #fff;
|
||||
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.25);
|
||||
transition: transform 0.12s;
|
||||
}
|
||||
|
||||
.bgm-volume-range:active::-webkit-slider-thumb {
|
||||
transform: scale(1.15);
|
||||
}
|
||||
|
||||
/* 切歌加载态 */
|
||||
.bgm-title-loading {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.bgm-spinner {
|
||||
width: 9px;
|
||||
height: 9px;
|
||||
border: 1.5px solid var(--color-text-4);
|
||||
border-top-color: rgb(var(--primary-6));
|
||||
border-radius: 50%;
|
||||
animation: bgm-spin 0.7s linear infinite;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
@keyframes bgm-spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
.bgm-progress-filled {
|
||||
height: 100%;
|
||||
background: rgb(var(--primary-6));
|
||||
@@ -564,6 +934,63 @@ defineExpose({ playFrom, getAudioElement, addToPlaylist, addBatch, restorePlayli
|
||||
background: var(--color-primary-light-1);
|
||||
}
|
||||
|
||||
.bgm-playlist-item.dragging {
|
||||
opacity: 0.4;
|
||||
}
|
||||
|
||||
.bgm-playlist-item.drag-over {
|
||||
box-shadow: inset 0 2px 0 rgb(var(--primary-6));
|
||||
}
|
||||
|
||||
/* 序号 / 播放中指示 */
|
||||
.bgm-pl-indicator {
|
||||
flex-shrink: 0;
|
||||
width: 16px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin-right: 4px;
|
||||
}
|
||||
|
||||
.bgm-pl-index {
|
||||
font-size: 10px;
|
||||
color: var(--color-text-4);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* 播放中均衡器动效 */
|
||||
.bgm-eq {
|
||||
display: inline-flex;
|
||||
align-items: flex-end;
|
||||
gap: 1.5px;
|
||||
height: 10px;
|
||||
}
|
||||
|
||||
.bgm-eq i {
|
||||
display: block;
|
||||
width: 2px;
|
||||
background: rgb(var(--primary-6));
|
||||
border-radius: 1px;
|
||||
animation: bgm-eq-bounce 0.9s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.bgm-eq i:nth-child(1) { height: 40%; animation-delay: 0s; }
|
||||
.bgm-eq i:nth-child(2) { height: 100%; animation-delay: 0.3s; }
|
||||
.bgm-eq i:nth-child(3) { height: 60%; animation-delay: 0.6s; }
|
||||
|
||||
@keyframes bgm-eq-bounce {
|
||||
0%, 100% { transform: scaleY(0.4); }
|
||||
50% { transform: scaleY(1); }
|
||||
}
|
||||
|
||||
.bgm-pl-dur {
|
||||
flex-shrink: 0;
|
||||
margin-left: 6px;
|
||||
font-size: 10px;
|
||||
color: var(--color-text-4);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.bgm-pl-name {
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
<template>
|
||||
<div class="file-editor-panel" :class="{ 'is-fullscreen': isFullscreen }" :style="{ width: width + '%' }">
|
||||
<div class="file-editor-panel" :class="{ 'is-fullscreen': isFullscreen }" :style="{ width: `calc(${width}% - 1.5px)` }">
|
||||
<!-- 有选中文件时显示表头和内容 -->
|
||||
<template v-if="config.currentFileName">
|
||||
<div class="panel-header">
|
||||
<span class="panel-title">
|
||||
<template v-if="config.activePlugin">{{ config.activePlugin.icon }} {{ config.activePlugin.name }}</template>
|
||||
<template v-else-if="config.isImageView">🖼️ 图片预览</template>
|
||||
<template v-else-if="config.isVideoView">🎬 视频预览</template>
|
||||
<template v-else-if="config.isAudioView">🎵 音频预览</template>
|
||||
<template v-else-if="config.isVideoView">🎬 视频预览</template>
|
||||
<template v-else-if="config.isPdfFile">📕 PDF 预览</template>
|
||||
<template v-else-if="config.isHtmlFile">🌐 HTML 预览</template>
|
||||
<template v-else-if="config.isMarkdownFile">📝 Markdown 预览</template>
|
||||
@@ -75,16 +75,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 视频预览 -->
|
||||
<div v-else-if="config.isVideoView" class="media-preview">
|
||||
<video :src="config.previewUrl" controls class="preview-video" @error="handleMediaError('视频')" @canplay="mediaErrorMsg = ''"></video>
|
||||
<div v-if="mediaErrorMsg" class="media-error">{{ mediaErrorMsg }}</div>
|
||||
<div class="media-meta">
|
||||
<a-tag color="arcoblue">🎬 视频</a-tag>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 音频预览 -->
|
||||
<!-- 音频预览(先于视频判定:ogg/webm 同属两列表,音频优先) -->
|
||||
<div v-else-if="config.isAudioView" class="media-preview">
|
||||
<audio
|
||||
ref="audioRef"
|
||||
@@ -101,7 +92,17 @@
|
||||
<a-tag color="green">🎵 音频</a-tag>
|
||||
<a-button v-if="!audioBGM" size="mini" :type="audioLoop ? 'primary' : 'outline'" @click="audioLoop = !audioLoop">🔁 循环</a-button>
|
||||
<a-button size="mini" :type="audioBGM ? 'primary' : 'outline'" @click="toggleBGM">📻 BGM</a-button>
|
||||
<a-button v-if="audioBGM" size="mini" type="outline" @click="scanAndAddAll" :loading="scanLoading" title="扫描当前目录音频文件并添加到播放列表">🎵+ 全部</a-button>
|
||||
<a-tooltip content="扫描当前目录音频文件并添加到播放列表"><a-button v-if="audioBGM" size="mini" type="outline" @click="scanAndAddAll" :loading="scanLoading">🎵+ 全部</a-button></a-tooltip>
|
||||
<a-tooltip content="扫描当前目录音频并从第一首顺序连播"><a-button v-if="audioBGM" size="mini" type="outline" @click="playAllSequential" :loading="scanLoading">▶ 连播</a-button></a-tooltip>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 视频预览 -->
|
||||
<div v-else-if="config.isVideoView" class="media-preview">
|
||||
<video :src="config.previewUrl" controls class="preview-video" @error="handleMediaError('视频')" @canplay="mediaErrorMsg = ''"></video>
|
||||
<div v-if="mediaErrorMsg" class="media-error">{{ mediaErrorMsg }}</div>
|
||||
<div class="media-meta">
|
||||
<a-tag color="arcoblue">🎬 视频</a-tag>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -173,6 +174,7 @@
|
||||
<!-- 编辑模式 -->
|
||||
<div v-else class="csv-edit-wrapper">
|
||||
<AsyncCodeEditor
|
||||
ref="codeEditorRef"
|
||||
:model-value="config.fileContent"
|
||||
:file-extension="config.currentFileExtension"
|
||||
:file-path="config.currentFileFullPath"
|
||||
@@ -244,11 +246,13 @@
|
||||
v-if="!config.isEditMode"
|
||||
class="html-preview-content"
|
||||
:src="htmlPreviewUrl"
|
||||
@load="handleHtmlIframeLoad"
|
||||
></iframe>
|
||||
|
||||
<!-- 编辑模式 -->
|
||||
<div v-else class="html-edit-wrapper">
|
||||
<AsyncCodeEditor
|
||||
ref="codeEditorRef"
|
||||
:model-value="config.fileContent"
|
||||
:file-extension="config.currentFileExtension"
|
||||
:file-path="config.currentFileFullPath"
|
||||
@@ -317,6 +321,7 @@
|
||||
<!-- 编辑模式 -->
|
||||
<div v-else class="markdown-edit-wrapper">
|
||||
<AsyncCodeEditor
|
||||
ref="codeEditorRef"
|
||||
:model-value="config.fileContent"
|
||||
:file-extension="config.currentFileExtension"
|
||||
:file-path="config.currentFileFullPath"
|
||||
@@ -372,6 +377,7 @@
|
||||
</div>
|
||||
|
||||
<AsyncCodeEditor
|
||||
ref="codeEditorRef"
|
||||
:model-value="config.fileContent"
|
||||
:file-extension="config.currentFileExtension"
|
||||
:file-path="config.currentFileFullPath"
|
||||
@@ -432,7 +438,7 @@
|
||||
:current-path="config.currentFileFullPath"
|
||||
:title="bgmTitle"
|
||||
:lyrics="bgmLyrics"
|
||||
@stop="stopBGM"
|
||||
@stop="hideBgm"
|
||||
@switch="onBgmSwitch"
|
||||
/>
|
||||
</div>
|
||||
@@ -475,6 +481,7 @@ const AsyncCodeEditor = defineAsyncComponent({
|
||||
|
||||
// Office 预览容器引用
|
||||
const excelPreviewRef = ref<HTMLElement | null>(null)
|
||||
const codeEditorRef = ref<{ flushEmit: () => void } | null>(null)
|
||||
const wordPreviewRef = ref<HTMLElement | null>(null)
|
||||
const csvPreviewRef = ref<HTMLElement | null>(null)
|
||||
|
||||
@@ -545,8 +552,27 @@ const htmlPreviewUrl = ref('')
|
||||
// 导出 PDF 需要本地可访问的源文件路径:远程文件取缓存副本,本地文件即原路径
|
||||
const htmlPreviewLocalPath = ref('')
|
||||
|
||||
// HTML iframe 预览:注入 body{margin:0} 消除预览区顶部空白(srcdoc/URL 两种模式同处理;跨域时静默跳过)
|
||||
const handleHtmlIframeLoad = (event: Event) => {
|
||||
try {
|
||||
const doc = (event.target as HTMLIFrameElement).contentDocument
|
||||
if (!doc) return
|
||||
const style = doc.createElement('style')
|
||||
style.textContent = 'body{margin:0}'
|
||||
doc.head?.appendChild(style)
|
||||
} catch {
|
||||
// 跨域 iframe 无法访问 contentDocument,忽略
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => [props.config.currentFileFullPath, props.config.isHtmlFile],
|
||||
// 预览态下 fileContent 也作为来源:外部(LLM/其它进程)改写文件后内容重载会触发 URL 重建;
|
||||
// 编辑态置 '' 避免按键打字反复重建(编辑态 iframe 本就不显示)
|
||||
() => [
|
||||
props.config.currentFileFullPath,
|
||||
props.config.isHtmlFile,
|
||||
props.config.isEditMode ? '' : props.config.fileContent
|
||||
],
|
||||
async ([path, isHtml]: [string, boolean]) => {
|
||||
htmlPreviewUrl.value = ''
|
||||
htmlPreviewLocalPath.value = ''
|
||||
@@ -554,7 +580,10 @@ watch(
|
||||
|
||||
// 下载到临时目录后是本地文件,统一用本地文件服务器
|
||||
const base = getFileServerBaseURL()
|
||||
const makeUrl = (localPath: string) => `${base}/localfs/html-preview?path=${encodeURIComponent(localPath)}`
|
||||
const makeUrl = (localPath: string) => {
|
||||
// _t 打破 WebView 缓存:同 path 重载时强制拉最新内容
|
||||
return `${base}/localfs/html-preview?path=${encodeURIComponent(localPath)}&_t=${Date.now()}`
|
||||
}
|
||||
const applyLocalPath = (localPath: string) => {
|
||||
htmlPreviewLocalPath.value = localPath
|
||||
htmlPreviewUrl.value = makeUrl(localPath)
|
||||
@@ -694,25 +723,45 @@ const loadLyrics = async (audioPath: string) => {
|
||||
|
||||
watch(audioLoop, (v) => localStorage.setItem('desk:audioLoop', String(v)))
|
||||
|
||||
// BGM 模式:将当前音频转为后台播放
|
||||
// BGM 模式:将当前音频转为后台播放(三态:未开启→开启 / 隐藏中→仅显示 / 可见中→彻底停止)
|
||||
const toggleBGM = () => {
|
||||
if (!audioBGM.value) {
|
||||
bgmSrc.value = props.config.previewUrl
|
||||
bgmTitle.value = props.config.currentFileName
|
||||
audioBGM.value = true
|
||||
bgmHidden.value = false
|
||||
localStorage.setItem('desk:bgmActive', 'true')
|
||||
localStorage.setItem('desk:bgmHidden', 'false')
|
||||
if (props.config.currentFileFullPath) loadLyrics(props.config.currentFileFullPath)
|
||||
// 暂停内联播放器,切换到 BgmBar
|
||||
const t = audioRef.value?.currentTime || 0
|
||||
if (audioRef.value) audioRef.value.pause()
|
||||
nextTick(() => bgmBarRef.value?.playFrom(t))
|
||||
} else if (bgmHidden.value) {
|
||||
// 音乐播放中但条被隐藏(✕ 仅隐藏):点 📻 只是把条显示回来,不打断播放
|
||||
bgmHidden.value = false
|
||||
localStorage.setItem('desk:bgmHidden', 'false')
|
||||
} else {
|
||||
stopBGM()
|
||||
}
|
||||
}
|
||||
|
||||
// 彻底停止 BGM(📻 按钮三态的关闭分支)
|
||||
const stopBGM = () => {
|
||||
bgmHidden.value = true
|
||||
// 同步清空源与元信息,避免 audio 元素仍持有 URL
|
||||
bgmSrc.value = ''
|
||||
bgmTitle.value = ''
|
||||
bgmLyrics.value = []
|
||||
audioBGM.value = false
|
||||
localStorage.setItem('desk:bgmActive', 'false')
|
||||
localStorage.setItem('desk:bgmHidden', 'false')
|
||||
}
|
||||
|
||||
// 仅隐藏 BGM 条(✕ 触发):音乐继续播放,重启后自动恢复后台播放
|
||||
const hideBgm = () => {
|
||||
bgmHidden.value = true
|
||||
localStorage.setItem('desk:bgmHidden', 'true')
|
||||
}
|
||||
|
||||
// 外部调用:直接将音频加入 BGM 播放列表并播放(不打开 tab)
|
||||
@@ -721,6 +770,8 @@ const playAudioAsBGM = (name: string, path: string, url: string) => {
|
||||
bgmTitle.value = name
|
||||
audioBGM.value = true
|
||||
bgmHidden.value = false
|
||||
localStorage.setItem('desk:bgmActive', 'true')
|
||||
localStorage.setItem('desk:bgmHidden', 'false')
|
||||
nextTick(() => {
|
||||
bgmBarRef.value?.addToPlaylist(name, path, url)
|
||||
bgmBarRef.value?.playFrom(0)
|
||||
@@ -730,8 +781,17 @@ const playAudioAsBGM = (name: string, path: string, url: string) => {
|
||||
|
||||
const onBgmSwitch = async (track: BgmTrack) => {
|
||||
bgmTitle.value = track.name
|
||||
const wasActive = audioBGM.value
|
||||
audioBGM.value = true
|
||||
bgmHidden.value = false
|
||||
localStorage.setItem('desk:bgmActive', 'true')
|
||||
// 仅首次开启时弹出条;自动切歌/启动恢复保持当前可见性(上次隐藏退出 → 重启后台播放不弹条)
|
||||
if (!wasActive) {
|
||||
const hidden = localStorage.getItem('desk:bgmHidden') === 'true'
|
||||
bgmHidden.value = hidden
|
||||
localStorage.setItem('desk:bgmHidden', String(hidden))
|
||||
}
|
||||
// URL 需远程解析时先置加载态,避免切歌期间 UI 无反馈
|
||||
if (!track.url && track.path) bgmBarRef.value?.markSwitching()
|
||||
try {
|
||||
if (track.url) {
|
||||
bgmSrc.value = track.url
|
||||
@@ -741,6 +801,7 @@ const onBgmSwitch = async (track: BgmTrack) => {
|
||||
} catch (e) {
|
||||
console.warn('[BGM] 切歌 URL 解析失败:', e)
|
||||
bgmSrc.value = ''
|
||||
bgmBarRef.value?.markSwitchFailed((e as Error)?.message || '地址解析失败')
|
||||
return
|
||||
}
|
||||
if (track.path) {
|
||||
@@ -751,43 +812,83 @@ const onBgmSwitch = async (track: BgmTrack) => {
|
||||
}
|
||||
|
||||
const scanLoading = ref(false)
|
||||
const scanAndAddAll = async () => {
|
||||
if (connectionManager.isRemote()) {
|
||||
Message.warning('远程模式下暂不支持批量扫描')
|
||||
return
|
||||
const OSS_SCAN_MAX = 50
|
||||
const SFTP_SCAN_MAX = 20
|
||||
|
||||
// 扫描目录音频并加入播放列表,返回成功导入的曲目(供连播入口复用)
|
||||
const scanAudioToPlaylist = async (): Promise<BgmTrack[]> => {
|
||||
const isOss = connectionManager.activeProfile?.type === 'oss'
|
||||
const isSftp = connectionManager.isSftp()
|
||||
if (!isOss && !isSftp && connectionManager.isRemote()) {
|
||||
Message.warning('该远程类型暂不支持批量扫描')
|
||||
return []
|
||||
}
|
||||
const dir = props.currentDirectory || getParentPath(props.config.currentFileFullPath)
|
||||
if (!dir) return
|
||||
if (!dir) return []
|
||||
console.debug('[BGM] 扫描目录:', dir)
|
||||
const max = isOss ? OSS_SCAN_MAX : SFTP_SCAN_MAX
|
||||
scanLoading.value = true
|
||||
try {
|
||||
const files = await listDir(dir)
|
||||
const audioFiles = files.filter(f => !f.isDir && isAudioFile(f.name))
|
||||
if (!audioFiles.length) {
|
||||
const audioAll = files.filter(f => !f.isDir && isAudioFile(f.name))
|
||||
if (!audioAll.length) {
|
||||
Message.info('当前目录未发现音频文件')
|
||||
return
|
||||
return []
|
||||
}
|
||||
const results = await Promise.allSettled(audioFiles.map(f => resolveFileUrl(f.path, true)))
|
||||
if (audioAll.length > max) {
|
||||
Message.warning(`音频文件超过 ${max} 首,仅添加前 ${max} 首`)
|
||||
}
|
||||
const audioFiles = audioAll.slice(0, max)
|
||||
if (isSftp) Message.info('需先缓存,文件多时较慢')
|
||||
const tracks: BgmTrack[] = []
|
||||
if (isOss) {
|
||||
// OSS:签名直链,并发解析
|
||||
const results = await Promise.allSettled(audioFiles.map(f => resolveFileUrl(f.path, true)))
|
||||
for (let i = 0; i < audioFiles.length; i++) {
|
||||
const r = results[i]
|
||||
if (r.status === 'fulfilled' && r.value) {
|
||||
tracks.push({ name: audioFiles[i].name, path: audioFiles[i].path, url: r.value })
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// SFTP/本地:逐条解析,失败静默跳过
|
||||
for (const f of audioFiles) {
|
||||
try {
|
||||
const url = await resolveFileUrl(f.path, true)
|
||||
if (url) tracks.push({ name: f.name, path: f.path, url })
|
||||
} catch (e) {
|
||||
console.warn('[BGM] 单曲解析失败,跳过:', f.path, e)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!tracks.length) {
|
||||
Message.warning('音频文件 URL 解析均失败')
|
||||
return
|
||||
return []
|
||||
}
|
||||
bgmBarRef.value?.addBatch(tracks)
|
||||
Message.success(`已添加 ${tracks.length} 首音频到播放列表`)
|
||||
return tracks
|
||||
} catch (e) {
|
||||
Message.error(`扫描失败: ${e?.message || e}`)
|
||||
return []
|
||||
} finally {
|
||||
scanLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const scanAndAddAll = () => scanAudioToPlaylist()
|
||||
|
||||
// 自动播放全部:扫描当前目录音频 → 循环模式 → 从第一首连播
|
||||
const playAllSequential = async () => {
|
||||
const tracks = await scanAudioToPlaylist()
|
||||
if (!tracks.length) return
|
||||
bgmBarRef.value?.setPlayMode('loop')
|
||||
audioBGM.value = true
|
||||
bgmHidden.value = false
|
||||
const first = tracks[0] // addBatch 逐个 unshift 使播放列表倒序,目录第一首即 tracks[0]
|
||||
await onBgmSwitch(first)
|
||||
}
|
||||
|
||||
// 切换文件时自动替换 BGM 内容(仅在 BGM 已激活时)
|
||||
watch(() => props.config.previewUrl, (url) => {
|
||||
mediaErrorMsg.value = ''
|
||||
@@ -1195,7 +1296,11 @@ onUnmounted(() => {
|
||||
copyCleanup()
|
||||
})
|
||||
|
||||
defineExpose({ toggleBGM, toggleBgmVisibility: () => { bgmHidden.value = !bgmHidden.value }, playAudioAsBGM })
|
||||
// 冲刷编辑器防抖队列(防丢尾/串写):保存或缓存 tab 状态前调用
|
||||
const flushEditors = () => {
|
||||
codeEditorRef.value?.flushEmit?.()
|
||||
}
|
||||
defineExpose({ toggleBGM, hideBgm, toggleBgmVisibility: () => { bgmHidden.value = !bgmHidden.value; localStorage.setItem('desk:bgmHidden', String(bgmHidden.value)) }, playAudioAsBGM, flushEditors })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<div class="file-list-panel" :style="{ width: width + '%' }">
|
||||
<div class="file-list-panel" :style="{ width: `calc(${width}% - 1.5px)` }">
|
||||
<div class="panel-header">
|
||||
<span class="panel-title">📋 文件列表</span>
|
||||
<div class="panel-header-right">
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
@mouseleave="onMenuLeave"
|
||||
@click="onClick(segment)"
|
||||
>
|
||||
<span class="segment-text">{{ segment.name }}</span>
|
||||
<span class="segment-text" :title="segment.name">{{ segment.name }}</span>
|
||||
|
||||
<!-- 悬停弹出菜单 -->
|
||||
<Transition name="dropdown-fade">
|
||||
@@ -228,7 +228,8 @@ watch(() => props.path, () => {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
flex-wrap: wrap;
|
||||
flex-wrap: nowrap;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.breadcrumb-segment {
|
||||
@@ -254,6 +255,10 @@ watch(() => props.path, () => {
|
||||
font-size: 13px;
|
||||
color: var(--color-text-1);
|
||||
white-space: nowrap;
|
||||
/* 超长目录名截断显示,不把地址栏撑成多行(悬停 title 可看全名) */
|
||||
max-width: 320px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.breadcrumb-separator {
|
||||
|
||||
@@ -114,9 +114,12 @@ export function useFileEdit(options: UseFileEditOptions = {}) {
|
||||
* 计算属性:文件内容是否改变
|
||||
*/
|
||||
const contentChanged = computed(() => {
|
||||
if (fileContent.value === '' || originalContent.value === undefined) return false
|
||||
// 未加载文件时不视为变更(未加载态两者同为 '',自然为 false)
|
||||
// 统一 CRLF → LF 再比较,避免编辑器内部 \n 与文件原始 \r\n 产生误判
|
||||
return originalContent.value.replace(/\r\n/g, '\n') !== fileContent.value.replace(/\r\n/g, '\n')
|
||||
// 注意:不能因 fileContent 为空就跳过比较——清空全文是合法编辑,否则保存按钮消失、无法保存
|
||||
// CM6 连裸 \r 也归一为 \n,故归一须同时覆盖 \r\n 与 lone \r
|
||||
const norm = (s: string) => s.replace(/\r\n/g, '\n').replace(/\r/g, '\n')
|
||||
return norm(originalContent.value) !== norm(fileContent.value)
|
||||
})
|
||||
|
||||
/**
|
||||
@@ -309,6 +312,8 @@ ${ext ? `文件类型: ${fileTypeDesc}\n` : ''}
|
||||
// 加载草稿(如果存在)
|
||||
loadDraft(path)
|
||||
} catch (error) {
|
||||
// 读取失败清残留内容,避免展示上一个文件的内容冒充当前文件
|
||||
clearContent()
|
||||
Message.error(`读取文件失败: ${error}`)
|
||||
}
|
||||
}
|
||||
@@ -331,8 +336,8 @@ ${ext ? `文件类型: ${fileTypeDesc}\n` : ''}
|
||||
return
|
||||
}
|
||||
|
||||
// 检查内容是否真的改变了
|
||||
if (fileContent.value === originalContent.value) {
|
||||
// 检查内容是否真的改变了(与 contentChanged 同口径:CRLF 归一后比较)
|
||||
if (!contentChanged.value) {
|
||||
if (!isShortcut) {
|
||||
Message.info('文件内容未变更')
|
||||
}
|
||||
@@ -555,10 +560,13 @@ ${ext ? `文件类型: ${fileTypeDesc}\n` : ''}
|
||||
}
|
||||
|
||||
// 监听文件路径变化,清除草稿
|
||||
// 重命名场景(updateFilePath 已迁移草稿 key 到新路径):newPath 对应的 key 与当前 draftKey 一致则不清除
|
||||
// (saveDraft 历史上以 FileItem 对象拼 key、loadDraft 以路径字符串拼 key,故用「key 包含新路径」宽松匹配)
|
||||
watch(currentFilePath, (newPath, oldPath) => {
|
||||
if (newPath !== oldPath) {
|
||||
if (newPath === oldPath) return
|
||||
const newPathStr = newPath ? getFilePath(newPath) : ''
|
||||
if (draftKey.value && newPathStr && draftKey.value.endsWith(newPathStr)) return
|
||||
clearDraft()
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
|
||||
@@ -70,7 +70,9 @@ async function resolveWithTransport(
|
||||
/**
|
||||
* 统一文件 URL 解析(使用当前活跃 transport)
|
||||
*/
|
||||
export async function resolveFileUrl(path: string, stream = false): Promise<string> {
|
||||
// 默认 stream=true:OSS 走 getSignedUrl 预签名直链(1h 有效),浏览器边下边播;
|
||||
// 本地/SFTP 无 getSignedUrl 自动回落原路径,行为不变
|
||||
export async function resolveFileUrl(path: string, stream = true): Promise<string> {
|
||||
if (!path) return ''
|
||||
return resolveWithTransport(connectionManager.getTransport(), path, stream)
|
||||
}
|
||||
@@ -80,11 +82,20 @@ export async function resolveFileUrl(path: string, stream = false): Promise<stri
|
||||
* 不切换当前活跃连接,直接从连接池取对应 transport
|
||||
*/
|
||||
export async function resolveFileUrlForProfile(
|
||||
path: string, profileId: string | undefined, stream = false
|
||||
path: string, profileId: string | undefined, stream = true
|
||||
): Promise<string> {
|
||||
if (!path) return ''
|
||||
if (profileId) {
|
||||
const transport = connectionManager.getTransportFor(profileId)
|
||||
let transport = connectionManager.getTransportFor(profileId)
|
||||
// 池中无该连接(应用刚启动/连接断开):自动建连后重试,避免历史播放列表因「连接未就绪」整体不可播
|
||||
if (!transport) {
|
||||
try {
|
||||
await connectionManager.connect(profileId)
|
||||
transport = connectionManager.getTransportFor(profileId)
|
||||
} catch (e) {
|
||||
throw new Error(`BGM 曲目所在连接 ${profileId} 无法建立: ${(e as Error).message}`)
|
||||
}
|
||||
}
|
||||
if (transport) return resolveWithTransport(transport, path, stream)
|
||||
}
|
||||
return resolveFileUrl(path, stream)
|
||||
@@ -167,7 +178,7 @@ export function useFilePreview() {
|
||||
* 判断文件是否可编辑
|
||||
*/
|
||||
const isEditable = (filename: string, fileSize: number): boolean => {
|
||||
if (fileSize > FILE_SIZE_THRESHOLDS.BIG_FILE) return false
|
||||
if (fileSize > FILE_SIZE_THRESHOLDS.LARGE_FILE) return false
|
||||
if (!filename || typeof filename !== 'string') return false
|
||||
const ext = getExt(filename)
|
||||
return FILE_EXTENSIONS.CODE.includes(ext) ||
|
||||
|
||||
@@ -62,7 +62,11 @@ function pathToId(path: string): string {
|
||||
}
|
||||
|
||||
export function isDirty(tab: PreviewTab): boolean {
|
||||
return !!(tab.fileContent && tab.originalContent !== undefined && tab.fileContent !== tab.originalContent)
|
||||
// 统一 CRLF → LF 再比较:CodeMirror 6 会把文档行尾归一为 \n 并回灌,
|
||||
// 裸比较会让 CRLF 文件未编辑即被误判为已变更(与 useFileEdit.contentChanged 同口径)
|
||||
const norm = (s: string) => s.replace(/\r\n/g, '\n').replace(/\r/g, '\n')
|
||||
return !!(tab.fileContent && tab.originalContent !== undefined &&
|
||||
norm(tab.fileContent) !== norm(tab.originalContent))
|
||||
}
|
||||
|
||||
export function useMultiPreview() {
|
||||
@@ -166,10 +170,14 @@ export function useMultiPreview() {
|
||||
return { tab: existing, isNew: false }
|
||||
}
|
||||
|
||||
// 超出上限,移除非活跃的最早 tab
|
||||
// 超出上限,优先淘汰非活跃且无未保存修改的最早 tab;全部 dirty 时退回最早并告警
|
||||
if (tabs.value.length >= MAX_TABS) {
|
||||
const victimIdx = tabs.value.findIndex(t => t.id !== activeTabId.value && t.id !== id)
|
||||
if (victimIdx !== -1) tabs.value.splice(victimIdx, 1)
|
||||
const candidates = tabs.value.filter(t => t.id !== activeTabId.value && t.id !== id)
|
||||
const victim = candidates.find(t => !isDirty(t)) || candidates[0]
|
||||
if (victim) {
|
||||
if (isDirty(victim)) console.warn('[MultiPreview] 所有 tab 均有未保存修改,淘汰最早的 tab:', victim.fileItem.path)
|
||||
tabs.value.splice(tabs.value.indexOf(victim), 1)
|
||||
}
|
||||
}
|
||||
|
||||
const tab = createTab(fileItem, profileId)
|
||||
@@ -245,6 +253,16 @@ export function useMultiPreview() {
|
||||
clearAll,
|
||||
persistSession,
|
||||
restoreSession,
|
||||
applyUnsavedContent
|
||||
applyUnsavedContent,
|
||||
renameTab: (oldPath: string, newPath: string, newName?: string) => {
|
||||
// 重命名场景:迁移 tab 身份(fileItem.path + tab.id 按 pathToId 口径)
|
||||
const tab = tabs.value.find(t => t.fileItem.path === oldPath)
|
||||
if (!tab) return
|
||||
tab.fileItem.path = newPath
|
||||
if (newName) tab.fileItem.name = newName
|
||||
const newId = pathToId(newPath)
|
||||
if (activeTabId.value === tab.id) activeTabId.value = newId
|
||||
tab.id = newId
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
/**
|
||||
* 路径导航 Composable
|
||||
* 提供路径输入、历史记录、前进/后退等功能
|
||||
* 历史记录按服务器设备(profileId)分桶持久化:切换机器时下拉历史相应切换为该机器上次的访问记录
|
||||
*/
|
||||
|
||||
import { ref, watch, computed } from 'vue'
|
||||
@@ -8,15 +9,41 @@ import { STORAGE_KEYS } from '@/utils/constants'
|
||||
import { normalizePathSeparators } from '@/utils/fileUtils'
|
||||
import type { PathHistory } from '@/types/file-system'
|
||||
|
||||
export interface UsePathNavigationOptions {
|
||||
onListDirectory?: (path: string) => Promise<void>
|
||||
/** 获取当前 profileId,用于历史记录绑定 */
|
||||
getCurrentProfileId?: () => string | undefined
|
||||
initialPath?: string
|
||||
// 按 profile 分桶的历史持久化 key(localStorage)
|
||||
const HISTORY_BY_PROFILE_KEY = 'desk:pathHistoryByProfile'
|
||||
// 每台机器保留的历史条数上限(原始栈条数)
|
||||
const HISTORY_PER_PROFILE_MAX = 50
|
||||
// 历史下拉折叠门槛:在目录停留不足该秒数视为“路过”,与下一跳是父子关系时折叠进终点
|
||||
const DWELL_THRESHOLD_MS = 5000
|
||||
|
||||
interface ProfileHistoryBucket {
|
||||
paths: string[]
|
||||
profileIds: (string | undefined)[]
|
||||
timestamps: number[]
|
||||
}
|
||||
|
||||
/** 读取全部分桶历史 */
|
||||
const loadHistoryBuckets = (): Record<string, ProfileHistoryBucket> => {
|
||||
try {
|
||||
const raw = localStorage.getItem(HISTORY_BY_PROFILE_KEY)
|
||||
return raw ? JSON.parse(raw) : {}
|
||||
} catch (error) {
|
||||
console.error('读取分桶历史失败:', error)
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
/** 写回全部分桶历史 */
|
||||
const persistHistoryBuckets = (buckets: Record<string, ProfileHistoryBucket>) => {
|
||||
try {
|
||||
localStorage.setItem(HISTORY_BY_PROFILE_KEY, JSON.stringify(buckets))
|
||||
} catch (error) {
|
||||
console.error('保存分桶历史失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 localStorage 恢复上次的路径
|
||||
* 从 localStorage 恢复上次的路径(本地场景,远程机器的历史在分桶里)
|
||||
*/
|
||||
const restoreLastPath = (): string | null => {
|
||||
try {
|
||||
@@ -32,7 +59,7 @@ const restoreLastPath = (): string | null => {
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存路径到 localStorage
|
||||
* 保存路径到 localStorage(仅本地场景;远程历史以分桶为真值)
|
||||
*/
|
||||
const saveLastPath = (path: string) => {
|
||||
try {
|
||||
@@ -42,19 +69,103 @@ const saveLastPath = (path: string) => {
|
||||
}
|
||||
}
|
||||
|
||||
export interface UsePathNavigationOptions {
|
||||
onListDirectory?: (path: string) => Promise<void>
|
||||
/** 获取当前 profileId,用于历史记录绑定 */
|
||||
getCurrentProfileId?: () => string | undefined
|
||||
initialPath?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 父子路径判定:parent 是 child 的直接前缀目录(A 是 A\B 的父)
|
||||
*/
|
||||
const isAncestorPath = (parent: string, child: string): boolean => {
|
||||
if (child.length <= parent.length) return false
|
||||
if (!child.startsWith(parent)) return false
|
||||
const sep = child[parent.length]
|
||||
return sep === '/' || sep === '\\'
|
||||
}
|
||||
|
||||
/**
|
||||
* 展示层折叠:相邻两条是父子关系且上一条停留不足门槛(「路过」)时,上一条折叠进终点。
|
||||
* 钻取链 A→A\B→A\B\C(每步秒过)折叠为单条 A\B\C;在中间层停留≥门槛则保留该层。
|
||||
* 只作用于历史下拉展示,导航栈(后退/前进)不受影响。
|
||||
*/
|
||||
const collapseDrillDownPaths = (paths: string[], timestamps: number[]): string[] => {
|
||||
const keep: string[] = []
|
||||
for (let i = 0; i < paths.length; i++) {
|
||||
const prev = keep[keep.length - 1]
|
||||
const dwell = timestamps[i - 1] !== undefined && timestamps[i] !== undefined
|
||||
? timestamps[i] - timestamps[i - 1]
|
||||
: Infinity // 旧数据无时间戳:不折叠,保守保留
|
||||
if (prev !== undefined && isAncestorPath(prev, paths[i]) && dwell < DWELL_THRESHOLD_MS) {
|
||||
keep[keep.length - 1] = paths[i]
|
||||
} else {
|
||||
keep.push(paths[i])
|
||||
}
|
||||
}
|
||||
return keep.reverse() // 下拉最新在上
|
||||
}
|
||||
|
||||
export function usePathNavigation(options: UsePathNavigationOptions = {}) {
|
||||
const { onListDirectory, getCurrentProfileId, initialPath = '' } = options
|
||||
|
||||
const savedPath = restoreLastPath()
|
||||
const filePath = ref(savedPath || initialPath)
|
||||
|
||||
// 历史记录(每条路径绑定 profileId)
|
||||
// 历史记录(每条路径绑定 profileId + 进入时刻;会话内在当前机器的桶上导航)
|
||||
const history = ref<PathHistory>({
|
||||
paths: [],
|
||||
profileIds: [],
|
||||
timestamps: [],
|
||||
currentIndex: -1
|
||||
})
|
||||
|
||||
// ===== 按 profile 分桶的历史(持久化 + 内存缓存) =====
|
||||
const _buckets = loadHistoryBuckets()
|
||||
let _activeProfileId = getCurrentProfileId?.() || 'local-default'
|
||||
|
||||
// 启动时载入当前机器的历史桶(filePath 保持单一 lastPath 行为不变)
|
||||
const _initBucket = _buckets[_activeProfileId]
|
||||
if (_initBucket?.paths.length) {
|
||||
history.value = {
|
||||
paths: [..._initBucket.paths],
|
||||
profileIds: [..._initBucket.profileIds],
|
||||
// 旧版持久化数据无 timestamps:补零长数组,折叠层按无时间戳保守处理
|
||||
timestamps: [...(_initBucket.timestamps ?? [])],
|
||||
currentIndex: _initBucket.paths.length - 1
|
||||
}
|
||||
}
|
||||
|
||||
/** 当前会话历史写回对应机器的桶并持久化 */
|
||||
const syncCurrentBucket = () => {
|
||||
_buckets[_activeProfileId] = {
|
||||
paths: [...history.value.paths],
|
||||
profileIds: [...history.value.profileIds],
|
||||
timestamps: [...history.value.timestamps]
|
||||
}
|
||||
persistHistoryBuckets(_buckets)
|
||||
}
|
||||
|
||||
/**
|
||||
* 连接切换时调用:历史下拉/后退前进切换为目标机器上次的访问记录
|
||||
*/
|
||||
const setActiveProfile = (profileId?: string) => {
|
||||
const id = profileId || 'local-default'
|
||||
if (id === _activeProfileId) return
|
||||
syncCurrentBucket()
|
||||
_activeProfileId = id
|
||||
const bucket = _buckets[id]
|
||||
history.value = bucket?.paths.length
|
||||
? {
|
||||
paths: [...bucket.paths],
|
||||
profileIds: [...bucket.profileIds],
|
||||
timestamps: [...(bucket.timestamps ?? [])],
|
||||
currentIndex: bucket.paths.length - 1
|
||||
}
|
||||
: { paths: [], profileIds: [], timestamps: [], currentIndex: -1 }
|
||||
}
|
||||
|
||||
/**
|
||||
* 导航到指定路径
|
||||
*/
|
||||
@@ -81,18 +192,30 @@ export function usePathNavigation(options: UsePathNavigationOptions = {}) {
|
||||
|
||||
/** 添加到历史记录 */
|
||||
const addToHistory = (path: string, profileId?: string) => {
|
||||
const { paths, profileIds, currentIndex } = history.value
|
||||
const { paths, profileIds, timestamps, currentIndex } = history.value
|
||||
|
||||
// 分支跳转:丢弃当前位置之后的失效前进栈(三数组同步裁剪)
|
||||
if (currentIndex < paths.length - 1) {
|
||||
history.value.paths = paths.slice(0, currentIndex + 1)
|
||||
history.value.profileIds = profileIds.slice(0, currentIndex + 1)
|
||||
history.value.timestamps = timestamps.slice(0, currentIndex + 1)
|
||||
}
|
||||
|
||||
const lastPath = history.value.paths[history.value.paths.length - 1]
|
||||
if (lastPath !== path) {
|
||||
history.value.paths.push(path)
|
||||
history.value.profileIds.push(profileId)
|
||||
history.value.timestamps.push(Date.now())
|
||||
history.value.currentIndex = history.value.paths.length - 1
|
||||
// 单机历史上限裁剪(裁最旧的,三数组同步)
|
||||
if (history.value.paths.length > HISTORY_PER_PROFILE_MAX) {
|
||||
const overflow = history.value.paths.length - HISTORY_PER_PROFILE_MAX
|
||||
history.value.paths.splice(0, overflow)
|
||||
history.value.profileIds.splice(0, overflow)
|
||||
history.value.timestamps.splice(0, overflow)
|
||||
history.value.currentIndex = history.value.paths.length - 1
|
||||
}
|
||||
syncCurrentBucket()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -187,7 +310,8 @@ export function usePathNavigation(options: UsePathNavigationOptions = {}) {
|
||||
})
|
||||
|
||||
const getPathHistory = computed(() => {
|
||||
return history.value.paths.slice().reverse()
|
||||
// 下拉展示:钻取链按「父子关系×停留时长」折叠(A→A\B→A\B\C 秒过只显示 A\B\C)
|
||||
return collapseDrillDownPaths(history.value.paths, history.value.timestamps)
|
||||
})
|
||||
|
||||
watch(filePath, (newPath) => {
|
||||
@@ -212,7 +336,8 @@ export function usePathNavigation(options: UsePathNavigationOptions = {}) {
|
||||
canGoForward,
|
||||
getPathHistory,
|
||||
getHistoryProfileId,
|
||||
getProfileIdForPath
|
||||
getProfileIdForPath,
|
||||
setActiveProfile
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -250,13 +250,20 @@ const filteredFileList = computed(() => {
|
||||
})
|
||||
|
||||
// 面板宽度(带 localStorage 持久化)
|
||||
/** 宽度校正:left 钳制到 [MIN, MAX],right 由 left 取余量,防止历史脏值把预览区压成不可见 */
|
||||
const clampPanelWidth = (left: number): { left: number; right: number } => {
|
||||
const safeLeft = Math.min(DEFAULTS.MAX_PANEL_WIDTH, Math.max(DEFAULTS.MIN_PANEL_WIDTH, left))
|
||||
return { left: safeLeft, right: 100 - safeLeft }
|
||||
}
|
||||
|
||||
const restorePanelWidth = (): { left: number; right: number } => {
|
||||
try {
|
||||
const saved = localStorage.getItem(STORAGE_KEYS.FILESYSTEM.PANEL_WIDTH)
|
||||
if (saved) {
|
||||
const parsed = JSON.parse(saved)
|
||||
if (parsed.left && parsed.right) {
|
||||
return parsed
|
||||
const left = Number(parsed?.left)
|
||||
if (Number.isFinite(left)) {
|
||||
return clampPanelWidth(left)
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -368,7 +375,7 @@ const transferStore = useTransferStore()
|
||||
const { favorites, draggingState, toggleFavorite: toggleFav, removeFavorite: removeFav, isFavorite, togglePin, renameFavorite: renameFav, updateFavoritePath, onLongPressStart, onLongPressCancel, onDragStart, onDragOver, onDrop, onDragEnd } = useFavorites()
|
||||
|
||||
// 路径导航
|
||||
const { filePath, history, navigate, back, forward, onPathSelect, onPathEnter, browseDirectory, getParentPath, getProfileIdForPath } =
|
||||
const { filePath, history, navigate, back, forward, onPathSelect, onPathEnter, browseDirectory, getParentPath, getProfileIdForPath, setActiveProfile, getPathHistory } =
|
||||
usePathNavigation({
|
||||
onListDirectory: async (path) => {
|
||||
await loadDirectory(path)
|
||||
@@ -376,6 +383,11 @@ const { filePath, history, navigate, back, forward, onPathSelect, onPathEnter, b
|
||||
getCurrentProfileId: () => connectionManager.activeProfile?.id
|
||||
})
|
||||
|
||||
// 连接切换时同步路径历史桶:历史下拉/前进后退切换为目标机器上次的访问记录
|
||||
connectionManager.onStateChange(() => {
|
||||
setActiveProfile(connectionManager.activeProfile?.id)
|
||||
})
|
||||
|
||||
// 文件预览
|
||||
const { previewUrl, updatePreviewUrl, imageLoading, currentImageDimensions, detectByContent } =
|
||||
useFilePreview()
|
||||
@@ -399,7 +411,8 @@ const hasSelectedFile = computed(() => selectedFileItem.value !== null)
|
||||
// 工具栏配置
|
||||
const toolbarConfig = computed(() => ({
|
||||
filePath: filePath.value || '',
|
||||
pathHistory: history.value.paths.slice(-50),
|
||||
// 折叠后的历史(钻取链 A→A\B→A\B\C 只显示 A\B\C;新→旧序,Toolbar 取前 N 即最新)
|
||||
pathHistory: getPathHistory.value,
|
||||
commonPaths: commonPaths.value,
|
||||
isBrowsingZip: false,
|
||||
displayPath: '',
|
||||
@@ -555,7 +568,9 @@ const handleFileChanged = async (event: any) => {
|
||||
if (normalize(changedPath) !== normalize(selectedFileItem.value.path)) return
|
||||
|
||||
// 有未保存修改时不覆盖用户编辑
|
||||
if (originalContent.value !== undefined && fileContent.value !== originalContent.value) return
|
||||
// 与 contentChanged 同口径行尾归一,避免编辑器回灌 LF 后被误判为「用户已改」而拒绝刷新
|
||||
const norm = (s: string) => s.replace(/\r\n/g, '\n').replace(/\r/g, '\n')
|
||||
if (originalContent.value !== undefined && norm(fileContent.value) !== norm(originalContent.value)) return
|
||||
|
||||
// 非文本文件(图片/视频等):刷新预览 URL 并追加文件变更时间打破浏览器缓存
|
||||
if (isMediaPreviewable(selectedFileItem.value.name)) {
|
||||
@@ -905,6 +920,9 @@ const handleSaveEditing = async (oldPath: string, newName: string) => {
|
||||
updateFilePath(newPath)
|
||||
updatePreviewUrl(newPath)
|
||||
}
|
||||
|
||||
// 同步迁移对应 tab 的身份(path/名/id),否则 tab 复用与持久化按旧路径失效
|
||||
multiPreview.renameTab(oldPath, newPath, trimmedName)
|
||||
} catch (error: any) {
|
||||
// 提取错误信息
|
||||
let errorMsg = error?.message || error?.toString() || '未知错误'
|
||||
@@ -1349,8 +1367,14 @@ const handleDeleteFile = async (file: FileItem) => {
|
||||
|
||||
// 编辑器事件
|
||||
const handleSave = async () => {
|
||||
// 先冲刷编辑器防抖队列,确保 fileContent 已是最新内容
|
||||
fileEditorPanelRef.value?.flushEditors?.()
|
||||
if (selectedFileItem.value) {
|
||||
await saveFile(selectedFileItem.value.path)
|
||||
// 保存成功后静默刷新文件列表(文件大小/时间等元信息同步),失败不打扰
|
||||
if (filePath.value) {
|
||||
loadDirectory(filePath.value).catch(() => {})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1494,6 +1518,8 @@ const syncPreviewToActiveProfile = async () => {
|
||||
|
||||
/** 缓存当前 tab 的编辑状态 */
|
||||
const cacheCurrentTabState = () => {
|
||||
// 先冲刷编辑器防抖队列,防止缓存到未同步的旧内容
|
||||
fileEditorPanelRef.value?.flushEditors?.()
|
||||
multiPreview.cacheCurrentTab({
|
||||
previewUrl: previewUrl.value,
|
||||
fileContent: fileContent.value,
|
||||
@@ -1572,7 +1598,8 @@ const loadFileContent = async (path: string) => {
|
||||
}
|
||||
|
||||
// 大文件预检:基于目录列表中的 size 字段,避免读取大文件导致卡死
|
||||
if (fileSize > FILE_SIZE_THRESHOLDS.BIG_FILE) {
|
||||
// CSV/TSV 豁免:表格预览自带分批渲染,大文件走 previewUrl 流式解析不会卡(文案喂给解析器反而渲染乱表格)
|
||||
if (fileSize > FILE_SIZE_THRESHOLDS.LARGE_FILE && !isCsvFile(fileName)) {
|
||||
const sizeMB = (fileSize / 1024 / 1024).toFixed(2)
|
||||
clearContent()
|
||||
fileContent.value = `================================================================
|
||||
@@ -1584,7 +1611,7 @@ const loadFileContent = async (path: string) => {
|
||||
文件大小: ${sizeMB} MB
|
||||
|
||||
================================================================
|
||||
当前文件超过 ${(FILE_SIZE_THRESHOLDS.BIG_FILE / 1024)}KB,不适合在编辑器中打开。
|
||||
当前文件超过 ${(FILE_SIZE_THRESHOLDS.LARGE_FILE / 1024)}KB,不适合在编辑器中打开。
|
||||
|
||||
💡 提示:
|
||||
• 右键菜单 → "使用系统程序打开" 在默认应用中打开
|
||||
@@ -1882,6 +1909,7 @@ const handleKeyDown = async (event: KeyboardEvent) => {
|
||||
// F5 刷新文件列表 + 重载当前预览文件
|
||||
if (event.key === 'F5') {
|
||||
event.preventDefault()
|
||||
const reloadPreview = async () => {
|
||||
if (filePath.value) {
|
||||
await loadDirectory(filePath.value)
|
||||
// 如果有正在预览的文件,同时重新加载其内容(类似重新点击一次)
|
||||
@@ -1889,6 +1917,21 @@ const handleKeyDown = async (event: KeyboardEvent) => {
|
||||
await loadFileContent(selectedFileItem.value.path)
|
||||
}
|
||||
}
|
||||
}
|
||||
// 行尾归一后的 dirty 检查:有未保存变更先确认,防止编辑内容被静默覆盖
|
||||
const norm = (s: string | undefined) => (s ?? '').replace(/\r\n/g, '\n').replace(/\r/g, '\n')
|
||||
if (selectedFileItem.value && !selectedFileItem.value.isDir &&
|
||||
norm(fileContent.value) !== norm(originalContent.value)) {
|
||||
Modal.confirm({
|
||||
title: '当前文件有未保存的修改',
|
||||
content: '刷新将重新加载文件内容,未保存的修改将丢失。是否继续?',
|
||||
okText: '继续刷新',
|
||||
cancelText: '取消',
|
||||
onOk: reloadPreview
|
||||
})
|
||||
} else {
|
||||
await reloadPreview()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -266,6 +266,8 @@ export interface PathHistory {
|
||||
paths: string[]
|
||||
/** 每条路径对应的 profileId */
|
||||
profileIds: (string | undefined)[]
|
||||
/** 每条路径的进入时刻(Date.now,展示层用于父子链折叠的停留时长判定) */
|
||||
timestamps: number[]
|
||||
/** 当前索引 */
|
||||
currentIndex: number
|
||||
}
|
||||
|
||||
@@ -80,12 +80,19 @@ export async function loadLanguageExtension(language) {
|
||||
case 'bash':
|
||||
case 'sh':
|
||||
case 'dockerfile': {
|
||||
const { StreamLanguage, shell } = await import('@codemirror/legacy-modes/mode/shell')
|
||||
// StreamLanguage 来自 @codemirror/language,legacy-modes 只提供模式定义
|
||||
const [{ StreamLanguage }, { shell }] = await Promise.all([
|
||||
import('@codemirror/language'),
|
||||
import('@codemirror/legacy-modes/mode/shell')
|
||||
])
|
||||
extension = StreamLanguage.define(shell)
|
||||
break
|
||||
}
|
||||
case 'powershell': {
|
||||
const { StreamLanguage, powerShell } = await import('@codemirror/legacy-modes/mode/powershell')
|
||||
const [{ StreamLanguage }, { powerShell }] = await Promise.all([
|
||||
import('@codemirror/language'),
|
||||
import('@codemirror/legacy-modes/mode/powershell')
|
||||
])
|
||||
extension = StreamLanguage.define(powerShell)
|
||||
break
|
||||
}
|
||||
|
||||
@@ -260,7 +260,7 @@ export async function previewCsv(file, container) {
|
||||
<style>
|
||||
.csv-preview{display:flex;flex-direction:column;height:100%;overflow:hidden}
|
||||
.csv-info{padding:4px 12px;background:var(--color-fill-1);font-size:12px;color:var(--color-text-3);border-bottom:1px solid var(--color-border-2)}
|
||||
.csv-content{flex:1;overflow:auto;padding:12px}
|
||||
.csv-content{flex:1;overflow:auto;padding:0 12px 12px}
|
||||
.csv-content table{width:100%;border-collapse:collapse;font-size:13px}
|
||||
.csv-content td,.csv-content th{border:1px solid var(--color-border-2);padding:6px 10px;text-align:left;white-space:nowrap;color:var(--color-text-1)}
|
||||
.csv-content th{background:var(--color-fill-2);font-weight:600;position:sticky;top:0;z-index:2}
|
||||
|
||||
@@ -28,8 +28,8 @@ export const PREVIEWABLE_TYPES = [
|
||||
* @type {string[]}
|
||||
*/
|
||||
export const KNOWN_BINARY_TYPES = [
|
||||
// 可执行文件
|
||||
'exe', 'dll', 'so', 'bin', 'dat', 'db', 'sqlite',
|
||||
// 可执行文件(dat 不盲判:常见文本数据交换格式,走内容检测兜底)
|
||||
'exe', 'dll', 'so', 'bin', 'db', 'sqlite',
|
||||
// 压缩文件
|
||||
'zip', 'rar', '7z', 'tar', 'gz', 'bz2', 'xz', 'iso', 'img', 'dmg',
|
||||
// 编译/中间产物
|
||||
|
||||
@@ -284,7 +284,9 @@ export function isMarkedReady(): boolean {
|
||||
/** 同步渲染(仅当已初始化时可用) */
|
||||
export function parseMarkdown(content: string): string {
|
||||
if (!_marked) return ''
|
||||
return _marked.parse(content) as string
|
||||
const html = _marked.parse(content) as string
|
||||
// 兜底:过滤空一级标题块(首行 `#`/`# ` 无文字产生的 <h1></h1> 空白条)
|
||||
return html.replace(/<h1(?:\s[^>]*)?>(?:\s| )*<\/h1>/g, '')
|
||||
}
|
||||
|
||||
/** 触发懒加载(可在空闲时调用) */
|
||||
|
||||
@@ -277,7 +277,7 @@ func handleLocalFileRequest(w http.ResponseWriter, r *http.Request) {
|
||||
transformedContent := transformCssContent(string(content), basePath)
|
||||
|
||||
w.Header().Set("Content-Type", "text/css")
|
||||
w.Header().Set("Cache-Control", "public, max-age=3600")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.Write([]byte(transformedContent))
|
||||
log.Printf("[LocalFileHandler] CSS文件转换完成: %s (原始=%d, 转换后=%d)", filePath, len(content), len(transformedContent))
|
||||
return
|
||||
@@ -299,7 +299,7 @@ func handleLocalFileRequest(w http.ResponseWriter, r *http.Request) {
|
||||
transformedContent := transformJsDynamicImports(string(content), basePath)
|
||||
|
||||
w.Header().Set("Content-Type", "application/javascript")
|
||||
w.Header().Set("Cache-Control", "public, max-age=3600")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.Write([]byte(transformedContent))
|
||||
log.Printf("[LocalFileHandler] JS文件转换完成: %s (原始=%d, 转换后=%d)", filePath, len(content), len(transformedContent))
|
||||
return
|
||||
@@ -317,12 +317,9 @@ func handleLocalFileRequest(w http.ResponseWriter, r *http.Request) {
|
||||
// 设置响应头
|
||||
contentType := getContentType(ext)
|
||||
w.Header().Set("Content-Type", contentType)
|
||||
// 媒体文件禁用缓存(避免 Chromium ERR_CACHE_OPERATION_NOT_SUPPORTED)
|
||||
if isMediaExt(ext) {
|
||||
// 预览文件一律禁用缓存:文件内容变化后同 URL 必须返回新内容,
|
||||
// 此前的 max-age=3600 会让本地/远程文件预览命中浏览器 1 小时缓存(陈旧内容,刷新也无效)
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
} else {
|
||||
w.Header().Set("Cache-Control", "public, max-age=3600")
|
||||
}
|
||||
// 支持 Range 请求
|
||||
w.Header().Set("Accept-Ranges", "bytes")
|
||||
|
||||
|
||||
@@ -15,6 +15,9 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"golang.org/x/text/encoding/simplifiedchinese"
|
||||
|
||||
"u-desk/internal/common"
|
||||
)
|
||||
@@ -50,6 +53,10 @@ type FileSystemService struct {
|
||||
// 状态管理
|
||||
mu sync.RWMutex
|
||||
initialized bool
|
||||
|
||||
// 编码回写缓存:ReadFile 判定为 GBK 的文件记录路径 → "gbk",WriteFile 按原编码回写
|
||||
encodingMu sync.Mutex
|
||||
encodingMap map[string]string
|
||||
}
|
||||
|
||||
// NewFileSystemService 创建新的文件系统服务
|
||||
@@ -63,6 +70,7 @@ func NewFileSystemService(config *Config) (*FileSystemService, error) {
|
||||
config: config,
|
||||
pathValidator: NewPathValidator(config),
|
||||
fileTypeManager: NewFileTypeManager(config),
|
||||
encodingMap: make(map[string]string),
|
||||
}
|
||||
|
||||
// 初始化基础设施组件
|
||||
@@ -145,9 +153,29 @@ func (s *FileSystemService) ReadFile(path string) (string, error) {
|
||||
}
|
||||
|
||||
s.logRead(path, int64(len(data)), nil)
|
||||
|
||||
// 记录 GBK 文件路径,WriteFile 按原编码回写(与 common.BytesToString 同判定口径)
|
||||
if isGBKBytes(data) {
|
||||
s.encodingMu.Lock()
|
||||
s.encodingMap[path] = "gbk"
|
||||
s.encodingMu.Unlock()
|
||||
}
|
||||
|
||||
return common.BytesToString(data), nil
|
||||
}
|
||||
|
||||
// isGBKBytes 判断原始字节是否为 GBK 编码(非 UTF-8 且 GBK 解码后为合法 UTF-8)
|
||||
func isGBKBytes(data []byte) bool {
|
||||
if utf8.Valid(data) {
|
||||
return false
|
||||
}
|
||||
decoded, err := simplifiedchinese.GBK.NewDecoder().Bytes(data)
|
||||
if err != nil || !utf8.Valid(decoded) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// writeFileWithLog 内部写入实现(路径验证+大小检查+写入+日志)
|
||||
func (s *FileSystemService) writeFileWithLog(path string, data []byte) error {
|
||||
if err := s.validatePath(path); err != nil {
|
||||
@@ -168,9 +196,32 @@ func (s *FileSystemService) writeFileWithLog(path string, data []byte) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// WriteFile 写入文件
|
||||
// WriteFile 写入文件(GBK 文件按原编码回写)
|
||||
func (s *FileSystemService) WriteFile(path, content string) error {
|
||||
return s.writeFileWithLog(path, []byte(content))
|
||||
s.encodingMu.Lock()
|
||||
encoding := s.encodingMap[path]
|
||||
s.encodingMu.Unlock()
|
||||
|
||||
data := []byte(content)
|
||||
if encoding == "gbk" {
|
||||
encoded, err := simplifiedchinese.GBK.NewEncoder().Bytes(data)
|
||||
if err != nil {
|
||||
return fmt.Errorf("GBK 编码失败: %v", err)
|
||||
}
|
||||
data = encoded
|
||||
}
|
||||
|
||||
if err := s.writeFileWithLog(path, data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 写入成功后清除编码缓存项(内容已按原编码落盘,下次读取会重新判定)
|
||||
if encoding == "gbk" {
|
||||
s.encodingMu.Lock()
|
||||
delete(s.encodingMap, path)
|
||||
s.encodingMu.Unlock()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SaveBase64File 将 base64 编码内容解码后写入二进制文件
|
||||
|
||||
@@ -15,7 +15,7 @@ import (
|
||||
// ==================== 常量定义 ====================
|
||||
|
||||
// AppVersion 应用版本号(发布时直接修改此处)
|
||||
const AppVersion = "0.5.1"
|
||||
const AppVersion = "0.5.3"
|
||||
|
||||
// 版本号缓存
|
||||
var (
|
||||
|
||||
@@ -269,17 +269,21 @@ func (s *Service) RenamePath(connID string, oldPath, newPath string) (*filesyste
|
||||
|
||||
// DownloadToTemp 下载远程文件到本地临时目录(带 SQLite 缓存)
|
||||
func (s *Service) DownloadToTemp(connID string, remotePath string) (string, error) {
|
||||
// 先获取文件元信息用于缓存键,确保远程文件变更时能淘汰旧缓存
|
||||
// 先获取文件元信息用于缓存键,确保远程文件变更时能淘汰旧缓存。
|
||||
// 元信息获取失败时禁用缓存直接下载:退化为 (path,0,"") 无指纹键会让该路径
|
||||
// 永远命中第一次的旧缓存(陈旧内容且刷新无效)
|
||||
var fileSize int64
|
||||
var modTime string
|
||||
if info, err := s.GetFileInfo(connID, remotePath); err == nil {
|
||||
info, err := s.GetFileInfo(connID, remotePath)
|
||||
if err != nil {
|
||||
return s.downloadToTempDirect(connID, remotePath)
|
||||
}
|
||||
if sz, ok := info["size"].(int64); ok {
|
||||
fileSize = sz
|
||||
}
|
||||
if mt, ok := info["mod_time"].(string); ok {
|
||||
modTime = mt
|
||||
}
|
||||
}
|
||||
return storage.DownloadToTempCached("sftp", connID, remotePath, fileSize, modTime, func() (string, error) {
|
||||
return s.downloadToTempDirect(connID, remotePath)
|
||||
})
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "u-desk",
|
||||
"outputfilename": "u-desk",
|
||||
"version": "0.5.1",
|
||||
"version": "0.5.3",
|
||||
"frontend:install": "npm install",
|
||||
"frontend:build": "npm run build",
|
||||
"author": {
|
||||
|
||||
Reference in new issue
Block a user