-
Notifications
You must be signed in to change notification settings - Fork 218
/
react-contenteditable.tsx
139 lines (121 loc) · 4.31 KB
/
react-contenteditable.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
import * as React from 'react';
import deepEqual from 'fast-deep-equal';
import * as PropTypes from 'prop-types';
function normalizeHtml(str: string): string {
return str && str.replace(/ |\u202F|\u00A0/g, ' ');
}
function replaceCaret(el: HTMLElement) {
// Place the caret at the end of the element
const target = document.createTextNode('');
el.appendChild(target);
// do not move caret if element was not focused
const isTargetFocused = document.activeElement === el;
if (target !== null && target.nodeValue !== null && isTargetFocused) {
var sel = window.getSelection();
if (sel !== null) {
var range = document.createRange();
range.setStart(target, target.nodeValue.length);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
if (el instanceof HTMLElement) el.focus();
}
}
/**
* A simple component for an html element with editable contents.
*/
export default class ContentEditable extends React.Component<Props> {
lastHtml: string = this.props.html;
el: any = typeof this.props.innerRef === 'function' ? { current: null } : React.createRef<HTMLElement>();
getEl = () => (this.props.innerRef && typeof this.props.innerRef !== 'function' ? this.props.innerRef : this.el).current;
render() {
const { tagName, html, innerRef, ...props } = this.props;
return React.createElement(
tagName || 'div',
{
...props,
ref: typeof innerRef === 'function' ? (current: HTMLElement) => {
innerRef(current)
this.el.current = current
} : innerRef || this.el,
onInput: this.emitChange,
onBlur: this.props.onBlur || this.emitChange,
onKeyUp: this.props.onKeyUp || this.emitChange,
onKeyDown: this.props.onKeyDown || this.emitChange,
contentEditable: !this.props.disabled,
dangerouslySetInnerHTML: { __html: html }
},
this.props.children);
}
shouldComponentUpdate(nextProps: Props): boolean {
const { props } = this;
const el = this.getEl();
// We need not rerender if the change of props simply reflects the user's edits.
// Rerendering in this case would make the cursor/caret jump
// Rerender if there is no element yet... (somehow?)
if (!el) return true;
// ...or if html really changed... (programmatically, not by user edit)
if (
normalizeHtml(nextProps.html) !== normalizeHtml(el.innerHTML)
) {
return true;
}
// Handle additional properties
return props.disabled !== nextProps.disabled ||
props.tagName !== nextProps.tagName ||
props.className !== nextProps.className ||
props.innerRef !== nextProps.innerRef ||
!deepEqual(props.style, nextProps.style);
}
componentDidUpdate() {
const el = this.getEl();
if (!el) return;
// Perhaps React (whose VDOM gets outdated because we often prevent
// rerendering) did not update the DOM. So we update it manually now.
if (this.props.html !== el.innerHTML) {
el.innerHTML = this.props.html;
}
this.lastHtml = this.props.html;
replaceCaret(el);
}
emitChange = (originalEvt: React.SyntheticEvent<any>) => {
const el = this.getEl();
if (!el) return;
const html = el.innerHTML;
if (this.props.onChange && html !== this.lastHtml) {
// Clone event with Object.assign to avoid
// "Cannot assign to read only property 'target' of object"
const evt = Object.assign({}, originalEvt, {
target: {
value: html
}
});
this.props.onChange(evt);
}
this.lastHtml = html;
}
static propTypes = {
html: PropTypes.string.isRequired,
onChange: PropTypes.func,
disabled: PropTypes.bool,
tagName: PropTypes.string,
className: PropTypes.string,
style: PropTypes.object,
innerRef: PropTypes.oneOfType([
PropTypes.object,
PropTypes.func,
])
}
}
export type ContentEditableEvent = React.SyntheticEvent<any, Event> & { target: { value: string } };
type Modify<T, R> = Pick<T, Exclude<keyof T, keyof R>> & R;
type DivProps = Modify<JSX.IntrinsicElements["div"], { onChange: ((event: ContentEditableEvent) => void) }>;
export interface Props extends DivProps {
html: string,
disabled?: boolean,
tagName?: string,
className?: string,
style?: Object,
innerRef?: React.RefObject<HTMLElement> | Function,
}