Skip to content
Closed
Changes from 1 commit
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
Prev Previous commit
Parse list of attributes in block comments
  • Loading branch information
dmsnell committed Apr 23, 2017
commit ee48578e7e19150583b9e6e8c93f91a806238dc2
40 changes: 37 additions & 3 deletions blocks/api/parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ export function parseWithGrammar( content ) {
*
* @type {RegExp}
*/
const blockOpenerPattern = /<!--\s*wp:([a-z](?:[a-z0-9/][a-z0-9]+)*)\s+((?!-->).)*-->/ig;
const blockOpenerPattern = /<!--\s*wp:([a-z](?:[a-z0-9/][a-z0-9]+)*)\s+((?:(?!-->).)*)-->/ig;

/**
* Matches closing block comments
Expand All @@ -246,6 +246,39 @@ const blockOpenerPattern = /<!--\s*wp:([a-z](?:[a-z0-9/][a-z0-9]+)*)\s+((?!-->).
*/
const blockCloserPattern = /<!--\s*\/wp:([a-z](?:[a-z0-9/][a-z0-9]+)*)\s+-->/ig;

/**
* Splits a string once at a given delimiter
*
* @param {String} delimiter pattern at which to split string
* @param {String} s input string to split
* @returns {[String,String]} [part before delimiter, part after delimiter]
*/
function splitAt( delimiter, s ) {
const [ name, ...values ] = s.split( delimiter );

return [ name, values.join( '' ) ];
}

/**
* Takes a string containing block comment attributes and
* returns an object of key/value pairs representing same
*
* Note: The last of a repeating definition of an attribute
* for a given key will be the value of the attribute
* in the returned object.
*
* @param {String} attrs e.g. " id:14 url:https://s0.wp.com/thing
* @returns {Object<String,String>} key/value pairs of attributes
*/
function regexParseAttrs( attrs ) {
return attrs
.trim()
.split( /\s+/ )
.map( s => splitAt( ':', s ) )
.filter( ( [ name, /* value */ ] ) => !! name )
.reduce( ( o, [ name, value ] ) => ( { ...o, [ name ]: value } ), {} );
}

/**
* Parses the post content with a RegExp based parser
* and returns a list of block data structures
Expand Down Expand Up @@ -316,13 +349,14 @@ export function regExpParser( content, output = [], remaining = '', openBlock =

// open a block
if ( firstOpen ) {
const [ /* fullMatch */, blockType, /* attrs */ ] = firstOpen;
const [ /* fullMatch */, blockType, rawAttrs ] = firstOpen;
const attrs = regexParseAttrs( rawAttrs );

return () => regExpParser(
content.slice( blockOpenerPattern.lastIndex ),
output,
content.slice( blockOpenerPattern.lastIndex ),
{ blockType, attrs: {} }
{ blockType, attrs }
);
}

Expand Down