diff --git a/src/components/home/test-card.tsx b/src/components/home/test-card.tsx index 310c1f24c..dead8a197 100644 --- a/src/components/home/test-card.tsx +++ b/src/components/home/test-card.tsx @@ -89,18 +89,18 @@ export const TestCard = () => { x.uid === uid ? { ...x, ...patch } : x, ) - mutateVerge({ ...verge, test_list: newList }) + mutateVerge((prev) => ({ ...prev, test_list: newList })) }, - [testList, verge, mutateVerge], + [testList, mutateVerge], ) const onDeleteTestListItem = useCallback( (uid: string) => { const newList = testList.filter((x) => x.uid !== uid) patchVerge({ test_list: newList }) - mutateVerge({ ...verge, test_list: newList }) + mutateVerge((prev) => ({ ...prev, test_list: newList })) }, - [testList, verge, patchVerge, mutateVerge], + [testList, patchVerge, mutateVerge], ) const onDragEnd = useCallback( @@ -131,7 +131,7 @@ export const TestCard = () => { newList.splice(newIndex, 0, removed) // 优化:先本地更新,再异步 patch,避免UI卡死 - mutateVerge({ ...verge, test_list: newList }) + mutateVerge((prev) => ({ ...prev, test_list: newList })) const patchFn = () => { try { patchVerge({ test_list: newList }) @@ -143,7 +143,7 @@ export const TestCard = () => { setTimeout(patchFn, 0) } }, - [testList, verge, mutateVerge, patchVerge], + [testList, mutateVerge, patchVerge], ) // 仅在verge首次加载时初始化测试列表 diff --git a/src/components/profile/groups-editor-viewer.tsx b/src/components/profile/groups-editor-viewer.tsx index b98070ff0..631162639 100644 --- a/src/components/profile/groups-editor-viewer.tsx +++ b/src/components/profile/groups-editor-viewer.tsx @@ -176,7 +176,10 @@ export const GroupsEditorViewer = (props: Props) => { }, }) const [groupList, setGroupList] = useState([]) - const [proxyPolicyList, setProxyPolicyList] = useState([]) + const [originPolicy, setOriginPolicy] = useState<{ + proxyNames: string[] + groupNames: string[] + }>({ proxyNames: [], groupNames: [] }) const [proxyProviderList, setProxyProviderList] = useState([]) const [prependSeq, setPrependSeq] = useState([]) const [appendSeq, setAppendSeq] = useState([]) @@ -354,6 +357,9 @@ export const GroupsEditorViewer = (props: Props) => { } }, [prependSeq, appendSeq, deleteSeq]) + // Origin policy names come from profile files that this dialog never + // rewrites while open, so they are read once per open; the live seq states + // are folded in by the derived proxyPolicyList below. const fetchProxyPolicy = useCallback(async () => { const data = await readProfileFile(profileUid) const proxiesData = await readProfileFile(proxiesUid) @@ -389,17 +395,13 @@ export const GroupsEditorViewer = (props: Props) => { (name): name is string => typeof name === 'string' && name.length > 0, ) - const computedPolicyList = builtinProxyPolicies.concat( - prependSeq.map((group: IProxyGroupConfig) => group.name), - (originGroupsObj?.['proxy-groups'] || []) - .map((group: IProxyGroupConfig) => group.name) - .filter((name) => !deleteSeq.includes(name)), - appendSeq.map((group: IProxyGroupConfig) => group.name), + setOriginPolicy({ proxyNames, - ) - - setProxyPolicyList(Array.from(new Set(computedPolicyList))) - }, [appendSeq, deleteSeq, prependSeq, profileUid, proxiesUid]) + groupNames: (originGroupsObj?.['proxy-groups'] || []).map( + (group) => group.name, + ), + }) + }, [profileUid, proxiesUid]) const fetchProfile = useCallback(async () => { const data = await readProfileFile(profileUid) const mergeData = await readProfileFile(mergeUid) @@ -443,6 +445,16 @@ export const GroupsEditorViewer = (props: Props) => { fetchProxyPolicy() }, [fetchProxyPolicy, open]) + const proxyPolicyList = useMemo(() => { + const computedPolicyList = builtinProxyPolicies.concat( + prependSeq.map((group) => group.name), + originPolicy.groupNames.filter((name) => !deleteSeq.includes(name)), + appendSeq.map((group) => group.name), + originPolicy.proxyNames, + ) + return Array.from(new Set(computedPolicyList)) + }, [appendSeq, deleteSeq, originPolicy, prependSeq]) + useEffect(() => { if (!open) return fetchContent() diff --git a/src/components/profile/profile-item.tsx b/src/components/profile/profile-item.tsx index 474d8dc47..d8dfeb0a6 100644 --- a/src/components/profile/profile-item.tsx +++ b/src/components/profile/profile-item.tsx @@ -61,6 +61,31 @@ const round = keyframes` to { transform: rotate(360deg); } ` +type ContextMenuItem = { + label: string + handler: () => void + disabled: boolean +} + +const menuLabels: Record = { + home: 'profiles.components.menu.home', + select: 'profiles.components.menu.select', + shareQrCode: 'profiles.components.menu.shareQrCode', + editInfo: 'profiles.components.menu.editInfo', + editFile: 'profiles.components.menu.editFile', + editRules: 'profiles.components.menu.editRules', + editProxies: 'profiles.components.menu.editProxies', + editGroups: 'profiles.components.menu.editGroups', + extendConfig: 'profiles.components.menu.extendConfig', + extendScript: 'profiles.components.menu.extendScript', + openFile: 'profiles.components.menu.openFile', + update: 'profiles.components.menu.update', + updateViaProxy: 'profiles.components.menu.updateViaProxy', + delete: 'shared.actions.delete', +} as const + +const EMPTY_CONTEXT_MENU: ContextMenuItem[] = [] + export interface ProfileItemProps { id: string index: number @@ -68,13 +93,13 @@ export interface ProfileItemProps { activating: boolean itemData: IProfileItem mutateProfiles: () => Promise - onSelect: (force: boolean) => void - onEdit: () => void - onSave?: (prev?: string, curr?: string) => void - onDelete: () => void + onSelect: (uid: string, force: boolean) => void + onEdit: (item: IProfileItem) => void + onSave?: (uid: string, prev?: string, curr?: string) => void + onDelete: (uid: string) => void batchMode?: boolean isSelected?: boolean - onSelectionChange?: () => void + onSelectionChange?: (uid: string) => void timerUpdateRevision: number completedUpdateRevision: number } @@ -322,7 +347,7 @@ const ProfileItemBase = (props: ProfileItemProps) => { const onEditInfo = () => { setAnchorEl(null) - onEdit() + onEdit(itemData) } const onShareQrCode = () => { @@ -362,7 +387,7 @@ const ProfileItemBase = (props: ProfileItemProps) => { const onForceSelect = () => { setAnchorEl(null) - onSelect(true) + onSelect(id, true) } const onOpenFile = useLockFn(async () => { @@ -412,175 +437,158 @@ const ProfileItemBase = (props: ProfileItemProps) => { } }) - type ContextMenuItem = { - label: string - handler: () => void - disabled: boolean - } - - const menuLabels: Record = { - home: 'profiles.components.menu.home', - select: 'profiles.components.menu.select', - shareQrCode: 'profiles.components.menu.shareQrCode', - editInfo: 'profiles.components.menu.editInfo', - editFile: 'profiles.components.menu.editFile', - editRules: 'profiles.components.menu.editRules', - editProxies: 'profiles.components.menu.editProxies', - editGroups: 'profiles.components.menu.editGroups', - extendConfig: 'profiles.components.menu.extendConfig', - extendScript: 'profiles.components.menu.extendScript', - openFile: 'profiles.components.menu.openFile', - update: 'profiles.components.menu.update', - updateViaProxy: 'profiles.components.menu.updateViaProxy', - delete: 'shared.actions.delete', - } as const - - const urlModeMenu: ContextMenuItem[] = [ - ...(hasHome - ? [ - { - label: menuLabels.home, - handler: onOpenHome, - disabled: false, - } satisfies ContextMenuItem, - ] - : []), - { - label: menuLabels.select, - handler: onForceSelect, - disabled: false, - }, - { - label: menuLabels.shareQrCode, - handler: onShareQrCode, - disabled: false, - }, - { - label: menuLabels.editInfo, - handler: onEditInfo, - disabled: false, - }, - { - label: menuLabels.editFile, - handler: onEditFile, - disabled: false, - }, - { - label: menuLabels.editRules, - handler: onEditRules, - disabled: !option?.rules, - }, - { - label: menuLabels.editProxies, - handler: onEditProxies, - disabled: !option?.proxies, - }, - { - label: menuLabels.editGroups, - handler: onEditGroups, - disabled: !option?.groups, - }, - { - label: menuLabels.extendConfig, - handler: onEditMerge, - disabled: !option?.merge, - }, - { - label: menuLabels.extendScript, - handler: onEditScript, - disabled: !option?.script, - }, - { - label: menuLabels.openFile, - handler: onOpenFile, - disabled: false, - }, - { - label: menuLabels.update, - handler: () => onUpdate(0), - disabled: false, - }, - { - label: menuLabels.updateViaProxy, - handler: () => onUpdate(2), - disabled: false, - }, - { - label: menuLabels.delete, - handler: () => { - setAnchorEl(null) - if (batchMode) { - if (onSelectionChange) { - onSelectionChange() - } - } else { - setConfirmOpen(true) - } - }, - disabled: false, - }, - ] - const fileModeMenu: ContextMenuItem[] = [ - { - label: menuLabels.select, - handler: onForceSelect, - disabled: false, - }, - { - label: menuLabels.editInfo, - handler: onEditInfo, - disabled: false, - }, - { - label: menuLabels.editFile, - handler: onEditFile, - disabled: false, - }, - { - label: menuLabels.editRules, - handler: onEditRules, - disabled: !option?.rules, - }, - { - label: menuLabels.editProxies, - handler: onEditProxies, - disabled: !option?.proxies, - }, - { - label: menuLabels.editGroups, - handler: onEditGroups, - disabled: !option?.groups, - }, - { - label: menuLabels.extendConfig, - handler: onEditMerge, - disabled: !option?.merge, - }, - { - label: menuLabels.extendScript, - handler: onEditScript, - disabled: !option?.script, - }, - { - label: menuLabels.openFile, - handler: onOpenFile, - disabled: false, - }, - { - label: menuLabels.delete, - handler: () => { - setAnchorEl(null) - if (batchMode) { - if (onSelectionChange) { - onSelectionChange() - } - } else { - setConfirmOpen(true) - } - }, - disabled: false, - }, - ] + // The context menu is closed on almost every render; building its items + // only while open keeps the idle path allocation-free. + const menuItems: ContextMenuItem[] = + anchorEl === null + ? EMPTY_CONTEXT_MENU + : hasUrl + ? [ + ...(hasHome + ? [ + { + label: menuLabels.home, + handler: onOpenHome, + disabled: false, + } satisfies ContextMenuItem, + ] + : []), + { + label: menuLabels.select, + handler: onForceSelect, + disabled: false, + }, + { + label: menuLabels.shareQrCode, + handler: onShareQrCode, + disabled: false, + }, + { + label: menuLabels.editInfo, + handler: onEditInfo, + disabled: false, + }, + { + label: menuLabels.editFile, + handler: onEditFile, + disabled: false, + }, + { + label: menuLabels.editRules, + handler: onEditRules, + disabled: !option?.rules, + }, + { + label: menuLabels.editProxies, + handler: onEditProxies, + disabled: !option?.proxies, + }, + { + label: menuLabels.editGroups, + handler: onEditGroups, + disabled: !option?.groups, + }, + { + label: menuLabels.extendConfig, + handler: onEditMerge, + disabled: !option?.merge, + }, + { + label: menuLabels.extendScript, + handler: onEditScript, + disabled: !option?.script, + }, + { + label: menuLabels.openFile, + handler: onOpenFile, + disabled: false, + }, + { + label: menuLabels.update, + handler: () => onUpdate(0), + disabled: false, + }, + { + label: menuLabels.updateViaProxy, + handler: () => onUpdate(2), + disabled: false, + }, + { + label: menuLabels.delete, + handler: () => { + setAnchorEl(null) + if (batchMode) { + if (onSelectionChange) { + onSelectionChange(id) + } + } else { + setConfirmOpen(true) + } + }, + disabled: false, + }, + ] + : [ + { + label: menuLabels.select, + handler: onForceSelect, + disabled: false, + }, + { + label: menuLabels.editInfo, + handler: onEditInfo, + disabled: false, + }, + { + label: menuLabels.editFile, + handler: onEditFile, + disabled: false, + }, + { + label: menuLabels.editRules, + handler: onEditRules, + disabled: !option?.rules, + }, + { + label: menuLabels.editProxies, + handler: onEditProxies, + disabled: !option?.proxies, + }, + { + label: menuLabels.editGroups, + handler: onEditGroups, + disabled: !option?.groups, + }, + { + label: menuLabels.extendConfig, + handler: onEditMerge, + disabled: !option?.merge, + }, + { + label: menuLabels.extendScript, + handler: onEditScript, + disabled: !option?.script, + }, + { + label: menuLabels.openFile, + handler: onOpenFile, + disabled: false, + }, + { + label: menuLabels.delete, + handler: () => { + setAnchorEl(null) + if (batchMode) { + if (onSelectionChange) { + onSelectionChange(id) + } + } else { + setConfirmOpen(true) + } + }, + disabled: false, + }, + ] const boxStyle = { height: 26, @@ -599,7 +607,7 @@ const ProfileItemBase = (props: ProfileItemProps) => { await profileDocument.reload() return } - onSave?.(profileDocument.savedValue, currentValue) + onSave?.(id, profileDocument.savedValue, currentValue) profileDocument.markSaved(currentValue) }) @@ -614,7 +622,7 @@ const ProfileItemBase = (props: ProfileItemProps) => { await mergeDocument.reload() return } - onSave?.(mergeDocument.savedValue, currentValue) + onSave?.(id, mergeDocument.savedValue, currentValue) mergeDocument.markSaved(currentValue) }) @@ -632,7 +640,7 @@ const ProfileItemBase = (props: ProfileItemProps) => { await scriptDocument.reload() return } - onSave?.(scriptDocument.savedValue, currentValue) + onSave?.(id, scriptDocument.savedValue, currentValue) scriptDocument.markSaved(currentValue) }) @@ -646,7 +654,7 @@ const ProfileItemBase = (props: ProfileItemProps) => { e.stopPropagation() return } - onSelect(false) + onSelect(id, false) }} onContextMenu={(event) => { const { clientX, clientY } = event @@ -687,7 +695,7 @@ const ProfileItemBase = (props: ProfileItemProps) => { onClick={(e) => { e.stopPropagation() if (onSelectionChange) { - onSelectionChange() + onSelectionChange(id) } }} > @@ -853,7 +861,7 @@ const ProfileItemBase = (props: ProfileItemProps) => { e.preventDefault() }} > - {(hasUrl ? urlModeMenu : fileModeMenu).map((item) => ( + {menuItems.map((item) => ( { profileUid={uid!} property={option?.rules ?? ''} open={true} - onSave={onSave} + onSave={(prev, curr) => onSave?.(id, prev, curr)} onClose={() => setRulesOpen(false)} /> )} @@ -906,7 +914,7 @@ const ProfileItemBase = (props: ProfileItemProps) => { profileUid={uid!} property={option?.proxies ?? ''} open={true} - onSave={onSave} + onSave={(prev, curr) => onSave?.(id, prev, curr)} onClose={() => setProxiesOpen(false)} /> )} @@ -917,7 +925,7 @@ const ProfileItemBase = (props: ProfileItemProps) => { profileUid={uid!} property={option?.groups ?? ''} open={true} - onSave={onSave} + onSave={(prev, curr) => onSave?.(id, prev, curr)} onClose={() => { setGroupsOpen(false) }} @@ -963,7 +971,7 @@ const ProfileItemBase = (props: ProfileItemProps) => { onCancel={() => setConfirmOpen(false)} onClose={() => setConfirmOpen(false)} onOk={() => { - onDelete() + onDelete(id) setConfirmOpen(false) }} > diff --git a/src/components/profile/proxies-editor-viewer.tsx b/src/components/profile/proxies-editor-viewer.tsx index 44f5fb7a1..5678b509e 100644 --- a/src/components/profile/proxies-editor-viewer.tsx +++ b/src/components/profile/proxies-editor-viewer.tsx @@ -181,7 +181,7 @@ export const ProxiesEditorViewer = (props: Props) => { // 优化:异步分片解析,避免主线程阻塞,解析完成后批量setState const handleParseAsync = (cb: (proxies: IProxyConfig[]) => void) => { const proxies: IProxyConfig[] = [] - const names: string[] = [] + const names = new Set() let uris: string try { uris = atob(proxyUri) @@ -199,9 +199,9 @@ export const ProxiesEditorViewer = (props: Props) => { const uri = lines[idx] try { const proxy = parseUri(uri.trim()) - if (!names.includes(proxy.name)) { + if (!names.has(proxy.name)) { proxies.push(proxy) - names.push(proxy.name) + names.add(proxy.name) } } catch (err) { console.warn( diff --git a/src/components/proxy/proxy-chain-model.ts b/src/components/proxy/proxy-chain-model.ts index 90ed18e6e..728069240 100644 --- a/src/components/proxy/proxy-chain-model.ts +++ b/src/components/proxy/proxy-chain-model.ts @@ -3,6 +3,7 @@ import * as yaml from 'js-yaml' import { getRecord, rebindNode, + sameSource, type ProxyNodeView, type ProxyViewV1, } from '@/types/proxy-view' @@ -20,22 +21,47 @@ export const rebindProxyChainItems = ( items: readonly ProxyChainItem[], candidates: readonly ProxyNodeView[], proxyView: ProxyViewV1, -): ProxyChainItem[] => - items.map((item) => { +): ProxyChainItem[] => { + // The proxy view refreshes on a fixed cadence; reusing item and array + // identities while the rebound values are equal keeps persistence effects + // and memoized chain rows from reprocessing identical content. + let reboundItems: ProxyChainItem[] | undefined + items.forEach((item, index) => { const rebound = rebindNode(candidates, { name: item.name, source: item.source, }) const record = rebound === undefined ? undefined : getRecord(proxyView, rebound.recordId) - return { + const source = rebound?.source ?? item.source + const type = rebound?.type ?? item.type + const delay = record?.history.at(-1)?.delay + const sourceReused = + item.source === source || + (item.source !== undefined && + source !== undefined && + sameSource(item.source, source)) + + if ( + item.recordId === rebound?.recordId && + sourceReused && + item.type === type && + item.delay === delay + ) { + return + } + + reboundItems ??= [...items] + reboundItems[index] = { ...item, recordId: rebound?.recordId, - source: rebound?.source ?? item.source, - type: rebound?.type ?? item.type, - delay: record?.history.at(-1)?.delay, + source, + type, + delay, } }) + return reboundItems ?? (items as ProxyChainItem[]) +} interface ParsedChainConfig { proxies?: Array<{ diff --git a/src/components/proxy/proxy-group-tools.tsx b/src/components/proxy/proxy-group-tools.tsx index c9da9bcc1..64c224556 100644 --- a/src/components/proxy/proxy-group-tools.tsx +++ b/src/components/proxy/proxy-group-tools.tsx @@ -31,9 +31,9 @@ interface Props { url?: string groupName: string headState: HeadState - onLocation: () => void - onCheckDelay: () => void - onHeadState: (val: Partial) => void + onLocation: (groupName: string) => void + onCheckDelay: (groupName: string) => void + onHeadState: (groupName: string, val: Partial) => void } export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) { @@ -76,7 +76,7 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) { // 因此对写入 headState 的动作做防抖,避免每输入一个字符就过滤一次。 const { run: applyFilter, flush: flushFilter } = useDebounceFn( (state: SearchState) => { - onHeadState({ + onHeadState(groupName, { filterText: state.text, filterMatchCase: state.matchCase, filterMatchWholeWord: state.matchWholeWord, @@ -125,7 +125,7 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) { e.preventDefault() e.stopPropagation() }} - onChange={(e) => onHeadState({ testUrl: e.target.value })} + onChange={(e) => onHeadState(groupName, { testUrl: e.target.value })} sx={{ flex: '1 1 auto', input: { py: 0.65, px: 1 } }} /> )} @@ -155,8 +155,8 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) { e.stopPropagation() if (!headState.open) // eslint-disable-next-line @eslint-react/dom-no-flush-sync - flushSync(() => onHeadState({ open: true })) - onLocation() + flushSync(() => onHeadState(groupName, { open: true })) + onLocation(groupName) }} > @@ -171,16 +171,16 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) { e.stopPropagation() if (!headState.open) // eslint-disable-next-line @eslint-react/dom-no-flush-sync - flushSync(() => onHeadState({ open: true })) + flushSync(() => onHeadState(groupName, { open: true })) // Remind the user that it is custom test url if (testUrl?.trim() && textState !== 'filter') { - onHeadState({ textState: 'url' }) + onHeadState(groupName, { textState: 'url' }) } if (testUrl?.trim() && !isValidUrl(testUrl)) { showNotice.warning('proxies.feedback.warnings.invalidTestUrl') return } - onCheckDelay() + onCheckDelay(groupName) }} > @@ -201,8 +201,8 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) { e.stopPropagation() if (!headState.open) // eslint-disable-next-line @eslint-react/dom-no-flush-sync - flushSync(() => onHeadState({ open: true })) - onHeadState({ + flushSync(() => onHeadState(groupName, { open: true })) + onHeadState(groupName, { sortType: ((sortType + 1) % 3) as ProxySortType, }) }} @@ -219,7 +219,7 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) { onClick={(e) => { e.preventDefault() e.stopPropagation() - onHeadState({ + onHeadState(groupName, { textState: textState === 'url' ? null : 'url', }) setTimeout(() => inputRef.current?.focus()) @@ -245,8 +245,8 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) { e.stopPropagation() if (!headState.open) // eslint-disable-next-line @eslint-react/dom-no-flush-sync - flushSync(() => onHeadState({ open: true })) - onHeadState({ showType: !showType }) + flushSync(() => onHeadState(groupName, { open: true })) + onHeadState(groupName, { showType: !showType }) }} > {showType ? ( @@ -265,8 +265,10 @@ export const ProxyGroupTools = memo(function ProxyGroupTools(props: Props) { e.stopPropagation() if (!headState.open && textState !== 'filter') // eslint-disable-next-line @eslint-react/dom-no-flush-sync - flushSync(() => onHeadState({ open: true })) - onHeadState({ textState: textState === 'filter' ? null : 'filter' }) + flushSync(() => onHeadState(groupName, { open: true })) + onHeadState(groupName, { + textState: textState === 'filter' ? null : 'filter', + }) setTimeout(() => inputRef.current?.focus()) }} > diff --git a/src/components/proxy/proxy-groups-chain.tsx b/src/components/proxy/proxy-groups-chain.tsx index 5b11fe2b0..b2891f87a 100644 --- a/src/components/proxy/proxy-groups-chain.tsx +++ b/src/components/proxy/proxy-groups-chain.tsx @@ -93,7 +93,7 @@ interface ProxyGroupsChainProps { // Shared callbacks onCheckAll: (groupName: string) => void onHeadState: (groupName: string, patch: Partial) => void - onLocation: (group: any) => void + onLocation: (groupName: string) => void onGroupSelect: (groupName: string) => void onScrollToTop: () => void } @@ -245,7 +245,7 @@ function ProxyVirtualList({ activeStickyIndex: number | null isChainMode?: boolean measureElement: (node: Element | null) => void - onLocation: (group: any) => void + onLocation: (groupName: string) => void onCheckAll: (groupName: string) => void onHeadState: (groupName: string, patch: Partial) => void onChangeProxy: (group: ProxyGroupView, member: ResolvedProxyMember) => void diff --git a/src/components/proxy/proxy-groups.tsx b/src/components/proxy/proxy-groups.tsx index 4dc4903e2..d2c569046 100644 --- a/src/components/proxy/proxy-groups.tsx +++ b/src/components/proxy/proxy-groups.tsx @@ -339,16 +339,20 @@ function ChainProxyGroups(props: { scrollTopRef.current = 0 }, []) - const handleLocation = useStableCallback((group: ProxyGroupView) => { - if (!group) return - const { name, now } = group + const handleLocation = useStableCallback((groupName: string) => { + // Flat (type 1) headers such as GLOBAL carry the same live group. + const headerIndex = renderList.findIndex( + (e) => (e.type === 0 || e.type === 1) && e.group?.name === groupName, + ) + const now = renderList[headerIndex]?.group?.now + if (!now) return const index = renderList.findIndex( - (item) => - item.group?.name === name && - ((item.type === 2 && item.member?.member.ref.name === now) || - (item.type === 4 && - item.memberCol?.some(({ member }) => member.ref.name === now))), + (e) => + e.group?.name === groupName && + ((e.type === 2 && e.member?.member.ref.name === now) || + (e.type === 4 && + e.memberCol?.some(({ member }) => member.ref.name === now))), ) if (index >= 0) { @@ -511,13 +515,17 @@ function NormalProxyGroups(props: { mode: string }) { [globalGroupName, select, setHeadState], ) - const handleLocation = useStableCallback((group: ProxyGroupView) => { - if (!group) return - const { name, now } = group + const handleLocation = useStableCallback((groupName: string) => { + // Flat (type 1) headers such as GLOBAL carry the same live group. + const headerIndex = renderList.findIndex( + (e) => (e.type === 0 || e.type === 1) && e.group?.name === groupName, + ) + const now = renderList[headerIndex]?.group?.now + if (!now) return const index = renderList.findIndex( (e) => - e.group?.name === name && + e.group?.name === groupName && ((e.type === 2 && e.member?.member.ref.name === now) || (e.type === 4 && e.memberCol?.some(({ member }) => member.ref.name === now))), @@ -531,21 +539,20 @@ function NormalProxyGroups(props: { mode: string }) { } }) - const handleGroupLocationByName = useCallback( - (groupName: string) => { - const index = renderList.findIndex( - (item) => item.type === 0 && item.group?.name === groupName, - ) + // Stable identity: this feeds the sticky-header render callback; a + // [renderList] dep would re-create it on every list rebuild. + const handleGroupLocationByName = useStableCallback((groupName: string) => { + const index = renderList.findIndex( + (item) => item.type === 0 && item.group?.name === groupName, + ) - if (index >= 0) { - stickyListRef.current?.scrollToIndex(index, { - align: 'start', - behavior: 'smooth', - }) - } - }, - [renderList], - ) + if (index >= 0) { + stickyListRef.current?.scrollToIndex(index, { + align: 'start', + behavior: 'smooth', + }) + } + }) const proxyGroupNames = useMemo(() => { const names = renderList diff --git a/src/components/proxy/proxy-head.tsx b/src/components/proxy/proxy-head.tsx index 99574b36a..23e507682 100644 --- a/src/components/proxy/proxy-head.tsx +++ b/src/components/proxy/proxy-head.tsx @@ -30,9 +30,9 @@ interface Props { url?: string groupName: string headState: HeadState - onLocation: () => void - onCheckDelay: () => void - onHeadState: (val: Partial) => void + onLocation: (groupName: string) => void + onCheckDelay: (groupName: string) => void + onHeadState: (groupName: string, val: Partial) => void } const defaultSx: SxProps = {} @@ -81,7 +81,7 @@ export const ProxyHead = ({ size="small" color="inherit" title={t('proxies.page.tooltips.locate')} - onClick={onLocation} + onClick={() => onLocation(groupName)} > @@ -95,13 +95,13 @@ export const ProxyHead = ({ // Remind the user that it is custom test url if (testUrl?.trim() && textState !== 'filter') { debugLog(`[ProxyHead] 使用自定义测试URL: ${testUrl}`) - onHeadState({ textState: 'url' }) + onHeadState(groupName, { textState: 'url' }) } if (testUrl?.trim() && !isValidUrl(testUrl)) { showNotice.warning('proxies.feedback.warnings.invalidTestUrl') return } - onCheckDelay() + onCheckDelay(groupName) }} > @@ -118,7 +118,9 @@ export const ProxyHead = ({ ][sortType] } onClick={() => - onHeadState({ sortType: ((sortType + 1) % 3) as ProxySortType }) + onHeadState(groupName, { + sortType: ((sortType + 1) % 3) as ProxySortType, + }) } > {sortType !== 1 && sortType !== 2 && } @@ -131,7 +133,9 @@ export const ProxyHead = ({ color="inherit" title={t('proxies.page.tooltips.delayCheckUrl')} onClick={() => - onHeadState({ textState: textState === 'url' ? null : 'url' }) + onHeadState(groupName, { + textState: textState === 'url' ? null : 'url', + }) } > {textState === 'url' ? ( @@ -149,7 +153,7 @@ export const ProxyHead = ({ ? t('proxies.page.tooltips.showBasic') : t('proxies.page.tooltips.showDetail') } - onClick={() => onHeadState({ showType: !showType })} + onClick={() => onHeadState(groupName, { showType: !showType })} > {showType ? : } @@ -159,7 +163,9 @@ export const ProxyHead = ({ color="inherit" title={t('proxies.page.tooltips.filter')} onClick={() => - onHeadState({ textState: textState === 'filter' ? null : 'filter' }) + onHeadState(groupName, { + textState: textState === 'filter' ? null : 'filter', + }) } > {textState === 'filter' ? : } @@ -176,7 +182,7 @@ export const ProxyHead = ({ useRegularExpression: filterUseRegularExpression, }} onSearch={(_, state) => - onHeadState({ + onHeadState(groupName, { filterText: state.text, filterMatchCase: state.matchCase, filterMatchWholeWord: state.matchWholeWord, @@ -197,7 +203,7 @@ export const ProxyHead = ({ size="small" variant="outlined" placeholder={t('proxies.page.placeholders.delayCheckUrl')} - onChange={(e) => onHeadState({ testUrl: e.target.value })} + onChange={(e) => onHeadState(groupName, { testUrl: e.target.value })} sx={{ ml: 0.5, flex: '1 1 auto', input: { py: 0.65, px: 1 } }} /> )} diff --git a/src/components/proxy/proxy-render.tsx b/src/components/proxy/proxy-render.tsx index 6fb01d6b6..09cdb6f3d 100644 --- a/src/components/proxy/proxy-render.tsx +++ b/src/components/proxy/proxy-render.tsx @@ -33,7 +33,7 @@ interface RenderProps { item: IRenderItem stickyed?: boolean isChainMode?: boolean - onLocation: (group: IRenderItem['group']) => void + onLocation: (groupName: string) => void onCheckAll: (groupName: string) => void onHeadState: (groupName: string, patch: Partial) => void onChangeProxy: ( @@ -179,9 +179,9 @@ const ProxyGroupHeader = (props: RenderProps) => { url={group.testUrl!} groupName={group.name} headState={headState!} - onLocation={() => onLocation(group)} - onCheckDelay={() => onCheckAll(group.name)} - onHeadState={(p) => onHeadState(group.name, p)} + onLocation={onLocation} + onCheckDelay={onCheckAll} + onHeadState={onHeadState} /> {!toolsOnLeft && proxyCount} @@ -270,9 +270,9 @@ export const ProxyRender = memo(function ProxyRender(props: RenderProps) { url={group.testUrl!} groupName={group.name} headState={headState!} - onLocation={() => onLocation(group)} - onCheckDelay={() => onCheckAll(group.name)} - onHeadState={(p) => onHeadState(group.name, p)} + onLocation={onLocation} + onCheckDelay={onCheckAll} + onHeadState={onHeadState} /> ) } diff --git a/src/components/proxy/use-render-list.ts b/src/components/proxy/use-render-list.ts index 116f73972..f1149c150 100644 --- a/src/components/proxy/use-render-list.ts +++ b/src/components/proxy/use-render-list.ts @@ -175,15 +175,19 @@ export const useRenderList = ( chainOccurrencesRef.current = chainOccurrences const chainDelayGroup = mode === 'rule' && selectedGroup ? selectedGroup : CHAIN_DELAY_GROUP - const chainDelayKey = chainOccurrences - .map(({ member }) => { - if (member.kind !== 'node') return `${member.kind}:${member.ref.name}` - const source = member.node.source - return source.kind === 'provider' - ? `provider:${source.providerName}:${source.proxyName}` - : `core:${source.proxyName}` - }) - .join('\u0000') + const chainDelayKey = useMemo( + () => + chainOccurrences + .map(({ member }) => { + if (member.kind !== 'node') return `${member.kind}:${member.ref.name}` + const source = member.node.source + return source.kind === 'provider' + ? `provider:${source.providerName}:${source.proxyName}` + : `core:${source.proxyName}` + }) + .join('\u0000'), + [chainOccurrences], + ) useEffect(() => { if (!isChainMode || !chainDelayKey) return diff --git a/src/components/setting/mods/dns-viewer.tsx b/src/components/setting/mods/dns-viewer.tsx index a6cace3ea..f0282a7ba 100644 --- a/src/components/setting/mods/dns-viewer.tsx +++ b/src/components/setting/mods/dns-viewer.tsx @@ -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 function parseNameserverPolicy(str: string): NameserverPolicy { @@ -520,9 +539,21 @@ export function DnsViewer({ ref }: { ref?: Ref }) { } }) - 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 }) { 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} /> )} diff --git a/src/components/setting/mods/layout-viewer.tsx b/src/components/setting/mods/layout-viewer.tsx index b11d17f17..eb26d9af8 100644 --- a/src/components/setting/mods/layout-viewer.tsx +++ b/src/components/setting/mods/layout-viewer.tsx @@ -121,7 +121,7 @@ export const LayoutViewer = forwardRef((_, ref) => { showNotice.error(err) } const onChangeData = (patch: Partial) => { - mutateVerge({ ...verge, ...patch }) + mutateVerge((prev) => ({ ...prev, ...patch })) } return ( diff --git a/src/components/setting/mods/sysproxy-viewer.tsx b/src/components/setting/mods/sysproxy-viewer.tsx index 3ea4f3bc8..bb6894a81 100644 --- a/src/components/setting/mods/sysproxy-viewer.tsx +++ b/src/components/setting/mods/sysproxy-viewer.tsx @@ -328,7 +328,7 @@ export const SysproxyViewer = forwardRef((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) diff --git a/src/components/setting/mods/update-viewer.tsx b/src/components/setting/mods/update-viewer.tsx index 8fdb59adb..648fd55f9 100644 --- a/src/components/setting/mods/update-viewer.tsx +++ b/src/components/setting/mods/update-viewer.tsx @@ -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 ( + { + 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} + + ) + }, + blockquote: ({ className, children }) => { + const alertType = getAlertTypeFromClassName(className) + + if (!alertType) { + return
{children}
+ } + + return ( + { + 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} + + ) + }, +} + 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 }) { }) 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 }) { ) as Record, [t], ) - const remarkGitHubAlertsPlugin = useMemo( - () => () => remarkGitHubAlerts(githubAlertLabels), + const remarkPlugins = useMemo( + () => [() => remarkGitHubAlerts(githubAlertLabels)], [githubAlertLabels], ) @@ -472,83 +546,8 @@ export function UpdateViewer({ ref }: { ref?: Ref }) { {open && ( }> { - const isFragment = href?.startsWith('#') ?? false - const renderedHref = isFragment - ? `#${UPDATE_MARKDOWN_ID_PREFIX}${href?.slice(1)}` - : href - ? '#' - : undefined - - return ( - { - 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} - - ) - }, - blockquote: ({ className, children }) => { - const alertType = getAlertTypeFromClassName(className) - - if (!alertType) { - return ( -
{children}
- ) - } - - return ( - { - 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} - - ) - }, - }} + remarkPlugins={remarkPlugins} + components={MARKDOWN_COMPONENTS} > {markdownContent}
diff --git a/src/components/setting/setting-system.tsx b/src/components/setting/setting-system.tsx index 3bf356d28..613ad7883 100644 --- a/src/components/setting/setting-system.tsx +++ b/src/components/setting/setting-system.tsx @@ -20,7 +20,7 @@ const SettingSystem = ({ onError }: Props) => { const { enable_auto_launch, enable_silent_start } = verge ?? {} const onChangeData = (patch: Partial) => { - mutateVerge({ ...verge, ...patch }) + mutateVerge((prev) => ({ ...prev, ...patch })) } return ( diff --git a/src/components/setting/setting-verge-basic.tsx b/src/components/setting/setting-verge-basic.tsx index 9fdf33091..d593f596b 100644 --- a/src/components/setting/setting-verge-basic.tsx +++ b/src/components/setting/setting-verge-basic.tsx @@ -72,7 +72,7 @@ const SettingVergeBasic = ({ onError }: Props) => { const backupRef = useRef(null) const onChangeData = (patch: any) => { - mutateVerge({ ...verge, ...patch }) + mutateVerge((prev) => ({ ...prev, ...patch })) } const onCopyClashEnv = useCallback(async () => { diff --git a/src/components/setting/settings-search.tsx b/src/components/setting/settings-search.tsx index dc62b021c..71d16d83a 100644 --- a/src/components/setting/settings-search.tsx +++ b/src/components/setting/settings-search.tsx @@ -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 = () => diff --git a/src/components/shared/proxy-control-switches.tsx b/src/components/shared/proxy-control-switches.tsx index 8d085f36d..844d320cc 100644 --- a/src/components/shared/proxy-control-switches.tsx +++ b/src/components/shared/proxy-control-switches.tsx @@ -163,7 +163,7 @@ const ProxyControlSwitches = ({ }) return false } - mutateVerge({ ...verge, enable_tun_mode: value }) + mutateVerge((prev) => ({ ...prev, enable_tun_mode: value })) await patchVerge({ enable_tun_mode: value }) } diff --git a/src/hooks/use-log-data.ts b/src/hooks/use-log-data.ts index e954457f3..cda396747 100644 --- a/src/hooks/use-log-data.ts +++ b/src/hooks/use-log-data.ts @@ -12,6 +12,9 @@ const FLUSH_DELAY_MS = 50 type LogType = ILogItem['type'] const DEFAULT_LOG_TYPES: LogType[] = ['debug', 'info', 'warning', 'error'] +// Shared empty fallback: a fresh [] would give `refresh` a new identity on +// every render and re-run the snapshot effect while logs stream. +const EMPTY_LOGS: ILogItem[] = [] const LOG_LEVEL_FILTERS: Record = { DEBUG: DEFAULT_LOG_TYPES, INFO: ['info', 'warning', 'error'], @@ -55,7 +58,7 @@ export const useLogData = () => { const { response, refresh, setData } = useMihomoWsSubscription({ subscriptionKey: enableLog ? 'getClashLog' : null, - fallbackData: [], + fallbackData: EMPTY_LOGS, connect: () => MihomoWebSocket.connect_logs(logLevel), setupHandlers: ({ next, scheduleReconnect, isMounted }) => { let flushTimer: ReturnType | null = null diff --git a/src/hooks/use-proxy-delay-state.ts b/src/hooks/use-proxy-delay-state.ts index 612b33d24..e600dd41d 100644 --- a/src/hooks/use-proxy-delay-state.ts +++ b/src/hooks/use-proxy-delay-state.ts @@ -61,7 +61,7 @@ export function useProxyDelayState( } const cachedUpdate = delayManager.getDelayUpdate(name, groupName) if (cachedUpdate) { - setDelayState({ ...cachedUpdate }) + setDelayState(cachedUpdate) return } diff --git a/src/hooks/use-verge.ts b/src/hooks/use-verge.ts index 553c558b6..6d3561dfa 100644 --- a/src/hooks/use-verge.ts +++ b/src/hooks/use-verge.ts @@ -3,12 +3,16 @@ import { useCallback } from 'react' import { getVergeConfig, patchVergeConfig } from '@/services/cmds' import { mutate } from '@/services/mutate' import { getPreloadConfig, setPreloadConfig } from '@/services/preload' -import { setCacheData, useQuery } from '@/services/query-client' +import { + revalidateQuery, + setCacheData, + useQuery, +} from '@/services/query-client' export const useVerge = () => { const initialVergeConfig = getPreloadConfig() - const { data: verge, refetch } = useQuery({ + const { data: verge } = useQuery({ queryKey: ['getVergeConfig'], queryFn: async () => { const config = await getVergeConfig() @@ -20,23 +24,25 @@ export const useVerge = () => { staleTime: 5000, }) - const mutateVerge = ( - updaterOrData?: - | IVergeConfig - | ((prev: IVergeConfig | undefined) => IVergeConfig | undefined) - | undefined, - ) => { - if (updaterOrData === undefined) { - void refetch() - return - } - void setCacheData( - ['getVergeConfig'], - typeof updaterOrData === 'function' - ? (current) => updaterOrData(current ?? verge) - : updaterOrData, - ) - } + // Stable identity: many consumers list mutateVerge in their own callback + // deps, so a per-render closure here would churn their memoization too. + // The updater receives the live cache value (preload snapshot when the + // cache is still empty) instead of a render-time snapshot, so an older + // render cannot clobber a newer cache write. + const mutateVerge = useCallback( + ( + updater?: (prev: IVergeConfig | undefined) => IVergeConfig | undefined, + ) => { + if (updater === undefined) { + void revalidateQuery(['getVergeConfig']) + return + } + void setCacheData(['getVergeConfig'], (current) => + updater(current ?? getPreloadConfig() ?? undefined), + ) + }, + [], + ) // Callers own the error toast (GuardState onCatch / page onError), so the // funnel must not add a second one. diff --git a/src/pages/profiles.tsx b/src/pages/profiles.tsx index c46bdf2df..3f032ae50 100644 --- a/src/pages/profiles.tsx +++ b/src/pages/profiles.tsx @@ -462,9 +462,12 @@ const ProfilePage = () => { [runProfileSwitchQueue], ) - const onSelect = async (profile: string, force: boolean) => { - await activateProfile(profile, true, force) - } + const onSelect = useCallback( + async (profile: string, force: boolean) => { + await activateProfile(profile, true, force) + }, + [activateProfile], + ) useEffect(() => { let cancelled = false @@ -594,7 +597,7 @@ const ProfilePage = () => { } } - const toggleProfileSelection = (uid: string) => { + const toggleProfileSelection = useCallback((uid: string) => { setSelectedProfiles((prev) => { const newSet = new Set(prev) if (newSet.has(uid)) { @@ -604,7 +607,40 @@ const ProfilePage = () => { } return newSet }) - } + }, []) + + // Item-grid callbacks stay identity-stable so ProfileItem's memo holds + // across unrelated page state (URL input keystrokes, switch spinners). + // onEnhance/onDelete are useLockFn wrappers whose identity changes every + // render, so they are read through refs here. + const onEnhanceRef = useRef(onEnhance) + onEnhanceRef.current = onEnhance + const onDeleteRef = useRef(onDelete) + onDeleteRef.current = onDelete + + const handleItemEdit = useCallback((item: IProfileItem) => { + viewerRef.current?.edit(item) + }, []) + + const handleItemSave = useCallback( + async (uid: string, prev?: string, curr?: string) => { + if (prev !== curr && profiles.current === uid) { + await onEnhanceRef.current(false) + } + }, + [profiles], + ) + + const handleItemDelete = useCallback( + (uid: string) => { + if (batchMode) { + toggleProfileSelection(uid) + } else { + onDeleteRef.current(uid) + } + }, + [batchMode, toggleProfileSelection], + ) const selectAllProfiles = () => { setSelectedProfiles(new Set(profileItems.map((item) => item.uid!))) @@ -908,23 +944,13 @@ const ProfilePage = () => { completedUpdateRevisions.get(item.uid!) ?? 0 } mutateProfiles={mutateProfiles} - onSelect={(f) => onSelect(item.uid!, f)} - onEdit={() => viewerRef.current?.edit(item)} - onSave={async (prev, curr) => { - if (prev !== curr && profiles.current === item.uid) { - await onEnhance(false) - } - }} - onDelete={() => { - if (batchMode) { - toggleProfileSelection(item.uid!) - } else { - onDelete(item.uid!) - } - }} + onSelect={onSelect} + onEdit={handleItemEdit} + onSave={handleItemSave} + onDelete={handleItemDelete} batchMode={batchMode} isSelected={selectedProfiles.has(item.uid!)} - onSelectionChange={() => toggleProfileSelection(item.uid!)} + onSelectionChange={toggleProfileSelection} /> ))} diff --git a/src/services/delay.ts b/src/services/delay.ts index 6260005f0..10ac8a1e8 100644 --- a/src/services/delay.ts +++ b/src/services/delay.ts @@ -237,7 +237,9 @@ class DelayManager { return undefined } - return { ...entry } + // Entries are replaced, never mutated, so the cached object is shared + // directly; readers treat it as immutable. + return entry } getDelay(name: string, group: string) { diff --git a/src/types/proxy-view.ts b/src/types/proxy-view.ts index cebd34f4f..9b68ac6d2 100644 --- a/src/types/proxy-view.ts +++ b/src/types/proxy-view.ts @@ -156,7 +156,7 @@ export const selectRuleChainMembers = ( }) } -const sameSource = ( +export const sameSource = ( left: ProxyNodeView['source'], right: ProxyNodeView['source'], ) => diff --git a/src/utils/traffic-sampler.ts b/src/utils/traffic-sampler.ts index 94ded4797..942a2d6ad 100644 --- a/src/utils/traffic-sampler.ts +++ b/src/utils/traffic-sampler.ts @@ -145,10 +145,10 @@ export class TrafficDataSampler { ) { rawStart++ } - const rawData = this.rawBuffer.slice(rawStart) + const rawCount = this.rawBuffer.length - rawStart if (minutes <= this.config.rawDataMinutes) { - return rawData + return this.rawBuffer.slice(rawStart) } const compressedCutoffUpper = @@ -161,19 +161,40 @@ export class TrafficDataSampler { ) { compressedStart++ } + let compressedEnd = compressedStart + while ( + compressedEnd < this.compressedBuffer.length && + this.compressedBuffer[compressedEnd].timestamp <= compressedCutoffUpper + ) { + compressedEnd++ + } - const compressedData = this.compressedBuffer - .slice(compressedStart) - .filter((p) => p.timestamp <= compressedCutoffUpper) - .map((p) => ({ - up: p.up, - down: p.down, - timestamp: p.timestamp, - })) + // Single preallocated result; raw entries keep their stored identity. + const compressedCount = compressedEnd - compressedStart + const result: ITrafficDataPoint[] = new Array(compressedCount + rawCount) + for (let i = 0; i < compressedCount; i++) { + const point = this.compressedBuffer[compressedStart + i] + result[i] = { + up: point.up, + down: point.down, + timestamp: point.timestamp, + } + } + for (let i = 0; i < rawCount; i++) { + result[compressedCount + i] = this.rawBuffer[rawStart + i] + } - return [...compressedData, ...rawData].sort( - (a, b) => a.timestamp - b.timestamp, - ) + // Compressed points precede raw ones except across the trim boundary; + // sort only when the two ranges actually interleave. + if ( + compressedCount > 0 && + rawCount > 0 && + this.compressedBuffer[compressedEnd - 1].timestamp > + this.rawBuffer[rawStart].timestamp + ) { + result.sort((a, b) => a.timestamp - b.timestamp) + } + return result } getStats(): ISamplerStats {