Skip to content

Instantly share code, notes, and snippets.

@deanmcpherson
Created June 16, 2016 07:54
Show Gist options
  • Save deanmcpherson/69f9962b744b273ffb64fe294ab71bc4 to your computer and use it in GitHub Desktop.
Save deanmcpherson/69f9962b744b273ffb64fe294ab71bc4 to your computer and use it in GitHub Desktop.
Text alignment -> draftjs workaround
.alignment--left {
.public-DraftStyleDefault-block {
text-align; left;
}
}
.alignment--center {
.public-DraftStyleDefault-block {
text-align; center;
}
}
.alignment--right {
.public-DraftStyleDefault-block {
text-align; right;
}
}
/** In the blockStyleFn **/
blockStyler = (block) => {
let alignment = getBlockAlignment(block);
if (!block.getText()) {
let previousBlock = this.state.editorState.getCurrentContent().getBlockBefore(block.getKey());
if (previousBlock) {
alignment = getBlockAlignment(previousBlock);
}
}
return `alignment--${alignment}`;
}
import {
CharacterMetadata
} from 'draft-js';
export default function getBlockAlignment(block) {
let style = 'left';
block.findStyleRanges(function(e) {
if (e.hasStyle('center')) style = 'center';
if (e.hasStyle('right')) style = 'right';
})
return style;
}
import {
SelectionState,
BlockMapBuilder,
EditorState,
Modifier
} from 'draft-js';
/**
USAGE
style = alignment you want (e.g. "left")
removeStyles = alignments to remove (["center", "right"])
**/
export default function styleWholeSelectedBlocksModifier(editorState, style, removeStyles = []) {
let currentContent = editorState.getCurrentContent();
let selection = editorState.getSelection();
let focusBlock = currentContent.getBlockForKey(selection.getFocusKey());
let anchorBlock = currentContent.getBlockForKey(selection.getAnchorKey());
let selectionIsBackward = selection.getIsBackward();
let changes = {
anchorOffset: 0,
focusOffset: focusBlock.getLength()
}
if (selectionIsBackward) {
changes = {
focusOffset: 0,
anchorOffset: anchorBlock.getLength()
}
}
let selectWholeBlocks = selection.merge(changes)
let modifiedContent = Modifier.applyInlineStyle(currentContent, selectWholeBlocks, style);
let finalContent = removeStyles.reduce(function(content, style) {
return Modifier.removeInlineStyle(content, selectWholeBlocks, style);
}, modifiedContent);
return EditorState.push(editorState, finalContent, 'change-inline-style');
}
@natterstefan
Copy link

@deanmcpherson Hi, thank you for creating this Gist. I am new into DraftJs, that's why I need to ask you: how do I add these files/logic to my Editor/Draft exactly? Have not figured it out (yet). Thanks in advance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment