Refactor code structure for improved readability and maintainability

This commit is contained in:
MengMengCode
2026-06-09 15:33:17 +08:00
parent cf00d0d03d
commit e971d99070
17 changed files with 2068 additions and 178 deletions
+182
View File
@@ -0,0 +1,182 @@
import { useEffect } from 'react'
import { useLocation } from 'react-router-dom'
import { useLanguage } from '../contexts/LanguageContext'
import { shouldTranslateText, translateText } from '../utils/i18n'
const translatedTitleAttr = 'data-i18n-title-original'
const translatedPlaceholderAttr = 'data-i18n-placeholder-original'
const translatedAriaLabelAttr = 'data-i18n-aria-label-original'
const attributeNames = ['title', 'placeholder', 'aria-label'] as const
const translatedTextNodes = new Set<Text>()
const textOriginals = new WeakMap<Text, string>()
const wholeTextSelector = 'button,a,span,label,option,th,td,p,h1,h2,h3,h4,small'
export default function AutoTranslate() {
const { language } = useLanguage()
const location = useLocation()
useEffect(() => {
if (language === 'zh') {
restoreTranslatedNodes(document.body)
return
}
translateNode(document.body)
const pending = new Set<Node>()
let scheduled = false
const flush = () => {
scheduled = false
const nodes = Array.from(pending)
pending.clear()
for (const node of nodes) {
if (node.isConnected) translateNode(node)
}
}
const schedule = (node: Node) => {
pending.add(node)
if (scheduled) return
scheduled = true
window.requestAnimationFrame(flush)
}
const observer = new MutationObserver((mutations) => {
for (const mutation of mutations) {
if (mutation.type === 'childList') {
mutation.addedNodes.forEach(schedule)
} else {
schedule(mutation.target)
}
}
})
observer.observe(document.body, {
childList: true,
subtree: true,
characterData: true,
attributes: true,
attributeFilter: [...attributeNames],
})
return () => observer.disconnect()
}, [language, location.pathname, location.search])
return null
}
function translateNode(root: Node) {
if (root.nodeType === Node.TEXT_NODE) {
translateTextNode(root as Text)
return
}
if (!(root instanceof Element)) return
if (shouldSkipElement(root)) return
translateWholeTextElement(root)
root.querySelectorAll<HTMLElement>(wholeTextSelector).forEach(translateWholeTextElement)
translateElementAttributes(root)
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
acceptNode(node) {
if (!node.textContent || !shouldTranslateText(node.textContent)) return NodeFilter.FILTER_REJECT
const parent = node.parentElement
if (!parent || shouldSkipElement(parent)) {
return NodeFilter.FILTER_REJECT
}
return NodeFilter.FILTER_ACCEPT
},
})
const nodes: Text[] = []
while (walker.nextNode()) nodes.push(walker.currentNode as Text)
for (const node of nodes) translateTextNode(node)
root.querySelectorAll<HTMLElement>('[title], [placeholder], [aria-label]').forEach(translateElementAttributes)
}
function translateTextNode(node: Text) {
const original = node.textContent || ''
if (!shouldTranslateText(original)) return
const parent = node.parentElement
if (!parent || shouldSkipElement(parent)) return
const translated = translateText(original)
if (translated === original) return
textOriginals.set(node, original)
translatedTextNodes.add(node)
node.textContent = translated
}
function translateWholeTextElement(el: Element) {
if (!(el instanceof HTMLElement) || shouldSkipElement(el) || !isSimpleTextElement(el)) return
const original = el.textContent || ''
if (!shouldTranslateText(original)) return
const translated = translateText(original)
if (translated === original) return
const textNodes = directTextNodes(el)
if (textNodes.length === 0) return
textNodes.forEach((node, index) => {
textOriginals.set(node, node.textContent || '')
translatedTextNodes.add(node)
node.textContent = index === 0 ? translated : ''
})
}
function directTextNodes(el: HTMLElement) {
return Array.from(el.childNodes).filter((node): node is Text => node.nodeType === Node.TEXT_NODE)
}
function translateElementAttributes(el: Element) {
if (!(el instanceof HTMLElement)) return
translateAttribute(el, 'title', translatedTitleAttr)
translateAttribute(el, 'placeholder', translatedPlaceholderAttr)
translateAttribute(el, 'aria-label', translatedAriaLabelAttr)
}
function restoreTranslatedNodes(root: ParentNode) {
for (const node of Array.from(translatedTextNodes)) {
if (!node.isConnected) {
translatedTextNodes.delete(node)
continue
}
if (root instanceof Document || root.contains(node)) {
node.textContent = textOriginals.get(node) || node.textContent
translatedTextNodes.delete(node)
}
}
root.querySelectorAll<HTMLElement>(`[${translatedTitleAttr}]`).forEach((el) => {
el.setAttribute('title', el.getAttribute(translatedTitleAttr) || '')
el.removeAttribute(translatedTitleAttr)
})
root.querySelectorAll<HTMLInputElement | HTMLTextAreaElement>(`[${translatedPlaceholderAttr}]`).forEach((el) => {
el.setAttribute('placeholder', el.getAttribute(translatedPlaceholderAttr) || '')
el.removeAttribute(translatedPlaceholderAttr)
})
root.querySelectorAll<HTMLElement>(`[${translatedAriaLabelAttr}]`).forEach((el) => {
el.setAttribute('aria-label', el.getAttribute(translatedAriaLabelAttr) || '')
el.removeAttribute(translatedAriaLabelAttr)
})
}
function translateAttribute(el: HTMLElement, attr: 'title' | 'placeholder' | 'aria-label', originalAttr: string) {
const storedOriginal = el.getAttribute(originalAttr)
const original = storedOriginal || el.getAttribute(attr) || ''
if (!shouldTranslateText(original)) return
const translated = translateText(original)
if (translated === original) return
if (!storedOriginal) {
el.setAttribute(originalAttr, original)
}
if (el.getAttribute(attr) !== translated) {
el.setAttribute(attr, translated)
}
}
function shouldSkipElement(el: Element) {
return !!el.closest('script, style, code, pre, textarea, [data-no-translate]')
}
function isSimpleTextElement(el: HTMLElement) {
if (!el.matches(wholeTextSelector)) return false
if (el.querySelector('input, textarea, select, button, table, pre, code, canvas, iframe')) return false
const textNodes = directTextNodes(el)
if (textNodes.length === 0) return false
return Array.from(el.children).every((child) => child.tagName.toLowerCase() === 'svg')
}
@@ -0,0 +1,19 @@
import { useEffect } from 'react'
import { useLanguage } from '../contexts/LanguageContext'
export default function BrowserDialogTranslator() {
const { t } = useLanguage()
useEffect(() => {
const originalAlert = window.alert
const originalConfirm = window.confirm
window.alert = (message?: unknown) => originalAlert(t(String(message ?? '')))
window.confirm = (message?: string) => originalConfirm(t(String(message ?? '')))
return () => {
window.alert = originalAlert
window.confirm = originalConfirm
}
}, [t])
return null
}
+6 -4
View File
@@ -1,5 +1,6 @@
import { useState, useCallback, createContext, useContext, ReactNode } from 'react'
import { AlertTriangle, CheckCircle, X } from 'lucide-react'
import { useLanguage } from '../contexts/LanguageContext'
type DialogType = 'confirm' | 'alert'
@@ -20,6 +21,7 @@ const DialogContext = createContext<DialogContextType | undefined>(undefined)
export function DialogProvider({ children }: { children: ReactNode }) {
const [dialog, setDialog] = useState<DialogState>({ open: false, type: 'alert', title: '', message: '' })
const { t } = useLanguage()
const confirm = useCallback((title: string, message: string) => {
return new Promise<boolean>((resolve) => {
@@ -50,7 +52,7 @@ export function DialogProvider({ children }: { children: ReactNode }) {
}`}>
{dialog.type === 'confirm' ? <AlertTriangle className="w-4 h-4" /> : <CheckCircle className="w-4 h-4" />}
</div>
<h3 className="text-sm font-semibold text-black flex-1">{dialog.title}</h3>
<h3 className="text-sm font-semibold text-black flex-1">{t(dialog.title)}</h3>
{dialog.type === 'alert' && (
<button onClick={() => close(true)} className="p-1 text-gray-400 hover:text-black rounded">
<X className="w-4 h-4" />
@@ -58,7 +60,7 @@ export function DialogProvider({ children }: { children: ReactNode }) {
)}
</div>
<div className="px-5 py-4">
<p className="text-sm text-gray-600">{dialog.message}</p>
<p className="text-sm text-gray-600">{t(dialog.message)}</p>
</div>
<div className="flex justify-end gap-2 px-5 py-3 bg-gray-50 border-t border-gray-100">
{dialog.type === 'confirm' && (
@@ -66,7 +68,7 @@ export function DialogProvider({ children }: { children: ReactNode }) {
onClick={() => close(false)}
className="px-4 py-2 text-sm text-gray-700 hover:bg-gray-200 rounded-md transition-colors"
>
{t('取消')}
</button>
)}
<button
@@ -77,7 +79,7 @@ export function DialogProvider({ children }: { children: ReactNode }) {
: 'bg-black text-white hover:bg-gray-800'
}`}
>
{dialog.type === 'confirm' ? '确认' : '确定'}
{dialog.type === 'confirm' ? t('确认') : t('确定')}
</button>
</div>
</div>
+4
View File
@@ -1,12 +1,16 @@
import { Outlet } from 'react-router-dom'
import Sidebar from './Sidebar'
import { useState } from 'react'
import AutoTranslate from './AutoTranslate'
import BrowserDialogTranslator from './BrowserDialogTranslator'
export default function Layout() {
const [sidebarCollapsed, setSidebarCollapsed] = useState(false)
return (
<div className="min-h-screen bg-gray-50 flex dark:bg-gray-950">
<AutoTranslate />
<BrowserDialogTranslator />
<Sidebar collapsed={sidebarCollapsed} onToggle={() => setSidebarCollapsed(!sidebarCollapsed)} />
<main className={`flex-1 transition-all duration-300 ${sidebarCollapsed ? 'ml-16' : 'ml-60'}`}>
<div className="p-6">
+36 -13
View File
@@ -19,6 +19,7 @@ import {
UserCog,
} from 'lucide-react'
import { useAuth } from '../contexts/AuthContext'
import { useLanguage } from '../contexts/LanguageContext'
import { useTheme } from '../contexts/ThemeContext'
import { getVersion } from '../services/api'
import AppIcon from './AppIcon'
@@ -45,11 +46,23 @@ function GitHubIcon({ className = '' }: { className?: string }) {
)
}
function LanguageIcon({ className = '' }: { className?: string }) {
return (
<svg className={className} viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<path
d="M213.333333 640v85.333333a85.333333 85.333333 0 0 0 78.933334 85.12L298.666667 810.666667h128v85.333333H298.666667a170.666667 170.666667 0 0 1-170.666667-170.666667v-85.333333h85.333333z m554.666667-213.333333l187.733333 469.333333h-91.946666l-51.242667-128h-174.506667l-51.157333 128h-91.904L682.666667 426.666667h85.333333z m-42.666667 123.093333L672.128 682.666667h106.325333L725.333333 549.76zM341.333333 85.333333v85.333334h170.666667v298.666666H341.333333v128H256v-128H85.333333V170.666667h170.666667V85.333333h85.333333z m384 42.666667a170.666667 170.666667 0 0 1 170.666667 170.666667v85.333333h-85.333333V298.666667a85.333333 85.333333 0 0 0-85.333334-85.333334h-128V128h128zM256 256H170.666667v128h85.333333V256z m170.666667 0H341.333333v128h85.333334V256z"
fill="currentColor"
/>
</svg>
)
}
export default function Sidebar({ collapsed, onToggle }: SidebarProps) {
const navigate = useNavigate()
const location = useLocation()
const { logout, isSubUser } = useAuth()
const { theme, toggleTheme } = useTheme()
const { language, toggleLanguage, t } = useLanguage()
const [version, setVersion] = useState('')
useEffect(() => {
@@ -99,7 +112,7 @@ export default function Sidebar({ collapsed, onToggle }: SidebarProps) {
<button
onClick={onToggle}
className="p-1 rounded hover:bg-gray-100 text-gray-500 dark:hover:bg-gray-800 dark:text-gray-400"
title="切换侧边栏"
title={t('切换侧边栏')}
>
{collapsed ? (
<ChevronRight className="w-4 h-4" />
@@ -253,18 +266,28 @@ export default function Sidebar({ collapsed, onToggle }: SidebarProps) {
<div className="border-t border-gray-200 dark:border-gray-700 p-2 space-y-1">
{/* Theme Toggle */}
<button
onClick={toggleTheme}
className="w-full flex items-center gap-3 px-3 py-2.5 rounded-md text-sm text-gray-600 hover:bg-gray-100 transition-colors dark:text-gray-400 dark:hover:bg-gray-800"
title={theme === 'dark' ? '切换亮色模式' : '切换暗黑模式'}
>
{theme === 'dark' ? (
<Sun className="w-4 h-4" />
) : (
<Moon className="w-4 h-4" />
)}
{!collapsed && <span>{theme === 'dark' ? '亮色模式' : '暗黑模式'}</span>}
</button>
<div className={collapsed ? 'space-y-1' : 'flex items-center gap-1'}>
<button
onClick={toggleTheme}
className={`${collapsed ? 'w-full justify-center' : 'flex-1'} flex items-center gap-3 px-3 py-2.5 rounded-md text-sm text-gray-600 hover:bg-gray-100 transition-colors dark:text-gray-400 dark:hover:bg-gray-800`}
title={t(theme === 'dark' ? '切换亮色模式' : '切换暗黑模式')}
>
{theme === 'dark' ? (
<Sun className="w-4 h-4" />
) : (
<Moon className="w-4 h-4" />
)}
{!collapsed && <span>{theme === 'dark' ? '亮色模式' : '暗黑模式'}</span>}
</button>
<button
onClick={() => { void toggleLanguage() }}
className={`${collapsed ? 'w-full' : 'w-10'} flex items-center justify-center rounded-md px-2 py-2.5 text-sm text-gray-600 hover:bg-gray-100 transition-colors dark:text-gray-400 dark:hover:bg-gray-800`}
title={language === 'en' ? '切换中文' : 'Switch to English'}
>
<LanguageIcon className="h-4 w-4" />
</button>
</div>
{/* Version */}
{version && (