Open platform to collect and prioritize feedback
Migrating existing functionality to use slate editor
Matt Roberts21c43edc45ca
diff --git a/public/components/common/form/SlateEditor.scss b/public/components/common/form/SlateEditor.scssnew file mode 100644index 000000000..1150ed4c2--- /dev/null+++ b/public/components/common/form/SlateEditor.scss@@ -0,0 +1,20 @@+@import "~@fider/assets/styles/variables.scss";++.slate-editor {+ background-color: get("colors.blue.100");+ width: 100%;+ line-height: get("font.size.xl");+ padding: spacing(2);+ resize: none;+ border: 1px solid get("colors.gray.300");+ border-radius: get("border.radius.medium");+ -webkit-appearance: none;+ appearance: none;++ &:disabled {+ @include disabled();+ }+ &--error {+ border-color: get("colors.red.600");+ }+}\ No newline at end of filediff --git a/public/components/common/form/SlateEditor.tsx b/public/components/common/form/SlateEditor.tsxnew file mode 100644index 000000000..e0f02dc03--- /dev/null+++ b/public/components/common/form/SlateEditor.tsx@@ -0,0 +1,59 @@+import React, { useState } from "react"+import { createEditor } from "slate"+// Import the Slate components and React plugin.+import { Slate, Editable, withReact } from "slate-react"+//+// TypeScript users only add this code+import { BaseEditor, Descendant, Node } from "slate"+import { ReactEditor } from "slate-react"+import "./SlateEditor.scss"++export type Paragraph = { type: "paragraph"; children: Text[] }+export type Text = { text: string }++declare module "slate" {+ interface CustomTypes {+ Editor: BaseEditor & ReactEditor+ Element: Paragraph+ Text: Text+ }+}++const emptyValue: Descendant[] = [+ {+ type: "paragraph",+ children: [{ text: "" }],+ },+]++interface SlateEditorProps {+ initialValue?: Descendant[]+ disabled?: boolean+ placeholder?: string+ onChange?: (value: Descendant[]) => void+ onFocus?: React.FocusEventHandler<HTMLDivElement>+ className?: string+}++export const SlateEditor: React.FunctionComponent<SlateEditorProps> = (props) => {+ const [editor] = useState(() => withReact(createEditor()))+ console.log(props.initialValue)++ return (+ <Slate editor={editor} initialValue={props.initialValue || emptyValue} onChange={props.onChange}>+ <Editable className="slate-editor" onFocus={props.onFocus} placeholder={props.placeholder} readOnly={props.disabled} />+ </Slate>+ )+}++export const Serialize = (nodes: Descendant[]): string => {+ return nodes.map((n) => Node.string(n)).join("\n")+}++export const Deserialize = (value: string): Descendant[] => {+ return value.split("\n").map((line) => {+ return {+ children: [{ text: line }],+ } as Descendant+ })+}diff --git a/public/components/common/index.tsx b/public/components/common/index.tsxindex e27734032..01521d7ef 100644--- a/public/components/common/index.tsx+++ b/public/components/common/index.tsx@@ -9,6 +9,7 @@ export * from "./form/DisplayError"export * from "./form/Select"export * from "./form/Field"export * from "./form/Checkbox"+export * from "./form/SlateEditor"export * from "./form/ImageViewer"export * from "./Markdown"export * from "./DevBanner"diff --git a/public/pages/ShowPost/components/CommentInput.tsx b/public/pages/ShowPost/components/CommentInput.tsxindex f97b82c49..5c23e6cc2 100644--- a/public/pages/ShowPost/components/CommentInput.tsx+++ b/public/pages/ShowPost/components/CommentInput.tsx@@ -9,24 +9,9 @@ import { useFider } from "@fider/hooks"import { HStack } from "@fider/components/layout"import { t, Trans } from "@lingui/macro"-import { createEditor } from "slate"-// Import the Slate components and React plugin.-import { Slate, Editable, withReact } from "slate-react"-//-// TypeScript users only add this code-import { BaseEditor, Descendant, Node } from "slate"-import { ReactEditor } from "slate-react"--type paragraph = { type: "paragraph"; children: text[] }-type text = { text: string }--declare module "slate" {- interface CustomTypes {- Editor: BaseEditor & ReactEditor- Element: paragraph- Text: text- }-}+import { SlateEditor, Serialize } from "@fider/components"+import { Descendant } from "slate"+import { Paragraph } from "@fider/components/common/form/SlateEditor"interface CommentInputProps {post: Post@@ -34,25 +19,22 @@ interface CommentInputProps {const CACHE_TITLE_KEY = "CommentInput-Comment-"-const initialValue: Descendant[] = [- {- type: "paragraph",- children: [{ text: "" }],- },-]-export const CommentInput = (props: CommentInputProps) => {const getCacheKey = () => `${CACHE_TITLE_KEY}${props.post.id}`- const [editor] = useState(() => withReact(createEditor()))+ const getContentFromCache = () => {+ const cacheVal = cache.session.get(getCacheKey())+ if (cacheVal) {+ return JSON.parse(cacheVal)+ }+ }const fider = useFider()// const inputRef = useRef<HTMLTextAreaElement>()- // const [content, setContent] = useState((fider.session.isAuthenticated && cache.session.get(getCacheKey())) || "")+ const [content, setContent] = useState<Descendant[]>((fider.session.isAuthenticated && getContentFromCache()) || null)const [isSignInModalOpen, setIsSignInModalOpen] = useState(false)const [attachments, setAttachments] = useState<ImageUpload[]>([])const [error, setError] = useState<Failure | undefined>(undefined)- const [hasContent, setHasContent] = useState(false)const hideModal = () => setIsSignInModalOpen(false)const clearError = () => setError(undefined)@@ -60,8 +42,7 @@ export const CommentInput = (props: CommentInputProps) => {const submit = async () => {clearError()- const editorText = serialize(editor.children)- console.log("editorText", editorText)+ const editorText = Serialize(content)const result = await actions.createComment(props.post.number, editorText, attachments)if (result.ok) {cache.session.remove(getCacheKey())@@ -71,23 +52,19 @@ export const CommentInput = (props: CommentInputProps) => {}}- const serialize = (nodes: Descendant[]): string => {- return nodes.map((n) => Node.string(n)).join("\n")- }-- const handleOnFocus = () => {- console.log("focus")+ const editorFocused = () => {if (!fider.session.isAuthenticated) {setIsSignInModalOpen(true)}}const commentChanged = (newContent: Descendant[]) => {- console.log("newContent", newContent, newContent.toString())- const contentExists = newContent.length > 0 && (newContent[0] as paragraph).children[0].text !== ""- setHasContent(contentExists)+ setContent(newContent)+ cache.session.set(getCacheKey(), JSON.stringify(newContent))}+ const hasContent = content?.length > 0 && (content[0] as Paragraph).children[0].text !== ""+return (<><SignInModal isOpen={isSignInModalOpen} onClose={hideModal} />@@ -100,9 +77,13 @@ export const CommentInput = (props: CommentInputProps) => {<UserName user={Fider.session.user} /></div>)}- <Slate editor={editor} initialValue={initialValue} onChange={commentChanged}>- <Editable onFocus={handleOnFocus} placeholder={t({ id: "showpost.commentinput.placeholder", message: "Leave a comment" })} />- </Slate>+ <SlateEditor+ initialValue={content}+ onChange={commentChanged}+ onFocus={editorFocused}+ disabled={!Fider.session.isAuthenticated}+ placeholder={t({ id: "showpost.commentinput.placeholder", message: "Leave a comment" })}+ />{hasContent && (<><MultiImageUploader field="attachments" maxUploads={2} onChange={setAttachments} />diff --git a/public/pages/ShowPost/components/ShowComment.tsx b/public/pages/ShowPost/components/ShowComment.tsxindex 73ef4ca1a..ff1d9d30b 100644--- a/public/pages/ShowPost/components/ShowComment.tsx+++ b/public/pages/ShowPost/components/ShowComment.tsx@@ -1,25 +1,13 @@import React, { useEffect, useRef, useState } from "react"import { Comment, Post, ImageUpload } from "@fider/models"-import {- Reactions,- Avatar,- UserName,- Moment,- Form,- TextArea,- Button,- Markdown,- Modal,- ImageViewer,- MultiImageUploader,- Dropdown,- Icon,-} 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, Trans } from "@lingui/macro"+import { Deserialize, Serialize, SlateEditor } from "@fider/components/common/form/SlateEditor"+import { Descendant } from "slate"interface ShowCommentProps {post: Post@@ -32,7 +20,7 @@ export const ShowComment = (props: ShowCommentProps) => {const fider = useFider()const node = useRef<HTMLDivElement | null>(null)const [isEditing, setIsEditing] = useState(false)- const [newContent, setNewContent] = useState("")+ const [newContent, setNewContent] = useState<Descendant[]>([])const [isDeleteConfirmationModalOpen, setIsDeleteConfirmationModalOpen] = useState(false)const [attachments, setAttachments] = useState<ImageUpload[]>([])const [localReactionCounts, setLocalReactionCounts] = useState(props.comment.reactionCounts)@@ -66,12 +54,13 @@ export const ShowComment = (props: ShowCommentProps) => {const cancelEdit = async () => {setIsEditing(false)- setNewContent("")+ setNewContent([])clearError()}const saveEdit = async () => {- const response = await actions.updateComment(props.post.number, props.comment.id, newContent, attachments)+ const editorText = Serialize(newContent)+ const response = await actions.updateComment(props.post.number, props.comment.id, editorText, attachments)if (response.ok) {location.reload()} else {@@ -126,7 +115,7 @@ export const ShowComment = (props: ShowCommentProps) => {)} else if (action === "edit") {setIsEditing(true)- setNewContent(props.comment.content)+ setNewContent(Deserialize(props.comment.content))clearError()} else if (action === "delete") {setIsDeleteConfirmationModalOpen(true)@@ -210,7 +199,8 @@ export const ShowComment = (props: ShowCommentProps) => {<div>{isEditing ? (<Form error={error}>- <TextArea field="content" minRows={1} value={newContent} placeholder={comment.content} onChange={setNewContent} />+ <SlateEditor initialValue={newContent} onChange={setNewContent} placeholder={comment.content} />+ {/* <TextArea field="content" minRows={1} value={newContent} placeholder={comment.content} onChange={setNewContent} /> */}<MultiImageUploader field="attachments" bkeys={comment.attachments} maxUploads={2} onChange={setAttachments} /><Button size="small" onClick={saveEdit} variant="primary"><Trans id="action.save">Save</Trans>