Skip to content

Instantly share code, notes, and snippets.

@adrianmcli
Last active April 7, 2016 18:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adrianmcli/84a0d7ea4cec280040770548f739255e to your computer and use it in GitHub Desktop.
Save adrianmcli/84a0d7ea4cec280040770548f739255e to your computer and use it in GitHub Desktop.
// ### Note ###
//
// R.difference(currentKeys, newKeys) returns an
// array of keys that I have, but the server does
// not have.
//
// Note also that the injectChanges function does not have any changes
componentWillReceiveProps(nextProps) {
this.locks = nextProps.locks;
const newRawContent = nextProps.raw;
const userId = this.props.user._id;
const clientIsAuthor = newRawContent && newRawContent.authorId === userId;
if (!clientIsAuthor) {
const contentBlocks = convertFromRaw(nextProps.raw);
const newContentState = ContentState.createFromBlockArray(contentBlocks);
const currentContentState = this.state.editorState.getCurrentContent();
// make sure server is up-to-date with client blocks before injecting
const blockKeysMatch = checkServerHasClientKeys(newContentState, currentContentState);
if (blockKeysMatch) {
this._injectChanges.bind(this)(newContentState);
}
}
}
function checkServerHasClientKeys(newContent, currentContent) {
function getBlockKeyArray(contentState) {
const blockArray = contentState.getBlocksAsArray();
return blockArray.map( x => x.getKey());
};
const newKeys = getBlockKeyArray(newContent);
const currentKeys = getBlockKeyArray(currentContent);
// server has all the keys that the client has
return R.difference(currentKeys, newKeys).length === 0;
}
_mergeBlockArrays(newBlocks, selectedBlocks) {
const contentState = this.state.editorState.getCurrentContent();
const selectedBlockKeys = selectedBlocks.map(x => x.getKey());
return newBlocks.map( newBlock => {
const key = newBlock.getKey();
const clientBlock = contentState.getBlockForKey(key);
const isSelected = R.contains(key, selectedBlockKeys);
return isSelected ? clientBlock : newBlock;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment