<commit_before>// tipsy, facebook style tooltips for jquery
// version 1.0.0a
// (c) 2008-2010 jason frame [jason@onehackoranother.com]
// released under the MIT license

(function($) {

    function maybeCall(thing, ctx) {
        return (typeof thing == 'function') ? (thing.call(ctx)) : thing;
    };

    function isElementInDOM(ele) {
      while (ele = ele.parentNode) {
        if (ele == document) return true;
      }
      return false;
    };

    function Tipsy(element, options) {
        this.$element = $(element);
        this.options = options;
        this.enabled = true;
        this.fixTitle();
    };

    Tipsy.prototype = {
        show: function() {
            var title = this.getTitle();
            if (title && this.enabled) {
                var $tip = this.tip();

                $tip.find('.tipsy-inner')[this.options.html ? 'html' : 'text'](title);
                $tip[0].className = 'tipsy'; // reset classname in case of dynamic gravity
                $tip.remove().css({top: 0, left: 0, visibility: 'hidden', display: 'block'}).prependTo(document.body);

                var pos = $.extend({}, this.$element.offset(), {
                    width: this.$element[0].offsetWidth,
                    height: this.$element[0].offsetHeight
                });

                var actualWidth = $tip[0].offsetWidth,
                    actualHeight = $tip[0].offsetHeight,
                    gravity = maybeCall(this.options.gravity, this.$element[0]);

                var tp;
                switch (gravity.charAt(0)) {
                    case 'n':
                        tp = {top: pos.top + pos.height + this.options.offset, left: pos.left + pos.width / 2 - actualWidth / 2};
                        break;
                    case 's':
                        tp = {top: pos.top - actualHeight - this.options.offset, left: pos.left + pos.width / 2 - actualWidth / 2};
                        break;
                    case 'e':
                        tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth - this.options.offset};
                        break;
                    case 'w':
                        tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width + this.options.offset};
                        break;
                }

                if (gravity.length == 2) {
                    if (gravity.charAt(1) == 'w') {
                        tp.left = pos.left + pos.width / 2 - 15;
                    } else {
                        tp.left = pos.left + pos.width / 2 - actualWidth + 15;
                    }
                }

                $tip.css(tp).addClass('tipsy-' + gravity);
                $tip.find('.tipsy-arrow')[0].className = 'tipsy-arrow tipsy-arrow-' + gravity.charAt(0);
                if (this.options.className) {
                    $tip.addClass(maybeCall(this.options.className, this.$element[0]));
                }

                if (this.options.fade) {
                    $tip.stop().css({opacity: 0, display: 'block', visibility: 'visible'}).animate({opacity: this.options.opacity});
                } else {
                    $tip.css({visibility: 'visible', opacity: this.options.opacity});
                }
            }
        },

        hide: function() {
            if (this.options.fade) {
                this.tip().stop().fadeOut(function() { $(this).remove(); });
            } else {
                this.tip().remove();
            }
        },

        fixTitle: function() {
            var $e = this.$element;
            if ($e.attr('title') || typeof($e.attr('original-title')) != 'string') {
                $e.attr('original-title', $e.attr('title') || '').removeAttr('title');
            }
        },

        getTitle: function() {
            var title, $e = this.$element, o = this.options;
            this.fixTitle();
            var title, o = this.options;
            if (typeof $e.attr('original-title') == 'string') {
                title = $e.attr('original-title');
                //title = $e.attr(o.title == 'title' ? 'original-title' : o.title);
            } else if (typeof o.title == 'string') {
                title = o.title;
            } else if (typeof o.title == 'function') {
                title = o.title.call($e[0]);
            }
            title = ('' + title).replace(/(^\s*|\s*$)/, "");
            return title || o.fallback;
        },

        tip: function() {
            if (!this.$tip) {
                this.$tip = $('

').html('

');
                this.$tip.data('tipsy-pointee', this.$element[0]);
            }
            return this.$tip;
        },

        validate: function() {
            if (!this.$element[0].parentNode) {
                this.hide();
                this.$element = null;
                this.options = null;
            }
        },

        enable: function() { this.enabled = true; },
        disable: function() { this.enabled = false; },
        toggleEnabled: function() { this.enabled = !this.enabled; }
    };

    $.fn.tipsy = function(options) {

        if (options === true) {
            return this.data('tipsy');
        } else if (typeof options == 'string') {
            var tipsy = this.data('tipsy');
            if (tipsy) tipsy[options]();
            return this;
        }

        options = $.extend({}, $.fn.tipsy.defaults, options);

        function get(ele) {
            var tipsy = $.data(ele, 'tipsy');
            if (!tipsy) {
                tipsy = new Tipsy(ele, $.fn.tipsy.elementOptions(ele, options));
                $.data(ele, 'tipsy', tipsy);
            }
            return tipsy;
        }

        function enter() {
            var tipsy = get(this);
            tipsy.hoverState = 'in';
            if (options.delayIn == 0) {
                tipsy.show();
            } else {
                tipsy.fixTitle();
                setTimeout(function() { if (tipsy.hoverState == 'in') tipsy.show(); }, options.delayIn);
            }
        };

        function leave() {
            var tipsy = get(this);
            tipsy.hoverState = 'out';
            if (options.delayOut == 0) {
                tipsy.hide();
            } else {
                setTimeout(function() { if (tipsy.hoverState == 'out') tipsy.hide(); }, options.delayOut);
            }
        };

        if (!options.live) this.each(function() { get(this); });

        if (options.trigger != 'manual') {
            var binder   = options.live ? 'live' : 'bind',
                eventIn  = options.trigger == 'hover' ? 'mouseenter' : 'focus',
                eventOut = options.trigger == 'hover' ? 'mouseleave' : 'blur';
            this[binder](eventIn, enter)[binder](eventOut, leave);
        }

        return this;

    };

    $.fn.tipsy.defaults = {
        className: null,
        delayIn: 0,
        delayOut: 0,
        fade: false,
        fallback: '',
        gravity: 'n',
        html: false,
        live: false,
        offset: 0,
        opacity: 0.8,
        title: 'title',
        trigger: 'hover'
    };

    $.fn.tipsy.revalidate = function() {
      $('.tipsy').each(function() {
        var pointee = $.data(this, 'tipsy-pointee');
        if (!pointee || !isElementInDOM(pointee)) {
          $(this).remove();
        }
      });
    };

    // Overwrite this method to provide options on a per-element basis.
    // For example, you could store the gravity in a 'tipsy-gravity' attribute:
    // return $.extend({}, options, {gravity: $(ele).attr('tipsy-gravity') || 'n' });
    // (remember - do not modify 'options' in place!)
    $.fn.tipsy.elementOptions = function(ele, options) {
        return $.metadata ? $.extend({}, options, $(ele).metadata()) : options;
    };

    $.fn.tipsy.autoNS = function() {
        return $(this).offset().top > ($(document).scrollTop() + $(window).height() / 2) ? 's' : 'n';
    };

    $.fn.tipsy.autoWE = function() {
        return $(this).offset().left > ($(document).scrollLeft() + $(window).width() / 2) ? 'e' : 'w';
    };

    /**
     * yields a closure of the supplied parameters, producing a function that takes
     * no arguments and is suitable for use as an autogravity function like so:
     *
     * @param margin (int) - distance from the viewable region edge that an
     *        element should be before setting its tooltip's gravity to be away
     *        from that edge.
     * @param prefer (string, e.g. 'n', 'sw', 'w') - the direction to prefer
     *        if there are no viewable region edges effecting the tooltip's
     *        gravity. It will try to vary from this minimally, for example,
     *        if 'sw' is preferred and an element is near the right viewable
     *        region edge, but not the top edge, it will set the gravity for
     *        that element's tooltip to be 'se', preserving the southern
     *        component.
     */
     $.fn.tipsy.autoBounds = function(margin, prefer) {
		return function() {
			var dir = {ns: prefer[0], ew: (prefer.length > 1 ? prefer[1] : false)},
			    boundTop = $(document).scrollTop() + margin,
			    boundLeft = $(document).scrollLeft() + margin,
			    $this = $(this);

			if ($this.offset().top < boundTop) dir.ns = 'n';
			if ($this.offset().left < boundLeft) dir.ew = 'w';
			if ($(window).width() + $(document).scrollLeft() - $this.offset().left < margin) dir.ew = 'e';
			if ($(window).height() + $(document).scrollTop() - $this.offset().top < margin) dir.ns = 's';

			return dir.ns + (dir.ew ? dir.ew : '');
		}
	};

})(jQuery);
<commit_msg>Add update method to tipsy to update title if tooltip is already visible, and call this update after updateTooltip@KDView<commit_after>// tipsy, facebook style tooltips for jquery
// version 1.0.0a
// (c) 2008-2010 jason frame [jason@onehackoranother.com]
// released under the MIT license

