<commit_before>import React from 'react'
import Page from 'components/Page'
import autobind from 'autobind-decorator'
import moment from 'moment'

import {DropdownButton, MenuItem} from 'react-bootstrap'
import Breadcrumbs from 'components/Breadcrumbs'
import ReportCollection from 'components/ReportCollection'
import ReportSummary from 'components/ReportSummary'

import API from 'api'
import {Report} from 'models'

var d3 = null/* required later */

const graphCss = {
	width: '100%',
	height: '300px'
}

const barColors = {
	verified: '#9CBDA4',
	unverified: '#F5D98C',
	incoming: '#DA9795',
}

export default class RollupShow extends Page {
	static propTypes = {
		date: React.PropTypes.object,
	}

	static defaultProps = {
		date: moment(),
	}

	static contextTypes = {
		app: React.PropTypes.object.isRequired,
	}

	get dateStr() { return this.props.date.format('DD MMM YYYY') }
	get dateLongStr() { return this.props.date.format('DD MMMM YYYY') }
	get rollupStart() { return moment(this.props.date).startOf('day') }
	get rollupEnd() { return moment(this.props.date).endOf('day') }

	constructor(props) {
		super(props)
		this.state = {
			date: {},
			reports: {list: []},
		}
	}

	componentDidMount() {
		super.componentDidMount()

		if (d3) {
			return
		}

		require.ensure([], () => {
			d3 = require('d3')
			this.forceUpdate()
		})
	}

	fetchData(props) {
		let rollupQuery = {
			releasedAtStart: this.rollupStart.valueOf(),
			releasedAtEnd: this.rollupEnd.valueOf(),
			engagementDateStart: moment(this.rollupStart).subtract(14, 'days').valueOf()
		}
		API.query(/* GraphQL */`
			reportList(f:search, query:$rollupQuery) {
				pageNum, pageSize, totalCount, list {
					id, state, intent, engagementDate, intent, keyOutcomes, nextSteps
					author { id, name }
					location { id, name, lat, lng}
					poams { id, longName }
					comments { id }
					primaryAdvisor {
						id, name, rank
						position { organization { id, shortName, longName }}
					}
					primaryPrincipal {
						id, name, rank
						position { organization { id, shortName, longName }}
					}
					advisorOrg {
						id, shortName
						parentOrg { id, shortName }
					}
				}
			}
		`, {rollupQuery}, '($rollupQuery: ReportSearchQuery)')
		.then(data => {
			data.reportList.list = Report.fromArray(data.reportList.list)
			if (data.reportList.pageSize == null) {
				data.reportList.pageSize = 1
				data.reportList.pageNum = 1
				data.reportList.totalCount = data.reportList.list.length
			}
			this.setState({reports: data.reportList})
		})
	}

	componentDidUpdate() {
		let reports = this.state.reports.list
		if (!reports || !d3)
			return

		// Sets up the data
		var step1 = d3.nest()
				.key(function(d){return (d.advisorOrg && d.advisorOrg.shortName)})
				.rollup(function(d){return {l:d.length,s:d[0].state,r:d}})
				.entries(reports)

		var svg = d3.select(this.graph),
			margin = {top: 20, right: 20, bottom: 20, left: 20},
			width = this.graph.clientWidth - margin.left - margin.right,
			height = this.graph.clientHeight - margin.top - margin.bottom,
			padding = 22,
			g = svg.append('g').attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')

		var x = d3.scaleBand().rangeRound([0,width])

		var y = d3.scaleLinear()
			.rangeRound([height, 0])

		x.domain(step1.map(function(d){return d.key}))
		y.domain([0,d3.max(step1.map(function(d){return d.value.l}))])
		d3.line()
			.x(function(d,i) { return x(d.key) })
			.y(function(d,i) { return y(d.value) })

		var xAxis = d3.axisBottom()
			.scale(x)
		var maxValue = d3.max(step1.map(function(d){
					return d.value.l
				  }))
		var yAxis = d3.axisLeft()
			.scale(y).ticks(Math.min(maxValue+1,10))

		g.append('g')
			.attr('transform', 'translate(0,' + height + ')')
			.attr('fill', '#000')
			.call(xAxis)

		g.append('g')
			.attr('fill', '#400')
			.call(yAxis)
			.append('text')
			.attr('fill', '#000')
			.attr('transform', 'rotate(-90)')
			.attr('y', 6)
			.attr('dy', '0.71em')
			.style('text-anchor', 'end')
			.text('# of Reports')

		g.selectAll('.bar')
			.data(step1)
			.enter().append('rect')
			.attr('class', 'line')
			.attr('width', width / step1.length - padding)
			.attr('x',function(d,i){return x(d.key) + (width / (step1.length + padding))})
			.attr('height', function(d,i){return height - y(d.value.l)})
			.attr('y',function(d,i){return y(d.value.l) })
			.attr('fill', function(d){return barColors.verified})
	}

	render() {
		// let reports = this.state.reports.list
		let reportOTD = null //reports[0]

		// Admins can edit poams, or super users if this poam is assigned to their org.
		let currentUser = this.context.app.state.currentUser
		let canEdit = currentUser && currentUser.isAdmin()

		return (

				<Breadcrumbs items={[['Rollup', ''],[this.dateStr, 'rollup/' +this.dateStr]]} />

				{canEdit &&

						<DropdownButton bsStyle="primary" title="Actions" id="actions" className="pull-right" onSelect={this.actionSelect}>
							<MenuItem eventKey="email">Email rollup</MenuItem>
							<MenuItem eventKey="print">Print</MenuItem>
						</DropdownButton>

				}

Daily Rollup - {this.dateLongStr}

				<fieldset>
					<legend>Summary of Report Input</legend>
					<svg ref={el => this.graph = el} style={graphCss} />
				</fieldset>

				{reportOTD && <fieldset>
					<legend>Report of the Day</legend>

					<ReportSummary report={reportOTD} />
				</fieldset>}

				<fieldset>
					<legend>Reports - {this.dateLongStr}</legend>

					<ReportCollection paginatedReports={this.state.reports} />
				</fieldset>

		)
	}

	@autobind
	actionSelect(eventKey, event) {
		console.log('Unimplemented Action: ' + eventKey)
	}
}
<commit_msg>Initial work for changing daily rollup date. Addresses #295<commit_after>import React from 'react'
import Page from 'components/Page'
import autobind from 'autobind-decorator'
import moment from 'moment'

import {DropdownButton, MenuItem, Button} from 'react-bootstrap'

import Breadcrumbs from 'components/Breadcrumbs'
import ReportCollection from 'components/ReportCollection'
import ReportSummary from 'components/ReportSummary'
import DatePicker from 'react-bootstrap-date-picker'

import API from 'api'
import {Report} from 'models'

var d3 = null/* required later */

const graphCss = {
	width: '100%',
	height: '300px'
}

const barColors = {
	verified: '#9CBDA4',
	unverified: '#F5D98C',
	incoming: '#DA9795',
}

export default class RollupShow extends Page {
	static propTypes = {
		date: React.PropTypes.object,
	}

	static defaultProps = {
		date: moment(),
	}

	static contextTypes = {
		app: React.PropTypes.object.isRequired,
	}

	get dateStr() { return this.state.date.format('DD MMM YYYY') }
	get dateLongStr() { return this.state.date.format('DD MMMM YYYY') }
	get rollupStart() { return moment(this.state.date).startOf('day') }
	get rollupEnd() { return moment(this.state.date).endOf('day') }

	constructor(props) {
		super(props)
		this.state = {
			date: props.date,
			reports: {list: []},
		}
	}

	componentDidMount() {
		super.componentDidMount()

		if (d3) {
			return
		}

		require.ensure([], () => {
			d3 = require('d3')
			this.forceUpdate()
		})
	}

	fetchData(props) {
		let rollupQuery = {
			releasedAtStart: this.rollupStart.valueOf(),
			releasedAtEnd: this.rollupEnd.valueOf(),
			engagementDateStart: moment(this.rollupStart).subtract(14, 'days').valueOf()
		}
		API.query(/* GraphQL */`
			reportList(f:search, query:$rollupQuery) {
				pageNum, pageSize, totalCount, list {
					id, state, intent, engagementDate, intent, keyOutcomes, nextSteps
					author { id, name }
					location { id, name, lat, lng}
					poams { id, longName }
					comments { id }
					primaryAdvisor {
						id, name, rank
						position { organization { id, shortName, longName }}
					}
					primaryPrincipal {
						id, name, rank
						position { organization { id, shortName, longName }}
					}
					advisorOrg {
						id, shortName
						parentOrg { id, shortName }
					}
				}
			}
		`, {rollupQuery}, '($rollupQuery: ReportSearchQuery)')
		.then(data => {
			data.reportList.list = Report.fromArray(data.reportList.list)
			if (data.reportList.pageSize == null) {
				data.reportList.pageSize = 1
				data.reportList.pageNum = 1
				data.reportList.totalCount = data.reportList.list.length
			}
			this.setState({reports: data.reportList})
		})
	}

	componentDidUpdate() {
		let reports = this.state.reports.list
		if (!reports || !d3) {
			return
		}

		// Sets up the data
		var step1 = d3.nest()
				.key(function(d){return (d.advisorOrg && d.advisorOrg.shortName)})
				.rollup(function(d){return {l:d.length,s:d[0].state,r:d}})
				.entries(reports)

		var svg = d3.select(this.graph),
			margin = {top: 20, right: 20, bottom: 20, left: 20},
			width = this.graph.clientWidth - margin.left - margin.right,
			height = this.graph.clientHeight - margin.top - margin.bottom,
			padding = 22,
			g = svg.append('g').attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')

		var x = d3.scaleBand().rangeRound([0,width])

		var y = d3.scaleLinear()
			.rangeRound([height, 0])

		x.domain(step1.map(function(d){return d.key}))
		y.domain([0,d3.max(step1.map(function(d){return d.value.l}))])
		d3.line()
			.x(function(d,i) { return x(d.key) })
			.y(function(d,i) { return y(d.value) })

		var xAxis = d3.axisBottom()
			.scale(x)
		var maxValue = d3.max(step1.map(function(d){
					return d.value.l
				  }))
		var yAxis = d3.axisLeft()
			.scale(y).ticks(Math.min(maxValue+1,10))

		g.append('g')
			.attr('transform', 'translate(0,' + height + ')')
			.attr('fill', '#000')

		g.append('g')
			.attr('fill', '#400')
			.call(yAxis)
			.append('text')
			.attr('fill', '#000')
			.attr('transform', 'rotate(-90)')
			.attr('y', 6)
			.attr('dy', '0.71em')
			.style('text-anchor', 'end')
			.text('# of Reports')

		g.selectAll('.bar')
			.data(step1)
			.enter().append('rect')
			.attr('class', 'line')
			.attr('width', width / step1.length - padding)
			.attr('x',function(d,i){return x(d.key) + (width / (step1.length + padding))})
			.attr('height', function(d,i){return height - y(d.value.l)})
			.attr('y',function(d,i){return y(d.value.l) })
			.attr('fill', function(d){return barColors.verified})
	}

	render() {
		// let reports = this.state.reports.list
		let reportOTD = null //reports[0]

		// Admins can edit poams, or super users if this poam is assigned to their org.
		let currentUser = this.context.app.state.currentUser
		let canEdit = currentUser && currentUser.isAdmin()

		return (

				<Breadcrumbs items={[['Rollup', ''],[this.dateStr, 'rollup/' +this.dateStr]]} />

				{canEdit &&

						<DropdownButton bsStyle="primary" title="Actions" id="actions" className="pull-right" onSelect={this.actionSelect}>
							<MenuItem eventKey="email">Email rollup</MenuItem>
							<MenuItem eventKey="print">Print</MenuItem>
						</DropdownButton>

				}

Daily Rollup - {this.dateLongStr}

				<Button bsStyle="primary" >
					<DatePicker showTodayButton onChange={this.changeRollupDate} />
				</Button>

				<fieldset>
					<legend>Summary of Report Input</legend>
					<svg ref={el => this.graph = el} style={graphCss} />
				</fieldset>

				{reportOTD && <fieldset>
					<legend>Report of the Day</legend>

					<ReportSummary report={reportOTD} />
				</fieldset>}

				<fieldset>
					<legend>Reports - {this.dateLongStr}</legend>

					<ReportCollection paginatedReports={this.state.reports} />
				</fieldset>

		)
	}

	@autobind
	actionSelect(eventKey, event) {
		console.log('Unimplemented Action: ' + eventKey)
	}

	@autobind
	changeRollupDate(event) {
		let dtg = moment(event)
		this.state.date = dtg
		this.loadData()
	}
}
<|endoftext|>


<commit_before>/*custom webhelp*/
var windowheight = $( window ).height();
var windowwidth = $( window ).width();

$( document ).ready(function() {

    /*adjust dev branch notification*/
    if ($( '#dev-notification' ).length ) {
        $( '#dev-notification', '.dev-notification-text' ).width($( '.navbar-header' ).width());
        $( '.navbar-header' ).css("padding-top", $( '#dev-notification' ).height() + 10);
    }

    /*insert links to module functions*/
    if ($( 'a.current' ).length && $( 'dt .headerlink' ).length ) {
        if (window.location.href.indexOf('/ref/cli/') == -1) {
            var tgt = $( 'a.current' );
            tgt.after('

');
            $('dt .headerlink').each(function(idx, elem) {
                var i = [
                '
',
                last(elem.href.split('.')),
                '
']
                .join('');
                $( '#function-list' ).append(i);
            });
        }
    }

    /*scroll the right-hand navigation*/
    //var wheight = $( window ).height() - $( '#sidebar-static' ).height() - $( '#sidebar-static-bottom' ).height();
    var wheight = $( window ).height() - 160;
    $(function(){
        $( '#sidebar-nav' ).slimScroll({
            width: 'inherit',
            size: '14px',
            height: wheight
        }).promise().done(function() {

            if (window.location.hash) {
                var hash = window.location.hash.substring(1);
                var $link = $( '#sidebar-nav').find('a[href$="#' + hash + '"]').addClass("selected");
                if ($link.length) {
                    var scrollTo_val = $link.offset().top - ($( '#sidebar-static' ).height() + 200) + 'px';
                    $( '#sidebar-nav' ).slimScroll({ scrollTo : scrollTo_val });
                }
                else if ($( 'a.current' ).length) {
                    var scrollTo_val = $( 'a.current' ).offset().top - ($( '#sidebar-static' ).height() + 200) + 'px';
                    $( '#sidebar-nav' ).slimScroll({ scrollTo : scrollTo_val });
                }
            }
            else if ($( 'a.current' ).length) {
                var scrollTo_val = $( 'a.current' ).offset().top - ($( '#sidebar-static' ).height() + 200) + 'px';
                $( '#sidebar-nav' ).slimScroll({ scrollTo : scrollTo_val });
            }
            /*hidden by css - make visible after slimScroll plug-in loads*/
            $( '#sidebar-wrapper').css('visibility','visible');
        });
    });

    /*permalink display*/
    $( 'a.headerlink').html( '');

    $( 'h1,h2,h3,h4,h5,h6').mouseenter(function(){
       $(this).find( '.permalink' ).find( 'i' ).css({'color':'#000'});
    }).mouseleave(function(){
        $(this).find( '.permalink' ).find( 'i' ).css({'color':'#fff'});
    });

    /*smooth on-page scrolling for long topic*/
    $( '#sidebar-nav' ).on('click','a[href^="#"]',function (e) {
        e.preventDefault();
        $( '#sidebar-nav' ).find( 'a' ).removeClass('selected');
        $(this).addClass('selected');
        var target = this.hash;
        var $target = $(target);

        $('html, body').stop().animate({
            'scrollTop': $target.offset().top + 200
        }, 900, 'swing', function () {
            window.location.hash = target;
        });
    });

    /*scroll to active topic*/
    $( '#sidebar-nav' ).on('click','a.function-nav-link',function (e) {
        e.preventDefault();
        $( 'a.function-nav-link' ).removeClass('selected');
        $(this).addClass('selected');
        var target = this.hash.substring(1);
        var $target = $('dt[id="' + target + '"]');

        $('html, body').stop().animate({
            'scrollTop': $target.offset().top + 200
        }, 900, 'swing', function () {
            window.location.hash = target;
        });
    });

    /*search form*/
    $( '#search-form' ).find( 'input' ).keypress(function(e) {
        if(e.which == 13) {
            var cx = '004624818632696854117:yfmprrbw3pk&q=';
            'find which search instance to use'
            if (DOCUMENTATION_OPTIONS.SEARCH_CX) {
                cx = DOCUMENTATION_OPTIONS.SEARCH_CX;
            }
            var searchterm = encodeURIComponent($(this).val());
            $(this).val("");
            window.location.href = 'https://www.google.com/cse?cx=' + cx + '&q=' + searchterm;
        }
    });

    /*menu collapse*/
    $( '#menu-toggle' ).click(function(e) {
        e.preventDefault();
        $( '#wrapper' ).toggleClass( 'toggled' );
    });

    /*version page selector*/
    $( 'div.releaselinks' ).on('click', 'a', function (e) {
        e.preventDefault();
        var clickedVer = $(this).attr("href");
        var $currentVer = $( 'div.versions' ).find( 'a.active' ).first();
        if (window.location.href.indexOf(clickedVer) == -1) {
            window.location.href = window.location.href.replace($currentVer.attr("href"), clickedVer);
        }
        else {
            if ($currentVer.text().indexOf(DOCUMENTATION_OPTIONS.REPO_PRIMARY_BRANCH_TAB_NAME) == -1) {
                window.location.href = clickedVer + "topics/releases/" + $currentVer.text().trim() + ".html";
            }
            else window.location.href = clickedVer + "topics/releases/";
        }
    });

    /*lightbox around images*/
    $( 'img' ).not( '.nolightbox' ).each(function() {
        var source = $(this).attr( 'src' );
        var id = $(this).attr( 'id' );
        $(this).wrap('' )
    });

    /*enable bootstrap tooltips*/
    $(function () {
        $('[data-toggle="tooltip"]').tooltip();
    });

    /*notification box*/
    var box;
    $("#notifications").on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        $.get('//docs.saltproject.io/en/announcements.html?id=1', function (data) {
            box = bootbox.dialog({
                title: "Announcements",
                message: data
            });
        _gaq.push(['_trackEvent', 'docs', 'announcement-view']);
        });
    });
    $(document).on('click', '.bootbox', function (event) {
        box.modal('hide');
    });

    getMetaStatus();
}); // $.document.ready

//refresh on window resize
var rtime = new Date(1, 1, 2000, 12,00,00);
var timeout = false;
var delta = 200;
$(window).resize(function() {

    if (!$( '#menu-toggle' ).is(":visible")) {
        rtime = new Date();
        if (timeout === false) {
            timeout = true;
            setTimeout(resizeend, delta);
        }
    }
});

function resizeend() {
    if (new Date() - rtime < delta) {
        setTimeout(resizeend, delta);
    } else {
        timeout = false;
        if ($( window ).height() != windowheight && $(window).width() != windowwidth) {
            location.reload(false);
        }
    }
}

function last(list) {
    return list[list.length - 1];
}

var reviewTag = '
Status:  Technical Review
';
var draftTag = '
Status:  Draft Content
';

function getMetaStatus() {
   var metas = document.getElementsByTagName('meta');

   for (i=0; i<metas.length; i++) {
      if (metas[i].getAttribute("name") == "status") {
         var statusType = metas[i].getAttribute("content");
         (statusType == "review") ? tag = reviewTag : tag = draftTag;
         $( "h1" ).first().after(tag);
      }
   }
}

(function(document, history, location) {
    var HISTORY_SUPPORT = !!(history && history.pushState);

    var anchorScrolls = {
        ANCHOR_REGEX: /^#[^ ]+$/,
        OFFSET_HEIGHT_PX: 60,

        /**
         * Establish events, and fix initial scroll position if a hash is provided.
         */
        init: function() {
            this.scrollIfAnchor(location.hash);
            $('body').on('click', 'a', $.proxy(this, 'delegateAnchors'));
        },

        /**
         * Return the offset amount to deduct from the normal scroll position.
         * Modify as appropriate to allow for dynamic calculations
         */
        getFixedOffset: function() {
            return this.OFFSET_HEIGHT_PX;
        },

        /**
         * If the provided href is an anchor which resolves to an element on the
         * page, scroll to it.
         * @param  {String} href
         * @return {Boolean} - Was the href an anchor.
         */
        scrollIfAnchor: function(href, pushToHistory) {
            var match, anchorOffset;

            if(!this.ANCHOR_REGEX.test(href)) {
                return false;
            }

            match = document.getElementById(href.slice(1));

            if(match) {
                anchorOffset = $(match).offset().top - this.getFixedOffset();
                $('html, body').animate({ scrollTop: anchorOffset});

                // Add the state to history as-per normal anchor links
                if(HISTORY_SUPPORT && pushToHistory) {
                    history.pushState({}, document.title, location.pathname + href);
                }
            }

            return !!match;
        },

        /**
         * If the click event's target was an anchor, fix the scroll position.
         */
        delegateAnchors: function(e) {
            var elem = e.target;

            if(this.scrollIfAnchor(elem.getAttribute('href'), true)) {
                e.preventDefault();
            }
        }
    };

    $(document).ready($.proxy(anchorScrolls, 'init'));
})(window.document, window.history, window.location);

<commit_msg>update docs to build off master instead of develop<commit_after>/*custom webhelp*/
var windowheight = $( window ).height();
var windowwidth = $( window ).width();

$( document ).ready(function() {

    /*adjust dev branch notification*/
    if ($( '#dev-notification' ).length ) {
        $( '#dev-notification', '.dev-notification-text' ).width($( '.navbar-header' ).width());
        $( '.navbar-header' ).css("padding-top", $( '#dev-notification' ).height() + 10);
    }

    /*insert links to module functions*/
    if ($( 'a.current' ).length && $( 'dt .headerlink' ).length ) {
        if (window.location.href.indexOf('/ref/cli/') == -1) {
            var tgt = $( 'a.current' );
            tgt.after('

');
            $('dt .headerlink').each(function(idx, elem) {
                var i = [
                '
',
                last(elem.href.split('.')),
                '
']
                .join('');
                $( '#function-list' ).append(i);
            });
        }
    }

    /*scroll the right-hand navigation*/
    //var wheight = $( window ).height() - $( '#sidebar-static' ).height() - $( '#sidebar-static-bottom' ).height();
    var wheight = $( window ).height() - 160;
    $(function(){
        $( '#sidebar-nav' ).slimScroll({
            width: 'inherit',
            size: '14px',
            height: wheight
        }).promise().done(function() {

            if (window.location.hash) {
                var hash = window.location.hash.substring(1);
                var $link = $( '#sidebar-nav').find('a[href$="#' + hash + '"]').addClass("selected");
                if ($link.length) {
                    var scrollTo_val = $link.offset().top - ($( '#sidebar-static' ).height() + 200) + 'px';
                    $( '#sidebar-nav' ).slimScroll({ scrollTo : scrollTo_val });
                }
                else if ($( 'a.current' ).length) {
                    var scrollTo_val = $( 'a.current' ).offset().top - ($( '#sidebar-static' ).height() + 200) + 'px';
                    $( '#sidebar-nav' ).slimScroll({ scrollTo : scrollTo_val });
                }
            }
            else if ($( 'a.current' ).length) {
                var scrollTo_val = $( 'a.current' ).offset().top - ($( '#sidebar-static' ).height() + 200) + 'px';
                $( '#sidebar-nav' ).slimScroll({ scrollTo : scrollTo_val });
            }
            /*hidden by css - make visible after slimScroll plug-in loads*/
            $( '#sidebar-wrapper').css('visibility','visible');
        });
    });

    /*permalink display*/
    $( 'a.headerlink').html( '');

    $( 'h1,h2,h3,h4,h5,h6').mouseenter(function(){
       $(this).find( '.permalink' ).find( 'i' ).css({'color':'#000'});
    }).mouseleave(function(){
        $(this).find( '.permalink' ).find( 'i' ).css({'color':'#fff'});
    });

    /*smooth on-page scrolling for long topic*/
    $( '#sidebar-nav' ).on('click','a[href^="#"]',function (e) {
        e.preventDefault();
        $( '#sidebar-nav' ).find( 'a' ).removeClass('selected');
        $(this).addClass('selected');
        var target = this.hash;
        var $target = $(target);

        $('html, body').stop().animate({
            'scrollTop': $target.offset().top + 200
        }, 900, 'swing', function () {
            window.location.hash = target;
        });
    });

    /*scroll to active topic*/
    $( '#sidebar-nav' ).on('click','a.function-nav-link',function (e) {
        e.preventDefault();
        $( 'a.function-nav-link' ).removeClass('selected');
        $(this).addClass('selected');
        var target = this.hash.substring(1);
        var $target = $('dt[id="' + target + '"]');

        $('html, body').stop().animate({
            'scrollTop': $target.offset().top + 200
        }, 900, 'swing', function () {
            window.location.hash = target;
        });
    });

    /*search form*/
    $( '#search-form' ).find( 'input' ).keypress(function(e) {
        if(e.which == 13) {
            var cx = '004624818632696854117:yfmprrbw3pk&q=';
            'find which search instance to use'
            if (DOCUMENTATION_OPTIONS.SEARCH_CX) {
                cx = DOCUMENTATION_OPTIONS.SEARCH_CX;
            }
            var searchterm = encodeURIComponent($(this).val());
            $(this).val("");
            window.location.href = 'https://www.google.com/cse?cx=' + cx + '&q=' + searchterm;
        }
    });

    /*menu collapse*/
    $( '#menu-toggle' ).click(function(e) {
        e.preventDefault();
        $( '#wrapper' ).toggleClass( 'toggled' );
    });

    /*version page selector*/
    $( 'div.releaselinks' ).on('click', 'a', function (e) {
        e.preventDefault();
        var clickedVer = $(this).attr("href");
        var $currentVer = $( 'div.versions' ).find( 'a.active' ).first();
        if (window.location.href.indexOf(clickedVer) == -1) {
            window.location.href = window.location.href.replace($currentVer.attr("href"), clickedVer);
        }
        else {
            if ($currentVer.text().indexOf(DOCUMENTATION_OPTIONS.REPO_PRIMARY_BRANCH_TAB_NAME) == -1) {
                window.location.href = clickedVer + "topics/releases/" + $currentVer.text().trim() + ".html";
            }
            else window.location.href = clickedVer + "topics/releases/";
        }
    });

    /*lightbox around images*/
    $( 'img' ).not( '.nolightbox' ).each(function() {
        var source = $(this).attr( 'src' );
        var id = $(this).attr( 'id' );
        $(this).wrap('' )
    });

    /*enable bootstrap tooltips*/
    $(function () {
        $('[data-toggle="tooltip"]').tooltip();
    });

    /*notification box*/
    var box;
    $("#notifications").on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        $.get('//docs.saltproject.io/en/announcements.html?id=1', function (data) {
            box = bootbox.dialog({
                title: "Announcements",
                message: data
            });
        _gaq.push(['_trackEvent', 'docs', 'announcement-view']);
        });
    });
    $(document).on('click', '.bootbox', function (event) {
        box.modal('hide');
    });

    getMetaStatus();
}); // $.document.ready

//refresh on window resize
var rtime = new Date(1, 1, 2000, 12,00,00);
var timeout = false;
var delta = 200;
$(window).resize(function() {

    if (!$( '#menu-toggle' ).is(":visible")) {
        rtime = new Date();
        if (timeout === false) {
            timeout = true;
            setTimeout(resizeend, delta);
        }
    }
});

function resizeend() {
    if (new Date() - rtime < delta) {
        setTimeout(resizeend, delta);
    } else {
        timeout = false;
        if ($( window ).height() != windowheight && $(window).width() != windowwidth) {
            location.reload(false);
        }
    }
}

function last(list) {
    return list[list.length - 1];
}

var reviewTag = '
Status:  Technical Review
';
var draftTag = '
Status:  Draft Content
';

function getMetaStatus() {
   var metas = document.getElementsByTagName('meta');

   for (i=0; i<metas.length; i++) {
      if (metas[i].getAttribute("name") == "status") {
         var statusType = metas[i].getAttribute("content");
         (statusType == "review") ? tag = reviewTag : tag = draftTag;
         $( "h1" ).first().after(tag);
      }
   }
}

(function(document, history, location) {
    var HISTORY_SUPPORT = !!(history && history.pushState);

    var anchorScrolls = {
        ANCHOR_REGEX: /^#[^ ]+$/,
        OFFSET_HEIGHT_PX: 60,

        /**
         * Establish events, and fix initial scroll position if a hash is provided.
         */
        init: function() {
            this.scrollIfAnchor(location.hash);
            $('body').on('click', 'a', $.proxy(this, 'delegateAnchors'));
        },

        /**
         * Return the offset amount to deduct from the normal scroll position.
         * Modify as appropriate to allow for dynamic calculations
         */
        getFixedOffset: function() {
            return this.OFFSET_HEIGHT_PX;
        },

        /**
         * If the provided href is an anchor which resolves to an element on the
         * page, scroll to it.
         * @param  {String} href
         * @return {Boolean} - Was the href an anchor.
         */
        scrollIfAnchor: function(href, pushToHistory) {
            var match, anchorOffset;

            if(!this.ANCHOR_REGEX.test(href)) {
                return false;
            }

            match = document.getElementById(href.slice(1));

            if(match) {
                anchorOffset = $(match).offset().top - this.getFixedOffset();
                $('html, body').animate({ scrollTop: anchorOffset});

                // Add the state to history as-per normal anchor links
                if(HISTORY_SUPPORT && pushToHistory) {
                    history.pushState({}, document.title, location.pathname + href);
                }
            }

            return !!match;
        },

        /**
         * If the click event's target was an anchor, fix the scroll position.
         */
        delegateAnchors: function(e) {
            var elem = e.target;

            if(this.scrollIfAnchor(elem.getAttribute('href'), true)) {
                e.preventDefault();
            }
        }
    };

    $(document).ready($.proxy(anchorScrolls, 'init'));
})(window.document, window.history, window.location);
<|endoftext|>


<commit_before>function onRun(context) {

var lines = []

function write(text) {
  lines.push(text)
}

var sketch = context.api()
var document = sketch.selectedDocument
var selection = document.selectedLayers
var labels = []
var shapes = []

selection.iterate(function(item) {
    if (item.isArtboard) {
        item.iterate(function(element) {
            if (element.isText) {
                labels.push(element)
            } else if (element.isShape) {
                shapes.push(element)
                //log(element.name)
                //log(element.sketchObject.style().fills()[0].color())
                //log(element.frame)
            }
        })
    }
});

/// GENERATED STEVIA CODE

write(uikitHeader())
labels.map(function(l) {
    write("    let " + sanitizeName(l.name) + " = UILabel()")
});
shapes.map(function(v) {
    write("    let " + sanitizeName(v.name) + " = UIView()")
});
write("")

write("    convenience init() {")
write("        self.init(frame:CGRect.zero)")
write("")
// View Hierarchy
write("        // View Hierarchy")

labels.map(function(l) {
  write("        " + sanitizeName(l.name) + ".translatesAutoresizingMaskIntoConstraints = false")
});
shapes.map(function(v) {
  write("        " + sanitizeName(v.name) + ".translatesAutoresizingMaskIntoConstraints = false")
});
  write("")
labels.map(function(l) {
  write("        addSubview(" + sanitizeName(l.name) + ")")
});
shapes.map(function(v) {
  write("        addSubview(" + sanitizeName(v.name) + ")")
});

write("")
// Layout
write("        // Layout")
labels.map(function(l) {

// Absolute positioning
write("        " + sanitizeName(l.name) + ".top(" + l.frame.y + ")")
write("            .left(" + l.frame.x + ")")
write("            .right(" +  (375-(l.frame.x + l.frame.width)) + ")")

    //if (l.alignment == "center")  {
       // log("        " + lowerCaseFirstLetter(l.name) + ".centerInContainer()")
    //}
});

  shapes.map(function(v) {
      var elementName = sanitizeName(v.name)

      // Top
      write("        addConstraint(")
      write("            NSLayoutConstraint(item: " + elementName + ",")
      write("                               attribute: .top,")
      write("                               relatedBy: .equal,")
      write("                               toItem: self,")
      write("                               attribute: .top,")
      write("                               multiplier: 1,")
      write("                               constant: " + v.frame.y + ")")
      write("         )")

      // Left
      write("        addConstraint(")
      write("            NSLayoutConstraint(item: " + elementName + ",")
      write("                               attribute: .left,")
      write("                               relatedBy: .equal,")
      write("                               toItem: self,")
      write("                               attribute: .left,")
      write("                               multiplier: 1,")
      write("                               constant: " + v.frame.x + ")")
      write("         )")

      // Width
      write("        addConstraint(")
      write("            NSLayoutConstraint(item: " + elementName + ",")
      write("                               attribute: .width,")
      write("                               relatedBy: .equal,")
      write("                               toItem: nil,")
      write("                               attribute: .notAnAttribute,")
      write("                               multiplier: 1,")
      write("                               constant: " + v.frame.width + ")")
      write("         )")

      // Height
      write("        addConstraint(")
      write("            NSLayoutConstraint(item: " + elementName + ",")
      write("                               attribute: .height,")
      write("                               relatedBy: .equal,")
      write("                               toItem: nil,")
      write("                               attribute: .notAnAttribute,")
      write("                               multiplier: 1,")
      write("                               constant: " + v.frame.height + ")")
      write("         )")
    //if (l.alignment == "center")  {
       // log("        " + lowerCaseFirstLetter(l.name) + ".centerInContainer()")
    //}
});
write("")
// Style
write("        // Style")
write("        backgroundColor = .white")
labels.map(function(l) {

  var elementName = sanitizeName(l.name)

var red = l.sketchObject.textColor().red()
var green = l.sketchObject.textColor().green()
var blue = l.sketchObject.textColor().blue()
var alpha = l.sketchObject.textColor().alpha()
    write("        " + elementName + '.font = UIFont(name: "' + l.sketchObject.fontPostscriptName() + '", size:' + l.sketchObject.fontSize() + ")" )
    write("        " + elementName + ".textColor =  UIColor(red: " + red + ", green: " + green + ", blue: " + blue + ", alpha: " + alpha + ")")
    if (l.alignment == "center") {
        write("        " + elementName + ".textAlignment = .center")
    }
});
shapes.map(function(v) {
var elementName = sanitizeName(v.name)
var color = v.sketchObject.style().fills()[0].color()
var red = color.red()
var green = color.green()
var blue = color.blue()
var alpha = color.alpha()
    write("        " + elementName + ".backgroundColor =  UIColor(red: " + red + ", green: " + green + ", blue: " + blue + ", alpha: " + alpha + ")")
});
// Content
write("")
write("        // Content")
labels.map(function(l) {
    write("        " + sanitizeName(l.name) + '.text = "' + l.text + '"')
});

write("    }")
write("}")

function lowerCaseFirstLetter(string) {
    return string.charAt(0).toLowerCase() + string.slice(1);
}

var fullText = ""
lines.forEach(function(line) {
    fullText += line + "\n"
})

log(fullText)

copyText(fullText)

function copyText(text) {
  var pasteBoard = [NSPasteboard generalPasteboard];
  [pasteBoard declareTypes:[NSArray arrayWithObject:NSPasteboardTypeString] owner:nil];
  [pasteBoard setString:text forType:NSPasteboardTypeString];
}

function sanitizeName(str) {
   return lowerCaseFirstLetter(removeSpaces(str))
}

function removeSpaces(str) {
   return str.replace(/\s+/g, '');
}

function lowerCaseFirstLetter(str) {
   return str.charAt(0).toLowerCase() + str.slice(1)
}

};

// Private functions

function uikitHeader() {
  return "\n"
  + "import UIKit" + "\n"
    + "\n"
    + "\n"
  + "class UIKitView: UIView {"
  + "\n"
}
<commit_msg>refactors view hierarchy<commit_after>function onRun(context) {

var lines = []

function write(text) {
  lines.push(text)
}

var sketch = context.api()
var document = sketch.selectedDocument
var selection = document.selectedLayers
var labels = []
var shapes = []
var allElements = []

selection.iterate(function(item) {
    if (item.isArtboard) {
        item.iterate(function(element) {
            if (element.isText) {
                labels.push(element)
            } else if (element.isShape) {
                shapes.push(element)
                //log(element.name)
                //log(element.sketchObject.style().fills()[0].color())
                //log(element.frame)
            }
            allElements.push(element)
        })
    }
});

/// GENERATED STEVIA CODE

write(uikitHeader())
labels.map(function(l) {
    write("    let " + sanitizeName(l.name) + " = UILabel()")
});
shapes.map(function(v) {
    write("    let " + sanitizeName(v.name) + " = UIView()")
});
write("")

write(uiviewInit())

// View Hierarchy
write(uikitViewHierarchy(allElements))

write("")
// Layout
write("        // Layout")
labels.map(function(l) {

// Absolute positioning
write("        " + sanitizeName(l.name) + ".top(" + l.frame.y + ")")
write("            .left(" + l.frame.x + ")")
write("            .right(" +  (375-(l.frame.x + l.frame.width)) + ")")

    //if (l.alignment == "center")  {
       // log("        " + lowerCaseFirstLetter(l.name) + ".centerInContainer()")
    //}
});

  shapes.map(function(v) {
      var elementName = sanitizeName(v.name)

      // Top
      write("        addConstraint(")
      write("            NSLayoutConstraint(item: " + elementName + ",")
      write("                               attribute: .top,")
      write("                               relatedBy: .equal,")
      write("                               toItem: self,")
      write("                               attribute: .top,")
      write("                               multiplier: 1,")
      write("                               constant: " + v.frame.y + ")")
      write("         )")

      // Left
      write("        addConstraint(")
      write("            NSLayoutConstraint(item: " + elementName + ",")
      write("                               attribute: .left,")
      write("                               relatedBy: .equal,")
      write("                               toItem: self,")
      write("                               attribute: .left,")
      write("                               multiplier: 1,")
      write("                               constant: " + v.frame.x + ")")
      write("         )")

      // Width
      write("        addConstraint(")
      write("            NSLayoutConstraint(item: " + elementName + ",")
      write("                               attribute: .width,")
      write("                               relatedBy: .equal,")
      write("                               toItem: nil,")
      write("                               attribute: .notAnAttribute,")
      write("                               multiplier: 1,")
      write("                               constant: " + v.frame.width + ")")
      write("         )")

      // Height
      write("        addConstraint(")
      write("            NSLayoutConstraint(item: " + elementName + ",")
      write("                               attribute: .height,")
      write("                               relatedBy: .equal,")
      write("                               toItem: nil,")
      write("                               attribute: .notAnAttribute,")
      write("                               multiplier: 1,")
      write("                               constant: " + v.frame.height + ")")
      write("         )")
    //if (l.alignment == "center")  {
       // log("        " + lowerCaseFirstLetter(l.name) + ".centerInContainer()")
    //}
});
write("")
// Style
write("        // Style")
write("        backgroundColor = .white")
labels.map(function(l) {

  var elementName = sanitizeName(l.name)

var red = l.sketchObject.textColor().red()
var green = l.sketchObject.textColor().green()
var blue = l.sketchObject.textColor().blue()
var alpha = l.sketchObject.textColor().alpha()
    write("        " + elementName + '.font = UIFont(name: "' + l.sketchObject.fontPostscriptName() + '", size:' + l.sketchObject.fontSize() + ")" )
    write("        " + elementName + ".textColor =  UIColor(red: " + red + ", green: " + green + ", blue: " + blue + ", alpha: " + alpha + ")")
    if (l.alignment == "center") {
        write("        " + elementName + ".textAlignment = .center")
    }
});
shapes.map(function(v) {
var elementName = sanitizeName(v.name)
var color = v.sketchObject.style().fills()[0].color()
var red = color.red()
var green = color.green()
var blue = color.blue()
var alpha = color.alpha()
    write("        " + elementName + ".backgroundColor =  UIColor(red: " + red + ", green: " + green + ", blue: " + blue + ", alpha: " + alpha + ")")
});
// Content
write("")
write("        // Content")
labels.map(function(l) {
    write("        " + sanitizeName(l.name) + '.text = "' + l.text + '"')
});

write("    }")
write("}")

function lowerCaseFirstLetter(string) {
    return string.charAt(0).toLowerCase() + string.slice(1);
}

var fullText = ""
lines.forEach(function(line) {
    fullText += line + "\n"
})

log(fullText)

copyText(fullText)

function copyText(text) {
  var pasteBoard = [NSPasteboard generalPasteboard];
  [pasteBoard declareTypes:[NSArray arrayWithObject:NSPasteboardTypeString] owner:nil];
  [pasteBoard setString:text forType:NSPasteboardTypeString];
}

function sanitizeName(str) {
   return lowerCaseFirstLetter(removeSpaces(str))
}

function removeSpaces(str) {
   return str.replace(/\s+/g, '');
}

function lowerCaseFirstLetter(str) {
   return str.charAt(0).toLowerCase() + str.slice(1)
}

};

// Private functions

function uikitHeader() {
  return "\n"
  + "import UIKit" + "\n"
    + "\n"
    + "\n"
  + "class UIKitView: UIView {"
  + "\n"
}

function uiviewInit() {
  return "    convenience init() {" + "\n"
  +      "        self.init(frame:CGRect.zero)" + "\n"
  + "\n"
}

function uikitViewHierarchy(elements) {
  var s = "\n"
  s += "        // View Hierarchy"
  s +=  "\n"
  elements.map(function(e) {
    s += "        " + sanitizeName(e.name) + ".translatesAutoresizingMaskIntoConstraints = false" + "\n"
  });
  elements.map(function(e) {
    s += "        addSubview(" + sanitizeName(e.name) + ")" + "\n"
  });

  return s
}
<|endoftext|>


<commit_before>const { matchWords } = require('~/assets/javascripts/lib/helpers')

describe('#matchWords', () => {
  const data = 'Aberdeen city -'

  it('should match one letter', () => {
    expect(matchWords(data, 'b')).to.equal(true)
  })

  it('should match one word', () => {
    expect(matchWords(data, 'Aberdeen')).to.equal(true)
  })

  it('should match two words', () => {
    expect(matchWords(data, 'Aberdeen city')).to.equal(true)
  })

  it('should match lowercase', () => {
    expect(matchWords(data, 'aberdeen')).to.equal(true)
  })

  it('should match uppercase', () => {
    expect(matchWords(data, 'ABERDEEN')).to.equal(true)
  })

  it('should match uppercase and lowercase', () => {
    expect(matchWords(data, 'AbErDeEn cIty')).to.equal(true)
  })

  it('should match words in reverse order', () => {
    expect(matchWords(data, 'city Aberdeen')).to.equal(true)
  })

  it('should match words with a hyphen', () => {
    expect(matchWords(data, '-')).to.equal(true)
  })

  it('should return false if not found', () => {
    expect(matchWords(data, 'z')).to.equal(false)
  })
})
<commit_msg>Add test around new checkDateFormat function<commit_after>const { matchWords, checkDateFormat } = require('~/assets/javascripts/lib/helpers')

describe('#matchWords', () => {
  const data = 'Aberdeen city -'

  it('should match one letter', () => {
    expect(matchWords(data, 'b')).to.equal(true)
  })

  it('should match one word', () => {
    expect(matchWords(data, 'Aberdeen')).to.equal(true)
  })

  it('should match two words', () => {
    expect(matchWords(data, 'Aberdeen city')).to.equal(true)
  })

  it('should match lowercase', () => {
    expect(matchWords(data, 'aberdeen')).to.equal(true)
  })

  it('should match uppercase', () => {
    expect(matchWords(data, 'ABERDEEN')).to.equal(true)
  })

  it('should match uppercase and lowercase', () => {
    expect(matchWords(data, 'AbErDeEn cIty')).to.equal(true)
  })

  it('should match words in reverse order', () => {
    expect(matchWords(data, 'city Aberdeen')).to.equal(true)
  })

  it('should match words with a hyphen', () => {
    expect(matchWords(data, '-')).to.equal(true)
  })

  it('should return false if not found', () => {
    expect(matchWords(data, 'z')).to.equal(false)
  })
})

describe('#checkDateFormat', () => {
  context('when the date matches the required date format', () => {
    it('should return true', () => {
      expect(checkDateFormat('01/01/2019')).to.equal(true)
    })
  })

  context('when the date does not match the required date format', () => {
    it('should return false', () => {
      expect(checkDateFormat('01')).to.equal(false)
      expect(checkDateFormat('01/')).to.equal(false)
      expect(checkDateFormat('01/01')).to.equal(false)
      expect(checkDateFormat('01/01/20')).to.equal(false)
      expect(checkDateFormat('aa/aa/aa')).to.equal(false)
      expect(checkDateFormat('2019/01/01')).to.equal(false)
    })
  })
})
<|endoftext|>


<commit_before>/* eslint-disable func-names, prefer-arrow-callback */

const Flint = require('../index.js');
const request = require('supertest');
const expect = require('chai').expect;
const mongoose = require('mongoose');

describe('server', function () {
  this.timeout(4000);
  let server;

  before('Creates a server', async function () {
    const flintServer = new Flint();
    server = await flintServer.startServer();
    return server;
  });

  describe('Monitoring', function () {
    it('is listening', function () {
      expect(server.listening).to.be.true;
    });
  });

  describe('GET /ping', function () {
    it('returns a 200 response', function (done) {
      request(server).get('/ping').expect(200, 'PONG', done);
    });
  });

  after('Closes the server', function (done) {
    mongoose.disconnect();
    server.shutdown(done);
  });
});
<commit_msg>Fix linter<commit_after>/* eslint-disable func-names, prefer-arrow-callback */

const Flint = require('../index.js');
const request = require('supertest');
const expect = require('chai').expect;
const mongoose = require('mongoose');

describe('server', function () {
  this.timeout(4000);
  let server;

  before('Creates a server', async function () {
    const flintServer = new Flint();
    server = await flintServer.startServer();
    return server;
  });

  describe('Monitoring', function () {
    it('is listening', function () {
      return expect(server.listening).to.be.true;
    });
  });

  describe('GET /ping', function () {
    it('returns a 200 response', function (done) {
      request(server).get('/ping').expect(200, 'PONG', done);
    });
  });

  after('Closes the server', function (done) {
    mongoose.disconnect();
    server.shutdown(done);
  });
});
<|endoftext|>


<commit_before>'use strict';

var Reflux = require('reflux');
var _ = require('lodash');

var ImageModel = require('./ImageModel');
var LayerActions = require('actions/LayerActions');
var ObjectActions = require('actions/ObjectActions');

var ImageStore = Reflux.createStore({
  /**
   * initial setup
   */
  init: function() {
      this.svgImage = ImageModel;

      // Register actions
      this.listenTo(LayerActions.changeLayerVisibility, this.onChangeLayerVisibility);
      this.listenTo(LayerActions.selectLayer, this.onSelectLayer);
      this.listenTo(LayerActions.preSelectLayer, this.onPreSelectLayer);
      this.listenTo(LayerActions.unPreSelectLayer, this.onUnPreSelectLayer);
      this.listenTo(LayerActions.deleteSelectedLayer, this.onDeleteSelectedLayer);
      this.listenTo(LayerActions.addNewLayer, this.onAddNewLayer);
      this.listenTo(LayerActions.moveUpSelectedLayer, this.onMoveUpSelectedLayer);
      this.listenTo(LayerActions.moveDownSelectedLayer, this.onMoveDownSelectedLayer);
      this.listenTo(LayerActions.createMaskFromSelectedLayer, this.onCreateMaskFromSelectedLayer);
      this.listenTo(LayerActions.applyMaskToLayer, this.onApplyMaskToLayer);

      this.listenTo(ObjectActions.addNewObjectToLayer, this.onAddNewObjectToLayer);
      this.listenTo(ObjectActions.updateObjectAttributes, this.onUpdateObjectAttributes);
      this.listenTo(ObjectActions.moveObject, this.onMoveObject);
      this.listenTo(ObjectActions.scaleObject, this.onScaleObject);
      this.listenTo(ObjectActions.rotateObject, this.onRotateObject);
      this.listenTo(ObjectActions.selectObjectInSelectedLayer, this.onSelectObjectInSelectedLayer);
  },

  /**
   * get svg image model
   */
  getImage: function() {
    return this.svgImage;
  },

  /**
   * get selected svg object
   */
  getSelectedObject: function() {
    return this.selectedSvgObject;
  },

  /**
   * change layer visible show/hide
   * @param  {string} layerId for manipulation
   */
  onChangeLayerVisibility: function(layerId) {
    // find layer and invert visible property
    var layer = _.find(this.svgImage.svgLayers, {name: layerId});
    if (!layer) {
      // no any layer found
      return;
    }

    if (layer.visible) {
      layer.visible = false;
    } else {
      layer.visible = true;
    }

    this.svgImage.selectedObject = null;

    // Pass on to listeners
    this.trigger(this.svgImage);
  },

  /**
   * select layer (for editing)
   * @param  {string} layerId for manipulation
   */
  onSelectLayer: function(layerId) {
    // find layer and select it
    var layer = _.find(this.svgImage.svgLayers, {name: layerId});
    if (!layer) {
      // no any layer found
      return;
    }

    // unselect previous layer
    var previousSelectedlayer = _.find(this.svgImage.svgLayers, {selected: true});
    if (previousSelectedlayer) {
      previousSelectedlayer.selected = false;
    }

    layer.selected = true;

    // remove object selection (due to in could be stay on other layer)
    this.svgImage.selectedObject = null;

    // Pass on to listeners
    this.trigger(this.svgImage);
  },

  /**
   * pre-select (i.e. when user do "mouse over" on layer name)
   * it is used for highlight objects which belong to level
   * @param  {string} layerId for manipulation
   */
  onPreSelectLayer: function(layerId) {
    // find layer and pre-select it
    var layer = _.find(this.svgImage.svgLayers, {name: layerId});
    if (!layer) {
      // no any layer found
      return;
    }

    // un-pre-select previous pre-selected layer
    var previousSelectedlayer = _.find(this.svgImage.svgLayers, {selected: true});
    if (previousSelectedlayer) {
      previousSelectedlayer.preSelected = false;
    }

    layer.preSelected = true;

    // Pass on to listeners
    this.trigger(this.svgImage);
  },

  /**
   * remove pre-selection
   * @param  {string} layerId for manipulation
   */
  onUnPreSelectLayer: function(layerId) {
    // find layer and un-pre-select it
    var layer = _.find(this.svgImage.svgLayers, {name: layerId});
    if (!layer) {
      // no any layer found
      return;
    }

    layer.preSelected = false;

    // Pass on to listeners
    this.trigger(this.svgImage);
  },

  /**
   * remove selected layer
   */
  onDeleteSelectedLayer: function() {
    // find layer
    var layer = _.find(this.svgImage.svgLayers, {selected: true});
    if (!layer) {
      // no any layer found
      return;
    }

    this.svgImage.svgLayers = _.filter(this.svgImage.svgLayers, function(layerIt) {
      return (layerIt.selected !== true);
    });

    // Pass on to listeners
    this.trigger(this.svgImage);
  },

  /**
   * add new layer
   */
  onAddNewLayer: function() {
    // create new object with name
    var newLayerName = 'Layer' + (this.svgImage.svgLayers.length + 1);
    var newLayer = ImageModel.emptyLayer(newLayerName);

    this.svgImage.svgLayers.push(newLayer);

    this.trigger(this.svgImage);
  },

  /**
   * move layer up (exchange with previous level)
   */
  onMoveUpSelectedLayer: function() {
    // find layer
    var layerIndex = _.findIndex(this.svgImage.svgLayers, {selected: true});
    if (layerIndex <= 0) {
      return;
    }

    if (this.svgImage.svgLayers.length < 2) {
      return;
    }
    // exchange
    var temp = this.svgImage.svgLayers[layerIndex];
    this.svgImage.svgLayers[layerIndex] = this.svgImage.svgLayers[layerIndex - 1];
    this.svgImage.svgLayers[layerIndex - 1] = temp;

    this.trigger(this.svgImage);
  },

  /**
   * move layer down (exchange with previous level)
   */
  onMoveDownSelectedLayer: function() {
    // find layer
    var layerIndex = _.findIndex(this.svgImage.svgLayers, {selected: true});
    if ((layerIndex === -1) ||
        (layerIndex === this.svgImage.svgLayers.length - 1)) {
      return;
    }

    if (this.svgImage.svgLayers.length < 2) {
      return;
    }

    // exchange
    var temp = this.svgImage.svgLayers[layerIndex];
    this.svgImage.svgLayers[layerIndex] = this.svgImage.svgLayers[layerIndex + 1];
    this.svgImage.svgLayers[layerIndex + 1] = temp;

    this.trigger(this.svgImage);
  },

  /**
   * create mask from selected layer
   */
  onCreateMaskFromSelectedLayer: function() {
    // find layer
    var layer = _.find(this.svgImage.svgLayers, {selected: true});
    if (!layer) {
      // no any layer found
      return;
    }

    // create mask from layer
    var mask = ImageModel.createMask(layer);

    // push masks
    this.svgImage.svgLayers.push(mask);

    this.trigger(this.svgImage);
  },

  /**
   * apply mask to specified layer
   */
  onApplyMaskToLayer: function(layerId) {
    // find layer
    var mask = _.find(this.svgImage.svgLayers, {selected: true, mask: true});
    if (!mask) {
      // no any layer found
      return;
    }

    // find layer
    var layer = _.find(this.svgImage.svgLayers, {name: layerId});
    if (!layer) {
      // no any layer found
      return;
    }

    layer.maskAdded = mask.name;

    // push masks
    this.trigger(this.svgImage);
  },

  /**
   * add new object to selected layer
   * @param  {string} objectType new object type (tect/rect)
   */
  onAddNewObjectToLayer: function(objectType) {
    // find selected layer
    var selectedlayer = _.find(this.svgImage.svgLayers, {selected: true});
    if (!selectedlayer) {
      // can't add anything
      return;
    }
    // create new object
    var svgObject = ImageModel.emptyObjectOfType(objectType);

    // add to layer
    selectedlayer.svgObjects.push(svgObject);

    // fire update notification
    this.trigger(this.svgImage);
  },

  /**
   * update some non-common attribute like text for text object
   * @param  {object} svgObject object
   * @param  {Array} attrs     list of attributes
   */
  onUpdateObjectAttributes: function(svgObject, attrs) {
    for (var k in attrs) {
      svgObject[k] = attrs[k];
    }

    // fire update notification
    this.trigger(this.svgImage);
  },

  /**
   * move object to new position
   * @param  {object} svgObject object
   */
  onMoveObject: function(svgObject, newPosition) {
    svgObject.position.x = newPosition.x;
    svgObject.position.y = newPosition.y;

    // fire update notification
    this.trigger(this.svgImage);
  },

  /**
   * re-scale object (set new scale)
   * @param  {object} svgObject object
   */
  onScaleObject: function(svgObject, newPosition) {
    svgObject.position.scale = newPosition.scale;

    // fire update notification
    this.trigger(this.svgImage);
  },

  /**
   * rotate object to new angle
   * @param  {object} svgObject object
   */
  onRotateObject: function(svgObject, newPosition) {
    svgObject.position.r = newPosition.r;

    // fire update notification
    this.trigger(this.svgImage);
  },

  /**
   * show selection for specific object which belongs to selected layer
   * @param  {string} layerId - object's layer ID
   * @param  {string} objectID - object ID (in layer)
   */
  onSelectObjectInSelectedLayer: function(layerID, objectID) {
    // find selected layer
    var selectedlayer = _.find(this.svgImage.svgLayers, {selected: true});
    if (!selectedlayer) {
      return;
    }

    if (selectedlayer.name !== layerID) {
      // can't select object on the other layer
      return;
    }

    this.svgImage.selectedObject = selectedlayer.svgObjects[objectID];

    // fire update notification
    this.trigger(this.svgImage);
  }
});

module.exports = ImageStore;
<commit_msg>remove mask's reverences<commit_after>'use strict';

var Reflux = require('reflux');
var _ = require('lodash');

var ImageModel = require('./ImageModel');
var LayerActions = require('actions/LayerActions');
var ObjectActions = require('actions/ObjectActions');

var ImageStore = Reflux.createStore({
  /**
   * initial setup
   */
  init: function() {
      this.svgImage = ImageModel;

      // Register actions
      this.listenTo(LayerActions.changeLayerVisibility, this.onChangeLayerVisibility);
      this.listenTo(LayerActions.selectLayer, this.onSelectLayer);
      this.listenTo(LayerActions.preSelectLayer, this.onPreSelectLayer);
      this.listenTo(LayerActions.unPreSelectLayer, this.onUnPreSelectLayer);
      this.listenTo(LayerActions.deleteSelectedLayer, this.onDeleteSelectedLayer);
      this.listenTo(LayerActions.addNewLayer, this.onAddNewLayer);
      this.listenTo(LayerActions.moveUpSelectedLayer, this.onMoveUpSelectedLayer);
      this.listenTo(LayerActions.moveDownSelectedLayer, this.onMoveDownSelectedLayer);
      this.listenTo(LayerActions.createMaskFromSelectedLayer, this.onCreateMaskFromSelectedLayer);
      this.listenTo(LayerActions.applyMaskToLayer, this.onApplyMaskToLayer);

      this.listenTo(ObjectActions.addNewObjectToLayer, this.onAddNewObjectToLayer);
      this.listenTo(ObjectActions.updateObjectAttributes, this.onUpdateObjectAttributes);
      this.listenTo(ObjectActions.moveObject, this.onMoveObject);
      this.listenTo(ObjectActions.scaleObject, this.onScaleObject);
      this.listenTo(ObjectActions.rotateObject, this.onRotateObject);
      this.listenTo(ObjectActions.selectObjectInSelectedLayer, this.onSelectObjectInSelectedLayer);
  },

  /**
   * get svg image model
   */
  getImage: function() {
    return this.svgImage;
  },

  /**
   * get selected svg object
   */
  getSelectedObject: function() {
    return this.selectedSvgObject;
  },

  /**
   * change layer visible show/hide
   * @param  {string} layerId for manipulation
   */
  onChangeLayerVisibility: function(layerId) {
    // find layer and invert visible property
    var layer = _.find(this.svgImage.svgLayers, {name: layerId});
    if (!layer) {
      // no any layer found
      return;
    }

    if (layer.visible) {
      layer.visible = false;
    } else {
      layer.visible = true;
    }

    this.svgImage.selectedObject = null;

    // Pass on to listeners
    this.trigger(this.svgImage);
  },

  /**
   * select layer (for editing)
   * @param  {string} layerId for manipulation
   */
  onSelectLayer: function(layerId) {
    // find layer and select it
    var layer = _.find(this.svgImage.svgLayers, {name: layerId});
    if (!layer) {
      // no any layer found
      return;
    }

    // unselect previous layer
    var previousSelectedlayer = _.find(this.svgImage.svgLayers, {selected: true});
    if (previousSelectedlayer) {
      previousSelectedlayer.selected = false;
    }

    layer.selected = true;

    // remove object selection (due to in could be stay on other layer)
    this.svgImage.selectedObject = null;

    // Pass on to listeners
    this.trigger(this.svgImage);
  },

  /**
   * pre-select (i.e. when user do "mouse over" on layer name)
   * it is used for highlight objects which belong to level
   * @param  {string} layerId for manipulation
   */
  onPreSelectLayer: function(layerId) {
    // find layer and pre-select it
    var layer = _.find(this.svgImage.svgLayers, {name: layerId});
    if (!layer) {
      // no any layer found
      return;
    }

    // un-pre-select previous pre-selected layer
    var previousSelectedlayer = _.find(this.svgImage.svgLayers, {selected: true});
    if (previousSelectedlayer) {
      previousSelectedlayer.preSelected = false;
    }

    layer.preSelected = true;

    // Pass on to listeners
    this.trigger(this.svgImage);
  },

  /**
   * remove pre-selection
   * @param  {string} layerId for manipulation
   */
  onUnPreSelectLayer: function(layerId) {
    // find layer and un-pre-select it
    var layer = _.find(this.svgImage.svgLayers, {name: layerId});
    if (!layer) {
      // no any layer found
      return;
    }

    layer.preSelected = false;

    // Pass on to listeners
    this.trigger(this.svgImage);
  },

  /**
   * remove selected layer
   */
  onDeleteSelectedLayer: function() {
    // find layer
    var layer = _.find(this.svgImage.svgLayers, {selected: true});
    if (!layer) {
      // no any layer found
      return;
    }

    this.svgImage.svgLayers = _.filter(this.svgImage.svgLayers, function(layerIt) {
      return (layerIt.selected !== true);
    });

    // if it is mask we should remove references from other layers
    if (layer.mask) {
      var refs = _.filter(this.svgImage.svgLayers, function(layerIt) {
        return (layerIt.maskAdded === layer.name);
      });

      _.forEach(refs, function(layerIt) {
        delete layerIt.maskAdded;
      });
    }

    // Pass on to listeners
    this.trigger(this.svgImage);
  },

  /**
   * add new layer
   */
  onAddNewLayer: function() {
    // create new object with name
    var newLayerName = 'Layer' + (this.svgImage.svgLayers.length + 1);
    var newLayer = ImageModel.emptyLayer(newLayerName);

    this.svgImage.svgLayers.push(newLayer);

    this.trigger(this.svgImage);
  },

  /**
   * move layer up (exchange with previous level)
   */
  onMoveUpSelectedLayer: function() {
    // find layer
    var layerIndex = _.findIndex(this.svgImage.svgLayers, {selected: true});
    if (layerIndex <= 0) {
      return;
    }

    if (this.svgImage.svgLayers.length < 2) {
      return;
    }
    // exchange
    var temp = this.svgImage.svgLayers[layerIndex];
    this.svgImage.svgLayers[layerIndex] = this.svgImage.svgLayers[layerIndex - 1];
    this.svgImage.svgLayers[layerIndex - 1] = temp;

    this.trigger(this.svgImage);
  },

  /**
   * move layer down (exchange with previous level)
   */
  onMoveDownSelectedLayer: function() {
    // find layer
    var layerIndex = _.findIndex(this.svgImage.svgLayers, {selected: true});
    if ((layerIndex === -1) ||
        (layerIndex === this.svgImage.svgLayers.length - 1)) {
      return;
    }

    if (this.svgImage.svgLayers.length < 2) {
      return;
    }

    // exchange
    var temp = this.svgImage.svgLayers[layerIndex];
    this.svgImage.svgLayers[layerIndex] = this.svgImage.svgLayers[layerIndex + 1];
    this.svgImage.svgLayers[layerIndex + 1] = temp;

    this.trigger(this.svgImage);
  },

  /**
   * create mask from selected layer
   */
  onCreateMaskFromSelectedLayer: function() {
    // find layer
    var layer = _.find(this.svgImage.svgLayers, {selected: true});
    if (!layer) {
      // no any layer found
      return;
    }

    // create mask from layer
    var mask = ImageModel.createMask(layer);

    // push masks
    this.svgImage.svgLayers.push(mask);

    this.trigger(this.svgImage);
  },

  /**
   * apply mask to specified layer
   */
  onApplyMaskToLayer: function(layerId) {
    // find layer
    var mask = _.find(this.svgImage.svgLayers, {selected: true, mask: true});
    if (!mask) {
      // no any layer found
      return;
    }

    // find layer
    var layer = _.find(this.svgImage.svgLayers, {name: layerId});
    if (!layer) {
      // no any layer found
      return;
    }

    layer.maskAdded = mask.name;

    // push masks
    this.trigger(this.svgImage);
  },

  /**
   * add new object to selected layer
   * @param  {string} objectType new object type (tect/rect)
   */
  onAddNewObjectToLayer: function(objectType) {
    // find selected layer
    var selectedlayer = _.find(this.svgImage.svgLayers, {selected: true});
    if (!selectedlayer) {
      // can't add anything
      return;
    }
    // create new object
    var svgObject = ImageModel.emptyObjectOfType(objectType);

    // add to layer
    selectedlayer.svgObjects.push(svgObject);

    // fire update notification
    this.trigger(this.svgImage);
  },

  /**
   * update some non-common attribute like text for text object
   * @param  {object} svgObject object
   * @param  {Array} attrs     list of attributes
   */
  onUpdateObjectAttributes: function(svgObject, attrs) {
    for (var k in attrs) {
      svgObject[k] = attrs[k];
    }

    // fire update notification
    this.trigger(this.svgImage);
  },

  /**
   * move object to new position
   * @param  {object} svgObject object
   */
  onMoveObject: function(svgObject, newPosition) {
    svgObject.position.x = newPosition.x;
    svgObject.position.y = newPosition.y;

    // fire update notification
    this.trigger(this.svgImage);
  },

  /**
   * re-scale object (set new scale)
   * @param  {object} svgObject object
   */
  onScaleObject: function(svgObject, newPosition) {
    svgObject.position.scale = newPosition.scale;

    // fire update notification
    this.trigger(this.svgImage);
  },

  /**
   * rotate object to new angle
   * @param  {object} svgObject object
   */
  onRotateObject: function(svgObject, newPosition) {
    svgObject.position.r = newPosition.r;

    // fire update notification
    this.trigger(this.svgImage);
  },

  /**
   * show selection for specific object which belongs to selected layer
   * @param  {string} layerId - object's layer ID
   * @param  {string} objectID - object ID (in layer)
   */
  onSelectObjectInSelectedLayer: function(layerID, objectID) {
    // find selected layer
    var selectedlayer = _.find(this.svgImage.svgLayers, {selected: true});
    if (!selectedlayer) {
      return;
    }

    if (selectedlayer.name !== layerID) {
      // can't select object on the other layer
      return;
    }

    this.svgImage.selectedObject = selectedlayer.svgObjects[objectID];

    // fire update notification
    this.trigger(this.svgImage);
  }
});

module.exports = ImageStore;
<|endoftext|>


<commit_before>define('app/controllers/machine_shell', ['app/models/command', 'ember'],
    /**
     * Machine Shell Controller
     *
     * @returns Class
     */
    function (Command) {
        return Ember.Object.extend(Ember.Evented, {

            /**
             *  Properties
             */

            command: null,
            machine: null,
            commandHistoryIndex: -1,

            /**
             *
             *  Methods
             *
             */

            open: function (machine) {
                this._clear();
                this.set('machine', machine);

                // Get the first ipv4 public ip to connect to
                var host = '';
                for (var i=0;i<machine.public_ips.length;i++){
                    if (machine.public_ips[i].search(':') == -1){
                        host = machine.public_ips[i];
                    }

                }
                if (host == '')
                    return false;

                // Open shell socket, give it a few shots
                var sock = undefined, retry = 0;
                while (sock == undefined) {
                    if (retry) {
                        warn('retry ' + retry);
                    }

                    sock = io.connect('/shell');
                    retry += 1;
                    if (retry > 5){
                        warn('failed to connect to shell socket after ' + retry + ' retries');
                        return false;
                    }
                }

                Mist.set('shell', sock);

                $('.ui-footer').hide(500);
                $('#machine-shell-popup').on('popupafteropen',
                    function(){
                        $('#machine-shell-popup').off('blur');
                        $(document).off('focusin');
                    }
                ).popup( "option", "dismissible", false ).popup('open');

                $(window).on('resize', function(){
                    var w, h, fontSize=18, wc, hc;

                    while (true){
                        wc = hc = false;
                        $('.fontSizeTest').css('font-size', fontSize + 'px');

                        w = $('.fontSizeTest').width() * 80;

                        if (w > window.innerWidth - 46){
                            wc = true;
                            warn('width constrained');
                        }

                        h = $('.fontSizeTest').height() * 24;

                        if (h > window.innerHeight-virtualKeyboardHeight() - 135){ //42.4 + 16 + 8 + 1 + 11.2 + 20 + 11.2 + 1 + 8 + 16
                            hc = true;
                            warn('height constrained');
                        }

                        if ((!wc && !hc) || fontSize <= 6){
                            break;
                        }

                        fontSize -= 1;
                    }

                    $('#shell-return').css('font-size', fontSize + 'px');

                    $('#shell-return').width(w);
                    $('#shell-return').height(h);

                    // Put popup it in the center
                    $('#machine-shell-popup-popup').css('left', ((window.innerWidth - $('#machine-shell-popup-popup').width())/2)+'px');

                    if (Terminal._textarea){ // Tap should trigger resize on touchscreens

                    } else
                        $('.terminal').focus();

                    // Make the hidden textfield focusable on android
                    if (Mist.term && Mist.term.isAndroid){
                        $(Terminal._textarea).width('100%');
                        $(Terminal._textarea).height($('#shell-return').height() + 60);
                    }
                    /*
                    if (Terminal._textarea){
                        $('html, body').animate({
                                            scrollTop: $('#shell-return').offset().top+(Mist.term.y-5)*$('#shell-return').height()/24
                                        }, 500);
                    }*/

                    return true;
                });
                $(window).trigger('resize');

                var term = new Terminal({
                  cols: 80,
                  rows: 24,
                  screenKeys: true
                });
                term.on('data', function(data) {
                    Mist.shell.emit('shell_data', data);
                });

                term.open(document.getElementById('shell-return'));

                var payload = {'backend_id': machine.backend.id,
                               'machine_id': machine.id,
                               'host': host
                               };
                Mist.shell.emit('shell_open', payload);
                Mist.shell.firstData = true;
                Mist.shell.on('shell_data', function(data){
                    term.write(data);
                    if (Mist.shell.firstData){
                        $('.terminal').focus();
                        Mist.shell.firstData = false;
                    }
                });
                term.write('Connecting to ' + host + '...\r\n');
                Mist.set('term', term);

                if(Terminal._textarea) {
                    // iOS virtual keyboard focus fix
                    $(document).off('focusin');

                    if (Mist.term && Mist.term.isAndroid){
                        $('#shell-return').bind('tap',function(){
                            $(window).trigger('resize');
                        });
                    }
                }

            },

            close: function () {
                warn('closing shell');
                Mist.shell.emit('shell_close');
                Mist.term.destroy();
                Mist.shell.disconnect();
                $('#machine-shell-popup').popup('close');
                $(window).off('resize');
                this._clear();
                $('.ui-footer').show(500);
            },

            /**
             *
             *  Pseudo-Private Methods
             *
             */

            _clear: function () {
                Ember.run(this, function () {
                    this.set('machine', null);
                });
            },

            _giveCallback: function (success, action) {
                if (this.callback) this.callback(success, action);
            },

            /**
             *
             *  Observers
             *
             */

            machinesObserver: function () {
                Ember.run.once(this, '_updateActions');
            }.observes('machines')
        });
    }
);
<commit_msg>adjust width to avoid terminal wrapping & cleanup<commit_after>define('app/controllers/machine_shell', ['app/models/command', 'ember'],
    /**
     * Machine Shell Controller
     *
     * @returns Class
     */
    function (Command) {
        return Ember.Object.extend(Ember.Evented, {

            /**
             *  Properties
             */

            command: null,
            machine: null,
            commandHistoryIndex: -1,

            /**
             *
             *  Methods
             *
             */

            open: function (machine) {
                this._clear();
                this.set('machine', machine);

                // Get the first ipv4 public ip to connect to
                var host = '';
                for (var i=0;i<machine.public_ips.length;i++){
                    if (machine.public_ips[i].search(':') == -1){
                        host = machine.public_ips[i];
                    }

                }
                if (host == '')
                    return false;

                // Open shell socket, give it a few shots
                var sock = undefined, retry = 0;
                while (sock == undefined) {
                    if (retry) {
                        warn('retry ' + retry);
                    }

                    sock = io.connect('/shell');
                    retry += 1;
                    if (retry > 5){
                        warn('failed to connect to shell socket after ' + retry + ' retries');
                        return false;
                    }
                }

                Mist.set('shell', sock);

                $('.ui-footer').hide(500);
                $('#machine-shell-popup').on('popupafteropen',
                    function(){
                        $('#machine-shell-popup').off('blur');
                        $(document).off('focusin');
                    }
                ).popup( "option", "dismissible", false ).popup('open');

                $(window).on('resize', function(){
                    var w, h, fontSize=18, wc, hc;

                    while (true){
                        wc = hc = false;
                        $('.fontSizeTest').css('font-size', fontSize + 'px');

                        w = $('.fontSizeTest').width() * 80;
                        h = $('.fontSizeTest').height() * 24;

                        if (w > window.innerWidth - 46){
                            // log('width constrained');
                            wc = true;
                        }

                        if (h > window.innerHeight-virtualKeyboardHeight() - 135){ //42.4 + 16 + 8 + 1 + 11.2 + 20 + 11.2 + 1 + 8 + 16
                            // log('height constrained');
                            hc = true;
                        }

                        if ((!wc && !hc) || fontSize <= 6){
                            break;
                        }

                        fontSize -= 1;
                    }

                    $('#shell-return').css('font-size', fontSize + 'px');

                    $('#shell-return').width(w+2);
                    $('#shell-return').height(h);

                    // Put popup it in the center
                    $('#machine-shell-popup-popup').css('left', ((window.innerWidth - $('#machine-shell-popup-popup').width())/2)+'px');

                    if (!Terminal._textarea)
                        $('.terminal').focus();

                    // Make the hidden textfield focusable on android
                    if (Mist.term && Mist.term.isAndroid){
                        $(Terminal._textarea).width('100%');
                        $(Terminal._textarea).height($('#shell-return').height() + 60);
                    }

                    return true;
                });
                $(window).trigger('resize');

                var term = new Terminal({
                  cols: 80,
                  rows: 24,
                  screenKeys: true
                });
                term.on('data', function(data) {
                    Mist.shell.emit('shell_data', data);
                });

                term.open(document.getElementById('shell-return'));

                var payload = {'backend_id': machine.backend.id,
                               'machine_id': machine.id,
                               'host': host
                               };
                Mist.shell.emit('shell_open', payload);
                Mist.shell.firstData = true;
                Mist.shell.on('shell_data', function(data){
                    term.write(data);
                    if (Mist.shell.firstData){
                        $('.terminal').focus();
                        Mist.shell.firstData = false;
                    }
                });
                term.write('Connecting to ' + host + '...\r\n');
                Mist.set('term', term);

                if(Terminal._textarea) {
                    // iOS virtual keyboard focus fix
                    $(document).off('focusin');

                    // Tap should trigger resize on Android for virtual keyboard to appear
                    if (Mist.term && Mist.term.isAndroid){
                        $('#shell-return').bind('tap',function(){
                            $(window).trigger('resize');
                        });
                    }
                    $(Terminal._textarea).show();
                }

            },

            close: function () {
                warn('closing shell');
                Mist.shell.emit('shell_close');
                Mist.term.destroy();
                Mist.shell.disconnect();
                $('#machine-shell-popup').popup('close');
                $(window).off('resize');
                this._clear();
                $('.ui-footer').show(500);
                if (Terminal._textarea)
                    $(Terminal._textarea).hide();

            },

            /**
             *
             *  Pseudo-Private Methods
             *
             */

            _clear: function () {
                Ember.run(this, function () {
                    this.set('machine', null);
                });
            },

            _giveCallback: function (success, action) {
                if (this.callback) this.callback(success, action);
            },

            /**
             *
             *  Observers
             *
             */

            machinesObserver: function () {
                Ember.run.once(this, '_updateActions');
            }.observes('machines')
        });
    }
);
<|endoftext|>


<commit_before>import html from "../core/html.js";
import * as template from "../core/template.js";
import Button from "./Button.js";
import Drawer from "./Drawer.js";
import * as internal from "./internal.js";

/**
 * A drawer that includes an always-visible grip element
 *
 * This variant of [Drawer](Drawer) includes a grip handle that remains visible
 * in the collapsed state. This both lets the user know the drawer is there, and
 * gives them a way to use a tap, click, or swipe to open or close the drawer.
 *
 * The default icon used to represent the handle can be replaced by slotting an
 * image or other element into the `grip` slot.
 *
 * @inherits Drawer
 * @part {Button} grip - the handle the user can tap, click, or swipe to open or close the drawer
 */
class DrawerWithGrip extends Drawer {
  /**
   * The class or tag used to create the `grip` part – the grip
   * handle the user can tap/click/swipe to open or close the drawer.
   *
   * @type {PartDescriptor}
   * @default Button
   */
  get gripPartType() {
    return this[internal.state].gripPartType;
  }
  set gripPartType(gripPartType) {
    this[internal.setState]({ gripPartType });
  }

  [internal.render](/** @type {ChangedFlags} */ changed) {
    if (super[internal.render]) {
      super[internal.render](changed);
    }

    renderParts(this[internal.shadowRoot], this[internal.state], changed);

    if (changed.gripPartType) {
      this[internal.ids].grip.addEventListener("click", (event) => {
        // Clicking grip toggles drawer.
        this[internal.raiseChangeEvents] = true;
        this.toggle();
        event.stopPropagation();
        this[internal.raiseChangeEvents] = false;
      });
    }

    if (changed.fromEdge || changed.rightToLeft) {
      // Position the grip so it's at the outer edge of the drawer.
      const { fromEdge, rightToLeft } = this[internal.state];

      const vertical = fromEdge === "top" || fromEdge === "bottom";
      this[internal.ids].frame.style.flexDirection = vertical
        ? "column"
        : "row";

      // Determine what grid we'll use to relatively position the content and
      // the grip.
      const mapFromEdgeToGrid = {
        bottom: "auto 1fr / auto",
        left: "auto / 1fr auto",
        right: "auto / auto 1fr",
        top: "1fr auto / auto",
      };
      mapFromEdgeToGrid.start = rightToLeft
        ? mapFromEdgeToGrid.right
        : mapFromEdgeToGrid.left;
      mapFromEdgeToGrid.end = rightToLeft
        ? mapFromEdgeToGrid.left
        : mapFromEdgeToGrid.right;

      // Determine what cell the grip will go in.
      const mapFromEdgeToGripCell = {
        bottom: "1 / 1",
        left: "1 / 2",
        right: "1 / 1",
        top: "2 / 1",
      };
      mapFromEdgeToGripCell.start = rightToLeft
        ? mapFromEdgeToGripCell.right
        : mapFromEdgeToGripCell.left;
      mapFromEdgeToGripCell.end = rightToLeft
        ? mapFromEdgeToGripCell.left
        : mapFromEdgeToGripCell.right;

      this[internal.ids].gripContainer.style.grid = mapFromEdgeToGrid[fromEdge];
      this[internal.ids].gripWorkaround.style.gridArea =
        mapFromEdgeToGripCell[fromEdge];
    }
  }

  [internal.rendered](/** @type {ChangedFlags} */ changed) {
    super[internal.rendered](changed);

    if (this[internal.state].gripSize === null) {
      // Use the rendered size of the grip to set the gripSize. This will ensure
      // the grip is visible, peeking out from the edge of the drawer's container.
      const { fromEdge } = this[internal.state];
      const vertical = fromEdge === "top" || fromEdge === "bottom";
      const dimension = vertical ? "offsetHeight" : "offsetWidth";
      const gripSize = this[internal.ids].grip[dimension];
      this[internal.setState]({ gripSize });
    }
  }

  get [internal.defaultState]() {
    return Object.assign(super[internal.defaultState], {
      gripPartType: Button,
    });
  }

  // Tell TrackpadSwipeMixin that the gripped content is the scrollable element
  // the user is going to try to scroll with the trackpad.
  get [internal.scrollTarget]() {
    return this[internal.ids].grippedContent;
  }

  get [internal.template]() {
    const result = super[internal.template];

    // Replace the default slot with one that includes a grip element.
    //
    // The gripWorkaround element exists for Safari, which doesn't correctly
    // measure the grip dimensions when mounted without it. Having a div that's
    // display: block instead of flex appears to be the reason this helps.
    const defaultSlot = result.content.querySelector("slot:not([name])");
    if (defaultSlot) {
      defaultSlot.replaceWith(html`

            <slot></slot>

              <slot name="grip"></slot>

      `);
    }

    renderParts(result.content, this[internal.state]);

    result.content.append(html`

    `);

    return result;
  }
}

/**
 * Render parts for the template or an instance.
 *
 * @private
 * @param {DocumentFragment} root
 * @param {PlainObject} state
 * @param {ChangedFlags} [changed]
 */
function renderParts(root, state, changed) {
  if (!changed || changed.gripPartType) {
    const { gripPartType } = state;
    const grip = root.getElementById("grip");
    if (grip) {
      template.transmute(grip, gripPartType);
    }
  }
}

export default DrawerWithGrip;
<commit_msg>Rearrange<commit_after>import html from "../core/html.js";
import * as template from "../core/template.js";
import Button from "./Button.js";
import Drawer from "./Drawer.js";
import * as internal from "./internal.js";

/**
 * A drawer that includes an always-visible grip element
 *
 * This variant of [Drawer](Drawer) includes a grip handle that remains visible
 * in the collapsed state. This both lets the user know the drawer is there, and
 * gives them a way to use a tap, click, or swipe to open or close the drawer.
 *
 * The default icon used to represent the handle can be replaced by slotting an
 * image or other element into the `grip` slot.
 *
 * @inherits Drawer
 * @part {Button} grip - the handle the user can tap, click, or swipe to open or close the drawer
 */
class DrawerWithGrip extends Drawer {
  get [internal.defaultState]() {
    return Object.assign(super[internal.defaultState], {
      gripPartType: Button,
    });
  }

  /**
   * The class or tag used to create the `grip` part – the grip
   * handle the user can tap/click/swipe to open or close the drawer.
   *
   * @type {PartDescriptor}
   * @default Button
   */
  get gripPartType() {
    return this[internal.state].gripPartType;
  }
  set gripPartType(gripPartType) {
    this[internal.setState]({ gripPartType });
  }

  [internal.render](/** @type {ChangedFlags} */ changed) {
    if (super[internal.render]) {
      super[internal.render](changed);
    }

    renderParts(this[internal.shadowRoot], this[internal.state], changed);

    if (changed.gripPartType) {
      this[internal.ids].grip.addEventListener("click", (event) => {
        // Clicking grip toggles drawer.
        this[internal.raiseChangeEvents] = true;
        this.toggle();
        event.stopPropagation();
        this[internal.raiseChangeEvents] = false;
      });
    }

    if (changed.fromEdge || changed.rightToLeft) {
      // Position the grip so it's at the outer edge of the drawer.
      const { fromEdge, rightToLeft } = this[internal.state];

      const vertical = fromEdge === "top" || fromEdge === "bottom";
      this[internal.ids].frame.style.flexDirection = vertical
        ? "column"
        : "row";

      // Determine what grid we'll use to relatively position the content and
      // the grip.
      const mapFromEdgeToGrid = {
        bottom: "auto 1fr / auto",
        left: "auto / 1fr auto",
        right: "auto / auto 1fr",
        top: "1fr auto / auto",
      };
      mapFromEdgeToGrid.start = rightToLeft
        ? mapFromEdgeToGrid.right
        : mapFromEdgeToGrid.left;
      mapFromEdgeToGrid.end = rightToLeft
        ? mapFromEdgeToGrid.left
        : mapFromEdgeToGrid.right;

      // Determine what cell the grip will go in.
      const mapFromEdgeToGripCell = {
        bottom: "1 / 1",
        left: "1 / 2",
        right: "1 / 1",
        top: "2 / 1",
      };
      mapFromEdgeToGripCell.start = rightToLeft
        ? mapFromEdgeToGripCell.right
        : mapFromEdgeToGripCell.left;
      mapFromEdgeToGripCell.end = rightToLeft
        ? mapFromEdgeToGripCell.left
        : mapFromEdgeToGripCell.right;

      this[internal.ids].gripContainer.style.grid = mapFromEdgeToGrid[fromEdge];
      this[internal.ids].gripWorkaround.style.gridArea =
        mapFromEdgeToGripCell[fromEdge];
    }
  }

  [internal.rendered](/** @type {ChangedFlags} */ changed) {
    super[internal.rendered](changed);

    if (this[internal.state].gripSize === null) {
      // Use the rendered size of the grip to set the gripSize. This will ensure
      // the grip is visible, peeking out from the edge of the drawer's container.
      const { fromEdge } = this[internal.state];
      const vertical = fromEdge === "top" || fromEdge === "bottom";
      const dimension = vertical ? "offsetHeight" : "offsetWidth";
      const gripSize = this[internal.ids].grip[dimension];
      this[internal.setState]({ gripSize });
    }
  }

  // Tell TrackpadSwipeMixin that the gripped content is the scrollable element
  // the user is going to try to scroll with the trackpad.
  get [internal.scrollTarget]() {
    return this[internal.ids].grippedContent;
  }

  get [internal.template]() {
    const result = super[internal.template];

    // Replace the default slot with one that includes a grip element.
    //
    // The gripWorkaround element exists for Safari, which doesn't correctly
    // measure the grip dimensions when mounted without it. Having a div that's
    // display: block instead of flex appears to be the reason this helps.
    const defaultSlot = result.content.querySelector("slot:not([name])");
    if (defaultSlot) {
      defaultSlot.replaceWith(html`

            <slot></slot>

              <slot name="grip"></slot>

      `);
    }

    renderParts(result.content, this[internal.state]);

    result.content.append(html`

    `);

    return result;
  }
}

/**
 * Render parts for the template or an instance.
 *
 * @private
 * @param {DocumentFragment} root
 * @param {PlainObject} state
 * @param {ChangedFlags} [changed]
 */
function renderParts(root, state, changed) {
  if (!changed || changed.gripPartType) {
    const { gripPartType } = state;
    const grip = root.getElementById("grip");
    if (grip) {
      template.transmute(grip, gripPartType);
    }
  }
}

export default DrawerWithGrip;
<|endoftext|>


<commit_before>'use strict';

var assert = require('assert');
var chromedriver = require('chromedriver');
var browser = require('../');

chromedriver.start();
browser.remote('http://localhost:9515/').timeout('60s').operationTimeout('20s');
after(function () {
  chromedriver.stop();
});

var getHeadingText = browser.async(function* (browser) {
  var heading = yield browser.elementByTagName('h1').text();
  return heading;
});

describe('www.example.com', function () {
  it('Has a header that reads "Example Domain"', browser(function* (browser) {
    yield browser.get('http://www.example.com');
    var heading = yield getHeadingText(browser);
    assert(heading.trim() == 'Example Domain');
  }));
});
<commit_msg>Support CI using sauce labs<commit_after>'use strict';

var assert = require('assert');
var chromedriver = require('chromedriver');
var browser = require('../');

var LOCAL = !process.env.CI;

if (LOCAL) {
  chromedriver.start();
  browser.remote('http://localhost:9515/').timeout('60s').operationTimeout('5s');
  after(function () {
    chromedriver.stop();
  });
} else {
  browser.remote('ondemand.saucelabs.com', 80, 'sauce-runner', 'c71a5c75-7c28-483f-9053-56da13b40bc2').timeout('240s').operationTimeout('30s');
}

var getHeadingText = browser.async(function* (browser) {
  var heading = yield browser.elementByTagName('h1').text();
  return heading;
});

describe('www.example.com', function () {
  it('Has a header that reads "Example Domain"', browser(function* (browser) {
    console.log('getting url');
    yield browser.get('http://www.example.com');
    console.log('getting heading text');
    var heading = yield getHeadingText(browser);
    console.log('checking heading text');
    assert(heading.trim() == 'Example Domain');
  }));
});
<|endoftext|>


<commit_before>var Splitter = artifacts.require("./Splitter.sol");

module.exports = function(deployer,network,accounts) {
  deployer.deploy(Splitter, accounts[1], accounts[2], { from: accounts[0] });
};<commit_msg>Change deploy script<commit_after>var Splitter = artifacts.require("./Splitter.sol");

module.exports = function(deployer,network,accounts) {
  deployer.deploy(Splitter, { from: accounts[0] });
};<|endoftext|>