fix(frontend): 修复纸页刷新宽度并完善侧栏和图表主题

This commit is contained in:
2026-09-05 19:23:21 +08:00
parent a63f6c57e0
commit 8692910508
10 changed files with 165 additions and 35 deletions
@@ -1,6 +1,6 @@
theme_id: paper-moments
name: 纸间时光 · Paper Moments
version: 1.4.0
version: 1.4.1
author: NotesAgent
description: 奶油纸张、手帐虚线与粉蓝胶带,把每天的灵感好好收藏。
min_app_version: 0.2.0
@@ -141,7 +141,7 @@ license: MIT
[data-theme="paper-moments"] .markdown-toolbar { background: #fff9e9; border-bottom: 1px dashed #b5a693; }
[data-theme="paper-moments"] .milkdown-host { padding: 30px 24px 40px; }
[data-theme="paper-moments"] .milkdown-host .milkdown { background: transparent; }
[data-theme="paper-moments"] .milkdown-host .ProseMirror {
[data-theme="paper-moments"] .visual-editor .milkdown-host .ProseMirror {
width: 90%;
max-width: none;
position: relative;
@@ -172,7 +172,7 @@ license: MIT
[data-theme="paper-moments"] .editor-pane.source { margin: 20px; width: calc(100% - 40px); border: 1px solid #b5a693; border-radius: 8px; background: #fffef8; box-shadow: var(--shadow-md); }
@media (max-width: 720px) {
[data-theme="paper-moments"] .milkdown-host { padding: 20px 12px 28px; }
[data-theme="paper-moments"] .milkdown-host .ProseMirror { width: 100%; padding: 30px 18px 40px 38px; }
[data-theme="paper-moments"] .visual-editor .milkdown-host .ProseMirror { width: 100%; padding: 30px 18px 40px 38px; }
}
/* Warm neutral surfaces preserve the contrast of the selected Shiki palette. */
@@ -11,11 +11,11 @@ let renderVersion = 0
const diagramTheme = computed<'light' | 'dark'>(() => (themeStore.isDark ? 'dark' : 'light'))
// 主题切换需要重渲染:Mermaid SVG 的配色在渲染时烘焙,无法靠 CSS 变量事后调整。
watch([() => props.source, diagramTheme], async ([source, theme]) => {
watch([() => props.source, diagramTheme, () => themeStore.currentThemeId], async ([source, theme]) => {
const version = ++renderVersion
const result = await renderMarkdown(source, { theme })
if (version === renderVersion) html.value = result
}, { immediate: true })
}, { immediate: true, flush: 'post' })
</script>
<template>
@@ -13,7 +13,7 @@ const emit = defineEmits<{
(e: 'rendered', info: { width: number; height: number }): void
}>()
const { mermaidTheme } = useMermaidTheme()
const { mermaidTheme, themeId } = useMermaidTheme()
const svgHtml = ref('')
const isLoading = ref(true)
const hasError = ref(false)
@@ -52,7 +52,7 @@ async function doRender() {
onMounted(doRender)
watch(() => [props.source, mermaidTheme.value], () => { scale.value = 1; doRender() })
watch(() => [props.source, mermaidTheme.value, themeId.value], () => { scale.value = 1; doRender() }, { flush: 'post' })
function zoomIn() { scale.value = Math.min(scale.value * 1.2, 5) }
function zoomOut() { scale.value = Math.max(scale.value / 1.2, 0.2) }
@@ -0,0 +1,23 @@
// @vitest-environment happy-dom
import { expect, it } from 'vitest'
import { mount } from '@vue/test-utils'
import { createRouter, createMemoryHistory } from 'vue-router'
import SecondarySidebar from './SecondarySidebar.vue'
it('resizes by keyboard, clamps bounds and restores the saved width', async () => {
localStorage.removeItem('workspace-sidebar-width')
const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/', component: { template: '<div />' } }] })
await router.push('/')
const options = { props: { component: 'file-tree' }, global: { plugins: [router], stubs: { FileTreePanel: true } } }
let wrapper = mount(SecondarySidebar, options)
await wrapper.get('[role="separator"]').trigger('keydown', { key: 'ArrowRight' })
expect(localStorage.getItem('workspace-sidebar-width')).toBe('288')
wrapper.unmount()
wrapper = mount(SecondarySidebar, options)
await wrapper.vm.$nextTick()
expect(wrapper.get('aside').attributes('style')).toContain('288px')
await wrapper.get('[role="separator"]').trigger('keydown', { key: 'Home' })
expect(wrapper.get('aside').attributes('style')).toContain('200px')
wrapper.unmount()
localStorage.removeItem('workspace-sidebar-width')
})
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { computed } from 'vue'
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import FileTreePanel from '@/features/workspace/FileTreePanel.vue'
import ConversationListPanel from '@/features/chat/ConversationListPanel.vue'
import RunListPanel from '@/features/agent/RunListPanel.vue'
@@ -15,6 +15,40 @@ const props = defineProps<{
const route = useRoute()
const routeName = computed(() => route.name as string)
const sidebar = ref<HTMLElement | null>(null)
const width = ref(272)
const maxWidth = ref(520)
let dragging = false
function saveWidth() { try { localStorage.setItem('workspace-sidebar-width', String(width.value)) } catch { /* Keep resizing available when storage is unavailable. */ } }
function clampWidth(value: number) { return Math.max(200, Math.min(maxWidth.value, value)) }
function updateBounds() {
maxWidth.value = Math.max(200, Math.min(520, window.innerWidth - (sidebar.value?.getBoundingClientRect().left ?? 0) - 320))
width.value = clampWidth(width.value)
}
function beginResize(event: PointerEvent) {
if (event.button !== 0) return
event.preventDefault()
updateBounds()
dragging = true
;(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId)
}
function resize(event: PointerEvent) {
if (dragging) width.value = clampWidth(event.clientX - (sidebar.value?.getBoundingClientRect().left ?? 0))
}
function endResize() { if (dragging) { dragging = false; saveWidth() } }
function resizeWithKeyboard(event: KeyboardEvent) {
if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return
event.preventDefault()
updateBounds()
width.value = event.key === 'Home' ? 200 : event.key === 'End' ? maxWidth.value : clampWidth(width.value + (event.key === 'ArrowLeft' ? -16 : 16))
saveWidth()
}
onMounted(() => {
try { const saved = Number(localStorage.getItem('workspace-sidebar-width')); if (saved >= 200 && Number.isFinite(saved)) width.value = saved } catch { /* Use default width. */ }
updateBounds()
window.addEventListener('resize', updateBounds)
})
onBeforeUnmount(() => { endResize(); window.removeEventListener('resize', updateBounds) })
const sidebarTitle = computed(() => {
const titles: Record<string, string> = {
@@ -32,7 +66,7 @@ const showSkillToggle = computed(() => routeName.value === 'skills' || routeName
</script>
<template>
<aside class="secondary-sidebar">
<aside ref="sidebar" class="secondary-sidebar" :style="component === 'file-tree' ? { width: `${width}px` } : undefined">
<div v-if="component !== 'file-tree'" class="sidebar-header">
<h3 class="sidebar-title">{{ sidebarTitle }}</h3>
<div v-if="showSkillToggle" class="sidebar-tabs">
@@ -48,11 +82,13 @@ const showSkillToggle = computed(() => routeName.value === 'skills' || routeName
<TaskFiltersPanel v-else-if="component === 'task-filters'" />
<ExtensionListPanel v-else-if="component === 'extension-list'" />
</div>
<div v-if="component === 'file-tree'" class="sidebar-resizer" role="separator" aria-orientation="vertical" :aria-label="t('调整文件侧栏宽度', 'Resize file sidebar')" :aria-valuenow="width" :aria-valuemin="200" :aria-valuemax="maxWidth" tabindex="0" @pointerdown="beginResize" @pointermove="resize" @pointerup="endResize" @pointercancel="endResize" @lostpointercapture="endResize" @keydown="resizeWithKeyboard" @dblclick="width = clampWidth(272); saveWidth()" />
</aside>
</template>
<style scoped>
.secondary-sidebar {
position: relative;
width: var(--sidebar-secondary-width);
background: var(--color-surface-secondary);
border-right: 1px solid var(--color-border-default);
@@ -111,6 +147,8 @@ const showSkillToggle = computed(() => routeName.value === 'skills' || routeName
overflow-x: hidden;
scrollbar-gutter: stable;
}
.sidebar-resizer { position: absolute; top: 0; bottom: 0; right: -3px; width: 6px; z-index: 20; cursor: col-resize; touch-action: none; }
.sidebar-resizer:hover, .sidebar-resizer:focus-visible { background: var(--color-accent-secondary); outline: none; }
.file-sidebar-content { min-height: 0; overflow: hidden; scrollbar-gutter: auto; }
</style>
@@ -62,6 +62,22 @@ const fontSizeInput = ref(16)
let crepe: Crepe | null = null
let disposeLanguagePicker: (() => void) | undefined
let disposeCodeLabels: (() => void) | undefined
const diagramPreviews = new Map<string, { source: string; apply: (value: HTMLElement) => void }>()
function renderDiagram(source: string, apply: (value: HTMLElement) => void) {
for (const [id, entry] of diagramPreviews) {
if (entry.apply === apply) diagramPreviews.delete(id)
}
const element = createMermaidPreview(source, themeStore.isDark, apply)
diagramPreviews.set(element.id, { source, apply })
return element
}
watch(() => themeStore.currentThemeId, () => {
const current = [...diagramPreviews.entries()]
diagramPreviews.clear()
for (const [id, entry] of current) {
if (editorRoot.value?.querySelector(`[id="${id}"]`)) entry.apply(renderDiagram(entry.source, entry.apply))
}
}, { flush: 'post' })
function applyProofingPreferences() {
const editable = editorRoot.value?.querySelector<HTMLElement>('.ProseMirror')
@@ -206,7 +222,7 @@ onMounted(async () => {
languages: shikiLanguages(themeStore.resolvedCodeBlockTheme),
renderLanguage: renderCodeLanguage,
renderPreview: (language, content, applyPreview) => language.trim().toLowerCase() === 'mermaid'
? createMermaidPreview(content, themeStore.isDark, applyPreview)
? renderDiagram(content, applyPreview)
: config.renderPreview(language, content, applyPreview),
extensions: [basicSetup, keymap.of([indentWithTab]), shikiEditorTheme(themeStore.resolvedCodeBlockTheme)],
})))
@@ -242,7 +258,7 @@ watch(() => editorStore.headingRequest, request => {
})
})
onBeforeUnmount(() => { disposeCodeLabels?.(); disposeLanguagePicker?.(); void crepe?.destroy() })
onBeforeUnmount(() => { diagramPreviews.clear(); disposeCodeLabels?.(); disposeLanguagePicker?.(); void crepe?.destroy() })
defineExpose({ getEditor: () => crepe?.editor })
</script>
@@ -48,6 +48,16 @@ afterEach(() => {
})
describe('FileTreePanel file switching', () => {
it('expands every nested folder from the toolbar', async () => {
const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/workspace', component: { template: '<div />' } }] })
await router.push('/workspace')
const store = useWorkspaceStore()
store.fileTree = [{ id: 'a', name: 'A', path: '/a', type: 'folder', is_open: false, children: [{ id: 'b', name: 'B', path: '/a/b', type: 'folder', is_open: false }] }]
wrapper = mount(FileTreePanel, { global: { plugins: [router] } })
await wrapper.get('[aria-label="全部展开文件夹"]').trigger('click')
expect(store.fileTree[0]!.is_open).toBe(true)
expect(store.fileTree[0]!.children![0]!.is_open).toBe(true)
})
it('switches full-height panels using tabs and preserves the file search', async () => {
const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/workspace', component: { template: '<div />' } }] })
await router.push('/workspace')
@@ -68,6 +68,12 @@ const filteredTree = computed(() => {
})
return filter(workspaceStore.fileTree)
})
function expandAllFiles() {
const expand = (nodes: FileNode[]) => nodes.forEach(node => {
if (node.type === 'folder') { node.is_open = true; expand(node.children ?? []) }
})
expand(workspaceStore.fileTree)
}
let lastScrollTop = 0
function revealSearch(event: WheelEvent) {
if (activeTab.value !== 'files') return
@@ -216,6 +222,7 @@ function containingFolder(path: string): string {
<button type="button" :title="t('新建笔记', 'New note')" :aria-label="t('新建笔记', 'New note')" @click.stop="beginCreate('file', selectedFolderPath)"><AppIcon :icon="DocumentAdd" /></button>
<button type="button" :title="t('新建文件夹', 'New folder')" :aria-label="t('新建文件夹', 'New folder')" @click.stop="beginCreate('folder', selectedFolderPath)"><AppIcon :icon="FolderAdd" /></button>
<button type="button" :aria-label="t('搜索文件', 'Search files')" :aria-expanded="searchVisible" @click="searchVisible = !searchVisible">{{ t('搜索', 'Search') }}</button>
<button type="button" :aria-label="t('全部展开文件夹', 'Expand all folders')" @click="expandAllFiles">{{ t('全部展开', 'Expand all') }}</button>
</div>
<div v-if="searchVisible || searchQuery || searchFocused" class="file-search">
<input v-model="searchQuery" type="search" :placeholder="t('搜索文件或文件夹…', 'Search files or folders…')" :aria-label="t('搜索文件或文件夹', 'Search files or folders')" @focus="searchFocused = true" @blur="searchFocused = false" />
+38 -24
View File
@@ -1,31 +1,45 @@
import mermaid from 'mermaid'
import { ref, watch } from 'vue'
import { computed } from 'vue'
import { useThemeStore } from '@/stores/theme'
let initialized = false
let initTheme: 'light' | 'dark' = 'light'
export function mermaidThemeVariables(dark: boolean) {
const style = typeof document === 'undefined' ? null : getComputedStyle(document.documentElement)
const color = (name: string, fallback: string) => style?.getPropertyValue(`--color-${name}`).trim() || fallback
const text = color('text-primary', dark ? '#e6edf3' : '#1f2328')
const border = color('border-default', dark ? '#484f58' : '#d0d7de')
const surface = color('surface-primary', dark ? '#161b22' : '#ffffff')
const primary = color('accent-soft', dark ? '#30363d' : '#eef0ff')
const line = color('text-secondary', dark ? '#b1bac4' : '#656d76')
return {
darkMode: dark, background: surface, primaryColor: primary, primaryTextColor: text, primaryBorderColor: border,
secondaryColor: color('info-soft', primary), secondaryTextColor: text, secondaryBorderColor: border,
tertiaryColor: color('success-soft', primary), tertiaryTextColor: text, tertiaryBorderColor: border,
textColor: text, lineColor: line, mainBkg: primary, nodeBorder: border,
clusterBkg: surface, clusterBorder: border, edgeLabelBackground: surface,
actorBkg: primary, actorBorder: border, actorTextColor: text, actorLineColor: line,
signalColor: line, signalTextColor: text, labelBoxBkgColor: surface, labelBoxBorderColor: border, labelTextColor: text,
noteBkgColor: color('warning-soft', primary), noteTextColor: text, noteBorderColor: border,
activationBkgColor: primary, activationBorderColor: border,
}
}
function ensureInitialized(theme: 'light' | 'dark') {
if (!initialized) {
mermaid.initialize({
startOnLoad: false,
theme: theme === 'dark' ? 'dark' : 'default',
theme: 'base',
themeVariables: mermaidThemeVariables(theme === 'dark'),
securityLevel: 'strict',
fontFamily: 'var(--font-ui-sans)',
flowchart: { useMaxWidth: true, htmlLabels: true },
sequence: { useMaxWidth: true },
gantt: { useMaxWidth: true },
})
initialized = true
initTheme = theme
return
}
if (initTheme !== theme) {
mermaid.initialize({
theme: theme === 'dark' ? 'dark' : 'default',
})
initTheme = theme
}
}
let queue: Promise<unknown> = Promise.resolve()
function serialized<T>(work: () => Promise<T>): Promise<T> {
const result = queue.then(work)
queue = result.catch(() => {})
return result
}
export interface MermaidRenderResult {
@@ -43,7 +57,11 @@ export interface MermaidParseError {
let renderCounter = 0
export async function renderMermaid(
export function renderMermaid(source: string, options: { theme?: 'light' | 'dark'; mode?: 'interactive' | 'static' } = {}): Promise<MermaidRenderResult> {
return serialized(() => renderMermaidNow(source, options))
}
async function renderMermaidNow(
source: string,
options: { theme?: 'light' | 'dark'; mode?: 'interactive' | 'static' } = {}
): Promise<MermaidRenderResult> {
@@ -106,18 +124,14 @@ function escapeXml(str: string): string {
export function useMermaidTheme() {
const themeStore = useThemeStore()
const mermaidTheme = ref<'light' | 'dark'>(themeStore.isDark ? 'dark' : 'light')
watch(() => themeStore.isDark, (isDark) => {
mermaidTheme.value = isDark ? 'dark' : 'light'
ensureInitialized(mermaidTheme.value)
})
return { mermaidTheme }
const mermaidTheme = computed<'light' | 'dark'>(() => themeStore.isDark ? 'dark' : 'light')
const themeId = computed(() => themeStore.currentThemeId)
return { mermaidTheme, themeId }
}
export async function validateMermaid(source: string): Promise<{ valid: boolean; error?: MermaidParseError }> {
try {
ensureInitialized('light')
await mermaid.parse(source)
await serialized(async () => { ensureInitialized('light'); await mermaid.parse(source) })
return { valid: true }
} catch (error) {
const message = error instanceof Error ? error.message : '未知错误'
@@ -0,0 +1,22 @@
// @vitest-environment happy-dom
import { afterEach, expect, it, vi } from 'vitest'
import mermaid from 'mermaid'
import { mermaidThemeVariables, renderMermaid } from './mermaidService'
vi.mock('mermaid', () => ({ default: { initialize: vi.fn(), render: vi.fn().mockResolvedValue({ svg: '<svg viewBox="0 0 10 10"></svg>' }) } }))
afterEach(() => { document.documentElement.removeAttribute('style'); vi.clearAllMocks() })
it('uses the current theme tokens for nodes, actors, text and lines', () => {
document.documentElement.style.setProperty('--color-accent-soft', '#f3e1d8')
document.documentElement.style.setProperty('--color-text-primary', '#493f35')
const theme = mermaidThemeVariables(false)
expect(theme.primaryColor).toBe('#f3e1d8')
expect(theme.actorBkg).toBe('#f3e1d8')
expect(theme.primaryTextColor).toBe('#493f35')
expect(theme.actorTextColor).toBe('#493f35')
})
it('keeps explicit diagram styling and initializes base palette on each render', async () => {
const source = 'graph TD; A-->B; style A fill:#f9f'
await renderMermaid(source)
expect(mermaid.initialize).toHaveBeenCalledWith(expect.objectContaining({ theme: 'base', securityLevel: 'strict', themeVariables: expect.any(Object) }))
expect(mermaid.render).toHaveBeenCalledWith(expect.any(String), source)
})