11import * as React from 'react' ;
2- import { useEffect , useState } from 'react' ;
2+ import { useState } from 'react' ;
33import {
44 List ,
55 ListItem ,
@@ -10,6 +10,7 @@ import {
1010} from '@mui/material' ;
1111import { styled } from '@mui/material/styles' ;
1212import ArrowDropDownIcon from '@mui/icons-material/ArrowDropDown' ;
13+ import { useEditorState } from '@tiptap/react' ;
1314import { useTranslate } from 'ra-core' ;
1415import clsx from 'clsx' ;
1516import { useTiptapEditor } from '../useTiptapEditor' ;
@@ -21,7 +22,23 @@ export const LevelSelect = (props: LevelSelectProps) => {
2122 null
2223 ) ;
2324 const { size } = props ;
24- const [ selectedOption , setSelectedOption ] = useState ( options [ 0 ] ) ;
25+
26+ const selectedOption = useEditorState ( {
27+ editor,
28+ selector : ( { editor } ) => {
29+ if ( ! editor ) return options [ 0 ] ;
30+ return (
31+ options . find ( option => {
32+ if ( option . value === 'paragraph' ) {
33+ return editor . isActive ( 'paragraph' ) ;
34+ }
35+ return editor . isActive ( 'heading' , {
36+ level : ( option as HeadingLevelOption ) . level ,
37+ } ) ;
38+ } ) ?? options [ 0 ]
39+ ) ;
40+ } ,
41+ } ) ;
2542
2643 const handleMenuItemClick = (
2744 event : React . MouseEvent < HTMLLIElement , MouseEvent > ,
@@ -50,44 +67,6 @@ export const LevelSelect = (props: LevelSelectProps) => {
5067 setAnchorElement ( null ) ;
5168 } ;
5269
53- useEffect ( ( ) => {
54- const handleUpdate = ( ) => {
55- setSelectedOption ( currentOption =>
56- options . reduce ( ( acc , option ) => {
57- if ( editor ) {
58- if (
59- option . value === 'paragraph' &&
60- editor . isActive ( 'paragraph' )
61- ) {
62- return option ;
63- }
64-
65- if (
66- editor . isActive ( 'heading' , {
67- level : ( option as HeadingLevelOption ) . level ,
68- } )
69- ) {
70- return option ;
71- }
72- }
73- return acc ;
74- } , currentOption )
75- ) ;
76- } ;
77-
78- if ( editor ) {
79- editor . on ( 'update' , handleUpdate ) ;
80- editor . on ( 'selectionUpdate' , handleUpdate ) ;
81- }
82-
83- return ( ) => {
84- if ( editor ) {
85- editor . off ( 'update' , handleUpdate ) ;
86- editor . off ( 'selectionUpdate' , handleUpdate ) ;
87- }
88- } ;
89- } , [ editor ] ) ;
90-
9170 return (
9271 < Root >
9372 < List
0 commit comments