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

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

// Statics
import TableFragment from '../_statics/TableFragment';
import HorizontalAlign from '../_statics/HorizontalAlign';
import SelectMode from '../_statics/SelectMode';
import SelectAllMode from '../_statics/SelectAllMode';
import SortingType from '../_statics/SortingType';

// Vendors
import Util from '../_vendors/Util';
import TC from '../_vendors/TableCalculation';

class ColGroup extends Component {

    static Fragment = TableFragment;
    static Align = HorizontalAlign;
    static SelectMode = SelectMode;
    static SelectAllMode = SelectAllMode;
    static SortingType = SortingType;

    constructor(props, ...restArgs) {
        super(props, ...restArgs);
    }

    getColumnWidth = column => {

        const {columnKeyField, columnsWidth, useColumnsWidth, data} = this.props;

        if (useColumnsWidth && columnKeyField && columnsWidth) {
            const width = columnsWidth.get(TC.getColumnKey(column, columnKeyField));
            if (width) {
                return width;
            }
        }

        if (typeof column.width === 'function') {
            const width = column.width(data);
            if (width) {
                return width;
            }
        }

        return column.width || null;

    };

    getColStyle = column => {

        const result = {
            width: this.getColumnWidth(column)
        };

        // min width
        result.minWidth = column.minWidth ?
            column.minWidth
            :
            result.width;

        return !result.width && !result.minWidth ? null : result;

    };

    render() {

        const {columns, ignoreColumnSpan} = this.props;

        return columns ?
            <colgroup>
                {
                    columns.map(({column, span}, index) => column ?
                        <col key={index}
                             style={this.getColStyle(column)}
                             span={ignoreColumnSpan ? null : (span && span > 1 ? span : null)}/>
                        :
                        null
                    )
                }
            </colgroup>
            :
            null;

    }

}

ColGroup.propTypes = {

    /**
     * Children passed into table header.
     */
    columns: PropTypes.arrayOf(PropTypes.shape({

        /**
         * unique keyof column.
         */
        key: PropTypes.string,

        /**
         * fixed position of column ( 'left' / 'right' ).
         */
        fixed: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * width of column.
         */
        width: PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.func]),

        /**
         * minimum width of column.
         */
        minWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),

        /**
         * align of current column.
         */
        align: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * no wrap of current column.
         */
        noWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),

        /**
         * The class name of header.
         */
        headClassName: PropTypes.string,

        /**
         * Override the styles of header.
         */
        headStyle: PropTypes.object,

        /**
         * align of table header cell
         */
        headAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * The render content in table head.
         *  (1) callback:
         *      function (tableData, colIndex) {
         *          return colIndex;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        headRenderer: PropTypes.any,

        /**
         * The title in table head.
         *  (1) callback:
         *      function (tableData, colIndex) {
         *          return colIndex;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        headTitle: PropTypes.any,

        /**
         * column span of table header.
         *  (1) function callback:
         *      function (tableData, colIndex) {
         *          return null;
         *      }
         *
         *  (2) number:
         *      render whatever you pass
         */
        headSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * no wrap of table header.
         */
        headNoWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),

        /**
         * The class name of td.
         */
        bodyClassName: PropTypes.string,

        /**
         * Override the styles of td.
         */
        bodyStyle: PropTypes.object,

        /**
         * align of table body cell.
         */
        bodyAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * The render content in table body.
         *  (1) callback:
         *      function (rowData, rowIndex, colIndex, parentData, tableData, collapsed, depth, path) {
         *          return rowData.id;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        bodyRenderer: PropTypes.any,

        /**
         * The title in table body.
         *  (1) callback:
         *      function (rowData, rowIndex, colIndex, parentData, tableData, collapsed, depth, path) {
         *          return rowData.id;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        bodyTitle: PropTypes.any,

        /**
         * column span of table body.
         *  (1) function callback:
         *      function (rowData, colIndex, rowIndex) {
         *          return null;
         *      }
         *
         *  (2) number:
         *      render whatever you pass
         */
        bodySpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * no wrap of table body.
         */
        bodyNoWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),

        /**
         * The class name of footer.
         */
        footClassName: PropTypes.string,

        /**
         * Override the styles of footer.
         */
        footStyle: PropTypes.object,

        /**
         * align of table footer cell
         */
        footAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * The render content in table foot.
         *  (1) callback:
         *      function (tableData, colIndex) {
         *          return colIndex;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        footRenderer: PropTypes.any,

        /**
         * The title in table foot.
         *  (1) callback:
         *      function (tableData, colIndex) {
         *          return colIndex;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        footTitle: PropTypes.any,

        /**
         * column span of table foot.
         *  (1) function callback:
         *      function (tableData, colIndex) {
         *          return null;
         *      }
         *
         *  (2) number:
         *      render whatever you pass
         */
        footSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * no wrap of table foot.
         */
        footNoWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),

        /**
         * If true, this column can be sorted.
         */
        sortable: PropTypes.bool,

        /**
         * Sorting property.
         */
        sortingProp: PropTypes.string,

        defaultSortingType: PropTypes.oneOf(Util.enumerateValue(SortingType)),

        /**
         * whether the column can be resized
         */
        resizable: PropTypes.bool

    })).isRequired,
    columnKeyField: PropTypes.string,
    columnsWidth: PropTypes.object,
    useColumnsWidth: PropTypes.bool,

    data: PropTypes.array,

    /**
     * column resizable
     */
    defaultColumnWidth: PropTypes.number,
    minColumnWidth: PropTypes.number,

    ignoreColumnSpan: PropTypes.bool

};

ColGroup.defaultProps = {

    columnKeyField: 'key',
    useColumnsWidth: false,

    /**
     * column resizable
     */
    defaultColumnWidth: 100,
    minColumnWidth: 64,

    ignoreColumnSpan: false

};

export default ColGroup;
<commit_msg>update ColGroup<commit_after>/**
 * @file ColGroup component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

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

// Statics
import TableFragment from '../_statics/TableFragment';
import HorizontalAlign from '../_statics/HorizontalAlign';
import SelectMode from '../_statics/SelectMode';
import SelectAllMode from '../_statics/SelectAllMode';
import SortingType from '../_statics/SortingType';

// Vendors
import Util from '../_vendors/Util';
import TC from '../_vendors/TableCalculation';

class ColGroup extends Component {

    static Fragment = TableFragment;
    static Align = HorizontalAlign;
    static SelectMode = SelectMode;
    static SelectAllMode = SelectAllMode;
    static SortingType = SortingType;

    constructor(props, ...restArgs) {
        super(props, ...restArgs);
    }

    getColumnWidth = column => {

        const {columnKeyField, columnsWidth, data} = this.props;

        if (columnKeyField && columnsWidth) {
            const width = columnsWidth.get(TC.getColumnKey(column, columnKeyField));
            if (width) {
                return width;
            }
        }

        if (typeof column.width === 'function') {
            const width = column.width(data);
            if (width) {
                return width;
            }
        }

        return column.width || null;

    };

    getColStyle = column => {

        const result = {
            width: this.getColumnWidth(column)
        };

        // min width
        result.minWidth = column.minWidth ?
            column.minWidth
            :
            result.width;

        return !result.width && !result.minWidth ? null : result;

    };

    render() {

        const {columns, ignoreColumnSpan} = this.props;

        return columns ?
            <colgroup>
                {
                    columns.map(({column, span}, index) => column ?
                        <col key={index}
                             style={this.getColStyle(column)}
                             span={ignoreColumnSpan ? null : (span && span > 1 ? span : null)}/>
                        :
                        null
                    )
                }
            </colgroup>
            :
            null;

    }

}

ColGroup.propTypes = {

    /**
     * Children passed into table header.
     */
    columns: PropTypes.arrayOf(PropTypes.shape({

        /**
         * unique keyof column.
         */
        key: PropTypes.string,

        /**
         * fixed position of column ( 'left' / 'right' ).
         */
        fixed: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * width of column.
         */
        width: PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.func]),

        /**
         * minimum width of column.
         */
        minWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),

        /**
         * align of current column.
         */
        align: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * no wrap of current column.
         */
        noWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),

        /**
         * The class name of header.
         */
        headClassName: PropTypes.string,

        /**
         * Override the styles of header.
         */
        headStyle: PropTypes.object,

        /**
         * align of table header cell
         */
        headAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * The render content in table head.
         *  (1) callback:
         *      function (tableData, colIndex) {
         *          return colIndex;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        headRenderer: PropTypes.any,

        /**
         * The title in table head.
         *  (1) callback:
         *      function (tableData, colIndex) {
         *          return colIndex;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        headTitle: PropTypes.any,

        /**
         * column span of table header.
         *  (1) function callback:
         *      function (tableData, colIndex) {
         *          return null;
         *      }
         *
         *  (2) number:
         *      render whatever you pass
         */
        headSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * no wrap of table header.
         */
        headNoWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),

        /**
         * The class name of td.
         */
        bodyClassName: PropTypes.string,

        /**
         * Override the styles of td.
         */
        bodyStyle: PropTypes.object,

        /**
         * align of table body cell.
         */
        bodyAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * The render content in table body.
         *  (1) callback:
         *      function (rowData, rowIndex, colIndex, parentData, tableData, collapsed, depth, path) {
         *          return rowData.id;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        bodyRenderer: PropTypes.any,

        /**
         * The title in table body.
         *  (1) callback:
         *      function (rowData, rowIndex, colIndex, parentData, tableData, collapsed, depth, path) {
         *          return rowData.id;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        bodyTitle: PropTypes.any,

        /**
         * column span of table body.
         *  (1) function callback:
         *      function (rowData, colIndex, rowIndex) {
         *          return null;
         *      }
         *
         *  (2) number:
         *      render whatever you pass
         */
        bodySpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * no wrap of table body.
         */
        bodyNoWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),

        /**
         * The class name of footer.
         */
        footClassName: PropTypes.string,

        /**
         * Override the styles of footer.
         */
        footStyle: PropTypes.object,

        /**
         * align of table footer cell
         */
        footAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * The render content in table foot.
         *  (1) callback:
         *      function (tableData, colIndex) {
         *          return colIndex;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        footRenderer: PropTypes.any,

        /**
         * The title in table foot.
         *  (1) callback:
         *      function (tableData, colIndex) {
         *          return colIndex;
         *      }
         *
         *  (2) others:
         *      render whatever you pass
         */
        footTitle: PropTypes.any,

        /**
         * column span of table foot.
         *  (1) function callback:
         *      function (tableData, colIndex) {
         *          return null;
         *      }
         *
         *  (2) number:
         *      render whatever you pass
         */
        footSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * no wrap of table foot.
         */
        footNoWrap: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),

        /**
         * If true, this column can be sorted.
         */
        sortable: PropTypes.bool,

        /**
         * Sorting property.
         */
        sortingProp: PropTypes.string,

        defaultSortingType: PropTypes.oneOf(Util.enumerateValue(SortingType)),

        /**
         * whether the column can be resized
         */
        resizable: PropTypes.bool

    })).isRequired,
    columnKeyField: PropTypes.string,
    columnsWidth: PropTypes.object,

    data: PropTypes.array,

    /**
     * column resizable
     */
    defaultColumnWidth: PropTypes.number,
    minColumnWidth: PropTypes.number,

    ignoreColumnSpan: PropTypes.bool

};

