Skip to content

Commit

Permalink
Migrate to TS strict mode 2/n (#2469)
Browse files Browse the repository at this point in the history
  • Loading branch information
thegreatercurve authored Jun 20, 2022
1 parent 93edc4e commit 30ad13b
Show file tree
Hide file tree
Showing 46 changed files with 267 additions and 173 deletions.
2 changes: 1 addition & 1 deletion packages/lexical-devtools/src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import * as ReactDOM from 'react-dom/client';

import App from './App';

ReactDOM.createRoot(document.getElementById('root')).render(
ReactDOM.createRoot(document.getElementById('root') as Element).render(
<React.StrictMode>
<App />
</React.StrictMode>,
Expand Down
34 changes: 23 additions & 11 deletions packages/lexical-file/src/fileImportExport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*
*/

import type {LexicalEditor} from 'lexical';
import type {EditorState, LexicalEditor} from 'lexical';

import {CLEAR_HISTORY_COMMAND, VERSION} from 'lexical';

Expand All @@ -25,20 +25,32 @@ function readTextFileFromSystem(callback: (text: string) => void) {
const input = document.createElement('input');
input.type = 'file';
input.accept = '.lexical';
input.addEventListener('change', (event: InputEvent) => {
input.addEventListener('change', (event: Event) => {
const target = event.target as HTMLInputElement;
const file = target.files[0];
const reader = new FileReader();
reader.readAsText(file, 'UTF-8');

reader.onload = (readerEvent) => {
const content = readerEvent.target.result;
callback(content as string);
};
if (target.files) {
const file = target.files[0];
const reader = new FileReader();
reader.readAsText(file, 'UTF-8');

reader.onload = (readerEvent) => {
if (readerEvent.target) {
const content = readerEvent.target.result;
callback(content as string);
}
};
}
});
input.click();
}

type DocumentJSON = {
editorState: EditorState;
lastSaved: number;
source: string | 'Lexical';
version: typeof VERSION;
};

export function exportFile(
editor: LexicalEditor,
config: Readonly<{
Expand All @@ -48,7 +60,7 @@ export function exportFile(
) {
const now = new Date();
const editorState = editor.getEditorState();
const documentJSON = {
const documentJSON: DocumentJSON = {
editorState: editorState,
lastSaved: now.getTime(),
source: config.source || 'Lexical',
Expand All @@ -59,7 +71,7 @@ export function exportFile(
}

// Adapted from https://stackoverflow.com/a/19328891/2013580
function exportBlob(data, fileName: string) {
function exportBlob(data: DocumentJSON, fileName: string) {
const a = document.createElement('a');
const body = document.body;

Expand Down
8 changes: 5 additions & 3 deletions packages/lexical-headless/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,18 @@ export function createHeadlessEditor(editorConfig?: {
const editor = createEditor(editorConfig);
editor._headless = true;

[
const unsupportedMethods = [
'registerDecoratorListener',
'registerRootListener',
'registerMutationListeners',
'registerMutationListener',
'getRootElement',
'setRootElement',
'getElementByKey',
'focus',
'blur',
].forEach((method) => {
] as const;

unsupportedMethods.forEach((method: typeof unsupportedMethods[number]) => {
editor[method] = () => {
throw new Error(`${method} is not supported in headless mode`);
};
Expand Down
25 changes: 13 additions & 12 deletions packages/lexical-html/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export function $generateNodesFromDOM(
editor: LexicalEditor,
dom: Document,
): Array<LexicalNode> {
let lexicalNodes = [];
let lexicalNodes: Array<LexicalNode> = [];
const elements: Array<Node> = dom.body ? Array.from(dom.body.childNodes) : [];
const elementsLength = elements.length;

Expand Down Expand Up @@ -67,15 +67,17 @@ export function $generateHtmlFromNodes(

for (let i = 0; i < topLevelChildren.length; i++) {
const topLevelNode = topLevelChildren[i];
$appendNodesToHTML(editor, selection, topLevelNode, container);
if (selection) {
$appendNodesToHTML(editor, selection, topLevelNode, container);
}
}

return container.innerHTML;
}

function $appendNodesToHTML(
editor: LexicalEditor,
selection: RangeSelection | NodeSelection | GridSelection | null,
selection: RangeSelection | NodeSelection | GridSelection,
currentNode: LexicalNode,
parentElement: HTMLElement | DocumentFragment,
): boolean {
Expand Down Expand Up @@ -141,18 +143,17 @@ function getConversionFunction(
let currentConversion: DOMConversion | null = null;

if (cachedConversions !== undefined) {
cachedConversions.forEach((cachedConversion) => {
for (const cachedConversion of cachedConversions) {
const domConversion = cachedConversion(domNode);

if (domConversion !== null) {
if (
currentConversion === null ||
currentConversion.priority < domConversion.priority
) {
currentConversion = domConversion;
}
if (
domConversion !== null &&
(currentConversion === null ||
currentConversion.priority < domConversion.priority)
) {
currentConversion = domConversion;
}
});
}
}

return currentConversion !== null ? currentConversion.conversion : null;
Expand Down
6 changes: 3 additions & 3 deletions packages/lexical-link/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ export class LinkNode extends ElementNode {
function convertAnchorElement(domNode: Node): DOMConversionOutput {
let node = null;
if (domNode instanceof HTMLAnchorElement) {
node = $createLinkNode(domNode.getAttribute('href'));
node = $createLinkNode(domNode.getAttribute('href') || '');
}
return {node};
}
Expand Down Expand Up @@ -289,8 +289,8 @@ export function toggleLink(url: null | string): void {
}
}

let prevParent = null;
let linkNode = null;
let prevParent: ElementNode | LinkNode | null = null;
let linkNode: LinkNode | null = null;

nodes.forEach((node) => {
const parent = node.getParent();
Expand Down
10 changes: 5 additions & 5 deletions packages/lexical-list/src/LexicalListItemNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ import {

export type SerializedListItemNode = Spread<
{
checked: boolean;
checked: boolean | undefined;
type: 'listitem';
value: number;
version: 1;
Expand All @@ -53,7 +53,7 @@ export type SerializedListItemNode = Spread<
>;
export class ListItemNode extends ElementNode {
__value: number;
__checked: boolean;
__checked?: boolean;

static getType(): string {
return 'listitem';
Expand Down Expand Up @@ -307,13 +307,13 @@ export class ListItemNode extends ElementNode {
self.__value = value;
}

getChecked(): boolean {
getChecked(): boolean | undefined {
const self = this.getLatest();

return self.__checked;
}

setChecked(checked: boolean): void {
setChecked(checked?: boolean): void {
const self = this.getWritable();
self.__checked = checked;
}
Expand Down Expand Up @@ -365,7 +365,7 @@ export class ListItemNode extends ElementNode {
const parent = this.getParentOrThrow();

if ($isListNode(parent)) {
const siblings = this.getNextSiblings();
const siblings = this.getNextSiblings<ListItemNode>();
updateChildrenListItemValue(parent, siblings);
}
}
Expand Down
13 changes: 9 additions & 4 deletions packages/lexical-list/src/formatList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ export function removeList(editor: LexicalEditor): void {

export function updateChildrenListItemValue(
list: ListNode,
children?: Array<LexicalNode>,
children?: Array<ListItemNode>,
): void {
(children || list.getChildren()).forEach((child: ListItemNode) => {
const prevValue = child.getValue();
Expand All @@ -272,8 +272,12 @@ export function $handleIndent(listItemNodes: Array<ListItemNode>): void {
}

const parent = listItemNode.getParent();
const nextSibling = listItemNode.getNextSibling<ListItemNode>();
const previousSibling = listItemNode.getPreviousSibling<ListItemNode>();

// We can cast both of the below `isNestedListNode` only returns a boolean type instead of a user-defined type guards
const nextSibling =
listItemNode.getNextSibling<ListItemNode>() as ListItemNode;
const previousSibling =
listItemNode.getPreviousSibling<ListItemNode>() as ListItemNode;
// if there are nested lists on either side, merge them all together.

if (isNestedListNode(nextSibling) && isNestedListNode(previousSibling)) {
Expand Down Expand Up @@ -337,6 +341,7 @@ export function $handleIndent(listItemNodes: Array<ListItemNode>): void {

export function $handleOutdent(listItemNodes: Array<ListItemNode>): void {
// go through each node and decide where to move it.

listItemNodes.forEach((listItemNode) => {
if (isNestedListNode(listItemNode)) {
return;
Expand Down Expand Up @@ -404,7 +409,7 @@ function maybeIndentOrOutdent(direction: 'indent' | 'outdent'): void {
return;
}
const selectedNodes = selection.getNodes();
let listItemNodes = [];
let listItemNodes: Array<ListItemNode> = [];

if (selectedNodes.length === 0) {
selectedNodes.push(selection.anchor.getNode());
Expand Down
6 changes: 3 additions & 3 deletions packages/lexical-list/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export function $getTopListNode(listItem: LexicalNode): ListNode {
invariant(false, 'A ListItemNode must have a ListNode for a parent.');
}

let parent = list;
let parent: ListNode | null = list;

while (parent !== null) {
parent = parent.getParent();
Expand All @@ -61,7 +61,7 @@ export function $isLastItemInList(listItem: ListItemNode): boolean {
if ($isListNode(firstChild)) {
return false;
}
let parent = listItem;
let parent: ListItemNode | null = listItem;

while (parent !== null) {
if ($isListItemNode(parent)) {
Expand Down Expand Up @@ -107,7 +107,7 @@ export function isNestedListNode(
export function findNearestListItemNode(
node: LexicalNode,
): ListItemNode | null {
let currentNode = node;
let currentNode: LexicalNode | null = node;

while (currentNode !== null) {
if ($isListItemNode(currentNode)) {
Expand Down
6 changes: 3 additions & 3 deletions packages/lexical-mark/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export function $wrapSelectionInMarkNode(
}
const isFirstNode = i === 0;
const isLastNode = i === nodesLength - 1;
let targetNode: LexicalNode;
let targetNode: LexicalNode | null = null;

if ($isTextNode(node)) {
const textContentSize = node.getTextContentSize();
Expand All @@ -72,7 +72,7 @@ export function $wrapSelectionInMarkNode(
} else if ($isElementNode(node) && node.isInline()) {
targetNode = node;
}
if (targetNode !== undefined) {
if (targetNode !== null) {
if (targetNode && targetNode.is(currentNodeParent)) {
continue;
}
Expand All @@ -97,7 +97,7 @@ export function $getMarkIDs(
node: TextNode,
offset: number,
): null | Array<string> {
let currentNode: LexicalNode = node;
let currentNode: LexicalNode | null = node;
while (currentNode !== null) {
if ($isMarkNode(currentNode)) {
return currentNode.getIDs();
Expand Down
31 changes: 19 additions & 12 deletions packages/lexical-markdown/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -555,17 +555,18 @@ function getPatternMatchResultsWithRegEx(
const patternMatchResults: PatternMatchResults = {
regExCaptureGroups: [],
};
const regExMatches = textToSearch.match(regEx);
const regExMatches: RegExpMatchArray | null = textToSearch.match(regEx);

if (
regExMatches !== null &&
regExMatches &&
regExMatches.length > 0 &&
(matchMustAppearAtStartOfString === false || regExMatches.index === 0) &&
(matchMustAppearAtEndOfString === false ||
regExMatches.index + regExMatches[0].length === textToSearch.length)
(matchMustAppearAtEndOfString === false || regExMatches.index
? regExMatches.index
: 0 + regExMatches[0].length === textToSearch.length)
) {
const captureGroupsCount = regExMatches.length;
let runningLength = regExMatches.index;
let runningLength = regExMatches.index || 0;

for (
let captureGroupIndex = 0;
Expand Down Expand Up @@ -1211,8 +1212,8 @@ function createSelectionWithCaptureGroups(
}

function removeTextByCaptureGroups(
anchorCaptureGroupIndex,
focusCaptureGroupIndex,
anchorCaptureGroupIndex: number,
focusCaptureGroupIndex: number,
scanningContext: ScanningContext,
parentElementNode: ElementNode,
) {
Expand Down Expand Up @@ -1382,15 +1383,18 @@ type BlockExport = (
exportChildren: (node: ElementNode) => string,
) => string | null;

function createHeadingExport(level): BlockExport {
function createHeadingExport(level: number): BlockExport {
return (node, exportChildren) => {
return $isHeadingNode(node) && node.getTag() === 'h' + level
? '#'.repeat(level) + ' ' + exportChildren(node)
: null;
};
}

function listExport(node, exportChildren) {
function listExport(
node: LexicalNode,
exportChildren: (_node: ElementNode) => string,
) {
return $isListNode(node) ? processNestedLists(node, exportChildren, 0) : null;
}

Expand All @@ -1401,7 +1405,7 @@ function processNestedLists(
listNode: ListNode,
exportChildren: (node: ElementNode) => string,
depth: number,
) {
): string {
const output = [];
const children = listNode.getChildren();
let index = 0;
Expand Down Expand Up @@ -1432,11 +1436,14 @@ function processNestedLists(
return output.join('\n');
}

function blockQuoteExport(node, exportChildren) {
function blockQuoteExport(
node: LexicalNode,
exportChildren: (_node: ElementNode) => string,
) {
return $isQuoteNode(node) ? '> ' + exportChildren(node) : null;
}

function codeBlockExport(node, exportChildren) {
function codeBlockExport(node: LexicalNode) {
if (!$isCodeNode(node)) {
return null;
}
Expand Down
Loading

2 comments on commit 30ad13b

@vercel
Copy link

@vercel vercel bot commented on 30ad13b Jun 20, 2022

Choose a reason for hiding this comment

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

Successfully deployed to the following URLs:

lexical – ./packages/lexical-website-new

lexical.dev
lexical-fbopensource.vercel.app
lexical-git-main-fbopensource.vercel.app
www.lexical.dev
lexicaljs.org
lexicaljs.com

@vercel
Copy link

@vercel vercel bot commented on 30ad13b Jun 20, 2022

Choose a reason for hiding this comment

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

Successfully deployed to the following URLs:

lexical-playground – ./packages/lexical-playground

lexical-playground.vercel.app
lexical-playground-git-main-fbopensource.vercel.app
playground.lexical.dev
lexical-playground-fbopensource.vercel.app

Please sign in to comment.