<commit_before>/*!
 * jBone.widget v0.0.1 - 2014-03-16 - Widget factory for jBone
 *
 * https://github.com/kupriyanenko/jbone.widget
 *
 * Copyright 2014 Alexey Kupriyanenko
 * Released under the MIT license.
 */

(function($) {
    var _id = 0,
        widgets = {};

    $.Widget = function(name, el, base) {
        this.id = _id++;
        this.name = name;
        this.el = el;
        this.$el = $(el);
        this._elements = [];

        // add reference to the parent class
        if (base) {
            this.super = base;
        }
    };

    $.Widget.prototype = {
        init: function() {
            this.render();
        },

        render: function() {
            return this;
        },

        on: function($el, options) {
            var callback, eventType;

            for (eventType in options) {
                this._elements.push($el);
                $el.on(eventType + ".widget" + this.id, options[eventType]);
            }
        },

        off: function($el, eventType, fn) {
            $el.off(eventType || "" + ".widget" + this.id, fn);
        },

        destroy: function() {
            for (var i in this._elements) {
                this._elements[i].off(".widget" + this.id);
            }

            this._elements = [];
            delete this.el.widget;
        }
    };

    $.widget = function(name, base, protoProps) {
        if (protoProps) {
            base = widgets[base];
        } else {
            protoProps = base;
            base = undefined;
        }

        widgets[name] = $.extend({}, base, protoProps);

        return $.fn[name] = function(options) {
            var i = 0,
                length = this.length,
                args = arguments,
                method, createWidget, runMethod;

            createWidget = function(el) {
                var widget;

                if (el.widgets && el.widgets[name]) {
                    return;
                }

                widget = new $.Widget(name, el, base);
                $.extend(widget, widgets[name]);
                widget.options = typeof widget.options === "function" ? widget.options() : widget.options;
                $.extend(widget.options, options);
                widget.init(widget.options);

                el.widgets = el.widgets || {};
                el.widgets[name] = widget;
            };

            runMethod = function(el) {
                if (!el.widgets || !el.widgets[name]) {
                    throw new Error("cannot call methods on " + name + " prior to initialization; attempted to call method " + options);
                }

                try {
                    el.widgets[name][options].apply(el.widgets[name], [].slice.call(args, 1));
                } catch (error) {
                    throw new Error("no such method " + options + " for " + name + " widget instance");
                }
            };

            // run widget method
            if (args.length > 0 && typeof options === "string") {
                method = runMethod;
            }
            // create new widget
            else {
                method = createWidget;
            }

            for (; i < length; i++) {
                method(this[i]);
            }

            return this;
        };
    };
}(window.jBone));
<commit_msg>update naming<commit_after>/*!
 * jBone.widget v0.0.1 - 2014-03-16 - Widget factory for jBone
 *
 * https://github.com/kupriyanenko/jbone.widget
 *
 * Copyright 2014 Alexey Kupriyanenko
 * Released under the MIT license.
 */

(function($) {
    var _id = 0,
        _widgets = {};

    $.Widget = function(name, el, base) {
        this.id = _id++;
        this.el = el;
        this.$el = $(el);
        this._elements = [];

        // add reference to the parent class
        if (base) {
            this.super = base;
        }
    };

    $.Widget.prototype = {
        init: function() {
            this.render();
        },

        render: function() {
            return this;
        },

        on: function($el, options) {
            var callback, eventType;

            for (eventType in options) {
                this._elements.push($el);
                $el.on(eventType + ".widget" + this.id, options[eventType]);
            }
        },

        off: function($el, eventType, fn) {
            $el.off(eventType || "" + ".widget" + this.id, fn);
        },

        destroy: function() {
            for (var i in this._elements) {
                this._elements[i].off(".widget" + this.id);
            }

            this._elements = [];
            delete this.el.widget;
        }
    };

    $.widget = function(name, base, protoProps) {
        if (protoProps) {
            base = _widgets[base];
        } else {
            protoProps = base;
            base = undefined;
        }

        _widgets[name] = $.extend({}, base, protoProps);

        return $.fn[name] = function(options) {
            var i = 0,
                length = this.length,
                args = arguments,
                action, createWidget, callMethod;

            createWidget = function(el) {
                var widget;

                if (el.widgets && el.widgets[name]) {
                    return;
                }

                widget = new $.Widget(name, el, base);
                $.extend(widget, _widgets[name]);
                widget.options = typeof widget.options === "function" ? widget.options() : widget.options;
                $.extend(widget.options, options);
                widget.init(widget.options);

                el.widgets = el.widgets || {};
                el.widgets[name] = widget;
            };

            callMethod = function(el) {
                if (!el.widgets || !el.widgets[name]) {
                    throw new Error("cannot call methods on " + name + " prior to initialization; attempted to call method " + options);
                }

                try {
                    el.widgets[name][options].apply(el.widgets[name], [].slice.call(args, 1));
                } catch (error) {
                    throw new Error("no such method " + options + " for " + name + " widget instance");
                }
            };

            if (typeof options === "string") {
                action = callMethod;
            } else {
                action = createWidget;
            }

            for (; i < length; i++) {
                action(this[i]);
            }

            return this;
        };
    };
}(window.jBone));
<|endoftext|>


<commit_before>const test = require('tape')
const Promise = require('bluebird')
const is = require('../src/is')
const tError = require('./test-error')
const enums = require('../src/enums')
const Queue = require('../src/queue')
const tOpts = require('./test-options')

module.exports = function () {
  return new Promise((resolve, reject) => {
    test('queue-change', (t) => {
      t.plan(77)

      const q = new Queue(tOpts.cxn(), tOpts.default())

      // ---------- Event Handler Setup ----------
      let testEvents = false
      let readyEventCount = 0
      let readyEventTotal = 0
      function readyEventHandler (queueId) {
        readyEventCount++
        if (testEvents) {
          t.ok(is.string(queueId), `Event: ready [${readyEventCount} of ${readyEventTotal}] [${queueId}]`)
        }
      }
      let addedEventCount = 0
      let addedEventTotal = 3
      function addedEventHandler (jobId) {
        addedEventCount++
        if (testEvents) {
          t.ok(is.uuid(jobId), `Event: added [${addedEventCount} of ${addedEventTotal}] [${jobId}]`)
        }
      }
      let activeEventCount = 0
      let activeEventTotal = 3
      function activeEventHandler (jobId) {
        activeEventCount++
        if (testEvents) {
          t.ok(is.uuid(jobId), `Event: active [${activeEventCount} of ${activeEventTotal}] [${jobId}]`)
        }
      }
      let processingEventCount = 0
      let processingEventTotal = 3
      function processingEventHandler (jobId) {
        processingEventCount++
        if (testEvents) {
          t.ok(is.uuid(jobId), `Event: processing [${processingEventCount} of ${processingEventTotal}] [${jobId}]`)
        }
      }
      let progressEventCount = 0
      let progressEventTotal = 3
      function progressEventHandler (jobId, percent) {
        progressEventCount++
        if (testEvents) {
          t.pass(`Event: progress  [${progressEventCount} of ${progressEventTotal}]`)
          t.ok(is.uuid(jobId), `Event: progress [${jobId}]`)
          t.ok(is.number(percent), `Event: progress [${percent}%]`)
        }
      }
      let completedEventCount = 0
      let completedEventTotal = 1
      function completedEventHandler (jobId) {
        completedEventCount++
        if (testEvents) {
          t.ok(is.uuid(jobId), `Event: completed [${completedEventCount} of ${completedEventTotal}] [${jobId}]`)
        }
      }
      let cancelledEventCount = 0
      let cancelledEventTotal = 1
      function cancelledEventHandler (jobId) {
        cancelledEventCount++
        if (testEvents) {
          t.ok(is.uuid(jobId), `Event: cancelled [${cancelledEventCount} of ${cancelledEventTotal}] [${jobId}]`)
        }
      }
      let failedEventCount = 0
      let failedEventTotal = 1
      function failedEventHandler (jobId) {
        failedEventCount++
        if (testEvents) {
          t.ok(is.uuid(jobId), `Event: failed [${failedEventCount} of ${failedEventTotal}] [${jobId}]`)
        }
      }
      let terminatedEventCount = 0
      let terminatedEventTotal = 1
      function terminatedEventHandler (jobId) {
        terminatedEventCount++
        if (testEvents) {
          t.ok(is.uuid(jobId), `Event: terminated [${terminatedEventCount} of ${terminatedEventTotal}] [${jobId}]`)
        }
      }
      let logEventCount = 0
      let logEventTotal = 1
      function logEventHandler (jobId) {
        logEventCount++
        if (testEvents) {
          t.ok(is.uuid(jobId), `Event: log [${logEventCount} of ${logEventTotal}] [${jobId}]`)
        }
      }
      let updatedEventCount = 0
      let updatedEventTotal = 0
      function updatedEventHandler (jobId) {
        updatedEventCount++
        if (testEvents) {
          t.ok(is.uuid(jobId), `Event: updated [${updatedEventCount} of ${updatedEventTotal}] [${jobId}]`)
        }
      }
      let pausingEventCount = 0
      let pausingEventTotal = 2
      function pausingEventHandler (global, queueId) {
        pausingEventCount++
        if (testEvents) {
          t.ok(is.string(queueId), `Event: pausing [${pausingEventCount} of ${pausingEventTotal}]`)
          t.ok(is.boolean(global), `Event: pausing [global: ${global}]`)
          t.ok(is.string(queueId), `Event: pausing [queueId: ${queueId}]`)
        }
      }
      let pausedEventCount = 0
      let pausedEventTotal = 2
      function pausedEventHandler (global, queueId) {
        pausedEventCount++
        if (testEvents) {
          t.ok(is.string(queueId), `Event: paused [${pausedEventCount} of ${pausedEventTotal}]`)
          t.ok(is.boolean(global), `Event: paused [global: ${global}]`)
          t.ok(is.string(queueId), `Event: paused [queueId: ${queueId}]`)
        }
      }
      let resumedEventCount = 0
      let resumedEventTotal = 2
      function resumedEventHandler (global, queueId) {
        resumedEventCount++
        if (testEvents) {
          t.ok(is.string(queueId), `Event: resumed [${resumedEventCount} of ${resumedEventTotal}]`)
          t.ok(is.boolean(global), `Event: resumed [global: ${global}]`)
          t.ok(is.string(queueId), `Event: resumed [queueId: ${queueId}]`)
        }
      }
      let removedEventCount = 0
      let removedEventTotal = 1
      function removedEventHandler (jobId) {
        removedEventCount++
        if (testEvents) {
          t.ok(is.uuid(jobId), `Event: removed [${removedEventCount} of ${removedEventTotal}] [${jobId}]`)
        }
      }
      let idleEventCount = 0
      let idleEventTotal = 1
      function idleEventHandler (queueId) {
        if (idleEventCount < 1) {
          idleEventCount++
          if (testEvents) {
            t.ok(is.string(queueId), `Event: idle [${idleEventCount} of ${idleEventTotal}] [${queueId}]`)
          }
        }
      }
      let reviewedEventCount = 0
      let reviewedEventTotal = 0
      function reviewedEventHandler (queueId) {
        reviewedEventCount++
        if (testEvents) {
          t.ok(is.string(queueId), `Event: reviewed [${reviewedEventCount} of ${reviewedEventTotal}] [${queueId}]`)
        }
      }
      let resetEventCount = 0
      let resetEventTotal = 1
      function resetEventHandler (total) {
        resetEventCount++
        if (testEvents) {
          t.ok(is.integer(total), `Event: reset [${resetEventCount} of ${resetEventTotal}] [${total}]`)
        }
      }
      let errorEventCount = 0
      let errorEventTotal = 0
      function errorEventHandler (err) {
        errorEventCount++
        if (testEvents) {
          t.ok(is.string(err.message), `Event: error [${errorEventCount} of ${errorEventTotal}] [${err.message}]`)
        }
      }
      let detachedEventCount = 0
      let detachedEventTotal = 0
      function detachedEventHandler (queueId) {
        detachedEventCount++
        if (testEvents) {
          t.ok(is.string(queueId), `Event: detached [${detachedEventCount} of ${detachedEventTotal}] [${queueId}]`)
        }
      }
      let stoppingEventCount = 0
      let stoppingEventTotal = 0
      function stoppingEventHandler (queueId) {
        stoppingEventCount++
        if (testEvents) {
          t.ok(is.string(queueId), `Event: stopping [${stoppingEventCount} of ${stoppingEventTotal}] [${queueId}]`)
        }
      }
      let stoppedEventCount = 0
      let stoppedEventTotal = 0
      function stoppedEventHandler (queueId) {
        stoppedEventCount++
        if (testEvents) {
          t.ok(is.string(queueId), `Event: stopped [${stoppedEventCount} of ${stoppedEventTotal}] [${queueId}]`)
        }
      }
      let droppedEventCount = 0
      let droppedEventTotal = 0
      function droppedEventHandler (queueId) {
        droppedEventCount++
        if (testEvents) {
          t.ok(is.string(queueId), `Event: dropped [${droppedEventCount} of ${droppedEventTotal}] [${queueId}]`)
        }
      }

      function addEventHandlers () {
        testEvents = true
        q.on(enums.status.ready, readyEventHandler)
        q.on(enums.status.added, addedEventHandler)
        q.on(enums.status.active, activeEventHandler)
        q.on(enums.status.processing, processingEventHandler)
        q.on(enums.status.progress, progressEventHandler)
        q.on(enums.status.completed, completedEventHandler)
        q.on(enums.status.cancelled, cancelledEventHandler)
        q.on(enums.status.failed, failedEventHandler)
        q.on(enums.status.terminated, terminatedEventHandler)
        q.on(enums.status.paused, pausedEventHandler)
        q.on(enums.status.pausing, pausingEventHandler)
        q.on(enums.status.resumed, resumedEventHandler)
        q.on(enums.status.removed, removedEventHandler)
        q.on(enums.status.log, logEventHandler)
        q.on(enums.status.updated, updatedEventHandler)
        q.on(enums.status.idle, idleEventHandler)
        q.on(enums.status.reviewed, reviewedEventHandler)
        q.on(enums.status.reset, resetEventHandler)
        q.on(enums.status.error, errorEventHandler)
        q.on(enums.status.detached, detachedEventHandler)
        q.on(enums.status.stopping, stoppingEventHandler)
        q.on(enums.status.stopped, stoppedEventHandler)
        q.on(enums.status.dropped, droppedEventHandler)
      }
      function removeEventHandlers () {
        testEvents = false
        q.removeListener(enums.status.ready, readyEventHandler)
        q.removeListener(enums.status.added, addedEventHandler)
        q.removeListener(enums.status.active, activeEventHandler)
        q.removeListener(enums.status.processing, processingEventHandler)
        q.removeListener(enums.status.progress, progressEventHandler)
        q.removeListener(enums.status.completed, completedEventHandler)
        q.removeListener(enums.status.cancelled, cancelledEventHandler)
        q.removeListener(enums.status.failed, failedEventHandler)
        q.removeListener(enums.status.terminated, terminatedEventHandler)
        q.removeListener(enums.status.paused, pausedEventHandler)
        q.removeListener(enums.status.pausing, pausingEventHandler)
        q.removeListener(enums.status.resumed, resumedEventHandler)
        q.removeListener(enums.status.removed, removedEventHandler)
        q.removeListener(enums.status.log, logEventHandler)
        q.removeListener(enums.status.updated, updatedEventHandler)
        q.removeListener(enums.status.idle, idleEventHandler)
        q.removeListener(enums.status.reviewed, reviewedEventHandler)
        q.removeListener(enums.status.reset, resetEventHandler)
        q.removeListener(enums.status.error, errorEventHandler)
        q.removeListener(enums.status.detached, detachedEventHandler)
        q.removeListener(enums.status.stopping, stoppingEventHandler)
        q.removeListener(enums.status.stopped, stoppedEventHandler)
        q.removeListener(enums.status.dropped, droppedEventHandler)
        return q.resume()
      }

      let job = q.createJob()
      let processDelay = 500

      return q.reset().then((resetResult) => {
        t.ok(is.integer(resetResult), 'Queue reset')
        return q.pause()
      }).then(() => {
        q.process((j, next) => {
          setTimeout(function jobProcessing () {
            t.equal(j.id, job.id, `Job Processed [${j.id}]`)
            next('queue-change')
          }, processDelay)
          return j.setProgress(50)
        })

        // ---------- Test added, active, progress completed, removed  ----------
        t.comment('queue-change: added, active, progress, completed, and removed change events')
        addEventHandlers()
      }).then(() => {
        return q.addJob(job)
      }).then((savedJob) => {
        t.equal(savedJob[0].id, job.id, 'Job saved successfully')
        return q.resume()
      }).then(() => {
        t.ok(!q.paused, 'Queue not paused')
      }).delay(processDelay).then(() => {
        return q.pause()
      }).delay(processDelay).then(() => {
        // t.ok(q.paused, 'Queue paused')
        return q.removeJob(job.id)
      }).delay(processDelay).then(() => {
        job = q.createJob()
        job.timeout = processDelay / 2000
        job.retryDelay = 0
        job.retryMax = 1

        // ---------- Test failed and terminated ----------
        t.comment('queue-change: failed and terminated change events')
        return q.addJob(job)
      }).then((savedJob) => {
        t.equal(savedJob[0].id, job.id, 'Job saved successfully')
        return q.resume()
      }).then(() => {
        t.ok(!q.paused, 'Queue not paused')
      }).delay(processDelay * 2).then(() => {
        return q.pause()
      }).delay(processDelay).then(() => {
        job = q.createJob()

        // ---------- Test log and cancelled ----------
        t.comment('queue-change: log and cancelled change events')
        return q.addJob(job)
      }).then((savedJob) => {
        t.equal(savedJob[0].id, job.id, 'Job saved successfully')
        return savedJob[0].addLog(savedJob[0].createLog('test log'))
      }).then(() => {
        return q.cancelJob(job.id, 'testing')
      }).delay(processDelay).then(() => {
        return q.reset()
      }).then((resetResult) => {
        t.ok(resetResult >= 0, 'Queue reset')
        removeEventHandlers()

        // ---------- Event summary Test ----------
        t.comment('queue: Event Summary')
        t.equal(readyEventCount, readyEventTotal, 'Ready event count valid')
        t.equal(addedEventCount, addedEventTotal, 'Added event count valid')
        t.equal(activeEventCount, activeEventTotal, 'Active event count valid')
        t.equal(processingEventCount, processingEventTotal, 'Processing event count valid')
        t.equal(progressEventCount, progressEventTotal, 'Progress event count valid')
        t.equal(completedEventCount, completedEventTotal, 'Completed event count valid')
        t.equal(cancelledEventCount, cancelledEventTotal, 'Cancelled event count valid')
        t.equal(failedEventCount, failedEventTotal, 'Failed event count valid')
        t.equal(terminatedEventCount, terminatedEventTotal, 'Terminated event count valid')
        t.equal(pausingEventCount, pausingEventTotal, 'Pausing event count valid')
        t.equal(pausedEventCount, pausedEventTotal, 'Paused event count valid')
        t.equal(resumedEventCount, resumedEventTotal, 'Resumed event count valid')
        t.equal(removedEventCount, removedEventTotal, 'Removed event count valid')
        t.equal(logEventCount, logEventTotal, 'Log event count valid')
        t.equal(updatedEventCount, updatedEventTotal, 'Updated event count valid')
        t.equal(idleEventCount, idleEventTotal, 'Idle event count valid')
        t.equal(reviewedEventCount, reviewedEventTotal, 'Reviewed event count valid')
        t.equal(resetEventCount, resetEventTotal, 'Reset event count valid')
        t.equal(errorEventCount, errorEventTotal, 'Error event count valid')
        t.equal(detachedEventCount, detachedEventTotal, 'Detached event count valid')
        t.equal(stoppingEventCount, stoppingEventTotal, 'Stopping event count valid')
        t.equal(stoppedEventCount, stoppedEventTotal, 'Stopped event count valid')
        t.equal(droppedEventCount, droppedEventTotal, 'Dropped event count valid')

        q.stop()
        return resolve(t.end())
      }).catch(err => tError(err, module, t))
    })
  })
}
<commit_msg>Fixed queue-change tests<commit_after>const test = require('tape')
const Promise = require('bluebird')
const is = require('../src/is')
const tError = require('./test-error')
const enums = require('../src/enums')
const Queue = require('../src/queue')
const tOpts = require('./test-options')

module.exports = function () {
  return new Promise((resolve, reject) => {
    test('queue-change', (t) => {
      t.plan(78)

      const q = new Queue(tOpts.cxn(), tOpts.default())

      // ---------- Event Handler Setup ----------
      let testEvents = false
      let readyEventCount = 0
      let readyEventTotal = 0
      function readyEventHandler (queueId) {
        readyEventCount++
        if (testEvents) {
          t.ok(is.string(queueId), `Event: ready [${readyEventCount} of ${readyEventTotal}] [${queueId}]`)
        }
      }
      let addedEventCount = 0
      let addedEventTotal = 3
      function addedEventHandler (jobId) {
        addedEventCount++
        if (testEvents) {
          t.ok(is.uuid(jobId), `Event: added [${addedEventCount} of ${addedEventTotal}] [${jobId}]`)
        }
      }
      let activeEventCount = 0
      let activeEventTotal = 3
      function activeEventHandler (jobId) {
        activeEventCount++
        if (testEvents) {
          t.ok(is.uuid(jobId), `Event: active [${activeEventCount} of ${activeEventTotal}] [${jobId}]`)
        }
      }
      let processingEventCount = 0
      let processingEventTotal = 3
      function processingEventHandler (jobId) {
        processingEventCount++
        if (testEvents) {
          t.ok(is.uuid(jobId), `Event: processing [${processingEventCount} of ${processingEventTotal}] [${jobId}]`)
        }
      }
      let progressEventCount = 0
      let progressEventTotal = 3
      function progressEventHandler (jobId, percent) {
        progressEventCount++
        if (testEvents) {
          t.pass(`Event: progress  [${progressEventCount} of ${progressEventTotal}]`)
          t.ok(is.uuid(jobId), `Event: progress [${jobId}]`)
          t.ok(is.number(percent), `Event: progress [${percent}%]`)
        }
      }
      let completedEventCount = 0
      let completedEventTotal = 1
      function completedEventHandler (jobId) {
        completedEventCount++
        if (testEvents) {
          t.ok(is.uuid(jobId), `Event: completed [${completedEventCount} of ${completedEventTotal}] [${jobId}]`)
        }
      }
      let cancelledEventCount = 0
      let cancelledEventTotal = 1
      function cancelledEventHandler (jobId) {
        cancelledEventCount++
        if (testEvents) {
          t.ok(is.uuid(jobId), `Event: cancelled [${cancelledEventCount} of ${cancelledEventTotal}] [${jobId}]`)
        }
      }
      let failedEventCount = 0
      let failedEventTotal = 1
      function failedEventHandler (jobId) {
        failedEventCount++
        if (testEvents) {
          t.ok(is.uuid(jobId), `Event: failed [${failedEventCount} of ${failedEventTotal}] [${jobId}]`)
        }
      }
      let terminatedEventCount = 0
      let terminatedEventTotal = 1
      function terminatedEventHandler (jobId) {
        terminatedEventCount++
        if (testEvents) {
          t.ok(is.uuid(jobId), `Event: terminated [${terminatedEventCount} of ${terminatedEventTotal}] [${jobId}]`)
        }
      }
      let logEventCount = 0
      let logEventTotal = 1
      function logEventHandler (jobId) {
        logEventCount++
        if (testEvents) {
          t.ok(is.uuid(jobId), `Event: log [${logEventCount} of ${logEventTotal}] [${jobId}]`)
        }
      }
      let updatedEventCount = 0
      let updatedEventTotal = 0
      function updatedEventHandler (jobId) {
        updatedEventCount++
        if (testEvents) {
          t.ok(is.uuid(jobId), `Event: updated [${updatedEventCount} of ${updatedEventTotal}] [${jobId}]`)
        }
      }
      let pausingEventCount = 0
      let pausingEventTotal = 2
      function pausingEventHandler (global, queueId) {
        pausingEventCount++
        if (testEvents) {
          t.ok(is.string(queueId), `Event: pausing [${pausingEventCount} of ${pausingEventTotal}]`)
          t.ok(is.boolean(global), `Event: pausing [global: ${global}]`)
          t.ok(is.string(queueId), `Event: pausing [queueId: ${queueId}]`)
        }
      }
      let pausedEventCount = 0
      let pausedEventTotal = 2
      function pausedEventHandler (global, queueId) {
        pausedEventCount++
        if (testEvents) {
          t.ok(is.string(queueId), `Event: paused [${pausedEventCount} of ${pausedEventTotal}]`)
          t.ok(is.boolean(global), `Event: paused [global: ${global}]`)
          t.ok(is.string(queueId), `Event: paused [queueId: ${queueId}]`)
        }
      }
      let resumedEventCount = 0
      let resumedEventTotal = 2
      function resumedEventHandler (global, queueId) {
        resumedEventCount++
        if (testEvents) {
          t.ok(is.string(queueId), `Event: resumed [${resumedEventCount} of ${resumedEventTotal}]`)
          t.ok(is.boolean(global), `Event: resumed [global: ${global}]`)
          t.ok(is.string(queueId), `Event: resumed [queueId: ${queueId}]`)
        }
      }
      let removedEventCount = 0
      let removedEventTotal = 1
      function removedEventHandler (jobId) {
        removedEventCount++
        if (testEvents) {
          t.ok(is.uuid(jobId), `Event: removed [${removedEventCount} of ${removedEventTotal}] [${jobId}]`)
        }
      }
      let idleEventCount = 0
      let idleEventTotal = 1
      function idleEventHandler (queueId) {
        if (idleEventCount < 1) {
          idleEventCount++
          if (testEvents) {
            t.ok(is.string(queueId), `Event: idle [${idleEventCount} of ${idleEventTotal}] [${queueId}]`)
          }
        }
      }
      let reviewedEventCount = 0
      let reviewedEventTotal = 1
      function reviewedEventHandler (result) {
        reviewedEventCount++
        if (testEvents) {
          t.ok(is.object(result), `Event: reviewed [${reviewedEventCount} of ${reviewedEventTotal}]`)
        }
      }
      let resetEventCount = 0
      let resetEventTotal = 1
      function resetEventHandler (total) {
        resetEventCount++
        if (testEvents) {
          t.ok(is.integer(total), `Event: reset [${resetEventCount} of ${resetEventTotal}] [${total}]`)
        }
      }
      let errorEventCount = 0
      let errorEventTotal = 0
      function errorEventHandler (err) {
        errorEventCount++
        if (testEvents) {
          t.ok(is.string(err.message), `Event: error [${errorEventCount} of ${errorEventTotal}] [${err.message}]`)
        }
      }
      let detachedEventCount = 0
      let detachedEventTotal = 0
      function detachedEventHandler (queueId) {
        detachedEventCount++
        if (testEvents) {
          t.ok(is.string(queueId), `Event: detached [${detachedEventCount} of ${detachedEventTotal}] [${queueId}]`)
        }
      }
      let stoppingEventCount = 0
      let stoppingEventTotal = 0
      function stoppingEventHandler (queueId) {
        stoppingEventCount++
        if (testEvents) {
          t.ok(is.string(queueId), `Event: stopping [${stoppingEventCount} of ${stoppingEventTotal}] [${queueId}]`)
        }
      }
      let stoppedEventCount = 0
      let stoppedEventTotal = 0
      function stoppedEventHandler (queueId) {
        stoppedEventCount++
        if (testEvents) {
          t.ok(is.string(queueId), `Event: stopped [${stoppedEventCount} of ${stoppedEventTotal}] [${queueId}]`)
        }
      }
      let droppedEventCount = 0
      let droppedEventTotal = 0
      function droppedEventHandler (queueId) {
        droppedEventCount++
        if (testEvents) {
          t.ok(is.string(queueId), `Event: dropped [${droppedEventCount} of ${droppedEventTotal}] [${queueId}]`)
        }
      }

      function addEventHandlers () {
        testEvents = true
        q.on(enums.status.ready, readyEventHandler)
        q.on(enums.status.added, addedEventHandler)
        q.on(enums.status.active, activeEventHandler)
        q.on(enums.status.processing, processingEventHandler)
        q.on(enums.status.progress, progressEventHandler)
        q.on(enums.status.completed, completedEventHandler)
        q.on(enums.status.cancelled, cancelledEventHandler)
        q.on(enums.status.failed, failedEventHandler)
        q.on(enums.status.terminated, terminatedEventHandler)
        q.on(enums.status.paused, pausedEventHandler)
        q.on(enums.status.pausing, pausingEventHandler)
        q.on(enums.status.resumed, resumedEventHandler)
        q.on(enums.status.removed, removedEventHandler)
        q.on(enums.status.log, logEventHandler)
        q.on(enums.status.updated, updatedEventHandler)
        q.on(enums.status.idle, idleEventHandler)
        q.on(enums.status.reviewed, reviewedEventHandler)
        q.on(enums.status.reset, resetEventHandler)
        q.on(enums.status.error, errorEventHandler)
        q.on(enums.status.detached, detachedEventHandler)
        q.on(enums.status.stopping, stoppingEventHandler)
        q.on(enums.status.stopped, stoppedEventHandler)
        q.on(enums.status.dropped, droppedEventHandler)
      }
      function removeEventHandlers () {
        testEvents = false
        q.removeListener(enums.status.ready, readyEventHandler)
        q.removeListener(enums.status.added, addedEventHandler)
        q.removeListener(enums.status.active, activeEventHandler)
        q.removeListener(enums.status.processing, processingEventHandler)
        q.removeListener(enums.status.progress, progressEventHandler)
        q.removeListener(enums.status.completed, completedEventHandler)
        q.removeListener(enums.status.cancelled, cancelledEventHandler)
        q.removeListener(enums.status.failed, failedEventHandler)
        q.removeListener(enums.status.terminated, terminatedEventHandler)
        q.removeListener(enums.status.paused, pausedEventHandler)
        q.removeListener(enums.status.pausing, pausingEventHandler)
        q.removeListener(enums.status.resumed, resumedEventHandler)
        q.removeListener(enums.status.removed, removedEventHandler)
        q.removeListener(enums.status.log, logEventHandler)
        q.removeListener(enums.status.updated, updatedEventHandler)
        q.removeListener(enums.status.idle, idleEventHandler)
        q.removeListener(enums.status.reviewed, reviewedEventHandler)
        q.removeListener(enums.status.reset, resetEventHandler)
        q.removeListener(enums.status.error, errorEventHandler)
        q.removeListener(enums.status.detached, detachedEventHandler)
        q.removeListener(enums.status.stopping, stoppingEventHandler)
        q.removeListener(enums.status.stopped, stoppedEventHandler)
        q.removeListener(enums.status.dropped, droppedEventHandler)
        return q.resume()
      }

      let job = q.createJob()
      let processDelay = 500

      return q.reset().then((resetResult) => {
        t.ok(is.integer(resetResult), 'Queue reset')
        return q.pause()
      }).then(() => {
        q.process((j, next) => {
          setTimeout(function jobProcessing () {
            t.equal(j.id, job.id, `Job Processed [${j.id}]`)
            next('queue-change')
          }, processDelay)
          return j.setProgress(50)
        })

        // ---------- Test added, active, progress completed, removed  ----------
        t.comment('queue-change: added, active, progress, completed, and removed change events')
        addEventHandlers()
      }).then(() => {
        return q.addJob(job)
      }).then((savedJob) => {
        t.equal(savedJob[0].id, job.id, 'Job saved successfully')
        return q.resume()
      }).then(() => {
        t.ok(!q.paused, 'Queue not paused')
      }).delay(processDelay).then(() => {
        return q.pause()
      }).delay(processDelay).then(() => {
        // t.ok(q.paused, 'Queue paused')
        return q.removeJob(job.id)
      }).delay(processDelay).then(() => {
        job = q.createJob()
        job.timeout = processDelay / 2000
        job.retryDelay = 0
        job.retryMax = 1

        // ---------- Test failed and terminated ----------
        t.comment('queue-change: failed and terminated change events')
        return q.addJob(job)
      }).then((savedJob) => {
        t.equal(savedJob[0].id, job.id, 'Job saved successfully')
        return q.resume()
      }).then(() => {
        t.ok(!q.paused, 'Queue not paused')
      }).delay(processDelay * 2).then(() => {
        return q.pause()
      }).delay(processDelay).then(() => {
        job = q.createJob()

        // ---------- Test log and cancelled ----------
        t.comment('queue-change: log and cancelled change events')
        return q.addJob(job)
      }).then((savedJob) => {
        t.equal(savedJob[0].id, job.id, 'Job saved successfully')
        return savedJob[0].addLog(savedJob[0].createLog('test log'))
      }).then(() => {
        return q.cancelJob(job.id, 'testing')
      }).delay(processDelay).then(() => {
        return q.reset()
      }).then((resetResult) => {
        t.ok(resetResult >= 0, 'Queue reset')
        removeEventHandlers()

        // ---------- Event summary Test ----------
        t.comment('queue: Event Summary')
        t.equal(readyEventCount, readyEventTotal, 'Ready event count valid')
        t.equal(addedEventCount, addedEventTotal, 'Added event count valid')
        t.equal(activeEventCount, activeEventTotal, 'Active event count valid')
        t.equal(processingEventCount, processingEventTotal, 'Processing event count valid')
        t.equal(progressEventCount, progressEventTotal, 'Progress event count valid')
        t.equal(completedEventCount, completedEventTotal, 'Completed event count valid')
        t.equal(cancelledEventCount, cancelledEventTotal, 'Cancelled event count valid')
        t.equal(failedEventCount, failedEventTotal, 'Failed event count valid')
        t.equal(terminatedEventCount, terminatedEventTotal, 'Terminated event count valid')
        t.equal(pausingEventCount, pausingEventTotal, 'Pausing event count valid')
        t.equal(pausedEventCount, pausedEventTotal, 'Paused event count valid')
        t.equal(resumedEventCount, resumedEventTotal, 'Resumed event count valid')
        t.equal(removedEventCount, removedEventTotal, 'Removed event count valid')
        t.equal(logEventCount, logEventTotal, 'Log event count valid')
        t.equal(updatedEventCount, updatedEventTotal, 'Updated event count valid')
        t.equal(idleEventCount, idleEventTotal, 'Idle event count valid')
        t.equal(reviewedEventCount, reviewedEventTotal, 'Reviewed event count valid')
        t.equal(resetEventCount, resetEventTotal, 'Reset event count valid')
        t.equal(errorEventCount, errorEventTotal, 'Error event count valid')
        t.equal(detachedEventCount, detachedEventTotal, 'Detached event count valid')
        t.equal(stoppingEventCount, stoppingEventTotal, 'Stopping event count valid')
        t.equal(stoppedEventCount, stoppedEventTotal, 'Stopped event count valid')
        t.equal(droppedEventCount, droppedEventTotal, 'Dropped event count valid')

        q.stop()
        return resolve(t.end())
      }).catch(err => tError(err, module, t))
    })
  })
}
<|endoftext|>


<commit_before>import ui from '../../lib/ui';
import ora from 'ora';
import Blueprint from '../../lib/blueprint';
import Promise from 'bluebird';
import { exec } from 'child_process';
import startCase from 'lodash/startCase';

const run = Promise.promisify(exec);

export default class AppBlueprint extends Blueprint {

  static blueprintName = 'app';
  static description = 'Creates a new app, initializes git and installs dependencies';

  params = [ 'name' ];

  locals({ name }) {
    return {
      name,
      className: startCase(name).replace(/\s/g, ''),
      humanizedName: startCase(name)
    };
  }

  postInstall({ name }) {
    let spinner = ora();
    ui.info('');
    spinner.text = 'Installing npm dependencies ...';
    spinner.start();
    run('npm install --loglevel=error', { cwd: name }).then(() => {
      spinner.stop();
      ui.success('Installing npm dependencies ... done ✔');
      spinner.text = 'Setting up git repo ...';
      spinner.start();
      return run('git init', { cwd: name });
    }).then(() => {
      return run('git add .', { cwd: name });
    }).then(() => {
      return run('git commit -am "Initial denali project scaffold"', { cwd: name });
    }).then(() => {
      spinner.stop();
      ui.success('Setting up git repo ... done ✔');
      ui.success('🏔 Installation complete!');
      ui.info('');
      ui.info('To launch your application, just run:');
      ui.info('');
      ui.info(`  $ cd ${ name } && denali server`);
      ui.info('');
    });
  }

}
<commit_msg>Increase max buffer in `new`<commit_after>import ui from '../../lib/ui';
import ora from 'ora';
import Blueprint from '../../lib/blueprint';
import Promise from 'bluebird';
import { exec } from 'child_process';
import startCase from 'lodash/startCase';

const run = Promise.promisify(exec);
const maxBuffer = 400 * 1024;

export default class AppBlueprint extends Blueprint {

  static blueprintName = 'app';
  static description = 'Creates a new app, initializes git and installs dependencies';

  params = [ 'name' ];

  locals({ name }) {
    return {
      name,
      className: startCase(name).replace(/\s/g, ''),
      humanizedName: startCase(name)
    };
  }

  postInstall({ name }) {
    let spinner = ora();
    ui.info('');
    spinner.text = 'Installing npm dependencies ...';
    spinner.start();
    run('npm install --loglevel=error', { cwd: name, maxBuffer }).then(() => {
      spinner.stop();
      ui.success('Installing npm dependencies ... done ✔');
      spinner.text = 'Setting up git repo ...';
      spinner.start();
      return run('git init', { cwd: name, maxBuffer });
    }).then(() => {
      return run('git add .', { cwd: name, maxBuffer });
    }).then(() => {
      return run('git commit -am "Initial denali project scaffold"', { cwd: name, maxBuffer });
    }).then(() => {
      spinner.stop();
      ui.success('Setting up git repo ... done ✔');
      ui.success('🏔 Installation complete!');
      ui.info('');
      ui.info('To launch your application, just run:');
      ui.info('');
      ui.info(`  $ cd ${ name } && denali server`);
      ui.info('');
    });
  }

}
<|endoftext|>


<commit_before>/**
 * API Facet to make calls to methods in the users namespace.
 *
 * This provides functions to call:
 *   - getPresence: {@link https://api.slack.com/methods/users.getPresence|users.getPresence}
 *   - identity: {@link https://api.slack.com/methods/users.identity|users.identity}
 *   - info: {@link https://api.slack.com/methods/users.info|users.info}
 *   - list: {@link https://api.slack.com/methods/users.list|users.list}
 *   - lookupByEmail: {@link https://api.slack.com/methods/users.lookupByEmail|users.lookupByEmail}
 *   - setActive: {@link https://api.slack.com/methods/users.setActive|users.setActive}
 *   - setPresence: {@link https://api.slack.com/methods/users.setPresence|users.setPresence}
 *
 */

function UsersFacet(makeAPICall) {
  this.name = 'users';
  this.makeAPICall = makeAPICall;
}

/**
 * Gets user presence information.
 * @see {@link https://api.slack.com/methods/users.getPresence|users.getPresence}
 *
 * @param {?} user - User to get presence info on. Defaults to the authed user.
 * @param {function=} optCb Optional callback, if not using promises.
 */
UsersFacet.prototype.getPresence = function getPresence(user, optCb) {
  var requiredArgs = {
    user: user
  };

  return this.makeAPICall('users.getPresence', requiredArgs, null, optCb);
};

/**
 * Get a user's identity.
 * @see {@link https://api.slack.com/methods/users.identity|users.identity}
 *
 * @param {function=} optCb Optional callback, if not using promises.
 */
UsersFacet.prototype.identity = function identity(optCb) {
  return this.makeAPICall('users.identity', null, null, optCb);
};

/**
 * Gets information about a user.
 * @see {@link https://api.slack.com/methods/users.info|users.info}
 *
 * @param {?} user - User to get info on
 * @param {function=} optCb Optional callback, if not using promises.
 */
UsersFacet.prototype.info = function info(user, optCb) {
  var requiredArgs = {
    user: user
  };

  return this.makeAPICall('users.info', requiredArgs, null, optCb);
};

/**
 * Lists all users in a Slack team.
 * @see {@link https://api.slack.com/methods/users.list|users.list}
 *
 * @param {Object=} opts
 * @param {?} opts.presence - Whether to include presence data in the output
 * @param {?} opts.include_locale - Set this to `true` to receive the locale for users. Defaults to
 * `false`
 * @param {function=} optCb Optional callback, if not using promises.
 */
UsersFacet.prototype.list = function list(opts, optCb) {
  return this.makeAPICall('users.list', null, opts, optCb);
};

/**
 * Find a user with an email address.
 * @see {@link https://api.slack.com/methods/users.lookupByEmail|users.lookupByEmail}
 *
 * @param {?} email - An email address belonging to a user in the workspace
 * @param {Object=} opts
 * @param {function=} optCb Optional callback, if not using promises.
 */
UsersFacet.prototype.lookupByEmail = function lookupByEmail(email, opts, optCb) {
  var requiredArgs = {
    email: email
  };

  return this.makeAPICall('users.lookupByEmail', requiredArgs, opts, optCb);
};

/**
 * Marks a user as active.
 * @see {@link https://api.slack.com/methods/users.setActive|users.setActive}
 *
 * @param {function=} optCb Optional callback, if not using promises.
 */
UsersFacet.prototype.setActive = function setActive(optCb) {
  return this.makeAPICall('users.setActive', null, null, optCb);
};

/**
 * Manually sets user presence.
 * @see {@link https://api.slack.com/methods/users.setPresence|users.setPresence}
 *
 * @param {?} presence - Either `auto` or `away`
 * @param {function=} optCb Optional callback, if not using promises.
 */
UsersFacet.prototype.setPresence = function setPresence(presence, optCb) {
  var requiredArgs = {
    presence: presence
  };

  return this.makeAPICall('users.setPresence', requiredArgs, null, optCb);
};

module.exports = UsersFacet;
<commit_msg>Make spacing consitent<commit_after>/**
 * API Facet to make calls to methods in the users namespace.
 *
 * This provides functions to call:
 *   - getPresence: {@link https://api.slack.com/methods/users.getPresence|users.getPresence}
 *   - identity: {@link https://api.slack.com/methods/users.identity|users.identity}
 *   - info: {@link https://api.slack.com/methods/users.info|users.info}
 *   - list: {@link https://api.slack.com/methods/users.list|users.list}
 *   - lookupByEmail: {@link https://api.slack.com/methods/users.lookupByEmail|users.lookupByEmail}
 *   - setActive: {@link https://api.slack.com/methods/users.setActive|users.setActive}
 *   - setPresence: {@link https://api.slack.com/methods/users.setPresence|users.setPresence}
 *
 */

function UsersFacet(makeAPICall) {
  this.name = 'users';
  this.makeAPICall = makeAPICall;
}

/**
 * Gets user presence information.
 * @see {@link https://api.slack.com/methods/users.getPresence|users.getPresence}
 *
 * @param {?} user - User to get presence info on. Defaults to the authed user.
 * @param {function=} optCb Optional callback, if not using promises.
 */
UsersFacet.prototype.getPresence = function getPresence(user, optCb) {
  var requiredArgs = {
    user: user
  };

  return this.makeAPICall('users.getPresence', requiredArgs, null, optCb);
};

/**
 * Get a user's identity.
 * @see {@link https://api.slack.com/methods/users.identity|users.identity}
 *
 * @param {function=} optCb Optional callback, if not using promises.
 */
UsersFacet.prototype.identity = function identity(optCb) {
  return this.makeAPICall('users.identity', null, null, optCb);
};

/**
 * Gets information about a user.
 * @see {@link https://api.slack.com/methods/users.info|users.info}
 *
 * @param {?} user - User to get info on
 * @param {function=} optCb Optional callback, if not using promises.
 */
UsersFacet.prototype.info = function info(user, optCb) {
  var requiredArgs = {
    user: user
  };

  return this.makeAPICall('users.info', requiredArgs, null, optCb);
};

/**
 * Lists all users in a Slack team.
 * @see {@link https://api.slack.com/methods/users.list|users.list}
 *
 * @param {Object=} opts
 * @param {?} opts.presence - Whether to include presence data in the output
 * @param {?} opts.include_locale - Set this to `true` to receive the locale for users. Defaults to
 * `false`
 * @param {function=} optCb Optional callback, if not using promises.
 */
UsersFacet.prototype.list = function list(opts, optCb) {
  return this.makeAPICall('users.list', null, opts, optCb);
};

/**
 * Find a user with an email address.
 * @see {@link https://api.slack.com/methods/users.lookupByEmail|users.lookupByEmail}
 *
 * @param {?} email - An email address belonging to a user in the workspace
 * @param {Object=} opts
 * @param {function=} optCb Optional callback, if not using promises.
 */
UsersFacet.prototype.lookupByEmail = function lookupByEmail(email, opts, optCb) {
  var requiredArgs = {
    email: email
  };

  return this.makeAPICall('users.lookupByEmail', requiredArgs, opts, optCb);
};

/**
 * Marks a user as active.
 * @see {@link https://api.slack.com/methods/users.setActive|users.setActive}
 *
 * @param {function=} optCb Optional callback, if not using promises.
 */
UsersFacet.prototype.setActive = function setActive(optCb) {
  return this.makeAPICall('users.setActive', null, null, optCb);
};

/**
 * Manually sets user presence.
 * @see {@link https://api.slack.com/methods/users.setPresence|users.setPresence}
 *
 * @param {?} presence - Either `auto` or `away`
 * @param {function=} optCb Optional callback, if not using promises.
 */
UsersFacet.prototype.setPresence = function setPresence(presence, optCb) {
  var requiredArgs = {
    presence: presence
  };

  return this.makeAPICall('users.setPresence', requiredArgs, null, optCb);
};

module.exports = UsersFacet;
<|endoftext|>


<commit_before>var locastyle = (function() {
  'use strict';

  // Used to run scripts when the HTML is ready
  function fastInit() {
    locastyle.sidebarToggle.init();
    locastyle.sidebars.init();
  }

  // Used to run scripts that just when all things are ready
  function init() {
    locastyle.breakpoints.init();
    loadModules();
    locastyle.general.init();
    locastyle.btnGroup.init();
    locastyle.alert.init();
    locastyle.datepicker.init();
    locastyle.form.togglePasswordField();
    checkClassForTrack();
    locastyle.browserDetect.init();
  }

  function loadModules() {
    var modules = getModules();
    for (var i in modules) {
      if (modules.hasOwnProperty(i)) {
        locastyle[modules[i]].init();
        console.info("Locastyle: module [" + modules[i] + "] successfully initialized.");
      }
    }
  }

  function checkClassForTrack() {
    if($("html").hasClass("ls-trackevent-on")){
      locastyle.trackEvents.init();
    }
  }

  function getModules() {
    var modules = [];
    $("[data-ls-module]").each(function () {
      var module = $(this).data("ls-module");
      if ( modules.indexOf(module) === -1 ) {
        modules.push(module);
      }
    });
    return modules;
  }

  return {
    init: init,
    fastInit: fastInit
  };

}());

var ls = locastyle;

$(window).load(function() {
  'use strict';
  ls.init();
});

$(document).ready(function(){
  'use strict';
  ls.fastInit();
});
<commit_msg>added event ready on initializer modules<commit_after>var locastyle = (function() {
  'use strict';

  // Used to run scripts when the HTML is ready
  function fastInit() {
    locastyle.sidebarToggle.init();
    locastyle.sidebars.init();
  }

  // Used to run scripts that just when all things are ready
  function init() {
    locastyle.breakpoints.init();
    loadModules();
    locastyle.general.init();
    locastyle.btnGroup.init();
    locastyle.alert.init();
    locastyle.datepicker.init();
    locastyle.form.togglePasswordField();
    checkClassForTrack();
    locastyle.browserDetect.init();
  }

  function loadModules() {
    var modules = getModules();
    for (var i in modules) {
      if (modules.hasOwnProperty(i)) {
        locastyle[modules[i]].init();
        console.info("Locastyle: module [" + modules[i] + "] successfully initialized.");

        $.event.trigger(modules[i] + ':ready');
      }
    }
  }

  function checkClassForTrack() {
    if($("html").hasClass("ls-trackevent-on")){
      locastyle.trackEvents.init();
    }
  }

  function getModules() {
    var modules = [];
    $("[data-ls-module]").each(function () {
      var module = $(this).data("ls-module");
      if ( modules.indexOf(module) === -1 ) {
        modules.push(module);
      }
    });
    return modules;
  }

  return {
    init: init,
    fastInit: fastInit
  };

}());

var ls = locastyle;

$(window).load(function() {
  'use strict';
  ls.init();
});

$(document).ready(function(){
  'use strict';
  ls.fastInit();
});
<|endoftext|>


<commit_before>$(function() {
  $( "#topic-2" ).tabs();
  $( "#topic-3" ).tabs();
  $( "#topic-5" ).tabs();
  $( "#topic-6" ).tabs();
  $( "#topic-7" ).tabs();
  $( "#topic-8" ).tabs();

  // Hover states on the static widgets
  $( "#dialog-link, #icons li" ).hover(
    function() {
      $( this ).addClass( "ui-state-hover" );
    },
    function() {
      $( this ).removeClass( "ui-state-hover" );
    }
  );
});
<commit_msg>Switch all the Sass/SCSS tabs together<commit_after>$(function() {
  $( "#topic-2" ).tabs();
  $( "#topic-3" ).tabs();
  $( "#topic-5" ).tabs();
  $( "#topic-6" ).tabs();
  $( "#topic-7" ).tabs();
  $( "#topic-8" ).tabs();

  // Hover states on the static widgets
  $( "#dialog-link, #icons li" ).hover(
    function() {
      $( this ).addClass( "ui-state-hover" );
    },
    function() {
      $( this ).removeClass( "ui-state-hover" );
    }
  );

  // Switch ALL the tabs (Sass/SCSS) together
  var
    noRecursion = false,
    jqA = $( "a.ui-tabs-anchor" ),
    jqASass = jqA.filter( ":contains('Sass')" ).click(function() {
      if ( !noRecursion ) {
        noRecursion = true;
        jqASass.not( this ).click();
        noRecursion = false;
      }
    }),
    jqASCSS = jqA.filter( ":contains('SCSS')" ).click(function() {
      if ( !noRecursion ) {
        noRecursion = true;
        jqASCSS.not( this ).click();
        noRecursion = false;
      }
    })
  ;
});
<|endoftext|>


<commit_before>var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
        document.addEventListener("offline", checkConnection, false);
        document.addEventListener("pause", onPause, false);
        document.addEventListener("resume", onResume, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
        screen.lockOrientation('portrait');
        localStorage.setItem("saldo_actual",0);
        localStorage.setItem("wisi",false);
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        getDeviceProperty();
        detectGEO();
    }
};

function detectGEO(){
  var options = {
    enableHighAccuracy: true,
    timeout: 5000,
    maximumAge: 75000
  };
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(onSuccess, onError, options);
  } else {
      console.log('Geolocalización no soportada');
  }
}

// onSuccess Geolocation    //
function onSuccess(position) {
  localStorage.removeItem("position");
  lat1= position.coords.latitude;
  lng1= position.coords.longitude;
  var pos= {lat:lat1,lng:lng1};
  localStorage.setItem("position",JSON.stringify(pos));
  console.log('Coordenadas detectadas');
}
function onError(error) {
  console.log('Error detectando coordenadas');
}

function getDeviceProperty()
{
     var deviceOS  = device.platform  ;  //fetch the device operating system
     var deviceOSVersion = device.version ;  //fetch the device OS version
     localStorage.setItem("OS",deviceOS);
}

function onPause() {
  window.setInterval(function(){
    WifiWizard.listNetworks(listHandler, fail);
  }, 5000);
}

function onResume() {
  localStorage.setItem("wisi",false);
}

function checkConnection() {
    var state=true;
    var networkState = navigator.connection.type;
    var states = {};
    states[Connection.UNKNOWN]  = 'Unknown connection';
    states[Connection.ETHERNET] = 'Ethernet connection';
    states[Connection.WIFI]     = 'WiFi connection';
    states[Connection.CELL_2G]  = 'Cell 2G connection';
    states[Connection.CELL_3G]  = 'Cell 3G connection';
    states[Connection.CELL_4G]  = 'Cell 4G connection';
    states[Connection.CELL]     = 'Cell generic connection';
    states[Connection.NONE]     = 'No network connection';

    if(states[networkState]=='No network connection'){
        navigator.vibrate(1000);
        alert('WIFI no activado!');
        state=false;
    }
    return state;
}

function fail(e){
    console.log("Detect active WIFI "+e);
}

function listHandler(a){
    for(var i=0; i<a.length; i++){
        if(a[i].search("WISI TE CONECTA")>0||a[i].search("VALENCIA_V")>0){
          if(!localStorage.wisi){
            navigator.vibrate(2000);
            myApp.alert("Red WISI detectada", "");
            localStorage.setItem("wisi",true);
          }
        }
    }
}<commit_msg>alert<commit_after>var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
        document.addEventListener("offline", checkConnection, false);
        document.addEventListener("pause", onPause, false);
        document.addEventListener("resume", onResume, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
        screen.lockOrientation('portrait');
        localStorage.setItem("saldo_actual",0);
        localStorage.setItem("wisi",false);
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        getDeviceProperty();
        detectGEO();
    }
};

function detectGEO(){
  var options = {
    enableHighAccuracy: true,
    timeout: 5000,
    maximumAge: 75000
  };
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(onSuccess, onError, options);
  } else {
      console.log('Geolocalización no soportada');
  }
}

// onSuccess Geolocation    //
function onSuccess(position) {
  localStorage.removeItem("position");
  lat1= position.coords.latitude;
  lng1= position.coords.longitude;
  var pos= {lat:lat1,lng:lng1};
  localStorage.setItem("position",JSON.stringify(pos));
  console.log('Coordenadas detectadas');
}
function onError(error) {
  console.log('Error detectando coordenadas');
}

function getDeviceProperty()
{
     var deviceOS  = device.platform  ;  //fetch the device operating system
     var deviceOSVersion = device.version ;  //fetch the device OS version
     localStorage.setItem("OS",deviceOS);
}

function onPause() {
  window.setInterval(function(){
    WifiWizard.listNetworks(listHandler, fail);
  }, 5000);
}

function onResume() {
  localStorage.setItem("wisi",false);
}

function checkConnection() {
    var state=true;
    var networkState = navigator.connection.type;
    var states = {};
    states[Connection.UNKNOWN]  = 'Unknown connection';
    states[Connection.ETHERNET] = 'Ethernet connection';
    states[Connection.WIFI]     = 'WiFi connection';
    states[Connection.CELL_2G]  = 'Cell 2G connection';
    states[Connection.CELL_3G]  = 'Cell 3G connection';
    states[Connection.CELL_4G]  = 'Cell 4G connection';
    states[Connection.CELL]     = 'Cell generic connection';
    states[Connection.NONE]     = 'No network connection';

    if(states[networkState]=='No network connection'){
        navigator.vibrate(1000);
        alert('WIFI no activado!');
        state=false;
    }
    return state;
}

function fail(e){
    console.log("Detect active WIFI "+e);
}

function listHandler(a){
    for(var i=0; i<a.length; i++){
        if(a[i].search("WISI TE CONECTA")>0||a[i].search("VALENCIA_V")>0){
          if(!localStorage.wisi){
            navigator.vibrate(2000);
            navigator.notification.alert(
                'You are the winner!',  // message
                'Game Over',            // title
                'Done'                  // buttonName
            );
            myApp.alert("Red WISI detectada", "");
            localStorage.setItem("wisi",true);
          }
        }
    }
}<|endoftext|>


<commit_before>var instanceMethods = {
    riskFormatter: function(obj) {
        if (obj.riskMid == null) return "-";
        var txt = obj.riskMid.toString();
        if (_.isFinite(obj.riskLow) && _.isFinite(obj.riskHigh)) {
            txt += ` (${obj.riskLow}–${obj.riskHigh})`;
        }
        if (obj.riskEstimated) txt = `[${txt}]`;
        return txt;
    },
    getDescription: function(){
        if (_.isEmpty(this.description)){
            this.description = NtpEpiDescriptive.findOne(this.parent_id);
        }
        return this.description;
    },

};
NtpEpiResult = new Meteor.Collection('ntpEpiResult', {
    transform: function (doc) {
        return  _.extend(Object.create(instanceMethods), doc);
    },
});

// collection class methods/attributes
_.extend(NtpEpiResult, {
    preSaveHook: function(tmpl, obj) {
        // save epi-results
        delete obj.exposureCategory;
        delete obj.numberExposed;
        delete obj.riskMid;
        delete obj.riskLow;
        delete obj.riskHigh;
        delete obj.riskEstimated;
        delete obj.inTrendTest;
        var trs = tmpl.findAll('.riskEstimateTbody tr');
        obj.riskEstimates = _.map(trs, function(row){
            return clientShared.newValues(row);
        });

        // save variables of concern
        delete obj.vocName;
        delete obj.vocAddressedInStats;
        delete obj.vocSimilarAcrossGroups;
        delete obj.vocCoexposuresAssociated;
        delete obj.vocOtherInformation;
        delete obj.vocStrengthOfAssociation;
        delete obj.vocRuleOutConfounding;
        trs = tmpl.findAll('#variablesOfConcern > tbody > tr');
        obj.variablesOfConcern = _.map(trs, function(row){
            return clientShared.newValues(row);
        });
    },
    variableOfConcernSchema: new SimpleSchema({
        vocName: {
            type: String,
            label: "Variable",
            popoverText: "Based on review of information, identify variables that may be a potential confounder/endpoint specific.",
            typeaheadMethod: "searchNtpEpiVariablesOfConcern",
        },
        vocAddressedInStats: {
            type: String,
            label: "Addressed in stats?",
            popoverText: "<add>",
        },
        vocSimilarAcrossGroups: {
            type: String,
            label: "Similar across groups?",
            popoverText: "<add>",
        },
        vocCoexposuresAssociated: {
            type: String,
            label: "Coexposures associated?",
            popoverText: "<add>",
        },
        vocOtherInformation: {
            type: String,
            label: "Other information",
            popoverText: "<add>",
        },
        vocStrengthOfAssociation: {
            type: String,
            label: "Strength of association",
            popoverText: "<add>",
        },
        vocRuleOutConfounding: {
            type: String,
            label: "Rule out confounding?",
            popoverText: "<add>",
        },
    }),
});

var isNumberOrNR = function() {
    if (this.isSet && (this.value === "NR" || _.isFinite(this.value))) {
        return undefined;
    } else {
        return "numOrNR";
    }
};

tblBuilderCollections.attachSchema(NtpEpiResult, _.extend({
    organSite: {
        label: "Organ site",
        type: String,
        min: 1,
        popoverText: "Specify ICD code where needed for clarity (e.g., for lymphomas)",
        typeaheadMethod: "searchNtpOrganSite",
    },
    effectMeasure: {
        label: "Measure of effect",
        type: String,
        min: 1,
        popoverText: "Risk metric used to display results (SMR, RR, etc.)",
        typeaheadMethod: "searchNtpEffectMeasure",
    },
    effectUnits: {
        label: "Units of effect measurement",
        type: String,
        optional: true,
        popoverText: "Units, if relevant (e.g., risk per 10 μg/m3)",
        typeaheadMethod: "searchNtpEffectUnits",
    },
    trendTest: {
        label: "p-value for trend",
        type: Number,
        decimal: true,
        optional: true,
        popoverText: "Provide p-value for trend-test when reported",
    },
    "riskEstimates.$.exposureCategory": {
        label: "Exposure category or level",
        type: String,
        min: 1,
        popoverText: "E.g., all exposed workers, second quartile of exposure, quantitative exposure level (always provide quantitative information when available)",
    },
    "riskEstimates.$.numberExposed": {
        label: "Exposed cases/deaths",
        type: String,
        custom: isNumberOrNR,
        popoverText: "Deaths/cases for cohort studies; Cases for case-control studies. If unknown, enter \"NR\"",
    },
    "riskEstimates.$.riskMid": {
        label: "Risk estimate",
        type: Number,
        decimal: true,
        optional: true,
        popoverText: "Central risk reported for risk estimate",
    },
    "riskEstimates.$.riskLow": {
        label: "95% lower CI",
        type: Number,
        decimal: true,
        optional: true,
        popoverText: "95% lower confidence interval risk estimate",
    },
    "riskEstimates.$.riskHigh": {
        label: "95% upper CI",
        type: Number,
        decimal: true,
        optional: true,
        popoverText: "95% upper confidence interval risk estimate",
    },
    "riskEstimates.$.riskEstimated": {
        label: "WG calculation?",
        type: Boolean,
        popoverText: "Calculations by the working-group (WG), not study-authors",
    },
    "riskEstimates.$.inTrendTest": {
        label: "Estimate in trend-test",
        type: Boolean,
        popoverText: "Risk estimate included in trend-test",
    },
    covariates: {
        label: "Covariates controlled",
        type: [String],
        minCount: 1,
        popoverText: "List all covariates which were controlled by matching or adjustment in the analysis reported. Enter each covariate individually, and then press <enter> to add it to the list. If no covariates were specified, add \"not-specified\"",
        typeaheadMethod: "searchNtpCovariates",
    },
    covariatesControlledText: {
        label: "Covariates controlled notes",
        type: String,
        optional: true,
        popoverText: "Further describe how covariates were controlled, if needed, such as details on matching methodology or adjustments made",
        textAreaRows: 4,
    },
    notes: {
        label: "General notes",
        type: String,
        optional: true,
        popoverText: "Note issues related to appropriateness of comparison groups, potential for uncontrolled confounding, etc. (e.g. matching criteria for case-control studies)",
        textAreaRows: 4,
    },
    parent_id: {
        type: SimpleSchema.RegEx.Id,
        denyUpdate: true,
    },
    "variablesOfConcern": {
        type: [NtpEpiResult.variableOfConcernSchema],
        minCount: 0,
    },
}, tblBuilderCollections.base, tblBuilderCollections.table));
<commit_msg>change label and help-text for epi results<commit_after>var instanceMethods = {
    riskFormatter: function(obj) {
        if (obj.riskMid == null) return "-";
        var txt = obj.riskMid.toString();
        if (_.isFinite(obj.riskLow) && _.isFinite(obj.riskHigh)) {
            txt += ` (${obj.riskLow}–${obj.riskHigh})`;
        }
        if (obj.riskEstimated) txt = `[${txt}]`;
        return txt;
    },
    getDescription: function(){
        if (_.isEmpty(this.description)){
            this.description = NtpEpiDescriptive.findOne(this.parent_id);
        }
        return this.description;
    },

};
NtpEpiResult = new Meteor.Collection('ntpEpiResult', {
    transform: function (doc) {
        return  _.extend(Object.create(instanceMethods), doc);
    },
});

// collection class methods/attributes
_.extend(NtpEpiResult, {
    preSaveHook: function(tmpl, obj) {
        // save epi-results
        delete obj.exposureCategory;
        delete obj.numberExposed;
        delete obj.riskMid;
        delete obj.riskLow;
        delete obj.riskHigh;
        delete obj.riskEstimated;
        delete obj.inTrendTest;
        var trs = tmpl.findAll('.riskEstimateTbody tr');
        obj.riskEstimates = _.map(trs, function(row){
            return clientShared.newValues(row);
        });

        // save variables of concern
        delete obj.vocName;
        delete obj.vocAddressedInStats;
        delete obj.vocSimilarAcrossGroups;
        delete obj.vocCoexposuresAssociated;
        delete obj.vocOtherInformation;
        delete obj.vocStrengthOfAssociation;
        delete obj.vocRuleOutConfounding;
        trs = tmpl.findAll('#variablesOfConcern > tbody > tr');
        obj.variablesOfConcern = _.map(trs, function(row){
            return clientShared.newValues(row);
        });
    },
    variableOfConcernSchema: new SimpleSchema({
        vocName: {
            type: String,
            label: "Variable",
            popoverText: "Based on review of information, identify variables that may be a potential confounder/endpoint specific.",
            typeaheadMethod: "searchNtpEpiVariablesOfConcern",
        },
        vocAddressedInStats: {
            type: String,
            label: "Addressed in stats?",
            popoverText: "<add>",
        },
        vocSimilarAcrossGroups: {
            type: String,
            label: "Similar across groups?",
            popoverText: "<add>",
        },
        vocCoexposuresAssociated: {
            type: String,
            label: "Coexposures associated?",
            popoverText: "<add>",
        },
        vocOtherInformation: {
            type: String,
            label: "Other information",
            popoverText: "<add>",
        },
        vocStrengthOfAssociation: {
            type: String,
            label: "Strength of association",
            popoverText: "<add>",
        },
        vocRuleOutConfounding: {
            type: String,
            label: "Rule out confounding?",
            popoverText: "<add>",
        },
    }),
});

var isNumberOrNR = function() {
    if (this.isSet && (this.value === "NR" || _.isFinite(this.value))) {
        return undefined;
    } else {
        return "numOrNR";
    }
};

tblBuilderCollections.attachSchema(NtpEpiResult, _.extend({
    organSite: {
        label: "Organ site",
        type: String,
        min: 1,
        popoverText: "Specify ICD code where needed for clarity (e.g., for lymphomas)",
        typeaheadMethod: "searchNtpOrganSite",
    },
    effectMeasure: {
        label: "Measure of effect",
        type: String,
        min: 1,
        popoverText: "Risk metric used to display results (SMR, RR, etc.)",
        typeaheadMethod: "searchNtpEffectMeasure",
    },
    effectUnits: {
        label: "Units of effect measurement",
        type: String,
        optional: true,
        popoverText: "Units, if relevant (e.g., risk per 10 μg/m3)",
        typeaheadMethod: "searchNtpEffectUnits",
    },
    trendTest: {
        label: "p-value for trend",
        type: Number,
        decimal: true,
        optional: true,
        popoverText: "Provide p-value for trend-test when reported",
    },
    "riskEstimates.$.exposureCategory": {
        label: "Exposure category or level",
        type: String,
        min: 1,
        popoverText: "E.g., all exposed workers, second quartile of exposure, quantitative exposure level (always provide quantitative information when available)",
    },
    "riskEstimates.$.numberExposed": {
        label: "Exposed cases/deaths",
        type: String,
        custom: isNumberOrNR,
        popoverText: "Deaths/cases for cohort studies; Cases for case-control studies. If unknown, enter \"NR\"",
    },
    "riskEstimates.$.riskMid": {
        label: "Risk estimate",
        type: Number,
        decimal: true,
        optional: true,
        popoverText: "Central risk reported for risk estimate",
    },
    "riskEstimates.$.riskLow": {
        label: "95% lower CI",
        type: Number,
        decimal: true,
        optional: true,
        popoverText: "95% lower confidence interval risk estimate",
    },
    "riskEstimates.$.riskHigh": {
        label: "95% upper CI",
        type: Number,
        decimal: true,
        optional: true,
        popoverText: "95% upper confidence interval risk estimate",
    },
    "riskEstimates.$.riskEstimated": {
        label: "WG calculation?",
        type: Boolean,
        popoverText: "Calculations by the working-group (WG), not study-authors",
    },
    "riskEstimates.$.inTrendTest": {
        label: "Estimate in trend-test",
        type: Boolean,
        popoverText: "Risk estimate included in trend-test",
    },
    covariates: {
        label: "Covariates controlled",
        type: [String],
        minCount: 1,
        popoverText: "List all covariates which were controlled by matching or adjustment in the analysis reported. Enter each covariate individually, and then press <enter> to add it to the list. If no covariates were specified, add \"not-specified\"",
        typeaheadMethod: "searchNtpCovariates",
    },
    covariatesControlledText: {
        label: "Covariates controlled notes",
        type: String,
        optional: true,
        popoverText: "Further describe how covariates were controlled, if needed, such as details on matching methodology or adjustments made",
        textAreaRows: 4,
    },
    notes: {
        label: "Confidence of evidence",
        type: String,
        optional: true,
        popoverText: "See the RoC handbook for guidance",
        textAreaRows: 4,
    },
    parent_id: {
        type: SimpleSchema.RegEx.Id,
        denyUpdate: true,
    },
    "variablesOfConcern": {
        type: [NtpEpiResult.variableOfConcernSchema],
        minCount: 0,
    },
}, tblBuilderCollections.base, tblBuilderCollections.table));
<|endoftext|>


<commit_before>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var DELIMITER = String.fromCharCode('\b');

var AnchorifyText = function (_React$Component) {
  _inherits(AnchorifyText, _React$Component);

  function AnchorifyText(props) {
    _classCallCheck(this, AnchorifyText);

    var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(AnchorifyText).call(this, props));

    var regex = void 0;
    if (_this.props.flags) {
      regex = new RegExp(_this.props.regex, _this.props.flags);
    } else {
      regex = new RegExp(_this.props.regex);
    }
    _this.state = {
      regex: regex
    };
    return _this;
  }

  _createClass(AnchorifyText, [{
    key: 'render',
    value: function render() {
      var content = this.anchorify(this.props.text);
      return _react2.default.createElement(
        'span',
        null,
        content
      );
    }
  }, {
    key: 'anchorify',
    value: function anchorify(text) {
      var _this2 = this;

      return text.replace(this.state.regex, function (url) {
        return DELIMITER + url + DELIMITER;
      }).split(DELIMITER).map(function (t, i) {
        var key = 'anchorify-text-' + i;
        if (_this2.state.regex.test(t)) {
          if (_react2.default.Children.count(_this2.props.children) === 1) {
            return _react2.default.cloneElement(_this2.props.children, { url: t, key: key });
          } else {
            if (t.indexOf('://') === -1) t = 'http://' + t;
            return _react2.default.createElement(
              'a',
              { key: key, href: t, target: _this2.props.target },
              t
            );
          }
        } else {
          return _react2.default.createElement(
            'span',
            { key: key },
            t
          );
        }
      });
    }
  }]);

  return AnchorifyText;
}(_react2.default.Component);

AnchorifyText.propTypes = {
  text: _react2.default.PropTypes.string.isRequired,
  regex: _react2.default.PropTypes.string,
  flags: _react2.default.PropTypes.string,
  target: _react2.default.PropTypes.string
};

AnchorifyText.defaultProps = {
  // http://stackoverflow.com/questions/17733236/optimize-gruber-url-regex-for-javascript
  regex: '\\b((?:[a-z][\\w-]+:(?:\\/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}\\/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:' + "'" + '.,<>?«»“”‘’]))',
  flags: 'ig',
  target: '_blank'
};

exports.default = AnchorifyText;<commit_msg>build<commit_after>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var DELIMITER = String.fromCharCode('\b');

var AnchorifyText = function (_React$Component) {
  _inherits(AnchorifyText, _React$Component);

  function AnchorifyText(props) {
    _classCallCheck(this, AnchorifyText);

    var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(AnchorifyText).call(this, props));

    var regex = void 0;
    if (_this.props.flags) {
      regex = new RegExp(_this.props.regex, _this.props.flags);
    } else {
      regex = new RegExp(_this.props.regex);
    }
    _this.state = {
      regex: regex
    };
    return _this;
  }

  _createClass(AnchorifyText, [{
    key: 'render',
    value: function render() {
      var content = this.anchorify(this.props.text);
      return _react2.default.createElement(
        'span',
        null,
        content
      );
    }
  }, {
    key: 'anchorify',
    value: function anchorify(text) {
      var _this2 = this;

      return text.replace(this.state.regex, function (url) {
        return DELIMITER + url + DELIMITER;
      }).split(DELIMITER).map(function (t, i) {
        var key = 'anchorify-text-' + i;
        if (_this2.state.regex.test(t)) {
          if (_react2.default.Children.count(_this2.props.children) === 1) {
            return _react2.default.cloneElement(_this2.props.children, { url: t, key: key });
          } else {
            var hrefURL = t.indexOf('://') === -1 ? 'http://' + t : t;
            return _react2.default.createElement(
              'a',
              { key: key, href: hrefURL, target: _this2.props.target },
              t
            );
          }
        } else {
          return _react2.default.createElement(
            'span',
            { key: key },
            t
          );
        }
      });
    }
  }]);

  return AnchorifyText;
}(_react2.default.Component);

AnchorifyText.propTypes = {
  text: _react2.default.PropTypes.string.isRequired,
  regex: _react2.default.PropTypes.string,
  flags: _react2.default.PropTypes.string,
  target: _react2.default.PropTypes.string
};

AnchorifyText.defaultProps = {
  // http://stackoverflow.com/questions/17733236/optimize-gruber-url-regex-for-javascript
  regex: '\\b((?:[a-z][\\w-]+:(?:\\/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}\\/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:' + "'" + '.,<>?«»“”‘’]))',
  flags: 'ig',
  target: '_blank'
};

exports.default = AnchorifyText;<|endoftext|>


<commit_before>// Copyright 2015 Yahoo! Inc.
// Copyrights licensed under the Mit License. See the accompanying LICENSE file for terms.

var Base = require('../base');

/**
 * @class Rect
 * @extends Base
 * @module Configuration
 * @submodule Atoms
 *
 * @property {int} _left
 * @property {int} _top
 * @property {int} _width
 * @property {int} _height
 */
var Rect = Base.extend(

	/**
	 * Rect constructor
	 *
	 * @param {object} options
	 * @param {int} options.left Offset from the left corner
	 * @param {int} options.top Offset from the top corner
	 * @param {int} options.width Width
	 * @param {int} options.height Height
	 * @param {int} [options.x] Offset from the left corner
	 * @param {int} [options.y] Offset from the top corner
	 * @constructor
	 */
	function (options) {
		this.__super();

		this.setLeft(options.left || options.x);
		this.setTop(options.top || options.y);
		this.setWidth(options.width);
		this.setHeight(options.height);
	},

	{
		/**
		 * Gets the offset from the left corner
		 *
		 * @method getLeft
		 * @return {int}
		 */
		getLeft: function () {
			return this._left;
		},

		/**
		 * Sets the offset from the left corner
		 *
		 * @method setLeft
		 * @param {int} value
		 */
		setLeft: function (value) {
			this._left = value;
		},

		/**
		 * Gets the offset from the top corner
		 *
		 * @method getTop
		 * @return {int}
		 */
		getTop: function () {
			return this._top;
		},

		/**
		 * Sets the offset from the top corner
		 *
		 * @method setTop
		 * @param {int} value
		 */
		setTop: function (value) {
			this._top = value;
		},

		/**
		 * Gets the width
		 *
		 * @method getWidth
		 * @return {int}
		 */
		getWidth: function () {
			return this._width;
		},

		/**
		 * Sets the width
		 *
		 * @method setWidth
		 * @param {int} value
		 */
		setWidth: function (value) {
			this._width = value;
		},

		/**
		 * Gets the height
		 *
		 * @method getHeight
		 * @return {int}
		 */
		getHeight: function () {
			return this._height;
		},

		/**
		 * Sets the height
		 *
		 * @method setHeight
		 * @param {int} value
		 */
		setHeight: function (value) {
			this._height = value;
		},

		/**
		 * Gets boundaries as rect structure
		 *
		 * @method getRect
		 * @return {{left: (int), top: (int), width: (int), height: (int)}}
		 */
		getRect: function () {
			return {
				left: this.getLeft(),
				top: this.getTop(),
				width: this.getWidth(),
				height: this.getHeight()
			};
		},

		/**
		 * Gets boundaries as coordinate structure
		 *
		 * @method getCoordinates
		 * @return {{x: (int), y: (int), width: (int), height: (int)}}
		 */
		getCoordinates: function () {
			return {
				x: this.getLeft(),
				y: this.getTop(),
				width: this.getWidth(),
				height: this.getHeight()
			};
		},

		/**
		 * Checks if a coordinate is within the bounds of the rect
		 *
		 * @method inBounds
		 * @param {int} x X-coordinate
		 * @param {int} y Y-coordinate
		 */
		inBounds: function (x, y) {
			if ((x < this.getLeft()) || (x > this.getLeft() + this.getWidth())) {
				return false;
			}
			if ((y < this.getTop()) || (y > this.getTop() + this.getHeight())) {
				return false;
			}
			return true;
		},

		/**
		 * Limits the rect coordinates to a specified rect
		 *
		 * Note:
		 *  Priority is on the x/y coordinates, and not on the size since the size will then be removed anyways.
		 *
		 * @method limitCoordinates
		 * @param {Rect} outerRect Outer rect
		 */
		limitCoordinates: function (outerRect) {

			var outerRectCoord = outerRect.getRect();

			// Set values if none given
			this._left = this._left || outerRectCoord.left;
			rect._top = rect.y || outerRectCoord.top;
			rect._width = rect.width || outerRectCoord.width;
			rect._height = rect.height || outerRectCoord.height;

			// Check negative values
			rect._left = Math.max(0, rect._left);
			rect._top = Math.max(0, rect._top);
			rect._width = Math.max(1, rect._width);
			rect._height = Math.max(1, rect._height);

			// Check dimensions
			rect._left = Math.min(rect.x, outerRectCoord.width - 1); // -1 to make sure that there is an image
			rect._top = Math.min(rect.y, outerRectCoord.height - 1);
			rect._width = Math.min(rect.width, outerRectCoord.width - this._left);
			rect._height = Math.min(rect.height, outerRectCoord.height - this._top);

			// Make sure that the rect is at least one pixel by one pixel
			rect._width = Math.max(1, rect._width);
			rect._height = Math.max(1, rect._height);
		},

		/**
		 * Clones the rect
		 *
		 * @method clone
		 * @return {Rect}
		 */
		clone: function () {
			return new Rect({
				left: this.getLeft(),
				top: this.getTop(),
				width: this.getWidth(),
				height: this.getHeight()
			});
		}
	},

	{
		/**
		 * @property TYPE
		 * @type {string}
		 * @static
		 */
		TYPE: 'CONFIGURATION_ATOM_RECT'
	}
);

module.exports = Rect;
<commit_msg>Bugfix for rect<commit_after>// Copyright 2015 Yahoo! Inc.
// Copyrights licensed under the Mit License. See the accompanying LICENSE file for terms.

var Base = require('../base');

/**
 * @class Rect
 * @extends Base
 * @module Configuration
 * @submodule Atoms
 *
 * @property {int} _left
 * @property {int} _top
 * @property {int} _width
 * @property {int} _height
 */
var Rect = Base.extend(

	/**
	 * Rect constructor
	 *
	 * @param {object} options
	 * @param {int} options.left Offset from the left corner
	 * @param {int} options.top Offset from the top corner
	 * @param {int} options.width Width
	 * @param {int} options.height Height
	 * @param {int} [options.x] Offset from the left corner
	 * @param {int} [options.y] Offset from the top corner
	 * @constructor
	 */
	function (options) {
		this.__super();

		this.setLeft(options.left || options.x);
		this.setTop(options.top || options.y);
		this.setWidth(options.width);
		this.setHeight(options.height);
	},

	{
		/**
		 * Gets the offset from the left corner
		 *
		 * @method getLeft
		 * @return {int}
		 */
		getLeft: function () {
			return this._left;
		},

		/**
		 * Sets the offset from the left corner
		 *
		 * @method setLeft
		 * @param {int} value
		 */
		setLeft: function (value) {
			this._left = value;
		},

		/**
		 * Gets the offset from the top corner
		 *
		 * @method getTop
		 * @return {int}
		 */
		getTop: function () {
			return this._top;
		},

		/**
		 * Sets the offset from the top corner
		 *
		 * @method setTop
		 * @param {int} value
		 */
		setTop: function (value) {
			this._top = value;
		},

		/**
		 * Gets the width
		 *
		 * @method getWidth
		 * @return {int}
		 */
		getWidth: function () {
			return this._width;
		},

		/**
		 * Sets the width
		 *
		 * @method setWidth
		 * @param {int} value
		 */
		setWidth: function (value) {
			this._width = value;
		},

		/**
		 * Gets the height
		 *
		 * @method getHeight
		 * @return {int}
		 */
		getHeight: function () {
			return this._height;
		},

		/**
		 * Sets the height
		 *
		 * @method setHeight
		 * @param {int} value
		 */
		setHeight: function (value) {
			this._height = value;
		},

		/**
		 * Gets boundaries as rect structure
		 *
		 * @method getRect
		 * @return {{left: (int), top: (int), width: (int), height: (int)}}
		 */
		getRect: function () {
			return {
				left: this.getLeft(),
				top: this.getTop(),
				width: this.getWidth(),
				height: this.getHeight()
			};
		},

		/**
		 * Gets boundaries as coordinate structure
		 *
		 * @method getCoordinates
		 * @return {{x: (int), y: (int), width: (int), height: (int)}}
		 */
		getCoordinates: function () {
			return {
				x: this.getLeft(),
				y: this.getTop(),
				width: this.getWidth(),
				height: this.getHeight()
			};
		},

		/**
		 * Checks if a coordinate is within the bounds of the rect
		 *
		 * @method inBounds
		 * @param {int} x X-coordinate
		 * @param {int} y Y-coordinate
		 */
		inBounds: function (x, y) {
			if ((x < this.getLeft()) || (x > this.getLeft() + this.getWidth())) {
				return false;
			}
			if ((y < this.getTop()) || (y > this.getTop() + this.getHeight())) {
				return false;
			}
			return true;
		},

		/**
		 * Limits the rect coordinates to a specified rect
		 *
		 * Note:
		 *  Priority is on the x/y coordinates, and not on the size since the size will then be removed anyways.
		 *
		 * @method limitCoordinates
		 * @param {Rect} outerRect Outer rect
		 */
		limitCoordinates: function (outerRect) {

			var outerRectCoord = outerRect.getRect();

			// Set values if none given
			this._left = this._left || outerRectCoord.left;
			this._top = this._top || outerRectCoord.top;
			this._width = this._width || outerRectCoord.width;
			this._height = this._height || outerRectCoord.height;

			// Check negative values
			this._left = Math.max(0, this._left);
			this._top = Math.max(0, this._top);
			this._width = Math.max(1, this._width);
			this._height = Math.max(1, this._height);

			// Check dimensions
			this._left = Math.min(this._left, outerRectCoord.width - 1); // -1 to make sure that there is an image
			this._top = Math.min(this._top, outerRectCoord.height - 1);
			this._width = Math.min(this._width, outerRectCoord.width - this._left);
			this._height = Math.min(this._height, outerRectCoord.height - this._top);

			// Make sure that the this is at least one pixel by one pixel
			this._width = Math.max(1, this._width);
			this._height = Math.max(1, this._height);
		},

		/**
		 * Clones the rect
		 *
		 * @method clone
		 * @return {Rect}
		 */
		clone: function () {
			return new Rect({
				left: this.getLeft(),
				top: this.getTop(),
				width: this.getWidth(),
				height: this.getHeight()
			});
		}
	},

	{
		/**
		 * @property TYPE
		 * @type {string}
		 * @static
		 */
		TYPE: 'CONFIGURATION_ATOM_RECT'
	}
);

module.exports = Rect;
<|endoftext|>