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 editor setup with toolbar #157

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
"react": "^18",
"react-dom": "^18",
"react-hook-form": "^7.53.0",
"react-icons": "^5.3.0",
"react-intersection-observer": "^9.13.1",
"rehype-external-links": "^3.0.0",
"rehype-parse": "^9.0.0",
Expand Down
153 changes: 153 additions & 0 deletions src/app/(site)/(editor)/write/ToolbarPlugin/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
import React, { useCallback, useEffect, useRef, useState } from "react";

import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
import { mergeRegister } from "@lexical/utils";
import {
$getSelection,
$isRangeSelection,
CAN_REDO_COMMAND,
CAN_UNDO_COMMAND,
FORMAT_ELEMENT_COMMAND,
FORMAT_TEXT_COMMAND,
REDO_COMMAND,
SELECTION_CHANGE_COMMAND,
UNDO_COMMAND,
} from "lexical";
import {
AiOutlineAlignCenter,
AiOutlineAlignLeft,
AiOutlineAlignRight,
AiOutlineBold,
AiOutlineItalic,
AiOutlineRedo,
AiOutlineStrikethrough,
AiOutlineUnderline,
AiOutlineUndo,
} from "react-icons/ai";

const LowPriority = 1;

export const ToolbarPlugin: React.FC = () => {
const [editor] = useLexicalComposerContext();
const toolbarRef = useRef(null);
const [canUndo, setCanUndo] = useState(false);
const [canRedo, setCanRedo] = useState(false);
const [isBold, setIsBold] = useState(false);
const [isItalic, setIsItalic] = useState(false);
const [isUnderline, setIsUnderline] = useState(false);
const [isStrikethrough, setIsStrikethrough] = useState(false);
const [align, setAlign] = useState<"left" | "center" | "right" | "">("");

const $updateToolbar = useCallback(() => {
const selection = $getSelection();
if ($isRangeSelection(selection)) {
// Update text format
setIsBold(selection.hasFormat("bold"));
setIsItalic(selection.hasFormat("italic"));
setIsUnderline(selection.hasFormat("underline"));
setIsStrikethrough(selection.hasFormat("strikethrough"));
}
}, []);

useEffect(() => {
return mergeRegister(
editor.registerUpdateListener(({ editorState }) => {
editorState.read(() => {
$updateToolbar();
});
}),
editor.registerCommand(
SELECTION_CHANGE_COMMAND,
(_payload, _newEditor) => {
$updateToolbar();
return false;
},
LowPriority,
),
editor.registerCommand(
CAN_UNDO_COMMAND,
(payload) => {
setCanUndo(payload);
return false;
},
LowPriority,
),
editor.registerCommand(
CAN_REDO_COMMAND,
(payload) => {
setCanRedo(payload);
return false;
},
LowPriority,
),
);
}, [editor, $updateToolbar]);
return (
<div className="fixed bottom-4 left-1/2 transform -translate-x-1/2 bg-border p-4 rounded-lg shadow-md flex gap-4" ref={toolbarRef}>
<AiOutlineUndo
className="text-2xl cursor-pointer"
title="Undo"
onClick={() => {
editor.dispatchCommand(UNDO_COMMAND, undefined);
}}
/>
<AiOutlineRedo
className="text-2xl cursor-pointer"
title="Redo"
onClick={() => {
editor.dispatchCommand(REDO_COMMAND, undefined);
}}
/>
<AiOutlineBold
className={`text-2xl cursor-pointer ${isBold ? "bg-gray-900 text-white rounded p-1" : ""}`}
title="Bold"
onClick={() => {
editor.dispatchCommand(FORMAT_TEXT_COMMAND, "bold");
}}
/>
<AiOutlineItalic
className={`text-2xl cursor-pointer ${isItalic ? "bg-gray-900 text-white rounded p-1" : ""}`}
title="Italic"
onClick={() => {
editor.dispatchCommand(FORMAT_TEXT_COMMAND, "italic");
}}
/>
<AiOutlineUnderline
className={`text-2xl cursor-pointer ${isUnderline ? "bg-gray-900 text-white rounded p-1" : ""}`}
title="Underline"
onClick={() => {
editor.dispatchCommand(FORMAT_TEXT_COMMAND, "underline");
}}
/>
<AiOutlineStrikethrough
className={`text-2xl cursor-pointer ${isStrikethrough ? "bg-gray-900 text-white rounded p-1" : ""}`}
aria-label="Format Strikethrough"
title="Strikethrough"
onClick={() => {
editor.dispatchCommand(FORMAT_TEXT_COMMAND, "strikethrough");
}}
/>
<AiOutlineAlignLeft
className={`text-2xl cursor-pointer ${align === "left" ? "bg-gray-900 text-white rounded p-1" : ""}`}
title="Align Left"
onClick={() => {
editor.dispatchCommand(FORMAT_ELEMENT_COMMAND, "left");
}}
/>
<AiOutlineAlignCenter
className={`text-2xl cursor-pointer ${align === "right" ? "bg-gray-900 text-white rounded p-1" : ""}`}
title="Align Center"
onClick={() => {
editor.dispatchCommand(FORMAT_ELEMENT_COMMAND, "center");
}}
/>
<AiOutlineAlignRight
className={`text-2xl cursor-pointer ${align === "center" ? "bg-gray-900 text-white rounded p-1" : ""}`}
title="Align Right"
onClick={() => {
editor.dispatchCommand(FORMAT_ELEMENT_COMMAND, "right");
}}
/>
</div>
);
};
84 changes: 56 additions & 28 deletions src/app/(site)/(editor)/write/page.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"use client";

