<commit_before>/**
 * @file DraggableGrid component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';

import DraggableGridItem from '../_DraggableGridItem';
import Tip from '../Tip';
import Theme from '../Theme';

import Util from '../_vendors/Util';
import Event from '../_vendors/Event';
import Calculation from '../_vendors/Calculation';
import SelectMode from '../_statics/SelectMode';

export default class DraggableGrid extends Component {

    static SelectMode = SelectMode;
    static Theme = Theme;

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.state = {
            value: Calculation.getInitValue(props)
        };

        this.listItemSelectHandler = ::this.listItemSelectHandler;
        this.listItemDeselectHandler = ::this.listItemDeselectHandler;

    }

    listItemSelectHandler(item, index) {

        const {selectMode} = this.props;

        let {value} = this.state;

        if (selectMode === SelectMode.MULTI_SELECT) {

            if (!value || !_.isArray(value)) {
                value = [];
            }

            value.push(item);

        } else if (selectMode === SelectMode.SINGLE_SELECT) {
            value = item;
        }

        this.setState({
            value
        }, () => {
            const {onItemSelect, onChange} = this.props;
            onItemSelect && onItemSelect(item, index);
            onChange && onChange(value, index);
        });

    }

    listItemDeselectHandler(item, index) {

        const {selectMode} = this.props;

        if (selectMode !== SelectMode.MULTI_SELECT) {
            return;
        }

        const {valueField, displayField} = this.props;
        let {value} = this.state;

        if (!value || !_.isArray(value)) {
            value = [];
        } else {
            value = value.filter(valueItem => {
                return Util.getValueByValueField(valueItem, valueField, displayField)
                    != Util.getValueByValueField(item, valueField, displayField);
            });
        }

        this.setState({
            value
        }, () => {
            const {onItemDeselect, onChange} = this.props;
            onItemDeselect && onItemDeselect(item, index);
            onChange && onChange(value, index);
        });

    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.value !== this.state.value) {
            this.setState({
                value: Calculation.getInitValue(nextProps)
            });
        }
    }

    render() {

        const {

                children, className, style, theme, data, itemHeight, col,

                selectTheme, selectMode, radioUncheckedIconCls, radioCheckedIconCls,
                checkboxUncheckedIconCls, checkboxCheckedIconCls, checkboxIndeterminateIconCls,

                idField, valueField, displayField, descriptionField, disabled, isLoading, renderer, onItemTouchTap

            } = this.props,
            {value} = this.state,

            listClassName = (className ? ' ' + className : '');

        return (
            <div className={'draggable-grid' + listClassName}
                 disabled={disabled}
                 style={style}
                 onWheel={e => {
                     Event.wheelHandler(e, this.props);
                 }}>

                {
                    _.isArray(data) && data.length > 0 ?
                        (
                            data.map((item, index) => {

                                return typeof item === 'object' ?
                                    (
                                        <DraggableGridItem key={item[idField] || index}
                                                           {...item}
                                                           index={index}
                                                           style={{height: itemHeight}}
                                                           theme={item.theme || theme}
                                                           col={col}
                                                           selectTheme={item.selectTheme || selectTheme}
                                                           radioUncheckedIconCls={item.radioUncheckedIconCls || radioUncheckedIconCls}
                                                           radioCheckedIconCls={item.radioCheckedIconCls || radioCheckedIconCls}
                                                           checkboxUncheckedIconCls={item.checkboxUncheckedIconCls || checkboxUncheckedIconCls}
                                                           checkboxCheckedIconCls={item.checkboxCheckedIconCls || checkboxCheckedIconCls}
                                                           checkboxIndeterminateIconCls={item.checkboxIndeterminateIconCls || checkboxIndeterminateIconCls}
                                                           data={item}
                                                           checked={Calculation.isItemChecked(item, value, this.props)}
                                                           value={Util.getValueByValueField(item, valueField, displayField)}
                                                           text={Util.getTextByDisplayField(item, displayField, valueField)}
                                                           desc={item[descriptionField] || null}
                                                           disabled={disabled || item.disabled}
                                                           isLoading={isLoading || item.isLoading}
                                                           selectMode={selectMode}
                                                           renderer={renderer}
                                                           onTouchTap={e => {
                                                               onItemTouchTap && onItemTouchTap(item, index, e);
                                                               item.onTouchTap && item.onTouchTap(e);
                                                           }}
                                                           onSelect={() => {
                                                               this.listItemSelectHandler(item, index);
                                                           }}
                                                           onDeselect={() => {
                                                               this.listItemDeselectHandler(item, index);
                                                           }}/>
                                    )
                                    :
                                    (
                                        <DraggableGridItem key={index}
                                                           index={index}
                                                           style={{height: itemHeight}}
                                                           theme={item.theme || theme}
                                                           col={col}
                                                           selectTheme={item.selectTheme || selectTheme}
                                                           radioUncheckedIconCls={item.radioUncheckedIconCls || radioUncheckedIconCls}
                                                           radioCheckedIconCls={item.radioCheckedIconCls || radioCheckedIconCls}
                                                           checkboxUncheckedIconCls={item.checkboxUncheckedIconCls || checkboxUncheckedIconCls}
                                                           checkboxCheckedIconCls={item.checkboxCheckedIconCls || checkboxCheckedIconCls}
                                                           checkboxIndeterminateIconCls={item.checkboxIndeterminateIconCls || checkboxIndeterminateIconCls}
                                                           data={item}
                                                           checked={Calculation.isItemChecked(item, value, this.props)}
                                                           value={item}
                                                           text={item}
                                                           disabled={disabled}
                                                           isLoading={isLoading}
                                                           selectMode={selectMode}
                                                           renderer={renderer}
                                                           onTouchTap={e => {
                                                               onItemTouchTap && onItemTouchTap(item, index, e);
                                                           }}
                                                           onSelect={() => {
                                                               this.listItemSelectHandler(item, index);
                                                           }}
                                                           onDeselect={() => {
                                                               this.listItemDeselectHandler(item, index);
                                                           }}/>
                                    );

                            })
                        )
                        :
                        null
                }

                {children}

            </div>
        );
    }
};

DraggableGrid.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * The theme of the grid item.
     */
    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * The theme of the grid item select radio or checkbox.
     */
    selectTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * The mode of listItem.
     */
    selectMode: PropTypes.oneOf(Util.enumerateValue(SelectMode)),

    /**
     * Children passed into the GridItem.
     */
    data: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.shape({

        /**
         * The CSS class name of the grid button.
         */
        className: PropTypes.string,

        /**
         * Override the styles of the grid button.
         */
        style: PropTypes.object,

        /**
         * The theme of the grid button.
         */
        theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

        /**
         * The text value of the grid button.Type can be string or number.
         */
        value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

        /**
         * The grid item's display text. Type can be string, number or bool.
         */
        text: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

        /**
         * The desc value of the grid button. Type can be string or number.
         */
        desc: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

        /**
         * If true,the grid item will be disabled.
         */
        disabled: PropTypes.bool,

        /**
         * If true,the button will be have loading effect.
         */
        isLoading: PropTypes.bool,

        /**
         * If true,the element's ripple effect will be disabled.
         */
        disableTouchRipple: PropTypes.bool,

        /**
         * Use this property to display an icon. It will display on the left.
         */
        iconCls: PropTypes.string,

        /**
         * Use this property to display an icon. It will display on the right.
         */
        rightIconCls: PropTypes.string,

        /**
         * The message of tip.
         */
        tip: PropTypes.string,

        /**
         * The position of tip.
         */
        tipPosition: PropTypes.oneOf(Util.enumerateValue(Tip.Position)),

        /**
         * If true,the item will have center displayed ripple effect.
         */
        rippleDisplayCenter: PropTypes.bool,

        /**
         * You can create a complicated renderer callback instead of value and desc prop.
         */
        itemRenderer: PropTypes.func,

        /**
         * Callback function fired when a grid item touch-tapped.
         */
        onTouchTap: PropTypes.func

    }), PropTypes.string, PropTypes.number, PropTypes.symbol])),

    value: PropTypes.any,

    /**
     * The id field name in data. (default: "id")
     */
    idField: PropTypes.string,

    /**
     * The value field name in data. (default: "value")
     */
    valueField: PropTypes.string,

    /**
     * The display field name in data. (default: "text")
     */
    displayField: PropTypes.string,

    /**
     * The description field name in data. (default: "desc")
     */
    descriptionField: PropTypes.string,

    /**
     * If true, the grid will be disabled.
     */
    disabled: PropTypes.bool,

    /**
     * If true, the grid will be at loading status.
     */
    isLoading: PropTypes.bool,

    shouldPreventContainerScroll: PropTypes.bool,

    radioUncheckedIconCls: PropTypes.string,
    radioCheckedIconCls: PropTypes.string,
    checkboxUncheckedIconCls: PropTypes.string,
    checkboxCheckedIconCls: PropTypes.string,
    checkboxIndeterminateIconCls: PropTypes.string,

    col: PropTypes.number,

    /**
     * You can create a complicated renderer callback instead of value and desc prop.
     */
    renderer: PropTypes.func,

    /**
     * Callback function fired when the grid-item touch tap.
     */
    onItemTouchTap: PropTypes.func,

    /**
     * Callback function fired when the grid-item select.
     */
    onItemSelect: PropTypes.func,

    /**
     * Callback function fired when the grid-item deselect.
     */
    onItemDeselect: PropTypes.func,

    /**
     * Callback function fired when the grid changed.
     */
    onChange: PropTypes.func,

    /**
     * Callback function fired when wrapper wheeled.
     */
    onWheel: PropTypes.func

};

DraggableGrid.defaultProps = {

    className: null,
    style: null,
    theme: Theme.DEFAULT,

    selectTheme: Theme.DEFAULT,
    selectMode: SelectMode.SINGLE_SELECT,

    data: null,

    idField: 'id',
    valueField: 'value',
    displayField: 'text',
    descriptionField: 'desc',
    disabled: false,
    shouldPreventContainerScroll: true,

    radioUncheckedIconCls: null,
    radioCheckedIconCls: null,
    checkboxUncheckedIconCls: 'fa fa-square-o',
    checkboxCheckedIconCls: 'fa fa-check-square',
    checkboxIndeterminateIconCls: 'fa fa-minus-square',

    col: 3

};<commit_msg>update DraggableGrid<commit_after>/**
 * @file DraggableGrid component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {DragDropContext, Droppable, Draggable} from 'react-beautiful-dnd';
import _ from 'lodash';

import DraggableGridItem from '../_DraggableGridItem';
import Tip from '../Tip';
import Theme from '../Theme';

import Util from '../_vendors/Util';
import Event from '../_vendors/Event';
import Calculation from '../_vendors/Calculation';
import SelectMode from '../_statics/SelectMode';

export default class DraggableGrid extends Component {

    static SelectMode = SelectMode;
    static Theme = Theme;

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.state = {
            value: Calculation.getInitValue(props)
        };

        this.listItemSelectHandler = ::this.listItemSelectHandler;
        this.listItemDeselectHandler = ::this.listItemDeselectHandler;
        this.onNodeDragEnd = ::this.onNodeDragEnd;
        this.renderGridItem = ::this.renderGridItem;

    }

    listItemSelectHandler(item, index) {

        const {selectMode} = this.props;

        let {value} = this.state;

        if (selectMode === SelectMode.MULTI_SELECT) {

            if (!value || !_.isArray(value)) {
                value = [];
            }

            value.push(item);

        } else if (selectMode === SelectMode.SINGLE_SELECT) {
            value = item;
        }

        this.setState({
            value
        }, () => {
            const {onItemSelect, onChange} = this.props;
            onItemSelect && onItemSelect(item, index);
            onChange && onChange(value, index);
        });

    }

    listItemDeselectHandler(item, index) {

        const {selectMode} = this.props;

        if (selectMode !== SelectMode.MULTI_SELECT) {
            return;
        }

        const {valueField, displayField} = this.props;
        let {value} = this.state;

        if (!value || !_.isArray(value)) {
            value = [];
        } else {
            value = value.filter(valueItem => {
                return Util.getValueByValueField(valueItem, valueField, displayField)
                    != Util.getValueByValueField(item, valueField, displayField);
            });
        }

        this.setState({
            value
        }, () => {
            const {onItemDeselect, onChange} = this.props;
            onItemDeselect && onItemDeselect(item, index);
            onChange && onChange(value, index);
        });

    }

    onNodeDragEnd(result) {

        /**
         *  result: {
         *      draggableId,
         *      type,
         *      source: {
         *          droppableId,
         *          index
         *      },
         *      destination: {
         *          droppableId,
         *          index
         *      }
         *  }
         */

        if (!result || !('draggableId' in result)
            || !result.source || !('index' in result.source)
            || !result.destination || !('index' in result.destination)) {
            return;
        }

        const {data} = this.state;

        Util.reorder(data, result.source.index, result.destination.index);

        this.setState({
            data
        }, () => {
            const {onNodeDragEnd, onSequenceChange} = this.props;
            onNodeDragEnd && onNodeDragEnd(result);
            onSequenceChange && onSequenceChange(data);
        });

    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.value !== this.state.value) {
            this.setState({
                value: Calculation.getInitValue(nextProps)
            });
        }
    }

    renderGridItem(item, index) {

        const {

                theme, itemHeight, col,

                selectTheme, selectMode, radioUncheckedIconCls, radioCheckedIconCls,
                checkboxUncheckedIconCls, checkboxCheckedIconCls, checkboxIndeterminateIconCls,

                idField, valueField, displayField, descriptionField, disabled, isLoading, renderer, onItemTouchTap

            } = this.props,
            {value} = this.state;

        return typeof item === 'object' ?
            (
                <DraggableGridItem key={item[idField] || index}
                                   {...item}
                                   index={index}
                                   style={{height: itemHeight}}
                                   theme={item.theme || theme}
                                   col={col}
                                   selectTheme={item.selectTheme || selectTheme}
                                   radioUncheckedIconCls={item.radioUncheckedIconCls || radioUncheckedIconCls}
                                   radioCheckedIconCls={item.radioCheckedIconCls || radioCheckedIconCls}
                                   checkboxUncheckedIconCls={item.checkboxUncheckedIconCls || checkboxUncheckedIconCls}
                                   checkboxCheckedIconCls={item.checkboxCheckedIconCls || checkboxCheckedIconCls}
                                   checkboxIndeterminateIconCls={item.checkboxIndeterminateIconCls || checkboxIndeterminateIconCls}
                                   data={item}
                                   checked={Calculation.isItemChecked(item, value, this.props)}
                                   value={Util.getValueByValueField(item, valueField, displayField)}
                                   text={Util.getTextByDisplayField(item, displayField, valueField)}
                                   desc={item[descriptionField] || null}
                                   disabled={disabled || item.disabled}
                                   isLoading={isLoading || item.isLoading}
                                   selectMode={selectMode}
                                   renderer={renderer}
                                   onTouchTap={e => {
                                       onItemTouchTap && onItemTouchTap(item, index, e);
                                       item.onTouchTap && item.onTouchTap(e);
                                   }}
                                   onSelect={() => {
                                       this.listItemSelectHandler(item, index);
                                   }}
                                   onDeselect={() => {
                                       this.listItemDeselectHandler(item, index);
                                   }}/>
            )
            :
            (
                <DraggableGridItem key={index}
                                   index={index}
                                   style={{height: itemHeight}}
                                   theme={item.theme || theme}
                                   col={col}
                                   selectTheme={item.selectTheme || selectTheme}
                                   radioUncheckedIconCls={item.radioUncheckedIconCls || radioUncheckedIconCls}
                                   radioCheckedIconCls={item.radioCheckedIconCls || radioCheckedIconCls}
                                   checkboxUncheckedIconCls={item.checkboxUncheckedIconCls || checkboxUncheckedIconCls}
                                   checkboxCheckedIconCls={item.checkboxCheckedIconCls || checkboxCheckedIconCls}
                                   checkboxIndeterminateIconCls={item.checkboxIndeterminateIconCls || checkboxIndeterminateIconCls}
                                   data={item}
                                   checked={Calculation.isItemChecked(item, value, this.props)}
                                   value={item}
                                   text={item}
                                   disabled={disabled}
                                   isLoading={isLoading}
                                   selectMode={selectMode}
                                   renderer={renderer}
                                   onTouchTap={e => {
                                       onItemTouchTap && onItemTouchTap(item, index, e);
                                   }}
                                   onSelect={() => {
                                       this.listItemSelectHandler(item, index);
                                   }}
                                   onDeselect={() => {
                                       this.listItemDeselectHandler(item, index);
                                   }}/>
            );

    }

    render() {

        const {

                children, className, style, data, disabled,

                onNodeDragStart

            } = this.props,

            listClassName = (className ? ' ' + className : '');

        return (
            <DragDropContext onDragStart={onNodeDragStart}
                             onDragEnd={this.onNodeDragEnd}>

                <Droppable droppableId="droppable">

                    {
                        dropProvided => (
                            <div ref={dropProvided.innerRef}
                                 className={'draggable-grid' + listClassName}
                                 disabled={disabled}
                                 style={style}
                                 onWheel={e => {
                                     Event.wheelHandler(e, this.props);
                                 }}>

                                {
                                    data.map((item, index) => (
                                        <Draggable key={index}
                                                   draggableId={index}>
                                            {
                                                (dragProvided, dragSnapshot) => (
                                                    <div>
                                                        <div ref={dragProvided.innerRef}
                                                             style={dragProvided.draggableStyle}
                                                             {...dragProvided.dragHandleProps}>

                                                            {this.renderGridItem(item, index)}

                                                        </div>

                                                        {dragProvided.placeholder}

                                                    </div>
                                                )
                                            }
                                        </Draggable>
                                    ))
                                }

                                {dropProvided.placeholder}

                                {children}

                            </div>
                        )
                    }

                </Droppable>

            </DragDropContext>
        );
    }
};

DraggableGrid.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * The theme of the grid item.
     */
    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * The theme of the grid item select radio or checkbox.
     */
    selectTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * The mode of listItem.
     */
    selectMode: PropTypes.oneOf(Util.enumerateValue(SelectMode)),

    /**
     * Children passed into the GridItem.
     */
    data: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.shape({

        /**
         * The CSS class name of the grid button.
         */
        className: PropTypes.string,

        /**
         * Override the styles of the grid button.
         */
        style: PropTypes.object,

        /**
         * The theme of the grid button.
         */
        theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

        /**
         * The text value of the grid button.Type can be string or number.
         */
        value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

        /**
         * The grid item's display text. Type can be string, number or bool.
         */
        text: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

        /**
         * The desc value of the grid button. Type can be string or number.
         */
        desc: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

        /**
         * If true,the grid item will be disabled.
         */
        disabled: PropTypes.bool,

        /**
         * If true,the button will be have loading effect.
         */
        isLoading: PropTypes.bool,

        /**
         * If true,the element's ripple effect will be disabled.
         */
        disableTouchRipple: PropTypes.bool,

        /**
         * Use this property to display an icon. It will display on the left.
         */
        iconCls: PropTypes.string,

        /**
         * Use this property to display an icon. It will display on the right.
         */
        rightIconCls: PropTypes.string,

        /**
         * The message of tip.
         */
        tip: PropTypes.string,

        /**
         * The position of tip.
         */
        tipPosition: PropTypes.oneOf(Util.enumerateValue(Tip.Position)),

        /**
         * If true,the item will have center displayed ripple effect.
         */
        rippleDisplayCenter: PropTypes.bool,

        /**
         * You can create a complicated renderer callback instead of value and desc prop.
         */
        itemRenderer: PropTypes.func,

        /**
         * Callback function fired when a grid item touch-tapped.
         */
        onTouchTap: PropTypes.func

    }), PropTypes.string, PropTypes.number, PropTypes.symbol])),

    value: PropTypes.any,

    /**
     * The id field name in data. (default: "id")
     */
    idField: PropTypes.string,

    /**
     * The value field name in data. (default: "value")
     */
    valueField: PropTypes.string,

    /**
     * The display field name in data. (default: "text")
     */
    displayField: PropTypes.string,

    /**
     * The description field name in data. (default: "desc")
     */
    descriptionField: PropTypes.string,

    /**
     * If true, the grid will be disabled.
     */
    disabled: PropTypes.bool,

    /**
     * If true, the grid will be at loading status.
     */
    isLoading: PropTypes.bool,

    shouldPreventContainerScroll: PropTypes.bool,

    radioUncheckedIconCls: PropTypes.string,
    radioCheckedIconCls: PropTypes.string,
    checkboxUncheckedIconCls: PropTypes.string,
    checkboxCheckedIconCls: PropTypes.string,
    checkboxIndeterminateIconCls: PropTypes.string,

    col: PropTypes.number,

    /**
     * You can create a complicated renderer callback instead of value and desc prop.
     */
    renderer: PropTypes.func,

    /**
     * Callback function fired when the grid-item touch tap.
     */
    onItemTouchTap: PropTypes.func,

    /**
     * Callback function fired when the grid-item select.
     */
    onItemSelect: PropTypes.func,

    /**
     * Callback function fired when the grid-item deselect.
     */
    onItemDeselect: PropTypes.func,

    /**
     * Callback function fired when the grid changed.
     */
    onChange: PropTypes.func,

    /**
     * Callback function fired when wrapper wheeled.
     */
    onWheel: PropTypes.func,

    onNodeDragStart: PropTypes.func,
    onNodeDragEnd: PropTypes.func,

    onSequenceChange: PropTypes.func

};

DraggableGrid.defaultProps = {

    className: null,
    style: null,
    theme: Theme.DEFAULT,

    selectTheme: Theme.DEFAULT,
    selectMode: SelectMode.SINGLE_SELECT,

    data: null,

    idField: 'id',
    valueField: 'value',
    displayField: 'text',
    descriptionField: 'desc',
    disabled: false,
    shouldPreventContainerScroll: true,

    radioUncheckedIconCls: null,
    radioCheckedIconCls: null,
    checkboxUncheckedIconCls: 'fa fa-square-o',
    checkboxCheckedIconCls: 'fa fa-check-square',
    checkboxIndeterminateIconCls: 'fa fa-minus-square',

    col: 3

};<|endoftext|>


