Skip to content

Commit

Permalink
Initial commit. Basic working version.
Browse files Browse the repository at this point in the history
  • Loading branch information
makenosound committed May 30, 2016
0 parents commit 461bffd
Show file tree
Hide file tree
Showing 14 changed files with 769 additions and 0 deletions.
14 changes: 14 additions & 0 deletions .babelrc
@@ -0,0 +1,14 @@
{
"env": {
"development": {
"presets": [
"babel-preset-es2015"
]
},
"test": {
"presets": [
"babel-preset-es2015"
]
}
}
}
16 changes: 16 additions & 0 deletions .eslintrc
@@ -0,0 +1,16 @@
{
extends: [
"standard",
],
rules: {
"comma-dangle": [2, "always-multiline"]
},
parserOptions: {
ecmaVersion: 6,
sourceType: "module",
},
plugins: [
"standard",
]
}

2 changes: 2 additions & 0 deletions .gitignore
@@ -0,0 +1,2 @@
node_modules
npm-debug.log*
15 changes: 15 additions & 0 deletions .npmignore
@@ -0,0 +1,15 @@
# Dependency directory
# Commenting this out is preferred by some people, see
# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git-
node_modules

# sources
/src/
.babelrc
.eslintrc
.gitignore
README.md
CHANGELOG.md

# NPM debug
npm-debug.log*
4 changes: 4 additions & 0 deletions CHANGELOG.md
@@ -0,0 +1,4 @@
# Change Log

All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).
9 changes: 9 additions & 0 deletions LICENSE.md
@@ -0,0 +1,9 @@
The MIT License (MIT)

