1- import React , { memo , useEffect , useMemo , useReducer , useRef } from 'react'
1+ import React , { useMemo , useRef } from 'react'
22import {
33 Undo2 ,
44 Redo2 ,
@@ -25,23 +25,13 @@ import {
2525} from 'lucide-react'
2626import styles from './index.module.less'
2727
28- function Toolbar ( { editor, viewMode, onChangeViewMode } ) {
28+ // editorKey 参数用于触发重新渲染,确保工具栏高亮状态更新
29+ function Toolbar ( { editor, viewMode, onChangeViewMode, editorKey } ) {
2930 const fileInputRef = useRef ( null )
3031 const iconSize = 18
31- const [ , forceRerender ] = useReducer ( ( x ) => x + 1 , 0 )
3232
33- useEffect ( ( ) => {
34- if ( ! editor ) return
35-
36- const rerender = ( ) => forceRerender ( )
37- editor . on ( 'selectionUpdate' , rerender )
38- editor . on ( 'transaction' , rerender )
39-
40- return ( ) => {
41- editor . off ( 'selectionUpdate' , rerender )
42- editor . off ( 'transaction' , rerender )
43- }
44- } , [ editor ] )
33+ // editorKey 变化时强制重新计算
34+ void editorKey
4535
4636 const handleAction = ( cmd , opt ) => {
4737 if ( ! editor ) return
@@ -114,16 +104,26 @@ function Toolbar({ editor, viewMode, onChangeViewMode }) {
114104
115105 if ( ! editor ) return null
116106
117- const isBtnActive = ( cmd , opt ) => {
118- if ( cmd === 'heading' ) {
119- const level = parseInt ( opt , 10 )
120- if ( ! isNaN ( level ) ) return editor . isActive ( 'heading' , { level } )
121- }
122- if ( cmd === 'textAlign' ) {
123- if ( opt ) return editor . isActive ( 'textAlign' , { textAlign : opt } )
107+ // 检查按钮是否处于激活状态
108+ const checkActive = ( cmd , opt ) => {
109+ if ( ! editor || ! editor . isActive ) return false
110+ try {
111+ if ( cmd === 'heading' ) {
112+ const level = Number ( opt )
113+ // 必须严格检查当前是否是指定级别的 heading
114+ return level >= 1 && level <= 6 && editor . isActive ( 'heading' , { level } )
115+ }
116+ if ( cmd === 'textAlign' ) {
117+ return opt ? editor . isActive ( { textAlign : opt } ) : false
118+ }
119+ if ( cmd === 'link' ) {
120+ return editor . isActive ( 'link' )
121+ }
122+ // 对于其他命令,直接检查
123+ return editor . isActive ( cmd )
124+ } catch {
125+ return false
124126 }
125- if ( cmd === 'link' ) return editor . isActive ( 'link' )
126- return editor . isActive ( cmd )
127127 }
128128
129129 return (
@@ -151,7 +151,7 @@ function Toolbar({ editor, viewMode, onChangeViewMode }) {
151151 if ( btn . type === 'separator' ) {
152152 return < div key = { `sep-${ idx } ` } className = { styles . mdxSeparator } />
153153 }
154- const isActive = isBtnActive ( btn . cmd , btn . opt )
154+ const isActive = checkActive ( btn . cmd , btn . opt )
155155 return (
156156 < button
157157 key = { `${ btn . cmd } -${ idx } ` }
@@ -195,4 +195,4 @@ function Toolbar({ editor, viewMode, onChangeViewMode }) {
195195 )
196196}
197197
198- export default memo ( Toolbar )
198+ export default Toolbar
0 commit comments