import React, { useEffect, useRef } from 'react' import type { CellParams } from '../types' export type GridCellFocusHealProps = { hasFocus: boolean CellRenderer: React.ComponentType> cellRendererProps: CellParams parentRef: React.MutableRefObject } export const GridCellFocusHeal = ({ CellRenderer, cellRendererProps, parentRef, hasFocus, }: GridCellFocusHealProps) => { const hadFocusBeforeRender = useRef(false) if (parentRef.current) { hadFocusBeforeRender.current = parentRef.current.contains( document.activeElement ) } useEffect(() => { if (parentRef.current && hadFocusBeforeRender.current) { /* Chrome will consistently fall back to document.body whereas Firefox/Safari will fallback to another element in the same parent if possible */ const needsFocusHeal = hasFocus && (document.activeElement === document.body || (parentRef.current.contains(document.activeElement) && document.activeElement?.getAttribute('tabindex') !== '0')) if (needsFocusHeal) { parentRef.current .querySelector(`[tabindex="0"]`) ?.focus({ preventScroll: true }) } } }) return }