Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[lexical] Feature: add a generic state property to all nodes #7117

Open
wants to merge 26 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
a6288f9
state to lexicalNode
GermanJablo Dec 19, 2024
a90a719
Squashed commit of the following:
GermanJablo Jan 30, 2025
448e2af
first version with default value
GermanJablo Jan 30, 2025
bf70110
make state json serializable
GermanJablo Jan 30, 2025
6ebd4e5
add import and export json tests
GermanJablo Jan 30, 2025
e46d735
getState returns immutable types
GermanJablo Jan 31, 2025
e404d32
fix tests
GermanJablo Jan 31, 2025
c1cfce4
Merge remote-tracking branch 'origin/main' into state
GermanJablo Jan 31, 2025
6d00c64
add docs
GermanJablo Jan 31, 2025
e0c5945
remove readonly property
GermanJablo Jan 31, 2025
7728780
add paragraph in docs about json serializable values
GermanJablo Jan 31, 2025
d807d4f
better example in docs. getState does not necessarily return undefined.
GermanJablo Jan 31, 2025
90a032b
use $createTextNode()
GermanJablo Jan 31, 2025
c663540
fix type
GermanJablo Jan 31, 2025
113a4f1
create a new object in setState
GermanJablo Jan 31, 2025
91148f3
fix unit test
GermanJablo Jan 31, 2025
47435b0
Update packages/lexical/src/LexicalNode.ts
GermanJablo Jan 31, 2025
fb7e164
Update packages/lexical/src/LexicalNode.ts
GermanJablo Jan 31, 2025
eab152e
Update packages/lexical/src/LexicalNode.ts
GermanJablo Jan 31, 2025
d2b4f21
Update packages/lexical/src/LexicalNode.ts
GermanJablo Jan 31, 2025
2bc4a0e
add null to State type, fix parse function in test
GermanJablo Feb 3, 2025
fca2071
add Bob's test about previous reconciled versions of the node
GermanJablo Feb 3, 2025
8cf6855
improve parse functions in tests again
GermanJablo Feb 3, 2025
abd3d3e
add stateStore to register state keys
GermanJablo Feb 3, 2025
3f8bba0
BIG CHANGE - state as class
GermanJablo Feb 7, 2025
4624e2f
improvements
GermanJablo Feb 10, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,10 @@ module.exports = {
],
'@typescript-eslint/ban-ts-comment': OFF,
'@typescript-eslint/no-this-alias': OFF,
'@typescript-eslint/no-unused-vars': [ERROR, {args: 'none'}],
'@typescript-eslint/no-unused-vars': [
ERROR,
{args: 'none', argsIgnorePattern: '^_', varsIgnorePattern: '^_'},
],
GermanJablo marked this conversation as resolved.
Show resolved Hide resolved
'header/header': [2, 'scripts/www/headerTemplate.js'],
},
},
Expand Down Expand Up @@ -226,8 +229,6 @@ module.exports = {

'no-unused-expressions': ERROR,

'no-unused-vars': [ERROR, {args: 'none'}],

'no-use-before-define': OFF,

// Flow fails with with non-string literal keys
Expand Down
43 changes: 42 additions & 1 deletion packages/lexical-website/docs/concepts/node-replacement.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,53 @@
# Node Customization
GermanJablo marked this conversation as resolved.
Show resolved Hide resolved

Originally the only way to customize nodes was using the node replacement API. Recently we have introduced a second way with the `state` property which has some advantages described below.

## State (Experimental)

The advantages of using state over the replacement API are:
1. Easier (less boilerplate)
2. Composable (multiple plugins extending the same node causes failures)
3. Allows metadata: useful for adding things to the RootNode.

```ts
// IMPLEMENTATION
const colorState = createState('color', {
parse: (value: unknown) => (typeof value === 'string' ? value : undefined),
});

// USAGE
const textNode = $createTextNode();
colorState.$set(textNode, "blue");
const textColor = colorState.$get(textNode) // -> "blue"
```

Inside state, you can put any serializable json value. Our recommendation is to always use TypeScript in strict mode, so you don't have to worry about these things!

### Important

we recommend that you use prefixes with low collision probability when defining state. For example, if you are making a plugin called `awesome-lexical`, you could do:

```ts
const color = createState('awesome-lexical-color', /** your parse fn */)
const bgColor = createState('awesome-lexical-bg-color', /** your parse fn */)

// Or you can add all your state inside an object:
type AwesomeLexical = {
color?: string;
bgColor?: string;
padding?: number
}
const awesomeLexical = createState('awesome-lexical', /** your parse fn which returns AwesomeLexical type */)

```

# Node Overrides / Node Replacements

Some of the most commonly used Lexical Nodes are owned and maintained by the core library. For example, ParagraphNode, HeadingNode, QuoteNode, List(Item)Node etc - these are all provided by Lexical packages, which provides an easier out-of-the-box experience for some editor features, but makes it difficult to override their behavior. For instance, if you wanted to change the behavior of ListNode, you would typically extend the class and override the methods. However, how would you tell Lexical to use *your* ListNode subclass in the ListPlugin instead of using the core ListNode? That's where Node Overrides can help.

Node Overrides allow you to replace all instances of a given node in your editor with instances of a different node class. This can be done through the nodes array in the Editor config:

```
```ts
const editorConfig = {
...
nodes=[
Expand Down
37 changes: 37 additions & 0 deletions packages/lexical/src/LexicalNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
type DecoratorNode,
ElementNode,
} from '.';
import {NodeState, State} from './LexicalNodeState';
import {
$getSelection,
$isNodeSelection,
Expand Down Expand Up @@ -59,6 +60,7 @@ export type SerializedLexicalNode = {
type: string;
/** A numeric version for this schema, defaulting to 1, but not generally recommended for use */
version: number;
state?: State;
};

/**
Expand Down Expand Up @@ -199,6 +201,18 @@ export class LexicalNode {
/** @internal */
__next: null | NodeKey;

/** @internal */
get __state() {
// @ts-expect-error
return this._state;
}

/** @internal */
set __state(value: NodeState) {
// @ts-expect-error
this._state = value;
}

// Flow doesn't support abstract classes unfortunately, so we can't _force_
// subclasses of Node to implement statics. All subclasses of Node should have
// a static getType and clone method though. We define getType and clone here so we can call it
Expand Down Expand Up @@ -286,6 +300,7 @@ export class LexicalNode {
this.__parent = prevNode.__parent;
this.__next = prevNode.__next;
this.__prev = prevNode.__prev;
this.__state = prevNode.__state || new NodeState();
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
Expand All @@ -297,6 +312,12 @@ export class LexicalNode {
this.__prev = null;
this.__next = null;
$setNodeKey(this, key);
Object.defineProperty(this, '_state', {
configurable: true,
enumerable: false,
value: new NodeState(),
writable: true,
});
Comment on lines +315 to +320
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Something I thought about but haven't tested yet is whether it would work to use a private javascript property instead.


if (__DEV__) {
if (this.__type !== 'root') {
Expand Down Expand Up @@ -882,9 +903,12 @@ export class LexicalNode {
*
* */
exportJSON(): SerializedLexicalNode {
// eslint-disable-next-line dot-notation
const state = this.__state['toJSON']();
return {
type: this.__type,
version: 1,
...(objectIsEmpty(state) ? {} : {state}),
};
}

Expand Down Expand Up @@ -934,6 +958,8 @@ export class LexicalNode {
updateFromJSON(
serializedNode: LexicalUpdateJSON<SerializedLexicalNode>,
): this {
// eslint-disable-next-line dot-notation
this.__state['unknownState'] = serializedNode.state || {};
return this;
}

Expand Down Expand Up @@ -1289,3 +1315,14 @@ export function insertRangeAfter(
currentNode = currentNode.insertAfter(nodeToInsert);
}
}

/**
* The best way to check if an object is empty in O(1)
* @see https://stackoverflow.com/a/59787784/10476393
*/
function objectIsEmpty(obj: object) {
for (const key in obj) {
return false;
}
return true;
}
131 changes: 131 additions & 0 deletions packages/lexical/src/LexicalNodeState.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
/* eslint-disable dot-notation */

Comment on lines +7 to +9
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reason I suggest using bracket-notation here is to give these properties more privacy in a safer way than the __ prefix.
In LexicalNode, I've defined __state because it's a pattern that's already all over the codebase and because the property is not enumerable.

see microsoft/TypeScript#19335 (comment)

import {LexicalNode} from './LexicalNode';

/**
* NOTE: we parse in getState and setState, but not in importJSON or exportJSON. Ideally,
* the normal thing would be the other way around. The reason we do it this way is because
* we don't have a composable way to declare states (or plugins), prior to creating the
* editor. Maybe later with something like https://lexical-builder.pages.dev/.
*/

export type DeepImmutable<T> = T extends Map<infer K, infer V>
? ReadonlyMap<DeepImmutable<K>, DeepImmutable<V>>
: T extends Set<infer S>
? ReadonlySet<DeepImmutable<S>>
: T extends object
? {
readonly [K in keyof T]: DeepImmutable<T[K]>;
}
: T;

export type State = {
[Key in string]?: string | number | boolean | null | undefined | State;
};

type StateValue = State[keyof State];

export function createState<K extends string, T extends StateValue>(
key: K,
config: {parse: (value: unknown) => T},
) {
// We create a stateConfig with a default value to save some work later
const stateConfig = {
defaultValue: config.parse(undefined),
key,
parse: config.parse,
};

const $get = (node: LexicalNode): DeepImmutable<T> => {
// 1. We first try to get the value from the knownState
const state = node.getLatest().__state;
const value = state['knownState'].get(stateConfig) as DeepImmutable<T>;
if (value !== undefined) {
return value;
}

// 2. If the value is not in the knownState, we try to get it from the unknownState
// and set it in the knownState Map (even if it's a default, so we don't parse again).
const unknownValue = state['unknownState'][key];
delete state['unknownState'][key];
const parsedValue = config.parse(unknownValue) as DeepImmutable<T>;
state['knownState'].set(stateConfig, parsedValue);

// We check collisions (the same string key used on the same node instance in 2 different `createState`)
// We could use a reverse map to avoid a lookup (Map<StateConfig, StateValue>), but it seems overkill.
state['knownState'].forEach((_, currentStateConfig) => {
if (
currentStateConfig.key === key &&
currentStateConfig !== stateConfig
) {
throw new Error(`State key collision detected: ${key}`);
}
});

return parsedValue;
};

const $set = (node: LexicalNode, value: T) => {
const self = node.getWritable();
self.__state = self.__state['clone']();
const parsedValue = config.parse(value);
delete self.__state['unknownState'][key];
self.__state['knownState'].set(stateConfig, parsedValue);
};

return {$get, $set};
}

interface StateConfig<
K extends string = string,
V extends StateValue = StateValue,
> {
readonly key: K;
readonly defaultValue: DeepImmutable<V>;
readonly parse: (value: unknown) => V;
}

export class NodeState {
/**
* State that has already been parsed in a get state, so it is safe. (can be returned with
* just a cast since the proof was given before).
*
* Note that it uses StateConfig, so in addition to (1) the CURRENT VALUE, it has access to
* (2) the State key (3) the DEFAULT VALUE and (4) the PARSE FUNCTION
*/
private knownState: Map<StateConfig, StateValue> = new Map();

/**
* It is a copy of serializedNode.state that is made when JSON is imported but has not been parsed yet.
* It stays here until a get state requires us to parse it, and since we then know the value is safe we move it to knownState
*
* note that it uses string as keys instead of StateConfig so it has no way to parse at export time.
* In exportJSON, we only parse knownState to save the default value which is not exported.
* For safety, we parse unknownState in get state.
*/
private unknownState: Record<string, unknown> = {};

private toJSON(): State {
const state = {...this.unknownState};
this.knownState.forEach((stateValue, stateConfig) => {
if (stateValue !== stateConfig.defaultValue) {
state[stateConfig.key] = stateConfig.parse(stateValue);
}
});
return state as State;
}

private clone() {
const newState = new NodeState();
newState.unknownState = {...this.unknownState};
newState.knownState = new Map(this.knownState);
return newState;
}
}
2 changes: 1 addition & 1 deletion packages/lexical/src/__tests__/unit/LexicalNode.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ import {
TestInlineElementNode,
} from '../utils';

class TestNode extends LexicalNode {
export class TestNode extends LexicalNode {
static getType(): string {
return 'test';
}
Expand Down
Loading