Skip to content

Instantly share code, notes, and snippets.

@fantactuka
Last active November 15, 2024 15:32
Show Gist options
  • Save fantactuka/32e0be49a66d6a99ec12e59b8874e08f to your computer and use it in GitHub Desktop.
Save fantactuka/32e0be49a66d6a99ec12e59b8874e08f to your computer and use it in GitHub Desktop.
hook useLexicalNode<TReturn, TNode: LexicalNode>(
nodeKey: NodeKey,
callback: (TNode | null) => TReturn,
predicate: (node: LexicalNode | null) => node is TNode,
): TReturn {
return useLexicalSubscription<TReturn>((editor: LexicalEditor) => {
const getValue = () => {
return editor.read(() => {
const node = $getNodeByKey<LexicalNode>(nodeKey);
return callback(predicate(node) ? node : null);
});
};
return {
initialValueFn() {
return getValue();
},
subscribe(setValue) {
return editor.registerUpdateListener(() => {
setValue(getValue());
});
},
};
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment