Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

Removed slate, more tidying

Matt Robertse7d669c373ae
diff --git a/package.json b/package.json
index e8bf2cd89..62b12d062 100644
--- a/package.json
+++ b/package.json
@@ -19,9 +19,6 @@
"react-dom": "^18.3.1",
"react-textarea-autosize": "^8.5.4",
"react-toastify": "^9.0.1",
- "slate": "^0.110.2",
- "slate-history": "^0.110.3",
- "slate-react": "^0.111.0",
"tippy.js": "^6.3.7",
"tiptap-markdown": "^0.8.10"
},
diff --git a/public/components/common/form/CommentEditor.tsx b/public/components/common/form/CommentEditor.tsx
index 98b0df9ac..0821f077e 100644
--- a/public/components/common/form/CommentEditor.tsx
+++ b/public/components/common/form/CommentEditor.tsx
@@ -1,351 +1,162 @@
-import React, { useMemo, useCallback, useRef, useEffect, useState, Fragment, ReactNode } from "react"
-import { Element, Editor, Transforms, Range, createEditor, Descendant, BaseEditor, BaseRange, Node } from "slate"
-import { HistoryEditor, withHistory } from "slate-history"
-import { Slate, Editable, ReactEditor, withReact, useSelected, useFocused, RenderPlaceholderProps } from "slate-react"
-
-export const IS_MAC = typeof navigator !== "undefined" && /Mac OS X/.test(navigator.userAgent)
-
-import ReactDOM from "react-dom"
-import { UserNames } from "@fider/models"
-import { actions } from "@fider/services"
+// src/Tiptap.tsx
+import { Editor } from "@tiptap/react"
+import StarterKit from "@tiptap/starter-kit"
+import React from "react"
+import { EditorContent, useEditor } from "@tiptap/react"
+import { Markdown } from "tiptap-markdown"
+import Placeholder from "@tiptap/extension-placeholder"
import "./CommentEditor.scss"
-export type TextType = { text: string }
-
-interface RenderElementProps {
- attributes: React.HTMLAttributes<HTMLElement>
- element: CustomElement
- children: React.ReactNode
-}
-
-type MentionElement = {
- type: "mention"
- character: string
- children: TextType[]
-}
-
-export type ParagraphElement = {
- type: "paragraph"
- children: Descendant[]
-}
-
-type CustomElement = MentionElement | ParagraphElement
-
-type CustomEditor = BaseEditor &
- ReactEditor &
- HistoryEditor & {
- nodeToDecorations?: Map<Element, Range[]>
- }
-
-const emptyValue: Descendant[] = [
- {
- type: "paragraph",
- children: [{ text: "" }],
- },
-]
-
-declare module "slate" {
- interface CustomTypes {
- Editor: CustomEditor
- Element: CustomElement
- Text: TextType
- Range: BaseRange & {
- [key: string]: unknown
- }
+// At the top of the file, add imports for your icons
+import IconH2 from "@fider/assets/images/heroicons-h2.svg"
+import IconH3 from "@fider/assets/images/heroicons-h3.svg"
+import IconItalic from "@fider/assets/images/heroicons-italic.svg"
+import IconBold from "@fider/assets/images/heroicons-bold.svg"
+import IconStrike from "@fider/assets/images/heroicons-strike.svg"
+import IconCode from "@fider/assets/images/heroicons-code.svg"
+import IconOrderedList from "@fider/assets/images/heroicons-orderedlist.svg"
+import IconBulletList from "@fider/assets/images/heroicons-bulletlist.svg"
+import { Icon } from "@fider/components"
+
+import suggestion from "./suggestion"
+import { CustomMention } from "./CustomMention"
+
+// define your extension array
+const MenuBar = ({ editor }: { editor: Editor | null }) => {
+ if (!editor) {
+ return null
}
-}
-const Portal = ({ children }: { children?: ReactNode }) => {
- return typeof document === "object" ? ReactDOM.createPortal(children, document.body) : null
+ return (
+ <div className="c-editor-toolbar">
+ <div className="c-editor-button-group">
+ <button
+ type="button"
+ title="Heading 2"
+ onClick={() => editor.chain().focus().toggleHeading({ level: 2 }).run()}
+ className={`c-editor-button ${editor.isActive("heading", { level: 2 }) ? "is-active" : ""}`}
+ >
+ <Icon sprite={IconH2} width="18" height="18" />
+ </button>
+ <button
+ type="button"
+ title="Heading 3"
+ onClick={() => editor.chain().focus().toggleHeading({ level: 3 }).run()}
+ className={`c-editor-button ${editor.isActive("heading", { level: 3 }) ? "is-active" : ""}`}
+ >
+ <Icon sprite={IconH3} />
+ </button>
+ <button
+ type="button"
+ title="Bold"
+ onClick={() => editor.chain().focus().toggleBold().run()}
+ className={`c-editor-button ${editor.isActive("bold") ? "is-active" : ""}`}
+ >
+ <Icon sprite={IconBold} />
+ </button>
+ <button
+ type="button"
+ title="Italic"
+ onClick={() => editor.chain().focus().toggleItalic().run()}
+ className={`c-editor-button ${editor.isActive("italic") ? "is-active" : ""}`}
+ >
+ <Icon sprite={IconItalic} />
+ </button>
+ <button
+ type="button"
+ title="Strikethrough"
+ onClick={() => editor.chain().focus().toggleStrike().run()}
+ className={`c-editor-button ${editor.isActive("strike") ? "is-active" : ""}`}
+ >
+ <Icon sprite={IconStrike} />
+ </button>
+ <button
+ type="button"
+ title="BulletList"
+ onClick={() => editor.chain().focus().toggleBulletList().run()}
+ className={`c-editor-button ${editor.isActive("bulletList") ? "is-active" : ""}`}
+ >
+ <Icon sprite={IconBulletList} />
+ </button>
+ <button
+ type="button"
+ title="OrderedList"
+ onClick={() => editor.chain().focus().toggleOrderedList().run()}
+ className={`c-editor-button ${editor.isActive("orderedList") ? "is-active" : ""}`}
+ >
+ <Icon sprite={IconOrderedList} />
+ </button>
+ <button
+ type="button"
+ title="Code"
+ onClick={() => editor.chain().focus().toggleCodeBlock().run()}
+ className={`c-editor-button ${editor.isActive("codeBlock") ? "is-active" : ""}`}
+ >
+ <Icon sprite={IconCode} />
+ </button>
+ </div>
+ </div>
+ )
}
interface CommentEditorProps {
- initialValue?: string
+ initialValue: string | null
placeholder?: string
onChange?: (value: string) => void
- onFocus?: React.FocusEventHandler<HTMLDivElement>
- className?: string
+ onFocus?: () => void
}
-const Placeholder = ({ attributes, children }: RenderPlaceholderProps) => {
- return (
- <span
- {...attributes}
- className="slate-editor--placeholder"
- style={{
- position: "absolute",
- opacity: 0.3,
- userSelect: "none",
- pointerEvents: "none",
- }}
- >
- {children}
- </span>
- )
-}
-
-export const CommentEditor: React.FunctionComponent<CommentEditorProps> = (props) => {
- const [users, setUsers] = useState<UserNames[]>([])
- const ref = useRef<HTMLDivElement | null>(null)
- const [target, setTarget] = useState<Range | undefined>()
- const [index, setIndex] = useState(0)
- const [search, setSearch] = useState("")
-
- useEffect(() => {
- console.log("target changed", target)
- }, [target])
-
- const renderElement = useCallback((props: RenderElementProps) => <SlateElement {...props} />, [])
- const editor = useMemo(() => withMentions(withReact(withHistory(createEditor()))), [])
-
- const filteredUsers = users.filter((user) => user.name.toLowerCase().startsWith(search.toLowerCase())).slice(0, 10)
-
- const onKeyDown = useCallback(
- (event: React.KeyboardEvent<HTMLDivElement>) => {
- if (target && filteredUsers.length > 0) {
- switch (event.key) {
- case "ArrowDown": {
- event.preventDefault()
- const prevIndex = index >= filteredUsers.length - 1 ? 0 : index + 1
- setIndex(prevIndex)
- break
- }
- case "ArrowUp": {
- event.preventDefault()
- const nextIndex = index <= 0 ? filteredUsers.length - 1 : index - 1
- setIndex(nextIndex)
- break
- }
- case "Tab":
- case "Enter":
- event.preventDefault()
- Transforms.select(editor, target)
- insertMention(editor, filteredUsers[index])
- setTarget(undefined)
- break
- case "Escape":
- event.preventDefault()
- setTarget(undefined)
- break
- }
+const Tiptap: React.FunctionComponent<CommentEditorProps> = (props) => {
+ const updated = ({ editor }: { editor: Editor; transaction: any }): void => {
+ const markdown = editor.storage.markdown.getMarkdown()
+ props.onChange && props.onChange(markdown)
+ }
+ const initialValue = props.initialValue ?? ""
+
+ const extensions = [
+ StarterKit,
+ Markdown.configure({
+ html: true,
+ }),
+ CustomMention.configure({
+ HTMLAttributes: {
+ class: "mention",
+ },
+ suggestion,
+ }),
+ Placeholder.configure({
+ placeholder: props.placeholder ?? "Write your comment here...",
+ emptyEditorClass: "tiptap-is-empty",
+ }),
+ ]
+
+ const editor = useEditor({
+ extensions,
+ content: initialValue,
+ onUpdate: updated,
+ onFocus: () => {
+ if (props.onFocus) {
+ props.onFocus()
}
},
- [filteredUsers, editor, index, target]
- )
-
- // Where to show the mentions portal
- useEffect(() => {
- if (target && filteredUsers.length > 0 && ref.current) {
- const el = ref.current
- const domRange = ReactEditor.toDOMRange(editor, target)
- const rect = domRange.getBoundingClientRect()
- el.style.top = `${rect.top + window.pageYOffset + 24}px`
- el.style.left = `${rect.left + window.pageXOffset}px`
- }
- }, [filteredUsers.length, editor, index, search, target])
-
- const initialValue = props.initialValue ? deserialize(props.initialValue) : emptyValue
-
- return (
- <Slate
- editor={editor}
- initialValue={initialValue}
- onChange={(descendant) => {
- const { selection } = editor
-
- if (selection && Range.isCollapsed(selection)) {
- const [start] = Range.edges(selection)
- const wordBefore = Editor.before(editor, start, { unit: "word" })
- const before = wordBefore && Editor.before(editor, wordBefore)
- const beforeRange = before && Editor.range(editor, before, start)
- const beforeText = beforeRange && Editor.string(editor, beforeRange)
- const beforeMatch = beforeText && beforeText.match(/^@(\w+)$/)
- const after = Editor.after(editor, start)
- const afterRange = Editor.range(editor, start, after)
- const afterText = Editor.string(editor, afterRange)
- const afterMatch = afterText.match(/^(\s|$)/)
-
- if (beforeMatch && afterMatch) {
- setTarget(beforeRange)
- setSearch(beforeMatch[1])
- setIndex(0)
-
- // Load users when @ is typed
- const loadUsers = async () => {
- const result = await actions.getTaggableUsers("")
- if (result.ok) {
- setUsers(result.data)
- }
- }
- users.length === 0 && loadUsers()
- return
- }
-
- console.log(JSON.stringify(descendant))
-
- props.onChange && props.onChange(serialize(descendant))
- }
-
- setTarget(undefined)
- }}
- >
- <Editable
- readOnly={false}
- className="slate-editor"
- renderElement={renderElement}
- onKeyDown={onKeyDown}
- onFocus={props.onFocus}
- placeholder={props.placeholder}
- renderPlaceholder={Placeholder}
- />
- {target && filteredUsers.length > 0 && (
- <Portal>
- <div ref={ref} className="slate-editor--mentions" data-cy="mentions-portal">
- {filteredUsers.map((user, i) => (
- <div
- key={user.id}
- onClick={() => {
- Transforms.select(editor, target)
- insertMention(editor, user)
- setTarget(undefined)
- }}
- style={{
- padding: "6px 12px",
- borderRadius: "3px",
- cursor: "pointer",
- background: i === index ? "#B4D5FF" : "transparent",
- }}
- >
- {user.name}
- </div>
- ))}
- </div>
- </Portal>
- )}
- </Slate>
- )
-}
-
-const withMentions = (editor: CustomEditor) => {
- const { isInline, isVoid, markableVoid } = editor
-
- editor.isInline = (element: CustomElement) => {
- return element.type === "mention" ? true : isInline(element)
- }
-
- editor.isVoid = (element: CustomElement) => {
- return element.type === "mention" ? true : isVoid(element)
- }
-
- editor.markableVoid = (element: CustomElement) => {
- return element.type === "mention" || markableVoid(element)
- }
-
- return editor
-}
-
-const insertMention = (editor: Editor, user: UserNames) => {
- const newMention = { ...user, isNew: true }
- const mention: MentionElement = {
- type: "mention",
- character: user.name,
- children: [{ text: "@" + JSON.stringify(newMention) }],
- }
- Transforms.insertNodes(editor, mention)
- Transforms.move(editor)
-}
-
-const SlateElement = (props: RenderElementProps) => {
- const { attributes, children, element } = props
- switch (element.type) {
- case "mention":
- return <Mention {...(props as { attributes: React.HTMLAttributes<HTMLSpanElement>; children: React.ReactNode; element: MentionElement })} />
- default:
- return <p {...attributes}>{children}</p>
- }
-}
+ editorProps: {
+ attributes: {
+ class: "no-focus",
+ },
+ },
+ })
-const Mention = ({
- attributes,
- children,
- element,
-}: {
- attributes: React.HTMLAttributes<HTMLSpanElement>
- children: React.ReactNode
- element: MentionElement
-}) => {
- const selected = useSelected()
- const focused = useFocused()
- const style: React.CSSProperties = {
- boxShadow: selected && focused ? "0 0 0 2px #B4D5FF" : "none",
- }
- // See if our empty text child has any styling marks applied and apply those
return (
- <span {...attributes} className="slate-editor--mention" contentEditable={false} data-cy={`mention-${element.character.replace(" ", "-")}`} style={style}>
- {/* Prevent Chromium from interrupting IME when moving the cursor */}
- {/* 1. span + inline-block 2. div + contenteditable=false */}
- <div contentEditable={false}>
- {IS_MAC ? (
- // Mac OS IME https://github.com/ianstormtaylor/slate/issues/3490
- <Fragment>
- {children}@{element.character}
- </Fragment>
- ) : (
- // Others like Android https://github.com/ianstormtaylor/slate/pull/5360
- <Fragment>
- @{element.character}
- {children}
- </Fragment>
- )}
- </div>
- </span>
+ <div className="fider-tiptap-editor">
+ <MenuBar editor={editor} />
+ <EditorContent editor={editor} />
+ </div>
)
}
-const serialize = (nodes: Descendant[]): string => {
- return nodes.map((n) => Node.string(n)).join("\n")
-}
-
-const deserialize = (markdown: string): Descendant[] => {
- return markdown.split("\n").map((line) => {
- const children: Descendant[] = []
- const regex = /@{\\?"id\\?":\d+,\\?"name\\?":\\?"[^"]+\\?"(,\\?"isNew\\?":[^}]+)?}/g
- let lastIndex = 0
+const CommentEditor = React.memo(Tiptap, (prevProps, nextProps) => {
+ return prevProps.placeholder === nextProps.placeholder
+})
- let match
- while ((match = regex.exec(line)) !== null) {
- // Add text before the mention
- if (match.index > lastIndex) {
- children.push({ text: line.slice(lastIndex, match.index) })
- }
-
- // Handle mention
- try {
- const jsonStr = match[0].replace(/\\/g, "").slice(1)
- const mentionData = JSON.parse(jsonStr)
- children.push({
- type: "mention",
- character: mentionData.name,
- children: [{ text: match[0] }],
- })
- } catch (err) {
- console.error("Error parsing mention:", err)
- // Just add the text as a normal paragraph
- children.push({ text: line })
- }
-
- lastIndex = match.index + match[0].length
- }
-
- // Add remaining text after last mention
- if (lastIndex <= line.length) {
- children.push({ text: line.slice(lastIndex) })
- }
-
- return {
- type: "paragraph",
- children,
- }
- })
-}
+export default CommentEditor
diff --git a/public/components/common/form/CommentEditor2.tsx b/public/components/common/form/CommentEditor2.tsx
deleted file mode 100644
index 0b0d7c568..000000000
--- a/public/components/common/form/CommentEditor2.tsx
+++ /dev/null
@@ -1,165 +0,0 @@
-// src/Tiptap.tsx
-import { Editor } from "@tiptap/react"
-import StarterKit from "@tiptap/starter-kit"
-import React from "react"
-import { EditorContent, useEditor } from "@tiptap/react"
-import { Markdown } from "tiptap-markdown"
-import Placeholder from "@tiptap/extension-placeholder"
-// import Mention from "@tiptap/extension-mention"
-
-import "./CommentEditor.scss"
-
-// At the top of the file, add imports for your icons
-import IconH2 from "@fider/assets/images/heroicons-h2.svg"
-import IconH3 from "@fider/assets/images/heroicons-h3.svg"
-import IconItalic from "@fider/assets/images/heroicons-italic.svg"
-import IconBold from "@fider/assets/images/heroicons-bold.svg"
-import IconStrike from "@fider/assets/images/heroicons-strike.svg"
-import IconCode from "@fider/assets/images/heroicons-code.svg"
-import IconOrderedList from "@fider/assets/images/heroicons-orderedlist.svg"
-import IconBulletList from "@fider/assets/images/heroicons-bulletlist.svg"
-import { Icon } from "@fider/components"
-
-import suggestion from "./suggestion"
-import { CustomMention } from "./CustomMention"
-// import CustomMarkdown from "./MentionMarkdown"
-
-// define your extension array
-
-const MenuBar = ({ editor }: { editor: Editor | null }) => {
- if (!editor) {
- return null
- }
-
- return (
- <div className="c-editor-toolbar">
- <div className="c-editor-button-group">
- <button
- type="button"
- title="Heading 2"
- onClick={() => editor.chain().focus().toggleHeading({ level: 2 }).run()}
- className={`c-editor-button ${editor.isActive("heading", { level: 2 }) ? "is-active" : ""}`}
- >
- <Icon sprite={IconH2} width="18" height="18" />
- </button>
- <button
- type="button"
- title="Heading 3"
- onClick={() => editor.chain().focus().toggleHeading({ level: 3 }).run()}
- className={`c-editor-button ${editor.isActive("heading", { level: 3 }) ? "is-active" : ""}`}
- >
- <Icon sprite={IconH3} />
- </button>
- <button
- type="button"
- title="Bold"
- onClick={() => editor.chain().focus().toggleBold().run()}
- className={`c-editor-button ${editor.isActive("bold") ? "is-active" : ""}`}
- >
- <Icon sprite={IconBold} />
- </button>
- <button
- type="button"
- title="Italic"
- onClick={() => editor.chain().focus().toggleItalic().run()}
- className={`c-editor-button ${editor.isActive("italic") ? "is-active" : ""}`}
- >
- <Icon sprite={IconItalic} />
- </button>
- <button
- type="button"
- title="Strikethrough"
- onClick={() => editor.chain().focus().toggleStrike().run()}
- className={`c-editor-button ${editor.isActive("strike") ? "is-active" : ""}`}
- >
- <Icon sprite={IconStrike} />
- </button>
- <button
- type="button"
- title="BulletList"
- onClick={() => editor.chain().focus().toggleBulletList().run()}
- className={`c-editor-button ${editor.isActive("bulletList") ? "is-active" : ""}`}
- >
- <Icon sprite={IconBulletList} />
- </button>
- <button
- type="button"
- title="OrderedList"
- onClick={() => editor.chain().focus().toggleOrderedList().run()}
- className={`c-editor-button ${editor.isActive("orderedList") ? "is-active" : ""}`}
- >
- <Icon sprite={IconOrderedList} />
- </button>
- <button
- type="button"
- title="Code"
- onClick={() => editor.chain().focus().toggleCodeBlock().run()}
- className={`c-editor-button ${editor.isActive("codeBlock") ? "is-active" : ""}`}
- >
- <Icon sprite={IconCode} />
- </button>
- </div>
- </div>
- )
-}
-
-interface CommentEditorProps2 {
- initialValue: string | null
- placeholder?: string
- onChange?: (value: string) => void
- onFocus?: () => void
-}
-
-const Tiptap: React.FunctionComponent<CommentEditorProps2> = (props) => {
- const updated = ({ editor }: { editor: Editor; transaction: any }): void => {
- const markdown = editor.storage.markdown.getMarkdown()
- props.onChange && props.onChange(markdown)
- }
- const initialValue = props.initialValue ?? ""
-
- const extensions = [
- StarterKit,
- Markdown.configure({
- html: true,
- }),
- CustomMention.configure({
- HTMLAttributes: {
- class: "mention",
- },
- suggestion,
- }),
- Placeholder.configure({
- placeholder: props.placeholder ?? "Write your comment here...",
- emptyEditorClass: "tiptap-is-empty",
- }),
- ]
-
- const editor = useEditor({
- extensions,
- content: initialValue,
- onUpdate: updated,
- onFocus: () => {
- if (props.onFocus) {
- props.onFocus()
- }
- },
- editorProps: {
- attributes: {
- class: "no-focus",
- },
- },
- })
-
- return (
- <div className="fider-tiptap-editor">
- <MenuBar editor={editor} />
- <EditorContent editor={editor} />
- </div>
- )
-}
-
-const MemoizedTiptap = React.memo(Tiptap, (prevProps, nextProps) => {
- return prevProps.placeholder === nextProps.placeholder
-})
-
-export default MemoizedTiptap
diff --git a/public/pages/ShowPost/components/CommentInput.tsx b/public/pages/ShowPost/components/CommentInput.tsx
index 6ed40de59..f582195f7 100644
--- a/public/pages/ShowPost/components/CommentInput.tsx
+++ b/public/pages/ShowPost/components/CommentInput.tsx
@@ -12,7 +12,7 @@ import { Trans } from "@lingui/react/macro"
// import { CommentEditor } from "@fider/components"
import { useFider } from "@fider/hooks"
// import Tiptap from "@fider/components/common/form/CommentEditor2"
-import MemoizedTiptap from "@fider/components/common/form/CommentEditor2"
+import CommentEditor from "@fider/components/common/form/CommentEditor"
interface CommentInputProps {
post: Post
@@ -76,7 +76,7 @@ export const CommentInput = (props: CommentInputProps) => {
<UserName user={Fider.session.user} />
</div>
)}
- <MemoizedTiptap
+ <CommentEditor
onChange={commentChanged}
onFocus={editorFocused}
initialValue={getContentFromCache()}
diff --git a/public/pages/ShowPost/components/ShowComment.tsx b/public/pages/ShowPost/components/ShowComment.tsx
index b3c232a2f..f6ae11947 100644
--- a/public/pages/ShowPost/components/ShowComment.tsx
+++ b/public/pages/ShowPost/components/ShowComment.tsx
@@ -1,26 +1,13 @@
import React, { useEffect, useRef, useState } from "react"
import { Comment, Post, ImageUpload } from "@fider/models"
-import {
- Reactions,
- Avatar,
- UserName,
- Moment,
- Form,
- Button,
- Markdown,
- Modal,
- ImageViewer,
- MultiImageUploader,
- Dropdown,
- Icon,
- CommentEditor,
-} from "@fider/components"
+import { Reactions, Avatar, UserName, Moment, Form, Button, Markdown, Modal, ImageViewer, MultiImageUploader, Dropdown, Icon } from "@fider/components"
import { HStack } from "@fider/components/layout"
import { formatDate, Failure, actions, notify, copyToClipboard, classSet, clearUrlHash } from "@fider/services"
import { useFider } from "@fider/hooks"
import IconDotsHorizontal from "@fider/assets/images/heroicons-dots-horizontal.svg"
import { t } from "@lingui/core/macro"
import { Trans } from "@lingui/react/macro"
+import CommentEditor from "@fider/components/common/form/CommentEditor"
interface ShowCommentProps {
post: Post