2
0

fix(editor): 🚸 Improve equality check

This commit is contained in:
Baptiste Arnaud
2022-03-10 15:11:42 +01:00
parent 533fdb1b3a
commit 5228cff468
2 changed files with 45 additions and 17 deletions

View File

@@ -5,7 +5,7 @@ import { css } from '@codemirror/lang-css'
import { javascript } from '@codemirror/lang-javascript'
import { html } from '@codemirror/lang-html'
import { useEffect, useRef, useState } from 'react'
import { useDebounce } from 'use-debounce'
import { useDebouncedCallback } from 'use-debounce'
type Props = {
value: string
@@ -22,12 +22,22 @@ export const CodeEditor = ({
}: Props & Omit<BoxProps, 'onChange'>) => {
const editorContainer = useRef<HTMLDivElement | null>(null)
const editorView = useRef<EditorView | null>(null)
const [plainTextValue, setPlainTextValue] = useState(value)
const [debouncedValue] = useDebounce(
plainTextValue,
const [, setPlainTextValue] = useState(value)
const debounced = useDebouncedCallback(
(value) => {
setPlainTextValue(value)
onChange && onChange(value)
},
process.env.NEXT_PUBLIC_E2E_TEST ? 0 : 1000
)
useEffect(
() => () => {
debounced.flush()
},
[debounced]
)
useEffect(() => {
if (!editorView.current || !isReadOnly) return
editorView.current.dispatch({
@@ -40,12 +50,6 @@ export const CodeEditor = ({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [value])
useEffect(() => {
if (!onChange || debouncedValue === value) return
onChange(debouncedValue)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [debouncedValue])
useEffect(() => {
const editor = initEditor(value)
return () => {
@@ -58,7 +62,7 @@ export const CodeEditor = ({
if (!editorContainer.current) return
const updateListenerExtension = EditorView.updateListener.of((update) => {
if (update.docChanged && onChange)
setPlainTextValue(update.state.doc.toJSON().join('\n'))
debounced(update.state.doc.toJSON().join('\n'))
})
const extensions = [
updateListenerExtension,