Skip to content

Commit

Permalink
Merge pull request #759 from pattern-lab/dev
Browse files Browse the repository at this point in the history
Pattern Lab Node 3.0.0 Alpha 6
  • Loading branch information
bmuenzenmeyer authored Jan 16, 2018
2 parents da38be4 + 1955516 commit 4645d55
Show file tree
Hide file tree
Showing 71 changed files with 6,377 additions and 5,493 deletions.
415 changes: 415 additions & 0 deletions core/index.js

Large diffs are not rendered by default.

46 changes: 46 additions & 0 deletions core/lib/addPattern.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
"use strict";

const _ = require('lodash');

const logger = require('./log');

module.exports = function (pattern, patternlab) {
//add the link to the global object
if (!patternlab.data.link) {
patternlab.data.link = {};
}
patternlab.data.link[pattern.patternPartial] = '/patterns/' + pattern.patternLink;

//only push to array if the array doesn't contain this pattern
var isNew = true;
for (var i = 0; i < patternlab.patterns.length; i++) {
//so we need the identifier to be unique, which patterns[i].relPath is
if (pattern.relPath === patternlab.patterns[i].relPath) {
//if relPath already exists, overwrite that element
patternlab.patterns[i] = pattern;
patternlab.partials[pattern.patternPartial] = pattern.extendedTemplate || pattern.template;
isNew = false;
break;
}
}

// if the pattern is new, we must register it with various data structures!
if (isNew) {

logger.debug(`found new pattern ${pattern.patternPartial}`);

// do global registration
if (pattern.isPattern) {
patternlab.partials[pattern.patternPartial] = pattern.extendedTemplate || pattern.template;

// do plugin-specific registration
pattern.registerPartial();
} else {
patternlab.partials[pattern.patternPartial] = pattern.patternDesc;
}

//patterns sorted by name so the patterntype and patternsubtype is adhered to for menu building
patternlab.patterns.splice(_.sortedIndexBy(patternlab.patterns, pattern, 'name'), 0, pattern);
patternlab.graph.add(pattern);
}
};
2 changes: 1 addition & 1 deletion core/lib/asset_copy.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ const asset_copier = () => {

//watch for changes and copy
assetWatcher.on('addDir', (p) => {
const destination = path.resolve(basePath, dir.public + '/' + path.basename(p));
const destination = path.resolve(basePath, dir.public);
copyFile(p, destination, copyOptions);
}).on('add', (p) => {
const destination = path.resolve(basePath, dir.public + '/' + path.basename(p));
Expand Down
39 changes: 39 additions & 0 deletions core/lib/buildFooter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
"use strict";

const jsonCopy = require('./json_copy');
const logger = require('./log');
const of = require('./object_factory');
const Pattern = of.Pattern;

let render = require('./render'); //eslint-disable-line prefer-const

/**
* Builds footer HTML from the general footer and user-defined footer
* @param patternlab - global data store
* @param patternPartial - the partial key to build this for, either viewall-patternPartial or a viewall-patternType-all
* @returns A promise which resolves with the HTML
*/
module.exports = function (patternlab, patternPartial) {
//first render the general footer
return render(Pattern.createEmpty({extendedTemplate: patternlab.footer}), {
patternData: JSON.stringify({
patternPartial: patternPartial,
}),
cacheBuster: patternlab.cacheBuster
}).then(footerPartial => {

let allFooterData;
try {
allFooterData = jsonCopy(patternlab.data, 'config.paths.source.data plus patterns data');
} catch (err) {
logger.warning('There was an error parsing JSON for patternlab.data');
logger.warning(err);
}
allFooterData.patternLabFoot = footerPartial;

return render(patternlab.userFoot, allFooterData);
}).catch(reason => {
console.log(reason);
logger.error('Error building buildFooterHTML');
});
};
27 changes: 27 additions & 0 deletions core/lib/buildListItems.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"use strict";

const _ = require('lodash');

module.exports = function (container) {
//combine all list items into one structure
var list = [];
for (var item in container.listitems) {
if (container.listitems.hasOwnProperty(item)) {
list.push(container.listitems[item]);
}
}
container.listItemArray = _.shuffle(list);

for (var i = 1; i <= container.listItemArray.length; i++) {
var tempItems = [];
if (i === 1) {
tempItems.push(container.listItemArray[0]);
container.listitems['' + i ] = tempItems;
} else {
for (var c = 1; c <= i; c++) {
tempItems.push(container.listItemArray[c - 1]);
container.listitems['' + i ] = tempItems;
}
}
}
};
49 changes: 49 additions & 0 deletions core/lib/decompose.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
"use strict";

const logger = require('./log');
const lh = require('./lineage_hunter');
const lih = require('./list_item_hunter');
const addPattern = require('./addPattern');
const expandPartials = require('./expandPartials');

const lineage_hunter = new lh();
const list_item_hunter = new lih();

/**
* A helper that unravels a pattern looking for partials or listitems to unravel.
* The goal is really to convert pattern.template into pattern.extendedTemplate
* @param pattern - the pattern to decompose
* @param patternlab - global data store
* @param ignoreLineage - whether or not to hunt for lineage for this pattern
*/
module.exports = function (pattern, patternlab, ignoreLineage) {

//set the extendedTemplate to operate on later if we find partials to replace
if (!pattern.extendedTemplate) {
pattern.extendedTemplate = pattern.template;
}

//find any listItem blocks that within the pattern, even if there are no partials
const listItemPromise = list_item_hunter.process_list_item_partials(pattern, patternlab);

const expandPartialPromise = expandPartials(pattern, patternlab);

let lineagePromise;

//find pattern lineage
if (!ignoreLineage) {
lineagePromise = Promise.resolve(lineage_hunter.find_lineage(pattern, patternlab));
} else {
lineagePromise = Promise.resolve();
}

const addPromise = Promise.resolve(() => {
//add to patternlab object so we can look these up later.
addPattern(pattern, patternlab);
});

return Promise.all([listItemPromise, expandPartialPromise, lineagePromise, addPromise])
.catch(reason => {
logger.error(reason);
});
};
70 changes: 70 additions & 0 deletions core/lib/expandPartials.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
"use strict";

const logger = require('./log');
const ph = require('./parameter_hunter');
const smh = require('./style_modifier_hunter');
const jsonCopy = require('./json_copy');
const getPartial = require('./get');

const parameter_hunter = new ph();
const style_modifier_hunter = new smh();

module.exports = function (currentPattern, patternlab) {

const processRecursive = require('./processRecursive');

//find how many partials there may be for the given pattern
const foundPatternPartials = currentPattern.findPartials();

// expand any partials present in this pattern; that is, drill down into
// the template and replace their calls in this template with rendered
// results
if (currentPattern.engine.expandPartials && (foundPatternPartials !== null && foundPatternPartials.length > 0)) {

logger.debug(`found partials for ${currentPattern.patternPartial}`);

// determine if the template contains any pattern parameters. if so they
// must be immediately consumed
return parameter_hunter.find_parameters(currentPattern, patternlab).then(() => {

//do something with the regular old partials
foundPatternPartials.forEach((foundPartial) => {

var partial = currentPattern.findPartial(foundPartial);
var partialPattern = getPartial(partial, patternlab);

//recurse through nested partials to fill out this extended template.
return processRecursive(partialPattern.relPath, patternlab).then(() => { //eslint-disable-line no-loop-func

//complete assembly of extended template
//create a copy of the partial so as to not pollute it after the getPartial call.
var cleanPartialPattern = jsonCopy(partialPattern, `partial pattern ${partial}`);

//if partial has style modifier data, replace the styleModifier value
if (currentPattern.stylePartials && currentPattern.stylePartials.length > 0) {
style_modifier_hunter.consume_style_modifier(cleanPartialPattern, foundPartial, patternlab);
}

//this is what we came here for
logger.debug(`within ${currentPattern.patternPartial}, replacing extendedTemplate partial ${foundPartial} with ${cleanPartialPattern.patternPartial}'s extendedTemplate`);

currentPattern.extendedTemplate = currentPattern.extendedTemplate.replace(foundPartial, cleanPartialPattern.extendedTemplate);

// update the extendedTemplate in the partials object in case this
// pattern is consumed later
patternlab.partials[currentPattern.patternPartial] = currentPattern.extendedTemplate;

return Promise.resolve();
}).catch(reason => {
console.log(reason);
logger.error(reason);
});
});

}).catch(reason => {
console.log(reason);
logger.error(reason);
});
}
return Promise.resolve();
};
54 changes: 54 additions & 0 deletions core/lib/exportData.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
"use strict";

const eol = require('os').EOL;
const path = require('path');
const _ = require('lodash');

const ae = require('./annotation_exporter');

let fs = require('fs-extra'); //eslint-disable-line prefer-const

/**
* Write out our pattern information for use by the front end
* @param patternlab - global data store
*/
module.exports = function (patternlab) {

const annotation_exporter = new ae(patternlab);

const paths = patternlab.config.paths;

//write out the data
let output = '';

//config
output += 'var config = ' + JSON.stringify(patternlab.config) + ';\n';

//ishControls
output += 'var ishControls = {"ishControlsHide":' + JSON.stringify(patternlab.config.ishControlsHide) + '};' + eol;

//navItems
output += 'var navItems = {"patternTypes": ' + JSON.stringify(patternlab.patternTypes) + ', "ishControlsHide": ' + JSON.stringify(patternlab.config.ishControlsHide) + '};' + eol;

//patternPaths
output += 'var patternPaths = ' + JSON.stringify(patternlab.patternPaths) + ';' + eol;

//viewAllPaths
output += 'var viewAllPaths = ' + JSON.stringify(patternlab.viewAllPaths) + ';' + eol;

//plugins
output += 'var plugins = ' + JSON.stringify(patternlab.plugins || []) + ';' + eol;

//smaller config elements
output += 'var defaultShowPatternInfo = ' + (patternlab.config.defaultShowPatternInfo ? patternlab.config.defaultShowPatternInfo : 'false') + ';' + eol;
output += 'var defaultPattern = "' + (patternlab.config.defaultPattern ? patternlab.config.defaultPattern : 'all') + '";' + eol;

//annotations
const annotationsJSON = annotation_exporter.gather();
const annotations = 'var comments = { "comments" : ' + JSON.stringify(annotationsJSON) + '};';
fs.outputFileSync(path.resolve(paths.public.annotations, 'annotations.js'), annotations);

//write all output to patternlab-data
fs.outputFileSync(path.resolve(paths.public.data, 'patternlab-data.js'), output);
return output;
};
35 changes: 35 additions & 0 deletions core/lib/get.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"use strict";

const logger = require('./log');

module.exports = function (partialName, patternlab) {
//look for exact partial matches
for (var i = 0; i < patternlab.patterns.length; i++) {
if (patternlab.patterns[i].patternPartial === partialName) {
return patternlab.patterns[i];
}
}

//else look by verbose syntax
for (var i = 0; i < patternlab.patterns.length; i++) {
switch (partialName) {
case patternlab.patterns[i].relPath:
return patternlab.patterns[i];
case patternlab.patterns[i].verbosePartial:
return patternlab.patterns[i];
}
}

//return the fuzzy match if all else fails
for (var i = 0; i < patternlab.patterns.length; i++) {
var partialParts = partialName.split('-'),
partialType = partialParts[0],
partialNameEnd = partialParts.slice(1).join('-');

if (patternlab.patterns[i].patternPartial.split('-')[0] === partialType && patternlab.patterns[i].patternPartial.indexOf(partialNameEnd) > -1) {
return patternlab.patterns[i];
}
}
logger.warning('Could not find pattern referenced with partial syntax ' + partialName + '. This can occur when a pattern was renamed, moved, or no longer exists but it still referenced within a different template or within data as a link.');
return undefined;
};
9 changes: 2 additions & 7 deletions core/lib/lineage_hunter.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,21 @@
'use strict';
const extend = require("util")._extend;
const getPartial = require('./get');
const logger = require('./log');

const lineage_hunter = function () {

function findlineage(pattern, patternlab) {

const pa = require('./pattern_assembler');
const pattern_assembler = new pa();

// As we are adding edges from pattern to ancestor patterns, ensure it is known to the graph
patternlab.graph.add(pattern);


//find the {{> template-name }} within patterns
const matches = pattern.findPartials();
if (matches !== null) {
matches.forEach(function (match) {
//get the ancestorPattern
const ancestorPattern = pattern_assembler.getPartial(pattern.findPartial(match), patternlab);
const ancestorPattern = getPartial(pattern.findPartial(match), patternlab);

if (ancestorPattern && pattern.lineageIndex.indexOf(ancestorPattern.patternPartial) === -1) {
//add it since it didnt exist
Expand Down Expand Up @@ -99,8 +96,6 @@ const lineage_hunter = function () {

//find all lineage - patterns being consumed by this one
for (let h = 0; h < lineage.length; h++) {
// Not needed, the graph already knows the concrete pattern
// let lineagePattern = pattern_assembler.getPartial(lineageIndex[h], patternlab);
setPatternState('fromFuture', lineage[h], pattern, patternlab.graph);
}
}
Expand Down
Loading

0 comments on commit 4645d55

Please sign in to comment.