<commit_before>//Developer: Sabbir Ahmed Siddiquee,
//Software Engineer, Selise rockin' software
//Git profile: https://github.com/prince3339

//safe code mode
// here ; is used to make sure that other codes loaded from different library/framework/file finished

//Main html view renderer engine where we'll pass an array of objects and it'll generate a list view
;
(function(window) {
    'use strict';
    var vm = window;
    config.fn.renderView = renderView;

    function renderView(todos_sorted) {
        for (var i = 0; i < todos_sorted.length; i++) {
            //console.log(todos[i].title);

            var li = document.createElement('li');
            li.className = 'padding-16 selise__todo__list flex-direction__row';
            li.setAttribute('tabindex', 0);

            var div_1 = document.createElement('div');
            if (todos_sorted[i].status) {
                div_1.className = 'flex__1 border-right padding-right-20 padding-8 selise__todo__list--completed';
            } else {
                div_1.className = 'flex__1 border-right padding-right-20 padding-8';
            }
            div_1.setAttribute('tabindex', 0);

            var div_2 = document.createElement('div');
            div_2.className = 'flex-direction__row flex-justify-content__space-between flex-align-items__center';

            var h3 = document.createElement('h3');
            h3.className = 'margin-0 font-size-fixed-16 line-height-normal opacity-50';
            h3.innerText = todos_sorted[i].title;

            div_2.appendChild(h3);

            var checkBox = document.createElement('input');
            checkBox.setAttribute("type", "checkbox");
            checkBox.setAttribute("name", "todo_list");
            checkBox.className = 'done_todo';
            checkBox.setAttribute('onChange', "config.fn.markComplete(this," + "'" + todos_sorted[i].id + "'" + ")");

            if (todos_sorted[i].status) {
                checkBox.setAttribute("checked", "true");
            } else {
                checkBox.removeAttribute("checked");
            }

            div_2.appendChild(checkBox);

            var p = document.createElement('p');
            p.className = 'font-size-fixed-14 margin-0 opacity-50 line-height-big margin-top-10';
            p.innerText = todos_sorted[i].description;

            div_1.appendChild(div_2);
            div_1.appendChild(p);

            li.appendChild(div_1);

            var div_3 = document.createElement('div');
            div_3.className = 'width-80 text-center flex-direction__row flex-justify-content__center flex-align-items__flex-start';

            var button_1 = document.createElement('button');
            button_1.className = 'margin-h-5 padding-5 border-none cur-pointer';
            button_1.setAttribute('role', 'button');
            button_1.setAttribute('aria-label', 'Make task done');
            button_1.setAttribute('onclick', "config.fn.showEditModal( event, " + "'" + todos_sorted[i].id + "'" + ")");
            if (todos_sorted[i].status) {
                button_1.setAttribute('disabled', 'true');
                button_1.className = 'margin-h-5 padding-5 border-none cur-not-allowed';
            }

            var i_1 = document.createElement('i');
            i_1.className = 'zmdi zmdi-border-color font-size-fixed-18 opacity-50';

            button_1.appendChild(i_1);

            var button_2 = document.createElement('button');
            button_2.className = 'border-none cur-pointer padding-5';
            button_2.setAttribute('role', 'button');
            button_2.setAttribute('aria-label', 'Delete this task');
            button_2.setAttribute('onclick', "config.fn.deleteTask(" + "'" + todos_sorted[i].id + "'" + ")");

            var i_2 = document.createElement('i');
            i_2.className = 'zmdi zmdi-delete font-size-fixed-18 opacity-50';

            button_2.appendChild(i_2);

            div_3.appendChild(button_1);
            div_3.appendChild(button_2);

            li.appendChild(div_3);

            listContainer.appendChild(li);
        }
    }

})(window)<commit_msg>delete btn padding issue solved<commit_after>//Developer: Sabbir Ahmed Siddiquee,
//Software Engineer, Selise rockin' software
//Git profile: https://github.com/prince3339

//safe code mode
// here ; is used to make sure that other codes loaded from different library/framework/file finished

//Main html view renderer engine where we'll pass an array of objects and it'll generate a list view
;
(function(window) {
    'use strict';
    var vm = window;
    config.fn.renderView = renderView;

    function renderView(todos_sorted) {
        for (var i = 0; i < todos_sorted.length; i++) {
            //console.log(todos[i].title);

            var li = document.createElement('li');
            li.className = 'padding-16 selise__todo__list flex-direction__row';
            li.setAttribute('tabindex', 0);

            var div_1 = document.createElement('div');
            if (todos_sorted[i].status) {
                div_1.className = 'flex__1 border-right padding-right-20 padding-8 selise__todo__list--completed';
            } else {
                div_1.className = 'flex__1 border-right padding-right-20 padding-8';
            }
            div_1.setAttribute('tabindex', 0);

            var div_2 = document.createElement('div');
            div_2.className = 'flex-direction__row flex-justify-content__space-between flex-align-items__center';

            var h3 = document.createElement('h3');
            h3.className = 'margin-0 font-size-fixed-16 line-height-normal opacity-50';
            h3.innerText = todos_sorted[i].title;

            div_2.appendChild(h3);

            var checkBox = document.createElement('input');
            checkBox.setAttribute("type", "checkbox");
            checkBox.setAttribute("name", "todo_list");
            checkBox.className = 'done_todo';
            checkBox.setAttribute('onChange', "config.fn.markComplete(this," + "'" + todos_sorted[i].id + "'" + ")");

            if (todos_sorted[i].status) {
                checkBox.setAttribute("checked", "true");
            } else {
                checkBox.removeAttribute("checked");
            }

            div_2.appendChild(checkBox);

            var p = document.createElement('p');
            p.className = 'font-size-fixed-14 margin-0 opacity-50 line-height-big margin-top-10';
            p.innerText = todos_sorted[i].description;

            div_1.appendChild(div_2);
            div_1.appendChild(p);

            li.appendChild(div_1);

            var div_3 = document.createElement('div');
            div_3.className = 'width-80 text-center flex-direction__row flex-justify-content__center flex-align-items__flex-start';

            var button_1 = document.createElement('button');
            button_1.className = 'margin-h-5 padding-5 border-none cur-pointer';
            button_1.setAttribute('role', 'button');
            button_1.setAttribute('aria-label', 'Make task done');
            button_1.setAttribute('onclick', "config.fn.showEditModal( event, " + "'" + todos_sorted[i].id + "'" + ")");
            if (todos_sorted[i].status) {
                button_1.setAttribute('disabled', 'true');
                button_1.className = 'margin-h-5 padding-5 border-none cur-not-allowed';
            }

            var i_1 = document.createElement('i');
            i_1.className = 'zmdi zmdi-border-color font-size-fixed-18 opacity-50';

            button_1.appendChild(i_1);

            var button_2 = document.createElement('button');
            button_2.className = 'border-none cur-pointer padding-v-5 padding-h-8';
            button_2.setAttribute('role', 'button');
            button_2.setAttribute('aria-label', 'Delete this task');
            button_2.setAttribute('onclick', "config.fn.deleteTask(" + "'" + todos_sorted[i].id + "'" + ")");

            var i_2 = document.createElement('i');
            i_2.className = 'zmdi zmdi-delete font-size-fixed-18 opacity-50';

            button_2.appendChild(i_2);

            div_3.appendChild(button_1);
            div_3.appendChild(button_2);

            li.appendChild(div_3);

            listContainer.appendChild(li);
        }
    }

})(window)<|endoftext|>


<commit_before>/*eslint-env browser */
/*globals require: false, module: false */
'use strict';

var React = require('react');
var ReactDOM = require('react-dom');
var _ = require('../underscore_ext');
var MenuItem = require('react-bootstrap/lib/MenuItem');
var SplitButton = require('react-bootstrap/lib/SplitButton');
var Badge = require('react-bootstrap/lib/Badge');
var Tooltip = require('react-bootstrap/lib/Tooltip');
var OverlayTrigger = require('react-bootstrap/lib/OverlayTrigger');
var DefaultTextInput = require('./DefaultTextInput');
var {RefGeneAnnotation} = require('../refGeneExons');
var SpreadSheetHighlight = require('../SpreadSheetHighlight');
var ResizeOverlay = require('./ResizeOverlay');
var widgets = require('../columnWidgets');
var aboutDatasetMenu = require('./aboutDatasetMenu');
var spinner = require('../ajax-loader.gif');

// XXX move this?
function download([fields, rows]) {
	var txt = _.map([fields].concat(rows), row => row.join('\t')).join('\n');
	// use blob for bug in chrome: https://code.google.com/p/chromium/issues/detail?id=373182
	var url = URL.createObjectURL(new Blob([txt], { type: 'text/tsv' }));
	var a = document.createElement('a');
	var filename = 'xenaDownload.tsv';
	_.extend(a, { id: filename, download: filename, href: url });
	document.body.appendChild(a);
	a.click();
	document.body.removeChild(a);
}

var styles = {
	badge: {
		fontSize: '100%',
		// Fix the width so it doesn't change if the label changes. This is important
		// when resizing, because we (unfortunately) inspect the DOM to discover
		// the minimum width we need to draw the column controls. If the label changes
		// to a different character, the width will be different, and our minimum width
		// becomes invalid.
		width: 24
	},
	status: {
		pointerEvents: 'none',
		textAlign: 'center',
		zIndex: 1,
		position: 'absolute',
		top: 0,
		left: 0,
		width: '100%',
		height: '100%',
		backgroundColor: 'rgba(255, 255, 255, 0.6)'
	},
	error: {
		textAlign: 'center',
		pointerEvents: 'all',
		cursor: 'pointer'
	}
};

function mutationMenu(props, {onMuPit}) {
	var {column, data} = props,
		assembly = _.getIn(column, ['assembly']),
		rightAssembly = (assembly === "hg19" || assembly === "GRCh37") ? true : false,  //MuPIT currently only support hg19
		noMenu = !rightAssembly || (data && _.isEmpty(data.refGene)),
		noData = !_.get(data, 'req'), // XXX
		menuItemName = noData ? 'MuPIT View (hg19) Loading' : 'MuPIT View (hg19)';
	return noMenu ? null : <MenuItem disabled={noData} onSelect={onMuPit}>{menuItemName}</MenuItem>;
}

function matrixMenu(props, {supportsGeneAverage, onMode}) {
	var {id, column: {fieldType, noGeneDetail}} = props;
	return supportsGeneAverage(id) ?
		(fieldType === 'genes' ?
			<MenuItem eventKey="geneProbes" title={noGeneDetail ? 'no common probemap' : ''}
				disabled={noGeneDetail} onSelect={onMode}>Detailed view</MenuItem> :
			<MenuItem eventKey="genes" onSelect={onMode}>Gene average</MenuItem>) :
		null;
}

// We could try to drive this from the column widgets, but it gets rather complex making
// the widgets care about a menu in their container.
function optionMenu(props, opts) {
	var {column: {valueType}} = props;
	return (valueType === 'mutation' ?  mutationMenu : matrixMenu)(props, opts);
}

function getStatusView(status, onReload) {
	if (status === 'loading') {
		return (

);
	}
	if (status === 'error') {
		return (

);
	}
	return null;
}

var Column = React.createClass({
	onResizeStop: function (size) {
		this.props.onResize(this.props.id, size);
	},
	onRemove: function () {
		this.props.onRemove(this.props.id);
	},
	onDownload: function () {
		download(this.refs.plot.download());
	},
	onViz: function () {
		this.props.onViz(this.props.id);
	},
	onKm: function () {
		this.props.onKm(this.props.id);
	},
	onMode: function (ev, newMode) {
		this.props.onMode(this.props.id, newMode);
	},
	onColumnLabel: function (value) {
		this.props.onColumnLabel(this.props.id, value);
	},
	onFieldLabel: function (value) {
		this.props.onFieldLabel(this.props.id, value);
	},
	onMuPit: function () {
		// Construct the url, which will be opened in new window
		let rows = _.getIn(this.props, ['data', 'req', 'rows']),
			uriList = _.uniq(_.map(rows, n => `${n.chr}:${n.start.toString()}`)).join(','),
			url = `http://mupit.icm.jhu.edu/?gm=${uriList}`;

		window.open(url);
	},
	onReload: function () {
		this.props.onReload(this.props.id);
	},
	getControlWidth: function () {
		var controlWidth = ReactDOM.findDOMNode(this.refs.controls).getBoundingClientRect().width,
			labelWidth = ReactDOM.findDOMNode(this.refs.label).getBoundingClientRect().width;
		return controlWidth + labelWidth;
	},
	render: function () {
		var {first, id, label, samples, samplesMatched, column, index,
				zoom, data, datasetMeta, fieldFormat, sampleFormat, disableKM, searching, supportsGeneAverage, onClick, tooltip} = this.props,
			{width, columnLabel, fieldLabel, user} = column,
			menu = optionMenu(this.props, {onMode: this.onMode, onMuPit: this.onMuPit, supportsGeneAverage}),
			[kmDisabled, kmTitle] = disableKM(id),
			status = _.get(data, 'status'),
			// move this to state to generalize to other annotations.
			doRefGene = _.get(data, 'refGene'),
			sortHelp = <Tooltip>Drag to change column order</Tooltip>,
			// In FF spans don't appear as event targets. In Chrome, they do.
			// If we omit Sortable-handle here, Chrome will only catch events
			// in the button but not in the span. If we omit Sortable-handle
			// in SplitButton, FF will catch no events, since span doesn't
			// emit any.
			moveIcon = (
				<OverlayTrigger placement='top' overlay={sortHelp}>

				</OverlayTrigger>);

		return (

				<SplitButton ref='controls' className='Sortable-handle' title={moveIcon} bsSize='xsmall'>
					{menu}
					{menu && <MenuItem divider />}
					<MenuItem title={kmTitle} onSelect={this.onKm} disabled={kmDisabled}>Kaplan Meier Plot</MenuItem>
					<MenuItem onSelect={this.onDownload}>Download</MenuItem>
					{aboutDatasetMenu(datasetMeta(id))}
					<MenuItem onSelect={this.onViz}>Viz Settings</MenuItem>
					<MenuItem onSelect={this.onRemove}>Remove</MenuItem>
				</SplitButton>
				<Badge ref='label' style={styles.badge} className='pull-right'>{label}</Badge>

				<DefaultTextInput
					onChange={this.onColumnLabel}
					value={{default: columnLabel, user: user.columnLabel}} />
				<DefaultTextInput
					onChange={this.onFieldLabel}
					value={{default: fieldLabel, user: user.fieldLabel}} />

					{doRefGene ?
						<RefGeneAnnotation
							width={width}
							refGene={_.values(data.refGene)[0]}
							layout={column.layout}
							position={{gene: column.fields[0]}}/> : null}

				<ResizeOverlay
					onResizeStop={this.onResizeStop}
					width={width}
					minWidth={this.getControlWidth}
					height={zoom.height}>

					<SpreadSheetHighlight
						animate={searching}
						width={width}
						height={zoom.height}
						samples={samples.slice(zoom.index, zoom.index + zoom.count)}
						samplesMatched={samplesMatched}/>

						{widgets.column({ref: 'plot', id, column, data, index, zoom, samples, onClick, fieldFormat, sampleFormat, tooltip})}
						{getStatusView(status, this.onReload)}

				</ResizeOverlay>

Legends

				{widgets.legend({column, data})}

		);
	}
});

module.exports = Column;
<commit_msg>Tooltips on column UI.<commit_after>/*eslint-env browser */
/*globals require: false, module: false */
'use strict';

var React = require('react');
var ReactDOM = require('react-dom');
var _ = require('../underscore_ext');
var MenuItem = require('react-bootstrap/lib/MenuItem');
var Dropdown = require('react-bootstrap/lib/Dropdown');
var Button = require('react-bootstrap/lib/Button');
var Badge = require('react-bootstrap/lib/Badge');
var Tooltip = require('react-bootstrap/lib/Tooltip');
var OverlayTrigger = require('react-bootstrap/lib/OverlayTrigger');
var DefaultTextInput = require('./DefaultTextInput');
var {RefGeneAnnotation} = require('../refGeneExons');
var SpreadSheetHighlight = require('../SpreadSheetHighlight');
var ResizeOverlay = require('./ResizeOverlay');
var widgets = require('../columnWidgets');
var aboutDatasetMenu = require('./aboutDatasetMenu');
var spinner = require('../ajax-loader.gif');

// XXX move this?
function download([fields, rows]) {
	var txt = _.map([fields].concat(rows), row => row.join('\t')).join('\n');
	// use blob for bug in chrome: https://code.google.com/p/chromium/issues/detail?id=373182
	var url = URL.createObjectURL(new Blob([txt], { type: 'text/tsv' }));
	var a = document.createElement('a');
	var filename = 'xenaDownload.tsv';
	_.extend(a, { id: filename, download: filename, href: url });
	document.body.appendChild(a);
	a.click();
	document.body.removeChild(a);
}

var styles = {
	badge: {
		fontSize: '100%',
		// Fix the width so it doesn't change if the label changes. This is important
		// when resizing, because we (unfortunately) inspect the DOM to discover
		// the minimum width we need to draw the column controls. If the label changes
		// to a different character, the width will be different, and our minimum width
		// becomes invalid.
		width: 24
	},
	status: {
		pointerEvents: 'none',
		textAlign: 'center',
		zIndex: 1,
		position: 'absolute',
		top: 0,
		left: 0,
		width: '100%',
		height: '100%',
		backgroundColor: 'rgba(255, 255, 255, 0.6)'
	},
	error: {
		textAlign: 'center',
		pointerEvents: 'all',
		cursor: 'pointer'
	},
	columnMenuToggle: {
		position: 'absolute',
		left: 0,
		top: 0,
		width: '100%',
		height: '100%'
	}
};

function mutationMenu(props, {onMuPit}) {
	var {column, data} = props,
		assembly = _.getIn(column, ['assembly']),
		rightAssembly = (assembly === "hg19" || assembly === "GRCh37") ? true : false,  //MuPIT currently only support hg19
		noMenu = !rightAssembly || (data && _.isEmpty(data.refGene)),
		noData = !_.get(data, 'req'), // XXX
		menuItemName = noData ? 'MuPIT View (hg19) Loading' : 'MuPIT View (hg19)';
	return noMenu ? null : <MenuItem disabled={noData} onSelect={onMuPit}>{menuItemName}</MenuItem>;
}

function matrixMenu(props, {supportsGeneAverage, onMode}) {
	var {id, column: {fieldType, noGeneDetail}} = props;
	return supportsGeneAverage(id) ?
		(fieldType === 'genes' ?
			<MenuItem eventKey="geneProbes" title={noGeneDetail ? 'no common probemap' : ''}
				disabled={noGeneDetail} onSelect={onMode}>Detailed view</MenuItem> :
			<MenuItem eventKey="genes" onSelect={onMode}>Gene average</MenuItem>) :
		null;
}

// We could try to drive this from the column widgets, but it gets rather complex making
// the widgets care about a menu in their container.
function optionMenu(props, opts) {
	var {column: {valueType}} = props;
	return (valueType === 'mutation' ?  mutationMenu : matrixMenu)(props, opts);
}

function getStatusView(status, onReload) {
	if (status === 'loading') {
		return (

);
	}
	if (status === 'error') {
		return (

);
	}
	return null;
}

var Column = React.createClass({
	onResizeStop: function (size) {
		this.props.onResize(this.props.id, size);
	},
	onRemove: function () {
		this.props.onRemove(this.props.id);
	},
	onDownload: function () {
		download(this.refs.plot.download());
	},
	onViz: function () {
		this.props.onViz(this.props.id);
	},
	onKm: function () {
		this.props.onKm(this.props.id);
	},
	onMode: function (ev, newMode) {
		this.props.onMode(this.props.id, newMode);
	},
	onColumnLabel: function (value) {
		this.props.onColumnLabel(this.props.id, value);
	},
	onFieldLabel: function (value) {
		this.props.onFieldLabel(this.props.id, value);
	},
	onMuPit: function () {
		// Construct the url, which will be opened in new window
		let rows = _.getIn(this.props, ['data', 'req', 'rows']),
			uriList = _.uniq(_.map(rows, n => `${n.chr}:${n.start.toString()}`)).join(','),
			url = `http://mupit.icm.jhu.edu/?gm=${uriList}`;

		window.open(url);
	},
	onReload: function () {
		this.props.onReload(this.props.id);
	},
	getControlWidth: function () {
		var controlWidth = ReactDOM.findDOMNode(this.refs.controls).getBoundingClientRect().width,
			labelWidth = ReactDOM.findDOMNode(this.refs.label).getBoundingClientRect().width;
		return controlWidth + labelWidth;
	},
	render: function () {
		var {first, id, label, samples, samplesMatched, column, index,
				zoom, data, datasetMeta, fieldFormat, sampleFormat, disableKM, searching, supportsGeneAverage, onClick, tooltip} = this.props,
			{width, columnLabel, fieldLabel, user} = column,
			menu = optionMenu(this.props, {onMode: this.onMode, onMuPit: this.onMuPit, supportsGeneAverage}),
			[kmDisabled, kmTitle] = disableKM(id),
			status = _.get(data, 'status'),
			// move this to state to generalize to other annotations.
			doRefGene = _.get(data, 'refGene'),
			sortHelp = <Tooltip>Drag to change column order</Tooltip>,
			menuHelp = <Tooltip>Column menu</Tooltip>,
			// In FF spans don't appear as event targets. In Chrome, they do.
			// If we omit Sortable-handle here, Chrome will only catch events
			// in the button but not in the span. If we omit Sortable-handle
			// in SplitButton, FF will catch no events, since span doesn't
			// emit any.
			moveIcon = (
				<OverlayTrigger placement='top' overlay={sortHelp}>

				</OverlayTrigger>);

		// FF 'button' tag will not emit 'mouseenter' events (needed for
		// tooltips) for children. We must use a different tag, e.g. 'label'.
		// Button and Dropdown.Toggle will allow overriding the tag.  However
		// Splitbutton will not pass props down to the underlying Button, so we
		// can't use Splitbutton.
		return (

				{/* Using Dropdown instead of SplitButton so we can put a Tooltip on the caret. :-p */}
				<Dropdown ref='controls' bsSize='xsmall'>
					<Button componentClass='label'>
						{moveIcon}
					</Button>
					{/* If OverlayTrigger contains Dropdown.Toggle, the toggle doesn't work. So we invert the nesting and use a span to cover the trigger area. */}
					<Dropdown.Toggle componentClass='label'>
						<OverlayTrigger placement='top' overlay={menuHelp}>

						</OverlayTrigger>
					</Dropdown.Toggle>
					<Dropdown.Menu>
						{menu}
						{menu && <MenuItem divider />}
						<MenuItem title={kmTitle} onSelect={this.onKm} disabled={kmDisabled}>Kaplan Meier Plot</MenuItem>
						<MenuItem onSelect={this.onDownload}>Download</MenuItem>
						{aboutDatasetMenu(datasetMeta(id))}
						<MenuItem onSelect={this.onViz}>Viz Settings</MenuItem>
						<MenuItem onSelect={this.onRemove}>Remove</MenuItem>
					</Dropdown.Menu>
				</Dropdown>
				<Badge ref='label' style={styles.badge} className='pull-right'>{label}</Badge>

				<DefaultTextInput
					onChange={this.onColumnLabel}
					value={{default: columnLabel, user: user.columnLabel}} />
				<DefaultTextInput
					onChange={this.onFieldLabel}
					value={{default: fieldLabel, user: user.fieldLabel}} />

					{doRefGene ?
						<RefGeneAnnotation
							width={width}
							refGene={_.values(data.refGene)[0]}
							layout={column.layout}
							position={{gene: column.fields[0]}}/> : null}

				<ResizeOverlay
					onResizeStop={this.onResizeStop}
					width={width}
					minWidth={this.getControlWidth}
					height={zoom.height}>

					<SpreadSheetHighlight
						animate={searching}
						width={width}
						height={zoom.height}
						samples={samples.slice(zoom.index, zoom.index + zoom.count)}
						samplesMatched={samplesMatched}/>

						{widgets.column({ref: 'plot', id, column, data, index, zoom, samples, onClick, fieldFormat, sampleFormat, tooltip})}
						{getStatusView(status, this.onReload)}

				</ResizeOverlay>

Legends

				{widgets.legend({column, data})}

		);
	}
});