<commit_before>define([
	"bacon",
	"../utils/destroy",
	"es6-shim",
], function(
	Bacon,
	destroy
){
	var identity = function (o) { return o; };

	var Bindable = {
		// call set(prop) with value from observable at each notification
		setR: function(prop, observable){
			return this.own(observable.onValue(this, "set", prop));
		},
		// create a bidi value binding from source to this
		bind: function(targetProp, source, sourceProp, options){
			var init = true;
			var target = this;
			var sourceValueR = source.getR(sourceProp);
			var targetValueR = target.getR(targetProp);
			var changing = false;
			var sourceHandler = sourceValueR.onValue(function(value){
				if (! changing){
					changing = true;
					target.set(targetProp, (options && options.convert ? options.convert.call(target, value) : value));
					changing = false;
				}
			});
			var targetHandler = targetValueR.onValue(function(value){
				if (! changing && ! init){ // prevent calling source.set at init time
					changing = true;
					source.set(sourceProp, (options && options.revert ? options.revert.call(target, value) : value));
					changing = false;
				}
			});
			init = false;
			return this.own(function(){
				targetHandler();
				sourceHandler();
			});
		},

		// create a bidi value binding from each prop of source to each prop of this
		bindEach: function(source, options){
			var init = true;
			var target = this;
			var sourceProps = Object.keys(options).map(function(key) {
				return options[key];
			});
			var targetProps = Object.keys(options);
			var sourceValueR = source.getEachR.apply(source, sourceProps);
			var targetValueR = target.getEachR.apply(target, targetProps);
			var changing = false;
			var sourceHandler = sourceValueR.onValue(function(values){
				if (! changing){
					changing = true;
					var valuesAsObject = {};
					Object.keys(options).forEach(function(key, index) {
						valuesAsObject[options[key]] = values[index];
					});
					target.setEach(valuesAsObject);
					changing = false;
				}
			});
			var targetHandler = targetValueR.onValue(function(values){
				if (! changing && ! init){ // prevent calling source.set at init time
					changing = true;
					var valuesAsObject = {};
					Object.keys(options).forEach(function(targetProp, index) {
						valuesAsObject[targetProp] = values[index];
					});
					source.setEach(valuesAsObject);
					changing = false;
				}
			});
			init = false;
			return this.own(function(){
				targetHandler();
				sourceHandler();
			});
		},

		// whenChanged(...props, cb(...props))
		// called whenever at least one of the props changed (so, only once when many props changed)
		// if cb returns something, this is owned by this (destroyed when this is destroyed) and destroyed at the next call
		// cb can also be a collection of cb
		whenChanged: function(){
			var cbCanceler;

			var props = Array.prototype.slice.call(arguments, 0, arguments.length-1);
			var binder;
			var lastArg = arguments[arguments.length-1];
			if (typeof lastArg === 'function'){
				binder = lastArg;
			} else {
				binder = function(){
					var cmps = arguments;
					return lastArg.map(function(cb) {
						return cb.apply(this, cmps);
					}.bind(this));
				};
			}

			var observingCanceler = this.getEachR.apply(this, props).onValue(function(propsValues){
				if (cbCanceler){
					destroy(cbCanceler);
					cbCanceler = undefined;
				}
				cbCanceler = binder.apply(this, propsValues);
			}.bind(this));

			return this.own(function(){
				destroy(observingCanceler);
				destroy(cbCanceler);
			});
		},

		/**
		 * Same as whenChanged but only call cb if all of props are defined (!== undefined)
		 * Whenever at least one key change, the last return from cb is destroyed even if the cb is not called. So the return of cb is only active during the time all of props are defined
		 * @param {string} props list of properties to observe
		 * @param {[function, iterable]} cb function or list of function that is/are called with the values of corresponding props whenever at least one of them change
		 * @return {[function]} canceler Stop observing the properties and calling cb. But the last return from cb is not destroyed
		 */
		whenDefined: function(){
			var collection = this;
			var args = arguments;
			var cbs = arguments[arguments.length-1];
			if (typeof cbs === 'function'){
				cbs = [cbs];
			}
			args[args.length-1] = cbs.map(function(cb) {
				return function(){
					if (Array.prototype.every.call(arguments, function(val){
						return val !== undefined;
					})) {
						return cb.apply(collection, arguments);
					}
				};
			});
			return this.whenChanged.apply(this, args);
		},

		whenDefinedEach: function() {
			Array.prototype.forEach.call(arguments, function(args) {
				this.whenDefined.apply(this, args);
			}, this);
		},

		bindEvent: function(source, eventType, target, targetMethod){
			return this.when(source, target, function(source, target){
				return source.on(eventType, function(ev){
					target[targetMethod](ev);
				});
			});
		},
		// create a bidirectionnal binding with the following logic: targetProp value is the item from the collection for which itemProp is truthy
		// at init time, the target prop value is the winner
		// TODO: allow a "multi" behavior > the targetProp become a collection (unordered set)
		bindSelection:function(targetProp, collection, itemProp, multi){
			var changing = false;
			var target = this;
			var currentItem = this.get(targetProp);
			// init time
			collection.forEach(function(item){
				item.set(itemProp, item === currentItem);
			});

			// incremental update
			var targetHandler = this.getR(targetProp).diff(undefined, function(oldItem, currentItem){
				return {oldItem: oldItem, currentItem: currentItem};
			}).changes().onValue(function(oldAndCurrentItems){
				if (! changing){
					changing = true;
					var oldItem = oldAndCurrentItems.oldItem;
					var currentItem = oldAndCurrentItems.currentItem;
					oldItem && collection.has(oldItem) && oldItem.set(itemProp, false);
					currentItem && collection.has(currentItem) && currentItem.set(itemProp, true);
					changing = false;
				}
			});

			var itemHandlers = new Map();
			var sourceHandler = collection.asChangesStream().onValue(function(changes){
				changes.forEach(function(change){
					var item = change.value;
					if (change.type === "add"){
						item.set(itemProp, item === target.get(targetProp));
						itemHandlers.set(item, item.getR(itemProp).changes().onValue(function(bool){
							if (! changing){
								changing = true;
								var oldItem = target.get(targetProp);
								oldItem && collection.has(oldItem) && oldItem.set(itemProp, false);
								target.set(targetProp, bool ? item : undefined);
								changing = false;
							}
						}));
					}
					if (change.type === "remove"){
						destroy(itemHandlers.get(item));
						itemHandlers.delete(item);
					}
				});
			});

			// return a canceler
			return this.own(function(){
				destroy(targetHandler);
				destroy(sourceHandler);
				itemHandlers.forEach(destroy);
			});
		},
		// create a bidirectionnal binding between this (source) and target where sourceProp has the value corresponding to the truthy property of the target
		// at init, the source prop is the master
		bindCase: function(sourceProp, target, map) {
			var source = this;

			var changing = false;
			var sourceCanceler = this.getR(sourceProp).onValue(function (sourceValue) {
				if (!changing) {
					changing = true;
					Object.keys(map).forEach(function(key) {
						var value = map[key];
						target.set(key, value === sourceValue);
					});
					changing = false;
				}
			}.bind(this));

			var targetCancelers = [];
			Object.keys(map).forEach(function(key) {
				var value = map[key];
				var canceler = target.getR(key).filter(identity).onValue(function() {
					source.set(sourceProp, value);
				});
				targetCancelers.push(canceler);
			});

		},
		// create a bidirectionnal binding with the following logic: targetProp value is true if all the items are true
		// if targetProp is set to true, all the items are set to true
		// if targetProp is set to false, all the items are set to false
		// at init time, the target prop value is the slave
		bindAll: function(targetProp, collection, itemProp){
			var changing = false;
			var target = this;
			// init time
			this.set('targetProp', collection.every(function(item){
				return item.get(itemProp);
			}));

			var targetHandler = this.getR(targetProp).changes().onValue(function(b){
				if (! changing){
					changing = true;
					collection.forEach(function(item) {
						item.set(itemProp, b);
					});
					changing = false;
				}
			});

			var sourceHandler = collection.asReactive().onEach().onValue(function(){
				if (! changing){
					var b = collection.every(function(item){
						return item.get(itemProp);
					});
					if (target.get(targetProp) !== b) {
						changing = true;
						target.set(targetProp, b);
						changing = false;
					}
				}
			});

			// return a canceler
			return this.own(function(){
				destroy(targetHandler);
				destroy(sourceHandler);
			});
		},
		// bi-directional binding so that targetProp is true if <item> is in sourceProp (which must be a Set)
		// so when targetProp is changed,  <item> is either added or removed from sourceProp collection
		bindIsIn: function(targetProp, source, sourceProp, item) {
			var init = true;
			var target = this;
			var sourceValueR = source.getChangesStream(sourceProp);
			var targetValueR = target.getR(targetProp);
			// init target prop value
			target.set(targetProp, source.get(sourceProp).has(item));
			// start observing source collection changes
			var changing = false;
			var sourceHandler = sourceValueR.onValue(function(changes){
				if (! changing && ! init){
					changing = true;
					changes.forEach(function(change) {
						if (change.value === item){
							if (change.type === 'add'){
								if (target.get(targetProp) !== true) {target.set(targetProp, true);}
							} else if (change.type === 'remove') {
								if (target.get(targetProp) !== false) {target.set(targetProp, false);}
							}
						}
					});
					changing = false;
				}
			});
			// start observing target prop changes
			var targetHandler = targetValueR.onValue(function(isIn){
				if (! changing && ! init){ // prevent calling source.set at init time
					changing = true;
					var collection = source.get(sourceProp);
					if (isIn) {
						if (!collection.has(item)){
							collection.add(item);
						}
					} else {
						if (collection.has(item)){
							collection.remove(item);
						}
					}
					changing = false;
				}
			});
			init = false;
			return this.own(function(){
				targetHandler();
				sourceHandler();
			});
		},

	};
	return Bindable;
});<commit_msg>Fix Bindable.whenDefinedEach, that did not return cancelers<commit_after>define([
	"bacon",
	"../utils/destroy",
	"es6-shim",
], function(
	Bacon,
	destroy
){
	var identity = function (o) { return o; };

	var Bindable = {
		// call set(prop) with value from observable at each notification
		setR: function(prop, observable){
			return this.own(observable.onValue(this, "set", prop));
		},
		// create a bidi value binding from source to this
		bind: function(targetProp, source, sourceProp, options){
			var init = true;
			var target = this;
			var sourceValueR = source.getR(sourceProp);
			var targetValueR = target.getR(targetProp);
			var changing = false;
			var sourceHandler = sourceValueR.onValue(function(value){
				if (! changing){
					changing = true;
					target.set(targetProp, (options && options.convert ? options.convert.call(target, value) : value));
					changing = false;
				}
			});
			var targetHandler = targetValueR.onValue(function(value){
				if (! changing && ! init){ // prevent calling source.set at init time
					changing = true;
					source.set(sourceProp, (options && options.revert ? options.revert.call(target, value) : value));
					changing = false;
				}
			});
			init = false;
			return this.own(function(){
				targetHandler();
				sourceHandler();
			});
		},

		// create a bidi value binding from each prop of source to each prop of this
		bindEach: function(source, options){
			var init = true;
			var target = this;
			var sourceProps = Object.keys(options).map(function(key) {
				return options[key];
			});
			var targetProps = Object.keys(options);
			var sourceValueR = source.getEachR.apply(source, sourceProps);
			var targetValueR = target.getEachR.apply(target, targetProps);
			var changing = false;
			var sourceHandler = sourceValueR.onValue(function(values){
				if (! changing){
					changing = true;
					var valuesAsObject = {};
					Object.keys(options).forEach(function(key, index) {
						valuesAsObject[options[key]] = values[index];
					});
					target.setEach(valuesAsObject);
					changing = false;
				}
			});
			var targetHandler = targetValueR.onValue(function(values){
				if (! changing && ! init){ // prevent calling source.set at init time
					changing = true;
					var valuesAsObject = {};
					Object.keys(options).forEach(function(targetProp, index) {
						valuesAsObject[targetProp] = values[index];
					});
					source.setEach(valuesAsObject);
					changing = false;
				}
			});
			init = false;
			return this.own(function(){
				targetHandler();
				sourceHandler();
			});
		},

		// whenChanged(...props, cb(...props))
		// called whenever at least one of the props changed (so, only once when many props changed)
		// if cb returns something, this is owned by this (destroyed when this is destroyed) and destroyed at the next call
		// cb can also be a collection of cb
		whenChanged: function(){
			var cbCanceler;

			var props = Array.prototype.slice.call(arguments, 0, arguments.length-1);
			var binder;
			var lastArg = arguments[arguments.length-1];
			if (typeof lastArg === 'function'){
				binder = lastArg;
			} else {
				binder = function(){
					var cmps = arguments;
					return lastArg.map(function(cb) {
						return cb.apply(this, cmps);
					}.bind(this));
				};
			}

			var observingCanceler = this.getEachR.apply(this, props).onValue(function(propsValues){
				if (cbCanceler){
					destroy(cbCanceler);
					cbCanceler = undefined;
				}
				cbCanceler = binder.apply(this, propsValues);
			}.bind(this));

			return this.own(function(){
				destroy(observingCanceler);
				destroy(cbCanceler);
			});
		},

		/**
		 * Same as whenChanged but only call cb if all of props are defined (!== undefined)
		 * Whenever at least one key change, the last return from cb is destroyed even if the cb is not called. So the return of cb is only active during the time all of props are defined
		 * @param {string} props list of properties to observe
		 * @param {[function, iterable]} cb function or list of function that is/are called with the values of corresponding props whenever at least one of them change
		 * @return {[function]} canceler Stop observing the properties and calling cb. But the last return from cb is not destroyed
		 */
		whenDefined: function(){
			var collection = this;
			var args = arguments;
			var cbs = arguments[arguments.length-1];
			if (typeof cbs === 'function'){
				cbs = [cbs];
			}
			args[args.length-1] = cbs.map(function(cb) {
				return function(){
					if (Array.prototype.every.call(arguments, function(val){
						return val !== undefined;
					})) {
						return cb.apply(collection, arguments);
					}
				};
			});
			return this.whenChanged.apply(this, args);
		},

		whenDefinedEach: function() {
			var cancelers = [];
			Array.prototype.forEach.call(arguments, function(args) {
				cancelers.push(this.whenDefined.apply(this, args));
			}, this);
			return cancelers;
		},

		bindEvent: function(source, eventType, target, targetMethod){
			return this.when(source, target, function(source, target){
				return source.on(eventType, function(ev){
					target[targetMethod](ev);
				});
			});
		},
		// create a bidirectionnal binding with the following logic: targetProp value is the item from the collection for which itemProp is truthy
		// at init time, the target prop value is the winner
		// TODO: allow a "multi" behavior > the targetProp become a collection (unordered set)
		bindSelection:function(targetProp, collection, itemProp, multi){
			var changing = false;
			var target = this;
			var currentItem = this.get(targetProp);
			// init time
			collection.forEach(function(item){
				item.set(itemProp, item === currentItem);
			});

			// incremental update
			var targetHandler = this.getR(targetProp).diff(undefined, function(oldItem, currentItem){
				return {oldItem: oldItem, currentItem: currentItem};
			}).changes().onValue(function(oldAndCurrentItems){
				if (! changing){
					changing = true;
					var oldItem = oldAndCurrentItems.oldItem;
					var currentItem = oldAndCurrentItems.currentItem;
					oldItem && collection.has(oldItem) && oldItem.set(itemProp, false);
					currentItem && collection.has(currentItem) && currentItem.set(itemProp, true);
					changing = false;
				}
			});

			var itemHandlers = new Map();
			var sourceHandler = collection.asChangesStream().onValue(function(changes){
				changes.forEach(function(change){
					var item = change.value;
					if (change.type === "add"){
						item.set(itemProp, item === target.get(targetProp));
						itemHandlers.set(item, item.getR(itemProp).changes().onValue(function(bool){
							if (! changing){
								changing = true;
								var oldItem = target.get(targetProp);
								oldItem && collection.has(oldItem) && oldItem.set(itemProp, false);
								target.set(targetProp, bool ? item : undefined);
								changing = false;
							}
						}));
					}
					if (change.type === "remove"){
						destroy(itemHandlers.get(item));
						itemHandlers.delete(item);
					}
				});
			});

			// return a canceler
			return this.own(function(){
				destroy(targetHandler);
				destroy(sourceHandler);
				itemHandlers.forEach(destroy);
			});
		},
		// create a bidirectionnal binding between this (source) and target where sourceProp has the value corresponding to the truthy property of the target
		// at init, the source prop is the master
		bindCase: function(sourceProp, target, map) {
			var source = this;

			var changing = false;
			var sourceCanceler = this.getR(sourceProp).onValue(function (sourceValue) {
				if (!changing) {
					changing = true;
					Object.keys(map).forEach(function(key) {
						var value = map[key];
						target.set(key, value === sourceValue);
					});
					changing = false;
				}
			}.bind(this));

			var targetCancelers = [];
			Object.keys(map).forEach(function(key) {
				var value = map[key];
				var canceler = target.getR(key).filter(identity).onValue(function() {
					source.set(sourceProp, value);
				});
				targetCancelers.push(canceler);
			});

		},
		// create a bidirectionnal binding with the following logic: targetProp value is true if all the items are true
		// if targetProp is set to true, all the items are set to true
		// if targetProp is set to false, all the items are set to false
		// at init time, the target prop value is the slave
		bindAll: function(targetProp, collection, itemProp){
			var changing = false;
			var target = this;
			// init time
			this.set('targetProp', collection.every(function(item){
				return item.get(itemProp);
			}));

			var targetHandler = this.getR(targetProp).changes().onValue(function(b){
				if (! changing){
					changing = true;
					collection.forEach(function(item) {
						item.set(itemProp, b);
					});
					changing = false;
				}
			});

			var sourceHandler = collection.asReactive().onEach().onValue(function(){
				if (! changing){
					var b = collection.every(function(item){
						return item.get(itemProp);
					});
					if (target.get(targetProp) !== b) {
						changing = true;
						target.set(targetProp, b);
						changing = false;
					}
				}
			});

			// return a canceler
			return this.own(function(){
				destroy(targetHandler);
				destroy(sourceHandler);
			});
		},
		// bi-directional binding so that targetProp is true if <item> is in sourceProp (which must be a Set)
		// so when targetProp is changed,  <item> is either added or removed from sourceProp collection
		bindIsIn: function(targetProp, source, sourceProp, item) {
			var init = true;
			var target = this;
			var sourceValueR = source.getChangesStream(sourceProp);
			var targetValueR = target.getR(targetProp);
			// init target prop value
			target.set(targetProp, source.get(sourceProp).has(item));
			// start observing source collection changes
			var changing = false;
			var sourceHandler = sourceValueR.onValue(function(changes){
				if (! changing && ! init){
					changing = true;
					changes.forEach(function(change) {
						if (change.value === item){
							if (change.type === 'add'){
								if (target.get(targetProp) !== true) {target.set(targetProp, true);}
							} else if (change.type === 'remove') {
								if (target.get(targetProp) !== false) {target.set(targetProp, false);}
							}
						}
					});
					changing = false;
				}
			});
			// start observing target prop changes
			var targetHandler = targetValueR.onValue(function(isIn){
				if (! changing && ! init){ // prevent calling source.set at init time
					changing = true;
					var collection = source.get(sourceProp);
					if (isIn) {
						if (!collection.has(item)){
							collection.add(item);
						}
					} else {
						if (collection.has(item)){
							collection.remove(item);
						}
					}
					changing = false;
				}
			});
			init = false;
			return this.own(function(){
				targetHandler();
				sourceHandler();
			});
		},

	};
	return Bindable;
});<|endoftext|>


