Example #1
1
        }, function (err, result) {
            if(err) { done(err); }
            try {
                var resultAst = css.parse(result);
                var orgAst = css.parse(originalCss);
                resultAst.stylesheet.rules.should.have.length.lessThan(orgAst.stylesheet.rules.length);
                done();
            } catch (ex) {
                done(ex);
            }

        });
Example #2
0
        }, function (err, result) {
            if (err) {
                done(err);
            }
            try {
                var resultAst = css.parse(result);
                var expectedAst = css.parse(yeomanExpectedCss);
                resultAst.should.eql(expectedAst);
                done();
            } catch (ex) {
                done(ex);
            }

        });
Example #3
0
		}, function (err, result) {
			if (err) {
				done(err);
				return;
			}
			try {
				var resultAst = css.parse(result);
				var orgAst = css.parse(originalCss);
				resultAst.should.eql(orgAst);
				done();
			} catch (ex) {
				done(ex);
			}

		});
Example #4
0
  it('should support the Rework API', function () {
    var ast = css.parse(input);
    flip.rework()(ast.stylesheet);
    var out = css.stringify(ast, {compress: true});

    assert.equal(out, expect, out + ' != ' + expect);
  });
Example #5
0
    this.files.forEach(function(f) {
      var src = f.src.filter(function(filepath) {
        // Warn on and remove invalid source files (if nonull was set).
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      }).map(function(filepath) {
        // Read file source.
        return grunt.file.read(filepath);
      }).join(grunt.util.normalizelf(grunt.util.linefeed));

      // Parse the style
      var style = css.parse(src);

      // Do the magic!
      style.stylesheet.rules = stripMediaQueries(style.stylesheet.rules, options.overridesOnly);

      var output = css.stringify(style);
      // Write the destination file.
      grunt.file.write(f.dest, output);

      // Print a success message.
      grunt.log.writeln('File "' + chalk.cyan(f.dest) + '" created: ' +
                        maxmin(src, output, false));
    });
Example #6
0
 function (err, normalizedCss) {
   debuglog('normalized css: ' + normalizedCss.length)
   ast = cssAstFormatter.parse(normalizedCss)
   debuglog('parsed normalised css into ast')
   resolve(ast)
   return
 }