module.exports = Column;
<|endoftext|>


<commit_before>var events = require('events');
var Service = require('./service');
var inherits = require('inherits');

module.exports = VoteService;

function VoteService(opts) {
    var self = this;
    Service.call(this, opts);
    var voteFields = opts.voteFields || {};
    var fpIdFields = opts.fpIdFields || {};
    var min = opts.min || 0;
    var max = opts.max || 1000;
    var oId = opts.oId;

    this.incrementVote = function(fc, field) {
        var f = fc.features[0];
        delete f.geometry;
        f.properties[field] += 1;
        return f;
    };

    function saveVote(vote, callback) {
        var field = voteFields[vote];
        self.getFeatures(function(err, fc) {
            self.service().updateFeature(self.incrementVote(fc, field), callback);
        });
    }

    this.getRandomId = function(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    };

    this.oId = function() {
        return oId || this.getRandomId(min, max);
    };

    this.addVote = function(vote) {
        saveVote(vote, function(err, res) {
            if (err) throw err;
            self.emit('vote-service::addVote', vote);
            self.emit('vote-service::saveVote', res);
        });
    };

    this.voteFields = voteFields;

    this.fpIdFields = fpIdFields;
}

inherits(VoteService, Service);

VoteService.prototype.getRandomFeature = function(callback) {
    this.setoId(this.getRandomId);
    this.getFeatures(callback);
};
<commit_msg>Remove unused module<commit_after>var Service = require('./service');
var inherits = require('inherits');

module.exports = VoteService;

function VoteService(opts) {
    var self = this;
    Service.call(this, opts);
    var voteFields = opts.voteFields || {};
    var fpIdFields = opts.fpIdFields || {};
    var min = opts.min || 0;
    var max = opts.max || 1000;
    var oId = opts.oId;

    this.incrementVote = function(fc, field) {
        var f = fc.features[0];
        delete f.geometry;
        f.properties[field] += 1;
        return f;
    };

    function saveVote(vote, callback) {
        var field = voteFields[vote];
        self.getFeatures(function(err, fc) {
            self.service().updateFeature(self.incrementVote(fc, field), callback);
        });
    }

    this.getRandomId = function(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    };

    this.oId = function() {
        return oId || this.getRandomId(min, max);
    };

    this.addVote = function(vote) {
        saveVote(vote, function(err, res) {
            if (err) throw err;
            self.emit('vote-service::addVote', vote);
            self.emit('vote-service::saveVote', res);
        });
    };

    this.voteFields = voteFields;

    this.fpIdFields = fpIdFields;
}

inherits(VoteService, Service);

VoteService.prototype.getRandomFeature = function(callback) {
    this.setoId(this.getRandomId);
    this.getFeatures(callback);
};
<|endoftext|>


<commit_before>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import keycode from 'keycode';

import icBEM from '../utils/icBEM';
import prefixClass from '../utils/prefixClass';
import getComponentName from '../utils/getComponentName';

import '../styles/Closable.scss';

export const COMPONENT_NAME = prefixClass('closable');
const ROOT_BEM = icBEM(COMPONENT_NAME);

const ESCAPE = 'Escape';

/**
 * `closable()` HOC mixin
 * ====================
 * Provide various of ways to determine when to “close” a component by
 * binding event listeners on `document`.
 *
 * Formerlly `escapable()`.
 *
 * @param {object} options
 * @param {boolean=} options.onEscape
 * @param {boolean=} options.onClickOutside
 * @param {boolean=} options.onClickInside
 */
const closable = ({
    onEscape = true,
    onClickOutside = false,
    onClickInside = false,
} = {}) => (WrappedComponent) => {
    const componentName = getComponentName(WrappedComponent);

    class Closable extends PureComponent {
        static displayName = `closable(${componentName})`;

        static propTypes = {
            onClose: PropTypes.func,
            closable: PropTypes.shape({
                onEscape: PropTypes.bool,
                onClickOutside: PropTypes.bool,
                onClickInside: PropTypes.bool,
            }),
        };

        static defaultProps = {
            onClose: () => {},
            closable: {
                onEscape,
                onClickInside,
                onClickOutside,
            },
        };

        constructor(props) {
            super(props);
            this.clickedInside = false;
        }

        componentDidMount() {
            document.addEventListener('keyup', this.handleDocumentKeyup);
        }

        componentWillUnmount() {
            document.removeEventListener('keyup', this.handleDocumentKeyup);
        }

        getOptions() {
            const configuredOptions = {
                onEscape,
                onClickInside,
                onClickOutside,
            };
            const runtimeOptions = this.props.closable;

            return {
                ...configuredOptions,
                ...runtimeOptions,
            };
        }

        /**
         * @param {KeyboardEvent} event
         */
        handleDocumentKeyup = (event) => {
            const options = this.getOptions();

            if (options.onEscape && event.keyCode === keycode(ESCAPE)) {
                this.props.onClose(event);
            }
        }

        /**
         * @param {React.MouseEvent} event
         */
        handleOuterLayerClick = (event) => {
            const options = this.getOptions();

            if (options.onClickOutside) {
                this.props.onClose(event);
            }
        }

        /**
         * @param {React.MouseEvent} event
         */
        handleInsideClick = (event) => {
            const options = this.getOptions();
            event.stopPropagation();

            if (options.onClickInside) {
                this.props.onClose(event);
            }
        }

        render() {
            const {
                onClose,
                closable: runtimeOptions,
                ...otherProps
            } = this.props;

            return (
                <div
                    role="presentation"
                    className={ROOT_BEM.toString()}
                    onClick={this.handleOuterLayerClick}>
                    <WrappedComponent
                        onInsideClick={this.handleInsideClick}
                        {...otherProps} />
                </div>
            );
        }
    }

    return Closable;
};

export default closable;
<commit_msg>Allow event from inside click to bubble up; ignore in outside handler<commit_after>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import keycode from 'keycode';

import icBEM from '../utils/icBEM';
import prefixClass from '../utils/prefixClass';
import getComponentName from '../utils/getComponentName';

import '../styles/Closable.scss';

export const COMPONENT_NAME = prefixClass('closable');
const ROOT_BEM = icBEM(COMPONENT_NAME);

const ESCAPE = 'Escape';

/**
 * `closable()` HOC mixin
 * ====================
 * Provide various of ways to determine when to “close” a component by
 * binding event listeners on `document`.
 *
 * Formerlly `escapable()`.
 *
 * @param {object} options
 * @param {boolean=} options.onEscape
 * @param {boolean=} options.onClickOutside
 * @param {boolean=} options.onClickInside
 */
const closable = ({
    onEscape = true,
    onClickOutside = false,
    onClickInside = false,
} = {}) => (WrappedComponent) => {
    const componentName = getComponentName(WrappedComponent);

    class Closable extends PureComponent {
        static displayName = `closable(${componentName})`;

        static propTypes = {
            onClose: PropTypes.func,
            closable: PropTypes.shape({
                onEscape: PropTypes.bool,
                onClickOutside: PropTypes.bool,
                onClickInside: PropTypes.bool,
            }),
        };

        static defaultProps = {
            onClose: () => {},
            closable: {
                onEscape,
                onClickInside,
                onClickOutside,
            },
        };

        constructor(props) {
            super(props);
            this.clickedInside = false;
        }

        componentDidMount() {
            document.addEventListener('keyup', this.handleDocumentKeyup);
        }

        componentWillUnmount() {
            document.removeEventListener('keyup', this.handleDocumentKeyup);
        }

        getOptions() {
            const configuredOptions = {
                onEscape,
                onClickInside,
                onClickOutside,
            };
            const runtimeOptions = this.props.closable;

            return {
                ...configuredOptions,
                ...runtimeOptions,
            };
        }

        /**
         * @param {KeyboardEvent} event
         */
        handleDocumentKeyup = (event) => {
            const options = this.getOptions();

            if (options.onEscape && event.keyCode === keycode(ESCAPE)) {
                this.props.onClose(event);
            }
        }

        /**
         * @param {React.MouseEvent} event
         */
        handleOuterLayerClick = (event) => {
            const options = this.getOptions();

            if (this.clickedInside) {
                // ignoring click events bubbling up from inside
                this.clickedInside = false;
                return;
            }

            if (options.onClickOutside) {
                this.props.onClose(event);
            }
        }

        /**
         * @param {React.MouseEvent} event
         */
        handleInsideClick = (event) => {
            const options = this.getOptions();
            this.clickedInside = true;

            if (options.onClickInside) {
                this.props.onClose(event);
            }
        }

        render() {
            const {
                onClose,
                closable: runtimeOptions,
                ...otherProps
            } = this.props;

            return (
                <div
                    role="presentation"
                    className={ROOT_BEM.toString()}
                    onClick={this.handleOuterLayerClick}>
                    <WrappedComponent
                        onInsideClick={this.handleInsideClick}
                        {...otherProps} />
                </div>
            );
        }
    }

    return Closable;
};

export default closable;
<|endoftext|>


<commit_before>const assert = require('assert')
const { removeSync } = require('fs-extra')
const { resolve } = require('path')
const Connector = require('../src/connector')

const { testProjectPath, testTmpPath } = require('../../../test/support/paths')
const { adapters } = require('./support/adapters')
const Component = require('../src/component')
const state = {
  config: {
    source: {
      components: [
        resolve(testProjectPath, 'src', 'elements'),
        resolve(testProjectPath, 'src', 'modules')
      ],
      templates: resolve(testProjectPath, 'src', 'templates'),
      data: resolve(__dirname, 'fixtures'),
      base: testProjectPath
    },
    themes: [
      {
        id: '_default',
        title: 'Default'
      }
    ],
    ui: {
      base: '/'
    },
    target: testTmpPath,
    adapters
  }
}

const assertComponent = (componentIds, componentId) => assert(componentIds.includes(componentId), `missing component "${componentId}"`)

