完善功能

This commit is contained in:
2026-07-10 16:07:53 +08:00
parent 0a3534a7e0
commit 78913c46b6
10 changed files with 971 additions and 31 deletions

View File

@@ -1,5 +1,6 @@
<script setup lang="ts">
import {ref, computed, onBeforeUnmount, watch} from "vue";
import {ref, computed, onBeforeUnmount, watch, nextTick} from "vue";
import { invoke } from "@tauri-apps/api/core";
import SettingsModal from "./SettingsModal.vue";
import TreeEntry from "./TreeEntry.vue";
@@ -19,6 +20,7 @@ interface WorkspaceEntry {
path: string;
}
const props = withDefaults(
defineProps<{
folderPath: string;
@@ -52,24 +54,225 @@ const emit = defineEmits<{
renameEntry: [path: string, newName: string];
updateDefaultDocumentMode: [mode: DocumentMode];
updateAppTheme: [theme: AppTheme];
"search-result-click": [filePath: string, lineNumber: number];
}>();
// Wrap the workspace root as a top-level tree node
const rootEntry = computed<DirEntry | null>(() => {
if (!props.folderPath) return null;
const name = props.folderPath.split(/[/\\]/).pop() || props.folderPath;
return {
name,
path: props.folderPath,
is_dir: true,
children: props.entries,
};
});
// ---- sidebar view mode ----
type ViewMode = "folder" | "search" | "setting";
const activeView = ref<ViewMode>("folder");
// ---- search types ----
interface SearchMatch {
line: number;
column: number;
line_text: string;
context_before: string[];
context_after: string[];
}
interface FileSearchResult {
relative_path: string;
absolute_path: string;
matches: SearchMatch[];
match_count: number;
}
const SEARCH_HISTORY_KEY = "yurou:search-history";
const MAX_SEARCH_HISTORY = 10;
const SEARCH_DEBOUNCE_MS = 300;
const searchKeyword = ref("");
const searchCaseSensitive = ref(false);
const searchUseRegex = ref(false);
const searchWholeWord = ref(false);
const searchExtensions = ref<string[]>(["md"]);
const searchResults = ref<FileSearchResult[]>([]);
const searchLoading = ref(false);
const searchError = ref("");
const searchHistory = ref<string[]>(loadSearchHistory());
const searchInputRef = ref<HTMLInputElement | null>(null);
const searchFocusedFile = ref<string | null>(null);
let searchDebounceTimer: ReturnType<typeof setTimeout> | null = null;
const searchableTypes = [
{ label: "Markdown (.md)", value: "md" },
{ label: "纯文本 (.txt)", value: "txt" },
{ label: "JSON (.json)", value: "json" },
{ label: "YAML (.yaml/.yml)", value: "yaml" },
{ label: "JavaScript (.js)", value: "js" },
{ label: "TypeScript (.ts)", value: "ts" },
{ label: "CSS (.css)", value: "css" },
{ label: "HTML (.html)", value: "html" },
{ label: "XML (.xml)", value: "xml" },
];
const showExtensionDropdown = ref(false);
const extensionDropdownRef = ref<HTMLElement | null>(null);
const totalMatchCount = computed(() => {
return searchResults.value.reduce((sum, f) => sum + f.match_count, 0);
});
function loadSearchHistory(): string[] {
try {
const stored = localStorage.getItem(SEARCH_HISTORY_KEY);
return stored ? JSON.parse(stored) : [];
} catch {
return [];
}
}
function saveSearchHistory() {
try {
const keyword = searchKeyword.value.trim();
if (!keyword) return;
const history = searchHistory.value.filter((h) => h !== keyword);
history.unshift(keyword);
const trimmed = history.slice(0, MAX_SEARCH_HISTORY);
searchHistory.value = trimmed;
localStorage.setItem(SEARCH_HISTORY_KEY, JSON.stringify(trimmed));
} catch { /* noop */ }
}
async function performSearch() {
const keyword = searchKeyword.value.trim();
if (!keyword || !props.folderPath) {
searchResults.value = [];
searchError.value = "";
return;
}
searchLoading.value = true;
searchError.value = "";
try {
const results = await invoke<FileSearchResult[]>("search_files", {
workspace: props.folderPath,
keyword,
caseSensitive: searchCaseSensitive.value,
useRegex: searchUseRegex.value,
wholeWord: searchWholeWord.value,
extensions: searchExtensions.value,
});
searchResults.value = results;
if (results.length === 0) {
searchError.value = "未找到匹配结果";
}
} catch (e) {
searchError.value = `搜索出错: ${e}`;
searchResults.value = [];
} finally {
searchLoading.value = false;
}
}
function triggerSearch() {
if (searchDebounceTimer) clearTimeout(searchDebounceTimer);
searchDebounceTimer = setTimeout(() => {
void performSearch();
}, SEARCH_DEBOUNCE_MS);
}
function clearSearch() {
searchKeyword.value = "";
searchResults.value = [];
searchError.value = "";
searchFocusedFile.value = null;
}
function toggleExtension(ext: string) {
const idx = searchExtensions.value.indexOf(ext);
if (idx >= 0) {
if (searchExtensions.value.length > 1) {
searchExtensions.value.splice(idx, 1);
}
} else {
searchExtensions.value = [...searchExtensions.value, ext];
}
triggerSearch();
}
function handleSearchKeydown(e: KeyboardEvent) {
if (e.key === "Escape") {
clearSearch();
} else if (e.key === "Enter" && searchResults.value.length > 0) {
const first = searchResults.value[0];
if (first.matches.length > 0) {
saveSearchHistory();
emit("search-result-click", first.absolute_path, first.matches[0].line);
}
}
}
function onResultClick(file: FileSearchResult, match: SearchMatch) {
saveSearchHistory();
emit("search-result-click", file.absolute_path, match.line);
}
function toggleFileCollapse(relativePath: string) {
searchFocusedFile.value = searchFocusedFile.value === relativePath ? null : relativePath;
}
function focusSearchInput() {
void nextTick(() => {
searchInputRef.value?.focus();
searchInputRef.value?.select();
});
}
function activateSearch() {
if (activeView.value !== "search") {
activeView.value = "search";
if (isCollapsed.value) expand();
}
focusSearchInput();
}
function highlightMatchText(text: string): string {
const keyword = searchKeyword.value.trim();
if (!keyword || searchUseRegex.value) {
return escapeHtml(text);
}
const escaped = keyword.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
try {
const flags = searchCaseSensitive.value ? "g" : "gi";
const re = new RegExp(`(${escaped})`, flags);
return escapeHtml(text).replace(re, "<mark class='search-highlight'>$1</mark>");
} catch {
return escapeHtml(text);
}
}
function escapeHtml(text: string): string {
return text
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;");
}
function closeExtensionDropdown(e: MouseEvent) {
if (extensionDropdownRef.value && !extensionDropdownRef.value.contains(e.target as Node)) {
showExtensionDropdown.value = false;
}
}
watch(showExtensionDropdown, (open) => {
if (open) {
setTimeout(() => document.addEventListener("click", closeExtensionDropdown), 0);
} else {
document.removeEventListener("click", closeExtensionDropdown);
}
});
watch([searchKeyword, searchCaseSensitive, searchUseRegex, searchWholeWord], () => {
triggerSearch();
});
// collapsed computed is defined above (line ~71), reuse it
defineExpose({
activateSearch,
});
// ---- sidebar resize ----
const MIN_SIDEBAR_WIDTH = 180;
const MAX_SIDEBAR_WIDTH = 500;
@@ -320,6 +523,8 @@ function openSettings(page: SettingsPage) {
settingsPage.value = page;
showSettings.value = true;
}
</script>
<template>
@@ -364,11 +569,14 @@ function openSettings(page: SettingsPage) {
<!-- ===== FOLDER VIEW ===== -->
<div v-if="activeView === 'folder'" class="flex flex-col flex-1 overflow-hidden">
<!-- File tree -->
<div class="flex-1 overflow-y-auto px-2 py-2 space-y-0.5">
<!-- Workspace root as top-level tree node -->
<div
class="flex-1 overflow-y-auto px-2 py-2 flex flex-col gap-0.5"
>
<TreeEntry
v-if="rootEntry"
:entry="rootEntry"
v-for="entry in entries"
:key="entry.path"
:entry="entry"
:depth="0"
:currentFilePath="currentFilePath"
@toggle-folder="(path: string) => emit('toggleFolder', path)"
@@ -398,20 +606,179 @@ function openSettings(page: SettingsPage) {
<!-- ===== SEARCH VIEW ===== -->
<div v-if="activeView === 'search'" class="flex flex-col flex-1 overflow-hidden">
<!-- 搜索输入区 -->
<div class="px-3 py-3">
<div class="relative">
<i class="sidebar-search-icon ri-search-line absolute left-2.5 top-1/2 -translate-y-1/2 text-sm"></i>
<input
class="sidebar-search-input w-full pl-8 pr-3 py-1.5 text-xs rounded-md outline-none"
ref="searchInputRef"
v-model="searchKeyword"
class="sidebar-search-input w-full pl-8 pr-8 py-1.5 text-xs rounded-md outline-none"
placeholder="搜索文件内容..."
disabled
@keydown="handleSearchKeydown"
/>
<button
v-if="searchKeyword"
class="absolute right-1.5 top-1/2 -translate-y-1/2 p-0.5 rounded text-xs cursor-pointer hover:bg-black/10 dark:hover:bg-white/10 text-[var(--app-subtle)]"
title="清空"
@click="clearSearch"
>
<i class="ri-close-line"></i>
</button>
</div>
<!-- 搜索选项 -->
<div class="flex items-center gap-2 mt-2 flex-wrap">
<button
class="search-option-btn"
:class="{ 'search-option-active': searchCaseSensitive }"
title="区分大小写"
@click="searchCaseSensitive = !searchCaseSensitive"
>
Aa
</button>
<button
class="search-option-btn"
:class="{ 'search-option-active': searchUseRegex }"
title="正则表达式"
@click="searchUseRegex = !searchUseRegex"
>
.*
</button>
<button
class="search-option-btn"
:class="{ 'search-option-active': searchWholeWord }"
title="全词匹配"
@click="searchWholeWord = !searchWholeWord"
>
<i class="ri-font-size"></i>
</button>
<!-- 文件类型下拉 -->
<div ref="extensionDropdownRef" class="relative">
<button
class="search-option-btn flex items-center gap-1"
@click="showExtensionDropdown = !showExtensionDropdown"
title="文件类型"
>
<span class="text-[10px]">.{{ searchExtensions.join(', .') }}</span>
<i class="ri-arrow-down-s-line text-[9px]"></i>
</button>
<div
v-if="showExtensionDropdown"
class="search-ext-dropdown absolute top-full left-0 mt-1 bg-[var(--app-surface)] border border-[var(--app-border)] rounded-md shadow-lg z-30 py-1 min-w-[150px] max-h-52 overflow-y-auto"
@click.stop
>
<label
v-for="type in searchableTypes"
:key="type.value"
class="flex items-center gap-2 px-3 py-1.5 text-xs cursor-pointer hover:bg-[var(--app-hover)]"
>
<input
type="checkbox"
:checked="searchExtensions.includes(type.value)"
class="w-3 h-3 accent-[var(--app-accent)]"
@change="toggleExtension(type.value)"
/>
{{ type.label }}
</label>
</div>
</div>
</div>
</div>
<div class="flex-1 flex items-center justify-center px-3 pb-8">
<p class="sidebar-empty text-xs text-center leading-relaxed">
搜索功能即将上线
</p>
<!-- 搜索结果区域 -->
<div class="flex-1 overflow-y-auto px-2 pb-2">
<!-- Loading -->
<div v-if="searchLoading" class="flex items-center justify-center py-8">
<p class="text-xs text-[var(--app-subtle)]">搜索中...</p>
</div>
<!-- Error / No results -->
<div v-else-if="searchError && searchResults.length === 0" class="flex items-center justify-center py-8">
<p class="text-xs text-[var(--app-subtle)]">{{ searchError }}</p>
</div>
<!-- Empty prompt / history -->
<div v-else-if="!searchKeyword.trim()" class="flex flex-col py-4 px-1">
<template v-if="searchHistory.length > 0">
<p class="text-[10px] text-[var(--app-subtle)] px-2 mb-2 uppercase tracking-wider">最近搜索</p>
<button
v-for="(item, idx) in searchHistory.slice(0, 5)"
:key="idx"
class="search-history-item flex items-center gap-1.5 text-xs px-2 py-1.5 rounded cursor-pointer hover:bg-[var(--app-hover)] w-full text-left truncate"
@click="searchKeyword = item"
>
<i class="ri-history-line text-[var(--app-subtle)] shrink-0"></i>
<span class="truncate text-[var(--app-text-soft)]">{{ item }}</span>
</button>
</template>
<div v-else class="flex flex-col items-center justify-center py-8">
<p v-if="props.folderPath" class="text-xs text-[var(--app-subtle)]">
输入关键词搜索工作目录中的文件
</p>
<p v-else class="text-xs text-[var(--app-subtle)]">
请先打开一个工作目录
</p>
</div>
</div>
<!-- Results list (grouped by file) -->
<div v-else class="flex flex-col gap-1">
<div class="text-[10px] text-[var(--app-subtle)] px-1 py-1">
{{ searchResults.length }} 个文件,共 {{ totalMatchCount }} 处匹配
</div>
<div
v-for="file in searchResults"
:key="file.absolute_path"
class="search-file-group"
>
<!-- File header -->
<button
class="search-file-header w-full flex items-center gap-1.5 px-2 py-1.5 text-xs rounded cursor-pointer hover:bg-[var(--app-hover)] transition-colors"
@click="toggleFileCollapse(file.relative_path)"
>
<i
class="text-[10px] transition-transform"
:class="searchFocusedFile === file.relative_path ? 'ri-arrow-down-s-line' : 'ri-arrow-right-s-line'"
></i>
<i class="ri-file-text-line text-[var(--app-subtle)] shrink-0"></i>
<span class="truncate flex-1 text-left text-[var(--app-text-soft)]">{{ file.relative_path }}</span>
<span class="text-[var(--app-subtle)] shrink-0 text-[10px]">{{ file.match_count }}</span>
</button>
<!-- File matches (collapsible) -->
<div
v-show="searchFocusedFile !== file.relative_path"
class="search-matches ml-5"
>
<button
v-for="(match, mIdx) in file.matches"
:key="mIdx"
class="search-match-item w-full text-left px-2 py-1.5 text-xs rounded cursor-pointer hover:bg-[var(--app-hover)] transition-colors block"
:class="{ 'bg-[var(--app-active-bg)]': props.currentFilePath === file.absolute_path }"
@click="onResultClick(file, match)"
>
<div class="flex items-baseline gap-2 mb-0.5">
<span class="text-[10px] text-[var(--app-accent)] shrink-0 font-mono">L{{ match.line }}</span>
<span class="truncate text-[var(--app-text-soft)]" v-html="highlightMatchText(match.line_text)"></span>
</div>
<!-- Context lines -->
<div v-if="match.context_before.length || match.context_after.length" class="text-[10px] text-[var(--app-subtle)] mt-0.5 space-y-0">
<div v-for="(ctxLine, ci) in match.context_before" :key="'b' + ci" class="truncate opacity-60">
{{ ctxLine }}
</div>
<div v-for="(ctxLine, ci) in match.context_after" :key="'a' + ci" class="truncate opacity-60">
{{ ctxLine }}
</div>
</div>
</button>
<div v-if="file.match_count > file.matches.length" class="text-[10px] text-[var(--app-subtle)] px-2 py-0.5">
... 还有 {{ file.match_count - file.matches.length }} 处匹配未显示
</div>
</div>
</div>
</div>
</div>
</div>
@@ -898,6 +1265,7 @@ function openSettings(page: SettingsPage) {
font-size: 15px;
}
.workspace-manager-overlay {
position: fixed;
inset: 0;
@@ -1283,4 +1651,61 @@ function openSettings(page: SettingsPage) {
width: 100%;
}
}
/* ── Search view ──────────────────────────────────────────────── */
.search-option-btn {
display: inline-flex;
align-items: center;
justify-content: center;
height: 24px;
min-width: 24px;
padding: 0 6px;
font-size: 11px;
font-weight: 500;
border-radius: 4px;
border: 1px solid transparent;
background: transparent;
color: var(--app-subtle);
cursor: pointer;
transition: all 0.15s;
}
.search-option-btn:hover {
background: var(--app-hover);
color: var(--app-text-soft);
}
.search-option-active {
background: color-mix(in srgb, var(--app-accent) 15%, transparent);
color: var(--app-accent);
border-color: color-mix(in srgb, var(--app-accent) 30%, transparent);
}
.search-file-header {
color: var(--app-text-soft);
}
.search-match-item {
border-left: 2px solid transparent;
}
.search-match-item:hover {
border-left-color: var(--app-accent-muted);
}
.search-highlight {
background: color-mix(in srgb, var(--app-accent) 30%, transparent);
color: var(--app-accent);
border-radius: 2px;
padding: 0 1px;
}
.search-history-item {
color: var(--app-text-soft);
}
.search-ext-dropdown {
backdrop-filter: blur(12px);
}
</style>