<commit_before>this.Comments = new Meteor.Collection('comments');

Schemas.Comments = new SimpleSchema({

	wordpressId: {
		type: Number,
		optional: true,
	},

	tenantId: {
			type: String,
			label: "Tenant",
			optional: true,
			autoform: {
				afFieldInput: {
					type: "select",
					options: function () {
						var tenants = [];
						_.map(Tenants.find().fetch(), function (tenant) {

							tenants.push({
								label: tenant.subdomain,
								value: tenant._id
							});

						});
						return tenants;
					}
				}
			}
	},

	commenters: {
		type: [Object],
		optional: true,
		blackbox: true,
		/*autoform: {
		 options: function() {
		 return _.map(Commenters.find().fetch(), function(commenter) {
		 return {
		 label: commenter.name,
		 value: commenter._id
		 };
		 });
		 }
		 }
		 */
	},

	work: {
		type: Object,
		optional: true,
		blackbox: true,

	},

	subwork: {
		type: Object,
		optional: true,
		blackbox: true,

	},

	lineFrom: {
		type: Number,
		optional: true,
	},

	lineTo: {
		type: Number,
		optional: true,
	},

	lineLetter: {
		type: String,
		optional: true,
	},

	nLines: {
		type: Number,
		optional: true,
	},

	paragraphN: {
		type: Number,
		optional: true,
	},

	commentOrder: {
		type: Number,
		optional: true,
	},

	reference: {
		type: String,
		optional: true,
	},

	referenceLink: {
		type: String,
		optional: true,
	},

	referenceSection: {
		type: Number,
		optional: true,
	},

	referenceChapter: {
		type: Number,
		optional: true,
	},

	referenceTranslation: {
		type: Number,
		optional: true,
	},

	referenceNote: {
		type: Number,
		optional: true,
	},

	keywords: {
		type: [Object],
		optional: true,
		blackbox: true,
	},

	revisions: {
		type: [Object],
		optional: true,
		blackbox: true,
	},

	discussionComments: {
		type: [Object],
		optional: true,
		blackbox: true,
	},

	isAnnotation: {
		type: Boolean,
		autoValue: function() {
			if (this.isInsert)
				return false;
		},
		autoform: {
			type: 'hidden',
			label: false,
		},
	},
});