describe('Component', () => {
  before(() => Connector.setup(state))
  afterEach(() => { removeSync(testTmpPath) })

  describe('#fetchById', function () {
    this.timeout(5000)

    it('should return component object', async () => {
      const data = await Component.fetchById(state, 'input')

      assert.strictEqual(data.id, 'input')
      assert.strictEqual(data.title, 'Inputs')
      assert.strictEqual(data.sourcePath, 'src/elements/input')
      assert.strictEqual(data.sourceFile, 'src/elements/input/component.config.js')
    })

    it('should return component object for components without component.config.js file', async () => {
      const data = await Component.fetchById(state, 'form')

      assert.strictEqual(data.id, 'form')
      assert.strictEqual(data.title, 'Form')
      assert.strictEqual(data.sourcePath, 'src/modules/form')
      assert.strictEqual(data.sourceFile, undefined)
    })

    it('should infer variants if they are not provided', async () => {
      const data = await Component.fetchById(state, 'formfield')
      const ids = data.variants.map(v => v.id.replace(/-\d$/, ''))

      assert.strictEqual(ids.length, 2)
      assert(ids.includes('formfield/text-with-label.pug'))
      assert(ids.includes('formfield/text-without-label.pug'))
    })

    it('should not infer variants if they are explicitely provided by variants attribute', async () => {
      const data = await Component.fetchById(state, 'label')

      assert.strictEqual(Object.keys(data.variants).length, 8)
      assert.strictEqual(data.variants[0].id, 'label/label.ejs-1')
      assert.strictEqual(data.variants[1].id, 'label/label.hbs-2')
      assert.strictEqual(data.variants[2].id, 'label/label.html-3')
      assert.strictEqual(data.variants[3].id, 'label/label.marko-4')
      assert.strictEqual(data.variants[4].id, 'label/label.pug-5')
      assert.strictEqual(data.variants[5].id, 'label/label.jsx-6')
      assert.strictEqual(data.variants[6].id, 'label/label.jsx-7')
      assert.strictEqual(data.variants[7].id, 'label/label.vue-8')
    })

    it('should render content from markdown', async () => {
      const data = await Component.fetchById(state, 'input')

      assert.strictEqual(data.content, '
An input field that can be used inside a form.
')
    })

    it('should return null if components source is not set', async () => {
      const data = await Component.fetchById({ config: { source: { } } }, 'input')

      assert.strictEqual(null, data)
    })

    it('should resolve title from attributes', async () => {
      const data = await Component.fetchById(state, 'input')

      assert.strictEqual('Inputs', data.title)
    })

    it('should resolve title from content heading if there is no title in attributes', async () => {
      const data = await Component.fetchById(state, 'formfield')

      assert.strictEqual('Formfields', data.title)
    })

    it('should resolve title from component id if there is no title in attributes or content', async () => {
      const data = await Component.fetchById(state, 'label')

      assert.strictEqual('Label', data.title)
    })

    it('should register component files and extract properties', async () => {
      const data = await Component.fetchById(state, 'label')
      const labelProps = data.properties['']

      assert(labelProps, 'React Label properties are not defined')

      assert.strictEqual(labelProps.title.type, 'String')
      assert.strictEqual(labelProps.title.required, true)
      assert.strictEqual(labelProps.for.type, 'String')
      assert.strictEqual(labelProps.for.required, true)
    })

    it('should register component files and extract dependencies', async () => {
      const data = await Component.fetchById(state, 'formfield')
      const { dependencies } = data

      assert(dependencies, 'Formfield dependencies are not defined')
      assert.strictEqual(dependencies.length, 2)
      assert(dependencies.includes('label'), 'Formfield dependencies do not include "label".')
      assert(dependencies.includes('input'), 'Formfield dependencies do not include "input".')
    })

    it('should register component files and extract dependents', async () => {
      const data = await Component.fetchById(state, 'label')
      const { dependentComponents, dependentTemplates } = data

      assert(dependentComponents, 'Dependent components for label are not defined')

      assert.strictEqual(dependentComponents.length, 2)
      assert(dependentComponents.includes('formfield'), 'Dependent components for label do not include "formfield".')
      assert(dependentComponents.includes('form'), 'Dependent components for label do not include "form".')

      assert(dependentTemplates, 'Dependent templates for label are not defined')
      assert.strictEqual(dependentTemplates.length, 1)
      assert(dependentTemplates.includes('page.pug'), 'Dependent templates for label do not include "page.pug".')
    })
  })

  describe('#fetchAll', () => {
    it('should return components object', async () => {
      const data = await Component.fetchAll(state)
      const componentIds = Object.keys(data)

      assert.strictEqual(componentIds.length, 4)
      assertComponent(componentIds, 'input')
      assertComponent(componentIds, 'label')
      assertComponent(componentIds, 'formfield')
      assertComponent(componentIds, 'form')
    })

    it('should return empty object if components source is not set', async () => {
      const data = await Component.fetchAll({ config: { source: { } } })
      const componentIds = Object.keys(data)

      assert.strictEqual(componentIds.length, 0)
    })
  })
})
<commit_msg>⏱ core: increase component test timeout<commit_after>const assert = require('assert')
const { removeSync } = require('fs-extra')
const { resolve } = require('path')
const Connector = require('../src/connector')

const { testProjectPath, testTmpPath } = require('../../../test/support/paths')
const { adapters } = require('./support/adapters')
const Component = require('../src/component')
const state = {
  config: {
    source: {
      components: [
        resolve(testProjectPath, 'src', 'elements'),
        resolve(testProjectPath, 'src', 'modules')
      ],
      templates: resolve(testProjectPath, 'src', 'templates'),
      data: resolve(__dirname, 'fixtures'),
      base: testProjectPath
    },
    themes: [
      {
        id: '_default',
        title: 'Default'
      }
    ],
    ui: {
      base: '/'
    },
    target: testTmpPath,
    adapters
  }
}

const assertComponent = (componentIds, componentId) => assert(componentIds.includes(componentId), `missing component "${componentId}"`)

describe('Component', () => {
  before(() => Connector.setup(state))
  afterEach(() => { removeSync(testTmpPath) })

  describe('#fetchById', function () {
    this.timeout(5000)

    it('should return component object', async () => {
      const data = await Component.fetchById(state, 'input')

      assert.strictEqual(data.id, 'input')
      assert.strictEqual(data.title, 'Inputs')
      assert.strictEqual(data.sourcePath, 'src/elements/input')
      assert.strictEqual(data.sourceFile, 'src/elements/input/component.config.js')
    })

    it('should return component object for components without component.config.js file', async () => {
      const data = await Component.fetchById(state, 'form')

      assert.strictEqual(data.id, 'form')
      assert.strictEqual(data.title, 'Form')
      assert.strictEqual(data.sourcePath, 'src/modules/form')
      assert.strictEqual(data.sourceFile, undefined)
    })

    it('should infer variants if they are not provided', async () => {
      const data = await Component.fetchById(state, 'formfield')
      const ids = data.variants.map(v => v.id.replace(/-\d$/, ''))

      assert.strictEqual(ids.length, 2)
      assert(ids.includes('formfield/text-with-label.pug'))
      assert(ids.includes('formfield/text-without-label.pug'))
    })

    it('should not infer variants if they are explicitely provided by variants attribute', async () => {
      const data = await Component.fetchById(state, 'label')

      assert.strictEqual(Object.keys(data.variants).length, 8)
      assert.strictEqual(data.variants[0].id, 'label/label.ejs-1')
      assert.strictEqual(data.variants[1].id, 'label/label.hbs-2')
      assert.strictEqual(data.variants[2].id, 'label/label.html-3')
      assert.strictEqual(data.variants[3].id, 'label/label.marko-4')
      assert.strictEqual(data.variants[4].id, 'label/label.pug-5')
      assert.strictEqual(data.variants[5].id, 'label/label.jsx-6')
      assert.strictEqual(data.variants[6].id, 'label/label.jsx-7')
      assert.strictEqual(data.variants[7].id, 'label/label.vue-8')
    })

    it('should render content from markdown', async () => {
      const data = await Component.fetchById(state, 'input')

      assert.strictEqual(data.content, '
An input field that can be used inside a form.
')
    })

    it('should return null if components source is not set', async () => {
      const data = await Component.fetchById({ config: { source: { } } }, 'input')

      assert.strictEqual(null, data)
    })

    it('should resolve title from attributes', async () => {
      const data = await Component.fetchById(state, 'input')

      assert.strictEqual('Inputs', data.title)
    })

    it('should resolve title from content heading if there is no title in attributes', async () => {
      const data = await Component.fetchById(state, 'formfield')

      assert.strictEqual('Formfields', data.title)
    })

    it('should resolve title from component id if there is no title in attributes or content', async () => {
      const data = await Component.fetchById(state, 'label')

      assert.strictEqual('Label', data.title)
    })

    it('should register component files and extract properties', async () => {
      const data = await Component.fetchById(state, 'label')
      const labelProps = data.properties['']

      assert(labelProps, 'React Label properties are not defined')

      assert.strictEqual(labelProps.title.type, 'String')
      assert.strictEqual(labelProps.title.required, true)
      assert.strictEqual(labelProps.for.type, 'String')
      assert.strictEqual(labelProps.for.required, true)
    })

    it('should register component files and extract dependencies', async () => {
      const data = await Component.fetchById(state, 'formfield')
      const { dependencies } = data

      assert(dependencies, 'Formfield dependencies are not defined')
      assert.strictEqual(dependencies.length, 2)
      assert(dependencies.includes('label'), 'Formfield dependencies do not include "label".')
      assert(dependencies.includes('input'), 'Formfield dependencies do not include "input".')
    })

    it('should register component files and extract dependents', async () => {
      const data = await Component.fetchById(state, 'label')
      const { dependentComponents, dependentTemplates } = data

      assert(dependentComponents, 'Dependent components for label are not defined')

      assert.strictEqual(dependentComponents.length, 2)
      assert(dependentComponents.includes('formfield'), 'Dependent components for label do not include "formfield".')
      assert(dependentComponents.includes('form'), 'Dependent components for label do not include "form".')

      assert(dependentTemplates, 'Dependent templates for label are not defined')
      assert.strictEqual(dependentTemplates.length, 1)
      assert(dependentTemplates.includes('page.pug'), 'Dependent templates for label do not include "page.pug".')
    })
  })

  describe('#fetchAll', function () {
    this.timeout(7500)

    it('should return components object', async () => {
      const data = await Component.fetchAll(state)
      const componentIds = Object.keys(data)

      assert.strictEqual(componentIds.length, 4)
      assertComponent(componentIds, 'input')
      assertComponent(componentIds, 'label')
      assertComponent(componentIds, 'formfield')
      assertComponent(componentIds, 'form')
    })

    it('should return empty object if components source is not set', async () => {
      const data = await Component.fetchAll({ config: { source: { } } })
      const componentIds = Object.keys(data)

      assert.strictEqual(componentIds.length, 0)
    })
  })
})
<|endoftext|>


<commit_before>/**
 * --------------------------------------------------------------------------
 * Licensed under MIT https://github.com/sitevision/envision/blob/master/LICENSE
 * --------------------------------------------------------------------------
 */

import jQuery from 'jquery';

const Dropdown = (($) => {
   const NAME = 'envDropdown';
   const NO_CONFLICT = $.fn[NAME];
   const ENV_DROPDOWN_OPEN = 'env-is-open';
   const TOGGLE_DROPDOWN = '[data-dropdown]';
   const ENV_DROPDOWN = '.env-dropdown';
   const ENV_CLICK_EVENT = 'click.env-dropdown';
   const ENV_KEYDOWN_EVENT = 'keydown.env-dropdown';
   const ENV_KEYUP_EVENT = 'keyup.env-dropdown';
   const ENV_DROPDOWN_MENU = '.env-dropdown__menu';
   const RIGHT_MOUSE_BUTTON = 2;
   const KEYS = {
      ESCAPE_KEY: 'Escape',
      ARROWDOWN: 'ArrowDown',
      ARROWUP: 'ArrowUp',
      SPACE: 32,
      TAB_KEY: 'Tab',
   };
   const REGEXP_KEYDOWN = new RegExp(
      `${KEYS.ARROWUP}|${KEYS.ARROWDOWN}|${KEYS.ESCAPE_KEY}`
   );

   class Dropdown {
      constructor(element) {
         this.el = element;
         this.$el = $(element);
         this._id = this.el.id;
      }

      toggle() {
         if (this.$el.hasClass(ENV_DROPDOWN_OPEN)) {
            this.hide();
         } else {
            this.show();
         }
      }

      show() {
         this.$el.addClass(ENV_DROPDOWN_OPEN);

         this.$el.find(TOGGLE_DROPDOWN).attr('aria-expanded', 'true');

         this._bindEvents();
      }

      hide() {
         this.$el.removeClass(ENV_DROPDOWN_OPEN);

         this.$el.find(TOGGLE_DROPDOWN).attr('aria-expanded', 'false');

         this._unbindEvents();
      }

      _bindEvents() {
         const ENV_CLICK = `${ENV_CLICK_EVENT}-${this.el.id}`;
         const ENV_KEYDOWN = `${ENV_KEYDOWN_EVENT}-${this.el.id}`;

         $(document)
            .off(ENV_CLICK)
            .on(ENV_CLICK, (event) => {
               if (!$(event.target).hasClass(ENV_DROPDOWN_MENU)) {
                  this.hide();
               }
            });

         this.$el.off(ENV_KEYDOWN).one(ENV_KEYDOWN, (event) => {
            if (event.key === KEYS.ESCAPE_KEY) {
               this.hide();
            }
         });
      }

      _unbindEvents() {
         $(document).off(`${ENV_CLICK_EVENT}-${this.el.id}`);
         this.$el.off(`${ENV_KEYDOWN_EVENT}-${this.el.id}`);
      }

      _selectMenuItem(event) {
         const $items = this.$el.find('.env-dropdown__item');

         if (!$items.length) {
            return;
         }

         let index = $items.index(event.target);

         if (event.key === KEYS.ARROWUP && index > 0) {
            index--;
         }

         if (event.key === KEYS.ARROWDOWN && index < $items.length - 1) {
            index++;
         }

         index = index === -1 ? 0 : index;

         $items[index].focus();
      }

      static KeydownHandler(event) {
         if (!REGEXP_KEYDOWN.test(event.key)) {
            return;
         }

         const isActive = $(this)
            .closest(ENV_DROPDOWN)
            .hasClass(ENV_DROPDOWN_OPEN);

         if (!isActive && event.key === KEYS.ESCAPE_KEY) {
            return;
         }

         event.preventDefault();
         event.stopPropagation();

         const getToggleButton = () =>
            this.matches(TOGGLE_DROPDOWN)
               ? this
               : $(this).closest(ENV_DROPDOWN).find(TOGGLE_DROPDOWN)[0];

         if (event.key === KEYS.ESCAPE_KEY) {
            Dropdown.clearMenus();
            getToggleButton().focus();

            return;
         }

         if (
            !isActive &&
            (event.key === KEYS.ARROWUP || event.key === KEYS.ARROWDOWN)
         ) {
            getToggleButton().click();
            return;
         }

         if (!isActive || event.which === KEYS.SPACE) {
            Dropdown.clearMenus();

            return;
         }

         const $this = $(this).closest(ENV_DROPDOWN);
         const data = $this.data('env.dropdown');

         data._selectMenuItem(event);
      }

      static clearMenus(event) {
         if (event) {
            if (
               event.button === RIGHT_MOUSE_BUTTON ||
               (event.type === 'keyup' && event.key !== KEYS.TAB_KEY)
            ) {
               return;
            }
         }

         const $toggles = $(TOGGLE_DROPDOWN);

         for (let i = 0, len = $toggles.length; i < len; i++) {
            const data = $($toggles[i])
               .closest(ENV_DROPDOWN)
               .data('env.dropdown');

            if (!data) {
               continue;
            }
            const dropdownMenu = data.$el.find(ENV_DROPDOWN_MENU)[0];

            if (event) {
               if (
                  event.originalEvent.path.includes(
                     document.documentElement.getElementsByClassName(
                        'env-dropdown env-is-open'
                     )[0]
                  )
               ) {
                  continue;
               }

               if (
                  event.type === 'keyup' &&
                  event.key === KEYS.TAB_KEY &&
                  dropdownMenu.contains(event.originalEvent.target)
               ) {
                  continue;
               }
            }

            data.hide();
         }
      }

      static _jQuery(config) {
         return this.each(function () {
            const $this = $(this);
            let data = $this.data('env.dropdown');

            if (!data) {
               data = new Dropdown(this);
               $this.data('env.dropdown', data);
            }

            if (typeof config === 'string') {
               const method = data[config];
               if (method === undefined) {
                  throw new Error(`No method named "${config}"`);
               }
               method.call(data);
               return;
            }

            data.toggle();
         });
      }
   }

   $.fn[NAME] = Dropdown._jQuery;
   $.fn[NAME].Constructor = Dropdown;
   $.fn[NAME].noConflict = () => {
      $.fn[NAME] = NO_CONFLICT;
      return Dropdown._jQuery;
   };

   $(document).on('click', TOGGLE_DROPDOWN, function (e) {
      e.preventDefault();

      const $this = $(this);
      const $target = $($this.data('target'));

      $target[NAME]();
   });

   $(document).on(ENV_KEYDOWN_EVENT, TOGGLE_DROPDOWN, Dropdown.KeydownHandler);

   $(document).on(
      ENV_KEYDOWN_EVENT,
      ENV_DROPDOWN_MENU,
      Dropdown.KeydownHandler
   );

   $(document).on(ENV_KEYUP_EVENT, Dropdown.clearMenus);

   return Dropdown;
})(jQuery);

export default Dropdown;
<commit_msg>env-13 code review<commit_after>/**
 * --------------------------------------------------------------------------
 * Licensed under MIT https://github.com/sitevision/envision/blob/master/LICENSE
 * --------------------------------------------------------------------------
 */

import jQuery from 'jquery';

const Dropdown = (($) => {
   const NAME = 'envDropdown';
   const NO_CONFLICT = $.fn[NAME];
   const ENV_DROPDOWN_OPEN = 'env-is-open';
   const TOGGLE_DROPDOWN = '[data-dropdown]';
   const ENV_DROPDOWN = '.env-dropdown';
   const ENV_CLICK_EVENT = 'click.env-dropdown';
   const ENV_KEYDOWN_EVENT = 'keydown.env-dropdown';
   const ENV_KEYUP_EVENT = 'keyup.env-dropdown';
   const ENV_DROPDOWN_MENU = '.env-dropdown__menu';
   const RIGHT_MOUSE_BUTTON = 2;
   const KEYS = {
      ESCAPE_KEY: 'Escape',
      ARROWDOWN: 'ArrowDown',
      ARROWUP: 'ArrowUp',
      SPACE: 32,
      TAB_KEY: 'Tab',
   };
   const REGEXP_KEYDOWN = new RegExp(
      `${KEYS.ARROWUP}|${KEYS.ARROWDOWN}|${KEYS.ESCAPE_KEY}`
   );

   class Dropdown {
      constructor(element) {
         this.el = element;
         this.$el = $(element);
         this._id = this.el.id;
      }

      toggle() {
         if (this.$el.hasClass(ENV_DROPDOWN_OPEN)) {
            this.hide();
         } else {
            this.show();
         }
      }

      show() {
         this.$el.addClass(ENV_DROPDOWN_OPEN);

         this.$el.find(TOGGLE_DROPDOWN).attr('aria-expanded', 'true');

         this._bindEvents();
      }

      hide() {
         this.$el.removeClass(ENV_DROPDOWN_OPEN);

         this.$el.find(TOGGLE_DROPDOWN).attr('aria-expanded', 'false');

         this._unbindEvents();
      }

      _bindEvents() {
         const ENV_CLICK = `${ENV_CLICK_EVENT}-${this.el.id}`;
         const ENV_KEYDOWN = `${ENV_KEYDOWN_EVENT}-${this.el.id}`;

         $(document)
            .off(ENV_CLICK)
            .on(ENV_CLICK, (event) => {
               if (!$(event.target).hasClass(ENV_DROPDOWN_MENU)) {
                  this.hide();
               }
            });

         this.$el.off(ENV_KEYDOWN).one(ENV_KEYDOWN, (event) => {
            if (event.key === KEYS.ESCAPE_KEY) {
               this.hide();
            }
         });
      }

      _unbindEvents() {
         $(document).off(`${ENV_CLICK_EVENT}-${this.el.id}`);
         this.$el.off(`${ENV_KEYDOWN_EVENT}-${this.el.id}`);
      }

      static _jQuery(config) {
         return this.each(function () {
            const $this = $(this);
            let data = $this.data('env.dropdown');

            if (!data) {
               data = new Dropdown(this);
               $this.data('env.dropdown', data);
            }

            if (typeof config === 'string') {
               const method = data[config];
               if (method === undefined) {
                  throw new Error(`No method named "${config}"`);
               }
               method.call(data);
               return;
            }

            data.toggle();
         });
      }
   }

   function selectMenuItem(event, $items) {
      if (!$items.length) {
         return;
      }

      let index = $items.index(event.target);

      if (event.key === KEYS.ARROWUP && index > 0) {
         index--;
      }

      if (event.key === KEYS.ARROWDOWN && index < $items.length - 1) {
         index++;
      }

      index = index === -1 ? 0 : index;

      $items[index].focus();
   }

   function clearMenus(event) {
      if (event) {
         if (
            event.button === RIGHT_MOUSE_BUTTON ||
            (event.type === 'keyup' && event.key !== KEYS.TAB_KEY)
         ) {
            return;
         }
      }

      const $toggles = $(TOGGLE_DROPDOWN);

      for (let i = 0, len = $toggles.length; i < len; i++) {
         const data = $($toggles[i]).closest(ENV_DROPDOWN).data('env.dropdown');

         if (!data) {
            continue;
         }
         const dropdownMenu = data.$el.find(ENV_DROPDOWN_MENU)[0];

         if (event) {
            if (
               event.originalEvent.path.includes(
                  document.documentElement.getElementsByClassName(
                     'env-dropdown env-is-open'
                  )[0]
               )
            ) {
               continue;
            }

            if (
               event.type === 'keyup' &&
               event.key === KEYS.TAB_KEY &&
               dropdownMenu.contains(event.originalEvent.target)
            ) {
               continue;
            }
         }

         data.hide();
      }
   }

   function KeydownHandler(event) {
      if (!REGEXP_KEYDOWN.test(event.key)) {
         return;
      }

      const isActive = $(this)
         .closest(ENV_DROPDOWN)
         .hasClass(ENV_DROPDOWN_OPEN);

      if (!isActive && event.key === KEYS.ESCAPE_KEY) {
         return;
      }

      event.preventDefault();
      event.stopPropagation();

      const getToggleButton = () =>
         this.matches(TOGGLE_DROPDOWN)
            ? this
            : $(this).closest(ENV_DROPDOWN).find(TOGGLE_DROPDOWN)[0];

      if (event.key === KEYS.ESCAPE_KEY) {
         clearMenus();
         getToggleButton().focus();

         return;
      }

      if (
         !isActive &&
         (event.key === KEYS.ARROWUP || event.key === KEYS.ARROWDOWN)
      ) {
         getToggleButton().click();
         return;
      }

      if (!isActive || event.which === KEYS.SPACE) {
         clearMenus();

         return;
      }

      const $dropdown = $(this).closest(ENV_DROPDOWN);

      selectMenuItem(event, $dropdown.find('.env-dropdown__item'));
   }

   $.fn[NAME] = Dropdown._jQuery;
   $.fn[NAME].Constructor = Dropdown;
   $.fn[NAME].noConflict = () => {
      $.fn[NAME] = NO_CONFLICT;
      return Dropdown._jQuery;
   };

   $(document).on('click', TOGGLE_DROPDOWN, function (e) {
      e.preventDefault();

      const $this = $(this);
      const $target = $($this.data('target'));

      $target[NAME]();
   });

   $(document).on(ENV_KEYDOWN_EVENT, TOGGLE_DROPDOWN, KeydownHandler);

   $(document).on(ENV_KEYDOWN_EVENT, ENV_DROPDOWN_MENU, KeydownHandler);

   $(document).on(ENV_KEYUP_EVENT, clearMenus);

   return Dropdown;
})(jQuery);

export default Dropdown;
<|endoftext|>


<commit_before>import React from 'react';
import { formValueSelector, FormSection } from 'redux-form';
import PropTypes from 'prop-types';
import Grid from 'material-ui/Grid';
import { connect } from 'react-redux';
import RadioForm from '../../../forms/radioForm';
import TextFieldForm from '../../../forms/textFieldForm';
import ArrayForm from '../../../forms/arrayForm';
import { visibleIfYes, BOOL_VAL } from '../../../../helpers/formHelper';
import GridRow from '../../../common/grid/gridRow';
import GridColumn from '../../../common/grid/gridColumn';

const messages = {
  boardOfDirectors: 'Does your organization have a board of director(s)?',
  authorisedOfficers: 'Does your organization have a authorised officer(s)?',
  directos: 'Board of Director(s)',
  officers: 'Authorised Officer(s)',
};

const directorForm = (director, readOnly) => (
  <GridColumn>
    <GridRow columns={3}>
      <TextFieldForm
        fieldName={`${director}.fullname`}
        label="Full Name"
        warn
        readOnly={readOnly}
      />
      <TextFieldForm
        fieldName={`${director}.job_title`}
        label="Job Title/Position"
        warn
        readOnly={readOnly}
      />
      <RadioForm
        fieldName={`${director}.authorized`}
        values={BOOL_VAL}
        warn
        label="Authorised Officer?"
        readOnly={readOnly}
      />
    </GridRow>
    <GridRow columns={3}>
      <TextFieldForm
        fieldName={`${director}.telephone`}
        label="Telephone"
        warn
        readOnly={readOnly}
      />
      <TextFieldForm
        fieldName={`${director}.fax`}
        label="Fax (optional)"
        optional
        readOnly={readOnly}
      />
      <TextFieldForm
        fieldName={`${director}.email`}
        label="Email"
        warn
        readOnly={readOnly}
      />
    </GridRow>
  </GridColumn>
);

const authorisedOfficerForm = (officer, readOnly) => (
  <GridColumn>
    <GridRow columns={3}>
      <TextFieldForm
        fieldName={`${officer}.fullname`}
        label="Full Name"
        warn
        readOnly={readOnly}
      />
      <TextFieldForm
        fieldName={`${officer}.job_title`}
        label="Job Title/Position"
        warn
        readOnly={readOnly}
      />
    </GridRow>
    <GridRow columns={3}>
      <TextFieldForm
        fieldName={`${officer}.telephone`}
        label="Telephone"
        warn
        readOnly={readOnly}
      />
      <TextFieldForm
        fieldName={`${officer}.fax`}
        label="Fax (optional)"
        optional
        readOnly={readOnly}
      />
      <TextFieldForm
        fieldName={`${officer}.email`}
        label="Email"
        warn
        readOnly={readOnly}
      />
    </GridRow>
  </GridColumn>
);

const PartnerProfileContactInfoOfficials = (props) => {
  const { readOnly, hasBoardOfDirectors, hasAuthorisedOfficers } = props;

  return (<FormSection name="authorised_officials">
    <GridColumn>
      <RadioForm
        label={messages.boardOfDirectors}
        fieldName="have_board_directors"
        values={BOOL_VAL}
        warn
        readOnly={readOnly}
      />
      {visibleIfYes(hasBoardOfDirectors)
        ? <ArrayForm
          limit={15}
          initial
          label={messages.directos}
          fieldName="directors"
          outerField={director => directorForm(director, readOnly)}
          readOnly={readOnly}
        />
        : null}
      <RadioForm
        label={messages.authorisedOfficers}
        fieldName="have_authorised_officers"
        values={BOOL_VAL}
        warn
        readOnly={readOnly}
      />

      {visibleIfYes(hasAuthorisedOfficers) ?
        <ArrayForm
          limit={15}
          initial
          label={messages.officers}
          fieldName="authorised_officers"
          outerField={officer => authorisedOfficerForm(officer, readOnly)}
          readOnly={readOnly}
        />
        : null}
    </GridColumn>
  </FormSection>
  );
};

PartnerProfileContactInfoOfficials.propTypes = {
  readOnly: PropTypes.bool,
  hasBoardOfDirectors: PropTypes.bool,
  hasAuthorisedOfficers: PropTypes.bool,
};

const selector = formValueSelector('partnerProfile');
export default connect(
  state => ({
    hasBoardOfDirectors: selector(state, 'mailing.authorised_officials.have_board_directors'),
    hasAuthorisedOfficers: selector(state, 'mailing.authorised_officials.have_authorised_officers'),
  }),
)(PartnerProfileContactInfoOfficials);
<commit_msg>label change<commit_after>import React from 'react';
import { formValueSelector, FormSection } from 'redux-form';
import PropTypes from 'prop-types';
import Grid from 'material-ui/Grid';
import { connect } from 'react-redux';
import RadioForm from '../../../forms/radioForm';
import TextFieldForm from '../../../forms/textFieldForm';
import ArrayForm from '../../../forms/arrayForm';
import { visibleIfYes, BOOL_VAL } from '../../../../helpers/formHelper';
import GridRow from '../../../common/grid/gridRow';
import GridColumn from '../../../common/grid/gridColumn';

const messages = {
  boardOfDirectors: 'Does your organization have a board of director(s)?',
  authorisedOfficers: 'Does your organization have any other authorized officers who are not listed above?',
  directos: 'Board of Director(s)',
  officers: 'Authorised Officer(s)',
};

const directorForm = (director, readOnly) => (
  <GridColumn>
    <GridRow columns={3}>
      <TextFieldForm
        fieldName={`${director}.fullname`}
        label="Full Name"
        warn
        readOnly={readOnly}
      />
      <TextFieldForm
        fieldName={`${director}.job_title`}
        label="Job Title/Position"
        warn
        readOnly={readOnly}
      />
      <RadioForm
        fieldName={`${director}.authorized`}
        values={BOOL_VAL}
        warn
        label="Authorised Officer?"
        readOnly={readOnly}
      />
    </GridRow>
    <GridRow columns={3}>
      <TextFieldForm
        fieldName={`${director}.telephone`}
        label="Telephone"
        warn
        readOnly={readOnly}
      />
      <TextFieldForm
        fieldName={`${director}.fax`}
        label="Fax (optional)"
        optional
        readOnly={readOnly}
      />
      <TextFieldForm
        fieldName={`${director}.email`}
        label="Email"
        warn
        readOnly={readOnly}
      />
    </GridRow>
  </GridColumn>
);

const authorisedOfficerForm = (officer, readOnly) => (
  <GridColumn>
    <GridRow columns={3}>
      <TextFieldForm
        fieldName={`${officer}.fullname`}
        label="Full Name"
        warn
        readOnly={readOnly}
      />
      <TextFieldForm
        fieldName={`${officer}.job_title`}
        label="Job Title/Position"
        warn
        readOnly={readOnly}
      />
    </GridRow>
    <GridRow columns={3}>
      <TextFieldForm
        fieldName={`${officer}.telephone`}
        label="Telephone"
        warn
        readOnly={readOnly}
      />
      <TextFieldForm
        fieldName={`${officer}.fax`}
        label="Fax (optional)"
        optional
        readOnly={readOnly}
      />
      <TextFieldForm
        fieldName={`${officer}.email`}
        label="Email"
        warn
        readOnly={readOnly}
      />
    </GridRow>
  </GridColumn>
);

const PartnerProfileContactInfoOfficials = (props) => {
  const { readOnly, hasBoardOfDirectors, hasAuthorisedOfficers } = props;

  return (<FormSection name="authorised_officials">
    <GridColumn>
      <RadioForm
        label={messages.boardOfDirectors}
        fieldName="have_board_directors"
        values={BOOL_VAL}
        warn
        readOnly={readOnly}
      />
      {visibleIfYes(hasBoardOfDirectors)
        ? <ArrayForm
          limit={15}
          initial
          label={messages.directos}
          fieldName="directors"
          outerField={director => directorForm(director, readOnly)}
          readOnly={readOnly}
        />
        : null}
      <RadioForm
        label={messages.authorisedOfficers}
        fieldName="have_authorised_officers"
        values={BOOL_VAL}
        warn
        readOnly={readOnly}
      />

      {visibleIfYes(hasAuthorisedOfficers) ?
        <ArrayForm
          limit={15}
          initial
          label={messages.officers}
          fieldName="authorised_officers"
          outerField={officer => authorisedOfficerForm(officer, readOnly)}
          readOnly={readOnly}
        />
        : null}
    </GridColumn>
  </FormSection>
  );
};

PartnerProfileContactInfoOfficials.propTypes = {
  readOnly: PropTypes.bool,
  hasBoardOfDirectors: PropTypes.bool,
  hasAuthorisedOfficers: PropTypes.bool,
};

const selector = formValueSelector('partnerProfile');
export default connect(
  state => ({
    hasBoardOfDirectors: selector(state, 'mailing.authorised_officials.have_board_directors'),
    hasAuthorisedOfficers: selector(state, 'mailing.authorised_officials.have_authorised_officers'),
  }),
)(PartnerProfileContactInfoOfficials);
<|endoftext|>


<commit_before>
/**
 * @fileoverview This file contains QUnit tests for a TabData object.
 * @author dld@google.com (DrakeDiedrich)
 *
 * Copyright 2013 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

test('TabData.deleteRequest', function() {
  var t = new TabData();

  var data = { requestId:1, timestamp:1000, url: 'http://host/' };
  t.startRequest(data);
  data.timestamp = 1001;
  t.deleteRequest(data);

  equal(t.stat.count('request'), 0, 'deleteRequest left 0 recorded requests');
});

test('TabData.endRequest', function() {
  var t = new TabData();

  var data = { requestId:1, timestamp:1000, url: 'http://host/' };
  t.startRequest(data);
  data.timestamp = 1001;
  t.endRequest(data);

  equal(t.stat.count('request'), 1, 'endRequest left 1 recorded requests');
});

test('TabData.tabUpdated', function() {
  var t = new TabData();

  var tab = {
    status: 'loading',
    url: 'http://server/path',
    tabId: 1,
  };
  var changeInfo = {};
  t.tabUpdated(changeInfo, tab);
  tab.status = 'complete';
  t.tabUpdated(changeInfo, tab);

  equal(t.stat.count('tabupdate'), 1, 'tabUpdated left 1 recorded tabupdate');
});

test('TabData.startNavigation', function() {
  var t = new TabData();

  var data = { frameId:0, parentFrameId:-1, processId:2999, tabId:30,
	       timeStamp:1000, url:'http://host/' };
  t.startNavigation(data);

  equal(t.navigation.frameId, 0, 'frameId');
});

test('TabData.endNavigation', function() {
  var t = new TabData();

  var data = { frameId:0, parentFrameId:-1, processId:2999, tabId:30,
	       timeStamp:1000, url:'http://host/' };
  t.startNavigation(data);
  delete data['parentFrameId'];
  data.timestamp = 1001;
  t.endNavigation(data);

  equal(t.stat.count('navigation'), 1, 'endNavigation left 1 recorded requests');
  equal(t.service, '.', "TabData.service == '.'");
});

<commit_msg>Fully qualify test URLs to avoid conflicts with local unqualified hostname rules<commit_after>
/**
 * @fileoverview This file contains QUnit tests for a TabData object.
 * @author dld@google.com (DrakeDiedrich)
 *
 * Copyright 2013 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

test('TabData.deleteRequest', function() {
  var t = new TabData();

  var data = { requestId:1, timestamp:1000, url: 'http://host.example.com/' };
  t.startRequest(data);
  data.timestamp = 1001;
  t.deleteRequest(data);

  equal(t.stat.count('request'), 0, 'deleteRequest left 0 recorded requests');
});

test('TabData.endRequest', function() {
  var t = new TabData();

  var data = { requestId:1, timestamp:1000, url: 'http://host.example.com/' };
  t.startRequest(data);
  data.timestamp = 1001;
  t.endRequest(data);

  equal(t.stat.count('request'), 1, 'endRequest left 1 recorded requests');
});

test('TabData.tabUpdated', function() {
  var t = new TabData();

  var tab = {
    status: 'loading',
    url: 'http://server/path',
    tabId: 1,
  };
  var changeInfo = {};
  t.tabUpdated(changeInfo, tab);
  tab.status = 'complete';
  t.tabUpdated(changeInfo, tab);

  equal(t.stat.count('tabupdate'), 1, 'tabUpdated left 1 recorded tabupdate');
});

test('TabData.startNavigation', function() {
  var t = new TabData();

  var data = { frameId:0, parentFrameId:-1, processId:2999, tabId:30,
	       timeStamp:1000, url:'http://host.example.com/' };
  t.startNavigation(data);

  equal(t.navigation.frameId, 0, 'frameId');
});

test('TabData.endNavigation', function() {
  var t = new TabData();

  var data = { frameId:0, parentFrameId:-1, processId:2999, tabId:30,
	       timeStamp:1000, url:'http://host.example.com/' };
  t.startNavigation(data);
  delete data['parentFrameId'];
  data.timestamp = 1001;
  t.endNavigation(data);

  equal(t.stat.count('navigation'), 1, 'endNavigation left 1 recorded requests');
  equal(t.service, '.', "TabData.service == '.'");
});

<|endoftext|>


<commit_before>Package.describe({
  summary: 'Blaze configuration templates for GitHub OAuth.',
  version: '1.0.0-beta.1'
});

Package.onUse(function (api) {
  api.use('templating@1.2.13', 'client');
  api.addFiles('github_login_button.css', 'client');
  api.addFiles(
    ['github_configure.html', 'github_configure.js'],
    'client'
  );
});
<commit_msg>Removed beta.1 version suffix.<commit_after>Package.describe({
  summary: 'Blaze configuration templates for GitHub OAuth.',
  version: '1.0.0'
});

Package.onUse(function (api) {
  api.use('templating@1.2.13', 'client');
  api.addFiles('github_login_button.css', 'client');
  api.addFiles(
    ['github_configure.html', 'github_configure.js'],
    'client'
  );
});
<|endoftext|>


<commit_before>'use strict'

const Mongodb = require('mongodb')
const ObjectID = Mongodb.ObjectID
const MongoStore = require('./store')
const StorePattern = require('hemera-store/pattern')
const serialize = require('mongodb-extended-json').serialize
const deserialize = require('mongodb-extended-json').deserialize

exports.plugin = function hemeraMongoStore (options, next) {
  const hemera = this
  const topic = 'mongo-store'
  const preResponseHandler = (result) => {
    if (options.serializeResult === true) {
      return serialize(result)
    }
    return result
  }

  Mongodb.MongoClient.connect(options.mongo.url, options.mongos.options, function (err, db) {
    if (err) {
      return hemera.emit('error', err)
    }

    hemera.expose('db', db)
    hemera.expose('mongodb', Mongodb)

    hemera.add({
      topic,
      cmd: 'dropCollection'
    }, function (req, cb) {
      const collection = db.collection(req.collection)
      collection.drop(cb)
    })

    hemera.add(StorePattern.create(topic), function (req, cb) {
      const collection = db.collection(req.collection)
      const store = new MongoStore(collection)
      store.ObjectID = ObjectID
      req.data = deserialize(req.data)

      store.create(req, cb)
    })

    hemera.add(StorePattern.update(topic), function (req, cb) {
      const collection = db.collection(req.collection)
      const store = new MongoStore(collection)
      store.ObjectID = ObjectID
      req.query = deserialize(req.query)

      store.update(req, deserialize(req.data), (err, result) => {
        if (err) {
          cb(err)
        } else {
          cb(err, preResponseHandler(result))
        }
      })
    })

    hemera.add(StorePattern.updateById(topic), function (req, cb) {
      const collection = db.collection(req.collection)
      const store = new MongoStore(collection)
      store.ObjectID = ObjectID

      store.updateById(req, deserialize(req.data), (err, result) => {
        if (err) {
          cb(err)
        } else {
          cb(err, preResponseHandler(result))
        }
      })
    })

    hemera.add(StorePattern.remove(topic), function (req, cb) {
      const collection = db.collection(req.collection)
      const store = new MongoStore(collection)
      store.ObjectID = ObjectID
      req.query = deserialize(req.query)

      store.remove(req, cb)
    })

    hemera.add(StorePattern.removeById(topic), function (req, cb) {
      const collection = db.collection(req.collection)
      const store = new MongoStore(collection)
      store.ObjectID = ObjectID

      store.removeById(req, (err, result) => {
        if (err) {
          cb(err)
        } else {
          cb(err, preResponseHandler(result))
        }
      })
    })

    hemera.add(StorePattern.replace(topic), function (req, cb) {
      const collection = db.collection(req.collection)
      const store = new MongoStore(collection)
      store.ObjectID = ObjectID
      req.query = deserialize(req.query)

      store.replace(req, deserialize(req.data), cb)
    })

    hemera.add(StorePattern.replaceById(topic), function (req, cb) {
      const collection = db.collection(req.collection)
      const store = new MongoStore(collection)
      store.ObjectID = ObjectID

      store.replaceById(req, deserialize(req.data), (err, result) => {
        if (err) {
          cb(err)
        } else {
          cb(err, preResponseHandler(result))
        }
      })
    })

    hemera.add(StorePattern.findById(topic), function (req, cb) {
      const collection = db.collection(req.collection)
      const store = new MongoStore(collection)
      store.ObjectID = ObjectID

      store.findById(req, (err, result) => {
        if (err) {
          cb(err)
        } else {
          cb(err, preResponseHandler(result))
        }
      })
    })

    hemera.add(StorePattern.find(topic), function (req, cb) {
      const collection = db.collection(req.collection)
      const store = new MongoStore(collection)
      store.ObjectID = ObjectID
      req.query = deserialize(req.query)

      store.find(req, req.options, (err, result) => {
        if (err) {
          cb(err)
        } else {
          cb(err, preResponseHandler(result))
        }
      })
    })

    hemera.log.debug('DB connected!')
    next()
  })
}

exports.options = {
  mongos: {},
  mongo: {
    url: 'mongodb://localhost:27017/'
  }
}

exports.attributes = {
  pkg: require('./package.json')
}
<commit_msg>Ensure success callback passed null error<commit_after>'use strict'

const Mongodb = require('mongodb')
const ObjectID = Mongodb.ObjectID
const MongoStore = require('./store')
const StorePattern = require('hemera-store/pattern')
const serialize = require('mongodb-extended-json').serialize
const deserialize = require('mongodb-extended-json').deserialize

exports.plugin = function hemeraMongoStore (options, next) {
  const hemera = this
  const topic = 'mongo-store'
  const preResponseHandler = (result) => {
    if (options.serializeResult === true) {
      return serialize(result)
    }
    return result
  }

  Mongodb.MongoClient.connect(options.mongo.url, options.mongos.options, function (err, db) {
    if (err) {
      return hemera.emit('error', err)
    }

    hemera.expose('db', db)
    hemera.expose('mongodb', Mongodb)

    hemera.add({
      topic,
      cmd: 'dropCollection'
    }, function (req, cb) {
      const collection = db.collection(req.collection)
      collection.drop(cb)
    })

    hemera.add(StorePattern.create(topic), function (req, cb) {
      const collection = db.collection(req.collection)
      const store = new MongoStore(collection)
      store.ObjectID = ObjectID
      req.data = deserialize(req.data)

      store.create(req, cb)
    })

    hemera.add(StorePattern.update(topic), function (req, cb) {
      const collection = db.collection(req.collection)
      const store = new MongoStore(collection)
      store.ObjectID = ObjectID
      req.query = deserialize(req.query)

      store.update(req, deserialize(req.data), (err, result) => {
        if (err) {
          cb(err)
        } else {
          cb(null, preResponseHandler(result))
        }
      })
    })

    hemera.add(StorePattern.updateById(topic), function (req, cb) {
      const collection = db.collection(req.collection)
      const store = new MongoStore(collection)
      store.ObjectID = ObjectID

      store.updateById(req, deserialize(req.data), (err, result) => {
        if (err) {
          cb(err)
        } else {
          cb(null, preResponseHandler(result))
        }
      })
    })

    hemera.add(StorePattern.remove(topic), function (req, cb) {
      const collection = db.collection(req.collection)
      const store = new MongoStore(collection)
      store.ObjectID = ObjectID
      req.query = deserialize(req.query)

      store.remove(req, cb)
    })

    hemera.add(StorePattern.removeById(topic), function (req, cb) {
      const collection = db.collection(req.collection)
      const store = new MongoStore(collection)
      store.ObjectID = ObjectID

      store.removeById(req, (err, result) => {
        if (err) {
          cb(err)
        } else {
          cb(null, preResponseHandler(result))
        }
      })
    })

    hemera.add(StorePattern.replace(topic), function (req, cb) {
      const collection = db.collection(req.collection)
      const store = new MongoStore(collection)
      store.ObjectID = ObjectID
      req.query = deserialize(req.query)

      store.replace(req, deserialize(req.data), cb)
    })

    hemera.add(StorePattern.replaceById(topic), function (req, cb) {
      const collection = db.collection(req.collection)
      const store = new MongoStore(collection)
      store.ObjectID = ObjectID

      store.replaceById(req, deserialize(req.data), (err, result) => {
        if (err) {
          cb(err)
        } else {
          cb(null, preResponseHandler(result))
        }
      })
    })

    hemera.add(StorePattern.findById(topic), function (req, cb) {
      const collection = db.collection(req.collection)
      const store = new MongoStore(collection)
      store.ObjectID = ObjectID

      store.findById(req, (err, result) => {
        if (err) {
          cb(err)
        } else {
          cb(null, preResponseHandler(result))
        }
      })
    })

    hemera.add(StorePattern.find(topic), function (req, cb) {
      const collection = db.collection(req.collection)
      const store = new MongoStore(collection)
      store.ObjectID = ObjectID
      req.query = deserialize(req.query)

      store.find(req, req.options, (err, result) => {
        if (err) {
          cb(err)
        } else {
          cb(null, preResponseHandler(result))
        }
      })
    })

    hemera.log.debug('DB connected!')
    next()
  })
}

exports.options = {
  mongos: {},
  mongo: {
    url: 'mongodb://localhost:27017/'
  }
}

exports.attributes = {
  pkg: require('./package.json')
}
<|endoftext|>


<commit_before>const fs = require('fs-extra');
const inquirer = require('inquirer');
exports.command = 'clean';
exports.description = 'Remove .idyll folder';

const PATH = './.idyll';

exports.handler = async _ => {
  try {
    let isTokenExists = await checkIfTokenExists();
    if (isTokenExists) {
      let userAnswer = await confirmClean();
      if (userAnswer === 'Yes') {
        removeIdyll();
      }
    } else {
      removeIdyll();
    }
  } catch (e) {
    console.log(e);
  }
};

checkIfTokenExists = _ => {
  return fs.pathExists(`${PATH}/token`);
};

confirmClean = async _ => {
  const userResponse = await inquirer.prompt([
    {
      type: 'list',
      name: 'confirmClean',
      message: `This command will remove the idyll cache folder, including your idyll.pub token.
      Subsequent deploys to idyll.pub will receive a new URL.
      Are you sure you wish to continue?`,
      choices: ['Yes', 'No']
    }
  ]);
  return userResponse.confirmClean;
};

removeIdyll = _ => {
  fs.remove(PATH, err => {
    if (err) return console.error(err);
  });
};
<commit_msg>change conifrmClean fn name to confirm<commit_after>const fs = require('fs-extra');
const inquirer = require('inquirer');
exports.command = 'clean';
exports.description = 'Remove .idyll folder';

const PATH = './.idyll';

exports.handler = async _ => {
  try {
    let isTokenExists = await checkIfTokenExists();
    if (isTokenExists) {
      let userAnswer = await confirm();
      if (userAnswer === 'Yes') {
        removeIdyll();
      }
    } else {
      removeIdyll();
    }
  } catch (e) {
    console.log(e);
  }
};

checkIfTokenExists = _ => {
  return fs.pathExists(`${PATH}/token`);
};

confirm = async _ => {
  const userResponse = await inquirer.prompt([
    {
      type: 'list',
      name: 'confirm',
      message: `This command will remove the idyll cache folder, including your idyll.pub token.
      Subsequent deploys to idyll.pub will receive a new URL.
      Are you sure you wish to continue?`,
      choices: ['Yes', 'No']
    }
  ]);
  return userResponse.confirm;
};

removeIdyll = _ => {
  fs.remove(PATH, err => {
    if (err) return console.error(err);
  });
};
<|endoftext|>


<commit_before>import typescript from '@rollup/plugin-typescript';
import { minify } from "terser";
import path from 'path';
import fs from 'fs';
import pkg from "./package.json";
import {builtinModules} from "module";
import dts from "rollup-plugin-dts";

var globals = {
	'jquery': '$',
	'flatpickr': 'flatpickr'
}

function normalizePath(fileName) {
    return fileName.split(path.win32.sep).join(path.posix.sep);
}

var outputs = [];

var rxNamespace = /^namespace\s?/;
var rxExport = /^export\s?/;
var rxDeclare = /^declare\s?/;
var rxDeclareGlobal = /^(declare\s+global.*\s*\{\r?\n)((^\s+.*\r?\n)*)?\}/gm;
var rxRemoveExports = /^export\s*\{[^\}]*\}\s*\;\s*\r?\n/gm;
var rxReferenceTypes = /^\/\/\/\s*\<reference\s*types\=\".*\r?\n/gm

var toGlobal = function(ns) {
	return {
		name: 'toGlobal',
		generateBundle(o, b) {
			for (var fileName of Object.keys(b)) {
				if (b[fileName].code && fileName.indexOf('.bundle.d.ts') >= 0) {
					var src = b[fileName].code;
					src = src.replace('\r', '');
					src = src.replace(rxRemoveExports, '');

					var refTypes = [];
					src = src.replace(rxReferenceTypes, function(match, offset, str) {
						refTypes.push(match);
						return '';
					});

					var globals = [];
					src = src.replace(rxDeclareGlobal, function(x, y, m1) {
						var g = m1.replace(/(\r?\n)*$/, '').split('\n')
							.map(s => s.length > 0 && s.charAt(0) == '\t' ? s.substring(1) : (s.substring(0, 4) == '    ' ? s.substring(4) : s))
							.map(s => {
								if (rxNamespace.test(s))
									return ("declare " + s);
								else if (rxExport.test(s))
									return "declare " + s.substring(7);
								else
									return s;
							})
							.join('\n');
						globals.push(g);
						return '';
					});

					if (ns) {
						src = 'declare namespace ' + ns + ' {\n' +
							src.replace(/(\r?\n)*$/, '').split('\n').map(s => {
								if (!s.length)
									return '';
								if (rxDeclare.test(s))
									return '    ' + s.substring(8);
								else
									return '    ' + s;
							}).join('\n') + '\n}'
					}

					src = refTypes.join('') + '\n' + src + '\n' + globals.join('\n');

					outputs.push(src);

					var toEmit = {
						type: 'asset',
						fileName: fileName.replace('.bundle.d.ts', '.global.d.ts'),
						source: src
					};
					this.emitFile(toEmit);
				}
			}
		}
	}
}

var extendGlobals = function() {
	return {
		name: 'extendGlobals',
		generateBundle(o, b) {
			for (var fileName of Object.keys(b)) {
				var code = b[fileName].code || b[fileName].source;

				if (code && fileName.indexOf('.js') >= 0) {
					var src = code;
					src = src.replace(/^(\s*)exports\.([A-Za-z_]+)\s*=\s*(.+?);/gm, function(match, grp1, grp2, grp3) {
						if (grp2.charAt(0) == '_' && grp2.charAt(1) == '_')
							return grp1 + "exports." + grp2 + " = exports." + grp2 + " || " + grp3 + ";";
						return grp1 + "exports." + grp2 + " = exports." + grp2 + " || {}; extend(exports." + grp2 + ", " + grp3 + ");";
					});
					b[fileName].code = src;
				}
				else if (code && /(Globals\/.*|Globals)\.d\.ts$/i.test(fileName) && code.indexOf('declare global') < 0) {
					outputs.push(code);
				}
			}
		}
	}
}

var writeMinJS = function() {
	return {
		name: 'writeMinJS',
		generateBundle: async function(o, b) {
			var self = this;
			Object.keys(b).forEach(async function(fileName) {
				if (b[fileName].code && /\.js$/i.test(fileName) >= 0) {
					var src = b[fileName].code;
					var minified = await minify(src, {
						mangle: true,
						format: {
							beautify: false,
							max_line_len: 1000
						}
					});
					var toEmit = {
						type: 'asset',
						fileName: fileName.replace(/\.js$/, '.min.js'),
						source: minified.code
					};
					self.emitFile(toEmit);
				}
			});
		}
	}
}

export default [
	{
		input: "CoreLib/CoreLib.ts",
		output: [
			{
				file: 'dist/Serenity.CoreLib.js',
				format: "iife",
				sourcemap: true,
				name: "window",
				extend: true,
				freeze: false,
				globals
			}
		],
		plugins: [
			typescript({
				tsconfig: 'CoreLib/tsconfig.json',
				outDir: 'CoreLib/built'
			}),
			extendGlobals(),
			writeMinJS()
		],
		external: [
			...builtinModules,
			...(pkg.dependencies == null ? [] : Object.keys(pkg.dependencies)),
			...(pkg.devDependencies == null ? [] : Object.keys(pkg.devDependencies)),
			...(pkg.peerDependencies == null ? [] : Object.keys(pkg.peerDependencies))
		]
	},
	{
		input: "./dist/built/Q/indexAll.d.ts",
		output: [{ file: "./dist/built/Q/indexAll.bundle.d.ts", format: "es" }],
		plugins: [dts(), toGlobal('Q')],
	},
	{
		input: "./dist/built/Serenity/index.d.ts",
		output: [{ file: "./dist/built/Serenity/index.bundle.d.ts", format: "es" }],
		plugins: [dts(), toGlobal('Serenity')],
	},
	{
		input: "./dist/built/Decorators/index.d.ts",
		output: [{ file: "./dist/built/Decorators/index.bundle.d.ts", format: "es" }],
		plugins: [dts(), toGlobal('Serenity.Decorators')],
	},
	{
		input: "./dist/built/Slick/index.d.ts",
		output: [{ file: "./dist/built/Slick/index.bundle.d.ts", format: "es" }],
		plugins: [dts(), toGlobal('Slick'), {
			name: 'writeFinal',
			generateBundle: function() {
				var src = outputs.join('\n');
				var refTypes = [];
				src = src.replace(rxReferenceTypes, function(match, offset, str) {
					refTypes.push(match);
					return '';
				});
				refTypes = refTypes.filter((x, i) => refTypes.indexOf(x) == i);
				src = refTypes.join('') + '\n' + src
				fs.writeFileSync('./dist/Serenity.CoreLib.d.ts', src);
			}
		}]
	}
];<commit_msg>decorators part of serenity module now<commit_after>import typescript from '@rollup/plugin-typescript';
import { minify } from "terser";
import path from 'path';
import fs from 'fs';
import pkg from "./package.json";
import {builtinModules} from "module";
import dts from "rollup-plugin-dts";

var globals = {
	'jquery': '$',
	'flatpickr': 'flatpickr'
}

function normalizePath(fileName) {
    return fileName.split(path.win32.sep).join(path.posix.sep);
}

var outputs = [];

var rxNamespace = /^namespace\s?/;
var rxExport = /^export\s?/;
var rxDeclare = /^declare\s?/;
var rxDeclareGlobal = /^(declare\s+global.*\s*\{\r?\n)((^\s+.*\r?\n)*)?\}/gm;
var rxRemoveExports = /^export\s*\{[^\}]*\}\s*\;\s*\r?\n/gm;
var rxReferenceTypes = /^\/\/\/\s*\<reference\s*types\=\".*\r?\n/gm

var toGlobal = function(ns) {
	return {
		name: 'toGlobal',
		generateBundle(o, b) {
			for (var fileName of Object.keys(b)) {
				if (b[fileName].code && fileName.indexOf('.bundle.d.ts') >= 0) {
					var src = b[fileName].code;
					src = src.replace('\r', '');
					src = src.replace(rxRemoveExports, '');

					var refTypes = [];
					src = src.replace(rxReferenceTypes, function(match, offset, str) {
						refTypes.push(match);
						return '';
					});

					var globals = [];
					src = src.replace(rxDeclareGlobal, function(x, y, m1) {
						var g = m1.replace(/(\r?\n)*$/, '').split('\n')
							.map(s => s.length > 0 && s.charAt(0) == '\t' ? s.substring(1) : (s.substring(0, 4) == '    ' ? s.substring(4) : s))
							.map(s => {
								if (rxNamespace.test(s))
									return ("declare " + s);
								else if (rxExport.test(s))
									return "declare " + s.substring(7);
								else
									return s;
							})
							.join('\n');
						globals.push(g);
						return '';
					});

					if (ns) {
						src = 'declare namespace ' + ns + ' {\n' +
							src.replace(/(\r?\n)*$/, '').split('\n').map(s => {
								if (!s.length)
									return '';
								if (rxDeclare.test(s))
									return '    ' + s.substring(8);
								else
									return '    ' + s;
							}).join('\n') + '\n}'
					}

					src = refTypes.join('') + '\n' + src + '\n' + globals.join('\n');

					outputs.push(src);

					var toEmit = {
						type: 'asset',
						fileName: fileName.replace('.bundle.d.ts', '.global.d.ts'),
						source: src
					};
					this.emitFile(toEmit);
				}
			}
		}
	}
}

var extendGlobals = function() {
	return {
		name: 'extendGlobals',
		generateBundle(o, b) {
			for (var fileName of Object.keys(b)) {
				var code = b[fileName].code || b[fileName].source;

				if (code && fileName.indexOf('.js') >= 0) {
					var src = code;
					src = src.replace(/^(\s*)exports\.([A-Za-z_]+)\s*=\s*(.+?);/gm, function(match, grp1, grp2, grp3) {
						if (grp2.charAt(0) == '_' && grp2.charAt(1) == '_')
							return grp1 + "exports." + grp2 + " = exports." + grp2 + " || " + grp3 + ";";
						return grp1 + "exports." + grp2 + " = exports." + grp2 + " || {}; extend(exports." + grp2 + ", " + grp3 + ");";
					});
					b[fileName].code = src;
				}
				else if (code && /(Globals\/.*|Globals)\.d\.ts$/i.test(fileName) && code.indexOf('declare global') < 0) {
					outputs.push(code);
				}
			}
		}
	}
}

var writeMinJS = function() {
	return {
		name: 'writeMinJS',
		generateBundle: async function(o, b) {
			var self = this;
			Object.keys(b).forEach(async function(fileName) {
				if (b[fileName].code && /\.js$/i.test(fileName) >= 0) {
					var src = b[fileName].code;
					var minified = await minify(src, {
						mangle: true,
						format: {
							beautify: false,
							max_line_len: 1000
						}
					});
					var toEmit = {
						type: 'asset',
						fileName: fileName.replace(/\.js$/, '.min.js'),
						source: minified.code
					};
					self.emitFile(toEmit);
				}
			});
		}
	}
}

export default [
	{
		input: "CoreLib/CoreLib.ts",
		output: [
			{
				file: 'dist/Serenity.CoreLib.js',
				format: "iife",
				sourcemap: true,
				name: "window",
				extend: true,
				freeze: false,
				globals
			}
		],
		plugins: [
			typescript({
				tsconfig: 'CoreLib/tsconfig.json',
				outDir: 'CoreLib/built'
			}),
			extendGlobals(),
			writeMinJS()
		],
		external: [
			...builtinModules,
			...(pkg.dependencies == null ? [] : Object.keys(pkg.dependencies)),
			...(pkg.devDependencies == null ? [] : Object.keys(pkg.devDependencies)),
			...(pkg.peerDependencies == null ? [] : Object.keys(pkg.peerDependencies))
		]
	},
	{
		input: "./dist/built/Q/indexAll.d.ts",
		output: [{ file: "./dist/built/Q/indexAll.bundle.d.ts", format: "es" }],
		plugins: [dts(), toGlobal('Q')],
	},
	{
		input: "./dist/built/Serenity/index.d.ts",
		output: [{ file: "./dist/built/Serenity/index.bundle.d.ts", format: "es" }],
		plugins: [dts(), toGlobal('Serenity')],
	},
	{
		input: "./dist/built/Slick/index.d.ts",
		output: [{ file: "./dist/built/Slick/index.bundle.d.ts", format: "es" }],
		plugins: [dts(), toGlobal('Slick'), {
			name: 'writeFinal',
			generateBundle: function() {
				var src = outputs.join('\n');
				var refTypes = [];
				src = src.replace(rxReferenceTypes, function(match, offset, str) {
					refTypes.push(match);
					return '';
				});
				refTypes = refTypes.filter((x, i) => refTypes.indexOf(x) == i);
				src = refTypes.join('') + '\n' + src
				fs.writeFileSync('./dist/Serenity.CoreLib.d.ts', src);
			}
		}]
	}
];<|endoftext|>