transform-tree.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. var contexts = require("./contexts"),
  2. visitor = require("./visitors"),
  3. tree = require("./tree");
  4. module.exports = function(root, options) {
  5. options = options || {};
  6. var evaldRoot,
  7. variables = options.variables,
  8. evalEnv = new contexts.Eval(options);
  9. //
  10. // Allows setting variables with a hash, so:
  11. //
  12. // `{ color: new tree.Color('#f01') }` will become:
  13. //
  14. // new tree.Rule('@color',
  15. // new tree.Value([
  16. // new tree.Expression([
  17. // new tree.Color('#f01')
  18. // ])
  19. // ])
  20. // )
  21. //
  22. if (typeof variables === 'object' && !Array.isArray(variables)) {
  23. variables = Object.keys(variables).map(function (k) {
  24. var value = variables[k];
  25. if (! (value instanceof tree.Value)) {
  26. if (! (value instanceof tree.Expression)) {
  27. value = new tree.Expression([value]);
  28. }
  29. value = new tree.Value([value]);
  30. }
  31. return new tree.Rule('@' + k, value, false, null, 0);
  32. });
  33. evalEnv.frames = [new tree.Ruleset(null, variables)];
  34. }
  35. var preEvalVisitors = [],
  36. visitors = [
  37. new visitor.JoinSelectorVisitor(),
  38. new visitor.MarkVisibleSelectorsVisitor(true),
  39. new visitor.ExtendVisitor(),
  40. new visitor.ToCSSVisitor({compress: Boolean(options.compress)})
  41. ], i;
  42. if (options.pluginManager) {
  43. var pluginVisitors = options.pluginManager.getVisitors();
  44. for (i = 0; i < pluginVisitors.length; i++) {
  45. var pluginVisitor = pluginVisitors[i];
  46. if (pluginVisitor.isPreEvalVisitor) {
  47. preEvalVisitors.push(pluginVisitor);
  48. } else {
  49. if (pluginVisitor.isPreVisitor) {
  50. visitors.splice(0, 0, pluginVisitor);
  51. } else {
  52. visitors.push(pluginVisitor);
  53. }
  54. }
  55. }
  56. }
  57. for (i = 0; i < preEvalVisitors.length; i++) {
  58. preEvalVisitors[i].run(root);
  59. }
  60. evaldRoot = root.eval(evalEnv);
  61. for (i = 0; i < visitors.length; i++) {
  62. visitors[i].run(evaldRoot);
  63. }
  64. return evaldRoot;
  65. };