From 276761f9da04ceece246034aec72fbba7a4379d0 Mon Sep 17 00:00:00 2001 From: New Geoff Date: Fri, 26 Feb 2016 20:53:22 -0600 Subject: [PATCH 01/17] add .editorconfig and .eslintrc from pattern-engines branch --- .editorconfig | 11 ++++++++ .eslintrc | 74 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 .editorconfig create mode 100644 .eslintrc diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..8951c3929 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,11 @@ +# editorconfig.org +root = true + +[*] +indent_style = space +indent_size = 2 +tab_width = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true diff --git a/.eslintrc b/.eslintrc new file mode 100644 index 000000000..4edaeae26 --- /dev/null +++ b/.eslintrc @@ -0,0 +1,74 @@ +{ + "env": { + "node": true, + "builtin": true + }, + "globals": {}, + "rules": { + "block-scoped-var": 2, + "camelcase": 0, + "curly": [ + 2, + "all" + ], + "dot-notation": [ + 1, + { + "allowKeywords": true + } + ], + "eqeqeq": [ + 2, + "allow-null" + ], + "global-strict": [ + 0, + "never" + ], + "guard-for-in": 2, + "key-spacing": [ + 0 + ], + "new-cap": 0, + "no-bitwise": 2, + "no-caller": 2, + "no-cond-assign": [ + 2, + "except-parens" + ], + "no-debugger": 2, + "no-empty": 2, + "no-eval": 2, + "no-extend-native": 2, + "no-extra-parens": 0, + "no-irregular-whitespace": 1, + "no-iterator": 2, + "no-loop-func": 2, + "no-mixed-requires": 0, + "no-multi-str": 2, + "no-multi-spaces": 0, + "no-new": 2, + "no-proto": 2, + "no-script-url": 2, + "no-sequences": 2, + "no-shadow": 2, + "no-undef": 2, + "no-underscore-dangle": 1, + "no-unused-vars": 2, + "no-with": 2, + "quotes": [ + 0, + "single" + ], + "semi": [ + 0, + "never" + ], + "strict": 0, + "valid-typeof": 2, + "wrap-iife": [ + 2, + "inside" + ] + } +} From 4f4b06ccfcdc3e98d9fdf619cb5a72af3b16ce2e Mon Sep 17 00:00:00 2001 From: New Geoff Date: Sat, 27 Feb 2016 11:24:04 -0600 Subject: [PATCH 02/17] Better .eslintrc with more rules --- .eslintrc | 77 +++++++++++++++++++++++++++---------------------------- 1 file changed, 38 insertions(+), 39 deletions(-) diff --git a/.eslintrc b/.eslintrc index 4edaeae26..d8f2a98e5 100644 --- a/.eslintrc +++ b/.eslintrc @@ -7,68 +7,67 @@ "rules": { "block-scoped-var": 2, "camelcase": 0, - "curly": [ - 2, - "all" - ], - "dot-notation": [ - 1, - { - "allowKeywords": true - } - ], - "eqeqeq": [ - 2, - "allow-null" - ], - "global-strict": [ - 0, - "never" - ], + "consistent-return": 2, + "curly": [2, "all"], + "dot-notation": [1, { "allowKeywords": true }], + "eqeqeq": [2, "allow-null"], + "global-strict": [0, "never"], "guard-for-in": 2, - "key-spacing": [ - 0 - ], + "indent": [2, 2, {"SwitchCase": 2, "VariableDeclarator": 2}], + "key-spacing": 0, "new-cap": 0, + "no-alert": 2, "no-bitwise": 2, "no-caller": 2, - "no-cond-assign": [ - 2, - "except-parens" - ], + "no-cond-assign": [2, "except-parens"], "no-debugger": 2, + "no-dupe-args": 2, + "no-dupe-keys": 2, "no-empty": 2, "no-eval": 2, "no-extend-native": 2, + "no-extra-bind": 2, "no-extra-parens": 0, + "no-extra-semi": 2, + "no-func-assign": 2, + "no-implied-eval": 2, + "no-invalid-regexp": 2, "no-irregular-whitespace": 1, "no-iterator": 2, "no-loop-func": 2, "no-mixed-requires": 0, "no-multi-str": 2, - "no-multi-spaces": 0, + "no-multi-spaces": 1, + "no-native-reassign": 2, "no-new": 2, + "no-param-reassign": 2, "no-proto": 2, + "no-redeclare": 2, "no-script-url": 2, + "no-self-assign": 2, + "no-self-compare": 2, "no-sequences": 2, "no-shadow": 2, "no-undef": 2, "no-underscore-dangle": 1, - "no-unused-vars": 2, + "no-unreachable": 1, + "no-unused-vars": 1, + "no-use-before-define": 1, + "no-useless-call": 2, + "no-useless-concat": 2, "no-with": 2, - "quotes": [ - 0, - "single" - ], - "semi": [ - 0, - "never" - ], + "quotes": [0, "single"], + "radix": 2, + "semi": [0, "never"], "strict": 0, + "space-before-blocks": 1, + "space-before-function-paren": [1, { + "anonymous": "always", + "named": "never" + }], + "space-infix-ops": 1, "valid-typeof": 2, - "wrap-iife": [ - 2, - "inside" - ] + "vars-on-top": 0, + "wrap-iife": [2, "inside"] } } From fae00ec743ad4c9f003392366c27b1ba3d480953 Mon Sep 17 00:00:00 2001 From: New Geoff Date: Sat, 27 Feb 2016 11:24:27 -0600 Subject: [PATCH 03/17] Reformatted lineage_hunter.js to pass lint --- builder/lineage_hunter.js | 146 +++++++++++++++++++------------------- 1 file changed, 74 insertions(+), 72 deletions(-) diff --git a/builder/lineage_hunter.js b/builder/lineage_hunter.js index 7325a5fde..6d3c8cf3e 100644 --- a/builder/lineage_hunter.js +++ b/builder/lineage_hunter.js @@ -1,76 +1,78 @@ -/* - * patternlab-node - v1.1.3 - 2016 - * +/* + * patternlab-node - v1.1.3 - 2016 + * * 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. * */ -(function () { - "use strict"; - - var lineage_hunter = function(){ - - function findlineage(pattern, patternlab){ - - var pa = require('./pattern_assembler'); - var pattern_assembler = new pa(); - - //find the {{> template-name }} within patterns - var matches = pattern_assembler.find_pattern_partials(pattern); - if(matches !== null){ - matches.forEach(function(match, index, matches){ - //strip out the template cruft - var foundPatternKey = match.replace("{{> ", "").replace(" }}", "").replace("{{>", "").replace("}}", ""); - - // remove any potential pattern parameters. this and the above are rather brutish but I didn't want to do a regex at the time - if(foundPatternKey.indexOf('(') > 0){ - foundPatternKey = foundPatternKey.substring(0, foundPatternKey.indexOf('(')); - } - - //remove any potential stylemodifiers. - foundPatternKey = foundPatternKey.split(':')[0]; - - //get the ancestorPattern - var ancestorPattern = pattern_assembler.get_pattern_by_key(foundPatternKey, patternlab); - - if (ancestorPattern && pattern.lineageIndex.indexOf(ancestorPattern.key) === -1){ - - //add it since it didnt exist - pattern.lineageIndex.push(ancestorPattern.key); - //create the more complex patternLineage object too - var l = { - "lineagePattern": ancestorPattern.key, - "lineagePath": "../../patterns/" + ancestorPattern.patternLink - }; - pattern.lineage.push(JSON.stringify(l)); - - //also, add the lineageR entry if it doesn't exist - if (ancestorPattern.lineageRIndex.indexOf(pattern.key) === -1){ - ancestorPattern.lineageRIndex.push(pattern.key); - - //create the more complex patternLineage object in reverse - var lr = { - "lineagePattern": pattern.key, - "lineagePath": "../../patterns/" + pattern.patternLink - }; - ancestorPattern.lineageR.push(JSON.stringify(lr)); - } - } - }); - } - } - - return { - find_lineage: function(pattern, patternlab){ - findlineage(pattern, patternlab); - } - }; - - }; - - module.exports = lineage_hunter; - -}()); +"use strict"; + +var lineage_hunter = function () { + + function findlineage(pattern, patternlab) { + + var pa = require('./pattern_assembler'); + var pattern_assembler = new pa(); + + //find the {{> template-name }} within patterns + var matches = pattern_assembler.find_pattern_partials(pattern); + if(matches !== null) { + matches.forEach(function (match) { + //strip out the template cruft + var foundPatternKey = match + .replace("{{> ", "") + .replace(" }}", "") + .replace("{{>", "") + .replace("}}", ""); + + // remove any potential pattern parameters. this and the above are + // rather brutish but I didn't want to do a regex at the time + if(foundPatternKey.indexOf('(') > 0) { + foundPatternKey = foundPatternKey.substring(0, foundPatternKey.indexOf('(')); + } + + //remove any potential stylemodifiers. + foundPatternKey = foundPatternKey.split(':')[0]; + + //get the ancestorPattern + var ancestorPattern = pattern_assembler.get_pattern_by_key(foundPatternKey, patternlab); + + if (ancestorPattern && pattern.lineageIndex.indexOf(ancestorPattern.key) === -1) { + + //add it since it didnt exist + pattern.lineageIndex.push(ancestorPattern.key); + //create the more complex patternLineage object too + var l = { + "lineagePattern": ancestorPattern.key, + "lineagePath": "../../patterns/" + ancestorPattern.patternLink + }; + pattern.lineage.push(JSON.stringify(l)); + + //also, add the lineageR entry if it doesn't exist + if (ancestorPattern.lineageRIndex.indexOf(pattern.key) === -1) { + ancestorPattern.lineageRIndex.push(pattern.key); + + //create the more complex patternLineage object in reverse + var lr = { + "lineagePattern": pattern.key, + "lineagePath": "../../patterns/" + pattern.patternLink + }; + ancestorPattern.lineageR.push(JSON.stringify(lr)); + } + } + }); + } + } + + return { + find_lineage: function (pattern, patternlab) { + findlineage(pattern, patternlab); + } + }; + +}; + +module.exports = lineage_hunter; From 31b94bd0b240b86eaf95398c3f98e78dfa01dcff Mon Sep 17 00:00:00 2001 From: New Geoff Date: Sat, 27 Feb 2016 11:53:16 -0600 Subject: [PATCH 04/17] add keyword spacing rule and update lineage_hunter to match --- .eslintrc | 1 + builder/lineage_hunter.js | 5 +++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.eslintrc b/.eslintrc index d8f2a98e5..05ba56ae1 100644 --- a/.eslintrc +++ b/.eslintrc @@ -15,6 +15,7 @@ "guard-for-in": 2, "indent": [2, 2, {"SwitchCase": 2, "VariableDeclarator": 2}], "key-spacing": 0, + "keyword-spacing": 2, "new-cap": 0, "no-alert": 2, "no-bitwise": 2, diff --git a/builder/lineage_hunter.js b/builder/lineage_hunter.js index 6d3c8cf3e..65a0e35cc 100644 --- a/builder/lineage_hunter.js +++ b/builder/lineage_hunter.js @@ -19,7 +19,7 @@ var lineage_hunter = function () { //find the {{> template-name }} within patterns var matches = pattern_assembler.find_pattern_partials(pattern); - if(matches !== null) { + if (matches !== null) { matches.forEach(function (match) { //strip out the template cruft var foundPatternKey = match @@ -30,7 +30,7 @@ var lineage_hunter = function () { // remove any potential pattern parameters. this and the above are // rather brutish but I didn't want to do a regex at the time - if(foundPatternKey.indexOf('(') > 0) { + if (foundPatternKey.indexOf('(') > 0) { foundPatternKey = foundPatternKey.substring(0, foundPatternKey.indexOf('(')); } @@ -44,6 +44,7 @@ var lineage_hunter = function () { //add it since it didnt exist pattern.lineageIndex.push(ancestorPattern.key); + //create the more complex patternLineage object too var l = { "lineagePattern": ancestorPattern.key, From 6db75a91edc298f1b51d8ad9c7bf58e9c5c883b7 Mon Sep 17 00:00:00 2001 From: New Geoff Date: Sat, 27 Feb 2016 15:23:16 -0600 Subject: [PATCH 05/17] more rule refinements --- .eslintrc | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/.eslintrc b/.eslintrc index 05ba56ae1..bcef947ef 100644 --- a/.eslintrc +++ b/.eslintrc @@ -7,15 +7,23 @@ "rules": { "block-scoped-var": 2, "camelcase": 0, + "comma-spacing": [1, {"before": false, "after": true}], "consistent-return": 2, "curly": [2, "all"], "dot-notation": [1, { "allowKeywords": true }], "eqeqeq": [2, "allow-null"], "global-strict": [0, "never"], "guard-for-in": 2, - "indent": [2, 2, {"SwitchCase": 2, "VariableDeclarator": 2}], + "indent": [2, 2, {"SwitchCase": 1, "VariableDeclarator": 2}], + "lines-around-comment": [2, { + "beforeBlockComment": true, + "beforeLineComment": true, + "allowBlockStart": true, + "allowObjectStart": true, + "allowArrayStart": true + }], "key-spacing": 0, - "keyword-spacing": 2, + "keyword-spacing": 1, "new-cap": 0, "no-alert": 2, "no-bitwise": 2, @@ -50,7 +58,7 @@ "no-sequences": 2, "no-shadow": 2, "no-undef": 2, - "no-underscore-dangle": 1, + "no-underscore-dangle": 0, "no-unreachable": 1, "no-unused-vars": 1, "no-use-before-define": 1, @@ -66,6 +74,7 @@ "anonymous": "always", "named": "never" }], + "space-in-parens": [1, "never"], "space-infix-ops": 1, "valid-typeof": 2, "vars-on-top": 0, From 8f27e792f6e33002440ec315610417ce06dc322e Mon Sep 17 00:00:00 2001 From: New Geoff Date: Sat, 27 Feb 2016 15:23:26 -0600 Subject: [PATCH 06/17] more reformatting and tweaks --- builder/list_item_hunter.js | 225 ++++++------ builder/media_hunter.js | 84 +++-- builder/object_factory.js | 110 +++--- builder/parameter_hunter.js | 167 ++++----- builder/pattern_assembler.js | 673 ++++++++++++++++++----------------- 5 files changed, 626 insertions(+), 633 deletions(-) diff --git a/builder/list_item_hunter.js b/builder/list_item_hunter.js index 93aa57890..62e8f5538 100644 --- a/builder/list_item_hunter.js +++ b/builder/list_item_hunter.js @@ -1,120 +1,115 @@ -/* - * patternlab-node - v1.1.3 - 2016 - * +/* + * patternlab-node - v1.1.3 - 2016 + * * 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. * */ -(function () { - "use strict"; - - var list_item_hunter = function(){ - - var extend = require('util')._extend, - pa = require('./pattern_assembler'), - smh = require('./style_modifier_hunter'), - mustache = require('mustache'), - pattern_assembler = new pa(), - style_modifier_hunter = new smh(), - items = [ 'zero','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen','twenty']; - - function processListItemPartials(pattern, patternlab){ - //find any listitem blocks - var matches = pattern_assembler.find_list_items(pattern, patternlab); - if(matches !== null){ - matches.forEach(function(liMatch, index, matches){ - - if(patternlab.config.debug){ - console.log('found listItem of size ' + liMatch + ' inside ' + pattern.key); - } - - //find the boundaries of the block - var loopNumberString = liMatch.split('.')[1].split('}')[0].trim(); - var end = liMatch.replace('#', '/'); - var patternBlock = pattern.template.substring(pattern.template.indexOf(liMatch) + liMatch.length, pattern.template.indexOf(end)).trim(); - //build arrays that repeat the block, however large we need to - var repeatedBlockTemplate = []; - var repeatedBlockHtml = ''; - for(var i = 0; i < items.indexOf(loopNumberString); i++){ - repeatedBlockTemplate.push(patternBlock); - } - - //check for a local listitems.json file - var listData = JSON.parse(JSON.stringify(patternlab.listitems)); - listData = pattern_assembler.merge_data(listData, pattern.listitems); - - //iterate over each copied block, rendering its contents along with pattenlab.listitems[i] - for(var i = 0; i < repeatedBlockTemplate.length; i++){ - - var thisBlockTemplate = repeatedBlockTemplate[i]; - var thisBlockHTML = ""; - - //combine listItem data with pattern data with global data - var itemData = listData['' + items.indexOf(loopNumberString)]; //this is a property like "2" - var globalData = JSON.parse(JSON.stringify(patternlab.data)); - var localData = JSON.parse(JSON.stringify(pattern.jsonFileData)); - - var allData = pattern_assembler.merge_data(globalData, localData); - allData = pattern_assembler.merge_data(allData, itemData != undefined ? itemData[i] : {}); //itemData could be undefined if the listblock contains no partial, just markup - allData.link = extend({}, patternlab.data.link); - - //check for partials within the repeated block - var foundPartials = pattern_assembler.find_pattern_partials({ 'template' : thisBlockTemplate }); - - if(foundPartials && foundPartials.length > 0){ - - for(var j = 0; j < foundPartials.length; j++){ - - //get the partial - var partialName = foundPartials[j].match(/([\w\-\.\/~]+)/g)[0]; - var partialPattern = pattern_assembler.get_pattern_by_key(partialName, patternlab); - - //create a copy of the partial so as to not pollute it after the get_pattern_by_key call. - var cleanPartialPattern = JSON.parse(JSON.stringify(partialPattern)); - - //if partial has style modifier data, replace the styleModifier value - if(foundPartials[j].indexOf(':') > -1){ - style_modifier_hunter.consume_style_modifier(cleanPartialPattern, foundPartials[j], patternlab); - } - - //replace its reference within the block with the extended template - thisBlockTemplate = thisBlockTemplate.replace(foundPartials[j], cleanPartialPattern.extendedTemplate); - } - - //render with data - thisBlockHTML = pattern_assembler.renderPattern(thisBlockTemplate, allData, patternlab.partials); - - } else{ - //just render with mergedData - thisBlockHTML = pattern_assembler.renderPattern(thisBlockTemplate, allData, patternlab.partials); - } - - //add the rendered HTML to our string - repeatedBlockHtml = repeatedBlockHtml + thisBlockHTML; - } - - //replace the block with our generated HTML - var repeatingBlock = pattern.extendedTemplate.substring(pattern.extendedTemplate.indexOf(liMatch), pattern.extendedTemplate.indexOf(end) + end.length); - pattern.extendedTemplate = pattern.extendedTemplate.replace(repeatingBlock, repeatedBlockHtml); - - //update the extendedTemplate in the partials object in case this pattern is consumed later - patternlab.partials[pattern.key] = pattern.extendedTemplate; - - }); - } - } - - return { - process_list_item_partials: function(pattern, patternlab){ - processListItemPartials(pattern, patternlab); - } - }; - - }; - - module.exports = list_item_hunter; -}()); +"use strict"; + +var list_item_hunter = function () { + + var extend = require('util')._extend, + pa = require('./pattern_assembler'), + smh = require('./style_modifier_hunter'), + pattern_assembler = new pa(), + style_modifier_hunter = new smh(), + items = [ 'zero','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen','twenty']; + + function processListItemPartials(pattern, patternlab) { + //find any listitem blocks + var matches = pattern_assembler.find_list_items(pattern, patternlab); + if (matches !== null) { + matches.forEach(function (liMatch) { + + if (patternlab.config.debug) { + console.log('found listItem of size ' + liMatch + ' inside ' + pattern.key); + } + + //find the boundaries of the block + var loopNumberString = liMatch.split('.')[1].split('}')[0].trim(); + var end = liMatch.replace('#', '/'); + var patternBlock = pattern.template.substring(pattern.template.indexOf(liMatch) + liMatch.length, pattern.template.indexOf(end)).trim(); + //build arrays that repeat the block, however large we need to + var repeatedBlockTemplate = []; + var repeatedBlockHtml = ''; + var i; // for loops + + for (i = 0; i < items.indexOf(loopNumberString); i++) { + repeatedBlockTemplate.push(patternBlock); + } + + //check for a local listitems.json file + var listData = JSON.parse(JSON.stringify(patternlab.listitems)); + listData = pattern_assembler.merge_data(listData, pattern.listitems); + + //iterate over each copied block, rendering its contents along with pattenlab.listitems[i] + for (i = 0; i < repeatedBlockTemplate.length; i++) { + var thisBlockTemplate = repeatedBlockTemplate[i]; + var thisBlockHTML = ""; + + //combine listItem data with pattern data with global data + var itemData = listData['' + items.indexOf(loopNumberString)]; //this is a property like "2" + var globalData = JSON.parse(JSON.stringify(patternlab.data)); + var localData = JSON.parse(JSON.stringify(pattern.jsonFileData)); + + var allData = pattern_assembler.merge_data(globalData, localData); + allData = pattern_assembler.merge_data(allData, itemData !== undefined ? itemData[i] : {}); //itemData could be undefined if the listblock contains no partial, just markup + allData.link = extend({}, patternlab.data.link); + + //check for partials within the repeated block + var foundPartials = pattern_assembler.find_pattern_partials({ 'template' : thisBlockTemplate }); + + if (foundPartials && foundPartials.length > 0) { + for (var j = 0; j < foundPartials.length; j++) { + //get the partial + var partialName = foundPartials[j].match(/([\w\-\.\/~]+)/g)[0]; + var partialPattern = pattern_assembler.get_pattern_by_key(partialName, patternlab); + + //create a copy of the partial so as to not pollute it after the get_pattern_by_key call. + var cleanPartialPattern = JSON.parse(JSON.stringify(partialPattern)); + + //if partial has style modifier data, replace the styleModifier value + if (foundPartials[j].indexOf(':') > -1) { + style_modifier_hunter.consume_style_modifier(cleanPartialPattern, foundPartials[j], patternlab); + } + + //replace its reference within the block with the extended template + thisBlockTemplate = thisBlockTemplate.replace(foundPartials[j], cleanPartialPattern.extendedTemplate); + } + + //render with data + thisBlockHTML = pattern_assembler.renderPattern(thisBlockTemplate, allData, patternlab.partials); + } else { + //just render with mergedData + thisBlockHTML = pattern_assembler.renderPattern(thisBlockTemplate, allData, patternlab.partials); + } + + //add the rendered HTML to our string + repeatedBlockHtml = repeatedBlockHtml + thisBlockHTML; + } + + //replace the block with our generated HTML + var repeatingBlock = pattern.extendedTemplate.substring(pattern.extendedTemplate.indexOf(liMatch), pattern.extendedTemplate.indexOf(end) + end.length); + pattern.extendedTemplate = pattern.extendedTemplate.replace(repeatingBlock, repeatedBlockHtml); + + //update the extendedTemplate in the partials object in case this pattern is consumed later + patternlab.partials[pattern.key] = pattern.extendedTemplate; + + }); + } + } + + return { + process_list_item_partials: function (pattern, patternlab) { + processListItemPartials(pattern, patternlab); + } + }; + +}; + +module.exports = list_item_hunter; diff --git a/builder/media_hunter.js b/builder/media_hunter.js index 3ee48f4fe..7aa12e10c 100644 --- a/builder/media_hunter.js +++ b/builder/media_hunter.js @@ -8,46 +8,44 @@ * */ -(function () { - "use strict"; - - var diveSync = require('diveSync'), - path = require('path'), - fs = require('fs-extra'); - - var media_hunter = function(){ - - function findMediaQueries(dir, patternlab){ - patternlab.mediaQueries = []; - - diveSync(dir, function(err, file){ - if(path.extname(file) === '.css'){ - var contents = fs.readFileSync(file, 'utf8'); - var safeContents = contents.replace("\r", " ").replace("\n", " "); - var matches = safeContents.match(/\((min|max)-width:([ ]+)?(([0-9]{1,5})(\.[0-9]{1,20}|)(px|em))/g); - for(var i = 0; i < matches.length; i++){ - var breakpoint = matches[i].substring(matches[i].indexOf(':') + 1).trimLeft(); - if(patternlab.mediaQueries.indexOf(breakpoint) === -1){ - patternlab.mediaQueries.push(breakpoint); - } - } - } - }); - patternlab.mediaQueries.sort(function(a,b){ - var integerPartA = a.match(/(?:\d*\.)?\d+/g); - var integerPartB = b.match(/(?:\d*\.)?\d+/g); - return parseInt(a,10) > parseInt(b,10); - }); - } - - return { - find_media_queries: function(dir, patternlab){ - findMediaQueries(dir, patternlab); - } - }; - - }; - - module.exports = media_hunter; - -}()); +"use strict"; + +var diveSync = require('diveSync'), + path = require('path'), + fs = require('fs-extra'); + +var media_hunter = function () { + + function findMediaQueries(dir, patternlab) { + patternlab.mediaQueries = []; + + diveSync(dir, function (err, file) { + if (path.extname(file) === '.css') { + var contents = fs.readFileSync(file, 'utf8'); + var safeContents = contents.replace("\r", " ").replace("\n", " "); + var matches = safeContents.match(/\((min|max)-width:([ ]+)?(([0-9]{1,5})(\.[0-9]{1,20}|)(px|em))/g); + for (var i = 0; i < matches.length; i++) { + var breakpoint = matches[i].substring(matches[i].indexOf(':') + 1).trimLeft(); + if (patternlab.mediaQueries.indexOf(breakpoint) === -1) { + patternlab.mediaQueries.push(breakpoint); + } + } + } + }); + patternlab.mediaQueries.sort(function (a, b) { + var integerPartA = a.match(/(?:\d*\.)?\d+/g); + var integerPartB = b.match(/(?:\d*\.)?\d+/g); + return parseInt(a, 10) > parseInt(b, 10); + }); + } + + return { + find_media_queries: function (dir, patternlab) { + findMediaQueries(dir, patternlab); + } + }; + +}; + +module.exports = media_hunter; + diff --git a/builder/object_factory.js b/builder/object_factory.js index 5526bdc18..c1e44ac38 100644 --- a/builder/object_factory.js +++ b/builder/object_factory.js @@ -8,65 +8,63 @@ * */ -(function () { - "use strict"; +"use strict"; - var oPattern = function(abspath, subdir, filename, data){ - this.fileName = filename.substring(0, filename.indexOf('.')); - this.abspath = abspath; - this.subdir = subdir; - this.name = subdir.replace(/[\/\\]/g, '-') + '-' + this.fileName; //this is the unique name with the subDir - this.jsonFileData = data || {}; - this.patternName = this.fileName.replace(/^\d*\-/, ''); - this.patternDisplayName = this.patternName.split('-').reduce(function(val, working){ - return val.charAt(0).toUpperCase() + val.slice(1) + ' ' + working.charAt(0).toUpperCase() + working.slice(1); - }, '').trim(); //this is the display name for the ui. strip numeric + hyphen prefixes - this.patternLink = this.name + '/' + this.name + '.html'; - this.patternGroup = this.name.substring(this.name.indexOf('-') + 1, this.name.indexOf('-', 4) + 1 - this.name.indexOf('-') + 1); - this.patternSubGroup = subdir.substring(subdir.indexOf('/') + 4); - this.flatPatternPath = subdir.replace(/[\/\\]/g, '-'); - this.key = this.patternGroup + '-' + this.patternName; - this.template = ''; - this.patternPartial = ''; - this.lineage = []; - this.lineageIndex = []; - this.lineageR = []; - this.lineageRIndex = []; - }; +var oPattern = function (abspath, subdir, filename, data) { + this.fileName = filename.substring(0, filename.indexOf('.')); + this.abspath = abspath; + this.subdir = subdir; + this.name = subdir.replace(/[\/\\]/g, '-') + '-' + this.fileName; //this is the unique name with the subDir + this.jsonFileData = data || {}; + this.patternName = this.fileName.replace(/^\d*\-/, ''); + this.patternDisplayName = this.patternName.split('-').reduce(function (val, working) { + return val.charAt(0).toUpperCase() + val.slice(1) + ' ' + working.charAt(0).toUpperCase() + working.slice(1); + }, '').trim(); //this is the display name for the ui. strip numeric + hyphen prefixes + this.patternLink = this.name + '/' + this.name + '.html'; + this.patternGroup = this.name.substring(this.name.indexOf('-') + 1, this.name.indexOf('-', 4) + 1 - this.name.indexOf('-') + 1); + this.patternSubGroup = subdir.substring(subdir.indexOf('/') + 4); + this.flatPatternPath = subdir.replace(/[\/\\]/g, '-'); + this.key = this.patternGroup + '-' + this.patternName; + this.template = ''; + this.patternPartial = ''; + this.lineage = []; + this.lineageIndex = []; + this.lineageR = []; + this.lineageRIndex = []; +}; - var oBucket = function(name){ - this.bucketNameLC = name; - this.bucketNameUC = name.split('-').reduce(function(val, working){ - return val.charAt(0).toUpperCase() + val.slice(1) + ' ' + working.charAt(0).toUpperCase() + working.slice(1); - }, '').trim(); - this.navItems = []; - this.navItemsIndex = []; - this.patternItems = []; - this.patternItemsIndex = []; - }; +var oBucket = function (name) { + this.bucketNameLC = name; + this.bucketNameUC = name.split('-').reduce(function (val, working) { + return val.charAt(0).toUpperCase() + val.slice(1) + ' ' + working.charAt(0).toUpperCase() + working.slice(1); + }, '').trim(); + this.navItems = []; + this.navItemsIndex = []; + this.patternItems = []; + this.patternItemsIndex = []; +}; - var oNavItem = function(name){ - this.sectionNameLC = name; - this.sectionNameUC = name.split('-').reduce(function(val, working){ - return val.charAt(0).toUpperCase() + val.slice(1) + ' ' + working.charAt(0).toUpperCase() + working.slice(1); - }, '').trim(); - this.navSubItems = []; - this.navSubItemsIndex = []; - }; +var oNavItem = function (name) { + this.sectionNameLC = name; + this.sectionNameUC = name.split('-').reduce(function (val, working) { + return val.charAt(0).toUpperCase() + val.slice(1) + ' ' + working.charAt(0).toUpperCase() + working.slice(1); + }, '').trim(); + this.navSubItems = []; + this.navSubItemsIndex = []; +}; - var oNavSubItem = function(name){ - this.patternPath = ''; - this.patternPartial = ''; - this.patternName = name.split(' ').reduce(function(val, working){ - return val.charAt(0).toUpperCase() + val.slice(1) + ' ' + working.charAt(0).toUpperCase() + working.slice(1); - }, '').trim(); - }; +var oNavSubItem = function (name) { + this.patternPath = ''; + this.patternPartial = ''; + this.patternName = name.split(' ').reduce(function (val, working) { + return val.charAt(0).toUpperCase() + val.slice(1) + ' ' + working.charAt(0).toUpperCase() + working.slice(1); + }, '').trim(); +}; - module.exports = { - oPattern: oPattern, - oBucket: oBucket, - oNavItem: oNavItem, - oNavSubItem: oNavSubItem - }; +module.exports = { + oPattern: oPattern, + oBucket: oBucket, + oNavItem: oNavItem, + oNavSubItem: oNavSubItem +}; -}()); diff --git a/builder/parameter_hunter.js b/builder/parameter_hunter.js index a3f574951..1c683780e 100644 --- a/builder/parameter_hunter.js +++ b/builder/parameter_hunter.js @@ -8,86 +8,87 @@ * */ -(function () { - "use strict"; - - var parameter_hunter = function(){ - - var extend = require('util')._extend, - pa = require('./pattern_assembler'), - mustache = require('mustache'), - smh = require('./style_modifier_hunter'), - style_modifier_hunter = new smh(), - pattern_assembler = new pa(); - - function findparameters(pattern, patternlab){ - - if(pattern.parameteredPartials && pattern.parameteredPartials.length > 0){ - //compile this partial immeadiately, essentially consuming it. - pattern.parameteredPartials.forEach(function(pMatch, index, matches){ - //find the partial's name and retrieve it - var partialName = pMatch.match(/([\w\-\.\/~]+)/g)[0]; - var partialPattern = pattern_assembler.get_pattern_by_key(partialName, patternlab); - //if we retrieved a pattern we should make sure that its extendedTemplate is reset. looks to fix #190 - partialPattern.extendedTemplate = partialPattern.template; - - if(patternlab.config.debug){ - console.log('found patternParameters for ' + partialName); - } - - //strip out the additional data, convert string to JSON. - var leftParen = pMatch.indexOf('('); - var rightParen = pMatch.indexOf(')'); - var paramString = '{' + pMatch.substring(leftParen + 1, rightParen) + '}'; - //if param keys are wrapped in single quotes, replace with double quotes. - var paramStringWellFormed = paramString.replace(/(')([^']+)(')(\s*\:)/g, '"$2"$4'); - //if params keys are not wrapped in any quotes, wrap in double quotes. - var paramStringWellFormed = paramStringWellFormed.replace(/([\{|,]\s*)([^\s"'\:]+)(\s*\:)/g, '$1"$2"$3'); - //if param values are wrapped in single quotes, replace with double quotes. - var paramStringWellFormed = paramStringWellFormed.replace(/(\:\s*)(')([^']+)(')/g, '$1"$3"'); - - var paramData = {}; - var globalData = {}; - var localData = {}; - - try { - paramData = JSON.parse(paramStringWellFormed); - globalData = JSON.parse(JSON.stringify(patternlab.data)); - localData = JSON.parse(JSON.stringify(pattern.jsonFileData || {})); - } catch(e){ - console.log(e); - } - - var allData = pattern_assembler.merge_data(globalData, localData); - allData = pattern_assembler.merge_data(allData, paramData); - - //if partial has style modifier data, replace the styleModifier value - if(pattern.stylePartials && pattern.stylePartials.length > 0){ - style_modifier_hunter.consume_style_modifier(partialPattern, pMatch, patternlab); - } - - //extend pattern data links into link for pattern link shortcuts to work. we do this locally and globally - allData.link = extend({}, patternlab.data.link); - - var renderedPartial = pattern_assembler.renderPattern(partialPattern.extendedTemplate, allData, patternlab.partials); - - //remove the parameter from the partial and replace it with the rendered partial + paramData - pattern.extendedTemplate = pattern.extendedTemplate.replace(pMatch, renderedPartial); - - //update the extendedTemplate in the partials object in case this pattern is consumed later - patternlab.partials[pattern.key] = pattern.extendedTemplate; - }); - } - } - - return { - find_parameters: function(pattern, patternlab){ - findparameters(pattern, patternlab); - } - }; - - }; - - module.exports = parameter_hunter; - -}()); +"use strict"; + +var parameter_hunter = function () { + + var extend = require('util')._extend, + pa = require('./pattern_assembler'), + smh = require('./style_modifier_hunter'), + style_modifier_hunter = new smh(), + pattern_assembler = new pa(); + + function findparameters(pattern, patternlab) { + if (pattern.parameteredPartials && pattern.parameteredPartials.length > 0) { + //compile this partial immeadiately, essentially consuming it. + + pattern.parameteredPartials.forEach(function (pMatch) { + //find the partial's name and retrieve it + var partialName = pMatch.match(/([\w\-\.\/~]+)/g)[0]; + var partialPattern = pattern_assembler.get_pattern_by_key(partialName, patternlab); + + //if we retrieved a pattern we should make sure that its extendedTemplate is reset. looks to fix #190 + partialPattern.extendedTemplate = partialPattern.template; + if (patternlab.config.debug) { + console.log('found patternParameters for ' + partialName); + } + + //strip out the additional data, convert string to JSON. + var leftParen = pMatch.indexOf('('); + var rightParen = pMatch.indexOf(')'); + var paramString = '{' + pMatch.substring(leftParen + 1, rightParen) + '}'; + + //if param keys are wrapped in single quotes, replace with double quotes. + var paramStringWellFormed = paramString.replace(/(')([^']+)(')(\s*\:)/g, '"$2"$4'); + + //if params keys are not wrapped in any quotes, wrap in double quotes. + paramStringWellFormed = paramStringWellFormed.replace(/([\{|,]\s*)([^\s"'\:]+)(\s*\:)/g, '$1"$2"$3'); + + //if param values are wrapped in single quotes, replace with double quotes. + paramStringWellFormed = paramStringWellFormed.replace(/(\:\s*)(')([^']+)(')/g, '$1"$3"'); + + var paramData = {}; + var globalData = {}; + var localData = {}; + + try { + paramData = JSON.parse(paramStringWellFormed); + globalData = JSON.parse(JSON.stringify(patternlab.data)); + localData = JSON.parse(JSON.stringify(pattern.jsonFileData || {})); + } catch (e) { + console.log(e); + } + + var allData = pattern_assembler.merge_data(globalData, localData); + allData = pattern_assembler.merge_data(allData, paramData); + + //if partial has style modifier data, replace the styleModifier value + if (pattern.stylePartials && pattern.stylePartials.length > 0) { + style_modifier_hunter.consume_style_modifier(partialPattern, pMatch, patternlab); + } + + //extend pattern data links into link for pattern link shortcuts to work. we do this locally and globally + allData.link = extend({}, patternlab.data.link); + + var renderedPartial = pattern_assembler.renderPattern(partialPattern.extendedTemplate, allData, patternlab.partials); + + //remove the parameter from the partial and replace it with the rendered partial + paramData + pattern.extendedTemplate = pattern.extendedTemplate.replace(pMatch, renderedPartial); + + //update the extendedTemplate in the partials object in case this pattern is consumed later + patternlab.partials[pattern.key] = pattern.extendedTemplate; + }); + } + } + + return { + find_parameters: function (pattern, patternlab) { + findparameters(pattern, patternlab); + } + }; + +}; + +module.exports = parameter_hunter; + + diff --git a/builder/pattern_assembler.js b/builder/pattern_assembler.js index d200f059d..3fc32d036 100644 --- a/builder/pattern_assembler.js +++ b/builder/pattern_assembler.js @@ -8,418 +8,419 @@ * */ -(function () { - "use strict"; - var pattern_assembler = function(){ +"use strict"; - function isObjectEmpty(obj) { - for(var prop in obj) { - if(obj.hasOwnProperty(prop)) - return false; - } +var pattern_assembler = function () { - return true; + function isObjectEmpty(obj) { + for (var prop in obj) { + if (obj.hasOwnProperty(prop)) { return false; } } - - // returns any patterns that match {{> value:mod }} or {{> value:mod(foo:"bar") }} within the pattern - function findPartialsWithStyleModifiers(pattern){ - var matches = pattern.template.match(/{{>([ ])?([\w\-\.\/~]+)(?!\()(\:[A-Za-z0-9-_|]+)+(?:(| )\(.*)?([ ])?}}/g); - return matches; + return true; + } + + // returns any patterns that match {{> value:mod }} or {{> value:mod(foo:"bar") }} within the pattern + function findPartialsWithStyleModifiers(pattern) { + var matches = pattern.template.match(/{{>([ ])?([\w\-\.\/~]+)(?!\()(\:[A-Za-z0-9-_|]+)+(?:(| )\(.*)?([ ])?}}/g); + return matches; + } + + // returns any patterns that match {{> value(foo:"bar") }} or {{> value:mod(foo:"bar") }} within the pattern + function findPartialsWithPatternParameters(pattern) { + var matches = pattern.template.match(/{{>([ ])?([\w\-\.\/~]+)(?:\:[A-Za-z0-9-_|]+)?(?:(| )\(.*)+([ ])?}}/g); + return matches; + } + + //find and return any {{> template-name* }} within pattern + function findPartials(pattern) { + var matches = pattern.template.match(/{{>([ ])?([\w\-\.\/~]+)(?:\:[A-Za-z0-9-_|]+)?(?:(| )\(.*)?([ ])?}}/g); + return matches; + } + + function findListItems(pattern) { + var matches = pattern.template.match(/({{#( )?)(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); + return matches; + } + + function setState(pattern, patternlab) { + if (patternlab.config.patternStates && patternlab.config.patternStates[pattern.patternName]) { + pattern.patternState = patternlab.config.patternStates[pattern.patternName]; + } else { + pattern.patternState = ""; } - - // returns any patterns that match {{> value(foo:"bar") }} or {{> value:mod(foo:"bar") }} within the pattern - function findPartialsWithPatternParameters(pattern){ - var matches = pattern.template.match(/{{>([ ])?([\w\-\.\/~]+)(?:\:[A-Za-z0-9-_|]+)?(?:(| )\(.*)+([ ])?}}/g); - return matches; + } + + 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 + var isNew = true, i; + for (i = 0; i < patternlab.patterns.length; i++) { + //so we need the identifier to be unique, which patterns[i].abspath is + if (pattern.abspath === patternlab.patterns[i].abspath) { + //if abspath already exists, overwrite that element + patternlab.patterns[i] = pattern; + patternlab.partials[pattern.key] = pattern.extendedTemplate || pattern.template; + isNew = false; + break; + } } - - //find and return any {{> template-name* }} within pattern - function findPartials(pattern){ - var matches = pattern.template.match(/{{>([ ])?([\w\-\.\/~]+)(?:\:[A-Za-z0-9-_|]+)?(?:(| )\(.*)?([ ])?}}/g); - return matches; + + //if the pattern is new, just push to the array + if (isNew) { + patternlab.patterns.push(pattern); + patternlab.partials[pattern.key] = pattern.extendedTemplate || pattern.template; } + } - function findListItems(pattern){ - var matches = pattern.template.match(/({{#( )?)(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); - return matches; - } + function renderPattern(template, data, partials) { + var mustache = require('mustache'); - function setState(pattern, patternlab){ - if(patternlab.config.patternStates && patternlab.config.patternStates[pattern.patternName]){ - pattern.patternState = patternlab.config.patternStates[pattern.patternName]; - } else{ - pattern.patternState = ""; - } + if (partials) { + return mustache.render(template, data, partials); + } else { + return mustache.render(template, data); } + } - 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 - var isNew = true; - for(var i = 0; i < patternlab.patterns.length; i++){ - //so we need the identifier to be unique, which patterns[i].abspath is - if(pattern.abspath === patternlab.patterns[i].abspath){ - //if abspath already exists, overwrite that element - patternlab.patterns[i] = pattern; - patternlab.partials[pattern.key] = pattern.extendedTemplate || pattern.template; - isNew = false; - break; - } - } - //if the pattern is new, just push to the array - if(isNew){ - patternlab.patterns.push(pattern); - patternlab.partials[pattern.key] = pattern.extendedTemplate || pattern.template; - } - } + function processPatternIterative(file, patternlab) { + var fs = require('fs-extra'), + of = require('./object_factory'), + path = require('path'); - function renderPattern(template, data, partials) { + //extract some information + var subdir = path.dirname(path.relative(patternlab.config.paths.source.patterns, file)).replace('\\', '/'); + var filename = path.basename(file); + var ext = path.extname(filename); - var mustache = require('mustache'); - - if(partials) { - return mustache.render(template, data, partials); - } else{ - return mustache.render(template, data); - } + //ignore dotfiles, underscored files, and non-variant .json files + if (filename.charAt(0) === '.' || (ext === '.json' && filename.indexOf('~') === -1)) { + return; } - function processPatternIterative(file, patternlab){ - var fs = require('fs-extra'), - of = require('./object_factory'), - path = require('path'); + //make a new Pattern Object + var currentPattern = new of.oPattern(file, subdir, filename); - //extract some information - var subdir = path.dirname(path.relative(patternlab.config.paths.source.patterns, file)).replace('\\', '/'); - var filename = path.basename(file); - var ext = path.extname(filename); + //if file is named in the syntax for variants, no need to process further + //processPatternRecursive() will run find_pseudopatterns() and look at each pattern for a variant + if (ext === '.json' && filename.indexOf('~') > -1) { + return; + } - //ignore dotfiles, underscored files, and non-variant .json files - if(filename.charAt(0) === '.' || (ext === '.json' && filename.indexOf('~') === -1)){ - return; - } + //can ignore all non-mustache files at this point + if (ext !== '.mustache') { + return; + } - //make a new Pattern Object - var currentPattern = new of.oPattern(file, subdir, filename); + //see if this file has a state + setState(currentPattern, patternlab); - //if file is named in the syntax for variants, no need to process further - //processPatternRecursive() will run find_pseudopatterns() and look at each pattern for a variant - if(ext === '.json' && filename.indexOf('~') > -1){ - return; + //look for a json file for this template + try { + var jsonFilename = path.resolve(patternlab.config.paths.source.patterns, currentPattern.subdir, currentPattern.fileName + ".json"); + currentPattern.jsonFileData = fs.readJSONSync(jsonFilename); + if (patternlab.config.debug) { + console.log('found pattern-specific data.json for ' + currentPattern.key); } + } + catch (error) { + // do nothing + } - //can ignore all non-mustache files at this point - if(ext !== '.mustache'){ - return; + //look for a listitems.json file for this template + try { + var listJsonFileName = path.resolve(patternlab.config.paths.source.patterns, currentPattern.subdir, currentPattern.fileName + ".listitems.json"); + currentPattern.listitems = fs.readJSONSync(listJsonFileName); + buildListItems(currentPattern); + if (patternlab.config.debug) { + console.log('found pattern-specific listitems.json for ' + currentPattern.key); } + } + catch (err) { + // do nothing + } - //see if this file has a state - setState(currentPattern, patternlab); + //add the raw template to memory + currentPattern.template = fs.readFileSync(file, 'utf8'); - //look for a json file for this template - try { - var jsonFilename = path.resolve(patternlab.config.paths.source.patterns, currentPattern.subdir, currentPattern.fileName + ".json"); - currentPattern.jsonFileData = fs.readJSONSync(jsonFilename); - if(patternlab.config.debug){ - console.log('found pattern-specific data.json for ' + currentPattern.key); - } - } - catch(e) { - } + //find any stylemodifiers that may be in the current pattern + currentPattern.stylePartials = findPartialsWithStyleModifiers(currentPattern); - //look for a listitems.json file for this template - try { - var listJsonFileName = path.resolve(patternlab.config.paths.source.patterns, currentPattern.subdir,currentPattern.fileName + ".listitems.json"); - currentPattern.listitems = fs.readJSONSync(listJsonFileName); - buildListItems(currentPattern); - if(patternlab.config.debug){ - console.log('found pattern-specific listitems.json for ' + currentPattern.key); - } - } - catch(e) { - } + //find any pattern parameters that may be in the current pattern + currentPattern.parameteredPartials = findPartialsWithPatternParameters(currentPattern); - //add the raw template to memory - currentPattern.template = fs.readFileSync(file, 'utf8'); + //add currentPattern to patternlab.patterns array + addPattern(currentPattern, patternlab); + } - //find any stylemodifiers that may be in the current pattern - currentPattern.stylePartials = findPartialsWithStyleModifiers(currentPattern); + function processPatternRecursive(file, patternlab) { + var lh = require('./lineage_hunter'), + ph = require('./parameter_hunter'), + pph = require('./pseudopattern_hunter'), + lih = require('./list_item_hunter'), + smh = require('./style_modifier_hunter'); - //find any pattern parameters that may be in the current pattern - currentPattern.parameteredPartials = findPartialsWithPatternParameters(currentPattern); + var parameter_hunter = new ph(), + lineage_hunter = new lh(), + list_item_hunter = new lih(), + style_modifier_hunter = new smh(), + pseudopattern_hunter = new pph(); - //add currentPattern to patternlab.patterns array - addPattern(currentPattern, patternlab); - } + //find current pattern in patternlab object using var file as a key + var currentPattern, + i; - function processPatternRecursive(file, patternlab, additionalData){ - - var fs = require('fs-extra'), - mustache = require('mustache'), - lh = require('./lineage_hunter'), - ph = require('./parameter_hunter'), - pph = require('./pseudopattern_hunter'), - lih = require('./list_item_hunter'), - smh = require('./style_modifier_hunter'), - path = require('path'); - - var parameter_hunter = new ph(), - lineage_hunter = new lh(), - list_item_hunter = new lih(), - style_modifier_hunter = new smh(), - pseudopattern_hunter = new pph(); - - //find current pattern in patternlab object using var file as a key - var currentPattern, - i; - - for(i = 0; i < patternlab.patterns.length; i++){ - if(patternlab.patterns[i].abspath === file){ - currentPattern = patternlab.patterns[i]; - break; - } + for (i = 0; i < patternlab.patterns.length; i++) { + if (patternlab.patterns[i].abspath === file) { + currentPattern = patternlab.patterns[i]; + break; } + } - //return if processing an ignored file - if(typeof currentPattern === 'undefined'){ - return; - } + //return if processing an ignored file + if (typeof currentPattern === 'undefined') { + return; + } - currentPattern.extendedTemplate = currentPattern.template; + currentPattern.extendedTemplate = currentPattern.template; - //find how many partials there may be for the given pattern - var foundPatternPartials = findPartials(currentPattern); + //find how many partials there may be for the given pattern + var foundPatternPartials = findPartials(currentPattern); - if(foundPatternPartials !== null && foundPatternPartials.length > 0){ + if (foundPatternPartials !== null && foundPatternPartials.length > 0) { - if(patternlab.config.debug){ - console.log('found partials for ' + currentPattern.key); - } + if (patternlab.config.debug) { + console.log('found partials for ' + currentPattern.key); + } - //find any listItem blocks - list_item_hunter.process_list_item_partials(currentPattern, patternlab); + //find any listItem blocks + list_item_hunter.process_list_item_partials(currentPattern, patternlab); - //determine if the template contains any pattern parameters. if so they must be immediately consumed - parameter_hunter.find_parameters(currentPattern, patternlab); + //determine if the template contains any pattern parameters. if so they must be immediately consumed + parameter_hunter.find_parameters(currentPattern, patternlab); - //do something with the regular old partials - for(i = 0; i < foundPatternPartials.length; i++){ - var partialKey = foundPatternPartials[i].replace(/{{>([ ])?([\w\-\.\/~]+)(:[A-z0-9-_|]+)?(?:\:[A-Za-z0-9-_]+)?(?:(| )\(.*)?([ ])?}}/g, '$2'); + //do something with the regular old partials + for (i = 0; i < foundPatternPartials.length; i++) { + var partialKey = foundPatternPartials[i].replace(/{{>([ ])?([\w\-\.\/~]+)(:[A-z0-9-_|]+)?(?:\:[A-Za-z0-9-_]+)?(?:(| )\(.*)?([ ])?}}/g, '$2'); - var partialPath; + var partialPath; - //identify which pattern this partial corresponds to - for(var j = 0; j < patternlab.patterns.length; j++){ - if(patternlab.patterns[j].key === partialKey || - patternlab.patterns[j].abspath.indexOf(partialKey) > -1) - { - partialPath = patternlab.patterns[j].abspath; - } + //identify which pattern this partial corresponds tou + for (var j = 0; j < patternlab.patterns.length; j++) { + if (patternlab.patterns[j].key === partialKey || + patternlab.patterns[j].abspath.indexOf(partialKey) > -1) { + partialPath = patternlab.patterns[j].abspath; } + } - //recurse through nested partials to fill out this extended template. - processPatternRecursive(partialPath, patternlab); - - //complete assembly of extended template - var partialPattern = getpatternbykey(partialKey, patternlab); + //recurse through nested partials to fill out this extended template. + processPatternRecursive(partialPath, patternlab); - //if partial has style modifier data, replace the styleModifier value - if(currentPattern.stylePartials && currentPattern.stylePartials.length > 0){ - style_modifier_hunter.consume_style_modifier(partialPattern, foundPatternPartials[i], patternlab); - } + //complete assembly of extended template + var partialPattern = getpatternbykey(partialKey, patternlab); - currentPattern.extendedTemplate = currentPattern.extendedTemplate.replace(foundPatternPartials[i], partialPattern.extendedTemplate); - - //update the extendedTemplate in the partials object in case this pattern is consumed later - patternlab.partials[currentPattern.key] = currentPattern.extendedTemplate; + //if partial has style modifier data, replace the styleModifier value + if (currentPattern.stylePartials && currentPattern.stylePartials.length > 0) { + style_modifier_hunter.consume_style_modifier(partialPattern, foundPatternPartials[i], patternlab); } - } else{ - //find any listItem blocks that within the pattern, even if there are no partials - list_item_hunter.process_list_item_partials(currentPattern, patternlab); - } - - //find pattern lineage - lineage_hunter.find_lineage(currentPattern, patternlab); + currentPattern.extendedTemplate = currentPattern.extendedTemplate.replace(foundPatternPartials[i], partialPattern.extendedTemplate); - //add to patternlab object so we can look these up later. - addPattern(currentPattern, patternlab); + //update the extendedTemplate in the partials object in case this pattern is consumed later + patternlab.partials[currentPattern.key] = currentPattern.extendedTemplate; + } - //look for a pseudo pattern by checking if there is a file containing same name, with ~ in it, ending in .json - pseudopattern_hunter.find_pseudopatterns(currentPattern, patternlab); + } else { + //find any listItem blocks that within the pattern, even if there are no partials + list_item_hunter.process_list_item_partials(currentPattern, patternlab); } - function getpatternbykey(key, patternlab){ + //find pattern lineage + lineage_hunter.find_lineage(currentPattern, patternlab); - //look for exact key matches - for(var i = 0; i < patternlab.patterns.length; i++){ - if(patternlab.patterns[i].key === key){ - return patternlab.patterns[i]; - } - } + //add to patternlab object so we can look these up later. + addPattern(currentPattern, patternlab); - //else look by verbose syntax - for(var i = 0; i < patternlab.patterns.length; i++){ - switch(key){ - case patternlab.patterns[i].subdir + '/' + patternlab.patterns[i].fileName: - case patternlab.patterns[i].subdir + '/' + patternlab.patterns[i].fileName + '.mustache': - return patternlab.patterns[i]; - } + //look for a pseudo pattern by checking if there is a file containing same name, with ~ in it, ending in .json + pseudopattern_hunter.find_pseudopatterns(currentPattern, patternlab); + } + + function getpatternbykey(key, patternlab) { + var i; // for the for loops + + //look for exact key matches + for (i = 0; i < patternlab.patterns.length; i++) { + if (patternlab.patterns[i].key === key) { + return patternlab.patterns[i]; } + } - //return the fuzzy match if all else fails - for(var i = 0; i < patternlab.patterns.length; i++){ - var keyParts = key.split('-'), - keyType = keyParts[0], - keyName = keyParts.slice(1).join('-'); - if(patternlab.patterns[i].key.split('-')[0] === keyType && patternlab.patterns[i].key.indexOf(keyName) > -1){ + //else look by verbose syntax + for (i = 0; i < patternlab.patterns.length; i++) { + switch (key) { + case patternlab.patterns[i].subdir + '/' + patternlab.patterns[i].fileName: + case patternlab.patterns[i].subdir + '/' + patternlab.patterns[i].fileName + '.mustache': return patternlab.patterns[i]; - } } - throw 'Could not find pattern with key ' + key; } - function mergeData(obj1, obj2){ - if(typeof obj2 === 'undefined'){ - obj2 = {}; + //return the fuzzy match if all else fails + for (i = 0; i < patternlab.patterns.length; i++) { + var keyParts = key.split('-'), + keyType = keyParts[0], + keyName = keyParts.slice(1).join('-'); + + if (patternlab.patterns[i].key.split('-')[0] === keyType && patternlab.patterns[i].key.indexOf(keyName) > -1) { + return patternlab.patterns[i]; } - for(var p in obj1){ - try { - // Only recurse if obj1[p] is an object. - if(obj1[p].constructor === Object){ - // Requires 2 objects as params; create obj2[p] if undefined. - if(typeof obj2[p] === 'undefined'){ - obj2[p] = {}; - } - obj2[p] = mergeData(obj1[p], obj2[p]); + } + throw 'Could not find pattern with key ' + key; + } + + function mergeData(obj1, obj2) { + /*eslint-disable guard-for-in, no-param-reassign*/ + if (typeof obj2 === 'undefined') { + obj2 = {}; + } + for (var p in obj1) { + try { + // Only recurse if obj1[p] is an object. + if (obj1[p].constructor === Object) { + // Requires 2 objects as params; create obj2[p] if undefined. + if (typeof obj2[p] === 'undefined') { + obj2[p] = {}; + } + obj2[p] = mergeData(obj1[p], obj2[p]); + // Pop when recursion meets a non-object. If obj1[p] is a non-object, // only copy to undefined obj2[p]. This way, obj2 maintains priority. - } else if(typeof obj2[p] === 'undefined'){ - obj2[p] = obj1[p]; - } - } catch(e) { - // Property in destination object not set; create it and set its value. - if(typeof obj2[p] === 'undefined'){ - obj2[p] = obj1[p]; - } + } else if (typeof obj2[p] === 'undefined') { + obj2[p] = obj1[p]; + } + } catch (e) { + // Property in destination object not set; create it and set its value. + if (typeof obj2[p] === 'undefined') { + obj2[p] = obj1[p]; } } - return obj2; } - - function buildListItems(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]); - } + return obj2; + } + + function buildListItems(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.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; - } else{ - for(var c = 1; c <= i; c++){ - tempItems.push(container.listItemArray[c - 1]); - container.listitems['' + i ] = tempItems; - } } } } - - //http://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array-in-javascript - function shuffle(o){ - for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x); - return o; - } - - function parseDataLinksHelper (patternlab, obj, key) { - var linkRE, dataObjAsString, linkMatches, expandedLink; - - linkRE = /link\.[A-z0-9-_]+/g - dataObjAsString = JSON.stringify(obj); - linkMatches = dataObjAsString.match(linkRE) - - if(linkMatches) { - for (var i = 0; i < linkMatches.length; i++) { - expandedLink = patternlab.data.link[linkMatches[i].split('.')[1]]; - if (expandedLink) { - if(patternlab.config.debug){ - console.log('expanded data link from ' + linkMatches[i] + ' to ' + expandedLink + ' inside ' + key); - } - dataObjAsString = dataObjAsString.replace(linkMatches[i], expandedLink); + } + + //http://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array-in-javascript + function shuffle(o) { + /*eslint-disable curly*/ + for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x); + return o; + } + + function parseDataLinksHelper(patternlab, obj, key) { + var linkRE, dataObjAsString, linkMatches, expandedLink; + + linkRE = /link\.[A-z0-9-_]+/g; + dataObjAsString = JSON.stringify(obj); + linkMatches = dataObjAsString.match(linkRE); + + if (linkMatches) { + for (var i = 0; i < linkMatches.length; i++) { + expandedLink = patternlab.data.link[linkMatches[i].split('.')[1]]; + if (expandedLink) { + if (patternlab.config.debug) { + console.log('expanded data link from ' + linkMatches[i] + ' to ' + expandedLink + ' inside ' + key); } + dataObjAsString = dataObjAsString.replace(linkMatches[i], expandedLink); } } - return JSON.parse(dataObjAsString) } - //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) { - //look for link.* such as link.pages-blog as a value - - patternlab.data = parseDataLinksHelper(patternlab, patternlab.data, 'data.json') - - //loop through all patterns - for (var i = 0; i < patternlab.patterns.length; i++) { - patternlab.patterns[i].jsonFileData = parseDataLinksHelper(patternlab, patternlab.patterns[i].jsonFileData, patternlab.patterns[i].key) - } + return JSON.parse(dataObjAsString); + } + + //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) { + //look for link.* such as link.pages-blog as a value + + patternlab.data = parseDataLinksHelper(patternlab, patternlab.data, 'data.json'); + + //loop through all patterns + for (var i = 0; i < patternlab.patterns.length; i++) { + patternlab.patterns[i].jsonFileData = parseDataLinksHelper(patternlab, patternlab.patterns[i].jsonFileData, patternlab.patterns[i].key); } + } + + return { + find_pattern_partials: function (pattern) { + return findPartials(pattern); + }, + find_pattern_partials_with_style_modifiers: function (pattern) { + return findPartialsWithStyleModifiers(pattern); + }, + find_pattern_partials_with_parameters: function (pattern) { + return findPartialsWithPatternParameters(pattern); + }, + find_list_items: function (pattern) { + return findListItems(pattern); + }, + setPatternState: function (pattern, patternlab) { + setState(pattern, patternlab); + }, + addPattern: function (pattern, patternlab) { + addPattern(pattern, patternlab); + }, + renderPattern: function (template, data, partials) { + return renderPattern(template, data, partials); + }, + process_pattern_iterative: function (file, patternlab) { + processPatternIterative(file, patternlab); + }, + process_pattern_recursive: function (file, patternlab, additionalData) { + processPatternRecursive(file, patternlab, additionalData); + }, + get_pattern_by_key: function (key, patternlab) { + return getpatternbykey(key, patternlab); + }, + merge_data: function (existingData, newData) { + return mergeData(existingData, newData); + }, + combine_listItems: function (patternlab) { + buildListItems(patternlab); + }, + is_object_empty: function (obj) { + return isObjectEmpty(obj); + }, + parse_data_links: function (patternlab) { + parseDataLinks(patternlab); + } + }; - return { - find_pattern_partials: function(pattern){ - return findPartials(pattern); - }, - find_pattern_partials_with_style_modifiers: function(pattern){ - return findPartialsWithStyleModifiers(pattern); - }, - find_pattern_partials_with_parameters: function(pattern){ - return findPartialsWithPatternParameters(pattern); - }, - find_list_items: function(pattern){ - return findListItems(pattern) - }, - setPatternState: function(pattern, patternlab){ - setState(pattern, patternlab); - }, - addPattern: function(pattern, patternlab){ - addPattern(pattern, patternlab); - }, - renderPattern: function(template, data, partials){ - return renderPattern(template, data, partials); - }, - process_pattern_iterative: function(file, patternlab){ - processPatternIterative(file, patternlab); - }, - process_pattern_recursive: function(file, patternlab, additionalData){ - processPatternRecursive(file, patternlab, additionalData); - }, - get_pattern_by_key: function(key, patternlab){ - return getpatternbykey(key, patternlab); - }, - merge_data: function(existingData, newData){ - return mergeData(existingData, newData); - }, - combine_listItems: function(patternlab){ - buildListItems(patternlab); - }, - is_object_empty: function(obj){ - return isObjectEmpty(obj); - }, - parse_data_links: function(patternlab){ - parseDataLinks(patternlab); - } - }; +}; - }; +module.exports = pattern_assembler; - module.exports = pattern_assembler; -}()); From d2ff6ea4c1fc1d93c9db5a220695bce8c7957a7c Mon Sep 17 00:00:00 2001 From: New Geoff Date: Sat, 27 Feb 2016 15:40:40 -0600 Subject: [PATCH 07/17] most of the rest of the builder JS, reformatted --- builder/pattern_exporter.js | 51 ++++---- builder/patternlab.js | 197 +++++++++++++++---------------- builder/patternlab_grunt.js | 50 ++++---- builder/patternlab_gulp.js | 13 +- builder/pseudopattern_hunter.js | 139 +++++++++++----------- builder/style_modifier_hunter.js | 54 ++++----- 6 files changed, 240 insertions(+), 264 deletions(-) diff --git a/builder/pattern_exporter.js b/builder/pattern_exporter.js index 3d04658d3..a7a70c05b 100644 --- a/builder/pattern_exporter.js +++ b/builder/pattern_exporter.js @@ -8,38 +8,33 @@ * */ -(function () { - "use strict"; - - var fs = require('fs-extra'), - path = require('path'); - - var pattern_exporter = function(){ - - function exportPatterns(patternlab){ - - //read the config export options - var exportKeys = patternlab.config.patternExportKeys; - - //find the chosen patterns to export - for (var i = 0; i < exportKeys.length; i++){ - for (var j = 0; j < patternlab.patterns.length; j++){ - if(exportKeys[i] === patternlab.patterns[j].key){ - //write matches to the desired location - fs.outputFileSync(patternlab.config.patternExportDirectory + patternlab.patterns[j].key + '.html', patternlab.patterns[j].patternPartial); - } +"use strict"; + +var fs = require('fs-extra'); + +var pattern_exporter = function () { + + function exportPatterns(patternlab) { + //read the config export options + var exportKeys = patternlab.config.patternExportKeys; + + //find the chosen patterns to export + for (var i = 0; i < exportKeys.length; i++) { + for (var j = 0; j < patternlab.patterns.length; j++) { + if (exportKeys[i] === patternlab.patterns[j].key) { + //write matches to the desired location + fs.outputFileSync(patternlab.config.patternExportDirectory + patternlab.patterns[j].key + '.html', patternlab.patterns[j].patternPartial); } } } + } - return { - export_patterns: function(patternlab){ - exportPatterns(patternlab); - } - }; - + return { + export_patterns: function (patternlab) { + exportPatterns(patternlab); + } }; - module.exports = pattern_exporter; +}; -}()); +module.exports = pattern_exporter; diff --git a/builder/patternlab.js b/builder/patternlab.js index aae791f23..d1745567b 100644 --- a/builder/patternlab.js +++ b/builder/patternlab.js @@ -12,17 +12,14 @@ var patternlab_engine = function (config) { 'use strict'; var path = require('path'), - fs = require('fs-extra'), - extend = require('util')._extend, - diveSync = require('diveSync'), - mustache = require('mustache'), - glob = require('glob'), - of = require('./object_factory'), - pa = require('./pattern_assembler'), - mh = require('./media_hunter'), - pe = require('./pattern_exporter'), - he = require('html-entities').AllHtmlEntities, - patternlab = {}; + fs = require('fs-extra'), + diveSync = require('diveSync'), + of = require('./object_factory'), + pa = require('./pattern_assembler'), + mh = require('./media_hunter'), + pe = require('./pattern_exporter'), + he = require('html-entities').AllHtmlEntities, + patternlab = {}; patternlab.package = fs.readJSONSync('./package.json'); patternlab.config = config || fs.readJSONSync(path.resolve(__dirname, '../config.json')); @@ -34,7 +31,7 @@ var patternlab_engine = function (config) { console.log(patternlab.package.version); } - function help(){ + function help() { console.log('Patternlab Node Help'); console.log('==============================='); console.log('Command Line Arguments'); @@ -51,13 +48,13 @@ var patternlab_engine = function (config) { function printDebug() { //debug file can be written by setting flag on config.json - if(patternlab.config.debug){ + if (patternlab.config.debug) { console.log('writing patternlab debug file to ./patternlab.json'); fs.outputFileSync('./patternlab.json', JSON.stringify(patternlab, null, 3)); } } - function buildPatterns(deletePatternDir){ + function buildPatterns(deletePatternDir) { patternlab.data = fs.readJSONSync(path.resolve(paths.source.data, 'data.json')); patternlab.listitems = fs.readJSONSync(path.resolve(paths.source.data, 'listitems.json')); patternlab.header = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'pattern-header-footer/header.html'), 'utf8'); @@ -67,47 +64,52 @@ var patternlab_engine = function (config) { patternlab.data.link = {}; var pattern_assembler = new pa(), - entity_encoder = new he(), - pattern_exporter = new pe(), - patterns_dir = paths.source.patterns; + entity_encoder = new he(), + pattern_exporter = new pe(), + patterns_dir = paths.source.patterns; pattern_assembler.combine_listItems(patternlab); //diveSync once to perform iterative populating of patternlab object - diveSync(patterns_dir, { - filter: function(path, dir) { - if(dir){ - var remainingPath = path.replace(patterns_dir, ''); - var isValidPath = remainingPath.indexOf('/_') === -1; - return isValidPath; - } + diveSync( + patterns_dir, + { + filter: function (filePath, dir) { + if (dir) { + var remainingPath = filePath.replace(patterns_dir, ''); + var isValidPath = remainingPath.indexOf('/_') === -1; + return isValidPath; + } return true; } }, - function(err, file){ + function (err, file) { //log any errors - if(err){ + if (err) { console.log(err); return; } pattern_assembler.process_pattern_iterative(path.resolve(file), patternlab); - }); + } + ); //diveSync again to recursively include partials, filling out the //extendedTemplate property of the patternlab.patterns elements - diveSync(patterns_dir, { - filter: function(path, dir) { - if(dir){ - var remainingPath = path.replace(patterns_dir, ''); - var isValidPath = remainingPath.indexOf('/_') === -1; - return isValidPath; - } + diveSync( + patterns_dir, + { + filter: function (filePath, dir) { + if (dir) { + var remainingPath = filePath.replace(patterns_dir, ''); + var isValidPath = remainingPath.indexOf('/_') === -1; + return isValidPath; + } return true; } }, - function(err, file){ + function (err, file) { //log any errors - if(err){ + if (err) { console.log(err); return; } @@ -120,15 +122,15 @@ var patternlab_engine = function (config) { pattern_assembler.parse_data_links(patternlab); //delete the contents of config.patterns.public before writing - if(deletePatternDir){ + if (deletePatternDir) { fs.emptyDirSync(paths.public.patterns); } //render all patterns last, so lineageR works - patternlab.patterns.forEach(function(pattern, index, patterns){ + patternlab.patterns.forEach(function (pattern) { //render the pattern, but first consolidate any data we may have - var allData = JSON.parse(JSON.stringify(patternlab.data)); + var allData = JSON.parse(JSON.stringify(patternlab.data)); allData = pattern_assembler.merge_data(allData, pattern.jsonFileData); //render the extendedTemplate with all data @@ -149,27 +151,25 @@ var patternlab_engine = function (config) { //export patterns if necessary pattern_exporter.export_patterns(patternlab); - } - function buildFrontEnd(){ + function buildFrontEnd() { var pattern_assembler = new pa(), media_hunter = new mh(), styleGuideExcludes = patternlab.config.styleGuideExcludes, - styleguidePatterns = []; + styleguidePatterns = [], + i; // for loops + patternlab.buckets = []; patternlab.bucketIndex = []; patternlab.patternPaths = {}; patternlab.viewAllPaths = {}; //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; - } + 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; }); @@ -179,41 +179,41 @@ var patternlab_engine = function (config) { // check if patterns are excluded, if not add them to styleguidePatterns if (styleGuideExcludes && styleGuideExcludes.length) { - for (i = 0; i < patternlab.patterns.length; i++) { + for (i = 0; i < patternlab.patterns.length; i++) { - // skip underscore-prefixed files - if(isPatternExcluded(patternlab.patterns[i])){ - if(patternlab.config.debug){ - console.log('Omitting ' + patternlab.patterns[i].key + " from styleguide pattern exclusion."); - } - continue; + // skip underscore-prefixed files + if (isPatternExcluded(patternlab.patterns[i])) { + if (patternlab.config.debug) { + console.log('Omitting ' + patternlab.patterns[i].key + " from styleguide pattern exclusion."); } + continue; + } - var key = patternlab.patterns[i].key; - var typeKey = key.substring(0, key.indexOf('-')); - var isExcluded = (styleGuideExcludes.indexOf(typeKey) > -1); - if (!isExcluded) { - styleguidePatterns.push(patternlab.patterns[i]); - } + var key = patternlab.patterns[i].key; + var typeKey = key.substring(0, key.indexOf('-')); + var isExcluded = (styleGuideExcludes.indexOf(typeKey) > -1); + if (!isExcluded) { + styleguidePatterns.push(patternlab.patterns[i]); } + } } else { styleguidePatterns = patternlab.patterns; } //build the styleguide var styleguideTemplate = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'styleguide.mustache'), 'utf8'), - styleguideHtml = pattern_assembler.renderPattern(styleguideTemplate, {partials: styleguidePatterns}); + styleguideHtml = pattern_assembler.renderPattern(styleguideTemplate, {partials: styleguidePatterns}); + fs.outputFileSync(path.resolve(paths.public.styleguide, 'html/styleguide.html'), styleguideHtml); //build the viewall pages var prevSubdir = '', - prevGroup = '', - i; + prevGroup = ''; for (i = 0; i < patternlab.patterns.length; i++) { // skip underscore-prefixed files - if(isPatternExcluded(patternlab.patterns[i])){ - if(patternlab.config.debug){ + if (isPatternExcluded(patternlab.patterns[i])) { + if (patternlab.config.debug) { console.log('Omitting ' + patternlab.patterns[i].key + " from view all rendering."); } continue; @@ -223,7 +223,7 @@ var patternlab_engine = function (config) { //create the view all for the section // check if the current section is different from the previous one - if (pattern.patternGroup != prevGroup){ + if (pattern.patternGroup !== prevGroup) { prevGroup = pattern.patternGroup; var viewAllPatterns = [], @@ -233,8 +233,8 @@ var patternlab_engine = function (config) { for (j = 0; j < patternlab.patterns.length; j++) { if (patternlab.patterns[j].patternGroup === pattern.patternGroup) { //again, skip any sibling patterns to the current one that may have underscores - if(isPatternExcluded(patternlab.patterns[j])){ - if(patternlab.config.debug){ + if (isPatternExcluded(patternlab.patterns[j])) { + if (patternlab.config.debug) { console.log('Omitting ' + patternlab.patterns[j].key + " from view all sibling rendering."); } continue; @@ -249,25 +249,24 @@ var patternlab_engine = function (config) { fs.outputFileSync(paths.public.patterns + pattern.subdir.slice(0, pattern.subdir.indexOf(pattern.patternGroup) + pattern.patternGroup.length) + '/index.html', viewAllHtml); } - //create the view all for the subsection + // create the view all for the subsection // check if the current sub section is different from the previous one if (pattern.subdir !== prevSubdir) { prevSubdir = pattern.subdir; var viewAllPatterns = [], - patternPartial = "viewall-" + pattern.patternGroup + "-" + pattern.patternSubGroup, - j; + patternPartial = "viewall-" + pattern.patternGroup + "-" + pattern.patternSubGroup, + j; for (j = 0; j < patternlab.patterns.length; j++) { if (patternlab.patterns[j].subdir === pattern.subdir) { //again, skip any sibling patterns to the current one that may have underscores - if(isPatternExcluded(patternlab.patterns[j])){ - if(patternlab.config.debug){ + if (isPatternExcluded(patternlab.patterns[j])) { + if (patternlab.config.debug) { console.log('Omitting ' + patternlab.patterns[j].key + " from view all sibling rendering."); } continue; } - viewAllPatterns.push(patternlab.patterns[j]); } } @@ -283,17 +282,17 @@ var patternlab_engine = function (config) { //loop through all patterns.to build the navigation //todo: refactor this someday - for(var i = 0; i < patternlab.patterns.length; i++){ + for (i = 0; i < patternlab.patterns.length; i++) { var pattern = patternlab.patterns[i]; var bucketName = pattern.name.replace(/\\/g, '-').split('-')[1]; //check if the bucket already exists var bucketIndex = patternlab.bucketIndex.indexOf(bucketName); - if(bucketIndex === -1){ + if (bucketIndex === -1) { // skip underscore-prefixed files. don't create a bucket on account of an underscored pattern - if(isPatternExcluded(pattern)){ + if (isPatternExcluded(pattern)) { continue; } @@ -313,7 +312,7 @@ var patternlab_engine = function (config) { //test whether the pattern struture is flat or not - usually due to a template or page var flatPatternItem = false; - if(navItemName === bucketName){ + if (navItemName === bucketName) { flatPatternItem = true; } @@ -331,15 +330,13 @@ var patternlab_engine = function (config) { } //if it is flat - we should not add the pattern to patternPaths - if(flatPatternItem){ - + if (flatPatternItem) { bucket.patternItems.push(navSubItem); //add to patternPaths addToPatternPaths(bucketName, pattern); - } else{ - + } else { bucket.navItems.push(navItem); bucket.navItemsIndex.push(navItemName); navItem.navSubItems.push(navSubItem); @@ -355,7 +352,6 @@ var patternlab_engine = function (config) { bucket.patternItems.push(navViewAllItem); patternlab.viewAllPaths[bucketName]['viewall'] = pattern.subdir.slice(0, pattern.subdir.indexOf(pattern.patternGroup) + pattern.patternGroup.length); - } //add the bucket. @@ -364,7 +360,7 @@ var patternlab_engine = function (config) { //done - } else{ + } else { //find the bucket var bucket = patternlab.buckets[bucketIndex]; @@ -383,21 +379,21 @@ var patternlab_engine = function (config) { navSubItem.patternPartial = bucketName + "-" + pattern.patternName; //add the hyphenated name //add the patternState if it exists - if(pattern.patternState){ + if (pattern.patternState) { navSubItem.patternState = pattern.patternState; } //test whether the pattern struture is flat or not - usually due to a template or page var flatPatternItem = false; - if(navItemName === bucketName){ + if (navItemName === bucketName) { flatPatternItem = true; } //if it is flat - we should not add the pattern to patternPaths - if(flatPatternItem){ + if (flatPatternItem) { // skip underscore-prefixed files - if(isPatternExcluded(pattern)){ + if (isPatternExcluded(pattern)) { continue; } @@ -407,14 +403,13 @@ var patternlab_engine = function (config) { //add to patternPaths addToPatternPaths(bucketName, pattern); - } else{ + } else { // only do this if pattern is included - if(!isPatternExcluded(pattern)){ + if (!isPatternExcluded(pattern)) { //check to see if navItem exists var navItemIndex = bucket.navItemsIndex.indexOf(navItemName); - if(navItemIndex === -1){ - + if (navItemIndex === -1) { var navItem = new of.oNavItem(navItemName); //add the navItem and navSubItem @@ -423,7 +418,7 @@ var patternlab_engine = function (config) { bucket.navItems.push(navItem); bucket.navItemsIndex.push(navItemName); - } else{ + } else { //add the navSubItem var navItem = bucket.navItems[navItemIndex]; navItem.navSubItems.push(navSubItem); @@ -482,30 +477,30 @@ var patternlab_engine = function (config) { fs.outputFileSync(path.resolve(paths.public.root, 'index.html'), patternlabSiteHtml); } - function addToPatternPaths(bucketName, pattern){ + function addToPatternPaths(bucketName, pattern) { //this is messy, could use a refactor. patternlab.patternPaths[bucketName][pattern.patternName] = pattern.subdir.replace(/\\/g, '/') + "/" + pattern.fileName; } //todo: refactor this as a method on the pattern object itself once we merge dev with pattern-engines branch - function isPatternExcluded(pattern){ + function isPatternExcluded(pattern) { // returns whether or not the first character of the pattern filename is an underscore, or excluded return pattern.fileName.charAt(0) === '_'; } return { - version: function(){ + version: function () { return getVersion(); }, - build: function(deletePatternDir){ + build: function (deletePatternDir) { buildPatterns(deletePatternDir); buildFrontEnd(); printDebug(); }, - help: function(){ + help: function () { help(); }, - build_patterns_only: function(deletePatternDir){ + build_patterns_only: function (deletePatternDir) { buildPatterns(deletePatternDir); printDebug(); } diff --git a/builder/patternlab_grunt.js b/builder/patternlab_grunt.js index 93b50b1e7..69085c291 100644 --- a/builder/patternlab_grunt.js +++ b/builder/patternlab_grunt.js @@ -10,31 +10,29 @@ var patternlab_engine = require('./patternlab.js'); -module.exports = function(grunt) { - grunt.registerTask('patternlab', 'create design systems with atomic design', function(arg) { - - var patternlab = patternlab_engine(); - - if(arguments.length === 0){ - patternlab.build(true); - } - - if(arg && arg === 'v'){ - patternlab.version(); - } - - if(arg && arg === "only_patterns"){ - patternlab.build_patterns_only(true); - } - - if(arg && arg === "help"){ - patternlab.help(); - } - - if(arg && (arg !== "v" && arg !=="only_patterns" && arg !=="help")){ - patternlab.help(); - } - - }); +module.exports = function (grunt) { + grunt.registerTask('patternlab', 'create design systems with atomic design', function (arg) { + var patternlab = patternlab_engine(); + + if (arguments.length === 0) { + patternlab.build(true); + } + + if (arg && arg === 'v') { + patternlab.version(); + } + + if (arg && arg === "only_patterns") { + patternlab.build_patterns_only(true); + } + + if (arg && arg === "help") { + patternlab.help(); + } + + if (arg && (arg !== "v" && arg !== "only_patterns" && arg !== "help")) { + patternlab.help(); + } + }); }; diff --git a/builder/patternlab_gulp.js b/builder/patternlab_gulp.js index e036b1bb5..291940b30 100644 --- a/builder/patternlab_gulp.js +++ b/builder/patternlab_gulp.js @@ -10,27 +10,26 @@ var patternlab_engine = require('./patternlab.js'); -module.exports = function(gulp) { - - gulp.task('patternlab', ['clean'], function(cb){ +module.exports = function (gulp) { + + gulp.task('patternlab', ['clean'], function (cb) { var patternlab = patternlab_engine(); patternlab.build(false); cb(); }); - gulp.task('patternlab:version', function(){ + gulp.task('patternlab:version', function () { var patternlab = patternlab_engine(); patternlab.version(); }); - gulp.task('patternlab:only_patterns', ['clean'], function(){ + gulp.task('patternlab:only_patterns', ['clean'], function () { var patternlab = patternlab_engine(); patternlab.build_patterns_only(false); }); - gulp.task('patternlab:help', function(){ + gulp.task('patternlab:help', function () { var patternlab = patternlab_engine(); patternlab.help(); }); - }; diff --git a/builder/pseudopattern_hunter.js b/builder/pseudopattern_hunter.js index 77773040e..0f0907ea1 100644 --- a/builder/pseudopattern_hunter.js +++ b/builder/pseudopattern_hunter.js @@ -8,76 +8,69 @@ * */ -(function () { - "use strict"; - - var pseudopattern_hunter = function(){ - - function findpseudopatterns(currentPattern, patternlab){ - - var glob = require('glob'), - fs = require('fs-extra'), - pa = require('./pattern_assembler'), - lh = require('./lineage_hunter'), - of = require('./object_factory'), - path = require('path'); - - var pattern_assembler = new pa(); - var lineage_hunter = new lh(); - var paths = patternlab.config.paths; - - //look for a pseudo pattern by checking if there is a file containing same name, with ~ in it, ending in .json - var needle = currentPattern.subdir + '/' + currentPattern.fileName + '~*.json'; - var pseudoPatterns = glob.sync(needle, { - cwd: paths.source.patterns, - debug: false, - nodir: true, - }); - - if(pseudoPatterns.length > 0){ - - for(var i = 0; i < pseudoPatterns.length; i++){ - - if(patternlab.config.debug){ - console.log('found pseudoPattern variant of ' + currentPattern.key); - } - - //we want to do everything we normally would here, except instead read the pseudoPattern data - var variantFileData = fs.readJSONSync(path.resolve(paths.source.patterns, pseudoPatterns[i])); - - //extend any existing data with variant data - variantFileData = pattern_assembler.merge_data(currentPattern.jsonFileData, variantFileData); - - var variantName = pseudoPatterns[i].substring(pseudoPatterns[i].indexOf('~') + 1).split('.')[0]; - var variantFilePath = path.resolve(paths.source.patterns, currentPattern.subdir, currentPattern.fileName + '~' + variantName + '.json'); - var variantFileName = currentPattern.fileName + '-' + variantName + '.'; - var patternVariant = new of.oPattern(variantFilePath, currentPattern.subdir, variantFileName, variantFileData); - - //see if this file has a state - pattern_assembler.setPatternState(patternVariant, patternlab); - - //use the same template as the non-variant - patternVariant.template = currentPattern.template; - patternVariant.extendedTemplate = currentPattern.extendedTemplate; - - //find pattern lineage - lineage_hunter.find_lineage(patternVariant, patternlab); - - //add to patternlab object so we can look these up later. - pattern_assembler.addPattern(patternVariant, patternlab); - } - } - - } - - return { - find_pseudopatterns: function(pattern, patternlab){ - findpseudopatterns(pattern, patternlab); - } - }; - - }; - - module.exports = pseudopattern_hunter; - -}()); +"use strict"; + +var pseudopattern_hunter = function () { + + function findpseudopatterns(currentPattern, patternlab) { + var glob = require('glob'), + fs = require('fs-extra'), + pa = require('./pattern_assembler'), + lh = require('./lineage_hunter'), + of = require('./object_factory'), + path = require('path'); + + var pattern_assembler = new pa(); + var lineage_hunter = new lh(); + var paths = patternlab.config.paths; + + //look for a pseudo pattern by checking if there is a file containing same name, with ~ in it, ending in .json + var needle = currentPattern.subdir + '/' + currentPattern.fileName + '~*.json'; + var pseudoPatterns = glob.sync(needle, { + cwd: paths.source.patterns, + debug: false, + nodir: true + }); + + if (pseudoPatterns.length > 0) { + for (var i = 0; i < pseudoPatterns.length; i++) { + if (patternlab.config.debug) { + console.log('found pseudoPattern variant of ' + currentPattern.key); + } + + //we want to do everything we normally would here, except instead read the pseudoPattern data + var variantFileData = fs.readJSONSync(path.resolve(paths.source.patterns, pseudoPatterns[i])); + + //extend any existing data with variant data + variantFileData = pattern_assembler.merge_data(currentPattern.jsonFileData, variantFileData); + + var variantName = pseudoPatterns[i].substring(pseudoPatterns[i].indexOf('~') + 1).split('.')[0]; + var variantFilePath = path.resolve(paths.source.patterns, currentPattern.subdir, currentPattern.fileName + '~' + variantName + '.json'); + var variantFileName = currentPattern.fileName + '-' + variantName + '.'; + var patternVariant = new of.oPattern(variantFilePath, currentPattern.subdir, variantFileName, variantFileData); + + //see if this file has a state + pattern_assembler.setPatternState(patternVariant, patternlab); + + //use the same template as the non-variant + patternVariant.template = currentPattern.template; + patternVariant.extendedTemplate = currentPattern.extendedTemplate; + + //find pattern lineage + lineage_hunter.find_lineage(patternVariant, patternlab); + + //add to patternlab object so we can look these up later. + pattern_assembler.addPattern(patternVariant, patternlab); + } + } + } + + return { + find_pseudopatterns: function (pattern, patternlab) { + findpseudopatterns(pattern, patternlab); + } + }; + +}; + +module.exports = pseudopattern_hunter; diff --git a/builder/style_modifier_hunter.js b/builder/style_modifier_hunter.js index a19fbf081..b9b616b86 100644 --- a/builder/style_modifier_hunter.js +++ b/builder/style_modifier_hunter.js @@ -8,40 +8,36 @@ * */ -(function () { - "use strict"; + "use strict"; - var style_modifier_hunter = function(){ + var style_modifier_hunter = function () { - function consumestylemodifier(pattern, partial, patternlab){ + function consumestylemodifier(pattern, partial, patternlab) { + //extract the classname from the stylemodifier which comes in the format of :className + var styleModifier = partial.match(/:([\w\-_|])+/g) ? partial.match(/:([\w\-_|])+/g)[0].slice(1) : null; + + if (styleModifier) { + //replace the special character pipe | used to separate multiple classes with a space + styleModifier = styleModifier.replace(/\|/g, ' '); - //extract the classname from the stylemodifier which comes in the format of :className - var styleModifier = partial.match(/:([\w\-_|])+/g) ? partial.match(/:([\w\-_|])+/g)[0].slice(1) : null; - if(styleModifier){ + if (patternlab.config.debug) { + console.log('found partial styleModifier within pattern ' + pattern.key); + } - //replace the special character pipe | used to separate multiple classes with a space - styleModifier = styleModifier.replace(/\|/g, ' '); + //replace the stylemodifier placeholder with the class name + pattern.extendedTemplate = pattern.extendedTemplate.replace(/{{[ ]?styleModifier[ ]?}}/i, styleModifier); - if(patternlab.config.debug){ - console.log('found partial styleModifier within pattern ' + pattern.key); - } + //update the extendedTemplate in the partials object in case this pattern is consumed later + patternlab.partials[pattern.key] = pattern.extendedTemplate; + } + } - //replace the stylemodifier placeholder with the class name - pattern.extendedTemplate = pattern.extendedTemplate.replace(/{{[ ]?styleModifier[ ]?}}/i, styleModifier); + return { + consume_style_modifier: function (pattern, partial, patternlab) { + consumestylemodifier(pattern, partial, patternlab); + } + }; - //update the extendedTemplate in the partials object in case this pattern is consumed later - patternlab.partials[pattern.key] = pattern.extendedTemplate; - } - } + }; - return { - consume_style_modifier: function(pattern, partial, patternlab){ - consumestylemodifier(pattern, partial, patternlab); - } - }; - - }; - - module.exports = style_modifier_hunter; - -}()); + module.exports = style_modifier_hunter; From 7863fefa7f6e22046f126adfc1198417f7d41835 Mon Sep 17 00:00:00 2001 From: New Geoff Date: Sat, 27 Feb 2016 15:50:24 -0600 Subject: [PATCH 08/17] config and task runner cleanup --- Gruntfile.js | 300 +++++++++++++++++++++++++-------------------------- config.json | 54 +++++----- gulpfile.js | 37 +++---- 3 files changed, 196 insertions(+), 195 deletions(-) diff --git a/Gruntfile.js b/Gruntfile.js index 06c6cf6d2..51452919f 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -1,161 +1,161 @@ -module.exports = function(grunt) { +module.exports = function (grunt) { - var path = require('path'); + var path = require('path'); - // Project configuration. - grunt.initConfig({ - pkg: grunt.file.readJSON('package.json'), - concat: { - options: { - stripBanners: true, - banner: '/* \n * <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("yyyy") %> \n * \n * <%= pkg.author %>, and the web community.\n * Licensed under the <%= pkg.license %> license. \n * \n * Many thanks to Brad Frost and Dave Olsen for inspiration, encouragement, and advice. \n *\n */\n\n', - }, - patternlab: { - src: './builder/patternlab.js', - dest: './builder/patternlab.js' - }, - object_factory: { - src: './builder/object_factory.js', - dest: './builder/object_factory.js' - }, - lineage: { - src: './builder/lineage_hunter.js', - dest: './builder/lineage_hunter.js' - }, - media_hunter: { - src: './builder/media_hunter.js', - dest: './builder/media_hunter.js' - }, - patternlab_grunt: { - src: './builder/patternlab_grunt.js', - dest: './builder/patternlab_grunt.js' - }, - patternlab_gulp: { - src: './builder/patternlab_gulp.js', - dest: './builder/patternlab_gulp.js' - }, - parameter_hunter: { - src: './builder/parameter_hunter.js', - dest: './builder/parameter_hunter.js' - }, - pattern_exporter: { - src: './builder/pattern_exporter.js', - dest: './builder/pattern_exporter.js' - }, - pattern_assembler: { - src: './builder/pattern_assembler.js', - dest: './builder/pattern_assembler.js' - }, - pseudopattern_hunter: { - src: './builder/pseudopattern_hunter.js', - dest: './builder/pseudopattern_hunter.js' - }, - list_item_hunter: { - src: './builder/list_item_hunter.js', - dest: './builder/list_item_hunter.js' - }, - style_modifier_hunter: { - src: './builder/style_modifier_hunter.js', - dest: './builder/style_modifier_hunter.js' - } - }, - copy: { - main: { - files: [ - { expand: true, cwd: path.resolve(paths().source.js), src: '*.js', dest: path.resolve(paths().public.js) }, - { expand: true, cwd: path.resolve(paths().source.css), src: '*.css', dest: path.resolve(paths().public.css) }, - { expand: true, cwd: path.resolve(paths().source.images), src: ['**/*.png', '**/*.jpg', '**/*.gif', '**/*.jpeg'], dest: path.resolve(paths().public.images) }, - { expand: true, cwd: path.resolve(paths().source.fonts), src: '*', dest: path.resolve(paths().public.fonts) }, - { expand: true, cwd: path.resolve(paths().source.data), src: 'annotations.js', dest: path.resolve(paths().public.data) } - ] - }, - styleguide: { - files: [ - { expand: true, cwd: path.resolve(paths().source.styleguide), src: ['*.*', '**/*.*'], dest: path.resolve(paths().public.styleguide) } - ] - } - }, - watch: { - all: { - files: [ - path.resolve(paths().source.css + '**/*.css'), - path.resolve(paths().source.styleguide + 'css/*.css'), - path.resolve(paths().source.patterns + '**/*.mustache'), - path.resolve(paths().source.patterns + '**/*.json'), - path.resolve(paths().source.fonts + '/*'), - path.resolve(paths().source.images + '/*'), - path.resolve(paths().source.data + '*.json') - ], - tasks: ['default', 'bsReload:css'] - } - }, - nodeunit: { - all: ['test/*_tests.js'] - }, - browserSync: { - dev: { - options: { - server: path.resolve(paths().public.root), - watchTask: true, - watchOptions: { - ignoreInitial: true, - ignored: '*.html' - }, - snippetOptions: { - // Ignore all HTML files within the templates folder - blacklist: ['/index.html', '/'] - }, - plugins: [ - { - module: 'bs-html-injector', - options: { - files: [path.resolve(paths().public.root + '/index.html'), path.resolve(paths().public.styleguide + '/styleguide.html')] - } - } - ], - notify: { - styles: [ - 'display: none', - 'padding: 15px', - 'font-family: sans-serif', - 'position: fixed', - 'font-size: 1em', - 'z-index: 9999', - 'bottom: 0px', - 'right: 0px', - 'border-top-left-radius: 5px', - 'background-color: #1B2032', - 'opacity: 0.4', - 'margin: 0', - 'color: white', - 'text-align: center' - ] - } - } - } - }, - bsReload: { - css: path.resolve(paths().public.root + '**/*.css') - } - }); + function paths() { + return require('./config.json').paths; + } - function paths () { - return require('./config.json').paths; - } + // Project configuration. + grunt.initConfig({ + pkg: grunt.file.readJSON('package.json'), + concat: { + options: { + stripBanners: true, + banner: '/* \n * <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("yyyy") %> \n * \n * <%= pkg.author %>, and the web community.\n * Licensed under the <%= pkg.license %> license. \n * \n * Many thanks to Brad Frost and Dave Olsen for inspiration, encouragement, and advice. \n *\n */\n\n' + }, + patternlab: { + src: './builder/patternlab.js', + dest: './builder/patternlab.js' + }, + object_factory: { + src: './builder/object_factory.js', + dest: './builder/object_factory.js' + }, + lineage: { + src: './builder/lineage_hunter.js', + dest: './builder/lineage_hunter.js' + }, + media_hunter: { + src: './builder/media_hunter.js', + dest: './builder/media_hunter.js' + }, + patternlab_grunt: { + src: './builder/patternlab_grunt.js', + dest: './builder/patternlab_grunt.js' + }, + patternlab_gulp: { + src: './builder/patternlab_gulp.js', + dest: './builder/patternlab_gulp.js' + }, + parameter_hunter: { + src: './builder/parameter_hunter.js', + dest: './builder/parameter_hunter.js' + }, + pattern_exporter: { + src: './builder/pattern_exporter.js', + dest: './builder/pattern_exporter.js' + }, + pattern_assembler: { + src: './builder/pattern_assembler.js', + dest: './builder/pattern_assembler.js' + }, + pseudopattern_hunter: { + src: './builder/pseudopattern_hunter.js', + dest: './builder/pseudopattern_hunter.js' + }, + list_item_hunter: { + src: './builder/list_item_hunter.js', + dest: './builder/list_item_hunter.js' + }, + style_modifier_hunter: { + src: './builder/style_modifier_hunter.js', + dest: './builder/style_modifier_hunter.js' + } + }, + copy: { + main: { + files: [ + { expand: true, cwd: path.resolve(paths().source.js), src: '*.js', dest: path.resolve(paths().public.js) }, + { expand: true, cwd: path.resolve(paths().source.css), src: '*.css', dest: path.resolve(paths().public.css) }, + { expand: true, cwd: path.resolve(paths().source.images), src: ['**/*.png', '**/*.jpg', '**/*.gif', '**/*.jpeg'], dest: path.resolve(paths().public.images) }, + { expand: true, cwd: path.resolve(paths().source.fonts), src: '*', dest: path.resolve(paths().public.fonts) }, + { expand: true, cwd: path.resolve(paths().source.data), src: 'annotations.js', dest: path.resolve(paths().public.data) } + ] + }, + styleguide: { + files: [ + { expand: true, cwd: path.resolve(paths().source.styleguide), src: ['*.*', '**/*.*'], dest: path.resolve(paths().public.styleguide) } + ] + } + }, + watch: { + all: { + files: [ + path.resolve(paths().source.css + '**/*.css'), + path.resolve(paths().source.styleguide + 'css/*.css'), + path.resolve(paths().source.patterns + '**/*.mustache'), + path.resolve(paths().source.patterns + '**/*.json'), + path.resolve(paths().source.fonts + '/*'), + path.resolve(paths().source.images + '/*'), + path.resolve(paths().source.data + '*.json') + ], + tasks: ['default', 'bsReload:css'] + } + }, + nodeunit: { + all: ['test/*_tests.js'] + }, + browserSync: { + dev: { + options: { + server: path.resolve(paths().public.root), + watchTask: true, + watchOptions: { + ignoreInitial: true, + ignored: '*.html' + }, + snippetOptions: { + // Ignore all HTML files within the templates folder + blacklist: ['/index.html', '/'] + }, + plugins: [ + { + module: 'bs-html-injector', + options: { + files: [path.resolve(paths().public.root + '/index.html'), path.resolve(paths().public.styleguide + '/styleguide.html')] + } + } + ], + notify: { + styles: [ + 'display: none', + 'padding: 15px', + 'font-family: sans-serif', + 'position: fixed', + 'font-size: 1em', + 'z-index: 9999', + 'bottom: 0px', + 'right: 0px', + 'border-top-left-radius: 5px', + 'background-color: #1B2032', + 'opacity: 0.4', + 'margin: 0', + 'color: white', + 'text-align: center' + ] + } + } + } + }, + bsReload: { + css: path.resolve(paths().public.root + '**/*.css') + } + }); - // load all grunt tasks - require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks); + // load all grunt tasks + require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks); - //load the patternlab task - grunt.task.loadTasks('./builder/'); + //load the patternlab task + grunt.task.loadTasks('./builder/'); - grunt.registerTask('default', ['patternlab', 'copy:main', 'copy:styleguide']); + grunt.registerTask('default', ['patternlab', 'copy:main', 'copy:styleguide']); - //travis CI task - grunt.registerTask('travis', ['nodeunit', 'patternlab']); + //travis CI task + grunt.registerTask('travis', ['nodeunit', 'patternlab']); - grunt.registerTask('serve', ['patternlab', 'copy:main', 'copy:styleguide', 'browserSync', 'watch:all']); + grunt.registerTask('serve', ['patternlab', 'copy:main', 'copy:styleguide', 'browserSync', 'watch:all']); - grunt.registerTask('build', ['nodeunit', 'concat']); + grunt.registerTask('build', ['nodeunit', 'concat']); }; diff --git a/config.json b/config.json index 0ca6ef1f0..187e8955d 100644 --- a/config.json +++ b/config.json @@ -22,36 +22,36 @@ "css" : "./public/css" } }, - "styleGuideExcludes": [ - "templates", - "pages" - ], - "ignored-extensions" : ["scss", "DS_Store", "less"], - "ignored-directories" : ["scss"], - "debug": false, - "ishControlsVisible": { - "s": true, - "m": true, - "l": true, - "full": true, - "random": true, - "disco": true, - "hay": true, - "mqs": true, - "find": true, - "views-all": true, - "views-annotations": true, - "views-code": true, - "views-new": true, - "tools-all": true, - "tools-sync": true, - "tools-shortcuts": true, - "tools-docs": true - }, + "styleGuideExcludes": [ + "templates", + "pages" + ], + "ignored-extensions" : ["scss", "DS_Store", "less"], + "ignored-directories" : ["scss"], + "debug": false, + "ishControlsVisible": { + "s": true, + "m": true, + "l": true, + "full": true, + "random": true, + "disco": true, + "hay": true, + "mqs": true, + "find": true, + "views-all": true, + "views-annotations": true, + "views-code": true, + "views-new": true, + "tools-all": true, + "tools-sync": true, + "tools-shortcuts": true, + "tools-docs": true + }, "patternStates": { "homepage-emergency" : "inprogress" }, "patternExportKeys": [], "patternExportDirectory": "./pattern_exports/", "baseurl" : "" - } +} diff --git a/gulpfile.js b/gulpfile.js index fb15e1439..8e93df2b0 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -1,4 +1,5 @@ -// Special thanks to oscar-g (https://github.com/oscar-g) for starting this at https://github.com/oscar-g/patternlab-node/tree/dev-gulp +// Special thanks to oscar-g (https://github.com/oscar-g) for starting this at +// https://github.com/oscar-g/patternlab-node/tree/dev-gulp var pkg = require('./package.json'), gulp = require('gulp'), @@ -20,21 +21,21 @@ var banner = [ '/** ', ' * Many thanks to Brad Frost and Dave Olsen for inspiration, encouragement, and advice.', ' * ', ' **/'].join(eol); -function paths () { +function paths() { return require('./config.json').paths; } //load patternlab-node tasks -gulp.loadTasks(__dirname+'/builder/patternlab_gulp.js'); +gulp.loadTasks(__dirname + '/builder/patternlab_gulp.js'); //clean patterns dir -gulp.task('clean', function(cb){ +gulp.task('clean', function (cb) { del.sync([path.resolve(paths().public.patterns, '*')], {force: true}); cb(); }); //build the banner -gulp.task('banner', function(){ +gulp.task('banner', function () { return gulp.src([ './builder/patternlab.js', './builder/object_factory.js', @@ -50,7 +51,7 @@ gulp.task('banner', function(){ './builder/style_modifier_hunter.js' ]) .pipe(strip_banner()) - .pipe(header( banner, { + .pipe(header(banner, { pkg : pkg, today : new Date().getFullYear() } )) @@ -61,40 +62,40 @@ gulp.task('banner', function(){ // COPY TASKS // JS copy -gulp.task('cp:js', function(){ - return gulp.src('**/*.js', {cwd: path.resolve(paths().source.js)} ) +gulp.task('cp:js', function () { + return gulp.src('**/*.js', {cwd: path.resolve(paths().source.js)}) .pipe(gulp.dest(path.resolve(paths().public.js))); }); // Images copy -gulp.task('cp:img', function(){ +gulp.task('cp:img', function () { return gulp.src( - [ '**/*.gif', '**/*.png', '**/*.jpg', '**/*.jpeg' ], - {cwd: path.resolve(paths().source.images)} ) + ['**/*.gif', '**/*.png', '**/*.jpg', '**/*.jpeg'], + {cwd: path.resolve(paths().source.images)}) .pipe(gulp.dest(path.resolve(paths().public.images))); }); // Fonts copy -gulp.task('cp:font', function(){ +gulp.task('cp:font', function () { return gulp.src('*', {cwd: path.resolve(paths().source.fonts)}) .pipe(gulp.dest(path.resolve(paths().public.fonts))); }); // Data copy -gulp.task('cp:data', function(){ +gulp.task('cp:data', function () { return gulp.src('annotations.js', {cwd: path.resolve(paths().source.data)}) .pipe(gulp.dest(path.resolve(paths().public.data))); }); // CSS Copy -gulp.task('cp:css', function(){ +gulp.task('cp:css', function () { return gulp.src(path.resolve(paths().source.css, 'style.css')) .pipe(gulp.dest(path.resolve(paths().public.css))) .pipe(browserSync.stream()); }); // Styleguide Copy -gulp.task('cp:styleguide', function(){ +gulp.task('cp:styleguide', function () { return gulp.src( ['**/*'], {cwd: path.resolve(paths().source.styleguide)}) @@ -151,13 +152,13 @@ gulp.task('connect', ['lab'], function () { }); //unit test -gulp.task('nodeunit', function(){ +gulp.task('nodeunit', function () { return gulp.src('./test/**/*_tests.js') .pipe(nodeunit()); }); -gulp.task('lab-pipe', ['lab'], function(cb){ +gulp.task('lab-pipe', ['lab'], function (cb) { cb(); browserSync.reload(); }); @@ -166,7 +167,7 @@ gulp.task('default', ['lab']); gulp.task('assets', ['cp:js', 'cp:img', 'cp:font', 'cp:data', 'cp:css', 'cp:styleguide' ]); gulp.task('prelab', ['clean', 'assets']); -gulp.task('lab', ['prelab', 'patternlab'], function(cb){cb();}); +gulp.task('lab', ['prelab', 'patternlab'], function (cb) { cb(); }); gulp.task('patterns', ['patternlab:only_patterns']); gulp.task('serve', ['lab', 'connect']); gulp.task('travis', ['lab', 'nodeunit']); From bf270833e7627c35dc52aef2f0f22fc8389cac2f Mon Sep 17 00:00:00 2001 From: BRIAN MUENZENMEYER Date: Sat, 27 Feb 2016 23:00:29 -0600 Subject: [PATCH 09/17] added eslint to devDependencies. removed dead function --- builder/list_item_hunter.js | 1 - builder/pattern_assembler.js | 32 +++++++++++--------------------- package.gulp.json | 1 + package.json | 3 ++- 4 files changed, 14 insertions(+), 23 deletions(-) diff --git a/builder/list_item_hunter.js b/builder/list_item_hunter.js index 62e8f5538..1474769dd 100644 --- a/builder/list_item_hunter.js +++ b/builder/list_item_hunter.js @@ -8,7 +8,6 @@ * */ - "use strict"; var list_item_hunter = function () { diff --git a/builder/pattern_assembler.js b/builder/pattern_assembler.js index 3fc32d036..72ddf7364 100644 --- a/builder/pattern_assembler.js +++ b/builder/pattern_assembler.js @@ -1,10 +1,10 @@ -/* - * patternlab-node - v1.1.3 - 2016 - * +/* + * patternlab-node - v1.1.3 - 2016 + * * 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. * */ @@ -13,13 +13,6 @@ var pattern_assembler = function () { - function isObjectEmpty(obj) { - for (var prop in obj) { - if (obj.hasOwnProperty(prop)) { return false; } - } - return true; - } - // returns any patterns that match {{> value:mod }} or {{> value:mod(foo:"bar") }} within the pattern function findPartialsWithStyleModifiers(pattern) { var matches = pattern.template.match(/{{>([ ])?([\w\-\.\/~]+)(?!\()(\:[A-Za-z0-9-_|]+)+(?:(| )\(.*)?([ ])?}}/g); @@ -67,7 +60,7 @@ var pattern_assembler = function () { break; } } - + //if the pattern is new, just push to the array if (isNew) { patternlab.patterns.push(pattern); @@ -249,7 +242,7 @@ var pattern_assembler = function () { function getpatternbykey(key, patternlab) { var i; // for the for loops - + //look for exact key matches for (i = 0; i < patternlab.patterns.length; i++) { if (patternlab.patterns[i].key === key) { @@ -271,7 +264,7 @@ var pattern_assembler = function () { var keyParts = key.split('-'), keyType = keyParts[0], keyName = keyParts.slice(1).join('-'); - + if (patternlab.patterns[i].key.split('-')[0] === keyType && patternlab.patterns[i].key.indexOf(keyName) > -1) { return patternlab.patterns[i]; } @@ -293,7 +286,7 @@ var pattern_assembler = function () { obj2[p] = {}; } obj2[p] = mergeData(obj1[p], obj2[p]); - + // Pop when recursion meets a non-object. If obj1[p] is a non-object, // only copy to undefined obj2[p]. This way, obj2 maintains priority. } else if (typeof obj2[p] === 'undefined') { @@ -360,7 +353,7 @@ var pattern_assembler = function () { } return JSON.parse(dataObjAsString); } - + //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) { @@ -411,9 +404,6 @@ var pattern_assembler = function () { combine_listItems: function (patternlab) { buildListItems(patternlab); }, - is_object_empty: function (obj) { - return isObjectEmpty(obj); - }, parse_data_links: function (patternlab) { parseDataLinks(patternlab); } diff --git a/package.gulp.json b/package.gulp.json index 7bdc7cb2c..3f2663854 100644 --- a/package.gulp.json +++ b/package.gulp.json @@ -13,6 +13,7 @@ }, "devDependencies": { "browser-sync": "^2.11.1", + "eslint": "^2.2.0", "gulp": "^3.9.0", "gulp-connect": "^2.3.1", "gulp-copy": "0.0.2", diff --git a/package.json b/package.json index 4cfbf8671..5ea2de257 100644 --- a/package.json +++ b/package.json @@ -13,9 +13,10 @@ }, "devDependencies": { "bs-html-injector": "^3.0.0", + "eslint": "^2.2.0", "grunt": "~0.4.5", - "grunt-contrib-concat": "^0.5.1", "grunt-browser-sync": "^2.2.0", + "grunt-contrib-concat": "^0.5.1", "grunt-contrib-copy": "^0.8.2", "grunt-contrib-nodeunit": "^0.4.1", "grunt-contrib-watch": "^0.6.1" From c7609d7d42cf033f897e723c1bef4730490c30f4 Mon Sep 17 00:00:00 2001 From: BRIAN MUENZENMEYER Date: Sat, 27 Feb 2016 23:26:17 -0600 Subject: [PATCH 10/17] loosen rules on block scope "violations" and redeclares. --- .eslintrc | 4 +- builder/list_item_hunter.js | 3 +- builder/media_hunter.js | 16 ++--- builder/parameter_hunter.js | 24 ++++---- builder/pattern_assembler.js | 112 +++++++++++++++++------------------ builder/patternlab.js | 44 +++++++------- 6 files changed, 102 insertions(+), 101 deletions(-) diff --git a/.eslintrc b/.eslintrc index bcef947ef..3c2d195a1 100644 --- a/.eslintrc +++ b/.eslintrc @@ -5,7 +5,7 @@ }, "globals": {}, "rules": { - "block-scoped-var": 2, + "block-scoped-var": 1, "camelcase": 0, "comma-spacing": [1, {"before": false, "after": true}], "consistent-return": 2, @@ -51,7 +51,7 @@ "no-new": 2, "no-param-reassign": 2, "no-proto": 2, - "no-redeclare": 2, + "no-redeclare": 1, "no-script-url": 2, "no-self-assign": 2, "no-self-compare": 2, diff --git a/builder/list_item_hunter.js b/builder/list_item_hunter.js index 1474769dd..453e3c44b 100644 --- a/builder/list_item_hunter.js +++ b/builder/list_item_hunter.js @@ -17,7 +17,7 @@ var list_item_hunter = function () { smh = require('./style_modifier_hunter'), pattern_assembler = new pa(), style_modifier_hunter = new smh(), - items = [ 'zero','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen','twenty']; + items = [ 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty']; function processListItemPartials(pattern, patternlab) { //find any listitem blocks @@ -33,6 +33,7 @@ var list_item_hunter = function () { var loopNumberString = liMatch.split('.')[1].split('}')[0].trim(); var end = liMatch.replace('#', '/'); var patternBlock = pattern.template.substring(pattern.template.indexOf(liMatch) + liMatch.length, pattern.template.indexOf(end)).trim(); + //build arrays that repeat the block, however large we need to var repeatedBlockTemplate = []; var repeatedBlockHtml = ''; diff --git a/builder/media_hunter.js b/builder/media_hunter.js index 7aa12e10c..0422c27bb 100644 --- a/builder/media_hunter.js +++ b/builder/media_hunter.js @@ -1,10 +1,10 @@ -/* - * patternlab-node - v1.1.3 - 2016 - * +/* + * patternlab-node - v1.1.3 - 2016 + * * 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. * */ @@ -33,8 +33,8 @@ var media_hunter = function () { } }); patternlab.mediaQueries.sort(function (a, b) { - var integerPartA = a.match(/(?:\d*\.)?\d+/g); - var integerPartB = b.match(/(?:\d*\.)?\d+/g); + a.match(/(?:\d*\.)?\d+/g); + b.match(/(?:\d*\.)?\d+/g); return parseInt(a, 10) > parseInt(b, 10); }); } diff --git a/builder/parameter_hunter.js b/builder/parameter_hunter.js index 1c683780e..b0a92c0a9 100644 --- a/builder/parameter_hunter.js +++ b/builder/parameter_hunter.js @@ -1,10 +1,10 @@ -/* - * patternlab-node - v1.1.3 - 2016 - * +/* + * patternlab-node - v1.1.3 - 2016 + * * 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. * */ @@ -20,13 +20,13 @@ var parameter_hunter = function () { function findparameters(pattern, patternlab) { if (pattern.parameteredPartials && pattern.parameteredPartials.length > 0) { - //compile this partial immeadiately, essentially consuming it. - + //compile this partial immediately, essentially consuming it. + pattern.parameteredPartials.forEach(function (pMatch) { //find the partial's name and retrieve it var partialName = pMatch.match(/([\w\-\.\/~]+)/g)[0]; var partialPattern = pattern_assembler.get_pattern_by_key(partialName, patternlab); - + //if we retrieved a pattern we should make sure that its extendedTemplate is reset. looks to fix #190 partialPattern.extendedTemplate = partialPattern.template; if (patternlab.config.debug) { @@ -37,13 +37,13 @@ var parameter_hunter = function () { var leftParen = pMatch.indexOf('('); var rightParen = pMatch.indexOf(')'); var paramString = '{' + pMatch.substring(leftParen + 1, rightParen) + '}'; - + //if param keys are wrapped in single quotes, replace with double quotes. var paramStringWellFormed = paramString.replace(/(')([^']+)(')(\s*\:)/g, '"$2"$4'); - + //if params keys are not wrapped in any quotes, wrap in double quotes. paramStringWellFormed = paramStringWellFormed.replace(/([\{|,]\s*)([^\s"'\:]+)(\s*\:)/g, '$1"$2"$3'); - + //if param values are wrapped in single quotes, replace with double quotes. paramStringWellFormed = paramStringWellFormed.replace(/(\:\s*)(')([^']+)(')/g, '$1"$3"'); diff --git a/builder/pattern_assembler.js b/builder/pattern_assembler.js index 72ddf7364..c719ff25e 100644 --- a/builder/pattern_assembler.js +++ b/builder/pattern_assembler.js @@ -78,6 +78,62 @@ var pattern_assembler = function () { } } + function buildListItems(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; + } + } + } + } + + function getpatternbykey(key, patternlab) { + var i; // for the for loops + + //look for exact key matches + for (i = 0; i < patternlab.patterns.length; i++) { + if (patternlab.patterns[i].key === key) { + return patternlab.patterns[i]; + } + } + + //else look by verbose syntax + for (i = 0; i < patternlab.patterns.length; i++) { + switch (key) { + case patternlab.patterns[i].subdir + '/' + patternlab.patterns[i].fileName: + case patternlab.patterns[i].subdir + '/' + patternlab.patterns[i].fileName + '.mustache': + return patternlab.patterns[i]; + } + } + + //return the fuzzy match if all else fails + for (i = 0; i < patternlab.patterns.length; i++) { + var keyParts = key.split('-'), + keyType = keyParts[0], + keyName = keyParts.slice(1).join('-'); + + if (patternlab.patterns[i].key.split('-')[0] === keyType && patternlab.patterns[i].key.indexOf(keyName) > -1) { + return patternlab.patterns[i]; + } + } + throw 'Could not find pattern with key ' + key; + } + function processPatternIterative(file, patternlab) { var fs = require('fs-extra'), of = require('./object_factory'), @@ -240,38 +296,6 @@ var pattern_assembler = function () { pseudopattern_hunter.find_pseudopatterns(currentPattern, patternlab); } - function getpatternbykey(key, patternlab) { - var i; // for the for loops - - //look for exact key matches - for (i = 0; i < patternlab.patterns.length; i++) { - if (patternlab.patterns[i].key === key) { - return patternlab.patterns[i]; - } - } - - //else look by verbose syntax - for (i = 0; i < patternlab.patterns.length; i++) { - switch (key) { - case patternlab.patterns[i].subdir + '/' + patternlab.patterns[i].fileName: - case patternlab.patterns[i].subdir + '/' + patternlab.patterns[i].fileName + '.mustache': - return patternlab.patterns[i]; - } - } - - //return the fuzzy match if all else fails - for (i = 0; i < patternlab.patterns.length; i++) { - var keyParts = key.split('-'), - keyType = keyParts[0], - keyName = keyParts.slice(1).join('-'); - - if (patternlab.patterns[i].key.split('-')[0] === keyType && patternlab.patterns[i].key.indexOf(keyName) > -1) { - return patternlab.patterns[i]; - } - } - throw 'Could not find pattern with key ' + key; - } - function mergeData(obj1, obj2) { /*eslint-disable guard-for-in, no-param-reassign*/ if (typeof obj2 === 'undefined') { @@ -302,30 +326,6 @@ var pattern_assembler = function () { return obj2; } - function buildListItems(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; - } - } - } - } - //http://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array-in-javascript function shuffle(o) { /*eslint-disable curly*/ diff --git a/builder/patternlab.js b/builder/patternlab.js index d1745567b..cec23d10d 100644 --- a/builder/patternlab.js +++ b/builder/patternlab.js @@ -1,10 +1,10 @@ -/* - * patternlab-node - v1.1.3 - 2016 - * +/* + * patternlab-node - v1.1.3 - 2016 + * * 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. * */ @@ -153,13 +153,24 @@ var patternlab_engine = function (config) { pattern_exporter.export_patterns(patternlab); } + function addToPatternPaths(bucketName, pattern) { + //this is messy, could use a refactor. + patternlab.patternPaths[bucketName][pattern.patternName] = pattern.subdir.replace(/\\/g, '/') + "/" + pattern.fileName; + } + + //todo: refactor this as a method on the pattern object itself once we merge dev with pattern-engines branch + function isPatternExcluded(pattern) { + // returns whether or not the first character of the pattern filename is an underscore, or excluded + return pattern.fileName.charAt(0) === '_'; + } + function buildFrontEnd() { var pattern_assembler = new pa(), media_hunter = new mh(), styleGuideExcludes = patternlab.config.styleGuideExcludes, styleguidePatterns = [], i; // for loops - + patternlab.buckets = []; patternlab.bucketIndex = []; patternlab.patternPaths = {}; @@ -169,7 +180,7 @@ var patternlab_engine = function (config) { 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; }); @@ -203,7 +214,7 @@ var patternlab_engine = function (config) { //build the styleguide var styleguideTemplate = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'styleguide.mustache'), 'utf8'), styleguideHtml = pattern_assembler.renderPattern(styleguideTemplate, {partials: styleguidePatterns}); - + fs.outputFileSync(path.resolve(paths.public.styleguide, 'html/styleguide.html'), styleguideHtml); //build the viewall pages @@ -325,7 +336,7 @@ var patternlab_engine = function (config) { navSubItem.patternPartial = bucketName + "-" + pattern.patternName; //add the hyphenated name //add the patternState if it exists - if(pattern.patternState){ + if (pattern.patternState) { navSubItem.patternState = pattern.patternState; } @@ -351,7 +362,7 @@ var patternlab_engine = function (config) { navViewAllItem.patternPartial = "viewall-" + pattern.patternGroup; bucket.patternItems.push(navViewAllItem); - patternlab.viewAllPaths[bucketName]['viewall'] = pattern.subdir.slice(0, pattern.subdir.indexOf(pattern.patternGroup) + pattern.patternGroup.length); + patternlab.viewAllPaths[bucketName].viewall = pattern.subdir.slice(0, pattern.subdir.indexOf(pattern.patternGroup) + pattern.patternGroup.length); } //add the bucket. @@ -477,17 +488,6 @@ var patternlab_engine = function (config) { fs.outputFileSync(path.resolve(paths.public.root, 'index.html'), patternlabSiteHtml); } - function addToPatternPaths(bucketName, pattern) { - //this is messy, could use a refactor. - patternlab.patternPaths[bucketName][pattern.patternName] = pattern.subdir.replace(/\\/g, '/') + "/" + pattern.fileName; - } - - //todo: refactor this as a method on the pattern object itself once we merge dev with pattern-engines branch - function isPatternExcluded(pattern) { - // returns whether or not the first character of the pattern filename is an underscore, or excluded - return pattern.fileName.charAt(0) === '_'; - } - return { version: function () { return getVersion(); From 07148557ef990fd9319dc56b7e7075f55241fe9f Mon Sep 17 00:00:00 2001 From: BRIAN MUENZENMEYER Date: Sat, 27 Feb 2016 23:47:06 -0600 Subject: [PATCH 11/17] shortened the eslint consecutive variable declaration indent- because editorconfig did not seem to support it, so the two tools would create contention. I can live with "misaligned" variables. ask me about work sometime --- .eslintrc | 2 +- builder/media_hunter.js | 4 +-- builder/parameter_hunter.js | 8 ++--- builder/pattern_assembler.js | 28 +++++++-------- builder/pattern_exporter.js | 14 ++++---- builder/patternlab.js | 42 +++++++++++----------- builder/patternlab_gulp.js | 14 ++++---- builder/pseudopattern_hunter.js | 22 ++++++------ builder/style_modifier_hunter.js | 60 ++++++++++++++++---------------- 9 files changed, 97 insertions(+), 97 deletions(-) diff --git a/.eslintrc b/.eslintrc index 3c2d195a1..fcea5476b 100644 --- a/.eslintrc +++ b/.eslintrc @@ -14,7 +14,7 @@ "eqeqeq": [2, "allow-null"], "global-strict": [0, "never"], "guard-for-in": 2, - "indent": [2, 2, {"SwitchCase": 1, "VariableDeclarator": 2}], + "indent": [2, 2, {"SwitchCase": 1, "VariableDeclarator": 1}], "lines-around-comment": [2, { "beforeBlockComment": true, "beforeLineComment": true, diff --git a/builder/media_hunter.js b/builder/media_hunter.js index 0422c27bb..e8de9a81f 100644 --- a/builder/media_hunter.js +++ b/builder/media_hunter.js @@ -11,8 +11,8 @@ "use strict"; var diveSync = require('diveSync'), - path = require('path'), - fs = require('fs-extra'); + path = require('path'), + fs = require('fs-extra'); var media_hunter = function () { diff --git a/builder/parameter_hunter.js b/builder/parameter_hunter.js index b0a92c0a9..72f8d7603 100644 --- a/builder/parameter_hunter.js +++ b/builder/parameter_hunter.js @@ -13,10 +13,10 @@ var parameter_hunter = function () { var extend = require('util')._extend, - pa = require('./pattern_assembler'), - smh = require('./style_modifier_hunter'), - style_modifier_hunter = new smh(), - pattern_assembler = new pa(); + pa = require('./pattern_assembler'), + smh = require('./style_modifier_hunter'), + style_modifier_hunter = new smh(), + pattern_assembler = new pa(); function findparameters(pattern, patternlab) { if (pattern.parameteredPartials && pattern.parameteredPartials.length > 0) { diff --git a/builder/pattern_assembler.js b/builder/pattern_assembler.js index c719ff25e..757844c24 100644 --- a/builder/pattern_assembler.js +++ b/builder/pattern_assembler.js @@ -92,11 +92,11 @@ var pattern_assembler = function () { var tempItems = []; if (i === 1) { tempItems.push(container.listItemArray[0]); - container.listitems['' + i ] = tempItems; + container.listitems['' + i] = tempItems; } else { for (var c = 1; c <= i; c++) { tempItems.push(container.listItemArray[c - 1]); - container.listitems['' + i ] = tempItems; + container.listitems['' + i] = tempItems; } } } @@ -136,8 +136,8 @@ var pattern_assembler = function () { function processPatternIterative(file, patternlab) { var fs = require('fs-extra'), - of = require('./object_factory'), - path = require('path'); + of = require('./object_factory'), + path = require('path'); //extract some information var subdir = path.dirname(path.relative(patternlab.config.paths.source.patterns, file)).replace('\\', '/'); @@ -206,20 +206,20 @@ var pattern_assembler = function () { function processPatternRecursive(file, patternlab) { var lh = require('./lineage_hunter'), - ph = require('./parameter_hunter'), - pph = require('./pseudopattern_hunter'), - lih = require('./list_item_hunter'), - smh = require('./style_modifier_hunter'); + ph = require('./parameter_hunter'), + pph = require('./pseudopattern_hunter'), + lih = require('./list_item_hunter'), + smh = require('./style_modifier_hunter'); var parameter_hunter = new ph(), - lineage_hunter = new lh(), - list_item_hunter = new lih(), - style_modifier_hunter = new smh(), - pseudopattern_hunter = new pph(); + lineage_hunter = new lh(), + list_item_hunter = new lih(), + style_modifier_hunter = new smh(), + pseudopattern_hunter = new pph(); //find current pattern in patternlab object using var file as a key var currentPattern, - i; + i; for (i = 0; i < patternlab.patterns.length; i++) { if (patternlab.patterns[i].abspath === file) { @@ -259,7 +259,7 @@ var pattern_assembler = function () { //identify which pattern this partial corresponds tou for (var j = 0; j < patternlab.patterns.length; j++) { if (patternlab.patterns[j].key === partialKey || - patternlab.patterns[j].abspath.indexOf(partialKey) > -1) { + patternlab.patterns[j].abspath.indexOf(partialKey) > -1) { partialPath = patternlab.patterns[j].abspath; } } diff --git a/builder/pattern_exporter.js b/builder/pattern_exporter.js index a7a70c05b..23c9777a4 100644 --- a/builder/pattern_exporter.js +++ b/builder/pattern_exporter.js @@ -1,10 +1,10 @@ -/* - * patternlab-node - v1.1.3 - 2016 - * +/* + * patternlab-node - v1.1.3 - 2016 + * * 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. * */ @@ -13,7 +13,7 @@ var fs = require('fs-extra'); var pattern_exporter = function () { - + function exportPatterns(patternlab) { //read the config export options var exportKeys = patternlab.config.patternExportKeys; diff --git a/builder/patternlab.js b/builder/patternlab.js index cec23d10d..b4705deaf 100644 --- a/builder/patternlab.js +++ b/builder/patternlab.js @@ -12,14 +12,14 @@ var patternlab_engine = function (config) { 'use strict'; var path = require('path'), - fs = require('fs-extra'), - diveSync = require('diveSync'), - of = require('./object_factory'), - pa = require('./pattern_assembler'), - mh = require('./media_hunter'), - pe = require('./pattern_exporter'), - he = require('html-entities').AllHtmlEntities, - patternlab = {}; + fs = require('fs-extra'), + diveSync = require('diveSync'), + of = require('./object_factory'), + pa = require('./pattern_assembler'), + mh = require('./media_hunter'), + pe = require('./pattern_exporter'), + he = require('html-entities').AllHtmlEntities, + patternlab = {}; patternlab.package = fs.readJSONSync('./package.json'); patternlab.config = config || fs.readJSONSync(path.resolve(__dirname, '../config.json')); @@ -64,9 +64,9 @@ var patternlab_engine = function (config) { patternlab.data.link = {}; var pattern_assembler = new pa(), - entity_encoder = new he(), - pattern_exporter = new pe(), - patterns_dir = paths.source.patterns; + entity_encoder = new he(), + pattern_exporter = new pe(), + patterns_dir = paths.source.patterns; pattern_assembler.combine_listItems(patternlab); @@ -166,10 +166,10 @@ var patternlab_engine = function (config) { function buildFrontEnd() { var pattern_assembler = new pa(), - media_hunter = new mh(), - styleGuideExcludes = patternlab.config.styleGuideExcludes, - styleguidePatterns = [], - i; // for loops + media_hunter = new mh(), + styleGuideExcludes = patternlab.config.styleGuideExcludes, + styleguidePatterns = [], + i; // for loops patternlab.buckets = []; patternlab.bucketIndex = []; @@ -213,13 +213,13 @@ var patternlab_engine = function (config) { //build the styleguide var styleguideTemplate = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'styleguide.mustache'), 'utf8'), - styleguideHtml = pattern_assembler.renderPattern(styleguideTemplate, {partials: styleguidePatterns}); + styleguideHtml = pattern_assembler.renderPattern(styleguideTemplate, {partials: styleguidePatterns}); fs.outputFileSync(path.resolve(paths.public.styleguide, 'html/styleguide.html'), styleguideHtml); //build the viewall pages var prevSubdir = '', - prevGroup = ''; + prevGroup = ''; for (i = 0; i < patternlab.patterns.length; i++) { // skip underscore-prefixed files @@ -238,8 +238,8 @@ var patternlab_engine = function (config) { prevGroup = pattern.patternGroup; var viewAllPatterns = [], - patternPartial = "viewall-" + pattern.patternGroup, - j; + patternPartial = "viewall-" + pattern.patternGroup, + j; for (j = 0; j < patternlab.patterns.length; j++) { if (patternlab.patterns[j].patternGroup === pattern.patternGroup) { @@ -266,8 +266,8 @@ var patternlab_engine = function (config) { prevSubdir = pattern.subdir; var viewAllPatterns = [], - patternPartial = "viewall-" + pattern.patternGroup + "-" + pattern.patternSubGroup, - j; + patternPartial = "viewall-" + pattern.patternGroup + "-" + pattern.patternSubGroup, + j; for (j = 0; j < patternlab.patterns.length; j++) { if (patternlab.patterns[j].subdir === pattern.subdir) { diff --git a/builder/patternlab_gulp.js b/builder/patternlab_gulp.js index 291940b30..82cf2a4ce 100644 --- a/builder/patternlab_gulp.js +++ b/builder/patternlab_gulp.js @@ -1,17 +1,17 @@ -/* - * patternlab-node - v1.1.3 - 2016 - * +/* + * patternlab-node - v1.1.3 - 2016 + * * 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. * */ var patternlab_engine = require('./patternlab.js'); module.exports = function (gulp) { - + gulp.task('patternlab', ['clean'], function (cb) { var patternlab = patternlab_engine(); patternlab.build(false); diff --git a/builder/pseudopattern_hunter.js b/builder/pseudopattern_hunter.js index 0f0907ea1..6366be9e8 100644 --- a/builder/pseudopattern_hunter.js +++ b/builder/pseudopattern_hunter.js @@ -1,10 +1,10 @@ -/* - * patternlab-node - v1.1.3 - 2016 - * +/* + * patternlab-node - v1.1.3 - 2016 + * * 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. * */ @@ -14,11 +14,11 @@ var pseudopattern_hunter = function () { function findpseudopatterns(currentPattern, patternlab) { var glob = require('glob'), - fs = require('fs-extra'), - pa = require('./pattern_assembler'), - lh = require('./lineage_hunter'), - of = require('./object_factory'), - path = require('path'); + fs = require('fs-extra'), + pa = require('./pattern_assembler'), + lh = require('./lineage_hunter'), + of = require('./object_factory'), + path = require('path'); var pattern_assembler = new pa(); var lineage_hunter = new lh(); diff --git a/builder/style_modifier_hunter.js b/builder/style_modifier_hunter.js index b9b616b86..742009ce4 100644 --- a/builder/style_modifier_hunter.js +++ b/builder/style_modifier_hunter.js @@ -1,43 +1,43 @@ -/* - * patternlab-node - v1.1.3 - 2016 - * +/* + * patternlab-node - v1.1.3 - 2016 + * * 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. * */ - "use strict"; - - var style_modifier_hunter = function () { +"use strict"; - function consumestylemodifier(pattern, partial, patternlab) { - //extract the classname from the stylemodifier which comes in the format of :className - var styleModifier = partial.match(/:([\w\-_|])+/g) ? partial.match(/:([\w\-_|])+/g)[0].slice(1) : null; - - if (styleModifier) { - //replace the special character pipe | used to separate multiple classes with a space - styleModifier = styleModifier.replace(/\|/g, ' '); +var style_modifier_hunter = function () { - if (patternlab.config.debug) { - console.log('found partial styleModifier within pattern ' + pattern.key); - } + function consumestylemodifier(pattern, partial, patternlab) { + //extract the classname from the stylemodifier which comes in the format of :className + var styleModifier = partial.match(/:([\w\-_|])+/g) ? partial.match(/:([\w\-_|])+/g)[0].slice(1) : null; - //replace the stylemodifier placeholder with the class name - pattern.extendedTemplate = pattern.extendedTemplate.replace(/{{[ ]?styleModifier[ ]?}}/i, styleModifier); + if (styleModifier) { + //replace the special character pipe | used to separate multiple classes with a space + styleModifier = styleModifier.replace(/\|/g, ' '); - //update the extendedTemplate in the partials object in case this pattern is consumed later - patternlab.partials[pattern.key] = pattern.extendedTemplate; + if (patternlab.config.debug) { + console.log('found partial styleModifier within pattern ' + pattern.key); } - } - return { - consume_style_modifier: function (pattern, partial, patternlab) { - consumestylemodifier(pattern, partial, patternlab); - } - }; + //replace the stylemodifier placeholder with the class name + pattern.extendedTemplate = pattern.extendedTemplate.replace(/{{[ ]?styleModifier[ ]?}}/i, styleModifier); + //update the extendedTemplate in the partials object in case this pattern is consumed later + patternlab.partials[pattern.key] = pattern.extendedTemplate; + } + } + + return { + consume_style_modifier: function (pattern, partial, patternlab) { + consumestylemodifier(pattern, partial, patternlab); + } }; - module.exports = style_modifier_hunter; +}; + +module.exports = style_modifier_hunter; From 7fab92b10c6cd4b021c7ec8f860fb81309fbc690 Mon Sep 17 00:00:00 2001 From: BRIAN MUENZENMEYER Date: Sat, 27 Feb 2016 23:49:09 -0600 Subject: [PATCH 12/17] missed reformatting this file --- builder/list_item_hunter.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/builder/list_item_hunter.js b/builder/list_item_hunter.js index 453e3c44b..7fcf3d188 100644 --- a/builder/list_item_hunter.js +++ b/builder/list_item_hunter.js @@ -13,11 +13,11 @@ var list_item_hunter = function () { var extend = require('util')._extend, - pa = require('./pattern_assembler'), - smh = require('./style_modifier_hunter'), - pattern_assembler = new pa(), - style_modifier_hunter = new smh(), - items = [ 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty']; + pa = require('./pattern_assembler'), + smh = require('./style_modifier_hunter'), + pattern_assembler = new pa(), + style_modifier_hunter = new smh(), + items = [ 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty']; function processListItemPartials(pattern, patternlab) { //find any listitem blocks From c304a78a8020e08cd5a7875e0d36c67b51e9851f Mon Sep 17 00:00:00 2001 From: BRIAN MUENZENMEYER Date: Sun, 28 Feb 2016 08:20:58 -0600 Subject: [PATCH 13/17] turn off block scoped var rule --- .eslintrc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.eslintrc b/.eslintrc index fcea5476b..df838cd02 100644 --- a/.eslintrc +++ b/.eslintrc @@ -5,7 +5,7 @@ }, "globals": {}, "rules": { - "block-scoped-var": 1, + "block-scoped-var": 0, "camelcase": 0, "comma-spacing": [1, {"before": false, "after": true}], "consistent-return": 2, From 657ca995161d171db8d29dd85041a692a48b0cc3 Mon Sep 17 00:00:00 2001 From: BRIAN MUENZENMEYER Date: Sun, 28 Feb 2016 08:22:17 -0600 Subject: [PATCH 14/17] turn off redeclare --- .eslintrc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.eslintrc b/.eslintrc index df838cd02..434d9fe85 100644 --- a/.eslintrc +++ b/.eslintrc @@ -51,7 +51,7 @@ "no-new": 2, "no-param-reassign": 2, "no-proto": 2, - "no-redeclare": 1, + "no-redeclare": 0, "no-script-url": 2, "no-self-assign": 2, "no-self-compare": 2, From 79855cbbfee8ca6dd1475129cf0927ab18024443 Mon Sep 17 00:00:00 2001 From: BRIAN MUENZENMEYER Date: Sun, 28 Feb 2016 22:56:40 -0600 Subject: [PATCH 15/17] Added eslint tasks to build (both) and travis step (grunt only) deleted jslintrc file Addresses #274 --- .jslintrc | 36 ------------------------------------ Gruntfile.js | 10 ++++++++-- builder/pattern_assembler.js | 17 +++++++---------- gulpfile.js | 11 ++++++++++- package.gulp.json | 2 +- package.json | 4 ++-- 6 files changed, 28 insertions(+), 52 deletions(-) delete mode 100644 .jslintrc diff --git a/.jslintrc b/.jslintrc deleted file mode 100644 index 8ac6b2e37..000000000 --- a/.jslintrc +++ /dev/null @@ -1,36 +0,0 @@ -{ - "ass": false, - "bitwise": false, - "browser": false, - "closure": false, - "continue": false, - "couch": false, - "debug": false, - "devel": true, - "eqeq": false, - "eval": true, - "evil": false, - "forin": false, - "indent": 2, - "maxerr": 50, - "maxlen": false, - "newcap": false, - "node": true, - "nomen": false, - "passfail": false, - "plusplus": false, - "predef": [ - "node", - "$", - "require" - ], - "regexp": false, - "rhino": false, - "sloppy": false, - "stupid": false, - "sub": false, - "todo": false, - "unparam": true, - "vars": false, - "white": true -} diff --git a/Gruntfile.js b/Gruntfile.js index 51452919f..96f35a284 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -138,6 +138,12 @@ module.exports = function (grunt) { } } }, + eslint: { + options: { + configFile: './.eslintrc' + }, + target: ['./builder/*'] + }, bsReload: { css: path.resolve(paths().public.root + '**/*.css') } @@ -152,10 +158,10 @@ module.exports = function (grunt) { grunt.registerTask('default', ['patternlab', 'copy:main', 'copy:styleguide']); //travis CI task - grunt.registerTask('travis', ['nodeunit', 'patternlab']); + grunt.registerTask('travis', ['nodeunit', 'eslint', 'patternlab']); grunt.registerTask('serve', ['patternlab', 'copy:main', 'copy:styleguide', 'browserSync', 'watch:all']); - grunt.registerTask('build', ['nodeunit', 'concat']); + grunt.registerTask('build', ['nodeunit', 'eslint', 'concat']); }; diff --git a/builder/pattern_assembler.js b/builder/pattern_assembler.js index 757844c24..6f17f62e0 100644 --- a/builder/pattern_assembler.js +++ b/builder/pattern_assembler.js @@ -8,7 +8,6 @@ * */ - "use strict"; var pattern_assembler = function () { @@ -78,6 +77,12 @@ var pattern_assembler = function () { } } + //http://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array-in-javascript + function shuffle(o) { + for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x); + return o; + } + function buildListItems(container) { //combine all list items into one structure var list = []; @@ -297,8 +302,7 @@ var pattern_assembler = function () { } function mergeData(obj1, obj2) { - /*eslint-disable guard-for-in, no-param-reassign*/ - if (typeof obj2 === 'undefined') { + if (typeof obj2 === 'undefined') { obj2 = {}; } for (var p in obj1) { @@ -326,13 +330,6 @@ var pattern_assembler = function () { return obj2; } - //http://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array-in-javascript - function shuffle(o) { - /*eslint-disable curly*/ - for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x); - return o; - } - function parseDataLinksHelper(patternlab, obj, key) { var linkRE, dataObjAsString, linkMatches, expandedLink; diff --git a/gulpfile.js b/gulpfile.js index 8e93df2b0..6519b0213 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -9,6 +9,7 @@ var pkg = require('./package.json'), strip_banner = require('gulp-strip-banner'), header = require('gulp-header'), nodeunit = require('gulp-nodeunit'), + eslint = require('gulp-eslint'), browserSync = require('browser-sync').create(); require('gulp-load')(gulp); @@ -151,6 +152,14 @@ gulp.task('connect', ['lab'], function () { }); +//lint +gulp.task('eslint', function () { + return gulp.src(['./builder/*.js', '!node_modules/**']) + .pipe(eslint()) + .pipe(eslint.format()) + .pipe(eslint.failAfterError()); +}); + //unit test gulp.task('nodeunit', function () { return gulp.src('./test/**/*_tests.js') @@ -170,7 +179,7 @@ gulp.task('prelab', ['clean', 'assets']); gulp.task('lab', ['prelab', 'patternlab'], function (cb) { cb(); }); gulp.task('patterns', ['patternlab:only_patterns']); gulp.task('serve', ['lab', 'connect']); -gulp.task('travis', ['lab', 'nodeunit']); +gulp.task('build', ['eslint', 'nodeunit', 'banner']); gulp.task('version', ['patternlab:version']); gulp.task('help', ['patternlab:help']); diff --git a/package.gulp.json b/package.gulp.json index 3f2663854..87a4d0044 100644 --- a/package.gulp.json +++ b/package.gulp.json @@ -13,10 +13,10 @@ }, "devDependencies": { "browser-sync": "^2.11.1", - "eslint": "^2.2.0", "gulp": "^3.9.0", "gulp-connect": "^2.3.1", "gulp-copy": "0.0.2", + "gulp-eslint": "^2.0.0", "gulp-header": "^1.7.1", "gulp-load": "^0.1.1", "gulp-nodeunit": "0.0.5", diff --git a/package.json b/package.json index 5ea2de257..a62664b52 100644 --- a/package.json +++ b/package.json @@ -13,13 +13,13 @@ }, "devDependencies": { "bs-html-injector": "^3.0.0", - "eslint": "^2.2.0", "grunt": "~0.4.5", "grunt-browser-sync": "^2.2.0", "grunt-contrib-concat": "^0.5.1", "grunt-contrib-copy": "^0.8.2", "grunt-contrib-nodeunit": "^0.4.1", - "grunt-contrib-watch": "^0.6.1" + "grunt-contrib-watch": "^0.6.1", + "grunt-eslint": "^18.0.0" }, "keywords": [ "Pattern Lab", From c638157271f1244fac398a615f74c55bcdf441b1 Mon Sep 17 00:00:00 2001 From: BRIAN MUENZENMEYER Date: Sun, 28 Feb 2016 23:23:30 -0600 Subject: [PATCH 16/17] add note about our new standardization tools in CONTRIBUTING.md closes #274 --- .github/CONTRIBUTING.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 7edd1a3d0..8598cddb2 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -1,5 +1,5 @@ # Contributing to Patternlab Node -If you'd like to contribute to Pattern Lab Node, please do so! There is always a lot of ground to cover and something for your wheelhouse. +If you'd like to contribute to Pattern Lab Node, please do so! There is always a lot of ground to cover and something for your wheelhouse. No pull request is too small. Check out any [up for grabs issues](https://github.com/pattern-lab/patternlab-node/labels/up%20for%20grabs) as a good way to get your feet wet, or add some more unit tests. @@ -9,4 +9,7 @@ No pull request is too small. Check out any [up for grabs issues](https://github 3. If you can, add some unit tests using the existing patterns in the `./test` directory ##Coding style -Regarding code style like indentation and whitespace, follow the conventions you see used in the source already. Add enough source code comments to help the next person. +Two files combine within the project to define and maintain our coding style. + +* The `.editorconfig` controls spaces / tabs within supported editors. Check out their [site](http://editorconfig.org/). +* The `.eslintrc` defines our javascript standards. Some editors will evaluate this real-time - otherwise it's run using `grunt|gulp build` From 2e3236b911342ec47e6740be356410478afddec6 Mon Sep 17 00:00:00 2001 From: BRIAN MUENZENMEYER Date: Mon, 29 Feb 2016 00:33:24 -0600 Subject: [PATCH 17/17] fix a bad merge --- builder/parameter_hunter.js | 117 ++++++++++++++++++++++++++++++++--- builder/pattern_assembler.js | 3 +- 2 files changed, 108 insertions(+), 12 deletions(-) diff --git a/builder/parameter_hunter.js b/builder/parameter_hunter.js index 73c804de1..2f8738034 100644 --- a/builder/parameter_hunter.js +++ b/builder/parameter_hunter.js @@ -18,10 +18,114 @@ var parameter_hunter = function () { style_modifier_hunter = new smh(), pattern_assembler = new pa(); + function paramToJson(pString) { + var paramStringWellFormed = ''; + var paramStringTmp; + var colonPos; + var delimitPos; + var quotePos; + var paramString = pString; + + do { + + //if param key is wrapped in single quotes, replace with double quotes. + paramString = paramString.replace(/(^\s*[\{|\,]\s*)'([^']+)'(\s*\:)/, '$1"$2"$3'); + + //if params key is not wrapped in any quotes, wrap in double quotes. + paramString = paramString.replace(/(^\s*[\{|\,]\s*)([^\s"'\:]+)(\s*\:)/, '$1"$2"$3'); + + //move param key to paramStringWellFormed var. + colonPos = paramString.indexOf(':'); + + //except to prevent infinite loops. + if (colonPos === -1) { + colonPos = paramString.length - 1; + } + else { + colonPos += 1; + } + paramStringWellFormed += paramString.substring(0, colonPos); + paramString = paramString.substring(colonPos, paramString.length).trim(); + + //if param value is wrapped in single quotes, replace with double quotes. + if (paramString[0] === '\'') { + quotePos = paramString.search(/[^\\]'/); + + //except for unclosed quotes to prevent infinite loops. + if (quotePos === -1) { + quotePos = paramString.length - 1; + } + else { + quotePos += 2; + } + + //prepare param value for move to paramStringWellFormed var. + paramStringTmp = paramString.substring(0, quotePos); + + //unescape any escaped single quotes. + paramStringTmp = paramStringTmp.replace(/\\'/g, '\''); + + //escape any double quotes. + paramStringTmp = paramStringTmp.replace(/"/g, '\\"'); + + //replace the delimiting single quotes with double quotes. + paramStringTmp = paramStringTmp.replace(/^'/, '"'); + paramStringTmp = paramStringTmp.replace(/'$/, '"'); + + //move param key to paramStringWellFormed var. + paramStringWellFormed += paramStringTmp; + paramString = paramString.substring(quotePos, paramString.length).trim(); + } + + //if param value is wrapped in double quotes, just move to paramStringWellFormed var. + else if (paramString[0] === '"') { + quotePos = paramString.search(/[^\\]"/); + + //except for unclosed quotes to prevent infinite loops. + if (quotePos === -1) { + quotePos = paramString.length - 1; + } + else { + quotePos += 2; + } + + //move param key to paramStringWellFormed var. + paramStringWellFormed += paramString.substring(0, quotePos); + paramString = paramString.substring(quotePos, paramString.length).trim(); + } + + //if param value is not wrapped in quotes, move everthing up to the delimiting comma to paramStringWellFormed var. + else { + delimitPos = paramString.indexOf(','); + + //except to prevent infinite loops. + if (delimitPos === -1) { + delimitPos = paramString.length - 1; + } + else { + delimitPos += 1; + } + paramStringWellFormed += paramString.substring(0, delimitPos); + paramString = paramString.substring(delimitPos, paramString.length).trim(); + } + + //break at the end. + if (paramString.length === 1) { + paramStringWellFormed += paramString.trim(); + paramString = ''; + break; + } + + } while (paramString); + + return paramStringWellFormed; + } + function findparameters(pattern, patternlab) { + if (pattern.parameteredPartials && pattern.parameteredPartials.length > 0) { - //compile this partial immediately, essentially consuming it. + //compile this partial immeadiately, essentially consuming it. pattern.parameteredPartials.forEach(function (pMatch) { //find the partial's name and retrieve it var partialName = pMatch.match(/([\w\-\.\/~]+)/g)[0]; @@ -29,6 +133,7 @@ var parameter_hunter = function () { //if we retrieved a pattern we should make sure that its extendedTemplate is reset. looks to fix #190 partialPattern.extendedTemplate = partialPattern.template; + if (patternlab.config.debug) { console.log('found patternParameters for ' + partialName); } @@ -37,15 +142,7 @@ var parameter_hunter = function () { var leftParen = pMatch.indexOf('('); var rightParen = pMatch.indexOf(')'); var paramString = '{' + pMatch.substring(leftParen + 1, rightParen) + '}'; - - //if param keys are wrapped in single quotes, replace with double quotes. - var paramStringWellFormed = paramString.replace(/(')([^']+)(')(\s*\:)/g, '"$2"$4'); - - //if params keys are not wrapped in any quotes, wrap in double quotes. - paramStringWellFormed = paramStringWellFormed.replace(/([\{|,]\s*)([^\s"'\:]+)(\s*\:)/g, '$1"$2"$3'); - - //if param values are wrapped in single quotes, replace with double quotes. - paramStringWellFormed = paramStringWellFormed.replace(/(\:\s*)(')([^']+)(')/g, '$1"$3"'); + var paramStringWellFormed = paramToJson(paramString); var paramData = {}; var globalData = {}; diff --git a/builder/pattern_assembler.js b/builder/pattern_assembler.js index 9bf227de0..2d40c1544 100644 --- a/builder/pattern_assembler.js +++ b/builder/pattern_assembler.js @@ -303,8 +303,7 @@ var pattern_assembler = function () { function mergeData(obj1, obj2) { if (typeof obj2 === 'undefined') { - //noinspection Eslint - obj2 = {}; + obj2 = {}; //eslint-disable-line no-param-reassign } for (var p in obj1) { //eslint-disable-line guard-for-in