Comments.attachSchema(Schemas.Comments);

Comments.attachBehaviour('timestampable', {
  createdAt: 'created',
  createdBy: 'createdBy',
  updatedAt: 'updated',
  updatedBy: 'updatedBy'
});

/*
 Comments.helpers({
 commenters: function() {
 var ref, ref1, ref2, user;
 commenter = Commenters.findOne(this.commenter);
 if (commenter != null) {
 return commenter.name;
 } else {
 return null;
 }
 }
 });
 */
/*
 Comments.helpers({
 commentTitle: function(){
 var comment_title = "";
 console.log(this);

 if(this.work){
 comment_title += this.work.title + " ";
 }
 if(this.subwork){
 comment_title += this.subwork + ".";
 }
 if(this.lineFrom){
 comment_title += this.lineFrom;
 }

 if(this.lineTo){
 comment_title += "-" + this.lineTo;

 }

 return comment_title;
 }
 });
 */
<commit_msg>add users to comments for annotations created by users<commit_after>this.Comments = new Meteor.Collection('comments');

Schemas.Comments = new SimpleSchema({

	wordpressId: {
		type: Number,
		optional: true,
	},

	tenantId: {
			type: String,
			label: "Tenant",
			optional: true,
			autoform: {
				afFieldInput: {
					type: "select",
					options: function () {
						var tenants = [];
						_.map(Tenants.find().fetch(), function (tenant) {

							tenants.push({
								label: tenant.subdomain,
								value: tenant._id
							});

						});
						return tenants;
					}
				}
			}
	},

	commenters: {
		type: [Object],
		optional: true,
		blackbox: true,
		/*autoform: {
		 options: function() {
		 return _.map(Commenters.find().fetch(), function(commenter) {
		 return {
		 label: commenter.name,
		 value: commenter._id
		 };
		 });
		 }
		 }
		 */
	},

	users: {
		type: [Object],
		optional: true,
		blackbox: true,
	},

	work: {
		type: Object,
		optional: true,
		blackbox: true,

	},

	subwork: {
		type: Object,
		optional: true,
		blackbox: true,

	},

	lineFrom: {
		type: Number,
		optional: true,
	},

	lineTo: {
		type: Number,
		optional: true,
	},

	lineLetter: {
		type: String,
		optional: true,
	},

	nLines: {
		type: Number,
		optional: true,
	},

	paragraphN: {
		type: Number,
		optional: true,
	},

	commentOrder: {
		type: Number,
		optional: true,
	},

	reference: {
		type: String,
		optional: true,
	},

	referenceLink: {
		type: String,
		optional: true,
	},

	referenceSection: {
		type: Number,
		optional: true,
	},

	referenceChapter: {
		type: Number,
		optional: true,
	},

	referenceTranslation: {
		type: Number,
		optional: true,
	},

	referenceNote: {
		type: Number,
		optional: true,
	},

	keywords: {
		type: [Object],
		optional: true,
		blackbox: true,
	},

	revisions: {
		type: [Object],
		optional: true,
		blackbox: true,
	},

	discussionComments: {
		type: [Object],
		optional: true,
		blackbox: true,
	},

	isAnnotation: {
		type: Boolean,
		autoValue: function() {
			if (this.isInsert)
				return false;
		},
		autoform: {
			type: 'hidden',
			label: false,
		},
	},
});

Comments.attachSchema(Schemas.Comments);

Comments.attachBehaviour('timestampable', {
  createdAt: 'created',
  createdBy: 'createdBy',
  updatedAt: 'updated',
  updatedBy: 'updatedBy'
});

/*
 Comments.helpers({
 commenters: function() {
 var ref, ref1, ref2, user;
 commenter = Commenters.findOne(this.commenter);
 if (commenter != null) {
 return commenter.name;
 } else {
 return null;
 }
 }
 });
 */
/*
 Comments.helpers({
 commentTitle: function(){
 var comment_title = "";
 console.log(this);

 if(this.work){
 comment_title += this.work.title + " ";
 }
 if(this.subwork){
 comment_title += this.subwork + ".";
 }
 if(this.lineFrom){
 comment_title += this.lineFrom;
 }

 if(this.lineTo){
 comment_title += "-" + this.lineTo;

 }

 return comment_title;
 }
 });
 */
<|endoftext|>


<commit_before>/*
 * #%L
 * BroadleafCommerce Open Admin Platform
 * %%
 * Copyright (C) 2009 - 2013 Broadleaf Commerce
 * %%
 * 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.
 * #L%
 */
(function($, BLCAdmin) {

    var adminFormats = {
        blcDateFormat : "yy.mm.dd",
        blcTimeFormat : "HH:mm:ss",
        displayDateFormat : 'mm/dd/yy',
        displayTimeFormat : 'HH:mm:ss'
    };

    // Add utility functions for dates to the BLCAdmin object
    BLCAdmin.dates = {
        /**
         * This function should be called for any element that wants to be a rulebuilder
         */
        initialize : function($element) {
            // Set the value of this datepicker to be the appropriately formatted one
            $element.val(this.getDisplayDate($element.val()));

            // Make it a date-time picker
            $element.datetimepicker({
                showSecond: true,
                timeFormat: 'HH:mm:ss'
            });
        },

        /**
         * serverDate should be in the Broadleaf datetime format, "yyyy.MM.dd HH:mm:ss" (Java spec)
         * returns the display format, "mm/dd/yy HH:mm:ss" (JavaScript spec)
         */
        getDisplayDate : function(serverDate) {
            var display = BLC.dates.getDisplayDate(serverDate, adminFormats);
            return display == null ? null : display.displayDate + " " + display.displayTime;
        },

        /**
         * displayDate should be in the format "mm/dd/yy HH:mm" (JavaScript spec)
         * returns the server-expected format, "yyyy.MM.dd HH:mm:ss Z" (Java spec)
         */
        getServerDate : function(displayDate) {
            var server = BLC.dates.getServerDate(displayDate, adminFormats);
            return server == null ? null : server.serverDate + " " + server.serverTime;
        },

        initializationHandler : function($container) {
            $container.find('.datepicker').each(function(index, element) {
                BLCAdmin.dates.initialize($(element));
            });
        },

        postValidationSubmitHandler : function($form) {
            $form.find('.datepicker').each(function(index, element) {
                var $this = $(this);
                if ($this.closest('.entityFormTab').data('initialized') != 'true') {
                    BLCAdmin.dates.initialize($this);
                }

                var name = $this.attr('name');

                var $hiddenClone = $('<input>', {
                    type: 'hidden',
                    name: name,
                    value: BLCAdmin.dates.getServerDate($this.val()),
                    'class': 'datepicker-clone'
                });

                $(this).data('previous-name', name).removeAttr('name').after($hiddenClone);
            });
        }
    };

    BLCAdmin.addInitializationHandler(BLCAdmin.dates.initializationHandler);
    BLCAdmin.addPostValidationSubmitHandler(BLCAdmin.dates.postValidationSubmitHandler);

})(jQuery, BLCAdmin);

$(document).ready(function() {

    $('body').on('click', 'div.datepicker-container', function(event) {
        $(this).find('input').datepicker('show');
    });

});
<commit_msg>#318 - Fix problem with JS date formatting and scheduling a deployment for a date in the future<commit_after>/*
 * #%L
 * BroadleafCommerce Open Admin Platform
 * %%
 * Copyright (C) 2009 - 2013 Broadleaf Commerce
 * %%
 * 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.
 * #L%
 */
(function($, BLCAdmin) {

    var adminFormats = {
        blcDateFormat : "yy.mm.dd",
        blcTimeFormat : "HH:mm:ss",
        displayDateFormat : 'mm/dd/yy',
        displayTimeFormat : 'HH:mm:ss',
        displayDateDelimiter : '/'
    };

    // Add utility functions for dates to the BLCAdmin object
    BLCAdmin.dates = {
        /**
         * This function should be called for any element that wants to be a rulebuilder
         */
        initialize : function($element) {
            // Set the value of this datepicker to be the appropriately formatted one
            $element.val($element.val().contains(adminFormats.displayDateDelimiter)?this.getDisplayDate(this.getServerDate($element.val())):this.getDisplayDate($element.val()));

            // Make it a date-time picker
            $element.datetimepicker({
                showSecond: true,
                timeFormat: 'HH:mm:ss'
            });
        },

        /**
         * serverDate should be in the Broadleaf datetime format, "yyyy.MM.dd HH:mm:ss" (Java spec)
         * returns the display format, "mm/dd/yy HH:mm:ss" (JavaScript spec)
         */
        getDisplayDate : function(serverDate) {
            var display = BLC.dates.getDisplayDate(serverDate, adminFormats);
            return display == null ? null : display.displayDate + " " + display.displayTime;
        },

        /**
         * displayDate should be in the format "mm/dd/yy HH:mm" (JavaScript spec)
         * returns the server-expected format, "yyyy.MM.dd HH:mm:ss Z" (Java spec)
         */
        getServerDate : function(displayDate) {
            var server = BLC.dates.getServerDate(displayDate, adminFormats);
            return server == null ? null : server.serverDate + " " + server.serverTime;
        },

        initializationHandler : function($container) {
            $container.find('.datepicker').each(function(index, element) {
                BLCAdmin.dates.initialize($(element));
            });
        },

        postValidationSubmitHandler : function($form) {
            $form.find('.datepicker').each(function(index, element) {
                var $this = $(this);
                if ($this.closest('.entityFormTab').data('initialized') != 'true') {
                    BLCAdmin.dates.initialize($this);
                }

                var name = $this.attr('name');

                var $hiddenClone = $('<input>', {
                    type: 'hidden',
                    name: name,
                    value: BLCAdmin.dates.getServerDate($this.val()),
                    'class': 'datepicker-clone'
                });

                $(this).data('previous-name', name).removeAttr('name').after($hiddenClone);
            });
        }
    };

    BLCAdmin.addInitializationHandler(BLCAdmin.dates.initializationHandler);
    BLCAdmin.addPostValidationSubmitHandler(BLCAdmin.dates.postValidationSubmitHandler);

})(jQuery, BLCAdmin);

$(document).ready(function() {

    $('body').on('click', 'div.datepicker-container', function(event) {
        $(this).find('input').datepicker('show');
    });

});
<|endoftext|>


<commit_before>/**
 * Created by julia on 02.10.2016.
 */
var cmd = 'np';
var i18nBean = require('../utility/i18nManager');
var t = i18nBean.getT();
var voice = require('../utility/voice');
var execute = function (message) {
    if (message.guild) {
        voice.now(message).then(result => {
            if (result.playing) {
                let repeat = (result.repeat) ? t('np.repeat-on') : '';
                if (typeof (result.duration) !== 'undefined' && result.duration !== '') {
                    message.reply(t('np.song-duration', {
                        lngs: message.lang,
                        title: result.title,
                        repeat: repeat,
                        duration: result.duration,
                        current: result.current,
                        interpolation: {escape: false}
                    }));
                } else {
                    message.reply(t('np.song', {
                        lngs: message.lang,
                        title: result.title,
                        repeat: repeat,
                        interpolation: {escape: false}
                    }));
                }
            } else {
                message.reply(t('generic.no-song-in-queue', {lngs: message.lang}));
            }
        }).catch(err => {
                message.reply(t('generic.no-song-in-queue', {lngs: message.lang}));
            });
    }
};
module.exports = {cmd: cmd, accessLevel: 0, exec: execute};<commit_msg>Fixed a Translation error<commit_after>/**
 * Created by julia on 02.10.2016.
 */
var cmd = 'np';
var i18nBean = require('../utility/i18nManager');
var t = i18nBean.getT();
var voice = require('../utility/voice');
var execute = function (message) {
    if (message.guild) {
        voice.now(message).then(result => {
            if (result.playing) {
                let repeat = (result.repeat) ? t('np.repeat-on', {lngs: message.lang}) : '';
                if (typeof (result.duration) !== 'undefined' && result.duration !== '') {
                    message.reply(t('np.song-duration', {
                        lngs: message.lang,
                        title: result.title,
                        repeat: repeat,
                        duration: result.duration,
                        current: result.current,
                        interpolation: {escape: false}
                    }));
                } else {
                    message.reply(t('np.song', {
                        lngs: message.lang,
                        title: result.title,
                        repeat: repeat,
                        interpolation: {escape: false}
                    }));
                }
            } else {
                message.reply(t('generic.no-song-in-queue', {lngs: message.lang}));
            }
        }).catch(err => {
                message.reply(t('generic.no-song-in-queue', {lngs: message.lang}));
            });
    }
};
module.exports = {cmd: cmd, accessLevel: 0, exec: execute};<|endoftext|>


<commit_before>import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { DialogModal, HeaderModal, InnerModal, usePlans } from 'react-components';
import { c } from 'ttag';
import { CYCLE, CURRENCIES } from 'proton-shared/lib/constants';

import PlansTable from '../../../components/sections/plans/PlansTable';

const { MONTHLY, YEARLY, TWO_YEARS } = CYCLE;

const PlanComparisonModal = ({ modalTitleID = 'modalTitle', onClose, defaultCycle, defaultCurrency, ...rest }) => {
    const [cycle, setCycle] = useState(defaultCycle);
    const [currency, setCurrency] = useState(defaultCurrency);
    const [plans, loadingPlans] = usePlans();

    return (
        <DialogModal {...rest} onClose={onClose} className="pm-modal--wider">
            <HeaderModal hasClose modalTitleID={modalTitleID} onClose={onClose}>
                {c('Title').t`ProtonVPN plan comparison`}
            </HeaderModal>

                <InnerModal>
                    <PlansTable
                        expand={true}
                        loading={loadingPlans}
                        currency={currency}
                        cycle={cycle}
                        updateCurrency={setCurrency}
                        updateCycle={setCycle}
                        plans={plans}
                    />
                </InnerModal>

        </DialogModal>
    );
};

PlanComparisonModal.propTypes = {
    ...DialogModal.propTypes,
    cycle: PropTypes.oneOf([MONTHLY, TWO_YEARS, YEARLY]).isRequired,
    currency: PropTypes.oneOf(CURRENCIES).isRequired
};

export default PlanComparisonModal;
<commit_msg>Hotfix - Remove warning<commit_after>import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { DialogModal, HeaderModal, InnerModal, usePlans } from 'react-components';
import { c } from 'ttag';
import { CYCLE, CURRENCIES } from 'proton-shared/lib/constants';

import PlansTable from '../../../components/sections/plans/PlansTable';

const { MONTHLY, YEARLY, TWO_YEARS } = CYCLE;

const PlanComparisonModal = ({ modalTitleID = 'modalTitle', onClose, defaultCycle, defaultCurrency, ...rest }) => {
    const [cycle, setCycle] = useState(defaultCycle);
    const [currency, setCurrency] = useState(defaultCurrency);
    const [plans, loadingPlans] = usePlans();

    return (
        <DialogModal onClose={onClose} className="pm-modal--wider" {...rest}>
            <HeaderModal hasClose modalTitleID={modalTitleID} onClose={onClose}>
                {c('Title').t`ProtonVPN plan comparison`}
            </HeaderModal>

                <InnerModal>
                    <PlansTable
                        expand={true}
                        loading={loadingPlans}
                        currency={currency}
                        cycle={cycle}
                        updateCurrency={setCurrency}
                        updateCycle={setCycle}
                        plans={plans}
                    />
                </InnerModal>

        </DialogModal>
    );
};

PlanComparisonModal.propTypes = {
    ...DialogModal.propTypes,
    cycle: PropTypes.oneOf([MONTHLY, TWO_YEARS, YEARLY]).isRequired,
    currency: PropTypes.oneOf(CURRENCIES).isRequired
};

export default PlanComparisonModal;
<|endoftext|>


<commit_before>/*
Language: C++
Contributors: Evgeny Stepanischev <imbolk@gmail.com>
*/

function(hljs) {
  var CPP_KEYWORDS = {
    keyword: 'false int float while private char catch export virtual operator sizeof ' +
      'dynamic_cast|10 typedef const_cast|10 const struct for static_cast|10 union namespace ' +
      'unsigned long throw volatile static protected bool template mutable if public friend ' +
      'do return goto auto void enum else break new extern using true class asm case typeid ' +
      'short reinterpret_cast|10 default double register explicit signed typename try this ' +
      'switch continue wchar_t inline delete alignof char16_t char32_t constexpr decltype ' +
      'noexcept nullptr static_assert thread_local restrict _Bool complex',
    built_in: 'std string cin cout cerr clog stringstream istringstream ostringstream ' +
      'auto_ptr deque list queue stack vector map set bitset multiset multimap unordered_set ' +
      'unordered_map unordered_multiset unordered_multimap array shared_ptr'
  };
  return {
    keywords: CPP_KEYWORDS,
    illegal: '</',
    contains: [
      hljs.C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE,
      hljs.QUOTE_STRING_MODE,
      {
        className: 'string',
        begin: '\'\\\\?.', end: '\'',
        illegal: '.'
      },
      {
        className: 'number',
        begin: '\\b(\\d+(\\.\\d*)?|\\.\\d+)(u|U|l|L|ul|UL|f|F)'
      },
      hljs.C_NUMBER_MODE,
      {
        className: 'preprocessor',
        begin: '#', end: '$'
      },
      {
        className: 'stl_container',
        begin: '\\b(deque|list|queue|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array)\\s*<', end: '>',
        keywords: CPP_KEYWORDS,
        relevance: 10,
        contains: ['self']
      }
    ]
  };
}
<commit_msg>Allow line comments in C++ preprocessor directives<commit_after>/*
Language: C++
Contributors: Evgeny Stepanischev <imbolk@gmail.com>
*/

function(hljs) {
  var CPP_KEYWORDS = {
    keyword: 'false int float while private char catch export virtual operator sizeof ' +
      'dynamic_cast|10 typedef const_cast|10 const struct for static_cast|10 union namespace ' +
      'unsigned long throw volatile static protected bool template mutable if public friend ' +
      'do return goto auto void enum else break new extern using true class asm case typeid ' +
      'short reinterpret_cast|10 default double register explicit signed typename try this ' +
      'switch continue wchar_t inline delete alignof char16_t char32_t constexpr decltype ' +
      'noexcept nullptr static_assert thread_local restrict _Bool complex',
    built_in: 'std string cin cout cerr clog stringstream istringstream ostringstream ' +
      'auto_ptr deque list queue stack vector map set bitset multiset multimap unordered_set ' +
      'unordered_map unordered_multiset unordered_multimap array shared_ptr'
  };
  return {
    keywords: CPP_KEYWORDS,
    illegal: '</',
    contains: [
      hljs.C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE,
      hljs.QUOTE_STRING_MODE,
      {
        className: 'string',
        begin: '\'\\\\?.', end: '\'',
        illegal: '.'
      },
      {
        className: 'number',
        begin: '\\b(\\d+(\\.\\d*)?|\\.\\d+)(u|U|l|L|ul|UL|f|F)'
      },
      hljs.C_NUMBER_MODE,
      {
        className: 'preprocessor',
        begin: '#', end: '$',
        contains: [hljs.C_LINE_COMMENT_MODE]
      },
      {
        className: 'stl_container',
        begin: '\\b(deque|list|queue|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array)\\s*<', end: '>',
        keywords: CPP_KEYWORDS,
        relevance: 10,
        contains: ['self']
      }
    ]
  };
}
<|endoftext|>


<commit_before>/*
Language: C++
Author: Ivan Sagalaev <maniac@softwaremaniacs.org>
Contributors: Evgeny Stepanischev <imbolk@gmail.com>, Zaven Muradyan <megalivoithos@gmail.com>, Roel Deckers <admin@codingcat.nl>
Category: common, system
*/

function(hljs) {
  var CPP_KEYWORDS = {
    keyword: 'false int float while private char catch export virtual operator sizeof ' +
      'dynamic_cast|10 typedef const_cast|10 const struct for static_cast|10 union namespace ' +
      'unsigned long throw volatile static protected bool template mutable if public friend ' +
      'do return goto auto void enum else break new extern using true class asm case typeid ' +
      'short reinterpret_cast|10 default double register explicit signed typename try this ' +
      'switch continue wchar_t inline delete alignof char16_t char32_t constexpr decltype ' +
      'noexcept nullptr static_assert thread_local restrict _Bool complex _Complex _Imaginary' +
      'intmax_t uintmax_t int8_t uint8_t int16_t uint16_t int32_t uint32_t  int64_t uint64_t' +
      'int_least8_t uint_least8_t int_least16_t uint_least16_t int_least32_t uint_least32_t' +
      'int_least64_t uint_least64_t int_fast8_t uint_fast8_t int_fast16_t uint_fast16_t int_fast32_t' +
      'uint_fast32_t int_fast64_t uint_fast64_t intptr_t uintptr_t atomic_bool atomic_char atomic_schar' +
      'atomic_uchar atomic_short atomic_ushort atomic_int atomic_uint atomic_long atomic_ulong atomic_llong' +
      'atomic_ullong atomic_wchar_t atomic_char16_t atomic_char32_t atomic_intmax_t atomic_uintmax_t' +
      'atomic_intptr_t atomic_uintptr_t atomic_size_t atomic_ptrdiff_t atomic_int_least8_t atomic_int_least16_t' +
      'atomic_int_least32_t atomic_int_least64_t atomic_uint_least8_t atomic_uint_least16_t atomic_uint_least32_t' +
      'atomic_uint_least64_t atomic_int_fast8_t atomic_int_fast16_t atomic_int_fast32_t atomic_int_fast64_t' +
      'atomic_uint_fast8_t atomic_uint_fast16_t atomic_uint_fast32_t atomic_uint_fast64_t',
    built_in: 'std string cin cout cerr clog stringstream istringstream ostringstream ' +
      'auto_ptr deque list queue stack vector map set bitset multiset multimap unordered_set ' +
      'unordered_map unordered_multiset unordered_multimap array shared_ptr abort abs acos ' +
      'asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp ' +
      'fscanf isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper ' +
      'isxdigit tolower toupper labs ldexp log10 log malloc memchr memcmp memcpy memset modf pow ' +
      'printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp ' +
      'strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan ' +
      'vfprintf vprintf vsprintf'
  };
  return {
    aliases: ['c', 'h', 'c++', 'h++'],
    keywords: CPP_KEYWORDS,
    illegal: '</',
    contains: [
      hljs.C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE,
      hljs.QUOTE_STRING_MODE,
      {
        className: 'string',
        begin: '\'\\\\?.', end: '\'',
        illegal: '.'
      },
      {
        className: 'number',
        begin: '\\b(\\d+(\\.\\d*)?|\\.\\d+)(u|U|l|L|ul|UL|f|F)'
      },
      hljs.C_NUMBER_MODE,
      {
        className: 'preprocessor',
        begin: '#', end: '$',
        keywords: 'if else elif endif define undef warning error line pragma',
        contains: [
          {
            begin: 'include\\s*[<"]', end: '[>"]',
            keywords: 'include',
            illegal: '\\n'
          },
          hljs.C_LINE_COMMENT_MODE
        ]
      },
      {
        className: 'stl_container',
        begin: '\\b(deque|list|queue|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array)\\s*<', end: '>',
        keywords: CPP_KEYWORDS,
        contains: ['self']
      },
      {
        begin: hljs.IDENT_RE + '::'
      }
    ]
  };
}
<commit_msg>Function titles for cpp.<commit_after>/*
Language: C++
Author: Ivan Sagalaev <maniac@softwaremaniacs.org>
Contributors: Evgeny Stepanischev <imbolk@gmail.com>, Zaven Muradyan <megalivoithos@gmail.com>, Roel Deckers <admin@codingcat.nl>
Category: common, system
*/

