Skip to content

Commit

Permalink
improve null check and invariant readability
Browse files Browse the repository at this point in the history
  • Loading branch information
2wheeh committed Apr 23, 2024
1 parent de34549 commit 29c8597
Show file tree
Hide file tree
Showing 23 changed files with 103 additions and 130 deletions.
4 changes: 2 additions & 2 deletions examples/vanilla-js-plugin/src/emoji-plugin/findEmoji.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@ const emojiReplacementMap = emojis.reduce<Map<string, string>>((acc, row) => {
}
acc.set(`:${row.short_name}:`, row.unified);

if (row.text != null) {
if (row.text !== null) {
acc.set(row.text, row.unified);
}
if (row.texts != null) {
if (row.texts !== null) {
row.texts.forEach((text) => acc.set(text, row.unified));
}

Expand Down
24 changes: 10 additions & 14 deletions packages/lexical-clipboard/src/clipboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,24 +214,20 @@ function exportNodeToJSON<T extends LexicalNode>(node: T): BaseSerializedNode {
const serializedNode = node.exportJSON();
const nodeClass = node.constructor;

if (serializedNode.type !== nodeClass.getType()) {
invariant(
false,
'LexicalNode: Node %s does not implement .exportJSON().',
nodeClass.name,
);
}
invariant(
serializedNode.type === nodeClass.getType(),
'LexicalNode: Node %s does not implement .exportJSON().',
nodeClass.name,
);

if ($isElementNode(node)) {
const serializedChildren = (serializedNode as SerializedElementNode)
.children;
if (!Array.isArray(serializedChildren)) {
invariant(
false,
'LexicalNode: Node %s is an element but .exportJSON() does not have a children array.',
nodeClass.name,
);
}
invariant(
Array.isArray(serializedChildren),
'LexicalNode: Node %s is an element but .exportJSON() does not have a children array.',
nodeClass.name,
);
}

return serializedNode;
Expand Down
7 changes: 3 additions & 4 deletions packages/lexical-code/src/CodeHighlighter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,10 +194,9 @@ export function getEndOfCodeInLine(
anchor: CodeHighlightNode | TabNode,
): CodeHighlightNode | TabNode {
const lastNode = getLastCodeNodeOfLine(anchor);
invariant(
!$isLineBreakNode(lastNode),
'Unexpected lineBreakNode in getEndOfCodeInLine',
);
if ($isLineBreakNode(lastNode)) {
invariant(false, 'Unexpected lineBreakNode in getEndOfCodeInLine');
}
return lastNode;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ export class InjectedPegasusService
}

toggleEditorPicker(): void {
if (this.pickerActive != null) {
if (this.pickerActive !== null) {
this.pickerActive?.stop();
this.pickerActive = null;

Expand All @@ -97,7 +97,7 @@ export class InjectedPegasusService
this.pickerActive.start({
elementFilter: (el) => {
let parent: HTMLElement | null = el;
while (parent != null && parent.tagName !== 'BODY') {
while (parent !== null && parent.tagName !== 'BODY') {
if ('__lexicalEditor' in parent) {
return parent;
}
Expand Down
4 changes: 2 additions & 2 deletions packages/lexical-devtools/src/lexicalForExtension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,13 +79,13 @@ export function $isTextNode(
export function $isRangeSelection(x: unknown): x is lexical.RangeSelection {
// Duck typing :P (and not instanceof RangeSelection) because extension operates
// from different JS bundle and has no reference to the RangeSelection used on the page
return x != null && typeof x === 'object' && 'applyDOMRange' in x;
return x !== null && typeof x === 'object' && 'applyDOMRange' in x;
}

export function $isNodeSelection(x: unknown): x is lexical.NodeSelection {
// Duck typing :P (and not instanceof NodeSelection) because extension operates
// from different JS bundle and has no reference to the NodeSelection used on the page
return x != null && typeof x === 'object' && '_nodes' in x;
return x !== null && typeof x === 'object' && '_nodes' in x;
}

export function readEditorState<V>(
Expand Down
10 changes: 4 additions & 6 deletions packages/lexical-list/src/LexicalListItemNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,12 +216,10 @@ export class ListItemNode extends ElementNode {
insertAfter(node: LexicalNode, restoreSelection = true): LexicalNode {
const listNode = this.getParentOrThrow();

if (!$isListNode(listNode)) {
invariant(
false,
'insertAfter: list node is not parent of list item node',
);
}
invariant(
$isListNode(listNode),
'insertAfter: list node is not parent of list item node',
);

if ($isListItemNode(node)) {
return super.insertAfter(node, restoreSelection);
Expand Down
7 changes: 4 additions & 3 deletions packages/lexical-list/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,10 @@ export function $getListDepth(listNode: ListNode): number {
export function $getTopListNode(listItem: LexicalNode): ListNode {
let list = listItem.getParent<ListNode>();

if (!$isListNode(list)) {
invariant(false, 'A ListItemNode must have a ListNode for a parent.');
}
invariant(
$isListNode(list),
'A ListItemNode must have a ListNode for a parent.',
);

let parent: ListNode | null = list;

Expand Down
12 changes: 5 additions & 7 deletions packages/lexical-markdown/src/MarkdownShortcuts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -341,13 +341,11 @@ export function registerMarkdownShortcuts(
if (type === 'element' || type === 'text-match') {
const dependencies = transformer.dependencies;
for (const node of dependencies) {
if (!editor.hasNode(node)) {
invariant(
false,
'MarkdownShortcuts: missing dependency %s for transformer. Ensure node dependency is included in editor initial config.',
node.getType(),
);
}
invariant(
editor.hasNode(node),
'MarkdownShortcuts: missing dependency %s for transformer. Ensure node dependency is included in editor initial config.',
node.getType(),
);
}
}
}
Expand Down
7 changes: 4 additions & 3 deletions packages/lexical-playground/src/plugins/TablePlugin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -157,9 +157,10 @@ export function TablePlugin({
const cellContext = useContext(CellContext);

useEffect(() => {
if (!editor.hasNodes([TableNode])) {
invariant(false, 'TablePlugin: TableNode is not registered on editor');
}
invariant(
editor.hasNodes([TableNode]),
'TablePlugin: TableNode is not registered on editor',
);

cellContext.set(cellEditorConfig, children);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export default function TypingPerfPlugin(): JSX.Element | null {
let invalidatingEvent = false;

const measureEventEnd = function logKeyPress() {
if (keyPressTimerId != null) {
if (keyPressTimerId !== null) {
if (invalidatingEvent) {
invalidatingEvent = false;
} else {
Expand All @@ -52,7 +52,7 @@ export default function TypingPerfPlugin(): JSX.Element | null {
};

const measureEventStart = function measureEvent() {
if (timerId != null) {
if (timerId !== null) {
clearTimeout(timerId);
timerId = null;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/lexical-playground/src/utils/getDOMRangeRect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export function getDOMRangeRect(

if (nativeSelection.anchorNode === rootElement) {
let inner = rootElement;
while (inner.firstElementChild != null) {
while (inner.firstElementChild !== null) {
inner = inner.firstElementChild as HTMLElement;
}
rect = inner.getBoundingClientRect();
Expand Down
10 changes: 4 additions & 6 deletions packages/lexical-react/src/LexicalAutoLinkPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -423,12 +423,10 @@ function useAutoLink(
onChange?: ChangeHandler,
): void {
useEffect(() => {
if (!editor.hasNodes([AutoLinkNode])) {
invariant(
false,
'LexicalAutoLinkPlugin: AutoLinkNode not registered on editor',
);
}
invariant(
editor.hasNodes([AutoLinkNode]),
'LexicalAutoLinkPlugin: AutoLinkNode not registered on editor',
);

const onChangeWrapped = (url: string | null, prevUrl: string | null) => {
if (onChange) {
Expand Down
10 changes: 4 additions & 6 deletions packages/lexical-react/src/LexicalTablePlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,10 @@ export function TablePlugin({
const [editor] = useLexicalComposerContext();

useEffect(() => {
if (!editor.hasNodes([TableNode, TableCellNode, TableRowNode])) {
invariant(
false,
'TablePlugin: TableNode, TableCellNode or TableRowNode not registered on editor',
);
}
invariant(
editor.hasNodes([TableNode, TableCellNode, TableRowNode]),
'TablePlugin: TableNode, TableCellNode or TableRowNode not registered on editor',
);

return mergeRegister(
editor.registerCommand<InsertTableCommandPayload>(
Expand Down
10 changes: 4 additions & 6 deletions packages/lexical-react/src/shared/useCharacterLimit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,10 @@ export function useCharacterLimit(
} = optional;

useEffect(() => {
if (!editor.hasNodes([OverflowNode])) {
invariant(
false,
'useCharacterLimit: OverflowNode not registered on editor',
);
}
invariant(
editor.hasNodes([OverflowNode]),
'useCharacterLimit: OverflowNode not registered on editor',
);
}, [editor]);

useEffect(() => {
Expand Down
8 changes: 2 additions & 6 deletions packages/lexical-table/src/LexicalTableObserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -335,9 +335,7 @@ export class TableObserver {
this.editor.update(() => {
const selection = $getSelection();

if (!$isTableSelection(selection)) {
invariant(false, 'Expected grid selection');
}
invariant($isTableSelection(selection), 'Expected grid selection');

const formatSelection = $createRangeSelection();

Expand Down Expand Up @@ -369,9 +367,7 @@ export class TableObserver {

const selection = $getSelection();

if (!$isTableSelection(selection)) {
invariant(false, 'Expected grid selection');
}
invariant($isTableSelection(selection), 'Expected grid selection');

const selectedNodes = selection.getNodes().filter($isTableCellNode);

Expand Down
12 changes: 5 additions & 7 deletions packages/lexical-utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -258,13 +258,11 @@ export function $getNearestBlockElementAncestorOrThrow(
startNode,
(node) => $isElementNode(node) && !node.isInline(),
);
if (!$isElementNode(blockNode)) {
invariant(
false,
'Expected node %s to have closest block element node.',
startNode.__key,
);
}
invariant(
$isElementNode(blockNode),
'Expected node %s to have closest block element node.',
startNode.__key,
);
return blockNode;
}

Expand Down
8 changes: 4 additions & 4 deletions packages/lexical-yjs/src/CollabElementNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ export class CollabElementNode {
const insertDelta = delta.insert;
const deleteDelta = delta.delete;

if (delta.retain != null) {
if (delta.retain !== undefined) {
currIndex += delta.retain;
} else if (typeof deleteDelta === 'number') {
let deletionSize = deleteDelta;
Expand Down Expand Up @@ -182,7 +182,7 @@ export class CollabElementNode {
break;
}
}
} else if (insertDelta != null) {
} else if (insertDelta !== undefined) {
if (typeof insertDelta === 'string') {
const {node, offset} = getPositionFromElementAndOffset(
this,
Expand Down Expand Up @@ -274,9 +274,9 @@ export class CollabElementNode {
childCollabNode.syncPropertiesAndTextFromYjs(binding, null);
} else if (childCollabNode instanceof CollabDecoratorNode) {
childCollabNode.syncPropertiesFromYjs(binding, null);
} else if (!(childCollabNode instanceof CollabLineBreakNode)) {
} else {
invariant(
false,
childCollabNode instanceof CollabLineBreakNode,
'syncChildrenFromYjs: expected text, element, decorator, or linebreak collab node',
);
}
Expand Down
9 changes: 7 additions & 2 deletions packages/lexical-yjs/src/Utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ function isExcludedProperty(

const nodeKlass = node.constructor;
const excludedProperties = binding.excludedProperties.get(nodeKlass);
return excludedProperties != null && excludedProperties.has(name);
return excludedProperties !== undefined && excludedProperties.has(name);
}

export function getIndexOfYjsNode(
Expand Down Expand Up @@ -166,7 +166,12 @@ function getNodeTypeFromSharedType(
sharedType instanceof YMap
? sharedType.get('__type')
: sharedType.getAttribute('__type');
invariant(type != null, 'Expected shared type to include type attribute');

invariant(
typeof type === 'string',
'Expected shared type to include type attribute',
);

return type;
}

Expand Down
24 changes: 10 additions & 14 deletions packages/lexical/src/LexicalEditorState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,24 +58,20 @@ function exportNodeToJSON<SerializedNode extends SerializedLexicalNode>(
const serializedNode = node.exportJSON();
const nodeClass = node.constructor;

if (serializedNode.type !== nodeClass.getType()) {
invariant(
false,
'LexicalNode: Node %s does not match the serialized type. Check if .exportJSON() is implemented and it is returning the correct type.',
nodeClass.name,
);
}
invariant(
serializedNode.type === nodeClass.getType(),
'LexicalNode: Node %s does not match the serialized type. Check if .exportJSON() is implemented and it is returning the correct type.',
nodeClass.name,
);

if ($isElementNode(node)) {
const serializedChildren = (serializedNode as SerializedElementNode)
.children;
if (!Array.isArray(serializedChildren)) {
invariant(
false,
'LexicalNode: Node %s is an element but .exportJSON() does not have a children array.',
nodeClass.name,
);
}
invariant(
Array.isArray(serializedChildren),
'LexicalNode: Node %s is an element but .exportJSON() does not have a children array.',
nodeClass.name,
);

const children = node.getChildren();

Expand Down
12 changes: 5 additions & 7 deletions packages/lexical/src/LexicalUpdates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -311,13 +311,11 @@ function $parseSerializedNodeImpl<

const nodeClass = registeredNode.klass;

if (serializedNode.type !== nodeClass.getType()) {
invariant(
false,
'LexicalNode: Node %s does not implement .importJSON().',
nodeClass.name,
);
}
invariant(
serializedNode.type === nodeClass.getType(),
'LexicalNode: Node %s does not implement .importJSON().',
nodeClass.name,
);

const node = nodeClass.importJSON(serializedNode);
const children = serializedNode.children;
Expand Down
Loading

0 comments on commit 29c8597

Please sign in to comment.