Last active
March 13, 2022 07:58
-
-
Save DJanoskova/18057401ca3b535a4f4d29b57166e3aa to your computer and use it in GitHub Desktop.
This file contains hidden or 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, {FunctionComponent, useRef, useState} from 'react'; | |
| import clsx from "clsx"; | |
| type ContentEditableProps = { | |
| onClick?: () => void; | |
| onClose?: () => void; | |
| onCancel?: () => void; | |
| onUpdate?: (value: string) => void; | |
| value?: string | number; | |
| className?: string; | |
| element: keyof JSX.IntrinsicElements; | |
| } | |
| const ContentEditable: FunctionComponent<ContentEditableProps> = ({ onClick, onClose, onCancel, onUpdate, value = '', className, element }) => { | |
| const [isEdit, setIsEdit] = useState(false); | |
| const elementRef = useRef(null); | |
| const classes = clsx(className,{ | |
| 'cursor-pointer': !isEdit, | |
| 'cursor-text': isEdit, | |
| }) | |
| const handleClick = () => { | |
| setIsEdit(true); | |
| onClick?.(); | |
| if (elementRef.current) { | |
| const sel: any = window.getSelection(); | |
| const range = document.createRange(); | |
| range.selectNodeContents(elementRef.current); | |
| sel.removeAllRanges(); | |
| sel.addRange(range); | |
| } | |
| } | |
| const handleChange = (e: any) => { | |
| const isEnter = e.code === 'Enter' || e.key === 'Enter'; | |
| const isEscape = e.code === 'Escape' || e.key === 'Escape'; | |
| if (isEnter || isEscape) { | |
| e.preventDefault(); | |
| setIsEdit(false); | |
| onClose?.(); | |
| const sel: any = window.getSelection(); | |
| sel.removeAllRanges(); | |
| } | |
| const text = (e.target as any).innerText; | |
| if (isEnter) { | |
| onUpdate?.(text); | |
| return; | |
| } else if (isEscape) { | |
| if (elementRef.current) { | |
| (elementRef.current as any).innerText = value; | |
| } | |
| onCancel?.(); | |
| return; | |
| } | |
| setIsEdit(true); | |
| } | |
| const Element: any = element; | |
| return ( | |
| <Element | |
| ref={elementRef} | |
| suppressContentEditableWarning | |
| className={classes} | |
| onClick={handleClick} | |
| onKeyDown={handleChange} | |
| contentEditable | |
| > | |
| {value} | |
| </Element> | |
| ) | |
| } | |
| export default ContentEditable; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment