Skip to content

Commit

Permalink
Initial Commit
Browse files Browse the repository at this point in the history
  • Loading branch information
lokiuz committed Mar 13, 2016
0 parents commit f701eda
Show file tree
Hide file tree
Showing 12 changed files with 474 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .babelrc
@@ -0,0 +1,3 @@
{
"presets": ["es2015"]
}
1 change: 1 addition & 0 deletions .eslintignore
@@ -0,0 +1 @@
lib/**
8 changes: 8 additions & 0 deletions .eslintrc
@@ -0,0 +1,8 @@
{
"extends": "airbnb/base",
"env": {
"browser": true,
"node": true,
"mocha": true
}
}
2 changes: 2 additions & 0 deletions .gitignore
@@ -0,0 +1,2 @@
node_modules
lib
3 changes: 3 additions & 0 deletions .npmignore
@@ -0,0 +1,3 @@
src
node_modules
test
21 changes: 21 additions & 0 deletions 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.
118 changes: 118 additions & 0 deletions 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) => <strong>{children}</strong>,
ITALIC: (children) => <em>{children}</em>,
UNDERLINE: (children) => <u>{children}</u>,
CODE: (children) => <span style={styles.code}>{children}</span>,
};

// just a helper to add a <br /> after a block
const addBreaklines = (children) => children.map(child => [child, <br />]);

/**
* Note that block callbacks receive an array of blocks with same styling
*/
const blockRenderers = {
unstyled: (children) => children.map(child => <p>{child}</p>),
blockquote: (children) => <blockquote>{addBreaklines(children)}</blockquote>,
'header-one': (children) => children.map(child => <h1>{child}</h1>),
'header-two': (children) => children.map(child => <h2>{child}</h2>),
'code-block': (children) => <pre style={styles.codeBlock}>{addBreaklines(children)}</pre>,
'unordered-list-item': (children) => <ul>{children.map(child => <li>{child}</li>)}</ul>,
'ordered-list-item': (children) => <ol>{children.map(child => <li>{child}</li>)}</ol>,
};

export default class Renderer extends Component {

static propTypes = {
raw: PropTypes.object
}

renderWarning() {
return <div>Nothing to render.</div>;
}

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 (
<div>
{rendered}
</div>
);
}
}
```

## 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)
29 changes: 29 additions & 0 deletions 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"
}
}
118 changes: 118 additions & 0 deletions 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();
}

}
8 changes: 8 additions & 0 deletions src/index.js
@@ -0,0 +1,8 @@
import RawParser from './RawParser';
import { renderRaw, renderNode } from './render';

export {
RawParser,
renderRaw,
renderNode,
};

0 comments on commit f701eda

Please sign in to comment.