2
0

refactor(editor): ♻️ Undo / Redo buttons + structure refacto

Yet another huge refacto... While implementing undo and redo features I understood that I updated the stored typebot too many times (i.e. on each key input) so I had to rethink it entirely. I also moved around some files.
This commit is contained in:
Baptiste Arnaud
2022-02-02 08:05:02 +01:00
parent fc1d654772
commit 8a350eee6c
153 changed files with 1512 additions and 1352 deletions

View File

@ -0,0 +1,156 @@
import { Flex, Stack, useOutsideClick } from '@chakra-ui/react'
import React, { useEffect, useMemo, useRef, useState } from 'react'
import {
Plate,
selectEditor,
serializeHtml,
TDescendant,
withPlate,
} from '@udecode/plate-core'
import { editorStyle, platePlugins } from 'libs/plate'
import { useTypebot } from 'contexts/TypebotContext/TypebotContext'
import { BaseSelection, createEditor, Transforms } from 'slate'
import { ToolBar } from './ToolBar'
import { parseHtmlStringToPlainText } from 'services/utils'
import { TextBubbleStep, Variable } from 'models'
import { VariableSearchInput } from 'components/shared/VariableSearchInput'
import { ReactEditor } from 'slate-react'
type Props = {
stepId: string
initialValue: TDescendant[]
onClose: () => void
}
export const TextBubbleEditor = ({ initialValue, stepId, onClose }: Props) => {
const randomEditorId = useMemo(() => Math.random().toString(), [])
const editor = useMemo(
() =>
withPlate(createEditor(), { id: randomEditorId, plugins: platePlugins }),
// eslint-disable-next-line react-hooks/exhaustive-deps
[]
)
const { updateStep } = useTypebot()
const [value, setValue] = useState(initialValue)
const varDropdownRef = useRef<HTMLDivElement | null>(null)
const rememberedSelection = useRef<BaseSelection | null>(null)
const [isVariableDropdownOpen, setIsVariableDropdownOpen] = useState(false)
const textEditorRef = useRef<HTMLDivElement>(null)
useOutsideClick({
ref: textEditorRef,
handler: () => {
save(value)
onClose()
},
})
useEffect(() => {
if (!isVariableDropdownOpen) return
const el = varDropdownRef.current
if (!el) return
const { top, left } = computeTargetCoord()
el.style.top = `${top}px`
el.style.left = `${left}px`
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isVariableDropdownOpen])
const computeTargetCoord = () => {
const selection = window.getSelection()
const relativeParent = textEditorRef.current
if (!selection || !relativeParent) return { top: 0, left: 0 }
const range = selection.getRangeAt(0)
const selectionBoundingRect = range.getBoundingClientRect()
const relativeRect = relativeParent.getBoundingClientRect()
return {
top: selectionBoundingRect.bottom - relativeRect.top,
left: selectionBoundingRect.left - relativeRect.left,
}
}
const save = (value: unknown[]) => {
if (value.length === 0) return
const html = serializeHtml(editor, {
nodes: value,
})
updateStep(stepId, {
content: {
html,
richText: value,
plainText: parseHtmlStringToPlainText(html),
},
} as TextBubbleStep)
}
const handleMouseDown = (e: React.MouseEvent) => {
e.stopPropagation()
}
const handleVariableSelected = (variable?: Variable) => {
setIsVariableDropdownOpen(false)
if (!rememberedSelection.current || !variable) return
Transforms.select(editor, rememberedSelection.current)
Transforms.insertText(editor, '{{' + variable.name + '}}')
ReactEditor.focus(editor as unknown as ReactEditor)
}
const handleChangeEditorContent = (val: unknown[]) => {
setValue(val)
setIsVariableDropdownOpen(false)
}
return (
<Stack
flex="1"
ref={textEditorRef}
borderWidth="2px"
borderColor="blue.500"
rounded="md"
onMouseDown={handleMouseDown}
pos="relative"
spacing={0}
>
<ToolBar onVariablesButtonClick={() => setIsVariableDropdownOpen(true)} />
<Plate
id={randomEditorId}
editableProps={{
style: editorStyle,
autoFocus: true,
onFocus: () => {
if (editor.children.length === 0) return
selectEditor(editor, {
edge: 'end',
})
},
'aria-label': 'Text editor',
onBlur: () => {
rememberedSelection.current = editor.selection
},
}}
initialValue={
initialValue.length === 0
? [{ type: 'p', children: [{ text: '' }] }]
: initialValue
}
onChange={handleChangeEditorContent}
editor={editor}
/>
{isVariableDropdownOpen && (
<Flex
pos="absolute"
ref={varDropdownRef}
shadow="lg"
rounded="md"
bgColor="white"
w="250px"
>
<VariableSearchInput
onSelectVariable={handleVariableSelected}
placeholder="Search for a variable"
isDefaultOpen
/>
</Flex>
)}
</Stack>
)
}

View File

@ -0,0 +1,54 @@
import { StackProps, HStack, Button } from '@chakra-ui/react'
import {
MARK_BOLD,
MARK_ITALIC,
MARK_UNDERLINE,
} from '@udecode/plate-basic-marks'
import { usePlateEditorRef, getPluginType } from '@udecode/plate-core'
import { LinkToolbarButton } from '@udecode/plate-ui-link'
import { MarkToolbarButton } from '@udecode/plate-ui-toolbar'
import { BoldIcon, ItalicIcon, UnderlineIcon, LinkIcon } from 'assets/icons'
type Props = { onVariablesButtonClick: () => void } & StackProps
export const ToolBar = (props: Props) => {
const editor = usePlateEditorRef()
const handleVariablesButtonMouseDown = (e: React.MouseEvent) => {
e.preventDefault()
props.onVariablesButtonClick()
}
return (
<HStack
bgColor={'white'}
borderTopRadius="md"
p={2}
w="full"
boxSizing="border-box"
borderBottomWidth={1}
{...props}
>
<Button size="sm" onMouseDown={handleVariablesButtonMouseDown}>
Variables
</Button>
<span data-testid="bold-button">
<MarkToolbarButton
type={getPluginType(editor, MARK_BOLD)}
icon={<BoldIcon />}
/>
</span>
<span data-testid="italic-button">
<MarkToolbarButton
type={getPluginType(editor, MARK_ITALIC)}
icon={<ItalicIcon />}
/>
</span>
<span data-testid="underline-button">
<MarkToolbarButton
type={getPluginType(editor, MARK_UNDERLINE)}
icon={<UnderlineIcon />}
/>
</span>
<LinkToolbarButton icon={<LinkIcon />} />
</HStack>
)
}

View File

@ -0,0 +1 @@
export { TextBubbleEditor } from './TextBubbleEditor'