fix tiptap editor types

This commit is contained in:
Philipinho
2024-04-05 01:16:07 +01:00
parent 1ea393b60c
commit 5ee74d49d7
8 changed files with 450 additions and 374 deletions

View File

@ -1,26 +1,26 @@
import React, { useState } from 'react'; import React, { useState } from "react";
import { Avatar, Dialog, Group, Stack, Text } from '@mantine/core'; import { Avatar, Dialog, Group, Stack, Text } from "@mantine/core";
import { useClickOutside } from '@mantine/hooks'; import { useClickOutside } from "@mantine/hooks";
import { useAtom } from 'jotai'; import { useAtom } from "jotai";
import { import {
activeCommentIdAtom, activeCommentIdAtom,
draftCommentIdAtom, draftCommentIdAtom,
showCommentPopupAtom, showCommentPopupAtom,
} from '@/features/comment/atoms/comment-atom'; } from "@/features/comment/atoms/comment-atom";
import { Editor } from '@tiptap/core'; import CommentEditor from "@/features/comment/components/comment-editor";
import CommentEditor from '@/features/comment/components/comment-editor'; import CommentActions from "@/features/comment/components/comment-actions";
import CommentActions from '@/features/comment/components/comment-actions'; import { currentUserAtom } from "@/features/user/atoms/current-user-atom";
import { currentUserAtom } from '@/features/user/atoms/current-user-atom'; import { useCreateCommentMutation } from "@/features/comment/queries/comment-query";
import { useCreateCommentMutation } from '@/features/comment/queries/comment-query'; import { asideStateAtom } from "@/components/navbar/atoms/sidebar-atom";
import { asideStateAtom } from '@/components/navbar/atoms/sidebar-atom'; import { useEditor } from "@tiptap/react";
interface CommentDialogProps { interface CommentDialogProps {
editor: Editor, editor: ReturnType<typeof useEditor>;
pageId: string, pageId: string;
} }
function CommentDialog({ editor, pageId }: CommentDialogProps) { function CommentDialog({ editor, pageId }: CommentDialogProps) {
const [comment, setComment] = useState(''); const [comment, setComment] = useState("");
const [, setShowCommentPopup] = useAtom(showCommentPopupAtom); const [, setShowCommentPopup] = useAtom(showCommentPopupAtom);
const [, setActiveCommentId] = useAtom(activeCommentIdAtom); const [, setActiveCommentId] = useAtom(activeCommentIdAtom);
const [draftCommentId, setDraftCommentId] = useAtom(draftCommentIdAtom); const [draftCommentId, setDraftCommentId] = useAtom(draftCommentIdAtom);
@ -34,6 +34,7 @@ function CommentDialog({ editor, pageId }: CommentDialogProps) {
const handleDialogClose = () => { const handleDialogClose = () => {
setShowCommentPopup(false); setShowCommentPopup(false);
// @ts-ignore
editor.chain().focus().unsetCommentDecoration().run(); editor.chain().focus().unsetCommentDecoration().run();
}; };
@ -52,11 +53,17 @@ function CommentDialog({ editor, pageId }: CommentDialogProps) {
selection: selectedText, selection: selectedText,
}; };
const createdComment = await createCommentMutation.mutateAsync(commentData); const createdComment =
editor.chain().setComment(createdComment.id).unsetCommentDecoration().run(); await createCommentMutation.mutateAsync(commentData);
editor
.chain()
.setContent(createdComment.id)
// @ts-ignore
.unsetCommentDecoration()
.run();
setActiveCommentId(createdComment.id); setActiveCommentId(createdComment.id);
setAsideState({ tab: 'comments', isAsideOpen: true }); setAsideState({ tab: "comments", isAsideOpen: true });
setTimeout(() => { setTimeout(() => {
const selector = `div[data-comment-id="${createdComment.id}"]`; const selector = `div[data-comment-id="${createdComment.id}"]`;
const commentElement = document.querySelector(selector); const commentElement = document.querySelector(selector);
@ -64,7 +71,7 @@ function CommentDialog({ editor, pageId }: CommentDialogProps) {
}); });
} finally { } finally {
setShowCommentPopup(false); setShowCommentPopup(false);
setDraftCommentId(''); setDraftCommentId("");
} }
}; };
@ -73,24 +80,38 @@ function CommentDialog({ editor, pageId }: CommentDialogProps) {
}; };
return ( return (
<Dialog opened={true} onClose={handleDialogClose} ref={useClickOutsideRef} size="lg" radius="md" <Dialog
w={300} position={{ bottom: 500, right: 50 }} withCloseButton withBorder> opened={true}
onClose={handleDialogClose}
ref={useClickOutsideRef}
size="lg"
radius="md"
w={300}
position={{ bottom: 500, right: 50 }}
withCloseButton
withBorder
>
<Stack gap={2}> <Stack gap={2}>
<Group> <Group>
<Avatar size="sm" c="blue">{currentUser.user.name.charAt(0)}</Avatar> <Avatar size="sm" c="blue">
{currentUser.user.name.charAt(0)}
</Avatar>
<div style={{ flex: 1 }}> <div style={{ flex: 1 }}>
<Group justify="space-between" wrap="nowrap"> <Group justify="space-between" wrap="nowrap">
<Text size="sm" fw={500} lineClamp={1}>{currentUser.user.name}</Text> <Text size="sm" fw={500} lineClamp={1}>
{currentUser.user.name}
</Text>
</Group> </Group>
</div> </div>
</Group> </Group>
<CommentEditor onUpdate={handleCommentEditorChange} placeholder="Write a comment" <CommentEditor
editable={true} autofocus={true} onUpdate={handleCommentEditorChange}
/> placeholder="Write a comment"
<CommentActions onSave={handleAddComment} isLoading={isPending} editable={true}
autofocus={true}
/> />
<CommentActions onSave={handleAddComment} isLoading={isPending} />
</Stack> </Stack>
</Dialog> </Dialog>
); );

View File

@ -1,14 +1,29 @@
import { BubbleMenu, BubbleMenuProps, isNodeSelection } from '@tiptap/react'; import {
import { FC, useState } from 'react'; BubbleMenu,
import { IconBold, IconCode, IconItalic, IconStrikethrough, IconUnderline, IconMessage } from '@tabler/icons-react'; BubbleMenuProps,
import clsx from 'clsx'; isNodeSelection,
import classes from './bubble-menu.module.css'; useEditor,
import { ActionIcon, rem, Tooltip } from '@mantine/core'; } from "@tiptap/react";
import { ColorSelector } from './color-selector'; import { FC, useState } from "react";
import { NodeSelector } from './node-selector'; import {
import { draftCommentIdAtom, showCommentPopupAtom } from '@/features/comment/atoms/comment-atom'; IconBold,
import { useAtom } from 'jotai'; IconCode,
import { v4 as uuidv4 } from 'uuid'; IconItalic,
IconStrikethrough,
IconUnderline,
IconMessage,
} from "@tabler/icons-react";
import clsx from "clsx";
import classes from "./bubble-menu.module.css";
import { ActionIcon, rem, Tooltip } from "@mantine/core";
import { ColorSelector } from "./color-selector";
import { NodeSelector } from "./node-selector";
import {
draftCommentIdAtom,
showCommentPopupAtom,
} from "@/features/comment/atoms/comment-atom";
import { useAtom } from "jotai";
import { v4 as uuidv4 } from "uuid";
export interface BubbleMenuItem { export interface BubbleMenuItem {
name: string; name: string;
@ -17,7 +32,9 @@ export interface BubbleMenuItem {
icon: typeof IconBold; icon: typeof IconBold;
} }
type EditorBubbleMenuProps = Omit<BubbleMenuProps, 'children'>; type EditorBubbleMenuProps = Omit<BubbleMenuProps, "children" | "editor"> & {
editor: ReturnType<typeof useEditor>;
};
export const EditorBubbleMenu: FC<EditorBubbleMenuProps> = (props) => { export const EditorBubbleMenu: FC<EditorBubbleMenuProps> = (props) => {
const [, setShowCommentPopup] = useAtom(showCommentPopupAtom); const [, setShowCommentPopup] = useAtom(showCommentPopupAtom);
@ -25,44 +42,44 @@ export const EditorBubbleMenu: FC<EditorBubbleMenuProps> = (props) => {
const items: BubbleMenuItem[] = [ const items: BubbleMenuItem[] = [
{ {
name: 'bold', name: "bold",
isActive: () => props.editor.isActive('bold'), isActive: () => props.editor.isActive("bold"),
command: () => props.editor.chain().focus().toggleBold().run(), command: () => props.editor.chain().focus().toggleBold().run(),
icon: IconBold, icon: IconBold,
}, },
{ {
name: 'italic', name: "italic",
isActive: () => props.editor.isActive('italic'), isActive: () => props.editor.isActive("italic"),
command: () => props.editor.chain().focus().toggleItalic().run(), command: () => props.editor.chain().focus().toggleItalic().run(),
icon: IconItalic, icon: IconItalic,
}, },
{ {
name: 'underline', name: "underline",
isActive: () => props.editor.isActive('underline'), isActive: () => props.editor.isActive("underline"),
command: () => props.editor.chain().focus().toggleUnderline().run(), command: () => props.editor.chain().focus().toggleUnderline().run(),
icon: IconUnderline, icon: IconUnderline,
}, },
{ {
name: 'strike', name: "strike",
isActive: () => props.editor.isActive('strike'), isActive: () => props.editor.isActive("strike"),
command: () => props.editor.chain().focus().toggleStrike().run(), command: () => props.editor.chain().focus().toggleStrike().run(),
icon: IconStrikethrough, icon: IconStrikethrough,
}, },
{ {
name: 'code', name: "code",
isActive: () => props.editor.isActive('code'), isActive: () => props.editor.isActive("code"),
command: () => props.editor.chain().focus().toggleCode().run(), command: () => props.editor.chain().focus().toggleCode().run(),
icon: IconCode, icon: IconCode,
}, },
]; ];
const commentItem: BubbleMenuItem = { const commentItem: BubbleMenuItem = {
name: "comment",
name: 'comment', isActive: () => props.editor.isActive("comment"),
isActive: () => props.editor.isActive('comment'),
command: () => { command: () => {
const commentId = uuidv4(); const commentId = uuidv4();
// @ts-ignore
props.editor.chain().focus().setCommentDecoration().run(); props.editor.chain().focus().setCommentDecoration().run();
setDraftCommentId(commentId); setDraftCommentId(commentId);
setShowCommentPopup(true); setShowCommentPopup(true);
@ -76,13 +93,17 @@ export const EditorBubbleMenu: FC<EditorBubbleMenuProps> = (props) => {
const { selection } = state; const { selection } = state;
const { empty } = selection; const { empty } = selection;
if (editor.isActive('image') || empty || isNodeSelection(selection)) { if (
props.editor.isActive("image") ||
empty ||
isNodeSelection(selection)
) {
return false; return false;
} }
return true; return true;
}, },
tippyOptions: { tippyOptions: {
moveTransition: 'transform 0.15s ease-out', moveTransition: "transform 0.15s ease-out",
onHidden: () => { onHidden: () => {
setIsNodeSelectorOpen(false); setIsNodeSelectorOpen(false);
setIsColorSelectorOpen(false); setIsColorSelectorOpen(false);
@ -96,10 +117,7 @@ export const EditorBubbleMenu: FC<EditorBubbleMenuProps> = (props) => {
const [isLinkSelectorOpen, setIsLinkSelectorOpen] = useState(false); const [isLinkSelectorOpen, setIsLinkSelectorOpen] = useState(false);
return ( return (
<BubbleMenu <BubbleMenu {...bubbleMenuProps} className={classes.bubbleMenu}>
{...bubbleMenuProps}
className={classes.bubbleMenu}
>
<NodeSelector <NodeSelector
editor={props.editor} editor={props.editor}
isOpen={isNodeSelectorOpen} isOpen={isNodeSelectorOpen}
@ -113,15 +131,19 @@ export const EditorBubbleMenu: FC<EditorBubbleMenuProps> = (props) => {
<ActionIcon.Group> <ActionIcon.Group>
{items.map((item, index) => ( {items.map((item, index) => (
<Tooltip key={index} label={item.name} withArrow> <Tooltip key={index} label={item.name} withArrow>
<ActionIcon
<ActionIcon key={index} variant="default" size="lg" radius="0" aria-label={item.name} key={index}
variant="default"
size="lg"
radius="0"
aria-label={item.name}
className={clsx({ [classes.active]: item.isActive() })} className={clsx({ [classes.active]: item.isActive() })}
style={{ border: 'none' }} style={{ border: "none" }}
onClick={item.command}> onClick={item.command}
>
<item.icon style={{ width: rem(16) }} stroke={2} /> <item.icon style={{ width: rem(16) }} stroke={2} />
</ActionIcon> </ActionIcon>
</Tooltip> </Tooltip>
))} ))}
</ActionIcon.Group> </ActionIcon.Group>
@ -136,14 +158,17 @@ export const EditorBubbleMenu: FC<EditorBubbleMenuProps> = (props) => {
/> />
<Tooltip label={commentItem.name} withArrow> <Tooltip label={commentItem.name} withArrow>
<ActionIcon
<ActionIcon variant="default" size="lg" radius="0" aria-label={commentItem.name} variant="default"
style={{ border: 'none' }} size="lg"
onClick={commentItem.command}> radius="0"
aria-label={commentItem.name}
style={{ border: "none" }}
onClick={commentItem.command}
>
<IconMessage style={{ width: rem(16) }} stroke={2} /> <IconMessage style={{ width: rem(16) }} stroke={2} />
</ActionIcon> </ActionIcon>
</Tooltip> </Tooltip>
</BubbleMenu> </BubbleMenu>
); );
}; };

View File

@ -1,8 +1,8 @@
import { Editor } from '@tiptap/core'; import { Dispatch, FC, SetStateAction } from "react";
import { Dispatch, FC, SetStateAction } from 'react'; import { IconCheck, IconChevronDown } from "@tabler/icons-react";
import { IconCheck, IconChevronDown } from '@tabler/icons-react'; import { Button, Popover, rem, ScrollArea, Text } from "@mantine/core";
import { Button, Popover, rem, ScrollArea, Text } from '@mantine/core'; import classes from "./bubble-menu.module.css";
import classes from './bubble-menu.module.css'; import { useEditor } from "@tiptap/react";
export interface BubbleColorMenuItem { export interface BubbleColorMenuItem {
name: string; name: string;
@ -10,106 +10,109 @@ export interface BubbleColorMenuItem {
} }
interface ColorSelectorProps { interface ColorSelectorProps {
editor: Editor; editor: ReturnType<typeof useEditor>;
isOpen: boolean; isOpen: boolean;
setIsOpen: Dispatch<SetStateAction<boolean>>; setIsOpen: Dispatch<SetStateAction<boolean>>;
} }
const TEXT_COLORS: BubbleColorMenuItem[] = [ const TEXT_COLORS: BubbleColorMenuItem[] = [
{ {
name: 'Default', name: "Default",
color: '', color: "",
}, },
{ {
name: 'Blue', name: "Blue",
color: '#2563EB', color: "#2563EB",
}, },
{ {
name: 'Green', name: "Green",
color: '#008A00', color: "#008A00",
}, },
{ {
name: 'Purple', name: "Purple",
color: '#9333EA', color: "#9333EA",
}, },
{ {
name: 'Red', name: "Red",
color: '#E00000', color: "#E00000",
}, },
{ {
name: 'Yellow', name: "Yellow",
color: '#EAB308', color: "#EAB308",
}, },
{ {
name: 'Orange', name: "Orange",
color: '#FFA500', color: "#FFA500",
}, },
{ {
name: 'Pink', name: "Pink",
color: '#BA4081', color: "#BA4081",
}, },
{ {
name: 'Gray', name: "Gray",
color: '#A8A29E', color: "#A8A29E",
}, },
]; ];
// TODO: handle dark mode // TODO: handle dark mode
const HIGHLIGHT_COLORS: BubbleColorMenuItem[] = [ const HIGHLIGHT_COLORS: BubbleColorMenuItem[] = [
{ {
name: 'Default', name: "Default",
color: '', color: "",
}, },
{ {
name: 'Blue', name: "Blue",
color: '#c1ecf9', color: "#c1ecf9",
}, },
{ {
name: 'Green', name: "Green",
color: '#acf79f', color: "#acf79f",
}, },
{ {
name: 'Purple', name: "Purple",
color: '#f6f3f8', color: "#f6f3f8",
}, },
{ {
name: 'Red', name: "Red",
color: '#fdebeb', color: "#fdebeb",
}, },
{ {
name: 'Yellow', name: "Yellow",
color: '#fbf4a2', color: "#fbf4a2",
}, },
{ {
name: 'Orange', name: "Orange",
color: '#faebdd', color: "#faebdd",
}, },
{ {
name: 'Pink', name: "Pink",
color: '#faf1f5', color: "#faf1f5",
}, },
{ {
name: 'Gray', name: "Gray",
color: '#f1f1ef', color: "#f1f1ef",
}, },
]; ];
export const ColorSelector: FC<ColorSelectorProps> = export const ColorSelector: FC<ColorSelectorProps> = ({
({ editor, isOpen, setIsOpen }) => { editor,
isOpen,
setIsOpen,
}) => {
const activeColorItem = TEXT_COLORS.find(({ color }) => const activeColorItem = TEXT_COLORS.find(({ color }) =>
editor.isActive('textStyle', { color }), editor.isActive("textStyle", { color }),
); );
const activeHighlightItem = HIGHLIGHT_COLORS.find(({ color }) => const activeHighlightItem = HIGHLIGHT_COLORS.find(({ color }) =>
editor.isActive('highlight', { color }), editor.isActive("highlight", { color }),
); );
return ( return (
<Popover width={200} opened={isOpen} withArrow> <Popover width={200} opened={isOpen} withArrow>
<Popover.Target> <Popover.Target>
<Button
<Button variant="default" radius="0" variant="default"
radius="0"
leftSection="A" leftSection="A"
rightSection={<IconChevronDown size={16} />} rightSection={<IconChevronDown size={16} />}
className={classes.colorButton} className={classes.colorButton}
@ -122,9 +125,10 @@ export const ColorSelector: FC<ColorSelectorProps> =
<Popover.Dropdown> <Popover.Dropdown>
{/* make mah responsive */} {/* make mah responsive */}
<ScrollArea.Autosize type="scroll" mah='400'> <ScrollArea.Autosize type="scroll" mah="400">
<Text span c="dimmed" inherit>
<Text span c="dimmed" inherit>COLOR</Text> COLOR
</Text>
<Button.Group orientation="vertical"> <Button.Group orientation="vertical">
{TEXT_COLORS.map(({ name, color }, index) => ( {TEXT_COLORS.map(({ name, color }, index) => (
@ -134,54 +138,58 @@ export const ColorSelector: FC<ColorSelectorProps> =
leftSection={<span style={{ color }}>A</span>} leftSection={<span style={{ color }}>A</span>}
justify="left" justify="left"
fullWidth fullWidth
rightSection={editor.isActive('textStyle', { color }) rightSection={
&& (<IconCheck style={{ width: rem(16) }} />)} editor.isActive("textStyle", { color }) && (
<IconCheck style={{ width: rem(16) }} />
)
}
onClick={() => { onClick={() => {
editor.commands.unsetColor(); editor.commands.unsetColor();
name !== 'Default' && name !== "Default" &&
editor editor
.chain() .chain()
.focus() .focus()
.setColor(color || '') .setColor(color || "")
.run(); .run();
setIsOpen(false); setIsOpen(false);
}} }}
style={{ border: 'none' }} style={{ border: "none" }}
> >
{name} {name}
</Button> </Button>
))} ))}
</Button.Group> </Button.Group>
<Text span c="dimmed" inherit>BACKGROUND</Text> <Text span c="dimmed" inherit>
BACKGROUND
</Text>
<Button.Group orientation="vertical"> <Button.Group orientation="vertical">
{HIGHLIGHT_COLORS.map(({ name, color }, index) => ( {HIGHLIGHT_COLORS.map(({ name, color }, index) => (
<Button <Button
key={index} key={index}
variant="default" variant="default"
leftSection={<span style={{ padding: '4px', background: color }}>A</span>} leftSection={
<span style={{ padding: "4px", background: color }}>A</span>
}
justify="left" justify="left"
fullWidth fullWidth
rightSection={editor.isActive('highlight', { color }) rightSection={
&& (<IconCheck style={{ width: rem(16) }} />)} editor.isActive("highlight", { color }) && (
<IconCheck style={{ width: rem(16) }} />
)
}
onClick={() => { onClick={() => {
editor.commands.unsetHighlight(); editor.commands.unsetHighlight();
name !== 'Default' && name !== "Default" && editor.commands.setHighlight({ color });
editor
.commands
.setHighlight({ color });
setIsOpen(false); setIsOpen(false);
}} }}
style={{ border: 'none' }} style={{ border: "none" }}
> >
{name} {name}
</Button> </Button>
))} ))}
</Button.Group> </Button.Group>
</ScrollArea.Autosize> </ScrollArea.Autosize>
</Popover.Dropdown> </Popover.Dropdown>
</Popover> </Popover>

View File

@ -1,20 +1,23 @@
import { Editor } from '@tiptap/core'; import React, { Dispatch, FC, SetStateAction } from "react";
import React, { Dispatch, FC, SetStateAction } from 'react';
import { import {
IconBlockquote, IconBlockquote,
IconCheck, IconCheckbox, IconChevronDown, IconCode, IconCheck,
IconCheckbox,
IconChevronDown,
IconCode,
IconH1, IconH1,
IconH2, IconH2,
IconH3, IconH3,
IconList, IconList,
IconListNumbers, IconListNumbers,
IconTypography, IconTypography,
} from '@tabler/icons-react'; } from "@tabler/icons-react";
import { Popover, Button, rem, ScrollArea } from '@mantine/core'; import { Popover, Button, rem, ScrollArea } from "@mantine/core";
import classes from '@/features/editor/components/bubble-menu/bubble-menu.module.css'; import classes from "@/features/editor/components/bubble-menu/bubble-menu.module.css";
import { useEditor } from "@tiptap/react";
interface NodeSelectorProps { interface NodeSelectorProps {
editor: Editor; editor: ReturnType<typeof useEditor>;
isOpen: boolean; isOpen: boolean;
setIsOpen: Dispatch<SetStateAction<boolean>>; setIsOpen: Dispatch<SetStateAction<boolean>>;
} }
@ -26,122 +29,120 @@ export interface BubbleMenuItem {
isActive: () => boolean; isActive: () => boolean;
} }
export const NodeSelector: FC<NodeSelectorProps> = export const NodeSelector: FC<NodeSelectorProps> = ({
({ editor, isOpen, setIsOpen }) => { editor,
isOpen,
setIsOpen,
}) => {
const items: BubbleMenuItem[] = [ const items: BubbleMenuItem[] = [
{ {
name: 'Text', name: "Text",
icon: IconTypography, icon: IconTypography,
command: () => command: () =>
editor.chain().focus().toggleNode('paragraph', 'paragraph').run(), editor.chain().focus().toggleNode("paragraph", "paragraph").run(),
isActive: () => isActive: () =>
editor.isActive('paragraph') && editor.isActive("paragraph") &&
!editor.isActive('bulletList') && !editor.isActive("bulletList") &&
!editor.isActive('orderedList'), !editor.isActive("orderedList"),
}, },
{ {
name: 'Heading 1', name: "Heading 1",
icon: IconH1, icon: IconH1,
command: () => editor.chain().focus().toggleHeading({ level: 1 }).run(), command: () => editor.chain().focus().toggleHeading({ level: 1 }).run(),
isActive: () => editor.isActive('heading', { level: 1 }), isActive: () => editor.isActive("heading", { level: 1 }),
}, },
{ {
name: 'Heading 2', name: "Heading 2",
icon: IconH2, icon: IconH2,
command: () => editor.chain().focus().toggleHeading({ level: 2 }).run(), command: () => editor.chain().focus().toggleHeading({ level: 2 }).run(),
isActive: () => editor.isActive('heading', { level: 2 }), isActive: () => editor.isActive("heading", { level: 2 }),
}, },
{ {
name: 'Heading 3', name: "Heading 3",
icon: IconH3, icon: IconH3,
command: () => editor.chain().focus().toggleHeading({ level: 3 }).run(), command: () => editor.chain().focus().toggleHeading({ level: 3 }).run(),
isActive: () => editor.isActive('heading', { level: 3 }), isActive: () => editor.isActive("heading", { level: 3 }),
}, },
{ {
name: 'To-do List', name: "To-do List",
icon: IconCheckbox, icon: IconCheckbox,
command: () => editor.chain().focus().toggleTaskList().run(), command: () => editor.chain().focus().toggleTaskList().run(),
isActive: () => editor.isActive('taskItem'), isActive: () => editor.isActive("taskItem"),
}, },
{ {
name: 'Bullet List', name: "Bullet List",
icon: IconList, icon: IconList,
command: () => editor.chain().focus().toggleBulletList().run(), command: () => editor.chain().focus().toggleBulletList().run(),
isActive: () => editor.isActive('bulletList'), isActive: () => editor.isActive("bulletList"),
}, },
{ {
name: 'Numbered List', name: "Numbered List",
icon: IconListNumbers, icon: IconListNumbers,
command: () => editor.chain().focus().toggleOrderedList().run(), command: () => editor.chain().focus().toggleOrderedList().run(),
isActive: () => editor.isActive('orderedList'), isActive: () => editor.isActive("orderedList"),
}, },
{ {
name: 'Blockquote', name: "Blockquote",
icon: IconBlockquote, icon: IconBlockquote,
command: () => command: () =>
editor editor
.chain() .chain()
.focus() .focus()
.toggleNode('paragraph', 'paragraph') .toggleNode("paragraph", "paragraph")
.toggleBlockquote() .toggleBlockquote()
.run(), .run(),
isActive: () => editor.isActive('blockquote'), isActive: () => editor.isActive("blockquote"),
}, },
{ {
name: 'Code', name: "Code",
icon: IconCode, icon: IconCode,
command: () => editor.chain().focus().toggleCodeBlock().run(), command: () => editor.chain().focus().toggleCodeBlock().run(),
isActive: () => editor.isActive('codeBlock'), isActive: () => editor.isActive("codeBlock"),
}, },
]; ];
const activeItem = items.filter((item) => item.isActive()).pop() ?? { const activeItem = items.filter((item) => item.isActive()).pop() ?? {
name: 'Multiple', name: "Multiple",
}; };
return ( return (
<Popover opened={isOpen} withArrow> <Popover opened={isOpen} withArrow>
<Popover.Target> <Popover.Target>
<Button variant="default" radius="0" <Button
variant="default"
radius="0"
rightSection={<IconChevronDown size={16} />} rightSection={<IconChevronDown size={16} />}
className={classes.colorButton} className={classes.colorButton}
onClick={() => setIsOpen(!isOpen)} onClick={() => setIsOpen(!isOpen)}
> >
{activeItem?.name} {activeItem?.name}
</Button> </Button>
</Popover.Target> </Popover.Target>
<Popover.Dropdown> <Popover.Dropdown>
<ScrollArea.Autosize type="scroll" mah={400}> <ScrollArea.Autosize type="scroll" mah={400}>
<Button.Group orientation="vertical"> <Button.Group orientation="vertical">
{items.map((item, index) => ( {items.map((item, index) => (
<Button <Button
key={index} key={index}
variant="default" variant="default"
leftSection={<item.icon size={16} />} leftSection={<item.icon size={16} />}
rightSection={activeItem.name === item.name rightSection={
&& (<IconCheck size={16} />)} activeItem.name === item.name && <IconCheck size={16} />
}
justify="left" justify="left"
fullWidth fullWidth
onClick={() => { onClick={() => {
item.command(); item.command();
setIsOpen(false); setIsOpen(false);
}} }}
style={{ border: 'none' }} style={{ border: "none" }}
> >
{item.name} {item.name}
</Button> </Button>
))} ))}
</Button.Group> </Button.Group>
</ScrollArea.Autosize> </ScrollArea.Autosize>
</Popover.Dropdown> </Popover.Dropdown>
</Popover> </Popover>
); );

View File

@ -1,14 +1,16 @@
import { Editor } from '@tiptap/core'; import { ReactRenderer, useEditor } from "@tiptap/react";
import { ReactRenderer } from '@tiptap/react'; import CommandList from "@/features/editor/components/slash-menu/command-list";
import CommandList from '@/features/editor/components/slash-menu/command-list'; import tippy from "tippy.js";
import tippy from 'tippy.js';
const renderItems = () => { const renderItems = () => {
let component: ReactRenderer | null = null; let component: ReactRenderer | null = null;
let popup: any | null = null; let popup: any | null = null;
return { return {
onStart: (props: { editor: Editor; clientRect: DOMRect }) => { onStart: (props: {
editor: ReturnType<typeof useEditor>;
clientRect: DOMRect;
}) => {
component = new ReactRenderer(CommandList, { component = new ReactRenderer(CommandList, {
props, props,
editor: props.editor, editor: props.editor,
@ -19,17 +21,20 @@ const renderItems = () => {
} }
// @ts-ignore // @ts-ignore
popup = tippy('body', { popup = tippy("body", {
getReferenceClientRect: props.clientRect, getReferenceClientRect: props.clientRect,
appendTo: () => document.body, appendTo: () => document.body,
content: component.element, content: component.element,
showOnCreate: true, showOnCreate: true,
interactive: true, interactive: true,
trigger: 'manual', trigger: "manual",
placement: 'bottom-start', placement: "bottom-start",
}); });
}, },
onUpdate: (props: { editor: Editor; clientRect: DOMRect }) => { onUpdate: (props: {
editor: ReturnType<typeof useEditor>;
clientRect: DOMRect;
}) => {
component?.updateProps(props); component?.updateProps(props);
if (!props.clientRect) { if (!props.clientRect) {
@ -42,7 +47,7 @@ const renderItems = () => {
}); });
}, },
onKeyDown: (props: { event: KeyboardEvent }) => { onKeyDown: (props: { event: KeyboardEvent }) => {
if (props.event.key === 'Escape') { if (props.event.key === "Escape") {
popup?.[0].hide(); popup?.[0].hide();
return true; return true;

View File

@ -1,16 +1,17 @@
import { Editor, Range } from '@tiptap/core'; import { Range } from "@tiptap/core";
import { useEditor } from "@tiptap/react";
export type CommandProps = { export type CommandProps = {
editor: Editor; editor: ReturnType<typeof useEditor>;
range: Range; range: Range;
} };
export type CommandListProps = { export type CommandListProps = {
items: SlashMenuGroupedItemsType; items: SlashMenuGroupedItemsType;
command: (item: SlashMenuItemType) => void; command: (item: SlashMenuItemType) => void;
editor: Editor; editor: ReturnType<typeof useEditor>;
range: Range; range: Range;
} };
export type SlashMenuItemType = { export type SlashMenuItemType = {
title: string; title: string;
@ -19,8 +20,8 @@ export type SlashMenuItemType = {
separator?: true; separator?: true;
searchTerms: string[]; searchTerms: string[];
command: (props: CommandProps) => void; command: (props: CommandProps) => void;
disable?: (editor: Editor) => boolean; disable?: (editor: ReturnType<typeof useEditor>) => boolean;
} };
export type SlashMenuGroupedItemsType = { export type SlashMenuGroupedItemsType = {
[category: string]: SlashMenuItemType[]; [category: string]: SlashMenuItemType[];

View File

@ -1,35 +1,35 @@
import { StarterKit } from '@tiptap/starter-kit'; import { StarterKit } from "@tiptap/starter-kit";
import { Placeholder } from '@tiptap/extension-placeholder'; import { Placeholder } from "@tiptap/extension-placeholder";
import { TextAlign } from '@tiptap/extension-text-align'; import { TextAlign } from "@tiptap/extension-text-align";
import { TaskList } from '@tiptap/extension-task-list'; import { TaskList } from "@tiptap/extension-task-list";
import { TaskItem } from '@tiptap/extension-task-item'; import { TaskItem } from "@tiptap/extension-task-item";
import { Underline } from '@tiptap/extension-underline'; import { Underline } from "@tiptap/extension-underline";
import { Link } from '@tiptap/extension-link'; import { Link } from "@tiptap/extension-link";
import { Superscript } from '@tiptap/extension-superscript'; import { Superscript } from "@tiptap/extension-superscript";
import SubScript from '@tiptap/extension-subscript'; import SubScript from "@tiptap/extension-subscript";
import { Highlight } from '@tiptap/extension-highlight'; import { Highlight } from "@tiptap/extension-highlight";
import { Typography } from '@tiptap/extension-typography'; import { Typography } from "@tiptap/extension-typography";
import DragAndDrop from '@/features/editor/extensions/drag-handle'; import DragAndDrop from "@/features/editor/extensions/drag-handle";
import { TextStyle } from '@tiptap/extension-text-style'; import { TextStyle } from "@tiptap/extension-text-style";
import { Color } from '@tiptap/extension-color'; import { Color } from "@tiptap/extension-color";
import SlashCommand from '@/features/editor/extensions/slash-command'; import SlashCommand from "@/features/editor/extensions/slash-command";
import { Collaboration } from '@tiptap/extension-collaboration'; import { Collaboration } from "@tiptap/extension-collaboration";
import { CollaborationCursor } from '@tiptap/extension-collaboration-cursor'; import { CollaborationCursor } from "@tiptap/extension-collaboration-cursor";
import { HocuspocusProvider } from '@hocuspocus/provider'; import { HocuspocusProvider } from "@hocuspocus/provider";
import { Comment, TrailingNode } from '@docmost/editor-ext'; import { Comment, TrailingNode } from "@docmost/editor-ext";
export const mainExtensions = [ export const mainExtensions = [
StarterKit.configure({ StarterKit.configure({
history: false, history: false,
dropcursor: { dropcursor: {
width: 3, width: 3,
color: '#70CFF8', color: "#70CFF8",
}, },
}), }),
Placeholder.configure({ Placeholder.configure({
placeholder: 'Enter "/" for commands', placeholder: 'Enter "/" for commands',
}), }),
TextAlign.configure({ types: ['heading', 'paragraph'] }), TextAlign.configure({ types: ["heading", "paragraph"] }),
TaskList, TaskList,
TaskItem.configure({ TaskItem.configure({
nested: true, nested: true,
@ -49,10 +49,10 @@ export const mainExtensions = [
SlashCommand, SlashCommand,
Comment.configure({ Comment.configure({
HTMLAttributes: { HTMLAttributes: {
class: 'comment-mark', class: "comment-mark",
}, },
}), }),
]; ] as any;
type CollabExtensions = (provider: HocuspocusProvider) => any[]; type CollabExtensions = (provider: HocuspocusProvider) => any[];

View File

@ -1,28 +1,38 @@
import '@/features/editor/styles/index.css'; import "@/features/editor/styles/index.css";
import React, { import React, { useEffect, useLayoutEffect, useMemo, useState } from "react";
useEffect, import { IndexeddbPersistence } from "y-indexeddb";
useLayoutEffect, import * as Y from "yjs";
useMemo, import { HocuspocusProvider } from "@hocuspocus/provider";
useState, import { EditorContent, useEditor } from "@tiptap/react";
} from 'react'; import {
import { IndexeddbPersistence } from 'y-indexeddb'; collabExtensions,
import * as Y from 'yjs'; mainExtensions,
import { HocuspocusProvider } from '@hocuspocus/provider'; } from "@/features/editor/extensions/extensions";
import { EditorContent, useEditor } from '@tiptap/react'; import { useAtom } from "jotai";
import { collabExtensions, mainExtensions } from '@/features/editor/extensions/extensions'; import { authTokensAtom } from "@/features/auth/atoms/auth-tokens-atom";
import { useAtom } from 'jotai'; import useCollaborationUrl from "@/features/editor/hooks/use-collaboration-url";
import { authTokensAtom } from '@/features/auth/atoms/auth-tokens-atom'; import { currentUserAtom } from "@/features/user/atoms/current-user-atom";
import useCollaborationUrl from '@/features/editor/hooks/use-collaboration-url'; import { pageEditorAtom } from "@/features/editor/atoms/editor-atoms";
import { currentUserAtom } from '@/features/user/atoms/current-user-atom'; import { asideStateAtom } from "@/components/navbar/atoms/sidebar-atom";
import { pageEditorAtom } from '@/features/editor/atoms/editor-atoms'; import {
import { asideStateAtom } from '@/components/navbar/atoms/sidebar-atom'; activeCommentIdAtom,
import { activeCommentIdAtom, showCommentPopupAtom } from '@/features/comment/atoms/comment-atom'; showCommentPopupAtom,
import CommentDialog from '@/features/comment/components/comment-dialog'; } from "@/features/comment/atoms/comment-atom";
import EditorSkeleton from '@/features/editor/components/editor-skeleton'; import CommentDialog from "@/features/comment/components/comment-dialog";
import { EditorBubbleMenu } from '@/features/editor/components/bubble-menu/bubble-menu'; import EditorSkeleton from "@/features/editor/components/editor-skeleton";
import { EditorBubbleMenu } from "@/features/editor/components/bubble-menu/bubble-menu";
const colors = ['#958DF1', '#F98181', '#FBBC88', '#FAF594', '#70CFF8', '#94FADB', '#B9F18D']; const colors = [
const getRandomElement = list => list[Math.floor(Math.random() * list.length)]; "#958DF1",
"#F98181",
"#FBBC88",
"#FAF594",
"#70CFF8",
"#94FADB",
"#B9F18D",
];
const getRandomElement = (list) =>
list[Math.floor(Math.random() * list.length)];
const getRandomColor = () => getRandomElement(colors); const getRandomColor = () => getRandomElement(colors);
interface PageEditorProps { interface PageEditorProps {
@ -30,7 +40,10 @@ interface PageEditorProps {
editable?: boolean; editable?: boolean;
} }
export default function PageEditor({ pageId, editable = true }: PageEditorProps) { export default function PageEditor({
pageId,
editable = true,
}: PageEditorProps) {
const [token] = useAtom(authTokensAtom); const [token] = useAtom(authTokensAtom);
const collaborationURL = useCollaborationUrl(); const collaborationURL = useCollaborationUrl();
const [currentUser] = useAtom(currentUserAtom); const [currentUser] = useAtom(currentUserAtom);
@ -46,12 +59,9 @@ export default function PageEditor({ pageId, editable = true }: PageEditorProps)
const [isRemoteSynced, setRemoteSynced] = useState(false); const [isRemoteSynced, setRemoteSynced] = useState(false);
const localProvider = useMemo(() => { const localProvider = useMemo(() => {
const provider = new IndexeddbPersistence( const provider = new IndexeddbPersistence(pageId, ydoc);
pageId,
ydoc,
);
provider.on('synced', () => { provider.on("synced", () => {
setLocalSynced(true); setLocalSynced(true);
}); });
@ -67,7 +77,7 @@ export default function PageEditor({ pageId, editable = true }: PageEditorProps)
connect: false, connect: false,
}); });
provider.on('synced', () => { provider.on("synced", () => {
setRemoteSynced(true); setRemoteSynced(true);
}); });
@ -85,10 +95,7 @@ export default function PageEditor({ pageId, editable = true }: PageEditorProps)
}; };
}, [remoteProvider, localProvider]); }, [remoteProvider, localProvider]);
const extensions = [ const extensions = [...mainExtensions, ...collabExtensions(remoteProvider)];
...mainExtensions,
...collabExtensions(remoteProvider),
];
const editor = useEditor( const editor = useEditor(
{ {
@ -97,8 +104,8 @@ export default function PageEditor({ pageId, editable = true }: PageEditorProps)
editorProps: { editorProps: {
handleDOMEvents: { handleDOMEvents: {
keydown: (_view, event) => { keydown: (_view, event) => {
if (['ArrowUp', 'ArrowDown', 'Enter'].includes(event.key)) { if (["ArrowUp", "ArrowDown", "Enter"].includes(event.key)) {
const slashCommand = document.querySelector('#slash-command'); const slashCommand = document.querySelector("#slash-command");
if (slashCommand) { if (slashCommand) {
return true; return true;
} }
@ -118,14 +125,18 @@ export default function PageEditor({ pageId, editable = true }: PageEditorProps)
useEffect(() => { useEffect(() => {
if (editor && currentUser.user) { if (editor && currentUser.user) {
editor.chain().focus().updateUser({ ...currentUser.user, color: getRandomColor() }).run(); editor
.chain()
.focus()
.updateUser({ ...currentUser.user, color: getRandomColor() })
.run();
} }
}, [editor, currentUser.user]); }, [editor, currentUser.user]);
const handleActiveCommentEvent = (event) => { const handleActiveCommentEvent = (event) => {
const { commentId } = event.detail; const { commentId } = event.detail;
setActiveCommentId(commentId); setActiveCommentId(commentId);
setAsideState({ tab: 'comments', isAsideOpen: true }); setAsideState({ tab: "comments", isAsideOpen: true });
const selector = `div[data-comment-id="${commentId}"]`; const selector = `div[data-comment-id="${commentId}"]`;
const commentElement = document.querySelector(selector); const commentElement = document.querySelector(selector);
@ -133,16 +144,19 @@ export default function PageEditor({ pageId, editable = true }: PageEditorProps)
}; };
useEffect(() => { useEffect(() => {
document.addEventListener('ACTIVE_COMMENT_EVENT', handleActiveCommentEvent); document.addEventListener("ACTIVE_COMMENT_EVENT", handleActiveCommentEvent);
return () => { return () => {
document.removeEventListener('ACTIVE_COMMENT_EVENT', handleActiveCommentEvent); document.removeEventListener(
"ACTIVE_COMMENT_EVENT",
handleActiveCommentEvent,
);
}; };
}, []); }, []);
useEffect(() => { useEffect(() => {
setActiveCommentId(null); setActiveCommentId(null);
setShowCommentPopup(false); setShowCommentPopup(false);
setAsideState({ tab: '', isAsideOpen: false }); setAsideState({ tab: "", isAsideOpen: false });
}, [pageId]); }, [pageId]);
const isSynced = isLocalSynced || isRemoteSynced; const isSynced = isLocalSynced || isRemoteSynced;
@ -165,6 +179,7 @@ export default function PageEditor({ pageId, editable = true }: PageEditorProps)
</div> </div>
)} )}
</div> </div>
) : <EditorSkeleton />; ) : (
<EditorSkeleton />
);
} }