Last active
July 21, 2020 19:01
-
-
Save FDSoftware/1ab767649ed06e0babb41d3b139c6e40 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Ref, useRef, useImperativeHandle, useCallback, useEffect, useState } from 'react' | |
import TextField, { TextFieldProps } from '@material-ui/core/TextField' | |
import { InputBaseComponentProps } from '@material-ui/core/InputBase' | |
import { EditorState } from 'draft-js' | |
import MUIRichTextEditor from '../../' | |
import { TMUIRichTextEditorRef } from '../../src/MUIRichTextEditor' | |
export const RichTextInput = ({ | |
inputRef, | |
doFocus, | |
onStateChange, | |
controls, | |
...richTextProps | |
}) => { | |
const acquireFocus = doFocus ? doFocus : false | |
// Setup ref for the rich text editor | |
const richTextRef = useRef(null) | |
// Attempts to focus the rich text editor reference | |
const focusRichText = useCallback(() => richTextRef.current?.focus(), [richTextRef]) | |
// Pass on the focus event of the input ref to the rich text ref | |
useImperativeHandle(inputRef, () => ({ focus: () => focusRichText })) | |
// If the `acquireFocus` is changed and its value is `true`, focus the editor | |
useEffect(() => { | |
if (acquireFocus) { | |
focusRichText() | |
} | |
}, [acquireFocus, focusRichText]) | |
return ( | |
<MUIRichTextEditor | |
{...richTextProps} | |
ref={richTextRef} | |
onChange={onStateChange} | |
/> | |
) | |
} | |
const RichTextField = ({ | |
id, | |
placeholder, | |
defaultValue, | |
onChange, | |
InputLabelProps, | |
variant, | |
...textFieldProps | |
}) => { | |
// Manually handle the TextField's focused state based on the editor's focused state | |
const [isFocused, setIsFocused] = useState(false) | |
const inputProps = { | |
id: id, | |
defaultValue: defaultValue, | |
label: placeholder, | |
inlineToolbar: true, | |
onStateChange: onChange, | |
doFocus: isFocused, | |
onFocus: () => setIsFocused(true), | |
onBlur: () => setIsFocused(false), | |
} | |
return ( | |
<TextField | |
{...textFieldProps} | |
id={id} | |
variant={variant} // Required to compile due to TextFieldProps variant incompatibility | |
focused={isFocused} | |
onClick={() => setIsFocused(true)} | |
InputLabelProps={{ ...InputLabelProps, shrink: true }} | |
InputProps={{ inputComponent: RichTextInput, inputProps: inputProps }} | |
/> | |
) | |
} | |
export default RichTextField |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment