<commit_before>
(function( _, halisConfig ) {
  var ns;

  (function() {
    var globalNS, conflict;
    globalNS = halisConfig.namespace || 'halis';
    if (window[globalNS]) {
      conflict = window[globalNS];
    }
    ns = window[globalNS] = {};

    if (!window.h) window.h = ns;

    ns.noConflict = function() {
      if (conflict) {
        window[globalNS] = conflict;
      }

      return this;
    };
    delete window.halisConfig;
  }());

  ns.typeNames = {
  	Boolean: 'Boolean',
  	Number: 'Number',
  	String: 'String',
  	Date: 'Date',
  	RegExp: 'RegExp',
  	Array: 'Array',
  	Object: 'Object',
  	Element: 'Element',
  	Function: 'Function',
  };
  ns.types = _.keys(ns.typeNames);

  String.prototype.isEmptyOrWhiteSpace = String.prototype.isEmptyOrWhiteSpace || function() {
    return this.trim() === '';
  };

  String.prototype.format = String.prototype.format || function() {
    var args, regex, esc, lb, rb, lbReplace, rbReplace, argReplace, ctr, that, delimiter;

    that = this;
    if (that.isEmptyOrWhiteSpace()) return that;
    args = _.toArray(arguments);
    if (!args || !args.length) return that;

    esc = '\\';
    lb = '{';
    rb = '}';
    that = that.toString();

    delimiter = '##%%';
    regex = new RegExp(esc + lb + esc + lb, 'g');
    lbReplace = delimiter + 'leftbracketreplace' + delimiter;
    that = that.replace(regex, lbReplace);

    regex = new RegExp(esc + rb + esc + rb, 'g');
    rbReplace = delimiter + 'rightbracketreplace' + delimiter;
    that = that.replace(regex, rbReplace);

    ctr = 0;
    _.each(args, function( arg ) {
      if (!_.isString(arg)) arg = arg.toString();

      argReplace = delimiter + ctr.toString() + delimiter;
      regex = new RegExp(esc + lb + ctr.toString() + esc + rb, 'g');
      that = that.replace(regex, argReplace);
      ctr++;
    }.bind(that));

    ctr = 0;
    _.each(args, function( arg ) {
      argReplace = delimiter + ctr.toString() + delimiter;
      regex = new RegExp(argReplace, 'g');
      that = that.replace(regex, arg);
      ctr++;
    }.bind(that));

    regex = new RegExp(lbReplace, 'g');
    that = that.replace(regex, lb);

    regex = new RegExp(rbReplace, 'g');
    that = that.replace(regex, rb);

    return that;
  };

  Array.prototype.contains = Array.prototype.contains || function( val ) {
    return this.indexOf(val) !== -1;
  };

  Date.prototype.toShortDateString = Date.prototype.toShortDateString || function() {
    return [this.getMonth() + 1,
            this.getDate(),
            this.getFullYear()
           ].join('/');
  };

  Date.prototype.toShortTimeString = Date.prototype.toShortTimeString || function() {
    var hours = this.getHours();

    return [hours - 12,
            this.getMinutes()
           ].join(':') + ' ' + (hours < 12 ? 'AM' : 'PM');
  };

  Date.prototype.toShortDateTimeString = Date.prototype.toShortDateTimeString || function() {
    return this.toShortDateString() + ' ' + this.toShortTimeString();
  }

  Date.prototype.toSortString = Date.prototype.toSortString || function() {
    var month, date, hours, minutes, seconds, ms;

    month = this.getMonth();
    date = this.getDate();
    hours = this.getHours();
    minutes = this.getMinutes();
    seconds = this.getSeconds();
    ms = this.getMilliseconds();

    function pad( num ) {
      if (num > 9) return num.toString();
      else return '0' + num;
    }

    function padMS( num ) {
      if (num > 99) return num.toString();
      else if (num > 9) return '0' + num;
      else return '00' + num;
    }

    return [this.getFullYear(),
            pad(month),
            pad(date),
            pad(hours),
            pad(minutes),
            pad(seconds),
            padMS(ms)
           ].join(':');
  };

  _.each(ns.types, function( type ) {
    var fn, fnName;

    fn = 'is{0}'.format(type);
    fnName = '{0}OrThrow'.format(fn);

    ns[fnName] = function( obj ) {
      if (!_[fn](obj)) throw 'value is not of type {0}'.format(type);
    };
  });

  ns.isArrayAndNotEmptyOrThrow = function( obj ) {
    ns.isArrayOrThrow(obj);
    if (_.isEmpty(obj)) throw 'value is empty';
  };

  ns.isObjectAndNotEmptyOrThrow = function( obj ) {
    ns.isObjectOrThrow(obj);
    if (_.isEmpty(obj)) throw 'value is empty';
  };

  ns.isStringNotEmptyOrThrow = function( obj ) {
    ns.isStringOrThrow(obj);
    if (obj.isEmptyOrWhiteSpace()) throw 'value is empty';
  };

  function HtmlCollection( arr ) {
    var that = this, h = {};
    ns.isArrayOrThrow(arr);
    that.elements = arr;

    that.pop = function() {
      return that.elements.pop();
    };

    that.push = function( val ) {
      that.elements.push(val);
      return that.elements;
    };

    return that;
  }

  function query( q, fnName ) {
    ns.isStringOrThrow(q);
    return new HtmlCollection(_.toArray(document[fnName](q)));
  }

  ns.q = ns.query = {};

  ns.q.i = ns.q.id = function( id ) {
    var el;
    ns.isStringOrThrow(id);
    el = document.getElementById(id);
    return new HtmlCollection(el ? [el] : []);
  };

  ns.q.c = ns.q.class = function( className ) {
    return query(className, 'getElementsByClassName');
  };

  ns.q.t = ns.q.tag = function( tagName ) {
    return query(tagName, 'getElementsByTagName');
  };

  ns.q.n = ns.q.name = function( name ) {
    return query(name, 'getElementsByName');
  };

  ns.q.a = ns.q.all = function( qry ) {
    return query(qry, 'querySelectorAll');
  };

  function ajaxFn( method, url, data, successFn, errorFn ) {
    var xhr;

    _.isStringOrThrow(url);
    if (successFn) _.isFunctionOrThrow(successFn);
    if (errorFn) _.isFunctionOrThrow(errorFn);

    xhr = new XMLHttpRequest();
    xhr.open(method, url);

    if (successFn || errorFn) {
      xhr.onreadystatechange = function (data) {
        // TODO: call successFn or errorFn in here
      }
    }

    if (data) xhr.send({ data: data });
    else xhr.send();
  }

  ns.ajax = {
    get: function( url, successFn, errorFn ) {
      ajaxFn('GET', url, null, successFn, errorFn);
    },
    post: function( url, data, successFn, errorFn ) {
      ajaxFn('POST', url, data, successFn, errorFn);
    }
  }

  HtmlCollection.prototype.html = function( html ) {
    ns.isStringOrThrow(html);
    _.each(this.elements, function( el ) {
      el.innerHTML = html;
    });

    return this;
  };

  HtmlCollection.prototype.append = function( html ) {
    ns.isStringOrThrow(html);
    _.each(this.elements, function( el ) {
      el.innerHTML += html;
    });

    return this;
  };

  HtmlCollection.prototype.empty = function() {
    _.each(this.elements, function( el ) {
      el.innerHTML = '';
    });

    return this;
  };

  HtmlCollection.prototype.text = function( text ) {
    ns.isStringOrThrow(text);
    _.each(this.elements, function( el ) {
      el.innerText = text;
    });

    return this;
  };

  HtmlCollection.prototype.attr = function( attr, val ) {
    var result;

    ns.isStringOrThrow(attr);

    if (val !== undefined) {
      _.each(this.elements, function( el ) {
        el.setAttribute(attr, val);
      });
      return this;
    }

    result = [];
    _.each(this.elements, function( el ) {
      result.push(el.getAttribute(attr));
    });

    return result;
  };

  HtmlCollection.prototype.attrs = function( attrs ) {
    ns.isObjectOrThrow(attrs);

    _.each(_.keys(attrs), function( key ) {
      this.attr(key, attrs[key]);
    }.bind(this));

    return this;
  };

  HtmlCollection.prototype.on = function( eventName, fn ) {
    var result;

    ns.isStringOrThrow(eventName);
    ns.isFunctionOrThrow(fn);

    _.each(this.elements, function( el ) {
      el.addEventListener(eventName, fn, false);

      if (!el.handlers) el.handlers = new HtmlHandlers(el);
      el.handlers.add(eventName, fn);
    });

    return this;
  };

  HtmlCollection.prototype.off = function( eventName ) {
    var handlers;

    ns.isStringOrThrow(eventName);

    _.each(this.elements, function( el ) {
      handlers = el.handlers.get()[eventName];
      _.each(handlers, function( handler ) {
        el.removeEventListener(eventName, handler);
      });
      if (!el.handlers) el.handlers = new HtmlHandlers(el);
      el.handlers.remove(eventName);
    });

    return this;
  };

  HtmlCollection.prototype.trigger = function( eventName ) {
    ns.isStringOrThrow(eventName);

    _.each(this.elements, function( el ) {
      if (el[eventName] && _.isFunction(el[eventName])) el[eventName]();
    });

    return this;
  };

  function classFn( className, fnName ) {
    ns.isStringNotEmptyOrThrow(className);

    _.each(this.elements, function( el ) {
      el.classList[fnName](className);
    });

    return this;
  }

  HtmlCollection.prototype.addClass = function( className ) {
    return classFn.bind(this)(className, 'add');
  };

  HtmlCollection.prototype.removeClass = function( className ) {
    return classFn.bind(this)(className, 'remove');
  };

  HtmlCollection.prototype.toggleClass = function( className ) {
    return classFn.bind(this)(className, 'toggle');
  };

  function cloneFn( deep ) {
    var result;

    ns.isBooleanOrThrow(deep);

    result = [];
    _.each(this.elements, function( el ) {
      result.push(el.cloneNode(deep));
    });

    return new HtmlCollection(result);
  }

  HtmlCollection.prototype.clone = function( ) {
    return cloneFn.bind(this)(true);
  };

  HtmlCollection.prototype.cloneShallow = function( ) {
    return cloneFn.bind(this)(false);
  };

  function siblingFn( fnName ) {
    var result;

    result = [];
    _.each(this.elements, function( el ) {
      result.push(el[fnName]);
    });

    return new HtmlCollection(result);
  }

  HtmlCollection.prototype.prev = function( ) {
    return siblingFn.bind(this)('previousElementSibling');
  };

  HtmlCollection.prototype.next = function( ) {
    return siblingFn.bind(this)('nextElementSibling');
  };

  function HtmlHandlers( el ) {
    var that = this;

    that.el = el;
    that.handlers = {};

    that.get = function() {
      return that.handlers;
    };

    that.add = function( eventName, handler ) {
      if (that.handlers[eventName]) that.handlers[eventName].push(handler);
      else that.handlers[eventName] = [handler];
    };

    that.remove = function( eventName ) {
      delete that.handlers[eventName];
    };

    return that;
  }

  ns.cancelEvent = function( e ) {
    e.preventDefault();
    e.stopImmediatePropagation();
    return false;
  };

}(_, window.halisConfig));
<commit_msg>one more spacing issue<commit_after>
(function( _, halisConfig ) {
  var ns;

  (function() {
    var globalNS, conflict;
    globalNS = halisConfig.namespace || 'halis';
    if (window[globalNS]) {
      conflict = window[globalNS];
    }
    ns = window[globalNS] = {};

    if (!window.h) window.h = ns;

    ns.noConflict = function() {
      if (conflict) {
        window[globalNS] = conflict;
      }

      return this;
    };
    delete window.halisConfig;
  }());

  ns.typeNames = {
  	Boolean: 'Boolean',
  	Number: 'Number',
  	String: 'String',
  	Date: 'Date',
  	RegExp: 'RegExp',
  	Array: 'Array',
  	Object: 'Object',
  	Element: 'Element',
  	Function: 'Function',
  };
  ns.types = _.keys(ns.typeNames);

  String.prototype.isEmptyOrWhiteSpace = String.prototype.isEmptyOrWhiteSpace || function() {
    return this.trim() === '';
  };

  String.prototype.format = String.prototype.format || function() {
    var args, regex, esc, lb, rb, lbReplace, rbReplace, argReplace, ctr, that, delimiter;

    that = this;
    if (that.isEmptyOrWhiteSpace()) return that;
    args = _.toArray(arguments);
    if (!args || !args.length) return that;

    esc = '\\';
    lb = '{';
    rb = '}';
    that = that.toString();

    delimiter = '##%%';
    regex = new RegExp(esc + lb + esc + lb, 'g');
    lbReplace = delimiter + 'leftbracketreplace' + delimiter;
    that = that.replace(regex, lbReplace);

    regex = new RegExp(esc + rb + esc + rb, 'g');
    rbReplace = delimiter + 'rightbracketreplace' + delimiter;
    that = that.replace(regex, rbReplace);

    ctr = 0;
    _.each(args, function( arg ) {
      if (!_.isString(arg)) arg = arg.toString();

      argReplace = delimiter + ctr.toString() + delimiter;
      regex = new RegExp(esc + lb + ctr.toString() + esc + rb, 'g');
      that = that.replace(regex, argReplace);
      ctr++;
    }.bind(that));

    ctr = 0;
    _.each(args, function( arg ) {
      argReplace = delimiter + ctr.toString() + delimiter;
      regex = new RegExp(argReplace, 'g');
      that = that.replace(regex, arg);
      ctr++;
    }.bind(that));

    regex = new RegExp(lbReplace, 'g');
    that = that.replace(regex, lb);

    regex = new RegExp(rbReplace, 'g');
    that = that.replace(regex, rb);

    return that;
  };

  Array.prototype.contains = Array.prototype.contains || function( val ) {
    return this.indexOf(val) !== -1;
  };

  Date.prototype.toShortDateString = Date.prototype.toShortDateString || function() {
    return [this.getMonth() + 1,
            this.getDate(),
            this.getFullYear()
           ].join('/');
  };

  Date.prototype.toShortTimeString = Date.prototype.toShortTimeString || function() {
    var hours = this.getHours();

    return [hours - 12,
            this.getMinutes()
           ].join(':') + ' ' + (hours < 12 ? 'AM' : 'PM');
  };

  Date.prototype.toShortDateTimeString = Date.prototype.toShortDateTimeString || function() {
    return this.toShortDateString() + ' ' + this.toShortTimeString();
  }

  Date.prototype.toSortString = Date.prototype.toSortString || function() {
    var month, date, hours, minutes, seconds, ms;

    month = this.getMonth();
    date = this.getDate();
    hours = this.getHours();
    minutes = this.getMinutes();
    seconds = this.getSeconds();
    ms = this.getMilliseconds();

    function pad( num ) {
      if (num > 9) return num.toString();
      else return '0' + num;
    }

    function padMS( num ) {
      if (num > 99) return num.toString();
      else if (num > 9) return '0' + num;
      else return '00' + num;
    }

    return [this.getFullYear(),
            pad(month),
            pad(date),
            pad(hours),
            pad(minutes),
            pad(seconds),
            padMS(ms)
           ].join(':');
  };

  _.each(ns.types, function( type ) {
    var fn, fnName;

    fn = 'is{0}'.format(type);
    fnName = '{0}OrThrow'.format(fn);

    ns[fnName] = function( obj ) {
      if (!_[fn](obj)) throw 'value is not of type {0}'.format(type);
    };
  });

  ns.isArrayAndNotEmptyOrThrow = function( obj ) {
    ns.isArrayOrThrow(obj);
    if (_.isEmpty(obj)) throw 'value is empty';
  };

  ns.isObjectAndNotEmptyOrThrow = function( obj ) {
    ns.isObjectOrThrow(obj);
    if (_.isEmpty(obj)) throw 'value is empty';
  };

  ns.isStringNotEmptyOrThrow = function( obj ) {
    ns.isStringOrThrow(obj);
    if (obj.isEmptyOrWhiteSpace()) throw 'value is empty';
  };

  function HtmlCollection( arr ) {
    var that = this, h = {};
    ns.isArrayOrThrow(arr);
    that.elements = arr;

    that.pop = function() {
      return that.elements.pop();
    };

    that.push = function( val ) {
      that.elements.push(val);
      return that.elements;
    };

    return that;
  }

  function query( q, fnName ) {
    ns.isStringOrThrow(q);
    return new HtmlCollection(_.toArray(document[fnName](q)));
  }

  ns.q = ns.query = {};

  ns.q.i = ns.q.id = function( id ) {
    var el;
    ns.isStringOrThrow(id);
    el = document.getElementById(id);
    return new HtmlCollection(el ? [el] : []);
  };

  ns.q.c = ns.q.class = function( className ) {
    return query(className, 'getElementsByClassName');
  };

  ns.q.t = ns.q.tag = function( tagName ) {
    return query(tagName, 'getElementsByTagName');
  };

  ns.q.n = ns.q.name = function( name ) {
    return query(name, 'getElementsByName');
  };

  ns.q.a = ns.q.all = function( qry ) {
    return query(qry, 'querySelectorAll');
  };

  function ajaxFn( method, url, data, successFn, errorFn ) {
    var xhr;

    _.isStringOrThrow(url);
    if (successFn) _.isFunctionOrThrow(successFn);
    if (errorFn) _.isFunctionOrThrow(errorFn);

    xhr = new XMLHttpRequest();
    xhr.open(method, url);

    if (successFn || errorFn) {
      xhr.onreadystatechange = function (data) {
        // TODO: call successFn or errorFn in here
      }
    }

    if (data) xhr.send({ data: data });
    else xhr.send();
  }

  ns.ajax = {
    get: function( url, successFn, errorFn ) {
      ajaxFn('GET', url, null, successFn, errorFn);
    },
    post: function( url, data, successFn, errorFn ) {
      ajaxFn('POST', url, data, successFn, errorFn);
    }
  }

  HtmlCollection.prototype.html = function( html ) {
    ns.isStringOrThrow(html);
    _.each(this.elements, function( el ) {
      el.innerHTML = html;
    });

    return this;
  };

  HtmlCollection.prototype.append = function( html ) {
    ns.isStringOrThrow(html);
    _.each(this.elements, function( el ) {
      el.innerHTML += html;
    });

    return this;
  };

  HtmlCollection.prototype.empty = function() {
    _.each(this.elements, function( el ) {
      el.innerHTML = '';
    });

    return this;
  };

  HtmlCollection.prototype.text = function( text ) {
    ns.isStringOrThrow(text);
    _.each(this.elements, function( el ) {
      el.innerText = text;
    });

    return this;
  };

  HtmlCollection.prototype.attr = function( attr, val ) {
    var result;

    ns.isStringOrThrow(attr);

    if (val !== undefined) {
      _.each(this.elements, function( el ) {
        el.setAttribute(attr, val);
      });
      return this;
    }

    result = [];
    _.each(this.elements, function( el ) {
      result.push(el.getAttribute(attr));
    });

    return result;
  };

  HtmlCollection.prototype.attrs = function( attrs ) {
    ns.isObjectOrThrow(attrs);

    _.each(_.keys(attrs), function( key ) {
      this.attr(key, attrs[key]);
    }.bind(this));

    return this;
  };

  HtmlCollection.prototype.on = function( eventName, fn ) {
    var result;

    ns.isStringOrThrow(eventName);
    ns.isFunctionOrThrow(fn);

    _.each(this.elements, function( el ) {
      el.addEventListener(eventName, fn, false);

      if (!el.handlers) el.handlers = new HtmlHandlers(el);
      el.handlers.add(eventName, fn);
    });

    return this;
  };

  HtmlCollection.prototype.off = function( eventName ) {
    var handlers;

    ns.isStringOrThrow(eventName);

    _.each(this.elements, function( el ) {
      handlers = el.handlers.get()[eventName];
      _.each(handlers, function( handler ) {
        el.removeEventListener(eventName, handler);
      });
      if (!el.handlers) el.handlers = new HtmlHandlers(el);
      el.handlers.remove(eventName);
    });

    return this;
  };

  HtmlCollection.prototype.trigger = function( eventName ) {
    ns.isStringOrThrow(eventName);

    _.each(this.elements, function( el ) {
      if (el[eventName] && _.isFunction(el[eventName])) el[eventName]();
    });

    return this;
  };

  function classFn( className, fnName ) {
    ns.isStringNotEmptyOrThrow(className);

    _.each(this.elements, function( el ) {
      el.classList[fnName](className);
    });

    return this;
  }

  HtmlCollection.prototype.addClass = function( className ) {
    return classFn.bind(this)(className, 'add');
  };

  HtmlCollection.prototype.removeClass = function( className ) {
    return classFn.bind(this)(className, 'remove');
  };

  HtmlCollection.prototype.toggleClass = function( className ) {
    return classFn.bind(this)(className, 'toggle');
  };

  function cloneFn( deep ) {
    var result;

    ns.isBooleanOrThrow(deep);

    result = [];
    _.each(this.elements, function( el ) {
      result.push(el.cloneNode(deep));
    });

    return new HtmlCollection(result);
  }

  HtmlCollection.prototype.clone = function( ) {
    return cloneFn.bind(this)(true);
  };

  HtmlCollection.prototype.cloneShallow = function( ) {
    return cloneFn.bind(this)(false);
  };

  function siblingFn( fnName ) {
    var result;

    result = [];
    _.each(this.elements, function( el ) {
      result.push(el[fnName]);
    });

    return new HtmlCollection(result);
  }

  HtmlCollection.prototype.prev = function( ) {
    return siblingFn.bind(this)('previousElementSibling');
  };

  HtmlCollection.prototype.next = function( ) {
    return siblingFn.bind(this)('nextElementSibling');
  };

  function HtmlHandlers( el ) {
    var that = this;

    that.el = el;
    that.handlers = {};

    that.get = function() {
      return that.handlers;
    };

    that.add = function( eventName, handler ) {
      if (that.handlers[eventName]) that.handlers[eventName].push(handler);
      else that.handlers[eventName] = [handler];
    };

    that.remove = function( eventName ) {
      delete that.handlers[eventName];
    };

    return that;
  }

  ns.cancelEvent = function( e ) {
    e.preventDefault();
    e.stopImmediatePropagation();
    return false;
  };

}(_, window.halisConfig));
<|endoftext|>