Copyright © 2016 [Icelab](http://icelab.com.au/).

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.
51 changes: 51 additions & 0 deletions README.md
@@ -0,0 +1,51 @@
# Draft.js Single Line plugin

*This is a plugin for the [`draft-js-plugins-editor`](https://www.draft-js-plugins.com/), a plugin system that sits on top of Draft.js.*

This plugin adds support restricting [Facebook’s Draft.js editor](https://facebook.github.io/draft-js/) to a single line of content. It will condense any blocks into a single block, and (optionally) strip any rich entities.

## What, why?!

Madness I know, however there places you want to allow _some_ rich styling yet the underlying value should still be a single line. Allowing titles for things like blog posts or pages to contain strong/emphasis is our main use-case.

## Usage

```js
import createSingleLinePlugin from 'draft-js-single-line-plugin'
const singleLinePlugin = createSingleLinePlugin()
```

This can then be passed into a `draft-js-plugins-editor` component:

```js
import createSingleLinePlugin from 'draft-js-single-line-plugin'
const singleLinePlugin = createSingleLinePlugin()
import Editor from 'draft-js-plugins-editor'

const plugins = [singleLinePlugin]

<Editor plugins={plugins}
blockRenderMap={singleLinePlugin.blockRenderMap} />
```

The plugin export a custom `blockRenderMap` that overrides the draft-js defaults and restricts the editor from rendering anything _except_ an `unstyled` block. You’ll need to manually pass it as above as the `draft-js-plugins-editor` doesn’t yet support this.

## Options

You can pass options to the plugin as you call it:

```js
const options = {
stripEntities: false
}
const singleLinePlugin = createSingleLinePlugin(options)
```

There’s only one option so far: `stripEntities: true/false`.

## Developing

```
npm install react react-dom draft-js
npm run test
```
112 changes: 112 additions & 0 deletions lib/index.js
@@ -0,0 +1,112 @@
'use strict';

Object.defineProperty(exports, "__esModule", {
value: true
});

var _immutable = require('immutable');

var _draftJs = require('draft-js');

var _utils = require('./utils');

/**
* Default options
* @type {Object}
*/
var defaultOptions = {
stripEntities: true
};

/**
* Single Line Plugin
* @param {Object} options Per-instance options to override the defaults
* @return {Object} Compatible draft-js-editor-plugin object
*/
function singleLinePlugin() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];

options = Object.assign({}, defaultOptions, options);

return {
/**
* Return a compatible blockRenderMap
*
* NOTE: Needs to be explicitly applied, the plugin system doesn’t do
* anything with this at the moment.
*
* @type {ImmutableMap}
*/
blockRenderMap: (0, _immutable.Map)({
'unstyled': {
element: 'div'
}
}),

/**
* onChange
*
* Condense multiple blocks into a single block and (optionally) strip all
* entities from the content of that block.
*
* @param {EditorState} editorState The current state of the editor
* @return {EditorState} A new editor state
*/
onChange: function onChange(editorState) {
var blocks = editorState.getCurrentContent().getBlocksAsArray();

// If we have more than one block, compress them
if (blocks.length > 1) {
editorState = (0, _utils.condenseBlocks)(editorState, blocks, options);
} else {
// We only have one content block
var contentBlock = blocks[0];
var text = contentBlock.getText();
var characterList = contentBlock.getCharacterList();

if (_utils.NEWLINE_REGEX.test(text) || (0, _utils.characterListhasEntities)(characterList)) {
// Replace the text stripped of its newlines. Note that we replace
// one '\n' with one ' ' so we don't need to modify the characterList
text = (0, _utils.replaceNewlines)(text);

// Strip entities?
if (options.stripEntities) {
characterList = characterList.map(_utils.stripEntityFromCharacterMetadata);
}

// Create a new content block based on the old one
contentBlock = new _draftJs.ContentBlock({
key: (0, _draftJs.genKey)(),
text: text,
type: 'unstyled',
characterList: characterList,
depth: 0
});

// Update the editor state with the compressed version
// const selection = editorState.getSelection()
var newContentState = _draftJs.ContentState.createFromBlockArray([contentBlock]);

// Create the new state as an undoable action
editorState = _draftJs.EditorState.push(editorState, newContentState, 'insert-characters');
editorState = _draftJs.EditorState.moveFocusToEnd(editorState);
}
}

return editorState;
},


/**
* Stop new lines being inserted by always handling the return
*
* @param {KeyboardEvent} e Synthetic keyboard event from draftjs
* @return {Boolean} Did we handle the return or not? (pro-trip: yes, we did)
*/
handleReturn: function handleReturn(e) {
return true;
}
};
}

exports.default = singleLinePlugin;
99 changes: 99 additions & 0 deletions lib/utils.js
@@ -0,0 +1,99 @@
'use strict';

Object.defineProperty(exports, "__esModule", {
value: true
});
exports.NEWLINE_REGEX = undefined;
exports.replaceNewlines = replaceNewlines;
exports.condenseBlocks = condenseBlocks;
exports.stripEntityFromCharacterMetadata = stripEntityFromCharacterMetadata;
exports.characterListhasEntities = characterListhasEntities;

var _draftJs = require('draft-js');

var _immutable = require('immutable');

/**
* Greedy regex for matching newlines
* @type {RegExp}
*/
var NEWLINE_REGEX = exports.NEWLINE_REGEX = /\n/g;

/**
* Replace newline characters with the passed string
* @param {String} str String to replace
* @param {String} replacement Replacement characters
* @return {String} Modified string
*/
function replaceNewlines(str) {
var replacement = arguments.length <= 1 || arguments[1] === undefined ? ' ' : arguments[1];

return str.replace(NEWLINE_REGEX, replacement);
}

/**
* Condense an array of content blocks into a single block
* @param {EditorState} editorState draft-js EditorState instance
* @param {Array} blocks Array of ContentBlocks
* @param {Object} options
* @return {EditorState} A modified EditorState instance
*/
function condenseBlocks(editorState, blocks, options) {
blocks = blocks || editorState.getCurrentContent().getBlocksAsArray();
var text = (0, _immutable.List)();
var characterList = (0, _immutable.List)();

// Gather all the text/characterList and concat them
blocks.forEach(function (block) {
// Atomic blocks should be ignored (stripped)
if (block.getType() !== 'atomic') {
text = text.push(replaceNewlines(block.getText()));
characterList = characterList.concat(block.getCharacterList());
}
});

// Strip entities?
if (options.stripEntities) {
characterList = characterList.map(stripEntityFromCharacterMetadata);
}

// Create a new content block
var contentBlock = new _draftJs.ContentBlock({
key: (0, _draftJs.genKey)(),
text: text.join(''),
type: 'unstyled',
characterList: characterList,
depth: 0
});

// Update the editor state with the compressed version
var newContentState = _draftJs.ContentState.createFromBlockArray([contentBlock]);
// Create the new state as an undoable action
editorState = _draftJs.EditorState.push(editorState, newContentState, 'remove-range');
// Move the selection to the end
return _draftJs.EditorState.moveFocusToEnd(editorState);
}

/**
* Strip any `entity` keys from a CharacterMetadata set
* @param {CharacterMetadata} characterMeta An Immutable.Record representing the metadata for an individual character
* @return {CharacterMetadata}
*/
function stripEntityFromCharacterMetadata(characterMeta) {
return characterMeta.set('entity', null);
}

/**
* Check if a CharacterList contains entities
* @param {CharacterList} characterList The list of characters to check
* @return {Boolean} Contains entities?
*/
function characterListhasEntities(characterList) {
var hasEntities = false;
characterList.forEach(function (characterMeta) {
if (characterMeta.get('entity') !== null) {
hasEntities = true;
}
});
return hasEntities;
}
53 changes: 53 additions & 0 deletions package.json
@@ -0,0 +1,53 @@
{
"name": "draft-js-single-line-plugin",
"version": "0.0.1",
"description": "Restrict a draft-js editor to a single line of input.",
"main": "lib/index.js",
"scripts": {
"build": "babel src --out-dir lib",
"compile": "npm run build",
"precompile": "npm run clean",
"prepublish": "npm run compile",
"test": "NODE_ENV=test babel-node test | faucet",
"posttest": "npm run lint",
"clean": "rm -rf ./lib/*",
"lint": "eslint 'src/*.js' 'src/**/*.js'; exit 0"
},
"repository": {
"type": "git",
"url": "https://github.com/icelab/draft-js-single-line-plugin.git"
},
"keywords": [
"draft-js",
"draft-js-plugins",
"plugins",
"plugin"
],
"authors": [
"Max Wheeler <max@icelab.com.au> (https://github.com/makenosound)"
],
"license": "MIT",
"bugs": {
"url": "https://github.com/icelab/draft-js-single-line-plugin/issues"
},
"homepage": "https://github.com/icelab/draft-js-single-line-plugin",
"peerDependencies": {
"draft-js": ">=0.7.0",
"react": ">=15.0.0",
"react-dom": ">=15.0.0"
},
"devDependencies": {
"babel-cli": "6.7.5",
"babel-preset-es2015": "6.6.0",
"eslint": "2.8.0",
"eslint-config-standard": "5.1.0",
"eslint-plugin-promise": "1.3.1",
"eslint-plugin-standard": "1.3.2",
"faucet": "0.0.1",
"is-function": "1.0.1",
"tape": "4.5.1"
},
"dependencies": {
"immutable": "3.8.1"
}
}

0 comments on commit 461bffd

Please sign in to comment.