"use client"; import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext"; import { $isTableCellNode, $isTableSelection } from "@lexical/table"; import { $getSelection } from "lexical"; import { useEffect, useRef } from "react"; const SELECTED_CELL_CLASS = "lexical-table-cell-selected"; export function TableSelectionHighlightPlugin(): null { const [editor] = useLexicalComposerContext(); const highlightedElementsRef = useRef>(new Set()); useEffect(() => { const clearHighlights = () => { for (const element of highlightedElementsRef.current) { element.classList.remove(SELECTED_CELL_CLASS); } highlightedElementsRef.current.clear(); }; return editor.registerUpdateListener(({ editorState }) => { const selectedCellKeys = new Set(); editorState.read(() => { const selection = $getSelection(); if (!$isTableSelection(selection)) return; for (const node of selection.getNodes()) { if ($isTableCellNode(node)) { selectedCellKeys.add(node.getKey()); } } }); clearHighlights(); for (const key of selectedCellKeys) { const element = editor.getElementByKey(key); if (element instanceof HTMLElement) { element.classList.add(SELECTED_CELL_CLASS); highlightedElementsRef.current.add(element); } } }); }, [editor]); return null; }