Skip to content

Commit

Permalink
Merge pull request #480 from pattern-lab/dev
Browse files Browse the repository at this point in the history
Pattern Lab Node 2.6.0-alpha
  • Loading branch information
bmuenzenmeyer authored Sep 27, 2016
2 parents f8d70c5 + aefb32a commit b048e70
Show file tree
Hide file tree
Showing 15 changed files with 276 additions and 48 deletions.
2 changes: 1 addition & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@
"no-with": 2,
"quotes": [0, "single"],
"radix": 2,
"semi": [0, "never"],
"semi": [1, "always"],
"strict": 0,
"space-before-blocks": 1,
"space-before-function-paren": [1, {
Expand Down
6 changes: 3 additions & 3 deletions core/lib/annotation_exporter.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,11 @@ var annotations_exporter = function (pl) {
//take the annotation snippets and split them on our custom delimiter
var annotationsYAML = annotationsMD.split('~*~');
for (var i = 0; i < annotationsYAML.length; i++) {
var annotation = buildAnnotationMD(annotationsYAML[i], markdown_parser)
var annotation = buildAnnotationMD(annotationsYAML[i], markdown_parser);
annotations.push(annotation);
}
return false;
}
};
}

/*
Expand All @@ -72,7 +72,7 @@ var annotations_exporter = function (pl) {
function parseAnnotationsMD() {
var markdown_parser = new mp();
var annotations = [];
var mdFiles = glob.sync(paths.source.annotations + '/*.md')
var mdFiles = glob.sync(paths.source.annotations + '/*.md');

mdFiles.forEach(parseMDFile(annotations, markdown_parser));
return annotations;
Expand Down
7 changes: 6 additions & 1 deletion core/lib/object_factory.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,14 +87,19 @@ Pattern.prototype = {
// calculated path from the root of the public directory to the generated html
// file for this pattern.
// Should look something like '00-atoms-00-global-00-colors/00-atoms-00-global-00-colors.html'
getPatternLink: function (patternlab, suffixType) {
getPatternLink: function (patternlab, suffixType, customfileExtension) {
// if no suffixType is provided, we default to rendered
var suffixConfig = patternlab.config.outputFileSuffixes;
var suffix = suffixType ? suffixConfig[suffixType] : suffixConfig.rendered;

if (suffixType === 'rawTemplate') {
return this.name + path.sep + this.name + suffix + this.fileExtension;
}

if (suffixType === 'custom') {
return this.name + path.sep + this.name + customfileExtension;
}

return this.name + path.sep + this.name + suffix + '.html';
},

Expand Down
2 changes: 1 addition & 1 deletion core/lib/pattern_assembler.js
Original file line number Diff line number Diff line change
Expand Up @@ -551,7 +551,7 @@ var pattern_assembler = function () {
parseDataLinks(patternlab);
},
parse_data_links_specific: function (patternlab, data, label) {
return parseDataLinksHelper(patternlab, data, label)
return parseDataLinksHelper(patternlab, data, label);
},
parse_pattern_markdown: function (pattern, patternlab) {
parsePatternMarkdown(pattern, patternlab);
Expand Down
59 changes: 54 additions & 5 deletions core/lib/patternlab.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* patternlab-node - v2.5.1 - 2016
* patternlab-node - v2.6.0-alpha - 2016
*
* Brian Muenzenmeyer, Geoff Pursell, and the web community.
* Licensed under the MIT license.
Expand All @@ -14,8 +14,13 @@ var diveSync = require('diveSync'),
glob = require('glob'),
_ = require('lodash'),
path = require('path'),
cleanHtml = require('js-beautify').html,
inherits = require('util').inherits,
pm = require('./plugin_manager'),
plutils = require('./utilities');

var EventEmitter = require('events').EventEmitter;

function buildPatternData(dataFilesPath, fs) {
var dataFiles = glob.sync(dataFilesPath + '*.json', {"ignore" : [dataFilesPath + 'listitems.json']});
var mergeObject = {};
Expand Down Expand Up @@ -73,6 +78,28 @@ function checkConfiguration(patternlab) {
patternlab.config.outputFileSuffixes = _.extend(outputFileSuffixes, patternlab.config.outputFileSuffixes);
}

/**
* Finds and calls the main method of any found plugins.
* @param patternlab - global data store
*/
function initializePlugins(patternlab) {
var plugin_manager = new pm(patternlab.config, path.resolve(__dirname, '../../patternlab-config.json'));
var foundPlugins = plugin_manager.detect_plugins();

if (foundPlugins && foundPlugins.length > 0) {

for (var i = 0; i < foundPlugins.length; i++) {
var plugin = plugin_manager.load_plugin(foundPlugins[i]);
plugin(patternlab);
}
}
}

function PatternLabEventEmitter() {
EventEmitter.call(this);
}
inherits(PatternLabEventEmitter, EventEmitter);

var patternlab_engine = function (config) {
'use strict';

Expand All @@ -92,9 +119,13 @@ var patternlab_engine = function (config) {

patternlab.package = fs.readJSONSync(path.resolve(__dirname, '../../package.json'));
patternlab.config = config || fs.readJSONSync(path.resolve(__dirname, '../../patternlab-config.json'));
patternlab.events = new PatternLabEventEmitter();

checkConfiguration(patternlab);

//todo: determine if this is the best place to wire up plugins
initializePlugins(patternlab);

var paths = patternlab.config.paths;

function getVersion() {
Expand Down Expand Up @@ -236,6 +267,9 @@ var patternlab_engine = function (config) {
}

function buildPatterns(deletePatternDir) {

patternlab.events.emit('patternlab-build-pattern-start', patternlab);

try {
patternlab.data = buildPatternData(paths.source.data, fs);
} catch (ex) {
Expand All @@ -245,7 +279,7 @@ var patternlab_engine = function (config) {
try {
patternlab.listitems = fs.readJSONSync(path.resolve(paths.source.data, 'listitems.json'));
} catch (ex) {
plutils.logRed('missing or malformed' + paths.source.data + 'listitems.json Pattern Lab may not work without this file.');
plutils.logOrange('WARNING: missing or malformed ' + paths.source.data + 'listitems.json file. Pattern Lab may not work without this file.');
patternlab.listitems = {};
}
try {
Expand All @@ -268,9 +302,13 @@ var patternlab_engine = function (config) {

pattern_assembler.combine_listItems(patternlab);

patternlab.events.emit('patternlab-build-global-data-end', patternlab);

// diveSync once to perform iterative populating of patternlab object
processAllPatternsIterative(pattern_assembler, paths.source.patterns, patternlab);

patternlab.events.emit('patternlab-pattern-iteration-end', patternlab);

//diveSync again to recursively include partials, filling out the
//extendedTemplate property of the patternlab.patterns elements
processAllPatternsRecursive(pattern_assembler, paths.source.patterns, patternlab);
Expand Down Expand Up @@ -384,15 +422,26 @@ var patternlab_engine = function (config) {

var footerHTML = pattern_assembler.renderPattern(patternlab.userFoot, allFooterData);

patternlab.events.emit('patternlab-pattern-write-begin', patternlab, pattern);

//write the compiled template to the public patterns directory
var patternPage = headHTML + pattern.patternPartialCode + footerHTML;
fs.outputFileSync(paths.public.patterns + pattern.getPatternLink(patternlab, 'rendered'), patternPage);

//beautify the output if configured to do so
var cleanedPatternPage = config.cleanOutputHtml ? cleanHtml(patternPage, {indent_size: 2}) : patternPage;
var cleanedPatternPartialCode = config.cleanOutputHtml ? cleanHtml(pattern.patternPartialCode, {indent_size: 2}) : pattern.patternPartialCode;
var cleanedPatternTemplateCode = config.cleanOutputHtml ? cleanHtml(pattern.template, {indent_size: 2}) : pattern.template;

//write the compiled template to the public patterns directory
fs.outputFileSync(paths.public.patterns + pattern.getPatternLink(patternlab, 'rendered'), cleanedPatternPage);

//write the mustache file too
fs.outputFileSync(paths.public.patterns + pattern.getPatternLink(patternlab, 'rawTemplate'), pattern.template);
fs.outputFileSync(paths.public.patterns + pattern.getPatternLink(patternlab, 'rawTemplate'), cleanedPatternTemplateCode);

//write the encoded version too
fs.outputFileSync(paths.public.patterns + pattern.getPatternLink(patternlab, 'markupOnly'), pattern.patternPartialCode);
fs.outputFileSync(paths.public.patterns + pattern.getPatternLink(patternlab, 'markupOnly'), cleanedPatternPartialCode);

patternlab.events.emit('patternlab-pattern-write-end', patternlab, pattern);

return true;
});
Expand Down
79 changes: 79 additions & 0 deletions core/lib/plugin_manager.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
"use strict";

var plugin_manager = function (config, configPath) {
var path = require('path'),
fs = require('fs-extra'),
util = require('./utilities');

function loadPlugin(pluginName) {
return require(path.join(process.cwd(), 'node_modules', pluginName));
}

function installPlugin(pluginName) {
try {
var pluginPath = path.resolve(
path.join(process.cwd(), 'node_modules', pluginName)
);
console.log('Attempting to load plugin from', pluginPath);
try {
var pluginDirStats = fs.statSync(pluginPath);
} catch (ex) {
util.logRed(pluginName + ' not found, please use npm to install it first.');
util.logRed(pluginName + ' not loaded.');
return;
}
var pluginPathDirExists = pluginDirStats.isDirectory();
if (pluginPathDirExists) {

//write config entry back
var diskConfig = fs.readJSONSync(path.resolve(configPath), 'utf8');
diskConfig[pluginName] = false;
fs.outputFileSync(path.resolve(configPath), JSON.stringify(diskConfig, null, 2));

util.logGreen('Plugin ' + pluginName + ' installed.');

//todo, tell them how to uninstall or disable

}
} catch (ex) {
console.log(ex);
}
}

function detectPlugins() {
var node_modules_path = path.join(process.cwd(), 'node_modules');
return fs.readdirSync(node_modules_path).filter(function (dir) {
var module_path = path.join(process.cwd(), 'node_modules', dir);
return fs.statSync(module_path).isDirectory() && dir.indexOf('plugin-node-') === 0;
});
}

function disablePlugin(pluginName) {
console.log('disablePlugin not implemented yet. No change made to state of plugin', pluginName);
}

function enablePlugin(pluginName) {
console.log('enablePlugin not implemented yet. No change made to state of plugin', pluginName);
}

return {
install_plugin: function (pluginName) {
installPlugin(pluginName);
},
load_plugin: function (pluginName) {
return loadPlugin(pluginName);
},
detect_plugins: function () {
return detectPlugins();
},
disable_plugin: function (pluginName) {
disablePlugin(pluginName);
},
enable_plugin: function (pluginName) {
enablePlugin(pluginName);
}
};

};

module.exports = plugin_manager;
2 changes: 2 additions & 0 deletions core/lib/pseudopattern_hunter.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ var pseudopattern_hunter = function () {
extendedTemplate: currentPattern.extendedTemplate,
isPseudoPattern: true,
basePattern: currentPattern,
stylePartials: currentPattern.stylePartials,
parameteredPartials: currentPattern.parameteredPartials,

// use the same template engine as the non-variant
engine: currentPattern.engine
Expand Down
32 changes: 30 additions & 2 deletions core/lib/starterkit_manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

var starterkit_manager = function (config) {
var path = require('path'),
fetch = require('node-fetch'),
fs = require('fs-extra'),
util = require('./utilities'),
paths = config.paths;
Expand Down Expand Up @@ -41,8 +42,35 @@ var starterkit_manager = function (config) {
}
}

/**
* @func listStarterkits
* @desc Fetches starterkit repos from GH API that contain 'starterkit' in their name for the user 'pattern-lab'
* @returns {Promise} Returns an Array<{name,url}> for the starterkit repos
*/
function listStarterkits() {
console.log('https://github.com/search?utf8=%E2%9C%93&q=starterkit+in%3Aname%2C+user%3Apattern-lab&type=Repositories&ref=searchresults');
return fetch('https://api.github.com/search/repositories?q=starterkit+in:name+user:pattern-lab&sort=stars&order=desc', {
method: 'GET',
headers: {
'Accept': 'application/json'
}
}).then(function (res) {
var contentType = res.headers.get('content-type');
if (contentType && contentType.indexOf('application/json') === -1) {
throw new TypeError("StarterkitManager->listStarterkits: Not valid JSON");
}
return res.json();
}).then(function (json) {
if (!json.items || !Array.isArray(json.items)) {
return false;
}
return json.items
.map(function (repo) {
return {name: repo.name, url: repo.html_url};
});
}).catch(function (err) {
console.error(err);
return false;
});
}

function packStarterkit() {
Expand All @@ -63,7 +91,7 @@ var starterkit_manager = function (config) {
loadStarterKit(starterkitName, clean);
},
list_starterkits: function () {
listStarterkits();
return listStarterkits();
},
pack_starterkit: function () {
packStarterkit();
Expand Down
15 changes: 11 additions & 4 deletions core/lib/ui_builder.js
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ var ui_builder = function () {
if (patternlab.config.debug) {
console.log('Omitting ' + pattern.patternPartial + ' from styleguide patterns because it is defined as a defaultPattern.');
}
patternlab.defaultPattern = pattern;
return true;
}

Expand Down Expand Up @@ -245,7 +246,7 @@ var ui_builder = function () {
patternState: pattern.patternState,
patternSrcPath: encodeURI(pattern.subdir + '/' + pattern.fileName),
patternPath: patternPath
}
};
}

/**
Expand Down Expand Up @@ -552,8 +553,8 @@ var ui_builder = function () {
//viewAllPaths
output += 'var viewAllPaths = ' + JSON.stringify(patternlab.viewAllPaths) + ';' + eol;

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

//smaller config elements
output += 'var defaultShowPatternInfo = ' + (patternlab.config.defaultShowPatternInfo ? patternlab.config.defaultShowPatternInfo : 'false') + ';' + eol;
Expand Down Expand Up @@ -611,6 +612,12 @@ var ui_builder = function () {
//build the viewall pages
var allPatterns = buildViewAllPages(headerHTML, patternlab, styleguidePatterns);

//add the defaultPattern if we found one
if (patternlab.defaultPattern) {
allPatterns.push(patternlab.defaultPattern);
addToPatternPaths(patternlab, patternlab.defaultPattern);
}

//build the main styleguide page
var styleguideHtml = pattern_assembler.renderPattern(patternlab.viewAll,
{
Expand Down Expand Up @@ -638,7 +645,7 @@ var ui_builder = function () {

return {
buildFrontend: function (patternlab) {
buildFrontend(patternlab)
buildFrontend(patternlab);
},
isPatternExcluded: function (pattern, patternlab) {
return isPatternExcluded(pattern, patternlab);
Expand Down
Loading

0 comments on commit b048e70

Please sign in to comment.