Add onTab event and fix space bug

This commit is contained in:
cyril lopez 2018-03-28 19:05:40 +02:00
parent 626efeafa8
commit e4f6082efa
5 changed files with 60 additions and 5 deletions

View File

@ -55,9 +55,10 @@
margin-top: 27px;
}
span {
white-space: pre-line;
}
// NOTE: we might need this later
// span {
// white-space: pre-line;
// }
}
h1+.editorParagraph{

View File

@ -94,3 +94,5 @@ export const CONTROLS = [
},
],
];
export const DEFAULT_INDENTATION = ' ';

View File

@ -37,6 +37,7 @@ import {
createNewBlock,
getNextBlocksList,
getSelectedBlocksList,
onTab,
updateSelection,
} from './utils';
import styles from './styles.scss';
@ -449,6 +450,13 @@ class Wysiwyg extends React.Component {
this.sendData(editorState);
};
handleTab = (e) => {
e.preventDefault();
const newEditorState = onTab(this.getEditorState());
return this.onChange(newEditorState);
}
sendData = editorState =>
this.props.onChange({
target: {
@ -545,6 +553,7 @@ class Wysiwyg extends React.Component {
keyBindingFn={this.mapKeyToEditorCommand}
onBlur={this.handleBlur}
onChange={this.onChange}
onTab={this.handleTab}
placeholder={this.props.placeholder}
setRef={editor => (this.domEditor = editor)}
stripPastedStyles

View File

@ -4,8 +4,10 @@
*
*/
import { ContentBlock, genKey } from 'draft-js';
import { ContentBlock, EditorState, genKey, Modifier } from 'draft-js';
import { List } from 'immutable';
import detectIndent from 'detect-indent';
import { DEFAULT_INDENTATION } from './constants';
export function createNewBlock(text = '', type = 'unstyled', key = genKey()) {
return new ContentBlock({ key, type, text, charaterList: List([]) });
@ -45,3 +47,43 @@ export function getSelectedBlocksList(editorState) {
.concat([[endKey, blockMap.get(endKey)]])
.toList();
}
/**
* Detect indentation in a text
* @param {String} text
* @return {String}
*/
export function getIndentation(text) {
const result = detectIndent(text);
return result.indent || DEFAULT_INDENTATION;
}
export function onTab(editorState) {
const contentState = editorState.getCurrentContent();
const selection = editorState.getSelection();
const startKey = selection.getStartKey();
const currentBlock = contentState.getBlockForKey(startKey);
const indentation = getIndentation(currentBlock.getText());
let newContentState;
if (selection.isCollapsed()) {
newContentState = Modifier.insertText(
contentState,
selection,
indentation,
);
} else {
newContentState = Modifier.replaceText(
contentState,
selection,
indentation,
);
}
return EditorState.push(
editorState,
newContentState,
'insert-characters'
);
}

View File

@ -48,6 +48,7 @@
"copy-webpack-plugin": "^4.3.1",
"cross-env": "^5.0.5",
"css-loader": "^0.28.5",
"detect-indent": "^5.0.0",
"draft-js": "^0.10.5",
"eslint": "^4.4.1",
"eslint-config-airbnb": "^15.1.0",
@ -112,4 +113,4 @@
"webpack-hot-middleware": "^2.18.2",
"whatwg-fetch": "^2.0.3"
}
}
}