<commit_before>module.exports = options => {
    const gulp    = options.gulp;
    const paths   = options.paths;
    const plugins = options.plugins;

    return {
        sass: function () {
            return gulp.src('/');
        },
        js: function () {
            return gulp.src('/');
        },
        css: function () {
            return gulp.src(gulp.data.get('paths.dev.base') + '/**/*.css')
                .pipe(plugins.csslint(gulp.data.get('paths.config.csslint')))
                .pipe(plugins.csslint.formatter());
        },
        html: function () {
            return gulp.src('/');
        },
    };
};
<commit_msg>updated arrow functions<commit_after>module.exports = options => {
    const gulp    = options.gulp;
    const paths   = options.paths;
    const plugins = options.plugins;

    return {
        sass: () => {
            return gulp.src('/');
        },
        js: () => {
            return gulp.src('/');
        },
        css: () => {
            return gulp.src(gulp.data.get('paths.dev.base') + '/**/*.css')
                .pipe(plugins.csslint(gulp.data.get('paths.config.csslint')))
                .pipe(plugins.csslint.formatter());
        },
        html: () => {
            return gulp.src('/');
        },
    };
};
<|endoftext|>


<commit_before>module.exports = {
    // 'custom' maps custom suffixes to values and it is specially useful for theming
    // or things that you need to change globally in many different atomic classes.
    // these key/value pairs map to the custom suffixes in 'classNames'.
    // i.e. H-uh will get height: 79px and C-primary will get color: #f6a1e1
    'custom': {
        uh: '79px',         // custom 1 (see classNames below)
        primary: '#f6a1e1'  // custom 2 (see classNames below)
    },
    // breakpoints define media queries and is used to contain the style of a class
    // only when that media query is active.
    // i.e. given the breakpoint below, `D-b--sm` will be inside of the media query
    // `@media(min-width:500px)`, meaning that it will only apply `display:block`
    // once the viewport has at least 500px.
    breakPoints: {
        'sm': '@media(min-width:500px)', // breakpoint 1 (see classNames below)
        'md': '@media(min-width:900px)', // breakpoint 2
        'lg': '@media(min-width:1200px)' // breakpoint 3
    },
    // this is the list of atomic class names your project uses.
    // you don't have to explictly declare them like this since atomizer can parse
    // any file and create this list automatically for you.  However, you always
    // have the option to explicitly declare classnames if you find it helpful for your
    // project.
    'classNames': [
        'H-uh',            // custom 1 (maps to 'custom' key above)
        'C-primary',       // custom 2 (maps to 'custom' key above)
        'Td-u',            // normal
        'Td-u:h',          // pseudo classs
        'D-b--sm',         // breakpoint 1
        'foo>W-uh',        // descendent
        'D-n!',            // important
        'Op-1!',           // important
        'Fl-start',        // normal (rtl support)
        'Fl-end',          // normal (rtl support)
        'W-1/12',          // fraction
        'W-2/12',          // fraction
        'W-3/12',          // fraction
        'W-4/12',          // fraction
        'W-5/12',          // fraction
        'W-6/12',          // fraction
        'W-7/12',          // fraction
        'W-8/12',          // fraction
        'W-9/12',          // fraction
        'W-10/12',         // fraction
        'W-11/12',         // fraction
        'W-12/12',         // fraction
        'W-1/12--sm'       // fraction with breakpoint
    ]
};<commit_msg>Adding examples of hex values<commit_after>module.exports = {
    // 'custom' maps custom suffixes to values and it is specially useful for theming
    // or things that you need to change globally in many different atomic classes.
    // these key/value pairs map to the custom suffixes in 'classNames'.
    // i.e. H-uh will get height: 79px and C-primary will get color: #f6a1e1
    'custom': {
        uh: '79px',             // custom 1 (see classNames below)
        primary: '#f6a1e1'      // custom 2 (see classNames below)
    },
    // breakpoints define media queries and is used to contain the style of a class
    // only when that media query is active.
    // i.e. given the breakpoint below, `D-b--sm` will be inside of the media query
    // `@media(min-width:500px)`, meaning that it will only apply `display:block`
    // once the viewport has at least 500px.
    breakPoints: {
        'sm': '@media(min-width:500px)', // breakpoint 1 (see classNames below)
        'md': '@media(min-width:900px)', // breakpoint 2
        'lg': '@media(min-width:1200px)' // breakpoint 3
    },
    // this is the list of atomic class names your project uses.
    // you don't have to explictly declare them like this since atomizer can parse
    // any file and create this list automatically for you.  However, you always
    // have the option to explicitly declare classnames if you find it helpful for your
    // project.
    'classNames': [
        'H-uh',            // custom 1 (maps to 'custom' key above)
        'C-primary',       // custom 2 (maps to 'custom' key above)
        'Td-u',            // normal
        'Td-u:h',          // pseudo classs
        'D-b--sm',         // breakpoint 1
        'foo>W-uh',        // descendent
        'D-n!',            // important
        'Op-1!',           // important
        'Fl-start',        // normal (rtl support)
        'Fl-end',          // normal (rtl support)
        'W-1/12',          // fraction
        'W-2/12',          // fraction
        'W-3/12',          // fraction
        'W-4/12',          // fraction
        'W-5/12',          // fraction
        'W-6/12',          // fraction
        'W-7/12',          // fraction
        'W-8/12',          // fraction
        'W-9/12',          // fraction
        'W-10/12',         // fraction
        'W-11/12',         // fraction
        'W-12/12',         // fraction
        'W-1/12--sm',      // fraction with breakpoint
        'Bgc-#333',        // hex value
        'Bgc-#fff.8'       // hex value + alpha
    ]
};
<|endoftext|>


<commit_before>FBL.ns(function() { with (FBL) {

// list taken from FirePalette (http://blog.endflow.net/?p=143)
var colorNames = {
  aliceblue: "f0f8ff", antiquewhite: "faebd7", aqua: "00ffff",
  aquamarine: "7fffd4", azure: "f0ffff", beige: "f5f5dc",
  bisque: "ffe4c4", black: "000000", blanchedalmond: "ffebcd",
  blue: "0000ff", blueviolet: "8a2be2", brown: "a52a2a",
  burlywood: "deb887", cadetblue: "5f9ea0", chartreuse: "7fff00",
  chocolate: "d2691e", coral: "ff7f50", cornflowerblue: "6495ed",
  cornsilk: "fff8dc", crimson: "dc143c", cyan: "00ffff",
  darkblue: "00008b", darkcyan: "008b8b", darkgoldenrod: "b8860b",
  darkgray: "a9a9a9", darkgreen: "006400", darkkhaki: "bdb76b",
  darkmagenta: "8b008b", darkolivegreen: "556b2f", darkorange: "ff8c00",
  darkorchid: "9932cc", darkred: "8b0000", darksalmon: "e9967a",
  darkseagreen: "8fbc8f", darkslateblue: "483d8b", darkslategray: "2f4f4f",
  darkturquoise: "00ced1", darkviolet: "9400d3", deeppink: "ff1493",
  deepskyblue: "00bfff", dimgray: "696969", dodgerblue: "1e90ff",
  feldspar: "d19275", firebrick: "b22222", floralwhite: "fffaf0",
  forestgreen: "228b22", fuchsia: "ff00ff", gainsboro: "dcdcdc",
  ghostwhite: "f8f8ff", gold: "ffd700", goldenrod: "daa520",
  gray: "808080", green: "008000", greenyellow: "adff2f",
  honeydew: "f0fff0", hotpink: "ff69b4", indianred : "cd5c5c",
  indigo : "4b0082", ivory: "fffff0", khaki: "f0e68c",
  lavender: "e6e6fa", lavenderblush: "fff0f5", lawngreen: "7cfc00",
  lemonchiffon: "fffacd", lightblue: "add8e6", lightcoral: "f08080",
  lightcyan: "e0ffff", lightgoldenrodyellow: "fafad2", lightgrey: "d3d3d3",
  lightgreen: "90ee90", lightpink: "ffb6c1", lightsalmon: "ffa07a",
  lightseagreen: "20b2aa", lightskyblue: "87cefa", lightslateblue: "8470ff",
  lightslategray: "778899", lightsteelblue: "b0c4de", lightyellow: "ffffe0",
  lime: "00ff00", limegreen: "32cd32", linen: "faf0e6",
  magenta: "ff00ff", maroon: "800000", mediumaquamarine: "66cdaa",
  mediumblue: "0000cd", mediumorchid: "ba55d3", mediumpurple: "9370d8",
  mediumseagreen: "3cb371", mediumslateblue: "7b68ee", mediumspringgreen: "00fa9a",
  mediumturquoise: "48d1cc", mediumvioletred: "c71585", midnightblue: "191970",
  mintcream: "f5fffa", mistyrose: "ffe4e1", moccasin: "ffe4b5",
  navajowhite: "ffdead", navy: "000080", oldlace: "fdf5e6",
  olive: "808000", olivedrab: "6b8e23", orange: "ffa500",
  orangered: "ff4500", orchid: "da70d6", palegoldenrod: "eee8aa",
  palegreen: "98fb98", paleturquoise: "afeeee", palevioletred: "d87093",
  papayawhip: "ffefd5", peachpuff: "ffdab9", peru: "cd853f",
  pink: "ffc0cb", plum: "dda0dd", powderblue: "b0e0e6",
  purple: "800080", red: "ff0000", rosybrown: "bc8f8f",
  royalblue: "4169e1", saddlebrown: "8b4513", salmon: "fa8072",
  sandybrown: "f4a460", seagreen: "2e8b57", seashell: "fff5ee",
  sienna: "a0522d", silver: "c0c0c0", skyblue: "87ceeb",
  slateblue: "6a5acd", slategray: "708090", snow: "fffafa",
  springgreen: "00ff7f", steelblue: "4682b4", tan: "d2b48c",
  teal: "008080", thistle: "d8bfd8", tomato: "ff6347",
  turquoise: "40e0d0", violet: "ee82ee", violetred: "d02090",
  wheat: "f5deb3", white: "ffffff", whitesmoke: "f5f5f5",
  yellow: "ffff00", yellowgreen: "9acd32"
};

// taken from Firebug | css.js
var reSplitCSS = /(url\("?[^"\)]+?"?\))|(rgb\(.*?\))|(#[\dA-Fa-f]+)|(-?\d+(\.\d+)?(%|[a-z]{1,2})?)|([^,\s]+)|"(.*?)"/;

function parseCSSValue(value, offset) {
  var start = 0;
  var m;
  while (1)
  {
    m = reSplitCSS.exec(value);
    if (m && m.index+m[0].length < offset)
    {
      value = value.substr(m.index+m[0].length);
      start += m.index+m[0].length;
      offset -= m.index+m[0].length;
    }
    else
    break;
  }

  if (m)
  {
    var type;
    if (m[1])
    type = "url";
    else if (m[2] || m[3])
    type = "rgb";
    else if (m[4])
    type = "int";

    return {value: m[0], start: start+m.index, end: start+m.index+(m[0].length-1), type: type};
  }
}

function rgbToHex(value) {
  return value.replace(/\brgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)/gi, function(_, r, g, b) {
    return '#' + ((1 << 24) + (r << 16) + (g << 8) + (b << 0)).toString(16).substr(-6).toUpperCase();
  });
}
// end of firebug helpers

var splitCSSValues = function(cssValue) {
  var offset = 0, cssValues = [], cssValueLength = cssValue.length, nextValue = parseCSSValue(cssValue, offset), previousValue;
  while (nextValue) {
    cssValues.push(nextValue);
    offset        = nextValue.end + 1;
    previousValue = nextValue;
    while ((nextValue = parseCSSValue(cssValue, offset)) && nextValue.start == previousValue.start) { offset++; }
  }
  return cssValues;
};

var ColorsDropDown = function(editor, firepicker) {
  this.editor     = editor;
  this.firepicker = firepicker;
};

ColorsDropDown.prototype = {
  tags: domplate({
    container: DIV({'class': 'firepicker_color_container'}),
    valueCell: DIV({'class': 'color_value', style: 'background-color: $color;'},
      DIV({'class': 'css_text'}, '$color')
    )
  }),

  editorShown: function() {
    this.onValueChange();
    this.attachInputChangeHandler();
  },

  attachInputChangeHandler: function() {
    if (!this.boundOnValueChange) { this.boundOnValueChange = bind(this.onValueChange, this); }
    this.editor.input.addEventListener('input', this.boundOnValueChange, false);
  },

  getListContainer: function() {
    if (!this.listContainer) {
      this.listContainer = this.tags.container.insertAfter({}, getChildByClass(this.editor.box, 'textEditorBottom1'));
      this.addStylesheet(this.listContainer.ownerDocument);
    }
    return this.listContainer;
  },

  addStylesheet: function(doc) {
    if (!$('firepickerDropDownStyle', doc)) {
      var styleSheet = createStyleSheet(doc, 'chrome://firepicker/skin/css-attribute-dialog.css');
      styleSheet.setAttribute('id', 'firepickerDropDownStyle');
      addStyleSheet(doc, styleSheet);
    }
  },

  onValueChange: function() {
    this.updateList(this.getCSSColorValues());
  },

  getCSSColorValues: function() {
    return this.filterColorValues(splitCSSValues(this.editor.input.value));
  },

  filterColorValues: function(cssValues) {
    var colorValues = [], cssValue;
    for (var i = 0, len = cssValues.length; i < len; i++) {
      cssValue = cssValues[i];
      if (cssValue.type == 'rgb' || isColorKeyword(cssValue.value)) { colorValues.push(cssValue); }
    }
    return colorValues;
  },

  updateList: function(colorValues) {
    var container = this.getListContainer();
    eraseNode(container);
    for (var i = 0, len = colorValues.length; i < len; i++) { this.addColorCell(container, colorValues[i]); }
    container.style.display = colorValues.length == 0 ? 'none' : 'block';
  },

  addColorCell: function(container, colorValue) {
    var newCell = this.tags.valueCell.append({color: colorValue.value}, container);
    newCell.colorValue = colorValue;
    newCell.dropDown   = this;
    newCell.addEventListener('mousedown', this.cellMousedown, false);
  },

  cellMousedown: function(e) {
    cancelEvent(e);

    var input = this.dropDown.editor.input, text = this.firstChild, style = this.style, colorValue = this.colorValue;

    colorValue = extend(colorValue, {
      prefix: input.value.substring(0, colorValue.start),
      suffix: input.value.substring(colorValue.end + 1)
    });

    this.dropDown.openPopup(this, function(newValue) {
      input.value           = colorValue.prefix + newValue + colorValue.suffix;
      text.innerHTML        = newValue;
      style.backgroundColor = newValue;

      Firebug.Editor.update(true);
    });
  },

  openPopup: function(colorCell, callback) {
    this.firepicker.openPopup(this.editor, colorCell, colorCell.colorValue.value, callback);
  }
};

var Popup = function() {};

Popup.prototype = {
  getPanel: function() {
    if (!this.panel) {
      this.panel                = $('fp-panel', document);
      this.panel._pickerBrowser = this.panel.getElementsByTagName('browser')[0];
      this.panel._pickerBrowser.contentDocument.setGlobalBrowserDoc(document);

      this.panel.addEventListener('popupshown',  this.callbacks.popupshown,  false);
      this.panel.addEventListener('popuphidden', this.callbacks.popuphidden, false);
    }
    return this.panel;
  },

  callbacks: {
    popuphidden: function() {
      if (this._options) {
        this._options.editor.colorsDropDown.onValueChange();
        this._pickerBrowser.contentDocument.popUpClosed();
        delete this._options;
      }
    },

    popupshown: function() {
      if (this._options) { this._pickerBrowser.contentDocument.initColorPicker(this._options.color, this._options.callback); }
    }
  },

  open: function(editor, colorCell, color, callback) {
    var panel = this.getPanel(), deck = $('fbPanelBar2', document).deck, position = this.computePosition(colorCell, deck, panel._pickerBrowser);

    panel._options = {editor: editor, color: color, callback: callback};
    panel.openPopup(deck, "overlap", position.x, position.y, false, true);
  },

  computePosition: function(colorCell, deck, browser) {
    var clientOffset = getClientOffset(colorCell),
        deckSize     = {height: deck.clientHeight, width: deck.clientWidth}
        popUpSize    = {height: browser.getAttribute('height'), width: browser.getAttribute('width')};

    return {
      x: clientOffset.x + colorCell.clientWidth,
      y: Math.min(clientOffset.y - ((popUpSize.height - colorCell.clientHeight) / 2), deckSize.height - popUpSize.height)
    };
  }
};

Firebug.FirepickerModel = extend(Firebug.Module, {
  ColorsDropDown: ColorsDropDown,
  Popup: Popup,

  enable: function() {
    if (!this.initialized) { this.initialize(); }
  },

  initialize: function() {
    this.hookIntoCSSPanel();
    this.initialized = true;
  },

  hookIntoCSSEditor: function(editor) {
    if (!editor.colorsDropDown) {
      var originalShow = editor.show, self = this;

      editor.colorsDropDown = new ColorsDropDown(editor, this);
      editor.show = function() {
        var result = originalShow.apply(this, arguments);
        this.colorsDropDown.editorShown();
        return result;
      };
    }
  },

  hookIntoCSSPanel: function() {
    var self = this, stylesheetPanelPrototype = Firebug.getPanelType('css').prototype, original = stylesheetPanelPrototype.getEditor;
    stylesheetPanelPrototype.getEditor = function() {
      var result = original.apply(this, arguments);
      if (this.editor) { self.hookIntoCSSEditor(this.editor); }
      return result;
    }
  },

  openPopup: function(editor, colorCell, color, callback) {
    if (!this.colorPickerPopup) { this.colorPickerPopup = new Popup(); }
    this.colorPickerPopup.open(editor, colorCell, this.fixColor(color), callback);
  },

  fixColor: function(color) {
    var rgbTranslation = colorNames[color.toLowerCase()];
    return rgbTranslation ? '#' + rgbTranslation : rgbToHex(color);
  },

  log: function() {
    for (var len = arguments.length, i = 0; i < len; i++) {
      Firebug.Console.log(arguments[i]);
    }
  }
});

Firebug.registerModule(Firebug.FirepickerModel);

}});<commit_msg>Make compatible with FF 3.7a.<commit_after>FBL.ns(function() { with (FBL) {

// list taken from FirePalette (http://blog.endflow.net/?p=143)
var colorNames = {
  aliceblue: "f0f8ff", antiquewhite: "faebd7", aqua: "00ffff",
  aquamarine: "7fffd4", azure: "f0ffff", beige: "f5f5dc",
  bisque: "ffe4c4", black: "000000", blanchedalmond: "ffebcd",
  blue: "0000ff", blueviolet: "8a2be2", brown: "a52a2a",
  burlywood: "deb887", cadetblue: "5f9ea0", chartreuse: "7fff00",
  chocolate: "d2691e", coral: "ff7f50", cornflowerblue: "6495ed",
  cornsilk: "fff8dc", crimson: "dc143c", cyan: "00ffff",
  darkblue: "00008b", darkcyan: "008b8b", darkgoldenrod: "b8860b",
  darkgray: "a9a9a9", darkgreen: "006400", darkkhaki: "bdb76b",
  darkmagenta: "8b008b", darkolivegreen: "556b2f", darkorange: "ff8c00",
  darkorchid: "9932cc", darkred: "8b0000", darksalmon: "e9967a",
  darkseagreen: "8fbc8f", darkslateblue: "483d8b", darkslategray: "2f4f4f",
  darkturquoise: "00ced1", darkviolet: "9400d3", deeppink: "ff1493",
  deepskyblue: "00bfff", dimgray: "696969", dodgerblue: "1e90ff",
  feldspar: "d19275", firebrick: "b22222", floralwhite: "fffaf0",
  forestgreen: "228b22", fuchsia: "ff00ff", gainsboro: "dcdcdc",
  ghostwhite: "f8f8ff", gold: "ffd700", goldenrod: "daa520",
  gray: "808080", green: "008000", greenyellow: "adff2f",
  honeydew: "f0fff0", hotpink: "ff69b4", indianred : "cd5c5c",
  indigo : "4b0082", ivory: "fffff0", khaki: "f0e68c",
  lavender: "e6e6fa", lavenderblush: "fff0f5", lawngreen: "7cfc00",
  lemonchiffon: "fffacd", lightblue: "add8e6", lightcoral: "f08080",
  lightcyan: "e0ffff", lightgoldenrodyellow: "fafad2", lightgrey: "d3d3d3",
  lightgreen: "90ee90", lightpink: "ffb6c1", lightsalmon: "ffa07a",
  lightseagreen: "20b2aa", lightskyblue: "87cefa", lightslateblue: "8470ff",
  lightslategray: "778899", lightsteelblue: "b0c4de", lightyellow: "ffffe0",
  lime: "00ff00", limegreen: "32cd32", linen: "faf0e6",
  magenta: "ff00ff", maroon: "800000", mediumaquamarine: "66cdaa",
  mediumblue: "0000cd", mediumorchid: "ba55d3", mediumpurple: "9370d8",
  mediumseagreen: "3cb371", mediumslateblue: "7b68ee", mediumspringgreen: "00fa9a",
  mediumturquoise: "48d1cc", mediumvioletred: "c71585", midnightblue: "191970",
  mintcream: "f5fffa", mistyrose: "ffe4e1", moccasin: "ffe4b5",
  navajowhite: "ffdead", navy: "000080", oldlace: "fdf5e6",
  olive: "808000", olivedrab: "6b8e23", orange: "ffa500",
  orangered: "ff4500", orchid: "da70d6", palegoldenrod: "eee8aa",
  palegreen: "98fb98", paleturquoise: "afeeee", palevioletred: "d87093",
  papayawhip: "ffefd5", peachpuff: "ffdab9", peru: "cd853f",
  pink: "ffc0cb", plum: "dda0dd", powderblue: "b0e0e6",
  purple: "800080", red: "ff0000", rosybrown: "bc8f8f",
  royalblue: "4169e1", saddlebrown: "8b4513", salmon: "fa8072",
  sandybrown: "f4a460", seagreen: "2e8b57", seashell: "fff5ee",
  sienna: "a0522d", silver: "c0c0c0", skyblue: "87ceeb",
  slateblue: "6a5acd", slategray: "708090", snow: "fffafa",
  springgreen: "00ff7f", steelblue: "4682b4", tan: "d2b48c",
  teal: "008080", thistle: "d8bfd8", tomato: "ff6347",
  turquoise: "40e0d0", violet: "ee82ee", violetred: "d02090",
  wheat: "f5deb3", white: "ffffff", whitesmoke: "f5f5f5",
  yellow: "ffff00", yellowgreen: "9acd32"
};

// taken from Firebug | css.js
var reSplitCSS = /(url\("?[^"\)]+?"?\))|(rgb\(.*?\))|(#[\dA-Fa-f]+)|(-?\d+(\.\d+)?(%|[a-z]{1,2})?)|([^,\s]+)|"(.*?)"/;

function parseCSSValue(value, offset) {
  var start = 0;
  var m;
  while (1)
  {
    m = reSplitCSS.exec(value);
    if (m && m.index+m[0].length < offset)
    {
      value = value.substr(m.index+m[0].length);
      start += m.index+m[0].length;
      offset -= m.index+m[0].length;
    }
    else
    break;
  }

  if (m)
  {
    var type;
    if (m[1])
    type = "url";
    else if (m[2] || m[3])
    type = "rgb";
    else if (m[4])
    type = "int";

    return {value: m[0], start: start+m.index, end: start+m.index+(m[0].length-1), type: type};
  }
}

function rgbToHex(value) {
  return value.replace(/\brgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)/gi, function(_, r, g, b) {
    return '#' + ((1 << 24) + (r << 16) + (g << 8) + (b << 0)).toString(16).substr(-6).toUpperCase();
  });
}
// end of firebug helpers

var splitCSSValues = function(cssValue) {
  var offset = 0, cssValues = [], cssValueLength = cssValue.length, nextValue = parseCSSValue(cssValue, offset), previousValue;
  while (nextValue) {
    cssValues.push(nextValue);
    offset        = nextValue.end + 1;
    previousValue = nextValue;
    while ((nextValue = parseCSSValue(cssValue, offset)) && nextValue.start == previousValue.start) { offset++; }
  }
  return cssValues;
};

var ColorsDropDown = function(editor, firepicker) {
  this.editor     = editor;
  this.firepicker = firepicker;
};

ColorsDropDown.prototype = {
  tags: domplate({
    container: DIV({'class': 'firepicker_color_container'}),
    valueCell: DIV({'class': 'color_value', style: 'background-color: $color;'},
      DIV({'class': 'css_text'}, '$color')
    )
  }),

  editorShown: function() {
    this.onValueChange();
    this.attachInputChangeHandler();
  },

  attachInputChangeHandler: function() {
    if (!this.boundOnValueChange) { this.boundOnValueChange = bind(this.onValueChange, this); }
    this.editor.input.addEventListener('input', this.boundOnValueChange, false);
  },

  getListContainer: function() {
    if (!this.listContainer) {
      this.listContainer = this.tags.container.insertAfter({}, getChildByClass(this.editor.box, 'textEditorBottom1'));
      this.addStylesheet(this.listContainer.ownerDocument);
    }
    return this.listContainer;
  },

  addStylesheet: function(doc) {
    if (!$('firepickerDropDownStyle', doc)) {
      var styleSheet = createStyleSheet(doc, 'chrome://firepicker/skin/css-attribute-dialog.css');
      styleSheet.setAttribute('id', 'firepickerDropDownStyle');
      addStyleSheet(doc, styleSheet);
    }
  },

  onValueChange: function() {
    this.updateList(this.getCSSColorValues());
  },

  getCSSColorValues: function() {
    return this.filterColorValues(splitCSSValues(this.editor.input.value));
  },

  filterColorValues: function(cssValues) {
    var colorValues = [], cssValue;
    for (var i = 0, len = cssValues.length; i < len; i++) {
      cssValue = cssValues[i];
      if (cssValue.type == 'rgb' || isColorKeyword(cssValue.value)) { colorValues.push(cssValue); }
    }
    return colorValues;
  },

  updateList: function(colorValues) {
    var container = this.getListContainer();
    eraseNode(container);
    for (var i = 0, len = colorValues.length; i < len; i++) { this.addColorCell(container, colorValues[i]); }
    container.style.display = colorValues.length == 0 ? 'none' : 'block';
  },

  addColorCell: function(container, colorValue) {
    var newCell = this.tags.valueCell.append({color: colorValue.value}, container);
    newCell.colorValue = colorValue;
    newCell.dropDown   = this;
    newCell.addEventListener('mousedown', this.cellMousedown, false);
  },

  cellMousedown: function(e) {
    cancelEvent(e);

    var input = this.dropDown.editor.input, text = this.firstChild, style = this.style, colorValue = this.colorValue;

    colorValue = extend(colorValue, {
      prefix: input.value.substring(0, colorValue.start),
      suffix: input.value.substring(colorValue.end + 1)
    });

    this.dropDown.openPopup(this, function(newValue) {
      input.value           = colorValue.prefix + newValue + colorValue.suffix;
      text.innerHTML        = newValue;
      style.backgroundColor = newValue;

      Firebug.Editor.update(true);
    });
  },

  openPopup: function(colorCell, callback) {
    this.firepicker.openPopup(this.editor, colorCell, colorCell.colorValue.value, callback);
  }
};

var Popup = function() {};

Popup.prototype = {
  getPanel: function() {
    if (!this.panel) {
      this.panel                = $('fp-panel', document);
      this.panel._pickerBrowser = this.panel.getElementsByTagName('browser')[0];
      this.panel._pickerBrowser.contentDocument.setGlobalBrowserDoc(document);

      this.panel.addEventListener('popupshown',  this.callbacks.popupshown,  false);
      this.panel.addEventListener('popuphidden', this.callbacks.popuphidden, false);
    }
    return this.panel;
  },

  callbacks: {
    popuphidden: function() {
      if (this._options) {
        this._options.editor.colorPickerClosed();
        this._options.editor.colorsDropDown.onValueChange();
        this._pickerBrowser.contentDocument.popUpClosed();
        delete this._options;
      }
    },

    popupshown: function() {
      if (this._options) { this._pickerBrowser.contentDocument.initColorPicker(this._options.color, this._options.callback); }
    }
  },

  open: function(editor, colorCell, color, callback) {
    var panel = this.getPanel(), deck = $('fbPanelBar2', document).deck, position = this.computePosition(colorCell, deck, panel._pickerBrowser);

    panel._options = {editor: editor, color: color, callback: callback};
    editor.openingColorPickerPopup();
    panel.openPopup(deck, "overlap", position.x, position.y, false, true);
  },

  computePosition: function(colorCell, deck, browser) {
    var clientOffset = getClientOffset(colorCell),
        deckSize     = {height: deck.clientHeight, width: deck.clientWidth}
        popUpSize    = {height: browser.getAttribute('height'), width: browser.getAttribute('width')};

    return {
      x: clientOffset.x + colorCell.clientWidth,
      y: Math.min(clientOffset.y - ((popUpSize.height - colorCell.clientHeight) / 2), deckSize.height - popUpSize.height)
    };
  }
};

Firebug.FirepickerModel = extend(Firebug.Module, {
  ColorsDropDown: ColorsDropDown,
  Popup: Popup,

  enable: function() {
    if (!this.initialized) { this.initialize(); }
  },

  initialize: function() {
    this.hookIntoCSSPanel();
    this.initialized = true;
  },

  editorExtensions: {
    openingColorPickerPopup: function() {
      // prevent Firebug from closing the editor in FF 3.7+ (where opening pop up "blurs" the editor's input)
      this._enterOnBlurWas = this.enterOnBlur;
      this.enterOnBlur     = false;
    },

    colorPickerClosed: function() {
      this.enterOnBlur = this._enterOnBlurWas;
      var input        = this.input;
      setTimeout(function() { input.focus(); }, 0); // return focus to the editor in FF 3.7+
    }
  },

  hookIntoCSSEditor: function(editor) {
    if (!editor.colorsDropDown) {
      var originalShow = editor.show, self = this;

      editor.colorsDropDown = new ColorsDropDown(editor, this);
      editor.show = function() {
        var result = originalShow.apply(this, arguments);
        this.colorsDropDown.editorShown();
        return result;
      };

      editor.openingColorPickerPopup = this.editorExtensions.openingColorPickerPopup;
      editor.colorPickerClosed       = this.editorExtensions.colorPickerClosed;
    }
  },

  hookIntoCSSPanel: function() {
    var self = this, stylesheetPanelPrototype = Firebug.getPanelType('css').prototype, original = stylesheetPanelPrototype.getEditor;
    stylesheetPanelPrototype.getEditor = function() {
      var result = original.apply(this, arguments);
      if (this.editor) { self.hookIntoCSSEditor(this.editor); }
      return result;
    }
  },

  openPopup: function(editor, colorCell, color, callback) {
    if (!this.colorPickerPopup) { this.colorPickerPopup = new Popup(); }
    this.colorPickerPopup.open(editor, colorCell, this.fixColor(color), callback);
  },

  fixColor: function(color) {
    var rgbTranslation = colorNames[color.toLowerCase()];
    return rgbTranslation ? '#' + rgbTranslation : rgbToHex(color);
  },

  log: function() {
    for (var len = arguments.length, i = 0; i < len; i++) {
      Firebug.Console.log(arguments[i]);
    }
  }
});

Firebug.registerModule(Firebug.FirepickerModel);

}});<|endoftext|>


<commit_before>var nodecastor = require('nodecastor'),
  util = require("util");
nodecastor.scan()
  .on('online', function(d) {
    console.log("New device: ", d.id);
    d.on('connect', function() {
    d.status(function(err, s) {
      if (!err) {
        console.log('Chromecast status', util.inspect(s));
        d.application('5C3F0A3C', function(err, a) {
          if (!err) {
            console.log('Application', util.inspect(a));
            a.run('urn:x-cast:es.offd.dashcast', function(err, s) {
              if (!err) {
                s.send('http://theregister.co.uk');
              }
            });
          }
      });
      }
    });
});
  })
  .on('offline', function(d) {
    console.log('Removed device', util.inspect(d));
  })
  .start();<commit_msg>Updates test.js so casting via commandline works<commit_after>var nodecastor = require('nodecastor'),
  util = require("util");
nodecastor.scan()
  .on('online', function(d) {
    console.log("New device: ", d.id);
    d.on('connect', function() {
    d.status(function(err, s) {
      if (!err) {
        console.log('Chromecast status', util.inspect(s));
        d.application('5C3F0A3C', function(err, a) {
          if (!err) {
            console.log('Application', util.inspect(a));
            a.run('urn:x-cast:es.offd.dashcast', function(err, s) {
              if (!err) {
                s.send({url: "http://codepen.io/fleeting/full/xklfq/"});
              }
            });
          }
      });
      }
    });
});
  })
  .on('offline', function(d) {
    console.log('Removed device', util.inspect(d));
  })
  .start();
<|endoftext|>


<commit_before>import _ from 'lodash'
import { expect } from 'chai'

import { childOf } from '../dashboardInit.js'
import { inChart } from '../dashboardInit.js'
import { choropleth } from '../dashboardInit.js'
import { getFacet } from '../dashboardInit.js'
import { series } from '../dashboardInit.js'

describe(__filename, () => {
  context('child of', () => {
    context('child has no parent', () => {
      it('child has no parent_location_id', () => {
        let child = {
          not_parent: 1
        }
        let parent = {}
        expect(childOf(parent, child)).to.be.false
      })

      it('child has parent_location_id equals to parent.id', () => {
        let child = {
          parent_location_id: 1
        }
        let parent = {
          id: 1
        }
        expect(childOf(parent, child)).to.be.true
      })
      it('child has parent_location_id not equal to parent.id', () => {
        let child = {
          parent_location_id: 1
        }
        let parent = {
          id: 2
        }
        expect(childOf(parent, child)).to.be.false
      })
    })

    context('child has parent', () => {
      it('child has parent.id equal to parent.id', () => {
        let child = {
          parent: {
            id: 1
          }
        }
        let parent = {
          id: 1
        }
        expect(childOf(parent, child)).to.be.true
      })
      it('child has parent.id not equal to parent.id, recursively call true case', () => {
        let child = {
          parent: {
            parent: {
              id: 1
            }
          }
        }
        let parent = {
          id: 1
        }
        expect(childOf(parent, child)).to.be.true
      })
      it('child has parent.id not equal to parent.id, recursively call false case', () => {
        let child = {
          parent: {
            parent: {
              no_parent: 2
            }
          }
        }
        let parent = {
          id: 1
        }
        expect(childOf(parent, child)).to.be.false
      })
    })
  })

  context('in chart', () => {
    let legalCampaign = { start_date: '2015-01-01' }
    let legalLocation = { id: 1, parent: { id: '1' } }
    let legalIndicator = { id: 1 }
    let legalDatum = {
      campaign: legalCampaign,
      location: legalLocation,
      indicator: legalIndicator
    }

    let illegalCampaign = { start_date: '2015-10-01' }
    let illegalLocation = { id: 2, parent: { id: 2 } }
    let illegalIndicator = { id: 2 }
    let illegalDatum = {
      campaign: illegalCampaign,
      location: illegalLocation,
      indicator: illegalIndicator
    }

    context('chart locations type is default', () => {
      it('should filter legal data with required conditions', () => {
        let data = [legalDatum]
        let indicators = [legalIndicator]
        let chart = {
          indicators: _.pluck(indicators, 'id')
        }
        var chartData = _.filter(data, _.partial(inChart, chart, legalCampaign, legalLocation))
        expect(chartData).to.eql([legalDatum])
      })
      it('should remove illegal data', () => {
        let data = [legalDatum, illegalDatum]
        let indicators = [legalIndicator, illegalIndicator]
        let chart = {
          indicators: _.pluck(indicators, 'id')
        }
        var chartData = _.filter(data, _.partial(inChart, chart, legalCampaign, legalLocation))
        expect(chartData).to.eql([legalDatum])
      })
    })
  })

  context('get choropleth data', () => {
    let campaign = { id: 1 }
    let data = [
      {
        campaign: { id: 1 },
        location: { id: 1 },
        indicator: { id: 1 },
        value: 0.3
      },
      {
        campaign: { id: 2 },
        location: { id: 1 },
        indicator: { id: 1 },
        value: 0.5
      }
    ]

    context('should generate chropleth features when original features matches data', () => {
      let originalFeatures = [
        {
          properties: { location_id: 1 }
        }
      ]
      let expectedFeatures = [
        {
          properties:
            {
              location_id: 1,
              1: 0.3
            }
        }
      ]
      let actualFeatures = choropleth(null, data, campaign, originalFeatures)
      expect(actualFeatures).to.eql(expectedFeatures)
    })
    context('should not generate chropleth features when original features donnot match data', () => {
      let originalFeatures = [
        {
          properties: { location_id: 3 }
        }
      ]
      let actualFeatures = choropleth(null, data, campaign, originalFeatures)
      expect(actualFeatures).to.eql(originalFeatures)
    })
  })

  context('getFacet', () => {
    context('should get path in data when path exists', () => {
      let datum = { name: 'test' }
      let path = 'name'
      expect(getFacet(datum, path)).to.eql('test')
    })
    context('should get first element in data when data has two layers', () => {
      let datum = {name: {short_name: 'test', name: 'test_indicator', title: 'ttt', id: '1'}}
      let path = 'name'
      expect(getFacet(datum, path)).to.eql('test')
    })
  })

  context('test for series method', () => {
    context('should get legal data', () => {
      let chart = { groupBy: 'location.name' }
      let legalDataA = {
        location: { id: 1, name: 'a' },
        indicator: { id: 1 },
        value: 1
      }
      let dataValueEqualsZero = {
        location: { id: 1, name: 'a' },
        indicator: { id: 2 },
        value: 0
      }
      let legalDataB = {
        location: { id: 2, name: 'b' },
        indicator: { id: 3 },
        value: 2
      }
      let originalData = [
        legalDataA,
        dataValueEqualsZero,
        legalDataB
      ]
      let expectedData = [
        {
          name: 'a',
          values: [legalDataA]
        },
        {
          name: 'b',
          values: [legalDataB]
        }
      ]
      console.log(series(chart, originalData), expectedData)
      expect(series(chart, originalData)).to.eql(expectedData)
    })
  })
})
<commit_msg>Remove dashboard init<commit_after><|endoftext|>


<commit_before>module.exports = {
  name: 'repl',
  pkg: require('../package'),
  provides: {
    config: [ 'repl' ]
  }
}

<commit_msg>[config] removde deprecated 'name' from trailpack config<commit_after>module.exports = {
  pkg: require('../package'),
  provides: {
    config: [ 'repl' ]
  }
}

<|endoftext|>


<commit_before>//---------------------------
//  Simple Closure Example
//---------------------------
function foo(){
  var bar = "bar";
  function baz(){
    console.log(bar);
  }
  bam(baz); // here we pass baz, functions 1st class objects
            // can be passed around
}
function bam(baz){
     baz(); // “bar"
            // when we execute baz over here, it still remembers
            // its lexical scope (this is closure)
}
foo();

//---------------------------
//  Simple Closure Example # 2
//---------------------------

function foo(){
  var bam = "bam"

  return function(){
    console.log(bam)
  }
}

function bar(){
  foo()();
}

bar();

//---------------------------
//  Simple Closure Example # 3
//---------------------------

//setTimeout or any type of Callback

function foo(){

  var bar = "bar"

  setTimeout(function(){
    consol.log(bar);
  },1000);

}

foo();

//---------------------------
//  Simple Closure Example # 4
//---------------------------

// click handlers are also closure
// closure is a necessarry mechanism for a languange where objs
// are first kind values, if functions would not remember their
// lexical scope, noone would pass functions around

function foo (){

  var bar = "bar"

  $('#btn').on('click', function(evt){
    console.log(bar)
  });

foo();
}

<commit_msg>minor changes<commit_after>//---------------------------
//  Simple Closure Example
//---------------------------
function foo(){
  var bar = "bar";
  function baz(){
    console.log(bar);
  }
  bam(baz); // here we pass baz, functions 1st class objects
            // can be passed around
}
function bam(baz){
     baz(); // “bar"
            // when we execute baz over here, it still remembers
            // its lexical scope (this is closure)
}
foo();

//---------------------------
//  Simple Closure Example # 2
//---------------------------

function foo(){
  var bam = "bam"

  return function(){
    console.log(bam)
  }
}

function bar(){
  foo()();
}

bar();

//---------------------------
//  Simple Closure Example # 3
//---------------------------

//setTimeout or any type of Callback

function foo(){

  var bar = "bar"

  setTimeout(function(){
    consol.log(bar);
  },1000);

}

foo();

//---------------------------
//  Simple Closure Example # 4
//---------------------------

// click handlers are also closure
// closure is a necessarry mechanism for a languange where objs
// are first kind values, if functions would not remember their
// lexical scope, noone would pass functions around

function foo (){

  var bar = "bar"

  $('#btn').on('click', function(evt){
    console.log(bar)
  });

foo();
}

<|endoftext|>


<commit_before>import React, {PropTypes} from 'react'
import S3Upload from 'react-s3-uploader/s3upload'
import Dropzone from 'react-dropzone'

export default class DropzoneS3Uploader extends React.Component {

  static propTypes = {
    filename: PropTypes.string,
    s3Url: PropTypes.string.isRequired,
    notDropzoneProps: PropTypes.array.isRequired,
    isImage: PropTypes.func.isRequired,
    passChildrenProps: PropTypes.bool,

    imageComponent: PropTypes.func,
    fileComponent: PropTypes.func,
    progressComponent: PropTypes.func,
    errorComponent: PropTypes.func,

    children: PropTypes.oneOfType([
      PropTypes.node,
      PropTypes.func,
    ]),

    onDrop: PropTypes.func,
    onError: PropTypes.func,
    onProgress: PropTypes.func,
    onFinish: PropTypes.func,

    // Passed to react-s3-uploader
    upload: PropTypes.object.isRequired,

    // Default styles for react-dropzone
    className: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.object,
    ]),
    style: PropTypes.object,
    activeStyle: PropTypes.object,
    rejectStyle: PropTypes.object,
  }

  static defaultProps = {
    upload: {},
    className: 'react-dropzone-s3-uploader',
    passChildrenProps: true,
    isImage: filename => filename && filename.match(/\.(jpeg|jpg|gif|png|svg)/i),
    notDropzoneProps: ['onFinish', 's3Url', 'filename', 'host', 'upload', 'isImage', 'notDropzoneProps'],

    style: {
      width: 200,
      height: 200,
      border: 'dashed 2px #999',
      borderRadius: 5,
      position: 'relative',
      cursor: 'pointer',
      overflow: 'hidden',
    },
    activeStyle: {
      borderStyle: 'solid',
      backgroundColor: '#eee',
    },
    rejectStyle: {
      borderStyle: 'solid',
      backgroundColor: '#ffdddd',
    },
  }

  constructor(props) {
    super()
    const uploadedFiles = []
    const {filename} = props
    if (filename) {
      uploadedFiles.push({
        filename,
        fileUrl: this.fileUrl(props.s3Url, filename),
        default: true,
        file: {},
      })
    }
    this.state = {uploadedFiles}
  }

  componentWillMount = () => this.setUploaderOptions(this.props)
  componentWillReceiveProps = props => this.setUploaderOptions(props)

  setUploaderOptions = props => {
    this.setState({
      uploaderOptions: Object.assign({
        signingUrl: '/s3/sign',
        contentDisposition: 'auto',
        uploadRequestHeaders: {'x-amz-acl': 'public-read'},
        onFinishS3Put: this.handleFinish,
        onProgress: this.handleProgress,
        onError: this.handleError,
      }, props.upload),
    })
  }

  handleProgress = (progress, textState, file) => {
    this.props.onProgress && this.props.onProgress(progress, textState, file)
    this.setState({progress})
  }

  handleError = err => {
    this.props.onError && this.props.onError(err)
    this.setState({error: err, progress: null})
  }

  handleFinish = (info, file) => {
    const uploadedFile = Object.assign({
      file,
      fileUrl: this.fileUrl(info.filename),
    }, info)

    const uploadedFiles = this.state.uploadedFiles
    uploadedFiles.push(uploadedFile)

    this.setState({uploadedFiles, error: null, progress: null}, () => {
      this.props.onFinish && this.props.onFinish(uploadedFile)
    })
  }

  handleDrop = (files, rejectedFiles) => {
    this.setState({uploadedFiles: [], error: null, progress: null})
    const options = {
      files,
      ...this.state.uploaderOptions,
    }
    new S3Upload(options) // eslint-disable-line
    this.props.onDrop && this.props.onDrop(files, rejectedFiles)
  }

  fileUrl = (s3Url, filename) => `${s3Url.endsWith('/') ? s3Url.slice(0, -1) : s3Url}/${filename}`

  renderImage = ({uploadedFile}) => (

)

  renderFile = ({uploadedFile}) => (

{uploadedFile.file.name}

  )

  renderProgress = ({progress}) => (progress ? (
{progress}
) : null)

  renderError = ({error}) => (error ? (
{error}
) : null)

  render() {
    const {
      s3Url,
      passChildrenProps,
      children,
      imageComponent,
      fileComponent,
      progressComponent,
      errorComponent,
      ...dropzoneProps,
    } = this.props

    const ImageComponent = imageComponent || this.renderImage
    const FileComponent = fileComponent || this.renderFile
    const ProgressComponent = progressComponent || this.renderProgress
    const ErrorComponent = errorComponent || this.renderError

    const {uploadedFiles} = this.state
    const childProps = {s3Url, ...this.state}
    this.props.notDropzoneProps.forEach(prop => delete dropzoneProps[prop])

    let content = null
    if (children) {
      content = passChildrenProps ?
        React.Children.map(children, child => React.cloneElement(child, childProps)) :
        this.props.children
    }
    else {
      content = (

          {uploadedFiles.map(uploadedFile => {
            const props = {
              key: uploadedFile.filename,
              uploadedFile: uploadedFile,
              ...childProps
            }
            return this.props.isImage(uploadedFile.fileUrl) ?
              (<ImageComponent  {...props} />) :
              (<FileComponent {...props} />)
          })}
          <ProgressComponent {...childProps} />
          <ErrorComponent {...childProps} />

      )
    }

    return (
      <Dropzone onDrop={this.handleDrop} {...dropzoneProps}>
        {content}
      </Dropzone>
    )
  }
}
<commit_msg>Fix bug in URL creation<commit_after>import React, {PropTypes} from 'react'
import S3Upload from 'react-s3-uploader/s3upload'
import Dropzone from 'react-dropzone'

export default class DropzoneS3Uploader extends React.Component {

  static propTypes = {
    filename: PropTypes.string,
    s3Url: PropTypes.string.isRequired,
    notDropzoneProps: PropTypes.array.isRequired,
    isImage: PropTypes.func.isRequired,
    passChildrenProps: PropTypes.bool,

    imageComponent: PropTypes.func,
    fileComponent: PropTypes.func,
    progressComponent: PropTypes.func,
    errorComponent: PropTypes.func,

    children: PropTypes.oneOfType([
      PropTypes.node,
      PropTypes.func,
    ]),

    onDrop: PropTypes.func,
    onError: PropTypes.func,
    onProgress: PropTypes.func,
    onFinish: PropTypes.func,

    // Passed to react-s3-uploader
    upload: PropTypes.object.isRequired,

    // Default styles for react-dropzone
    className: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.object,
    ]),
    style: PropTypes.object,
    activeStyle: PropTypes.object,
    rejectStyle: PropTypes.object,
  }

  static defaultProps = {
    upload: {},
    className: 'react-dropzone-s3-uploader',
    passChildrenProps: true,
    isImage: filename => filename && filename.match(/\.(jpeg|jpg|gif|png|svg)/i),
    notDropzoneProps: ['onFinish', 's3Url', 'filename', 'host', 'upload', 'isImage', 'notDropzoneProps'],

    style: {
      width: 200,
      height: 200,
      border: 'dashed 2px #999',
      borderRadius: 5,
      position: 'relative',
      cursor: 'pointer',
      overflow: 'hidden',
    },
    activeStyle: {
      borderStyle: 'solid',
      backgroundColor: '#eee',
    },
    rejectStyle: {
      borderStyle: 'solid',
      backgroundColor: '#ffdddd',
    },
  }

  constructor(props) {
    super()
    const uploadedFiles = []
    const {filename} = props
    if (filename) {
      uploadedFiles.push({
        filename,
        fileUrl: this.fileUrl(props.s3Url, filename),
        default: true,
        file: {},
      })
    }
    this.state = {uploadedFiles}
  }

  componentWillMount = () => this.setUploaderOptions(this.props)
  componentWillReceiveProps = props => this.setUploaderOptions(props)

  setUploaderOptions = props => {
    this.setState({
      uploaderOptions: Object.assign({
        signingUrl: '/s3/sign',
        contentDisposition: 'auto',
        uploadRequestHeaders: {'x-amz-acl': 'public-read'},
        onFinishS3Put: this.handleFinish,
        onProgress: this.handleProgress,
        onError: this.handleError,
      }, props.upload),
    })
  }

  handleProgress = (progress, textState, file) => {
    this.props.onProgress && this.props.onProgress(progress, textState, file)
    this.setState({progress})
  }

  handleError = err => {
    this.props.onError && this.props.onError(err)
    this.setState({error: err, progress: null})
  }

  handleFinish = (info, file) => {
    const uploadedFile = Object.assign({
      file,
      fileUrl: this.fileUrl(this.props.s3Url, info.filename),
    }, info)

    const uploadedFiles = this.state.uploadedFiles
    uploadedFiles.push(uploadedFile)

    this.setState({uploadedFiles, error: null, progress: null}, () => {
      this.props.onFinish && this.props.onFinish(uploadedFile)
    })
  }

  handleDrop = (files, rejectedFiles) => {
    this.setState({uploadedFiles: [], error: null, progress: null})
    const options = {
      files,
      ...this.state.uploaderOptions,
    }
    new S3Upload(options) // eslint-disable-line
    this.props.onDrop && this.props.onDrop(files, rejectedFiles)
  }

  fileUrl = (s3Url, filename) => `${s3Url.endsWith('/') ? s3Url.slice(0, -1) : s3Url}/${filename}`

  renderImage = ({uploadedFile}) => (

)

  renderFile = ({uploadedFile}) => (

{uploadedFile.file.name}

  )

  renderProgress = ({progress}) => (progress ? (
{progress}
) : null)

  renderError = ({error}) => (error ? (
{error}
) : null)

  render() {
    const {
      s3Url,
      passChildrenProps,
      children,
      imageComponent,
      fileComponent,
      progressComponent,
      errorComponent,
      ...dropzoneProps,
    } = this.props

    const ImageComponent = imageComponent || this.renderImage
    const FileComponent = fileComponent || this.renderFile
    const ProgressComponent = progressComponent || this.renderProgress
    const ErrorComponent = errorComponent || this.renderError

    const {uploadedFiles} = this.state
    const childProps = {s3Url, ...this.state}
    this.props.notDropzoneProps.forEach(prop => delete dropzoneProps[prop])

    let content = null
    if (children) {
      content = passChildrenProps ?
        React.Children.map(children, child => React.cloneElement(child, childProps)) :
        this.props.children
    }
    else {
      content = (

          {uploadedFiles.map(uploadedFile => {
            const props = {
              key: uploadedFile.filename,
              uploadedFile: uploadedFile,
              ...childProps
            }
            return this.props.isImage(uploadedFile.fileUrl) ?
              (<ImageComponent  {...props} />) :
              (<FileComponent {...props} />)
          })}
          <ProgressComponent {...childProps} />
          <ErrorComponent {...childProps} />

      )
    }

    return (
      <Dropzone onDrop={this.handleDrop} {...dropzoneProps}>
        {content}
      </Dropzone>
    )
  }
}
<|endoftext|>


<commit_before>(function (window, document) {

    const toggles = Array.prototype.slice.call(
        document.querySelectorAll('[data-toggle="process"]')
    );

    toggles.forEach(function (toggle) {

        toggle.addEventListener('click', function (event) {

            event.preventDefault();

            NProgress.start();

            swal({
                icon: 'info',
                buttons: false,
                closeOnEsc: false,
                closeOnClickOutside: false,
                text: toggle.dataset.message,
            });

            let messages = document.querySelector('.swal-text');

            let request = new XMLHttpRequest();

            request.open('GET', event.target.href, true);
            request.setRequestHeader('Content-Type', 'application/json');

            request.send();

            setTimeout(function () {
                request.abort();
            }, 2000);

            let checkLog = setInterval(function () {

                let log = new XMLHttpRequest();

                log.open('GET', REQUEST_ROOT_PATH + '/app/' + APPLICATION_REFERENCE + '/process.log', true);
                log.setRequestHeader('Content-Type', 'application/json');

                log.send();

                log.addEventListener('readystatechange', function (event) {

                    /**
                     * Start checking the status.
                     */
                    if (log.readyState == 4 && log.status == 200) {

                        // Stop checking.
                        clearInterval(checkLog);

                        /**
                         * Check the status periodically.
                         * Log to console and when finished
                         * cleanup and show resulting message.
                         *
                         * @type {number}
                         */
                        let checkStatus = function () {

                            let status = new XMLHttpRequest();

                            status.open('GET', REQUEST_ROOT_PATH + '/app/' + APPLICATION_REFERENCE + '/process.log', true);
                            status.setRequestHeader('Content-Type', 'application/json');

                            status.send();

                            status.addEventListener('readystatechange', function () {

                                /**
                                 * Check the status and update messages.
                                 */
                                if (status.readyState == 4 && status.status == 200) {

                                    if (status.responseText.length != 0) {

                                        messages.innerText = status.responseText;

                                        document.title = status.responseText;
                                    }

                                    setTimeout(function () {
                                        checkStatus();
                                    }, 500);
                                }

                                /**
                                 * The file has been removed which
                                 * means composer has finished up.
                                 */
                                if (status.readyState == 4 && status.status == 404) {

                                    document.title = 'Done!';

                                    swal({
                                        text: 'Done!',
                                        icon: 'success',
                                        closeOnEsc: false,
                                        closeOnClickOutside: false,
                                        buttons: false,
                                    });

                                    setTimeout(function () {
                                        window.location.reload();
                                    }, 1000);
                                }
                            }, false);
                        };

                        checkStatus();
                    }
                });
            }, 500);
        });
    });

})(window, document);
<commit_msg>Abort and THEN go on<commit_after>(function (window, document) {

    const toggles = Array.prototype.slice.call(
        document.querySelectorAll('[data-toggle="process"]')
    );

    toggles.forEach(function (toggle) {

        toggle.addEventListener('click', function (event) {

            event.preventDefault();

            NProgress.start();

            swal({
                icon: 'info',
                buttons: false,
                closeOnEsc: false,
                closeOnClickOutside: false,
                text: toggle.dataset.message,
            });

            let messages = document.querySelector('.swal-text');

            let request = new XMLHttpRequest();

            request.open('GET', event.target.href, true);
            request.setRequestHeader('Content-Type', 'application/json');

            request.send();

            setTimeout(function () {

                request.abort();

                let checkLog = setInterval(function () {

                    let log = new XMLHttpRequest();

                    log.open('GET', REQUEST_ROOT_PATH + '/app/' + APPLICATION_REFERENCE + '/process.log', true);
                    log.setRequestHeader('Content-Type', 'application/json');

                    log.send();

                    log.addEventListener('readystatechange', function (event) {

                        /**
                         * Start checking the status.
                         */
                        if (log.readyState == 4 && log.status == 200) {

                            // Stop checking.
                            clearInterval(checkLog);

                            /**
                             * Check the status periodically.
                             * Log to console and when finished
                             * cleanup and show resulting message.
                             *
                             * @type {number}
                             */
                            let checkStatus = function () {

                                let status = new XMLHttpRequest();

                                status.open('GET', REQUEST_ROOT_PATH + '/app/' + APPLICATION_REFERENCE + '/process.log', true);
                                status.setRequestHeader('Content-Type', 'application/json');

                                status.send();

                                status.addEventListener('readystatechange', function () {

                                    /**
                                     * Check the status and update messages.
                                     */
                                    if (status.readyState == 4 && status.status == 200) {

                                        if (status.responseText.length != 0) {

                                            messages.innerText = status.responseText;

                                            document.title = status.responseText;
                                        }

                                        setTimeout(function () {
                                            checkStatus();
                                        }, 500);
                                    }

                                    /**
                                     * The file has been removed which
                                     * means composer has finished up.
                                     */
                                    if (status.readyState == 4 && status.status == 404) {

                                        document.title = 'Done!';

                                        swal({
                                            text: 'Done!',
                                            icon: 'success',
                                            closeOnEsc: false,
                                            closeOnClickOutside: false,
                                            buttons: false,
                                        });

                                        setTimeout(function () {
                                            window.location.reload();
                                        }, 1000);
                                    }
                                }, false);
                            };

                            checkStatus();
                        }
                    });
                }, 500);
            }, 2000);
        });
    });

})(window, document);
<|endoftext|>


<commit_before>/**
 * Trailpack Configuration
 * (app.config.trailpack)
 *
 * @see http://trailsjs.io/doc/config/trailpack
 */
module.exports = {

  disabled: [
  ],

  /**
   * Order does *not* matter. Each module is loaded according to its own requirements.
   */
  packs: [
    require('trailpack-core'),
    require('trailpack-repl'),
    require('trailpack-router'),
  ],

  paths: {
    root: `${__dirname}/..`
  }
}
<commit_msg>[config] re-enable the hapi trailpack<commit_after>/**
 * Trailpack Configuration
 * (app.config.trailpack)
 *
 * @see http://trailsjs.io/doc/config/trailpack
 */
module.exports = {

  disabled: [
  ],

  /**
   * Order does *not* matter. Each module is loaded according to its own requirements.
   */
  packs: [
    require('trailpack-core'),
    require('trailpack-repl'),
    require('trailpack-router'),
    require('trailpack-hapi')
  ],

  paths: {
    root: `${__dirname}/..`
  }
}
<|endoftext|>


<commit_before>(function () {
  var root = this

  function retinafy (imgs) {
    var isArray = Object.prototype.toString.call(imgs) == "[object Array]" || imgs.jQuery
    imgs = isArray ? imgs : [imgs]

    var dpr = ((root.devicePixelRatio || 1) + "").replace(".", "_")

    for (var i = 0; i < imgs.length; ++i) {
      var src = imgs[i].getAttribute("data-src-" + dpr + "x")
             || imgs[i].getAttribute("data-src-1x")
             || imgs[i].getAttribute("data-src")
      if (src) {
        imgs[i].src = src
      }
    }
    return imgs.length > 1 ? imgs : isArray ? imgs : imgs[0]
  }

  if (typeof module !== "undefined" && module.exports) {
    module.exports = retinafy
  } else {
    root.retinafy = retinafy
  }
})()
<commit_msg>Fix jquery detection, optimise.<commit_after>(function () {
  var root = this

  function retinafy (img) {
    var imgs = Object.prototype.toString.call(img) == "[object Array]" || img.jquery ? img : [img]
      , dpr = ((root.devicePixelRatio || 1) + "").replace(".", "_")

    for (var i = 0; i < imgs.length; ++i) {
      var src = imgs[i].getAttribute("data-src-" + dpr + "x")
             || imgs[i].getAttribute("data-src-1x")
             || imgs[i].getAttribute("data-src")
      if (src) {
        imgs[i].src = src
      }
    }
    return img
  }

  if (typeof module !== "undefined" && module.exports) {
    module.exports = retinafy
  } else {
    root.retinafy = retinafy
  }
})()
<|endoftext|>


<commit_before>/**
 *  email_composer.js
 *  Cordova EmailComposer Plugin
 *
 *  Created by Sebastian Katzer (github.com/katzer) on 10/08/2013.
 *  Copyright 2013 Sebastian Katzer. All rights reserved.
 *  GPL v2 licensed
 */

var EmailComposer = function () {

};

EmailComposer.prototype = {
    /**
     * Öffnet den Email-Kontroller mit vorausgefüllten Daten.
     *
     * @param {Object?} options
     */
    open: function (options) {
        var callbackFn = null,
            options    = options || {};

      	if (typeof options['callback'] == 'function'){
      		callbackFn = function (code) {
      			options.callback.call(options.scope || window, code);
      		};
      	};

        cordova.exec(callbackFn, null, 'EmailComposer', 'open', [options]);
    },

    /**
     * Alias für `open()`.
     */
    openDraft: function () {
        this.open.apply(this, arguments);
    },

    /**
     * Gibt an, ob Emails versendet werden können.
     *
     * @param {Function} callback
     * @param {Object?}  scope (default: window)
     */
    isServiceAvailable: function (callback, scope) {
		var callbackFn = function () {
			callback.apply(scope || window, arguments);
		};

    	cordova.exec(callbackFn, null, 'EmailComposer', 'isServiceAvailable', []);
    }

};

var plugin = new EmailComposer();

module.exports = plugin;<commit_msg>The callback function is only supported as iOS specific function.<commit_after>/**
 *  email_composer.js
 *  Cordova EmailComposer Plugin
 *
 *  Created by Sebastian Katzer (github.com/katzer) on 10/08/2013.
 *  Copyright 2013 Sebastian Katzer. All rights reserved.
 *  GPL v2 licensed
 */

var EmailComposer = function () {

};

EmailComposer.prototype = {
    /**
     * Öffnet den Email-Kontroller mit vorausgefüllten Daten.
     *
     * @param {Object?} options
     */
    open: function (options) {
        var callbackFn = null,
            options    = options || {};

        if (device.platform == 'iOS' && typeof options['callback'] == 'function'){
            callbackFn = function (code) {
                options.callback.call(options.scope || window, code);
            };
        };

        cordova.exec(callbackFn, null, 'EmailComposer', 'open', [options]);
    },

    /**
     * Alias für `open()`.
     */
    openDraft: function () {
        this.open.apply(this, arguments);
    },

    /**
     * Gibt an, ob Emails versendet werden können.
     *
     * @param {Function} callback
     * @param {Object?}  scope (default: window)
     */
    isServiceAvailable: function (callback, scope) {
        var callbackFn = function () {
            callback.apply(scope || window, arguments);
        };

        cordova.exec(callbackFn, null, 'EmailComposer', 'isServiceAvailable', []);
    }

};

var plugin = new EmailComposer();

module.exports = plugin;<|endoftext|>


<commit_before>// @flow
import React, { Component } from 'react'
import { Provider } from 'react-redux'

import DragDropContext from '../DragDropContext'
import HotKeyDecorator from '../HotKey/Decorator'
import { editable } from '../../selector/editable'
import PluginService from '../../service/plugin'
import Inner from './Inner'

import type { Store } from '../../types/redux'
import { shouldPureComponentUpdate } from '../../helper/shouldComponentUpdate'

class Editable extends Component {
  componentDidMount() {
    if (!this.props.id) {
      throw new Error('The state must have an unique id')
    }

    this.props.editor.store.subscribe(this.onChange)
    this.previousState = null
  }

  shouldComponentUpdate = shouldPureComponentUpdate

  previousState: any = {}

  props: {
    id: string,
    editor: {
      plugins: PluginService,
      store: Store,
      defaultPlugin: any
    },
    onChange?: Function
  }

  onChange = () => {
    const { onChange } = this.props
    if (typeof onChange !== 'function') {
      return
    }

    const state: any = editable(this.props.editor.store.getState(), {
      id: this.props.id
    })
    if (state === this.previousState || !state) {
      return
    }

    const serialized = this.props.editor.plugins.serialize(state)
    onChange(serialized)
  }

  render() {
    const { id, editor: { store, defaultPlugin } } = this.props

    return (
      <Provider store={store}>
        <DragDropContext>
          <HotKeyDecorator id={id}>
            <Inner id={id} defaultPlugin={defaultPlugin} />
          </HotKeyDecorator>
        </DragDropContext>
      </Provider>
    )
  }
}

export default Editable
<commit_msg>components/Editable: unsubscribe from redux store on componentWillUnmount (#405)<commit_after>// @flow
import React, { Component } from 'react'
import { Provider } from 'react-redux'

import DragDropContext from '../DragDropContext'
import HotKeyDecorator from '../HotKey/Decorator'
import { editable } from '../../selector/editable'
import PluginService from '../../service/plugin'
import Inner from './Inner'

import type { Store } from '../../types/redux'
import { shouldPureComponentUpdate } from '../../helper/shouldComponentUpdate'

class Editable extends Component {
  componentDidMount() {
    if (!this.props.id) {
      throw new Error('The state must have an unique id')
    }

    this.unsubscribe = this.props.editor.store.subscribe(this.onChange)
    this.previousState = null
  }

  componentWillUnmount() {
    this.unsubscribe();
  }

  shouldComponentUpdate = shouldPureComponentUpdate

  previousState: any = {}

  props: {
    id: string,
    editor: {
      plugins: PluginService,
      store: Store,
      defaultPlugin: any
    },
    onChange?: Function
  }

  onChange = () => {
    const { onChange } = this.props
    if (typeof onChange !== 'function') {
      return
    }

    const state: any = editable(this.props.editor.store.getState(), {
      id: this.props.id
    })
    if (state === this.previousState || !state) {
      return
    }

    const serialized = this.props.editor.plugins.serialize(state)
    onChange(serialized)
  }

  render() {
    const { id, editor: { store, defaultPlugin } } = this.props

    return (
      <Provider store={store}>
        <DragDropContext>
          <HotKeyDecorator id={id}>
            <Inner id={id} defaultPlugin={defaultPlugin} />
          </HotKeyDecorator>
        </DragDropContext>
      </Provider>
    )
  }
}

export default Editable
<|endoftext|>