<commit_before>/**
 * Scroll to content
 * @module Ink.UI.SmoothScroller_1
 * @version 1
 */
Ink.createModule('Ink.UI.SmoothScroller', '1', ['Ink.UI.Common_1', 'Ink.Dom.Event_1', 'Ink.Dom.Element_1', 'Ink.Dom.Selector_1','Ink.Dom.Css_1'], function(Common, Event, InkElement, Selector, Css) {
    'use strict';

    var requestAnimationFrame =
        window.requestAnimationFrame ||
        function (cb) { return setTimeout(cb, 10); };

    var cancelAnimationFrame =
        window.cancelAnimationFrame ||
        function (id) { clearTimeout(id); };

    /**
     * @namespace Ink.UI.SmoothScroller
     * @version 1
     * @static
     *
     * SmoothScroller is a component which replaces the default scroll-to behaviour of `<a>` tags which refer to IDs on the page.
     *
     * For example, when you have this:
     *
     *          Todo
     *              [...]
     *

     *              [...]
     *
     * You can click the `<a>` and the page will scroll until the section you pointed to.
     *
     * When you use SmoothScroller, instead of immediately scrolling to the element, you get a smooth motion.
     *
     * Also, you can define the data-margin option if you have a `position:fixed` top menu ruining the behaviour.
     *
     * @example
     *
     *      go to Part 1
     *
     *      [lots and lots of content...]
     *
     *
Part 1

     *
     *
     */
    var SmoothScroller = {

        /**
         * Sets the speed of the scrolling
         *
         * @property speed
         * @type {Number}
         * @readOnly
         * @static
         */
        speed: 10,

        /**
         * Moves the scrollbar to the target element. This is the function
         * which animates the scroll position bit by bit. It calls itself in
         * the end through requestAnimationFrame
         *
         * @method scroll
         * @param  {Number} d Y coordinate value to stop
         * @public
         * @static
         */
        scroll: function(d, options) {
            var a = Math.round(InkElement.scrollHeight());
            var margin = options.margin || 0;

            var endPos = Math.round(d - margin);

            var speed = options.speed !== null ?
                options.speed :
                SmoothScroller.speed;

            if (endPos > a) {
                a += Math.ceil((endPos - a) / speed);
            } else {
                a = a + (endPos - a) / speed;
            }

            cancelAnimationFrame(SmoothScroller.interval);

            if (!((a) === endPos || SmoothScroller.offsetTop === a)) {
                SmoothScroller.interval = requestAnimationFrame(
                    Ink.bindMethod(SmoothScroller, 'scroll', d, options), document.body);
            } else {
                SmoothScroller.onDone(options);
            }

            window.scrollTo(0, a);
            SmoothScroller.offsetTop = a;
        },

        /**
         * Has smooth scrolling applied to relevant elements upon page load.
         *
         * @method init
         * @param [selector='a.scrollableLink,a.ink-smooth-scroll'] Selector string for finding links with smooth scrolling enabled.
         * @public
         * @static
         */
        init: function(selector) {
            Event.on(document, 'click', selector, SmoothScroller.onClick);
        },

        // Deprecated. Kept around just in case someone is still calling this.
        render: function() {},

        /**
         * Handles clicks on link elements
         *
         * @method onClick
         * @public
         * @static
         */
        onClick: function(event) {
            var link = event.currentTarget;

            var thisDocument =    (location + '').replace(/#.*?$/, '');
            var linkedDocument = (link.href + '').replace(/#.*?$/, '');

            if (linkedDocument !== thisDocument) {
                return; // It's an external link.
            }

            var hash = link.getAttribute('data-hash') || (link.getAttribute('href') || '')
                .replace(/^.*?#/, '');

            if(hash) {
                event.preventDefault();
                var activeLiSelector = 'ul > li.active > ' + selector;

                var selector = 'a[name="' + hash + '"],#' + hash;
                var elm = Ink.s(selector);
                var activeLi = Ink.s(activeLiSelector);
                activeLi = activeLi && activeLi.parentNode;

                if (elm) {
                    if (!Css.hasClassName(link.parentNode, 'active')) {
                        if (activeLi) {
                            Css.removeClassName(activeLi, 'active');
                        }
                        Css.addClassName(link.parentNode, 'active');
                    }

                    var options = Common.options('SmoothScroller link options', {
                        margin: ['Number', 0],
                        speed: ['Number', null],
                        noHashChange: ['Boolean', false]
                    }, {}, link);

                    SmoothScroller.hash = hash;

                    SmoothScroller.scroll(InkElement.offsetTop(elm), options);
                }
            }
        },

        /**
         * Called when the scroll movement is done. Updates browser address.
         */
        onDone: function (options) {
            if (!options.noHashChange) {
                window.location.hash = SmoothScroller.hash;
            }

            SmoothScroller.hash = SmoothScroller.offsetTop = null;
        }
    };

    return SmoothScroller;

});
<commit_msg>get rid of the double negative inherent to the name dontChangeHash<commit_after>/**
 * Scroll to content
 * @module Ink.UI.SmoothScroller_1
 * @version 1
 */
Ink.createModule('Ink.UI.SmoothScroller', '1', ['Ink.UI.Common_1', 'Ink.Dom.Event_1', 'Ink.Dom.Element_1', 'Ink.Dom.Selector_1','Ink.Dom.Css_1'], function(Common, Event, InkElement, Selector, Css) {
    'use strict';

    var requestAnimationFrame =
        window.requestAnimationFrame ||
        function (cb) { return setTimeout(cb, 10); };

    var cancelAnimationFrame =
        window.cancelAnimationFrame ||
        function (id) { clearTimeout(id); };

    /**
     * @namespace Ink.UI.SmoothScroller
     * @version 1
     * @static
     *
     * SmoothScroller is a component which replaces the default scroll-to behaviour of `<a>` tags which refer to IDs on the page.
     *
     * For example, when you have this:
     *
     *          Todo
     *              [...]
     *

     *              [...]
     *
     * You can click the `<a>` and the page will scroll until the section you pointed to.
     *
     * When you use SmoothScroller, instead of immediately scrolling to the element, you get a smooth motion.
     *
     * Also, you can define the data-margin option if you have a `position:fixed` top menu ruining the behaviour.
     *
     * @example
     *
     *      go to Part 1
     *
     *      [lots and lots of content...]
     *
     *
Part 1

     *
     *
     */
    var SmoothScroller = {

        /**
         * Sets the speed of the scrolling
         *
         * @property speed
         * @type {Number}
         * @readOnly
         * @static
         */
        speed: 10,

        /**
         * Moves the scrollbar to the target element. This is the function
         * which animates the scroll position bit by bit. It calls itself in
         * the end through requestAnimationFrame
         *
         * @method scroll
         * @param  {Number} d Y coordinate value to stop
         * @public
         * @static
         */
        scroll: function(d, options) {
            var a = Math.round(InkElement.scrollHeight());
            var margin = options.margin || 0;

            var endPos = Math.round(d - margin);

            var speed = options.speed !== null ?
                options.speed :
                SmoothScroller.speed;

            if (endPos > a) {
                a += Math.ceil((endPos - a) / speed);
            } else {
                a = a + (endPos - a) / speed;
            }

            cancelAnimationFrame(SmoothScroller.interval);

            if (!((a) === endPos || SmoothScroller.offsetTop === a)) {
                SmoothScroller.interval = requestAnimationFrame(
                    Ink.bindMethod(SmoothScroller, 'scroll', d, options), document.body);
            } else {
                SmoothScroller.onDone(options);
            }

            window.scrollTo(0, a);
            SmoothScroller.offsetTop = a;
        },

        /**
         * Has smooth scrolling applied to relevant elements upon page load.
         *
         * @method init
         * @param [selector='a.scrollableLink,a.ink-smooth-scroll'] Selector string for finding links with smooth scrolling enabled.
         * @public
         * @static
         */
        init: function(selector) {
            Event.on(document, 'click', selector, SmoothScroller.onClick);
        },

        // Deprecated. Kept around just in case someone is still calling this.
        render: function() {},

        /**
         * Handles clicks on link elements
         *
         * @method onClick
         * @public
         * @static
         */
        onClick: function(event) {
            var link = event.currentTarget;

            var thisDocument =    (location + '').replace(/#.*?$/, '');
            var linkedDocument = (link.href + '').replace(/#.*?$/, '');

            if (linkedDocument !== thisDocument) {
                return; // It's an external link.
            }

            var hash = link.getAttribute('data-hash') || (link.getAttribute('href') || '')
                .replace(/^.*?#/, '');

            if(hash) {
                event.preventDefault();
                var activeLiSelector = 'ul > li.active > ' + selector;

                var selector = 'a[name="' + hash + '"],#' + hash;
                var elm = Ink.s(selector);
                var activeLi = Ink.s(activeLiSelector);
                activeLi = activeLi && activeLi.parentNode;

                if (elm) {
                    if (!Css.hasClassName(link.parentNode, 'active')) {
                        if (activeLi) {
                            Css.removeClassName(activeLi, 'active');
                        }
                        Css.addClassName(link.parentNode, 'active');
                    }

                    var options = Common.options('SmoothScroller link options', {
                        margin: ['Number', 0],
                        speed: ['Number', null],
                        changeHash: ['Boolean', true]
                    }, {}, link);

                    SmoothScroller.hash = hash;

                    SmoothScroller.scroll(InkElement.offsetTop(elm), options);
                }
            }
        },

        /**
         * Called when the scroll movement is done. Updates browser address.
         *
         * @method onDone
         * @param {Object} options Options object from the element.
         * @private
         */
        onDone: function (options) {
            if (options.changeHash === true) {
                window.location.hash = SmoothScroller.hash;
            }

            SmoothScroller.hash = SmoothScroller.offsetTop = null;
        }
    };

    return SmoothScroller;

});
<|endoftext|>


<commit_before>/**
 * Animates the page so that the Action Drawer slides in and out.
 * By default, the drawer will be hidden.
 *
 */
betterlink_user_interface.createModule("Drawer Slider", function(api, apiInternal) {
	api.requireModules( ["Util.DOM", "Drawer Reset CSS"] );

	var BODY_DRAWER_CLASS = "betterlink-drawer";
	var BODY_DISPLACED_CLASS = "betterlink-displaced";
	var BODY_POSITION_CLASS = "betterlink-position-absolute";

	var DRAWER_SLIDING_CLASS = "betterlink-drawer-slider";
	var DRAWER_OPEN_CLASS = "betterlink-drawer-open";
	var DRAWER_OFFPAGE_CLASS = 'betterlink-drawer-offpage';

	var DRAWER_WIDTH = '230px';
	var TRANSITION_LENGTH = 400; // assumed less than 1000 and an even hundred
	var TRANSITION_STRING = "right 0." + TRANSITION_LENGTH/100 + "s linear;";
	var FULL_TRANSITION_STRING = "-webkit-transition: " + TRANSITION_STRING + " transition: " + TRANSITION_STRING;

	var DRAWER_CSS =
		[   "." + DRAWER_SLIDING_CLASS + " { visibility: hidden; " + FULL_TRANSITION_STRING + "}",
			"." + DRAWER_OPEN_CLASS + " { visibility: visible; }",
			"." + DRAWER_OFFPAGE_CLASS + " { right: -230px !important; }"
		].join(' ');

	var BODY_CSS =
		[   "body." + BODY_DRAWER_CLASS + " { right: 0; " + FULL_TRANSITION_STRING + "}",
			"body." + BODY_DISPLACED_CLASS + " { right: 230px !important; }",
			"body." + BODY_POSITION_CLASS + " { position: absolute !important; }"
		].join(' ');

	var html = document.getElementsByTagName("html")[0];
	var body = document.body;
	var stylesInitialized = false;
	var animateDrawer;
	var bodyWidth;
	var drawer;

	apiInternal.slider = {
		initialize: initializeSlider,
		slideDrawerIn: slideDrawerIn,
		slideDrawerAway: slideDrawerAway
	};
	/****************************************************************************************************/

	function initializeSlider(drawerElement, opt_animate) {
		if(!stylesInitialized) {
			addBodyWidthToCss();
			toggleAnimation(opt_animate);
			initializeStyles();
		}

		drawer = drawerElement;
		apiInternal.util.dom.applyClassToElement(body, BODY_DRAWER_CLASS);
		apiInternal.util.dom.applyClassToElement(drawer, DRAWER_SLIDING_CLASS);
		apiInternal.util.dom.applyClassToElement(drawer, DRAWER_OFFPAGE_CLASS);
	}

	// Display the drawer on the page and displace the body to make room. The body
	// needs to be displaced in the event that there are elements added to the page
	// that have a z-index applied. Otherwise, those elements may appear to cover
	// the drawer.
	function slideDrawerIn() {
		html.style.overflowX = 'hidden';

		apiInternal.util.dom.applyClassToElement(drawer, DRAWER_OPEN_CLASS);
		apiInternal.util.dom.applyClassToElement(body, BODY_POSITION_CLASS);
		apiInternal.util.dom.applyClassToElement(body, BODY_DISPLACED_CLASS);
		apiInternal.util.dom.removeClassFromElement(drawer, DRAWER_OFFPAGE_CLASS);
	}

	// Hide the drawer and move the body back into position
	function slideDrawerAway() {
		apiInternal.util.dom.applyClassToElement(drawer, DRAWER_OFFPAGE_CLASS);
		apiInternal.util.dom.removeClassFromElement(body, BODY_DISPLACED_CLASS);

		if(animateDrawer) {
			window.setTimeout(runReplacement, TRANSITION_LENGTH);
		}
		else {
			runReplacement();
		}
	}

	function runReplacement() {
		apiInternal.util.dom.removeClassFromElement(body, BODY_POSITION_CLASS);
		apiInternal.util.dom.removeClassFromElement(drawer, DRAWER_OPEN_CLASS);
		html.style.overflowX = '';
	}

	// Toggle whether the CSS includes the transition styles. Also sets the
	// global variable.
	function toggleAnimation(shouldAnimate) {
		if(!shouldAnimate) {
			BODY_CSS = BODY_CSS.replace(FULL_TRANSITION_STRING, '');
			DRAWER_CSS = DRAWER_CSS.replace(FULL_TRANSITION_STRING, '');
		}
		animateDrawer = shouldAnimate;
	}

	// Gets the width of the body and adds it as a CSS attribute that will be added to
	// the page. Applying the width as a class seems more consistent than attempting
	// to apply as an inline style using 'body.style.width'.
	//
	// The width needs to be added to the body so that when it is displaced (via position:
	// absolute) the whole page appears to shift, instead of contracting.
	function addBodyWidthToCss() {
		bodyWidth = getBodyWidth();
		BODY_CSS = BODY_CSS.replace("position:", "width: " + bodyWidth + "px; position:");
	}

	function getBodyWidth() {
		return Math.max(body.scrollWidth, body.offsetWidth, body.clientWidth);
	}

	function initializeStyles() {
		stylesInitialized = true;
		apiInternal.util.dom.createAndAppendStyleElement(DRAWER_CSS + ' ' + BODY_CSS);
	}
});
<commit_msg>register cleanup function<commit_after>/**
 * Animates the page so that the Action Drawer slides in and out.
 * By default, the drawer will be hidden.
 *
 */
betterlink_user_interface.createModule("Drawer Slider", function(api, apiInternal) {
	api.requireModules( ["Util.DOM", "Drawer Reset CSS"] );

	var BODY_DRAWER_CLASS = "betterlink-drawer";
	var BODY_DISPLACED_CLASS = "betterlink-displaced";
	var BODY_POSITION_CLASS = "betterlink-position-absolute";

	var DRAWER_SLIDING_CLASS = "betterlink-drawer-slider";
	var DRAWER_OPEN_CLASS = "betterlink-drawer-open";
	var DRAWER_OFFPAGE_CLASS = 'betterlink-drawer-offpage';

	var DRAWER_WIDTH = '230px';
	var TRANSITION_LENGTH = 400; // assumed less than 1000 and an even hundred
	var TRANSITION_STRING = "right 0." + TRANSITION_LENGTH/100 + "s linear;";
	var FULL_TRANSITION_STRING = "-webkit-transition: " + TRANSITION_STRING + " transition: " + TRANSITION_STRING;

	var DRAWER_CSS =
		[   "." + DRAWER_SLIDING_CLASS + " { visibility: hidden; " + FULL_TRANSITION_STRING + "}",
			"." + DRAWER_OPEN_CLASS + " { visibility: visible; }",
			"." + DRAWER_OFFPAGE_CLASS + " { right: -230px !important; }"
		].join(' ');

	var BODY_CSS =
		[   "body." + BODY_DRAWER_CLASS + " { right: 0; " + FULL_TRANSITION_STRING + "}",
			"body." + BODY_DISPLACED_CLASS + " { right: 230px !important; }",
			"body." + BODY_POSITION_CLASS + " { position: absolute !important; }"
		].join(' ');

	var html = document.getElementsByTagName("html")[0];
	var body = document.body;
	var stylesInitialized = false;
	var animateDrawer;
	var bodyWidth;
	var drawer;

	apiInternal.slider = {
		initialize: initializeSlider,
		slideDrawerIn: slideDrawerIn,
		slideDrawerAway: slideDrawerAway
	};
	/****************************************************************************************************/

	apiInternal.events.registerObserverForRemoveBetterlink(removeBodyStyles);
	function removeBodyStyles() {
		apiInternal.util.dom.removeClassFromElement(body, BODY_POSITION_CLASS);
		apiInternal.util.dom.removeClassFromElement(body, BODY_DISPLACED_CLASS);
		apiInternal.util.dom.removeClassFromElement(body, BODY_DRAWER_CLASS);
		html.style.overflowX = '';
	}

	function initializeSlider(drawerElement, opt_animate) {
		if(!stylesInitialized) {
			addBodyWidthToCss();
			toggleAnimation(opt_animate);
			initializeStyles();
		}

		drawer = drawerElement;
		apiInternal.util.dom.applyClassToElement(body, BODY_DRAWER_CLASS);
		apiInternal.util.dom.applyClassToElement(drawer, DRAWER_SLIDING_CLASS);
		apiInternal.util.dom.applyClassToElement(drawer, DRAWER_OFFPAGE_CLASS);
	}

	// Display the drawer on the page and displace the body to make room. The body
	// needs to be displaced in the event that there are elements added to the page
	// that have a z-index applied. Otherwise, those elements may appear to cover
	// the drawer.
	function slideDrawerIn() {
		html.style.overflowX = 'hidden';

		apiInternal.util.dom.applyClassToElement(drawer, DRAWER_OPEN_CLASS);
		apiInternal.util.dom.applyClassToElement(body, BODY_POSITION_CLASS);
		apiInternal.util.dom.applyClassToElement(body, BODY_DISPLACED_CLASS);
		apiInternal.util.dom.removeClassFromElement(drawer, DRAWER_OFFPAGE_CLASS);
	}

	// Hide the drawer and move the body back into position
	function slideDrawerAway() {
		apiInternal.util.dom.applyClassToElement(drawer, DRAWER_OFFPAGE_CLASS);
		apiInternal.util.dom.removeClassFromElement(body, BODY_DISPLACED_CLASS);

		if(animateDrawer) {
			window.setTimeout(runReplacement, TRANSITION_LENGTH);
		}
		else {
			runReplacement();
		}
	}

	function runReplacement() {
		apiInternal.util.dom.removeClassFromElement(body, BODY_POSITION_CLASS);
		apiInternal.util.dom.removeClassFromElement(drawer, DRAWER_OPEN_CLASS);
		html.style.overflowX = '';
	}

	// Toggle whether the CSS includes the transition styles. Also sets the
	// global variable.
	function toggleAnimation(shouldAnimate) {
		if(!shouldAnimate) {
			BODY_CSS = BODY_CSS.replace(FULL_TRANSITION_STRING, '');
			DRAWER_CSS = DRAWER_CSS.replace(FULL_TRANSITION_STRING, '');
		}
		animateDrawer = shouldAnimate;
	}

	// Gets the width of the body and adds it as a CSS attribute that will be added to
	// the page. Applying the width as a class seems more consistent than attempting
	// to apply as an inline style using 'body.style.width'.
	//
	// The width needs to be added to the body so that when it is displaced (via position:
	// absolute) the whole page appears to shift, instead of contracting.
	function addBodyWidthToCss() {
		bodyWidth = getBodyWidth();
		BODY_CSS = BODY_CSS.replace("position:", "width: " + bodyWidth + "px; position:");
	}

	function getBodyWidth() {
		return Math.max(body.scrollWidth, body.offsetWidth, body.clientWidth);
	}

	function initializeStyles() {
		stylesInitialized = true;
		apiInternal.util.dom.createAndAppendStyleElement(DRAWER_CSS + ' ' + BODY_CSS);
	}
});
<|endoftext|>


<commit_before>var Backbone = require('backbone');
var Miner = require('../Miner.js');
Backbone.LocalStorage = require("backbone.localstorage");

module.exports = Backbone.Collection.extend({
  model: Miner,
  url: "http://localhost:1337/api/v1/miner",
//  localStorage: new Backbone.LocalStorage("miners-backbone"),
});
<commit_msg>swapping in hashware api live<commit_after>var Backbone = require('backbone');
var Miner = require('../Miner.js');
Backbone.LocalStorage = require("backbone.localstorage");

module.exports = Backbone.Collection.extend({
  model: Miner,
  //url: "http://localhost:1337/api/v1/miner",
  url: "http://hashware-api.herokuapp.com/api/v1/miner"
//  localStorage: new Backbone.LocalStorage("miners-backbone"),
});
<|endoftext|>


<commit_before>import React from 'react';

const FieldSelect = (props) => {
  return (

      <select {...props}>
        {props.children}
      </select>

  );
};

FieldSelect.defaultProps = {
  name: '',
  onChange() {},
  value: ''
};

FieldSelect.propTypes = {
  name: React.PropTypes.string,
  onChange: React.PropTypes.func,
  value: React.PropTypes.oneOfType([
    React.PropTypes.number,
    React.PropTypes.string
  ])
};

module.exports = FieldSelect;
<commit_msg>Remove default name property<commit_after>import React from 'react';

const FieldSelect = (props) => {
  return (

      <select {...props}>
        {props.children}
      </select>

  );
};

FieldSelect.defaultProps = {
  onChange() {},
  value: ''
};

FieldSelect.propTypes = {
  name: React.PropTypes.string,
  onChange: React.PropTypes.func,
  value: React.PropTypes.oneOfType([
    React.PropTypes.number,
    React.PropTypes.string
  ])
};

module.exports = FieldSelect;
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2013-2016 Memba Sarl. All rights reserved.
 * Sources at https://github.com/Memba
 */

/* jshint browser: true, jquery: true */
/* globals define: false */

(function (f, define) {
    'use strict';
    define([
        './window.assert',
        './window.logger',
        './vendor/kendo/kendo.binder',
        './vendor/kendo/kendo.dropdownlist',
        './vendor/kendo/kendo.treeview'
        // './vendor/kendo/kendo.multiselect' // required because of a test in kendo.binder.js
    ], f);
})(function () {

    'use strict';

    (function ($, undefined) {

        var kendo = window.kendo;
        var data = kendo.data;
        var DataSource = data.DataSource;
        var ui = kendo.ui;
        var DropDownList = ui.DropDownList;
        var TreeView = ui.TreeView;
        var assert = window.assert;
        var logger = new window.Logger('kidoju.widgets.dropdowntree');
        // var STRING = 'string';
        var UNDEFINED = 'undefined';
        var CHANGE = 'change';
        var DIV = '<div/>';

        /*********************************************************************************
         * Helpers
         *********************************************************************************/

        /**
         * Processes a table (dropDownList dataSource) with dataParentField into a hierarchy (Hierarchical dataSOurce for treeView)
         * Note: see also app.cache.getCategoryHierarchy
         * @param data
         * @param idField
         * @param dataParentField
         * @returns {*}
         */
        function processTable(data, idField, dataParentField) {
            var hash = {};
            for (var i = 0; i < data.length; i++) {
                var item = data[i];
                var id = item[idField];
                var parentId = item[dataParentField] || 'root';
                hash[id] = hash[id] || [];
                hash[parentId] = hash[parentId] || [];
                item.items = hash[id];
                hash[parentId].push(item);
            }
            return hash.root || [];
        }

        /*********************************************************************************
         * Widget
         * @see http://kendoui-feedback.telerik.com/forums/127393-telerik-kendo-ui-feedback/suggestions/3767009-treeview-in-combobox
         *********************************************************************************/

        var DropDownTree = DropDownList.extend({

            /**
             * Initialization
             * @param element
             * @param options
             */
            init: function (element, options) {
                var that = this;
                DropDownList.fn.init.call(that, element, options);
                that._layout();
                that.refresh();
            },

            /**
             * Options
             */
            options: {
                name: 'DropDownTree',
                dataParentField: 'parentId',
                dataImageUrlField: 'icon',
                treeTemplate: '' // tree template uses item instead of data
            },

            /**
             * Events
             */
            /*
            events: [
                CHANGE,
                DATABINDING,
                DATABOUND
            ],
            */

            /**
             * Value
             * @param value
             */
            value: function (value) {
                var that = this;
                if ($.type(value) === UNDEFINED) {
                    return DropDownList.fn.value.call(this);
                } else {
                    var options = that.options;
                    // DropDownList.fn.value.call(this, value);
                    var dataItem = that.dataSource.data().find(function (record) { return record[options.dataValueField] === value; });
                    if (dataItem) {
                        that.text(dataItem[options.dataTextField]);
                    } else {
                        that.text('');
                    }
                }
            },

            /**
             * Replace popup list with treeview
             * @private
             */
            _layout: function () {
                var that = this;
                var options = this.options;
                assert.instanceof($, that.list, kendo.format(assert.messages.instanceof.default, 'this.list', 'jQuery'));

                // Find the popup list
                var popupList = $('ul', that.list);
                if (popupList.length) {

                    // Destroy it
                    var popupListWidget = kendo.widgetInstance(popupList);
                    if (popupListWidget && $.isFunction(popupListWidget.destroy)) {
                        popupListWidget.destroy();
                    }

                    // Replace it with a div
                    var popupTreeView = $(DIV)
                        .css({ maxHeight: options.height, overflowX: 'hidden', overflowY: 'scroll' });
                    popupList.replaceWith(popupTreeView);

                    // Create the treeView
                    that.treeView = popupTreeView
                        .kendoTreeView({
                            dataSource: [],
                            dataTextField: options.dataTextField,
                            loadOnDemand: false,
                            autoBind: options.autoBind,
                            template: options.treeTemplate,
                            select: function (e) {
                                // e.preventDefault();
                                var dataItem = that.treeView.dataItem(e.node);
                                // that.text(dataItem[options.dataTextField]);
                                that.value(dataItem[options.dataValueField]);
                                that.trigger(CHANGE);
                                that.popup.canClose = true;
                                that.popup.close();
                            },
                            collapse: function () {
                                // prevent closing popup when collapsing a node
                                that.popup.canClose = false;
                            },
                            expand: function () {
                                // prevent closing popup when expanding a node
                                that.popup.canClose = false;
                            }
                        })
                        .data('kendoTreeView');

                    // Keep flag for avoiding to close the popup
                    // when expanding and collapsing nodes
                    that.popup.canClose = true;

                    // Replace _closeHandler
                    that._closeHandler = function (e) {
                        that.popup.canClose = true;
                        kendo.ui.DropDownList.fn._closeHandler.call(this, e);
                    };

                    // Bind popup open and close events
                    that.popup
                        .bind('open', function () {
                            if (that.value()) {
                                var treeview = that.treeView;
                                var selectedNode = treeview.findByText(that.text());
                                treeview.expandTo(selectedNode);
                                treeview.select(selectedNode);
                            }
                        })
                        .bind('close', function (e) {
                            if (!that.popup.canClose) {
                                e.preventDefault();
                                that.popup.canClose = true;
                            }
                        });
                }
            },

            /**
             *
             * @returns {*}
             */
            items: function () {
                // return DropDownList.fn.items.call(this);
                return this.treeView.items();
            },

            /**
             * Replace dataSource
             * @param dataSource
             */
            setDataSource: function (dataSource) {
                // TODO
                DropDownList.fn.setDataSource.call(this, dataSource);
            },

            /**
             * Initialize dataSource
             * @param dataSource
             */
            _dataSource: function () {
                var that = this;
                DropDownList.fn._dataSource.call(that);
                // bind to the change event to refresh the widget
                if (that.dataSource instanceof DataSource) {
                    if (that._refreshHandler) {
                        that.dataSource.unbind(CHANGE, that._refreshHandler);
                    }
                    that._refreshHandler = $.proxy(that.refresh, that);
                    that.dataSource.bind(CHANGE, that._refreshHandler);
                }
            },

            /**
             * Refresh
             */
            refresh: function (e) {
                var that = this;
                var options = that.options;
                DropDownList.fn.refresh.call(that, e);
                if (this.treeView instanceof TreeView) {
                    this.treeView.setDataSource(processTable(that.dataSource._pristineData, options.dataValueField, options.dataParentField));
                }
            },

            /**
             * Clear DOM
             * @private
             */
            _clear: function () {
                // TODO
            },

            /**
             * Destroy
             */
            destroy: function () {
                var that = this;
                // TODO: unbind dataSource
                this.treeView.destroy();
                DropDownList.fn.destroy.call(this);
            }
        });

        kendo.ui.plugin(DropDownTree);

    }(window.jQuery));

    return window.kendo;

}, typeof define === 'function' && define.amd ? define : function (_, f) { 'use strict'; f(); });
<commit_msg>Fixed issue create by _clear method (conflict with _clear in kendo.list.js)<commit_after>/**
 * Copyright (c) 2013-2016 Memba Sarl. All rights reserved.
 * Sources at https://github.com/Memba
 */

/* jshint browser: true, jquery: true */
/* globals define: false */

(function (f, define) {
    'use strict';
    define([
        './window.assert',
        './window.logger',
        './vendor/kendo/kendo.binder',
        './vendor/kendo/kendo.dropdownlist',
        './vendor/kendo/kendo.treeview'
        // './vendor/kendo/kendo.multiselect' // required because of a test in kendo.binder.js
    ], f);
})(function () {

    'use strict';

    (function ($, undefined) {

        var kendo = window.kendo;
        var data = kendo.data;
        var DataSource = data.DataSource;
        var ui = kendo.ui;
        var DropDownList = ui.DropDownList;
        var TreeView = ui.TreeView;
        var assert = window.assert;
        var logger = new window.Logger('kidoju.widgets.dropdowntree');
        // var STRING = 'string';
        var UNDEFINED = 'undefined';
        var CHANGE = 'change';
        var DIV = '<div/>';

        /*********************************************************************************
         * Helpers
         *********************************************************************************/

        /**
         * Processes a table (dropDownList dataSource) with dataParentField into a hierarchy (Hierarchical dataSOurce for treeView)
         * Note: see also app.cache.getCategoryHierarchy
         * @param data
         * @param idField
         * @param dataParentField
         * @returns {*}
         */
        function processTable(data, idField, dataParentField) {
            var hash = {};
            for (var i = 0; i < data.length; i++) {
                var item = data[i];
                var id = item[idField];
                var parentId = item[dataParentField] || 'root';
                hash[id] = hash[id] || [];
                hash[parentId] = hash[parentId] || [];
                item.items = hash[id];
                hash[parentId].push(item);
            }
            return hash.root || [];
        }

        /*********************************************************************************
         * Widget
         * @see http://kendoui-feedback.telerik.com/forums/127393-telerik-kendo-ui-feedback/suggestions/3767009-treeview-in-combobox
         *********************************************************************************/

        var DropDownTree = DropDownList.extend({

            /**
             * Initialization
             * @param element
             * @param options
             */
            init: function (element, options) {
                var that = this;
                DropDownList.fn.init.call(that, element, options);
                that._layout();
                that.refresh();
            },

            /**
             * Options
             */
            options: {
                name: 'DropDownTree',
                dataParentField: 'parentId',
                dataImageUrlField: 'icon',
                treeTemplate: '' // tree template uses item instead of data
            },

            /**
             * Events
             */
            /*
            events: [
                CHANGE,
                DATABINDING,
                DATABOUND
            ],
            */

            /**
             * Value
             * @param value
             */
            value: function (value) {
                var that = this;
                if ($.type(value) === UNDEFINED) {
                    return DropDownList.fn.value.call(this);
                } else {
                    var options = that.options;
                    // DropDownList.fn.value.call(this, value);
                    var dataItem = that.dataSource.data().find(function (record) { return record[options.dataValueField] === value; });
                    if (dataItem) {
                        that.text(dataItem[options.dataTextField]);
                    } else {
                        that.text('');
                    }
                }
            },

            /**
             * Replace popup list with treeview
             * @private
             */
            _layout: function () {
                var that = this;
                var options = this.options;
                assert.instanceof($, that.list, kendo.format(assert.messages.instanceof.default, 'this.list', 'jQuery'));

                // Find the popup list
                var popupList = $('ul', that.list);
                if (popupList.length) {

                    // Destroy it
                    var popupListWidget = kendo.widgetInstance(popupList);
                    if (popupListWidget && $.isFunction(popupListWidget.destroy)) {
                        popupListWidget.destroy();
                    }

                    // Replace it with a div
                    var popupTreeView = $(DIV)
                        .css({ maxHeight: options.height, overflowX: 'hidden', overflowY: 'scroll' });
                    popupList.replaceWith(popupTreeView);

                    // Create the treeView
                    that.treeView = popupTreeView
                        .kendoTreeView({
                            dataSource: [],
                            dataTextField: options.dataTextField,
                            loadOnDemand: false,
                            autoBind: options.autoBind,
                            template: options.treeTemplate,
                            select: function (e) {
                                // e.preventDefault();
                                var dataItem = that.treeView.dataItem(e.node);
                                // that.text(dataItem[options.dataTextField]);
                                that.value(dataItem[options.dataValueField]);
                                that.trigger(CHANGE);
                                that.popup.canClose = true;
                                that.popup.close();
                            },
                            collapse: function () {
                                // prevent closing popup when collapsing a node
                                that.popup.canClose = false;
                            },
                            expand: function () {
                                // prevent closing popup when expanding a node
                                that.popup.canClose = false;
                            }
                        })
                        .data('kendoTreeView');

                    // Keep flag for avoiding to close the popup
                    // when expanding and collapsing nodes
                    that.popup.canClose = true;

                    // Replace _closeHandler
                    that._closeHandler = function (e) {
                        that.popup.canClose = true;
                        kendo.ui.DropDownList.fn._closeHandler.call(this, e);
                    };

                    // Bind popup open and close events
                    that.popup
                        .bind('open', function () {
                            if (that.value()) {
                                var treeview = that.treeView;
                                var selectedNode = treeview.findByText(that.text());
                                treeview.expandTo(selectedNode);
                                treeview.select(selectedNode);
                            }
                        })
                        .bind('close', function (e) {
                            if (!that.popup.canClose) {
                                e.preventDefault();
                                that.popup.canClose = true;
                            }
                        });
                }
            },

            /**
             *
             * @returns {*}
             */
            items: function () {
                // return DropDownList.fn.items.call(this);
                return this.treeView.items();
            },

            /**
             * Replace dataSource
             * @param dataSource
             */
            setDataSource: function (dataSource) {
                // TODO
                DropDownList.fn.setDataSource.call(this, dataSource);
            },

            /**
             * Initialize dataSource
             * @param dataSource
             */
            _dataSource: function () {
                var that = this;
                DropDownList.fn._dataSource.call(that);
                // bind to the change event to refresh the widget
                if (that.dataSource instanceof DataSource) {
                    if (that._refreshHandler) {
                        that.dataSource.unbind(CHANGE, that._refreshHandler);
                    }
                    that._refreshHandler = $.proxy(that.refresh, that);
                    that.dataSource.bind(CHANGE, that._refreshHandler);
                }
            },

            /**
             * Refresh
             */
            refresh: function (e) {
                var that = this;
                var options = that.options;
                DropDownList.fn.refresh.call(that, e);
                if (this.treeView instanceof TreeView) {
                    this.treeView.setDataSource(processTable(that.dataSource._pristineData, options.dataValueField, options.dataParentField));
                }
            },

            /**
             * Destroy
             */
            destroy: function () {
                var that = this;
                // TODO: unbind dataSource
                this.treeView.destroy();
                DropDownList.fn.destroy.call(this);
            }
        });

        kendo.ui.plugin(DropDownTree);

    }(window.jQuery));

    return window.kendo;

}, typeof define === 'function' && define.amd ? define : function (_, f) { 'use strict'; f(); });
<|endoftext|>


<commit_before>/*!
 * medium-editor-insert-plugin v0.2.4 - jQuery insert plugin for MediumEditor
 *
 * Embeds Addon
 *
 * https://github.com/orthes/medium-editor-insert-plugin
 *
 * Copyright (c) 2014 Vexus2 (https://github.com/vexus2)
 * Released under the MIT license
 */

(function ($) {

  $.fn.mediumInsert.registerAddon('embeds', {

    /**
     * Embeds initial function
     * @return {void}
     */
    init : function () {
      this.$el = $.fn.mediumInsert.insert.$el;
      this.setEmbedButtonEvents();
    },

    insertButton : function (buttonLabels) {
      var label = 'Embed';
      if (buttonLabels == 'fontawesome' || typeof buttonLabels === 'object' && !!(buttonLabels.fontawesome)) {
        label = '';
      }
      return '<button data-addon="embeds" data-action="add" class="medium-editor-action medium-editor-action-image mediumInsert-action">' + label + '</button>';
    },

    /**
     * Add embed to $placeholder
     * @param {element} $placeholder $placeholder to add embed to
     * @return {void}
     */
    add : function ($placeholder) {
      $.fn.mediumInsert.insert.deselect();

      var formHtml = '
<input type="text" value="" placeholder="type or paste url here" class="mediumInsert-embedsText">
';
      $(formHtml).appendTo($placeholder.prev());
      setTimeout(function () {
        $placeholder.prev().find('input').focus();
      }, 50);

      $.fn.mediumInsert.insert.deselect();

      this.currentPlaceholder = $placeholder;
      $(".mediumInsert-embedsText").focus();
    },

    setEmbedButtonEvents : function () {
      var that = this;
      $(document).on('keypress', 'input.mediumInsert-embedsText', function (e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
          that.setEnterActionEvents();
          that.removeToolbar();
        }
      });

      this.$el.on('blur', '.mediumInsert-embedsText', function () {
        that.removeToolbar();
      });

    },
    setEnterActionEvents : function () {
      var that = this;
      if ($.fn.mediumInsert.settings.enabled === false) {
        return false;
      }

      var url = $("input.mediumInsert-embedsText").val();
      if (!url) {
        return false;
      }
      var embed_tag = that.convertUrlToEmbedTag(url);
      if (!embed_tag) {
        alert('Incorrect URL format specified');
        return false;
      } else {
        embed_tag = $('

').append(embed_tag);
        that.currentPlaceholder.parent().append(embed_tag);
      }
    },

    removeToolbar : function () {
      $(".mediumInsert-embedsWire").remove();
    },

    convertUrlToEmbedTag : function (url) {
      var embed_tag = url.replace(/\n?/g, '').replace(/^((http(s)?:\/\/)?(www\.)?(youtube\.com|youtu\.be)\/(watch\?v=|v\/)?)([a-zA-Z0-9-_]+)(.*)?$/, '

')
        .replace(/http:\/\/vimeo\.com\/(\d+)$/, '')
        .replace(/https:\/\/twitter\.com\/(\w+)\/status\/(\d+)\/?$/, '

')
        .replace(/https:\/\/www\.facebook\.com\/(\w+)\/posts\/(\d+)$/, '

')
        .replace(/http:\/\/instagram\.com\/p\/(.+)\/?$/, '');
      return /<("[^"]*"|'[^']*'|[^'">])*>/.test(embed_tag) ? embed_tag : false;
    }

  });

}(jQuery));
<commit_msg>Switch YouTube embed URL to be protocol independent<commit_after>/*!
 * medium-editor-insert-plugin v0.2.4 - jQuery insert plugin for MediumEditor
 *
 * Embeds Addon
 *
 * https://github.com/orthes/medium-editor-insert-plugin
 *
 * Copyright (c) 2014 Vexus2 (https://github.com/vexus2)
 * Released under the MIT license
 */

(function ($) {

  $.fn.mediumInsert.registerAddon('embeds', {

    /**
     * Embeds initial function
     * @return {void}
     */
    init : function () {
      this.$el = $.fn.mediumInsert.insert.$el;
      this.setEmbedButtonEvents();
    },

    insertButton : function (buttonLabels) {
      var label = 'Embed';
      if (buttonLabels == 'fontawesome' || typeof buttonLabels === 'object' && !!(buttonLabels.fontawesome)) {
        label = '';
      }
      return '<button data-addon="embeds" data-action="add" class="medium-editor-action medium-editor-action-image mediumInsert-action">' + label + '</button>';
    },

    /**
     * Add embed to $placeholder
     * @param {element} $placeholder $placeholder to add embed to
     * @return {void}
     */
    add : function ($placeholder) {
      $.fn.mediumInsert.insert.deselect();

      var formHtml = '
<input type="text" value="" placeholder="type or paste url here" class="mediumInsert-embedsText">
';
      $(formHtml).appendTo($placeholder.prev());
      setTimeout(function () {
        $placeholder.prev().find('input').focus();
      }, 50);

      $.fn.mediumInsert.insert.deselect();

      this.currentPlaceholder = $placeholder;
      $(".mediumInsert-embedsText").focus();
    },

    setEmbedButtonEvents : function () {
      var that = this;
      $(document).on('keypress', 'input.mediumInsert-embedsText', function (e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
          that.setEnterActionEvents();
          that.removeToolbar();
        }
      });

      this.$el.on('blur', '.mediumInsert-embedsText', function () {
        that.removeToolbar();
      });

    },
    setEnterActionEvents : function () {
      var that = this;
      if ($.fn.mediumInsert.settings.enabled === false) {
        return false;
      }

      var url = $("input.mediumInsert-embedsText").val();
      if (!url) {
        return false;
      }
      var embed_tag = that.convertUrlToEmbedTag(url);
      if (!embed_tag) {
        alert('Incorrect URL format specified');
        return false;
      } else {
        embed_tag = $('

').append(embed_tag);
        that.currentPlaceholder.parent().append(embed_tag);
      }
    },

    removeToolbar : function () {
      $(".mediumInsert-embedsWire").remove();
    },

    convertUrlToEmbedTag : function (url) {
      var embed_tag = url.replace(/\n?/g, '').replace(/^((http(s)?:\/\/)?(www\.)?(youtube\.com|youtu\.be)\/(watch\?v=|v\/)?)([a-zA-Z0-9-_]+)(.*)?$/, '

')
        .replace(/http:\/\/vimeo\.com\/(\d+)$/, '')
        .replace(/https:\/\/twitter\.com\/(\w+)\/status\/(\d+)\/?$/, '

')
        .replace(/https:\/\/www\.facebook\.com\/(\w+)\/posts\/(\d+)$/, '

')
        .replace(/http:\/\/instagram\.com\/p\/(.+)\/?$/, '');
      return /<("[^"]*"|'[^']*'|[^'">])*>/.test(embed_tag) ? embed_tag : false;
    }

  });

}(jQuery));
<|endoftext|>


<commit_before>(function () {
  var ns = $.namespace('pskl.service');

  ns.BeforeUnloadService = function (piskelController) {
    this.piskelController = piskelController;
  };

  ns.BeforeUnloadService.prototype.init = function () {
    window.addEventListener('beforeunload', this.onBeforeUnload.bind(this));
  };

  ns.BeforeUnloadService.prototype.onBeforeUnload = function (evt) {
    pskl.app.backupService.backup();
    if (pskl.app.savedStatusService.isDirty()) {
      var confirmationMessage = 'Your Piskel seems to have unsaved changes';

      (evt || window.event).returnValue = confirmationMessage;
      return confirmationMessage;
    }
  };

})();
<commit_msg>add confirmation message when closing desktop app with unsaved changes<commit_after>(function () {
  var ns = $.namespace('pskl.service');

  ns.BeforeUnloadService = function (piskelController) {
    this.piskelController = piskelController;
  };

  ns.BeforeUnloadService.prototype.init = function () {
    if (pskl.utils.Environment.detectNodeWebkit()) {
      // Add a dedicated listener to window 'close' event in nwjs environment.
      var win = require('nw.gui').Window.get();
      win.on('close', this.onNwWindowClose.bind(this, win));
    }

    window.addEventListener('beforeunload', this.onBeforeUnload.bind(this));
  };

  /**
   * In nw.js environment "onbeforeunload" is not triggered when closing the window.
   * Polyfill the behavior here.
   */
  ns.BeforeUnloadService.prototype.onNwWindowClose = function (win) {
    var msg = this.onBeforeUnload();
    if (msg) {
      if (!window.confirm(msg)) {
        return false;
      }
    }
    win.close(true);
  };

  ns.BeforeUnloadService.prototype.onBeforeUnload = function (evt) {
    pskl.app.backupService.backup();
    if (pskl.app.savedStatusService.isDirty()) {
      var confirmationMessage = 'Your Piskel seems to have unsaved changes';

      evt = evt || window.event;
      if (evt) {
        evt.returnValue = confirmationMessage;
      }
      return confirmationMessage;
    }
  };

})();
<|endoftext|>


<commit_before>import { Vector3 } from '../Three';
import { CanvasPopup } from './CanvasPopup';

const __v1 = new Vector3();
const __v2 = new Vector3();

class StationDistancePopup extends CanvasPopup {

	constructor ( ctx, survey, startStation, endStation ) {

		super( ctx, 20000 );

		this.addLine( startStation.getPath() );
		this.addLine( endStation.getPath() );

		const p1 = survey.getGeographicalPosition( startStation, __v1 );
		const p2 = survey.getGeographicalPosition( endStation, __v2 );

		this.addValue( 'dX', Math.abs( p1.x - p2.x ) );
		this.addValue( 'dY', Math.abs( p1.y - p2.y ) );
		this.addValue( 'dZ', Math.abs( p1.z - p2.z ) );
		this.addValue( 'distance', p1.distanceTo( p2 ) );

		this.finish( endStation );

	}

}

export { StationDistancePopup };<commit_msg>add connecting line<commit_after>import { Vector3 } from '../Three';
import { CanvasPopup } from './CanvasPopup';
import { LineSegmentsGeometry } from '../core/LineSegmentsGeometry';
import { LineSegments2 } from '../core/LineSegments2';

const __v1 = new Vector3();
const __v2 = new Vector3();

class StationDistancePopup extends CanvasPopup {

	constructor ( ctx, survey, startStation, endStation ) {

		super( ctx, 20000 );

		this.addLine( startStation.getPath() );
		this.addLine( endStation.getPath() );

		const p1 = survey.getGeographicalPosition( startStation, __v1 );
		const p2 = survey.getGeographicalPosition( endStation, __v2 );

		this.addValue( 'dX', Math.abs( p1.x - p2.x ) );
		this.addValue( 'dY', Math.abs( p1.y - p2.y ) );
		this.addValue( 'dZ', Math.abs( p1.z - p2.z ) );
		this.addValue( 'distance', p1.distanceTo( p2 ) );

		this.finish( endStation );

		const geometry = new LineSegmentsGeometry();

		geometry.setPositions( [
			startStation.x, startStation.y, startStation.z,
			endStation.x, endStation.y, endStation.z
		] );

		this.line = new LineSegments2( geometry, ctx.materials.getLine2Material() );
		survey.addStatic( this.line );

	}

	close () {

		super.close();
		this.line.removeFromParent();

	}

}

export { StationDistancePopup };<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012-2013 André Bargull
 * Alle Rechte vorbehalten / All Rights Reserved.  Use is subject to license terms.
 *
 * <https://github.com/anba/es6draft>
 */

(function Generator(global) {
"use strict";

const Object = global.Object,
      Function = global.Function;

const Object_defineProperty = Object.defineProperty,
      Object_hasOwnProperty = Function.prototype.call.bind(Object.prototype.hasOwnProperty);

const GeneratorPrototype = Object.getPrototypeOf(function*(){}).prototype;
const GeneratorPrototype_next = GeneratorPrototype.next;
const genState = newSym("genState");

Object.defineProperty(GeneratorPrototype, "next", {
  value() {
    if (!Object_hasOwnProperty(this, genState)) {
      Object_defineProperty(this, genState, {value: true});
    }
    return GeneratorPrototype_next.apply(this, arguments);
  },
  writable: true, enumerable: false, configurable: true
});

// add send() function to prototype
Object.defineProperty(GeneratorPrototype, "send", {
  value() {
    if (!Object_hasOwnProperty(this, genState)) {
      Object_defineProperty(this, genState, {value: true});
      // drop arguments on first call to next()
      return GeneratorPrototype_next.call(this);
    }
    return GeneratorPrototype_next.apply(this, arguments);
  },
  writable: true, enumerable: false, configurable: true
});

})(this);
<commit_msg>Update generator compatiblity script to match new tests<commit_after>/*
 * Copyright (c) 2012-2013 André Bargull
 * Alle Rechte vorbehalten / All Rights Reserved.  Use is subject to license terms.
 *
 * <https://github.com/anba/es6draft>
 */

(function Generator(global) {
"use strict";

const Object = global.Object,
      Function = global.Function;

const Object_defineProperty = Object.defineProperty,
      Object_hasOwnProperty = Function.prototype.call.bind(Object.prototype.hasOwnProperty);

const GeneratorPrototype = Object.getPrototypeOf(function*(){}).prototype;
const GeneratorPrototype_next = GeneratorPrototype.next;
const genState = newSym("genState");

Object.defineProperty(GeneratorPrototype, "next", {
  value() {
    if (!Object_hasOwnProperty(this, genState)) {
      Object_defineProperty(this, genState, {value: true});
      // drop arguments on first call to next()
      return GeneratorPrototype_next.call(this);
    }
    return GeneratorPrototype_next.apply(this, arguments);
  },
  writable: true, enumerable: false, configurable: true
});

// add send() function to prototype
Object.defineProperty(GeneratorPrototype, "send", {
  value() {
    if (!Object_hasOwnProperty(this, genState)) {
      Object_defineProperty(this, genState, {value: true});
      // drop arguments on first call to next()
      return GeneratorPrototype_next.call(this);
    }
    return GeneratorPrototype_next.apply(this, arguments);
  },
  writable: true, enumerable: false, configurable: true
});

const iteratorSym = getSym("@@iterator");

Object.defineProperty(Object.prototype, iteratorSym, {
  get() { return () => ({next: () => Object(this.next()) }) },
  enumerable: false, configurable: true
});

})(this);
<|endoftext|>


<commit_before>//progressive enhancement (jQuery)

// $(function() {
jQuery(window).load(function() {

    var browserNotSupported = (function () {
        var div = document.createElement('DIV');
        // http://msdn.microsoft.com/en-us/library/ms537512(v=vs.85).aspx
        div.innerHTML = '';
        return div.getElementsByTagName('I').length > 0;
    }());
    if (browserNotSupported) {
        setTimeout(function() {
            $('#loading-overlay').fadeOut(300);
        }, 500);
    } else {
        $('body').append('');
        jsEnhance();
    }

    function jsEnhance() {
        $('.js-enhance--show').show();
        $('.js-enhance--hide').hide();
        $('.nojs-hidden').removeClass('nojs-hidden');

        jsEnhanceULNavToSelectNav();
        jsEnhanceHome();
        jsEnhanceLinechart();
        jsEnhancePrint();
        jsEnhanceNumberSeparator();
        jsEnhanceMarkdownCharts();
        jsEnhanceMarkdownTables();
        jsEnhancePrintCompendium();
        jsEnhanceBoxHeight();
        jsEnhanceBoxHeightResize();

        setTimeout(function() {
            $('#loading-overlay').fadeOut(300);
        }, 500);
    }

    function jsEnhanceULNavToSelectNav() {
        $('.js-enhance--ul-to-select').each(function() {
            var labeltext = $('p:first', this).text();
            var selectoptions = $('ul:first li a', this);

            //IE9 dosent like this...
            // var label = $('', {
            //     class: 'definition-emphasis',
            //     text: labeltext
            // });
            var label = $(document.createElement('label'));
            label.attr('class', 'definition-emphasis');
            label.attr('text', labeltext);

            //$(document.createElement('select')) is faster
            // var newselect = $('<select>', {
            //     class: 'field field--spaced'
            // });
            var newselect = $(document.createElement('select'));
            newselect.attr('class', 'field field--spaced');

            newselect.append($('<option>', {
                value: '',
                text: 'Select a related time series'
            }));

            newselect.change(function() {
                var location = $(this).find('option:selected').val();
                if (location) {
                    window.location = location;
                }
            });

            $.each(selectoptions, function(i, item) {
                newselect.append($('<option>', {
                    value: $(this).attr('href'),
                    text: $(this).text()
                }));
            });

            label.append(newselect);

            $(this).html(label);

        });
    }

    function jsEnhanceHome() {

        var herostatarea = $('.stat__wrap--home');

        $(herostatarea).click(function() {
            var herostatarealink = $('a:last', this).attr('href');

            window.location = herostatarealink;
        });

        $(herostatarea).css({
            'cursor': 'pointer'
        });

        $(herostatarea).hover(function() {
            $(this).css({
                'background-color': '#f8fadc'
            })
        }, function() {
            $(this).css({
                'background-color': 'transparent'
            });
        });

    }

    function jsEnhanceLinechart() {

        var chartContainer = $("[data-chart]");
        if (!chartContainer.length) {
            return;
        }

        var location = stripTrailingSlash(window.location.pathname) + "/data";
        // console.debug("Downloading timseries data from " + location)

        $.getJSON(location, function(timeseries) {
            // console.log("Successfuly read timseries data");
            linechart = linechart(timeseries); //Global variable

        }).fail(function(d, textStatus, error) {
            // console.error("Failed reading timseries, status: " + textStatus + ", error: " + error)
        });
    }

    function stripTrailingSlash(str) {
        if(str.substr(-1) === '/') {
            return str.substr(0, str.length - 1);
        }
        return str;
    }

    function jsEnhanceMarkdownCharts() {

        var chartContainer = $(".markdown-chart-container");
        if (!chartContainer.length) {
            return;
        }

        chartContainer.each(function() {
            var $this = $(this);
            var uri = $this.attr('id');
            $this.empty();

            if (uri.indexOf('/') !== 0) {
                uri = '/' + uri;
            }

            new pym.Parent(uri, uri + "/chart", {});
        });
    }

    function jsEnhancePrint() {
    $('#jsEnhancePrint').click(function()
        {
            window.print();
            return false;
        });
    }

    function jsEnhanceNumberSeparator() {
      // Adapted from http://stackoverflow.com/questions/14075014/jquery-function-to-to-format-number-with-commas-and-decimal
      $( ".stat__figure-enhance" ).each(function( index ) {
        //console.log( index + ": " + $( this ).text() );
        var number = $( this ).text();
        var n= number.toString().split(".");
        //Comma-fies the first part
        n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        // //Combines the two sections
        $( this ).text(n.join("."));
      });
    }

    function jsEnhanceMarkdownTables() {

        var chartContainer = $(".markdown-table-container");
        if (!chartContainer.length) {
            return;
        }

        chartContainer.each(function() {
            var $this = $(this);
            var uri = $this.attr('id');
            $this.empty();

            if (uri.indexOf('/') !== 0) {
                uri = '/' + uri;
            }

            new pym.Parent(uri, uri + "/table", {});
        });
    }

    function jsEnhancePrintCompendium() {
        $('#jsEnhancePrintCompendium').click(function(e) {
            addLoadingOverlay();

            // TODO Will get function to add in div, so no empty divs on page at load
            //$("

").insertAfter('.desktop-grid-full-width');

            // TODO Remove existing page content from print
            // $(".wrapper").remove();

            $('.chapter').each(function() {
                var url = $(this).attr('href');

                var getContent = ('main');

                $('
').load(url, function() {
                    $('.print-content').append("
" + $(this).find(getContent).html() + "
");
                });

                e.preventDefault();
            });

            $(document).ajaxStop(function() {
                window.print();
                location.reload();
            });
        });
    }

    function jsEnhanceBoxHeight() {
        if ($(window).width() > 608) {
            var highestBox = 0;
            $('.box--headline').each(function(){

                if($(this).height() > highestBox) {
                   highestBox = $(this).height();
               }
            });

            $('.box--headline').height(highestBox);
        }

        function jsEnhanceBoxHeightResize() {
            $( window ).resize(function() {
                $('.box--headline').height('auto');
                jsEnhanceBoxHeight();
            });
        }
    }

});<commit_msg>Remove box-resize function from box-height function<commit_after>//progressive enhancement (jQuery)

// $(function() {
jQuery(window).load(function() {

    var browserNotSupported = (function () {
        var div = document.createElement('DIV');
        // http://msdn.microsoft.com/en-us/library/ms537512(v=vs.85).aspx
        div.innerHTML = '';
        return div.getElementsByTagName('I').length > 0;
    }());
    if (browserNotSupported) {
        setTimeout(function() {
            $('#loading-overlay').fadeOut(300);
        }, 500);
    } else {
        $('body').append('');
        jsEnhance();
    }

    function jsEnhance() {
        $('.js-enhance--show').show();
        $('.js-enhance--hide').hide();
        $('.nojs-hidden').removeClass('nojs-hidden');

        jsEnhanceULNavToSelectNav();
        jsEnhanceHome();
        jsEnhanceLinechart();
        jsEnhancePrint();
        jsEnhanceNumberSeparator();
        jsEnhanceMarkdownCharts();
        jsEnhanceMarkdownTables();
        jsEnhancePrintCompendium();
        jsEnhanceBoxHeight();
        jsEnhanceBoxHeightResize();

        setTimeout(function() {
            $('#loading-overlay').fadeOut(300);
        }, 500);
    }

    function jsEnhanceULNavToSelectNav() {
        $('.js-enhance--ul-to-select').each(function() {
            var labeltext = $('p:first', this).text();
            var selectoptions = $('ul:first li a', this);

            //IE9 dosent like this...
            // var label = $('', {
            //     class: 'definition-emphasis',
            //     text: labeltext
            // });
            var label = $(document.createElement('label'));
            label.attr('class', 'definition-emphasis');
            label.attr('text', labeltext);

            //$(document.createElement('select')) is faster
            // var newselect = $('<select>', {
            //     class: 'field field--spaced'
            // });
            var newselect = $(document.createElement('select'));
            newselect.attr('class', 'field field--spaced');

            newselect.append($('<option>', {
                value: '',
                text: 'Select a related time series'
            }));

            newselect.change(function() {
                var location = $(this).find('option:selected').val();
                if (location) {
                    window.location = location;
                }
            });

            $.each(selectoptions, function(i, item) {
                newselect.append($('<option>', {
                    value: $(this).attr('href'),
                    text: $(this).text()
                }));
            });

            label.append(newselect);

            $(this).html(label);

        });
    }

    function jsEnhanceHome() {

        var herostatarea = $('.stat__wrap--home');

        $(herostatarea).click(function() {
            var herostatarealink = $('a:last', this).attr('href');

            window.location = herostatarealink;
        });

        $(herostatarea).css({
            'cursor': 'pointer'
        });

        $(herostatarea).hover(function() {
            $(this).css({
                'background-color': '#f8fadc'
            })
        }, function() {
            $(this).css({
                'background-color': 'transparent'
            });
        });

    }

    function jsEnhanceLinechart() {

        var chartContainer = $("[data-chart]");
        if (!chartContainer.length) {
            return;
        }

        var location = stripTrailingSlash(window.location.pathname) + "/data";
        // console.debug("Downloading timseries data from " + location)

        $.getJSON(location, function(timeseries) {
            // console.log("Successfuly read timseries data");
            linechart = linechart(timeseries); //Global variable

        }).fail(function(d, textStatus, error) {
            // console.error("Failed reading timseries, status: " + textStatus + ", error: " + error)
        });
    }

    function stripTrailingSlash(str) {
        if(str.substr(-1) === '/') {
            return str.substr(0, str.length - 1);
        }
        return str;
    }

    function jsEnhanceMarkdownCharts() {

        var chartContainer = $(".markdown-chart-container");
        if (!chartContainer.length) {
            return;
        }

        chartContainer.each(function() {
            var $this = $(this);
            var uri = $this.attr('id');
            $this.empty();

            if (uri.indexOf('/') !== 0) {
                uri = '/' + uri;
            }

            new pym.Parent(uri, uri + "/chart", {});
        });
    }

    function jsEnhancePrint() {
    $('#jsEnhancePrint').click(function()
        {
            window.print();
            return false;
        });
    }

    function jsEnhanceNumberSeparator() {
      // Adapted from http://stackoverflow.com/questions/14075014/jquery-function-to-to-format-number-with-commas-and-decimal
      $( ".stat__figure-enhance" ).each(function( index ) {
        //console.log( index + ": " + $( this ).text() );
        var number = $( this ).text();
        var n= number.toString().split(".");
        //Comma-fies the first part
        n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        // //Combines the two sections
        $( this ).text(n.join("."));
      });
    }

    function jsEnhanceMarkdownTables() {

        var chartContainer = $(".markdown-table-container");
        if (!chartContainer.length) {
            return;
        }

        chartContainer.each(function() {
            var $this = $(this);
            var uri = $this.attr('id');
            $this.empty();

            if (uri.indexOf('/') !== 0) {
                uri = '/' + uri;
            }

            new pym.Parent(uri, uri + "/table", {});
        });
    }

    function jsEnhancePrintCompendium() {
        $('#jsEnhancePrintCompendium').click(function(e) {
            addLoadingOverlay();

            // TODO Will get function to add in div, so no empty divs on page at load
            //$("

").insertAfter('.desktop-grid-full-width');

            // TODO Remove existing page content from print
            // $(".wrapper").remove();

            $('.chapter').each(function() {
                var url = $(this).attr('href');

                var getContent = ('main');

                $('
').load(url, function() {
                    $('.print-content').append("
" + $(this).find(getContent).html() + "
");
                });

                e.preventDefault();
            });

            $(document).ajaxStop(function() {
                window.print();
                location.reload();
            });
        });
    }

    function jsEnhanceBoxHeight() {
        if ($(window).width() > 608) {
            var highestBox = 0;
            $('.box--headline').each(function(){

                if($(this).height() > highestBox) {
                   highestBox = $(this).height();
               }
            });

            $('.box--headline').height(highestBox);
        }
    }

    function jsEnhanceBoxHeightResize() {
        $( window ).resize(function() {
            $('.box--headline').height('auto');
            jsEnhanceBoxHeight();
        });
    }

});<|endoftext|>


<commit_before>(function(coinswap) {

coinswap.Trade = Backbone.Model.extend({
  defaults: {
    buy: true,
    pair: ['LTC', 'BTC'],
    symbols: ['', ''],
    balances: [0, 0],
    price: 0,
    quantity: 0,
    total: 0
  },

  initialize: function(attributes, options) {
    if(options.id) {
      var pair = this.get('pair');
      var coins = this.get('coins');
      pair[0] = options.id;
      pair[1] = coins.get(pair[0]).get('pairs')[0];
    }

    this.on('change:pair', this.updatePair);
    this.on('change:price', this.updateValues);
    this.on('change:quantity', this.updateValues);
    this.on('change:total', this.updateTotal);

    coinswap.trade.on('depth', this.updateDepth.bind(this));

    this.updatePair();
  },

  updatePair: function() {
    var pair = this.getPair();
    var pairs = pair[0].get('pairs');
    if(pairs.indexOf(pair[1].id) === -1)
      this.get('pair')[1] = pairs[0];

    var ticker = coinswap.trade.ticker(pair[0].id, pair[1].id);

    this.set({
      symbols: [ pair[0].get('symbol'), pair[1].get('symbol') ],
      balances: [ pair[0].get('balance'), pair[1].get('balance') ],
      bestBid: ticker.bestBid,
      bestAsk: ticker.bestAsk
    });
  },

  getPair: function() {
    var pair = this.get('pair');
    var coins = this.get('coins');

    var models = [
      coins.get(pair[0]),
      coins.get(pair[1])
    ];

    if(models[0].get('index') < models[1].get('index'))
      models.reverse();

    return models;
  },

  updateValues: function() {
    var total = coinmath.multiply(this.get('price'), this.get('quantity'));
    this.set('total', total, { silent: true });
  },

  updateTotal: function() {
    var quantity = coinmath.divide(this.get('total'), this.get('price'));
    this.set('quantity', quantity, { silent: true });
  },

  updateDepth: function() {
    this.set('depth', coinswap.trade.depth());
  }
});

})(coinswap);
<commit_msg>Trade: Ensure pair ordering is correct<commit_after>(function(coinswap) {

coinswap.Trade = Backbone.Model.extend({
  defaults: {
    buy: true,
    pair: ['LTC', 'BTC'],
    symbols: ['', ''],
    balances: [0, 0],
    price: 0,
    quantity: 0,
    total: 0
  },

  initialize: function(attributes, options) {
    if(options.id) {
      var pair = this.get('pair');
      var coins = this.get('coins');
      pair[0] = options.id;
      pair[1] = coins.get(pair[0]).get('pairs')[0];
    }

    this.on('change:pair', this.updatePair);
    this.on('change:price', this.updateValues);
    this.on('change:quantity', this.updateValues);
    this.on('change:total', this.updateTotal);

    coinswap.trade.on('depth', this.updateDepth.bind(this));

    this.updatePair();
  },

  updatePair: function() {
    var pair = this.getPair();
    var pairs = pair[0].get('pairs');
    if(pairs.indexOf(pair[1].id) === -1)
      this.get('pair')[1] = pairs[0];

    var ticker = coinswap.trade.ticker(pair[0].id, pair[1].id);

    this.set('pair', [pair[0].get('id'), pair[1].get('id')], { silent: true });

    this.set({
      symbols: [ pair[0].get('symbol'), pair[1].get('symbol') ],
      balances: [ pair[0].get('balance'), pair[1].get('balance') ],
      bestBid: ticker.bestBid,
      bestAsk: ticker.bestAsk
    });
  },

  getPair: function() {
    var pair = this.get('pair');
    var coins = this.get('coins');

    var models = [
      coins.get(pair[0]),
      coins.get(pair[1])
    ];

    if(models[0].get('index') < models[1].get('index'))
      models.reverse();

    return models;
  },

  updateValues: function() {
    var total = coinmath.multiply(this.get('price'), this.get('quantity'));
    this.set('total', total, { silent: true });
  },

  updateTotal: function() {
    var quantity = coinmath.divide(this.get('total'), this.get('price'));
    this.set('quantity', quantity, { silent: true });
  },

  updateDepth: function() {
    this.set('depth', coinswap.trade.depth());
  }
});

})(coinswap);
<|endoftext|>


<commit_before>var defaultLanguage = undefined;
function getDefaultLanguage() {
    if (!defaultLanguage && app)
        defaultLanguage = app.getConfig().getDefaultLanguage();
    return defaultLanguage;
}

function convertBasicHtml(content) {

    var options = Opal.hash2(['backend', 'safe', 'attributes'], {
        backend: 'html5',
        safe: 'safeMode',
        attributes: 'showtitle icons=font@ source-highlighter=highlight.js platform=opal platform-opal env=browser env-browser idprefix idseparator=- '
    });

    var doc = Opal.Asciidoctor.$load(content,options);

    doc.attributes.keys["lang"] = doc.attributes.keys["lang"] || getDefaultLanguage();

    return doc.$convert();
}

function convertHtmlBook(content) {

    var options = Opal.hash2(['backend', 'safe', 'attributes', "header_footer"], {
        backend: 'html5',
        safe: 'safeMode',
        attributes: 'showtitle icons=font@ source-highlighter=highlight.js platform=opal platform-opal env=browser env-browser idprefix idseparator=- '
        , 'header_footer': true
    });

    var doc = Opal.Asciidoctor.$load(content,options);

    doc.attributes.keys["lang"] = doc.attributes.keys["lang"] || getDefaultLanguage();

    return doc.$render();
}

function convertHtmlArticle(content) {

    var options = Opal.hash2(['attributes', 'header_footer'],
        {
            'attributes': ['backend=html5', 'doctype=article',"idprefix=","idseparator=-"],
            'header_footer': true
        });

    var doc = Opal.Asciidoctor.$load(content,options);

    doc.attributes.keys["lang"] = doc.attributes.keys["lang"] || getDefaultLanguage();

    return doc.$render();
}

function convertDocbook(content, includeHeader) {

    var options = Opal.hash2(['attributes', 'header_footer'],
        {
            'attributes': ['backend=docbook5', 'doctype=book'],
            'header_footer': includeHeader
        });

    var doc = Opal.Asciidoctor.$load(content, options);

    doc.attributes.keys["lang"] = doc.attributes.keys["lang"] || getDefaultLanguage();

    return doc.$render();
}

function convertDocbookArticle(content) {

    var options = Opal.hash2(["lang", 'attributes', 'header_footer'],
        {
            'attributes': ['backend=docbook5', 'doctype=article'],
            'header_footer': true
        });

    var doc = Opal.Asciidoctor.$load(content,options);

    doc.attributes.keys["lang"] = doc.attributes.keys["lang"] || getDefaultLanguage();

    return doc.$render();
}

function scrollTo60(position) {
    $(window).scrollTop(position - 60);
}

function runScroller(content) {

    var renderedSelection = Opal.Asciidoctor.$render(content);

    if (renderedSelection.trim() == "") {
        return;
    }
    else if ($(renderedSelection).css("page-break-after")) {
        //page break element
        return;
    }
    else if ($(renderedSelection).is("hr")) {
        // horizontal rules
        return;
    }
    else if ($(renderedSelection).is(".imageblock")) {
        var src = $(renderedSelection).find("img").attr("src");
        scrollTo60($("img[src^='" + src + "']").offset().top);
        return;
    }

    if ($(renderedSelection).is(".admonitionblock")) {
        scrollToElement(".admonitionblock", $(renderedSelection).find(".content").text());
    }
    else if ($(renderedSelection).is(".exampleblock")) {
        scrollToUniqueElement(".exampleblock", $(renderedSelection).text(), /^Example \d+\./, "Example 1.");
    }
    else if ($(renderedSelection).is(".listingblock")) {
        scrollToElement(".listingblock", $(renderedSelection).text());
    }
    else if ($(renderedSelection).is(".literalblock")) {
        scrollToElement(".literalblock", $(renderedSelection).text());
    }
    else if ($(renderedSelection).is(".openblock")) {
        scrollToElement(".openblock", $(renderedSelection).text());
    }
    else if ($(renderedSelection).is(".sidebarblock")) {
        scrollToElement(".sidebarblock", $(renderedSelection).text());
    }
    else if ($(renderedSelection).is(".quoteblock")) {
        scrollToElement(".quoteblock > blockquote, .verseblock > .content", $(renderedSelection).find(".paragraph").text());
    }
    else if ($(renderedSelection).is(".paragraph")) {
        scrollToElement(".paragraph, .quoteblock > blockquote", $($(renderedSelection).get(0)).text());
    }
    else if ($(renderedSelection).is(".ulist")) {
        scrollToElement(".ulist:not(.checklist) > ul > li", $(renderedSelection).text());
    }
    else if ($(renderedSelection).is(".olist")) {
        scrollToElement(".olist > ol > li", $(renderedSelection).text());
    }
    else if ($(renderedSelection).is(".colist")) {
        scrollToUniqueElement(".colist > table > tbody > tr", $(renderedSelection).text(), /^\d+ */, "");
    }
    else if ($(renderedSelection).is(".tableblock")) {
        scrollToUniqueElement("table.tableblock, table.frame-all", $(renderedSelection).text(), /^Table \d+\./, "Table 1.");
    }
    else {
        var header = false;

        $("*:header").each(function () {
            if ($(this).text().trim() == $(renderedSelection).text().trim()) {
                header = true;
                scrollTo60($(this).offset().top);
                return false;
            }
        });

        if (!header) {
            var search = $("*:contains(" + $(renderedSelection).text().trim() + "):last");
            scrollTo60(search.offset().top);
        }
    }
}

function scrollToElement(elements, content) {
    if(content.trim() == "")
        return;

    $(elements).each(function () {
        if (simplify($(this).text()) == simplify(content)) {
            scrollTo60($(this).offset().top);
            return false;
        }
    });
}

function scrollToUniqueElement(elements, content, pattern, expected) {
    $(elements).each(function () {
        var element = $(this).text().trim().replace(pattern, expected);
        if (simplify(element) == simplify(content)) {
            scrollTo60($(this).offset().top);
            return false;
        }
    });
}

function simplify(text) {
    return text.replace(/( |\n|\r|\t|\")/g, "");
}
<commit_msg>disable sectanchors attributes<commit_after>var defaultLanguage = undefined;
function getDefaultLanguage() {
    if (!defaultLanguage && app)
        defaultLanguage = app.getConfig().getDefaultLanguage();
    return defaultLanguage;
}

function convertBasicHtml(content) {

    var options = Opal.hash2(['backend', 'safe', 'attributes'], {
        backend: 'html5',
        safe: 'safeMode',
        attributes: 'showtitle icons=font@ source-highlighter=highlight.js platform=opal platform-opal env=browser env-browser idprefix sectanchors idseparator=- '
    });

    var doc = Opal.Asciidoctor.$load(content,options);

    doc.attributes.keys["lang"] = doc.attributes.keys["lang"] || getDefaultLanguage();

    return doc.$convert();
}

function convertHtmlBook(content) {

    var options = Opal.hash2(['backend', 'safe', 'attributes', "header_footer"], {
        backend: 'html5',
        safe: 'safeMode',
        attributes: 'showtitle icons=font@ source-highlighter=highlight.js platform=opal platform-opal env=browser env-browser idprefix sectanchors idseparator=- '
        , 'header_footer': true
    });

    var doc = Opal.Asciidoctor.$load(content,options);

    doc.attributes.keys["lang"] = doc.attributes.keys["lang"] || getDefaultLanguage();

    return doc.$render();
}

function convertHtmlArticle(content) {

    var options = Opal.hash2(['attributes', 'header_footer'],
        {
            'attributes': ['backend=html5', 'doctype=article',"idprefix=","idseparator=-","sectanchors="],
            'header_footer': true
        });

    var doc = Opal.Asciidoctor.$load(content,options);

    doc.attributes.keys["lang"] = doc.attributes.keys["lang"] || getDefaultLanguage();

    return doc.$render();
}

function convertDocbook(content, includeHeader) {

    var options = Opal.hash2(['attributes', 'header_footer'],
        {
            'attributes': ['backend=docbook5', 'doctype=book'],
            'header_footer': includeHeader
        });

    var doc = Opal.Asciidoctor.$load(content, options);

    doc.attributes.keys["lang"] = doc.attributes.keys["lang"] || getDefaultLanguage();

    return doc.$render();
}

function convertDocbookArticle(content) {

    var options = Opal.hash2(["lang", 'attributes', 'header_footer'],
        {
            'attributes': ['backend=docbook5', 'doctype=article'],
            'header_footer': true
        });

    var doc = Opal.Asciidoctor.$load(content,options);

    doc.attributes.keys["lang"] = doc.attributes.keys["lang"] || getDefaultLanguage();

    return doc.$render();
}

function scrollTo60(position) {
    $(window).scrollTop(position - 60);
}

function runScroller(content) {

    var renderedSelection = Opal.Asciidoctor.$render(content);

    if (renderedSelection.trim() == "") {
        return;
    }
    else if ($(renderedSelection).css("page-break-after")) {
        //page break element
        return;
    }
    else if ($(renderedSelection).is("hr")) {
        // horizontal rules
        return;
    }
    else if ($(renderedSelection).is(".imageblock")) {
        var src = $(renderedSelection).find("img").attr("src");
        scrollTo60($("img[src^='" + src + "']").offset().top);
        return;
    }

    if ($(renderedSelection).is(".admonitionblock")) {
        scrollToElement(".admonitionblock", $(renderedSelection).find(".content").text());
    }
    else if ($(renderedSelection).is(".exampleblock")) {
        scrollToUniqueElement(".exampleblock", $(renderedSelection).text(), /^Example \d+\./, "Example 1.");
    }
    else if ($(renderedSelection).is(".listingblock")) {
        scrollToElement(".listingblock", $(renderedSelection).text());
    }
    else if ($(renderedSelection).is(".literalblock")) {
        scrollToElement(".literalblock", $(renderedSelection).text());
    }
    else if ($(renderedSelection).is(".openblock")) {
        scrollToElement(".openblock", $(renderedSelection).text());
    }
    else if ($(renderedSelection).is(".sidebarblock")) {
        scrollToElement(".sidebarblock", $(renderedSelection).text());
    }
    else if ($(renderedSelection).is(".quoteblock")) {
        scrollToElement(".quoteblock > blockquote, .verseblock > .content", $(renderedSelection).find(".paragraph").text());
    }
    else if ($(renderedSelection).is(".paragraph")) {
        scrollToElement(".paragraph, .quoteblock > blockquote", $($(renderedSelection).get(0)).text());
    }
    else if ($(renderedSelection).is(".ulist")) {
        scrollToElement(".ulist:not(.checklist) > ul > li", $(renderedSelection).text());
    }
    else if ($(renderedSelection).is(".olist")) {
        scrollToElement(".olist > ol > li", $(renderedSelection).text());
    }
    else if ($(renderedSelection).is(".colist")) {
        scrollToUniqueElement(".colist > table > tbody > tr", $(renderedSelection).text(), /^\d+ */, "");
    }
    else if ($(renderedSelection).is(".tableblock")) {
        scrollToUniqueElement("table.tableblock, table.frame-all", $(renderedSelection).text(), /^Table \d+\./, "Table 1.");
    }
    else {
        var header = false;

        $("*:header").each(function () {
            if ($(this).text().trim() == $(renderedSelection).text().trim()) {
                header = true;
                scrollTo60($(this).offset().top);
                return false;
            }
        });

        if (!header) {
            var search = $("*:contains(" + $(renderedSelection).text().trim() + "):last");
            scrollTo60(search.offset().top);
        }
    }
}

function scrollToElement(elements, content) {
    if(content.trim() == "")
        return;

    $(elements).each(function () {
        if (simplify($(this).text()) == simplify(content)) {
            scrollTo60($(this).offset().top);
            return false;
        }
    });
}

function scrollToUniqueElement(elements, content, pattern, expected) {
    $(elements).each(function () {
        var element = $(this).text().trim().replace(pattern, expected);
        if (simplify(element) == simplify(content)) {
            scrollTo60($(this).offset().top);
            return false;
        }
    });
}

function simplify(text) {
    return text.replace(/( |\n|\r|\t|\")/g, "");
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

/*jslint node: true */
'use strict';

var hajimaru = require(__dirname + '/../lib/hajimaru'),
    os = require('os'),
    pkg = require(__dirname + '/../package.json'),
    program = require('commander'),
    version = pkg.version;

program
  .version(version)
  .usage('<project>')
  .option('-c, --coffeescript', 'enable coffeescript support')
  .parse(process.argv);

if (program.args.length !== 1) {
  console.log(program.help());
  return;
}

var project = {};
var directories = ['lib', 'test'];
var files = {};
var dependencies = {};
var eol = 'win32' === os.platform() ? '\r\n' : '\n';

project.root = program.args[0];
project.unroot = project.root.replace(/-/g, '_');
project.ext = program.coffeescript ? '.coffee' : '.js';
project.directories = directories;
project.files = files;

if (program.coffeescript) {
  dependencies['coffee-script'] = '*';
}

files['.gitignore'] = [
  '.DS_store',
  'lib-cov',
  '*.seed',
  '*.log',
  '*.csv',
  '*.dat',
  '*.out',
  '*.pid',
  '*.swp',
  '*.swo',
  '*.gz',
  '',
  'pids',
  'logs',
  'results',
  '',
  'npm-debug.log',
  'node_modules/'
].join(eol);

files['.npmignore'] = [
  '.DS_Store',
  'lib-cov',
  'coverage.html',
  '.git*',
  'docs/',
  'examples/',
  'support/',
  'test/',
  'testing.js'
].join(eol);

files['index.js'] = [
  '\'use strict\';',
  '',
  'module.exports = require(\'./lib/index\');'
].join(eol);

if (program.coffeescript) {
  var temp = files['index.js'];
  files['index.js'] = [
    'require("coffee-script");',
    temp
  ].join(eol);
}

files['package.json'] = JSON.stringify({
  name: project.root,
  version: '0.0.1',
  description: '',
  main: 'index.js',
  scripts: {
    'start': 'node index',
    'test': 'node test/index'
  },
  repository: '',
  author: '',
  license: '',
  dependencies: dependencies
}, null, 4);

files['README.md'] = [
  '# ' + project.root
].join(eol);

files['lib/index' + project.ext] = [
  '\'use strict\';'
].join(eol);

files['test/index' + project.ext] = [
  '\'use strict\';',
  '',
  'var assert = require(\'assert\');',
  '',
  'module.exports = function() { assert(1 > 0); };'
].join(eol);

hajimaru.generate(project);
<commit_msg>Fix sample test assertion<commit_after>#!/usr/bin/env node

/*jslint node: true */
'use strict';

var hajimaru = require(__dirname + '/../lib/hajimaru'),
    os = require('os'),
    pkg = require(__dirname + '/../package.json'),
    program = require('commander'),
    version = pkg.version;

program
  .version(version)
  .usage('<project>')
  .option('-c, --coffeescript', 'enable coffeescript support')
  .parse(process.argv);

if (program.args.length !== 1) {
  console.log(program.help());
  return;
}

var project = {};
var directories = ['lib', 'test'];
var files = {};
var dependencies = {};
var eol = 'win32' === os.platform() ? '\r\n' : '\n';

project.root = program.args[0];
project.unroot = project.root.replace(/-/g, '_');
project.ext = program.coffeescript ? '.coffee' : '.js';
project.directories = directories;
project.files = files;

if (program.coffeescript) {
  dependencies['coffee-script'] = '*';
}

files['.gitignore'] = [
  '.DS_store',
  'lib-cov',
  '*.seed',
  '*.log',
  '*.csv',
  '*.dat',
  '*.out',
  '*.pid',
  '*.swp',
  '*.swo',
  '*.gz',
  '',
  'pids',
  'logs',
  'results',
  '',
  'npm-debug.log',
  'node_modules/'
].join(eol);

files['.npmignore'] = [
  '.DS_Store',
  'lib-cov',
  'coverage.html',
  '.git*',
  'docs/',
  'examples/',
  'support/',
  'test/',
  'testing.js'
].join(eol);

files['index.js'] = [
  '\'use strict\';',
  '',
  'module.exports = require(\'./lib\');'
].join(eol);

if (program.coffeescript) {
  var temp = files['index.js'];
  files['index.js'] = [
    'require("coffee-script");',
    temp
  ].join(eol);
}

files['package.json'] = JSON.stringify({
  name: project.root,
  version: '0.0.1',
  description: '',
  main: 'index.js',
  scripts: {
    'start': 'node index',
    'test': 'node test/index'
  },
  repository: '',
  author: '',
  license: '',
  dependencies: dependencies
}, null, 4);

files['README.md'] = [
  '# ' + project.root
].join(eol);

files['lib/index' + project.ext] = [
  '\'use strict\';'
].join(eol);

files['test/index' + project.ext] = [
  '\'use strict\';',
  '',
  'var assert = require(\'assert\');',
  'var ' + project.unroot + ' = require(\'..\');',
  '',
  'assert(typeof ' + project.unroot + ' === \'object\');'
].join(eol);

hajimaru.generate(project);
<|endoftext|>