<commit_before>/*eslint no-native-reassign:0 */
(function ($) {
    'use strict';

    var WebWorker = null,
        NativeWorker = null,

        context = null,
        className = null,

        defaultContext = window,
        defaultClassName = 'WebWorker',

        Action = null,

        Event = null,
        eventPrefix = 'webworker:',

        EventMap = null,

        Error = null,

        slice = null;

    var windowConsole = window.console,
        console = null;

    console = {
        log: function (data, suppressNoise) {
            suppressNoise = suppressNoise || false;

            if (suppressNoise) {
                windowConsole.log(data);
            }
            else {
                windowConsole.log({
                    '>>>>>>>> internal': true,
                    'log': data
                });
            }

            return;
        },
        warn: windowConsole.warn,
        error: windowConsole.error
    };

    context = context || defaultContext;
    className = className || defaultClassName;

    WebWorker = context[className] || null;

    if (WebWorker !== null) {
        return;
    }

    slice = Array.prototype.slice;
    NativeWorker = window.Worker;

    WebWorker = function () {
        this._constructor.apply(this, arguments);
        return;
    };

    WebWorker.prototype.$ = null;

    WebWorker.prototype._workerUrl = null;
    WebWorker.prototype._workerBlobUrl = null;

    WebWorker.prototype._workerScript = null;

    WebWorker.prototype._nativeWorker = null;
    WebWorker.prototype._lastError = null;

    WebWorker.prototype._hasLoaded = false;

    WebWorker.prototype._constructor = function (opts) {
        var $scriptElement = null,
            scriptContents = null,
            workerUrl = null;

        this.$ = $(this);

        opts = opts || null;

        if (opts === null) {
            this.throwError(Error.INVALID_ARGUMENTS, null, true);
            return;
        }

        if (typeof opts === 'string') {
            opts = $.trim(opts);

            try {
                $scriptElement = $(opts);
            }
            catch (err) {
                // Cannot be resolved as a selector
            }

            if ($scriptElement !== null && $scriptElement.length > 0) {
                // Matching script element found
                // Cache its contents
                scriptContents = $scriptElement.text();
                this._workerScript = scriptContents;
            }
            else {
                workerUrl = opts;
            }
        }

        this._workerUrl = workerUrl;

        this._assignEventHandlers();

        this.trigger(Event.INITIALIZED);

        return;
    };

    WebWorker.prototype.getUrl = function () {
        return this._workerUrl;
    };

    WebWorker.prototype.getBlobUrl = function () {
        return this._workerBlobUrl;
    };

    WebWorker.prototype.getNativeWorker = function () {
        return this._nativeWorker;
    };

    WebWorker.prototype.hasLoaded = function () {
        return this._hasLoaded;
    };

    WebWorker.prototype.load = function () {
        var worker = this,
            workerUrl = null,
            onScriptLoaded = null;

        // Trigger event
        worker.trigger(Event.WORKER_LOADING);

        workerUrl = worker.getUrl() || null;
        onScriptLoaded = function () {
            var blob = null,
                scriptContents = null;

            scriptContents = worker._workerScript;
            blob = new window.Blob([scriptContents], {
                type: "text/javascript"
            });
            worker._workerBlobUrl = window.URL.createObjectURL(blob);

            worker._createWorker();

            return;
        };

        if (workerUrl === null) {
            // Script already available
            onScriptLoaded();
        }
        else {
            // Ajax request
            $.ajax({
                async: true,
                url: workerUrl,
                dataType: 'text',
                crossDomain: true,
                success: function (responseText) {
                    worker._workerScript = responseText;
                    onScriptLoaded();
                    return;
                },
                error: function () {
                    worker.throwError(Error.WORKER_DID_NOT_LOAD, arguments);
                    return;
                }
            });
        }

        return worker;
    };

    WebWorker.prototype._createWorker = function () {
        var worker = this;

        worker._nativeWorker = new NativeWorker(worker.getUrl());

        // TODO: Cleanup
        $(worker.getNativeWorker()).on('message', function (event) {
            console.log('onmessage');
            console.log(event, true);

            var originalEvent = event.originalEvent || event,
                msg = originalEvent.data,
                action = null,
                args = null;

            if ((typeof msg === 'object')
                && ('__isWebWorkerMsg' in msg)
                && (msg.__isWebWorkerMsg)) {
                action = msg.action;
                args = msg.args;

                worker[action].apply(worker, args);
                return;
            }

            return;
        });

        worker._initializeWorker();
        return;
    };

    WebWorker.prototype._assignEventHandlers = function () {
        var worker = this;

        worker.on(Event.ERROR, function () {
            console.log('error');
            console.log(arguments);
            return;
        });

        worker.on(Event.WORKER_LOADED, function () {
            worker._hasLoaded = true;
            return;
        });

        return worker;
    };

    WebWorker.prototype.start = function () {
        var worker = this,
            args = null;

        if (!worker.hasLoaded()) {
            return false;
        }

        worker.trigger(Event.WORKER_STARTING);

        args = slice.call(arguments);
        worker.sendMessage(Action.START, args);

        return worker;
    };

    WebWorker.prototype.sendMessage = function (action, args) {
        var worker = this,
            nativeWorker = null,
            message = null;

        action = action || null;
        args = args || null;

        if (action === null) {
            return false;
        }

        message = {
            __isWebWorkerMsg: true
        };

        message.action = action;
        message.args = args;

        nativeWorker = worker.getNativeWorker();

        if (nativeWorker !== null) {
            nativeWorker.postMessage(message);
        }

        return worker;
    };

    WebWorker.prototype._initializeWorker = function () {
        var worker = this;
        //worker.sendMessage(Action.INIT);
        return worker;
    };

    WebWorker.prototype.terminate = function () {
        var worker = this,
            nativeWorker = worker.getNativeWorker() || null;

        if (nativeWorker !== null) {
            worker.trigger(Event.WORKER_TERMINATING);
            worker.sendMessage(Action.TERMINATE, arguments);
        }

        return;
    };

    WebWorker.prototype.terminateNow = function (returnValue) {
        var worker = this,
            nativeWorker = null;

        nativeWorker = worker.getNativeWorker() || null;

        if (nativeWorker !== null) {
            nativeWorker.terminate();
            worker._hasLoaded = false;
            worker.trigger(Event.WORKER_TERMINATED, {returnValue: returnValue});
        }
        return;
    };

    WebWorker.prototype.on = function () {
        var $worker = this.$;
        $worker.on.apply($worker, arguments);
        return this;
    };

    WebWorker.prototype.one = function () {
        var $worker = this.$;
        $worker.one.apply($worker, arguments);
        return this;
    };

    WebWorker.prototype.off = function () {
        var worker = this,
            $worker = worker.$;

        $worker.off.apply($worker, arguments);
        worker._assignEventHandlers();

        return this;
    };

    WebWorker.prototype.trigger = function (event) {
        var worker = this,
            passedEventString = false,
            eventType = null,
            eventArgs = null;

        if (typeof event === 'object') {
            eventType = event.type || null;
        }

        if (typeof event === 'string') {
            eventType = event || null;
            passedEventString = true;
        }

        if (eventType === null) {
            return worker;
        }

        if (eventType in EventMap) {
            if (passedEventString) {
                event = new $.Event(eventType);
            }
            event.worker = worker;
            eventArgs = [event];
            if (arguments.length > 1) {
                eventArgs = eventArgs.concat(slice.call(arguments, 1));
            }

            worker._triggerSelf.apply(worker, eventArgs);
            return worker;
        }

        if (passedEventString) {
            event = {
                type: eventType,
                data: null
            };
        }
        eventArgs = [event];
        worker.sendMessage(Action.TRIGGER_SELF, eventArgs);

        return worker;
    };

    WebWorker.prototype.triggerSelf = function (event) {
        var worker = this,
            eventType = null,
            eventArgs = null;

        if (typeof event === 'string') {
            eventType = event;
            event = new $.Event(eventType);
        }

        event.worker = worker;
        eventArgs = [event];
        if (arguments.length > 1) {
            eventArgs = eventArgs.concat(slice.call(arguments, 1));
        }

        worker._triggerSelf.apply(worker, eventArgs);

        return;
    };

    WebWorker.prototype._triggerSelf = function () {
        var worker = this,
            $worker = null;

        $worker = worker.$;
        $worker.trigger.apply($worker, arguments);

        return;
    };

    WebWorker.prototype.throwError = function (error, data, throwException) {
        var worker = this;

        error = error || Error.UNKNOWN;
        data = (typeof data === 'undefined') ? null : data;
        throwException = throwException || false;

        worker._lastError = error;
        WebWorker._lastError = error;

        if ('_triggerError' in worker) {
            worker._triggerError(error, data, throwException);
        }

        if (throwException) {
            throw new window.Error(error);
        }

        return;
    };

    WebWorker.prototype._triggerError = function (error, data, throwException) {
        var worker = this,
            errorEvent = null;

        errorEvent = new $.Event(Event.ERROR);
        errorEvent.message = worker.getLastError();
        errorEvent.data = data;
        errorEvent.throwsException = (!!throwException);

        worker.trigger(errorEvent);
        return;
    };

    WebWorker.prototype.getLastError = function () {
        return this._lastError;
    };

    // Static

    WebWorker._lastError = null;

    Action = {
        INIT: 'init',
        START: 'start',
        TERMINATE: 'terminate',
        TERMINATE_NOW: 'terminateNow',
        TRIGGER: 'trigger',
        TRIGGER_SELF: 'triggerSelf'
    };
    WebWorker.Action = Action;

    Event = {
        INITIALIZED: 'initialized',
        ERROR: 'error',

        WORKER_LOADING: 'worker-loading',
        WORKER_LOADED: 'worker-loaded',

        WORKER_STARTING: 'worker-starting',
        WORKER_STARTED: 'worker-started',

        WORKER_TERMINATING: 'worker-terminating',
        WORKER_TERMINATED: 'worker-terminated'
    };
    WebWorker.Event = Event;

    EventMap = {};
    // Add eventPrefix to all event types
    for (var key in Event) {
        Event[key] = eventPrefix + Event[key];
        EventMap[Event[key]] = key;
    }

    Error = {
        UNKNOWN: "An unknown error occured.",
        INVALID_ARGUMENTS: "Invalid arguments were supplied to this method.",
        WORKER_DID_NOT_LOAD: "Unable to load worker."
    };
    WebWorker.Error = Error;

    WebWorker.throwError = WebWorker.prototype.throwError;

    // TODO: Make this method more manageable and consistent with the way jQuery handles things.
    WebWorker.noConflict = function (context, className) {
        context = context || defaultContext;
        className = className || defaultClassName;

        context[className] = WebWorker;

        return WebWorker;
    };

    WebWorker.noConflict(context, className);

    return;
})(jQuery);
<commit_msg>Polish terminate logic<commit_after>/*eslint no-native-reassign:0 */
(function ($) {
    'use strict';

    var WebWorker = null,
        NativeWorker = null,

        context = null,
        className = null,

        defaultContext = window,
        defaultClassName = 'WebWorker',

        Action = null,

        Event = null,
        eventPrefix = 'webworker:',

        EventMap = null,

        Error = null,

        slice = null;

    var windowConsole = window.console,
        console = null;

    console = {
        log: function (data, suppressNoise) {
            suppressNoise = suppressNoise || false;

            if (suppressNoise) {
                windowConsole.log(data);
            }
            else {
                windowConsole.log({
                    '>>>>>>>> internal': true,
                    'log': data
                });
            }

            return;
        },
        warn: windowConsole.warn,
        error: windowConsole.error
    };

    context = context || defaultContext;
    className = className || defaultClassName;

    WebWorker = context[className] || null;

    if (WebWorker !== null) {
        return;
    }

    slice = Array.prototype.slice;
    NativeWorker = window.Worker;

    WebWorker = function () {
        this._constructor.apply(this, arguments);
        return;
    };

    WebWorker.prototype.$ = null;

    WebWorker.prototype._workerUrl = null;
    WebWorker.prototype._workerBlobUrl = null;

    WebWorker.prototype._workerScript = null;

    WebWorker.prototype._nativeWorker = null;
    WebWorker.prototype._lastError = null;

    WebWorker.prototype._hasLoaded = false;

    WebWorker.prototype._isTerminateInitialized = false;

    WebWorker.prototype._constructor = function (opts) {
        var $scriptElement = null,
            scriptContents = null,
            workerUrl = null;

        this.$ = $(this);

        opts = opts || null;

        if (opts === null) {
            this.throwError(Error.INVALID_ARGUMENTS, null, true);
            return;
        }

        if (typeof opts === 'string') {
            opts = $.trim(opts);

            try {
                $scriptElement = $(opts);
            }
            catch (err) {
                // Cannot be resolved as a selector
            }

            if ($scriptElement !== null && $scriptElement.length > 0) {
                // Matching script element found
                // Cache its contents
                scriptContents = $scriptElement.text();
                this._workerScript = scriptContents;
            }
            else {
                workerUrl = opts;
            }
        }

        this._workerUrl = workerUrl;

        this._assignEventHandlers();

        this.trigger(Event.INITIALIZED);

        return;
    };

    WebWorker.prototype.getUrl = function () {
        return this._workerUrl;
    };

    WebWorker.prototype.getBlobUrl = function () {
        return this._workerBlobUrl;
    };

    WebWorker.prototype.getNativeWorker = function () {
        return this._nativeWorker;
    };

    WebWorker.prototype.hasLoaded = function () {
        return this._hasLoaded;
    };

    WebWorker.prototype.load = function () {
        var worker = this,
            workerUrl = null,
            onScriptLoaded = null;

        // Trigger event
        worker.trigger(Event.WORKER_LOADING);

        workerUrl = worker.getUrl() || null;
        onScriptLoaded = function () {
            var blob = null,
                scriptContents = null;

            scriptContents = worker._workerScript;
            blob = new window.Blob([scriptContents], {
                type: "text/javascript"
            });
            worker._workerBlobUrl = window.URL.createObjectURL(blob);

            worker._createWorker();

            return;
        };

        if (workerUrl === null) {
            // Script already available
            onScriptLoaded();
        }
        else {
            // Ajax request
            $.ajax({
                async: true,
                url: workerUrl,
                dataType: 'text',
                crossDomain: true,
                success: function (responseText) {
                    worker._workerScript = responseText;
                    onScriptLoaded();
                    return;
                },
                error: function () {
                    worker.throwError(Error.WORKER_DID_NOT_LOAD, arguments);
                    return;
                }
            });
        }

        return worker;
    };

    WebWorker.prototype._createWorker = function () {
        var worker = this;

        worker._nativeWorker = new NativeWorker(worker.getUrl());

        // TODO: Cleanup
        $(worker.getNativeWorker()).on('message', function (event) {
            console.log('onmessage');
            console.log(event, true);

            var originalEvent = event.originalEvent || event,
                msg = originalEvent.data,
                action = null,
                args = null;

            if ((typeof msg === 'object')
                && ('__isWebWorkerMsg' in msg)
                && (msg.__isWebWorkerMsg)) {
                action = msg.action;
                args = msg.args;

                worker[action].apply(worker, args);
                return;
            }

            return;
        });

        worker._initializeWorker();
        return;
    };

    WebWorker.prototype._assignEventHandlers = function () {
        var worker = this;

        worker.on(Event.ERROR, function () {
            console.log('error');
            console.log(arguments);
            return;
        });

        worker.on(Event.WORKER_LOADED, function () {
            worker._hasLoaded = true;
            return;
        });

        worker.on(Event.TERMINATE, function () {
            worker._isTerminateInitialized = true;
            return;
        });

        return worker;
    };

    WebWorker.prototype.isTerminateInitialized = function () {
        return this._isTerminateInitialized;
    };

    WebWorker.prototype.start = function () {
        var worker = this,
            args = null;

        if (!worker.hasLoaded()) {
            return false;
        }

        worker.trigger(Event.WORKER_STARTING);

        args = slice.call(arguments);
        worker.sendMessage(Action.START, args);

        return worker;
    };

    WebWorker.prototype.sendMessage = function (action, args) {
        var worker = this,
            nativeWorker = null,
            message = null;

        action = action || null;
        args = args || null;

        if (action === null) {
            return false;
        }

        message = {
            __isWebWorkerMsg: true
        };

        message.action = action;
        message.args = args;

        nativeWorker = worker.getNativeWorker();

        if (nativeWorker !== null) {
            nativeWorker.postMessage(message);
        }

        return worker;
    };

    WebWorker.prototype._initializeWorker = function () {
        var worker = this;
        //worker.sendMessage(Action.INIT);
        return worker;
    };

    WebWorker.prototype.terminate = function () {
        var worker = this,
            nativeWorker = worker.getNativeWorker() || null;

        if (nativeWorker !== null) {
            worker.trigger(Event.WORKER_TERMINATING);
            worker.sendMessage(Action.TERMINATE, arguments);
        }

        return;
    };

    WebWorker.prototype.terminateNow = function (returnValue) {
        var worker = this,
            nativeWorker = null;

        if (!worker.isTerminateInitialized()) {
            worker.trigger(Event.WORKER_TERMINATING);
        }

        nativeWorker = worker.getNativeWorker() || null;

        if (nativeWorker !== null) {
            nativeWorker.terminate();
            worker._hasLoaded = false;
            worker.trigger(Event.WORKER_TERMINATED, {returnValue: returnValue});
        }
        return;
    };

    WebWorker.prototype.on = function () {
        var $worker = this.$;
        $worker.on.apply($worker, arguments);
        return this;
    };

    WebWorker.prototype.one = function () {
        var $worker = this.$;
        $worker.one.apply($worker, arguments);
        return this;
    };

    WebWorker.prototype.off = function () {
        var worker = this,
            $worker = worker.$;

        $worker.off.apply($worker, arguments);
        worker._assignEventHandlers();

        return this;
    };

    WebWorker.prototype.trigger = function (event) {
        var worker = this,
            passedEventString = false,
            eventType = null,
            eventArgs = null;

        if (typeof event === 'object') {
            eventType = event.type || null;
        }

        if (typeof event === 'string') {
            eventType = event || null;
            passedEventString = true;
        }

        if (eventType === null) {
            return worker;
        }

        if (eventType in EventMap) {
            if (passedEventString) {
                event = new $.Event(eventType);
            }
            event.worker = worker;
            eventArgs = [event];
            if (arguments.length > 1) {
                eventArgs = eventArgs.concat(slice.call(arguments, 1));
            }

            worker._triggerSelf.apply(worker, eventArgs);
            return worker;
        }

        if (passedEventString) {
            event = {
                type: eventType,
                data: null
            };
        }
        eventArgs = [event];
        worker.sendMessage(Action.TRIGGER_SELF, eventArgs);

        return worker;
    };

    WebWorker.prototype.triggerSelf = function (event) {
        var worker = this,
            eventType = null,
            eventArgs = null;

        if (typeof event === 'string') {
            eventType = event;
            event = new $.Event(eventType);
        }

        event.worker = worker;
        eventArgs = [event];
        if (arguments.length > 1) {
            eventArgs = eventArgs.concat(slice.call(arguments, 1));
        }

        worker._triggerSelf.apply(worker, eventArgs);

        return;
    };

    WebWorker.prototype._triggerSelf = function () {
        var worker = this,
            $worker = null;

        $worker = worker.$;
        $worker.trigger.apply($worker, arguments);

        return;
    };

    WebWorker.prototype.throwError = function (error, data, throwException) {
        var worker = this;

        error = error || Error.UNKNOWN;
        data = (typeof data === 'undefined') ? null : data;
        throwException = throwException || false;

        worker._lastError = error;
        WebWorker._lastError = error;

        if ('_triggerError' in worker) {
            worker._triggerError(error, data, throwException);
        }

        if (throwException) {
            throw new window.Error(error);
        }

        return;
    };

    WebWorker.prototype._triggerError = function (error, data, throwException) {
        var worker = this,
            errorEvent = null;

        errorEvent = new $.Event(Event.ERROR);
        errorEvent.message = worker.getLastError();
        errorEvent.data = data;
        errorEvent.throwsException = (!!throwException);

        worker.trigger(errorEvent);
        return;
    };

    WebWorker.prototype.getLastError = function () {
        return this._lastError;
    };

    // Static

    WebWorker._lastError = null;

    Action = {
        INIT: 'init',
        START: 'start',
        TERMINATE: 'terminate',
        TERMINATE_NOW: 'terminateNow',
        TRIGGER: 'trigger',
        TRIGGER_SELF: 'triggerSelf'
    };
    WebWorker.Action = Action;

    Event = {
        INITIALIZED: 'initialized',
        ERROR: 'error',

        WORKER_LOADING: 'worker-loading',
        WORKER_LOADED: 'worker-loaded',

        WORKER_STARTING: 'worker-starting',
        WORKER_STARTED: 'worker-started',

        WORKER_TERMINATING: 'worker-terminating',
        WORKER_TERMINATED: 'worker-terminated'
    };
    WebWorker.Event = Event;

    EventMap = {};

    // Add eventPrefix to all event types
    for (var key in Event) {
        Event[key] = eventPrefix + Event[key];
        EventMap[Event[key]] = key;
    }

    Error = {
        UNKNOWN: "An unknown error occured.",
        INVALID_ARGUMENTS: "Invalid arguments were supplied to this method.",
        WORKER_DID_NOT_LOAD: "Unable to load worker."
    };
    WebWorker.Error = Error;

    WebWorker.throwError = WebWorker.prototype.throwError;

    // TODO: Make this method more manageable and consistent with the way jQuery handles things.
    WebWorker.noConflict = function (context, className) {
        context = context || defaultContext;
        className = className || defaultClassName;

        context[className] = WebWorker;

        return WebWorker;
    };

    WebWorker.noConflict(context, className);

    return;
})(jQuery);
<|endoftext|>


<commit_before>/*
Language: CSS
*/

function(hljs) {
  var IDENT_RE = '[a-zA-Z-][a-zA-Z0-9_-]*';
  var FUNCTION = {
    className: 'function',
    begin: IDENT_RE + '\\(', end: '\\)',
    contains: ['self', hljs.NUMBER_MODE, hljs.APOS_STRING_MODE, hljs.QUOTE_STRING_MODE]
  };
  return {
    case_insensitive: true,
    illegal: '[=/|\']',
    contains: [
      hljs.C_BLOCK_COMMENT_MODE,
      {
        className: 'id', begin: '\\#[A-Za-z0-9_-]+'
      },
      {
        className: 'class', begin: '\\.[A-Za-z0-9_-]+',
        relevance: 0
      },
      {
        className: 'attr_selector',
        begin: '\\[', end: '\\]',
        illegal: '$'
      },
      {
        className: 'pseudo',
        begin: ':(:)?[a-zA-Z0-9\\_\\-\\+\\(\\)\\"\\\']+'
      },
      {
        className: 'at_rule',
        begin: '@(font-face|page)',
        lexems: '[a-z-]+',
        keywords: 'font-face page'
      },
      {
        className: 'at_rule',
        begin: '@', end: '[{;]', // at_rule eating first "{" is a good thing
                                 // because it doesn’t let it to be parsed as
                                 // a rule set but instead drops parser into
                                 // the default mode which is how it should be.
        excludeEnd: true,
        keywords: 'import page media charset',
        contains: [
          FUNCTION,
          hljs.APOS_STRING_MODE, hljs.QUOTE_STRING_MODE,
          hljs.NUMBER_MODE
        ]
      },
      {
        className: 'tag', begin: IDENT_RE,
        relevance: 0
      },
      {
        className: 'rules',
        begin: '{', end: '}',
        illegal: '[^\\s]',
        relevance: 0,
        contains: [
          hljs.C_BLOCK_COMMENT_MODE,
          {
            className: 'rule',
            begin: '[^\\s]', returnBegin: true, end: ';', endsWithParent: true,
            contains: [
              {
                className: 'attribute',
                begin: '[A-Z\\_\\.\\-]+', end: ':',
                excludeEnd: true,
                illegal: '[^\\s]',
                starts: {
                  className: 'value',
                  endsWithParent: true, excludeEnd: true,
                  contains: [
                    FUNCTION,
                    hljs.NUMBER_MODE,
                    hljs.QUOTE_STRING_MODE,
                    hljs.APOS_STRING_MODE,
                    hljs.C_BLOCK_COMMENT_MODE,
                    {
                      className: 'hexcolor', begin: '\\#[0-9A-F]+'
                    },
                    {
                      className: 'important', begin: '!important'
                    }
                  ]
                }
              }
            ]
          }
        ]
      }
    ]
  };
}
<commit_msg>Fix hexcolor definition for CSS too.<commit_after>/*
Language: CSS
*/

function(hljs) {
  var IDENT_RE = '[a-zA-Z-][a-zA-Z0-9_-]*';
  var FUNCTION = {
    className: 'function',
    begin: IDENT_RE + '\\(', end: '\\)',
    contains: ['self', hljs.NUMBER_MODE, hljs.APOS_STRING_MODE, hljs.QUOTE_STRING_MODE]
  };
  return {
    case_insensitive: true,
    illegal: '[=/|\']',
    contains: [
      hljs.C_BLOCK_COMMENT_MODE,
      {
        className: 'id', begin: '\\#[A-Za-z0-9_-]+'
      },
      {
        className: 'class', begin: '\\.[A-Za-z0-9_-]+',
        relevance: 0
      },
      {
        className: 'attr_selector',
        begin: '\\[', end: '\\]',
        illegal: '$'
      },
      {
        className: 'pseudo',
        begin: ':(:)?[a-zA-Z0-9\\_\\-\\+\\(\\)\\"\\\']+'
      },
      {
        className: 'at_rule',
        begin: '@(font-face|page)',
        lexems: '[a-z-]+',
        keywords: 'font-face page'
      },
      {
        className: 'at_rule',
        begin: '@', end: '[{;]', // at_rule eating first "{" is a good thing
                                 // because it doesn’t let it to be parsed as
                                 // a rule set but instead drops parser into
                                 // the default mode which is how it should be.
        excludeEnd: true,
        keywords: 'import page media charset',
        contains: [
          FUNCTION,
          hljs.APOS_STRING_MODE, hljs.QUOTE_STRING_MODE,
          hljs.NUMBER_MODE
        ]
      },
      {
        className: 'tag', begin: IDENT_RE,
        relevance: 0
      },
      {
        className: 'rules',
        begin: '{', end: '}',
        illegal: '[^\\s]',
        relevance: 0,
        contains: [
          hljs.C_BLOCK_COMMENT_MODE,
          {
            className: 'rule',
            begin: '[^\\s]', returnBegin: true, end: ';', endsWithParent: true,
            contains: [
              {
                className: 'attribute',
                begin: '[A-Z\\_\\.\\-]+', end: ':',
                excludeEnd: true,
                illegal: '[^\\s]',
                starts: {
                  className: 'value',
                  endsWithParent: true, excludeEnd: true,
                  contains: [
                    FUNCTION,
                    hljs.NUMBER_MODE,
                    hljs.QUOTE_STRING_MODE,
                    hljs.APOS_STRING_MODE,
                    hljs.C_BLOCK_COMMENT_MODE,
                    {
                      className: 'hexcolor', begin: '#[0-9A-Fa-f]+'
                    },
                    {
                      className: 'important', begin: '!important'
                    }
                  ]
                }
              }
            ]
          }
        ]
      }
    ]
  };
}
<|endoftext|>


<commit_before>/*
Language: HTML, XML
Category: common
*/

hljs.LANGUAGES.xml = function(){
  var XML_IDENT_RE = '[A-Za-z0-9\\._:-]+';
  var TAG_INTERNALS = {
    endsWithParent: true,
    contains: [
      {
        className: 'attribute',
        begin: XML_IDENT_RE,
        relevance: 0
      },
      {
        begin: '="', returnBegin: true, end: '"',
        contains: [{
            className: 'value',
            begin: '"', endsWithParent: true
        }]
      },
      {
        begin: '=\'', returnBegin: true, end: '\'',
        contains: [{
          className: 'value',
          begin: '\'', endsWithParent: true
        }]
      },
      {
        begin: '=',
        contains: [{
          className: 'value',
          begin: '[^\\s/>]+'
        }]
      }
    ]
  };
  return {
    case_insensitive: true,
    defaultMode: {
      contains: [
        {
          className: 'pi',
          begin: '<\\?', end: '\\?>',
          relevance: 10
        },
        {
          className: 'doctype',
          begin: '<!DOCTYPE', end: '>',
          relevance: 10
        },
        {
          className: 'comment',
          begin: '<!--', end: '-->',
          relevance: 10
        },
        {
          className: 'cdata',
          begin: '<\\!\\[CDATA\\[', end: '\\]\\]>',
          relevance: 10
        },
        {
          className: 'tag',
          begin: '<style', end: '>',
          keywords: {'title': {'style': 1}},
          contains: [TAG_INTERNALS],
          starts: {
            className: 'css',
            end: '</style>', returnEnd: true,
            subLanguage: 'css'
          }
        },
        {
          className: 'tag',
          begin: '<script', end: '>',
          keywords: {'title': {'script': 1}},
          contains: [TAG_INTERNALS],
          starts: {
            className: 'javascript',
            end: '</script>', returnEnd: true,
            subLanguage: 'javascript'
          }
        },
        {
          className: 'vbscript',
          begin: '<%', end: '%>',
          subLanguage: 'vbscript'
        },
        {
          className: 'tag',
          begin: '</?', end: '/?>',
          contains: [
            {
              className: 'title', begin: '[^ />]+'
            },
            TAG_INTERNALS
          ]
        }
      ]
    }
  };
}();
<commit_msg>Eat everything between [ .. ] inside XML DOCTYPE<commit_after>/*
Language: HTML, XML
Category: common
*/

hljs.LANGUAGES.xml = function(){
  var XML_IDENT_RE = '[A-Za-z0-9\\._:-]+';
  var TAG_INTERNALS = {
    endsWithParent: true,
    contains: [
      {
        className: 'attribute',
        begin: XML_IDENT_RE,
        relevance: 0
      },
      {
        begin: '="', returnBegin: true, end: '"',
        contains: [{
            className: 'value',
            begin: '"', endsWithParent: true
        }]
      },
      {
        begin: '=\'', returnBegin: true, end: '\'',
        contains: [{
          className: 'value',
          begin: '\'', endsWithParent: true
        }]
      },
      {
        begin: '=',
        contains: [{
          className: 'value',
          begin: '[^\\s/>]+'
        }]
      }
    ]
  };
  return {
    case_insensitive: true,
    defaultMode: {
      contains: [
        {
          className: 'pi',
          begin: '<\\?', end: '\\?>',
          relevance: 10
        },
        {
          className: 'doctype',
          begin: '<!DOCTYPE', end: '>',
          relevance: 10,
          contains: [{begin: '\\[', end: '\\]'}]
        },
        {
          className: 'comment',
          begin: '<!--', end: '-->',
          relevance: 10
        },
        {
          className: 'cdata',
          begin: '<\\!\\[CDATA\\[', end: '\\]\\]>',
          relevance: 10
        },
        {
          className: 'tag',
          begin: '<style', end: '>',
          keywords: {'title': {'style': 1}},
          contains: [TAG_INTERNALS],
          starts: {
            className: 'css',
            end: '</style>', returnEnd: true,
            subLanguage: 'css'
          }
        },
        {
          className: 'tag',
          begin: '<script', end: '>',
          keywords: {'title': {'script': 1}},
          contains: [TAG_INTERNALS],
          starts: {
            className: 'javascript',
            end: '</script>', returnEnd: true,
            subLanguage: 'javascript'
          }
        },
        {
          className: 'vbscript',
          begin: '<%', end: '%>',
          subLanguage: 'vbscript'
        },
        {
          className: 'tag',
          begin: '</?', end: '/?>',
          contains: [
            {
              className: 'title', begin: '[^ />]+'
            },
            TAG_INTERNALS
          ]
        }
      ]
    }
  };
}();
<|endoftext|>


<commit_before>const indent = require('./indent')
const os = require('os')
const Result = require('./Result')

module.exports = class NestedResult extends Result {
  constructor (runnable, results = []) {
    super(runnable,
          results.some(result => result.error !== undefined) || undefined)
    this.results = results
  }

  toTree () {
    const indented = this.results.map(result => indent(result.toTree()))
    return [this.toString(), ...indented].join(os.EOL)
  }
}
<commit_msg>Simplify NestedResult constructor<commit_after>const _ = require('lodash/fp')
const indent = require('./indent')
const os = require('os')
const Result = require('./Result')

module.exports = class NestedResult extends Result {
  constructor (runnable, results = []) {
    super(runnable, _.some('error')(results) || undefined)
    this.results = results
  }

  toTree () {
    const indented = this.results.map(result => indent(result.toTree()))
    return [this.toString(), ...indented].join(os.EOL)
  }
}
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import Link from 'gatsby-link'
import Helmet from 'react-helmet'
import { ThemeProvider } from 'styled-components'

import Icons from '../assets/images/icons'
import settings from '../lib/settings'
import './reset.css'
import './base.css'

const TemplateWrapper = ({ children }) => (

    <Icons />
    <Helmet>
      <title>Barrier & Co</title>
      <meta name='description' content="Barrier & Company exists to create a solution for some of today's greatest technological problems so that other people can enjoy the fullness of life itself."  />
      <meta itemprop="name" content="Barrier & Co." />
      <meta itemprop="description" content="Barrier & Company exists to create a solution for some of today's greatest technological problems so that other people can enjoy the fullness of life itself." />
      <meta itemprop="image" content="http://barrierandco.com/static/meta-image.png" />
      <meta name="twitter:card" content="summary_large_image" />
      <meta name="twitter:title" content="Barrier & Co." />
      <meta name="twitter:description" content="Barrier & Company exists to create a solution for some of today's greatest technological problems so that other people can enjoy the fullness of life itself." />
      <meta name="twitter:creator" content="@jhnwlsn" />
      <meta name="twitter:image:src" content="http://barrierandco.com/static/meta-image.png" />
      <meta property="og:title" content="Barrier & Co." />
      <meta property="og:type" content="website" />
      <meta property="og:url" content="http://barrierandco.com" />
      <meta property="og:image" content="http://barrierandco.com/static/meta-image.png" />
      <meta property="og:image:height" content="150" />
      <meta property="og:image:width" content="280" />
      <meta property="og:description" content="Barrier & Company exists to create a solution for some of today's greatest technological problems so that other people can enjoy the fullness of life itself." />
      <meta property="og:site_name" content="Barrier & Co." />

    </Helmet>
    <ThemeProvider theme={settings}>
      {children()}
    </ThemeProvider>

)

TemplateWrapper.propTypes = {
  children: PropTypes.func,
}

export default TemplateWrapper<commit_msg>Remove drift<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import Link from 'gatsby-link'
import Helmet from 'react-helmet'
import { ThemeProvider } from 'styled-components'

import Icons from '../assets/images/icons'
import settings from '../lib/settings'
import './reset.css'
import './base.css'

const TemplateWrapper = ({ children }) => (

    <Icons />
    <Helmet>
      <title>Barrier & Co</title>
      <meta name='description' content="Barrier & Company exists to create a solution for some of today's greatest technological problems so that other people can enjoy the fullness of life itself."  />
      <meta itemprop="name" content="Barrier & Co." />
      <meta itemprop="description" content="Barrier & Company exists to create a solution for some of today's greatest technological problems so that other people can enjoy the fullness of life itself." />
      <meta itemprop="image" content="http://barrierandco.com/static/meta-image.png" />
      <meta name="twitter:card" content="summary_large_image" />
      <meta name="twitter:title" content="Barrier & Co." />
      <meta name="twitter:description" content="Barrier & Company exists to create a solution for some of today's greatest technological problems so that other people can enjoy the fullness of life itself." />
      <meta name="twitter:creator" content="@jhnwlsn" />
      <meta name="twitter:image:src" content="http://barrierandco.com/static/meta-image.png" />
      <meta property="og:title" content="Barrier & Co." />
      <meta property="og:type" content="website" />
      <meta property="og:url" content="http://barrierandco.com" />
      <meta property="og:image" content="http://barrierandco.com/static/meta-image.png" />
      <meta property="og:image:height" content="150" />
      <meta property="og:image:width" content="280" />
      <meta property="og:description" content="Barrier & Company exists to create a solution for some of today's greatest technological problems so that other people can enjoy the fullness of life itself." />
      <meta property="og:site_name" content="Barrier & Co." />

    </Helmet>
    <ThemeProvider theme={settings}>
      {children()}
    </ThemeProvider>

)

TemplateWrapper.propTypes = {
  children: PropTypes.func,
}

export default TemplateWrapper<|endoftext|>


<commit_before>var React = require('react');
var ContextTypes = require('./ContextTypes');
var ShouldUpdate = require('./ShouldUpdate');

var Component = React.Component;
Component.contextTypes = ContextTypes;
Component.shouldComponentUpdate = ShouldUpdate.shouldComponentUpdate;

module.exports = Component;<commit_msg>autobinding<commit_after>var React = require('react');
var ContextTypes = require('./ContextTypes');
var ShouldUpdate = require('./ShouldUpdate');

var Base = React.Component;
Base.contextTypes = ContextTypes;
Base.shouldComponentUpdate = ShouldUpdate.shouldComponentUpdate;

class Component extends Base {
  constructor(props, shouldAutoBind = true) {
    super(props);
    if (shouldAutoBind)
      this.autoBind();
  }

  bind(methods) {
    methods.forEach(method => this[method] = this[method].bind(this));
  }

  autoBind() {
    const classProps = Object.getOwnPropertyNames(this.constructor.prototype);
    const classFuncs = classProps.filter(prop => typeof this[prop] === 'function');
    this.bind(classFuncs);
  }
}

module.exports = Component;<|endoftext|>


<commit_before>/**
	_onyx.IntegerPicker_, a subkind of onyx.Picker, is used to
	display	a list of integers that can be selected, ranging from _min_ to _max_. It is meant
	to be used in conjunction with an onyx.PickerDecorator.
	The decorator loosely couples the picker with an
	onyx.PickerButton--a button that, when
	tapped, shows the picker. Once an item is selected, the list of items closes,
	but the item stays selected and the PickerButton displays the choice that
	was made.

	To initialize the IntegerPicker to a particular value, set the _value_ property to
	the integer that should be selected.

		{kind: "onyx.PickerDecorator", components: [
			{}, //this uses the defaultKind property of PickerDecorator to inherit from PickerButton
			{kind: "onyx.IntegerPicker", min: 0, max: 25, value: 5}
		]}

	Each item in the list is an onyx.MenuItem, so
	an _onSelect_ event with the item can be listened to by a client application
	to determine which picker item was selected.

	For more information, see the documentation on
	Pickers in the
	Enyo Developer Guide.
 */
enyo.kind({
	name: "onyx.IntegerPicker",
	kind: "onyx.Picker",
	published: {
		value: 0,
		min: 0,
		max: 9
	},
	//* @protected
	create: function() {
		this.inherited(arguments);
		this.rangeChanged();
	},
	minChanged: function() {
		this.destroyClientControls();
		this.rangeChanged();
		this.render();
	},
	maxChanged: function() {
		this.destroyClientControls();
		this.rangeChanged();
		this.render();
	},
	rangeChanged: function() {
		for (var i=this.min; i<=this.max; i++) {
			this.createComponent({content: i, active: (i===this.value) ? true : false});
		}
	},
	valueChanged: function(inOld) {
		var controls = this.getClientControls();
		var len = controls.length;
		// Validate our value
		this.value = this.value >= this.min && this.value <= this.max ? this.value : this.min;
		for (var i=0; i<len; i++) {
			if (this.value === parseInt(controls[i].content)) {
				this.setSelected(controls[i]);
				break;
			}
		}
	},
	selectedChanged: function(inOld) {
		if (inOld) {
			inOld.removeClass("selected");
		}
		if (this.selected) {
			this.selected.addClass("selected");
			this.doChange({selected: this.selected, content: this.selected.content});
		}
		this.value = parseInt(this.selected.content);
	}
});
<commit_msg>API comment cleanup for new kind. Enyo-DCO-1.1-Signed-off-by: Jim Tang <jim.tang@palm.com><commit_after>/**
    _onyx.IntegerPicker_, a subkind of onyx.Picker,
    is used to display a list of integers that can be selected, ranging from
    _min_ to _max_. It is meant to be used in conjunction with an
    onyx.PickerDecorator. The decorator
    loosely couples the picker with an
    onyx.PickerButton--a button that, when
    tapped, shows the picker. Once an item is selected, the list of items
    closes,	but the item stays selected and the PickerButton displays the choice
    that was made.

    To initialize the IntegerPicker to a particular value, set the _value_
    property to the integer that should be selected.

        {kind: "onyx.PickerDecorator", components: [
            {}, //this uses the defaultKind property of PickerDecorator to inherit from PickerButton
            {kind: "onyx.IntegerPicker", min: 0, max: 25, value: 5}
        ]}

    Each item in the list is an onyx.MenuItem, so
    an application may listen for an _onSelect_ event with the item to determine
    which picker item was selected.

    For more information, see the documentation on
    Pickers in the
    Enyo Developer Guide.
 */
enyo.kind({
	name: "onyx.IntegerPicker",
	kind: "onyx.Picker",
	published: {
		value: 0,
		min: 0,
		max: 9
	},
	//* @protected
	create: function() {
		this.inherited(arguments);
		this.rangeChanged();
	},
	minChanged: function() {
		this.destroyClientControls();
		this.rangeChanged();
		this.render();
	},
	maxChanged: function() {
		this.destroyClientControls();
		this.rangeChanged();
		this.render();
	},
	rangeChanged: function() {
		for (var i=this.min; i<=this.max; i++) {
			this.createComponent({content: i, active: (i===this.value) ? true : false});
		}
	},
	valueChanged: function(inOld) {
		var controls = this.getClientControls();
		var len = controls.length;
		// Validate our value
		this.value = this.value >= this.min && this.value <= this.max ? this.value : this.min;
		for (var i=0; i<len; i++) {
			if (this.value === parseInt(controls[i].content)) {
				this.setSelected(controls[i]);
				break;
			}
		}
	},
	selectedChanged: function(inOld) {
		if (inOld) {
			inOld.removeClass("selected");
		}
		if (this.selected) {
			this.selected.addClass("selected");
			this.doChange({selected: this.selected, content: this.selected.content});
		}
		this.value = parseInt(this.selected.content);
	}
});
<|endoftext|>


<commit_before>/**
	_moon.IntegerPicker_ is a control that displays a list of integers
	ranging from _min_ to _max_, soliciting a choice from the user.

	To initialize the picker to a particular integer, set the _value_ property to
	that integer:

		{kind: "moon.IntegerPicker", noneText: "None Selected",
			content: "Choose a Number", min: 0, max: 25, value: 5}

	The picker may be changed programmatically by modifying the published
	properties _value_,	_min_, or _max_ in the normal manner, by calling _set()_.
*/
enyo.kind({
	name: "moon.IntegerPicker",
	//* @protected
	classes: "moon-scroll-picker-container",
	//* @public
	published: {
		//* Current value of the picker
		value: null,
		//* Minimum value of the picker
		min: 0,
		//* Maximum value of the picker
		max: 9,
		//* If a number is specified, the picker value is displayed as this many
		//* zero-filled digits
		digits: null,
		/**
			When true, incrementing beyond _max_ will wrap to _min_, and decrementing
			beyond _min_ will wrap to _max_
		*/
		wrap: false
	},
	//* @protected
	handlers: {
		onSpotlightUp:"next",
		onSpotlightDown:"previous",
		onSpotlightBlur:"spotlightBlur",
		onSpotlightScrollUp:"next",
		onSpotlightScrollDown:"previous",
		onmousewheel:"mousewheel"
	},
	//* @public
	events: {
		/**
			Fires when the currently selected value changes (i.e., when either
			_topOverlay_ or _bottomOverlay_ is tapped).

			_inEvent.name_ contains the name of the IntegerPicker instance.

			_inEvent.value_ contains the current value of the picker.
		*/
		onChange: ""
	},
	//* @protected
	spotlight: true,
	//* Cache scroll bounds so we don't have to run _stop()_ every time we need them
	scrollBounds: {},
	components: [
		{name:"topOverlay", ondown:"downNext", onholdpulse:"next", classes:"moon-scroll-picker-overlay-container top top-image", components:[
			{classes:"moon-scroll-picker-overlay top"},
			{classes: "moon-scroll-picker-taparea"}
		]},
		{kind: "enyo.Scroller", thumb:false, touch:true, useMouseWheel: false, classes: "moon-scroll-picker", components:[
			{name:"repeater", kind:"enyo.FlyweightRepeater", ondragstart: "dragstart", onSetupItem: "setupItem", components: [
				{name: "item", classes:"moon-scroll-picker-item"}
			]}
		]},
		{name:"bottomOverlay", ondown:"downPrevious", onholdpulse:"previous", classes:"moon-scroll-picker-overlay-container bottom bottom-image", components:[
			{classes:"moon-scroll-picker-overlay bottom"},
			{classes: "moon-scroll-picker-taparea"}
		]}
	],
	//* @protected
	scrollFrame: 3, // parameter that determines scroll math simulation speed
	rendered: function(){
		this.inherited(arguments);
		this.rangeChanged();
		this.updateOverlays();
		this.refreshScrollState();
		this.$.scroller.getStrategy().setFixedTime(false);
		this.$.scroller.getStrategy().setFrame(this.scrollFrame);
	},
	refreshScrollState: function() {
		this.updateScrollBounds();
		var node = this.$.repeater.fetchRowNode(this.value - this.min);
		if (node) {
			this.$.scroller.scrollToNode(node);
		}
	},
	setupItem: function(inSender, inEvent) {
		var index = inEvent.index;
		var content = index + this.min;
		if (this.digits) {
			content = ("00000000000000000000" + content).slice(-this.digits);
		}
		this.$.item.setContent(content);
	},
	rangeChanged: function() {
		this.value = this.value >= this.min && this.value <= this.max ? this.value : this.min;
		this.$.repeater.setCount(this.max-this.min+1);
		this.$.repeater.render();
		//asynchronously scroll to the current node, this works around a potential scrolling glitch
		enyo.asyncMethod(this.bindSafely(function(){
			var node = this.$.repeater.fetchRowNode(this.value - this.min);
			if (node) {
				this.$.scroller.scrollToNode(node);
			}
		}));
	},
	valueChanged: function(inOld) {
		var node = this.$.repeater.fetchRowNode(this.value - this.min);
		if (node) {
			this.$.scroller.scrollTo(node.offsetLeft, node.offsetTop);
		}
		this.updateOverlays();
	},
	//prevent scroller dragging
	dragstart: function(inSender, inEvent) {
		return true;
	},
	/**
		fail-safe design.
		If out boundary value is assigned, adjust boundary.
	*/
	setValue: function(inValue) {
		if (inValue < this.min) {
			this.setMin(inValue);
		} else if (inValue > this.max) {
			this.setMax(inValue);
		}
		this.set("value", inValue);
	},
	minChanged: function() {
		this.rangeChanged();
	},
	maxChanged: function() {
		this.rangeChanged();
	},
	previous: function(inSender, inEvent) {
		if (this.value > this.min) {
			this.setValue(this.value - 1);
		} else if (this.wrap) {
			this.setValue(this.max);
		} else {
			return;
		}
		this.$.bottomOverlay.addClass("selected");
		if (inEvent.originator != this.$.upArrow) {
			this.startJob("hideBottomOverlay", "hideBottomOverlay", 350);
		}
		this.fireChangeEvent();
		return true;
	},
	next: function(inSender, inEvent) {
		if (this.value < this.max) {
			this.setValue(this.value + 1);
		} else if (this.wrap) {
			this.setValue(this.min);
		} else {
			return;
		}
		this.$.topOverlay.addClass("selected");
		if (inEvent.originator != this.$.downArrow) {
			this.startJob("hideTopOverlay", "hideTopOverlay", 350);
		}
		this.fireChangeEvent();
		return true;
	},
	downPrevious: function(inSender, inEvent) {
		inEvent.configureHoldPulse({endHold: "onLeave", delay: 300});
		this.previous(inSender, inEvent);
	},
	downNext: function(inSender, inEvent) {
		inEvent.configureHoldPulse({endHold: "onLeave", delay: 300});
		this.next(inSender, inEvent);
	},
	updateOverlays: function() {
		this.$.bottomOverlay.addRemoveClass("bottom-image", this.wrap || (this.value !== this.min));
		this.$.topOverlay.addRemoveClass("top-image", this.wrap || (this.value !== this.max));
	},
	hideTopOverlay: function() {
		this.$.topOverlay.removeClass("selected");
	},
	hideBottomOverlay: function() {
		this.$.bottomOverlay.removeClass("selected");
	},
	fireChangeEvent: function() {
		this.doChange({
			name:this.name,
			value:this.value
		});
	},
	resetOverlay: function() {
		this.hideTopOverlay();
		this.hideBottomOverlay();
	},
	spotlightFocus: function() {
		this.bubble("onRequestScrollIntoView");
	},
	spotlightBlur: function() {
		this.hideTopOverlay();
		this.hideBottomOverlay();
	},
	//* Cache scroll bounds in _this.scrollBounds_ so we don't have to call stop() to retrieve them later
	updateScrollBounds: function() {
		this.scrollBounds = this.$.scroller.getStrategy()._getScrollBounds();
	},
	//* Silently scrolls to the _inValue_ y-position without animating
	setScrollTop: function(inValue) {
		this.$.scroller.setScrollTop(inValue);
	},
	//* Ensures scroll position is in bounds.
	stabilize: function() {
		this.$.scroller.stabilize();
	},
	mousewheel: function(inSender, inEvent) {
		// Make sure scrollers that container integer pickers don't scroll
		inEvent.preventDefault();
		return true;
	}
});

// For backward compatibility
moon.IntegerScrollPicker = moon.IntegerPicker;
<commit_msg>ANG-6413 Use changed method rather than setter. Previous code could not handle a case that user calls set("value", new date).<commit_after>/**
	_moon.IntegerPicker_ is a control that displays a list of integers
	ranging from _min_ to _max_, soliciting a choice from the user.

	To initialize the picker to a particular integer, set the _value_ property to
	that integer:

		{kind: "moon.IntegerPicker", noneText: "None Selected",
			content: "Choose a Number", min: 0, max: 25, value: 5}

	The picker may be changed programmatically by modifying the published
	properties _value_,	_min_, or _max_ in the normal manner, by calling _set()_.
*/
enyo.kind({
	name: "moon.IntegerPicker",
	//* @protected
	classes: "moon-scroll-picker-container",
	//* @public
	published: {
		//* Current value of the picker
		value: null,
		//* Minimum value of the picker
		min: 0,
		//* Maximum value of the picker
		max: 9,
		//* If a number is specified, the picker value is displayed as this many
		//* zero-filled digits
		digits: null,
		/**
			When true, incrementing beyond _max_ will wrap to _min_, and decrementing
			beyond _min_ will wrap to _max_
		*/
		wrap: false
	},
	//* @protected
	handlers: {
		onSpotlightUp:"next",
		onSpotlightDown:"previous",
		onSpotlightBlur:"spotlightBlur",
		onSpotlightScrollUp:"next",
		onSpotlightScrollDown:"previous",
		onmousewheel:"mousewheel"
	},
	//* @public
	events: {
		/**
			Fires when the currently selected value changes (i.e., when either
			_topOverlay_ or _bottomOverlay_ is tapped).

			_inEvent.name_ contains the name of the IntegerPicker instance.

			_inEvent.value_ contains the current value of the picker.
		*/
		onChange: ""
	},
	//* @protected
	spotlight: true,
	//* Cache scroll bounds so we don't have to run _stop()_ every time we need them
	scrollBounds: {},
	components: [
		{name:"topOverlay", ondown:"downNext", onholdpulse:"next", classes:"moon-scroll-picker-overlay-container top top-image", components:[
			{classes:"moon-scroll-picker-overlay top"},
			{classes: "moon-scroll-picker-taparea"}
		]},
		{kind: "enyo.Scroller", thumb:false, touch:true, useMouseWheel: false, classes: "moon-scroll-picker", components:[
			{name:"repeater", kind:"enyo.FlyweightRepeater", ondragstart: "dragstart", onSetupItem: "setupItem", components: [
				{name: "item", classes:"moon-scroll-picker-item"}
			]}
		]},
		{name:"bottomOverlay", ondown:"downPrevious", onholdpulse:"previous", classes:"moon-scroll-picker-overlay-container bottom bottom-image", components:[
			{classes:"moon-scroll-picker-overlay bottom"},
			{classes: "moon-scroll-picker-taparea"}
		]}
	],
	//* @protected
	scrollFrame: 3, // parameter that determines scroll math simulation speed
	rendered: function(){
		this.inherited(arguments);
		this.rangeChanged();
		this.updateOverlays();
		this.refreshScrollState();
		this.$.scroller.getStrategy().setFixedTime(false);
		this.$.scroller.getStrategy().setFrame(this.scrollFrame);
	},
	refreshScrollState: function() {
		this.updateScrollBounds();
		var node = this.$.repeater.fetchRowNode(this.value - this.min);
		if (node) {
			this.$.scroller.scrollToNode(node);
		}
	},
	setupItem: function(inSender, inEvent) {
		var index = inEvent.index;
		var content = index + this.min;
		if (this.digits) {
			content = ("00000000000000000000" + content).slice(-this.digits);
		}
		this.$.item.setContent(content);
	},
	rangeChanged: function() {
		this.value = this.value >= this.min && this.value <= this.max ? this.value : this.min;
		this.$.repeater.setCount(this.max-this.min+1);
		this.$.repeater.render();
		//asynchronously scroll to the current node, this works around a potential scrolling glitch
		enyo.asyncMethod(this.bindSafely(function(){
			var node = this.$.repeater.fetchRowNode(this.value - this.min);
			if (node) {
				this.$.scroller.scrollToNode(node);
			}
		}));
	},
	/**
		fail-safe design.
		If out boundary value is assigned, adjust boundary.
	*/
	valueChanged: function(inOld) {
		if (this.value < this.min) {
			this.setMin(this.value);
		} else if (this.value > this.max) {
			this.setMax(this.value);
		}

		var node = this.$.repeater.fetchRowNode(this.value - this.min);
		if (node) {
			this.$.scroller.scrollTo(node.offsetLeft, node.offsetTop);
		}
		this.updateOverlays();
	},
	//prevent scroller dragging
	dragstart: function(inSender, inEvent) {
		return true;
	},
	minChanged: function() {
		this.rangeChanged();
	},
	maxChanged: function() {
		this.rangeChanged();
	},
	previous: function(inSender, inEvent) {
		if (this.value > this.min) {
			this.setValue(this.value - 1);
		} else if (this.wrap) {
			this.setValue(this.max);
		} else {
			return;
		}
		this.$.bottomOverlay.addClass("selected");
		if (inEvent.originator != this.$.upArrow) {
			this.startJob("hideBottomOverlay", "hideBottomOverlay", 350);
		}
		this.fireChangeEvent();
		return true;
	},
	next: function(inSender, inEvent) {
		if (this.value < this.max) {
			this.setValue(this.value + 1);
		} else if (this.wrap) {
			this.setValue(this.min);
		} else {
			return;
		}
		this.$.topOverlay.addClass("selected");
		if (inEvent.originator != this.$.downArrow) {
			this.startJob("hideTopOverlay", "hideTopOverlay", 350);
		}
		this.fireChangeEvent();
		return true;
	},
	downPrevious: function(inSender, inEvent) {
		inEvent.configureHoldPulse({endHold: "onLeave", delay: 300});
		this.previous(inSender, inEvent);
	},
	downNext: function(inSender, inEvent) {
		inEvent.configureHoldPulse({endHold: "onLeave", delay: 300});
		this.next(inSender, inEvent);
	},
	updateOverlays: function() {
		this.$.bottomOverlay.addRemoveClass("bottom-image", this.wrap || (this.value !== this.min));
		this.$.topOverlay.addRemoveClass("top-image", this.wrap || (this.value !== this.max));
	},
	hideTopOverlay: function() {
		this.$.topOverlay.removeClass("selected");
	},
	hideBottomOverlay: function() {
		this.$.bottomOverlay.removeClass("selected");
	},
	fireChangeEvent: function() {
		this.doChange({
			name:this.name,
			value:this.value
		});
	},
	resetOverlay: function() {
		this.hideTopOverlay();
		this.hideBottomOverlay();
	},
	spotlightFocus: function() {
		this.bubble("onRequestScrollIntoView");
	},
	spotlightBlur: function() {
		this.hideTopOverlay();
		this.hideBottomOverlay();
	},
	//* Cache scroll bounds in _this.scrollBounds_ so we don't have to call stop() to retrieve them later
	updateScrollBounds: function() {
		this.scrollBounds = this.$.scroller.getStrategy()._getScrollBounds();
	},
	//* Silently scrolls to the _inValue_ y-position without animating
	setScrollTop: function(inValue) {
		this.$.scroller.setScrollTop(inValue);
	},
	//* Ensures scroll position is in bounds.
	stabilize: function() {
		this.$.scroller.stabilize();
	},
	mousewheel: function(inSender, inEvent) {
		// Make sure scrollers that container integer pickers don't scroll
		inEvent.preventDefault();
		return true;
	}
});

// For backward compatibility
moon.IntegerScrollPicker = moon.IntegerPicker;
<|endoftext|>


<commit_before>var Accents = new Backbone.Marionette.Application();

// pluggible regions
Accents.addRegions({
    navbar: 'header',
    main: '#maincontent',
    footer: 'footer'
});

Accents.navigate = function(route, options){
  console.log("Navigate ");
  console.log(route);
  console.log(options);
  var options = options || {};
  Backbone.history.navigate(route, options);
};

Accents.getCurrentRoute = function(){
  return Backbone.history.fragment;
};

// wire up application
var onCompleteSync = function(){
  // console.log("Trigger list:term due to onCompleteSync call");
  // Accents.trigger("list:term")
  // console.log("sync called every 10 seconds timer");
  // setTimeout(sync,10000);
};

Accents.addInitializer(function () {
  Accents.db = new PouchDB('accents');
  Accents.remoteDb = 'accents';
  //Accents.domainRemoteDb = 'localhost:5984';
  Accents.domainRemoteDb = 'diacritics.iriscouch.com';
  //Accents.domainRemoteDb = 'accents.couchappy.com'; // backup db

  Accents.db.changes({live: true, onChange: function(change){ /*console.log(change); */} });

  sync();

  Accents.Entities.Preload = new Accents.Entities.Terms();
  var user = {};
  if(typeof(Storage)!=="undefined"){
    var userSession = sessionStorage.getItem( "session-user" );
    if(userSession){
      user = $.parseJSON(userSession);
    }
  }
  Accents.user = new Accents.Entities.Login(user);
});

Accents.on("sync", function(){
  console.log("triggering list:term");
  Accents.trigger("list:term")
});

var sync = function(){
  console.log("sync called");
  var opts = {live: true, complete: onCompleteSync, batch_size: 3000};
  var urlConnection = "http://" + Accents.domainRemoteDb + "/" + Accents.remoteDb;
  PouchDB.replicate('accents', urlConnection, opts, function(err, data){ console.log("replicating local to remote");/*console.log(err); console.log(data); */});
  PouchDB.replicate(urlConnection, 'accents', opts, function(err, data){ console.log("replicating remote to local");/*console.log(err); console.log(data);*/ });
};

Accents.on("initialize:after", function(){
  console.log("initialize:after called");
  if(Backbone.history){
    Backbone.history.start();
    if( !Accents.user.isLoggedIn() ){
      Accents.trigger("login");
    }else if( Accents.getCurrentRoute() == "" ){
      Accents.trigger("list:term");
    }
  }
});
<commit_msg>changed the synchronization size back to 500 records, from 3k<commit_after>var Accents = new Backbone.Marionette.Application();

// pluggible regions
Accents.addRegions({
    navbar: 'header',
    main: '#maincontent',
    footer: 'footer'
});

Accents.navigate = function(route, options){
  console.log("Navigate ");
  console.log(route);
  console.log(options);
  var options = options || {};
  Backbone.history.navigate(route, options);
};

Accents.getCurrentRoute = function(){
  return Backbone.history.fragment;
};

// wire up application
var onCompleteSync = function(){
  // console.log("Trigger list:term due to onCompleteSync call");
  // Accents.trigger("list:term")
  // console.log("sync called every 10 seconds timer");
  // setTimeout(sync,10000);
};

Accents.addInitializer(function () {
  Accents.db = new PouchDB('accents');
  Accents.remoteDb = 'accents';
  //Accents.domainRemoteDb = 'localhost:5984';
  Accents.domainRemoteDb = 'diacritics.iriscouch.com';
  //Accents.domainRemoteDb = 'accents.couchappy.com'; // backup db

  Accents.db.changes({live: true, onChange: function(change){ /*console.log(change); */} });

  sync();

  Accents.Entities.Preload = new Accents.Entities.Terms();
  var user = {};
  if(typeof(Storage)!=="undefined"){
    var userSession = sessionStorage.getItem( "session-user" );
    if(userSession){
      user = $.parseJSON(userSession);
    }
  }
  Accents.user = new Accents.Entities.Login(user);
});

Accents.on("sync", function(){
  console.log("triggering list:term");
  Accents.trigger("list:term")
});

var sync = function(){
  console.log("sync called");
  var opts = {live: true, complete: onCompleteSync, batch_size: 500};
  var urlConnection = "http://" + Accents.domainRemoteDb + "/" + Accents.remoteDb;
  PouchDB.replicate('accents', urlConnection, opts, function(err, data){ console.log("replicating local to remote");/*console.log(err); console.log(data); */});
  PouchDB.replicate(urlConnection, 'accents', opts, function(err, data){ console.log("replicating remote to local");/*console.log(err); console.log(data);*/ });
};

Accents.on("initialize:after", function(){
  console.log("initialize:after called");
  if(Backbone.history){
    Backbone.history.start();
    if( !Accents.user.isLoggedIn() ){
      Accents.trigger("login");
    }else if( Accents.getCurrentRoute() == "" ){
      Accents.trigger("list:term");
    }
  }
});
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { BackAndroid } from 'react-native';

import RootScene from './RootScene';
import { actionCreators as navigationActions } from './actions';
import { propTypes as navigationPropTypes } from './reducer';

class TabContainer extends Component {

  componentDidMount() {
    if (this.props.isActiveTab) {
      this.addAndroidBackButtonListener();
    }
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.isActiveTab && !nextProps.isActiveTab) {
      this.removeAndroidBackButtonListener();
    } else if (!this.props.isActiveTab && nextProps.isActiveTab) {
      this.addAndroidBackButtonListener();
    }
  }

  componentWillUnmount() {
    this.removeAndroidBackButtonListener();
  }

  addAndroidBackButtonListener() {
    BackAndroid.addEventListener('hardwareBackPress', this.handleAndroidBackButton);
  }

  removeAndroidBackButtonListener() {
    BackAndroid.removeEventListener('hardwareBackPress', this.handleAndroidBackButton);
  }

  handleAndroidBackButton = () => {
    if (this.props.routeStack && this.props.routeStack.length) {
      this.props.dispatch(navigationActions.pop());
      return true;
    }
  }

  render() {
    return <RootScene {...this.props} />;
  }
}

TabContainer.propTypes = {
  isActiveTab: React.PropTypes.bool,
  ...RootScene.propTypes
};

const mapStateToProps = (store, props) => {
  if (!props.tabIndex && props.tabIndex !== 0) {
    throw new Error('prop "tabIndex" must be present in TabContainer');
  }
  const navState = store.navigation[props.tabIndex];
  return {
    activeRoute: navState && navState.activeRoute,
    navigationMethod: navState && navState.method,
    routeStack: navState && navState.routeStack,
    isActiveTab: store.navigation.activeTabIndex === props.tabIndex
  };
};

export default connect(mapStateToProps)(TabContainer);
<commit_msg>remove unused import<commit_after>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { BackAndroid } from 'react-native';

import RootScene from './RootScene';
import { actionCreators as navigationActions } from './actions';

class TabContainer extends Component {

  componentDidMount() {
    if (this.props.isActiveTab) {
      this.addAndroidBackButtonListener();
    }
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.isActiveTab && !nextProps.isActiveTab) {
      this.removeAndroidBackButtonListener();
    } else if (!this.props.isActiveTab && nextProps.isActiveTab) {
      this.addAndroidBackButtonListener();
    }
  }

  componentWillUnmount() {
    this.removeAndroidBackButtonListener();
  }

  addAndroidBackButtonListener() {
    BackAndroid.addEventListener('hardwareBackPress', this.handleAndroidBackButton);
  }

  removeAndroidBackButtonListener() {
    BackAndroid.removeEventListener('hardwareBackPress', this.handleAndroidBackButton);
  }

  handleAndroidBackButton = () => {
    if (this.props.routeStack && this.props.routeStack.length) {
      this.props.dispatch(navigationActions.pop());
      return true;
    }
  }

  render() {
    return <RootScene {...this.props} />;
  }
}

TabContainer.propTypes = {
  isActiveTab: React.PropTypes.bool,
  ...RootScene.propTypes
};

const mapStateToProps = (store, props) => {
  if (!props.tabIndex && props.tabIndex !== 0) {
    throw new Error('prop "tabIndex" must be present in TabContainer');
  }
  const navState = store.navigation[props.tabIndex];
  return {
    activeRoute: navState && navState.activeRoute,
    navigationMethod: navState && navState.method,
    routeStack: navState && navState.routeStack,
    isActiveTab: store.navigation.activeTabIndex === props.tabIndex
  };
};

export default connect(mapStateToProps)(TabContainer);
<|endoftext|>


<commit_before>import React from 'react';

const handlers = new Map();

function handleClick( node, event ) {
  this._keyDownHasFocus = event.target === node || node.contains( event.target );
}

function handleKeyDown( { which } ) {
  const handler = [ ...handlers ].find( ( [ componentInstance ] ) => componentInstance._keyDownHasFocus );
  if ( handler ) {
    const [ componentInstance, { bindings } ] = handler;
    bindings.forEach( ( fn, keys ) => ( !keys || ~keys.indexOf( which ) ) && fn.call( componentInstance, event ) );
  }
}

function bindListeners() {
  document.addEventListener( 'keydown', handleKeyDown );
}

function unbindListeners() {
  document.removeEventListener( 'keydown', handleKeyDown );
}

function onMount( { keys, fn } ) {
  const handlerDict = handlers.get( this );
  if ( !handlerDict ) {
    if ( !handlers.size ) bindListeners();
    const node = React.findDOMNode( this );
    const onClickBound = handleClick.bind( this, node );

    handlers.set( this, {
      bindings: new Map( [ [ keys, fn ] ] ),
      onClick: onClickBound
    });

    document.addEventListener( 'click', onClickBound );
    this._keyDownHasFocus = true;
  } else {
    handlerDict.bindings.set( keys, fn );
  }
}

function onUnmount() {
  const handler = handlers.get( this );
  if ( handler ) {
    document.removeEventListener( 'click', handler.onClick );
    handlers.delete( this );
  }
  if ( !handlers.size ) unbindListeners();
  this._keyDownHasFocus = false;
}

export { onMount, onUnmount };
<commit_msg>remove reliance on private component instance property to keep components as clean as possible<commit_after>import React from 'react';

const handlers = new Map();

function handleClick( node, { target } ) {
  handlers.get( this ).hasFocus = target === node || node.contains( target );
}

function handleKeyDown( { which } ) {
  const focusedComponent = [ ...handlers ].find( ( [, data ] ) => data.hasFocus );
  if ( focusedComponent ) {
    const [ componentInstance, { bindings } ] = focusedComponent;
    bindings.forEach( ( fn, keys ) => ( !keys || ~keys.indexOf( which ) ) && fn.call( componentInstance, event ) );
  }
}

function bindListeners() {
  document.addEventListener( 'keydown', handleKeyDown );
}

function unbindListeners() {
  document.removeEventListener( 'keydown', handleKeyDown );
}

function onMount( { keys, fn } ) {
  const handlerDict = handlers.get( this );
  if ( !handlerDict ) {
    if ( !handlers.size ) bindListeners();
    const node = React.findDOMNode( this );
    const onClickBound = handleClick.bind( this, node );

    handlers.set( this, {
      bindings: new Map( [ [ keys, fn ] ] ),
      onClick: onClickBound
    });

    document.addEventListener( 'click', onClickBound );
  } else {
    handlerDict.bindings.set( keys, fn );
  }
  handlers.get( this ).hasFocus = true;
}

function onUnmount() {
  const handler = handlers.get( this );
  if ( handler ) {
    document.removeEventListener( 'click', handler.onClick );
    handlers.delete( this );
  }
  if ( !handlers.size ) unbindListeners();
}

export { onMount, onUnmount };
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

define(function (require, exports) {
    "use strict";

    var unitsIn = require("src/lib/unit"),
        colorObject = require("src/lib/color").colorObject;

    /**
     * Create a text layer
     *
     * @param {ActionDescriptor} sourceRef Layer reference
     * @param {string} strTextKey The text string.
     * @param {array} numClickPointH The horizontal text click point.
     * @param {array} numClickPointV The vertical text click point.
     *
     * Preconditions:
     * Open or create a document
     *
     * Examples:
     * createText("Photoshop Playground",20,20);
     */
    var createText = function (sourceRef, strTextKey, numClickPointH, numClickPointV) {
        return {
            command: "make",
            descriptor: {
                "null": sourceRef,
                "using": {
                    "obj": "textLayer",
                    "value": {
                        "textKey": strTextKey,
                        "textClickPoint": {
                            "obj": "paint",
                            "value": {
                                "horizontal": unitsIn.percent(numClickPointH),
                                "vertical": unitsIn.percent(numClickPointV)
                            }
                        },
                        "textStyleRange": [
                        ]
                    }
                }
            }
        };
    };

    /**
     * Set the font face
     *
     * @param {ActionDescriptor} sourceRef Layer reference
     * @param {string} face The string of font family name
     * @param {string} weight The string of font style name
     *
     * @returns {PlayObject} The action descriptor of the text style.
     *
     * Preconditions:
     * Select a text layer
     *
     * Examples:
     * setFace("Helvetica","Light");
     */
    var setFace = function (sourceRef, face, weight) {
        return {
            command: "set",
            descriptor: {
                "null": sourceRef,
                "to": {
                    fontName: face,
                    fontStyleName: weight
                }
            }
        };
    };

    /**
     * Set the font size
     *
     * @param {ActionDescriptor} sourceRef Layer reference
     * @param {number} val The size of the font.
     *      Points: 0.01pt to 1296.00pt
     *      Pixels: 0.01px to 1296.00px
     *      Millimeters: 0.00mm to 457.19mm
     * @param {string} unit The unit of the type.  "pt","px", or "mm"
     *
     * @return {object} The action descriptor of the text style.
     *
     * Preconditions:
     * Select a text layer
     *
     * Examples:
     * setSize(14, "pt");
     */
    var setSize = function (sourceRef, val, unit) {
        return {
            command: "set",
            descriptor: {
                "null": sourceRef,
                "to": {
                    "obj": "textStyle",
                    "value": {
                        "size": unitsIn[unit](val),
                    }
                }
            }
        };
    };

    /**
     * Set the font alignment
     *
     * @param {ActionDescriptor} sourceRef Layer reference
     * @param {string} orient The alignment of the type.  "right", "center", "left", "justifyAll"
     *
     * @return {object} The action descriptor of the paragraph style.
     *
     * Preconditions:
     * Select a text layer
     *
     * Examples:
     * setAlignment("center");
     */
    var setAlignment = function (sourceRef, orient) {
        return {
            command: "set",
            desciptor: {
                "null": sourceRef,
                "to": {
                    "value": {
                        "align": {
                            "enum": "alignmentType",
                            "value": orient
                        }
                    }
                }
            }
        };
    };

    /**
     * Set the text leading
     *
     * @param {ActionDescriptor} sourceRef Layer reference
     * @param {boolean} auto Whether the auto leading is enabled.
     * @param {number} val The leading of the text.
     *      Points: 0.01pt to 5000.00pt
     *      Pixels: 0.01px to 5000.00px
     *      Millimeters: 0.00mm to 1763.88mm
     * @param {string} unit The unit of the type.  "pointsUnit","pixelsUnit", or "millimetersUnit"
     *
     * @return {object} The action descriptor of the text style.
     *
     * Preconditions:
     * Select a text layer
     *
     * Examples:
     * setLeading(true);
     * setLeading(false,14,"pt");
     * setLeading(false,14);
     */
    var setLeading = function (sourceRef, auto, val, unit) {
        if (auto === false) {
            return {
                command: "set",
                desciptor: {
                    "null": sourceRef,
                    "to": {
                        "obj": "textStyle",
                        "value": {
                            "autoLeading": auto,
                            "leading": unitsIn[unit](val)
                        }
                    }
                }
            };
        } else {
            return {
                command: "set",
                desciptor: {
                    "null": sourceRef,
                    "to": {
                        "obj": "textStyle",
                        "value": {
                            "autoLeading": auto
                        }
                    }
                }
            };
        }
    };

    /**
     * Set the text tracking
     *
     * @param {ActionDescriptor} sourceRef Layer reference
     * @param {number} val The amount of space between a range of letters or characters. -1000 to 10000
     *
     * @return {object} The action descriptor of the text style.
     *
     * Preconditions:
     * Select a text layer
     *
     * Examples:
     * setLeading(10);
     */
    var setTracking = function (sourceRef, val) {
        return {
            command: "set",
            desciptor: {
                "null": sourceRef,
                "to": {
                    "obj": "textStyle",
                    "value": {
                        "tracking": val
                    }
                }
            }
        };
    };

    /**
     * Set the text color
     *
     * @param {ActionDescriptor} sourceRef Layer reference
     * @param {array} arrayTextColor The array of RGB color [red,green,blue]. 0 to 255
     *
     * @return {object} The action descriptor of the text style.
     *
     * Preconditions:
     * Select a text layer
     *
     * Examples:
     * setColor([100,200,100]);
     */
    var setColor = function (sourceRef, arrayTextColor) {
        return {
            command: "set",
            desciptor: {
                "null": sourceRef,
                "to": {
                    "obj": "textStyle",
                    "value": {
                        "color": colorObject(arrayTextColor)
                    }
                }
            }
        };
    };

    /**
     * Set the text orientation
     *
     * @param {ActionDescriptor} sourceRef Layer reference
     * @param {string} strTextOrientation The text orientation. "horizontal" or "vertical"
     *
     * Preconditions:
     * Select a text layer
     *
     * Examples:
     * setOrientation("vertical");
     */
    var setOrientation = function (sourceRef, strTextOrientation) {
        return {
            command: "set",
            descriptor: {
                "null": sourceRef,
                "to": {
                    "enum": "orientation",
                    "value": strTextOrientation
                }
            }
        };
    };

    /**
     * Set the text anti alias
     *
     * @param {ActionDescriptor} sourceRef Layer reference
     * @param {string} strAntiAliasType The anti alias type. "none","sharp","crisp","strong","smooth","macLcd", or "mac"
     *
     * Preconditions:
     * Select a text layer
     *
     * Examples:
     * setAntiAlias("smooth");
     */
    var setAntiAlias = function (sourceRef, strAntiAliasType) {
        return {
            command: "set",
            desciptor: {
                "null": sourceRef,
                "to": {
                    "enum": "antiAliasType",
                    "value": _antiAlias[strAntiAliasType]
                }
            }
        };
    };

    var _antiAlias = {
        none: "antiAliasNone",
        sharp: "antiAliasSharp",
        crisp: "antiAliasCrisp",
        strong: "antiAliasStrong",
        smooth: "antiAliasSmooth",
        macLcd: "antiAliasPlatformLCD",
        mac: "antiAliasPlatformGray"
    };

    /**
     * Set range and change text style
     *
     * @param {ActionDescriptor} sourceRef Layer reference
     * @param {number} from The index of string to set the range from
     * @param {number} to The index of string to set the range to
     * @param {string} face The string of font family name
     * @param {string} weight The string of font style name
     * @param {string} unit The unit of the type.  "pt","px", or "mm"
     * @param {number} size The size of the font.
     *      Points: 0.01pt to 1296.00pt
     *      Pixels: 0.01px to 1296.00px
     *      Millimeters: 0.00mm to 457.19mm
     * @param {array} arrayTextColor The array of RGB color [red,green,blue]. 0 to 255
     *
     * Preconditions:
     * Select a text layer
     *
     * Examples:
     * setRangeAndChangeTextStyle(0,1,"Helvetica","Bold","pt",60,[200,100,150]);
     * setRangeAndChangeTextStyle(0,3,"","","pt",20,[200,100,150]);
     */
    var setRangeAndChangeTextStyle = function (sourceRef, from, to, face, weight, unit, size, arrayTextColor) {
        return {
            command: "set",
            desciptor: {
                "null": sourceRef,
                "to": {
                    "obj": "textLayer",
                    "value": {
                        "textStyleRange": [
                            {
                                "obj": "textStyleRange",
                                "value": {
                                    "from": from,
                                    "to": to,
                                    "textStyle": {
                                        "obj": "textStyle",
                                        "value": {
                                            "fontName" : face,
                                            "fontStyleName" : weight,
                                            "size": unitsIn[unit](size),
                                            "color": colorObject(arrayTextColor)
                                        }
                                    }
                                }
                            }
                        ]
                    }
                }
            }
        };
    };

    exports.createText = createText;
    exports.setFace = setFace;
    exports.setSize = setSize;
    exports.setAlignment = setAlignment;
    exports.setLeading = setLeading;
    exports.setTracking = setTracking;
    exports.setColor = setColor;
    exports.createText = createText;
    exports.setOrientation = setOrientation;
    exports.setAntiAlias = setAntiAlias;

    exports.setRangeAndChangeTextStyle = setRangeAndChangeTextStyle;

});
<commit_msg>Updated JS doc<commit_after>/*
 * Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

define(function (require, exports) {
    "use strict";

    var unitsIn = require("src/lib/unit"),
        colorObject = require("src/lib/color").colorObject;

    /**
     * Create a text layer
     *
     * @param {ActionDescriptor} sourceRef Layer reference
     * @param {string} strTextKey The text string.
     * @param {array} numClickPointH The horizontal text click point.
     * @param {array} numClickPointV The vertical text click point.
     *
     * @return {PlayObject} The action descriptor of the text style.
     *
     * Preconditions:
     * Open or create a document
     *
     * Examples:
     * createText("Photoshop Playground",20,20);
     */
    var createText = function (sourceRef, strTextKey, numClickPointH, numClickPointV) {
        return {
            command: "make",
            descriptor: {
                "null": sourceRef,
                "using": {
                    "obj": "textLayer",
                    "value": {
                        "textKey": strTextKey,
                        "textClickPoint": {
                            "obj": "paint",
                            "value": {
                                "horizontal": unitsIn.percent(numClickPointH),
                                "vertical": unitsIn.percent(numClickPointV)
                            }
                        },
                        "textStyleRange": [
                        ]
                    }
                }
            }
        };
    };

    /**
     * Set the font face
     *
     * @param {ActionDescriptor} sourceRef Layer reference
     * @param {string} face The string of font family name
     * @param {string} weight The string of font style name
     *
     * @returns {PlayObject} The action descriptor of the text style.
     *
     * Preconditions:
     * Select a text layer
     *
     * Examples:
     * setFace("Helvetica","Light");
     */
    var setFace = function (sourceRef, face, weight) {
        return {
            command: "set",
            descriptor: {
                "null": sourceRef,
                "to": {
                    fontName: face,
                    fontStyleName: weight
                }
            }
        };
    };

    /**
     * Set the font size
     *
     * @param {ActionDescriptor} sourceRef Layer reference
     * @param {number} val The size of the font.
     *      Points: 0.01pt to 1296.00pt
     *      Pixels: 0.01px to 1296.00px
     *      Millimeters: 0.00mm to 457.19mm
     * @param {string} unit The unit of the type.  "pt","px", or "mm"
     *
     * @return {PlayObject} The action descriptor of the text style.
     *
     * Preconditions:
     * Select a text layer
     *
     * Examples:
     * setSize(14, "pt");
     */
    var setSize = function (sourceRef, val, unit) {
        return {
            command: "set",
            descriptor: {
                "null": sourceRef,
                "to": {
                    "obj": "textStyle",
                    "value": {
                        "size": unitsIn[unit](val),
                    }
                }
            }
        };
    };

    /**
     * Set the font alignment
     *
     * @param {ActionDescriptor} sourceRef Layer reference
     * @param {string} orient The alignment of the type.  "right", "center", "left", "justifyAll"
     *
     * @return {PlayObject} The action descriptor of the paragraph style.
     *
     * Preconditions:
     * Select a text layer
     *
     * Examples:
     * setAlignment("center");
     */
    var setAlignment = function (sourceRef, orient) {
        return {
            command: "set",
            desciptor: {
                "null": sourceRef,
                "to": {
                    "value": {
                        "align": {
                            "enum": "alignmentType",
                            "value": orient
                        }
                    }
                }
            }
        };
    };

    /**
     * Set the text leading
     *
     * @param {ActionDescriptor} sourceRef Layer reference
     * @param {boolean} auto Whether the auto leading is enabled.
     * @param {number} val The leading of the text.
     *      Points: 0.01pt to 5000.00pt
     *      Pixels: 0.01px to 5000.00px
     *      Millimeters: 0.00mm to 1763.88mm
     * @param {string} unit The unit of the type.  "pointsUnit","pixelsUnit", or "millimetersUnit"
     *
     * @return {PlayObject} The action descriptor of the text style.
     *
     * Preconditions:
     * Select a text layer
     *
     * Examples:
     * setLeading(true);
     * setLeading(false,14,"pt");
     * setLeading(false,14);
     */
    var setLeading = function (sourceRef, auto, val, unit) {
        if (auto === false) {
            return {
                command: "set",
                desciptor: {
                    "null": sourceRef,
                    "to": {
                        "obj": "textStyle",
                        "value": {
                            "autoLeading": auto,
                            "leading": unitsIn[unit](val)
                        }
                    }
                }
            };
        } else {
            return {
                command: "set",
                desciptor: {
                    "null": sourceRef,
                    "to": {
                        "obj": "textStyle",
                        "value": {
                            "autoLeading": auto
                        }
                    }
                }
            };
        }
    };

    /**
     * Set the text tracking
     *
     * @param {ActionDescriptor} sourceRef Layer reference
     * @param {number} val The amount of space between a range of letters or characters. -1000 to 10000
     *
     * @return {PlayObject} The action descriptor of the text style.
     *
     * Preconditions:
     * Select a text layer
     *
     * Examples:
     * setLeading(10);
     */
    var setTracking = function (sourceRef, val) {
        return {
            command: "set",
            desciptor: {
                "null": sourceRef,
                "to": {
                    "obj": "textStyle",
                    "value": {
                        "tracking": val
                    }
                }
            }
        };
    };

    /**
     * Set the text color
     *
     * @param {ActionDescriptor} sourceRef Layer reference
     * @param {array} arrayTextColor The array of RGB color [red,green,blue]. 0 to 255
     *
     * @return {PlayObject} The action descriptor of the text style.
     *
     * Preconditions:
     * Select a text layer
     *
     * Examples:
     * setColor([100,200,100]);
     */
    var setColor = function (sourceRef, arrayTextColor) {
        return {
            command: "set",
            desciptor: {
                "null": sourceRef,
                "to": {
                    "obj": "textStyle",
                    "value": {
                        "color": colorObject(arrayTextColor)
                    }
                }
            }
        };
    };

    /**
     * Set the text orientation
     *
     * @param {ActionDescriptor} sourceRef Layer reference
     * @param {string} strTextOrientation The text orientation. "horizontal" or "vertical"
     *
     * @return {PlayObject} The action descriptor of the text style.
     *
     * Preconditions:
     * Select a text layer
     *
     * Examples:
     * setOrientation("vertical");
     */
    var setOrientation = function (sourceRef, strTextOrientation) {
        return {
            command: "set",
            descriptor: {
                "null": sourceRef,
                "to": {
                    "enum": "orientation",
                    "value": strTextOrientation
                }
            }
        };
    };

    /**
     * Set the text anti alias
     *
     * @param {ActionDescriptor} sourceRef Layer reference
     * @param {string} strAntiAliasType The anti alias type. "none","sharp","crisp","strong","smooth","macLcd", or "mac"
     *
     * @return {PlayObject} The action descriptor of the text style.
     *
     * Preconditions:
     * Select a text layer
     *
     * Examples:
     * setAntiAlias("smooth");
     */
    var setAntiAlias = function (sourceRef, strAntiAliasType) {
        return {
            command: "set",
            desciptor: {
                "null": sourceRef,
                "to": {
                    "enum": "antiAliasType",
                    "value": _antiAlias[strAntiAliasType]
                }
            }
        };
    };

    var _antiAlias = {
        none: "antiAliasNone",
        sharp: "antiAliasSharp",
        crisp: "antiAliasCrisp",
        strong: "antiAliasStrong",
        smooth: "antiAliasSmooth",
        macLcd: "antiAliasPlatformLCD",
        mac: "antiAliasPlatformGray"
    };

    /**
     * Set range and change text style
     *
     * @param {ActionDescriptor} sourceRef Layer reference
     * @param {number} from The index of string to set the range from
     * @param {number} to The index of string to set the range to
     * @param {string} face The string of font family name
     * @param {string} weight The string of font style name
     * @param {string} unit The unit of the type.  "pt","px", or "mm"
     * @param {number} size The size of the font.
     *      Points: 0.01pt to 1296.00pt
     *      Pixels: 0.01px to 1296.00px
     *      Millimeters: 0.00mm to 457.19mm
     * @param {array} arrayTextColor The array of RGB color [red,green,blue]. 0 to 255
     *
     * @return {PlayObject} The action descriptor of the text style.
     *
     * Preconditions:
     * Select a text layer
     *
     * Examples:
     * setRangeAndChangeTextStyle(0,1,"Helvetica","Bold","pt",60,[200,100,150]);
     * setRangeAndChangeTextStyle(0,3,"","","pt",20,[200,100,150]);
     */
    var setRangeAndChangeTextStyle = function (sourceRef, from, to, face, weight, unit, size, arrayTextColor) {
        return {
            command: "set",
            desciptor: {
                "null": sourceRef,
                "to": {
                    "obj": "textLayer",
                    "value": {
                        "textStyleRange": [
                            {
                                "obj": "textStyleRange",
                                "value": {
                                    "from": from,
                                    "to": to,
                                    "textStyle": {
                                        "obj": "textStyle",
                                        "value": {
                                            "fontName" : face,
                                            "fontStyleName" : weight,
                                            "size": unitsIn[unit](size),
                                            "color": colorObject(arrayTextColor)
                                        }
                                    }
                                }
                            }
                        ]
                    }
                }
            }
        };
    };

    exports.createText = createText;
    exports.setFace = setFace;
    exports.setSize = setSize;
    exports.setAlignment = setAlignment;
    exports.setLeading = setLeading;
    exports.setTracking = setTracking;
    exports.setColor = setColor;
    exports.createText = createText;
    exports.setOrientation = setOrientation;
    exports.setAntiAlias = setAntiAlias;

    exports.setRangeAndChangeTextStyle = setRangeAndChangeTextStyle;

});
<|endoftext|>