diff --git a/packages/patternengine-node-twig/.eslintrc b/packages/patternengine-node-twig/.eslintrc index 9f090e1e2..eb695c29c 100644 --- a/packages/patternengine-node-twig/.eslintrc +++ b/packages/patternengine-node-twig/.eslintrc @@ -1,9 +1,6 @@ { "env": { - "jasmine": true, "node": true, - "mocha": true, - "browser": true, "builtin": true }, "globals": {}, diff --git a/packages/patternengine-node-twig/.gitignore b/packages/patternengine-node-twig/.gitignore index 7200b256a..08b9a2f83 100644 --- a/packages/patternengine-node-twig/.gitignore +++ b/packages/patternengine-node-twig/.gitignore @@ -4,6 +4,7 @@ public/index.html public/styleguide.html public/styleguide/html/styleguide.html public/css/* +public/data/* public/fonts/* public/js/* public/images/* diff --git a/packages/patternengine-node-twig/.travis.yml b/packages/patternengine-node-twig/.travis.yml index 611cfd7d6..1a080079e 100644 --- a/packages/patternengine-node-twig/.travis.yml +++ b/packages/patternengine-node-twig/.travis.yml @@ -16,3 +16,4 @@ branches: only: - master - dev + - pattern-engines diff --git a/packages/patternengine-node-twig/CHANGELOG b/packages/patternengine-node-twig/CHANGELOG index 6e29f56f0..c01f4e782 100644 --- a/packages/patternengine-node-twig/CHANGELOG +++ b/packages/patternengine-node-twig/CHANGELOG @@ -1,5 +1,20 @@ THIS CHANGELOG IS AN ATTEMPT TO DOCUMENT CHANGES TO THIS PROJECT. +PL-node-v1.0.0 +- FIX: Resolve issue with not hiding underscored patterns. +- THX: Thanks @ivancamilov for reporting this regression. +- FIX: Fix misapplied error input class +- THX: Thanks @johngerome for the pull request! +- ADD: Added a note in the README during installation to run with elevated privileges +- THX: Thanks @RichardBray for the heads up +- ADD: Added a Prerequisites section to the README +- ADD: Added unit tests for pattern states and pseudopatterns +- CHG: Changed pseudopattern generation to use config.patterns.source directory instead of hardcode +- CHG: Explicitly sorting patterns by name prior to building the UI +- ADD: Added ability to specify link.* urls inside data objects +- CHG: Incremented version to 1.0.0. Achieved near-parity with PL PHP 1! +- THX: Thanks to each and every person who cared about Pattern Lab Node! - Brian + PL-node-v0.15.1 - FIX: Resolve issue with styleModifiers not being replaced when the partial has spaces in it. - ADD: Support multiple styleModifier classes using the | pipe syntax diff --git a/packages/patternengine-node-twig/README.md b/packages/patternengine-node-twig/README.md index c628bf065..b2353e58b 100644 --- a/packages/patternengine-node-twig/README.md +++ b/packages/patternengine-node-twig/README.md @@ -6,12 +6,20 @@ The Node version of [Pattern Lab](http://patternlab.io/) is, at its core, a stat This repository contains the vanilla builder logic, grunt and gulp configurations, and some sample template/css/data to illustrate the power and flexibility of the tool. +### Prerequisites + +Make sure Node and npm are installed. A great guide can be found here: [https://docs.npmjs.com/getting-started/installing-node](https://docs.npmjs.com/getting-started/installing-node) + ### Download * Download the [latest release of patternlab-node](https://github.com/pattern-lab/patternlab-node/releases/latest) from Github * Via npm, run `npm install patternlab-node` (Note this will auto install the grunt version currently. see below) * **NOTE** Node version 4.X and 5.X have tentative support, citing [a lot of Windows issues](https://github.com/nodejs/node-gyp/issues/629), including [mine](https://github.com/pattern-lab/patternlab-node/issues/162). Upgrade node at your own risk until otherwise stated. I've tried to catalog some issues and troubleshooting steps on the [wiki](https://github.com/pattern-lab/patternlab-node/wiki/Windows-Issues). +### Troubleshooting Installs + +Make sure you are running your terminal/command line session as administrator. This could mean `sudo`, or opening the window with a right-click option. + ### Choose Your Adventure! Now Vanilla, Grunt & Gulp This repository ships with two `package.json` files, a `Gruntfile.js`, and a `gulpfile.js`. The default is grunt currently. The core builder is not dependent on either. diff --git a/packages/patternengine-node-twig/builder/lineage_hunter.js b/packages/patternengine-node-twig/builder/lineage_hunter.js index dc13a859c..0ee3bda24 100644 --- a/packages/patternengine-node-twig/builder/lineage_hunter.js +++ b/packages/patternengine-node-twig/builder/lineage_hunter.js @@ -1,5 +1,5 @@ /* - * patternlab-node - v0.15.1 - 2015 + * patternlab-node - v1.0.0 - 2015 * * Brian Muenzenmeyer, and the web community. * Licensed under the MIT license. @@ -20,9 +20,6 @@ var config = require('../config.json'); //find the {{> template-name }} within patterns - if (config.debug) { - console.log('===\n', pattern, '\n==='); - } var matches = pattern.findPartials(); if(matches !== null){ matches.forEach(function(match, index, matches){ diff --git a/packages/patternengine-node-twig/builder/list_item_hunter.js b/packages/patternengine-node-twig/builder/list_item_hunter.js index 75118e2ce..99c2f0e26 100644 --- a/packages/patternengine-node-twig/builder/list_item_hunter.js +++ b/packages/patternengine-node-twig/builder/list_item_hunter.js @@ -1,5 +1,5 @@ /* - * patternlab-node - v0.15.1 - 2015 + * patternlab-node - v1.0.0 - 2015 * * Brian Muenzenmeyer, and the web community. * Licensed under the MIT license. diff --git a/packages/patternengine-node-twig/builder/media_hunter.js b/packages/patternengine-node-twig/builder/media_hunter.js index d5ada91ce..e7eb70a15 100644 --- a/packages/patternengine-node-twig/builder/media_hunter.js +++ b/packages/patternengine-node-twig/builder/media_hunter.js @@ -1,5 +1,5 @@ /* - * patternlab-node - v0.15.1 - 2015 + * patternlab-node - v1.0.0 - 2015 * * Brian Muenzenmeyer, and the web community. * Licensed under the MIT license. diff --git a/packages/patternengine-node-twig/builder/object_factory.js b/packages/patternengine-node-twig/builder/object_factory.js index 6a9f646e4..d929db6e9 100644 --- a/packages/patternengine-node-twig/builder/object_factory.js +++ b/packages/patternengine-node-twig/builder/object_factory.js @@ -1,6 +1,6 @@ -/* - * patternlab-node - v0.15.1 - 2015 - * +/* + * patternlab-node - v1.0.0 - 2015 + * * Brian Muenzenmeyer, and the web community. * Licensed under the MIT license. * @@ -20,9 +20,6 @@ // oPattern properties var oPattern = function(abspath, subdir, filename, data) { - if (config.debug) { - console.log('=== NEW OPATTERN.', '\nabsPath:', abspath, '\nsubdir:', subdir, '\nfilename:', filename, '\ndata:\n', data); - } this.fileName = filename.substring(0, filename.indexOf('.')); this.fileExtension = path.extname(abspath); this.abspath = abspath; @@ -61,6 +58,12 @@ return this.engine.renderPattern(this.extendedTemplate, data, partials); }, + registerPartial: function () { + if (typeof this.engine.registerPartial === 'function') { + this.engine.registerPartial(this); + } + }, + // the finders all delegate to the PatternEngine, which also encapsulates all // appropriate regexes findPartials: function () { diff --git a/packages/patternengine-node-twig/builder/parameter_hunter.js b/packages/patternengine-node-twig/builder/parameter_hunter.js index fe2d61ea7..bf108ae62 100644 --- a/packages/patternengine-node-twig/builder/parameter_hunter.js +++ b/packages/patternengine-node-twig/builder/parameter_hunter.js @@ -1,10 +1,10 @@ -/* - * patternlab-node - v0.15.1 - 2015 - * +/* + * patternlab-node - v1.0.0 - 2015 + * * Brian Muenzenmeyer, and the web community. - * Licensed under the MIT license. - * - * Many thanks to Brad Frost and Dave Olsen for inspiration, encouragement, and advice. + * Licensed under the MIT license. + * + * Many thanks to Brad Frost and Dave Olsen for inspiration, encouragement, and advice. * */ diff --git a/packages/patternengine-node-twig/builder/pattern_assembler.js b/packages/patternengine-node-twig/builder/pattern_assembler.js index 52f975f9b..9b9074b03 100644 --- a/packages/patternengine-node-twig/builder/pattern_assembler.js +++ b/packages/patternengine-node-twig/builder/pattern_assembler.js @@ -1,5 +1,5 @@ /* - * patternlab-node - v0.15.1 - 2015 + * patternlab-node - v1.0.0 - 2015 * * Brian Muenzenmeyer, and the web community. * Licensed under the MIT license. @@ -12,15 +12,16 @@ "use strict"; var pattern_assembler = function(){ - - var fs = require('fs-extra'), + var path = require('path'), + fs = require('fs-extra'), of = require('./object_factory'), plutils = require('./utilities'), - patternEngines = require('./pattern_engines/pattern_engines'), - config = fs.readJSONSync('./config.json'); + patternEngines = require('./pattern_engines/pattern_engines'); + + var config = fs.readJSONSync('./config.json'); function setState(pattern, patternlab){ - if(patternlab.config.patternStates[pattern.patternName]){ + if(patternlab.config.patternStates && patternlab.config.patternStates[pattern.patternName]){ pattern.patternState = patternlab.config.patternStates[pattern.patternName]; } else{ pattern.patternState = ""; @@ -28,6 +29,7 @@ } function addPattern(pattern, patternlab){ + //add the link to the global object patternlab.data.link[pattern.patternGroup + '-' + pattern.patternName] = '/patterns/' + pattern.patternLink; //only push to array if the array doesn't contain this pattern @@ -43,7 +45,10 @@ } //if the pattern is new, just push to the array if(isNew){ + // do global registration patternlab.patterns.push(pattern); + // do plugin-specific registration + pattern.registerPartial(); } } @@ -66,44 +71,29 @@ } function processPatternIterative(file, patternlab){ - var fs = require('fs-extra'), - of = require('./object_factory'), - path = require('path'); - //extract some information var subdir = path.dirname(path.relative(patternlab.config.patterns.source, file)).replace('\\', '/'); var filename = path.basename(file); var ext = path.extname(filename); if (config.debug) { - console.log('processPatternIterative:', 'filename:', filename); + console.log('processPatternIterative:', filename); } // skip non-pattern files - if (!patternEngines.isPatternFile(filename, patternlab)) { return; } - if (config.debug) { - console.log('processPatternIterative:', 'found pattern', file); - } + if (!patternEngines.isPatternFile(filename, patternlab)) { return null; } //make a new Pattern Object var currentPattern = new of.oPattern(file, subdir, filename); //if file is named in the syntax for variants if(patternEngines.isPseudoPatternJSON(filename)){ - //add current pattern to patternlab object with minimal data - //processPatternRecursive() will run find_pseudopatterns() to fill out - //the object in the next diveSync - addPattern(currentPattern, patternlab); - //no need to process further - return; + return currentPattern; } - //can ignore all non-mustache files at this point - if(ext !== '.mustache'){ - if (config.debug) { - console.log('==================== FOUND NON-MUSTACHE FILE'); - } - return; + //can ignore all non-supported files at this point + if(patternEngines.isFileExtensionSupported(ext) === false){ + return currentPattern; } //see if this file has a state @@ -114,7 +104,7 @@ var jsonFilename = patternlab.config.patterns.source + currentPattern.subdir + '/' + currentPattern.fileName + ".json"; currentPattern.jsonFileData = fs.readJSONSync(jsonFilename.substring(2)); if(patternlab.config.debug){ - console.log('found pattern-specific data.json for ' + currentPattern.key); + console.log('processPatternIterative: found pattern-specific data.json for ' + currentPattern.key); } } catch(e) { @@ -143,6 +133,8 @@ //add currentPattern to patternlab.patterns array addPattern(currentPattern, patternlab); + + return currentPattern; } @@ -277,6 +269,36 @@ + //look for pattern links included in data files. + //these will be in the form of link.* WITHOUT {{}}, which would still be there from direct pattern inclusion + function parseDataLinks(patternlab){ + + //loop through all patterns + for (var i = 0; i < patternlab.patterns.length; i++){ + var pattern = patternlab.patterns[i]; + //look for link.* such as link.pages-blog as a value + var linkRE = /link.[A-z0-9-_]+/g; + //convert to string for easier searching + var dataObjAsString = JSON.stringify(pattern.jsonFileData); + var linkMatches = dataObjAsString.match(linkRE); + + //if no matches found, escape current loop iteration + if(linkMatches === null) { continue; } + + for(var i = 0; i < linkMatches.length; i++){ + //for each match, find the expanded link within the already constructed patternlab.data.link object + var expandedLink = patternlab.data.link[linkMatches[i].split('.')[1]]; + if(patternlab.config.debug){ + console.log('expanded data link from ' + linkMatches[i] + ' to ' + expandedLink + ' inside ' + pattern.key); + } + //replace value with expandedLink on the pattern + dataObjAsString = dataObjAsString.replace(linkMatches[i], expandedLink); + } + //write back to data on the pattern + pattern.jsonFileData = JSON.parse(dataObjAsString); + } + } + return { find_pattern_partials: function(pattern){ return pattern.findPartials(); @@ -300,7 +322,7 @@ return renderPattern(template, data, partials); }, process_pattern_iterative: function(file, patternlab){ - processPatternIterative(file, patternlab); + return processPatternIterative(file, patternlab); }, process_pattern_recursive: function(file, patternlab, additionalData){ processPatternRecursive(file, patternlab, additionalData); @@ -310,6 +332,9 @@ }, combine_listItems: function(patternlab){ buildListItems(patternlab); + }, + parse_data_links: function(patternlab){ + parseDataLinks(patternlab); } }; diff --git a/packages/patternengine-node-twig/builder/pattern_engines/engine_handlebars.js b/packages/patternengine-node-twig/builder/pattern_engines/engine_handlebars.js new file mode 100644 index 000000000..9cdd83b13 --- /dev/null +++ b/packages/patternengine-node-twig/builder/pattern_engines/engine_handlebars.js @@ -0,0 +1,70 @@ +/* + * handlebars pattern engine for patternlab-node - v0.15.1 - 2015 + * + * Geoffrey Pursell, Brian Muenzenmeyer, and the web community. + * Licensed under the MIT license. + * + * Many thanks to Brad Frost and Dave Olsen for inspiration, encouragement, and advice. + * + */ + +(function () { + "use strict"; + + var Handlebars = require('handlebars'); + + var engine_handlebars = { + engine: Handlebars, + engineName: 'handlebars', + engineFileExtension: '.hbs', + + // regexes, stored here so they're only compiled once + // GTP warning: unchanged copypasta from mustache engine + // findPartialsRE: /{{>\s*((?:\d+-[\w-]+\/)+(\d+-[\w-]+(\.\w+)?)|[A-Za-z0-9-]+)(\:[\w-]+)?(\(\s*\w+\s*:\s*(?:'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")\))?\s*}}/g, + findPartialsRE: /{{#?>\s*([\w-\/.]+)(?:.|\s+)*?}}/g, + findPartialsWithStyleModifiersRE: /{{>([ ])?([\w\-\.\/~]+)(?!\()(\:[A-Za-z0-9-_|]+)+(?:(| )\(.*)?([ ])?}}/g, + findPartialsWithPatternParametersRE: /{{>([ ])?([\w\-\.\/~]+)(?:\:[A-Za-z0-9-_|]+)?(?:(| )\(.*)+([ ])?}}/g, + findListItemsRE: /({{#( )?)(list(I|i)tems.)(one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty)( )?}}/g, + + // render it + renderPattern: function renderPattern(template, data, partials) { + if (partials) { + Handlebars.registerPartial(partials); + } + var compiled = Handlebars.compile(template); + return compiled(data); + }, + + registerPartial: function (oPattern) { + Handlebars.registerPartial(oPattern.key, oPattern.template); + }, + + // find and return any {{> template-name }} within pattern + findPartials: function findPartials(pattern) { + var matches = pattern.template.match(this.findPartialsRE); + return matches; + }, + findPartialsWithStyleModifiers: function(pattern) { + var matches = pattern.template.match(this.findPartialsWithStyleModifiersRE); + return matches; + }, + // returns any patterns that match {{> value(foo:"bar") }} or {{> + // value:mod(foo:"bar") }} within the pattern + findPartialsWithPatternParameters: function(pattern) { + var matches = pattern.template.match(this.findPartialsWithPatternParametersRE); + return matches; + }, + findListItems: function(pattern) { + var matches = pattern.template.match(this.findListItemsRE); + return matches; + }, + // given a pattern, and a partial string, tease out the "pattern key" and + // return it. + getPartialKey: function(pattern, partialString) { + var partialKey = partialString.replace(this.findPartialsRE, '$1'); + return partialKey; + } + }; + + module.exports = engine_handlebars; +})(); diff --git a/packages/patternengine-node-twig/builder/pattern_engines/pattern_engines.js b/packages/patternengine-node-twig/builder/pattern_engines/pattern_engines.js index 13ef654f0..2968de9a8 100644 --- a/packages/patternengine-node-twig/builder/pattern_engines/pattern_engines.js +++ b/packages/patternengine-node-twig/builder/pattern_engines/pattern_engines.js @@ -13,25 +13,97 @@ 'use strict'; var path = require('path'); + var diveSync = require('diveSync'); + var engineMatcher = /^engine_(.*)\.js/; + var enginesDirectory = __dirname; - // list of supported pattern engines - var supportedPatternEngineNames = [ - 'mustache', - 'handlebars' - ]; + var PatternEngines; // the main export object + var engineNameForExtension; // generated mapping of extension to engine name - // mapping of file extensions to engine names, for lookup use - var engineNameForExtension = {}; - // Object/hash of all loaded pattern engines, empty at first. - // My intention here is to make this return an object that can be used to - // obtain any loaded PatternEngine by addressing them like this: + // free "private" functions, for internal setup only + + function findSupportedPatternEngineNames() { + var foundPatternEngineNames = []; + + // find + diveSync(enginesDirectory, { + recursive: false, + filter: function (filePath, dir) { + var baseName = path.basename(filePath), + engineMatch = baseName.match(engineMatcher); + + if (dir || engineMatch !== null) { return true; } + return false; + } + }, function (err, filePath) { + if (err) { throw err; } + var baseName = path.basename(filePath), + engineMatch = baseName.match(engineMatcher), + foundEngineName = engineMatch[1]; + + foundPatternEngineNames.push(foundEngineName); + }); + + return foundPatternEngineNames; + } + + // try to load all supported engines + function loadAllEngines(enginesObject) { + console.log('\nLoading engines...'); + + enginesObject.supportedPatternEngineNames.forEach(function (engineName) { + var notLoaded = false; + + try { + enginesObject[engineName] = require('./engine_' + engineName); + } catch (err) { + // Handle errors loading each pattern engine. This will usually be + // because the engine's renderer hasn't been installed by the end user + // -- we don't include any of them (except mustache) by default as + // depedencies in package.json. + notLoaded = (err.code === 'MODULE_NOT_FOUND'); + } finally { + console.log('-', engineName, 'engine:', + notLoaded ? 'renderer not installed; engine disabled' : 'good to go'); + } + }); + console.log('...done loading engines.\n'); + } + + // produce a mapping between file extension and engine name for each of the + // loaded engines + function createFileExtensionToEngineNameMap(enginesObject) { + var mapping = {}; + + Object.keys(enginesObject).forEach(function (engineName) { + var extensionForEngine = enginesObject[engineName].engineFileExtension; + mapping[extensionForEngine] = engineName; + }); + + return mapping; + } + + + // + // PatternEngines: the main export of this module // - // var PatternEngines = require('./pattern_engines/pattern_engines'); - // var Mustache = PatternEngines['mustache']; + // It's an Object/hash of all loaded pattern engines, empty at first. My + // intention here is to make this return an object that can be used to obtain + // any loaded PatternEngine by addressing them like this: // - var PatternEngines = Object.create({ - supportedPatternEngineNames: supportedPatternEngineNames, + // var PatternEngines = require('./pattern_engines/pattern_engines'); + // var Mustache = PatternEngines['mustache']; + // + // Object.create lets us create an object with a specified prototype. We want + // this here because we would like the object's "own properties" to include + // only the engine names so we can easily iterate over them; all the handy + // methods and properites below should therefore be on its prototype. + + PatternEngines = Object.create({ + // build the list of supported pattern engines based on what plugins we have + // in the pattern_engines directory + supportedPatternEngineNames: findSupportedPatternEngineNames(), getEngineNameForPattern: function (pattern) { // avoid circular dependency by putting this in here. TODO: is this slow? @@ -93,30 +165,12 @@ } }); - // try to load all supported engines - (function loadAllEngines() { - supportedPatternEngineNames.forEach(function (engineName) { - try { - PatternEngines[engineName] = require('./engine_' + engineName); - } catch (err) { - console.log(err, 'pattern engine "' + engineName + '" not loaded. Did you install its dependency with npm?'); - } - }); - })(); - - // produce a mapping between file extension and engine name for each of the - // loaded engines - engineNameForExtension = (function () { - var mapping = {}; - Object.keys(PatternEngines).forEach(function (engineName) { - var extensionForEngine = PatternEngines[engineName].engineFileExtension; - mapping[extensionForEngine] = engineName; - }); - - return mapping; - })(); + // load up the engines we found + loadAllEngines(PatternEngines); + // mapping of file extensions to engine names, for lookup use + engineNameForExtension = createFileExtensionToEngineNameMap(PatternEngines); module.exports = PatternEngines; })(); diff --git a/packages/patternengine-node-twig/builder/pattern_exporter.js b/packages/patternengine-node-twig/builder/pattern_exporter.js index 90915ec86..ddbf74023 100644 --- a/packages/patternengine-node-twig/builder/pattern_exporter.js +++ b/packages/patternengine-node-twig/builder/pattern_exporter.js @@ -1,5 +1,5 @@ /* - * patternlab-node - v0.15.1 - 2015 + * patternlab-node - v1.0.0 - 2015 * * Brian Muenzenmeyer, and the web community. * Licensed under the MIT license. diff --git a/packages/patternengine-node-twig/builder/patternlab.js b/packages/patternengine-node-twig/builder/patternlab.js index 2d9f5f940..646ed146d 100644 --- a/packages/patternengine-node-twig/builder/patternlab.js +++ b/packages/patternengine-node-twig/builder/patternlab.js @@ -1,6 +1,6 @@ -/* - * patternlab-node - v0.15.1 - 2015 - * +/* + * patternlab-node - v1.0.0 - 2015 + * * Brian Muenzenmeyer, and the web community. * Licensed under the MIT license. * @@ -19,6 +19,7 @@ var patternlab_engine = function () { mh = require('./media_hunter'), pe = require('./pattern_exporter'), he = require('html-entities').AllHtmlEntities, + util = require('util'), plutils = require('./utilities'), patternlab = {}; @@ -46,10 +47,21 @@ var patternlab_engine = function () { } function printDebug() { + // A replacer function to pass to stringify below; this is here to prevent + // the debug output from blowing up into a massive fireball of circular + // references. This happens specifically with the Handlebars engine. Remove + // if you like 180MB log files. + function propertyStringReplacer(key, value) { + if (key === 'engine' && value.engineName) { + return '{' + value.engineName + ' engine object}'; + } + return value; + } + //debug file can be written by setting flag on config.json if(patternlab.config.debug){ console.log('writing patternlab debug file to ./patternlab.json'); - fs.outputFileSync('./patternlab.json', JSON.stringify(patternlab, null, 3)); + fs.outputFileSync('./patternlab.json', JSON.stringify(patternlab, propertyStringReplacer, 3)); } } @@ -90,6 +102,10 @@ var patternlab_engine = function () { pattern_assembler.process_pattern_iterative(file.substring(2), patternlab); }); + //now that all the main patterns are known, look for any links that might be within data and expand them + //we need to do this before expanding patterns & partials into extendedTemplates, otherwise we could lose the data -> partial reference + pattern_assembler.parse_data_links(patternlab); + //diveSync again to recursively include partials, filling out the //extendedTemplate property of the patternlab.patterns elements diveSync(patterns_dir, { @@ -110,7 +126,8 @@ var patternlab_engine = function () { } pattern_assembler.process_pattern_recursive(file.substring(2), patternlab); - }); + }); + //delete the contents of config.patterns.public before writing if(deletePatternDir){ @@ -123,6 +140,7 @@ var patternlab_engine = function () { var allData = JSON.parse(JSON.stringify(patternlab.data)); allData = plutils.mergeData(allData, pattern.jsonFileData); + //render the extendedTemplate with all data pattern.patternPartial = pattern_assembler.renderPattern(pattern, allData); //add footer info before writing @@ -140,7 +158,6 @@ var patternlab_engine = function () { //export patterns if necessary pattern_exporter.export_patterns(patternlab); - } function buildFrontEnd(){ @@ -210,6 +227,18 @@ var patternlab_engine = function () { //build the patternlab website var patternlabSiteTemplate = fs.readFileSync('./source/_patternlab-files/index.mustache', 'utf8'); + //sort all patterns explicitly. + patternlab.patterns = patternlab.patterns.sort(function(a,b){ + if (a.name > b.name) { + return 1; + } + if (a.name < b.name) { + return -1; + } + // a must be equal to b + return 0; + }); + //loop through all patterns.to build the navigation //todo: refactor this someday for(var i = 0; i < patternlab.patterns.length; i++){ diff --git a/packages/patternengine-node-twig/builder/patternlab_grunt.js b/packages/patternengine-node-twig/builder/patternlab_grunt.js index 843dd07f1..f56e58074 100644 --- a/packages/patternengine-node-twig/builder/patternlab_grunt.js +++ b/packages/patternengine-node-twig/builder/patternlab_grunt.js @@ -1,5 +1,5 @@ /* - * patternlab-node - v0.15.1 - 2015 + * patternlab-node - v1.0.0 - 2015 * * Brian Muenzenmeyer, and the web community. * Licensed under the MIT license. diff --git a/packages/patternengine-node-twig/builder/patternlab_gulp.js b/packages/patternengine-node-twig/builder/patternlab_gulp.js index d4014cb79..e20e1e1a7 100644 --- a/packages/patternengine-node-twig/builder/patternlab_gulp.js +++ b/packages/patternengine-node-twig/builder/patternlab_gulp.js @@ -1,5 +1,5 @@ /* - * patternlab-node - v0.15.1 - 2015 + * patternlab-node - v1.0.0 - 2015 * * Brian Muenzenmeyer, and the web community. * Licensed under the MIT license. diff --git a/packages/patternengine-node-twig/builder/pseudopattern_hunter.js b/packages/patternengine-node-twig/builder/pseudopattern_hunter.js index 937dffa4f..070fd296f 100644 --- a/packages/patternengine-node-twig/builder/pseudopattern_hunter.js +++ b/packages/patternengine-node-twig/builder/pseudopattern_hunter.js @@ -1,5 +1,5 @@ /* - * patternlab-node - v0.15.1 - 2015 + * patternlab-node - v1.0.0 - 2015 * * Brian Muenzenmeyer, and the web community. * Licensed under the MIT license. @@ -29,7 +29,7 @@ //name, with ~ in it, ending in .json var needle = currentPattern.subdir + '/' + currentPattern.fileName + '~*.json'; var pseudoPatterns = glob.sync(needle, { - cwd: 'source/_patterns/', //relative to gruntfile + cwd: patternlab.config.patterns.source + '/', debug: false, nodir: true }); @@ -43,14 +43,14 @@ console.log('found pseudoPattern variant of ' + currentPattern.key); } - //we want to do everything we normally would here, except instead head the pseudoPattern data - var variantFileData = fs.readJSONSync('source/_patterns/' + pseudoPatterns[i]); + //we want to do everything we normally would here, except instead read the pseudoPattern data + var variantFileData = fs.readJSONSync(patternlab.config.patterns.source + '/' + pseudoPatterns[i]); //extend any existing data with variant data variantFileData = plutils.mergeData(currentPattern.jsonFileData, variantFileData); var variantName = pseudoPatterns[i].substring(pseudoPatterns[i].indexOf('~') + 1).split('.')[0]; - var variantFilePath = 'source/_patterns/' + currentPattern.subdir + '/' + currentPattern.fileName + '~' + variantName + '.json'; + var variantFilePath = patternlab.config.patterns.source + '/' + currentPattern.subdir + '/' + currentPattern.fileName + '~' + variantName + '.json'; var variantFileName = currentPattern.fileName + '-' + variantName + '.'; var patternVariant = of.oPattern.create(variantFilePath, currentPattern.subdir, variantFileName, variantFileData, { //use the same template as the non-variant diff --git a/packages/patternengine-node-twig/builder/style_modifier_hunter.js b/packages/patternengine-node-twig/builder/style_modifier_hunter.js index 9baa6f0aa..8a42889bd 100644 --- a/packages/patternengine-node-twig/builder/style_modifier_hunter.js +++ b/packages/patternengine-node-twig/builder/style_modifier_hunter.js @@ -1,10 +1,10 @@ -/* - * patternlab-node - v0.15.1 - 2015 - * +/* + * patternlab-node - v1.0.0 - 2015 + * * Brian Muenzenmeyer, and the web community. - * Licensed under the MIT license. - * - * Many thanks to Brad Frost and Dave Olsen for inspiration, encouragement, and advice. + * Licensed under the MIT license. + * + * Many thanks to Brad Frost and Dave Olsen for inspiration, encouragement, and advice. * */ diff --git a/packages/patternengine-node-twig/package.gulp.json b/packages/patternengine-node-twig/package.gulp.json index 099c8d907..dbece6e4b 100644 --- a/packages/patternengine-node-twig/package.gulp.json +++ b/packages/patternengine-node-twig/package.gulp.json @@ -1,7 +1,7 @@ { "name": "patternlab-node", "description": "Pattern Lab is a collection of tools to help you create atomic design systems. This is the node command line interface (CLI).", - "version": "0.15.1", + "version": "1.0.0", "devDependencies": { "browser-sync": "^2.10.0", "del": "^2.0.2", diff --git a/packages/patternengine-node-twig/package.json b/packages/patternengine-node-twig/package.json index 8d3953d22..e95ad0f2c 100644 --- a/packages/patternengine-node-twig/package.json +++ b/packages/patternengine-node-twig/package.json @@ -1,7 +1,7 @@ { "name": "patternlab-node", "description": "Pattern Lab is a collection of tools to help you create atomic design systems. This is the node command line interface (CLI).", - "version": "0.15.1", + "version": "1.0.0", "devDependencies": { "bs-html-injector": "^3.0.0", "diveSync": "^0.3.0", @@ -13,6 +13,7 @@ "grunt-contrib-copy": "^0.8.2", "grunt-contrib-nodeunit": "^0.4.1", "grunt-contrib-watch": "^0.6.1", + "handlebars": "^4.0.5", "html-entities": "^1.2.0", "matchdep": "^1.0.0", "mustache": "^2.2.0" diff --git a/packages/patternengine-node-twig/public/data/annotations.js b/packages/patternengine-node-twig/public/data/annotations.js deleted file mode 100644 index fc8209531..000000000 --- a/packages/patternengine-node-twig/public/data/annotations.js +++ /dev/null @@ -1,109 +0,0 @@ -var comments = { -"comments" : [ - { - "el": "header[role=banner]", - "title" : "Masthead", - "comment": "The main header of the site doesn't take up too much screen real estate in order to keep the focus on the core content. It's using a linear CSS gradient instead of a background image to give greater design flexibility and reduce HTTP requests." - }, - { - "el": ".logo", - "title" : "Logo", - "comment": "The logo image is an SVG file, which ensures that the logo displays crisply even on high resolution displays. A PNG fallback is provided for browsers that don't support SVG images.</p><p>Further reading: <a href=\"http://bradfrostweb.com/blog/mobile/hi-res-optimization/\">Optimizing Web Experiences for High Resolution Screens</a></p>" - }, - { - "el": "#nav", - "title" : "Navigation", - "comment": "<p>Navigation for adaptive web experiences can be tricky. Top navigations are typical on desktop sites, but mobile screen sizes don't give us the luxury of space. We're dealing with this situation by creating a simple menu anchor that toggles the main navigation on small screens. This is just one method. <a href=\"http://bagcheck.com/\">Bagcheck</a> and <a href=\"http://contentsmagazine.com/\">Contents Magazine</a> add an anchor in the header that jumps users to the navigation which is placed in the footer. This solution works well because it doesn't require any Javascript in order to work. Other methods exist too. For example, <a href=\"http://m.espn.com\">ESPN's mobile navigation</a> overlays the main content of the page.</p><p>The nav is only hidden when a certain level of javascript is supported in order to ensure that users with little/poor javascript support can still access the navigation. Once the screen size is large enough to accommodate the nav, we show the main navigation links and hide the menu anchor.<p><p>See also: <a href=\"http://bradfrostweb.com/blog/web/responsive-nav-patterns/\">Responsive Navigation Patterns</a></p>" - }, - { - "el": "input[type=search]", - "title" : "Search", - "comment": "<p>Search is an incredibly important priority, especially for mobile. It is a great idea to give users the ability to jump directly to what they are looking for without forcing them to wade through your site's navigation. Check out the <a href=\"http://burton.com\">Burton</a> and <a href=\"http://yelp.com\">Yelp</a> mobile sites for great examples of experiences that prioritize search.</p><p>We're also using the <a href=\"http://dev.w3.org/html5/markup/input.search.html\">HTML5 search input type</a>, which is great for mobile devices that can <a href=\"http://diveintohtml5.info/forms.html\">bring up the appropriate virtual keyboard</a> for many smartphones. And like the main header navigation, we're hiding the search form on small screens to save space. Clicking the search anchor toggles the form. </p>" - }, - { - "el": "#product-img nav", - "title" : "Image Navigation", - "comment": "<p>Instead of providing bullets, pagination or text-based image navigation, it's good e-commerce practice to show a preview of the various product views. By default the images simply link through to their larger counterparts, and if adequate javascript support exists, the images get loaded into the main image container.</p>" - }, - { - "el": "#img-container", - "title" : "Product Image", - "comment": "<p>The product image is the focal point of the page for good reason. It's typically what the user is there to see. The default markup simply includes the main product image, but that gets replaced with an image gallery if adequate javascript support exists.</p><p>We're also using <a href=\"http://www.modernizr.com/\">Modernizr</a> to detect if the browser supports <a href=\"https://developer.mozilla.org/en/DOM/Touch_events\">touch events</a> and if it does, we load in an excellent lightweight script called <a href=\"http://swipejs.com/\">Swipe.js</a> to create a touch-friendly image carousel. This allows users to swipe between product photos in a touch-friendly way. Because gestures are invisible, they might get overlooked, but clicking on the image navigation thumbnails animates the slideshow and hints to the user gestural interaction is available.</p>" - }, - { - "el": ".product-main header", - "title" : "Product Overview", - "comment": "The product overview appears in the markup before the image container in order to provide the user with the product name, how much it costs and how popular it is. Providing this information as soon as possible can help the user determine whether or not this is the product they're looking for without having to wait for the rest of the page to load." - }, - { - "el": ".star", - "title" : "Rating Stars", - "comment": "<p>We're using HTML special characters to display the product rating stars. We're using HTML characters instead of images to reduce the amount of images we're requesting and also maintaining crispness on high resolution screens. Not every device supports HTML special characters (Blackberry <=5.0 for example), but support is strong enough and the benefits are many.</p><p>See also: <a href=\"http://bradfrostweb.com/blog/mobile/hi-res-optimization/\">Optimizing Web Experiences for High Resolution Screens</a></p>" - }, - { - "el": ".review-count", - "title" : "Review Count", - "comment": "This is a simple anchor link that points to the review section of the page. This may seem like a small detail, but consider a mobile use case. Users can be in stores looking at the physical product, and <a href=\"http://googlemobileads.blogspot.com/2011/04/smartphone-user-study-shows-mobile.html\">79% of smartphone consumers use their phones to help with shopping</a>. They might be interested in buying in-store but turn to their phones to verify its popularity and quality. Making it easy for uses to read product reviews on small screens can help drive more sales, both online and offline.</p><p>While not incorporated yet, it would be easy to load the reviews for small screens on demand, thereby saving a step.</p>" - }, - { - "el": ".qty-field", - "title" : "Quantity Field", - "comment": "We're using the HTML5 number input type, which <a href=\"http://diveintohtml5.info/forms.html\">brings up the appropriate virtual keyboard</a> for many mobile browsers. To increase usability, the input labels are using the \"for\" attribute, which focuses the cursor in the form field when clicked. However, iOS doesn't honor \"for\" default functionality, so we're adding \"cursor: pointer\" to the labels to get Mobile Safari to behave properly." - }, - { - "el": ".size-field", - "title" : "Size Dropdown", - "comment": "We're using a basic select menu to choose the size, which is commonplace for any e-commerce site. Select menus can be especially difficult to style and can vary greatly in behavior between platforms. Keep this in mind when creating " - }, - { - "el": ".submit-form", - "title" : "Add to Cart button", - "comment": "The add to cart button is the primary user action on the page. That's why it's large and in charge and very prominently placed on the page. The button is using box-shadows and rounded corners to create an attractive button that will hopefully get plenty of clicks." - }, - { - "el": ".share-btn", - "title" : "Share button", - "comment": "It seems like everything has a share button on it these days. And for good reason. Sharing content and products on social networks can be a great way to increase exposure. However, tacking on tons of social widgets adds a lot of overhead, which can be extremely <a href=\"http://www.strangeloopnetworks.com/web-performance-optimization-hub/topics/third-party-content/\">detrimental to the site's performance</a>. Including a simple share link that loads the heavy widgets only when requested is one way to keep pages fast and social. Check out <a href=\"http://target.com\">Target's mobile site</a> for an example of a site that isolates share functionality in a separate page fragment." - }, - { - "el": ".find-nearby", - "title" : "Geolocation", - "comment": "One of the most important aspects of the mobile context is location. We carry our mobile devices with us everywhere. Using <a href=\"http://dev.w3.org/geo/api/spec-source.html\">geolocation</a> we can tap into the user's location to deliver an enhanced experience. In this case we're giving them a chance to check out what stores nearby might sell this product. The geolocation API is well supported in mobile browsers as well as desktop browsers. We're using <a href=\"http://modernizr.com\">Modernizr</a> to detect for geolocation support and if its support, we ask the user for their latitude and longitude. If the browser does not support geolocation, the default experience could take the user to a simple web form asking for a ZIP code. Check out <a href=\"http://m.tiffany.com\">Tiffany's mobile site</a> store locator for an example of geolocation in action." - }, - { - "el": "#p-desc", - "title" : "Product Description", - "comment": "A product description is an essential part of any e-commerce experience. Descriptions offer tangible details that inform and persuade, and the tone can help support the physical product. Provide relevant information clearly and concisely. Check out the <a href=\"http://developer.android.com/design/style/writing.html\">Android design guide</a> for some tips on how to keep copy short and extremely effective." - }, - { - "el": "#related-products", - "title" : "Related Products", - "comment": "<p>Related products are obviously an important aspect of e-commerce sites as they drive awareness of other similar products and can lead to more purchases. However, including a lot of auxiliary content can bog down the site performance, which is especially crucial on mobile. On slow connections, the presence of this extra content might slow down the user experience enough that the user gives up.</p><p>We're handling the issue by <a href=\"http://24ways.org/2011/conditional-loading-for-responsive-designs\">conditionally loading</a> the auxiliary content.</p><p>By default, the related item link simply clicks through to an HTML fragment containing the related products. The content is still accessible, even on devices with poor or no javascript support. When the user clicks on the related products on small screens, the content gets dynamically loaded inline and the link becomes a toggler for the content. Once the experience reaches a certain width breakpoint, we then load in the content. However, screen size != fast connection, so we should keep our eyes on the emerging <a href=\"http://davidbcalhoun.com/2010/using-navigator-connection-android\">navigator.connection</a> to better gauge real connection speed.</p><p>See also: <a href=\"http://filamentgroup.com/lab/ajax_includes_modular_content/\">An Ajax-Include Pattern for Modular Content</a></p><p>All these wonderful t-shirts are retired/rejected <a href=\"http://bustedtees.com\">Busted Tees</a>, graciously donated to this demo by <a href=\"http://www.willschneidblog.com/\">Will Schneider</a>.</p>" - }, - { - "el": "#reviews", - "title" : "Reviews", - "comment": "Reviews are incredibly influential on a user's decision to purchase a product or pass on it. Also, because we carry our mobile phones with us everywhere, we use them to inform our in-store purchased. <a href=\"http://googlemobileads.blogspot.com/2011/04/smartphone-user-study-shows-mobile.html\">70% of smartphone owners use them while in brick and mortar stores</a>, and often times they're looking for reviews to give them the green light to buy.</p><p>Only the primary product content gets loaded by default, and the reviews exist as their own separate HTML fragment. The reviews remain accessible and don't get loaded until we <a href=\"http://24ways.org/2011/conditional-loading-for-responsive-designs\">conditionally load</a> them when the screen is large enough or small screen users click the reviews link. This keeps things nimble while still providing access to the valuable reviews.</p><p>See also: <a href=\"http://filamentgroup.com/lab/ajax_includes_modular_content/\">An Ajax-Include Pattern for Modular Content</a></p>" - }, - { - "el": "#p-reviews .btn", - "title" : "More Reviews Button", - "comment": "<p>All reviews aren't loaded by default in order to keep the site performance in top shape. Ultimately, this button could be replaced with a <a href=\"http://www.infinite-scroll.com/\">lazy-loading</a> solution to remove the need for the button.</p>" - }, - { - "el": ".footer .nav", - "title" : "Footer Nav", - "comment": "<p>Repetition of elements isn't a bad thing, especially with potentially long scrolling pages on mobile. Providing access to the main site navigation is a good way for the user to jump off to another section and avoids leaving them with a dead end. Also, some mobile sites like <a href=\"http://bagcheck.com/\">Bagcheck</a> and <a href=\"http://contentsmagazine.com/\">Contents Magazine</a> keep the primary navigation at the footer and simply link to it with an anchor in the header. That way the nav stays accessible but the focus stays on on the core page content.</p>" - }, - { - "el": ".tel", - "title" : "Customer Service Number", - "comment": "<p>We sometimes forget that <a href=\"http://bradfrostweb.com/blog/mobile/a-tel-tale-sign/\">mobile phones can make phone calls</a>. Whether a user is having trouble with the site or simply has some questions about the product he's about to buy, it's a smart decision to provide a clickable phone number to facilitate that call. What happens when desktops and other non-phone devices click on the <a href=\"http://www.mobilexweb.com/blog/click-to-call-links-mobile-browsers\">tel link</a>? Well, some devices (like iPads and other tablets) ask the user if they'd like to add the number to their contact list, other desktops open 3rd party VoIP programs like Skype, and others simply give an error message.</p>" - }, - { - "el": ".top", - "title" : "Back to Top Link", - "comment": "<p>Back to top links are simple yet underrated. They provide users with an easy way back up to the top of the page with minimum effort. This is especially helpful on mobile devices, which tend to have long scrolling pages.</p><p>We're using an HTML character for the back to top arrow in order to reduce image elements and keep things looking crisp on high res displays.</p>" - } -] -}; \ No newline at end of file diff --git a/packages/patternengine-node-twig/source/css/scss/base/_forms.scss b/packages/patternengine-node-twig/source/css/scss/base/_forms.scss index d121af100..75e4ad6c8 100644 --- a/packages/patternengine-node-twig/source/css/scss/base/_forms.scss +++ b/packages/patternengine-node-twig/source/css/scss/base/_forms.scss @@ -111,7 +111,7 @@ input[type="search"]::-webkit-search-decoration { } /* Validation */ -.has-error { +.is-error { border-color: $error; } .is-valid { @@ -135,4 +135,4 @@ input[type="search"]::-webkit-search-decoration { border: 0; border-left: 1px solid $gray; color: $gray; -} \ No newline at end of file +} diff --git a/packages/patternengine-node-twig/test/engine_handlebars_tests.js b/packages/patternengine-node-twig/test/engine_handlebars_tests.js new file mode 100644 index 000000000..7a50c1460 --- /dev/null +++ b/packages/patternengine-node-twig/test/engine_handlebars_tests.js @@ -0,0 +1,164 @@ +(function () { + "use strict"; + + var path = require('path'); + var pa = require('../builder/pattern_assembler'); + var object_factory = require('../builder/object_factory'); + var testPatternsPath = path.resolve(__dirname, 'files', '_handlebars-test-patterns'); + + // fake pattern lab constructor: + // sets up a fake patternlab object, which is needed by the pattern processing + // apparatus. + function fakePatternLab() { + var fpl = { + partials: {}, + patterns: [], + footer: '', + header: '', + listitems: {}, + listItemArray: [], + data: { + link: {} + }, + config: require('../config.json'), + package: {} + }; + + // patch the pattern source so the pattern assembler can correctly determine + // the "subdir" + fpl.config.patterns.source = './test/files/_handlebars-test-patterns'; + + return fpl; + } + + + // function for testing sets of partials + function testFindPartials(test, partialTests) { + test.expect(partialTests.length + 1); + + // setup current pattern from what we would have during execution + // docs on partial syntax are here: + // http://patternlab.io/docs/pattern-including.html + var currentPattern = object_factory.oPattern.create( + '/home/fakeuser/pl/source/_patterns/01-molecules/00-testing/00-test-mol.hbs', // abspath + '01-molecules\\00-testing', // subdir + '00-test-mol.hbs', // filename, + null, // data + { + template: partialTests.join() + } + ); + + // act + var results = currentPattern.findPartials(); + + // assert + test.equals(results.length, partialTests.length); + partialTests.forEach(function(testString, index) { + test.equals(results[index], testString); + }); + + test.done(); + } + + exports['engine_handlebars'] = { + 'hello world handlebars pattern renders': function (test) { + test.expect(1); + + var patternPath = path.resolve( + testPatternsPath, + '00-atoms', + '00-global', + '00-helloworld.hbs' + ); + + // do all the normal processing of the pattern + var patternlab = new fakePatternLab(); + var assembler = new pa(); + var helloWorldPattern = assembler.process_pattern_iterative(patternPath, patternlab); + assembler.process_pattern_recursive(patternPath, patternlab); + + test.equals(helloWorldPattern.render(), 'Hello world!\n'); + test.done(); + }, + 'hello worlds handlebars pattern can see the atoms-helloworld partial and renders it twice': function (test) { + test.expect(1); + + // pattern paths + var pattern1Path = path.resolve( + testPatternsPath, + '00-atoms', + '00-global', + '00-helloworld.hbs' + ); + var pattern2Path = path.resolve( + testPatternsPath, + '00-molecules', + '00-global', + '00-helloworlds.hbs' + ); + + // set up environment + var patternlab = new fakePatternLab(); // environment + var assembler = new pa(); + + // do all the normal processing of the pattern + assembler.process_pattern_iterative(pattern1Path, patternlab); + var helloWorldsPattern = assembler.process_pattern_iterative(pattern2Path, patternlab); + assembler.process_pattern_recursive(pattern1Path, patternlab); + assembler.process_pattern_recursive(pattern2Path, patternlab); + + // test + test.equals(helloWorldsPattern.render(), 'Hello world!\n and Hello world!\n\n'); + test.done(); + }, + 'find_pattern_partials finds partials': function(test){ + testFindPartials(test, [ + "{{> molecules-comment-header}}", + "{{> molecules-comment-header}}", + "{{> \n molecules-comment-header\n}}", + "{{> molecules-weird-spacing }}", + "{{> molecules-ba_d-cha*rs }}" + ]); + }, + 'find_pattern_partials finds verbose partials': function(test){ + testFindPartials(test, [ + '{{> 01-molecules/06-components/03-comment-header.hbs }}', + "{{> 01-molecules/06-components/02-single-comment.hbs(description: 'A life is like a garden. Perfect moments can be had, but not preserved, except in memory.') }}", + '{{> molecules-single-comment:foo }}', + "{{>atoms-error(message: 'That\'s no moon...')}}", + "{{> atoms-error(message: 'That\'s no moon...') }}", + '{{> 00-atoms/00-global/06-test }}' + ]); + }, + 'find_pattern_partials finds simple partials with parameters': function(test){ + testFindPartials(test, [ + "{{> molecules-single-comment(description: 'A life isn\'t like a garden. Perfect moments can be had, but not preserved, except in memory.') }}", + '{{> molecules-single-comment(description:"A life is like a \"garden\". Perfect moments can be had, but not preserved, except in memory.") }}' + ]); + }, + 'find_pattern_partials finds simple partials with style modifiers': function(test){ + testFindPartials(test, [ + '{{> molecules-single-comment:foo }}' + ]); + }, + 'find_pattern_partials finds partials with handlebars parameters': function(test){ + testFindPartials(test, [ + '{{> atoms-title title="bravo" headingLevel="2" headingSize="bravo" position="left"}}', + '{{> atoms-title title="bravo"\n headingLevel="2"\n headingSize="bravo"\n position="left"}}', + '{{> atoms-title title="color <span style=\'font-weight:normal\'>midnight blue</span>" headingSize="charlie"}}', + '{{> atoms-input label="city" required=true}}', + '{{> organisms-product-filter filterData}}', + '{{> atoms-input email required=true}}', + '{{> molecules-storycard variants.flex }}', + '{{> myPartial name=../name }}' + ]); + }, + + 'find_pattern_partials finds handlebars block partials': function(test){ + testFindPartials(test, [ + '{{#> myPartial }}' + ]); + } + }; +})(); diff --git a/packages/patternengine-node-twig/test/files/_handlebars-test-patterns/00-atoms/00-global/00-helloworld.hbs b/packages/patternengine-node-twig/test/files/_handlebars-test-patterns/00-atoms/00-global/00-helloworld.hbs new file mode 100644 index 000000000..cd0875583 --- /dev/null +++ b/packages/patternengine-node-twig/test/files/_handlebars-test-patterns/00-atoms/00-global/00-helloworld.hbs @@ -0,0 +1 @@ +Hello world! diff --git a/packages/patternengine-node-twig/test/files/_handlebars-test-patterns/00-molecules/00-global/00-helloworlds.hbs b/packages/patternengine-node-twig/test/files/_handlebars-test-patterns/00-molecules/00-global/00-helloworlds.hbs new file mode 100644 index 000000000..1df8b851d --- /dev/null +++ b/packages/patternengine-node-twig/test/files/_handlebars-test-patterns/00-molecules/00-global/00-helloworlds.hbs @@ -0,0 +1 @@ +{{> atoms-helloworld}} and {{> atoms-helloworld}} diff --git a/packages/patternengine-node-twig/test/files/_patterns/00-test/03-styled-atom~alt.json b/packages/patternengine-node-twig/test/files/_patterns/00-test/03-styled-atom~alt.json new file mode 100644 index 000000000..d4595ffd0 --- /dev/null +++ b/packages/patternengine-node-twig/test/files/_patterns/00-test/03-styled-atom~alt.json @@ -0,0 +1,3 @@ +{ + "message": "alternateMessage" +} diff --git a/packages/patternengine-node-twig/test/files/_patterns/00-test/_ignored-pattern.mustache b/packages/patternengine-node-twig/test/files/_patterns/00-test/_ignored-pattern.mustache new file mode 100644 index 000000000..ae9ed0946 --- /dev/null +++ b/packages/patternengine-node-twig/test/files/_patterns/00-test/_ignored-pattern.mustache @@ -0,0 +1 @@ +<div>These aren't the patterns you are looking for.</div> diff --git a/packages/patternengine-node-twig/test/files/_patterns/00-test/link.mustache b/packages/patternengine-node-twig/test/files/_patterns/00-test/link.mustache new file mode 100644 index 000000000..b34269824 --- /dev/null +++ b/packages/patternengine-node-twig/test/files/_patterns/00-test/link.mustache @@ -0,0 +1 @@ +<a href="{{url}}">Cool Dude</a> diff --git a/packages/patternengine-node-twig/test/files/_patterns/00-test/nav.json b/packages/patternengine-node-twig/test/files/_patterns/00-test/nav.json new file mode 100644 index 000000000..32a6c0952 --- /dev/null +++ b/packages/patternengine-node-twig/test/files/_patterns/00-test/nav.json @@ -0,0 +1,11 @@ +{ + "brad" : { + "url" : "link.twitter-brad" + }, + "dave" : { + "url" : "link.twitter-dave" + }, + "brian" : { + "url" : "link.twitter-brian" + } +} diff --git a/packages/patternengine-node-twig/test/files/_patterns/00-test/nav.mustache b/packages/patternengine-node-twig/test/files/_patterns/00-test/nav.mustache new file mode 100644 index 000000000..b76f77dfc --- /dev/null +++ b/packages/patternengine-node-twig/test/files/_patterns/00-test/nav.mustache @@ -0,0 +1,9 @@ +{{# brad }} + {{> test-link }} +{{/ brad }} +{{# dave }} + {{> test-link }} +{{/ dave }} +{{# brian }} + {{> test-link }} +{{/ brian }} diff --git a/packages/patternengine-node-twig/test/pattern_assembler_tests.js b/packages/patternengine-node-twig/test/pattern_assembler_tests.js index dfede2a5e..0aa05893c 100644 --- a/packages/patternengine-node-twig/test/pattern_assembler_tests.js +++ b/packages/patternengine-node-twig/test/pattern_assembler_tests.js @@ -369,6 +369,7 @@ //arrange var fs = require('fs-extra'); var pattern_assembler = new pa(); + var patterns_dir = './test/files/_patterns'; var pl = {}; pl.config = {}; @@ -376,7 +377,7 @@ pl.data.link = {}; pl.config.debug = false; pl.patterns = []; - var patterns_dir = './test/files/_patterns'; + pl.config.patterns = { source: patterns_dir}; var atomPattern = new object_factory.oPattern('test/files/_patterns/00-test/03-styled-atom.mustache', '00-test', '03-styled-atom.mustache'); atomPattern.template = fs.readFileSync(patterns_dir + '/00-test/03-styled-atom.mustache', 'utf8'); @@ -401,6 +402,7 @@ //arrange var fs = require('fs-extra'); var pattern_assembler = new pa(); + var patterns_dir = './test/files/_patterns'; var pl = {}; pl.config = {}; @@ -408,7 +410,7 @@ pl.data.link = {}; pl.config.debug = false; pl.patterns = []; - var patterns_dir = './test/files/_patterns'; + pl.config.patterns = { source: patterns_dir}; var atomPattern = new object_factory.oPattern('test/files/_patterns/00-test/03-styled-atom.mustache', '00-test', '03-styled-atom.mustache'); atomPattern.template = fs.readFileSync(patterns_dir + '/00-test/03-styled-atom.mustache', 'utf8'); @@ -433,6 +435,7 @@ //arrange var fs = require('fs-extra'); var pattern_assembler = new pa(); + var patterns_dir = './test/files/_patterns'; var pl = {}; pl.config = {}; @@ -440,7 +443,7 @@ pl.data.link = {}; pl.config.debug = false; pl.patterns = []; - var patterns_dir = './test/files/_patterns'; + pl.config.patterns = { source: patterns_dir}; var atomPattern = new object_factory.oPattern('test/files/_patterns/00-test/03-styled-atom.mustache', '00-test', '03-styled-atom.mustache'); atomPattern.template = fs.readFileSync(patterns_dir + '/00-test/03-styled-atom.mustache', 'utf8'); @@ -468,6 +471,7 @@ //arrange var fs = require('fs-extra'); var pattern_assembler = new pa(); + var patterns_dir = './test/files/_patterns'; var pl = {}; pl.config = {}; @@ -475,7 +479,7 @@ pl.data.link = {}; pl.config.debug = false; pl.patterns = []; - var patterns_dir = './test/files/_patterns'; + pl.config.patterns = { source: patterns_dir}; var atomPattern = new object_factory.oPattern('test/files/_patterns/00-test/03-styled-atom.mustache', '00-test', '03-styled-atom.mustache'); atomPattern.template = fs.readFileSync(patterns_dir + '/00-test/03-styled-atom.mustache', 'utf8'); @@ -502,6 +506,7 @@ //arrange var fs = require('fs-extra'); var pattern_assembler = new pa(); + var patterns_dir = './test/files/_patterns'; var pl = {}; pl.config = {}; @@ -509,7 +514,7 @@ pl.data.link = {}; pl.config.debug = false; pl.patterns = []; - var patterns_dir = './test/files/_patterns'; + pl.config.patterns = { source: patterns_dir}; var atomPattern = new object_factory.oPattern('test/files/_patterns/00-test/03-styled-atom.mustache', '00-test', '03-styled-atom.mustache'); atomPattern.template = fs.readFileSync(patterns_dir + '/00-test/03-styled-atom.mustache', 'utf8'); @@ -531,6 +536,214 @@ var expectedValue = '<div class="test_group"> <span class="test_base {{styleModifier}}"> {{message}} </span> <span class="test_base test_2"> 2 </span> <span class="test_base test_3"> 3 </span> <span class="test_base {{styleModifier}}"> {{message}} </span> </div>'; test.equals(bookendPattern.extendedTemplate.replace(/\s\s+/g, ' ').replace(/\n/g, ' ').trim(), expectedValue.trim()); test.done(); + }, + 'processPatternIterative - ignores files that start with underscore' : function(test){ + //arrange + var diveSync = require('diveSync'); + var fs = require('fs-extra'); + var pa = require('../builder/pattern_assembler'); + var pattern_assembler = new pa(); + var patterns_dir = './test/files/_patterns'; + var patternlab = {}; + patternlab.config = fs.readJSONSync('./config.json'); + patternlab.config.patterns = {source: patterns_dir}; + patternlab.data = fs.readJSONSync('./source/_data/data.json'); + patternlab.listitems = fs.readJSONSync('./source/_data/listitems.json'); + patternlab.header = fs.readFileSync('./source/_patternlab-files/pattern-header-footer/header.html', 'utf8'); + patternlab.footer = fs.readFileSync('./source/_patternlab-files/pattern-header-footer/footer.html', 'utf8'); + patternlab.patterns = []; + patternlab.data.link = {}; + patternlab.partials = {}; + + //act + diveSync(patterns_dir, + { + filter: function(path, dir){ + if(dir){ + var remainingPath = path.replace(patterns_dir, ''); + var isValidPath = remainingPath.indexOf('/_') === -1; + return isValidPath; + } + return true; + } + }, + function(err, file){ + //log any errors + if(err){ + console.log(err); + return; + } + + pattern_assembler.process_pattern_iterative(file.substring(2), patternlab); + } + ); + + //assert + var foundIgnoredPattern = false; + for(var i = 0; i < patternlab.patterns.length; i++){ + if(patternlab.patterns[i].fileName[0] === '_'){ + foundIgnoredPattern = true; + } + } + test.equals(foundIgnoredPattern, false); + test.done(); + }, + 'processPatternIterative - ignores files that are variants' : function(test){ + //arrange + var diveSync = require('diveSync'); + var fs = require('fs-extra'); + var pa = require('../builder/pattern_assembler'); + var pattern_assembler = new pa(); + var patterns_dir = './test/files/_patterns'; + var patternlab = {}; + //THIS IS BAD. + patternlab.config = fs.readJSONSync('./config.json'); + patternlab.config.patterns = {source: patterns_dir}; + patternlab.data = fs.readJSONSync('./source/_data/data.json'); + patternlab.listitems = fs.readJSONSync('./source/_data/listitems.json'); + patternlab.header = fs.readFileSync('./source/_patternlab-files/pattern-header-footer/header.html', 'utf8'); + patternlab.footer = fs.readFileSync('./source/_patternlab-files/pattern-header-footer/footer.html', 'utf8'); + patternlab.patterns = []; + patternlab.data.link = {}; + patternlab.partials = {}; + + //act + diveSync(patterns_dir, + { + filter: function(path, dir){ + if(dir){ + var remainingPath = path.replace(patterns_dir, ''); + var isValidPath = remainingPath.indexOf('/_') === -1; + return isValidPath; + } + return true; + } + }, + function(err, file){ + //log any errors + if(err){ + console.log(err); + return; + } + + pattern_assembler.process_pattern_iterative(file.substring(2), patternlab); + } + ); + + //assert + var foundVariant = false; + for(var i = 0; i < patternlab.patterns.length; i++){ + if(patternlab.patterns[i].fileName.indexOf('~') > -1){ + foundVariant = true; + } + } + test.equals(foundVariant, false); + test.done(); + }, + 'setState - applies any patternState matching the pattern' : function(test){ + //arrange + var pa = require('../builder/pattern_assembler'); + var pattern_assembler = new pa(); + var patternlab = {}; + patternlab.config = {}; + patternlab.config.patternStates = {}; + patternlab.config.patternStates["homepage-emergency"] = "inprogress"; + + var pattern = { + patternName: "homepage-emergency" + }; + + //act + pattern_assembler.setPatternState(pattern, patternlab); + + //assert + test.equals(pattern.patternState, "inprogress"); + test.done(); + }, + 'setState - does not apply any patternState if nothing matches the pattern' : function(test){ + //arrange + var pa = require('../builder/pattern_assembler'); + var pattern_assembler = new pa(); + var patternlab = {}; + patternlab.config = {}; + patternlab.config.patternStates = {}; + patternlab.config.patternStates["homepage-emergency"] = "inprogress"; + + var pattern = { + patternName: "homepage" + }; + + //act + pattern_assembler.setPatternState(pattern, patternlab); + + //assert + test.equals(pattern.patternState, ""); + test.done(); + }, + 'parseDataLinks - replaces found link.* data for their expanded links' : function(test){ + //arrange + var diveSync = require('diveSync'); + var fs = require('fs-extra'); + var pa = require('../builder/pattern_assembler'); + var pattern_assembler = new pa(); + var patterns_dir = './test/files/_patterns/'; + var patternlab = {}; + //THIS IS BAD + patternlab.config = fs.readJSONSync('./config.json'); + patternlab.config.patterns = {source: patterns_dir}; + patternlab.data = fs.readJSONSync('./source/_data/data.json'); + patternlab.listitems = fs.readJSONSync('./source/_data/listitems.json'); + patternlab.header = fs.readFileSync('./source/_patternlab-files/pattern-header-footer/header.html', 'utf8'); + patternlab.footer = fs.readFileSync('./source/_patternlab-files/pattern-header-footer/footer.html', 'utf8'); + patternlab.patterns = []; + patternlab.data.link = {}; + patternlab.partials = {}; + + diveSync(patterns_dir, + { + filter: function(path, dir){ + if(dir){ + var remainingPath = path.replace(patterns_dir, ''); + var isValidPath = remainingPath.indexOf('/_') === -1; + return isValidPath; + } + return true; + } + }, + function(err, file){ + //log any errors + if(err){ + console.log(err); + return; + } + pattern_assembler.process_pattern_iterative(file.substring(2), patternlab); + } + ); + + //for the sake of the test, also imagining I have the following pages... + patternlab.data.link['twitter-brad'] = 'https://twitter.com/brad_frost'; + patternlab.data.link['twitter-dave'] = 'https://twitter.com/dmolsen'; + patternlab.data.link['twitter-brian'] = 'https://twitter.com/bmuenzenmeyer'; + + var pattern; + for(var i = 0; i < patternlab.patterns.length; i++){ + if(patternlab.patterns[i].key === 'test-nav'){ + pattern = patternlab.patterns[i]; + } + } + //assert before + test.equals(pattern.jsonFileData.brad.url, "link.twitter-brad"); + test.equals(pattern.jsonFileData.dave.url, "link.twitter-dave"); + test.equals(pattern.jsonFileData.brian.url, "link.twitter-brian"); + + //act + pattern_assembler.parse_data_links(patternlab); + + //assert after + test.equals(pattern.jsonFileData.brad.url, "https://twitter.com/brad_frost"); + test.equals(pattern.jsonFileData.dave.url, "https://twitter.com/dmolsen"); + test.equals(pattern.jsonFileData.brian.url, "https://twitter.com/bmuenzenmeyer"); + test.done(); } }; })(); diff --git a/packages/patternengine-node-twig/test/pseudopattern_hunter_tests.js b/packages/patternengine-node-twig/test/pseudopattern_hunter_tests.js new file mode 100644 index 000000000..5a50dbcdd --- /dev/null +++ b/packages/patternengine-node-twig/test/pseudopattern_hunter_tests.js @@ -0,0 +1,45 @@ +(function () { + "use strict"; + + var pha = require('../builder/pseudopattern_hunter'); + var pa = require('../builder/pattern_assembler'); + var object_factory = require('../builder/object_factory'); + + exports['pseudopattern_hunter'] = { + 'pseudpattern found and added as a pattern' : function(test){ + //arrange + var fs = require('fs-extra'); + var pattern_assembler = new pa(); + var pseudopattern_hunter = new pha(); + var patterns_dir = './test/files/_patterns/'; + + var pl = {}; + pl.config = {}; + pl.data = {}; + pl.data.link = {}; + pl.config.debug = false; + pl.patterns = []; + pl.config.patterns = { source: patterns_dir}; + pl.config.patternStates = {}; + + var atomPattern = new object_factory.oPattern('test/files/_patterns/00-test/03-styled-atom.mustache', '00-test', '03-styled-atom.mustache'); + atomPattern.template = fs.readFileSync(patterns_dir + '00-test/03-styled-atom.mustache', 'utf8'); + atomPattern.extendedTemplate = atomPattern.template; + atomPattern.stylePartials = pattern_assembler.find_pattern_partials_with_style_modifiers(atomPattern); + + pl.patterns.push(atomPattern); + + //act + var patternCountBefore = pl.patterns.length; + pseudopattern_hunter.find_pseudopatterns(atomPattern, pl); + + //assert + test.equals(patternCountBefore + 1, pl.patterns.length); + test.equals(pl.patterns[1].key, 'test-styled-atom-alt'); + test.equals(pl.patterns[1].extendedTemplate.replace(/\s\s+/g, ' ').replace(/\n/g, ' ').trim(), '<span class="test_base {{styleModifier}}"> {{message}} </span>'); + test.equals(JSON.stringify(pl.patterns[1].jsonFileData), JSON.stringify({"message": "alternateMessage"})); + + test.done(); + } + } +}());