<commit_before>var WinJS = require('winjs'),
  ioc = require('../ioc'),
  config = require('../config'),
  base = require('./base'),
  log = require('../log'),
  winjsHelper = require("../helper/winjs");

var _constructor = function(options) {
  base.call(this, arguments);
  this._onNavigatingBinding = this._onNavigating.bind(this);
  this._onNavigatedBinding = this._onNavigated.bind(this);
  this._onNavigateBackMessageBinding = this._onNavigateBackMessage.bind(this);
  this._onBeforeNavigateBinding = this._onBeforeNavigate.bind(this);
  this._onResizedBinding = this._onResized.bind(this);
  this._onPopStateBinding = this._onPopState.bind(this);
  this._onNavigateToMessageBinding = this._onNavigateToMessage.bind(this);
  this._lastNavigationPromise = WinJS.Promise.as();
  this.MessageService = ioc.getService("message");
  this._element = document.createElement("div");
};

var instanceMembers = {
  start: function() {
    var that = this;
    return base.prototype.start.apply(this, arguments).then(function() {
      WinJS.Navigation.addEventListener("navigating",
        that._onNavigatingBinding);
      WinJS.Navigation.addEventListener("navigated",
        that._onNavigatedBinding);
      WinJS.Navigation.addEventListener("beforenavigate",
        that._onBeforeNavigateBinding);
      that.MessageService.register("navigateToMessage", that._onNavigateToMessageBinding);
      that.MessageService.register("navigateBackMessage", that._onNavigateBackMessageBinding);
      window.addEventListener("resize", that._onResizedBinding);
      window.addEventListener("popstate", that._onPopStateBinding);
    });
  },

  _onPopState: function(event) {
    this.MessageService.send("navigateBackMessage");
  },

  _onNavigateBackMessage: function(type, args) {
    if (this.getViewModel() && this.getViewModel().getBackNavigationDisabled()) {
      log.info("NavigationService: back navigation cancelled based on current vm getBackNavigationDisabled value");
    }
    args = args || {};
    var steps = args.steps || 1;
    return WinJS.Navigation.back(steps);
  },

  _onNavigateToMessage: function(type, args) {
    var viewKey = args.viewKey;
    var state = args.state;
    var viewTemplateUri = config.get("pages:" + viewKey + ":template");
    if (viewTemplateUri) {
      var viewClassDef = ioc.getViewDef(viewKey);
      winjsHelper.pageDefine(viewKey, viewTemplateUri, viewClassDef);
      var vmInstance = ioc.getViewModel(viewKey);
      vmInstance.setKey(viewKey);
      vmInstance.setData(args.state);

      if (this.getViewModel())
        this.getViewModel().onNavigateFrom();

      if (window["history"]) {
        window.history.pushState({
          context: state,
          key: viewKey
        }, viewKey, "#" + viewKey);
      }
      WinJS.Navigation.navigate(viewTemplateUri, vmInstance);
    }
  },

  _onBeforeNavigate: function(args) {
    if (this.getViewModel() && this.getViewModel().getBackNavigationDisabled()) {
      log.info("NavigationService: back navigation cancelled based on current vm getBackNavigationDisabled value");
      args.preventDefault();
    }
  },

  _onNavigating: function(args) {
    var that = this;
    var newElement = this.createDefaultPageElement();
    this._element.appendChild(newElement);
    this._lastNavigationPromise.cancel();

    function cleanup() {
      if (that.getView() && that.getViewModel())
        that.getViewModel().dispose();

      if (args.detail.delta == -1) {
        if (that.getView())
          ioc.delViewInstance(that.getView().getViewModel().getKey(), that.getView());
        if (that.getViewModel())
          ioc.delViewModelInstance(that.getViewModel().getKey(), that.getViewModel());
      }

      if (that._element.childElementCount > 1) {
        var oldElement = that._element.firstElementChild;
        // Cleanup and remove previous element
        if (oldElement.winControl) {

          if (oldElement.winControl.unload) {
            oldElement.winControl.unload();
          }
          oldElement.winControl.dispose();
        }
        oldElement.parentNode.removeChild(oldElement);
        oldElement.innerText = "";
        WinJS.Utilities.disposeSubTree(oldElement);
      }
    }

    // TODO: archive the old view/viewModel
    this._lastNavigationPromise = WinJS.Promise.as().then(cleanup, cleanup).then(function() {
      that.MessageService.send("navigatingMessage", args);
      return WinJS.UI.Pages.render(args.detail.location,
        newElement,
        args.detail.state);
    });
    args.detail.setPromise(this._lastNavigationPromise);
  },

  _onNavigated: function() {
    this.MessageService.send("navigatedMessage");
    this.getViewModel().onNavigateTo();
  },

  _onResized: function() {
    var view = this.getView();
    if (view && view.updateLayout)
      view.updateLayout();
  },

  getRootElement: function() {
    return this._element;
  },

  setRootElement: function(val) {
    this._element = val;
  },

  createDefaultPageElement: function() {
    var element = document.createElement("div");
    element.setAttribute("dir", window.getComputedStyle(this._element, null).direction);
    element.style.position = "absolute";
    element.style.width = "100%";
    element.style.height = "100%";
    return element;
  },

  getView: function() {
    var viewElem = this.getViewElement();
    if (viewElem && viewElem.winControl)
      return viewElem.winControl
    return null;
  },

  getViewElement: function() {
    return this._element.firstElementChild;
  },

  getViewModel: function() {
    var view = this.getView();
    if (view) {
      var viewModel = view.getViewModel();
      if (viewModel)
        return viewModel;
    }
    return null;
  },

  stop: function() {
    var that = this;
    return base.prototype.start.apply(this, arguments)
      .then(function() {
        WinJS.Navigation.removeEventListener("navigating",
          that._onNavigatingBinding);
        WinJS.Navigation.removeEventListener("navigated",
          that._onNavigatedBinding);
        WinJS.Navigation.removeEventListener("beforenavigate",
          that._onBeforeNavigateBinding);
        that.MessageService.unregister("navigateToMessage", that._onNavigateToMessageBinding);
        that.MessageService.unregister("navigateBackMessage", that._onNavigateBackMessageBinding);
        window.removeEventListener("resize", that._onResizedBinding);
        window.removeEventListener("popstate", that._onPopStateBinding)

        if (this._element)
          WinJS.Utilities.disposeSubTree(this._element);
      });
  }
};

var staticMembers = {

};

module.exports = WinJS.Class.derive(base, _constructor,
  instanceMembers, staticMembers);
<commit_msg>Bugfix for vm dipose call<commit_after>var WinJS = require('winjs'),
  ioc = require('../ioc'),
  config = require('../config'),
  base = require('./base'),
  log = require('../log'),
  winjsHelper = require("../helper/winjs");

var _constructor = function(options) {
  base.call(this, arguments);
  this._onNavigatingBinding = this._onNavigating.bind(this);
  this._onNavigatedBinding = this._onNavigated.bind(this);
  this._onNavigateBackMessageBinding = this._onNavigateBackMessage.bind(this);
  this._onBeforeNavigateBinding = this._onBeforeNavigate.bind(this);
  this._onResizedBinding = this._onResized.bind(this);
  this._onPopStateBinding = this._onPopState.bind(this);
  this._onNavigateToMessageBinding = this._onNavigateToMessage.bind(this);
  this._lastNavigationPromise = WinJS.Promise.as();
  this.MessageService = ioc.getService("message");
  this._element = document.createElement("div");
};

var instanceMembers = {
  start: function() {
    var that = this;
    return base.prototype.start.apply(this, arguments).then(function() {
      WinJS.Navigation.addEventListener("navigating",
        that._onNavigatingBinding);
      WinJS.Navigation.addEventListener("navigated",
        that._onNavigatedBinding);
      WinJS.Navigation.addEventListener("beforenavigate",
        that._onBeforeNavigateBinding);
      that.MessageService.register("navigateToMessage", that._onNavigateToMessageBinding);
      that.MessageService.register("navigateBackMessage", that._onNavigateBackMessageBinding);
      window.addEventListener("resize", that._onResizedBinding);
      window.addEventListener("popstate", that._onPopStateBinding);
    });
  },

  _onPopState: function(event) {
    this.MessageService.send("navigateBackMessage");
  },

  _onNavigateBackMessage: function(type, args) {
    if (this.getViewModel() && this.getViewModel().getBackNavigationDisabled()) {
      log.info("NavigationService: back navigation cancelled based on current vm getBackNavigationDisabled value");
    }
    args = args || {};
    var steps = args.steps || 1;
    return WinJS.Navigation.back(steps);
  },

  _onNavigateToMessage: function(type, args) {
    var viewKey = args.viewKey;
    var state = args.state;
    var viewTemplateUri = config.get("pages:" + viewKey + ":template");
    if (viewTemplateUri) {
      var viewClassDef = ioc.getViewDef(viewKey);
      winjsHelper.pageDefine(viewKey, viewTemplateUri, viewClassDef);
      var vmInstance = ioc.getViewModel(viewKey);
      vmInstance.setKey(viewKey);
      vmInstance.setData(args.state);

      if (this.getViewModel())
        this.getViewModel().onNavigateFrom();

      if (window["history"]) {
        window.history.pushState({
          context: state,
          key: viewKey
        }, viewKey, "#" + viewKey);
      }
      WinJS.Navigation.navigate(viewTemplateUri, vmInstance);
    }
  },

  _onBeforeNavigate: function(args) {
    if (this.getViewModel() && this.getViewModel().getBackNavigationDisabled()) {
      log.info("NavigationService: back navigation cancelled based on current vm getBackNavigationDisabled value");
      args.preventDefault();
    }
  },

  _onNavigating: function(args) {
    var that = this;
    var newElement = this.createDefaultPageElement();
    this._element.appendChild(newElement);
    this._lastNavigationPromise.cancel();

    function cleanup() {
      if (args.detail.delta == -1) {
        if (that.getView() && that.getViewModel())
          that.getViewModel().dispose();

        if (that.getView())
          ioc.delViewInstance(that.getView().getViewModel().getKey(), that.getView());
        if (that.getViewModel())
          ioc.delViewModelInstance(that.getViewModel().getKey(), that.getViewModel());
      }

      if (that._element.childElementCount > 1) {
        var oldElement = that._element.firstElementChild;
        // Cleanup and remove previous element
        if (oldElement.winControl) {

          if (oldElement.winControl.unload) {
            oldElement.winControl.unload();
          }
          oldElement.winControl.dispose();
        }
        oldElement.parentNode.removeChild(oldElement);
        oldElement.innerText = "";
        WinJS.Utilities.disposeSubTree(oldElement);
      }
    }

    // TODO: archive the old view/viewModel
    this._lastNavigationPromise = WinJS.Promise.as().then(cleanup, cleanup).then(function() {
      that.MessageService.send("navigatingMessage", args);
      return WinJS.UI.Pages.render(args.detail.location,
        newElement,
        args.detail.state);
    });
    args.detail.setPromise(this._lastNavigationPromise);
  },

  _onNavigated: function() {
    this.MessageService.send("navigatedMessage");
    this.getViewModel().onNavigateTo();
  },

  _onResized: function() {
    var view = this.getView();
    if (view && view.updateLayout)
      view.updateLayout();
  },

  getRootElement: function() {
    return this._element;
  },

  setRootElement: function(val) {
    this._element = val;
  },

  createDefaultPageElement: function() {
    var element = document.createElement("div");
    element.setAttribute("dir", window.getComputedStyle(this._element, null).direction);
    element.style.position = "absolute";
    element.style.width = "100%";
    element.style.height = "100%";
    return element;
  },

  getView: function() {
    var viewElem = this.getViewElement();
    if (viewElem && viewElem.winControl)
      return viewElem.winControl
    return null;
  },

  getViewElement: function() {
    return this._element.firstElementChild;
  },

  getViewModel: function() {
    var view = this.getView();
    if (view) {
      var viewModel = view.getViewModel();
      if (viewModel)
        return viewModel;
    }
    return null;
  },

  stop: function() {
    var that = this;
    return base.prototype.start.apply(this, arguments)
      .then(function() {
        WinJS.Navigation.removeEventListener("navigating",
          that._onNavigatingBinding);
        WinJS.Navigation.removeEventListener("navigated",
          that._onNavigatedBinding);
        WinJS.Navigation.removeEventListener("beforenavigate",
          that._onBeforeNavigateBinding);
        that.MessageService.unregister("navigateToMessage", that._onNavigateToMessageBinding);
        that.MessageService.unregister("navigateBackMessage", that._onNavigateBackMessageBinding);
        window.removeEventListener("resize", that._onResizedBinding);
        window.removeEventListener("popstate", that._onPopStateBinding)

        if (this._element)
          WinJS.Utilities.disposeSubTree(this._element);
      });
  }
};

var staticMembers = {

};

module.exports = WinJS.Class.derive(base, _constructor,
  instanceMembers, staticMembers);
<|endoftext|>


<commit_before>/* window process */
const { FileSystemBackend } = require('stencila-node')
const remote = require('electron').remote
const path = require('path')
const fs = require('fs')
const { app } = remote

const DOCUMENTS_DIR = app.getPath('documents')
const STENCILA_LIBRARY_DIR = path.join(DOCUMENTS_DIR, 'Stencila-0.25.1')
const STENCILA_LIBRARY_FILE = path.join(STENCILA_LIBRARY_DIR, 'library.json')
const fileSystemBackend = new FileSystemBackend(STENCILA_LIBRARY_DIR)

/*
  Seeds the filesystem backend if necessary. This means that a file
  library.json gets created in STENCILA_LIBRARY_DIR if not present.

  NOTE: This is done synchronously for now. It won't take much time.
*/
function initBackend() {
  if (!fs.existsSync(STENCILA_LIBRARY_FILE)) {

    // Create the needed folders
    if (!fs.existsSync(STENCILA_LIBRARY_DIR)) {
      fs.mkdirSync(STENCILA_LIBRARY_DIR)
    }
    // Create empty library file
    fs.writeFileSync(path.join(STENCILA_LIBRARY_DIR, 'library.json'), '{}', 'utf8')

    let documentIds = Object.keys(window.GUIDES)

    let createDocument = (documentId) => {
      let html = window.GUIDES[documentId]
      return fileSystemBackend.createDocument(html)
    }

    let runTasksInSeries = documentIds.reduce(function(p, documentId) {
      return p.then(function() {
        return createDocument(documentId)
      })
    }, Promise.resolve())

    return runTasksInSeries.then(() => {
      return fileSystemBackend
    })

  } else {
    // Nothing to do - just resolve the promise
    return Promise.resolve(fileSystemBackend)
  }
}

module.exports = initBackend
<commit_msg>Fix stencila-node used<commit_after>/* window process */
const { FileSystemBackend } = require('stencila-node-0.26.0')
const remote = require('electron').remote
const path = require('path')
const fs = require('fs')
const { app } = remote

const DOCUMENTS_DIR = app.getPath('documents')
const STENCILA_LIBRARY_DIR = path.join(DOCUMENTS_DIR, 'Stencila-0.25.1')
const STENCILA_LIBRARY_FILE = path.join(STENCILA_LIBRARY_DIR, 'library.json')
const fileSystemBackend = new FileSystemBackend(STENCILA_LIBRARY_DIR)

/*
  Seeds the filesystem backend if necessary. This means that a file
  library.json gets created in STENCILA_LIBRARY_DIR if not present.

  NOTE: This is done synchronously for now. It won't take much time.
*/
function initBackend() {
  if (!fs.existsSync(STENCILA_LIBRARY_FILE)) {

    // Create the needed folders
    if (!fs.existsSync(STENCILA_LIBRARY_DIR)) {
      fs.mkdirSync(STENCILA_LIBRARY_DIR)
    }
    // Create empty library file
    fs.writeFileSync(path.join(STENCILA_LIBRARY_DIR, 'library.json'), '{}', 'utf8')

    let documentIds = Object.keys(window.GUIDES)

    let createDocument = (documentId) => {
      let html = window.GUIDES[documentId]
      return fileSystemBackend.createDocument(html)
    }

    let runTasksInSeries = documentIds.reduce(function(p, documentId) {
      return p.then(function() {
        return createDocument(documentId)
      })
    }, Promise.resolve())

    return runTasksInSeries.then(() => {
      return fileSystemBackend
    })

  } else {
    // Nothing to do - just resolve the promise
    return Promise.resolve(fileSystemBackend)
  }
}

module.exports = initBackend
<|endoftext|>


<commit_before>(function (window, $, ch) {
    'use strict';

    if (ch === undefined) {
        throw new window.Error('Expected ch namespace defined.');
    }

    /**
     * Tooltip improves the native tooltips. Tooltip uses the 'alt' and 'title' attributes to grab its content.
     * @name Tooltip
     * @class Tooltip
     * @augments ch.Floats
     * @memberOf ch
     * @param {Object} [conf] Object with configuration properties.
     * @param {Boolean} [conf.fx] Enable or disable UI effects. By default, the effects are enable.
     * @param {String} [conf.points] Sets the points where component will be positioned, specified by configuration or centered by default: "cm cm".
     * @param {String} [conf.offset] Sets the offset in pixels that component will be displaced from original position determined by points. It's specified by configuration or zero by default: "0 0".
     * @returns itself
     * @factorized
     * @see ch.Modal
     * @see ch.Layer
     * @see ch.Zoom
     * @see ch.Flaots
     * @exampleDescription Create a tooltip.
     * @example
     * var widget = $(".some-element").tooltip();
     * @exampleDescription Create a new tooltip with configuration.
     * @example
     * var widget = $("a.example").tooltip({
     *     "fx": false,
     *     "offset": "10 -10",
     *     "points": "lt rt"
     * });
     * @exampleDescription
     * Now widget is a reference to the tooltip instance controller.
     * You can set a new content by using widget like this:
     * @example
     * widget.width(300);
     */
    function Modal($el, options) {

        this.init($el, options);

        /**
         * Reference to a internal component instance, saves all the information and configuration properties.
         * @private
         * @type {Object}
         */
        var that = this;

        /**
         * Triggers when the component is ready to use (Since 0.8.0).
         * @name ch.Popover#ready
         * @event
         * @public
         * @since 0.8.0
         * @exampleDescription Following the first example, using widget as popover's instance controller:
         * @example
         * widget.on("ready",function () {
         * this.show();
         * });
         */
        window.setTimeout(function () { that.emit('ready'); }, 50);
    }

    /**
     * Private members
     */
    var parent = ch.util.inherits(Modal, ch.Popover),

        $body = $('body'),

        $underlay = $('
');

    /**
     * Public members
     */
    Modal.prototype.name = 'modal';

    Modal.prototype.constructor = Modal;

    Modal.prototype._defaults = $.extend(ch.util.clone(parent._defaults), {
        '_className': 'ch-modal ch-box-lite',
        'ariaRole': 'dialog',
        'width': '50%',
        'hiddenby': 'all',
        'reference': ch.viewport,
        'waiting': '

',
        'positioned': 'fixed'
    });

    Modal.prototype.init = function ($el, options) {
        parent.init.call(this, $el, options);
    };

    /**
     * Inner show method. Attach the component layout to the DOM tree.
     * @protected
     * @name ch.Popover#innerShow
     * @function
     * @returns itself
     */
    Modal.prototype.show = function (content) {

        if (!this._enabled) {
            return this;
        }

        var that = this,
            hiddenby = this._options.hiddenby;

        // Add to the underlay the ability to close the widget only if the closable config. allows
        if (hiddenby === 'all' || hiddenby === 'pointers-only') {
            // Allow only one click to analize the config every time
            $underlay.one(ch.onpointertap, function (event) {
                // Close underlay and execute the original hide()
                that.hide();
            });
        }

        // Append underlay element
        $underlay.css('z-index', ch.util.zIndex).appendTo($body);

        if (ch.support.fx) {
            $underlay.fadeIn();
        } else {
            $underlay.removeClass('ch-hide');
        }

        // Execute the original show()
        parent.show.call(this, content);

        // Return the instance
        return this;
    };

    /**
     * Inner hide method. Hides the component and detach it from DOM tree.
     * @protected
     * @name ch.Popover#innerHide
     * @function
     * @returns itself
     */
    Modal.prototype.hide = function () {
        // Delete the underlay element
        if (ch.support.fx) {
            $underlay.fadeOut('normal', function () {
                $underlay.remove(null, true);
            });
        } else {
            $underlay.addClass('ch-hide').remove(null, true);
        }
        // Execute the original hide()
        parent.hide.call(this);
        // Return the instance
        return this;
    };

    /**
     * Factory
     */
    ch.factory(Modal, parent._normalizeOptions);

}(this, this.ch.$, this.ch));
<commit_msg>GH-887 Modal: Define in init one method to show and one to hide the underlay depending on the ability and the request to have effects.<commit_after>(function (window, $, ch) {
    'use strict';

    if (ch === undefined) {
        throw new window.Error('Expected ch namespace defined.');
    }

    /**
     * Tooltip improves the native tooltips. Tooltip uses the 'alt' and 'title' attributes to grab its content.
     * @name Tooltip
     * @class Tooltip
     * @augments ch.Floats
     * @memberOf ch
     * @param {Object} [conf] Object with configuration properties.
     * @param {Boolean} [conf.fx] Enable or disable UI effects. By default, the effects are enable.
     * @param {String} [conf.points] Sets the points where component will be positioned, specified by configuration or centered by default: "cm cm".
     * @param {String} [conf.offset] Sets the offset in pixels that component will be displaced from original position determined by points. It's specified by configuration or zero by default: "0 0".
     * @returns itself
     * @factorized
     * @see ch.Modal
     * @see ch.Layer
     * @see ch.Zoom
     * @see ch.Flaots
     * @exampleDescription Create a tooltip.
     * @example
     * var widget = $(".some-element").tooltip();
     * @exampleDescription Create a new tooltip with configuration.
     * @example
     * var widget = $("a.example").tooltip({
     *     "fx": false,
     *     "offset": "10 -10",
     *     "points": "lt rt"
     * });
     * @exampleDescription
     * Now widget is a reference to the tooltip instance controller.
     * You can set a new content by using widget like this:
     * @example
     * widget.width(300);
     */
    function Modal($el, options) {

        this.init($el, options);

        /**
         * Reference to a internal component instance, saves all the information and configuration properties.
         * @private
         * @type {Object}
         */
        var that = this;

        /**
         * Triggers when the component is ready to use (Since 0.8.0).
         * @name ch.Popover#ready
         * @event
         * @public
         * @since 0.8.0
         * @exampleDescription Following the first example, using widget as popover's instance controller:
         * @example
         * widget.on("ready",function () {
         * this.show();
         * });
         */
        window.setTimeout(function () { that.emit('ready'); }, 50);
    }

    /**
     * Private members
     */
    var parent = ch.util.inherits(Modal, ch.Popover),
        $body = $('body'),
        $underlay = $('
');

    /**
     * Public members
     */
    Modal.prototype.name = 'modal';

    Modal.prototype.constructor = Modal;

    Modal.prototype._defaults = $.extend(ch.util.clone(parent._defaults), {
        '_className': 'ch-modal ch-box-lite',
        'ariaRole': 'dialog',
        'width': '50%',
        'hiddenby': 'all',
        'reference': ch.viewport,
        'waiting': '

',
        'positioned': 'fixed'
    });

    Modal.prototype.init = function ($el, options) {

        parent.init.call(this, $el, options);

        // Determine a specific Show and Hide for the underlay, defined
        // by the ability (and user's request) to have effects or not
        if (ch.support.fx && this._options.fx !== false && this._options.fx !== 'none') {
            this._showUnderlay = function () {
                $underlay.css('z-index', ch.util.zIndex).appendTo($body).fadeIn();
            };
            this._hideUnderlay = function () {
                $underlay.fadeOut('normal', function () { $underlay.remove(null, true); });
            };
        } else {
            this._showUnderlay = function () {
                $underlay.css('z-index', ch.util.zIndex).appendTo($body).removeClass('ch-hide');
            };

            this._hideUnderlay = function () {
                $underlay.addClass('ch-hide').remove(null, true);
            };
        }
    };

    /**
     * Inner show method. Attach the component layout to the DOM tree.
     * @protected
     * @name ch.Popover#innerShow
     * @function
     * @returns itself
     */
    Modal.prototype.show = function (content) {

        if (!this._enabled) {
            return this;
        }

        var that = this;

        // Add to the underlay the ability to close the widget only if the closable config. allows
        if (this._options.hiddenby === 'all' || this._options.hiddenby === 'pointers-only') {
            // Allow only one click to analize the config every time
            $underlay.one(ch.onpointertap, function () {
                that.hide();
            });
        }

        // Show the underlay
        this._showUnderlay();
        // Execute the original show()
        parent.show.call(this, content);
        // Return the instance
        return this;
    };

    /**
     * Inner hide method. Hides the component and detach it from DOM tree.
     * @protected
     * @name ch.Popover#innerHide
     * @function
     * @returns itself
     */
    Modal.prototype.hide = function () {
        // Delete the underlay listener
        $underlay.off(ch.onpointertap);
        // Hide the underlay element
        this._hideUnderlay();
        // Execute the original hide()
        parent.hide.call(this);
        // Return the instance
        return this;
    };

    /**
     * Factory
     */
    ch.factory(Modal, parent._normalizeOptions);

}(this, this.ch.$, this.ch));
<|endoftext|>


<commit_before>(function (factory) {
    var global = window;
    var $ = global.$ || global.jQuery;
    var _ = global._ || global.lodash;

    if (!$) throw new Error('SirTrevorAdapter requires jQuery');
    if (!_) throw new Error('SirTrevorAdapter requires lodash');

    global.SirTrevorAdapter = factory($, _);
} (function($, _) {
    'use strict';
    /** @class SirTrevorAdapter */

    /**
     * The minimun representation for a SirTrevor data instance.
     * @typedef {Object} SirTrevorData
     * @property {String} type - The type of this instance
     * @property {Object} data - The data that represents the object type.
     */

    /**
     * @typedef {Object} SirTrevorAdapterTemplates
     * Each key for this template should correspond to a SirTrevorData type. The value can be
     * a String that will be interpolated via `lodash.template` or a `function (data)` that
     * recives as first argument the data of the SirTrevorData.
     */
    var templates = {
        'text': '<%= text %>',
        'quote': '<quote><%= text %></quote>',
        'image': '
<img src="<%- src %>
', // Still needs work (Backend implementation)
        'heading': '
<%= text %>
',
        'list': '
<% _.each(listItems, function(e) { %>
<%- e %>
<% }) %>
',
        'tweet': '

', // TODO
        'video': '

', // TODO
        'button': '<%= text %>',
        'widget': '<%= text %>'
    }

    /**
     * @typedef {Object} SirTrevorAdapterConfig
     * @property {String} elementEnclosingTag - Defines the HTML tag to be used arround every SirTrevorData that is serialized by this instance.
     * @property {String} elementClass - Defines the class to be added to the HTML added arround every SirTrevorData serialized by this instance.
     * @property {boolean} addElementTypeClass - Determines if a type specific class should be added alongside the `elementClass`.
     * @property {String} attrName - Defines the attribute name added to the HTML for each SirTrevorData. Note this will be always prepended by `data-`
     * @property {SirTrevorAdapterTemplates} @see SirTrevorAdapterTemplates
     */
    var defaultConfig = {
        elementEnclosingTag: 'div',
        elementClass : 'st-render',
        addElementTypeClass : true,
        attrName: 'st',
    }

    /**
     * Creates a new instance of SirTrevorAdapter. Each instance has its own config and templates.
     * @constructor
     * @param {SirTrevorAdapterConfig}
     * @see SirTrevorAdapterConfig
     * @see SirTrevorAdapterTemplates
     */
    var SirTrevorAdapter = function(config) {
        config = config || {};
        this.templates = _.defaults(config.templates || {}, templates);

        delete config.template;
        this.config = _.defaults(defaultConfig, config);
    };

    /**
     * @private
     * @param {Mixed} obj - The object of study
     * @returns {boolean} {true} if the given obj is a valid {SirTrevorData}; or {false} otherwise
     * @requires lodash
     * @memberof SirTrevorAdapter
     */
    SirTrevorAdapter.prototype._isSirTrevorData = function(obj) {
        return obj && obj.type && obj.data && _.isObject(obj.data);
    };

    /**
     * @public
     * @desc Finds the HTML template for the type given and compiles it with the data provided.
     * @param {String} type - The type of template you want to render.
     * @param {Object} data - The data to be used as template replacements.
     * @returns {String} The compiled HTML for the combination of arguments given. If a not valid type is given an empty String is returned.
     * @memberof SirTrevorAdapter
     * @requires lodash
    */
    SirTrevorAdapter.prototype.renderType = function(type, data) {
        var template = this.templates[type];

        if (!template) {
            console.error('No template for type ' + type);
            return '';
        }

        if (_.isFunction(template))
            return template(data);
        else
            return _.template(template, data);
    }

    /**
     * Given a SirTrevor object this function returns the HTML that will be able to serve as a representation
     * of the given object and also it is an HTML that this library is able to convert back to the original
     * JSON representation
     * @param {Object} obj - An instance of SirTrevor data, this must contain type and data properties.
     * @returns {String} The HTML generated for the given object.
     * @memberof SirTrevorAdapter
     * @requires jQuery
     */
    SirTrevorAdapter.prototype.map = function(obj) {
        if (!this._isSirTrevorData(obj)) {
            console.error(JSON.stringify(obj) + ' is not a valid SirTrevor object');
            return '';
        }

        var innerHTML = this.renderType(obj.type, obj.data);
        var classes = [ this.config.elementClass ];
        // If the config is set, also add the element type associated class
        if (this.config.addElementTypeClass)
            classes.push (this.config.elementClass + '-' + obj.type);

        var container = $('<' + this.config.elementEnclosingTag + '>', { class: classes.join(' ') });
        container.attr('data-' + this.config.attrName, JSON.stringify(obj));
        container.html(innerHTML);
        return container[0].outerHTML;
    }

    /**
     * Given a collection (or a single) of SirTrevorData, the function returns an HTML that contains
     * the rendered view for each element warped arround a single DOM element.
     * @param {SirTrevorData | SirTrevorData[]} json - The data to be serialized to HTML.
     * @returns {String} The HTML representation of each element. Also contains enough data for recover the original JSON afterwards.
     * @memberof SirTrevorAdapter
     * @requires lodash
     */
    SirTrevorAdapter.prototype.toHTML = function(json) {
        if (!_.isArray(json))
            json = [ json ];
        var container = $('<' + this.config.elementEnclosingTag + '>', { class: this.config.elementClass + '-container' });
        return '
' + json.map(this.map, this).join('\n') + '
';
    }
    SirTrevorAdapter.prototype.fromJSON = SirTrevorAdapter.prototype.toHTML;

    /**
     * Given an HTML generated by an instance of SirTrevorAdapter, this function returns the original JSON
     * used to generate the given HTML.
     * @param {String} html - The HTML to be parsed.
     * @memberof SirTrevorAdapter
     * @returns {SirTrevorData[]} The collection of SirTrevor Data recovered from the HTML.
     */
    SirTrevorAdapter.prototype.toJSON = function(html) {
        var self = this;
        var doms = $(html);
        var $doms = $(doms);
        var result = [];
        $doms.find('.st-render').each(function (i, obj) {
            result.push($(obj).data(self.config.attrName));
        });
        return result;
    }
    SirTrevorAdapter.prototype.fromHTML = SirTrevorAdapter.prototype.toJSON;

    return SirTrevorAdapter;
}))<commit_msg>Added  video adapter from the SirTrevor video block<commit_after>(function (factory) {
    var global = window;
    var $ = global.$ || global.jQuery;
    var _ = global._ || global.lodash;

    if (!$) throw new Error('SirTrevorAdapter requires jQuery');
    if (!_) throw new Error('SirTrevorAdapter requires lodash');

    global.SirTrevorAdapter = factory($, _);
} (function($, _) {
    'use strict';
    /** @class SirTrevorAdapter */

    /**
     * The minimun representation for a SirTrevor data instance.
     * @typedef {Object} SirTrevorData
     * @property {String} type - The type of this instance
     * @property {Object} data - The data that represents the object type.
     */

    /**
     * @typedef {Object} SirTrevorAdapterTemplates
     * Each key for this template should correspond to a SirTrevorData type. The value can be
     * a String that will be interpolated via `lodash.template` or a `function (data)` that
     * recives as first argument the data of the SirTrevorData.
     */
    var templates = {
        text: '<%= text %>',
        quote: '<quote><%= text %></quote>',
        image: '
<img src="<%- src %>
', // Still needs work (Backend implementation)
        heading: '
<%= text %>
',
        list: '
<% _.each(listItems, function(e) { %>
<%- e %>
<% }) %>
',
        tweet: '

', // TODO
        button: '<%= text %>',
        widget: '<%= text %>',
        video: function(data) {

            // more providers at https://gist.github.com/jeffling/a9629ae28e076785a14f
            var providers = {
                vimeo: {
                    regex: /(?:http[s]?:\/\/)?(?:www.)?vimeo\.co(?:.+(?:\/)([^\/].*)+$)/,
                    html: "<iframe src=\"<%= protocol %>//player.vimeo.com/video/<%= remote_id %>?title=0&byline=0\" width=\"580\" height=\"320\" frameborder=\"0\">"
                },
                youtube: {
                    regex: /^.*(?:(?:youtu\.be\/)|(?:youtube\.com)\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*)/,
                    html: "<iframe src=\"<%= protocol %>//www.youtube.com/embed/<%= remote_id %>\" width=\"580\" height=\"320\" frameborder=\"0\" allowfullscreen>"
                }
            };

            if (!providers.hasOwnProperty(data.source))
                return "";

            var source = providers[data.source];

            var protocol = window.location.protocol === "file:" ?
              "http:" : window.location.protocol;

            return _.template(source.html, {
                protocol: protocol,
                remote_id: data.remote_id
            });
        },
    }

    /**
     * @typedef {Object} SirTrevorAdapterConfig
     * @property {String} elementEnclosingTag - Defines the HTML tag to be used arround every SirTrevorData that is serialized by this instance.
     * @property {String} elementClass - Defines the class to be added to the HTML added arround every SirTrevorData serialized by this instance.
     * @property {boolean} addElementTypeClass - Determines if a type specific class should be added alongside the `elementClass`.
     * @property {String} attrName - Defines the attribute name added to the HTML for each SirTrevorData. Note this will be always prepended by `data-`
     * @property {SirTrevorAdapterTemplates} @see SirTrevorAdapterTemplates
     */
    var defaultConfig = {
        elementEnclosingTag: 'div',
        elementClass : 'st-render',
        addElementTypeClass : true,
        attrName: 'st',
    }

    /**
     * Creates a new instance of SirTrevorAdapter. Each instance has its own config and templates.
     * @constructor
     * @param {SirTrevorAdapterConfig}
     * @see SirTrevorAdapterConfig
     * @see SirTrevorAdapterTemplates
     */
    var SirTrevorAdapter = function(config) {
        config = config || {};
        this.templates = _.defaults(config.templates || {}, templates);

        delete config.template;
        this.config = _.defaults(defaultConfig, config);
    };

    /**
     * @private
     * @param {Mixed} obj - The object of study
     * @returns {boolean} {true} if the given obj is a valid {SirTrevorData}; or {false} otherwise
     * @requires lodash
     * @memberof SirTrevorAdapter
     */
    SirTrevorAdapter.prototype._isSirTrevorData = function(obj) {
        return obj && obj.type && obj.data && _.isObject(obj.data);
    };

    /**
     * @public
     * @desc Finds the HTML template for the type given and compiles it with the data provided.
     * @param {String} type - The type of template you want to render.
     * @param {Object} data - The data to be used as template replacements.
     * @returns {String} The compiled HTML for the combination of arguments given. If a not valid type is given an empty String is returned.
     * @memberof SirTrevorAdapter
     * @requires lodash
    */
    SirTrevorAdapter.prototype.renderType = function(type, data) {
        var template = this.templates[type];

        if (!template) {
            console.error('No template for type ' + type);
            return '';
        }

        if (_.isFunction(template))
            return template(data);
        else
            return _.template(template, data);
    }

    /**
     * Given a SirTrevor object this function returns the HTML that will be able to serve as a representation
     * of the given object and also it is an HTML that this library is able to convert back to the original
     * JSON representation
     * @param {Object} obj - An instance of SirTrevor data, this must contain type and data properties.
     * @returns {String} The HTML generated for the given object.
     * @memberof SirTrevorAdapter
     * @requires jQuery
     */
    SirTrevorAdapter.prototype.map = function(obj) {
        if (!this._isSirTrevorData(obj)) {
            console.error(JSON.stringify(obj) + ' is not a valid SirTrevor object');
            return '';
        }

        var innerHTML = this.renderType(obj.type, obj.data);
        var classes = [ this.config.elementClass ];
        // If the config is set, also add the element type associated class
        if (this.config.addElementTypeClass)
            classes.push (this.config.elementClass + '-' + obj.type);

        var container = $('<' + this.config.elementEnclosingTag + '>', { class: classes.join(' ') });
        container.attr('data-' + this.config.attrName, JSON.stringify(obj));
        container.html(innerHTML);
        return container[0].outerHTML;
    }

    /**
     * Given a collection (or a single) of SirTrevorData, the function returns an HTML that contains
     * the rendered view for each element warped arround a single DOM element.
     * @param {SirTrevorData | SirTrevorData[]} json - The data to be serialized to HTML.
     * @returns {String} The HTML representation of each element. Also contains enough data for recover the original JSON afterwards.
     * @memberof SirTrevorAdapter
     * @requires lodash
     */
    SirTrevorAdapter.prototype.toHTML = function(json) {
        if (!_.isArray(json))
            json = [ json ];
        var container = $('<' + this.config.elementEnclosingTag + '>', { class: this.config.elementClass + '-container' });
        return '
' + json.map(this.map, this).join('\n') + '
';
    }
    SirTrevorAdapter.prototype.fromJSON = SirTrevorAdapter.prototype.toHTML;

    /**
     * Given an HTML generated by an instance of SirTrevorAdapter, this function returns the original JSON
     * used to generate the given HTML.
     * @param {String} html - The HTML to be parsed.
     * @memberof SirTrevorAdapter
     * @returns {SirTrevorData[]} The collection of SirTrevor Data recovered from the HTML.
     */
    SirTrevorAdapter.prototype.toJSON = function(html) {
        var self = this;
        var doms = $(html);
        var $doms = $(doms);
        var result = [];
        $doms.find('.st-render').each(function (i, obj) {
            result.push($(obj).data(self.config.attrName));
        });
        return result;
    }
    SirTrevorAdapter.prototype.fromHTML = SirTrevorAdapter.prototype.toJSON;

    return SirTrevorAdapter;
}))<|endoftext|>


<commit_before>var path = require('path');
var webpack = require('webpack');

module.exports = {
  devtool: 'cheap-module-eval-source-map',
  entry: [
    // 'eventsource-polyfill',
    'webpack-hot-middleware/client',
    './demo/container',
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/static/',
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
  ],
  module: {
    loaders: [
      {
      test: /\.js$/,
      loaders: ['babel'],
      },
      {
        test: /\.css/,
        loader: 'style!css',
      },
      {
        test: /\.(png|jpg)$/,
        loader: 'url',
      },
    ],

  },
};
<commit_msg>fix webpack sourcemap<commit_after>var path = require('path');
var webpack = require('webpack');

module.exports = {
  devtool: 'source-map',
  entry: [
    // 'eventsource-polyfill',
    'webpack-hot-middleware/client',
    './demo/container',
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/static/',
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
  ],
  module: {
    loaders: [
      {
      test: /\.js$/,
      loaders: ['babel'],
      },
      {
        test: /\.css/,
        loader: 'style!css',
      },
      {
        test: /\.(png|jpg)$/,
        loader: 'url',
      },
    ],

  },
};
<|endoftext|>


<commit_before>// circleci.js
// https://circleci.com/docs/1.0/configuration/#notify
// ========
const BaseProvider = require('../util/BaseProvider');

class CircleCi extends BaseProvider {
    static getName() {
        return 'CircleCi';
    }

    async parseData(req) {
        this.payload.setEmbedColor(0x000000);
        this.payload.addEmbed({
            title: `Build #${this.body.payload.build_num}`,
            url: this.body.payload.build_url,
            author: {
                name: `${this.body.payload.reponame}:${this.body.payload.branch}`,
                icon_url: `https://github.com/${this.body.payload.committer_name}.png`
            },
            description: `[\`${this.body.payload.vcs_revision.slice(0,7)}\`](${this.body.payload.compare}) : ${this.body.payload.subject} - ${this.body.payload.committer_name}\n\`Outcome\`: ${this.body.payload.outcome}`
        });
    }
}

module.exports = CircleCi;<commit_msg>embed color to match color used in circleci logo<commit_after>// circleci.js
// https://circleci.com/docs/1.0/configuration/#notify
// ========
const BaseProvider = require('../util/BaseProvider');

class CircleCi extends BaseProvider {
    static getName() {
        return 'CircleCi';
    }

    async parseData(req) {
        this.payload.setEmbedColor('#343433');
        this.payload.addEmbed({
            title: `Build #${this.body.payload.build_num}`,
            url: this.body.payload.build_url,
            author: {
                name: `${this.body.payload.reponame}:${this.body.payload.branch}`,
                icon_url: `https://github.com/${this.body.payload.committer_name}.png`
            },
            description: `[\`${this.body.payload.vcs_revision.slice(0,7)}\`](${this.body.payload.compare}) : ${this.body.payload.subject} - ${this.body.payload.committer_name}\n\`Outcome\`: ${this.body.payload.outcome}`
        });
    }
}

module.exports = CircleCi;<|endoftext|>


<commit_before>"use strict";

var uniq = require('uniq');

var printFloat = function printFloat (v) {
    return (v === v|0 ? v.toPrecision(2) : v.toString(10));
};

var generateComment = function generateComment (what, rule, outOfBoundValue) {
    var comments = [
        '/**',
        ' * ' + what + ' generated by cellular-automata-voxel-shader 0.2.1',
        ' * ',
        ' * Rule : ' + rule.ruleString,
        ' * Out of bound value : ' + outOfBoundValue,
        ' */'
    ];

    return comments.join('\n');
};

var generateUniformsAndConstants = function generateUniformsAndConstants () {
    return [
        '// console command',
        '// \'xs [iterations] shadername\' : e.g. \'xs 20 shadername\'',
        '',
        '// shader inputs',
        '// uniform vec3    iVolumeSize;    // volume size [1-126]',
        '// uniform float   iColorIndex;    // current color index [1-255]',
        '// uniform vec3    iMirror;        // current mirror mode [0-1]',
        '// uniform vec3    iAxis;          // current axis mode [0-1]',
        '// uniform float   iFrame;         // current frame',
        '// uniform float   iArgs[8];       // user args',
        '',
        '// built-in functions',
        '// float voxel(vec3 v);'
    ].join('\n')
};

var generateGetVoxelGlsl = function generateGetVoxelGlsl (outOfBoundValue) {
    outOfBoundValue = outOfBoundValue || 0;

    if (outOfBoundValue === 'wrap') {
        return [
            'int getVoxel(const in vec3 currentPos, const in vec3 add) {',
            '  vec3 voxelPos = mod((currentPos + add), iVolumeSize);',
            '  return int(voxel(voxelPos));',
            '}'
        ].join('\n');
    } else if(outOfBoundValue === 'clamp') {
        return [
            'int getVoxel(const in vec3 currentPos, const in vec3 add) {',
            '  vec3 voxelPos = (currentPos + add) ;',
            '  voxelPos = clamp(voxelPos, vec3(0.), iVolumeSize - vec3(1.));',
            '  return int(voxel(voxelPos));',
            '}'
        ].join('\n');
    } else {
        return [
            'int getVoxel(const in vec3 currentPos, const in vec3 add) {',
            '  vec3 voxelPos = (currentPos + add) ;',
            '  if(voxelPos.x < 0. || voxelPos.y < 0. || voxelPos.z < 0. || voxelPos.x >= iVolumeSize.x || voxelPos.y >= iVolumeSize.y || voxelPos.z >= iVolumeSize.z) {',
            '    return ' + outOfBoundValue + ';',
            '  } else {',
            '    return int(voxel(voxelPos));',
            '  }',
            '}'
        ].join('\n');
    }
};

var generateGetNeighbourhood = function (neighbourhood) {
    var glsl = [
        'int getNeighbourhood (const in vec3 currentPos) {',
        '  int sum = 0;',
        ''
    ];

    for (var i = 0; i < neighbourhood.length; i++) {
        var neighbour = neighbourhood[i];
        glsl.push('  sum += getVoxel(currentPos, vec3(' + printFloat(neighbour[0]) + ', ' + printFloat(neighbour[1]) + ', ' + printFloat(neighbour[2]) + ')) > 0 ? 1 : 0;');
    }

    glsl.push('', '  return sum;', '}');

    return glsl.join('\n');
};

var generateGetNeighbourhoodSum = function (neighbourhood) {
    var glsl = [
        'int getNeighbourhoodSum (const in vec3 currentPos) {',
        '  int sum = 0;',
        ''
    ];

    for (var i = 0; i < neighbourhood.length; i++) {
        var neighbour = neighbourhood[i];
        glsl.push('  sum += getVoxel(currentPos, vec3(' + printFloat(neighbour[0]) + ', ' + printFloat(neighbour[1]) + ', ' + printFloat(neighbour[2]) + '));');
    }

    glsl.push('', '  return sum;', '}');

    return glsl.join('\n');
};

var generateGetNeighbourhoodCond = function (neighbourhood) {
    var glsl = [
        'int getNeighbourhoodCond (const in vec3 currentPos, const in int desiredValue) {',
        '  int sum = 0;',
        ''
    ];

    for (var i = 0; i < neighbourhood.length; i++) {
        var neighbour = neighbourhood[i];
        glsl.push('  sum += getVoxel(currentPos, vec3(' + printFloat(neighbour[0]) + ', ' + printFloat(neighbour[1]) + ', ' + printFloat(neighbour[2]) + ')) == desiredValue ? 1 : 0;');
    }

    glsl.push('', '  return sum;', '}');

    return glsl.join('\n');
};

var generateNeighbourhoodGlsl = function generateNeighbourhoodGlsl (neighbourhood) {
    var glsl = [
        generateGetNeighbourhood(neighbourhood),
        '',
        generateGetNeighbourhoodSum(neighbourhood),
        '',
        generateGetNeighbourhoodCond(neighbourhood)
    ];

    return glsl.join('\n');
};

var generateEqualityCheck = function generateEqualityCheck (values, variable) {
    var checkString = [],
        groupedValues = [],
        previousValue = null,
        i;

    variable = variable || 'sum';

    if (values && values.length) {
        values.sort(function(a, b) {
            return a - b;
        });

        uniq(values, null, true);

        for (i = 0; i < values.length; i++) {
            if (previousValue === values[i] - 1) {
                groupedValues[groupedValues.length - 1].push(values[i]);
            } else {
                groupedValues.push([values[i]]);
            }

            previousValue = values[i];
        }

        for (i = 0; i < groupedValues.length; i++) {
            if (groupedValues[i].length > 1) {
                checkString.push('(' + variable + ' >= ' + groupedValues[i][0] + ' && ' + variable + ' <= ' + groupedValues[i][groupedValues[i].length - 1] + ')');
            } else {
                checkString.push(variable + ' == ' + groupedValues[i][0]);
            }
        }
    } else {
        checkString.push('false');
    }

    return checkString.join(' || ');
};

var generateProcessGlslGenerations = function generateProcessGlslGenerations (stateCount, survival, birth) {
    var glsl = [
        'int process(const in int currentValue, const in vec3 position) {',
        '  int sum = getNeighbourhoodCond(position, 1);',
        '  if (currentValue == 0 && (' + generateEqualityCheck(birth) + ')) {',
        '    return 1;',
        '  } else if (currentValue == 1 && (' + generateEqualityCheck(survival) + ')) {',
        '    return 1;',
        '  } else if (currentValue > 0) {',
        '    return int(mod(float(currentValue + 1), ' + printFloat(stateCount) + '));',
        '  }',
        '  return 0;',
        '}'
    ];

    return glsl.join('\n');
};

var generateProcessGlslLife = function generateProcessGlslLife (survival, birth) {
    var glsl = [
        'int process(const in int currentValue, const in vec3 position) {',
        '  int sum = getNeighbourhood(position);',
        '  if (currentValue == 0 && (' + generateEqualityCheck(birth) + ')) {',
        '    return 1;',
        '  } else if (currentValue > 0 && (' + generateEqualityCheck(survival) + ')) {',
        '    return 1;',
        '  }',
        '  return 0;',
        '}'
    ];

    return glsl.join('\n');
};

var generateProcessGlslVote = function generateProcessGlslVote (votes) {
    var glsl = [
        'int process(const in int currentValue, const in vec3 position) {',
        '  int sum = getNeighbourhood(position) + (currentValue > 0 ? 1 : 0);',
        '  if (' + generateEqualityCheck(votes) + ') {',
        '    return 1;',
        '  }',
        '  return 0;',
        '}'
    ];

    return glsl.join('\n');
};

var generateProcessGlslLuky = function generateProcessGlslLuky (lowSurvival, highSurvival, lowBirth, highBirth) {
    var glsl = [
        'int process(const in int currentValue, const in vec3 position) {',
        '  int sum = getNeighbourhood(position);',
        '  if (currentValue == 0 && sum >= ' + lowBirth + ' && sum <= ' + highBirth + ') {',
        '    return 1;',
        '  } else if (currentValue > 0 && sum >= ' + lowSurvival + ' && sum <= ' + highSurvival + ') {',
        '    return 1;',
        '  }',
        '  return 0;',
        '}'
    ];

    return glsl.join('\n');
};

var generateProcessGlslNluky = function generateProcessGlslNluky (stateCount, lowSurvival, highSurvival, lowBirth, highBirth) {
    var glsl = [
        'int process(const in int currentValue, const in vec3 position) {',
        '  int sum = getNeighbourhoodCond(position, 1);',
        '  if (currentValue == 0 && sum >= ' + lowBirth + ' && sum <= ' + highBirth + ') {',
        '    return 1;',
        '  } else if (currentValue == 1 && sum >= ' + lowSurvival + ' && sum <= ' + highSurvival + ') {',
        '    return 1;',
        '  } else if (currentValue == 1) {',
        '    return ' + (2 % (2 + stateCount * 2)) + ';',
        '  } else if (currentValue >= 2) {',
        '    return int(mod(float(currentValue + 2), ' + printFloat(2 + stateCount * 2) + '));',
        '  }',
        '  return 0;',
        '}'
    ];

    return glsl.join('\n');
};

var generateProcessGlslCyclic = function generateProcessGlslCyclic (stateCount, threshold, greenbergHastingsModel) {
    var glsl = [
        'int process(const in int currentValue, const in vec3 position) {',
        '  int nextValue = int(mod(float(currentValue + 1), ' + printFloat(stateCount) + '));',
        '  int sum = getNeighbourhoodCond(position, nextValue);',
        '  if (sum >= ' + threshold + (greenbergHastingsModel ? ' || currentValue > 0' : '') + ') {',
        '    return nextValue;',
        '  }',
        '  return currentValue;',
        '}'
    ];

    return glsl.join('\n');
};

var generateProcessGlsl = function generateProcessGlsl (rule) {
    /*
     // debug process function
     var glsl = [
     'float process(const float currentValue, const int sum) {',
     '  return float(sum) / 255.;',
     '}'
     ];

     return glsl.join('\n');
     */

    if (rule.ruleFormat === 'life' || rule.ruleFormat === 'extended-life') {
        return generateProcessGlslLife(rule.survival, rule.birth);
    } else if (rule.ruleFormat === 'generations' || rule.ruleFormat === 'extended-generations') {
        return generateProcessGlslGenerations(rule.stateCount, rule.survival, rule.birth);
    } else if (rule.ruleFormat === 'vote') {
        return generateProcessGlslVote(rule.vote);
    } else if (rule.ruleFormat === 'luky') {
        return generateProcessGlslLuky(rule.lowSurvival, rule.highSurvival, rule.lowBirth, rule.highBirth);
    } else if (rule.ruleFormat === 'nluky') {
        return generateProcessGlslNluky(rule.stateCount, rule.lowSurvival, rule.highSurvival, rule.lowBirth, rule.highBirth);
    } else if (rule.ruleFormat === 'cyclic') {
        return generateProcessGlslCyclic(rule.stateCount, rule.threshold, rule.greenbergHastingsModel);
    }

    throw new Error('Unsupported ruleFormat : ' + rule.ruleFormat);
};

var generateGlsl = function generateGlsl (rule, neighbourhood, outOfBoundValue) {
    var glsl = [
        generateComment('Voxel Shader for MagicaVoxel 0.97.1', rule, outOfBoundValue),
        '',
        generateUniformsAndConstants(),
        '',
        generateGetVoxelGlsl(outOfBoundValue),
        '',
        generateNeighbourhoodGlsl(neighbourhood),
        '',
        generateProcessGlsl(rule),
        '',
        'float map(vec3 v) {',
        '  int currentValue = int(voxel(v));',
        '  return float(process(currentValue, v));',
        '}'
    ];

    return glsl.join('\n')
};

module.exports = generateGlsl;
<commit_msg>handle parenthesis in generateEqualityCheck, dont use any if there is only one statement<commit_after>"use strict";

var uniq = require('uniq');

var printFloat = function printFloat (v) {
    return (v === v|0 ? v.toPrecision(2) : v.toString(10));
};

var generateComment = function generateComment (what, rule, outOfBoundValue) {
    var comments = [
        '/**',
        ' * ' + what + ' generated by cellular-automata-voxel-shader 0.2.1',
        ' * ',
        ' * Rule : ' + rule.ruleString,
        ' * Out of bound value : ' + outOfBoundValue,
        ' */'
    ];

    return comments.join('\n');
};

var generateUniformsAndConstants = function generateUniformsAndConstants () {
    return [
        '// console command',
        '// \'xs [iterations] shadername\' : e.g. \'xs 20 shadername\'',
        '',
        '// shader inputs',
        '// uniform vec3    iVolumeSize;    // volume size [1-126]',
        '// uniform float   iColorIndex;    // current color index [1-255]',
        '// uniform vec3    iMirror;        // current mirror mode [0-1]',
        '// uniform vec3    iAxis;          // current axis mode [0-1]',
        '// uniform float   iFrame;         // current frame',
        '// uniform float   iArgs[8];       // user args',
        '',
        '// built-in functions',
        '// float voxel(vec3 v);'
    ].join('\n')
};

var generateGetVoxelGlsl = function generateGetVoxelGlsl (outOfBoundValue) {
    outOfBoundValue = outOfBoundValue || 0;

    if (outOfBoundValue === 'wrap') {
        return [
            'int getVoxel(const in vec3 currentPos, const in vec3 add) {',
            '  vec3 voxelPos = mod((currentPos + add), iVolumeSize);',
            '  return int(voxel(voxelPos));',
            '}'
        ].join('\n');
    } else if(outOfBoundValue === 'clamp') {
        return [
            'int getVoxel(const in vec3 currentPos, const in vec3 add) {',
            '  vec3 voxelPos = (currentPos + add) ;',
            '  voxelPos = clamp(voxelPos, vec3(0.), iVolumeSize - vec3(1.));',
            '  return int(voxel(voxelPos));',
            '}'
        ].join('\n');
    } else {
        return [
            'int getVoxel(const in vec3 currentPos, const in vec3 add) {',
            '  vec3 voxelPos = (currentPos + add) ;',
            '  if(voxelPos.x < 0. || voxelPos.y < 0. || voxelPos.z < 0. || voxelPos.x >= iVolumeSize.x || voxelPos.y >= iVolumeSize.y || voxelPos.z >= iVolumeSize.z) {',
            '    return ' + outOfBoundValue + ';',
            '  } else {',
            '    return int(voxel(voxelPos));',
            '  }',
            '}'
        ].join('\n');
    }
};

var generateGetNeighbourhood = function (neighbourhood) {
    var glsl = [
        'int getNeighbourhood (const in vec3 currentPos) {',
        '  int sum = 0;',
        ''
    ];

    for (var i = 0; i < neighbourhood.length; i++) {
        var neighbour = neighbourhood[i];
        glsl.push('  sum += getVoxel(currentPos, vec3(' + printFloat(neighbour[0]) + ', ' + printFloat(neighbour[1]) + ', ' + printFloat(neighbour[2]) + ')) > 0 ? 1 : 0;');
    }

    glsl.push('', '  return sum;', '}');

    return glsl.join('\n');
};

var generateGetNeighbourhoodSum = function (neighbourhood) {
    var glsl = [
        'int getNeighbourhoodSum (const in vec3 currentPos) {',
        '  int sum = 0;',
        ''
    ];

    for (var i = 0; i < neighbourhood.length; i++) {
        var neighbour = neighbourhood[i];
        glsl.push('  sum += getVoxel(currentPos, vec3(' + printFloat(neighbour[0]) + ', ' + printFloat(neighbour[1]) + ', ' + printFloat(neighbour[2]) + '));');
    }

    glsl.push('', '  return sum;', '}');

    return glsl.join('\n');
};

var generateGetNeighbourhoodCond = function (neighbourhood) {
    var glsl = [
        'int getNeighbourhoodCond (const in vec3 currentPos, const in int desiredValue) {',
        '  int sum = 0;',
        ''
    ];

    for (var i = 0; i < neighbourhood.length; i++) {
        var neighbour = neighbourhood[i];
        glsl.push('  sum += getVoxel(currentPos, vec3(' + printFloat(neighbour[0]) + ', ' + printFloat(neighbour[1]) + ', ' + printFloat(neighbour[2]) + ')) == desiredValue ? 1 : 0;');
    }

    glsl.push('', '  return sum;', '}');

    return glsl.join('\n');
};

var generateNeighbourhoodGlsl = function generateNeighbourhoodGlsl (neighbourhood) {
    var glsl = [
        generateGetNeighbourhood(neighbourhood),
        '',
        generateGetNeighbourhoodSum(neighbourhood),
        '',
        generateGetNeighbourhoodCond(neighbourhood)
    ];

    return glsl.join('\n');
};

var generateEqualityCheck = function generateEqualityCheck (values, variable) {
    var checkString = [],
        groupedValues = [],
        previousValue = null,
        i;

    variable = variable || 'sum';

    if (values && values.length) {
        values.sort(function(a, b) {
            return a - b;
        });

        uniq(values, null, true);

        for (i = 0; i < values.length; i++) {
            if (previousValue === values[i] - 1) {
                groupedValues[groupedValues.length - 1].push(values[i]);
            } else {
                groupedValues.push([values[i]]);
            }

            previousValue = values[i];
        }

        for (i = 0; i < groupedValues.length; i++) {
            if (groupedValues[i].length > 1) {
                checkString.push('(' + variable + ' >= ' + groupedValues[i][0] + ' && ' + variable + ' <= ' + groupedValues[i][groupedValues[i].length - 1] + ')');
            } else {
                checkString.push(variable + ' == ' + groupedValues[i][0]);
            }
        }
    } else {
        checkString.push('false');
    }

    return checkString.length > 1 ? '(' + checkString.join(' || ') + ')' : checkString[0];
};

var generateProcessGlslGenerations = function generateProcessGlslGenerations (stateCount, survival, birth) {
    var glsl = [
        'int process(const in int currentValue, const in vec3 position) {',
        '  int sum = getNeighbourhoodCond(position, 1);',
        '  if (currentValue == 0 && ' + generateEqualityCheck(birth) + ') {',
        '    return 1;',
        '  } else if (currentValue == 1 && ' + generateEqualityCheck(survival) + ') {',
        '    return 1;',
        '  } else if (currentValue > 0) {',
        '    return int(mod(float(currentValue + 1), ' + printFloat(stateCount) + '));',
        '  }',
        '  return 0;',
        '}'
    ];

    return glsl.join('\n');
};

var generateProcessGlslLife = function generateProcessGlslLife (survival, birth) {
    var glsl = [
        'int process(const in int currentValue, const in vec3 position) {',
        '  int sum = getNeighbourhood(position);',
        '  if (currentValue == 0 && ' + generateEqualityCheck(birth) + ') {',
        '    return 1;',
        '  } else if (currentValue > 0 && ' + generateEqualityCheck(survival) + ') {',
        '    return 1;',
        '  }',
        '  return 0;',
        '}'
    ];

    return glsl.join('\n');
};

var generateProcessGlslVote = function generateProcessGlslVote (votes) {
    var glsl = [
        'int process(const in int currentValue, const in vec3 position) {',
        '  int sum = getNeighbourhood(position) + (currentValue > 0 ? 1 : 0);',
        '  if (' + generateEqualityCheck(votes) + ') {',
        '    return 1;',
        '  }',
        '  return 0;',
        '}'
    ];

    return glsl.join('\n');
};

var generateProcessGlslLuky = function generateProcessGlslLuky (lowSurvival, highSurvival, lowBirth, highBirth) {
    var glsl = [
        'int process(const in int currentValue, const in vec3 position) {',
        '  int sum = getNeighbourhood(position);',
        '  if (currentValue == 0 && sum >= ' + lowBirth + ' && sum <= ' + highBirth + ') {',
        '    return 1;',
        '  } else if (currentValue > 0 && sum >= ' + lowSurvival + ' && sum <= ' + highSurvival + ') {',
        '    return 1;',
        '  }',
        '  return 0;',
        '}'
    ];

    return glsl.join('\n');
};

var generateProcessGlslNluky = function generateProcessGlslNluky (stateCount, lowSurvival, highSurvival, lowBirth, highBirth) {
    var glsl = [
        'int process(const in int currentValue, const in vec3 position) {',
        '  int sum = getNeighbourhoodCond(position, 1);',
        '  if (currentValue == 0 && sum >= ' + lowBirth + ' && sum <= ' + highBirth + ') {',
        '    return 1;',
        '  } else if (currentValue == 1 && sum >= ' + lowSurvival + ' && sum <= ' + highSurvival + ') {',
        '    return 1;',
        '  } else if (currentValue == 1) {',
        '    return ' + (2 % (2 + stateCount * 2)) + ';',
        '  } else if (currentValue >= 2) {',
        '    return int(mod(float(currentValue + 2), ' + printFloat(2 + stateCount * 2) + '));',
        '  }',
        '  return 0;',
        '}'
    ];

    return glsl.join('\n');
};

var generateProcessGlslCyclic = function generateProcessGlslCyclic (stateCount, threshold, greenbergHastingsModel) {
    var glsl = [
        'int process(const in int currentValue, const in vec3 position) {',
        '  int nextValue = int(mod(float(currentValue + 1), ' + printFloat(stateCount) + '));',
        '  int sum = getNeighbourhoodCond(position, nextValue);',
        '  if (sum >= ' + threshold + (greenbergHastingsModel ? ' || currentValue > 0' : '') + ') {',
        '    return nextValue;',
        '  }',
        '  return currentValue;',
        '}'
    ];

    return glsl.join('\n');
};

var generateProcessGlsl = function generateProcessGlsl (rule) {
    /*
     // debug process function
     var glsl = [
     'float process(const float currentValue, const int sum) {',
     '  return float(sum) / 255.;',
     '}'
     ];

     return glsl.join('\n');
     */

    if (rule.ruleFormat === 'life' || rule.ruleFormat === 'extended-life') {
        return generateProcessGlslLife(rule.survival, rule.birth);
    } else if (rule.ruleFormat === 'generations' || rule.ruleFormat === 'extended-generations') {
        return generateProcessGlslGenerations(rule.stateCount, rule.survival, rule.birth);
    } else if (rule.ruleFormat === 'vote') {
        return generateProcessGlslVote(rule.vote);
    } else if (rule.ruleFormat === 'luky') {
        return generateProcessGlslLuky(rule.lowSurvival, rule.highSurvival, rule.lowBirth, rule.highBirth);
    } else if (rule.ruleFormat === 'nluky') {
        return generateProcessGlslNluky(rule.stateCount, rule.lowSurvival, rule.highSurvival, rule.lowBirth, rule.highBirth);
    } else if (rule.ruleFormat === 'cyclic') {
        return generateProcessGlslCyclic(rule.stateCount, rule.threshold, rule.greenbergHastingsModel);
    }

    throw new Error('Unsupported ruleFormat : ' + rule.ruleFormat);
};

var generateGlsl = function generateGlsl (rule, neighbourhood, outOfBoundValue) {
    var glsl = [
        generateComment('Voxel Shader for MagicaVoxel 0.97.1', rule, outOfBoundValue),
        '',
        generateUniformsAndConstants(),
        '',
        generateGetVoxelGlsl(outOfBoundValue),
        '',
        generateNeighbourhoodGlsl(neighbourhood),
        '',
        generateProcessGlsl(rule),
        '',
        'float map(vec3 v) {',
        '  int currentValue = int(voxel(v));',
        '  return float(process(currentValue, v));',
        '}'
    ];

    return glsl.join('\n')
};

module.exports = generateGlsl;
<|endoftext|>


<commit_before>/**
* jquery.matchHeight-min.js v0.5.2
* http://brm.io/jquery-match-height/
* License: MIT
*/
(function(c){var n=-1,f=-1,r=function(a){var b=null,d=[];c(a).each(function(){var a=c(this),k=a.offset().top-h(a.css("margin-top")),l=0<d.length?d[d.length-1]:null;null===l?d.push(a):1>=Math.floor(Math.abs(b-k))?d[d.length-1]=l.add(a):d.push(a);b=k});return d},h=function(a){return parseFloat(a)||0},p=function(a){var b={byRow:!0,remove:!1,property:"height"};if("object"===typeof a)return c.extend(b,a);"boolean"===typeof a?b.byRow=a:"remove"===a&&(b.remove=!0);return b},b=c.fn.matchHeight=function(a){a=
p(a);if(a.remove){var e=this;this.css(a.property,"");c.each(b._groups,function(a,b){b.elements=b.elements.not(e)});return this}if(1>=this.length)return this;b._groups.push({elements:this,options:a});b._apply(this,a);return this};b._groups=[];b._throttle=80;b._maintainScroll=!1;b._beforeUpdate=null;b._afterUpdate=null;b._apply=function(a,e){var d=p(e),g=c(a),k=[g],l=c(window).scrollTop(),f=c("html").outerHeight(!0),m=g.parents().filter(":hidden");m.each(function(){var a=c(this);a.data("style-cache",
a.attr("style"))});m.css("display","block");d.byRow&&(g.each(function(){var a=c(this),b="inline-block"===a.css("display")?"inline-block":"block";a.data("style-cache",a.attr("style"));a.css({display:b,"padding-top":"0","padding-bottom":"0","margin-top":"0","margin-bottom":"0","border-top-width":"0","border-bottom-width":"0",height:"100px"})}),k=r(g),g.each(function(){var a=c(this);a.attr("style",a.data("style-cache")||"")}));c.each(k,function(a,b){var e=c(b),f=0;d.byRow&&1>=e.length?e.css(d.property,
""):(e.each(function(){var a=c(this),b={display:"inline-block"===a.css("display")?"inline-block":"block"};b[d.property]="";a.css(b);a.outerHeight(!1)>f&&(f=a.outerHeight(!1));a.css("display","")}),e.each(function(){var a=c(this),b=0;"border-box"!==a.css("box-sizing")&&(b+=h(a.css("border-top-width"))+h(a.css("border-bottom-width")),b+=h(a.css("padding-top"))+h(a.css("padding-bottom")));a.css(d.property,f-b)}))});m.each(function(){var a=c(this);a.attr("style",a.data("style-cache")||null)});b._maintainScroll&&
c(window).scrollTop(l/f*c("html").outerHeight(!0));return this};b._applyDataApi=function(){var a={};c("[data-match-height], [data-mh]").each(function(){var b=c(this),d=b.attr("data-match-height")||b.attr("data-mh");a[d]=d in a?a[d].add(b):b});c.each(a,function(){this.matchHeight(!0)})};var q=function(a){b._beforeUpdate&&b._beforeUpdate(a,b._groups);c.each(b._groups,function(){b._apply(this.elements,this.options)});b._afterUpdate&&b._afterUpdate(a,b._groups)};b._update=function(a,e){if(e&&"resize"===
e.type){var d=c(window).width();if(d===n)return;n=d}a?-1===f&&(f=setTimeout(function(){q(e);f=-1},b._throttle)):q(e)};c(b._applyDataApi);c(window).bind("load",function(a){b._update(!1,a)});c(window).bind("resize orientationchange",function(a){b._update(!0,a)})})(jQuery);<commit_msg>Updated minified version<commit_after>(function(b){var f=-1,e=-1,c=false;var g=function(n){var j=1,l=b(n),k=null,m=[];l.each(function(){var o=b(this),q=o.offset().top-d(o.css("margin-top")),p=m.length>0?m[m.length-1]:null;if(p===null){m.push(o)}else{if(Math.floor(Math.abs(k-q))<=j){m[m.length-1]=p.add(o)}else{m.push(o)}}k=q});return m};var d=function(j){return parseFloat(j)||0};var i=function(j){var k={byRow:true,remove:false,property:"height",matchedClass:"match-height"};if(typeof j==="object"){return b.extend(k,j)}if(typeof j==="boolean"){k.byRow=j}else{if(j==="remove"){k.remove=true}}return k};var a=b.fn.matchHeight=function(j){var l=i(j);if(l.remove){var k=this;this.css(l.property,"");b.each(a._groups,function(m,n){n.elements=n.elements.not(k)});return this}if(this.length<=1){return this}a._groups.push({elements:this,options:l});a._apply(this,l);return this};a._groups=[];a._throttle=80;a._maintainScroll=false;a._beforeUpdate=null;a._afterUpdate=null;a._apply=function(p,l){var n=i(l),m=b(p),o=[m];var q=b(window).scrollTop(),k=b("html").outerHeight(true);var j=m.parents().filter(":hidden");j.each(function(){var r=b(this);r.data("style-cache",r.attr("style"))});j.css("display","block");if(n.byRow){m.each(function(){var r=b(this),s=r.css("display")==="inline-block"?"inline-block":"block";r.data("style-cache",r.attr("style"));r.css({display:s,"padding-top":"0","padding-bottom":"0","margin-top":"0","margin-bottom":"0","border-top-width":"0","border-bottom-width":"0",height:"100px"})});o=g(m);m.each(function(){var r=b(this);r.attr("style",r.data("style-cache")||"")})}b.each(o,function(s,u){var r=b(u),t=0;if(n.byRow&&r.length<=1){r.css(n.property,"");return}r.each(function(){var v=b(this),x=v.css("display")==="inline-block"?"inline-block":"block";var w={display:x};w[n.property]="";v.css(w);if(v.outerHeight(false)>t){t=v.outerHeight(false)}v.css("display","")});r.each(function(){var w=b(this),v=0;if(w.css("box-sizing")!=="border-box"){v+=d(w.css("border-top-width"))+d(w.css("border-bottom-width"));v+=d(w.css("padding-top"))+d(w.css("padding-bottom"))}w.css(n.property,t-v);if(c===false){c=true;if(n.matchedClass!==""){w.addClass(n.matchedClass)}}})});j.each(function(){var r=b(this);r.attr("style",r.data("style-cache")||null)});if(a._maintainScroll){b(window).scrollTop((q/k)*b("html").outerHeight(true))}return this};a._applyDataApi=function(){var j={};b("[data-match-height], [data-mh]").each(function(){var l=b(this),k=l.attr("data-match-height")||l.attr("data-mh");if(k in j){j[k]=j[k].add(l)}else{j[k]=l}});b.each(j,function(){this.matchHeight(true)})};var h=function(j){if(a._beforeUpdate){a._beforeUpdate(j,a._groups)}b.each(a._groups,function(){a._apply(this.elements,this.options)});if(a._afterUpdate){a._afterUpdate(j,a._groups)}};a._update=function(l,k){if(k&&k.type==="resize"){var j=b(window).width();if(j===f){return}f=j}if(!l){h(k)}else{if(e===-1){e=setTimeout(function(){h(k);e=-1},a._throttle)}}};b(a._applyDataApi);b(window).bind("load",function(j){a._update(false,j)});b(window).bind("resize orientationchange",function(j){a._update(true,j)})})(jQuery);<|endoftext|>


<commit_before>/***************************************************************
 *  Copyright notice
 *
 *  (c) 2013 Taras Zakus <Taras.Zakus@pixabit-interactive.de>, Pixabit Interactive GmbH
 *
 *  License: MIT (http://www.opensource.org/licenses/mit-license.php)
 ***************************************************************/

(function($, itemsSelector, pluginDataKey) {
	"use strict";

	/**
	 * Constructor
	 * @param element
	 * @param options
	 * @constructor
	 */
	var SelectBoxedDate = function(element, options) {
		this.$element = $(element);
		this.options = options;

		if (!this.$element.is("input")) {
			throw "The element must be of type input!";
		}

		if (!this.$element.is(":hidden")) {
			this.$element.hide();
		}

		this.date = (element.value.length > 0
			? this.parseDate(element.value)
			: null);

		this.rangeFrom = this.getDateObject(this.options.rangeFrom);
		this.rangeTo = this.getDateObject(this.options.rangeTo);
		if (this.options.rangeRound) {
			// Set month range.
			this.rangeFrom.setMonth(0);
			this.rangeTo.setMonth(11);
			// Set date range.
			this.rangeFrom.setDate(1);
			this.rangeTo.setDate(31);
		}

		this.selectBoxes = [];
		var mapping = this.options.mapping.split("|"),
			wrapper = $('<div/>'),
			i, type, selectBox;
		for (i = 0; type = mapping[i]; i++) {
			selectBox = createSelectBox(
				this.options["label" + firstLetterUpperCase(type)],
				type,
				this.rangeFrom,
				this.rangeTo,
				((this.date instanceof Date)
					? this.date["get" + firstLetterUpperCase(fitToDateObjectType(type))]()
					: null),
				this.options.onSelectBoxOptionsChanged
			);
			selectBox.appendTo(wrapper);
			this.selectBoxes.push(selectBox);
		}
		wrapper.insertAfter(this.$element);
		if (typeof this.options.onSelectBoxesCreated === "function") {
			this.options.onSelectBoxesCreated.call(this);
		}

		var that = this,
			selectBoxes = [],
			month_selectBox,
			year_selectBox;
		for (i = 0; selectBox = this.selectBoxes[i]; i++) {
			type = selectBox.data("type");
			if (type === "month") {
				month_selectBox = selectBox;
			} else if (type === "year") {
				year_selectBox = selectBox;
			}
			selectBoxes.push(selectBox[0]);
		}
		$(selectBoxes)
			.on("change", function() {
				var $this = $(this),
					type = $this.data("type");
				if ((type === "month") ||
				    (type === "year")) {
					that.getSelectBox("day")
						.updateDays(getNumberOfDaysIn(
							month_selectBox.val(),
							year_selectBox.val()
						));
				}
				// Update element value
				that.updateElementValue();
			});
	};

	// --------------------------------------------------------------------
	// Public methods/properties
	// --------------------------------------------------------------------

	// TODO: handle date of different formats
	SelectBoxedDate.prototype.parseDate = function(value) {
		var chunks = value.split("-");
		if (chunks.length !== 3) {
			return null;
		}
		return new Date(chunks[2], (chunks[0] - 1), chunks[1]);
	};

	SelectBoxedDate.prototype.getDateObject = function(date) {
		var dateObject = new Date();

		var incDec_regExp = /([+-])([0-9]+)(y)/;
		if (incDec_regExp.test(date)) {
			var matches = incDec_regExp.exec(date);
			dateObject.setFullYear(dateObject.getFullYear() + (matches[1] + 1) * matches[2]);
		} else {
			throw "At this moment another formats are not available!";
		}

		return dateObject;
	};

	SelectBoxedDate.prototype.getSelectBox = function(type) {
		for (var i = 0, selectBox; selectBox = this.selectBoxes[i]; i++) {
			if (selectBox.data("type") === type) {
				return selectBox;
			}
		}
		throw "No such selectBox type: " + type;
	};

	SelectBoxedDate.prototype.updateElementValue = function() {
		for (var value = "", i = 0, char;
			char = this.options.format[i];
			i++) {
			switch (char) {
				case "m":
					value += withLeadingZeros(this.getSelectBox("month").val());
					break;
				case "d":
					value += withLeadingZeros(this.getSelectBox("day").val());
					break;
				case "Y":
					value += withLeadingZeros(this.getSelectBox("year").val());
					break;
				default:
					value += char;
					break;
			}
		}
		this.$element
			.val(value);
	};

	// --------------------------------------------------------------------
	// Private static methods/properties
	// --------------------------------------------------------------------

	function isLeapYear(year) {
		return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0));
	}

	function getNumberOfDaysIn(month, year) {
		var numberOfDays;
		if (parseInt(month) === 2) {
			numberOfDays = (isLeapYear(year)
				? 29
				: 28);
		} else if (",4,6,9,11,".indexOf("," + month + ",") !== -1) {
			numberOfDays = 30;
		} else if (",1,3,5,7,8,10,12,".indexOf("," + month + ",") !== -1) {
			numberOfDays = 31;
		} else {
			throw "Invalid month number";
		}
		return numberOfDays;
	}

	function withLeadingZeros(int_number, segments) {
		int_number = parseInt(int_number);
		if (isNaN(int_number)) {
			int_number = 0;
		}
		if (typeof segments === "undefined") {
			segments = 2;
		}
		var zerosNumber = (segments - int_number.toString().length + 1);
		if (zerosNumber > 0) {
			return (new Array(zerosNumber).join("0") + int_number);
		} else {
			return int_number;
		}
	}

	function createSelectBox(label, type, dateRangeFrom, dateRangeTo, selectedValue, onSelectBoxOptionsChanged) {
		var originalType = type;
		type = fitToDateObjectType(type);

		var selectBox = $('<select/>'),
			getTypeValue = ("get" + firstLetterUpperCase(type)),
			from = dateRangeFrom[getTypeValue](),
			to = dateRangeTo[getTypeValue](),
			i, n;

		// Append placeholder-option.
		getOption(0, label, true, true)
			.appendTo(selectBox);

		if (type === "fullYear") { // Make the list upside down.
			for (i = to; i >= from; i--) {
				getOption(i, i, (i === selectedValue))
					.appendTo(selectBox);
			}
		} else {
			for (i = from; i <= to; i++) {
				n = ((type === "month") ? (i + 1) : i); // Since in the Date object month starts from 0.
				getOption(n, withLeadingZeros(n), (i === selectedValue))
					.appendTo(selectBox);
			}
		}

		// Set additional properties and methods
		selectBox.data("type", originalType);
		if (type === "date") {
			selectBox.updateDays = function(numberOfDays) {
				var that = this,
					needReset = (this.val() > numberOfDays),
					optionsChanged = false;
				this.children("option").each(function(index) {
					var $this = $(this);
					if (this.value <= numberOfDays) {
						if ($this.is(":disabled") &&
						    (this.value != 0)) {
							this.disabled = false;
							$this.show();
							optionsChanged = true;
						}
						if (needReset) {
							this.selected = true;
							that.selectedIndex = index;
							that.trigger("change");
							needReset = false;
						}
					} else if (!$this.is(":disabled")) {
						this.disabled = true;
						$this.hide();
						optionsChanged = true;
					}
				});
				if (optionsChanged &&
				    (typeof onSelectBoxOptionsChanged === "function")) {
					onSelectBoxOptionsChanged(this);
				}
			};
		}

		return selectBox;
	}

	function getOption(value, title, selected, disabled) {
		var option = '<option value="' + value + '"';
		if (selected) {
			option += ' selected="selected"'
		}
		if (disabled) {
			option += ' disabled="disabled"'
		}
		option += '>' + title + '</option>';
		return $(option);
	}

	function firstLetterUpperCase(string) {
		return (string.slice(0, 1).toUpperCase() + string.slice(1));
	}

	function fitToDateObjectType(type) {
		if (type === "day") {
			type = "date";
		} else if (type === "year") {
			type = "fullYear";
		}
		return type;
	}

	// --------------------------------------------------------------------
	// Bootstrap
	// --------------------------------------------------------------------

	SelectBoxedDate.DEFAULTS = {
		rangeFrom: "-200y",
		rangeTo: "-12y",
		rangeRound: true,
		labelDay: "Day",
		labelMonth: "Month",
		labelYear: "Year",
		format: "m-d-Y",
		mapping: "day|month|year",
		onSelectBoxesCreated: function() {/* Apply some styling or anything else. */},
		onSelectBoxOptionsChanged: function(selectBox) {}
	};

	$.fn.selectBoxedDate = function(option) {
		return this.each(function() {
			var $this = $(this),
				data = $this.data(pluginDataKey),
				options = $.extend({}, SelectBoxedDate.DEFAULTS, $this.data(), (typeof option === "object") && option);
			if (!data) $this.data(pluginDataKey, (data = new SelectBoxedDate(this, options)));
			if (typeof option == "string") data[option].call($this);
		});
	};
	$(window).on("load", function() {
		$(itemsSelector).each(function() {
			var $this = $(this);
			$this.selectBoxedDate($this.data());
		});
	});
})(window.jQuery, ".select-boxed-date", "sbd");
<commit_msg>ReFormat code<commit_after>/***************************************************************
 *  Copyright notice
 *
 *  (c) 2013 Taras Zakus <Taras.Zakus@pixabit-interactive.de>, Pixabit Interactive GmbH
 *
 *  License: MIT (http://www.opensource.org/licenses/mit-license.php)
 ***************************************************************/

(function ($, itemsSelector, pluginDataKey) {
    "use strict";

    /**
     * Constructor
     * @param element
     * @param options
     * @constructor
     */
    var SelectBoxedDate = function (element, options) {
        this.$element = $(element);
        this.options = options;

        if (!this.$element.is("input")) {
            throw "The element must be of type input!";
        }

        if (!this.$element.is(":hidden")) {
            this.$element.hide();
        }

        this.date = (element.value.length > 0
            ? this.parseDate(element.value)
            : null);

        this.rangeFrom = this.getDateObject(this.options.rangeFrom);
        this.rangeTo = this.getDateObject(this.options.rangeTo);
        if (this.options.rangeRound) {
            // Set month range.
            this.rangeFrom.setMonth(0);
            this.rangeTo.setMonth(11);
            // Set date range.
            this.rangeFrom.setDate(1);
            this.rangeTo.setDate(31);
        }

        this.selectBoxes = [];
        var mapping = this.options.mapping.split("|"),
            wrapper = $('<div/>'),
            i, type, selectBox;
        for (i = 0; type = mapping[i]; i++) {
            selectBox = createSelectBox(
                this.options["label" + firstLetterUpperCase(type)],
                type,
                this.rangeFrom,
                this.rangeTo,
                ((this.date instanceof Date)
                    ? this.date["get" + firstLetterUpperCase(fitToDateObjectType(type))]()
                    : null),
                this.options.onSelectBoxOptionsChanged
            );
            selectBox.appendTo(wrapper);
            this.selectBoxes.push(selectBox);
        }
        wrapper.insertAfter(this.$element);
        if (typeof this.options.onSelectBoxesCreated === "function") {
            this.options.onSelectBoxesCreated.call(this);
        }

        var that = this,
            selectBoxes = [],
            month_selectBox,
            year_selectBox;
        for (i = 0; selectBox = this.selectBoxes[i]; i++) {
            type = selectBox.data("type");
            if (type === "month") {
                month_selectBox = selectBox;
            } else if (type === "year") {
                year_selectBox = selectBox;
            }
            selectBoxes.push(selectBox[0]);
        }
        $(selectBoxes)
            .on("change", function () {
                var $this = $(this),
                    type = $this.data("type");
                if ((type === "month") ||
                    (type === "year")) {
                    that.getSelectBox("day")
                        .updateDays(getNumberOfDaysIn(
                            month_selectBox.val(),
                            year_selectBox.val()
                        ));
                }
                // Update element value
                that.updateElementValue();
            });
    };

    // --------------------------------------------------------------------
    // Public methods/properties
    // --------------------------------------------------------------------

    // TODO: handle date of different formats
    SelectBoxedDate.prototype.parseDate = function (value) {
        var chunks = value.split("-");
        if (chunks.length !== 3) {
            return null;
        }
        return new Date(chunks[2], (chunks[0] - 1), chunks[1]);
    };

    SelectBoxedDate.prototype.getDateObject = function (date) {
        var dateObject = new Date();

        var incDec_regExp = /([+-])([0-9]+)(y)/;
        if (incDec_regExp.test(date)) {
            var matches = incDec_regExp.exec(date);
            dateObject.setFullYear(dateObject.getFullYear() + (matches[1] + 1) * matches[2]);
        } else {
            throw "At this moment another formats are not available!";
        }

        return dateObject;
    };

    SelectBoxedDate.prototype.getSelectBox = function (type) {
        for (var i = 0, selectBox; selectBox = this.selectBoxes[i]; i++) {
            if (selectBox.data("type") === type) {
                return selectBox;
            }
        }
        throw "No such selectBox type: " + type;
    };

    SelectBoxedDate.prototype.updateElementValue = function () {
        for (var value = "", i = 0, char;
             char = this.options.format[i];
             i++) {
            switch (char) {
                case "m":
                    value += withLeadingZeros(this.getSelectBox("month").val());
                    break;
                case "d":
                    value += withLeadingZeros(this.getSelectBox("day").val());
                    break;
                case "Y":
                    value += withLeadingZeros(this.getSelectBox("year").val());
                    break;
                default:
                    value += char;
                    break;
            }
        }
        this.$element
            .val(value);
    };

    // --------------------------------------------------------------------
    // Private static methods/properties
    // --------------------------------------------------------------------

    function isLeapYear(year) {
        return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0));
    }

    function getNumberOfDaysIn(month, year) {
        var numberOfDays;
        if (parseInt(month) === 2) {
            numberOfDays = (isLeapYear(year)
                ? 29
                : 28);
        } else if (",4,6,9,11,".indexOf("," + month + ",") !== -1) {
            numberOfDays = 30;
        } else if (",1,3,5,7,8,10,12,".indexOf("," + month + ",") !== -1) {
            numberOfDays = 31;
        } else {
            throw "Invalid month number";
        }
        return numberOfDays;
    }

    function withLeadingZeros(int_number, segments) {
        int_number = parseInt(int_number);
        if (isNaN(int_number)) {
            int_number = 0;
        }
        if (typeof segments === "undefined") {
            segments = 2;
        }
        var zerosNumber = (segments - int_number.toString().length + 1);
        if (zerosNumber > 0) {
            return (new Array(zerosNumber).join("0") + int_number);
        } else {
            return int_number;
        }
    }

    function createSelectBox(label, type, dateRangeFrom, dateRangeTo, selectedValue, onSelectBoxOptionsChanged) {
        var originalType = type;
        type = fitToDateObjectType(type);

        var selectBox = $('<select/>'),
            getTypeValue = ("get" + firstLetterUpperCase(type)),
            from = dateRangeFrom[getTypeValue](),
            to = dateRangeTo[getTypeValue](),
            i, n;

        // Append placeholder-option.
        getOption(0, label, true, true)
            .appendTo(selectBox);

        if (type === "fullYear") { // Make the list upside down.
            for (i = to; i >= from; i--) {
                getOption(i, i, (i === selectedValue))
                    .appendTo(selectBox);
            }
        } else {
            for (i = from; i <= to; i++) {
                n = ((type === "month") ? (i + 1) : i); // Since in the Date object month starts from 0.
                getOption(n, withLeadingZeros(n), (i === selectedValue))
                    .appendTo(selectBox);
            }
        }

        // Set additional properties and methods
        selectBox.data("type", originalType);
        if (type === "date") {
            selectBox.updateDays = function (numberOfDays) {
                var that = this,
                    needReset = (this.val() > numberOfDays),
                    optionsChanged = false;
                this.children("option").each(function (index) {
                    var $this = $(this);
                    if (this.value <= numberOfDays) {
                        if ($this.is(":disabled") &&
                            (this.value != 0)) {
                            this.disabled = false;
                            $this.show();
                            optionsChanged = true;
                        }
                        if (needReset) {
                            this.selected = true;
                            that.selectedIndex = index;
                            that.trigger("change");
                            needReset = false;
                        }
                    } else if (!$this.is(":disabled")) {
                        this.disabled = true;
                        $this.hide();
                        optionsChanged = true;
                    }
                });
                if (optionsChanged &&
                    (typeof onSelectBoxOptionsChanged === "function")) {
                    onSelectBoxOptionsChanged(this);
                }
            };
        }

        return selectBox;
    }

    function getOption(value, title, selected, disabled) {
        var option = '<option value="' + value + '"';
        if (selected) {
            option += ' selected="selected"'
        }
        if (disabled) {
            option += ' disabled="disabled"'
        }
        option += '>' + title + '</option>';
        return $(option);
    }

    function firstLetterUpperCase(string) {
        return (string.slice(0, 1).toUpperCase() + string.slice(1));
    }

    function fitToDateObjectType(type) {
        if (type === "day") {
            type = "date";
        } else if (type === "year") {
            type = "fullYear";
        }
        return type;
    }

    // --------------------------------------------------------------------
    // Bootstrap
    // --------------------------------------------------------------------

    SelectBoxedDate.DEFAULTS = {
        rangeFrom: "-200y",
        rangeTo: "-12y",
        rangeRound: true,
        labelDay: "Day",
        labelMonth: "Month",
        labelYear: "Year",
        format: "m-d-Y",
        mapping: "day|month|year",
        onSelectBoxesCreated: function () {/* Apply some styling or anything else. */
        },
        onSelectBoxOptionsChanged: function (selectBox) {
        }
    };

    $.fn.selectBoxedDate = function (option) {
        return this.each(function () {
            var $this = $(this),
                data = $this.data(pluginDataKey),
                options = $.extend({}, SelectBoxedDate.DEFAULTS, $this.data(), (typeof option === "object") && option);
            if (!data) $this.data(pluginDataKey, (data = new SelectBoxedDate(this, options)));
            if (typeof option == "string") data[option].call($this);
        });
    };
    $(window).on("load", function () {
        $(itemsSelector).each(function () {
            var $this = $(this);
            $this.selectBoxedDate($this.data());
        });
    });
})(window.jQuery, ".select-boxed-date", "sbd");
<|endoftext|>


<commit_before>myApp.controller('InventoryController', function($scope, $window, $location, $routeParams, $timeout, inventoryService, breadCrumbService) {
    var id = $routeParams.id, itemId = $routeParams.itemId;
    $scope.inventories = inventoryService.getInventories();
    $scope.inventory = inventoryService.getInventory(id);
    $scope.item = inventoryService.getItem(id, itemId) || {};
    $scope.breadCrumbs = breadCrumbService;

    $scope.$on('$routeChangeSuccess', function (e, curr, prev) {
        breadCrumbService.update(curr.locals.breadCrumb);
    });

    $scope.editInventory = function(inv) {
        $location.path(`/edit/${inv.id}`);
    };

    $scope.newInventory = function() {
        $location.path('/new');
    };

    $scope.addInventory = function(id) {
        var inventory = $scope.inventory, inv;

        if(id) {
            // TODO: move updating into inventoryService
            inv = inventoryService.getInventory(id);
            inv.name = inventory.name;
            inv.coin.gp = inventory.coin.gp;
            inv.coin.sp = inventory.coin.sp;
            inv.coin.cp = inventory.coin.cp;
            inventoryService.storeInventories();
        }
        else inv = inventoryService.newInventory(inventory.name, inventory.coin);

        $location.path(`/view/${inv.id}`);
    };

    $scope.removeInventory = function(id) {
        var invToDelete = inventoryService.getInventory(id);
        var index = $scope.inventories.findIndex(function(inv) {
            return inv.id === invToDelete.id;
        });
        $scope.inventories[index].delete = true;

        var notification = document.querySelector('.mdl-js-snackbar');
        notification.MaterialSnackbar.showSnackbar({
            message: `Deleted ${invToDelete.name}`,
            actionText: 'Undo',
            actionHandler: function() {
                delete $scope.inventories[index].delete;
            },
            timeout: 3000
        });

        $timeout(function() {
            if($scope.inventories[index].delete) {
                $scope.inventories.splice(index, 1);
                inventoryService.removeInventory(id);
            }
        }, 3500);
    };

    $scope.newItem = function(id) {
        $location.path(`/edit/${id}/item/new`);
    };

    $scope.addItem = function(id, itemId) {
        var item = $scope.item;

        if(itemId) {
            // TODO: move updating into inventoryService
            var oldItem = inventoryService.getItem(id, itemId);
            oldItem.name = item.name;
            oldItem.value = item.value;
            oldItem.desc = item.desc;
            inventoryService.storeInventories();
        }
        else inventoryService.newItem(id, item.name, item.value, item.desc);

        $location.path(`/view/${id}`);
    };

    $scope.removeItem = function(inv, item) {
        inventoryService.removeItem(inv.id, item.id);
        $location.path(`/view/${inv.id}`);
    };
});
<commit_msg>Simplify removeInventory method<commit_after>myApp.controller('InventoryController', function($scope, $window, $location, $routeParams, $timeout, inventoryService, breadCrumbService) {
    var id = $routeParams.id, itemId = $routeParams.itemId;
    $scope.inventories = inventoryService.getInventories();
    $scope.inventory = inventoryService.getInventory(id);
    $scope.item = inventoryService.getItem(id, itemId) || {};
    $scope.breadCrumbs = breadCrumbService;

    $scope.$on('$routeChangeSuccess', function (e, curr, prev) {
        breadCrumbService.update(curr.locals.breadCrumb);
    });

    $scope.editInventory = function(inv) {
        $location.path(`/edit/${inv.id}`);
    };

    $scope.newInventory = function() {
        $location.path('/new');
    };

    $scope.addInventory = function(id) {
        var inventory = $scope.inventory, inv;

        if(id) {
            // TODO: move updating into inventoryService
            inv = inventoryService.getInventory(id);
            inv.name = inventory.name;
            inv.coin.gp = inventory.coin.gp;
            inv.coin.sp = inventory.coin.sp;
            inv.coin.cp = inventory.coin.cp;
            inventoryService.storeInventories();
        }
        else inv = inventoryService.newInventory(inventory.name, inventory.coin);

        $location.path(`/view/${inv.id}`);
    };

    $scope.removeInventory = function(id) {
        var invToDelete = inventoryService.getInventory(id);
        invToDelete.delete = true;

        var timeout = $timeout(function() {
            if(invToDelete.delete)
                inventoryService.removeInventory(id);
        }, 4500);

        var notification = document.querySelector('.mdl-js-snackbar');
        notification.MaterialSnackbar.showSnackbar({
            message: `Deleted ${invToDelete.name}`,
            actionText: 'Undo',
            actionHandler: function() {
                delete invToDelete.delete;
                $timeout.cancel(timeout);
            },
            timeout: 3000
        });
    };

    $scope.newItem = function(id) {
        $location.path(`/edit/${id}/item/new`);
    };

    $scope.addItem = function(id, itemId) {
        var item = $scope.item;

        if(itemId) {
            // TODO: move updating into inventoryService
            var oldItem = inventoryService.getItem(id, itemId);
            oldItem.name = item.name;
            oldItem.value = item.value;
            oldItem.desc = item.desc;
            inventoryService.storeInventories();
        }
        else inventoryService.newItem(id, item.name, item.value, item.desc);

        $location.path(`/view/${id}`);
    };

    $scope.removeItem = function(inv, item) {
        inventoryService.removeItem(inv.id, item.id);
        $location.path(`/view/${inv.id}`);
    };
});
<|endoftext|>