|
| 1 | +import { FC, useRef, useState } from 'react'; |
| 2 | +import { SectionElementProps } from '../store/Section'; |
| 3 | +import { useStore } from './store'; |
| 4 | + |
| 5 | +export const KeyNameRender: SectionElementProps['render'] = ( |
| 6 | + { children, ...reset }, |
| 7 | + { value, parentValue, keyName }, |
| 8 | +) => { |
| 9 | + if (typeof children === 'number') { |
| 10 | + return <span {...reset}>{children}</span>; |
| 11 | + } |
| 12 | + return ( |
| 13 | + <Child {...reset} value={value} parentValue={parentValue} keyName={keyName}> |
| 14 | + {children} |
| 15 | + </Child> |
| 16 | + ); |
| 17 | +}; |
| 18 | + |
| 19 | +interface ChildProps extends React.HTMLAttributes<HTMLSpanElement> { |
| 20 | + value: unknown; |
| 21 | + parentValue?: unknown; |
| 22 | + keyName: string | number; |
| 23 | +} |
| 24 | + |
| 25 | +const Child: FC<ChildProps> = (props) => { |
| 26 | + const { value, parentValue, keyName, ...reset } = props; |
| 27 | + const $dom = useRef<HTMLElement>(null); |
| 28 | + const [currentValue, setCurrentValue] = useState(props.children); |
| 29 | + const { onEdit } = useStore(); |
| 30 | + |
| 31 | + const onKeyDown = (evn: React.KeyboardEvent<HTMLSpanElement>) => { |
| 32 | + if (evn.key === 'Enter') { |
| 33 | + $dom.current?.setAttribute('contentEditable', 'false'); |
| 34 | + } |
| 35 | + }; |
| 36 | + |
| 37 | + const onClick = (evn: React.MouseEvent<HTMLSpanElement, MouseEvent>) => { |
| 38 | + evn.stopPropagation(); |
| 39 | + $dom.current?.setAttribute('contentEditable', 'true'); |
| 40 | + $dom.current?.focus(); |
| 41 | + }; |
| 42 | + |
| 43 | + const onBlur = (evn: React.FocusEvent<HTMLSpanElement, Element>) => { |
| 44 | + $dom.current?.setAttribute('contentEditable', 'false'); |
| 45 | + const callback = onEdit && onEdit({ value: evn.target.textContent, oldValue: value, keyName }); |
| 46 | + if (callback) { |
| 47 | + setCurrentValue(evn.target.textContent); |
| 48 | + } |
| 49 | + }; |
| 50 | + |
| 51 | + const spanProps: React.HTMLAttributes<HTMLSpanElement> = { |
| 52 | + ...reset, |
| 53 | + onKeyDown, |
| 54 | + onClick, |
| 55 | + onBlur, |
| 56 | + spellCheck: false, |
| 57 | + contentEditable: 'false', |
| 58 | + suppressContentEditableWarning: true, |
| 59 | + children: currentValue, |
| 60 | + }; |
| 61 | + |
| 62 | + return <span {...spanProps} ref={$dom} />; |
| 63 | +}; |
0 commit comments