Skip to content
This repository was archived by the owner on Nov 3, 2021. It is now read-only.
Open
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
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ Interpolate-Components takes a single options object as an argument and returns

- **mixedString** A string that contains component tokens to be interpolated
- **components** An object with components assigned to named attributes
- **tags** (optional) An object with custom tag syntax to be used
- **throwErrors** (optional) Whether errors should be thrown (as in pre-production environments) or we should more gracefully return the un-interpolated original string (as in production). This is optional and is false by default.

## Component tokens
Expand All @@ -37,6 +38,20 @@ const jsxExample = <p>{ children }</p>;
// <p>This is a <em>fine</em> example.</p>
```

## Custom tag syntax

```js
interpolateComponents( {
mixedString: 'This uses <<em>>custom<</em>> syntax <<icon />>',
components: { em: <em />, icon: <Icon /> },
tags: {
componentOpen: [ '<<', '>>' ],
componentClose: [ '<</', '>>' ],
componentSelfClosing: [ '<<', '/>>' ],
}
} );
```

## Testing
```sh
# install dependencies
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "interpolate-components",
"version": "1.1.1",
"version": "1.2.1",
"description": "Convert strings into structured React components.",
"repository": {
"type": "git",
Expand Down
18 changes: 16 additions & 2 deletions src/index.es6
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ import createFragment from 'react-addons-create-fragment';
*/
import tokenize from './tokenize';

const DEFAULT_TAGS = {
componentOpen: ['{{', '}}'],
componentClose: ['{{/', '}}'],
componentSelfClosing: ['{{', '/}}'],
};

let currentMixedString;

function getCloseIndex( openIndex, tokens ) {
Expand Down Expand Up @@ -95,7 +101,7 @@ function buildChildren( tokens, components ) {
}

function interpolate( options ) {
const { mixedString, components, throwErrors } = options;
const { mixedString, components, throwErrors, tags = DEFAULT_TAGS } = options;

currentMixedString = mixedString;

Expand All @@ -111,7 +117,15 @@ function interpolate( options ) {
return mixedString;
}

let tokens = tokenize( mixedString );
if ( typeof tags !== 'object' || ! tags.componentOpen || ! tags.componentClose || ! tags.componentSelfClosing ) {
if ( throwErrors ) {
throw new Error( `Interpolation Error: unable to process \`${ mixedString }\` because tags is invalid` );
}

return mixedString;
}

let tokens = tokenize( mixedString, tags );

try {
return buildChildren( tokens, components );
Expand Down
75 changes: 51 additions & 24 deletions src/tokenize.es6
Original file line number Diff line number Diff line change
@@ -1,32 +1,59 @@
function identifyToken( item ) {
// {{/example}}
if ( item.match( /^\{\{\// ) ) {
return {
type: 'componentClose',
value: item.replace( /\W/g, '' )
};
}
// {{example /}}
if ( item.match( /\/\}\}$/ ) ) {
return {
type: 'componentSelfClosing',
value: item.replace( /\W/g, '' )
};
}
// {{example}}
if ( item.match( /^\{\{/ ) ) {
return {
type: 'componentOpen',
value: item.replace( /\W/g, '' )
};
const TOKEN_TYPES = [ 'componentClose', 'componentSelfClosing', 'componentOpen' ];

function identifyToken( item, regExps ) {
for ( let i = 0; i < TOKEN_TYPES.length; i++ ) {
const type = TOKEN_TYPES[ i ];
const match = item.match( regExps[ type ] );

if ( match ) {
return {
type: type,
value: match[ 1 ]
};
}
}

return {
type: 'string',
value: item
};
}

module.exports = function( mixedString ) {
const tokenStrings = mixedString.split( /(\{\{\/?\s*\w+\s*\/?\}\})/g ); // split to components and strings
return tokenStrings.map( identifyToken );
/**
* @param {string} str
* @returns {string}
*/
function escapeRegExp( str ) {
return str.replace( /[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&' );
}

/**
* @param {string[]} tag
* @param {boolean} match
* @returns {RegExp}
*/
function makeRegExp( tag, match ) {
const [ start, end ] = tag;
const inner = match ? '\\s*(\\w+)\\s*' : '\\s*\\w+\\s*';
return new RegExp( `${escapeRegExp( start )}${inner}${escapeRegExp( end )}` );
}

module.exports = function( mixedString, tags ) {
// create regular expression that matches all components
const combinedRegExpString = TOKEN_TYPES
.map( type => tags[ type ] )
.map( tag => makeRegExp( tag, false ).source )
.join( '|' );
const combinedRegExp = new RegExp( `(${combinedRegExpString})`, 'g' );

// split to components and strings
const tokenStrings = mixedString.split( combinedRegExp );

// create regular expressions for identifying tokens
const componentRegExps = {};
TOKEN_TYPES.forEach( type => {
componentRegExps[ type ] = makeRegExp( tags[ type ], true );
});

return tokenStrings.map( (tokenString) => identifyToken( tokenString, componentRegExps ) );
};
44 changes: 44 additions & 0 deletions test/test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -253,4 +253,48 @@ describe( 'interpolate-components', () => {
assert.equal( expectedResultString, ReactDomServer.renderToStaticMarkup( instance ) );
} );
} );

describe( 'custom tags', () => {
it( 'should allow custom tags', () => {
const expectedResultString = '<span><div>test</div> <input/></span>';
const interpolatedComponent = interpolateComponents( {
mixedString: '<<div>>test<</div>> <<input/>>',
components: {
div: div,
input: input
},
tags: {
componentOpen: [ '<<', '>>' ],
componentClose: [ '<</', '>>' ],
componentSelfClosing: [ '<<', '/>>' ],
}
} );
const instance = <span>{ interpolatedComponent }</span>;
assert.equal( expectedResultString, ReactDomServer.renderToStaticMarkup( instance ) );
} );

it( 'should throw if tags is not an object', () => {
assert.throws( () => {
interpolateComponents( {
mixedString: 'test',
components: {},
tags: '{{',
throwErrors: true
} );
} );
} );

it( 'should throw if not all tags are provided', () => {
assert.throws( () => {
interpolateComponents( {
mixedString: 'test',
components: {},
tags: {
componentOpen: [ '{{', '}}' ],
},
throwErrors: true
} );
} );
} );
} );
} );