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

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

// Components
import ColGroup from '../_ColGroup';
import Thead from '../_Thead';
import Tbody from '../_Tbody';
import Tfoot from '../_Tfoot';

// 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 classNames from 'classnames';
import Util from '../_vendors/Util';
import TC from '../_vendors/TableCalculation';

class BaseTable extends Component {

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

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

    getColumns = (columns = this.props.columns) => {
        return columns ?
            columns.map((column, index) => ({
                column,
                path: [index]
            }))
            :
            columns;
    };

    getColumnsSpan = (columns = this.getColumns()) => {

        const {fragment, bodyColumns, onRequestColumnsSpan} = this.props;

        return onRequestColumnsSpan ?
            onRequestColumnsSpan(fragment, bodyColumns || columns)
            :
            TC.getColumnsSpan(fragment, bodyColumns || columns);

    };

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

        const {

                className, style, data, dynamicRenderData, value, idProp, baseColIndex, fragment, scrollEl,
                headColumns, bodyColumns, columnsWidth, selectMode, selectAllMode, expandRows, resizingColumnPath,
                useDynamicRender, scrollHeight, rowHeight, scrollBuffer,
                isColumnResizable, defaultColumnWidth, minColumnWidth, maxColumnWidth,
                isHeadHidden, isBodyHidden, isFootHidden,
                isMouseEventForbidden, isLayoutFixed, isHeadFixed, isFootFixed,
                ignoreColumnSpan, hasHeadRenderer, hasBodyRenderer, hasFootRenderer,
                sorting, defaultSortingType, sortingAscIconCls, sortingDescIconCls, isClickSorting,
                onSortChange, onExpandChange, onRequestColumnsSpan,
                onColumnsWidthChange, onColumnResizeStart, onColumnResizeEnd,

                // not passing down these props
                columns: cols,

                ...restProps

            } = this.props,
            columns = this.getColumns();

        return (
            <table {...restProps}
                   className={classNames('base-table', {
                       [className]: className
                   })}
                   style={{
                       ...style,
                       tableLayout: isLayoutFixed ? 'fixed' : null
                   }}>

                <ColGroup columns={this.getColumnsSpan(columns)}
                          columnsWidth={columnsWidth}
                          isColumnResizable={isColumnResizable}
                          defaultColumnWidth={defaultColumnWidth}
                          minColumnWidth={minColumnWidth}
                          ignoreColumnSpan={ignoreColumnSpan}/>

                {
                    !isHeadHidden && hasHeadRenderer ?
                        <Thead {...restProps}
                               columns={headColumns || columns}
                               columnsWidth={columnsWidth}
                               data={data}
                               dynamicRenderData={dynamicRenderData}
                               selectMode={selectMode}
                               selectAllMode={selectAllMode}
                               sorting={sorting}
                               defaultSortingType={defaultSortingType}
                               sortingAscIconCls={sortingAscIconCls}
                               sortingDescIconCls={sortingDescIconCls}
                               isClickSorting={isClickSorting}
                               ignoreColumnSpan={ignoreColumnSpan}
                               scrollEl={scrollEl}
                               isColumnResizable={isColumnResizable}
                               defaultColumnWidth={defaultColumnWidth}
                               minColumnWidth={minColumnWidth}
                               maxColumnWidth={maxColumnWidth}
                               resizingColumnPath={resizingColumnPath}
                               onSortChange={onSortChange}
                               onRequestColumnsSpan={onRequestColumnsSpan}
                               onColumnsWidthChange={onColumnsWidthChange}
                               onColumnResizeStart={onColumnResizeStart}
                               onColumnResizeEnd={onColumnResizeEnd}/>
                        :
                        null
                }

                {
                    !isBodyHidden && hasBodyRenderer ?
                        <Tbody {...restProps}
                               columns={bodyColumns || columns}
                               data={data}
                               dynamicRenderData={dynamicRenderData}
                               value={value}
                               selectMode={selectMode}
                               selectAllMode={selectAllMode}
                               expandRows={expandRows}
                               idProp={idProp}
                               baseColIndex={baseColIndex}
                               sorting={sorting}
                               isMouseEventForbidden={isMouseEventForbidden}
                               ignoreColumnSpan={ignoreColumnSpan}
                               scrollEl={scrollEl}
                               defaultColumnWidth={defaultColumnWidth}
                               useDynamicRender={useDynamicRender}
                               scrollHeight={scrollHeight}
                               rowHeight={rowHeight}
                               scrollBuffer={scrollBuffer}
                               onExpandChange={onExpandChange}
                               onRequestColumnsSpan={onRequestColumnsSpan}/>
                        :
                        null
                }

                {/** render foot if a footRenderer exists in columns */}
                {
                    !isFootHidden && hasFootRenderer ?
                        <Tfoot {...restProps}
                               columns={bodyColumns || columns}
                               data={data}
                               dynamicRenderData={dynamicRenderData}
                               selectMode={selectMode}
                               selectAllMode={selectAllMode}
                               ignoreColumnSpan={ignoreColumnSpan}
                               scrollEl={scrollEl}
                               defaultColumnWidth={defaultColumnWidth}
                               onRequestColumnsSpan={onRequestColumnsSpan}/>
                        :
                        null
                }

            </table>
        );

    }
}

BaseTable.propTypes = {

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

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

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

    /**
     * The select all mode of table, all or current page.
     */
    selectAllMode: PropTypes.oneOf(Util.enumerateValue(SelectAllMode)),

    fragment: PropTypes.oneOf(Util.enumerateValue(TableFragment)),

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

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

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

        /**
         * 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))

    })),
    headColumns: PropTypes.array,
    bodyColumns: PropTypes.array,
    columnsWidth: PropTypes.object,
    data: PropTypes.array,
    dynamicRenderData: PropTypes.array,
    value: PropTypes.array,
    idProp: PropTypes.string,
    baseColIndex: PropTypes.number,
    disabled: PropTypes.bool,
    expandRows: PropTypes.array,
    isMouseEventForbidden: PropTypes.bool,
    ignoreColumnSpan: PropTypes.bool,
    scrollEl: PropTypes.object,

    /**
     * fixed
     */
    isLayoutFixed: PropTypes.bool,
    isHeadFixed: PropTypes.bool,
    isFootFixed: PropTypes.bool,

    /**
     * hidden
     */
    isHeadHidden: PropTypes.bool,
    isBodyHidden: PropTypes.bool,
    isFootHidden: PropTypes.bool,

    /**
     * has renderer
     */
    hasHeadRenderer: PropTypes.bool,
    hasBodyRenderer: PropTypes.bool,
    hasFootRenderer: PropTypes.bool,

    /**
     * sorting
     */
    sorting: PropTypes.shape({
        prop: PropTypes.string,
        type: PropTypes.oneOf(Util.enumerateValue(SortingType))
    }),
    defaultSortingType: PropTypes.oneOf(Util.enumerateValue(SortingType)),
    sortingAscIconCls: PropTypes.string,
    sortingDescIconCls: PropTypes.string,
    isClickSorting: PropTypes.bool,

    /**
     * Dynamic Render
     */
    useDynamicRender: PropTypes.bool,
    scrollHeight: PropTypes.number,
    rowHeight: PropTypes.number,
    scrollBuffer: PropTypes.number,

    /**
     * column resizable
     */
    isColumnResizable: PropTypes.bool,
    defaultColumnWidth: PropTypes.number,
    minColumnWidth: PropTypes.number,
    maxColumnWidth: PropTypes.number,
    resizingColumnPath: PropTypes.array,

    /**
     * callback
     */
    onSortChange: PropTypes.func,
    onHeadClick: PropTypes.func,
    onRowClick: PropTypes.func,
    onCellClick: PropTypes.func,
    onFootClick: PropTypes.func,
    onExpandChange: PropTypes.func,
    onRequestColumnsSpan: PropTypes.func,
    onColumnsWidthChange: PropTypes.func,
    onColumnResizeStart: PropTypes.func,
    onColumnResizeEnd: PropTypes.func

};

BaseTable.defaultProps = {

    baseColIndex: 0,
    disabled: false,
    expandRows: [],
    idProp: 'id',
    isMouseEventForbidden: false,
    ignoreColumnSpan: false,

    /**
     * fixed
     */
    isLayoutFixed: true,
    isHeadFixed: false,
    isFootFixed: false,

    /**
     * hidden
     */
    isHeadHidden: false,
    isBodyHidden: false,
    isFootHidden: false,

    /**
     * has renderer
     */
    hasHeadRenderer: true,
    hasBodyRenderer: true,
    hasFootRenderer: true,

    /**
     * sorting
     */
    defaultSortingType: SortingType.ASC,
    sortingAscIconCls: 'fas fa-sort-up',
    sortingDescIconCls: 'fas fa-sort-down',
    isClickSorting: true,

    /**
     * Dynamic Render
     */
    useDynamicRender: false,
    scrollHeight: 500,
    rowHeight: 50,
    scrollBuffer: 8,

    /**
     * column resizable
     */
    isColumnResizable: false,
    defaultColumnWidth: 100,
    minColumnWidth: 64,
    maxColumnWidth: Infinity

};

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

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

// Components
import ColGroup from '../_ColGroup';
import Thead from '../_Thead';
import Tbody from '../_Tbody';
import Tfoot from '../_Tfoot';

// 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 classNames from 'classnames';
import Util from '../_vendors/Util';
import TC from '../_vendors/TableCalculation';

class BaseTable extends Component {

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

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

    getColumns = (columns = this.props.columns) => {
        return columns ?
            columns.map((column, index) => ({
                column,
                path: [index]
            }))
            :
            columns;
    };

    getColumnsSpan = (columns = this.getColumns()) => {

        const {fragment, bodyColumns, onRequestColumnsSpan} = this.props;

        return onRequestColumnsSpan ?
            onRequestColumnsSpan(fragment, bodyColumns || columns)
            :
            TC.getColumnsSpan(fragment, bodyColumns || columns);

    };

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

        const {

                className, style, data, dynamicRenderData, value, idField, baseColIndex, fragment, scrollEl,
                headColumns, bodyColumns, columnsWidth, selectMode, selectAllMode, expandRows, resizingColumnPath,
                useDynamicRender, scrollHeight, rowHeight, scrollBuffer,
                isColumnResizable, defaultColumnWidth, minColumnWidth, maxColumnWidth,
                isHeadHidden, isBodyHidden, isFootHidden,
                isMouseEventForbidden, isLayoutFixed, isHeadFixed, isFootFixed,
                ignoreColumnSpan, hasHeadRenderer, hasBodyRenderer, hasFootRenderer,
                sorting, defaultSortingType, sortingAscIconCls, sortingDescIconCls, isClickSorting,
                onSortChange, onExpandChange, onRequestColumnsSpan,
                onColumnsWidthChange, onColumnResizeStart, onColumnResizeEnd, onColumnResize,

                // not passing down these props
                columns: cols,

                ...restProps

            } = this.props,
            columns = this.getColumns();

        return (
            <table {...restProps}
                   className={classNames('base-table', {
                       [className]: className
                   })}
                   style={{
                       ...style,
                       tableLayout: isLayoutFixed ? 'fixed' : null
                   }}>

                <ColGroup columns={this.getColumnsSpan(columns)}
                          columnsWidth={columnsWidth}
                          isColumnResizable={isColumnResizable}
                          defaultColumnWidth={defaultColumnWidth}
                          minColumnWidth={minColumnWidth}
                          ignoreColumnSpan={ignoreColumnSpan}/>

                {
                    !isHeadHidden && hasHeadRenderer ?
                        <Thead {...restProps}
                               columns={headColumns || columns}
                               columnsWidth={columnsWidth}
                               data={data}
                               dynamicRenderData={dynamicRenderData}
                               selectMode={selectMode}
                               selectAllMode={selectAllMode}
                               sorting={sorting}
                               defaultSortingType={defaultSortingType}
                               sortingAscIconCls={sortingAscIconCls}
                               sortingDescIconCls={sortingDescIconCls}
                               isClickSorting={isClickSorting}
                               ignoreColumnSpan={ignoreColumnSpan}
                               scrollEl={scrollEl}
                               isColumnResizable={isColumnResizable}
                               defaultColumnWidth={defaultColumnWidth}
                               minColumnWidth={minColumnWidth}
                               maxColumnWidth={maxColumnWidth}
                               resizingColumnPath={resizingColumnPath}
                               onSortChange={onSortChange}
                               onRequestColumnsSpan={onRequestColumnsSpan}
                               onColumnsWidthChange={onColumnsWidthChange}
                               onColumnResizeStart={onColumnResizeStart}
                               onColumnResizeEnd={onColumnResizeEnd}/>
                        :
                        null
                }

                {
                    !isBodyHidden && hasBodyRenderer ?
                        <Tbody {...restProps}
                               columns={bodyColumns || columns}
                               data={data}
                               dynamicRenderData={dynamicRenderData}
                               value={value}
                               selectMode={selectMode}
                               selectAllMode={selectAllMode}
                               expandRows={expandRows}
                               idField={idField}
                               baseColIndex={baseColIndex}
                               sorting={sorting}
                               isMouseEventForbidden={isMouseEventForbidden}
                               ignoreColumnSpan={ignoreColumnSpan}
                               scrollEl={scrollEl}
                               defaultColumnWidth={defaultColumnWidth}
                               useDynamicRender={useDynamicRender}
                               scrollHeight={scrollHeight}
                               rowHeight={rowHeight}
                               scrollBuffer={scrollBuffer}
                               onExpandChange={onExpandChange}
                               onRequestColumnsSpan={onRequestColumnsSpan}
                               onColumnResize={onColumnResize}/>
                        :
                        null
                }

                {/** render foot if a footRenderer exists in columns */}
                {
                    !isFootHidden && hasFootRenderer ?
                        <Tfoot {...restProps}
                               columns={bodyColumns || columns}
                               data={data}
                               dynamicRenderData={dynamicRenderData}
                               selectMode={selectMode}
                               selectAllMode={selectAllMode}
                               ignoreColumnSpan={ignoreColumnSpan}
                               scrollEl={scrollEl}
                               defaultColumnWidth={defaultColumnWidth}
                               onRequestColumnsSpan={onRequestColumnsSpan}/>
                        :
                        null
                }

            </table>
        );

    }
}

BaseTable.propTypes = {

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

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

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

    /**
     * The select all mode of table, all or current page.
     */
    selectAllMode: PropTypes.oneOf(Util.enumerateValue(SelectAllMode)),

    fragment: PropTypes.oneOf(Util.enumerateValue(TableFragment)),

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

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

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

        /**
         * 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))

    })),
    headColumns: PropTypes.array,
    bodyColumns: PropTypes.array,
    columnsWidth: PropTypes.object,
    data: PropTypes.array,
    dynamicRenderData: PropTypes.array,
    value: PropTypes.array,
    idField: PropTypes.string,
    baseColIndex: PropTypes.number,
    disabled: PropTypes.bool,
    expandRows: PropTypes.array,
    isMouseEventForbidden: PropTypes.bool,
    ignoreColumnSpan: PropTypes.bool,
    scrollEl: PropTypes.object,

    /**
     * fixed
     */
    isLayoutFixed: PropTypes.bool,
    isHeadFixed: PropTypes.bool,
    isFootFixed: PropTypes.bool,

    /**
     * hidden
     */
    isHeadHidden: PropTypes.bool,
    isBodyHidden: PropTypes.bool,
    isFootHidden: PropTypes.bool,

    /**
     * has renderer
     */
    hasHeadRenderer: PropTypes.bool,
    hasBodyRenderer: PropTypes.bool,
    hasFootRenderer: PropTypes.bool,

    /**
     * sorting
     */
    sorting: PropTypes.shape({
        prop: PropTypes.string,
        type: PropTypes.oneOf(Util.enumerateValue(SortingType))
    }),
    defaultSortingType: PropTypes.oneOf(Util.enumerateValue(SortingType)),
    sortingAscIconCls: PropTypes.string,
    sortingDescIconCls: PropTypes.string,
    isClickSorting: PropTypes.bool,

    /**
     * Dynamic Render
     */
    useDynamicRender: PropTypes.bool,
    scrollHeight: PropTypes.number,
    rowHeight: PropTypes.number,
    scrollBuffer: PropTypes.number,

    /**
     * column resizable
     */
    isColumnResizable: PropTypes.bool,
    defaultColumnWidth: PropTypes.number,
    minColumnWidth: PropTypes.number,
    maxColumnWidth: PropTypes.number,
    resizingColumnPath: PropTypes.array,

    /**
     * callback
     */
    onSortChange: PropTypes.func,
    onHeadClick: PropTypes.func,
    onRowClick: PropTypes.func,
    onCellClick: PropTypes.func,
    onFootClick: PropTypes.func,
    onExpandChange: PropTypes.func,
    onRequestColumnsSpan: PropTypes.func,
    onColumnsWidthChange: PropTypes.func,
    onColumnResizeStart: PropTypes.func,
    onColumnResizeEnd: PropTypes.func,
    onColumnResize: PropTypes.func

};

BaseTable.defaultProps = {

    baseColIndex: 0,
    disabled: false,
    expandRows: [],
    idField: 'id',
    isMouseEventForbidden: false,
    ignoreColumnSpan: false,

    /**
     * fixed
     */
    isLayoutFixed: true,
    isHeadFixed: false,
    isFootFixed: false,

    /**
     * hidden
     */
    isHeadHidden: false,
    isBodyHidden: false,
    isFootHidden: false,

    /**
     * has renderer
     */
    hasHeadRenderer: true,
    hasBodyRenderer: true,
    hasFootRenderer: true,

    /**
     * sorting
     */
    defaultSortingType: SortingType.ASC,
    sortingAscIconCls: 'fas fa-sort-up',
    sortingDescIconCls: 'fas fa-sort-down',
    isClickSorting: true,

    /**
     * Dynamic Render
     */
    useDynamicRender: false,
    scrollHeight: 500,
    rowHeight: 50,
    scrollBuffer: 8,

    /**
     * column resizable
     */
    isColumnResizable: false,
    defaultColumnWidth: 100,
    minColumnWidth: 64,
    maxColumnWidth: Infinity

};

export default BaseTable;
<|endoftext|>


<commit_before>'use strict';

module.exports = function(kbox) {

  // Modules
  var path = require('path');
  var fs = require('fs');
  var _ = require('lodash');

  // Nobody expects the Spanish Inquisition!
  var inquirer = require('inquirer');

  // "Constants"
  var PLUGIN_NAME = 'kalabox-plugin-pantheon';

  kbox.ifApp(function(app) {

    // Get our push and pull stuff
    var puller = require('./pull.js')(kbox, app);
    var pusher = require('./push.js')(kbox, app);

    // Grab the needed clients
    var Terminus = require('./terminus.js');
    var terminus = new Terminus(kbox, app);
    var pathToRoot = path.resolve(__dirname, '..', '..', '..');
    var pathToNode = path.join(pathToRoot, 'node_modules');
    var Drush = require(pathToNode + '/kalabox-plugin-drush/lib/drush.js');
    var drush = new Drush(kbox, app, 'terminus', PLUGIN_NAME);

    /*
     * Filter out questions that have been answered interactively
     */
    var filterQuestions = function(questions, options) {

      return _.filter(questions, function(question) {

        var option = options[question.name];

        if (question.filter) {
          options[question.name] = question.filter(options[question.name]);
        }
        if (option === false || option === undefined) {
          return true;
        }
        else {
          return !_.includes(Object.keys(options), question.name);
        }

      });
    };

    // Tasks
    // kbox terminus COMMAND
    kbox.tasks.add(function(task) {
      task.path = [app.name, 'terminus'];
      task.category = 'appCmd';
      task.description = 'Run terminus commands.';
      task.kind = 'delegate';
      task.func = function(done) {
        var opts = terminus.getOpts(this.options);
        var cmd = this.payload;
        terminus.cmd(cmd, opts, done);
      };
    });

    // kbox drush COMMAND
    kbox.tasks.add(function(task) {
      task.path = [app.name, 'drush'];
      task.category = 'appCmd';
      task.description = 'Run drush commands.';
      task.kind = 'delegate';
      task.options.push({
        name: 'drush-version',
        kind: 'string',
        description: 'The version of drush that you want.'
      });
      task.func = function(done) {
        var opts = drush.getOpts(this.options);
        var cmd = this.payload;
        cmd.unshift('@dev');
        cmd.push('--strict=0');
        drush.cmd(cmd, opts, done);
      };
    });

    // kbox pull
    kbox.tasks.add(function(task) {

      // Grab pantheon config so we can mix in interactives
      var pantheonConf = app.config.pluginConf['kalabox-plugin-pantheon'];

      // Define our task metadata
      task.path = [app.name, 'pull'];
      task.category = 'appAction';
      task.description = 'Pull down new code and optionally data and files.';
      task.kind = 'delegate';
      task.options.push({
        name: 'database',
        kind: 'boolean',
        description: 'Import latest database backup.'
      });
      task.options.push({
        name: 'files',
        kind: 'boolean',
        description: 'Import latest files.'
      });

      // This is what we run yo!
      task.func = function(done) {

        // Grab the CLI options that are available
        var options = this.options;
        var questions = [
          {
            type: 'confirm',
            name: 'database',
            message: 'Also refresh from latest database backup?',
          },
          {
            type: 'confirm',
            name: 'files',
            message: 'Also grab latest files?',
          },
        ];

        // Filter out interactive questions based on passed in options
        questions = filterQuestions(questions, options);

        // Launch the inquiry
        inquirer.prompt(questions, function(answers) {

          // Collect our answers
          var choices = _.merge({}, options, answers);

          // Grab pantheon aliases
          return terminus.getSiteAliases()

          // Pull our code
          .then(function() {
            return puller.pullCode(pantheonConf.site, pantheonConf.env);
          })

          // Pull our DB if selected
          .then(function() {
            if (choices.database) {
              return puller.pullDB(pantheonConf.site, pantheonConf.env);
            }
          })

          // Pull our files if selected
          .then(function() {
            if (choices.files) {
              return puller.pullFiles(pantheonConf.site, pantheonConf.env);
            }
          })

          .nodeify(done);

        });

      };
    });

    // kbox appname push
    kbox.tasks.add(function(task) {

      // Grab pantheon conf
      var pantheonConf = app.config.pluginConf[PLUGIN_NAME];

      // Task metadata
      task.path = [app.name, 'push'];
      task.category = 'appAction';
      task.description = 'Push up new code and optionally data and files.';
      task.kind = 'delegate';
      task.options.push({
        name: 'message',
        kind: 'string',
        description: 'Tell us about your change'
      });
      task.options.push({
        name: 'database',
        kind: 'boolean',
        description: 'Push local database up.'
      });
      task.options.push({
        name: 'files',
        kind: 'boolean',
        description: 'Push local files up.'
      });

      // This is how we do it
      // https://www.youtube.com/watch?v=0hiUuL5uTKc
      task.func = function(done) {

        // Grab the CLI options that are available
        var options = this.options;
        var questions = [
          {
            type: 'input',
            name: 'm',
            message: 'Tell us about these changes.',
            default: 'Best changes ever!'
          },
          {
            type: 'confirm',
            name: 'database',
            message: 'Also push up your local database?',
          },
          {
            type: 'confirm',
            name: 'files',
            message: 'Also push up your local files directory?',
          },
        ];

        // Filter out interactive questions based on passed in options
        questions = filterQuestions(questions, options);

        // Launch the inquiry
        inquirer.prompt(questions, function(answers) {

          // Collect our choices
          var choices = _.merge({}, options, answers);

          // Grab pantheon site aliases
          return terminus.getSiteAliases()

          // Push our code
          .then(function() {
            return pusher.pushCode(
              pantheonConf.site,
              pantheonConf.env,
              choices.message
            );
          })

          // Push our DB is selected
          .then(function() {
            if (choices.database) {
              return pusher.pushDB(pantheonConf.site, pantheonConf.env);
            }
          })

          // Push our files if selected
          .then(function() {
            if (choices.files) {
              return pusher.pushFiles(pantheonConf.site, pantheonConf.env);
            }
          })

          .nodeify(done);

        });

      };
    });

    // Events
    // Build the site after post-create happens
    kbox.core.events.on('post-create-app', function(app, done) {

      // Our pantheon config for later on
      var pantheonConf = app.config.pluginConf[PLUGIN_NAME];

      // Get our pantheon site aliases
      return terminus.getSiteAliases()

      // Pull our code for the first time
      .then(function() {
        return puller.pullCode(pantheonConf.site, pantheonConf.env);
      })

      // Pull our DB
      .then(function() {
        return puller.pullDB(pantheonConf.site, pantheonConf.env);
      })

      // Get our files
      .then(function() {
        return puller.pullFiles(pantheonConf.site, pantheonConf.env);
      })

      .nodeify(done);

    });

  });

};
<commit_msg>#530: clean up for kbox push<commit_after>'use strict';

module.exports = function(kbox) {

  // Modules
  var path = require('path');
  var fs = require('fs');
  var _ = require('lodash');

  // Nobody expects the Spanish Inquisition!
  var inquirer = require('inquirer');

  // "Constants"
  var PLUGIN_NAME = 'kalabox-plugin-pantheon';

  kbox.ifApp(function(app) {

    // Get our push and pull stuff
    var puller = require('./pull.js')(kbox, app);
    var pusher = require('./push.js')(kbox, app);

    // Grab the needed clients
    var Terminus = require('./terminus.js');
    var terminus = new Terminus(kbox, app);
    var pathToRoot = path.resolve(__dirname, '..', '..', '..');
    var pathToNode = path.join(pathToRoot, 'node_modules');
    var Drush = require(pathToNode + '/kalabox-plugin-drush/lib/drush.js');
    var drush = new Drush(kbox, app, 'terminus', PLUGIN_NAME);

    /*
     * Filter out questions that have been answered interactively
     */
    var filterQuestions = function(questions, options) {

      return _.filter(questions, function(question) {

        var option = options[question.name];

        if (question.filter) {
          options[question.name] = question.filter(options[question.name]);
        }
        if (option === false || option === undefined) {
          return true;
        }
        else {
          return !_.includes(Object.keys(options), question.name);
        }

      });
    };

    // Tasks
    // kbox terminus COMMAND
    kbox.tasks.add(function(task) {
      task.path = [app.name, 'terminus'];
      task.category = 'appCmd';
      task.description = 'Run terminus commands.';
      task.kind = 'delegate';
      task.func = function(done) {
        var opts = terminus.getOpts(this.options);
        var cmd = this.payload;
        terminus.cmd(cmd, opts, done);
      };
    });

    // kbox drush COMMAND
    kbox.tasks.add(function(task) {
      task.path = [app.name, 'drush'];
      task.category = 'appCmd';
      task.description = 'Run drush commands.';
      task.kind = 'delegate';
      task.options.push({
        name: 'drush-version',
        kind: 'string',
        description: 'The version of drush that you want.'
      });
      task.func = function(done) {
        var opts = drush.getOpts(this.options);
        var cmd = this.payload;
        cmd.unshift('@dev');
        cmd.push('--strict=0');
        drush.cmd(cmd, opts, done);
      };
    });

    // kbox pull
    kbox.tasks.add(function(task) {

      // Grab pantheon config so we can mix in interactives
      var pantheonConf = app.config.pluginConf['kalabox-plugin-pantheon'];

      // Define our task metadata
      task.path = [app.name, 'pull'];
      task.category = 'appAction';
      task.description = 'Pull down new code and optionally data and files.';
      task.kind = 'delegate';
      task.options.push({
        name: 'database',
        kind: 'boolean',
        description: 'Import latest database backup.'
      });
      task.options.push({
        name: 'files',
        kind: 'boolean',
        description: 'Import latest files.'
      });

      // This is what we run yo!
      task.func = function(done) {

        // Grab the CLI options that are available
        var options = this.options;
        var questions = [
          {
            type: 'confirm',
            name: 'database',
            message: 'Also refresh from latest database backup?',
          },
          {
            type: 'confirm',
            name: 'files',
            message: 'Also grab latest files?',
          },
        ];

        // Filter out interactive questions based on passed in options
        questions = filterQuestions(questions, options);

        // Launch the inquiry
        inquirer.prompt(questions, function(answers) {

          // Collect our answers
          var choices = _.merge({}, options, answers);

          // Grab pantheon aliases
          return terminus.getSiteAliases()

          // Pull our code
          .then(function() {
            return puller.pullCode(pantheonConf.site, pantheonConf.env);
          })

          // Pull our DB if selected
          .then(function() {
            if (choices.database) {
              return puller.pullDB(pantheonConf.site, pantheonConf.env);
            }
          })

          // Pull our files if selected
          .then(function() {
            if (choices.files) {
              return puller.pullFiles(pantheonConf.site, pantheonConf.env);
            }
          })

          .nodeify(done);

        });

      };
    });

    // kbox appname push
    kbox.tasks.add(function(task) {

      // Grab pantheon conf
      var pantheonConf = app.config.pluginConf[PLUGIN_NAME];

      // Task metadata
      task.path = [app.name, 'push'];
      task.category = 'appAction';
      task.description = 'Push up new code and optionally data and files.';
      task.kind = 'delegate';
      task.options.push({
        name: 'message',
        alias: 'm',
        kind: 'string',
        description: 'Tell us about your change'
      });
      task.options.push({
        name: 'database',
        kind: 'boolean',
        description: 'Push local database up.'
      });
      task.options.push({
        name: 'files',
        kind: 'boolean',
        description: 'Push local files up.'
      });

      // This is how we do it
      // https://www.youtube.com/watch?v=0hiUuL5uTKc
      task.func = function(done) {

        // Grab the CLI options that are available
        var options = this.options;
        var questions = [
          {
            type: 'input',
            name: 'message',
            message: 'Tell us about these changes.',
            default: 'Best changes ever!'
          },
          {
            type: 'confirm',
            name: 'database',
            message: 'Also push up your local database?',
          },
          {
            type: 'confirm',
            name: 'files',
            message: 'Also push up your local files directory?',
          },
        ];

        // Filter out interactive questions based on passed in options
        questions = filterQuestions(questions, options);

        // Launch the inquiry
        inquirer.prompt(questions, function(answers) {

          // Collect our choices
          var choices = _.merge({}, options, answers);

          // Grab pantheon site aliases
          return terminus.getSiteAliases()

          // Push our code
          .then(function() {
            return pusher.pushCode(
              pantheonConf.site,
              pantheonConf.env,
              choices.message
            );
          })

          // Push our DB is selected
          .then(function() {
            if (choices.database) {
              return pusher.pushDB(pantheonConf.site, pantheonConf.env);
            }
          })

          // Push our files if selected
          .then(function() {
            if (choices.files) {
              return pusher.pushFiles(pantheonConf.site, pantheonConf.env);
            }
          })

          .nodeify(done);

        });

      };
    });

    // Events
    // Build the site after post-create happens
    kbox.core.events.on('post-create-app', function(app, done) {

      // Our pantheon config for later on
      var pantheonConf = app.config.pluginConf[PLUGIN_NAME];

      // Get our pantheon site aliases
      return terminus.getSiteAliases()

      // Pull our code for the first time
      .then(function() {
        return puller.pullCode(pantheonConf.site, pantheonConf.env);
      })

      // Pull our DB
      .then(function() {
        return puller.pullDB(pantheonConf.site, pantheonConf.env);
      })

      // Get our files
      .then(function() {
        return puller.pullFiles(pantheonConf.site, pantheonConf.env);
      })

      .nodeify(done);

    });

  });

};
<|endoftext|>


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

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

// Statics
import HorizontalAlign from '../_statics/HorizontalAlign';
import SortingType from '../_statics/SortingType';

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

class MeasureTd extends Component {

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.td = createRef();
        this.tdEl = null;

        this.lastWidth = null;

    }

    componentDidMount() {

        Event.addEvent(window, 'resize', this.handleMeasure);

        this.tdEl = this.td?.current;
        this.handleMeasure();

    }

    componentDidUpdate(prevProps, prevState, snapshot) {
        this.handleMeasure();
    }

    componentWillUnmount() {
        Event.removeEvent(window, 'resize', this.handleMeasure);
    }

    handleMeasure = () => {

        const width = this.tdEl.offsetWidth;

        if (width !== this.lastWidth) {

            this.lastWidth = width;

            const {column, columnKeyField, onMeasure} = this.props;
            onMeasure && onMeasure((columnKeyField && column[columnKeyField]) || column, width);

        }

    };

    render() {
        return (

        );
    }

}

MeasureTd.propTypes = {

    className: PropTypes.string,
    style: PropTypes.object,

    column: 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]),

        /**
         * 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))

    }),
    columnKeyField: PropTypes.string,

    onMeasure: PropTypes.func

};

MeasureTd.defaultProps = {
    columnKeyField: 'key'
};

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

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

// Statics
import HorizontalAlign from '../_statics/HorizontalAlign';
import SortingType from '../_statics/SortingType';

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

class MeasureTd extends Component {

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.td = createRef();
        this.tdEl = null;

        this.lastWidth = null;

    }

    componentDidMount() {

        Event.addEvent(window, 'resize', this.handleMeasure);

        this.tdEl = this.td?.current;
        this.handleMeasure();

    }

    componentDidUpdate(prevProps, prevState, snapshot) {
        this.handleMeasure();
    }

    componentWillUnmount() {
        Event.removeEvent(window, 'resize', this.handleMeasure);
    }

    handleMeasure = () => {

        const width = this.tdEl.offsetWidth;

        if (width !== this.lastWidth) {

            this.lastWidth = width;

            const {column, columnKeyField, onMeasure} = this.props;
            onMeasure && onMeasure((columnKeyField && column[columnKeyField]) || column, width);

        }

    };

    render() {
        return (

        );
    }

}

MeasureTd.propTypes = {

    className: PropTypes.string,
    style: PropTypes.object,

    column: 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))

    }),
    columnKeyField: PropTypes.string,

    onMeasure: PropTypes.func

};

MeasureTd.defaultProps = {
    columnKeyField: 'key'
};

export default MeasureTd;
<|endoftext|>


<commit_before>import Ember from 'ember';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';

export default Ember.Route.extend(AuthenticatedRouteMixin, {
  currentUser: Ember.inject.service('current-user'),
  model() {
    let user_id = this.get('currentUser.user.id');
    return this.get('store').query('convention', {
      'assignments__person__user': user_id,
      'assignments__kind': 5, //Hard-coded
      'status__lt': 45 //Hard-coded
    });
  },
});
<commit_msg>Update kind -> category for assignment lists<commit_after>import Ember from 'ember';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';

export default Ember.Route.extend(AuthenticatedRouteMixin, {
  currentUser: Ember.inject.service('current-user'),
  model() {
    let user_id = this.get('currentUser.user.id');
    return this.get('store').query('convention', {
      'assignments__person__user': user_id,
      'assignments__category': 5, //Hard-coded
      'status__lt': 45 //Hard-coded
    });
  },
});
<|endoftext|>


<commit_before>'use strict';
define(['app', 'challenge_show_view', 'challenge_entity'], function(App, View) {
    App.module('Challenge.Show', function (Show, App, Backbone, Marionette, $) { // , _
        Show.Controller = {
            show: function(id) {
                var layout = new View.Layout();

                // ---- Make awesome slider region: ----
                var PageRegion = Backbone.Marionette.Region.extend({
                    el: '#show_page',
                });
                PageRegion.prototype.open = function(view) {
                    this.$el.hide();
                    this.$el.html(view.el);
                    this.$el.slideDown('fast');
                };
                layout.pageRegion = new PageRegion();
                App.mainRegion.show(layout);
                // ---- End awesome slider region ----

                // set bac button
                App.execute('set:back', {
                    route: 'domain/' + id + '/challenges',
                    page: 'Challenges'
                });

                // make the custom menu for this challenge
                var menu = new View.ChallengeMenu({

                });
                layout.menuRegion.show(menu);

                // NOTE: without a model, you do not need itemview on the watch string
                menu.on('menu:clicked', function(item) {
                    layout.pageRegion.show(showViews[item]);
                });

                var fetchingChallenge = App.request('challenge:entity', id);

                var showViews = [];

                $.when(fetchingChallenge).done(function(challenge) {
                    if(id === 1) {
                        showViews.activities = new View.Draggable({
                            model: challenge
                        });
                    } else {
                        showViews.activities = new View.Sortable({
                            model: challenge
                        });
                    }

                    showViews.resources = new View.Resources({
                    });

                    showViews.stuff = new View.Stuff({
                    });

                    layout.pageRegion.show(showViews.activities);

                });

            }
        };
    });
    return App.Challenge.Show.Controller;
});<commit_msg>back button working<commit_after>'use strict';
define(['app', 'challenge_show_view', 'challenge_entity'], function(App, View) {
    App.module('Challenge.Show', function (Show, App, Backbone, Marionette, $) { // , _
        Show.Controller = {
            show: function(id) {
                var layout = new View.Layout();

                // ---- Make awesome slider region: ----
                var PageRegion = Backbone.Marionette.Region.extend({
                    el: '#show_page',
                });
                PageRegion.prototype.open = function(view) {
                    this.$el.hide();
                    this.$el.html(view.el);
                    this.$el.slideDown('fast');
                };
                layout.pageRegion = new PageRegion();
                App.mainRegion.show(layout);
                // ---- End awesome slider region ----

                // make the custom menu for this challenge
                var menu = new View.ChallengeMenu({

                });
                layout.menuRegion.show(menu);

                // NOTE: without a model, you do not need itemview on the watch string
                menu.on('menu:clicked', function(item) {
                    layout.pageRegion.show(showViews[item]);
                });

                var fetchingChallenge = App.request('challenge:entity', id);

                var showViews = [];

                $.when(fetchingChallenge).done(function(challenge) {

                    // set back button
                    App.execute('set:back', {
                        route: 'domain/' + challenge.get('domain') + '/challenges',
                        page: 'Challenges'
                    });

                    if(id === 1) {
                        showViews.activities = new View.Draggable({
                            model: challenge
                        });
                    } else {
                        showViews.activities = new View.Sortable({
                            model: challenge
                        });
                    }

                    showViews.resources = new View.Resources({
                    });

                    showViews.stuff = new View.Stuff({
                    });

                    layout.pageRegion.show(showViews.activities);

                });

            }
        };
    });
    return App.Challenge.Show.Controller;
});<|endoftext|>


<commit_before>function validateEmpty(fld,fldName) {
    var error = "";
    fld.value = fld.value.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    if (fld.value.length == 0) {
        error = org_wso2_carbon_registry_common_ui_jsi18n["the.required.field"] + " "+fldName+" " + org_wso2_carbon_registry_common_ui_jsi18n["not.filled"] + "
";
    } else {
//        fld.style.background = 'White';
    }
    return error;
}

function validateRegex(regexStr, fldEleArr, fldName) {
    var regex = new RegExp(regexStr);
    var actual = "";
    for (var i=0; i<fldEleArr.size(); ++i) {
        if (i != 0) {
            actual += ":";
        }
        var val = (!fldEleArr[i] ||  fldEleArr[i].value == null || fldEleArr[i].value == undefined)
            ? "" : fldEleArr[i].value;
        actual += val.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    }

    if (!regex.test(actual)) {
        return fldName + " " + org_wso2_carbon_registry_common_ui_jsi18n["invalid.regex"] + ": " +
            regexStr  + "
";
    } else {
        return "";
    }
}

function validateUrl(fld,fldName) {

	var error = "";
	var regx = RegExp("(http|https|ftp|file)://[^\\s]*?.*");
	if(!(fld.value.match(regx))){
		error = org_wso2_carbon_registry_common_ui_jsi18n["the"] + " "+fldName+" " + org_wso2_carbon_registry_common_ui_jsi18n["not.valid.url"] + "
";
	}

	return error;
}
function validateTextForIllegal(fld,fldName) {

    var illegalChars = /([?#^\|<>\"\'])/;
    var illegalCharsInput = /(\<[a-zA-Z0-9\s\/]*>)/;
    if (illegalChars.test(fld.value) || illegalCharsInput.test(fld.value)) {
       return false;
    } else {
       return true;
    }
}
function validateIllegal(fld,fldName){
    var error = "";
    //var illegalChars = /([^a-zA-Z0-9_\-\x2E\&\?\/\:\,\s\(\)\[\]])/;
    var illegalChars = /([~!@#;%^*+={}\|\\<>\"\',])/; // disallow ~!@#$;%^*+={}|\<>"',
    var illegalCharsInput = /(\<[a-zA-Z0-9\s\/]*>)/;
    if (illegalChars.test(fld.value) || illegalCharsInput.test(fld.value)) {
        error = org_wso2_carbon_registry_common_ui_jsi18n["the"] + " "+fldName+" " + org_wso2_carbon_registry_common_ui_jsi18n["contains.illegal.chars"] + "
";
    } else{
//        fld.style.background = 'White';
    }

   return error;
}
function validateIllegalNoPercent(fld,fldName){
    var error = "";
    //var illegalChars = /([^a-zA-Z0-9_\-\x2E\&\?\/\:\,\s\(\)\[\]])/;
    var illegalChars = /([~!@#;^*+={}\|\\<>\"\',])/; // disallow ~!@#$;%^*+={}|\<>"',
    var illegalCharsInput = /(\<[a-zA-Z0-9\s\/]*>)/;
    if (illegalChars.test(fld.value) || illegalCharsInput.test(fld.value)) {
        error = org_wso2_carbon_registry_common_ui_jsi18n["the"] + " "+fldName+" " + org_wso2_carbon_registry_common_ui_jsi18n["contains.illegal.chars"] + "
";
    } else{
//        fld.style.background = 'White';
    }

    return error;
}

function validateForInput(fld,fldName){
    var error = "";
    var illegalChars = /(\<[a-zA-Z0-9\s\/]*>)/; // match any starting tag

    if (illegalChars.test(fld.value)) {
        error = org_wso2_carbon_registry_common_ui_jsi18n["the"] + " "+fldName+" " + org_wso2_carbon_registry_common_ui_jsi18n["input.contains.illegal.chars"] + "
";
    } else{
//        fld.style.background = 'White';
    }
   return error;
}

function validateValueForInput(fldValue,fldName){
    var error = "";
    var illegalChars = /(\<[a-zA-Z0-9\s\/]*>)/; // match any starting tag

    if (illegalChars.test(fldValue)) {
        error = org_wso2_carbon_registry_common_ui_jsi18n["the"] + " " + fldName + " " + org_wso2_carbon_registry_common_ui_jsi18n["input.contains.illegal.chars"] + "
";
    }
   return error;
}

function validateToFromDate(from, to) {
    var error = "";
    if (Date.parse(from.value) > Date.parse(to.value)) {
        error = org_wso2_carbon_registry_common_ui_jsi18n["invalid.tofrom.date"];
    }
    return error;
}

function validateDate(fld,fldName){
    var error = "";
    var allowed= /^((0[1-9]|1[0-2])\/([0-2][0-9]|3[0-1])\/[1-2][0-9][0-9][0-9])$/;
    if (fld.value.length == 0 || allowed.test(fld.value)) {
//        fld.style.background = 'White';
    }
    else {
        error = org_wso2_carbon_registry_common_ui_jsi18n["the"] + " "+fldName+ " " + org_wso2_carbon_registry_common_ui_jsi18n["invalid.date"] + "
";
    }
    return error;
}
function validateUsername(fld) {

    //validates the user name against the given regex given in user-mgt.xml
    var error = "";
    var regexString = document.getElementById('userNameRegex');
    if(regexString != null && regexString.value != null){
        regexString = regexString.value;
    } else {
        regexString = '^[\\S]{3,30}$';
    }
    var regex = RegExp(regexString);
    if (fld.value == "") {
        error = org_wso2_carbon_registry_common_ui_jsi18n["no.username"] + "
";
    }  else if (!(fld.value.match(regex))) {
        error = org_wso2_carbon_registry_common_ui_jsi18n["illegal.username"] + "
";
    } else {
//        fld.style.background = 'White';
    }
    return error;
}

function validatePassword(fld) {
    var error = "";
    var illegalChars = /[\W_]/; // allow only letters and numbers

    if (fld.value == "") {
        error = org_wso2_carbon_registry_common_ui_jsi18n["no.password"] + "
";
    } else if ((fld.value.length < 3) || (fld.value.length > 15)) {
        error = org_wso2_carbon_registry_common_ui_jsi18n["wrong.password"] + "
";

    } else if (illegalChars.test(fld.value)) {
        error = org_wso2_carbon_registry_common_ui_jsi18n["illegal.password"] + "
";
    } /*else if (!((fld.value.search(/(a-z)+/)) && (fld.value.search(/(0-9)+/)))) {
        error = "The password must contain at least one numeral.
";
    } */else {
//        fld.style.background = 'White';
    }
   return error;
}

function trim(str)
{
  return str.replace(/^\s+|\s+$/, '');
}
function ltrim(str) {
	for(var k = 0; k < str.length && isWhitespace(str.charAt(k)); k++) {}
	return str.substring(k, str.length);
}
function isWhitespace(charToCheck) {
	var whitespaceChars = " \t\n\r\f";
	return (whitespaceChars.indexOf(charToCheck) != -1);
}

function validateEmail(fld) {
    var error="";
    var tfld = trim(fld.value);                        // value of field with whitespace trimmed off
    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\'\$\[\]]/ ;

    if (fld.value == "") {
        error = org_wso2_carbon_registry_common_ui_jsi18n["no.email"] + "
";
    } else if (!emailFilter.test(tfld)) {             //test email for illegal characters
        error = org_wso2_carbon_registry_common_ui_jsi18n["wrong.email"] + "
";
    } else if (fld.value.match(illegalChars)) {
        error = org_wso2_carbon_registry_common_ui_jsi18n["illegal.email"] + "
";
    } else {
//        fld.style.background = 'White';
    }
    return error;
}

function validateSimpleSearch() {
    // JS injection validation
    if (!validateTextForIllegal(document.forms["searchForm"]["criteria"], "resource path")) {
        CARBON.showWarningDialog(org_wso2_carbon_registry_common_ui_jsi18n["the"] +
        " " + "search content" + " " + org_wso2_carbon_registry_common_ui_jsi18n["contains.illegal.chars"]);
        return false;
    }

    var searchText = document.forms["searchForm"]["criteria"].value;
    if (searchText == null || searchText == "") {
        CARBON.showWarningDialog(org_wso2_carbon_registry_search_ui_jsi18n["validate.simple.search"]);
        return false;
    }
    document.forms['searchForm'].submit();
    return true;
}

function validateFilterName(fld, fldName) {

    var illegalChars = /\//; // do not allow slash
    var fnReason = "";

    fnReason += validateEmpty(fld, fldName);

    if (fnReason == "") {
        fnReason += validateForInput(fld, fldName);
    }
    if (fnReason == "") {
        fnReason += validateIllegal(fld, fldName);
    }
    if (fnReason == "" && illegalChars.test(fld.value)) {
        fnReason += org_wso2_carbon_registry_search_ui_jsi18n["filter.name.cannot.contain.slash"];
    }

    return fnReason;
}

function validatePropertyValues() {
    var leftVal = parseInt(document.getElementById('valueLeft').value);
    var rightVal = parseInt(document.getElementById('valueRight').value);

    if (leftVal != "" && rightVal != "") {
        if (leftVal >= rightVal) {
            return 0;
        }
    }
    return 1;
}

function validateEmptyPropertyValues() {

    var leftVal = document.getElementById('valueLeft').value;
    var rightVal = document.getElementById('valueRight').value;
    var opRight = document.getElementById('opRight');
    var propertyName = document.getElementById('#_propertyName').value;

    if (leftVal != "" || rightVal != "") {
        if (propertyName == "") {
            return 1;
        }
    }

    return 0;
}

function validateIllegalContentSearchString(fld, fldName) {
    var error = "";
    var illegalChars = /([~!@#$;%^*+{}\|\\<>\"\',\[\]\(\)])/; // disallow ~!@#$;%^*+={}|\<>"',[]()
    var illegalCharsInput = /(\<[a-zA-Z0-9\s\/]*>)/;
    if (illegalChars.test(fld.value) || illegalCharsInput.test(fld.value)) {
        error = org_wso2_carbon_registry_search_ui_jsi18n["the"] +
        " " + fldName + " " + org_wso2_carbon_registry_search_ui_jsi18n["contains.illegal.chars"] + "
";
    }

    return error;
}

function validateTagsInput(fld, fldName) {
    var error = "";
    var illegalChars = /(^,+$)/; // match any starting tag

    if (illegalChars.test(fld.value)) {
        error = org_wso2_carbon_registry_search_ui_jsi18n["the"] +
        " " + fldName + " " + org_wso2_carbon_registry_search_ui_jsi18n["contains.invalid.tag.search"] + "
";
    } else {
//        fld.style.background = 'White';
    }
    if (error != "") {
        return error;
    }

    return validateForInput(fld, fldName);
}

function validateIllegalSearchString(fld, fldName) {
    var error = "";
    var illegalChars = /([~!@#$;^*+{}\|\\<>\"\',\[\]\(\)])/;
    var illegalCharsInput = /(\<[a-zA-Z0-9\s\/]*>)/;
    if (illegalChars.test(fld.value) || illegalCharsInput.test(fld.value)) {
        error = org_wso2_carbon_registry_search_ui_jsi18n["the"] + " " + fldName + " " + org_wso2_carbon_registry_search_ui_jsi18n["contains.illegal.chars.second"] + "
";
    }

    return error;
}
<commit_msg>Removeing unwanted else statement<commit_after>function validateEmpty(fld,fldName) {
    var error = "";
    fld.value = fld.value.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    if (fld.value.length == 0) {
        error = org_wso2_carbon_registry_common_ui_jsi18n["the.required.field"] + " "+fldName+" " + org_wso2_carbon_registry_common_ui_jsi18n["not.filled"] + "
";
    } else {
//        fld.style.background = 'White';
    }
    return error;
}

function validateRegex(regexStr, fldEleArr, fldName) {
    var regex = new RegExp(regexStr);
    var actual = "";
    for (var i=0; i<fldEleArr.size(); ++i) {
        if (i != 0) {
            actual += ":";
        }
        var val = (!fldEleArr[i] ||  fldEleArr[i].value == null || fldEleArr[i].value == undefined)
            ? "" : fldEleArr[i].value;
        actual += val.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    }

    if (!regex.test(actual)) {
        return fldName + " " + org_wso2_carbon_registry_common_ui_jsi18n["invalid.regex"] + ": " +
            regexStr  + "
";
    } else {
        return "";
    }
}

function validateUrl(fld,fldName) {

	var error = "";
	var regx = RegExp("(http|https|ftp|file)://[^\\s]*?.*");
	if(!(fld.value.match(regx))){
		error = org_wso2_carbon_registry_common_ui_jsi18n["the"] + " "+fldName+" " + org_wso2_carbon_registry_common_ui_jsi18n["not.valid.url"] + "
";
	}

	return error;
}
function validateTextForIllegal(fld,fldName) {

    var illegalChars = /([?#^\|<>\"\'])/;
    var illegalCharsInput = /(\<[a-zA-Z0-9\s\/]*>)/;
    if (illegalChars.test(fld.value) || illegalCharsInput.test(fld.value)) {
       return false;
    } else {
       return true;
    }
}
function validateIllegal(fld,fldName){
    var error = "";
    //var illegalChars = /([^a-zA-Z0-9_\-\x2E\&\?\/\:\,\s\(\)\[\]])/;
    var illegalChars = /([~!@#;%^*+={}\|\\<>\"\',])/; // disallow ~!@#$;%^*+={}|\<>"',
    var illegalCharsInput = /(\<[a-zA-Z0-9\s\/]*>)/;
    if (illegalChars.test(fld.value) || illegalCharsInput.test(fld.value)) {
        error = org_wso2_carbon_registry_common_ui_jsi18n["the"] + " "+fldName+" " + org_wso2_carbon_registry_common_ui_jsi18n["contains.illegal.chars"] + "
";
    } else{
//        fld.style.background = 'White';
    }

   return error;
}
function validateIllegalNoPercent(fld,fldName){
    var error = "";
    //var illegalChars = /([^a-zA-Z0-9_\-\x2E\&\?\/\:\,\s\(\)\[\]])/;
    var illegalChars = /([~!@#;^*+={}\|\\<>\"\',])/; // disallow ~!@#$;%^*+={}|\<>"',
    var illegalCharsInput = /(\<[a-zA-Z0-9\s\/]*>)/;
    if (illegalChars.test(fld.value) || illegalCharsInput.test(fld.value)) {
        error = org_wso2_carbon_registry_common_ui_jsi18n["the"] + " "+fldName+" " + org_wso2_carbon_registry_common_ui_jsi18n["contains.illegal.chars"] + "
";
    } else{
//        fld.style.background = 'White';
    }

    return error;
}

function validateForInput(fld,fldName){
    var error = "";
    var illegalChars = /(\<[a-zA-Z0-9\s\/]*>)/; // match any starting tag

    if (illegalChars.test(fld.value)) {
        error = org_wso2_carbon_registry_common_ui_jsi18n["the"] + " "+fldName+" " + org_wso2_carbon_registry_common_ui_jsi18n["input.contains.illegal.chars"] + "
";
    } else{
//        fld.style.background = 'White';
    }
   return error;
}

function validateValueForInput(fldValue,fldName){
    var error = "";
    var illegalChars = /(\<[a-zA-Z0-9\s\/]*>)/; // match any starting tag

    if (illegalChars.test(fldValue)) {
        error = org_wso2_carbon_registry_common_ui_jsi18n["the"] + " " + fldName + " " + org_wso2_carbon_registry_common_ui_jsi18n["input.contains.illegal.chars"] + "
";
    }
   return error;
}

function validateToFromDate(from, to) {
    var error = "";
    if (Date.parse(from.value) > Date.parse(to.value)) {
        error = org_wso2_carbon_registry_common_ui_jsi18n["invalid.tofrom.date"];
    }
    return error;
}

function validateDate(fld,fldName){
    var error = "";
    var allowed= /^((0[1-9]|1[0-2])\/([0-2][0-9]|3[0-1])\/[1-2][0-9][0-9][0-9])$/;
    if (fld.value.length == 0 || allowed.test(fld.value)) {
//        fld.style.background = 'White';
    }
    else {
        error = org_wso2_carbon_registry_common_ui_jsi18n["the"] + " "+fldName+ " " + org_wso2_carbon_registry_common_ui_jsi18n["invalid.date"] + "
";
    }
    return error;
}
function validateUsername(fld) {

    //validates the user name against the given regex given in user-mgt.xml
    var error = "";
    var regexString = document.getElementById('userNameRegex');
    if(regexString != null && regexString.value != null){
        regexString = regexString.value;
    } else {
        regexString = '^[\\S]{3,30}$';
    }
    var regex = RegExp(regexString);
    if (fld.value == "") {
        error = org_wso2_carbon_registry_common_ui_jsi18n["no.username"] + "
";
    }  else if (!(fld.value.match(regex))) {
        error = org_wso2_carbon_registry_common_ui_jsi18n["illegal.username"] + "
";
    } else {
//        fld.style.background = 'White';
    }
    return error;
}

function validatePassword(fld) {
    var error = "";
    var illegalChars = /[\W_]/; // allow only letters and numbers

    if (fld.value == "") {
        error = org_wso2_carbon_registry_common_ui_jsi18n["no.password"] + "
";
    } else if ((fld.value.length < 3) || (fld.value.length > 15)) {
        error = org_wso2_carbon_registry_common_ui_jsi18n["wrong.password"] + "
";

    } else if (illegalChars.test(fld.value)) {
        error = org_wso2_carbon_registry_common_ui_jsi18n["illegal.password"] + "
";
    } /*else if (!((fld.value.search(/(a-z)+/)) && (fld.value.search(/(0-9)+/)))) {
        error = "The password must contain at least one numeral.
";
    } */else {
//        fld.style.background = 'White';
    }
   return error;
}

function trim(str)
{
  return str.replace(/^\s+|\s+$/, '');
}
function ltrim(str) {
	for(var k = 0; k < str.length && isWhitespace(str.charAt(k)); k++) {}
	return str.substring(k, str.length);
}
function isWhitespace(charToCheck) {
	var whitespaceChars = " \t\n\r\f";
	return (whitespaceChars.indexOf(charToCheck) != -1);
}

function validateEmail(fld) {
    var error="";
    var tfld = trim(fld.value);                        // value of field with whitespace trimmed off
    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\'\$\[\]]/ ;

    if (fld.value == "") {
        error = org_wso2_carbon_registry_common_ui_jsi18n["no.email"] + "
";
    } else if (!emailFilter.test(tfld)) {             //test email for illegal characters
        error = org_wso2_carbon_registry_common_ui_jsi18n["wrong.email"] + "
";
    } else if (fld.value.match(illegalChars)) {
        error = org_wso2_carbon_registry_common_ui_jsi18n["illegal.email"] + "
";
    } else {
//        fld.style.background = 'White';
    }
    return error;
}

function validateSimpleSearch() {
    // JS injection validation
    if (!validateTextForIllegal(document.forms["searchForm"]["criteria"], "resource path")) {
        CARBON.showWarningDialog(org_wso2_carbon_registry_common_ui_jsi18n["the"] +
        " " + "search content" + " " + org_wso2_carbon_registry_common_ui_jsi18n["contains.illegal.chars"]);
        return false;
    }

    var searchText = document.forms["searchForm"]["criteria"].value;
    if (searchText == null || searchText == "") {
        CARBON.showWarningDialog(org_wso2_carbon_registry_search_ui_jsi18n["validate.simple.search"]);
        return false;
    }
    document.forms['searchForm'].submit();
    return true;
}

function validateFilterName(fld, fldName) {

    var illegalChars = /\//; // do not allow slash
    var fnReason = "";

    fnReason += validateEmpty(fld, fldName);

    if (fnReason == "") {
        fnReason += validateForInput(fld, fldName);
    }
    if (fnReason == "") {
        fnReason += validateIllegal(fld, fldName);
    }
    if (fnReason == "" && illegalChars.test(fld.value)) {
        fnReason += org_wso2_carbon_registry_search_ui_jsi18n["filter.name.cannot.contain.slash"];
    }

    return fnReason;
}

function validatePropertyValues() {
    var leftVal = parseInt(document.getElementById('valueLeft').value);
    var rightVal = parseInt(document.getElementById('valueRight').value);

    if (leftVal != "" && rightVal != "") {
        if (leftVal >= rightVal) {
            return 0;
        }
    }
    return 1;
}

function validateEmptyPropertyValues() {

    var leftVal = document.getElementById('valueLeft').value;
    var rightVal = document.getElementById('valueRight').value;
    var opRight = document.getElementById('opRight');
    var propertyName = document.getElementById('#_propertyName').value;

    if (leftVal != "" || rightVal != "") {
        if (propertyName == "") {
            return 1;
        }
    }

    return 0;
}

function validateIllegalContentSearchString(fld, fldName) {
    var error = "";
    var illegalChars = /([~!@#$;%^*+{}\|\\<>\"\',\[\]\(\)])/; // disallow ~!@#$;%^*+={}|\<>"',[]()
    var illegalCharsInput = /(\<[a-zA-Z0-9\s\/]*>)/;
    if (illegalChars.test(fld.value) || illegalCharsInput.test(fld.value)) {
        error = org_wso2_carbon_registry_search_ui_jsi18n["the"] +
        " " + fldName + " " + org_wso2_carbon_registry_search_ui_jsi18n["contains.illegal.chars"] + "
";
    }

    return error;
}

function validateTagsInput(fld, fldName) {
    var error = "";
    var illegalChars = /(^,+$)/; // match any starting tag

    if (illegalChars.test(fld.value)) {
        error = org_wso2_carbon_registry_search_ui_jsi18n["the"] +
        " " + fldName + " " + org_wso2_carbon_registry_search_ui_jsi18n["contains.invalid.tag.search"] + "
";
    }
    if (error != "") {
        return error;
    }

    return validateForInput(fld, fldName);
}

function validateIllegalSearchString(fld, fldName) {
    var error = "";
    var illegalChars = /([~!@#$;^*+{}\|\\<>\"\',\[\]\(\)])/;
    var illegalCharsInput = /(\<[a-zA-Z0-9\s\/]*>)/;
    if (illegalChars.test(fld.value) || illegalCharsInput.test(fld.value)) {
        error = org_wso2_carbon_registry_search_ui_jsi18n["the"] + " " + fldName + " " + org_wso2_carbon_registry_search_ui_jsi18n["contains.illegal.chars.second"] + "
";
    }

    return error;
}
<|endoftext|>


<commit_before>"use strict";
/*global alert: true, ODSA, console */

(function ($) {
  var av;
  var code;
  var arr;

  function runit() {
    av = new JSAV($(".avcontainer"));
    MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}});
	$(".avcontainer").on("jsav-message", function() {
      // invoke MathJax to do conversion again
      MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
    });
	$(".avcontainer").on("jsav-updatecounter", function(){
      // invoke MathJax to do conversion again
      MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
    });
	code = av.code({url: "../../../SourceCode/Processing/Sorting/Insertionsort.pde",
                    lineNumbers: true,
                    startAfter: "/* *** ODSATag: Insertionsort *** */",
                    endBefore: "/* *** ODSAendTag: Insertionsort *** */", top: 225, left: 150});
	av.displayInit();

	av.umsg("When record $i$ is processed, the number of times through the inner for loop depends on how far out of order the record is");
	arr = av.ds.array(["0", "1", "...","i-1", "i","...", "n-1"], {"left":250, "top":20,"indexed":false});
	var rect = av.g.rect(271, 256, 480, 15).css({"fill": "green","opacity":0.3});
	arr.highlight(4);
	av.step();

	av.umsg("The inner for loop is executed once for each value greater than the value of record $i$ that appears in positions $0$ to $i-1$");
	arr.css([0,1,2,3],{"background-color":"#00FA9A"});
	av.step();

	av.umsg("To calculate the average cost, we want to determine what is the average number of inversions will be for the record in position $i$");
	rect.hide();
	av.step();

	av.umsg("This can be calculated as:");
	var eq1 = av.label("$$\\frac{\\displaystyle\\sum_{j=1}^{i}j}{i}$$",  {"top": "-30px", "left": "25px"}).css({'font-size': '14px', "text-align": "center"});
	av.step();

	av.umsg("And since this had to be done for the records from $1$ to $n-1$, then we have the total cost as:");
	eq1.hide();
	var eq2 = av.label("$$\\displaystyle\\sum_{i=1}^{n-1}\\frac{\\displaystyle\\sum_{j=1}^{i}j}{i}$$",  {"top": "-30px", "left": "25px"}).css({'font-size': '14px', "text-align": "center"});
	var label = av.label("|____________________|",  {"top": "85px", "left": "315px"}).css({'font-size': '20px', "text-align": "center"});
	rect = av.g.rect(263, 235, 170, 15).css({"fill": "green","opacity":0.3});
	arr.unhighlight(4);
	arr.css([0,1,2,3],{"background-color":"white"});
	av.step();
	av.umsg("This can be solved as:");
	av.label("$$=\\sum_{i=1}^{n-1}\\frac{i+1}{2}$$",
	{"top": "50px", "left": "20px"}).css({'font-size': '14px', "text-align": "center"});
	av.step();
	av.label("$$=\\frac{(n-1)(n+4)}{4}$$",
	{"top": "110px", "left": "20px"}).css({'font-size': '14px', "text-align": "center"});;
	av.step();
	av.umsg("Therefore, the average case running time of insertion sort is $\\theta(n^2)$");
	rect.hide();
	label.hide();
	av.recorded();
  }
  function about() {
    var mystring = "Insertion Sort Analysis\nWritten by Mohammed Fawzy and Cliff Shaffer\nCreated as part of the OpenDSA hypertextbook project.\nFor more information, see http://algoviz.org/OpenDSA\nWritten during February, 2014\nJSAV library version " + JSAV.version();
    alert(mystring);
  }

  // Connect action callbacks to the HTML entities
  $('#about').click(about);
  $('#runit').click(runit);
  $('#reset').click(ODSA.AV.reset);
}(jQuery));
<commit_msg>Aligning equations<commit_after>"use strict";
/*global alert: true, ODSA, console */

(function ($) {
  var av;
  var code;
  var arr;

  function runit() {
    av = new JSAV($(".avcontainer"));
    MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}});
	$(".avcontainer").on("jsav-message", function() {
      // invoke MathJax to do conversion again
      MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
    });
	$(".avcontainer").on("jsav-updatecounter", function(){
      // invoke MathJax to do conversion again
      MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
    });
	code = av.code({url: "../../../SourceCode/Processing/Sorting/Insertionsort.pde",
                    lineNumbers: true,
                    startAfter: "/* *** ODSATag: Insertionsort *** */",
                    endBefore: "/* *** ODSAendTag: Insertionsort *** */", top: 225, left: 150});

    //av.label("\\begin{eqnarray*} \\mathbf{T}(n) &=& \\mathbf{T}(n-(n-1)) + (n-(n-2)) + \\cdots + (n-1) +n \\\\ &=& 1 + 2 + \\cdots + (n-1) + n\\end{eqnarray*}",{"top": "-30px", "left": "15px"});
	av.displayInit();

	av.umsg("When record $i$ is processed, the number of times through the inner for loop depends on how far out of order the record is");
	arr = av.ds.array(["0", "1", "...","i-1", "i","...", "n-1"], {"left":300, "top":20,"indexed":false});
	var rect = av.g.rect(271, 256, 480, 15).css({"fill": "green","opacity":0.3});
	arr.highlight(4);
	av.step();

	av.umsg("The inner for loop is executed once for each value greater than the value of record $i$ that appears in positions $0$ to $i-1$");
	arr.css([0,1,2,3],{"background-color":"#00FA9A"});
	av.step();

	av.umsg("To calculate the average cost, we want to determine what is the average number of inversions will be for the record in position $i$");
	rect.hide();
	av.step();

	av.umsg("This can be calculated as:");
	var eq = av.label("$\\frac{\\displaystyle\\sum_{j=1}^{i}j}{i}$",  {"top": "-30px", "left": "15px"}).css({'font-size': '14px', "text-align": "left"});
	av.step();

	av.umsg("And since this had to be done for the records from $1$ to $n-1$, then we have the total cost as:");
	eq.text
("\\begin{eqnarray*}\\displaystyle\\sum_{i=1}^{n-1}\\frac{\\displaystyle\\sum_{j=1}^{i}j}{i} \\end{eqnarray*}");
	var label = av.label("|____________________|",  {"top": "85px", "left": "315px"}).css({'font-size': '20px', "text-align": "center"});
	rect = av.g.rect(263, 235, 170, 15).css({"fill": "green","opacity":0.3});
	arr.unhighlight(4);
	arr.css([0,1,2,3],{"background-color":"white"});
	av.step();
	av.umsg("This can be solved as:");
	var current_content = eq.text();
	var added_content = "&=&\\displaystyle\\sum_{i=1}^{n-1}\\frac{i+1}{2} \\\\";
	var new_content = insert_equation(current_content, added_content);
	eq.text(new_content);
	av.step();
	current_content = eq.text();
	added_content = "&=&\\frac{(n-1)(n+4)}{4}";
	new_content = insert_equation(current_content, added_content);
	eq.text(new_content);
	av.step();
	av.umsg("Therefore, the average case running time of insertion sort is $\\theta(n^2)$");
	rect.hide();
	label.hide();
	av.recorded();
  }
  function insert_equation(current, added){
    var new_equation;
    var end_index = current.indexOf("\\end{eqnarray*}");
	new_equation = current.substr(0, end_index)+ added + current.substr(end_index);
    return new_equation;
  }
  function about() {
    var mystring = "Insertion Sort Analysis\nWritten by Mohammed Fawzy and Cliff Shaffer\nCreated as part of the OpenDSA hypertextbook project.\nFor more information, see http://algoviz.org/OpenDSA\nWritten during February, 2014\nJSAV library version " + JSAV.version();
    alert(mystring);
  }

  // Connect action callbacks to the HTML entities
  $('#about').click(about);
  $('#runit').click(runit);
  $('#reset').click(ODSA.AV.reset);
}(jQuery));
<|endoftext|>