@gravityforms/gulp-tasks
Version:
Configurable Gulp tasks for use in Gravity Forms projects.
127 lines (99 loc) • 2.48 kB
JavaScript
function getGroupHeaders( groups ) {
const headers = [];
groups.forEach( ( group ) => {
group.forEach( ( lineItem ) => {
const parts = lineItem.split( /:\s+/ );
if ( parts.length < 2 ) {
return;
}
headers.push( parts[0].trim() );
});
});
return [ ...new Set( headers ) ];
}
function processRows( headers, groupedRows ) {
let resp = '';
resp += `<table><thead>`;
headers.forEach( ( header ) => {
resp += `<th>${header}</th>`;
} );
resp += `</thead><tbody>`;
groupedRows.forEach( ( { label, rows } ) => {
if ( label ) {
resp += `<tr class="group-heading"><td colspan="${ headers.length }"><strong>${ label }</strong></td></tr>`;
}
rows.forEach( ( row ) => {
resp += `<tr>`;
headers.forEach( ( header ) => {
resp += `<td>${ row[ header ] || '' }</td>`;
});
resp += `</tr>`;
} );
} );
resp += `</tbody></table>`;
return resp;
}
function isProp( text ) {
const matches = text.match( /^@[a-zA-Z0-9]+prop/ );
if ( ! matches ) {
return false;
}
return true;
}
function getGroups( lines ) {
let group = [];
const groups = [];
let propType = false;
let currentGroupName = null;
lines.forEach( ( line, lineIdx ) => {
const lineItem = line.trim();
if ( lineItem.startsWith( 'Group:' ) ) {
currentGroupName = lineItem.replace( 'Group:', '' ).trim();
return;
}
if ( propType && ! isProp( lineItem ) ) {
group.push( lineItem );
}
if (
( propType && isProp( lineItem ) ) ||
( group.length && lineIdx === lines.length - 1 )
) {
groups.push( { label: currentGroupName, lines: group } );
group = [];
currentGroupName = null;
}
if ( isProp( lineItem ) ) {
propType = lineItem;
group = [];
return;
}
});
return groups;
}
function render( lines ) {
const groups = getGroups( lines );
const headers = getGroupHeaders( groups.map( g => g.lines ) );
let rows = [];
groups.forEach( ( group ) => {
const row = [];
group.lines.forEach( ( lineItem ) => {
const parts = lineItem.split( /:\s+/ );
if ( parts.length < 2 ) {
return;
}
const key = parts[0].trim();
const value = parts[1].trim();
const lastRow = row[ row.length - 1 ];
if ( lastRow && ! lastRow[ key ] ) {
lastRow[ key ] = value;
} else {
const newRow = {};
newRow[ key ] = value;
row.push( newRow );
}
} );
rows.push( { label: group.label, rows: row } );
} );
return processRows( headers, rows );
}
module.exports = { render };