Skip to content

Commit

Permalink
[Documentation][lexical-website]: Documentation for useLexical node s…
Browse files Browse the repository at this point in the history
…election hook (facebook#6976)
  • Loading branch information
Kingscliq authored Dec 18, 2024
1 parent ad7187d commit 62b3713
Showing 1 changed file with 30 additions and 4 deletions.
34 changes: 30 additions & 4 deletions packages/lexical-react/src/useLexicalNodeSelection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,23 +18,48 @@ import {
} from 'lexical';
import {useCallback, useEffect, useState} from 'react';

/**
* A helper function to determine if a specific node is selected in a Lexical editor.
*
* @param {LexicalEditor} editor - The LexicalEditor instance.
* @param {NodeKey} key - The key of the node to check.
* @returns {boolean} Whether the node is selected.
*/

function isNodeSelected(editor: LexicalEditor, key: NodeKey): boolean {
return editor.getEditorState().read(() => {
const node = $getNodeByKey(key);

if (node === null) {
return false;
return false; // Node doesn't exist, so it's not selected.
}

return node.isSelected();
return node.isSelected(); // Check if the node is selected.
});
}

/**
* A custom hook to manage the selection state of a specific node in a Lexical editor.
*
* This hook provides utilities to:
* - Check if a node is selected.
* - Update its selection state.
* - Clear the selection.
*
* @param {NodeKey} key - The key of the node to track selection for.
* @returns {[boolean, (selected: boolean) => void, () => void]} A tuple containing:
* - `isSelected` (boolean): Whether the node is currently selected.
* - `setSelected` (function): A function to set the selection state of the node.
* - `clearSelected` (function): A function to clear the selection of the node.
*
*/

export function useLexicalNodeSelection(
key: NodeKey,
): [boolean, (arg0: boolean) => void, () => void] {
): [boolean, (selected: boolean) => void, () => void] {
const [editor] = useLexicalComposerContext();

// State to track whether the node is currently selected.
const [isSelected, setIsSelected] = useState(() =>
isNodeSelected(editor, key),
);
Expand All @@ -48,7 +73,7 @@ export function useLexicalNodeSelection(
});

return () => {
isMounted = false;
isMounted = false; // Prevent updates after component unmount.
unregister();
};
}, [editor, key]);
Expand All @@ -62,6 +87,7 @@ export function useLexicalNodeSelection(
selection = $createNodeSelection();
$setSelection(selection);
}

if ($isNodeSelection(selection)) {
if (selected) {
selection.add(key);
Expand Down

0 comments on commit 62b3713

Please sign in to comment.