From f701eda482180219dae79be9248a29727cbc6e23 Mon Sep 17 00:00:00 2001 From: Wiktor Ozga Date: Sun, 13 Mar 2016 17:23:40 +0100 Subject: [PATCH] Initial Commit --- .babelrc | 3 ++ .eslintignore | 1 + .eslintrc | 8 ++++ .gitignore | 2 + .npmignore | 3 ++ LICENSE | 21 +++++++++ README.md | 118 +++++++++++++++++++++++++++++++++++++++++++++++ package.json | 29 ++++++++++++ src/RawParser.js | 118 +++++++++++++++++++++++++++++++++++++++++++++++ src/index.js | 8 ++++ src/render.js | 82 ++++++++++++++++++++++++++++++++ test/render.js | 81 ++++++++++++++++++++++++++++++++ 12 files changed, 474 insertions(+) create mode 100644 .babelrc create mode 100644 .eslintignore create mode 100644 .eslintrc create mode 100644 .gitignore create mode 100644 .npmignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 package.json create mode 100644 src/RawParser.js create mode 100644 src/index.js create mode 100644 src/render.js create mode 100644 test/render.js diff --git a/.babelrc b/.babelrc new file mode 100644 index 0000000..c13c5f6 --- /dev/null +++ b/.babelrc @@ -0,0 +1,3 @@ +{ + "presets": ["es2015"] +} diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 0000000..fdf7ed5 --- /dev/null +++ b/.eslintignore @@ -0,0 +1 @@ +lib/** diff --git a/.eslintrc b/.eslintrc new file mode 100644 index 0000000..400c86e --- /dev/null +++ b/.eslintrc @@ -0,0 +1,8 @@ +{ + "extends": "airbnb/base", + "env": { + "browser": true, + "node": true, + "mocha": true + } +} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..491fc35 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +node_modules +lib diff --git a/.npmignore b/.npmignore new file mode 100644 index 0000000..b0b20bd --- /dev/null +++ b/.npmignore @@ -0,0 +1,3 @@ +src +node_modules +test diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..dace46e --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Wiktor Ożga + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..05a983e --- /dev/null +++ b/README.md @@ -0,0 +1,118 @@ +# Redraft +Renders the result of Draft.js convertToRaw using provided callbacks, works well with React + +## What does it do? +It can convert whole raw state or just specific parts to desired output like React components or an html string. + +Additionally you could just parse the raw using provided RawPraser to get a nested structure for a specific block. + +## Install +``` sh +$ npm install --save redraft +``` + +## Example rendering to React +``` js +import React, { Component, PropTypes } from 'react'; +import { renderRaw } from 'redraft'; + +/** + * You can use inline styles or classNames inside your callbacks + */ +const styles = { + code: { + backgroundColor: 'rgba(0, 0, 0, 0.05)', + fontFamily: '"Inconsolata", "Menlo", "Consolas", monospace', + fontSize: 16, + padding: 2, + }, + codeBlock: { + backgroundColor: 'rgba(0, 0, 0, 0.05)', + fontFamily: '"Inconsolata", "Menlo", "Consolas", monospace', + fontSize: 16, + padding: 20, + }, +}; + +/** + * Those callbacks will be called recursively to render a nested structure + */ +const inlineRenderers = { + BOLD: (children) => {children}, + ITALIC: (children) => {children}, + UNDERLINE: (children) => {children}, + CODE: (children) => {children}, +}; + +// just a helper to add a
after a block +const addBreaklines = (children) => children.map(child => [child,
]); + +/** + * Note that block callbacks receive an array of blocks with same styling + */ +const blockRenderers = { + unstyled: (children) => children.map(child =>

{child}

), + blockquote: (children) =>
{addBreaklines(children)}
, + 'header-one': (children) => children.map(child =>

{child}

), + 'header-two': (children) => children.map(child =>

{child}

), + 'code-block': (children) =>
{addBreaklines(children)}
, + 'unordered-list-item': (children) => , + 'ordered-list-item': (children) =>
    {children.map(child =>
  1. {child}
  2. )}
, +}; + +export default class Renderer extends Component { + + static propTypes = { + raw: PropTypes.object + } + + renderWarning() { + return
Nothing to render.
; + } + + render() { + const { raw } = this.props; + if (!raw) { + return this.renderWarning(); + } + const rendered = renderRaw(raw, inlineRenderers, blockRenderers); + // renderRaw returns a null if there's nothing to render + if (!rendered) { + return this.renderWarning(); + } + return ( +
+ {rendered} +
+ ); + } +} +``` + +## API +### `renderRaw(Object:raw, Object:inlineRendrers, Object:blockRenderers)` +Returns an array of rendered blocks. +- raw - result of the Draft.js convertToRaw +- inlineRendrers - object of key => callback pairs, where key is a Draft.js style and callback accepts an array of children +- inlineRendrers - similar to inlineRendrers - here each child is a block with same style - see the example for a use case + +### `new RawPraser(Object: block)` +Initialize a new raw parser with a single block +- block - single element of Drafts raw.blocks + +### `RawPraser.parse()` +Parses the provided block and returns an nested node object + +### `renderNode(Object:node, Object:inlineRendrers)` +Returns an rendered single block. +- node - result of the RawPraser.parse() + + +## What's missing / TODO +- Entities +- Support for 'ordered-list-item' and 'unordered-list-item' with depth +- Consider dropping the lodash dependecy + +## Credits +- [backdraft-js](https://github.com/evanc/backdraft-js) +- [Draft.js](https://facebook.github.io/draft-js) diff --git a/package.json b/package.json new file mode 100644 index 0000000..0144c3d --- /dev/null +++ b/package.json @@ -0,0 +1,29 @@ +{ + "name": "redraft", + "version": "0.1.0", + "description": "Renders the result of Draft.js convertToRaw using provided callbacks, works well with React", + "main": "./lib/index.js", + "scripts": { + "compile": "babel src --out-dir lib", + "lint": "eslint src", + "mocha": "mocha --compilers js:babel-core/register", + "test": "npm run lint && npm run mocha" + }, + "keywords": [ + "draft-js" + ], + "author": "", + "license": "MIT", + "dependencies": { + "lodash": "^4.6.1" + }, + "devDependencies": { + "babel-cli": "^6.6.5", + "babel-core": "^6.7.2", + "babel-preset-es2015": "^6.6.0", + "chai": "^3.5.0", + "eslint": "^2.4.0", + "eslint-config-airbnb": "^6.1.0", + "mocha": "^2.4.5" + } +} diff --git a/src/RawParser.js b/src/RawParser.js new file mode 100644 index 0000000..ca7d26f --- /dev/null +++ b/src/RawParser.js @@ -0,0 +1,118 @@ +import { difference, filter } from 'lodash'; + +export default class RawParser { + + constructor({ text, inlineStyleRanges: ranges }) { + this.setRelevantIndexes(ranges, text); + this.text = text; + this.ranges = ranges; + } + + // values in haystack must be unique + containsSome(haystack, needles) { + return haystack.length > difference(haystack, needles).length; + } + + relevantStyles(offset) { + const styles = filter(this.ranges, + (range) => offset >= range.offset && offset < (range.offset + range.length) + ); + return styles.map((style) => style.style); + } + + /** + * Creates an array of soreted char indexes to avoid iterating over every single character + */ + setRelevantIndexes(ranges, text) { + const relevantIndexes = []; // its const but its going to be mutated :) + + // set indexes to corresponding keys to ensure uniquenes + ranges.forEach((range) => { + relevantIndexes.push(range.offset); + relevantIndexes.push(range.offset + range.length); + // also add neighbouring chars as relevant + relevantIndexes.push(range.offset - 1); + relevantIndexes.push(range.offset + 1); + relevantIndexes.push(range.offset + range.length - 1); + relevantIndexes.push(range.offset + range.length + 1); + }); + + // add text start and end to relevant indexes + relevantIndexes.push(0); + relevantIndexes.push(text.length - 1); + const uniqueRelevantIndexes = relevantIndexes.filter( + (value, index, self) => self.indexOf(value) === index + ); + // and sort it + uniqueRelevantIndexes.sort((aa, bb) => (aa - bb)); + + this.relevantIndexes = uniqueRelevantIndexes; + } + + + /** + * Iterates over relevant text indexes and calls itself to create nested nodes + */ + nodeIterator(nodeStyle = null) { + const node = { style: nodeStyle, content: [] }; + for (this.iterator; this.iterator < this.relevantIndexes.length; this.iterator++) { + const index = this.relevantIndexes[this.iterator]; + + if (index < 0 || index > (this.text.length - 1)) { + continue; + } + // figure out what styles this char and the next char need + // (regardless of whether there *is* a next char or not) + const characterStyles = this.relevantStyles(index); + const nextCharacterStyles = this.relevantStyles(index + 1); + + // calculate styles to add and remove + const stylesToAdd = difference(characterStyles, this.styleStack); + this.stylesToRemove = difference(characterStyles, nextCharacterStyles); + + if (stylesToAdd[0]) { + this.styleStack.push(stylesToAdd[0]); + // create a nested node if theres a style to add + node.content.push(this.nodeIterator(stylesToAdd[0])); + this.styleStack.pop(); + // close the node if there are styles to remove + if (this.containsSome(this.styleStack, this.stylesToRemove)) { + return node; + } + // move on to next character + continue; + } + // push self + node.content.push(this.text.substr(index, 1)); + // close the node if there are styles to remove + if (this.containsSome(this.styleStack, this.stylesToRemove)) { + return node; + } + // calculate distance or set it to 0 if thers no next relevantIndex + const distance = this.relevantIndexes[this.iterator + 1] + ? this.relevantIndexes[this.iterator + 1] - index + : 0; + // we check if there are any chars between current and the next one + if (distance > 1) { + // add all the chars up to next relevantIndex + node.content.push(this.text.substr(index + 1, distance - 1)); + } + } + return node; + } + + + /** + * Converts raw block to object with nested style objects, + * while it returns an object not a string + * the idea is still mostly same as backdraft.js (https://github.com/evanc/backdraft-js) + */ + parse() { + // reset some calss propeties + this.styleStack = []; + this.stylesToRemove = []; + this.iterator = 0; + return this.nodeIterator(); + } + +} diff --git a/src/index.js b/src/index.js new file mode 100644 index 0000000..76515bd --- /dev/null +++ b/src/index.js @@ -0,0 +1,8 @@ +import RawParser from './RawParser'; +import { renderRaw, renderNode } from './render'; + +export { + RawParser, + renderRaw, + renderNode, +}; diff --git a/src/render.js b/src/render.js new file mode 100644 index 0000000..2c1baae --- /dev/null +++ b/src/render.js @@ -0,0 +1,82 @@ +import RawParser from './RawParser'; + + +/** + * Concats or insets a string at given array index + */ +const pushString = (string, array, index) => { + const tempArray = array; + if (!array[index]) { + tempArray[index] = string; + } else { + tempArray[index] += string; + } + return tempArray; +}; + +/** + * Recursively renders a node with nested nodes with given callbacks + */ +export const renderNode = (node, styleRendrers) => { + let children = []; + let index = 0; + node.content.forEach((part) => { + if (typeof part === 'string' || part instanceof String) { + children = pushString(part, children, index); + } else { + index++; + children[index] = renderNode(part, styleRendrers); + index++; + } + }); + if (styleRendrers[node.style]) { + return styleRendrers[node.style](children); + } + return children; +}; + + +/** + * Renders blocks grouped by type using provided blockStyleRenderers + */ +const renderBlocks = (blocks, inlineRendrers = {}, blockRenderers = {}) => { + // initialize + const rendered = []; + let group = []; + let prevType = null; + blocks.forEach((block) => { + const node = new RawParser(block).parse(); + const renderedNode = renderNode(node, inlineRendrers); + // if type of the block has changed render the block and clear group + if (prevType && prevType !== block.type) { + if (blockRenderers[prevType]) { + rendered.push(blockRenderers[prevType](group)); + } else { + rendered.push(group); + } + group = []; + } + // push current node to group + group.push(renderedNode); + // lastly save current type for refference + prevType = block.type; + }); + // render last group + if (blockRenderers[prevType]) { + rendered.push(blockRenderers[prevType](group)); + } else { + rendered.push(group); + } + return rendered; +}; + +/** + * Converts and renders each block of Draft.js rawState + */ +export const renderRaw = (raw, inlineRendrers = {}, blockRenderers = {}) => { + const blocks = raw.blocks; + if (!blocks || blocks[0].text.length === 0) { + return null; + } + return renderBlocks(blocks, inlineRendrers, blockRenderers); +}; diff --git a/test/render.js b/test/render.js new file mode 100644 index 0000000..63a68b2 --- /dev/null +++ b/test/render.js @@ -0,0 +1,81 @@ +import chai from 'chai'; +import { renderRaw } from '../src'; + +chai.should(); + +const raw = { + entityMap: {}, + blocks: [{ + key: '77n1t', + text: 'Lorem ipsum dolor sit amet, pro nisl sonet ad. ', + type: 'unstyled', + depth: 0, + inlineStyleRanges: [ + { + offset: 0, + length: 17, + style: 'BOLD', + }, + { + offset: 6, + length: 21, + style: 'ITALIC', + }, + ], + entityRanges: {}, + }, { + key: 'a005', + text: 'Eos affert numquam id, in est meis nobis. Legimus singulis suscipiantur eum in, ceteros invenire tractatos his id. ', // eslint-disable-line max-len + type: 'blockquote', + depth: 0, + inlineStyleRanges: [ + { + offset: 80, + length: 17, + style: 'ITALIC', + }, + ], + entityRanges: {}, + }, { + key: 'ee96q', + text: 'Facer facilis definiebas ea pro, mei malis libris latine an. Senserit moderatius vituperata vis in.', // eslint-disable-line max-len + type: 'unstyled', + depth: 0, + inlineStyleRanges: [ + { + offset: 0, + length: 99, + style: 'BOLD', + }, + ], + entityRanges: {}, + }], +}; + +// to render to a plain string we need to be sure all the arrays are joined after render +const joinRecursively = (array) => array.map((child) => { + if (Array.isArray(child)) { + return joinRecursively(child); + } + return child; +}).join(''); + +// render to HTML +const inlineRenderers = { + BOLD: (children) => `${children.join('')}`, + ITALIC: (children) => `${children.join('')}`, +}; + +const blockRenderers = { + unstyled: (children) => `

${joinRecursively(children)}

`, + blockquote: (children) => `
${joinRecursively(children)}
`, +}; + + +describe('renderRaw', () => { + it('should render correctly', () => { + const rendered = renderRaw(raw, inlineRenderers, blockRenderers); + const joined = joinRecursively(rendered); + joined.should.equal('

Lorem ipsum dolor sit amet, pro nisl sonet ad.

Eos affert numquam id, in est meis nobis. Legimus singulis suscipiantur eum in, ceteros invenire tractatos his id.

Facer facilis definiebas ea pro, mei malis libris latine an. Senserit moderatius vituperata vis in.

'); // eslint-disable-line max-len + }); +});