Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
185 changes: 185 additions & 0 deletions articles/lexical-link-preview/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
import React, { useRef, useState } from "react";
import LexicalErrorBoundary from "@lexical/react/LexicalErrorBoundary";

import { HistoryPlugin } from "@lexical/react/LexicalHistoryPlugin";
import { MarkdownShortcutPlugin } from "@lexical/react/LexicalMarkdownShortcutPlugin";
import { TRANSFORMERS } from "@lexical/markdown";
import { CodeHighlightNode, CodeNode } from "@lexical/code";
import { AutoLinkNode, LinkNode } from "@lexical/link";
import { RichTextPlugin } from "@lexical/react/LexicalRichTextPlugin";
import { HeadingNode, QuoteNode } from "@lexical/rich-text";
import { ListItemNode, ListNode } from "@lexical/list";
import { TabIndentationPlugin } from "@lexical/react/LexicalTabIndentationPlugin";
import { HashtagNode } from "@lexical/hashtag";
import { CheckListPlugin } from "@lexical/react/LexicalCheckListPlugin";
import {
BannerNode,
BannerPlugin,
} from "../../features/article/components/lexicalComponents/Banner";
import { JsonButtonContainer } from "../../utils/lexical";
import { HorizontalRuleNode } from "@lexical/react/LexicalHorizontalRuleNode";
import { HorizontalRulePlugin } from "@lexical/react/LexicalHorizontalRulePlugin";
import { AutoFocusPlugin } from "@lexical/react/LexicalAutoFocusPlugin";
import { EditorState, LineBreakNode, ParagraphNode } from "lexical";
import { HashtagPlugin } from "@lexical/react/LexicalHashtagPlugin";
import ToolbarPlugin from "../../features/article/components/lexicalComponents/ToolbarPlugin";
import {
LinkPreviewNode,
ResOfWebsite,
} from "../../features/article/components/lexicalComponents/LinkPreviewNode";
import { LinkPreviewPlugin } from "../../features/article/components/lexicalComponents/LinkPreviewPlugin";
import TreeViewPlugin from "../../features/article/components/lexicalComponents/TreeViewPlugin";
import {
AutoLinkPlugin,
createLinkMatcherWithRegExp,
} from "@lexical/react/LexicalAutoLinkPlugin";
import { OnChangePlugin } from "@lexical/react/LexicalOnChangePlugin";
import {
LoadFromJsonOnToolbar,
SaveToJsonOnToolbar,
CodeHighlightPlugin,
} from "../../features/article/components/lexicalComponents/OwnLexicalToolbar";
import { LexicalComposer } from "@lexical/react/LexicalComposer";
import DraggableBlockPlugin from "../../features/article/components/lexicalComponents/DraggableBlockPlugin";
import { ContentEditable } from "@lexical/react/LexicalContentEditable";

function onError(error: Error): void {
console.error(error);
}

const myTheme = {
text: {
bold: "textBold",
code: "textCode",
italic: "textItalic",
strikethrough: "textStrikethrough",
subscript: "textSubscript",
superscript: "textSuperscript",
underline: "textUnderline",
underlineStrikethrough: "textUnderlineStrikethrough",
},
list: {
listitem: "listItem",
listitemChecked: "listItemChecked",
listitemUnchecked: "listItemUnchecked",
},
quote: "quote",
link: "mylink",
hashtag: "hashtag",
linkPreviewContainer: "linkPreviewContainer",
};

const initialConfig = {
namespace: "MyEditor",
theme: myTheme,
onError,
nodes: [
HeadingNode,
ListNode,
ListItemNode,
LinkNode,
BannerNode,
HorizontalRuleNode,
CodeNode,
QuoteNode,
HashtagNode,
CodeHighlightNode,
ParagraphNode,
AutoLinkNode,
LinkPreviewNode,
LineBreakNode,
],
};

async function thisFetchingFunction(link: string): Promise<ResOfWebsite> {
const data = await fetch("/api/link-preview", {
method: "POST",
body: JSON.stringify({
link,
}),
});
const {
data: { url, title, description, images },
} = await data.json();
return { url, title, description, images };
}

const Editor = (): JSX.Element => {
const editorStateRef = useRef<EditorState>();
const [editorJson, setEditorJson] = useState("");
const [floatingAnchorElem, setFloatingAnchorElem] =
useState<HTMLDivElement | null>(null);

const onRef = (_floatingAnchorElem: HTMLDivElement) => {
if (_floatingAnchorElem !== null) {
setFloatingAnchorElem(_floatingAnchorElem);
}
};

const URL_REGEX =
/((https?:\/\/(www\.)?)|(www\.))[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)/;

const MATCHERS = [
createLinkMatcherWithRegExp(URL_REGEX, (text) => {
return text.startsWith("http") ? text : `https://${text}`;
}),
];
return (
<LexicalComposer initialConfig={initialConfig}>
<div style={{ position: "relative" }}>
<TabIndentationPlugin />
<AutoFocusPlugin />
<HistoryPlugin />

{floatingAnchorElem && (
<DraggableBlockPlugin anchorElem={floatingAnchorElem} />
)}

<ToolbarPlugin />
<AutoLinkPlugin matchers={MATCHERS} />
<LinkPreviewPlugin
showLink={false}
fetchingFunction={thisFetchingFunction}
/>
<HashtagPlugin />
<MarkdownShortcutPlugin />
<BannerPlugin />
<HorizontalRulePlugin />
<CheckListPlugin />
<CodeHighlightPlugin />
<MarkdownShortcutPlugin transformers={TRANSFORMERS} />

<RichTextPlugin
contentEditable={
<div className="editor-scroller">
<div ref={onRef} className={"editor"}>
<ContentEditable className={"ContentEditable__root"} />
</div>
</div>
}
placeholder={<div className={"placeholder"}> 🖇 Paste your link!</div>}
ErrorBoundary={LexicalErrorBoundary}
/>

<OnChangePlugin
onChange={(editorState) => {
if (editorStateRef) editorStateRef.current = editorState;
}}
/>
<JsonButtonContainer>
<SaveToJsonOnToolbar
onClick={() => {
if (editorStateRef.current)
setEditorJson(JSON.stringify(editorStateRef.current));
}}
/>
<LoadFromJsonOnToolbar data={editorJson} />
</JsonButtonContainer>

<TreeViewPlugin />
</div>
</LexicalComposer>
);
};

export default Editor;
93 changes: 93 additions & 0 deletions features/article/components/lexicalComponents/Banner.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import {
$createParagraphNode,
$getSelection,
$isRangeSelection,
COMMAND_PRIORITY_LOW,
createCommand,
EditorConfig,
ElementNode,
LexicalNode,
RangeSelection,
} from "lexical";
import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
import { $setBlocksType } from "@lexical/selection";
////////////////////////////////////////////////////////////////
// 1.)
export class BannerNode extends ElementNode {
// constructor(key?: NodeKey) {
// super(key);
// }

static getType(): string {
return "banner";
}

static clone(node: BannerNode): BannerNode {
return new BannerNode(node.__key);
}

createDOM(config: EditorConfig): HTMLElement {
const element = document.createElement("div");
element.style.backgroundColor = "lightblue";
return element;
}

updateDOM(): false {
return false;
}

insertNewAfter(
selection: RangeSelection,
restoreSelection?: boolean | undefined,
): LexicalNode | null {
const newBlock = $createParagraphNode();
const direction = this.getDirection();
newBlock.setDirection(direction);
this.inserAfter(newBlock, restoreSelection);
return newBlock;
}

collapseAtStart(): boolean {
const p = $createParagraphNode();
const children = this.getChildren();
children.forEach((child) => p.append(child));
this.replace(p);

return true;
}
}

export function $createBannerNode(): BannerNode {
return new BannerNode();
}

// function $isBannerNode(node: LexicalNode): node is BannerNode {
// return node instanceof BannerNode;
// }

////////////////////////////////////////////////////////////////
// 2.)
export const INSERT_BANNER_COMMAND = createCommand("insertCommand");

////////////////////////////////////////////////////////////////
// 3.)
export const BannerPlugin = (): null => {
const [editor] = useLexicalComposerContext();
if (!editor.hasNodes([BannerNode]))
throw new Error("BannerNode is not registered in the editor");

editor.registerCommand(
INSERT_BANNER_COMMAND,
() => {
const selection = $getSelection();
if ($isRangeSelection(selection)) {
$setBlocksType(selection, $createBannerNode);
}
return true;
},
COMMAND_PRIORITY_LOW,
);
return null;
};

////////////////////////////////////////////////////////////////
Loading