Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 5 additions & 19 deletions .babelrc
Original file line number Diff line number Diff line change
Expand Up @@ -13,29 +13,15 @@
],
"env": {
"esm": {
"plugins": [
["@babel/transform-runtime"]
],
"ignore": [
"**/*.test.js",
"**/__tests__/**",
"**/__mocks__/**"
]
"plugins": [["@babel/transform-runtime"]],
"ignore": ["**/*.test.js", "**/__tests__/**", "**/__mocks__/**"]
},
"cjs": {
"plugins": [
"transform-es2015-modules-commonjs"
],
"ignore": [
"**/*.test.js",
"**/__tests__/**",
"**/__mocks__/**"
]
"plugins": ["transform-es2015-modules-commonjs"],
"ignore": ["**/*.test.js", "**/__tests__/**", "**/__mocks__/**"]
},
"test": {
"plugins": [
"transform-es2015-modules-commonjs"
]
"plugins": ["transform-es2015-modules-commonjs"]
}
},
"plugins": [
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ jobs:
strategy:
fail-fast: false
matrix:
node: [8, 10, 12]
node: [10, 12]

steps:
- name: Clone repository
Expand Down
4 changes: 4 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/coverage/
/dist/
/example/index.min.js
/lib/
36 changes: 19 additions & 17 deletions example/index.html
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello World</title>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css"
integrity="sha256-2YQRJMXD7pIAPHiXr0s+vlRWA7GYJEK0ARns7k2sbHY="
crossorigin="anonymous"
/>
<style>
.my-class {
outline: none;
}
</style>
</head>

<head>
<meta charset="UTF-8" />
<title>Hello World</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" integrity="sha256-2YQRJMXD7pIAPHiXr0s+vlRWA7GYJEK0ARns7k2sbHY="
crossorigin="anonymous" />
<style>
.my-class {
outline: none;
}
</style>
</head>

<body>
<div id="root"></div>
<script src="./index.min.js"></script>
</body>

<body>
<div id="root"></div>
<script src="./index.min.js"></script>
</body>
</html>
3 changes: 2 additions & 1 deletion example/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ class App extends Component {
<pre
style={{
fontSize: 14,
fontFamily: '\'Courier New\', Courier, \'Lucida Sans Typewriter\', \'Lucida Typewriter\', monospace',
fontFamily:
"'Courier New', Courier, 'Lucida Sans Typewriter', 'Lucida Typewriter', monospace",
}}
>
{this.state.title}
Expand Down
10 changes: 5 additions & 5 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@ module.exports = {
collectCoverage: true,

// An array of glob patterns indicating a set of files for which coverage information should be collected
collectCoverageFrom: ["src/*"],
collectCoverageFrom: ['src/*'],

// The directory where Jest should output its coverage files
coverageDirectory: "coverage",
coverageDirectory: 'coverage',

// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
Expand Down Expand Up @@ -118,13 +118,13 @@ module.exports = {
// setupFiles: [],

// The path to a module that runs some code to configure or set up the testing framework before each test
setupTestFrameworkScriptFile: "<rootDir>/jest.setup.js",
setupTestFrameworkScriptFile: '<rootDir>/jest.setup.js',

// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],

// The test environment that will be used for testing
testEnvironment: "jest-environment-jsdom",
testEnvironment: 'jest-environment-jsdom',

// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
Expand Down Expand Up @@ -153,7 +153,7 @@ module.exports = {
// testRunner: "jasmine2",

// This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
testURL: "http://localhost/",
testURL: 'http://localhost/',

// Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
// timers: "real",
Expand Down
24 changes: 19 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,13 @@
"name": "react-sane-contenteditable",
"version": "1.6.1",
"description": "React component with sane defaults to make any element contentEditable",
"keywords": ["content-editable", "contenteditable", "editable", "react", "react-component"],
"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"
Expand All @@ -13,8 +19,16 @@
},
"license": "MIT",
"author": "Ashley Williams <hi@ashleyw.co.uk>",
"contributors": ["Nick Aspinall", "Raphael Silva Cavalcanti", "Jess Telford"],
"files": ["lib", "LICENSE", "README.md"],
"contributors": [
"Nick Aspinall",
"Raphael Silva Cavalcanti",
"Jess Telford"
],
"files": [
"lib",
"LICENSE",
"README.md"
],
"main": "lib/cjs/react-sane-contenteditable.js",
"module": "lib/esm/react-sane-contenteditable.js",
"directories": {
Expand All @@ -30,7 +44,7 @@
"dev": "yarn run demo -w",
"dev:test": "jest --watch --verbose false",
"lint": "yarn run lint:prettier",
"lint:prettier": "prettier --write src/**/*",
"lint:prettier": "prettier --write .",
"prepublish": "yarn build",
"test": "jest"
},
Expand Down Expand Up @@ -62,7 +76,7 @@
"husky": "1.0.0-rc.13",
"jest": "^23.4.2",
"jsdom": "^11.12.0",
"prettier": "1.14.2",
"prettier": "^2.0.4",
"react": "^16.4.2",
"react-dom": "^16.3.2",
"rimraf": "^2.6.2",
Expand Down
7 changes: 1 addition & 6 deletions rollup.config.demo.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,7 @@ export default {
include: common.plugins.commonJs.include,
exclude: ['node_modules/process-es6/**'],
namedExports: {
'node_modules/react/index.js': [
'Children',
'Component',
'PropTypes',
'createElement',
],
'node_modules/react/index.js': ['Children', 'Component', 'PropTypes', 'createElement'],
'node_modules/react-dom/index.js': ['render'],
},
}),
Expand Down
7 changes: 2 additions & 5 deletions rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,7 @@ export default [
format: 'esm',
name: common.output.name,
},
external: id => !id.startsWith('\0') && !id.startsWith('.') && !id.startsWith('/'),
plugins: [
babel(common.plugins.babel),
sizeSnapshot(),
],
external: (id) => !id.startsWith('\0') && !id.startsWith('.') && !id.startsWith('/'),
plugins: [babel(common.plugins.babel), sizeSnapshot()],
},
];
7 changes: 2 additions & 5 deletions src/__tests__/react-sane-contenteditable.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,7 @@ global.document.createRange = jest.fn(() => mockedRange);

// Helpers
const focusThenBlur = (wrapper, element = 'div') =>
wrapper
.find(element)
.simulate('focus')
.simulate('blur');
wrapper.find(element).simulate('focus').simulate('blur');

// Styled components
const Wrapper = styled.div``;
Expand Down Expand Up @@ -295,7 +292,7 @@ describe('Sanitisation', () => {
it('calls sanitise prop when provided', () => {
const content = 'foo';
const nextContent = 'foo bar';
const sanitise = jest.fn(value => value);
const sanitise = jest.fn((value) => value);
const wrapper = mount(<ContentEditable content={content} />);

wrapper.setProps({ content: nextContent, sanitise });
Expand Down
87 changes: 50 additions & 37 deletions src/react-sane-contenteditable.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,23 +67,26 @@ class ContentEditable extends Component {

componentDidUpdate(prevProps, prevState) {
const { caretPosition, content, focus } = this.props;
const updateCaretPosition = prevProps.caretPosition !== caretPosition
|| prevProps.focus !== focus;
const updateCaretPosition =
prevProps.caretPosition !== caretPosition || prevProps.focus !== focus;
const updateContent = prevProps.content !== content;

if (updateCaretPosition || updateContent) {
this.setState({
caretPosition: updateCaretPosition
? this.getCaretPositionFromProps() : prevState.caretPosition,
value: updateContent
? this.sanitiseValue(content) : prevState.value,
}, () => {
this.setCaretPosition();
});
this.setState(
{
caretPosition: updateCaretPosition
? this.getCaretPositionFromProps()
: prevState.caretPosition,
value: updateContent ? this.sanitiseValue(content) : prevState.value,
},
() => {
this.setCaretPosition();
},
);
}
}

getRange () {
getRange() {
return this.selection.rangeCount ? this.selection.getRangeAt(0) : document.createRange();
}

Expand Down Expand Up @@ -127,7 +130,7 @@ class ContentEditable extends Component {
const prefix = prevValue.slice(0, startOffset);
const suffix = prevValue.slice(endOffset);

return [prefix, valueToInsert, suffix].join('')
return [prefix, valueToInsert, suffix].join('');
};

sanitiseValue(value, props = this.props) {
Expand Down Expand Up @@ -155,12 +158,16 @@ class ContentEditable extends Component {
.replace(/\r|\n{3,}/g, '\n\n')
// Remove leading & trailing whitespace
// FIXME This causes an issue when setting caret position
.split('\n').map(line => line.trim()).join('\n');
.split('\n')
.map((line) => line.trim())
.join('\n');
}

return nextValue
// Ensure maxLength not exceeded
.substr(0, maxLength);
return (
nextValue
// Ensure maxLength not exceeded
.substr(0, maxLength)
);
}

onBlur = (ev) => {
Expand All @@ -180,18 +187,21 @@ class ContentEditable extends Component {
return;
}

this.setState({
caretPosition: this.getCaret(),
value: this.sanitiseValue(innerText),
}, () => {
const { onChange } = this.props;
this.setState(
{
caretPosition: this.getCaret(),
value: this.sanitiseValue(innerText),
},
() => {
const { onChange } = this.props;

if (isFunction(onChange)) {
const { value } = this.state;
if (isFunction(onChange)) {
const { value } = this.state;

onChange(ev, value);
}
});
onChange(ev, value);
}
},
);
};

onKeyDown = (ev) => {
Expand Down Expand Up @@ -237,23 +247,26 @@ class ContentEditable extends Component {
}
};

onPaste = ev => {
onPaste = (ev) => {
ev.preventDefault();

const pastedValue = ev.clipboardData.getData('text');
const value = this.insertAtCaret(this.ref.innerText, pastedValue);
const { startOffset } = this.getRange();

this.setState({
caretPosition: this.getSafeCaretPosition(startOffset + pastedValue.length, value),
value: this.sanitiseValue(value),
}, () => {
const { onPaste } = this.props;

if (isFunction(onPaste)) {
onPaste(value);
}
});
this.setState(
{
caretPosition: this.getSafeCaretPosition(startOffset + pastedValue.length, value),
value: this.sanitiseValue(value),
},
() => {
const { onPaste } = this.props;

if (isFunction(onPaste)) {
onPaste(value);
}
},
);
};

setRef = (ref) => {
Expand Down
11 changes: 6 additions & 5 deletions src/utils.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
const reduceTargetKeys = (target, keys, predicate) =>
Object.keys(target).reduce(predicate, {});
const reduceTargetKeys = (target, keys, predicate) => Object.keys(target).reduce(predicate, {});

export const omit = (target = {}, keys = []) => reduceTargetKeys(target, keys, (acc, key) =>
keys.some(omitKey => omitKey === key) ? acc : { ...acc, [key]: target[key] });
export const omit = (target = {}, keys = []) =>
reduceTargetKeys(target, keys, (acc, key) =>
keys.some((omitKey) => omitKey === key) ? acc : { ...acc, [key]: target[key] },
);

export const isFunction = fn => Object.prototype.toString.call(fn) === '[object Function]';
export const isFunction = (fn) => Object.prototype.toString.call(fn) === '[object Function]';
Loading