function(hljs) {
  var CPP_KEYWORDS = {
    keyword: 'false int float while private char catch export virtual operator sizeof ' +
      'dynamic_cast|10 typedef const_cast|10 const struct for static_cast|10 union namespace ' +
      'unsigned long volatile static protected bool template mutable if public friend ' +
      'do goto auto void enum else break extern using true class asm case typeid ' +
      'short reinterpret_cast|10 default double register explicit signed typename try this ' +
      'switch continue wchar_t inline delete alignof char16_t char32_t constexpr decltype ' +
      'noexcept nullptr static_assert thread_local restrict _Bool complex _Complex _Imaginary' +
      'intmax_t uintmax_t int8_t uint8_t int16_t uint16_t int32_t uint32_t  int64_t uint64_t' +
      'int_least8_t uint_least8_t int_least16_t uint_least16_t int_least32_t uint_least32_t' +
      'int_least64_t uint_least64_t int_fast8_t uint_fast8_t int_fast16_t uint_fast16_t int_fast32_t' +
      'uint_fast32_t int_fast64_t uint_fast64_t intptr_t uintptr_t atomic_bool atomic_char atomic_schar' +
      'atomic_uchar atomic_short atomic_ushort atomic_int atomic_uint atomic_long atomic_ulong atomic_llong' +
      'atomic_ullong atomic_wchar_t atomic_char16_t atomic_char32_t atomic_intmax_t atomic_uintmax_t' +
      'atomic_intptr_t atomic_uintptr_t atomic_size_t atomic_ptrdiff_t atomic_int_least8_t atomic_int_least16_t' +
      'atomic_int_least32_t atomic_int_least64_t atomic_uint_least8_t atomic_uint_least16_t atomic_uint_least32_t' +
      'atomic_uint_least64_t atomic_int_fast8_t atomic_int_fast16_t atomic_int_fast32_t atomic_int_fast64_t' +
      'atomic_uint_fast8_t atomic_uint_fast16_t atomic_uint_fast32_t atomic_uint_fast64_t',
    built_in: 'std string cin cout cerr clog stringstream istringstream ostringstream ' +
      'auto_ptr deque list queue stack vector map set bitset multiset multimap unordered_set ' +
      'unordered_map unordered_multiset unordered_multimap array shared_ptr abort abs acos ' +
      'asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp ' +
      'fscanf isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper ' +
      'isxdigit tolower toupper labs ldexp log10 log malloc memchr memcmp memcpy memset modf pow ' +
      'printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp ' +
      'strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan ' +
      'vfprintf vprintf vsprintf'
  };
  return {
    aliases: ['c', 'h', 'c++', 'h++'],
    keywords: CPP_KEYWORDS,
    illegal: '</',
    contains: [
      hljs.C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE,
      hljs.QUOTE_STRING_MODE,
      {
        className: 'string',
        begin: '\'\\\\?.', end: '\'',
        illegal: '.'
      },
      {
        className: 'number',
        begin: '\\b(\\d+(\\.\\d*)?|\\.\\d+)(u|U|l|L|ul|UL|f|F)'
      },
      hljs.C_NUMBER_MODE,
      {
        className: 'preprocessor',
        begin: '#', end: '$',
        keywords: 'if else elif endif define undef warning error line pragma',
        contains: [
          {
            begin: 'include\\s*[<"]', end: '[>"]',
            keywords: 'include',
            illegal: '\\n'
          },
          hljs.C_LINE_COMMENT_MODE
        ]
      },
      {
        className: 'stl_container',
        begin: '\\b(deque|list|queue|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array)\\s*<', end: '>',
        keywords: CPP_KEYWORDS,
        contains: ['self']
      },
      {
        begin: hljs.IDENT_RE + '::'
      },
      {
        // Expression keywords prevent 'keyword Name(...)' from being
        // recognized as a function definition
        beginKeywords: 'new throw return',
        relevance: 0
      },
      {
        className: 'function',
        begin: '(' + hljs.IDENT_RE + '\\s+)+' + hljs.IDENT_RE + '\\s*\\(', returnBegin: true, end: /[{;=]/,
        excludeEnd: true,
        keywords: CPP_KEYWORDS,
        contains: [
          {
            begin: hljs.IDENT_RE + '\\s*\\(', returnBegin: true,
            contains: [hljs.TITLE_MODE],
            relevance: 0
          },
          {
            className: 'params',
            begin: /\(/, end: /\)/,
            keywords: CPP_KEYWORDS,
            relevance: 0,
            contains: [
              hljs.C_BLOCK_COMMENT_MODE
            ]
          },
          hljs.C_LINE_COMMENT_MODE,
          hljs.C_BLOCK_COMMENT_MODE
        ]
      }
    ]
  };
}
<|endoftext|>


<commit_before>"use strict";

const net = require("net");
const execa = require("execa");

const args = {
  v4: ["-4", "-r"],
  v6: ["-6", "-r"],
};

const get = family => {
  return execa.stdout("ip", args[family]).then(stdout => {
    let result;

    (stdout || "").trim().split("\n").some(line => {
      const [_, gateway, iface] = /default via (.+?) dev (.+?)( |$)/.exec(line) || [];
      if (gateway && net.isIP(gateway)) {
        result = {gateway: gateway, interface: (iface ? iface : null)};
        return true;
      }
    });

    if (!result) {
      throw new Error("Unable to determine default gateway");
    }

    return result;
  });
};

module.exports.v4 = () => get("v4");
module.exports.v6 = () => get("v6");
<commit_msg>fix linux<commit_after>"use strict";

const net = require("net");
const execa = require("execa");

const args = {
  v4: ["-4", "r"],
  v6: ["-6", "r"],
};

const get = family => {
  return execa.stdout("ip", args[family]).then(stdout => {
    let result;

    (stdout || "").trim().split("\n").some(line => {
      const [_, gateway, iface] = /default via (.+?) dev (.+?)( |$)/.exec(line) || [];
      if (gateway && net.isIP(gateway)) {
        result = {gateway: gateway, interface: (iface ? iface : null)};
        return true;
      }
    });

    if (!result) {
      throw new Error("Unable to determine default gateway");
    }

    return result;
  });
};

module.exports.v4 = () => get("v4");
module.exports.v6 = () => get("v6");
<|endoftext|>


<commit_before>/*
Language: C++
*/

hljs.LANGUAGES.cpp = function(){
  var CPP_KEYWORDS = {
    'keyword': {
      'false': 1, 'int': 1, 'float': 1, 'while': 1, 'private': 1, 'char': 1,
      'catch': 1, 'export': 1, 'virtual': 1, 'operator': 2, 'sizeof': 2,
      'dynamic_cast': 2, 'typedef': 2, 'const_cast': 2, 'const': 1,
      'struct': 1, 'for': 1, 'static_cast': 2, 'union': 1, 'namespace': 1,
      'unsigned': 1, 'long': 1, 'throw': 1, 'volatile': 2, 'static': 1,
      'protected': 1, 'bool': 1, 'template': 1, 'mutable': 1, 'if': 1,
      'public': 1, 'friend': 2, 'do': 1, 'return': 1, 'goto': 1, 'auto': 1,
      'void': 2, 'enum': 1, 'else': 1, 'break': 1, 'new': 1, 'extern': 1,
      'using': 1, 'true': 1, 'class': 1, 'asm': 1, 'case': 1, 'typeid': 1,
      'short': 1, 'reinterpret_cast': 2, 'default': 1, 'double': 1,
      'register': 1, 'explicit': 1, 'signed': 1, 'typename': 1, 'try': 1,
      'this': 1, 'switch': 1, 'continue': 1, 'wchar_t': 1, 'inline': 1,
      'delete': 1, 'alignof': 1, 'char16_t': 1, 'char32_t': 1, 'constexpr': 1,
      'decltype': 1, 'noexcept': 1, 'nullptr': 1, 'static_assert': 1,
      'thread_local': 1
    },
    'built_in': {
      'std': 1, 'string': 1, 'cin': 1, 'cout': 1, 'cerr': 1, 'clog': 1,
      'stringstream': 1, 'istringstream': 1, 'ostringstream': 1, 'auto_ptr': 1,
      'deque': 1, 'list': 1, 'queue': 1, 'stack': 1, 'vector': 1, 'map': 1,
      'set': 1, 'bitset': 1, 'multiset': 1, 'multimap': 1, 'unordered_set': 1,
      'unordered_map': 1, 'unordered_multiset': 1, 'unordered_multimap': 1,
      'array': 1, 'shared_ptr': 1
    }
  };
  return {
    defaultMode: {
      keywords: CPP_KEYWORDS,
      illegal: '</',
      contains: [
        hljs.C_LINE_COMMENT_MODE,
        hljs.C_BLOCK_COMMENT_MODE,
        hljs.QUOTE_STRING_MODE,
        {
          className: 'string',
          begin: '\'\\\\?.', end: '\'',
          illegal: '.'
        },
        hljs.C_NUMBER_MODE,
        {
          className: 'preprocessor',
          begin: '#', end: '$'
        },
        {
          className: 'stl_container',
          begin: '\\b(deque|list|queue|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array)\\s*<', end: '>',
          keywords: CPP_KEYWORDS,
          relevance: 10,
          contains: ['self']
        }
      ]
    }
  };
}();
<commit_msg>+restrict keyword (C99)<commit_after>/*
Language: C++
Contributors: Evgeny Stepanischev <imbolk@gmail.com>
*/

hljs.LANGUAGES.cpp = function(){
  var CPP_KEYWORDS = {
    'keyword': {
      'false': 1, 'int': 1, 'float': 1, 'while': 1, 'private': 1, 'char': 1,
      'catch': 1, 'export': 1, 'virtual': 1, 'operator': 2, 'sizeof': 2,
      'dynamic_cast': 2, 'typedef': 2, 'const_cast': 2, 'const': 1,
      'struct': 1, 'for': 1, 'static_cast': 2, 'union': 1, 'namespace': 1,
      'unsigned': 1, 'long': 1, 'throw': 1, 'volatile': 2, 'static': 1,
      'protected': 1, 'bool': 1, 'template': 1, 'mutable': 1, 'if': 1,
      'public': 1, 'friend': 2, 'do': 1, 'return': 1, 'goto': 1, 'auto': 1,
      'void': 2, 'enum': 1, 'else': 1, 'break': 1, 'new': 1, 'extern': 1,
      'using': 1, 'true': 1, 'class': 1, 'asm': 1, 'case': 1, 'typeid': 1,
      'short': 1, 'reinterpret_cast': 2, 'default': 1, 'double': 1,
      'register': 1, 'explicit': 1, 'signed': 1, 'typename': 1, 'try': 1,
      'this': 1, 'switch': 1, 'continue': 1, 'wchar_t': 1, 'inline': 1,
      'delete': 1, 'alignof': 1, 'char16_t': 1, 'char32_t': 1, 'constexpr': 1,
      'decltype': 1, 'noexcept': 1, 'nullptr': 1, 'static_assert': 1,
      'thread_local': 1, 'restrict': 1
    },
    'built_in': {
      'std': 1, 'string': 1, 'cin': 1, 'cout': 1, 'cerr': 1, 'clog': 1,
      'stringstream': 1, 'istringstream': 1, 'ostringstream': 1, 'auto_ptr': 1,
      'deque': 1, 'list': 1, 'queue': 1, 'stack': 1, 'vector': 1, 'map': 1,
      'set': 1, 'bitset': 1, 'multiset': 1, 'multimap': 1, 'unordered_set': 1,
      'unordered_map': 1, 'unordered_multiset': 1, 'unordered_multimap': 1,
      'array': 1, 'shared_ptr': 1
    }
  };
  return {
    defaultMode: {
      keywords: CPP_KEYWORDS,
      illegal: '</',
      contains: [
        hljs.C_LINE_COMMENT_MODE,
        hljs.C_BLOCK_COMMENT_MODE,
        hljs.QUOTE_STRING_MODE,
        {
          className: 'string',
          begin: '\'\\\\?.', end: '\'',
          illegal: '.'
        },
        hljs.C_NUMBER_MODE,
        {
          className: 'preprocessor',
          begin: '#', end: '$'
        },
        {
          className: 'stl_container',
          begin: '\\b(deque|list|queue|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array)\\s*<', end: '>',
          keywords: CPP_KEYWORDS,
          relevance: 10,
          contains: ['self']
        }
      ]
    }
  };
}();
<|endoftext|>


<commit_before>/*
Language: CSS
Category: common, css
Website: https://developer.mozilla.org/en-US/docs/Web/CSS
*/

/** @type LanguageFn */
export default function(hljs) {
  var FUNCTION_LIKE = {
    begin: /[\w-]+\(/, returnBegin: true,
    contains: [
      {
        className: 'built_in',
        begin: /[\w-]+/
      },
      {
        begin: /\(/, end: /\)/,
        contains: [
          hljs.APOS_STRING_MODE,
          hljs.QUOTE_STRING_MODE,
          hljs.CSS_NUMBER_MODE,
        ]
      }
    ]
  }
  var ATTRIBUTE = {
    className: 'attribute',
    begin: /\S/, end: ':', excludeEnd: true,
    starts: {
      endsWithParent: true, excludeEnd: true,
      contains: [
        FUNCTION_LIKE,
        hljs.CSS_NUMBER_MODE,
        hljs.QUOTE_STRING_MODE,
        hljs.APOS_STRING_MODE,
        hljs.C_BLOCK_COMMENT_MODE,
        {
          className: 'number', begin: '#[0-9A-Fa-f]+'
        },
        {
          className: 'meta', begin: '!important'
        }
      ]
    }
  }
  var AT_IDENTIFIER = '@[a-z-]+' // @font-face
  var AT_MODIFIERS = "and or not only"
  var MEDIA_TYPES = "all print screen speech"
  var AT_PROPERTY_RE = /@-?\w[\w]*(-\w+)*/ // @-webkit-keyframes
  var IDENT_RE = '[a-zA-Z-][a-zA-Z0-9_-]*';
  var RULE = {
    begin: /(?:[A-Z_.-]+|--[a-zA-Z0-9_-]+)\s*:/, returnBegin: true, end: ';', endsWithParent: true,
    contains: [
      ATTRIBUTE
    ]
  };

  return {
    name: 'CSS',
    case_insensitive: true,
    illegal: /[=|'\$]/,
    contains: [
      hljs.C_BLOCK_COMMENT_MODE,
      {
        className: 'selector-id', begin: /#[A-Za-z0-9_-]+/
      },
      {
        className: 'selector-class', begin: '\\.' + IDENT_RE
      },
      {
        className: 'selector-attr',
        begin: /\[/, end: /\]/,
        illegal: '$',
        contains: [
          hljs.APOS_STRING_MODE,
          hljs.QUOTE_STRING_MODE,
        ]
      },
      {
        className: 'selector-pseudo',
        begin: /:(:)?[a-zA-Z0-9_+()"'.-]+/
      },
      // matching these here allows us to treat them more like regular CSS
      // rules so everything between the {} gets regular rule highlighting,
      // which is what we want for page and font-face
      {
        begin: '@(page|font-face)',
        lexemes: AT_IDENTIFIER,
        keywords: '@page @font-face'
      },
      {
        begin: '@', end: '[{;]', // at_rule eating first "{" is a good thing
                                 // because it doesn’t let it to be parsed as
                                 // a rule set but instead drops parser into
                                 // the default mode which is how it should be.
        illegal: /:/, // break on Less variables @var: ...
        returnBegin: true,
        contains: [
          {
            className: 'keyword',
            begin: AT_PROPERTY_RE
          },
          {
            begin: /\s/, endsWithParent: true, excludeEnd: true,
            relevance: 0,
            keywords: AT_MODIFIERS,
            contains: [
              {
                begin: /[a-z-]+:/,
                className:"attribute"
              },
              hljs.APOS_STRING_MODE,
              hljs.QUOTE_STRING_MODE,
              hljs.CSS_NUMBER_MODE
            ]
          }
        ]
      },
      {
        className: 'selector-tag', begin: IDENT_RE,
        relevance: 0
      },
      {
        begin: /\{/, end: /\}/,
        illegal: /\S/,
        contains: [
          hljs.C_BLOCK_COMMENT_MODE,
          RULE,
        ]
      }
    ]
  };
}
<commit_msg>fix(autodetect) css: allow extra ;<commit_after>/*
Language: CSS
Category: common, css
Website: https://developer.mozilla.org/en-US/docs/Web/CSS
*/

/** @type LanguageFn */
export default function(hljs) {
  var FUNCTION_LIKE = {
    begin: /[\w-]+\(/, returnBegin: true,
    contains: [
      {
        className: 'built_in',
        begin: /[\w-]+/
      },
      {
        begin: /\(/, end: /\)/,
        contains: [
          hljs.APOS_STRING_MODE,
          hljs.QUOTE_STRING_MODE,
          hljs.CSS_NUMBER_MODE,
        ]
      }
    ]
  }
  var ATTRIBUTE = {
    className: 'attribute',
    begin: /\S/, end: ':', excludeEnd: true,
    starts: {
      endsWithParent: true, excludeEnd: true,
      contains: [
        FUNCTION_LIKE,
        hljs.CSS_NUMBER_MODE,
        hljs.QUOTE_STRING_MODE,
        hljs.APOS_STRING_MODE,
        hljs.C_BLOCK_COMMENT_MODE,
        {
          className: 'number', begin: '#[0-9A-Fa-f]+'
        },
        {
          className: 'meta', begin: '!important'
        }
      ]
    }
  }
  var AT_IDENTIFIER = '@[a-z-]+' // @font-face
  var AT_MODIFIERS = "and or not only"
  var MEDIA_TYPES = "all print screen speech"
  var AT_PROPERTY_RE = /@-?\w[\w]*(-\w+)*/ // @-webkit-keyframes
  var IDENT_RE = '[a-zA-Z-][a-zA-Z0-9_-]*';
  var RULE = {
    begin: /(?:[A-Z_.-]+|--[a-zA-Z0-9_-]+)\s*:/, returnBegin: true, end: ';', endsWithParent: true,
    contains: [
      ATTRIBUTE
    ]
  };

  return {
    name: 'CSS',
    case_insensitive: true,
    illegal: /[=|'\$]/,
    contains: [
      hljs.C_BLOCK_COMMENT_MODE,
      {
        className: 'selector-id', begin: /#[A-Za-z0-9_-]+/
      },
      {
        className: 'selector-class', begin: '\\.' + IDENT_RE
      },
      {
        className: 'selector-attr',
        begin: /\[/, end: /\]/,
        illegal: '$',
        contains: [
          hljs.APOS_STRING_MODE,
          hljs.QUOTE_STRING_MODE,
        ]
      },
      {
        className: 'selector-pseudo',
        begin: /:(:)?[a-zA-Z0-9_+()"'.-]+/
      },
      // matching these here allows us to treat them more like regular CSS
      // rules so everything between the {} gets regular rule highlighting,
      // which is what we want for page and font-face
      {
        begin: '@(page|font-face)',
        lexemes: AT_IDENTIFIER,
        keywords: '@page @font-face'
      },
      {
        begin: '@', end: '[{;]', // at_rule eating first "{" is a good thing
                                 // because it doesn’t let it to be parsed as
                                 // a rule set but instead drops parser into
                                 // the default mode which is how it should be.
        illegal: /:/, // break on Less variables @var: ...
        returnBegin: true,
        contains: [
          {
            className: 'keyword',
            begin: AT_PROPERTY_RE
          },
          {
            begin: /\s/, endsWithParent: true, excludeEnd: true,
            relevance: 0,
            keywords: AT_MODIFIERS,
            contains: [
              {
                begin: /[a-z-]+:/,
                className:"attribute"
              },
              hljs.APOS_STRING_MODE,
              hljs.QUOTE_STRING_MODE,
              hljs.CSS_NUMBER_MODE
            ]
          }
        ]
      },
      {
        className: 'selector-tag', begin: IDENT_RE,
        relevance: 0
      },
      {
        begin: /\{/, end: /\}/,
        illegal: /\S/,
        contains: [
          hljs.C_BLOCK_COMMENT_MODE,
          { begin: /;/ }, // empty ; rule
          RULE,
        ]
      }
    ]
  };
}
<|endoftext|>