Feature: Implement lint rule about using node variable in update closure
- Dominant language
- TypeScript
- Stars
- 23.9k
- Forks
- 2.2k
- Avg merge
- 1d 14h
- Merged PRs (30d)
- 57
Description
## Description
In some cases, a variable within an update may be closed with a node, especially in the context of React. A contrived example:
```js
const [sourceNode, setSourceNode] = useState(null)
const [editor] = useLexicalComposerContext();
const handleClick() => {
if (!sourceNode) return;
editor.update(() => {
sourceNode.selectEnd();
});
}
```
The pitfall of this code is that, despite checking for the presence of the `sourceNode`, it may be missing from the LexicalState for some reason during an update. The correct pattern would be to check via the `isAttached()` method
```diff
- if (!sourceNode) return;
+ if (!sourceNode || !sourceNode.isAttached()) return;
```
or to store the key and check via `$getNodeByKey`
```diff
-const [sourceNode, setSourceNode] = useState(null)
+const [sourceNodeKey, setSourceNodeKey] = useState()
const [editor] = useLexicalComposerContext();
const handleClick() => {
+ const sourceNode = $getNodeByKey(sourceNodeKey);
if (!sourceNode) return;
editor.update(() => {
sourceNode.selectEnd();
});
}
```
Otherwise, if the node is detached from the state, [the exception will be thrown](https://github.com/facebook/lexical/blob/v0.50.0/packages/lexical/src/LexicalNode.ts#L1393):
```
Lexical node does not exist in active editor state.
Avoid using the same node references between nested closures from editorState.read/editor.update.
```
## Impact
A lint rule would prevent such potential errors and allow for safer code handling of state. A similar error can occur not only during updating, but also during reading of state
Contributor guide
Research direction
Start by reading packages/lexical/src/LexicalNode.ts around the referenced exception, then inspect the repository's existing lint rules and their tests to find the appropriate entry point. Done means the rule identifies unsafe node references captured by editor.update or editorState.read closures and has coverage for the examples described in the issue.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- react, typescript
- Domain
- tooling
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Active
- Clarity
- Mostly clear
- Newbie friendliness
- 55/100