Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rewire patterns plugin #1674

Merged
merged 7 commits into from
Jul 26, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions blocks/editable/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { BACKSPACE, DELETE, ENTER } from 'utils/keycodes';
import './style.scss';
import FormatToolbar from './format-toolbar';
import TinyMCE from './tinymce';
import patterns from './patterns';

function createTinyMCEElement( type, props, ...children ) {
if ( props[ 'data-mce-bogus' ] === 'all' ) {
Expand Down Expand Up @@ -81,6 +82,8 @@ export default class Editable extends Component {
editor.on( 'selectionChange', this.onSelectionChange );
editor.on( 'PastePostProcess', this.onPastePostProcess );

patterns.apply( this, [ editor ] );

if ( this.props.onSetup ) {
this.props.onSetup( editor );
}
Expand Down
241 changes: 241 additions & 0 deletions blocks/editable/patterns.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,241 @@
/**
* External dependencies
*/
import tinymce from 'tinymce';
import { find, get, escapeRegExp, partition, drop } from 'lodash';

/**
* WordPress dependencies
*/
import { ESCAPE, ENTER, SPACE, BACKSPACE } from 'utils/keycodes';

/**
* Internal dependencies
*/
import { getBlockTypes } from '../api/registration';

/**
* Browser dependencies
*/
const { setTimeout } = window;

export default function( editor ) {
const getContent = this.getContent.bind( this );
const { onReplace } = this.props;

const VK = tinymce.util.VK;
const settings = editor.settings.wptextpattern || {};

const patterns = getBlockTypes().reduce( ( acc, blockType ) => {
const transformsFrom = get( blockType, 'transforms.from', [] );
const transforms = transformsFrom.filter( ( { type } ) => type === 'pattern' );
return [ ...acc, ...transforms ];
}, [] );
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice use of a reducer here!


const [ enterPatterns, spacePatterns ] = partition(
patterns,
( { regExp } ) => regExp.source.endsWith( '$' ),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ES2015 string prototypes methods aren't polyfilled, so this will error in IE11.

See also: #746

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks 🙈

);

const inlinePatterns = settings.inline || [
{ delimiter: '`', format: 'code' },
];

let canUndo;

editor.on( 'selectionchange', function() {
canUndo = null;
} );

editor.on( 'keydown', function( event ) {
const { keyCode } = event;

if ( ( canUndo && keyCode === ESCAPE ) || ( canUndo === 'space' && keyCode === BACKSPACE ) ) {
editor.undoManager.undo();
event.preventDefault();
event.stopImmediatePropagation();
}

if ( VK.metaKeyPressed( event ) ) {
return;
}

if ( keyCode === ENTER ) {
enter();
// Wait for the browser to insert the character.
} else if ( keyCode === SPACE ) {
setTimeout( space );
} else if ( keyCode > 47 && ! ( keyCode >= 91 && keyCode <= 93 ) ) {
setTimeout( inline );
}
}, true );

function inline() {
const range = editor.selection.getRng();
const node = range.startContainer;
const carretOffset = range.startOffset;

// We need a non empty text node with an offset greater than zero.
if ( ! node || node.nodeType !== 3 || ! node.data.length || ! carretOffset ) {
return;
}

const textBeforeCaret = node.data.slice( 0, carretOffset );
const charBeforeCaret = node.data.charAt( carretOffset - 1 );

const { start, pattern } = inlinePatterns.reduce( ( acc, item ) => {
if ( acc.result ) {
return acc;
}

if ( charBeforeCaret !== item.delimiter.slice( -1 ) ) {
return acc;
}

const escapedDelimiter = escapeRegExp( item.delimiter );
const regExp = new RegExp( '(.*)' + escapedDelimiter + '.+' + escapedDelimiter + '$' );
const match = textBeforeCaret.match( regExp );

if ( ! match ) {
return acc;
}

const startOffset = match[ 1 ].length;
const endOffset = carretOffset - item.delimiter.length;
const before = textBeforeCaret.charAt( startOffset - 1 );
const after = textBeforeCaret.charAt( startOffset + item.delimiter.length );
const delimiterFirstChar = item.delimiter.charAt( 0 );

// test*test* => format applied
// test *test* => applied
// test* test* => not applied
if ( startOffset && /\S/.test( before ) ) {
if ( /\s/.test( after ) || before === delimiterFirstChar ) {
return acc;
}
}

const contentRegEx = new RegExp( '^[\\s' + escapeRegExp( delimiterFirstChar ) + ']+$' );
const content = textBeforeCaret.slice( startOffset, endOffset );

// Do not replace when only whitespace and delimiter characters.
if ( contentRegEx.test( content ) ) {
return acc;
}

return {
start: startOffset,
pattern: item,
};
}, {} );

if ( ! pattern ) {
return;
}

const { delimiter, format } = pattern;
const formats = editor.formatter.get( format );

if ( ! formats || ! formats[ 0 ].inline ) {
return;
}

editor.undoManager.add();
editor.undoManager.transact( () => {
node.insertData( carretOffset, '\uFEFF' );

const newNode = node.splitText( start );
const zero = newNode.splitText( carretOffset - start );

newNode.deleteData( 0, delimiter.length );
newNode.deleteData( newNode.data.length - delimiter.length, delimiter.length );

editor.formatter.apply( format, {}, newNode );
editor.selection.setCursorLocation( zero, 1 );

// We need to wait for native events to be triggered.
setTimeout( () => {
canUndo = 'space';

editor.once( 'selectionchange', () => {
if ( zero ) {
const zeroOffset = zero.data.indexOf( '\uFEFF' );

if ( zeroOffset !== -1 ) {
zero.deleteData( zeroOffset, zeroOffset + 1 );
}
}
} );
} );
} );
}

function space() {
if ( ! onReplace ) {
return;
}

// Merge text nodes.
editor.getBody().normalize();

const content = getContent();

if ( ! content.length ) {
return;
}

const firstText = content[ 0 ];

const { result, pattern } = spacePatterns.reduce( ( acc, item ) => {
return acc.result ? acc : {
result: item.regExp.exec( firstText ),
pattern: item,
};
}, {} );

if ( ! result ) {
return;
}

const range = editor.selection.getRng();
const matchLength = result[ 0 ].length;
const remainingText = firstText.slice( matchLength );

// The caret position must be at the end of the match.
if ( range.startOffset !== matchLength ) {
return;
}

const block = pattern.transform( {
content: [ remainingText, ...drop( content ) ],
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm trying to track down what this transform function is meant to accept as an argument. Is the content object intended to be an array of two members, the first entry the text following the matching and the second entry the matched substring? Is it then expected that any pattern must match only at the start of a string? Where is this documented?

match: result,
} );

onReplace( [ block ] );
}

function enter() {
if ( ! onReplace ) {
return;
}

// Merge text nodes.
editor.getBody().normalize();

const content = getContent();

if ( ! content.length ) {
return;
}

const pattern = find( enterPatterns, ( { regExp } ) => regExp.test( content[ 0 ] ) );

if ( ! pattern ) {
return;
}

const block = pattern.transform( { content } );

editor.once( 'keyup', () => onReplace( [ block ] ) );
}
}
12 changes: 11 additions & 1 deletion blocks/library/code/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { __ } from 'i18n';
* Internal dependencies
*/
import './style.scss';
import { registerBlockType, query } from '../../api';
import { registerBlockType, query, createBlock } from '../../api';

const { prop } = query;

Expand All @@ -27,6 +27,16 @@ registerBlockType( 'core/code', {
content: prop( 'code', 'textContent' ),
},

transforms: {
from: [
{
type: 'pattern',
regExp: /^```$/,
transform: () => createBlock( 'core/code' ),
},
],
},

edit( { attributes, setAttributes, className } ) {
return (
<TextareaAutosize
Expand Down
12 changes: 12 additions & 0 deletions blocks/library/heading/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,18 @@ registerBlockType( 'core/heading', {
nodeName: prop( 'h1,h2,h3,h4,h5,h6', 'nodeName' ),
},
},
{
type: 'pattern',
regExp: /^(#{2,6})\s/,
transform: ( { content, match } ) => {
const level = match[ 1 ].length;

return createBlock( 'core/heading', {
nodeName: `H${ level }`,
content,
} );
},
},
],
to: [
{
Expand Down
20 changes: 20 additions & 0 deletions blocks/library/list/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,26 @@ registerBlockType( 'core/list', {
values: children( 'ol,ul' ),
},
},
{
type: 'pattern',
regExp: /^[*-]\s/,
transform: ( { content } ) => {
return createBlock( 'core/list', {
nodeName: 'ul',
values: fromBrDelimitedContent( content ),
} );
},
},
{
type: 'pattern',
regExp: /^1[.)]\s/,
transform: ( { content } ) => {
return createBlock( 'core/list', {
nodeName: 'ol',
values: fromBrDelimitedContent( content ),
} );
},
},
],
to: [
{
Expand Down
9 changes: 9 additions & 0 deletions blocks/library/quote/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,15 @@ registerBlockType( 'core/quote', {
} );
},
},
{
type: 'pattern',
regExp: /^>\s/,
transform: ( { content } ) => {
return createBlock( 'core/quote', {
value: content,
} );
},
},
],
to: [
{
Expand Down
12 changes: 11 additions & 1 deletion blocks/library/separator/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { __ } from 'i18n';
* Internal dependencies
*/
import './block.scss';
import { registerBlockType } from '../../api';
import { registerBlockType, createBlock } from '../../api';

registerBlockType( 'core/separator', {
title: __( 'Separator' ),
Expand All @@ -16,6 +16,16 @@ registerBlockType( 'core/separator', {

category: 'layout',

transforms: {
from: [
{
type: 'pattern',
regExp: /^-{3,}$/,
transform: () => createBlock( 'core/separator' ),
},
],
},

edit( { className } ) {
return <hr className={ className } />;
},
Expand Down
3 changes: 2 additions & 1 deletion blocks/library/text/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ registerBlockType( 'core/text', {
};
},

edit( { attributes, setAttributes, insertBlocksAfter, focus, setFocus, mergeBlocks } ) {
edit( { attributes, setAttributes, insertBlocksAfter, focus, setFocus, mergeBlocks, onReplace } ) {
const { align, content, dropCap, placeholder } = attributes;
const toggleDropCap = () => setAttributes( { dropCap: ! dropCap } );
return [
Expand Down Expand Up @@ -99,6 +99,7 @@ registerBlockType( 'core/text', {
] );
} }
onMerge={ mergeBlocks }
onReplace={ onReplace }
style={ { textAlign: align } }
className={ dropCap && 'has-drop-cap' }
placeholder={ placeholder || __( 'New Paragraph' ) }
Expand Down
Loading