(function($) {

    function maybeCall(thing, ctx) {
        return (typeof thing == 'function') ? (thing.call(ctx)) : thing;
    };

    function isElementInDOM(ele) {
      while (ele = ele.parentNode) {
        if (ele == document) return true;
      }
      return false;
    };

    function Tipsy(element, options) {
        this.$element = $(element);
        this.options = options;
        this.enabled = true;
        this.fixTitle();
    };

    Tipsy.prototype = {
        show: function() {
            var title = this.getTitle();
            if (title && this.enabled) {
                var $tip = this.tip();

                $tip.find('.tipsy-inner')[this.options.html ? 'html' : 'text'](title);
                $tip[0].className = 'tipsy'; // reset classname in case of dynamic gravity
                $tip.remove().css({top: 0, left: 0, visibility: 'hidden', display: 'block'}).prependTo(document.body);

                var pos = $.extend({}, this.$element.offset(), {
                    width: this.$element[0].offsetWidth,
                    height: this.$element[0].offsetHeight
                });

                var actualWidth = $tip[0].offsetWidth,
                    actualHeight = $tip[0].offsetHeight,
                    gravity = maybeCall(this.options.gravity, this.$element[0]);

                var tp;
                switch (gravity.charAt(0)) {
                    case 'n':
                        tp = {top: pos.top + pos.height + this.options.offset, left: pos.left + pos.width / 2 - actualWidth / 2};
                        break;
                    case 's':
                        tp = {top: pos.top - actualHeight - this.options.offset, left: pos.left + pos.width / 2 - actualWidth / 2};
                        break;
                    case 'e':
                        tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth - this.options.offset};
                        break;
                    case 'w':
                        tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width + this.options.offset};
                        break;
                }

                if (gravity.length == 2) {
                    if (gravity.charAt(1) == 'w') {
                        tp.left = pos.left + pos.width / 2 - 15;
                    } else {
                        tp.left = pos.left + pos.width / 2 - actualWidth + 15;
                    }
                }

                $tip.css(tp).addClass('tipsy-' + gravity);
                $tip.find('.tipsy-arrow')[0].className = 'tipsy-arrow tipsy-arrow-' + gravity.charAt(0);
                if (this.options.className) {
                    $tip.addClass(maybeCall(this.options.className, this.$element[0]));
                }

                if (this.options.fade) {
                    $tip.stop().css({opacity: 0, display: 'block', visibility: 'visible'}).animate({opacity: this.options.opacity});
                } else {
                    $tip.css({visibility: 'visible', opacity: this.options.opacity});
                }
            }
        },

        hide: function() {
            if (this.options.fade) {
                this.tip().stop().fadeOut(function() { $(this).remove(); });
            } else {
                this.tip().remove();
            }
        },

        fixTitle: function() {
            var $e = this.$element;
            if ($e.attr('title') || typeof($e.attr('original-title')) != 'string') {
                $e.attr('original-title', $e.attr('title') || '').removeAttr('title');
            }
        },

        getTitle: function() {
            var title, $e = this.$element, o = this.options;
            this.fixTitle();
            var title, o = this.options;
            if (typeof $e.attr('original-title') == 'string') {
                title = $e.attr('original-title');
                //title = $e.attr(o.title == 'title' ? 'original-title' : o.title);
            } else if (typeof o.title == 'string') {
                title = o.title;
            } else if (typeof o.title == 'function') {
                title = o.title.call($e[0]);
            }
            title = ('' + title).replace(/(^\s*|\s*$)/, "");
            return title || o.fallback;
        },

        update: function() {
            if (this.hoverState == 'in') this.show();
        },

        tip: function() {
            if (!this.$tip) {
                this.$tip = $('

').html('

');
                this.$tip.data('tipsy-pointee', this.$element[0]);
            }
            return this.$tip;
        },

        validate: function() {
            if (!this.$element[0].parentNode) {
                this.hide();
                this.$element = null;
                this.options = null;
            }
        },

        enable: function() { this.enabled = true; },
        disable: function() { this.enabled = false; },
        toggleEnabled: function() { this.enabled = !this.enabled; }
    };

    $.fn.tipsy = function(options) {

        if (options === true) {
            return this.data('tipsy');
        } else if (typeof options == 'string') {
            var tipsy = this.data('tipsy');
            if (tipsy) tipsy[options]();
            return this;
        }

        options = $.extend({}, $.fn.tipsy.defaults, options);

        function get(ele) {
            var tipsy = $.data(ele, 'tipsy');
            if (!tipsy) {
                tipsy = new Tipsy(ele, $.fn.tipsy.elementOptions(ele, options));
                $.data(ele, 'tipsy', tipsy);
            }
            return tipsy;
        }

        function enter() {
            var tipsy = get(this);
            tipsy.hoverState = 'in';
            if (options.delayIn == 0) {
                tipsy.show();
            } else {
                tipsy.fixTitle();
                setTimeout(function() { if (tipsy.hoverState == 'in') tipsy.show(); }, options.delayIn);
            }
        };

        function leave() {
            var tipsy = get(this);
            tipsy.hoverState = 'out';
            if (options.delayOut == 0) {
                tipsy.hide();
            } else {
                setTimeout(function() { if (tipsy.hoverState == 'out') tipsy.hide(); }, options.delayOut);
            }
        };

        if (!options.live) this.each(function() { get(this); });

        if (options.trigger != 'manual') {
            var binder   = options.live ? 'live' : 'bind',
                eventIn  = options.trigger == 'hover' ? 'mouseenter' : 'focus',
                eventOut = options.trigger == 'hover' ? 'mouseleave' : 'blur';
            this[binder](eventIn, enter)[binder](eventOut, leave);
        }

        return this;

    };

    $.fn.tipsy.defaults = {
        className: null,
        delayIn: 0,
        delayOut: 0,
        fade: false,
        fallback: '',
        gravity: 'n',
        html: false,
        live: false,
        offset: 0,
        opacity: 0.8,
        title: 'title',
        trigger: 'hover'
    };

    $.fn.tipsy.revalidate = function() {
      $('.tipsy').each(function() {
        var pointee = $.data(this, 'tipsy-pointee');
        if (!pointee || !isElementInDOM(pointee)) {
          $(this).remove();
        }
      });
    };

    // Overwrite this method to provide options on a per-element basis.
    // For example, you could store the gravity in a 'tipsy-gravity' attribute:
    // return $.extend({}, options, {gravity: $(ele).attr('tipsy-gravity') || 'n' });
    // (remember - do not modify 'options' in place!)
    $.fn.tipsy.elementOptions = function(ele, options) {
        return $.metadata ? $.extend({}, options, $(ele).metadata()) : options;
    };

    $.fn.tipsy.autoNS = function() {
        return $(this).offset().top > ($(document).scrollTop() + $(window).height() / 2) ? 's' : 'n';
    };

    $.fn.tipsy.autoWE = function() {
        return $(this).offset().left > ($(document).scrollLeft() + $(window).width() / 2) ? 'e' : 'w';
    };

    /**
     * yields a closure of the supplied parameters, producing a function that takes
     * no arguments and is suitable for use as an autogravity function like so:
     *
     * @param margin (int) - distance from the viewable region edge that an
     *        element should be before setting its tooltip's gravity to be away
     *        from that edge.
     * @param prefer (string, e.g. 'n', 'sw', 'w') - the direction to prefer
     *        if there are no viewable region edges effecting the tooltip's
     *        gravity. It will try to vary from this minimally, for example,
     *        if 'sw' is preferred and an element is near the right viewable
     *        region edge, but not the top edge, it will set the gravity for
     *        that element's tooltip to be 'se', preserving the southern
     *        component.
     */
     $.fn.tipsy.autoBounds = function(margin, prefer) {
		return function() {
			var dir = {ns: prefer[0], ew: (prefer.length > 1 ? prefer[1] : false)},
			    boundTop = $(document).scrollTop() + margin,
			    boundLeft = $(document).scrollLeft() + margin,
			    $this = $(this);

			if ($this.offset().top < boundTop) dir.ns = 'n';
			if ($this.offset().left < boundLeft) dir.ew = 'w';
			if ($(window).width() + $(document).scrollLeft() - $this.offset().left < margin) dir.ew = 'e';
			if ($(window).height() + $(document).scrollTop() - $this.offset().top < margin) dir.ns = 's';

			return dir.ns + (dir.ew ? dir.ew : '');
		}
	};

})(jQuery);
<|endoftext|>


<commit_before>export const getDateString = (isoDate) => {
    const event = new Date(isoDate);
    const options = { year: 'numeric', month: 'short', day: 'numeric' };
    return event.toLocaleDateString('en-GB', options);
};
<commit_msg>Fixed lint<commit_after>export const getDateString = (isoDate) => {
    const event = new Date(isoDate);
    const options = {year: 'numeric', month: 'short', day: 'numeric'};
    return event.toLocaleDateString('en-GB', options);
};
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'

import DevTools from '../../DevTools'

// Import Components
import Helmet from 'react-helmet'
import Headroom from 'react-headroom'
import Grid from 'react-bootstrap/lib/Grid'

import UWHeader from './components/UWHeader/UWHeader'
import STFHeader from './components/STFHeader/STFHeader'
import Footer from './components/Footer/Footer'

import styles from './Template.css'

// Import Actions
import { toggleAddPost } from './TemplateActions'

const meta = [
  { charset: 'utf-8' },
  { 'http-equiv': 'X-UA-Compatible', content: 'IE=edge' },
  { name: 'viewport', content: 'width=device-width, initial-scale=1' }
]

export class Template extends React.Component {
  constructor (props) {
    super(props)
    this.state = { mounted: false }
  }
  componentDidMount () { this.setState({mounted: true}) }
  render () {
    return (

        {this.state.mounted && !window.devToolsExtension && process.env.NODE_ENV === 'development' && <DevTools />}

          <Helmet title='UW Student Tech Fee Commitee' titleTemplate='%s - Student Tech Fee' meta={meta} />
          <UWHeader />
          <Headroom pinStart={55}>
            <STFHeader />
          </Headroom>
          {/*
 */}
          <Grid>
            {this.props.children}
          </Grid>
          {/*
 */}

         this.props.dispatch(toggleAddPost())}>
          Debug Placeholder: Add a post!

    )
  }
}

Template.propTypes = {
  children: PropTypes.object.isRequired,
  dispatch: PropTypes.func.isRequired
}

// Retrieve data from store as props
function mapStateToProps (store) {
  return {}
}

export default connect(mapStateToProps)(Template)
<commit_msg>Fixed react headroom issue.<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'

import DevTools from '../../DevTools'

// Import Components
import Helmet from 'react-helmet'
import Headroom from 'react-headroom'
import Grid from 'react-bootstrap/lib/Grid'

import UWHeader from './components/UWHeader/UWHeader'
import STFHeader from './components/STFHeader/STFHeader'
import Footer from './components/Footer/Footer'

import styles from './Template.css'

// Import Actions
import { toggleAddPost } from './TemplateActions'

const meta = [
  { charset: 'utf-8' },
  { 'http-equiv': 'X-UA-Compatible', content: 'IE=edge' },
  { name: 'viewport', content: 'width=device-width, initial-scale=1' }
]

export class Template extends React.Component {
  constructor (props) {
    super(props)
    this.state = { mounted: false }
  }
  componentDidMount () { this.setState({mounted: true}) }
  render () {
    return (

        {this.state.mounted && !window.devToolsExtension && process.env.NODE_ENV === 'development' && <DevTools />}

          <Helmet title='UW Student Tech Fee Commitee' titleTemplate='%s - Student Tech Fee' meta={meta} />
          <UWHeader />
          <Headroom pinStart={55} wrapperStyle={{height: 'inherit !important'}}>
            <STFHeader />
          </Headroom>
          {/*
 */}
          <Grid>
            {this.props.children}
          </Grid>
          {/*
 */}

         this.props.dispatch(toggleAddPost())}>
          Debug Placeholder: Add a post!

    )
  }
}

Template.propTypes = {
  children: PropTypes.object.isRequired,
  dispatch: PropTypes.func.isRequired
}

// Retrieve data from store as props
function mapStateToProps (store) {
  return {}
}

export default connect(mapStateToProps)(Template)
<|endoftext|>


<commit_before>/*
 * @title Paths
 * @description An function that returns an object containing file paths
 */

/*********************************************************************************
 1. EXPORTS
 *********************************************************************************/

module.exports = function () {

    const srcBase = './src';
    const distBase = './dist';

    return {
        srcDir: srcBase,
        srcIndex: `${srcBase}/index.html`,
        imagesSrcFiles: `${srcBase}/images/**/*.{jpg,png,gif,svg}`,
        imagesOutputFiles: `${distBase}/images`,
        outputDir: distBase,

        eslintSrcFiles: [
            './.eslintrc',
            './bower.json',
            './package.json',
            `${srcBase}/js/**/*.js`,
            './gulpfile.babel.js/**/*.js'
        ],

        fontsIconSrcFiles: `${srcBase}/fonts/iconfont/*.svg`,
        fontsSrcFiles: `${srcBase}/fonts/*.{eot,svg,ttf,woff,woff2}`,
        fontsOutputDir: `${distBase}/fonts`,

        revManifest: `${distBase}/rev-manifest.json`,

        scriptsSrcFiles: [
            `${srcBase}/js/**/*.js`,
            `!${srcBase}/js/**/*.spec.js`
        ],
        scriptsOutputFiles: [
            `${distBase}/js/bower/**/*.js`,
            `${distBase}/js/app.js`,
            `${distBase}/js/**/*.js`
        ],
        scriptsOutputDir: `${distBase}/js`,
        scriptsLibsOutputDir: `${distBase}/js/bower`,

        outputFiles: [`${distBase}/**/*.{html,css,js}`],

        stylesMainSrcFiles: [`${srcBase}/sass/*.scss`],
        stylesAllSrcFiles: [`${srcBase}/sass/**/*.scss`],
        stylesSrcGeneratedDir: `${srcBase}/sass/generated`,
        stylesOutputFiles: [`${distBase}/css/*.css`],
        stylesOutputDir: `${distBase}/css`

    };
}();
<commit_msg>chore(gulp): tidy up<commit_after>/*
 * @title Paths
 * @description An function that returns an object containing file paths
 */

/*********************************************************************************
 1. EXPORTS
 *********************************************************************************/

module.exports = function () {

    const srcBase = './src';
    const distBase = './dist';

    return {
        srcDir: srcBase,
        srcIndex: `${srcBase}/index.html`,
        imagesSrcFiles: `${srcBase}/images/**/*.{jpg,png,gif,svg}`,
        imagesOutputFiles: `${distBase}/images`,
        outputDir: distBase,
        eslintSrcFiles: [
            './.eslintrc',
            './bower.json',
            './package.json',
            `${srcBase}/js/**/*.js`,
            './gulpfile.babel.js/**/*.js'
        ],
        fontsIconSrcFiles: `${srcBase}/fonts/iconfont/*.svg`,
        fontsSrcFiles: `${srcBase}/fonts/*.{eot,svg,ttf,woff,woff2}`,
        fontsOutputDir: `${distBase}/fonts`,
        revManifest: `${distBase}/rev-manifest.json`,
        scriptsSrcFiles: [
            `${srcBase}/js/**/*.js`,
            `!${srcBase}/js/**/*.spec.js`
        ],
        scriptsOutputFiles: [
            `${distBase}/js/bower/**/*.js`,
            `${distBase}/js/app.js`,
            `${distBase}/js/**/*.js`
        ],
        outputFiles: [`${distBase}/**/*.{html,css,js}`],
        scriptsOutputDir: `${distBase}/js`,
        scriptsLibsOutputDir: `${distBase}/js/bower`,
        stylesMainSrcFiles: [`${srcBase}/sass/*.scss`],
        stylesAllSrcFiles: [`${srcBase}/sass/**/*.scss`],
        stylesSrcGeneratedDir: `${srcBase}/sass/generated`,
        stylesOutputFiles: [`${distBase}/css/*.css`],
        stylesOutputDir: `${distBase}/css`

    };
}();
<|endoftext|>


<commit_before>/* global d3 */
/* global mstrmojo */
(function () {
  if (!mstrmojo.plugins.d3flow941) {
    mstrmojo.plugins.d3flow941 = {};
  }
  mstrmojo.requiresCls("mstrmojo.Vis", "mstrmojo._LoadsScript");

  mstrmojo.plugins.d3flow941.d3flow941 = mstrmojo.declare(
    mstrmojo.Vis, [mstrmojo._LoadsScript], {
      scriptClass: 'mstrmojo.plugins.d3flow941.d3flow941',
      //HTML to render in place of widget
      //ming commented
      // markupString: '
' +
      // '

	' +
      // '
',
      markupString: '

', //ming

      properties: {},

      postBuildRendering: function () {
        if (this._super) {
          this._super();
        }
        this.domNode.style.width = parseInt(this.width, 10) + 'px';
        this.domNode.style.height = parseInt(this.height, 10) + 'px';
        //if eg exists then we do not have data
        if (this.model.eg) {
          //displaying No data message
          this.domNode.innerHTML = this.model.eg;
        } else {
          //parsing properties
          // this.properties = this.getProperties();
          this.loadScripts();
        }
      },

      loadScripts: function () {
        var externalLibraries = [
          {
            url: "http://d3js.org/d3.v3.min.js"
              // url: "https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"
          },
          {
            url: "../plugins/d3flow941/javascript/mojo/js/source/sankey.js"
          },
          {
            url: "../plugins/d3flow941/javascript/mojo/js/source/draw-sankey.js"
          },
          // {
          //   url: "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"
          // }
                ];
        var me = this;
        // load required external JS files and after that run renderGraph method
        this.requiresExternalScripts(externalLibraries, function () {
          // $(document).ready(function () {
          //     $('head').append('<link href="../plugins/d3flow941/style/global.css" rel="stylesheet" id="styleSheet" />');
          // });
          me.renderGraph();
        });
      },

      /**
       * Reads properties from model
       * @returns properties
       */
      getProperties: function () {
        var prop = {};
        prop.title = prop.defTitle = 'd3flow Integration for 9.4.1';
        prop.type = prop.defType = 'serial';
        prop.theme = prop.defTheme = 'none';
        if (this.model && this.model.vp) {
          if (this.model.vp.graphTitle) {
            prop.title = this.model.vp.graphTitle;
          }
          if (this.model.vp.graphType) {
            prop.type = this.model.vp.graphType;
          }
          if (this.model.vp.graphTheme) {
            prop.theme = this.model.vp.graphTheme;
          }
        }
        return prop;
      },

      useRichTooltip: true,
      reuseDOMNode: true,
      errorDetails: "This visualization requires one or more attributes and one metric.",

      renderGraph: function (type) {

        var gridData = this.getDataParser();
        // var metricName = gridData.getColHeaders(0).getHeader(0).getName();//not needed
        var negValFound = false;
        var nodeDict = {};
        var data = {
          nodes: [],
          flows: [],
        };

        for (var i = 0; i < gridData.getTotalRows(); i++) {
          var value = gridData.getMetricValue(i, 0).getRawValue();
          if (value <= 0) {
            console.error(
              'Warning: negative value(s) in the metric. Assuming zero.'
            );
            if (!negValFound) {
              negValFound = true;
            }
            continue;
          }
          var f = {
            value: value,
            thru: [],
          };
          for (var j = 0; j < gridData.getRowTitles().size(); j++) {
            var attrTitle = gridData.getRowTitles().getTitle(j).getName();
            var attr = gridData.getRowHeaders(i).getHeader(j).getName();
            if (!attr || attr === '') {
              attr = ' ';
            }
            var name = attr + ' - ' + attrTitle;
            if (!nodeDict[name]) {
              var newnode = {
                name: name,
                disp: attr,
              };
              data.nodes.push(newnode);
              nodeDict[name] = newnode;
            }
            // f.thru.push(data.nodes.indexOf(nodeDict[name])); //both works
            f.thru.push(nodeDict[name]);
          }
          data.flows.push(f);
        }

        d3.drawSankey(d3.select(this.domNode), data, {
          width: parseInt(this.domNode.style.width, 10),
          height: parseInt(this.domNode.style.height, 10),
        });
      }
    }
  );
}());
<commit_msg>plugin<commit_after>/* global d3 */
/* global mstrmojo */
(function () {
  if (!mstrmojo.plugins.d3flow941) {
    mstrmojo.plugins.d3flow941 = {};
  }
  mstrmojo.requiresCls("mstrmojo.Vis", "mstrmojo._LoadsScript");

  mstrmojo.plugins.d3flow941.d3flow941 = mstrmojo.declare(
    mstrmojo.Vis, [mstrmojo._LoadsScript], {
      scriptClass: 'mstrmojo.plugins.d3flow941.d3flow941',
      //HTML to render in place of widget
      //ming commented
      // markupString: '
' +
      // '

	' +
      // '
',
      markupString: '

', //ming

      properties: {},

      postBuildRendering: function () {
        if (this._super) {
          this._super();
        }
        this.domNode.style.width = parseInt(this.width, 10) + 'px';
        this.domNode.style.height = parseInt(this.height, 10) + 'px';
        //if eg exists then we do not have data
        if (this.model.eg) {
          //displaying No data message
          this.domNode.innerHTML = this.model.eg;
        } else {
          //parsing properties
          // this.properties = this.getProperties();
          this.loadScripts();
        }
      },

      loadScripts: function () {
        var externalLibraries = [
          {
            url: "http://d3js.org/d3.v3.min.js"
              // url: "https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"
          },
          {
            url: "../plugins/d3flow941/javascript/mojo/js/source/sankey.js"
          },
          {
            url: "../plugins/d3flow941/javascript/mojo/js/source/draw-sankey.js"
          },
          // {
          //   url: "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"
          // }
                ];
        var me = this;
        // load required external JS files and after that run renderGraph method
        this.requiresExternalScripts(externalLibraries, function () {
          // $(document).ready(function () {
          //     $('head').append('<link href="../plugins/d3flow941/style/global.css" rel="stylesheet" id="styleSheet" />');
          // });
          me.renderGraph();
        });
      },

      /**
       * Reads properties from model
       * @returns properties
       */
      getProperties: function () {
        var prop = {};
        prop.title = prop.defTitle = 'd3flow Integration for 9.4.1';
        prop.type = prop.defType = 'serial';
        prop.theme = prop.defTheme = 'none';
        if (this.model && this.model.vp) {
          if (this.model.vp.graphTitle) {
            prop.title = this.model.vp.graphTitle;
          }
          if (this.model.vp.graphType) {
            prop.type = this.model.vp.graphType;
          }
          if (this.model.vp.graphTheme) {
            prop.theme = this.model.vp.graphTheme;
          }
        }
        return prop;
      },

      useRichTooltip: true,
      reuseDOMNode: true,
      errorDetails: "This visualization requires one or more attributes and one metric.",

      renderGraph: function (type) {

        var gridData = this.getDataParser();
        // var metricName = gridData.getColHeaders(0).getHeader(0).getName();//not needed
        var negValFound = false;
        var nodeDict = {};
        var data = {
          nodes: [],
          flows: [],
        };

        for (var i = 0; i < gridData.getTotalRows(); i++) {
          var value = gridData.getMetricValue(i, 0).getRawValue();
          if (value <= 0) {
            console.error(
              'Warning: negative value(s) in the metric. Assuming zero.'
            );
            if (!negValFound) {
              negValFound = true;
            }
            continue;
          }
          var f = {
            value: value,
            thru: [],
          };
          for (var j = 0; j < gridData.getRowTitles().size(); j++) {
            var attrTitle = gridData.getRowTitles().getTitle(j).getName();
            var attr = gridData.getRowHeaders(i).getHeader(j).getName();
            if (!attr || attr === '') {
              attr = ' ';
            }
            var name = attr + ' - ' + attrTitle;
            if (!nodeDict[name]) {
              var newnode = {
                name: name,
                disp: attr,
              };
              data.nodes.push(newnode);
              nodeDict[name] = newnode;
            }
            // f.thru.push(data.nodes.indexOf(nodeDict[name])); //both works
            f.thru.push(nodeDict[name]);
          }
          data.flows.push(f);
        }

        var canvas = d3.select(this.domNode);
        var sz = {
          width: parseInt(this.domNode.style.width, 10),
          height: parseInt(this.domNode.style.height, 10),
        };

        var margin = {
          top: 25,
          left: 25,
          bottom: 10,
          right: 10,
        };

        canvas
          .html('')
          .append('svg')
            .attr("width", sz.width)
            .attr("height", sz.height)
          .append("g")
            .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

        var driver = new SankeyDriver();
        driver.draw(canvas, data, {
          width : sz.width - margin.left - margin.right,
          height: sz.height - margin.top - margin.bottom,
        });
      }
    }
  );
}());
<|endoftext|>


<commit_before>'use strict';
var React = require('react');
var ReactNative = require('react-native');

var {
  Navigator,
  Text,
  TouchableOpacity,
  View,
  BackAndroid
} = ReactNative;

import {
  Icon
} from '@shoutem/ui';

//引入子页面
var SearchResult = require('./SearchResult').default;
var RouteDetail = require('./RouteDetail').default;
var TabView = require('./TabView').default;
var SearchContainer = require('./SearchContainer').default;

//设置导航栏
var NavigationBarRouteMapper = {
  //设置导航栏左按钮
  LeftButton: function(route,navigator,index,navState) {
    if(index === 0){
      return;
    }else{
      return(
        <View style={{flex:1}}>
          <TouchableOpacity
            underlayColor='transparent'
            onPress={()=>navigator.pop()}>
            <Icon name="back" style={{marginVertical:17,marginLeft:10}}/>
          </TouchableOpacity>
        </View>
      );
    }

  },

  //设置导航栏标题
  Title: function(route,navigator,index,navState) {
    return (<Text style={{flex:1, fontSize: 18,color: '#373E4D',fontWeight: '500', marginVertical: 15}}>{route.title}</Text>);
  },

  //设置导航栏右按钮
  RightButton: function(route,navigator,index,navState) {
  }
};

class NavigationBar extends Navigator.NavigationBar {
  render() {
    let routes = this.props.navState.routeStack;
    if (routes.length) {
      let route = routes[routes.length - 1];
      console.log(this.props.navState.routeStack);
      if (route.name === 'TabView') { // First page (Tab view) => No nav bar
        return null;
      }
    }

    return super.render();
  }
}

let globalNavigator;
// back button
BackAndroid.addEventListener('hardwareBackPress', () => {
  if (globalNavigator && globalNavigator.getCurrentRoutes().length > 1) {
    globalNavigator.pop();
    return true;
  }
  return false;
});

var SearchHome = React.createClass ({

  //设置导航子页面导航路由方式
  renderScene: function(route, navigator) {
    this._navigator = navigator;
    globalNavigator = navigator;
    switch(route.name) {
      case 'TabView':
        return <TabView navigator={navigator} {...route.passProps}/>;
      case 'SearchResult' :
        return <SearchResult navigator={navigator} {...route.passProps}/>;
      case 'RouteDetail' :
        return <RouteDetail navigator={navigator} {...route.passProps}/>;
      case 'SearchContainer' :
        return <SearchContainer navigator={navigator} {...route.passProps}/>;
    }
  },

  render: function() {
    return(
      //返回导航栏视图，并通过initialRoute显示第一次显示的子页面，initialRouteStack导航栏的子页面路由栈，configureScence导航栏子页面切换动画，navigationBar导航栏标题栏实现，renderScene导航栏路由方式
      <Navigator
        initialRoute={{name: 'TabView'}}
        navigationBar={<NavigationBar style={{height: 55,backgroundColor: 'white'}} routeMapper={NavigationBarRouteMapper}/>}
        renderScene={this.renderScene}/>
    );
  }
});

module.exports = SearchHome;
<commit_msg>Delete comments in chinese.<commit_after>'use strict';
var React = require('react');
var ReactNative = require('react-native');

var {
  Navigator,
  Text,
  TouchableOpacity,
  View,
  BackAndroid
} = ReactNative;

import {
  Icon
} from '@shoutem/ui';

var SearchResult = require('./SearchResult').default;
var RouteDetail = require('./RouteDetail').default;
var TabView = require('./TabView').default;
var SearchContainer = require('./SearchContainer').default;

var NavigationBarRouteMapper = {
  LeftButton: function(route,navigator,index,navState) {
    if(index === 0){
      return;
    }else{
      return(
        <View style={{flex:1}}>
          <TouchableOpacity
            underlayColor='transparent'
            onPress={()=>navigator.pop()}>
            <Icon name="back" style={{marginVertical:17,marginLeft:10}}/>
          </TouchableOpacity>
        </View>
      );
    }

  },

  Title: function(route,navigator,index,navState) {
    return (<Text style={{flex:1, fontSize: 18,color: '#373E4D',fontWeight: '500', marginVertical: 15}}>{route.title}</Text>);
  },

  RightButton: function(route,navigator,index,navState) {
  }
};

class NavigationBar extends Navigator.NavigationBar {
  render() {
    let routes = this.props.navState.routeStack;
    if (routes.length) {
      let route = routes[routes.length - 1];
      console.log(this.props.navState.routeStack);
      if (route.name === 'TabView') { // First page (Tab view) => No nav bar
        return null;
      }
    }

    return super.render();
  }
}

let globalNavigator;
// back button
BackAndroid.addEventListener('hardwareBackPress', () => {
  if (globalNavigator && globalNavigator.getCurrentRoutes().length > 1) {
    globalNavigator.pop();
    return true;
  }
  return false;
});

var SearchHome = React.createClass ({

  renderScene: function(route, navigator) {
    this._navigator = navigator;
    globalNavigator = navigator;
    switch(route.name) {
      case 'TabView':
        return <TabView navigator={navigator} {...route.passProps}/>;
      case 'SearchResult' :
        return <SearchResult navigator={navigator} {...route.passProps}/>;
      case 'RouteDetail' :
        return <RouteDetail navigator={navigator} {...route.passProps}/>;
      case 'SearchContainer' :
        return <SearchContainer navigator={navigator} {...route.passProps}/>;
    }
  },

  render: function() {
    return(
      <Navigator
        initialRoute={{name: 'TabView'}}
        navigationBar={<NavigationBar style={{height: 55,backgroundColor: 'white'}} routeMapper={NavigationBarRouteMapper}/>}
        renderScene={this.renderScene}/>
    );
  }
});

module.exports = SearchHome;
<|endoftext|>


<commit_before>
HTMLArea.Dialog = function(editor, html, localizer)
{
  this.id    = { };
  this.r_id  = { }; // reverse lookup id
  this.editor   = editor;
  this.document = document;

  this.rootElem = document.createElement('div');
  this.rootElem.className = 'dialog';
  this.rootElem.style.position = 'absolute';
  this.rootElem.style.display  = 'none';
  this.editor._framework.ed_cell.insertBefore(this.rootElem, this.editor._framework.ed_cell.firstChild);
  this.rootElem.style.width  = this.width  =  this.editor._framework.ed_cell.offsetWidth + 'px';
  this.rootElem.style.height = this.height =  this.editor._framework.ed_cell.offsetHeight + 'px';

  var dialog = this;
  if(typeof localizer == 'function')
  {
    this._lc = localizer;
  }
  else if(localizer)
  {
    this._lc = function(string)
    {
      return HTMLArea._lc(string,localizer);
    }
  }
  else
  {
    this._lc = function(string)
    {
      return string;
    }
  }

  html = html.replace(/\[([a-z0-9_]+)\]/ig,
                      function(fullString, id)
                      {
                        if(typeof dialog.id[id] == 'undefined')
                        {
                          dialog.id[id] = HTMLArea.uniq('Dialog');
                          dialog.r_id[dialog.id[id]] = id;
                        }
                        return dialog.id[id];
                      }
             ).replace(/<l10n>(.*?)<\/l10n>/ig,
                       function(fullString,translate)
                       {
                         return dialog._lc(translate) ;
                       }
             ).replace(/="_\((.*?)\)"/g,
                       function(fullString, translate)
                       {
                         return '="' + dialog._lc(translate) + '"';
                       }
             );

  this.rootElem.innerHTML = html;

  this.editor.notifyOn
   ('resize',
      function(e, args)
      {
        dialog.rootElem.style.width  = dialog.width  =  dialog.editor._framework.ed_cell.offsetWidth + 'px';
        dialog.rootElem.style.height = dialog.height =  dialog.editor._framework.ed_cell.offsetHeight + 'px';
        dialog.onresize();
      }
    );
}

HTMLArea.Dialog.prototype.onresize = function()
{
  return true;
}

HTMLArea.Dialog.prototype.show = function(values)
{
  // We need to preserve the selection for IE
  if(HTMLArea.is_ie)
  {
    this._lastRange = this.editor._createRange(this.editor._getSelection());
  }

  if(typeof values != 'undefined')
  {
    this.setValues(values);
  }
  this._restoreTo = [this.editor._textArea.style.display, this.editor._iframe.style.visibility, this.editor.hidePanels()];

  this.editor._textArea.style.display = 'none';
  this.editor._iframe.style.visibility   = 'hidden';
  this.rootElem.style.display   = '';
}

HTMLArea.Dialog.prototype.hide = function()
{
  this.rootElem.style.display         = 'none';
  this.editor._textArea.style.display = this._restoreTo[0];
  this.editor._iframe.style.visibility   = this._restoreTo[1];
  this.editor.showPanels(this._restoreTo[2]);

  // Restore the selection
  if(HTMLArea.is_ie)
  {
    this._lastRange.select();
  }
  this.editor.updateToolbar();
  return this.getValues();
}

HTMLArea.Dialog.prototype.toggle = function()
{
  if(this.rootElem.style.display == 'none')
  {
    this.show();
  }
  else
  {
    this.hide();
  }
}

HTMLArea.Dialog.prototype.setValues = function(values)
{
  for(var i in values)
  {
    var elems = this.getElementsByName(i);
    if(!elems) continue;
    for(var x = 0; x < elems.length; x++)
    {
      var e = elems[x];
      switch(e.tagName.toLowerCase())
      {
        case 'select'  :
        {
          for(var j = 0; j < e.options.length; j++)
          {
            if(typeof values[i] == 'object')
            {
              for(var k = 0; k < values[i].length; k++)
              {
                if(values[i][k] == e.options[j].value)
                {
                  e.options[j].selected = true;
                }
              }
            }
            else if(values[i] == e.options[j].value)
            {
              e.options[j].selected = true;
            }
          }
          break;
        }

        case 'textarea':
        case 'input'   :
        {
          switch(e.getAttribute('type'))
          {
            case 'radio'   :
            {
              if(e.value == values[i])
              {
                e.checked = true;
              }
              break;
            }

            case 'checkbox':
            {
              if(typeof values[i] == 'object')
              {
                for(var j in values[i])
                {
                  if(values[i][j] == e.value)
                  {
                    e.checked = true;
                  }
                }
              }
              else
              {
                if(values[i] == e.value)
                {
                  e.checked = true;
                }
              }
              break;
            }

            default    :
            {
              e.value = values[i];
            }
          }
          break;
        }

        default        :
        break;
      }
    }
  }
}

HTMLArea.Dialog.prototype.getValues = function()
{
  var values = [ ];
  var inputs = HTMLArea.collectionToArray(this.rootElem.getElementsByTagName('input'))
              .append(HTMLArea.collectionToArray(this.rootElem.getElementsByTagName('textarea')))
              .append(HTMLArea.collectionToArray(this.rootElem.getElementsByTagName('select')));

  for(var x = 0; x < inputs.length; x++)
  {
    var i = inputs[x];
    if(!(i.name && this.r_id[i.name])) continue;

    if(typeof values[this.r_id[i.name]] == 'undefined')
    {
      values[this.r_id[i.name]] = null;
    }
    var v = values[this.r_id[i.name]];

    switch(i.tagName.toLowerCase())
    {
      case 'select':
      {
        if(i.multiple)
        {
          if(!v.push)
          {
            if(v != null)
            {
              v = [v];
            }
            else
            {
              v = new Array();
            }
          }
          for(var j = 0; j < i.options.length; j++)
          {
            if(i.options[j].selected)
            {
              v.push(i.options[j].value);
            }
          }
        }
        else
        {
          if(i.selectedIndex >= 0)
          {
            v = i.options[i.selectedIndex];
          }
        }
        break;
      }

      case 'textarea':
      case 'input'   :
      default        :
      {
        switch(i.type.toLowerCase())
        {
          case  'radio':
          {
            if(i.checked)
            {
              v = i.value;
              break;
            }
          }

          case 'checkbox':
          {
            if(v == null)
            {
              if(this.getElementsByName(this.r_id[i.name]).length > 1)
              {
                v = new Array();
              }
            }

            if(i.checked)
            {
              if(typeof v == 'object' && v.push)
              {
                v.push(i.value);
              }
              else
              {
                v = i.value;
              }
            }
            break;
          }

          default   :
          {
            v = i.value;
            break;
          }
        }
      }

    }

    values[this.r_id[i.name]] = v;
  }
  return values;
}

HTMLArea.Dialog.prototype.getElementById = function(id)
{
  return this.document.getElementById(this.id[id] ? this.id[id] : id);
}

HTMLArea.Dialog.prototype.getElementsByName = function(name)
{
  return this.document.getElementsByName(this.id[name] ? this.id[name] : name);
}
<commit_msg>#432 superclean (and any other inline-dialog that would use checkboxes) didn't work<commit_after>
HTMLArea.Dialog = function(editor, html, localizer)
{
  this.id    = { };
  this.r_id  = { }; // reverse lookup id
  this.editor   = editor;
  this.document = document;

  this.rootElem = document.createElement('div');
  this.rootElem.className = 'dialog';
  this.rootElem.style.position = 'absolute';
  this.rootElem.style.display  = 'none';
  this.editor._framework.ed_cell.insertBefore(this.rootElem, this.editor._framework.ed_cell.firstChild);
  this.rootElem.style.width  = this.width  =  this.editor._framework.ed_cell.offsetWidth + 'px';
  this.rootElem.style.height = this.height =  this.editor._framework.ed_cell.offsetHeight + 'px';

  var dialog = this;
  if(typeof localizer == 'function')
  {
    this._lc = localizer;
  }
  else if(localizer)
  {
    this._lc = function(string)
    {
      return HTMLArea._lc(string,localizer);
    }
  }
  else
  {
    this._lc = function(string)
    {
      return string;
    }
  }

  html = html.replace(/\[([a-z0-9_]+)\]/ig,
                      function(fullString, id)
                      {
                        if(typeof dialog.id[id] == 'undefined')
                        {
                          dialog.id[id] = HTMLArea.uniq('Dialog');
                          dialog.r_id[dialog.id[id]] = id;
                        }
                        return dialog.id[id];
                      }
             ).replace(/<l10n>(.*?)<\/l10n>/ig,
                       function(fullString,translate)
                       {
                         return dialog._lc(translate) ;
                       }
             ).replace(/="_\((.*?)\)"/g,
                       function(fullString, translate)
                       {
                         return '="' + dialog._lc(translate) + '"';
                       }
             );

  this.rootElem.innerHTML = html;

  this.editor.notifyOn
   ('resize',
      function(e, args)
      {
        dialog.rootElem.style.width  = dialog.width  =  dialog.editor._framework.ed_cell.offsetWidth + 'px';
        dialog.rootElem.style.height = dialog.height =  dialog.editor._framework.ed_cell.offsetHeight + 'px';
        dialog.onresize();
      }
    );
}

HTMLArea.Dialog.prototype.onresize = function()
{
  return true;
}

HTMLArea.Dialog.prototype.show = function(values)
{
  // We need to preserve the selection for IE
  if(HTMLArea.is_ie)
  {
    this._lastRange = this.editor._createRange(this.editor._getSelection());
  }

  if(typeof values != 'undefined')
  {
    this.setValues(values);
  }
  this._restoreTo = [this.editor._textArea.style.display, this.editor._iframe.style.visibility, this.editor.hidePanels()];

  this.editor._textArea.style.display = 'none';
  this.editor._iframe.style.visibility   = 'hidden';
  this.rootElem.style.display   = '';
}

HTMLArea.Dialog.prototype.hide = function()
{
  this.rootElem.style.display         = 'none';
  this.editor._textArea.style.display = this._restoreTo[0];
  this.editor._iframe.style.visibility   = this._restoreTo[1];
  this.editor.showPanels(this._restoreTo[2]);

  // Restore the selection
  if(HTMLArea.is_ie)
  {
    this._lastRange.select();
  }
  this.editor.updateToolbar();
  return this.getValues();
}

HTMLArea.Dialog.prototype.toggle = function()
{
  if(this.rootElem.style.display == 'none')
  {
    this.show();
  }
  else
  {
    this.hide();
  }
}

HTMLArea.Dialog.prototype.setValues = function(values)
{
  for(var i in values)
  {
    var elems = this.getElementsByName(i);
    if(!elems) continue;
    for(var x = 0; x < elems.length; x++)
    {
      var e = elems[x];
      switch(e.tagName.toLowerCase())
      {
        case 'select'  :
        {
          for(var j = 0; j < e.options.length; j++)
          {
            if(typeof values[i] == 'object')
            {
              for(var k = 0; k < values[i].length; k++)
              {
                if(values[i][k] == e.options[j].value)
                {
                  e.options[j].selected = true;
                }
              }
            }
            else if(values[i] == e.options[j].value)
            {
              e.options[j].selected = true;
            }
          }
          break;
        }

        case 'textarea':
        case 'input'   :
        {
          switch(e.getAttribute('type'))
          {
            case 'radio'   :
            {
              if(e.value == values[i])
              {
                e.checked = true;
              }
              break;
            }

            case 'checkbox':
            {
              if(typeof values[i] == 'object')
              {
                for(var j in values[i])
                {
                  if(values[i][j] == e.value)
                  {
                    e.checked = true;
                  }
                }
              }
              else
              {
                if(values[i] == e.value)
                {
                  e.checked = true;
                }
              }
              break;
            }

            default    :
            {
              e.value = values[i];
            }
          }
          break;
        }

        default        :
        break;
      }
    }
  }
}

HTMLArea.Dialog.prototype.getValues = function()
{
  var values = [ ];
  var inputs = HTMLArea.collectionToArray(this.rootElem.getElementsByTagName('input'))
              .append(HTMLArea.collectionToArray(this.rootElem.getElementsByTagName('textarea')))
              .append(HTMLArea.collectionToArray(this.rootElem.getElementsByTagName('select')));

  for(var x = 0; x < inputs.length; x++)
  {
    var i = inputs[x];
    if(!(i.name && this.r_id[i.name])) continue;

    if(typeof values[this.r_id[i.name]] == 'undefined')
    {
      values[this.r_id[i.name]] = null;
    }
    var v = values[this.r_id[i.name]];

    switch(i.tagName.toLowerCase())
    {
      case 'select':
      {
        if(i.multiple)
        {
          if(!v.push)
          {
            if(v != null)
            {
              v = [v];
            }
            else
            {
              v = new Array();
            }
          }
          for(var j = 0; j < i.options.length; j++)
          {
            if(i.options[j].selected)
            {
              v.push(i.options[j].value);
            }
          }
        }
        else
        {
          if(i.selectedIndex >= 0)
          {
            v = i.options[i.selectedIndex];
          }
        }
        break;
      }

      case 'textarea':
      case 'input'   :
      default        :
      {
        switch(i.type.toLowerCase())
        {
          case  'radio':
          {
            if(i.checked)
            {
              v = i.value;
              break;
            }
          }

          case 'checkbox':
          {
            if(v == null)
            {
              if(this.getElementsByName(this.r_id[i.name]).length > 1)
              {
                v = new Array();
              }
            }

            if(i.checked)
            {
              if(v != null && typeof v == 'object' && v.push)
              {
                v.push(i.value);
              }
              else
              {
                v = i.value;
              }
            }
            break;
          }

          default   :
          {
            v = i.value;
            break;
          }
        }
      }

    }

    values[this.r_id[i.name]] = v;
  }
  return values;
}

HTMLArea.Dialog.prototype.getElementById = function(id)
{
  return this.document.getElementById(this.id[id] ? this.id[id] : id);
}

HTMLArea.Dialog.prototype.getElementsByName = function(name)
{
  return this.document.getElementsByName(this.id[name] ? this.id[name] : name);
}
<|endoftext|>


<commit_before>var raven = require('../');
raven.parsers = require('../lib/parsers');

describe('raven.parsers', function(){
  describe('#parseText()', function(){
    it('should parse some text without kwargs', function(){
      var parsed = raven.parsers.parseText('Howdy');
      parsed['message'].should.equal('Howdy');
      parsed.should.have.property('sentry.interfaces.Message');
      parsed['sentry.interfaces.Message'].message.should.equal('Howdy');
    });

    it('should parse some text with kwargs', function(){
      var parsed = raven.parsers.parseText('Howdy', {'foo': 'bar'});
      parsed['message'].should.equal('Howdy');
      parsed.should.have.property('sentry.interfaces.Message');
      parsed['sentry.interfaces.Message'].message.should.equal('Howdy');
      parsed['foo'].should.equal('bar');
    });
  });

  describe('#parseQuery()', function(){
    it('should parse a query', function(){
      var query = 'SELECT * FROM `something`';
      var engine = 'mysql';
      var parsed = raven.parsers.parseQuery(query, engine);
      parsed['message'].should.equal('SELECT * FROM `something`');
      parsed.should.have.property('sentry.interfaces.Query');
      parsed['sentry.interfaces.Query'].query.should.equal('SELECT * FROM `something`');
      parsed['sentry.interfaces.Query'].engine.should.equal('mysql');
    });
  });

  describe('#parseRequest()', function(){
    it('should parse a request object', function(){
      var mockReq = {
        method: 'GET',
        url: '/some/path?key=value',
        headers: {
          host: 'mattrobenolt.com'
        },
        body: '',
        cookies: {},
        socket: {
          encrypted: true
        }
      };
      var parsed = raven.parsers.parseRequest(mockReq);
      parsed.should.have.property('sentry.interfaces.Http');
      parsed['sentry.interfaces.Http'].url.should.equal('https://mattrobenolt.com/some/path?key=value');
      parsed['sentry.interfaces.Http'].env.NODE_ENV.should.equal('production');
    });
  });

  describe('#parseError()', function(){
    it('should parse plain Error object', function(done){
      raven.parsers.parseError(new Error(), {}, function(parsed){
        parsed['message'].should.equal('Error: <no message>');
        parsed.should.have.property('sentry.interfaces.Exception');
        parsed['sentry.interfaces.Exception']['type'].should.equal('Error');
        parsed['sentry.interfaces.Exception']['value'].should.equal('');
        parsed.should.have.property('sentry.interfaces.Stacktrace');
        parsed['sentry.interfaces.Stacktrace'].should.have.property('frames');
        parsed.should.have.property('culprit');
        parsed['culprit'].should.match(/^.+?:.+$/);
        done();
      });
    });

    it('should parse Error with message', function(done){
      raven.parsers.parseError(new Error('Crap'), {}, function(parsed){
        parsed['message'].should.equal('Error: Crap');
        parsed.should.have.property('sentry.interfaces.Exception');
        parsed['sentry.interfaces.Exception']['type'].should.equal('Error');
        parsed['sentry.interfaces.Exception']['value'].should.equal('Crap');
        parsed.should.have.property('sentry.interfaces.Stacktrace');
        parsed['sentry.interfaces.Stacktrace'].should.have.property('frames');
        parsed.should.have.property('culprit');
        parsed['culprit'].should.match(/^.+?:.+$/);
        done();
      });
    });

    it('should parse TypeError with message', function(done){
      raven.parsers.parseError(new TypeError('Crap'), {}, function(parsed){
        parsed['message'].should.equal('TypeError: Crap');
        parsed.should.have.property('sentry.interfaces.Exception');
        parsed['sentry.interfaces.Exception']['type'].should.equal('TypeError');
        parsed['sentry.interfaces.Exception']['value'].should.equal('Crap');
        parsed.should.have.property('sentry.interfaces.Stacktrace');
        parsed['sentry.interfaces.Stacktrace'].should.have.property('frames');
        parsed.should.have.property('culprit');
        parsed['culprit'].should.match(/^.+?:.+$/);
        done();
      });
    });

    it('should parse thrown Error', function(done){
      try {
        throw new Error('Derp');
      } catch(e) {
        raven.parsers.parseError(e, {}, function(parsed){
          parsed['message'].should.equal('Error: Derp');
          parsed.should.have.property('sentry.interfaces.Exception');
          parsed['sentry.interfaces.Exception']['type'].should.equal('Error');
          parsed['sentry.interfaces.Exception']['value'].should.equal('Derp');
          parsed.should.have.property('sentry.interfaces.Stacktrace');
          parsed['sentry.interfaces.Stacktrace'].should.have.property('frames');
          parsed.should.have.property('culprit');
          parsed['culprit'].should.match(/^.+?:.+$/);
          done();
        });
      }
    });

    it('should parse caught real error', function(done){
      try {
        var o = {};
        o['...']['Derp']();
      } catch(e) {
        raven.parsers.parseError(e, {}, function(parsed){
          parsed['message'].should.equal('TypeError: Cannot call method \'Derp\' of undefined');
          parsed.should.have.property('sentry.interfaces.Exception');
          parsed['sentry.interfaces.Exception']['type'].should.equal('TypeError');
          parsed['sentry.interfaces.Exception']['value'].should.equal('Cannot call method \'Derp\' of undefined');
          parsed.should.have.property('sentry.interfaces.Stacktrace');
          parsed['sentry.interfaces.Stacktrace'].should.have.property('frames');
          parsed.should.have.property('culprit');
          parsed['culprit'].should.match(/^.+?:.+$/);
          done();
        });
      }
    });
  });
});<commit_msg>Try to fix Travis.<commit_after>var raven = require('../');
raven.parsers = require('../lib/parsers');

describe('raven.parsers', function(){
  describe('#parseText()', function(){
    it('should parse some text without kwargs', function(){
      var parsed = raven.parsers.parseText('Howdy');
      parsed['message'].should.equal('Howdy');
      parsed.should.have.property('sentry.interfaces.Message');
      parsed['sentry.interfaces.Message'].message.should.equal('Howdy');
    });

    it('should parse some text with kwargs', function(){
      var parsed = raven.parsers.parseText('Howdy', {'foo': 'bar'});
      parsed['message'].should.equal('Howdy');
      parsed.should.have.property('sentry.interfaces.Message');
      parsed['sentry.interfaces.Message'].message.should.equal('Howdy');
      parsed['foo'].should.equal('bar');
    });
  });

  describe('#parseQuery()', function(){
    it('should parse a query', function(){
      var query = 'SELECT * FROM `something`';
      var engine = 'mysql';
      var parsed = raven.parsers.parseQuery(query, engine);
      parsed['message'].should.equal('SELECT * FROM `something`');
      parsed.should.have.property('sentry.interfaces.Query');
      parsed['sentry.interfaces.Query'].query.should.equal('SELECT * FROM `something`');
      parsed['sentry.interfaces.Query'].engine.should.equal('mysql');
    });
  });

  describe('#parseRequest()', function(){
    it('should parse a request object', function(){
      var mockReq = {
        method: 'GET',
        url: '/some/path?key=value',
        headers: {
          host: 'mattrobenolt.com'
        },
        body: '',
        cookies: {},
        socket: {
          encrypted: true
        }
      };
      var parsed = raven.parsers.parseRequest(mockReq);
      parsed.should.have.property('sentry.interfaces.Http');
      parsed['sentry.interfaces.Http'].url.should.equal('https://mattrobenolt.com/some/path?key=value');
      parsed['sentry.interfaces.Http'].env.NODE_ENV.should.equal(process.env.NODE_ENV);
    });
  });

  describe('#parseError()', function(){
    it('should parse plain Error object', function(done){
      raven.parsers.parseError(new Error(), {}, function(parsed){
        parsed['message'].should.equal('Error: <no message>');
        parsed.should.have.property('sentry.interfaces.Exception');
        parsed['sentry.interfaces.Exception']['type'].should.equal('Error');
        parsed['sentry.interfaces.Exception']['value'].should.equal('');
        parsed.should.have.property('sentry.interfaces.Stacktrace');
        parsed['sentry.interfaces.Stacktrace'].should.have.property('frames');
        parsed.should.have.property('culprit');
        parsed['culprit'].should.match(/^.+?:.+$/);
        done();
      });
    });

    it('should parse Error with message', function(done){
      raven.parsers.parseError(new Error('Crap'), {}, function(parsed){
        parsed['message'].should.equal('Error: Crap');
        parsed.should.have.property('sentry.interfaces.Exception');
        parsed['sentry.interfaces.Exception']['type'].should.equal('Error');
        parsed['sentry.interfaces.Exception']['value'].should.equal('Crap');
        parsed.should.have.property('sentry.interfaces.Stacktrace');
        parsed['sentry.interfaces.Stacktrace'].should.have.property('frames');
        parsed.should.have.property('culprit');
        parsed['culprit'].should.match(/^.+?:.+$/);
        done();
      });
    });

    it('should parse TypeError with message', function(done){
      raven.parsers.parseError(new TypeError('Crap'), {}, function(parsed){
        parsed['message'].should.equal('TypeError: Crap');
        parsed.should.have.property('sentry.interfaces.Exception');
        parsed['sentry.interfaces.Exception']['type'].should.equal('TypeError');
        parsed['sentry.interfaces.Exception']['value'].should.equal('Crap');
        parsed.should.have.property('sentry.interfaces.Stacktrace');
        parsed['sentry.interfaces.Stacktrace'].should.have.property('frames');
        parsed.should.have.property('culprit');
        parsed['culprit'].should.match(/^.+?:.+$/);
        done();
      });
    });

    it('should parse thrown Error', function(done){
      try {
        throw new Error('Derp');
      } catch(e) {
        raven.parsers.parseError(e, {}, function(parsed){
          parsed['message'].should.equal('Error: Derp');
          parsed.should.have.property('sentry.interfaces.Exception');
          parsed['sentry.interfaces.Exception']['type'].should.equal('Error');
          parsed['sentry.interfaces.Exception']['value'].should.equal('Derp');
          parsed.should.have.property('sentry.interfaces.Stacktrace');
          parsed['sentry.interfaces.Stacktrace'].should.have.property('frames');
          parsed.should.have.property('culprit');
          parsed['culprit'].should.match(/^.+?:.+$/);
          done();
        });
      }
    });

    it('should parse caught real error', function(done){
      try {
        var o = {};
        o['...']['Derp']();
      } catch(e) {
        raven.parsers.parseError(e, {}, function(parsed){
          parsed['message'].should.equal('TypeError: Cannot call method \'Derp\' of undefined');
          parsed.should.have.property('sentry.interfaces.Exception');
          parsed['sentry.interfaces.Exception']['type'].should.equal('TypeError');
          parsed['sentry.interfaces.Exception']['value'].should.equal('Cannot call method \'Derp\' of undefined');
          parsed.should.have.property('sentry.interfaces.Stacktrace');
          parsed['sentry.interfaces.Stacktrace'].should.have.property('frames');
          parsed.should.have.property('culprit');
          parsed['culprit'].should.match(/^.+?:.+$/);
          done();
        });
      }
    });
  });
});
<|endoftext|>


<commit_before>if (Meteor.isServer) {
    // Start a server to test HTTP client streams.
    var http = Npm.require("http");
    var url = Npm.require("url");
    var server = http.createServer(function(req, res) {
        var url = req.url;

        switch (url) {
            case "/test1":
                res.write("OK");
                res.end();
                break;

            case "/test2":
                res.write("1");
                setTimeout(function() { res.write("2"); }, 10);
                setTimeout(function() { res.write("3"); }, 20);
                setTimeout(function() { res.write("4"); }, 30);
                setTimeout(function() { res.write("5"); }, 40);
                setTimeout(function() { res.end(); }, 50);
                break;

            case "/test3":
                var buf1 = new Buffer([1,2,3,4]);
                res.write(buf1);

                setTimeout(function() {
                    var buf2 = new Buffer([5,6,7,8]);
                    res.write(buf2);

                    res.end();
                }, 50);

                break;

            case "/test4":
                var buffers = [];

                req.on("data", function(data) {
                    buffers.push(data);
                });

                req.on("end", function() {
                    res.write(Buffer.concat(buffers));
                    res.end();
                });

                break;

            case "/method":
                res.setHeader("X-METHOD", "HEAD");

                if (req.method !== "HEAD") {
                    res.write(req.method);
                }

                res.end();
                break;

            case "/echo":
                var body = "";

                req.on("data", function(data) {
                    body += data;
                });

                req.on("end", function() {
                    res.write(body);
                    res.end();
                });

                break;

            case "/hang":
                // Do not respond.
                break;

            case "/getToken":
                var token = req.headers["x-token"];
                res.write(token);
                res.end();
                break;

            case "/404":
                res.writeHead(404, "Not found.");
                res.end();
                break;

            case "/500":
                res.writeHead(500, "Internal server error.");
                res.end();
                break;

            default:
                console.error("Bad path");
                res.writeHead(400, "Bad path");
                res.end();
                break;
        }
    });

    var port = 10492;
    server.listen(port, "127.0.0.1");

    var makeAddr = function(path) {
        return "http://127.0.0.1:" + port + path;
    };

    Tinytest.add("GET /test1 (basic)", function(test) {
        var addr = makeAddr("/test1");
        var res = request.getSync(addr);
        test.equal(res.body, "OK");
    });

    Tinytest.add("GET /test2 (\"more\" async)", function(test) {
        var addr = makeAddr("/test2");
        var res = request.getSync(addr);
        test.equal(res.body, "12345");
    });

    Tinytest.add("GET /test3 (buffer)", function(test) {
        var addr = makeAddr("/test3");
        var res = request.getSync(addr, {
            encoding: null
        });

        test.isTrue(res.body instanceof Buffer, "res.body should be a Buffer");
        for (var i = 0; i < 8; i++) {
            test.equal(res.body[i], i + 1);
        }
    });

    Tinytest.add("POST /test4 (echo binary)", function(test) {
        var addr = makeAddr("/test4");
        var buf = new Buffer([0,1,2]);
        var res = request.postSync(addr, {
            body: buf,
            encoding: null
        });

        test.isTrue(res.body instanceof Buffer, "res.body should be a buffer");
        test.equal(res.body.length, 3);
        test.equal(res.body[0], 0);
        test.equal(res.body[1], 1);
        test.equal(res.body[2], 2);
    });

    Tinytest.add("PATCH /echo", function(test) {
        var addr = makeAddr("/echo");
        var res = request.patchSync(addr, {
            body: "patch test"
        });
        test.equal(res.body, "patch test");
    });

    Tinytest.add("POST /echo", function(test) {
        var addr = makeAddr("/echo");
        var res = request.postSync(addr, {
            body: "post test"
        });
        test.equal(res.body, "post test");
    });

    Tinytest.add("PUT /echo", function(test) {
        var addr = makeAddr("/echo");
        var res = request.putSync(addr, {
            body: "put test"
        });
        test.equal(res.body, "put test");
    });

    Tinytest.add("GET /method", function(test) {
        var addr = makeAddr("/method");
        var res = request.getSync(addr);
        test.equal(res.body, "GET");
    });

    Tinytest.add("PUT /method", function(test) {
        var addr = makeAddr("/method");
        var res = request.putSync(addr);
        test.equal(res.body, "PUT");
    });

    Tinytest.add("PATCH /method", function(test) {
        var addr = makeAddr("/method");
        var res = request.patchSync(addr);
        test.equal(res.body, "PATCH");
    });

    Tinytest.add("POST /method", function(test) {
        var addr = makeAddr("/method");
        var res = request.postSync(addr);
        test.equal(res.body, "POST");
    });

    Tinytest.add("HEAD /method", function(test) {
        var addr = makeAddr("/method");
        var res = request.headSync(addr);
        var method = res.response.headers["x-method"];
        test.equal(method, "HEAD");
    });

    Tinytest.add("DELETE /method", function(test) {
        var addr = makeAddr("/method");
        var res = request.delSync(addr);
        test.equal(res.body, "DELETE");
    });

    Tinytest.add("Just options (url in options)", function(test) {
        var addr = makeAddr("/method");
        var res = request.getSync({
            url: addr
        });
        test.equal(res.body, "GET");
    });

    Tinytest.add("Just options, no options.url should throw", function(test) {
        test.throws(function() {
            var res = request.getSync({ });
        });
    });

    // To me this seems undocumented, but it's how request works.
    Tinytest.add("With parsed url object (surprisingly fails)", function(test) {
        test.throws(function() {
            var addr = makeAddr("/method");
            var uri = url.parse(addr);
            request.getSync(uri);
        });
    });

    Tinytest.add("With parsed url object and options", function(test) {
        var addr = makeAddr("/getToken");
        var uri = url.parse(addr);
        var res = request.getSync(uri, {
            headers: { "X-TOKEN": "XYZ" }
        });
        test.equal(res.body, "XYZ");
    });

    Tinytest.add("With parsed url object in options", function(test) {
        var addr = makeAddr("/method");
        var uri = url.parse(addr);
        var res = request.getSync({
            uri: uri
        });
        test.equal(res.body, "GET");
    });

    Tinytest.add("Throw without URI/options", function(test) {
        test.throws(function() {
            request.getSync();
        });
    });

    Tinytest.add("Timeout", function(test) {
        test.throws(function() {
            var addr = makeAddr("/hang");
            request.getSync(addr, {
                timeout: 100
            });
        });
    });

    Tinytest.add("GET /404", function(test) {
        var addr = makeAddr("/404");
        var res = request.getSync(addr);
        test.equal(res.response.statusCode, 404);
    });

    Tinytest.add("GET /500", function(test) {
        var addr = makeAddr("/500");
        var res = request.getSync(addr);
        test.equal(res.response.statusCode, 500);
    });

    Tinytest.add("Test defaults", function(test) {
        var defaults = request.defaults({
            headers: { "X-TOKEN": "XYZ" }
        });

        var addr = makeAddr("/getToken");
        var res = defaults.getSync(addr);
        test.equal(res.body, "XYZ");
    });

    Tinytest.add("request.sync should exist", function(test) {
        test.equal(typeof request.sync, "function");
    });

    Tinytest.add("request.sync should default to GET", function(test) {
        var addr = makeAddr("/method");
        var res = request.sync(addr);
        test.equal(res.body, "GET");
    });

    Tinytest.add("request.sync GET should work", function(test) {
        var addr = makeAddr("/method");
        var res = request.sync(addr);
        test.equal(res.body, "GET");
    });

    Tinytest.add("request.sync with options should work", function(test) {
        var addr = makeAddr("/getToken");
        var res = request.sync({
            url: addr,
            headers: { "X-TOKEN": "XYZ" }
        });
        test.equal(res.body, "XYZ");
    });
}

<commit_msg>Group tests.<commit_after>if (Meteor.isServer) {
    // Start a server to test HTTP client streams.
    var http = Npm.require("http");
    var url = Npm.require("url");
    var server = http.createServer(function(req, res) {
        var url = req.url;

        switch (url) {
            case "/test1":
                res.write("OK");
                res.end();
                break;

            case "/test2":
                res.write("1");
                setTimeout(function() { res.write("2"); }, 10);
                setTimeout(function() { res.write("3"); }, 20);
                setTimeout(function() { res.write("4"); }, 30);
                setTimeout(function() { res.write("5"); }, 40);
                setTimeout(function() { res.end(); }, 50);
                break;

            case "/test3":
                var buf1 = new Buffer([1,2,3,4]);
                res.write(buf1);

                setTimeout(function() {
                    var buf2 = new Buffer([5,6,7,8]);
                    res.write(buf2);

                    res.end();
                }, 50);

                break;

            case "/test4":
                var buffers = [];

                req.on("data", function(data) {
                    buffers.push(data);
                });

                req.on("end", function() {
                    res.write(Buffer.concat(buffers));
                    res.end();
                });

                break;

            case "/method":
                res.setHeader("X-METHOD", "HEAD");

                if (req.method !== "HEAD") {
                    res.write(req.method);
                }

                res.end();
                break;

            case "/echo":
                var body = "";

                req.on("data", function(data) {
                    body += data;
                });

                req.on("end", function() {
                    res.write(body);
                    res.end();
                });

                break;

            case "/hang":
                // Do not respond.
                break;

            case "/getToken":
                var token = req.headers["x-token"];
                res.write(token);
                res.end();
                break;

            case "/404":
                res.writeHead(404, "Not found.");
                res.end();
                break;

            case "/500":
                res.writeHead(500, "Internal server error.");
                res.end();
                break;

            default:
                console.error("Bad path");
                res.writeHead(400, "Bad path");
                res.end();
                break;
        }
    });

    var port = 10492;
    server.listen(port, "127.0.0.1");

    var makeAddr = function(path) {
        return "http://127.0.0.1:" + port + path;
    };

    Tinytest.add("basic - GET /test1 (basic)", function(test) {
        var addr = makeAddr("/test1");
        var res = request.getSync(addr);
        test.equal(res.body, "OK");
    });

    Tinytest.add("basic - GET /test2 (\"more\" async)", function(test) {
        var addr = makeAddr("/test2");
        var res = request.getSync(addr);
        test.equal(res.body, "12345");
    });

    Tinytest.add("basic - GET /test3 (buffer)", function(test) {
        var addr = makeAddr("/test3");
        var res = request.getSync(addr, {
            encoding: null
        });

        test.isTrue(res.body instanceof Buffer, "res.body should be a Buffer");
        for (var i = 0; i < 8; i++) {
            test.equal(res.body[i], i + 1);
        }
    });

    Tinytest.add("basic - POST /test4 (echo binary)", function(test) {
        var addr = makeAddr("/test4");
        var buf = new Buffer([0,1,2]);
        var res = request.postSync(addr, {
            body: buf,
            encoding: null
        });

        test.isTrue(res.body instanceof Buffer, "res.body should be a buffer");
        test.equal(res.body.length, 3);
        test.equal(res.body[0], 0);
        test.equal(res.body[1], 1);
        test.equal(res.body[2], 2);
    });

    Tinytest.add("echo - PATCH /echo", function(test) {
        var addr = makeAddr("/echo");
        var res = request.patchSync(addr, {
            body: "patch test"
        });
        test.equal(res.body, "patch test");
    });

    Tinytest.add("echo - POST /echo", function(test) {
        var addr = makeAddr("/echo");
        var res = request.postSync(addr, {
            body: "post test"
        });
        test.equal(res.body, "post test");
    });

    Tinytest.add("echo - PUT /echo", function(test) {
        var addr = makeAddr("/echo");
        var res = request.putSync(addr, {
            body: "put test"
        });
        test.equal(res.body, "put test");
    });

    Tinytest.add("methods - GET /method", function(test) {
        var addr = makeAddr("/method");
        var res = request.getSync(addr);
        test.equal(res.body, "GET");
    });

    Tinytest.add("methods - PUT /method", function(test) {
        var addr = makeAddr("/method");
        var res = request.putSync(addr);
        test.equal(res.body, "PUT");
    });

    Tinytest.add("methods - PATCH /method", function(test) {
        var addr = makeAddr("/method");
        var res = request.patchSync(addr);
        test.equal(res.body, "PATCH");
    });

    Tinytest.add("methods - POST /method", function(test) {
        var addr = makeAddr("/method");
        var res = request.postSync(addr);
        test.equal(res.body, "POST");
    });

    Tinytest.add("methods - HEAD /method", function(test) {
        var addr = makeAddr("/method");
        var res = request.headSync(addr);
        var method = res.response.headers["x-method"];
        test.equal(method, "HEAD");
    });

    Tinytest.add("methods - DELETE /method", function(test) {
        var addr = makeAddr("/method");
        var res = request.delSync(addr);
        test.equal(res.body, "DELETE");
    });

    Tinytest.add("options - Just options (url in options)", function(test) {
        var addr = makeAddr("/method");
        var res = request.getSync({
            url: addr
        });
        test.equal(res.body, "GET");
    });

    Tinytest.add("options - Just options, no options.url should throw", function(test) {
        test.throws(function() {
            var res = request.getSync({ });
        });
    });

    // To me this seems undocumented, but it's how request works.
    Tinytest.add("options - With parsed url object (surprisingly fails)", function(test) {
        test.throws(function() {
            var addr = makeAddr("/method");
            var uri = url.parse(addr);
            request.getSync(uri);
        });
    });

    Tinytest.add("options - With parsed url object and options", function(test) {
        var addr = makeAddr("/getToken");
        var uri = url.parse(addr);
        var res = request.getSync(uri, {
            headers: { "X-TOKEN": "XYZ" }
        });
        test.equal(res.body, "XYZ");
    });

    Tinytest.add("options - With parsed url object in options", function(test) {
        var addr = makeAddr("/method");
        var uri = url.parse(addr);
        var res = request.getSync({
            uri: uri
        });
        test.equal(res.body, "GET");
    });

    Tinytest.add("options - Throw without URI/options", function(test) {
        test.throws(function() {
            request.getSync();
        });
    });

    Tinytest.add("errors - Timeout", function(test) {
        test.throws(function() {
            var addr = makeAddr("/hang");
            request.getSync(addr, {
                timeout: 100
            });
        });
    });

    Tinytest.add("errors - GET /404", function(test) {
        var addr = makeAddr("/404");
        var res = request.getSync(addr);
        test.equal(res.response.statusCode, 404);
    });

    Tinytest.add("errors - GET /500", function(test) {
        var addr = makeAddr("/500");
        var res = request.getSync(addr);
        test.equal(res.response.statusCode, 500);
    });

    Tinytest.add("defaults - Test defaults", function(test) {
        var defaults = request.defaults({
            headers: { "X-TOKEN": "XYZ" }
        });

        var addr = makeAddr("/getToken");
        var res = defaults.getSync(addr);
        test.equal(res.body, "XYZ");
    });

    Tinytest.add("sync - request.sync should exist", function(test) {
        test.equal(typeof request.sync, "function");
    });

    Tinytest.add("sync - request.sync should default to GET", function(test) {
        var addr = makeAddr("/method");
        var res = request.sync(addr);
        test.equal(res.body, "GET");
    });

    Tinytest.add("sync - request.sync GET should work", function(test) {
        var addr = makeAddr("/method");
        var res = request.sync(addr);
        test.equal(res.body, "GET");
    });

    Tinytest.add("sync - request.sync with options should work", function(test) {
        var addr = makeAddr("/getToken");
        var res = request.sync({
            url: addr,
            headers: { "X-TOKEN": "XYZ" }
        });
        test.equal(res.body, "XYZ");
    });
}

<|endoftext|>


<commit_before>'use strict';

var isCopy      = require('es5-ext/lib/Array/prototype/is-copy')
  , d           = require('es5-ext/lib/Object/descriptor')
  , makeEl      = require('dom-ext/lib/Document/prototype/make-element')
  , Db          = require('dbjs')
  , DOMInput    = require('./_controls/input')
  , DOMRadio    = require('./_controls/radio')
  , DOMCheckbox = require('./_controls/checkbox')

  , isArray = Array.isArray
  , BooleanType = Db.Boolean
  , getValue =
	Object.getOwnPropertyDescriptor(DOMCheckbox.prototype, 'value').get
  , getName = Object.getOwnPropertyDescriptor(DOMInput.prototype, 'name').get
  , Radio, Checkbox, arrResult = ['0', '1'].sort();

Radio = function (document, ns/*, options*/) {
	var tOption, fOption, options = Object(arguments[2]), reverse;
	DOMRadio.call(this, document, ns, options);
	tOption = this.createOption('1', options.trueLabel || ns._trueLabel);
	fOption = this.createOption('0', options.falseLabel || ns._falseLabel);

	reverse = Number(options.order) < 0;
	this.dom.appendChild(reverse ? fOption : tOption);
	this.dom.appendChild(document.createTextNode(' '));
	this.dom.appendChild(reverse ? tOption : fOption);
};
Radio.prototype = Object.create(DOMRadio.prototype, { constructor: d(Radio) });

Checkbox = function (document, ns/*, options*/) {
	DOMCheckbox.apply(this, arguments);
};
Checkbox.prototype = Object.create(DOMCheckbox.prototype, {
	constructor: d(Checkbox),
	inputValue: d.gs(function () { return this.control.checked ? '1' : '0'; }),
	_render: d(function () {
		var el = makeEl.bind(this.document);
		this.controls = {};
		this.dom = el('span', this.control = el('input',
			{ type: 'checkbox', value: '1' }), this.hidden = el('input',
				{ type: 'hidden', value: '0' }));
	}),
	name: d.gs(getName, function (name) {
		this._name = name;
		name = this.name;
		if (name) {
			this.control.setAttribute('name', name);
			this.hidden.setAttribute('name', name);
		} else {
			this.control.removeAttribute('name');
			this.hidden.removeAttribute('name');
		}
	}),
	value: d.gs(getValue, function (value) {
		var old = this.inputValue, nu = this.ns.toInputValue(value);
		if (nu == null) nu = '0';
		if (nu !== this._value) {
			if (nu !== '1') this.control.removeAttribute('checked');
			else this.control.setAttribute('checked', 'checked');
		}

		if (nu !== old) this.control.checked = (nu === '1');
		this.onChange();
	}),
	setCheckedValue: d(function () { throw new Error("Not supported"); })
});

module.exports = Object.defineProperties(BooleanType, {
	fromInputValue: d(function (value) {
		if (value == null) return undefined;
		if (value === '0') return false;
		if (value === '1') return true;
		if (isArray(value) && isCopy.call(value.sort(), arrResult)) {
			return true;
		}
		return null;
	}),
	toInputValue: d(function (value) {
		if (value == null) return null;
		else return value.valueOf() ? '1' : '0';
	}),
	DOMRadio: d(Radio),
	DOMCheckbox: d(Checkbox),
	toDOMInput: d(function (document/*, options*/) {
		var options = Object(arguments[1]);
		if (options.multiple) {
			return new this.DOMMultipleInput(document, this, options);
		}
		if (options.type === 'checkbox') {
			return new this.DOMCheckbox(document, this, options);
		} else {
			return new this.DOMRadio(document, this, options);
		}
	})
});
<commit_msg>Read labels from db relation<commit_after>'use strict';

var isCopy      = require('es5-ext/lib/Array/prototype/is-copy')
  , d           = require('es5-ext/lib/Object/descriptor')
  , makeEl      = require('dom-ext/lib/Document/prototype/make-element')
  , Db          = require('dbjs')
  , DOMInput    = require('./_controls/input')
  , DOMRadio    = require('./_controls/radio')
  , DOMCheckbox = require('./_controls/checkbox')

  , isArray = Array.isArray
  , BooleanType = Db.Boolean
  , getValue =
	Object.getOwnPropertyDescriptor(DOMCheckbox.prototype, 'value').get
  , getName = Object.getOwnPropertyDescriptor(DOMInput.prototype, 'name').get
  , Radio, Checkbox, arrResult = ['0', '1'].sort(), getLabel;

getLabel = function (name, options, ns) {
	name += 'Label';
	if (options[name]) return options[name];
	options = options.dbOptions;
	if (options[name]) return options['_' + name];
	return ns['_' + name];
};

Radio = function (document, ns/*, options*/) {
	var tOption, fOption, options = Object(arguments[2]), reverse;
	DOMRadio.call(this, document, ns, options);
	tOption = this.createOption('1', getLabel('true', options, ns));
	fOption = this.createOption('0', getLabel('false', options, ns));

	reverse = Number(options.order) < 0;
	this.dom.appendChild(reverse ? fOption : tOption);
	this.dom.appendChild(document.createTextNode(' '));
	this.dom.appendChild(reverse ? tOption : fOption);
};
Radio.prototype = Object.create(DOMRadio.prototype, { constructor: d(Radio) });

Checkbox = function (document, ns/*, options*/) {
	DOMCheckbox.apply(this, arguments);
};
Checkbox.prototype = Object.create(DOMCheckbox.prototype, {
	constructor: d(Checkbox),
	inputValue: d.gs(function () { return this.control.checked ? '1' : '0'; }),
	_render: d(function () {
		var el = makeEl.bind(this.document);
		this.controls = {};
		this.dom = el('span', this.control = el('input',
			{ type: 'checkbox', value: '1' }), this.hidden = el('input',
				{ type: 'hidden', value: '0' }));
	}),
	name: d.gs(getName, function (name) {
		this._name = name;
		name = this.name;
		if (name) {
			this.control.setAttribute('name', name);
			this.hidden.setAttribute('name', name);
		} else {
			this.control.removeAttribute('name');
			this.hidden.removeAttribute('name');
		}
	}),
	value: d.gs(getValue, function (value) {
		var old = this.inputValue, nu = this.ns.toInputValue(value);
		if (nu == null) nu = '0';
		if (nu !== this._value) {
			if (nu !== '1') this.control.removeAttribute('checked');
			else this.control.setAttribute('checked', 'checked');
		}

		if (nu !== old) this.control.checked = (nu === '1');
		this.onChange();
	}),
	setCheckedValue: d(function () { throw new Error("Not supported"); })
});

module.exports = Object.defineProperties(BooleanType, {
	fromInputValue: d(function (value) {
		if (value == null) return undefined;
		if (value === '0') return false;
		if (value === '1') return true;
		if (isArray(value) && isCopy.call(value.sort(), arrResult)) {
			return true;
		}
		return null;
	}),
	toInputValue: d(function (value) {
		if (value == null) return null;
		else return value.valueOf() ? '1' : '0';
	}),
	DOMRadio: d(Radio),
	DOMCheckbox: d(Checkbox),
	toDOMInput: d(function (document/*, options*/) {
		var options = Object(arguments[1]);
		if (options.multiple) {
			return new this.DOMMultipleInput(document, this, options);
		}
		if (options.type === 'checkbox') {
			return new this.DOMCheckbox(document, this, options);
		} else {
			return new this.DOMRadio(document, this, options);
		}
	})
});
<|endoftext|>