ColGroup.defaultProps = {

    columnKeyField: 'key',

    /**
     * column resizable
     */
    defaultColumnWidth: 100,
    minColumnWidth: 64,

    ignoreColumnSpan: false

};

export default ColGroup;
<|endoftext|>


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

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import Checkbox from '../Checkbox';
import Radio from '../Radio';
import CircularLoading from '../CircularLoading';
import TipProvider from '../TipProvider';
import TouchRipple from '../TouchRipple';

import Theme from '../Theme';
import Position from '../_statics/Position';
import SelectMode from '../_statics/SelectMode';

import Util from '../_vendors/Util';

class ListItem extends Component {

    static SelectMode = SelectMode;
    static Theme = Theme;

    constructor(props, ...restArgs) {
        super(props, ...restArgs);
    }

    handleMultiSelectChange = checked => {
        if (checked) {
            this.props.onSelect?.();
        } else {
            this.props.onDeselect?.();
        }
    };

    handleSingleSelectChange = () => {
        if (!this.props.checked) {
            this.props.onSelect?.();
        }
    };

    handleClick = e => {

        const {disabled, isLoading, readOnly, autoSelect} = this.props;

        if (disabled || isLoading || readOnly) {
            return;
        }

        this.props.onClick?.(e);

        if (!autoSelect) {
            return;
        }

        switch (this.props.selectMode) {
            case SelectMode.MULTI_SELECT:
                return this.handleMultiSelectChange(!this.props.checked);
            case SelectMode.SINGLE_SELECT:
                return this.handleSingleSelectChange();
        }

    };

    handleRadioCheck = () => {
        this.handleSingleSelectChange();
    };

    handleCheckboxCheck = () => {
        this.handleMultiSelectChange(true);
    };

    handleCheckboxUncheck = () => {
        this.handleMultiSelectChange(false);
    };

    /* eslint-disable complexity */
    render() {

        const {

                index, className, style, theme, activatedTheme, data, text, desc, title, iconCls, rightIconCls,
                tipClassName, tip, tipPosition, disabled, isLoading, disableTouchRipple, rippleDisplayCenter, readOnly,
                renderer, itemRenderer,

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

                onMouseEnter, onMouseLeave,
                parentEl

            } = this.props,

            indeterminated = indeterminateCallback && indeterminateCallback(data) || false,
            loadingIconPosition = (rightIconCls && !iconCls) ? 'right' : 'left';

        return (
            <TipProvider className={tipClassName}
                         tipContent={tip}
                         parentEl={parentEl}
                         position={tipPosition}>

                <div className={classNames('list-item', {
                    [`theme-${theme}`]: !checked && theme,
                    [`theme-${activatedTheme}`]: checked && activatedTheme,
                    activated: checked,
                    indeterminated,
                    [className]: className
                })}
                     style={style}
                     disabled={disabled || isLoading}
                     readOnly={readOnly}
                     title={title}
                     onClick={this.handleClick}
                     onMouseEnter={onMouseEnter}
                     onMouseLeave={onMouseLeave}>

                    {
                        selectMode === SelectMode.SINGLE_SELECT && (radioUncheckedIconCls || radioCheckedIconCls) ?
                            <Radio className="list-item-select"
                                   theme={selectTheme}
                                   checked={checked}
                                   disabled={disabled || isLoading}
                                   uncheckedIconCls={radioUncheckedIconCls}
                                   checkedIconCls={radioCheckedIconCls}
                                   disableTouchRipple={true}
                                   onCheck={this.handleRadioCheck}/>
                            :
                            null
                    }

                    {
                        selectMode === SelectMode.MULTI_SELECT ?
                            <Checkbox className="list-item-select"
                                      theme={selectTheme}
                                      checked={checked}
                                      indeterminate={indeterminated}
                                      disabled={disabled || isLoading}
                                      uncheckedIconCls={checkboxUncheckedIconCls}
                                      checkedIconCls={checkboxCheckedIconCls}
                                      indeterminateIconCls={checkboxIndeterminateIconCls}
                                      disableTouchRipple={true}
                                      onCheck={this.handleCheckboxCheck}
                                      onUncheck={this.handleCheckboxUncheck}/>
                            :
                            null
                    }

                    {
                        isLoading && loadingIconPosition === 'left' ?

                                <CircularLoading className="button-loading-icon"
                                                 size="small"/>

                            :
                            (
                                iconCls ?
                                    <i className={`button-icon button-icon-left ${iconCls}`}
                                       aria-hidden="true">
                                    :
                                    null
                            )
                    }

                    {
                        itemRenderer && typeof itemRenderer === 'function' ?
                            itemRenderer(data, index)
                            :
                            (
                                renderer && typeof renderer === 'function' ?
                                    renderer(data, index)
                                    :
                                    (
                                        desc ?

                                                    {text}

                                                    {desc}

                                            :
                                            text
                                    )
                            )
                    }

                    {
                        isLoading && loadingIconPosition === 'right' ?
                            <CircularLoading className="button-icon button-icon-right button-loading-icon"
                                             size="small"/>
                            :
                            (
                                rightIconCls ?
                                    <i className={`button-icon button-icon-right ${rightIconCls}`}
                                       aria-hidden="true">
                                    :
                                    null
                            )
                    }

                    {
                        disableTouchRipple || readOnly ?
                            null
                            :
                            <TouchRipple className={disabled || isLoading ? 'hidden' : ''}
                                         displayCenter={rippleDisplayCenter}/>
                    }

            </TipProvider>
        );

    }
}

ListItem.propTypes = {

    index: PropTypes.number,

    className: PropTypes.string,
    style: PropTypes.object,
    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),
    activatedTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    selectTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),
    selectMode: PropTypes.oneOf(Util.enumerateValue(SelectMode)),

    data: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.object]),
    value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    text: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    desc: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    title: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

    disabled: PropTypes.bool,
    isLoading: PropTypes.bool,
    disableTouchRipple: PropTypes.bool,
    rippleDisplayCenter: PropTypes.bool,
    checked: PropTypes.bool,
    readOnly: PropTypes.bool,
    parentEl: PropTypes.object,

    iconCls: PropTypes.string,
    rightIconCls: PropTypes.string,

    tipClassName: PropTypes.string,
    tip: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    tipPosition: PropTypes.oneOf(Util.enumerateValue(Position)),

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

    itemRenderer: PropTypes.func,
    renderer: PropTypes.func,
    indeterminateCallback: PropTypes.func,

    autoSelect: PropTypes.bool,

    onClick: PropTypes.func,
    onSelect: PropTypes.func,
    onDeselect: PropTypes.func,
    onMouseEnter: PropTypes.func,
    onMouseLeave: PropTypes.func

};

ListItem.defaultProps = {

    index: 0,

    theme: Theme.DEFAULT,
    activatedTheme: Theme.DEFAULT,

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

    disabled: false,
    isLoading: false,
    disableTouchRipple: false,
    rippleDisplayCenter: false,
    checked: false,
    readOnly: false,

    tipPosition: Position.BOTTOM,

    checkboxUncheckedIconCls: 'far fa-square',
    checkboxCheckedIconCls: 'fas fa-check-square',
    checkboxIndeterminateIconCls: 'fas fa-minus-square',

    autoSelect: true

};

export default ListItem;
<commit_msg>update ListItem<commit_after>/**
 * @file ListItem component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

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

// Components
import Checkbox from '../Checkbox';
import Radio from '../Radio';
import CircularLoading from '../CircularLoading';
import TipProvider from '../TipProvider';
import TouchRipple from '../TouchRipple';

// Statics
import Theme from '../Theme';
import Position from '../_statics/Position';
import SelectMode from '../_statics/SelectMode';

// Vendors
import classNames from 'classnames';
import Util from '../_vendors/Util';

class ListItem extends Component {

    static SelectMode = SelectMode;
    static Theme = Theme;

    constructor(props, ...restArgs) {
        super(props, ...restArgs);
    }

    handleMultiSelectChange = checked => {
        if (checked) {
            this.props.onSelect?.();
        } else {
            this.props.onDeselect?.();
        }
    };

    handleSingleSelectChange = () => {
        if (!this.props.checked) {
            this.props.onSelect?.();
        }
    };

    handleClick = e => {

        const {disabled, isLoading, readOnly, autoSelect} = this.props;

        if (disabled || isLoading || readOnly) {
            return;
        }

        this.props.onClick?.(e);

        if (!autoSelect) {
            return;
        }

        switch (this.props.selectMode) {
            case SelectMode.MULTI_SELECT:
                return this.handleMultiSelectChange(!this.props.checked);
            case SelectMode.SINGLE_SELECT:
                return this.handleSingleSelectChange();
            default:
                return;
        }

    };

    handleRadioCheck = () => {
        this.handleSingleSelectChange();
    };

    handleCheckboxCheck = () => {
        this.handleMultiSelectChange(true);
    };

    handleCheckboxUncheck = () => {
        this.handleMultiSelectChange(false);
    };

    /* eslint-disable complexity */
    render() {

        const {

                index, className, style, theme, activatedTheme, data, text, desc, title, iconCls, rightIconCls,
                tipClassName, tip, tipPosition, disabled, isLoading, disableTouchRipple, rippleDisplayCenter, readOnly,
                renderer, itemRenderer,

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

                onMouseEnter, onMouseLeave,
                parentEl

            } = this.props,

            indeterminated = indeterminateCallback && indeterminateCallback(data) || false,
            loadingIconPosition = (rightIconCls && !iconCls) ? 'right' : 'left';

        return (
            <TipProvider className={tipClassName}
                         tipContent={tip}
                         parentEl={parentEl}
                         position={tipPosition}>

                <div className={classNames('list-item', {
                    [`theme-${theme}`]: !checked && theme,
                    [`theme-${activatedTheme}`]: checked && activatedTheme,
                    activated: checked,
                    indeterminated,
                    [className]: className
                })}
                     style={style}
                     disabled={disabled || isLoading}
                     readOnly={readOnly}
                     title={title}
                     onClick={this.handleClick}
                     onMouseEnter={onMouseEnter}
                     onMouseLeave={onMouseLeave}>

                    {
                        selectMode === SelectMode.SINGLE_SELECT && (radioUncheckedIconCls || radioCheckedIconCls) ?
                            <Radio className="list-item-select"
                                   theme={selectTheme}
                                   checked={checked}
                                   disabled={disabled || isLoading}
                                   uncheckedIconCls={radioUncheckedIconCls}
                                   checkedIconCls={radioCheckedIconCls}
                                   disableTouchRipple={true}
                                   onCheck={this.handleRadioCheck}/>
                            :
                            null
                    }

                    {
                        selectMode === SelectMode.MULTI_SELECT ?
                            <Checkbox className="list-item-select"
                                      theme={selectTheme}
                                      checked={checked}
                                      indeterminate={indeterminated}
                                      disabled={disabled || isLoading}
                                      uncheckedIconCls={checkboxUncheckedIconCls}
                                      checkedIconCls={checkboxCheckedIconCls}
                                      indeterminateIconCls={checkboxIndeterminateIconCls}
                                      disableTouchRipple={true}
                                      onCheck={this.handleCheckboxCheck}
                                      onUncheck={this.handleCheckboxUncheck}/>
                            :
                            null
                    }

                    {
                        isLoading && loadingIconPosition === 'left' ?

                                <CircularLoading className="button-loading-icon"
                                                 size="small"/>

                            :
                            (
                                iconCls ?
                                    <i className={`button-icon button-icon-left ${iconCls}`}
                                       aria-hidden="true">
                                    :
                                    null
                            )
                    }

                    {
                        itemRenderer && typeof itemRenderer === 'function' ?
                            itemRenderer(data, index)
                            :
                            (
                                renderer && typeof renderer === 'function' ?
                                    renderer(data, index)
                                    :
                                    (
                                        desc ?

                                                    {text}

                                                    {desc}

                                            :
                                            text
                                    )
                            )
                    }

                    {
                        isLoading && loadingIconPosition === 'right' ?
                            <CircularLoading className="button-icon button-icon-right button-loading-icon"
                                             size="small"/>
                            :
                            (
                                rightIconCls ?
                                    <i className={`button-icon button-icon-right ${rightIconCls}`}
                                       aria-hidden="true">
                                    :
                                    null
                            )
                    }

                    {
                        disableTouchRipple || readOnly ?
                            null
                            :
                            <TouchRipple className={disabled || isLoading ? 'hidden' : ''}
                                         displayCenter={rippleDisplayCenter}/>
                    }

            </TipProvider>
        );

    }
}

ListItem.propTypes = {

    index: PropTypes.number,

    className: PropTypes.string,
    style: PropTypes.object,
    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),
    activatedTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    selectTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),
    selectMode: PropTypes.oneOf(Util.enumerateValue(SelectMode)),

    data: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.object]),
    value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    text: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    desc: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    title: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

    disabled: PropTypes.bool,
    isLoading: PropTypes.bool,
    disableTouchRipple: PropTypes.bool,
    rippleDisplayCenter: PropTypes.bool,
    checked: PropTypes.bool,
    readOnly: PropTypes.bool,
    parentEl: PropTypes.object,

    iconCls: PropTypes.string,
    rightIconCls: PropTypes.string,

    tipClassName: PropTypes.string,
    tip: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    tipPosition: PropTypes.oneOf(Util.enumerateValue(Position)),

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

    itemRenderer: PropTypes.func,
    renderer: PropTypes.func,
    indeterminateCallback: PropTypes.func,

    autoSelect: PropTypes.bool,

    onClick: PropTypes.func,
    onSelect: PropTypes.func,
    onDeselect: PropTypes.func,
    onMouseEnter: PropTypes.func,
    onMouseLeave: PropTypes.func

};

ListItem.defaultProps = {

    index: 0,

    theme: Theme.DEFAULT,
    activatedTheme: Theme.DEFAULT,

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

    disabled: false,
    isLoading: false,
    disableTouchRipple: false,
    rippleDisplayCenter: false,
    checked: false,
    readOnly: false,

    tipPosition: Position.BOTTOM,

    checkboxUncheckedIconCls: 'far fa-square',
    checkboxCheckedIconCls: 'fas fa-check-square',
    checkboxIndeterminateIconCls: 'fas fa-minus-square',

    autoSelect: true

};

export default ListItem;
<|endoftext|>


<commit_before>"use strict";

var path = require('path'),
	exec = require('child_process').exec;

module.exports = function (grunt) {
	grunt.registerTask('data-zdump', '3. Dump data with zdump(8).', function (version) {
		version = version || 'latest';

		var done      = this.async(),
			zicBase   = path.resolve('temp/zic', version),
			zdumpBase = path.resolve('temp/zdump', version),
			files     = grunt.file.expand({ filter : 'isFile', cwd : 'temp/zic/' + version }, '**/*');

		function next () {
			if (!files.length) {
				grunt.log.ok('Dumped data for ' + version);
				return done();
			}

			var file = files.pop(),
				src  = path.join(zicBase, file),
				dest = path.join(zdumpBase, file);

			exec('zdump -v ' + src, function (err, stdout) {
				if (err) { throw err; }

				grunt.file.mkdir(path.dirname(dest));
				grunt.file.write(dest + '.zdump', stdout.replace(new RegExp(zicBase + '/', 'g'), ''));

				grunt.verbose.ok('Dumped data for ' + version + ':' + file);

				next();
			});
		}

		next();
	});
};
<commit_msg>Fix for error "stderr: maxBuffer exceeded", while running `data-zdump` grunt task.<commit_after>"use strict";

var path = require('path'),
	exec = require('child_process').exec;

module.exports = function (grunt) {
	grunt.registerTask('data-zdump', '3. Dump data with zdump(8).', function (version) {
		version = version || 'latest';

		var done      = this.async(),
			zicBase   = path.resolve('temp/zic', version),
			zdumpBase = path.resolve('temp/zdump', version),
			files     = grunt.file.expand({ filter : 'isFile', cwd : 'temp/zic/' + version }, '**/*');

		function next () {
			if (!files.length) {
				grunt.log.ok('Dumped data for ' + version);
				return done();
			}

			var file = files.pop(),
				src  = path.join(zicBase, file),
				dest = path.join(zdumpBase, file);

			exec('zdump -v ' + src, { maxBuffer: 20*1024*1024 }, function (err, stdout) {
				if (err) { throw err; }

				grunt.file.mkdir(path.dirname(dest));
				grunt.file.write(dest + '.zdump', stdout.replace(new RegExp(zicBase + '/', 'g'), ''));

				grunt.verbose.ok('Dumped data for ' + version + ':' + file);

				next();
			});
		}

		next();
	});
};
<|endoftext|>


<commit_before>/**
 * @file Defines the lifeflow chart for {@link sequence-viz}
 * @author Sigfried Gold <sigfried@sigfried.org>
 * @license http://sigfried.mit-license.org/
 * Don't trust this documentation yet. It's just beginning to be
 * written.
 */
'use strict';
var lifeflowChart = function () {
    /** @namespace lifeflowChart */

    //============================================================
    // Public Variables with Default Settings
    //------------------------------------------------------------

    var margin = {
        top: 0,
        right: 0,
        bottom: 0,
        left: 0
        }
        , lifeflowData
        , timelineData
        , entityIdProp = null,
        eventNameProp = null,
        eventNames = null,
        eventOrder = [],
        alignChoices,
        startDateProp = null,
        endDateField = null,
        defaultDuration = null,
        alignmentLineWidth = 28,
        eventNodeWidth = 0,
        endNodeWidth = 0,
        width = 960,
        height = 500,
        id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one
        , x = d3.scale.linear()
        , y = d3.scale.linear()
        , relativeX
        //, color = nv.utils.defaultColor()
        , color = d3.scale.category20()
        , alignBy
        , dispatch = d3.dispatch('lifeflowMouseover', 'lifeflowMouseout');
        /*
        , dispatch = d3.dispatch('chartClick', 'elementClick',
                'elementDblClick', 'elementMouseover', 'elementMouseout',
                'toggleEvt','alignBy','selectRecs','doneDrawing'),
        */
            ;
    //============================================================
    function chart(selection) {
        selection.each(function (data) {
            lifeflowData = data;
            x = d3.scale.linear().range([0,width])
            y = d3.scale.linear()
                .range([0,height])
                .domain([0,lifeflowData
                    .where({depth:0})
                    .invoke('dy')
                    .reduce(function(p,c) { return p + c }) - 1])
            x.domain([
                            d3.min([0].concat(lifeflowData.map(function(d) {
                                return d.x() + d.dx()
                            }))),
                            d3.max([0].concat(lifeflowData.map(function(d) {
                                return d.x() + d.dx()
                            })))
                        ]);
            relativeX = d3.scale.linear()
                                .range(x.range())
                                .domain([0, x.domain()[1] - x.domain()[0]]);
            var container = d3.select(this);
            var nodes = container.selectAll('g.event-node')
                .data(lifeflowData
                    , function (d) {
                        var id = chart.alignBy() + d.namePath({noRoot:false}) + d.backwards
                        d.joinId = id;
                        return id;
                        // paths can be the same on either
                        // side of an alignment, so include backwards flag
                    })
            y.domain([0, _(lifeflowData).reduce(
                function(memo,node){
                    return Math.max(memo, node.y() + node.dy())
                },0)]);

            enterNodes();
            function enterNodes() {
                var enteringGs = nodes.enter()
                    .append('g')
                        .attr('class', 'event-node')
                        .attr('depth', function(d) { return d.depth })
                        .attr('path', function (d) {
                            return d.namePath({noRoot:false}) // don't need noRoot anymore
                        })
                        .attr('transform', function (d) {
                            return 'translate(' + x(d.x()) + ',' + y(d.y()) + ')'
                        })
                        .on("mouseover", function(d,i) {
                            dispatch.lifeflowMouseover(chart, this, d, i);
                        })
                        .on("mouseout", function(d,i) {
                            dispatch.lifeflowMouseout(chart, this, d, i);
                        })
                        //.on("mouseover", gMouseover)
                        //.on("mouseout", gMouseout)
                var newRects = enteringGs
                    //.filter(function(d) { return d.depth !== 0 })
                    .append('rect')
                        .attr('class', 'event-node')
                        .attr('fill', function (d) {
                            return color(d.valueOf())
                        })
                        .attr('x', function(d) { return relativeX(d.dx())})
                        .attr('width', relativeX(eventNodeWidth))
                        .attr('height', function (d) {
                            //console.log(d.dy + '   ' + this.className.baseVal + '   ' + d.namePath())
                            return y(d.dy())
                        })
                        //.attr('y', function(d) { return y(d.y) })
                        .attr('height', function(d) { return y(d.dy()) })
                    //.on("mouseover", rectMouseover)
                    //.on("mouseout", rectMouseout)
                return;
                /*
                var fillRects = enteringGs
                    .filter(function(d) { return d.parent })
                    .append('rect')
                        .attr('class', 'gap-fill')
                        .attr('fill', function (d) {
                            return color(d.parent.valueOf())
                        })
                        .attr('stroke', '#888')
                        .attr('stroke-width', '1px')
                        .attr('opacity', .5)
                        .attr('width', 0)
                        .attr('height', function (d) {
                            //console.log(d.dy + '   ' + this.className.baseVal + '   ' + d.namePath())
                            return y(d.dy)
                        })
                    .on("mouseover", rectMouseover)
                    .on("mouseout", rectMouseout)
                */
                var fmt = d3.format('5.0f');
                nodes.attr('transform', function (d) {
                            var xpos = x(d.x())
                            return 'translate(' + xpos + ',' + y(d.y()) + ')'
                        })
                nodes.select('rect.event-node')
                    .attr('height', function (d) {
                        //console.log(d.dy + '   ' + this.className.baseVal + '   ' + d.namePath())
                        return y(d.dy())
                    })
                nodes.select('rect.gap-fill')
                    .attr('height', function (d) {
                        //console.log(d.dy + '   ' + this.className.baseVal + '   ' + d.namePath())
                        return y(d.dy())
                    })
                    .attr('x', function(d) {
                        var shift = d.backwards ?  d.parent.dx() :
                                -d.parent.dx() + eventNodeWidth;
                        return relativeX(shift)
                    })
                    .attr('width', function(d) {
                        return Math.max(relativeX( Math.abs(d.parent.dx())
                                - eventNodeWidth), 0);
                    })
                    //.attr('y', function(d) { return y(d.y) })
                    .attr('height', function(d) { return y(d.dy()) })
            }
        });
        return chart;
    }

    //============================================================
    // mouseover code. tooltips broken for now
    // distribution lines still working
    //------------------------------------------------------------

    /*
            function rectMouseover(d, i) {
                console.log("not connected right now")
                d3.select(this)
                    .classed('hover', true)
                var path = d.namePath({noRoot:false})
                //var avgDays = d3.mean(_(d.records).invoke('fromPrev'));
                var avg = Math.round(d3.mean(_.chain(d.records).invoke('timeline').invoke('duration').value()));
                var tt = d.toString() + ', ' + d.records.length + ' timelines with ';
                tt += avg + ' mean duration';
                dispatch.lifeflowMouseover({
                    value: d,
                    text: tt,
                    series: _(d.pedigree({asValues:true}))
                        .map(function(lfnode) {
                            return {
                                key: lfnode.toString(),
                                value: Math.round(d3.mean(_(lfnode.records).invoke('toNext'))),
                                color: color(lfnode.toString())
                            }
                        }),
                    e: d3.event
                });
            }
            function rectMouseout(d, i) {
                dispatch.lifeflowMouseout();
            }
            function gMouseout(d, i) {
                d3.select(this).selectAll('rect.gap-fill').attr('opacity',.5)
                var path = d3.select(this).selectAll('path');
                //path.remove();
                path.transition().duration(4000).style('opacity', 0).remove()
                var circle = d3.select(this).selectAll('circle');
                //circle.remove();
                circle.transition().duration(4000).style('opacity', 0).remove()
                    /*
                d3.selectAll('rect.gap-fill')
                    .transition().delay(3000).duration(700)
                    .attr('opacity', 0.5);
                d3.selectAll('rect.event-node')
                    .transition().delay(3000).duration(700)
                    .attr('opacity', 0.5);
                    * /
            }
            var nodesWithDistributionsShowing = [];
            function gMouseover(lfnode, i) {
                throw new Error("shouldn't be working now");
                /*
                d3.selectAll('rect')
                    .transition().duration(700)
                    .attr('opacity', 0.4);
                    * /
                console.log('mouse over ' + nodesWithDistributionsShowing.length);
                console.log(nodesWithDistributionsShowing);
                var alreadyDisplayed = false;
                _(nodesWithDistributionsShowing).each(function(d) {
                    if (d === lfnode) {
                        alreadyDisplayed = true;
                        return;
                    }
                    d.distCircles.remove();
                    d.distPath.remove();
                    delete d.distCircles;
                    delete d.distPath;
                });
                nodesWithDistributionsShowing.length = 0;
                if (alreadyDisplayed) {
                    nodesWithDistributionsShowing.push(lfnode);
                }
                d3.select(this).selectAll('rect.gap-fill').attr('opacity',1)
                var recs, xFunc;
                if (!lfnode.parent) {
                    recs = [];
                } else if (lfnode.backwards) {
                    recs = lfnode.records.sort(function (a, b) {
                        return a.toNext() - b.toNext();
                    });
                    //xFunc = function(d) { return relativeX(-d.toNext()) };
                    xFunc = function(d) {
                            return relativeX(-lfnode.parent.dx() -
                                    d.toNext())
                    };
                } else {
                    recs = lfnode.records.sort(function (a, b) {
                        return a.fromPrev() - b.fromPrev();
                    });
                    xFunc = function(d) {
                        return relativeX(d.fromPrev())
                    };
                }
                var line = d3.svg.line()
                    .x(xFunc)
                    .y(function (d, i) {
                        return y(i)
                    });
                var path = d3.select(this).selectAll('path')
                    .data([recs])
                path.enter()
                    .append('path')
                    .attr('d', line)
                path.attr('fill-opacity', 0)
                    .attr('stroke', 'black')
                    .style('pointer-events', 'none')
                    .style('stroke-opacity', 1)
                var circle = d3.select(this).selectAll('circle')
                    .data(recs)
                circle.enter()
                    .append('circle')
                    .attr('cx', xFunc)
                    .attr('cy', function (d, i) {
                        return y(i)
                    })
                    .attr('r', 4)
                    .on("mouseover", function (d, i) {
                        d3.select(this).classed('hover', true)
                        var fmt = d3.time.format('%Y-%m-%d');
                        dispatch.lifeflowMouseover({
                            value: d,
                            text: d.timeline() + ': ' + d.eventName() +
                                ' - ' + d.toNext() + ' of ' +
                                d.timeline().duration() + ' total ' + timeUnit,
                            series: _(d.timeline().records).map(function(rec) {
                                return {
                                    key: rec.eventName(),
                                    value: fmt(rec.startDate()),
                                    color: color(rec.eventName())
                                }
                            }),
                            e: d3.event
                        });
                    })
                circle.style('fill-opacity', 0)
                //.style('stroke-opacity',1)
                //.style('pointer-events','none')
                .attr('stroke', 'black')
                    .attr('stroke-opacity', 0.2)
                //.attr('stroke', function() { return color(d.valueOf()) })
                if (alreadyDisplayed) {
                    if (!_(lfnode).has('distCircles'))
                        throw new Error('what up');
                } else {
                    lfnode.distCircles = circle;
                    lfnode.distPath = path;
                    nodesWithDistributionsShowing.push(lfnode);
                }
            }
            */
    //============================================================
    // Expose Public Variables
    //------------------------------------------------------------
    chart.dispatch = dispatch;

    /*
    chart.entityIdProp = function (_) {
        if (!arguments.length) return entityIdProp;
        entityIdProp = _;
        return chart;
    };
    chart.eventNameProp = function (_) {
        if (!arguments.length) return eventNameProp;
        eventNameProp = _;
        return chart;
    };
    chart.eventOrder = function (_) {
        if (!arguments.length) return eventOrder;
        eventOrder = _;
        return chart;
    };
    chart.startDateProp = function (_) {
        if (!arguments.length) return startDateProp;
        startDateProp = _;
        return chart;
    };
    chart.endDateField = function (_) {
        if (!arguments.length) return endDateField;
        endDateField = _;
        return chart;
    };
    chart.defaultDuration = function (_) {
        if (!arguments.length) return defaultDuration;
        defaultDuration = _;
        return chart;
    };
    */
    chart.margin = function (_) {
        if (!arguments.length) return margin;
        margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
        margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
        margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
        margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
        return chart;
    };

    chart.eventNames = function (_) {
        if (!arguments.length) return eventNames;
        eventNames = _;
        return chart;
    };
    chart.timelineData = function (_) {
        if (!arguments.length) return timelineData;
        timelineData = _;
        return chart;
    };
    chart.width = function (_) {
        if (!arguments.length) return width;
        width = _;
        return chart;
    };

    chart.height = function (_) {
        if (!arguments.length) return height;
        height = _;
        return chart;
    };

    chart.xScale = function (_) {
        if (!arguments.length) return x;
        x = _;
        return chart;
    };
    chart.relativeX = function (_) {
        if (!arguments.length) return relativeX;
        relativeX = _;
        return chart;
    };

    chart.yScale = function (_) {
        if (!arguments.length) return y;
        y = _;
        return chart;
    };

    chart.color = function (_) {
        if (!arguments.length) return color;
        //color = nv.utils.getColor(_);
        color = _;
        return chart;
    };

    chart.disabled = function (_) {
        if (!arguments.length) return disabled;
        disabled = _;
        return chart;
    };

    chart.id = function (_) {
        if (!arguments.length) return id;
        id = _;
        return chart;
    };

    chart.alignBy = function (_) {
        if (!arguments.length) return alignBy;
        alignBy = _;
        return chart;
    };
    chart.xAxis = function (_) {
        if (!arguments.length) return xAxis;
        xAxis = _;
        return chart;
    };
    chart.lifeflowData = function (_) {
        if (!arguments.length) return lifeflowData;
        lifeflowData = _;
        return chart;
    };
    chart.alignChoices = function (_) {
        if (!arguments.length) return alignChoices;
        alignChoices = _;
        return chart;
    };
    chart.eventNodeWidth = function(_) {
        if (!arguments.length) return eventNodeWidth;
        eventNodeWidth = _;
        return chart;
    };
    /*
    chart.alignmentLineWidth = function(_) {
        if (!arguments.length) return alignmentLineWidth;
        alignmentLineWidth = _;
        return chart;
    };
    chart.endNodeWidth = function(_) {
        if (!arguments.length) return endNodeWidth;
        endNodeWidth = _;
        return chart;
    };
    */
    return chart;
}
<commit_msg>moved mouseover handlers from containing g to inner rect so they wouldn't be triggered by mousing over distribution line/circles<commit_after>/**
 * @file Defines the lifeflow chart for {@link sequence-viz}
 * @author Sigfried Gold <sigfried@sigfried.org>
 * @license http://sigfried.mit-license.org/
 * Don't trust this documentation yet. It's just beginning to be
 * written.
 */
'use strict';
var lifeflowChart = function () {
    /** @namespace lifeflowChart */

    //============================================================
    // Public Variables with Default Settings
    //------------------------------------------------------------

    var margin = {
        top: 0,
        right: 0,
        bottom: 0,
        left: 0
        }
        , lifeflowData
        , timelineData
        , entityIdProp = null,
        eventNameProp = null,
        eventNames = null,
        eventOrder = [],
        alignChoices,
        startDateProp = null,
        endDateField = null,
        defaultDuration = null,
        alignmentLineWidth = 28,
        eventNodeWidth = 0,
        endNodeWidth = 0,
        width = 960,
        height = 500,
        id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one
        , x = d3.scale.linear()
        , y = d3.scale.linear()
        , relativeX
        //, color = nv.utils.defaultColor()
        , color = d3.scale.category20()
        , alignBy
        , dispatch = d3.dispatch('lifeflowMouseover', 'lifeflowMouseout');
        /*
        , dispatch = d3.dispatch('chartClick', 'elementClick',
                'elementDblClick', 'elementMouseover', 'elementMouseout',
                'toggleEvt','alignBy','selectRecs','doneDrawing'),
        */
            ;
    //============================================================
    function chart(selection) {
        selection.each(function (data) {
            lifeflowData = data;
            x = d3.scale.linear().range([0,width])
            y = d3.scale.linear()
                .range([0,height])
                .domain([0,lifeflowData
                    .where({depth:0})
                    .invoke('dy')
                    .reduce(function(p,c) { return p + c }) - 1])
            x.domain([
                            d3.min([0].concat(lifeflowData.map(function(d) {
                                return d.x() + d.dx()
                            }))),
                            d3.max([0].concat(lifeflowData.map(function(d) {
                                return d.x() + d.dx()
                            })))
                        ]);
            relativeX = d3.scale.linear()
                                .range(x.range())
                                .domain([0, x.domain()[1] - x.domain()[0]]);
            var container = d3.select(this);
            var nodes = container.selectAll('g.event-node')
                .data(lifeflowData
                    , function (d) {
                        var id = chart.alignBy() + d.namePath({noRoot:false}) + d.backwards
                        d.joinId = id;
                        return id;
                        // paths can be the same on either
                        // side of an alignment, so include backwards flag
                    })
            y.domain([0, _(lifeflowData).reduce(
                function(memo,node){
                    return Math.max(memo, node.y() + node.dy())
                },0)]);

            enterNodes();
            function enterNodes() {
                var enteringGs = nodes.enter()
                    .append('g')
                        .attr('class', 'event-node')
                        .attr('depth', function(d) { return d.depth })
                        .attr('path', function (d) {
                            return d.namePath({noRoot:false}) // don't need noRoot anymore
                        })
                        .attr('transform', function (d) {
                            return 'translate(' + x(d.x()) + ',' + y(d.y()) + ')'
                        })
                        //.on("mouseover", gMouseover)
                        //.on("mouseout", gMouseout)
                var newRects = enteringGs
                    //.filter(function(d) { return d.depth !== 0 })
                    .append('rect')
                        .attr('class', 'event-node')
                        .attr('fill', function (d) {
                            return color(d.valueOf())
                        })
                        .attr('x', function(d) { return relativeX(d.dx())})
                        .attr('width', relativeX(eventNodeWidth))
                        .attr('height', function (d) {
                            //console.log(d.dy + '   ' + this.className.baseVal + '   ' + d.namePath())
                            return y(d.dy())
                        })
                        //.attr('y', function(d) { return y(d.y) })
                        .attr('height', function(d) { return y(d.dy()) })
                        .on("mouseover", function(d,i) {
                            dispatch.lifeflowMouseover(chart, this, d, i);
                        })
                        .on("mouseout", function(d,i) {
                            dispatch.lifeflowMouseout(chart, this, d, i);
                        })
                    //.on("mouseover", rectMouseover)
                    //.on("mouseout", rectMouseout)
                return;
                /*
                var fillRects = enteringGs
                    .filter(function(d) { return d.parent })
                    .append('rect')
                        .attr('class', 'gap-fill')
                        .attr('fill', function (d) {
                            return color(d.parent.valueOf())
                        })
                        .attr('stroke', '#888')
                        .attr('stroke-width', '1px')
                        .attr('opacity', .5)
                        .attr('width', 0)
                        .attr('height', function (d) {
                            //console.log(d.dy + '   ' + this.className.baseVal + '   ' + d.namePath())
                            return y(d.dy)
                        })
                    .on("mouseover", rectMouseover)
                    .on("mouseout", rectMouseout)
                */
                var fmt = d3.format('5.0f');
                nodes.attr('transform', function (d) {
                            var xpos = x(d.x())
                            return 'translate(' + xpos + ',' + y(d.y()) + ')'
                        })
                nodes.select('rect.event-node')
                    .attr('height', function (d) {
                        //console.log(d.dy + '   ' + this.className.baseVal + '   ' + d.namePath())
                        return y(d.dy())
                    })
                nodes.select('rect.gap-fill')
                    .attr('height', function (d) {
                        //console.log(d.dy + '   ' + this.className.baseVal + '   ' + d.namePath())
                        return y(d.dy())
                    })
                    .attr('x', function(d) {
                        var shift = d.backwards ?  d.parent.dx() :
                                -d.parent.dx() + eventNodeWidth;
                        return relativeX(shift)
                    })
                    .attr('width', function(d) {
                        return Math.max(relativeX( Math.abs(d.parent.dx())
                                - eventNodeWidth), 0);
                    })
                    //.attr('y', function(d) { return y(d.y) })
                    .attr('height', function(d) { return y(d.dy()) })
            }
        });
        return chart;
    }

    //============================================================
    // mouseover code. tooltips broken for now
    // distribution lines still working
    //------------------------------------------------------------

    /*
            function rectMouseover(d, i) {
                console.log("not connected right now")
                d3.select(this)
                    .classed('hover', true)
                var path = d.namePath({noRoot:false})
                //var avgDays = d3.mean(_(d.records).invoke('fromPrev'));
                var avg = Math.round(d3.mean(_.chain(d.records).invoke('timeline').invoke('duration').value()));
                var tt = d.toString() + ', ' + d.records.length + ' timelines with ';
                tt += avg + ' mean duration';
                dispatch.lifeflowMouseover({
                    value: d,
                    text: tt,
                    series: _(d.pedigree({asValues:true}))
                        .map(function(lfnode) {
                            return {
                                key: lfnode.toString(),
                                value: Math.round(d3.mean(_(lfnode.records).invoke('toNext'))),
                                color: color(lfnode.toString())
                            }
                        }),
                    e: d3.event
                });
            }
            function rectMouseout(d, i) {
                dispatch.lifeflowMouseout();
            }
            function gMouseout(d, i) {
                d3.select(this).selectAll('rect.gap-fill').attr('opacity',.5)
                var path = d3.select(this).selectAll('path');
                //path.remove();
                path.transition().duration(4000).style('opacity', 0).remove()
                var circle = d3.select(this).selectAll('circle');
                //circle.remove();
                circle.transition().duration(4000).style('opacity', 0).remove()
                    /*
                d3.selectAll('rect.gap-fill')
                    .transition().delay(3000).duration(700)
                    .attr('opacity', 0.5);
                d3.selectAll('rect.event-node')
                    .transition().delay(3000).duration(700)
                    .attr('opacity', 0.5);
                    * /
            }
            var nodesWithDistributionsShowing = [];
            function gMouseover(lfnode, i) {
                throw new Error("shouldn't be working now");
                /*
                d3.selectAll('rect')
                    .transition().duration(700)
                    .attr('opacity', 0.4);
                    * /
                console.log('mouse over ' + nodesWithDistributionsShowing.length);
                console.log(nodesWithDistributionsShowing);
                var alreadyDisplayed = false;
                _(nodesWithDistributionsShowing).each(function(d) {
                    if (d === lfnode) {
                        alreadyDisplayed = true;
                        return;
                    }
                    d.distCircles.remove();
                    d.distPath.remove();
                    delete d.distCircles;
                    delete d.distPath;
                });
                nodesWithDistributionsShowing.length = 0;
                if (alreadyDisplayed) {
                    nodesWithDistributionsShowing.push(lfnode);
                }
                d3.select(this).selectAll('rect.gap-fill').attr('opacity',1)
                var recs, xFunc;
                if (!lfnode.parent) {
                    recs = [];
                } else if (lfnode.backwards) {
                    recs = lfnode.records.sort(function (a, b) {
                        return a.toNext() - b.toNext();
                    });
                    //xFunc = function(d) { return relativeX(-d.toNext()) };
                    xFunc = function(d) {
                            return relativeX(-lfnode.parent.dx() -
                                    d.toNext())
                    };
                } else {
                    recs = lfnode.records.sort(function (a, b) {
                        return a.fromPrev() - b.fromPrev();
                    });
                    xFunc = function(d) {
                        return relativeX(d.fromPrev())
                    };
                }
                var line = d3.svg.line()
                    .x(xFunc)
                    .y(function (d, i) {
                        return y(i)
                    });
                var path = d3.select(this).selectAll('path')
                    .data([recs])
                path.enter()
                    .append('path')
                    .attr('d', line)
                path.attr('fill-opacity', 0)
                    .attr('stroke', 'black')
                    .style('pointer-events', 'none')
                    .style('stroke-opacity', 1)
                var circle = d3.select(this).selectAll('circle')
                    .data(recs)
                circle.enter()
                    .append('circle')
                    .attr('cx', xFunc)
                    .attr('cy', function (d, i) {
                        return y(i)
                    })
                    .attr('r', 4)
                    .on("mouseover", function (d, i) {
                        d3.select(this).classed('hover', true)
                        var fmt = d3.time.format('%Y-%m-%d');
                        dispatch.lifeflowMouseover({
                            value: d,
                            text: d.timeline() + ': ' + d.eventName() +
                                ' - ' + d.toNext() + ' of ' +
                                d.timeline().duration() + ' total ' + timeUnit,
                            series: _(d.timeline().records).map(function(rec) {
                                return {
                                    key: rec.eventName(),
                                    value: fmt(rec.startDate()),
                                    color: color(rec.eventName())
                                }
                            }),
                            e: d3.event
                        });
                    })
                circle.style('fill-opacity', 0)
                //.style('stroke-opacity',1)
                //.style('pointer-events','none')
                .attr('stroke', 'black')
                    .attr('stroke-opacity', 0.2)
                //.attr('stroke', function() { return color(d.valueOf()) })
                if (alreadyDisplayed) {
                    if (!_(lfnode).has('distCircles'))
                        throw new Error('what up');
                } else {
                    lfnode.distCircles = circle;
                    lfnode.distPath = path;
                    nodesWithDistributionsShowing.push(lfnode);
                }
            }
            */
    //============================================================
    // Expose Public Variables
    //------------------------------------------------------------
    chart.dispatch = dispatch;

    /*
    chart.entityIdProp = function (_) {
        if (!arguments.length) return entityIdProp;
        entityIdProp = _;
        return chart;
    };
    chart.eventNameProp = function (_) {
        if (!arguments.length) return eventNameProp;
        eventNameProp = _;
        return chart;
    };
    chart.eventOrder = function (_) {
        if (!arguments.length) return eventOrder;
        eventOrder = _;
        return chart;
    };
    chart.startDateProp = function (_) {
        if (!arguments.length) return startDateProp;
        startDateProp = _;
        return chart;
    };
    chart.endDateField = function (_) {
        if (!arguments.length) return endDateField;
        endDateField = _;
        return chart;
    };
    chart.defaultDuration = function (_) {
        if (!arguments.length) return defaultDuration;
        defaultDuration = _;
        return chart;
    };
    */
    chart.margin = function (_) {
        if (!arguments.length) return margin;
        margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
        margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
        margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
        margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
        return chart;
    };

    chart.eventNames = function (_) {
        if (!arguments.length) return eventNames;
        eventNames = _;
        return chart;
    };
    chart.timelineData = function (_) {
        if (!arguments.length) return timelineData;
        timelineData = _;
        return chart;
    };
    chart.width = function (_) {
        if (!arguments.length) return width;
        width = _;
        return chart;
    };

    chart.height = function (_) {
        if (!arguments.length) return height;
        height = _;
        return chart;
    };

    chart.xScale = function (_) {
        if (!arguments.length) return x;
        x = _;
        return chart;
    };
    chart.relativeX = function (_) {
        if (!arguments.length) return relativeX;
        relativeX = _;
        return chart;
    };

    chart.yScale = function (_) {
        if (!arguments.length) return y;
        y = _;
        return chart;
    };

    chart.color = function (_) {
        if (!arguments.length) return color;
        //color = nv.utils.getColor(_);
        color = _;
        return chart;
    };

    chart.disabled = function (_) {
        if (!arguments.length) return disabled;
        disabled = _;
        return chart;
    };

    chart.id = function (_) {
        if (!arguments.length) return id;
        id = _;
        return chart;
    };

    chart.alignBy = function (_) {
        if (!arguments.length) return alignBy;
        alignBy = _;
        return chart;
    };
    chart.xAxis = function (_) {
        if (!arguments.length) return xAxis;
        xAxis = _;
        return chart;
    };
    chart.lifeflowData = function (_) {
        if (!arguments.length) return lifeflowData;
        lifeflowData = _;
        return chart;
    };
    chart.alignChoices = function (_) {
        if (!arguments.length) return alignChoices;
        alignChoices = _;
        return chart;
    };
    chart.eventNodeWidth = function(_) {
        if (!arguments.length) return eventNodeWidth;
        eventNodeWidth = _;
        return chart;
    };
    /*
    chart.alignmentLineWidth = function(_) {
        if (!arguments.length) return alignmentLineWidth;
        alignmentLineWidth = _;
        return chart;
    };
    chart.endNodeWidth = function(_) {
        if (!arguments.length) return endNodeWidth;
        endNodeWidth = _;
        return chart;
    };
    */
    return chart;
}
<|endoftext|>


<commit_before>$(document).ready(function() {

	//Lorsque vous cliquez sur un lien de la classe poplight
	$('a.poplight').click(function() {
		var popID = $(this).attr('rel'); //Trouver la pop-up correspondante

		//Récupérer les variables depuis le lien
		var popWidth = 500; //La première valeur du lien

		//Faire apparaitre la pop-up et ajouter le bouton de fermeture
		$('#' + popID).fadeIn().css({
			'width': Number(popWidth)
		})
		.prepend('');

		//Récupération du margin, qui permettra de centrer la fenêtre - on ajuste de 80px en conformité avec le CSS
		var popMargTop = ($('#' + popID).height() + 80) / 2;
		var popMargLeft = ($('#' + popID).width() + 80) / 2;

		//On affecte le margin
		$('#' + popID).css({
			'margin-top' : -popMargTop,
			'margin-left' : -popMargLeft
		});

		//Effet fade-in du fond opaque
		$('body').append('

'); //Ajout du fond opaque noir
		//Apparition du fond - .css({'filter' : 'alpha(opacity=80)'}) pour corriger les bogues de IE
		$('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn();

		return false;
	});

	//Fermeture de la pop-up et du fond
	$('a.close, #fade').live('click', function() { //Au clic sur le bouton ou sur le calque...
		$('#fade , .popup_block').fadeOut(function() {
			$('#fade, a.close').remove();  //...ils disparaissent ensemble
		});
		return false;
	});

});<commit_msg>delete<commit_after><|endoftext|>


<commit_before>var Reactor = require('reactor')
var cadence = require('cadence')
var Vestibule = require('vestibule')

function Delegate (colleague, child) {
    this._colleague = colleague
    this._colleague.messages.on('message', this.colleagueMessage.bind(this))
    this._messages = new Reactor({ object: this, method: '_colleagueMessage' })
    this._initializers = new Vestibule
    this._initialized = false
    this._child = child
    this._child.on('message', this.childMessage.bind(this))
}

Delegate.prototype.initialize = function (callback) {
    if (this._initialized) {
        callback()
    } else {
        this._initializers.enter(callback)
    }
}

Delegate.prototype._colleagueMessage = cadence(function (async, timeout, message) {
    this._child.send(message, async())
})

Delegate.prototype.colleagueMessage = function (message) {
    this._messages.push(message)
}

Delegate.prototype.childMessage = function (message) {
    switch (message.type) {
    case 'initialized':
        if (!this._initialized) {
            this._initialized = true
            this._initializers.notify()
        }
        break
    case 'publish':
        this._colleague.publish(message.reinstatementId, message.entry)
        break
    }
}

Delegate.prototype.stop = function () {
    this._child.kill('SIGINT')
}

module.exports = Delegate
<commit_msg>Delete `ipc.js`.<commit_after><|endoftext|>


<commit_before>// @flow
// @inheritedComponent FormControl

import React from 'react';
import warning from 'warning';
import type { ChildrenArray, Node } from 'react';
import Input, { InputLabel } from '../Input';
import FormControl from '../Form/FormControl';
import FormHelperText from '../Form/FormHelperText';
import Select from '../Select/Select';

export type Props = {
  /**
   * This property helps users to fill forms faster, especially on mobile devices.
   * The name can be confusion, it's more like an autofill.
   * You can learn about it with that article
   * https://developers.google.com/web/updates/2015/06/checkout-faster-with-autofill
   */
  autoComplete?: string,
  /**
   * If `true`, the input will be focused during the first mount.
   */
  autoFocus?: boolean,
  /**
   * @ignore
   */
  children?: ChildrenArray<*>,
  /**
   * @ignore
   */
  className?: string,
  /**
   * The default value of the `Input` element.
   */
  defaultValue?: string,
  /**
   * If `true`, the input will be disabled.
   */
  disabled?: boolean,
  /**
   * If `true`, the label will be displayed in an error state.
   */
  error?: boolean,
  /**
   * Properties applied to the `FormHelperText` element.
   */
  FormHelperTextProps?: Object,
  /**
   * If `true`, the input will take up the full width of its container.
   */
  fullWidth?: boolean,
  /**
   * The helper text content.
   */
  helperText?: Node,
  /**
   * The CSS class name of the helper text element.
   */
  helperTextClassName?: string,
  /**
   * The id of the `input` element.
   */
  id?: string,
  /**
   * The CSS class name of the `input` element.
   */
  inputClassName?: string,
  /**
   * The CSS class name of the `Input` element.
   */
  InputClassName?: string,
  /**
   * Properties applied to the `InputLabel` element.
   */
  InputLabelProps?: Object,
  /**
   * Properties applied to the `input` element.
   */
  inputProps?: Object,
  /**
   * Properties applied to the `Input` element.
   */
  InputProps?: Object,
  /**
   * Use that property to pass a ref callback to the native input component.
   */
  inputRef?: Function,
  /**
   * The label content.
   */
  label?: Node,
  /**
   * The CSS class name of the label element.
   */
  labelClassName?: string,
  /**
   * If `true`, a textarea element will be rendered instead of an input.
   */
  multiline?: boolean,
  /**
   * Name attribute of the `input` element.
   */
  name?: string,
  /**
   * Callback fired when the value is changed.
   *
   * @param {object} event The event source of the callback
   */
  onChange?: (event: SyntheticInputEvent<>) => void,
  /**
   * The short hint displayed in the input before the user enters a value.
   */
  placeholder?: string,
  /**
   * If `true`, the label is displayed as required.
   */
  required?: boolean,
  /**
   * Use that property to pass a ref callback to the root component.
   */
  rootRef?: Function,
  /**
   * Number of rows to display when multiline option is set to true.
   */
  rows?: string | number,
  /**
   * Maximum number of rows to display when multiline option is set to true.
   */
  rowsMax?: string | number,
  /**
   * Render a `Select` element while passing the `Input` element to `Select` as `input` parameter.
   * If this option is set you must pass the options of the select as children.
   */
  select?: boolean,
  /**
   * Properties applied to the `Select` element.
   */
  SelectProps?: Object,
  /**
   * Type attribute of the `Input` element. It should be a valid HTML5 input type.
   */
  type?: string,
  /**
   * The value of the `Input` element, required for a controlled component.
   */
  value?: string | number,
  /**
   * If `dense` or `normal`, will adjust vertical spacing of this and contained components.
   */
  margin?: 'none' | 'dense' | 'normal',
};

function TextField(props: Props) {
  const {
    autoComplete,
    autoFocus,
    children,
    className,
    defaultValue,
    disabled,
    error,
    id,
    inputClassName,
    InputClassName,
    inputProps: inputPropsProp,
    InputProps,
    inputRef,
    label,
    labelClassName,
    InputLabelProps,
    helperText,
    helperTextClassName,
    FormHelperTextProps,
    fullWidth,
    required,
    type,
    multiline,
    name,
    onChange,
    placeholder,
    rootRef,
    rows,
    rowsMax,
    select,
    SelectProps,
    value,
    ...other
  } = props;

  let inputProps = inputPropsProp;

  if (inputClassName) {
    inputProps = {
      className: inputClassName,
      ...inputProps,
    };
  }

  warning(
    !select || Boolean(children),
    'Material-UI: `children` must be passed when using the `TextField` component with `select`.',
  );

  const InputComponent = (
    <Input
      autoComplete={autoComplete}
      autoFocus={autoFocus}
      className={InputClassName}
      defaultValue={defaultValue}
      disabled={disabled}
      multiline={multiline}
      name={name}
      rows={rows}
      rowsMax={rowsMax}
      type={type}
      value={value}
      id={id}
      inputProps={inputProps}
      inputRef={inputRef}
      onChange={onChange}
      placeholder={placeholder}
      {...InputProps}
    />
  );

  return (
    <FormControl
      fullWidth={fullWidth}
      className={className}
      error={error}
      required={required}
      {...other}
      ref={rootRef}
    >
      {label && (
        <InputLabel htmlFor={id} className={labelClassName} {...InputLabelProps}>
          {label}
        </InputLabel>
      )}
      {select ? (
        <Select input={InputComponent} {...SelectProps}>
          {children}
        </Select>
      ) : (
        InputComponent
      )}
      {helperText && (
        <FormHelperText className={helperTextClassName} {...FormHelperTextProps}>
          {helperText}
        </FormHelperText>
      )}
    </FormControl>
  );
}

TextField.defaultProps = {
  required: false,
  select: false,
};

export default TextField;
<commit_msg>[TextField] Better select support (#9224)<commit_after>// @flow
// @inheritedComponent FormControl

import React from 'react';
import warning from 'warning';
import type { ChildrenArray, Node } from 'react';
import Input, { InputLabel } from '../Input';
import FormControl from '../Form/FormControl';
import FormHelperText from '../Form/FormHelperText';
import Select from '../Select/Select';

export type Props = {
  /**
   * This property helps users to fill forms faster, especially on mobile devices.
   * The name can be confusion, it's more like an autofill.
   * You can learn about it with that article
   * https://developers.google.com/web/updates/2015/06/checkout-faster-with-autofill
   */
  autoComplete?: string,
  /**
   * If `true`, the input will be focused during the first mount.
   */
  autoFocus?: boolean,
  /**
   * @ignore
   */
  children?: ChildrenArray<*>,
  /**
   * @ignore
   */
  className?: string,
  /**
   * The default value of the `Input` element.
   */
  defaultValue?: string,
  /**
   * If `true`, the input will be disabled.
   */
  disabled?: boolean,
  /**
   * If `true`, the label will be displayed in an error state.
   */
  error?: boolean,
  /**
   * Properties applied to the `FormHelperText` element.
   */
  FormHelperTextProps?: Object,
  /**
   * If `true`, the input will take up the full width of its container.
   */
  fullWidth?: boolean,
  /**
   * The helper text content.
   */
  helperText?: Node,
  /**
   * The CSS class name of the helper text element.
   */
  helperTextClassName?: string,
  /**
   * The id of the `input` element.
   */
  id?: string,
  /**
   * The CSS class name of the `input` element.
   */
  inputClassName?: string,
  /**
   * The CSS class name of the `Input` element.
   */
  InputClassName?: string,
  /**
   * Properties applied to the `InputLabel` element.
   */
  InputLabelProps?: Object,
  /**
   * Properties applied to the `input` element.
   */
  inputProps?: Object,
  /**
   * Properties applied to the `Input` element.
   */
  InputProps?: Object,
  /**
   * Use that property to pass a ref callback to the native input component.
   */
  inputRef?: Function,
  /**
   * The label content.
   */
  label?: Node,
  /**
   * The CSS class name of the label element.
   */
  labelClassName?: string,
  /**
   * If `true`, a textarea element will be rendered instead of an input.
   */
  multiline?: boolean,
  /**
   * Name attribute of the `input` element.
   */
  name?: string,
  /**
   * Callback fired when the value is changed.
   *
   * @param {object} event The event source of the callback
   */
  onChange?: (event: SyntheticInputEvent<>) => void,
  /**
   * The short hint displayed in the input before the user enters a value.
   */
  placeholder?: string,
  /**
   * If `true`, the label is displayed as required.
   */
  required?: boolean,
  /**
   * Use that property to pass a ref callback to the root component.
   */
  rootRef?: Function,
  /**
   * Number of rows to display when multiline option is set to true.
   */
  rows?: string | number,
  /**
   * Maximum number of rows to display when multiline option is set to true.
   */
  rowsMax?: string | number,
  /**
   * Render a `Select` element while passing the `Input` element to `Select` as `input` parameter.
   * If this option is set you must pass the options of the select as children.
   */
  select?: boolean,
  /**
   * Properties applied to the `Select` element.
   */
  SelectProps?: Object,
  /**
   * Type attribute of the `Input` element. It should be a valid HTML5 input type.
   */
  type?: string,
  /**
   * The value of the `Input` element, required for a controlled component.
   */
  value?: string | number,
  /**
   * If `dense` or `normal`, will adjust vertical spacing of this and contained components.
   */
  margin?: 'none' | 'dense' | 'normal',
};

function TextField(props: Props) {
  const {
    autoComplete,
    autoFocus,
    children,
    className,
    defaultValue,
    disabled,
    error,
    id,
    inputClassName,
    InputClassName,
    inputProps: inputPropsProp,
    InputProps,
    inputRef,
    label,
    labelClassName,
    InputLabelProps,
    helperText,
    helperTextClassName,
    FormHelperTextProps,
    fullWidth,
    required,
    type,
    multiline,
    name,
    onChange,
    placeholder,
    rootRef,
    rows,
    rowsMax,
    select,
    SelectProps,
    value,
    ...other
  } = props;

  let inputProps = inputPropsProp;

  if (inputClassName) {
    inputProps = {
      className: inputClassName,
      ...inputProps,
    };
  }

  warning(
    !select || Boolean(children),
    'Material-UI: `children` must be passed when using the `TextField` component with `select`.',
  );

  const InputComponent = (
    <Input
      autoComplete={autoComplete}
      autoFocus={autoFocus}
      className={InputClassName}
      defaultValue={defaultValue}
      disabled={disabled}
      multiline={multiline}
      name={name}
      rows={rows}
      rowsMax={rowsMax}
      type={type}
      value={value}
      id={id}
      inputProps={inputProps}
      inputRef={inputRef}
      onChange={onChange}
      placeholder={placeholder}
      {...InputProps}
    />
  );

  return (
    <FormControl
      fullWidth={fullWidth}
      className={className}
      error={error}
      required={required}
      {...other}
      ref={rootRef}
    >
      {label && (
        <InputLabel htmlFor={id} className={labelClassName} {...InputLabelProps}>
          {label}
        </InputLabel>
      )}
      {select ? (
        <Select value={value} input={InputComponent} {...SelectProps}>
          {children}
        </Select>
      ) : (
        InputComponent
      )}
      {helperText && (
        <FormHelperText className={helperTextClassName} {...FormHelperTextProps}>
          {helperText}
        </FormHelperText>
      )}
    </FormControl>
  );
}

TextField.defaultProps = {
  required: false,
  select: false,
};

export default TextField;
<|endoftext|>


<commit_before>/**
* Loosetime.js
*
*	Author: Bruce Taylor
*	URL: www.loosetime.com
*	Date: 07/06/2014
*	License: MIT License, open source
*
*/
/*
 * Parses datetime given by user and provides a string to be used for validation
 * e.g. for DD/MM/YYYY HH24:mm:SS.s --> 31/12/2999 23:59:59:9999
 */
function parseDateTime(parseStr)
{
	var validString = "";
	var res = parseStr.split(/[\/\/:.\s]/g);
	console.log(res.length);
	for(var i = 0; i < res.length; i++)
	{
		console.log(res[i]);
		switch(res[i])
		{
			case "DD":
			validString += "31";
			break;

			case "MM":
			validString += "12";
			break;

			case "YY":
			validString += "99";
			break;

			case "YYYY":
			validString += "2999";
			break;

			case "HH24":
			validString += "23";
			break;

			case "HH12":
			validString += "11";
			break;

			case "mm":
			validString += "59";
			break;

			case "SS":
			validString += "59";
			break;

			case "s":
			validString += "99";
			break;
		}
		//add delimiter
		validString += "/";
	}

	return validString;
}

/*
 * Sets the cursor position on user click of input element
 *
 */
function resetCursosPos()
{
	$(this).prop(
	{
		selectionStart : 0,
		selectionEnd : 0
	}
	);
}

/*
 * Validates user input against constraints given in time format
 */
function dateTimeRules(event, f)
{

	// if user does not enter tab or backspace then move input
	// cursor pos
	if (event.charCode >= 48 && event.charCode <= 57)
	{
		var delims = new Array('/', '-', '_', '.', '|', ',', ' ', ':');

		// get input cursor position
		var sel = $(this).prop('selectionStart');
		var val = $(this).val();
		explode = val.split("");
		var input = event.charCode - 48;
		if(sel <= $(this).prop('maxlength')+1)
		{
			// get value of char pos in loosetime attribute

			var thisChar = $(this).attr('loosetime').charAt(sel);
			// if position is on delimiter, jump to next position

			if((event.charCode - 48) <= thisChar)
			{
					if ($.inArray(explode[sel], delims) != -1)
					{
						 explode = val.split("");
						 explode[sel+1] = event.charCode - 48;
						 val = explode.join("");
						 newsel = sel + 2;
					}

					//move cursor to next position
					else
					{
						// if input value > loosetime char, prevent movement

						//replace char infront of cursor pos
						explode = val.split("");
						explode[sel] = event.charCode - 48;
						val = explode.join("");
						newsel = sel + 1;

					}

					$(this).prop({
									value : val,
									selectionStart : newsel,
									selectionEnd : newsel

								});
					}
					else
					{
						window.alert("Invalid input, the maximum value you can enter is " + thisChar + "\n"
						+ " you entered " + input);

					}

					// non numeric chars will be ignored, input cursor pos will stay

		}
	}
}

// takes datetime format, append location, name, value
function loosetime(a, b, c, d)
{
	var format = a;
	var appendLoc = b;
	var newName = c;
	var newVal = d;
	var newSize;

	// parse the time format passed in
	try
	{

		if (typeof(format) == 'undefined')
		{
			format = parseDateTime("DD/MM/YY HH24:MM:SS.s");
		}
		else
		{
			format = parseDateTime(format);
		}

		// check newVal given
		try
		{
			if (typeof(newVal) == 'undefined')
			{
				newVal = 'DD/MM/YY 00:00.00';
				newSize = 15;
			}

			// construct input element
			var input = $("<input>",
				{
					name : newName,
					maxlength : newSize,
					size : newSize,
					type : 'text',
					value : newVal,
					keypress : dateTimeRules,
					click : resetCursosPos,
					loosetime : format
				}
				);

			// append loosetime to the designated element in the DOM
			try
			{
				var col = document.getElementById('demotime');
				input.appendTo(col);
			}
			// catch omition of append location
			catch (e)
			{
				window.alert("Error, no Element given to append loosetime to.")

			}
		}

		// catch newVal exception
		catch (e)
		{
			window.alert("Error, Value is invalid." + e.toString());
		}
	}
	// catch format exception
	catch (e)
	{
		window.alert("Error, Date format missing or invalid.");
	}
}
<commit_msg>Refactored code<commit_after>/**
 * Loosetime.js
 *
 *	Author: Bruce Taylor
 *	URL: www.loosetime.com
 *	Date: 22/07/2014
 *	License: MIT License, open source
 */

(function(){
	config(
		{
			"format" : "DD/MM/YY HH24:MM:SS.s",
			"value" : "DD/MM/YY 00:00.00",
			"length" : 13,
		}
	);
})

function loosetime(a,b,c,d)
{

		var format = a;
		var appendLoc = b;
		var newName = c;
		var newVal = d;
		var newSize;

		// parse the time format passed in
		try
		{

			if (typeof(format) == 'undefined')
			{
				format = parseDateTime("DD/MM/YY HH24:MM:SS.s");
			}
			else
			{
				format = parseDateTime(format);
			}

			// check newVal given
			try
			{
				if (typeof(newVal) == 'undefined')
				{
					newVal = "DD/MM/YY 00:00.00";
					newSize = 15;
				}

				// construct input element
				var input = $("<input>",
					{
						name : newName,
						maxlength : newSize,
						size : newSize,
						type : 'text',
						value : newVal,
						keypress : dateTimeRules,
						click : resetCursosPos,
						loosetime : format
					}
					);

				// append loosetime to the designated element in the DOM
				try
				{
					var col = document.getElementById('demotime');
					input.appendTo(col);
				}
				// catch omition of append location
				catch (e)
				{
					window.alert("Error, no Element given to append loosetime to.")

				}
			}

			// catch newVal exception
			catch (e)
			{
				window.alert("Error, Value is invalid." + e.toString());
			}
		}
		// catch format exception
		catch (e)
		{
			window.alert("Error, Date format missing or invalid.");
		}

	/*
	 * Parses datetime given by user and provides a string to be used for validation
	 * e.g. for DD/MM/YYYY HH24:mm:SS.s --> 31/12/2999 23:59:59:9999
	 */
	function parseDateTime(parseStr)
	{
		var validString = "";
		var res = parseStr.split(/[\/\/:.\s]/g);
		console.log(res.length);
		for (var i = 0; i < res.length; i++)
		{
			console.log(res[i]);
			switch (res[i])
			{
			case "DD":
				validString += "31";
				break;

			case "MM":
				validString += "12";
				break;

			case "YY":
				validString += "99";
				break;

			case "YYYY":
				validString += "2999";
				break;

			case "HH24":
				validString += "23";
				break;

			case "HH12":
				validString += "11";
				break;

			case "mm":
				validString += "59";
				break;

			case "SS":
				validString += "59";
				break;

			case "s":
				validString += "99";
				break;
			}
			//add delimiter
			validString += "/";
		}

		return validString;
	}

	/*
	 * Sets the cursor position on user click of input element
	 */
	function resetCursosPos()
	{
		$(this).prop(
		{
			selectionStart : 0,
			selectionEnd : 0
		}
		);
	}

	/*
	 * Validates user input against constraints given in time format
	 */
	function dateTimeRules(event, f)
	{

		// if user does not enter tab or backspace then move input
		// cursor pos
		if (event.charCode >= 48 && event.charCode <= 57)
		{
			var delims = new Array('/', '-', '_', '.', '|', ',', ' ', ':');

			// get input cursor position
			var sel = $(this).prop('selectionStart');
			var val = $(this).val();
			explode = val.split("");
			var input = event.charCode - 48;
			if (sel <= $(this).prop('maxlength') + 1)
			{
				// get value of char pos in loosetime attribute

				var thisChar = $(this).attr('loosetime').charAt(sel);
				// if position is on delimiter, jump to next position

				if ($.inArray(explode[sel], delims) != -1)
				{
					explode = val.split("");
					explode[sel + 1] = event.charCode - 48;
					val = explode.join("");
					newsel = sel + 2;
				}

				//move cursor to next position
				else
				{
					// if input value > loosetime char, prevent movement

					//replace char infront of cursor pos
					explode = val.split("");
					explode[sel] = event.charCode - 48;
					val = explode.join("");
					newsel = sel + 1;

				}

				$(this).prop(
				{
					value : val,
					selectionStart : newsel,
					selectionEnd : newsel

				}
				);

				// non numeric chars will be ignored, input cursor pos will stay
			}
		}
	}

}
<|endoftext|>