Open platform to collect and prioritize feedback
Mentions work but much refatoring needed.
Matt Robertsa18edc7f8a23
diff --git a/public/components/common/form/SlateEditor.scss b/public/components/common/form/SlateEditor.scssindex 1150ed4c2..866eedef4 100644--- a/public/components/common/form/SlateEditor.scss+++ b/public/components/common/form/SlateEditor.scss@@ -2,14 +2,15 @@.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;+ // 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;+ margin: spacing(3) 0;&:disabled {@include disabled();@@ -17,4 +18,25 @@&--error {border-color: get("colors.red.600");}-}\ No newline at end of file+}+.slate-editor--mention {+ // padding: 3px 3px 2px;+ margin: 0 1px;+ vertical-align: baseline;+ display: inline-block;+ border-radius: 4px;+ background-color: get("colors.gray.100");+ font-size: get("font.size.sm");+}++.slate-editor--mentions {+ top: -9999px;+ left: -9999px;+ position: absolute;+ z-index: 1;+ padding: 3px;+ background: get("colors.white");+ border-radius: 4px;+ box-shadow: 0 1px 5px rgba(0, 0, 0, 0.2);+}+diff --git a/public/components/common/form/SlateEditor.tsx b/public/components/common/form/SlateEditor.tsxindex e0f02dc03..4789413cf 100644--- a/public/components/common/form/SlateEditor.tsx+++ b/public/components/common/form/SlateEditor.tsx@@ -1,59 +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- })-}+// 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 "slate2" {+// 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/form/SlateEditor2.tsx b/public/components/common/form/SlateEditor2.tsxnew file mode 100644index 000000000..2b7dbbd16--- /dev/null+++ b/public/components/common/form/SlateEditor2.tsx@@ -0,0 +1,326 @@+import React, { useMemo, useCallback, useRef, useEffect, useState, Fragment, ReactNode } from "react"+import { Editor, Transforms, Range, createEditor, Descendant, BaseEditor, BaseRange } from "slate"+import { HistoryEditor, withHistory } from "slate-history"+import { Slate, Editable, ReactEditor, withReact, useSelected, useFocused } 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"++import "./SlateEditor.scss"++type CustomText = {+ bold?: boolean+ italic?: boolean+ code?: boolean+ text: string+}++type EmptyText = {+ text: string+}++interface RenderElementProps {+ attributes: React.HTMLAttributes<HTMLElement>+ element: CustomElement+ children: React.ReactNode+}++type MentionElement = {+ type: "mention"+ character: string+ children: CustomText[]+}++type ParagraphElement = {+ type: "paragraph"+ align?: string+ children: Descendant[]+}++type CustomElement = MentionElement | ParagraphElement++type CustomEditor = BaseEditor &+ ReactEditor &+ HistoryEditor & {+ nodeToDecorations?: Map<Element, Range[]>+ }++declare module "slate" {+ interface CustomTypes {+ Editor: CustomEditor+ Element: CustomElement+ Text: CustomText | EmptyText+ Range: BaseRange & {+ [key: string]: unknown+ }+ }+}++const Portal = ({ children }: { children?: ReactNode }) => {+ return typeof document === "object" ? ReactDOM.createPortal(children, document.body) : null+}++export const MentionExample = () => {+ 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("")++ // Fetch users when component mounts+ useEffect(() => {+ const loadUsers = async () => {+ const result = await actions.getTaggableUsers("")+ if (result.ok) {+ setUsers(result.data)+ }+ }+ loadUsers()+ }, [])++ const renderElement = useCallback((props: RenderElementProps) => <Element {...props} />, [])+ // const renderLeaf = useCallback((props: { attributes: any; leaf: any; children: any }) => <Leaf {...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].name)+ setTarget(undefined)+ break+ case "Escape":+ event.preventDefault()+ setTarget(undefined)+ break+ }+ }+ },+ [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])++ return (+ <Slate+ editor={editor}+ initialValue={initialValue}+ onChange={() => {+ 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)+ return+ }+ }++ setTarget(undefined)+ }}+ >+ <Editable className="slate-editor" renderElement={renderElement} onKeyDown={onKeyDown} placeholder="Enter some text..." />+ {target && filteredUsers.length > 0 && (+ <Portal>+ <div ref={ref} className="slate-editor--mentions" data-cy="mentions-portal">+ {filteredUsers.map((char, i) => (+ <div+ key={char.name}+ onClick={() => {+ Transforms.select(editor, target)+ insertMention(editor, char.name)+ setTarget(undefined)+ }}+ style={{+ padding: "6px 12px",+ borderRadius: "3px",+ cursor: "pointer",+ background: i === index ? "#B4D5FF" : "transparent",+ }}+ >+ {char.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, character: string) => {+ const mention: MentionElement = {+ type: "mention",+ character,+ children: [{ text: "" }],+ }+ Transforms.insertNodes(editor, mention)+ Transforms.move(editor)+}++const Element = (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>+ }+}++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>+ )+}+const initialValue: Descendant[] = [+ {+ type: "paragraph",+ children: [+ {+ text: "This example shows how you might implement a simple ",+ },+ {+ text: "@-mentions",+ bold: true,+ },+ {+ text: " feature that lets users autocomplete mentioning a user by their username. Which, in this case means Star Wars characters. The ",+ },+ {+ text: "mentions",+ bold: true,+ },+ {+ text: " are rendered as ",+ },+ {+ text: "void inline elements",+ code: true,+ },+ {+ text: " inside the document.",+ },+ ],+ },+ {+ type: "paragraph",+ children: [+ { text: "Try mentioning characters, like " },+ {+ type: "mention",+ character: "R2-D2",+ children: [{ text: "", bold: true }],+ },+ { text: " or " },+ {+ type: "mention",+ character: "Mace Windu",+ children: [{ text: "" }],+ },+ { text: "!" },+ ],+ },+]++// 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 01521d7ef..6908a513f 100644--- a/public/components/common/index.tsx+++ b/public/components/common/index.tsx@@ -9,7 +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/SlateEditor2"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 5c23e6cc2..8b83a7281 100644--- a/public/pages/ShowPost/components/CommentInput.tsx+++ b/public/pages/ShowPost/components/CommentInput.tsx@@ -5,13 +5,10 @@ import { Avatar, UserName, Button, Form, MultiImageUploader } from "@fider/compoimport { SignInModal } from "@fider/components"import { cache, actions, Failure, Fider } from "@fider/services"-import { useFider } from "@fider/hooks"import { HStack } from "@fider/components/layout"-import { t, Trans } from "@lingui/macro"+import { Trans } from "@lingui/macro"-import { SlateEditor, Serialize } from "@fider/components"-import { Descendant } from "slate"-import { Paragraph } from "@fider/components/common/form/SlateEditor"+import { MentionExample } from "@fider/components"interface CommentInputProps {post: Post@@ -22,16 +19,8 @@ const CACHE_TITLE_KEY = "CommentInput-Comment-"export const CommentInput = (props: CommentInputProps) => {const getCacheKey = () => `${CACHE_TITLE_KEY}${props.post.id}`- 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<Descendant[]>((fider.session.isAuthenticated && getContentFromCache()) || null)const [isSignInModalOpen, setIsSignInModalOpen] = useState(false)const [attachments, setAttachments] = useState<ImageUpload[]>([])const [error, setError] = useState<Failure | undefined>(undefined)@@ -42,7 +31,7 @@ export const CommentInput = (props: CommentInputProps) => {const submit = async () => {clearError()- const editorText = Serialize(content)+ const editorText = "Hello"const result = await actions.createComment(props.post.number, editorText, attachments)if (result.ok) {cache.session.remove(getCacheKey())@@ -52,18 +41,7 @@ export const CommentInput = (props: CommentInputProps) => {}}- const editorFocused = () => {- if (!fider.session.isAuthenticated) {- setIsSignInModalOpen(true)- }- }-- const commentChanged = (newContent: Descendant[]) => {- setContent(newContent)- cache.session.set(getCacheKey(), JSON.stringify(newContent))- }-- const hasContent = content?.length > 0 && (content[0] as Paragraph).children[0].text !== ""+ const hasContent = truereturn (<>@@ -77,13 +55,7 @@ export const CommentInput = (props: CommentInputProps) => {<UserName user={Fider.session.user} /></div>)}- <SlateEditor- initialValue={content}- onChange={commentChanged}- onFocus={editorFocused}- disabled={!Fider.session.isAuthenticated}- placeholder={t({ id: "showpost.commentinput.placeholder", message: "Leave a comment" })}- />+ <MentionExample />{hasContent && (<><MultiImageUploader field="attachments" maxUploads={2} onChange={setAttachments} />diff --git a/public/pages/ShowPost/components/ShowComment.tsx b/public/pages/ShowPost/components/ShowComment.tsxindex ff1d9d30b..e4fae2b08 100644--- a/public/pages/ShowPost/components/ShowComment.tsx+++ b/public/pages/ShowPost/components/ShowComment.tsx@@ -1,13 +1,26 @@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 } from "@fider/components"+import {+ Reactions,+ Avatar,+ UserName,+ Moment,+ Form,+ Button,+ Markdown,+ Modal,+ ImageViewer,+ MultiImageUploader,+ Dropdown,+ Icon,+ TextArea,+} 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"+// import { Deserialize, Serialize} from "@fider/components/common/form/SlateEditor"interface ShowCommentProps {post: Post@@ -20,7 +33,7 @@ export const ShowComment = (props: ShowCommentProps) => {const fider = useFider()const node = useRef<HTMLDivElement | null>(null)const [isEditing, setIsEditing] = useState(false)- const [newContent, setNewContent] = useState<Descendant[]>([])+ const [newContent, setNewContent] = useState<string>()const [isDeleteConfirmationModalOpen, setIsDeleteConfirmationModalOpen] = useState(false)const [attachments, setAttachments] = useState<ImageUpload[]>([])const [localReactionCounts, setLocalReactionCounts] = useState(props.comment.reactionCounts)@@ -54,12 +67,12 @@ export const ShowComment = (props: ShowCommentProps) => {const cancelEdit = async () => {setIsEditing(false)- setNewContent([])+ setNewContent("")clearError()}const saveEdit = async () => {- const editorText = Serialize(newContent)+ const editorText = "hello"const response = await actions.updateComment(props.post.number, props.comment.id, editorText, attachments)if (response.ok) {location.reload()@@ -115,7 +128,7 @@ export const ShowComment = (props: ShowCommentProps) => {)} else if (action === "edit") {setIsEditing(true)- setNewContent(Deserialize(props.comment.content))+ setNewContent("hello")clearError()} else if (action === "delete") {setIsDeleteConfirmationModalOpen(true)@@ -199,8 +212,8 @@ export const ShowComment = (props: ShowCommentProps) => {<div>{isEditing ? (<Form error={error}>- <SlateEditor initialValue={newContent} onChange={setNewContent} placeholder={comment.content} />- {/* <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} /><MultiImageUploader field="attachments" bkeys={comment.attachments} maxUploads={2} onChange={setAttachments} /><Button size="small" onClick={saveEdit} variant="primary"><Trans id="action.save">Save</Trans>