Files
Thing/src/modules/editor/components/SearchResultsPanel.vue
T
2026-10-10 14:29:48 +08:00

407 lines
16 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<script setup lang="ts">
/**
* 目录 / 笔记库检索的底部结果面板(IDEA「Find in Path」工具窗的位置)。
*
* # 为什么从搜索卡片里搬出来
*
* 结果列表塞在悬浮卡片里有两个硬伤:卡片宽度有限(预览被截断得厉害),且卡片一关
* 结果就没了 —— 而「先搜完、再逐条点开看」才是这个功能的真实用法。搬到编辑区底部的
* 独立面板后,结果可以一直摆着,边看代码边点下一条。
*
* # 结果点开后会怎样
*
* 面板只管「导航」,不负责判重:命中来自磁盘扫描,文件此刻可能已被外部改动。行号越界
* 由 `EditorHost.jumpToLine` 夹取(跳到近似位置好过整块报错)。
*
* # 历史是「条件」不是「结果」
*
* 点历史条目 = 按原条件**重跑**(见 `editorSearchStore` 的注释)。因此在历史页把鼠标
* 悬在条目上会提示「点击重新检索」,避免用户误以为是快照。
*/
import { computed, ref, watch } from 'vue'
import { ChevronDown, ChevronRight, History, Loader2, RotateCw, SearchX, Trash2, X } from '@lucide/vue'
import { Button } from '@/components/ui/button'
import { ScrollArea } from '@/components/ui/scroll-area'
import { StateBlock } from '@/components/common'
import { useEditorSearchStore, specToQuery, type SearchRecord } from '@/stores/editorSearchStore'
import type { PathSearchFileHits, PathSearchMatch } from '@/types/editor'
const emit = defineEmits<{
/** 打开文件并跳到某行某列 */
'open-file': [payload: { path: string; line: number; column: number }]
}>()
const store = useEditorSearchStore()
const tab = ref<'results' | 'history'>('results')
// ===== 上边缘拖拽调高 =====
//
// 用 Pointer Events + `setPointerCapture`:指针一旦被捕获,即使拖出面板/窗口边界也继续
// 收到 move 事件,不会出现「拖快了就丢手柄」的经典问题(用 mousemove 就得在 window 上
// 挂一堆全局监听与清理)。
const resizing = ref(false)
let dragStartY = 0
let dragStartHeight = 0
function onResizeStart(event: PointerEvent): void {
dragStartY = event.clientY
dragStartHeight = store.panelHeight
resizing.value = true
;(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId)
}
function onResizeMove(event: PointerEvent): void {
if (!resizing.value) return
// 往上拖 = 面板变高(clientY 越小越高)
store.setPanelHeight(dragStartHeight + (dragStartY - event.clientY))
}
function onResizeEnd(event: PointerEvent): void {
if (!resizing.value) return
resizing.value = false
;(event.currentTarget as HTMLElement).releasePointerCapture(event.pointerId)
store.persistPanelHeight()
}
/** 预览切片:切成「命中前 / 命中 / 命中后」三段(永远走插值,不用 v-html)。 */
function pieces(match: PathSearchMatch): Array<{ text: string; hit: boolean }> {
const chars = Array.from(match.preview)
const start = Math.max(0, Math.min(match.matchStart, chars.length))
const end = Math.max(start, Math.min(match.matchEnd, chars.length))
return [
{ text: chars.slice(0, start).join(''), hit: false },
{ text: chars.slice(start, end).join(''), hit: true },
{ text: chars.slice(end).join(''), hit: false }
]
}
const isCollapsed = (path: string): boolean => store.collapsed.includes(path)
// ===== 前端分段显示 =====
//
// 后端把全树命中总数统计完整(`total` 可能上万),但预览条数有上限(`returned`)。
// 就算只渲染 `returned` 条,几千行 DOM 也会让面板滚动卡顿 —— 这里每段只挂
// `PAGE_SIZE` 条,底部「显示更多」续一段;换一次检索结果就回到第一段。
/** 每段渲染的命中条数 */
const PAGE_SIZE = 200
const visibleCount = ref(PAGE_SIZE)
watch(
() => store.results,
() => {
visibleCount.value = PAGE_SIZE
}
)
/** 窗口内的文件切片:窗口耗尽即停,文件内剩余命中不渲染(数据都在,点开就有)。 */
const visibleFiles = computed<Array<{ file: PathSearchFileHits; shown: PathSearchMatch[] }>>(() => {
const r = store.results
if (!r) return []
let budget = visibleCount.value
const out: Array<{ file: PathSearchFileHits; shown: PathSearchMatch[] }> = []
for (const file of r.files) {
if (budget <= 0) break
const shown = file.matches.slice(0, budget)
out.push({ file, shown })
budget -= shown.length
}
return out
})
/** 还有多少条已回传但未渲染的命中(「显示更多」按钮的文案来源)。 */
const remainingCount = computed(() => {
const r = store.results
if (!r) return 0
return Math.max(0, r.returned - visibleCount.value)
})
function showMore(): void {
visibleCount.value += PAGE_SIZE
}
/** 命中数 / 文件数的汇总文案(`total` 是全树统计,不是回传数)。 */
const summary = computed(() => {
const r = store.results
if (!r) return ''
return `${r.total} 处命中 · ${r.totalFiles} 个文件`
})
/** 条件的可读摘要(历史列表与结果页眉都用它,避免两处格式漂移)。 */
function describe(record: {
dir: string
pattern: string
fileTypes: string | null
skipDirs: string
caseSensitive: boolean
wholeWord: boolean
regex: boolean
}): string {
const flags: string[] = []
if (record.caseSensitive) flags.push('Aa')
if (record.wholeWord) flags.push('W')
if (record.regex) flags.push('.*')
const parts = [`「${record.pattern}」`]
if (flags.length) parts.push(flags.join(' '))
if (record.fileTypes) parts.push(record.fileTypes)
return parts.join(' · ')
}
function relativeTime(at: number): string {
const diff = Date.now() - at
const minute = 60_000
if (diff < minute) return '刚刚'
if (diff < 60 * minute) return `${Math.floor(diff / minute)} 分钟前`
if (diff < 24 * 60 * minute) return `${Math.floor(diff / (60 * minute))} 小时前`
return new Date(at).toLocaleDateString()
}
function rerun(record: SearchRecord): void {
tab.value = 'results'
void store.rerunRecord(record.id)
}
/** 重跑当前结果(文件可能已被改动)。 */
function refresh(): void {
const record = store.records.find(r => r.id === store.activeId)
if (!record) return
void store.rerunRecord(record.id)
}
/** 直接以这条记录的条件拼查询串(用于 tooltip 展示搜索目标目录)。 */
function queryOf(record: SearchRecord): string {
return specToQuery(record).dir
}
</script>
<template>
<section
v-if="store.panelOpen"
class="flex shrink-0 flex-col bg-background"
:style="{ height: `${store.panelHeight}px` }"
>
<!--
上边缘:既是「编辑区 / 结果区」的分界线(主题色,够明显),也是拖拽调高的手柄。
手柄本身做厚一点(h-1.5)并带 hover/拖动高亮,否则 2px 的线很难点中。
-->
<div
class="group flex h-1.5 shrink-0 cursor-row-resize touch-none items-center justify-center border-t-2 border-primary/60 bg-primary/5 select-none transition-colors duration-150 hover:bg-primary/20"
:class="resizing && 'bg-primary/25'"
title="拖动调整结果面板高度"
@pointerdown="onResizeStart"
@pointermove="onResizeMove"
@pointerup="onResizeEnd"
@pointercancel="onResizeEnd"
>
<span class="h-0.5 w-10 rounded-full bg-primary/50 group-hover:bg-primary/80" />
</div>
<!-- 页眉:Tab + 当前条件 + 操作 -->
<div class="flex h-8 shrink-0 items-center gap-1 border-b border-border px-2">
<button
type="button"
class="rounded-sm px-2 py-0.5 text-xs transition-colors duration-150"
:class="
tab === 'results'
? 'bg-active font-medium text-foreground'
: 'text-fg-secondary hover:bg-hover hover:text-foreground'
"
@click="tab = 'results'"
>
结果
</button>
<button
type="button"
class="flex items-center gap-1 rounded-sm px-2 py-0.5 text-xs transition-colors duration-150"
:class="
tab === 'history'
? 'bg-active font-medium text-foreground'
: 'text-fg-secondary hover:bg-hover hover:text-foreground'
"
@click="tab = 'history'"
>
<History class="size-3" />历史
<span v-if="store.records.length" class="tabular-nums text-fg-disabled">
{{ store.records.length }}
</span>
</button>
<!-- 结果页眉:条件 + 汇总 + 重跑 -->
<template v-if="tab === 'results'">
<span v-if="store.searching" class="ml-2 flex items-center gap-1.5 text-[11px] text-muted-foreground">
<Loader2 class="size-3 animate-spin" />检索中…
</span>
<template v-else-if="store.error">
<span class="ml-2 min-w-0 truncate text-[11px] text-destructive">{{ store.error }}</span>
</template>
<template v-else-if="store.results">
<span class="ml-2 text-[11px] tabular-nums text-muted-foreground">{{ summary }}</span>
<span
v-if="store.results.truncated"
class="text-[11px] tabular-nums text-warning"
title="为避免拖慢界面,预览只回传了一部分;总数仍是全树统计"
>
(已回传前 {{ store.results.returned }} 条)
</span>
<span
class="ml-2 min-w-0 flex-1 truncate font-mono text-[10px] text-fg-disabled"
:title="store.records.find(r => r.id === store.activeId)?.dir ?? ''"
>
{{ store.records.find(r => r.id === store.activeId)?.dir ?? '' }}
</span>
</template>
</template>
<div class="ml-auto flex shrink-0 items-center gap-0.5">
<Button
v-if="tab === 'results' && store.activeId"
variant="ghost"
size="icon-sm"
title="按原条件重新检索(磁盘内容可能已变)"
@click="refresh"
>
<RotateCw class="size-3.5" />
</Button>
<Button
v-if="tab === 'history' && store.records.length"
variant="ghost"
size="icon-sm"
title="清空全部检索历史"
@click="store.clearRecords()"
>
<Trash2 class="size-3.5" />
</Button>
<Button variant="ghost" size="icon-sm" title="关闭结果面板" @click="store.panelOpen = false">
<X class="size-3.5" />
</Button>
</div>
</div>
<!-- ===== 结果页 ===== -->
<ScrollArea v-if="tab === 'results'" class="min-h-0 flex-1">
<div v-if="store.results?.files.length" class="px-1.5 py-1">
<div v-for="entry in visibleFiles" :key="entry.file.path">
<button
type="button"
class="flex w-full items-center gap-1.5 rounded-sm px-1.5 py-1 text-left transition-colors duration-150 hover:bg-row-hover"
:title="entry.file.path"
@click="store.toggleFile(entry.file.path)"
>
<component
:is="isCollapsed(entry.file.path) ? ChevronRight : ChevronDown"
class="size-3 shrink-0 opacity-60"
/>
<span class="truncate text-xs font-medium text-foreground">{{ entry.file.name }}</span>
<span
class="shrink-0 text-[10px] tabular-nums"
:class="entry.shown.length < entry.file.totalInFile ? 'text-warning' : 'text-muted-foreground'"
:title="entry.shown.length < entry.file.totalInFile ? `该文件共 ${entry.file.totalInFile} 处命中` : undefined"
>
{{ entry.shown.length < entry.file.totalInFile ? `${entry.shown.length} / ${entry.file.totalInFile}` : entry.file.totalInFile }}
</span>
<span class="ml-auto min-w-0 truncate pl-2 text-[10px] text-fg-disabled">
{{ entry.file.path }}
</span>
</button>
<template v-if="!isCollapsed(entry.file.path)">
<button
v-for="match in entry.shown"
:key="`${entry.file.path}:${match.line}:${match.column}`"
type="button"
class="flex w-full items-center gap-2 rounded-sm py-0.5 pr-1.5 pl-6 text-left transition-colors duration-150 hover:bg-row-hover"
@click="emit('open-file', { path: entry.file.path, line: match.line, column: match.column })"
>
<span class="w-10 shrink-0 text-right text-[10px] tabular-nums text-muted-foreground">
{{ match.line }}
</span>
<span
class="min-w-0 flex-1 overflow-hidden text-ellipsis whitespace-pre font-mono text-[11px] text-fg-secondary"
>
<template v-for="(piece, index) in pieces(match)" :key="index">
<mark
v-if="piece.hit"
class="rounded-xs bg-primary-soft px-0.5 text-primary-soft-text"
>{{ piece.text }}</mark>
<template v-else>{{ piece.text }}</template>
</template>
</span>
</button>
</template>
</div>
<!-- 分段续读:已回传的命中分页渲染,点一次多挂 PAGE_SIZE 条 -->
<button
v-if="remainingCount > 0"
type="button"
class="mx-1.5 my-1 flex w-[calc(100%-12px)] items-center justify-center gap-1 rounded-sm border border-dashed border-border py-1.5 text-xs text-muted-foreground transition-colors duration-150 hover:border-primary/40 hover:bg-row-hover hover:text-foreground"
@click="showMore"
>
显示更多(剩余 {{ remainingCount }} 处)
</button>
</div>
<StateBlock
v-else-if="!store.searching && !store.error && store.results"
variant="empty"
title="没有匹配"
description="换个关键词或调整过滤条件再试"
:min-height="120"
/>
<StateBlock
v-else-if="!store.searching && !store.error"
variant="empty"
title="还没有检索结果"
description="在搜索栏选「目录」或「笔记库」范围,输入关键词后按回车"
:min-height="120"
/>
</ScrollArea>
<!-- ===== 历史页 ===== -->
<ScrollArea v-else class="min-h-0 flex-1">
<div v-if="store.records.length" class="flex flex-col px-1.5 py-1">
<div
v-for="record in store.records"
:key="record.id"
class="group flex items-center gap-2 rounded-sm px-1.5 py-1 transition-colors duration-150 hover:bg-row-hover"
>
<button
type="button"
class="flex min-w-0 flex-1 items-center gap-2 text-left"
:title="`点击按原条件重新检索\n目录:${queryOf(record)}`"
@click="rerun(record)"
>
<SearchX class="size-3.5 shrink-0 opacity-60" />
<span class="min-w-0 flex-1 truncate text-xs text-fg-secondary group-hover:text-foreground">
{{ describe(record) }}
</span>
<span class="shrink-0 text-[10px] tabular-nums text-fg-disabled">
{{ record.hits }} 处 / {{ record.files }} 文件
</span>
<span class="w-16 shrink-0 text-right text-[10px] text-fg-disabled">
{{ relativeTime(record.at) }}
</span>
</button>
<button
type="button"
class="shrink-0 rounded-sm p-0.5 opacity-0 transition-opacity group-hover:opacity-100 hover:bg-active"
title="删除这条历史"
@click="store.removeRecord(record.id)"
>
<X class="size-3" />
</button>
</div>
</div>
<StateBlock
v-else
variant="empty"
title="还没有检索历史"
description="每次在目录 / 笔记库范围检索都会记下条件(只存条件,点击时重新检索)"
:min-height="120"
/>
</ScrollArea>
</section>
</template>