@@ -320,20 +320,43 @@ function applyFromToolbar(event: Event) {
320320 applyStyle ( target , style )
321321}
322322
323+ function setFocusManagement ( toolbar : MarkdownToolbarElement ) {
324+ toolbar . addEventListener ( 'keydown' , focusKeydown )
325+ toolbar . setAttribute ( 'tabindex' , '0' )
326+ toolbar . addEventListener ( 'focus' , onToolbarFocus , { once : true } )
327+ }
328+
329+ function unsetFocusManagement ( toolbar : MarkdownToolbarElement ) {
330+ toolbar . removeEventListener ( 'keydown' , focusKeydown )
331+ toolbar . removeAttribute ( 'tabindex' )
332+ toolbar . removeEventListener ( 'focus' , onToolbarFocus )
333+ }
334+
323335class MarkdownToolbarElement extends HTMLElement {
336+ static observedAttributes = [ 'data-no-focus' ]
337+
324338 connectedCallback ( ) : void {
325339 if ( ! this . hasAttribute ( 'role' ) ) {
326340 this . setAttribute ( 'role' , 'toolbar' )
327341 }
328- this . addEventListener ( 'keydown' , focusKeydown )
329- this . setAttribute ( 'tabindex' , '0' )
330- this . addEventListener ( 'focus' , onToolbarFocus , { once : true } )
342+ if ( ! this . hasAttribute ( 'data-no-focus' ) ) {
343+ setFocusManagement ( this )
344+ }
331345 this . addEventListener ( 'keydown' , keydown ( applyFromToolbar ) )
332346 this . addEventListener ( 'click' , applyFromToolbar )
333347 }
334348
349+ attributeChangedCallback ( name : string , oldValue : string , newValue : string ) : void {
350+ if ( name !== 'data-no-focus' ) return
351+ if ( newValue === null ) {
352+ setFocusManagement ( this )
353+ } else {
354+ unsetFocusManagement ( this )
355+ }
356+ }
357+
335358 disconnectedCallback ( ) : void {
336- this . removeEventListener ( 'keydown' , focusKeydown )
359+ unsetFocusManagement ( this )
337360 }
338361
339362 get field ( ) : HTMLTextAreaElement | null {
@@ -350,7 +373,6 @@ class MarkdownToolbarElement extends HTMLElement {
350373
351374function onToolbarFocus ( { target} : FocusEvent ) {
352375 if ( ! ( target instanceof Element ) ) return
353- if ( target . hasAttribute ( 'data-no-focus' ) ) return
354376 target . removeAttribute ( 'tabindex' )
355377 let tabindex = '0'
356378 for ( const button of getButtons ( target ) ) {
@@ -367,7 +389,6 @@ function focusKeydown(event: KeyboardEvent) {
367389 if ( key !== 'ArrowRight' && key !== 'ArrowLeft' && key !== 'Home' && key !== 'End' ) return
368390 const toolbar = event . currentTarget
369391 if ( ! ( toolbar instanceof HTMLElement ) ) return
370- if ( toolbar . hasAttribute ( 'data-no-focus' ) ) return
371392 const buttons = getButtons ( toolbar )
372393 const index = buttons . indexOf ( event . target as HTMLElement )
373394 const length = buttons . length
0 commit comments