Skip to content

Instantly share code, notes, and snippets.

@joepie91

joepie91/1-input Secret

Last active March 4, 2017 14:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joepie91/3e7125c395444963346f3bf619c630e9 to your computer and use it in GitHub Desktop.
Save joepie91/3e7125c395444963346f3bf619c630e9 to your computer and use it in GitHub Desktop.
foo{{{}}
{{align:center}bar
qux {class:test1,test2}baz{/class}{/align}}
// AST
[ { type: 'text', text: 'foo{{{}}\n{' },
{ type: 'alignment',
alignment: 'center',
contents:
[ { type: 'text', text: 'bar\nqux ' },
{ type: 'class',
classNames: [ 'test1', 'test2' ],
contents: [ { type: 'text', text: 'baz' } ] } ] },
{ type: 'text', text: '}' } ]
// Flattened into individual renderable text elements
[ { type: 'text', text: 'foo{{{}}', tags: [] },
{ type: 'newline' },
{ type: 'text', text: '{', tags: [] },
{ type: 'text',
text: 'bar',
tags: [ { type: 'alignment', alignment: 'center', contents: null } ] },
{ type: 'newline' },
{ type: 'text',
text: 'qux ',
tags: [ { type: 'alignment', alignment: 'center', contents: null } ] },
{ type: 'text',
text: 'baz',
tags:
[ { type: 'alignment', alignment: 'center', contents: null },
{ type: 'class',
classNames: [ 'test1', 'test2' ],
contents: null } ] },
{ type: 'text', text: '}', tags: [] } ]
'use strict';
module.exports = function splitTextComponents(treeList) {
function flatten(treeList, tagStack) {
return treeList.reduce((all, item) => {
if (item.type === "text") {
let splitItems = item.text.split("\n").reduce((items, line) => {
return items.concat([{
type: "text",
text: line,
tags: tagStack
}, {
type: "newline"
}]);
}, []);
/* Remove the last newline, because it's not delimiting anything. */
splitItems.pop();
return all.concat(splitItems);
} else {
return all.concat(flatten(item.contents, tagStack.concat([item])));
}
}, []);
}
return flatten(treeList, []);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment