Files
clash-verge-rev/src/components/profile/proxies-editor-viewer.tsx
T
Tunglies 69b76cc6a9 refactor(frontend): contract flow (#8131)
* feat(contract): export wire contract from backend and generate frontend types

Adds a zero-dependency `frontend-contract` bin that serializes the real
NoticeStatus variants and FrontendEvent payloads, scripts/gen-contract.mjs
which emits the committed src/services/contract.ts, and a CI job that
regenerates it and fails on a non-empty diff. events.ts now derives its
event map from the generated contract instead of hand-typed shapes.

* feat(events): route all backend events through a single event bus and store

Adds src/services/bus (the only listen/emit site: one handler per contract
event plus the frontend-internal test-all event) and the React
context/reducer app store. Migrates the five scattered subscriptions
(layout events, pending failures, proxy refresh, profile update/timer,
test-all), deletes the old glue (events.ts, use-listen, use-layout-events,
LoadingCacheProvider), moves run state into the store, and adds an
architecture gate script wired into CI. Behavior is unchanged; the
run-state query's poll/focus safety net is preserved by the store
provider.

* refactor(notice): make the notice table exhaustive and drop dead wire entries

D5 cleanup, frontend and backend in one commit: removes the six
config_validate::* statuses that never receive a backend send and the
set_config::ok send (enum variants, golden list 41→34, send point in
restart_clash_core), their frontend handlers, and the five i18n keys only
those handlers used. The notice table is now typed as a Record over the
generated NoticeStatus union, so a status without a frontend entry fails
to compile. The info status (sent by the silent updater for breaking
change notices, previously dropped with a console warning) now shows an
info toast — the one deliberate behavior delta.

* feat(mutate): single funnel for user-intent commands and invoke gate

Adds src/services/mutate.ts: one path for optimistic apply, services-layer
invoke, Busy handling, failure rollback, and the error toast, with busy
bookkeeping mirrored into the app store. The patch hooks (verge, clash,
profiles) now route through it. Moves the remaining direct invokes
(unlock ×3, DNS ×4) into cmds.ts and turns on the invoke-only-in-services
architecture gate in CI.

* refactor(settings): route settings-domain commands through the mutate funnel

Ports port saving, webdav/local backup operations, core change/restart/
upgrade, service install/uninstall/repair flows, the system-proxy toggle
queue, the DNS override toggle, and app lifecycle commands onto the single
funnel. Bespoke flows keep their own error handling via errorNotice:false;
simple flows gain the funnel's default error toast and revalidation.

* refactor(profiles): route profile operations through the mutate funnel

Ports profile create/import/reorder/delete/update/patch/save-file and
enhance calls onto the funnel; retry and editor flows keep their own
error handling with errorNotice:false. Per-uid ids keep the update
worker pool concurrent under the funnel's in-flight dedupe.

* refactor(proxies): route proxy/home/misc commands through the mutate funnel

Ports mode switching (page and home card), chain runtime updates, node
selection with tray sync, selection recording, provider updates and
syncs, and lightweight-mode entry onto the funnel; every site keeps its
existing optimistic/revert and error-handling behavior.

* docs: add frontend architecture guardrails for src

Layering rules for the contract flow: generated contract as the only
wire-typing source, event bus as the only listen/emit site, pure-reducer
store for event-derived state, the mutate funnel for user intent, and
invoke only in the services layer — each backed by the CI gates.

* fix(events): close run-state race and restore single error toasts

Self-review findings: the bus now re-reads the run-state snapshot in
onSubscribed so an event racing the store's initial read cannot leave a
stale snapshot (the ordering the old layout listener guaranteed), and the
patch hooks pass errorNotice:false so GuardState/page handlers remain the
only error toast, matching the pre-migration behavior.

* fix(frontend): preserve queued intents and fresh runtime snapshots

* refactor(frontend): trim unused mutation and busy state APIs

* docs(frontend): focus guardrails on architecture ownership
2026-10-07 07:38:55 +00:00

501 lines
14 KiB
TypeScript

import { arrayMove } from '@dnd-kit/helpers'
import {
VerticalAlignBottomRounded,
VerticalAlignTopRounded,
} from '@mui/icons-material'
import {
Box,
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
List,
ListItem,
TextField,
styled,
} from '@mui/material'
import { useLockFn } from 'ahooks'
import * as yaml from 'js-yaml'
import {
startTransition,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react'
import { useTranslation } from 'react-i18next'
import { BaseSearchBox, MonacoEditor } from '@/components/base'
import { ProxyItem } from '@/components/profile/proxy-item'
import { readProfileFile, saveProfileFile } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service'
import { useThemeMode } from '@/services/states'
import type { MonacoEditorInstance } from '@/types/monaco'
import { MONACO_FONT_FAMILY } from '@/utils/font-family'
import parseUri from '@/utils/uri-parser'
import { parseYamlSafe } from '@/utils/yaml'
import {
buildGroupedItems,
type GroupedVirtualItem,
GroupedVirtualList,
} from './grouped-virtual-list'
interface Props {
profileUid: string
property: string
open: boolean
onClose: () => void
onSave?: (prev?: string, curr?: string) => void
}
const findRealIndex = (
list: IProxyConfig[],
filtered: IProxyConfig[],
filteredIndex: number,
): number => {
const item = filtered[filteredIndex]
if (!item) return -1
return list.findIndex((proxy) => proxy.name === item.name)
}
// 节点的 name 会被用作 sortable item id、React key 以及拖拽排序的
// 依据。当 name 为空/null(例如高级模式下粘贴了缺少 name 的节点)时,
// 无效 name 不能作为 sortable item id,否则会导致拖拽注册失败。
// 这里统一过滤掉没有有效 name 的节点,避免可视化编辑页崩溃;原始 YAML
// 数据仍然保留,用户可在高级(文本)模式中查看并修正这些节点。
const hasValidName = (proxy: IProxyConfig) =>
typeof proxy?.name === 'string' && proxy.name.length > 0
export const ProxiesEditorViewer = (props: Props) => {
const { profileUid, property, open, onClose, onSave } = props
const { t } = useTranslation()
const themeMode = useThemeMode()
const editorRef = useRef<MonacoEditorInstance | null>(null)
const [prevData, setPrevData] = useState('')
const [currData, setCurrData] = useState('')
const [visualization, setVisualization] = useState(true)
const [match, setMatch] = useState(() => (_: string) => true)
const [proxyUri, setProxyUri] = useState<string>('')
const [proxyList, setProxyList] = useState<IProxyConfig[]>([])
const [prependSeq, setPrependSeq] = useState<IProxyConfig[]>([])
const [appendSeq, setAppendSeq] = useState<IProxyConfig[]>([])
const [deleteSeq, setDeleteSeq] = useState<string[]>([])
const hasLoadedSeqConfigRef = useRef(false)
const filteredPrependSeq = useMemo(
() =>
prependSeq.filter((proxy) => hasValidName(proxy) && match(proxy.name)),
[prependSeq, match],
)
const filteredProxyList = useMemo(
() => proxyList.filter((proxy) => hasValidName(proxy) && match(proxy.name)),
[proxyList, match],
)
const filteredAppendSeq = useMemo(
() => appendSeq.filter((proxy) => hasValidName(proxy) && match(proxy.name)),
[appendSeq, match],
)
const items = useMemo(
() =>
buildGroupedItems(
filteredPrependSeq,
filteredProxyList,
filteredAppendSeq,
(proxy) => proxy.name,
),
[filteredPrependSeq, filteredProxyList, filteredAppendSeq],
)
const renderItem = (entry: GroupedVirtualItem<IProxyConfig>) => {
const { category, item } = entry
if (category === 'original') {
const isDeleted = deleteSeq.includes(item.name)
return (
<ProxyItem
type={isDeleted ? 'delete' : 'original'}
proxy={item}
onDelete={() => {
if (isDeleted) {
setDeleteSeq(deleteSeq.filter((v) => v !== item.name))
} else {
setDeleteSeq((prev) => [...prev, item.name])
}
}}
/>
)
}
if (category === 'prepend') {
return (
<ProxyItem
type="prepend"
proxy={item}
onDelete={() => {
setPrependSeq(prependSeq.filter((v) => v.name !== item.name))
}}
/>
)
}
return (
<ProxyItem
type="append"
proxy={item}
onDelete={() => {
setAppendSeq(appendSeq.filter((v) => v.name !== item.name))
}}
/>
)
}
const onReorder = (
category: 'prepend' | 'append',
activeIndex: number,
overIndex: number,
) => {
const list = category === 'prepend' ? prependSeq : appendSeq
const filtered =
category === 'prepend' ? filteredPrependSeq : filteredAppendSeq
const setList = category === 'prepend' ? setPrependSeq : setAppendSeq
const activeRealIndex = findRealIndex(list, filtered, activeIndex)
const overRealIndex = findRealIndex(list, filtered, overIndex)
if (
activeRealIndex < 0 ||
overRealIndex < 0 ||
activeRealIndex === overRealIndex
) {
return
}
setList(arrayMove(list, activeRealIndex, overRealIndex))
}
// 优化:异步分片解析,避免主线程阻塞,解析完成后批量setState
const handleParseAsync = (cb: (proxies: IProxyConfig[]) => void) => {
const proxies: IProxyConfig[] = []
const names: string[] = []
let uris: string
try {
uris = atob(proxyUri)
} catch {
uris = proxyUri
}
const lines = uris.trim().split('\n')
let idx = 0
const batchSize = 50
let parseTimer: number | undefined
const parseBatch = () => {
const end = Math.min(idx + batchSize, lines.length)
for (; idx < end; idx++) {
const uri = lines[idx]
try {
const proxy = parseUri(uri.trim())
if (!names.includes(proxy.name)) {
proxies.push(proxy)
names.push(proxy.name)
}
} catch (err) {
console.warn(
'[ProxiesEditorViewer] parseUri failed for line:',
uri,
err,
)
// 不阻塞主流程
}
}
if (idx < lines.length) {
parseTimer = window.setTimeout(parseBatch, 0)
} else {
if (parseTimer !== undefined) {
clearTimeout(parseTimer)
parseTimer = undefined
}
cb(proxies)
}
}
parseBatch()
}
const fetchProfile = useCallback(async () => {
const data = await readProfileFile(profileUid)
const originProxiesObj = parseYamlSafe(data) as {
proxies: IProxyConfig[]
} | null
setProxyList(originProxiesObj?.proxies || [])
}, [profileUid])
const fetchContent = useCallback(async () => {
hasLoadedSeqConfigRef.current = false
const data = await readProfileFile(property)
const obj = parseYamlSafe(data) as ISeqProfileConfig | null | undefined
setPrevData(data)
setCurrData(data)
if (obj === undefined) {
setVisualization(false)
return
}
setPrependSeq(obj?.prepend || [])
setAppendSeq(obj?.append || [])
setDeleteSeq(obj?.delete || [])
hasLoadedSeqConfigRef.current = true
}, [property])
const handleVisualizationToggle = () => {
if (visualization) {
setVisualization(false)
return
}
const obj = parseYamlSafe(currData) as ISeqProfileConfig | null | undefined
if (obj === undefined) {
hasLoadedSeqConfigRef.current = false
return
}
hasLoadedSeqConfigRef.current = true
startTransition(() => {
setPrependSeq(obj?.prepend ?? [])
setAppendSeq(obj?.append ?? [])
setDeleteSeq(obj?.delete ?? [])
})
setVisualization(true)
}
useEffect(() => {
if (
!hasLoadedSeqConfigRef.current ||
!(prependSeq && appendSeq && deleteSeq)
) {
return
}
const serialize = () => {
if (!hasLoadedSeqConfigRef.current) {
return
}
try {
setCurrData(
yaml.dump(
{ prepend: prependSeq, append: appendSeq, delete: deleteSeq },
{ forceQuotes: true },
),
)
} catch (e) {
console.warn('[ProxiesEditorViewer] yaml.dump failed:', e)
// 防止异常导致UI卡死
}
}
let idleId: number | undefined
let timeoutId: number | undefined
if (window.requestIdleCallback) {
idleId = window.requestIdleCallback(serialize)
} else {
timeoutId = window.setTimeout(serialize, 0)
}
return () => {
if (idleId !== undefined && window.cancelIdleCallback) {
window.cancelIdleCallback(idleId)
}
if (timeoutId !== undefined) {
clearTimeout(timeoutId)
}
}
}, [prependSeq, appendSeq, deleteSeq])
useEffect(() => {
if (!open) return
fetchContent()
fetchProfile()
}, [fetchContent, fetchProfile, open])
useEffect(() => {
return () => {
editorRef.current?.dispose()
editorRef.current = null
}
}, [])
const handleSave = useLockFn(async () => {
try {
const result = await mutate(() => saveProfileFile(property, currData), {
id: `save-profile-file:${property}`,
errorNotice: false,
})
if (!(result.ok && result.value === true)) {
await fetchContent()
onClose()
return
}
showNotice.success('shared.feedback.notifications.saved')
onSave?.(prevData, currData)
onClose()
} catch (err) {
showNotice.error(err)
}
})
return (
<Dialog
open={open}
onClose={onClose}
maxWidth="xl"
fullWidth
disableEnforceFocus={!visualization}
>
<DialogTitle>
{
<Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
{t('profiles.modals.proxiesEditor.title')}
<Box>
<Button
variant="contained"
size="small"
onClick={handleVisualizationToggle}
>
{visualization
? t('shared.editorModes.advanced')
: t('shared.editorModes.visualization')}
</Button>
</Box>
</Box>
}
</DialogTitle>
<DialogContent
sx={{ display: 'flex', width: 'auto', height: 'calc(100vh - 185px)' }}
>
{visualization ? (
<>
<List
sx={{
width: '50%',
padding: '0 10px',
}}
>
<Box
sx={{
height: 'calc(100% - 80px)',
overflowY: 'auto',
}}
>
<Item>
<TextField
autoComplete="new-password"
placeholder={t(
'profiles.modals.proxiesEditor.placeholders.multiUri',
)}
fullWidth
rows={9}
multiline
size="small"
onChange={(e) => setProxyUri(e.target.value)}
/>
</Item>
</Box>
<Item>
<Button
fullWidth
variant="contained"
startIcon={<VerticalAlignTopRounded />}
onClick={() => {
handleParseAsync((proxies) => {
setPrependSeq((prev) => [...proxies, ...prev])
})
}}
>
{t('profiles.modals.proxiesEditor.actions.prepend')}
</Button>
</Item>
<Item>
<Button
fullWidth
variant="contained"
startIcon={<VerticalAlignBottomRounded />}
onClick={() => {
handleParseAsync((proxies) => {
setAppendSeq((prev) => [...prev, ...proxies])
})
}}
>
{t('profiles.modals.proxiesEditor.actions.append')}
</Button>
</Item>
</List>
<List
sx={{
width: '50%',
padding: '0 10px',
}}
>
<BaseSearchBox onSearch={(match) => setMatch(() => match)} />
<GroupedVirtualList
items={items}
renderItem={renderItem}
onReorder={onReorder}
style={{ height: 'calc(100% - 24px)', marginTop: '8px' }}
/>
</List>
</>
) : (
<MonacoEditor
height="100%"
language="yaml"
value={currData}
theme={themeMode === 'light' ? 'light' : 'vs-dark'}
onMount={(editorInstance) => {
editorRef.current = editorInstance
}}
options={{
tabSize: 2, // 根据语言类型设置缩进大小
minimap: {
enabled: document.documentElement.clientWidth >= 1500, // 超过一定宽度显示minimap滚动条
},
mouseWheelZoom: true, // 按住Ctrl滚轮调节缩放比例
quickSuggestions: {
strings: true, // 字符串类型的建议
comments: true, // 注释类型的建议
other: true, // 其他类型的建议
},
padding: {
top: 33, // 顶部padding防止遮挡snippets
},
fontFamily: MONACO_FONT_FAMILY,
fontLigatures: false, // 连字符
smoothScrolling: true, // 平滑滚动
}}
onChange={(value) => setCurrData(value ?? '')}
/>
)}
</DialogContent>
<DialogActions>
<Button onClick={onClose} variant="outlined">
{t('shared.actions.cancel')}
</Button>
<Button onClick={handleSave} variant="contained">
{t('shared.actions.save')}
</Button>
</DialogActions>
</Dialog>
)
}
const Item = styled(ListItem)(() => ({
padding: '5px 2px',
}))