react-sane-contenteditable
Advanced tools
Comparing version 1.5.2-beta.0 to 1.6.0
@@ -15,2 +15,4 @@ "use strict"; | ||
var _utils = require("./utils"); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
@@ -22,2 +24,4 @@ | ||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } | ||
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } | ||
@@ -43,34 +47,4 @@ | ||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
var reduceTargetKeys = function reduceTargetKeys(target, keys, predicate) { | ||
return Object.keys(target).reduce(predicate, {}); | ||
}; | ||
var omit = function omit() { | ||
var target = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; | ||
var keys = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; | ||
return reduceTargetKeys(target, keys, function (acc, key) { | ||
return keys.some(function (omitKey) { | ||
return omitKey === key; | ||
}) ? acc : _objectSpread({}, acc, _defineProperty({}, key, target[key])); | ||
}); | ||
}; | ||
var pick = function pick() { | ||
var target = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; | ||
var keys = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; | ||
return reduceTargetKeys(target, keys, function (acc, key) { | ||
return keys.some(function (pickKey) { | ||
return pickKey === key; | ||
}) ? _objectSpread({}, acc, _defineProperty({}, key, target[key])) : acc; | ||
}); | ||
}; | ||
var isEqual = function isEqual(a, b) { | ||
return JSON.stringify(a) === JSON.stringify(b); | ||
}; | ||
var propTypes = { | ||
@@ -84,30 +58,13 @@ content: _propTypes2.default.string, | ||
caretPosition: _propTypes2.default.oneOf(['start', 'end']), | ||
// The element to make contenteditable. | ||
// Takes an element string ('div', 'span', 'h1') or a styled component | ||
tagName: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.func]), | ||
// The element to make contenteditable. Takes an element string ('div', 'span', 'h1') or a styled component | ||
innerRef: _propTypes2.default.func, | ||
onBlur: _propTypes2.default.func, | ||
onFocus: _propTypes2.default.func, | ||
onKeyDown: _propTypes2.default.func, | ||
onKeyUp: _propTypes2.default.func, | ||
onPaste: _propTypes2.default.func, | ||
onChange: _propTypes2.default.func, | ||
styled: _propTypes2.default.bool // If element is a styled component (uses innerRef instead of ref) | ||
styled: _propTypes2.default.bool | ||
}; | ||
var defaultProps = { | ||
content: '', | ||
editable: true, | ||
focus: false, | ||
maxLength: Infinity, | ||
multiLine: false, | ||
sanitise: true, | ||
caretPosition: null, | ||
tagName: 'div', | ||
innerRef: function innerRef() {}, | ||
onBlur: function onBlur() {}, | ||
onFocus: function onFocus() {}, | ||
onKeyDown: function onKeyDown() {}, | ||
onPaste: function onPaste() {}, | ||
onChange: function onChange() {}, | ||
styled: false | ||
}; | ||
@@ -126,104 +83,124 @@ var ContentEditable = | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "setFocus", function () { | ||
if (_this.props.focus && _this._element) { | ||
_this._element.focus(); | ||
} | ||
}); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "insertAtCaret", function (prevValue, valueToInsert) { | ||
var _this$getRange = _this.getRange(), | ||
startOffset = _this$getRange.startOffset, | ||
endOffset = _this$getRange.endOffset; | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "setCaret", function () { | ||
var caretPosition = _this.props.caretPosition; | ||
if (caretPosition && _this._element) { | ||
var value = _this.state.value; | ||
var offset = value.length && caretPosition === 'end' ? 1 : 0; | ||
var range = document.createRange(); | ||
var selection = window.getSelection(); | ||
range.setStart(_this._element, offset); | ||
range.collapse(true); | ||
selection.removeAllRanges(); | ||
selection.addRange(range); | ||
} | ||
var prefix = prevValue.slice(0, startOffset); | ||
var suffix = prevValue.slice(endOffset); | ||
return [prefix, valueToInsert, suffix].join(''); | ||
}); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "_onChange", function (ev) { | ||
var sanitise = _this.props.sanitise; | ||
var rawValue = _this._element.innerText; | ||
var value = sanitise ? _this.sanitiseValue(rawValue) : rawValue; | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "onBlur", function (ev) { | ||
var value = _this.state.value; | ||
var onBlur = _this.props.onBlur; | ||
if (_this.state.value !== value) { | ||
_this.setState({ | ||
value: rawValue | ||
}, function () { | ||
_this.props.onChange(ev, value); | ||
}); | ||
if ((0, _utils.isFunction)(onBlur)) { | ||
onBlur(ev, value); | ||
} | ||
}); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "_onPaste", function (ev) { | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "onInput", function (ev) { | ||
var maxLength = _this.props.maxLength; | ||
ev.preventDefault(); | ||
var text = ev.clipboardData.getData('text').substr(0, maxLength); | ||
document.execCommand('insertText', false, text); | ||
var innerText = ev.target.innerText; | ||
_this.props.onPaste(ev); | ||
}); | ||
if (innerText.length >= maxLength) { | ||
return; | ||
} | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "_onBlur", function (ev) { | ||
var sanitise = _this.props.sanitise; | ||
var rawValue = _this._element.innerText; | ||
var value = sanitise ? _this.sanitiseValue(rawValue) : rawValue; // We finally set the state to the sanitised version (rather than the `rawValue`) because we're blurring the field. | ||
_this.setState({ | ||
value: value, | ||
isFocused: false | ||
caretPosition: _this.getCaret(), | ||
value: _this.sanitiseValue(innerText) | ||
}, function () { | ||
_this.props.onChange(ev, value); | ||
var onChange = _this.props.onChange; | ||
_this.forceUpdate(); | ||
if ((0, _utils.isFunction)(onChange)) { | ||
var value = _this.state.value; | ||
onChange(value); | ||
} | ||
}); | ||
_this.props.onBlur(ev); | ||
}); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "_onFocus", function (ev) { | ||
_this.setState({ | ||
isFocused: true | ||
}); | ||
_this.props.onFocus(ev); | ||
}); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "_onKeyDown", function (ev) { | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "onKeyDown", function (ev) { | ||
var innerText = ev.target.innerText; | ||
var _this$props = _this.props, | ||
maxLength = _this$props.maxLength, | ||
multiLine = _this$props.multiLine; | ||
var value = _this._element.innerText; // return key | ||
multiLine = _this$props.multiLine, | ||
onKeyDown = _this$props.onKeyDown; | ||
var value = innerText; // Return key | ||
if (!multiLine && ev.keyCode === 13) { | ||
if (ev.keyCode === 13) { | ||
ev.preventDefault(); | ||
ev.currentTarget.blur(); // Call onKeyUp directly as ev.preventDefault() means that it will not be called | ||
_this._onKeyUp(ev); | ||
if (multiLine) { | ||
var caretPosition = _this.getCaret(); | ||
var hasLineBreak = /\r|\n/g.test(innerText.charAt(caretPosition)); | ||
var hasCharAfter = !!innerText.charAt(caretPosition); | ||
value = _this.insertAtCaret(innerText, hasLineBreak || hasCharAfter ? '\n' : '\n\n'); | ||
_this.setState({ | ||
caretPosition: caretPosition + 1, | ||
value: value | ||
}); | ||
} else { | ||
ev.currentTarget.blur(); | ||
} | ||
} // Ensure we don't exceed `maxLength` (keycode 8 === backspace) | ||
if (maxLength && !ev.metaKey && ev.which !== 8 && value.replace(/\s\s/g, ' ').length >= maxLength) { | ||
ev.preventDefault(); // Call onKeyUp directly as ev.preventDefault() means that it will not be called | ||
if (maxLength && !ev.metaKey && ev.which !== 8 && innerText.length >= maxLength) { | ||
ev.preventDefault(); | ||
} | ||
_this._onKeyUp(ev); | ||
if ((0, _utils.isFunction)(onKeyDown)) { | ||
onKeyDown(ev, value); | ||
} | ||
}); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "_onKeyUp", function (ev) { | ||
// Call prop.onKeyDown callback from the onKeyUp event to mitigate both of these issues: | ||
// Access to Synthetic event: https://github.com/ashleyw/react-sane-contenteditable/issues/14 | ||
// Current value onKeyDown: https://github.com/ashleyw/react-sane-contenteditable/pull/6 | ||
// this._onKeyDown can't be moved in it's entirety to onKeyUp as we lose the opportunity to preventDefault | ||
_this.props.onKeyDown(ev, _this._element.innerText); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "onKeyUp", function (ev) { | ||
var innerText = ev.target.innerText; | ||
var onKeyUp = _this.props.onKeyUp; | ||
if ((0, _utils.isFunction)(onKeyUp)) { | ||
onKeyUp(ev, innerText); | ||
} | ||
}); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "onPaste", function (ev) { | ||
ev.preventDefault(); | ||
var pastedValue = ev.clipboardData.getData('text'); | ||
var value = _this.insertAtCaret(_this.ref.innerText, pastedValue); | ||
var _this$getRange2 = _this.getRange(), | ||
startOffset = _this$getRange2.startOffset; | ||
_this.setState({ | ||
caretPosition: _this.getSafeCaretPosition(startOffset + pastedValue.length, value), | ||
value: _this.sanitiseValue(value) | ||
}, function () { | ||
var onPaste = _this.props.onPaste; | ||
if ((0, _utils.isFunction)(onPaste)) { | ||
onPaste(value); | ||
} | ||
}); | ||
}); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "setRef", function (ref) { | ||
var innerRef = _this.props.innerRef; | ||
_this.ref = ref; | ||
if ((0, _utils.isFunction)(innerRef)) { | ||
innerRef(ref); | ||
} | ||
}); | ||
_this.state = { | ||
value: props.content, | ||
isFocused: false | ||
caretPosition: _this.getCaretPositionFromProps(props), | ||
value: _this.sanitiseValue(props.content, props) | ||
}; | ||
_this.ref = null; | ||
_this.selection = document.getSelection(); | ||
return _this; | ||
@@ -235,15 +212,27 @@ } | ||
value: function componentDidMount() { | ||
this.setFocus(); | ||
this.setCaret(); | ||
var focus = this.props.focus; | ||
if (focus && this.ref) { | ||
this.setCaretPosition(); | ||
this.ref.focus(); | ||
} | ||
} | ||
}, { | ||
key: "componentWillReceiveProps", | ||
value: function componentWillReceiveProps(nextProps) { | ||
key: "componentDidUpdate", | ||
value: function componentDidUpdate(prevProps, prevState) { | ||
var _this2 = this; | ||
if (nextProps.content !== this.sanitiseValue(this.state.value)) { | ||
var _this$props2 = this.props, | ||
caretPosition = _this$props2.caretPosition, | ||
content = _this$props2.content, | ||
focus = _this$props2.focus; | ||
var updateCaretPosition = prevProps.caretPosition !== caretPosition || prevProps.focus !== focus; | ||
var updateContent = prevProps.content !== content; | ||
if (updateCaretPosition || updateContent) { | ||
this.setState({ | ||
value: nextProps.content | ||
caretPosition: updateCaretPosition ? this.getCaretPositionFromProps() : prevState.caretPosition, | ||
value: updateContent ? this.sanitiseValue(content) : prevState.value | ||
}, function () { | ||
if (!_this2.state.isFocused) _this2.forceUpdate(); | ||
_this2.setCaretPosition(); | ||
}); | ||
@@ -253,41 +242,74 @@ } | ||
}, { | ||
key: "shouldComponentUpdate", | ||
value: function shouldComponentUpdate(nextProps) { | ||
var propKeys = Object.keys(nextProps).filter(function (key) { | ||
return key !== 'content'; | ||
}); | ||
return !isEqual(pick(nextProps, propKeys), pick(this.props, propKeys)); | ||
key: "getRange", | ||
value: function getRange() { | ||
return this.selection.rangeCount ? this.selection.getRangeAt(0) : document.createRange(); | ||
} | ||
}, { | ||
key: "componentDidUpdate", | ||
value: function componentDidUpdate() { | ||
this.setFocus(); | ||
this.setCaret(); | ||
key: "getCaret", | ||
value: function getCaret() { | ||
var originalRange = this.getRange(); | ||
var range = originalRange.cloneRange(); | ||
range.selectNodeContents(this.ref); | ||
range.setEnd(originalRange.endContainer, originalRange.endOffset); | ||
return range.toString().length; | ||
} | ||
}, { | ||
key: "getSafeCaretPosition", | ||
value: function getSafeCaretPosition(position, nextValue) { | ||
var _this$state = this.state, | ||
caretPosition = _this$state.caretPosition, | ||
value = _this$state.value; | ||
var val = nextValue || value; | ||
var pos = position || caretPosition; | ||
return Math.min(pos, val.length); | ||
} | ||
}, { | ||
key: "setCaretPosition", | ||
value: function setCaretPosition() { | ||
var range = this.getRange(); | ||
range.setStart(this.ref.childNodes[0] || this.ref, this.getSafeCaretPosition()); | ||
range.collapse(); | ||
this.selection.removeAllRanges(); | ||
this.selection.addRange(range); | ||
} | ||
}, { | ||
key: "getCaretPositionFromProps", | ||
value: function getCaretPositionFromProps() { | ||
var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.props; | ||
var caretPosition = props.caretPosition === 'end' ? props.content.length : 0; | ||
return props.focus ? caretPosition : null; | ||
} | ||
}, { | ||
key: "sanitiseValue", | ||
value: function sanitiseValue(val) { | ||
var _this$props2 = this.props, | ||
maxLength = _this$props2.maxLength, | ||
multiLine = _this$props2.multiLine, | ||
sanitise = _this$props2.sanitise; | ||
value: function sanitiseValue(value) { | ||
var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.props; | ||
var maxLength = props.maxLength, | ||
multiLine = props.multiLine, | ||
sanitise = props.sanitise; | ||
if (!sanitise) { | ||
return val; | ||
} // replace encoded spaces | ||
return value; | ||
} | ||
if ((0, _utils.isFunction)(sanitise)) { | ||
return sanitise(value, this.getRange()); | ||
} | ||
var value = val.replace(/ /, ' ').replace(/[\u00a0\u2000-\u200b\u2028-\u2029\u202e-\u202f\u3000]/g, ' '); | ||
var nextValue = value // Normalise whitespace | ||
.replace(/[ \u00a0\u2000-\u200b\u2028-\u2029\u202e-\u202f\u3000]/g, ' ') // Remove multiple whitespace chars and if not multiLine, remove lineBreaks | ||
// FIXME This causes an issue when setting caret position | ||
.replace(multiLine ? /[\t\v\f\r ]+/g : /\s+/g, ' '); | ||
if (multiLine) { | ||
// replace any 2+ character whitespace (other than new lines) with a single space | ||
value = value.replace(/[\t\v\f\r ]+/g, ' '); | ||
} else { | ||
value = value.replace(/\s+/g, ' '); | ||
nextValue = nextValue // Replace 3+ line breaks with two | ||
// FIXME This causes an issue when setting caret position | ||
.replace(/\r|\n{3,}/g, '\n\n') // Remove leading & trailing whitespace | ||
// FIXME This causes an issue when setting caret position | ||
.split('\n').map(function (line) { | ||
return line.trim(); | ||
}).join('\n'); | ||
} | ||
return value.split('\n').map(function (line) { | ||
return line.trim(); | ||
}).join('\n').replace(/\n{3,}/g, '\n\n') // replace 3+ line breaks with two | ||
.trim().substr(0, maxLength); | ||
return nextValue // Ensure maxLength not exceeded | ||
.substr(0, maxLength); | ||
} | ||
@@ -297,21 +319,12 @@ }, { | ||
value: function render() { | ||
var _this3 = this; | ||
var _this$props3 = this.props, | ||
Element = _this$props3.tagName, | ||
content = _this$props3.content, | ||
editable = _this$props3.editable, | ||
styled = _this$props3.styled, | ||
props = _objectWithoutProperties(_this$props3, ["tagName", "content", "editable", "styled"]); | ||
props = _objectWithoutProperties(_this$props3, ["tagName", "editable", "styled"]); | ||
return _react2.default.createElement(Element, _extends({}, omit(props, Object.keys(propTypes)), styled ? { | ||
innerRef: function innerRef(c) { | ||
_this3._element = c; | ||
props.innerRef(c); | ||
} | ||
return _react2.default.createElement(Element, _extends({}, (0, _utils.omit)(props, Object.keys(propTypes)), styled ? { | ||
innerRef: this.setRef | ||
} : { | ||
ref: function ref(c) { | ||
_this3._element = c; | ||
props.innerRef(c); | ||
} | ||
ref: this.setRef | ||
}, { | ||
@@ -322,12 +335,10 @@ style: _objectSpread({ | ||
contentEditable: editable, | ||
key: Date(), | ||
dangerouslySetInnerHTML: { | ||
__html: this.state.value | ||
}, | ||
onBlur: this._onBlur, | ||
onFocus: this._onFocus, | ||
onInput: this._onChange, | ||
onKeyDown: this._onKeyDown, | ||
onKeyUp: this._onKeyUp, | ||
onPaste: this._onPaste | ||
onBlur: this.onBlur, | ||
onInput: this.onInput, | ||
onKeyDown: this.onKeyDown, | ||
onKeyUp: this.onKeyUp, | ||
onPaste: this.onPaste | ||
})); | ||
@@ -340,3 +351,20 @@ } | ||
ContentEditable.defaultProps = defaultProps; | ||
_defineProperty(ContentEditable, "defaultProps", { | ||
content: '', | ||
editable: true, | ||
focus: false, | ||
maxLength: Infinity, | ||
multiLine: false, | ||
sanitise: true, | ||
caretPosition: null, | ||
tagName: 'div', | ||
innerRef: null, | ||
onBlur: null, | ||
onKeyDown: null, | ||
onKeyUp: null, | ||
onPaste: null, | ||
onChange: null, | ||
styled: false | ||
}); | ||
exports.default = ContentEditable; |
import _extends from "@babel/runtime/helpers/extends"; | ||
import _objectSpread from "@babel/runtime/helpers/objectSpread"; | ||
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties"; | ||
@@ -10,34 +11,5 @@ import _classCallCheck from "@babel/runtime/helpers/classCallCheck"; | ||
import _defineProperty from "@babel/runtime/helpers/defineProperty"; | ||
import _objectSpread from "@babel/runtime/helpers/objectSpread"; | ||
import React, { Component } from 'react'; | ||
import PropTypes from 'prop-types'; | ||
var reduceTargetKeys = function reduceTargetKeys(target, keys, predicate) { | ||
return Object.keys(target).reduce(predicate, {}); | ||
}; | ||
var omit = function omit() { | ||
var target = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; | ||
var keys = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; | ||
return reduceTargetKeys(target, keys, function (acc, key) { | ||
return keys.some(function (omitKey) { | ||
return omitKey === key; | ||
}) ? acc : _objectSpread({}, acc, _defineProperty({}, key, target[key])); | ||
}); | ||
}; | ||
var pick = function pick() { | ||
var target = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; | ||
var keys = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; | ||
return reduceTargetKeys(target, keys, function (acc, key) { | ||
return keys.some(function (pickKey) { | ||
return pickKey === key; | ||
}) ? _objectSpread({}, acc, _defineProperty({}, key, target[key])) : acc; | ||
}); | ||
}; | ||
var isEqual = function isEqual(a, b) { | ||
return JSON.stringify(a) === JSON.stringify(b); | ||
}; | ||
import { isFunction, omit } from './utils'; | ||
var propTypes = { | ||
@@ -51,30 +23,13 @@ content: PropTypes.string, | ||
caretPosition: PropTypes.oneOf(['start', 'end']), | ||
// The element to make contenteditable. | ||
// Takes an element string ('div', 'span', 'h1') or a styled component | ||
tagName: PropTypes.oneOfType([PropTypes.string, PropTypes.func]), | ||
// The element to make contenteditable. Takes an element string ('div', 'span', 'h1') or a styled component | ||
innerRef: PropTypes.func, | ||
onBlur: PropTypes.func, | ||
onFocus: PropTypes.func, | ||
onKeyDown: PropTypes.func, | ||
onKeyUp: PropTypes.func, | ||
onPaste: PropTypes.func, | ||
onChange: PropTypes.func, | ||
styled: PropTypes.bool // If element is a styled component (uses innerRef instead of ref) | ||
styled: PropTypes.bool | ||
}; | ||
var defaultProps = { | ||
content: '', | ||
editable: true, | ||
focus: false, | ||
maxLength: Infinity, | ||
multiLine: false, | ||
sanitise: true, | ||
caretPosition: null, | ||
tagName: 'div', | ||
innerRef: function innerRef() {}, | ||
onBlur: function onBlur() {}, | ||
onFocus: function onFocus() {}, | ||
onKeyDown: function onKeyDown() {}, | ||
onPaste: function onPaste() {}, | ||
onChange: function onChange() {}, | ||
styled: false | ||
}; | ||
@@ -93,104 +48,124 @@ var ContentEditable = | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "setFocus", function () { | ||
if (_this.props.focus && _this._element) { | ||
_this._element.focus(); | ||
} | ||
}); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "insertAtCaret", function (prevValue, valueToInsert) { | ||
var _this$getRange = _this.getRange(), | ||
startOffset = _this$getRange.startOffset, | ||
endOffset = _this$getRange.endOffset; | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "setCaret", function () { | ||
var caretPosition = _this.props.caretPosition; | ||
if (caretPosition && _this._element) { | ||
var value = _this.state.value; | ||
var offset = value.length && caretPosition === 'end' ? 1 : 0; | ||
var range = document.createRange(); | ||
var selection = window.getSelection(); | ||
range.setStart(_this._element, offset); | ||
range.collapse(true); | ||
selection.removeAllRanges(); | ||
selection.addRange(range); | ||
} | ||
var prefix = prevValue.slice(0, startOffset); | ||
var suffix = prevValue.slice(endOffset); | ||
return [prefix, valueToInsert, suffix].join(''); | ||
}); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "_onChange", function (ev) { | ||
var sanitise = _this.props.sanitise; | ||
var rawValue = _this._element.innerText; | ||
var value = sanitise ? _this.sanitiseValue(rawValue) : rawValue; | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "onBlur", function (ev) { | ||
var value = _this.state.value; | ||
var onBlur = _this.props.onBlur; | ||
if (_this.state.value !== value) { | ||
_this.setState({ | ||
value: rawValue | ||
}, function () { | ||
_this.props.onChange(ev, value); | ||
}); | ||
if (isFunction(onBlur)) { | ||
onBlur(ev, value); | ||
} | ||
}); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "_onPaste", function (ev) { | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "onInput", function (ev) { | ||
var maxLength = _this.props.maxLength; | ||
ev.preventDefault(); | ||
var text = ev.clipboardData.getData('text').substr(0, maxLength); | ||
document.execCommand('insertText', false, text); | ||
var innerText = ev.target.innerText; | ||
_this.props.onPaste(ev); | ||
}); | ||
if (innerText.length >= maxLength) { | ||
return; | ||
} | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "_onBlur", function (ev) { | ||
var sanitise = _this.props.sanitise; | ||
var rawValue = _this._element.innerText; | ||
var value = sanitise ? _this.sanitiseValue(rawValue) : rawValue; // We finally set the state to the sanitised version (rather than the `rawValue`) because we're blurring the field. | ||
_this.setState({ | ||
value: value, | ||
isFocused: false | ||
caretPosition: _this.getCaret(), | ||
value: _this.sanitiseValue(innerText) | ||
}, function () { | ||
_this.props.onChange(ev, value); | ||
var onChange = _this.props.onChange; | ||
_this.forceUpdate(); | ||
if (isFunction(onChange)) { | ||
var value = _this.state.value; | ||
onChange(value); | ||
} | ||
}); | ||
_this.props.onBlur(ev); | ||
}); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "_onFocus", function (ev) { | ||
_this.setState({ | ||
isFocused: true | ||
}); | ||
_this.props.onFocus(ev); | ||
}); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "_onKeyDown", function (ev) { | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "onKeyDown", function (ev) { | ||
var innerText = ev.target.innerText; | ||
var _this$props = _this.props, | ||
maxLength = _this$props.maxLength, | ||
multiLine = _this$props.multiLine; | ||
var value = _this._element.innerText; // return key | ||
multiLine = _this$props.multiLine, | ||
onKeyDown = _this$props.onKeyDown; | ||
var value = innerText; // Return key | ||
if (!multiLine && ev.keyCode === 13) { | ||
if (ev.keyCode === 13) { | ||
ev.preventDefault(); | ||
ev.currentTarget.blur(); // Call onKeyUp directly as ev.preventDefault() means that it will not be called | ||
_this._onKeyUp(ev); | ||
if (multiLine) { | ||
var caretPosition = _this.getCaret(); | ||
var hasLineBreak = /\r|\n/g.test(innerText.charAt(caretPosition)); | ||
var hasCharAfter = !!innerText.charAt(caretPosition); | ||
value = _this.insertAtCaret(innerText, hasLineBreak || hasCharAfter ? '\n' : '\n\n'); | ||
_this.setState({ | ||
caretPosition: caretPosition + 1, | ||
value: value | ||
}); | ||
} else { | ||
ev.currentTarget.blur(); | ||
} | ||
} // Ensure we don't exceed `maxLength` (keycode 8 === backspace) | ||
if (maxLength && !ev.metaKey && ev.which !== 8 && value.replace(/\s\s/g, ' ').length >= maxLength) { | ||
ev.preventDefault(); // Call onKeyUp directly as ev.preventDefault() means that it will not be called | ||
if (maxLength && !ev.metaKey && ev.which !== 8 && innerText.length >= maxLength) { | ||
ev.preventDefault(); | ||
} | ||
_this._onKeyUp(ev); | ||
if (isFunction(onKeyDown)) { | ||
onKeyDown(ev, value); | ||
} | ||
}); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "_onKeyUp", function (ev) { | ||
// Call prop.onKeyDown callback from the onKeyUp event to mitigate both of these issues: | ||
// Access to Synthetic event: https://github.com/ashleyw/react-sane-contenteditable/issues/14 | ||
// Current value onKeyDown: https://github.com/ashleyw/react-sane-contenteditable/pull/6 | ||
// this._onKeyDown can't be moved in it's entirety to onKeyUp as we lose the opportunity to preventDefault | ||
_this.props.onKeyDown(ev, _this._element.innerText); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "onKeyUp", function (ev) { | ||
var innerText = ev.target.innerText; | ||
var onKeyUp = _this.props.onKeyUp; | ||
if (isFunction(onKeyUp)) { | ||
onKeyUp(ev, innerText); | ||
} | ||
}); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "onPaste", function (ev) { | ||
ev.preventDefault(); | ||
var pastedValue = ev.clipboardData.getData('text'); | ||
var value = _this.insertAtCaret(_this.ref.innerText, pastedValue); | ||
var _this$getRange2 = _this.getRange(), | ||
startOffset = _this$getRange2.startOffset; | ||
_this.setState({ | ||
caretPosition: _this.getSafeCaretPosition(startOffset + pastedValue.length, value), | ||
value: _this.sanitiseValue(value) | ||
}, function () { | ||
var onPaste = _this.props.onPaste; | ||
if (isFunction(onPaste)) { | ||
onPaste(value); | ||
} | ||
}); | ||
}); | ||
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "setRef", function (ref) { | ||
var innerRef = _this.props.innerRef; | ||
_this.ref = ref; | ||
if (isFunction(innerRef)) { | ||
innerRef(ref); | ||
} | ||
}); | ||
_this.state = { | ||
value: props.content, | ||
isFocused: false | ||
caretPosition: _this.getCaretPositionFromProps(props), | ||
value: _this.sanitiseValue(props.content, props) | ||
}; | ||
_this.ref = null; | ||
_this.selection = document.getSelection(); | ||
return _this; | ||
@@ -202,15 +177,27 @@ } | ||
value: function componentDidMount() { | ||
this.setFocus(); | ||
this.setCaret(); | ||
var focus = this.props.focus; | ||
if (focus && this.ref) { | ||
this.setCaretPosition(); | ||
this.ref.focus(); | ||
} | ||
} | ||
}, { | ||
key: "componentWillReceiveProps", | ||
value: function componentWillReceiveProps(nextProps) { | ||
key: "componentDidUpdate", | ||
value: function componentDidUpdate(prevProps, prevState) { | ||
var _this2 = this; | ||
if (nextProps.content !== this.sanitiseValue(this.state.value)) { | ||
var _this$props2 = this.props, | ||
caretPosition = _this$props2.caretPosition, | ||
content = _this$props2.content, | ||
focus = _this$props2.focus; | ||
var updateCaretPosition = prevProps.caretPosition !== caretPosition || prevProps.focus !== focus; | ||
var updateContent = prevProps.content !== content; | ||
if (updateCaretPosition || updateContent) { | ||
this.setState({ | ||
value: nextProps.content | ||
caretPosition: updateCaretPosition ? this.getCaretPositionFromProps() : prevState.caretPosition, | ||
value: updateContent ? this.sanitiseValue(content) : prevState.value | ||
}, function () { | ||
if (!_this2.state.isFocused) _this2.forceUpdate(); | ||
_this2.setCaretPosition(); | ||
}); | ||
@@ -220,41 +207,74 @@ } | ||
}, { | ||
key: "shouldComponentUpdate", | ||
value: function shouldComponentUpdate(nextProps) { | ||
var propKeys = Object.keys(nextProps).filter(function (key) { | ||
return key !== 'content'; | ||
}); | ||
return !isEqual(pick(nextProps, propKeys), pick(this.props, propKeys)); | ||
key: "getRange", | ||
value: function getRange() { | ||
return this.selection.rangeCount ? this.selection.getRangeAt(0) : document.createRange(); | ||
} | ||
}, { | ||
key: "componentDidUpdate", | ||
value: function componentDidUpdate() { | ||
this.setFocus(); | ||
this.setCaret(); | ||
key: "getCaret", | ||
value: function getCaret() { | ||
var originalRange = this.getRange(); | ||
var range = originalRange.cloneRange(); | ||
range.selectNodeContents(this.ref); | ||
range.setEnd(originalRange.endContainer, originalRange.endOffset); | ||
return range.toString().length; | ||
} | ||
}, { | ||
key: "getSafeCaretPosition", | ||
value: function getSafeCaretPosition(position, nextValue) { | ||
var _this$state = this.state, | ||
caretPosition = _this$state.caretPosition, | ||
value = _this$state.value; | ||
var val = nextValue || value; | ||
var pos = position || caretPosition; | ||
return Math.min(pos, val.length); | ||
} | ||
}, { | ||
key: "setCaretPosition", | ||
value: function setCaretPosition() { | ||
var range = this.getRange(); | ||
range.setStart(this.ref.childNodes[0] || this.ref, this.getSafeCaretPosition()); | ||
range.collapse(); | ||
this.selection.removeAllRanges(); | ||
this.selection.addRange(range); | ||
} | ||
}, { | ||
key: "getCaretPositionFromProps", | ||
value: function getCaretPositionFromProps() { | ||
var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.props; | ||
var caretPosition = props.caretPosition === 'end' ? props.content.length : 0; | ||
return props.focus ? caretPosition : null; | ||
} | ||
}, { | ||
key: "sanitiseValue", | ||
value: function sanitiseValue(val) { | ||
var _this$props2 = this.props, | ||
maxLength = _this$props2.maxLength, | ||
multiLine = _this$props2.multiLine, | ||
sanitise = _this$props2.sanitise; | ||
value: function sanitiseValue(value) { | ||
var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.props; | ||
var maxLength = props.maxLength, | ||
multiLine = props.multiLine, | ||
sanitise = props.sanitise; | ||
if (!sanitise) { | ||
return val; | ||
} // replace encoded spaces | ||
return value; | ||
} | ||
if (isFunction(sanitise)) { | ||
return sanitise(value, this.getRange()); | ||
} | ||
var value = val.replace(/ /, ' ').replace(/[\u00a0\u2000-\u200b\u2028-\u2029\u202e-\u202f\u3000]/g, ' '); | ||
var nextValue = value // Normalise whitespace | ||
.replace(/[ \u00a0\u2000-\u200b\u2028-\u2029\u202e-\u202f\u3000]/g, ' ') // Remove multiple whitespace chars and if not multiLine, remove lineBreaks | ||
// FIXME This causes an issue when setting caret position | ||
.replace(multiLine ? /[\t\v\f\r ]+/g : /\s+/g, ' '); | ||
if (multiLine) { | ||
// replace any 2+ character whitespace (other than new lines) with a single space | ||
value = value.replace(/[\t\v\f\r ]+/g, ' '); | ||
} else { | ||
value = value.replace(/\s+/g, ' '); | ||
nextValue = nextValue // Replace 3+ line breaks with two | ||
// FIXME This causes an issue when setting caret position | ||
.replace(/\r|\n{3,}/g, '\n\n') // Remove leading & trailing whitespace | ||
// FIXME This causes an issue when setting caret position | ||
.split('\n').map(function (line) { | ||
return line.trim(); | ||
}).join('\n'); | ||
} | ||
return value.split('\n').map(function (line) { | ||
return line.trim(); | ||
}).join('\n').replace(/\n{3,}/g, '\n\n') // replace 3+ line breaks with two | ||
.trim().substr(0, maxLength); | ||
return nextValue // Ensure maxLength not exceeded | ||
.substr(0, maxLength); | ||
} | ||
@@ -264,21 +284,12 @@ }, { | ||
value: function render() { | ||
var _this3 = this; | ||
var _this$props3 = this.props, | ||
Element = _this$props3.tagName, | ||
content = _this$props3.content, | ||
editable = _this$props3.editable, | ||
styled = _this$props3.styled, | ||
props = _objectWithoutProperties(_this$props3, ["tagName", "content", "editable", "styled"]); | ||
props = _objectWithoutProperties(_this$props3, ["tagName", "editable", "styled"]); | ||
return React.createElement(Element, _extends({}, omit(props, Object.keys(propTypes)), styled ? { | ||
innerRef: function innerRef(c) { | ||
_this3._element = c; | ||
props.innerRef(c); | ||
} | ||
innerRef: this.setRef | ||
} : { | ||
ref: function ref(c) { | ||
_this3._element = c; | ||
props.innerRef(c); | ||
} | ||
ref: this.setRef | ||
}, { | ||
@@ -289,12 +300,10 @@ style: _objectSpread({ | ||
contentEditable: editable, | ||
key: Date(), | ||
dangerouslySetInnerHTML: { | ||
__html: this.state.value | ||
}, | ||
onBlur: this._onBlur, | ||
onFocus: this._onFocus, | ||
onInput: this._onChange, | ||
onKeyDown: this._onKeyDown, | ||
onKeyUp: this._onKeyUp, | ||
onPaste: this._onPaste | ||
onBlur: this.onBlur, | ||
onInput: this.onInput, | ||
onKeyDown: this.onKeyDown, | ||
onKeyUp: this.onKeyUp, | ||
onPaste: this.onPaste | ||
})); | ||
@@ -307,3 +316,20 @@ } | ||
ContentEditable.defaultProps = defaultProps; | ||
_defineProperty(ContentEditable, "defaultProps", { | ||
content: '', | ||
editable: true, | ||
focus: false, | ||
maxLength: Infinity, | ||
multiLine: false, | ||
sanitise: true, | ||
caretPosition: null, | ||
tagName: 'div', | ||
innerRef: null, | ||
onBlur: null, | ||
onKeyDown: null, | ||
onKeyUp: null, | ||
onPaste: null, | ||
onChange: null, | ||
styled: false | ||
}); | ||
export default ContentEditable; |
{ | ||
"name": "react-sane-contenteditable", | ||
"version": "1.5.2-beta.0", | ||
"version": "1.6.0", | ||
"description": "React component with sane defaults to make any element contentEditable", | ||
"main": "lib/cjs/react-sane-contenteditable.js", | ||
"module": "lib/esm/react-sane-contenteditable.js", | ||
"keywords": ["content-editable", "contenteditable", "editable", "react", "react-component"], | ||
"homepage": "https://github.com/ashleyw/react-sane-contenteditable#readme", | ||
"bugs": { | ||
"url": "https://github.com/ashleyw/react-sane-contenteditable/issues" | ||
}, | ||
"repository": { | ||
@@ -11,7 +14,34 @@ "type": "git", | ||
}, | ||
"license": "MIT", | ||
"author": "Ashley Williams <hi@ashleyw.co.uk>", | ||
"contributors": ["Nick Aspinall", "Raphael Silva Cavalcanti", "Jess Telford"], | ||
"license": "MIT", | ||
"files": ["lib", "LICENSE", "README.md"], | ||
"main": "lib/cjs/react-sane-contenteditable.js", | ||
"module": "lib/esm/react-sane-contenteditable.js", | ||
"directories": { | ||
"lib": "lib" | ||
}, | ||
"scripts": { | ||
"build": "yarn run build:clean && yarn run build:esm && yarn run build:cjs && yarn run build:umd", | ||
"build:cjs": "cross-env BABEL_ENV=cjs babel src --out-dir lib/cjs", | ||
"build:clean": "rimraf dist/ && rimraf lib/", | ||
"build:esm": "cross-env BABEL_ENV=esm babel src --out-dir lib/esm", | ||
"build:umd": "rollup -c && rimraf dist/index.esm.js", | ||
"demo": "rollup -c rollup.config.demo.js", | ||
"dev": "yarn run demo -w", | ||
"dev:test": "jest --watch --verbose false", | ||
"lint": "yarn run lint:prettier", | ||
"lint:prettier": "prettier --write src/**/*", | ||
"prepublish": "yarn build", | ||
"test": "jest" | ||
}, | ||
"husky": { | ||
"hooks": { | ||
"pre-commit": "yarn run lint && yarn run build && git add lib/* .size-snapshot.json", | ||
"pre-push": "yarn test" | ||
} | ||
}, | ||
"dependencies": { | ||
"@babel/runtime": "^7.1.2" | ||
"@babel/runtime": "^7.1.2", | ||
"prop-types": "^15.6.2" | ||
}, | ||
@@ -37,3 +67,2 @@ "devDependencies": { | ||
"prettier": "1.14.2", | ||
"prop-types": "^15.6.2", | ||
"react": "^16.4.2", | ||
@@ -55,32 +84,4 @@ "react-dom": "^16.3.2", | ||
"peerDependencies": { | ||
"prop-types": "^15.6.2", | ||
"react": "^16.4.2" | ||
}, | ||
"scripts": { | ||
"build": "yarn run build:clean && yarn run build:esm && yarn run build:cjs && yarn run build:umd", | ||
"build:clean": "rimraf dist/ && rimraf lib/", | ||
"build:cjs": "cross-env BABEL_ENV=cjs babel src --out-dir lib/cjs", | ||
"build:esm": "cross-env BABEL_ENV=esm babel src --out-dir lib/esm", | ||
"build:umd": "rollup -c && rimraf dist/index.esm.js", | ||
"prepublish": "yarn build", | ||
"demo": "rollup -c rollup.config.demo.js", | ||
"dev": "yarn run demo -w", | ||
"dev:test": "jest --watch --verbose false", | ||
"test": "jest", | ||
"lint": "./node_modules/prettier/bin-prettier.js --write src/**/*" | ||
}, | ||
"husky": { | ||
"hooks": { | ||
"pre-commit": "yarn run lint && yarn run build && git add lib/* .size-snapshot.json", | ||
"pre-push": "yarn test" | ||
} | ||
}, | ||
"bugs": { | ||
"url": "https://github.com/ashleyw/react-sane-contenteditable/issues" | ||
}, | ||
"homepage": "https://github.com/ashleyw/react-sane-contenteditable#readme", | ||
"directories": { | ||
"lib": "lib" | ||
}, | ||
"keywords": ["react-component", "contenteditable", "editable", "react", "content-editable"] | ||
} | ||
} |
@@ -13,5 +13,5 @@ # react-sane-contenteditable | ||
* Clean and sanitise the output | ||
* Remove rich text formatting when pasting | ||
* Prevent the cursor from jumping around | ||
- Clean and sanitise the output | ||
- Remove rich text formatting when pasting | ||
- Prevent the cursor from jumping around | ||
@@ -21,4 +21,4 @@ ## Example | ||
```jsx | ||
import React, { Component } from "react"; | ||
import ContentEditable from "react-sane-contenteditable"; | ||
import React, { Component } from 'react'; | ||
import ContentEditable from 'react-sane-contenteditable'; | ||
@@ -30,3 +30,3 @@ class App extends Component { | ||
this.state = { | ||
title: "Title here" | ||
title: 'Title here', | ||
}; | ||
@@ -60,10 +60,13 @@ } | ||
### Tests | ||
`yarn test` | ||
### Linting | ||
`yarn run lint` | ||
### Dev | ||
Runs the rollup dev server with file watching on both the src and demo | ||
`yarn run dev` |
Deprecated
MaintenanceThe maintainer of the package marked it as deprecated. This could indicate that a single version should not be used, or that the package is no longer maintained and any new vulnerabilities will not be fixed.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Deprecated
MaintenanceThe maintainer of the package marked it as deprecated. This could indicate that a single version should not be used, or that the package is no longer maintained and any new vulnerabilities will not be fixed.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
32
0
69
33029
7
621
1
+ Addedprop-types@^15.6.2