import { useEffect } from "react";
import React, { useEffect, useState } from "react";

import { CodeNode } from "@lexical/code";
import { AutoLinkNode, LinkNode } from "@lexical/link";
Expand All @@ -27,6 +27,10 @@ import {
} from "lexical";
import { type Link, type Root } from "mdast";

import { ToolbarPlugin } from "./ToolbarPlugin";

import "./style.css";

// LexicalOnChangePlugin!
function onChange(editorState: EditorState) {
editorState.read(() => {
Expand Down Expand Up @@ -61,45 +65,69 @@ function onError(error: unknown) {
}

export default function Editor() {
const [isClient, setIsClient] = useState(false);
const [showToolbar, setShowToolbar] = useState(false);

useEffect(() => {
setIsClient(true);
}, []);

if (!isClient) {
return null;
}

const initialConfig: InitialConfigType = {
namespace: "NoteStackEditor",
// theme: getTheme("dark"),
editorState: () =>
$convertFromMarkdownString(
"# Don't write anything here yet!",
TRANSFORMERS,
),
$convertFromMarkdownString("# Start writing!", TRANSFORMERS),
nodes: [
HorizontalRuleNode,
// // BannerNode,
// BannerNode,
HeadingNode,
// ImageNode,
// QuoteNode,
// CodeNode,
// ListNode,
// ListItemNode,
// LinkNode,
// AutoLinkNode,
QuoteNode,
CodeNode,
ListNode,
ListItemNode,
LinkNode,
AutoLinkNode,
],
onError,
};

return (
<div className="flex h-screen w-full items-center justify-center">
<LexicalComposer initialConfig={initialConfig}>
<RichTextPlugin
contentEditable={
<ContentEditable className="prose h-full w-full max-w-none overflow-auto border border-red-500 p-12 caret-foreground dark:prose-invert selection:bg-blue-300/25 focus:outline-none" />
}
ErrorBoundary={LexicalErrorBoundary}
/>

<OnChangePlugin onChange={onChange} />
{/* <MarkdownShortcutPlugin transformers={TRANSFORMERS} /> */}

<HistoryPlugin />
<MyCustomAutoFocusPlugin />
</LexicalComposer>
</div>
<LexicalComposer initialConfig={initialConfig}>
<div className="h-[90vh] flex items-center justify-center border border-border">
<div className="border border-gray-300 p-4 rounded-md h-[80vh] w-[80vw] max-w-[800px] flex flex-col bg-secondary relative overflow-hidden">
{/* Toolbar Toggle Button */}
<button
className="self-end mb-2 p-2 bg-blue-600 text-white border-none rounded cursor-pointer hover:bg-blue-800"
onClick={() => setShowToolbar((prev) => !prev)}
>
{showToolbar ? "Hide Toolbar" : "Show Toolbar"}
</button>

{/* Rich Text Editor */}
<div className="relative flex-1 flex overflow-y-auto">
<RichTextPlugin
contentEditable={<ContentEditable className="flex-1 outline-none overflow-auto p-2 max-h-full" />}
placeholder={<div className="text-gray-500 absolute top-2 left-2 pointer-events-none">Enter some text...</div>}
ErrorBoundary={LexicalErrorBoundary}
/>
</div>

{/* Toolbar Plugin */}
{showToolbar && <ToolbarPlugin />}

{/* Plugins */}
<OnChangePlugin onChange={onChange} />
{/* <MarkdownShortcutPlugin transformers={TRANSFORMERS} /> */}

<HistoryPlugin />
<MyCustomAutoFocusPlugin />
</div>
</div>
</LexicalComposer>
);
}
7 changes: 7 additions & 0 deletions src/app/(site)/(editor)/write/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
.editor-placeholder {
color: #888;
position: absolute;
top: 0.5rem;
left: 0.5rem;
pointer-events: none;
}