mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-11-24 14:32:13 +08:00
perf(ui): stabilize hot-path render identities across profile, proxy, log and settings views (#8694)
* perf(profile): stabilize profile grid callbacks and context menus ProfileItem is memoized, but the grid passed five freshly-created closure props per render, so URL keystrokes and switch spinners re-rendered every card. The callbacks are now uid/item-parameterized stable handlers, and the context-menu label map and item literals are hoisted or gated on the menu being open. * perf(profile): derive editor policy names and dedupe pasted proxies The groups editor re-read both profile files and re-parsed three YAML documents on every prepend/append/delete edit. The origin names are now read once per open and folded into a memoized policy list, and batch pasted proxy names dedupe through a Set instead of a linear scan. * perf(ui): keep mutateVerge identity stable across renders mutateVerge was a per-render closure that dozens of consumer callbacks depended on, and its updater fell back to a render-time config snapshot. It now keeps a stable identity, revalidates through the module-level query helper, and passes the live cache value (preload snapshot when the cache is still empty) to function updaters; object-form callers were migrated to updater functions. * perf(ui): hoist static dialog identities and memoize settings search The DNS viewer rebuilt Monaco's options object per keystroke, the update dialog rebuilt its markdown component map and plugin array per progress chunk (remounting link and blockquote subtrees), and the settings search rescanned the ~180-entry catalog on unrelated renders such as arrow-key selection. These identities are now module constants or single memos; the width-dependent minimap option is applied at editor mount. * perf(proxy): stable tool callbacks and shared delay entries Group headers and heads passed freshly-created closures into the memoized tools, defeating it on every render; the tool callbacks are now groupName-parameterized and forwarded directly. Cached delay entries are write-once, so the defensive copy on read and the second copy in the delay-state reducer were dropped. * perf(proxy): stable group location and chain list identities The sticky-header scroll callback depended on the render list identity, re-creating the item renderer on every list rebuild; it now reads the list through a stable ref callback. Rebinding no longer allocates new chain items and arrays when values are unchanged, so the 15s proxy-view refresh stops re-serializing identical chains to localStorage, and the chain delay key join is memoized. * perf(log): reuse the empty logs fallback identity A fresh [] fallback gave the subscription hook's refresh callback and snapshot effect a new identity on every render while logs streamed; the empty list is now a shared module constant. * perf(home): build traffic range snapshots in one pass The 200ms graph snapshot built three to four intermediate arrays on the compressed path before posting to the worker. It now fills one preallocated result in a single pass and only sorts when the compressed and raw ranges actually interleave. * chore(changelog): drop the render efficiency entry
This commit is contained in:
@@ -51,6 +51,25 @@ const Item = styled(ListItem)(() => ({
|
||||
},
|
||||
}))
|
||||
|
||||
// Static editor settings; a per-render object would re-trigger Monaco's
|
||||
// updateOptions and listener resubscription on every keystroke. The minimap
|
||||
// depends on the live window width and is applied at editor mount instead.
|
||||
const MONACO_OPTIONS = {
|
||||
tabSize: 2,
|
||||
mouseWheelZoom: true,
|
||||
quickSuggestions: {
|
||||
strings: true,
|
||||
comments: true,
|
||||
other: true,
|
||||
},
|
||||
padding: {
|
||||
top: 33,
|
||||
},
|
||||
fontFamily: MONACO_FONT_FAMILY,
|
||||
fontLigatures: false,
|
||||
smoothScrolling: true,
|
||||
} as const
|
||||
|
||||
type NameserverPolicy = Record<string, any>
|
||||
|
||||
function parseNameserverPolicy(str: string): NameserverPolicy {
|
||||
@@ -520,9 +539,21 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
|
||||
}
|
||||
})
|
||||
|
||||
const handleYamlChange = (value?: string) => {
|
||||
const handleYamlChange = useCallback((value?: string) => {
|
||||
setYamlContent(value || '')
|
||||
}
|
||||
}, [])
|
||||
|
||||
const handleEditorMount = useCallback(
|
||||
(editorInstance: MonacoEditorInstance) => {
|
||||
editorRef.current = editorInstance
|
||||
editorInstance.updateOptions({
|
||||
minimap: {
|
||||
enabled: document.documentElement.clientWidth >= 1500,
|
||||
},
|
||||
})
|
||||
},
|
||||
[],
|
||||
)
|
||||
|
||||
const handleChange = (field: string) => (event: any) => {
|
||||
const value =
|
||||
@@ -1052,27 +1083,8 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
|
||||
value={yamlContent}
|
||||
theme={themeMode === 'light' ? 'light' : 'vs-dark'}
|
||||
className="flex-grow"
|
||||
onMount={(editorInstance) => {
|
||||
editorRef.current = editorInstance
|
||||
}}
|
||||
options={{
|
||||
tabSize: 2,
|
||||
minimap: {
|
||||
enabled: document.documentElement.clientWidth >= 1500,
|
||||
},
|
||||
mouseWheelZoom: true,
|
||||
quickSuggestions: {
|
||||
strings: true,
|
||||
comments: true,
|
||||
other: true,
|
||||
},
|
||||
padding: {
|
||||
top: 33,
|
||||
},
|
||||
fontFamily: MONACO_FONT_FAMILY,
|
||||
fontLigatures: false,
|
||||
smoothScrolling: true,
|
||||
}}
|
||||
onMount={handleEditorMount}
|
||||
options={MONACO_OPTIONS}
|
||||
onChange={handleYamlChange}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -121,7 +121,7 @@ export const LayoutViewer = forwardRef<DialogRef>((_, ref) => {
|
||||
showNotice.error(err)
|
||||
}
|
||||
const onChangeData = (patch: Partial<IVergeConfig>) => {
|
||||
mutateVerge({ ...verge, ...patch })
|
||||
mutateVerge((prev) => ({ ...prev, ...patch }))
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
@@ -328,7 +328,7 @@ export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
|
||||
Promise.resolve().then(async () => {
|
||||
try {
|
||||
if (Object.keys(patch).length > 0) {
|
||||
mutateVerge({ ...verge, ...patch })
|
||||
mutateVerge((prev) => ({ ...prev, ...patch }))
|
||||
}
|
||||
if (Object.keys(patch).length > 0) {
|
||||
await patchVerge(patch)
|
||||
|
||||
@@ -114,6 +114,84 @@ const getAlertTypeFromClassName = (
|
||||
return match?.[1] as GitHubAlertType | null
|
||||
}
|
||||
|
||||
const openUrlWithNotice = (url: string) => {
|
||||
void openExternalUrl(url).catch(showNotice.error)
|
||||
}
|
||||
|
||||
// Renderer map is static; a per-render identity would remount every link and
|
||||
// blockquote subtree while download progress re-renders the dialog.
|
||||
const MARKDOWN_COMPONENTS: ReactMarkdownOptions['components'] = {
|
||||
a: ({ href, children, ...props }) => {
|
||||
const isFragment = href?.startsWith('#') ?? false
|
||||
const renderedHref = isFragment
|
||||
? `#${UPDATE_MARKDOWN_ID_PREFIX}${href?.slice(1)}`
|
||||
: href
|
||||
? '#'
|
||||
: undefined
|
||||
|
||||
return (
|
||||
<a
|
||||
{...props}
|
||||
href={renderedHref}
|
||||
target={undefined}
|
||||
rel={undefined}
|
||||
onClick={(event) => {
|
||||
if (isFragment) return
|
||||
event.preventDefault()
|
||||
if (!href) return
|
||||
openUrlWithNotice(href)
|
||||
}}
|
||||
onAuxClick={(event) => {
|
||||
if (isFragment) return
|
||||
event.preventDefault()
|
||||
if (event.button === 1 && href) {
|
||||
openUrlWithNotice(href)
|
||||
}
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</a>
|
||||
)
|
||||
},
|
||||
blockquote: ({ className, children }) => {
|
||||
const alertType = getAlertTypeFromClassName(className)
|
||||
|
||||
if (!alertType) {
|
||||
return <blockquote className={className}>{children}</blockquote>
|
||||
}
|
||||
|
||||
return (
|
||||
<Box
|
||||
component="blockquote"
|
||||
className={className}
|
||||
sx={(theme) => {
|
||||
const color = GITHUB_ALERTS[alertType].color
|
||||
return {
|
||||
m: '12px 0 18px',
|
||||
px: 2,
|
||||
py: 1,
|
||||
borderLeft: `4px solid ${color}`,
|
||||
borderRadius: 1,
|
||||
bgcolor: alpha(color, theme.palette.mode === 'dark' ? 0.16 : 0.08),
|
||||
'& p': {
|
||||
my: 0.75,
|
||||
},
|
||||
'& .markdown-alert-title': {
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 0.75,
|
||||
fontWeight: 700,
|
||||
lineHeight: 1.4,
|
||||
},
|
||||
}
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</Box>
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
const findFirstTextNode = (node: MarkdownNode): MarkdownNode | null => {
|
||||
if (node.type === 'text') return node
|
||||
for (const child of node.children ?? []) {
|
||||
@@ -185,10 +263,6 @@ export function UpdateViewer({ ref }: { ref?: Ref<DialogRef> }) {
|
||||
})
|
||||
const { downloaded, total } = download
|
||||
|
||||
const openUrlWithNotice = (url: string) => {
|
||||
void openExternalUrl(url).catch(showNotice.error)
|
||||
}
|
||||
|
||||
const progress = total <= 0 ? 0 : Math.min((downloaded / total) * 100, 100)
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
@@ -209,8 +283,8 @@ export function UpdateViewer({ ref }: { ref?: Ref<DialogRef> }) {
|
||||
) as Record<GitHubAlertType, string>,
|
||||
[t],
|
||||
)
|
||||
const remarkGitHubAlertsPlugin = useMemo(
|
||||
() => () => remarkGitHubAlerts(githubAlertLabels),
|
||||
const remarkPlugins = useMemo(
|
||||
() => [() => remarkGitHubAlerts(githubAlertLabels)],
|
||||
[githubAlertLabels],
|
||||
)
|
||||
|
||||
@@ -472,83 +546,8 @@ export function UpdateViewer({ ref }: { ref?: Ref<DialogRef> }) {
|
||||
{open && (
|
||||
<Suspense fallback={<LinearProgress />}>
|
||||
<LazyReactMarkdown
|
||||
remarkPlugins={[remarkGitHubAlertsPlugin]}
|
||||
components={{
|
||||
a: ({ href, children, ...props }) => {
|
||||
const isFragment = href?.startsWith('#') ?? false
|
||||
const renderedHref = isFragment
|
||||
? `#${UPDATE_MARKDOWN_ID_PREFIX}${href?.slice(1)}`
|
||||
: href
|
||||
? '#'
|
||||
: undefined
|
||||
|
||||
return (
|
||||
<a
|
||||
{...props}
|
||||
href={renderedHref}
|
||||
target={undefined}
|
||||
rel={undefined}
|
||||
onClick={(event) => {
|
||||
if (isFragment) return
|
||||
event.preventDefault()
|
||||
if (!href) return
|
||||
openUrlWithNotice(href)
|
||||
}}
|
||||
onAuxClick={(event) => {
|
||||
if (isFragment) return
|
||||
event.preventDefault()
|
||||
if (event.button === 1 && href) {
|
||||
openUrlWithNotice(href)
|
||||
}
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</a>
|
||||
)
|
||||
},
|
||||
blockquote: ({ className, children }) => {
|
||||
const alertType = getAlertTypeFromClassName(className)
|
||||
|
||||
if (!alertType) {
|
||||
return (
|
||||
<blockquote className={className}>{children}</blockquote>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Box
|
||||
component="blockquote"
|
||||
className={className}
|
||||
sx={(theme) => {
|
||||
const color = GITHUB_ALERTS[alertType].color
|
||||
return {
|
||||
m: '12px 0 18px',
|
||||
px: 2,
|
||||
py: 1,
|
||||
borderLeft: `4px solid ${color}`,
|
||||
borderRadius: 1,
|
||||
bgcolor: alpha(
|
||||
color,
|
||||
theme.palette.mode === 'dark' ? 0.16 : 0.08,
|
||||
),
|
||||
'& p': {
|
||||
my: 0.75,
|
||||
},
|
||||
'& .markdown-alert-title': {
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 0.75,
|
||||
fontWeight: 700,
|
||||
lineHeight: 1.4,
|
||||
},
|
||||
}
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</Box>
|
||||
)
|
||||
},
|
||||
}}
|
||||
remarkPlugins={remarkPlugins}
|
||||
components={MARKDOWN_COMPONENTS}
|
||||
>
|
||||
{markdownContent}
|
||||
</LazyReactMarkdown>
|
||||
|
||||
@@ -20,7 +20,7 @@ const SettingSystem = ({ onError }: Props) => {
|
||||
const { enable_auto_launch, enable_silent_start } = verge ?? {}
|
||||
|
||||
const onChangeData = (patch: Partial<IVergeConfig>) => {
|
||||
mutateVerge({ ...verge, ...patch })
|
||||
mutateVerge((prev) => ({ ...prev, ...patch }))
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
@@ -72,7 +72,7 @@ const SettingVergeBasic = ({ onError }: Props) => {
|
||||
const backupRef = useRef<DialogRef>(null)
|
||||
|
||||
const onChangeData = (patch: any) => {
|
||||
mutateVerge({ ...verge, ...patch })
|
||||
mutateVerge((prev) => ({ ...prev, ...patch }))
|
||||
}
|
||||
|
||||
const onCopyClashEnv = useCallback(async () => {
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
TextField,
|
||||
Typography,
|
||||
} from '@mui/material'
|
||||
import { useEffect, useRef, useState, type ReactNode } from 'react'
|
||||
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import getSystem from '@/utils/get-system'
|
||||
@@ -21,6 +21,9 @@ import {
|
||||
type SearchDialog,
|
||||
} from './settings-search-context'
|
||||
|
||||
// Constant for the runtime; module-level like the other getSystem() callers.
|
||||
const OS = getSystem()
|
||||
|
||||
export function SettingsSearch({
|
||||
children,
|
||||
}: {
|
||||
@@ -40,11 +43,17 @@ export function SettingsSearch({
|
||||
const originalScrollRef = useRef(0)
|
||||
const resultScrollRef = useRef(0)
|
||||
const cancelLocateRef = useRef<() => void>(() => {})
|
||||
const results = searchSettings(
|
||||
query,
|
||||
getSystem(),
|
||||
(key) => t(key),
|
||||
(key) => t(key, { lng: 'en' }),
|
||||
// The catalog scan touches every entry with translations; memoizing keeps
|
||||
// unrelated state (arrow-key selection) from re-running it.
|
||||
const results = useMemo(
|
||||
() =>
|
||||
searchSettings(
|
||||
query,
|
||||
OS,
|
||||
(key) => t(key),
|
||||
(key) => t(key, { lng: 'en' }),
|
||||
),
|
||||
[query, t],
|
||||
)
|
||||
const searching = !!query.trim()
|
||||
const scroller = () =>
|
||||
|
||||
Reference in New Issue
Block a user