Example #7
0
const parseCSS = (font) => {
    let fileContents = '';
    if (typeof font.files === 'object') {
        font.files.forEach( file => {
            fileContents += readFile(font.directory, file)
        });
    } else {
        fileContents = readFile(font.directory, font.files);
    }

    let ast = CSS.parse(fileContents);
    let rules = ast.stylesheet.rules;

    let output = rules.map(item => {
        if (typeof item.selectors !== 'undefined' && item.selectors[0].startsWith(font.pattern.before) && item.selectors[0].endsWith(font.pattern.after)) {
            let output = {};

            output.selector = item.selectors[0]
            .replace(/^\./, '')
            .replace(/:before$/, '');

            item.declarations.forEach( declaration => {
                if (declaration.property === 'content') output.code = declaration.value.replace(/("|')*/g, '').replace(/\\/g, '');
            });

            return output;
        }

    });

    // Remove null keys
    output = output.filter(e => e);

    return output;
}
Example #8
0
function mqRemove(contents, query) {
    var data = css.parse(contents);

    var filterRule = function (rule) {
        if (rule.type === "media" && !mediaQuery.match(rule.media, query)) {
            return false;
        }

        // Recurse
        if (rule.rules) {
            rule.rules = rule.rules.filter(filterRule);
        }

        return true;
    };

    if (data.stylesheet) {
        filterRule(data.stylesheet);
        if (data.stylesheet.rules) {
            data.stylesheet.rules = data.stylesheet.rules.reduce(mqFlatten, []);
        }
    }

    return css.stringify(data);
}
Example #9
0
export function style($scope){

    let cssRules = $scope.css

    if (this.attribs['style'] || this.attribs['color']){
        // grab style from attribute
        let cssText = _.get(this, 'attribs.style', '')

        // convert <g color="red"> to a css rule
        // --> color:red;

        let color = this.attribs['color']
        if (color){
            cssText = `color:${color};` + cssText
        }

        let ast = css.parse('* {' + cssText + '}')

        // add the new rules to the end
        cssRules = cssRules.concat(ast.stylesheet.rules)
    }

    // console.log(cssRules)
    this.computeStyle(cssRules)
}
Example #10
0
function cssProcessor(contents, classes) {
  const cssAst = css.parse(contents);
  const config = new Config();
  const verbose = Verbose.getInstance(config.rc.verbose);

  function processRule(rule) {
    rule.selectors = rule.selectors.map((selector) => {
      return config.rc.presets.css.reduce((convertedSelector, converter) => {
        return converter(convertedSelector, classes, minify, verbose);
      }, selector);
    });

    return rule;
  }

  cssAst.stylesheet.rules = cssAst.stylesheet.rules.map((rule) => {
    if (rule) {
      if (rule.type === 'media') {
        rule.rules = rule.rules.map((mediaRule) => {
          return processRule(mediaRule);
        });
      } else if (rule.type === 'rule') {
        processRule(rule);
      }
    }

    return rule;
  });

  return css.stringify(cssAst, {
    indent: '',
    compress: true
  });
}
Example #11
0
function generateCss(sourcePath, fileContent) {
  var generator = new SourceMapGenerator({ file: sourcePath });
  var ast = css.parse(fileContent, { silent: true });

  function registerTokens(ast) {
    if (ast.position) {
      generator.addMapping({
        original: ast.position.start,
        generated: ast.position.start,
        source: sourcePath,
      });
    }

    for (var key in ast) {
      if (key === 'position' || !ast[key]) {
        break;
      }
      if (Object.prototype.toString.call(ast[key]) === '[object Object]') {
        registerTokens(ast[key]);
      } else if (Array.isArray(ast[key])) {
        ast[key].forEach(registerTokens);
      }
    }
  }
  registerTokens(ast);
  generator.setSourceContent(sourcePath, fileContent);

  return generator.toJSON();
}
Example #12
0
pro.parse = function(config){
    // parse css content
    var css = require('css'),
        ast = css.parse(
            this._source,{
                silent:!0,
                source:this._file
            }
        ),
        err = ast.stylesheet.parsingErrors;
    // check parse error
    if (!!err&&err.length>0){
        err = err[0];
        delete err.source;
        this.emit('warn',{
            data:[err],
            message:'illegal style content %j'
        });
        this._source = this._completeResource(
            this._source,config
        );
        return;
    }
    // complete resouce path
    this._checkResource(
        ast.stylesheet.rules||[],config
    );
    this._source = css.stringify(ast,{
        indent:0,
        compress:!0,
        sourcemap:!1,
        inputSourcemaps:!1
    });
};
    function fetchClasses(text, classes) {
        var parsedCss = css.parse(text);
        
        // go through each of the rules...
        parsedCss.stylesheet.rules.forEach(function (rule) {
            // ...of type rule
            if (rule.type === 'rule') {
                // go through each of the selectors of the current rule 
                rule.selectors.forEach(function (selector) {
                    var classesRegex = /[.]([\w-]+)/g;
                    var tempClasses = [];
                    var item = null;
                    
                    // check if the current selector contains class names
                    while (item = classesRegex.exec(selector)) {
                        tempClasses.push(item[1]);
                    }

                    if (tempClasses.length > 0) {
                        // extract class names specified on the current selector
                        // and then go through each of them
                        tempClasses.forEach(function (className) {
                            // check if the current class name is not in the classes array
                            if (classes.indexOf(className) === -1) {
                                // if so adds it to it
                                classes.push(className);
                            }
                        });
                    }
                });
            }
        });

        return classes;
    }
Example #14
0
module.exports = function(css){
  var ast = parse(css)

  ast = ruleReplacer(ast, pseudopseudo.replace)

  var selectors = getSelectors(ast)
  selectors = sortSpecificity(selectors).reverse()

  var styles = exposeRuleStyles(ast)

  return {
    get css(){
      return css
    },
    get sortedSelectors(){
      return selectors
    },
    get selectors(){
      return selectors
    },
    get styles(){
      return styles
    }
  }
}
Example #15
0
// Parse a style attribute string (a set of declarations)
function parseStyleAttribute(style) {
  // Wrap the style declarations around a fake selector so that the CSS parser
  // can parse it.
  var csstree = parseCSS("fake-selector { " + style + " }");
  // Pull out just the declarations from the parsed object
  return csstree.stylesheet.rules[0].declarations;
}
Example #16
0
    grunt.registerTask("icon", "SVG Icon Build", function() {
        var content = fs.readFileSync(grunt.config("icon.css"), { encoding : "utf8" }),
            obj = css.parse(content),
            icons = [];

        obj.stylesheet.rules.forEach(function(item) {
            if (item.declarations && item.declarations[0] && item.declarations[0].property == "content"  ) {

                if (item.selectors[0].indexOf(".datepicker") > -1 || item.selectors[0].indexOf(".calendar") > -1) {

                }  else {
                    var obj = {
                        name : item.selectors[0].replace(".jui .icon-", "").replace(":before", ""),
                        content : '\\' + item.declarations[0].value.replace(/\"/g, "").replace(/[\\]+/g, 'u')
                    }

                    icons.push('\t\t"' + obj.name + '" : "' + obj.content + '"');
                }

            }
        })

        var str = 'jui.define("chart.icon.jennifer", [], function() {\n' +
            '\treturn ' +
            "{\n" + icons.join(",\r\n") + "\n\t}\n" +
            "});";

        fs.writeFileSync(grunt.config("icon.dist"), new Buffer(str));

        grunt.log.writeln("File " + grunt.config("icon.dist") + " created.");
    });
Example #17
0
function run(data) {
    const opts = _.defaults(cli.flags, {basePath: process.cwd()});
    ok = true;

    if (data) {
        // Detect html
        try {
            css.parse(data);
            opts.css = data;
        } catch (err) {
            opts.html = data;
        }
    }

    _.forEach(cli.input, file => {
        const tmp = read(file);
        try {
            css.parse(tmp);
            opts.css = tmp;
        } catch (err) {
            opts.html = tmp;
        }
    });

    if (!opts.html || !opts.css) {
        cli.showHelp();
    }

    try {
        const out = inlineCritical(opts.html, opts.css, opts);
        process.stdout.write(out.toString(), process.exit);
    } catch (err) {
        error(err);
    }
}
Example #18
0
function parseStyleSheet(path) {
  let maps = [],
    ast, rules;
  let content = fs.readFileSync(path);
  ast = css.parse("" + content);
  rules = ast.stylesheet.rules;

  for (let i = 0, len = rules.length; i < len; i++) {
    let item = rules[i],
      selector, decls;

    if (item.type == 'rule') {
      // statement
      selector = item.selectors;
      decls = item.declarations;
      let styles = decls.map ? decls.map(function(v, k) {
        return v.property + ":" + v.value + ";";
      }) : '';

      let tmp = {};
      tmp[selector] = styles.join("");
      maps.push(tmp);
    }
  }
  return maps;
}
module.exports = function(mod, graph) {
  if (!/.*\.(css|styl|sass|scss|less)$/.exec(mod.id)) return

  var ast = css.parse(mod.source.toString())

  var rewrites = ast.stylesheet.rules
    .map(function(r) {
      if (r.type === 'rule' && r.selectors[0] == '@font-face') {
        return r.declarations.map(function(d) {
          var m = woffURL.exec(d.value)
          if (m)
            return {
              declaration: d,
              filename: m[2]
                .replace(/\?.*/, '')
                .replace(/^'/, '')
                .replace(/'$/, '')
            }
        }).filter(Boolean)[0]
      }
    })
    .filter(Boolean)
    .map(function(task) {
      var filename = path.resolve(path.dirname(mod.id), task.filename)
      return readFile(filename, {encoding: 'base64'})
        .then(function(data) {
          task.declaration.value = (
            'url(data:application/woff;charset=utf-8;base64,' +
            data + ") format('woff')")
        })
    })

  return q.all(rewrites).then(function() { return {source: css.stringify(ast)} })
}
Example #20
0
      }).map(function(filepath) {
        var newCssString = '';
        var extname = path.extname(filepath);
        //html后缀
        if (options.htmlExt.indexOf(extname) != -1) {
          var html = grunt.file.read(filepath);
          var $ = cheerio.load(html,{
            decodeEntities:false
          });
          var destDir = f.orig.dest;
          removeTagsByClass($,destDir);
          // replaceSpmTagForMT($);
          replaceMtTag($,destDir);
          replaceCssTag($,destDir);

          grunt.file.write(f.dest, $.html().replace(/&apos;/gi, "'"));
          grunt.log.writeln('html File "' + f.dest + '" created.');
        }

        if (options.cssExt.indexOf(extname) != -1) {
          var html = grunt.file.read(filepath);
          var cssParse = css.parse(html);
          var newCss = handleCss(cssParse);
          grunt.file.write(f.dest, newCss);
          grunt.log.writeln('css File "' + f.dest + '" created.');
        }

      });
Example #21
0
                        .then(function(fileContent) {
                            fileContent += '';
                            var line = 0,
                                lines = fileContent.replace(/\\r\\n/g, '\n').split('\n'),
                                ast = css.parse(fileContent),
                                ctx = {
                                    media: 0
                                },
                                out = [];

                            for (var r = 0; r < ast.stylesheet.rules.length; r++) {
                                line = processRule(
                                    ast.stylesheet.rules[r],
                                    {
                                        line: line,
                                        lines: lines,
                                        byfile: byfile,
                                        file: file,
                                        out: out
                                    },
                                    ctx);
                            }

                            return qfs.write(
                                path.join('gemini-coverage', url.parse(file).pathname.replace(/\//g, '_') + '.html'),
                                hb.compile(tmpl)({blocks: out}));
                        });
Example #22
0
        return new Promise(function (resolve) {
            var pathProps = {
                'path': path,
                'props': {}
            };

            _.each(cssProps, function (item) {
                pathProps.props[item] = [];
            });

            var ast = css.parse(content, {source: path});
            _.each(ast.stylesheet.rules, function (rule) {
                _.each(rule.declarations, function (dec) {
                    if (cssProps.indexOf(dec.property) !== -1) {
                        pathProps.props[dec.property].push(dec.value);
                    }
                });
            });

            _.each(pathProps.props, function (item, key) {
                pathProps.props[key] = _.uniq(item);
            });

            resolve(pathProps);
        });
Example #23
0
function DeadStyleEliminator(src, options) {
  this.ast = css.parse(src);
  var selectors = this.selectors = [];
  var rules = this.rules = {};
  function walk(node) {
    if (node.type === 'stylesheet') {
      node.stylesheet.rules.forEach(walk);
    } else if (node.type === 'media') {
      node.rules.forEach(walk);
    } else if (node.type === 'rule') {
      var selector = node.selectors.map(function (selector) {
        return selector.split(':')[0];
      }).join(', ');
      if (options && options.ignore && options.ignore.some(function (ignore) {
        return selector.indexOf(ignore) !== -1;
      })) {
        return;
      }
      if (selectors.indexOf(selector) === -1) {
        selectors.push(selector);
        rules[selector] = [];
      }
      rules[selector].push(node);
    }
  }
  walk(this.ast);
}
Example #24
0
/**
 * BiDi flip a CSS string.
 *
 * @param {String} str
 * @param {Object} [options]
 *   @param {Boolean} [options.compress] Whether to slightly compress output.
 *     Some newlines and indentation are removed. Comments stay intact.
 *   @param {String} [options.indent] Default is `'  '` (two spaces).
 * @returns {String}
 */
function flip(str, options) {
  var ast = css.parse(str, options);

  flipNode(ast.stylesheet);

  return css.stringify(ast, options);
}
Example #25
0
function convertCssToD3Rules(cssText) {
	var d3Rules = "",
		obj = css.parse(cssText),
		rules = obj.stylesheet.rules;


	rules.forEach(function (rule) {
		if (rule.type === "rule") {
			var builder = d3RuleBuilder(),
				selectors = rule.selectors,
				declarations = rule.declarations,
				declaration;

			builder.selectors(selectors);
			for (var i = 0, l = declarations.length; i < l; i++) {
				declaration = declarations[i];
				if (declaration.type === "declaration") {
					builder.addRule(declaration.property, declaration.value);
				}
			}

			d3Rules = d3Rules.concat(builder.build(), "\n");
		}
	});

	return d3Rules;
}
Example #26
0
    return through.obj(function (file, enc, cb) {

        if (file.isNull()) {
            cb();
            return;
        }

        if (file.isStream()) {
            this.emit('error', new PluginError('gulp-css-merge-url', 'Streaming not supported'));
            cb();
            return;
        }

        var css = null;
        var CSSObjects = {};

        if (file.isBuffer()) {
            css = file.contents.toString();
            css = cssparse.parse(css);
        }

        if (typeof css !== 'undefined' && css) {
            if (css.type === 'stylesheet' && css.stylesheet.rules.length > 0) {
                goCMU(css.stylesheet.rules, CSSObjects);
            }

            if (file.isBuffer() && Object.keys(CSSObjects).length > 0) {
                insertCSSObject(CSSObjects, css);
                file.contents = new Buffer(cssparse.stringify(css));
            }
        }

        cb(null, file);
    });
Example #27
0
module.exports = function(source) {
  if (this.cacheable) {
    this.cacheable();
  }

  var stylesheet = css.parse(source).stylesheet;

  if (stylesheet.parsingErrors.length) {
    throw new Error('Parsing Error occured.');
  }

  var stylesheet = {};

  stylesheet.rules.forEach(function(rule) {
    var style = {};

    if (rule.type === RULE) {
      rule.declarations.forEach(function(declaration) {
        var camelCaseProperty = convertProp(declaration.property)
        style[camelCaseProperty] = convertValue(camelCaseProperty, declaration.value);
      });
    }

    rule.selectors.forEach(function(selector) {
      stylesheet[sanitizeSelector(selector)] = style;
    });
  });

  return stylesheet;
};
Example #28
0
    parse: function(content) {
        var self = this,
            obj = css.parse(content),
            mergeIndexList = [];

        utils.cssBgWalk({
            cssAst: obj,
            options: self.options,
            ruleStartHandler: function() {
                mergeIndexList = [];
            },
            declareHandler: function (declare, index, list) {
                if (declare.property === "merge" || declare.property === 'imerge') {
                    mergeIndexList.push(index);
                }
            },
            ruleDoneHandler: function (rule, ruleResult, merge, isHack) {
                mergeIndexList.sort(function (a, b) {
                    return a < b;
                });
                _.each(mergeIndexList, function (mergeIndex) {
                    rule.declarations.splice(mergeIndex, 1);
                });
                _.each(ruleResult, function (bgObj) {
                    self.rewriteBackground(rule, bgObj.bgDecls, bgObj.merge, bgObj.isHack);
                });
            }
        });

        return obj;
    },
Example #29
0
function parseCSSFonts(item, cssText) {
    var sheet;
    var dblQuote = /(^['"])|(['"]$)/g

    try {
        sheet = parseCSS(cssText).stylesheet;
    } catch(e) {
        console.log("Error with style sheet", item.url, e.message);
        return;
    }
    var fntFaces = sheet.rules.filter(function(r) {
        return r.type === 'font-face';
    });

    if (!item.fontFamilies || CLEAN)
        item.fontFamilies = [];

    if (fntFaces.length > 0) {
        // console.log("Got some font-faces");
        fntFaces.forEach(function(f) {
            f.declarations.forEach(function(dec) {
                if (dec.type === 'declaration' && dec.property === 'font-family') {
                    var val = dec.value.replace(dblQuote, '')
                    if ( CLEAN || item.fontFamilies.indexOf( val ) === -1) {
                        item.fontFamilies.push(val);
                    }
                }
            })
        });
    }

    var imports = sheet.rules.filter(function(r) {
        return r.type === 'import'
    })
    if (imports.length > 0) {
        console.warn(chalk.yellow("Skipping imports for", item.url));
    }

    sheet.rules.forEach(function(r) {
        if (r.type !== "rule")
            return;

        r.declarations.forEach(function(prop) {
            // if (prop === 'font') {
            //     // item.fontStyles.push(prop.value)
            // } else 
            if (prop === 'font-family') {
                item.fontFamilies.push(prop.value.replace(dblQuote, ''));
            }
        })
    });


    item.fontFamilies = uniq(item.fontFamilies);
    // item.fontStyles = uniq(item.fontStyles);

    if (item.fontFamilies.length>0)
        console.log(item.url, item.fontFamilies);
}
Example #30
0
module.exports = function(html, selectors, cb){
  var $ = cheerio.load(html)

  // expose style
  var rules = parse($("style").text()).stylesheet.rules // BAD
  var selectorStyles = {}
  rules.forEach(function(rule){
    if(rule.type !== "rule") return;
    rule.selectors.forEach(function(selector){
      selectorStyles[selector] = rule.declarations
    })
  })
  // applicate style
  selectors = sortSpecificity(selectors).reverse()
  selectors.forEach(function(selector){
    var styles = selectorStyles[selector]
    if(!styles) return
    $(selector).each(function(){
      var self = this
      styles.forEach(function(style){
        $(self).css(style.property, style.value)
      })
    })
  })
  // import
  selectors.forEach(function(selector){
    var styles = selectorStyles[selector]
    if(!styles) return
    $(selector).each(function(){
      var self = this
      styles.forEach(function(style){
        if(/\!important/.test(style.value)){
          $(self).css(style.property, style.value)
        }
      })
    })
  })


  // get styles
  var result = {}
  selectors.forEach(function(selector){
    var find = function($, selector){
      var $item;
      $(selector).each(function(i){
        var dataSelector = $(this).data('selector')
        if(selector == dataSelector){
          $item = $(this)
        }
      })
      return $item
    }
    var $elm = find($, selector)
    result[selector] = $elm.css()
  })

  cb(null, result)

}