<commit_before>/*
 * Uses the following MIT-licensed library for computing the Voronoi diagram:
 *   https://github.com/gorhill/Javascript-Voronoi
 */

(function() {
  "use strict";

  // [min, max)
  function randInt(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
  }

  function randColor() {
    var r = 200;
    var g = randInt(50, 150);
    var b = 0;
    return "rgb(" + r + "," + g + "," + b + ")";
  }

  function point(x, y, angle) {
    return {
      "x": x,
      "y": y,
      "angle": angle
    };
  }

  function color(strokeStyle) {
    return {
      "strokeStyle": strokeStyle
    };
  }

  var ctx, bbox, points, colors;
  var previousTimestamp, delta;

  function render() {
    ctx.fillRect(0, 0, bbox.xr, bbox.yb);

    var voronoi = new Voronoi();
    var diagram = voronoi.compute(points, bbox);
    var cells = diagram.cells;

    for (var c = 0; c < cells.length; c++) {
      var edges = cells[c].halfedges;

      ctx.strokeStyle = colors[c].strokeStyle;

      ctx.beginPath();
      // closePath fills in last edge
      for (var e = 0; e < edges.length - 1; e++) {
        var edge = edges[e];
        var startpoint = edge.getStartpoint();
        var endpoint = edge.getEndpoint();

        if (e == 0) {
          ctx.moveTo(startpoint.x, startpoint.y);
        }
        ctx.lineTo(endpoint.x, endpoint.y);
      }
      ctx.closePath();

      ctx.stroke();
    }
  }

  var xSpeed = 10;
  var ySpeed = 10;
  function update(delta) {
    for (var p = 0; p < points.length; p++) {
      var angle = points[p].angle;
      var dx = Math.cos(angle) * xSpeed * delta;
      var dy = Math.sin(angle) * ySpeed * delta;
      points[p].x += dx;
      points[p].y += dy;
      points[p].angle += Math.random() - 0.5;
    }
  }

  function step(timestamp) {
    var delta = previousTimestamp ? (timestamp - previousTimestamp) / 1000 : 0;
    previousTimestamp = timestamp;

    update(delta);

    render();

    window.requestAnimationFrame(step);
  }

  window.onload = function () {
    var mainCanvas = document.getElementById("voronoi");
    mainCanvas.width = window.innerWidth;
    mainCanvas.height = window.innerHeight;

    bbox = {xl: -10, xr: mainCanvas.width + 10, yt: -10, yb: mainCanvas.height + 10};

    ctx = mainCanvas.getContext("2d");

    var grd = ctx.createLinearGradient(bbox.xr / 2, 0, bbox.xr / 2, bbox.yb);
    grd.addColorStop(0, "hsl(12, 100%, 50%)");
    grd.addColorStop(1, "hsl(12, 100%, 15%)");
    ctx.fillStyle = grd;
    ctx.lineWidth = 2;

    var N = 50;

    points = [];
    colors = [];
    for (var i = 0; i < N; i++) {
      var x = randInt(0, bbox.xr);
      var y = randInt(0, bbox.yb);
      var angle = 0;
      points.push(point(x, y, angle));

      var stroke = "rgba(0, 0, 0, 0.05)";
      colors.push(color(stroke));
    }

    window.requestAnimationFrame(step);
  }
})();
<commit_msg>Fix resizing bug for root page<commit_after>/*
 * Uses the following MIT-licensed library for computing the Voronoi diagram:
 *   https://github.com/gorhill/Javascript-Voronoi
 */

(function() {
  "use strict";

  // [min, max)
  function randInt(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
  }

  function randColor() {
    var r = 200;
    var g = randInt(50, 150);
    var b = 0;
    return "rgb(" + r + "," + g + "," + b + ")";
  }

  function point(x, y, angle) {
    return {
      "x": x,
      "y": y,
      "angle": angle
    };
  }

  function color(strokeStyle) {
    return {
      "strokeStyle": strokeStyle
    };
  }

  var mainCanvas, ctx, bbox, points, colors;
  var previousTimestamp, delta;

  function render() {
    ctx.fillRect(0, 0, bbox.xr, bbox.yb);

    var voronoi = new Voronoi();
    var diagram = voronoi.compute(points, bbox);
    var cells = diagram.cells;

    for (var c = 0; c < cells.length; c++) {
      var edges = cells[c].halfedges;

      ctx.strokeStyle = colors[c].strokeStyle;

      ctx.beginPath();
      // closePath fills in last edge
      for (var e = 0; e < edges.length - 1; e++) {
        var edge = edges[e];
        var startpoint = edge.getStartpoint();
        var endpoint = edge.getEndpoint();

        if (e == 0) {
          ctx.moveTo(startpoint.x, startpoint.y);
        }
        ctx.lineTo(endpoint.x, endpoint.y);
      }
      ctx.closePath();

      ctx.stroke();
    }
  }

  var xSpeed = 10;
  var ySpeed = 10;
  function update(delta) {
    for (var p = 0; p < points.length; p++) {
      var angle = points[p].angle;
      var dx = Math.cos(angle) * xSpeed * delta;
      var dy = Math.sin(angle) * ySpeed * delta;
      points[p].x += dx;
      points[p].y += dy;
      points[p].angle += Math.random() - 0.5;
    }
  }

  function step(timestamp) {
    var delta = previousTimestamp ? (timestamp - previousTimestamp) / 1000 : 0;
    previousTimestamp = timestamp;

    update(delta);

    render();

    window.requestAnimationFrame(step);
  }

  function setSizes() {
    mainCanvas.width = window.innerWidth;
    mainCanvas.height = window.innerHeight;

    bbox = {
      xl: -10,
      xr: mainCanvas.width + 10,
      yt: -10,
      yb: mainCanvas.height + 10
    };

    var grd = ctx.createLinearGradient(bbox.xr / 2, 0, bbox.xr / 2, bbox.yb);
    grd.addColorStop(0, "hsl(12, 100%, 50%)");
    grd.addColorStop(1, "hsl(12, 100%, 15%)");
    ctx.fillStyle = grd;
    ctx.lineWidth = 2;
  }

  function setPoints() {
    var N = 50;

    points = [];
    colors = [];
    for (var i = 0; i < N; i++) {
      var x = randInt(0, bbox.xr);
      var y = randInt(0, bbox.yb);
      var angle = 0;
      points.push(point(x, y, angle));

      var stroke = "rgba(0, 0, 0, 0.05)";
      colors.push(color(stroke));
    }
  }

  window.onload = function () {
    mainCanvas = document.getElementById("voronoi");
    ctx = mainCanvas.getContext("2d");

    var resizeTimer;
    window.onresize = function() {
      setSizes();

      // Only execute when finished resizing
      clearTimeout(resizeTimer);
      resizeTimer = window.setTimeout(function() {
        setPoints();
      }, 250);
    };

    setSizes();
    setPoints();

    window.requestAnimationFrame(step);
  }
})();
<|endoftext|>


<commit_before><commit_msg>Refactored the CombatAction to go through all combat phases.<commit_after><|endoftext|>


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

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

import Dropdown from '../Dropdown';
import TextField from '../TextField';
import List from '../List';
import DynamicRenderList from '../DynamicRenderList';
import Checkbox from '../Checkbox';
import Theme from '../Theme';

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

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

class DropdownSelect extends Component {

    static SelectMode = SelectMode;
    static Theme = Theme;
    static Position = Position;

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.state = {
            value: props.value,
            filter: '',
            popupVisible: false
        };

    }

    /**
     * public
     */
    startRipple = (e, props) => {
        this.refs.dropdown && this.refs.dropdown.startRipple(e, props);
    };

    /**
     * public
     */
    endRipple = () => {
        this.refs.dropdown && this.refs.dropdown.endRipple();
    };

    /**
     * public
     */
    triggerRipple = (e, props) => {
        this.refs.dropdown && this.refs.dropdown.triggerRipple(e, props);
    };

    /**
     * public
     */
    resetPopupPosition = () => {
        this.refs.dropdown && this.refs.dropdown.resetPosition();
    };

    /**
     * public
     */
    closePopup = () => {
        this.refs.dropdown && this.refs.dropdown.closePopup();
    };

    filterChangeHandler = filter => {
        this.setState({
            filter
        }, () => {
            const el = this.refs.dropdown;
            el && el.resetPopupPosition();
        });
    };

    filterData = (filter = this.state.filter, data = this.props.data) => {

        if (!filter) {
            return data;
        }

        const {displayField, isGrouped} = this.props,
            filterFunc = originData => originData.filter(item => typeof item === 'object' && !!item[displayField] ?
                item[displayField].toString().toUpperCase().includes(filter.toUpperCase())
                :
                item.toString().toUpperCase().includes(filter.toUpperCase()));

        if (isGrouped) {

            let result = Object.assign(data);

            for (let i = 0, len = result.length; i < len; i++) {
                let group = result[i];
                group.children = filterFunc(group.children);
                if (group.children.length < 1) {
                    result.splice(i, 1);
                    i--;
                }
            }

        }

        return filterFunc(data);

    };

    selectAllClickHandler = () => {

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

        if (!data) {
            return;
        }

        const isSelectAll = !value || (value && value.length < data.length),
            newValue = isSelectAll ? data : [];

        this.setState({
            value: newValue
        }, () => {
            this.changeHandler(newValue);
        });

    };

    itemClickHandler = (...args) => {

        const {autoClose, onItemClick} = this.props;

        if (autoClose) {
            this.closePopup();
        }

        onItemClick && onItemClick(...args);

    };

    changeHandler = value => {

        const {autoClose} = this.props;
        if (autoClose) {
            this.closePopup();
        }

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

        setTimeout(() => {
            this.refs.hiddenFilter && this.refs.hiddenFilter.focus();
        }, 1000);
    };

    popupOpenHandler = e => {

        const {isHiddenInputFilter, useFilter} = this.props;

        if (isHiddenInputFilter) {
            this.refs.hiddenFilter && this.refs.hiddenFilter.focus();
        } else if (useFilter) {
            this.refs.filter && this.refs.filter.focus();
        }

        this.setState({
            popupVisible: true
        }, () => {
            const {onOpenPopup} = this.props;
            onOpenPopup && onOpenPopup(e);
        });

    };

    popupCloseHandler = e => {

        this.refs.hiddenFilter && this.refs.hiddenFilter.blur();

        this.setState({
            popupVisible: false
        }, () => {
            const {onClosePopup} = this.props;
            onClosePopup && onClosePopup(e);
        });
    };

    hiddenFilterChangeHandle = e => {

        const {data, displayField, clearHiddenInputFilterInterval} = this.props;

        if (!data) {
            return;
        }

        let target = e.target,
            timer = setTimeout(() => {
                clearTimeout(timer);
                target.value = '';
            }, clearHiddenInputFilterInterval);

        let index = data.findIndex(item =>
            typeof item === 'object' ?
                item[displayField].toUpperCase().startsWith(target.value.toUpperCase())
                :
                item.toUpperCase().startsWith(target.value.toUpperCase())
        );

        this.scrollTo(this.refs.dropdownSelectListScroller, (index) * 40, 200);

    };

    scrollTo = (element, to, duration) => {

        if (!element) {
            return;
        }

        // jump to target if duration zero
        if (duration <= 0) {
            element.scrollTop = to;
            return;
        }

        const difference = to - element.scrollTop,
            perTick = difference / duration * 10;

        setTimeout(() => {
            element.scrollTop = element.scrollTop + perTick;
            if (element.scrollTop === to) return;
            this.scrollTo(element, to, duration - 10);
        }, 10);

    };

    getTriggerValue = () => {

        const {placeholder, triggerRenderer, renderer, valueField, displayField, selectMode} = this.props,
            {value} = this.state,
            isMultiSelect = selectMode === SelectMode.MULTI_SELECT;

        if (triggerRenderer) {
            return typeof triggerRenderer === 'function' ? triggerRenderer(value) : triggerRenderer;
        }

        if (!value) {
            return placeholder;
        }

        return isMultiSelect ?
            (
                value.length > 0 ?
                    value.length + ' selected'
                    :
                    placeholder
            )
            :
            (
                renderer ?
                    renderer(value)
                    :
                    Util.getTextByDisplayField(value, displayField, valueField)
            );

    };

    static getDerivedStateFromProps(props, state) {
        return {
            prevProps: props,
            value: ComponentUtil.getDerivedState(props, state, 'value')
        };
    }

    render() {

        const {

                className, triggerClassName, popupClassName, style, name, popupTheme, data, triggerRenderer,
                useDynamicRenderList, listHeight, itemHeight, scrollBuffer, renderer, selectMode,
                useFilter, filterIconCls, useSelectAll, selectAllText, valueField, displayField, descriptionField,
                popupChildren, isHiddenInputFilter, noMatchedMsg, radioUncheckedIconCls, radioCheckedIconCls,
                checkboxUncheckedIconCls, checkboxCheckedIconCls, checkboxIndeterminateIconCls,

                ...restProps

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

            isMultiSelect = selectMode === SelectMode.MULTI_SELECT,

            selectClassName = classNames('dropdown-select', {
                activated: popupVisible,
                [className]: className
            }),
            dropdownTriggerClassName = classNames({
                empty: !triggerRenderer && !value,
                [triggerClassName]: triggerClassName
            }),

            listData = this.filterData();

        return (

                {
                    name ?
                        <input type="hidden"
                               name={name}
                               value={Util.getValueByValueField(value, valueField, displayField)}/>
                        :
                        null
                }

                {
                    isHiddenInputFilter ?
                        <input ref="hiddenFilter"
                               className="hiddenFilter"
                               type="text"
                               onChange={this.hiddenFilterChangeHandle}/>
                        :
                        null
                }

                <Dropdown {...restProps}
                          ref="dropdown"
                          triggerClassName={dropdownTriggerClassName}
                          popupClassName={'dropdown-select-popup' + (popupClassName ? ' ' + popupClassName : '')}
                          popupTheme={popupTheme}
                          triggerValue={this.getTriggerValue()}
                          onOpenPopup={this.popupOpenHandler}
                          onClosePopup={this.popupCloseHandler}>

                        {
                            useFilter ?
                                <TextField ref="filter"
                                           className="dropdown-select-filter"
                                           value={filter}
                                           rightIconCls={filterIconCls}
                                           onChange={this.filterChangeHandler}/>
                                :
                                null
                        }

                        {
                            isMultiSelect && useSelectAll ?

                                    <Checkbox className="list-item-select"
                                              checked={data && value && value.length === data.length}
                                              indeterminate={data && value && value.length > 0 && value.length < data.length}
                                              uncheckedIconCls={checkboxUncheckedIconCls}
                                              checkedIconCls={checkboxCheckedIconCls}
                                              indeterminateIconCls={checkboxIndeterminateIconCls}/>
                                    {selectAllText}

                                :
                                null
                        }

 Event.wheelHandler(e, this.props)}>

                        {
                            useFilter ?

                                :
                                null
                        }

                        {
                            isMultiSelect && useSelectAll ?

                                :
                                null
                        }

                        {
                            listData.length < 1 ?

                                    {
                                        noMatchedMsg ?
                                            noMatchedMsg
                                            :

                                                No matched value.

                                    }

                                :
                                useDynamicRenderList ?
                                    <DynamicRenderList className="dropdown-select-list"
                                                       theme={popupTheme}
                                                       selectMode={selectMode}
                                                       data={listData}
                                                       value={value}
                                                       valueField={valueField}
                                                       displayField={displayField}
                                                       descriptionField={descriptionField}
                                                       listHeight={listHeight}
                                                       itemHeight={itemHeight}
                                                       scrollBuffer={scrollBuffer}
                                                       renderer={renderer}
                                                       radioUncheckedIconCls={radioUncheckedIconCls}
                                                       radioCheckedIconCls={radioCheckedIconCls}
                                                       checkboxUncheckedIconCls={checkboxUncheckedIconCls}
                                                       checkboxCheckedIconCls={checkboxCheckedIconCls}
                                                       checkboxIndeterminateIconCls={checkboxIndeterminateIconCls}
                                                       onItemClick={this.itemClickHandler}
                                                       onChange={this.changeHandler}/>
                                    :
                                    <List className="dropdown-select-list"
                                          theme={popupTheme}
                                          selectMode={selectMode}
                                          data={listData}
                                          value={value}
                                          valueField={valueField}
                                          displayField={displayField}
                                          descriptionField={descriptionField}
                                          renderer={renderer}
                                          radioUncheckedIconCls={radioUncheckedIconCls}
                                          radioCheckedIconCls={radioCheckedIconCls}
                                          checkboxUncheckedIconCls={checkboxUncheckedIconCls}
                                          checkboxCheckedIconCls={checkboxCheckedIconCls}
                                          checkboxIndeterminateIconCls={checkboxIndeterminateIconCls}
                                          onItemClick={this.itemClickHandler}
                                          onChange={this.changeHandler}/>
                        }

                    {popupChildren}

                </Dropdown>

        );

    }
}

DropdownSelect.propTypes = {

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

    /**
     * The CSS class name of the trigger element.
     */
    triggerClassName: PropTypes.string,

    /**
     * The class name of the popup element.
     */
    popupClassName: PropTypes.string,

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

    /**
     * Override the styles of the popup element.
     */
    popupStyle: PropTypes.object,

    /**
     * The theme.
     */
    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * The theme.
     */
    popupTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    position: PropTypes.oneOf(Util.enumerateValue(Position)),

    /**
     * The name of the dropDownSelect.
     */
    name: PropTypes.string,

    /**
     * The value of the dropDownSelect.
     */
    value: PropTypes.any,

    /**
     * The placeholder of the dropDownSelect.
     */
    placeholder: PropTypes.string,

    title: PropTypes.string,

    triggerRenderer: PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.func]),

    rightIconCls: PropTypes.string,

    /**
     * The options data.
     */
    data: PropTypes.oneOfType([

        // not grouped
        PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.shape({

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

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

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

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

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

            title: PropTypes.string,

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

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

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

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

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

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

            /**
             * Callback function fired when a list item touch-tapped.
             */
            onClick: PropTypes.func

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

        // grouped
        PropTypes.array

    ]).isRequired,

    /**
     * The invalid message of dropDownSelect.
     */
    invalidMsg: PropTypes.string,

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

    /**
     * The select mode of listItem.Can be normal,checkbox.
     */
    selectMode: PropTypes.oneOf(Util.enumerateValue(SelectMode)),

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

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

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

    /**
     * The message of the dropDownSelect.
     */
    infoMsg: PropTypes.string,

    /**
     * Use this function to format the options's text.
     */
    textFormat: PropTypes.func,

    /**
     * If true,the drop-down box automatically closed after selection.
     */
    autoClose: PropTypes.bool,

    /**
     * If true,the drop-down box will have search input.
     */
    useFilter: PropTypes.bool,

    filterIconCls: PropTypes.string,
    useSelectAll: PropTypes.bool,
    selectAllText: PropTypes.string,

    /**
     * The message of no matching option.
     */
    noMatchedMsg: PropTypes.string,

    shouldPreventContainerScroll: PropTypes.bool,

    popupChildren: PropTypes.any,

    useDynamicRenderList: PropTypes.bool,
    listHeight: PropTypes.number,
    itemHeight: PropTypes.number,
    scrollBuffer: PropTypes.number,

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

    renderer: PropTypes.func,

    /**
     * Callback function fired when the button is touch-tapped.
     */
    onItemClick: PropTypes.func,

    /**
     * Callback function fired when the popup is open.
     */
    onOpenPopup: PropTypes.func,

    /**
     * Callback function fired when the popup is close.
     */
    onClosePopup: PropTypes.func,

    /**
     * Callback function fired when a menu item is selected.
     */
    onChange: PropTypes.func,

    onWheel: PropTypes.func,
    onFocus: PropTypes.func,
    onBlur: PropTypes.func,
    onMouseOver: PropTypes.func,
    onMouseOut: PropTypes.func,
    isHiddenInputFilter: PropTypes.bool,
    clearHiddenInputFilterInterval: PropTypes.number

};

DropdownSelect.defaultProps = {

    theme: Theme.DEFAULT,
    popupTheme: Theme.DEFAULT,

    placeholder: 'Please select ...',
    rightIconCls: 'fas fa-angle-down',
    data: [],
    disabled: false,
    selectMode: SelectMode.SINGLE_SELECT,

    valueField: 'value',
    displayField: 'text',
    descriptionField: 'desc',

    autoClose: true,
    useFilter: false,
    filterIconCls: 'fas fa-search',
    useSelectAll: false,
    selectAllText: 'Select All',
    shouldPreventContainerScroll: true,
    useDynamicRenderList: false,
    isHiddenInputFilter: false,
    clearHiddenInputFilterInterval: 1000

};

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

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

import Dropdown from '../Dropdown';
import TextField from '../TextField';
import List from '../List';
import DynamicRenderList from '../DynamicRenderList';
import Checkbox from '../Checkbox';
import Theme from '../Theme';

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

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

class DropdownSelect extends Component {

    static SelectMode = SelectMode;
    static Theme = Theme;
    static Position = Position;

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.state = {
            value: props.value,
            filter: '',
            popupVisible: false
        };

    }

    /**
     * public
     */
    startRipple = (e, props) => {
        this.refs.dropdown && this.refs.dropdown.startRipple(e, props);
    };

    /**
     * public
     */
    endRipple = () => {
        this.refs.dropdown && this.refs.dropdown.endRipple();
    };

    /**
     * public
     */
    triggerRipple = (e, props) => {
        this.refs.dropdown && this.refs.dropdown.triggerRipple(e, props);
    };

    /**
     * public
     */
    resetPopupPosition = () => {
        this.refs.dropdown && this.refs.dropdown.resetPosition();
    };

    /**
     * public
     */
    openPopup = () => {
        this.refs.dropdown && this.refs.dropdown.openPopup();
    };

    /**
     * public
     */
    closePopup = () => {
        this.refs.dropdown && this.refs.dropdown.closePopup();
    };

    filterChangeHandler = filter => {
        this.setState({
            filter
        }, () => {
            const el = this.refs.dropdown;
            el && el.resetPopupPosition();
        });
    };

    filterData = (filter = this.state.filter, data = this.props.data) => {

        if (!filter) {
            return data;
        }

        const {displayField, isGrouped} = this.props,
            filterFunc = originData => originData.filter(item => typeof item === 'object' && !!item[displayField] ?
                item[displayField].toString().toUpperCase().includes(filter.toUpperCase())
                :
                item.toString().toUpperCase().includes(filter.toUpperCase()));

        if (isGrouped) {

            let result = Object.assign(data);

            for (let i = 0, len = result.length; i < len; i++) {
                let group = result[i];
                group.children = filterFunc(group.children);
                if (group.children.length < 1) {
                    result.splice(i, 1);
                    i--;
                }
            }

        }

        return filterFunc(data);

    };

    selectAllClickHandler = () => {

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

        if (!data) {
            return;
        }

        const isSelectAll = !value || (value && value.length < data.length),
            newValue = isSelectAll ? data : [];

        this.setState({
            value: newValue
        }, () => {
            this.changeHandler(newValue);
        });

    };

    itemClickHandler = (...args) => {

        const {autoClose, onItemClick} = this.props;

        if (autoClose) {
            this.closePopup();
        }

        onItemClick && onItemClick(...args);

    };

    changeHandler = value => {

        const {autoClose} = this.props;
        if (autoClose) {
            this.closePopup();
        }

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

        setTimeout(() => {
            this.refs.hiddenFilter && this.refs.hiddenFilter.focus();
        }, 1000);
    };

    popupOpenHandler = e => {

        const {isHiddenInputFilter, useFilter} = this.props;

        if (isHiddenInputFilter) {
            this.refs.hiddenFilter && this.refs.hiddenFilter.focus();
        } else if (useFilter) {
            this.refs.filter && this.refs.filter.focus();
        }

        this.setState({
            popupVisible: true
        }, () => {
            const {onOpenPopup} = this.props;
            onOpenPopup && onOpenPopup(e);
        });

    };

    popupCloseHandler = e => {

        this.refs.hiddenFilter && this.refs.hiddenFilter.blur();

        this.setState({
            popupVisible: false
        }, () => {
            const {onClosePopup} = this.props;
            onClosePopup && onClosePopup(e);
        });
    };

    hiddenFilterChangeHandle = e => {

        const {data, displayField, clearHiddenInputFilterInterval} = this.props;

        if (!data) {
            return;
        }

        let target = e.target,
            timer = setTimeout(() => {
                clearTimeout(timer);
                target.value = '';
            }, clearHiddenInputFilterInterval);

        let index = data.findIndex(item =>
            typeof item === 'object' ?
                item[displayField].toUpperCase().startsWith(target.value.toUpperCase())
                :
                item.toUpperCase().startsWith(target.value.toUpperCase())
        );

        this.scrollTo(this.refs.dropdownSelectListScroller, (index) * 40, 200);

    };

    scrollTo = (element, to, duration) => {

        if (!element) {
            return;
        }

        // jump to target if duration zero
        if (duration <= 0) {
            element.scrollTop = to;
            return;
        }

        const difference = to - element.scrollTop,
            perTick = difference / duration * 10;

        setTimeout(() => {
            element.scrollTop = element.scrollTop + perTick;
            if (element.scrollTop === to) return;
            this.scrollTo(element, to, duration - 10);
        }, 10);

    };

    getTriggerValue = () => {

        const {placeholder, triggerRenderer, renderer, valueField, displayField, selectMode} = this.props,
            {value} = this.state,
            isMultiSelect = selectMode === SelectMode.MULTI_SELECT;

        if (triggerRenderer) {
            return typeof triggerRenderer === 'function' ? triggerRenderer(value) : triggerRenderer;
        }

        if (!value) {
            return placeholder;
        }

        return isMultiSelect ?
            (
                value.length > 0 ?
                    value.length + ' selected'
                    :
                    placeholder
            )
            :
            (
                renderer ?
                    renderer(value)
                    :
                    Util.getTextByDisplayField(value, displayField, valueField)
            );

    };

    static getDerivedStateFromProps(props, state) {
        return {
            prevProps: props,
            value: ComponentUtil.getDerivedState(props, state, 'value')
        };
    }

    render() {

        const {

                className, triggerClassName, popupClassName, style, name, popupTheme, data, triggerRenderer,
                useDynamicRenderList, listHeight, itemHeight, scrollBuffer, renderer, selectMode,
                useFilter, filterIconCls, useSelectAll, selectAllText, valueField, displayField, descriptionField,
                popupChildren, isHiddenInputFilter, noMatchedMsg, radioUncheckedIconCls, radioCheckedIconCls,
                checkboxUncheckedIconCls, checkboxCheckedIconCls, checkboxIndeterminateIconCls,

                ...restProps

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

            isMultiSelect = selectMode === SelectMode.MULTI_SELECT,

            selectClassName = classNames('dropdown-select', {
                activated: popupVisible,
                [className]: className
            }),
            dropdownTriggerClassName = classNames({
                empty: !triggerRenderer && !value,
                [triggerClassName]: triggerClassName
            }),

            listData = this.filterData();

        return (

                {
                    name ?
                        <input type="hidden"
                               name={name}
                               value={Util.getValueByValueField(value, valueField, displayField)}/>
                        :
                        null
                }

                {
                    isHiddenInputFilter ?
                        <input ref="hiddenFilter"
                               className="hiddenFilter"
                               type="text"
                               onChange={this.hiddenFilterChangeHandle}/>
                        :
                        null
                }

                <Dropdown {...restProps}
                          ref="dropdown"
                          triggerClassName={dropdownTriggerClassName}
                          popupClassName={'dropdown-select-popup' + (popupClassName ? ' ' + popupClassName : '')}
                          popupTheme={popupTheme}
                          triggerValue={this.getTriggerValue()}
                          onOpenPopup={this.popupOpenHandler}
                          onClosePopup={this.popupCloseHandler}>

                        {
                            useFilter ?
                                <TextField ref="filter"
                                           className="dropdown-select-filter"
                                           value={filter}
                                           rightIconCls={filterIconCls}
                                           onChange={this.filterChangeHandler}/>
                                :
                                null
                        }

                        {
                            isMultiSelect && useSelectAll ?

                                    <Checkbox className="list-item-select"
                                              checked={data && value && value.length === data.length}
                                              indeterminate={data && value && value.length > 0 && value.length < data.length}
                                              uncheckedIconCls={checkboxUncheckedIconCls}
                                              checkedIconCls={checkboxCheckedIconCls}
                                              indeterminateIconCls={checkboxIndeterminateIconCls}/>
                                    {selectAllText}

                                :
                                null
                        }

 Event.wheelHandler(e, this.props)}>

                        {
                            useFilter ?

                                :
                                null
                        }

                        {
                            isMultiSelect && useSelectAll ?

                                :
                                null
                        }

                        {
                            listData.length < 1 ?

                                    {
                                        noMatchedMsg ?
                                            noMatchedMsg
                                            :

                                                No matched value.

                                    }

                                :
                                useDynamicRenderList ?
                                    <DynamicRenderList className="dropdown-select-list"
                                                       theme={popupTheme}
                                                       selectMode={selectMode}
                                                       data={listData}
                                                       value={value}
                                                       valueField={valueField}
                                                       displayField={displayField}
                                                       descriptionField={descriptionField}
                                                       listHeight={listHeight}
                                                       itemHeight={itemHeight}
                                                       scrollBuffer={scrollBuffer}
                                                       renderer={renderer}
                                                       radioUncheckedIconCls={radioUncheckedIconCls}
                                                       radioCheckedIconCls={radioCheckedIconCls}
                                                       checkboxUncheckedIconCls={checkboxUncheckedIconCls}
                                                       checkboxCheckedIconCls={checkboxCheckedIconCls}
                                                       checkboxIndeterminateIconCls={checkboxIndeterminateIconCls}
                                                       onItemClick={this.itemClickHandler}
                                                       onChange={this.changeHandler}/>
                                    :
                                    <List className="dropdown-select-list"
                                          theme={popupTheme}
                                          selectMode={selectMode}
                                          data={listData}
                                          value={value}
                                          valueField={valueField}
                                          displayField={displayField}
                                          descriptionField={descriptionField}
                                          renderer={renderer}
                                          radioUncheckedIconCls={radioUncheckedIconCls}
                                          radioCheckedIconCls={radioCheckedIconCls}
                                          checkboxUncheckedIconCls={checkboxUncheckedIconCls}
                                          checkboxCheckedIconCls={checkboxCheckedIconCls}
                                          checkboxIndeterminateIconCls={checkboxIndeterminateIconCls}
                                          onItemClick={this.itemClickHandler}
                                          onChange={this.changeHandler}/>
                        }

                    {popupChildren}

                </Dropdown>

        );

    }
}

DropdownSelect.propTypes = {

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

    /**
     * The CSS class name of the trigger element.
     */
    triggerClassName: PropTypes.string,

    /**
     * The class name of the popup element.
     */
    popupClassName: PropTypes.string,

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

    /**
     * Override the styles of the popup element.
     */
    popupStyle: PropTypes.object,

    /**
     * The theme.
     */
    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * The theme.
     */
    popupTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    position: PropTypes.oneOf(Util.enumerateValue(Position)),

    /**
     * The name of the dropDownSelect.
     */
    name: PropTypes.string,

    /**
     * The value of the dropDownSelect.
     */
    value: PropTypes.any,

    /**
     * The placeholder of the dropDownSelect.
     */
    placeholder: PropTypes.string,

    title: PropTypes.string,

    triggerRenderer: PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.func]),

    rightIconCls: PropTypes.string,

    /**
     * The options data.
     */
    data: PropTypes.oneOfType([

        // not grouped
        PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.shape({

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

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

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

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

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

            title: PropTypes.string,

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

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

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

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

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

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

            /**
             * Callback function fired when a list item touch-tapped.
             */
            onClick: PropTypes.func

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

        // grouped
        PropTypes.array

    ]).isRequired,

    /**
     * The invalid message of dropDownSelect.
     */
    invalidMsg: PropTypes.string,

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

    /**
     * The select mode of listItem.Can be normal,checkbox.
     */
    selectMode: PropTypes.oneOf(Util.enumerateValue(SelectMode)),

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

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

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

    /**
     * The message of the dropDownSelect.
     */
    infoMsg: PropTypes.string,

    /**
     * Use this function to format the options's text.
     */
    textFormat: PropTypes.func,

    /**
     * If true,the drop-down box automatically closed after selection.
     */
    autoClose: PropTypes.bool,

    /**
     * If true,the drop-down box will have search input.
     */
    useFilter: PropTypes.bool,

    filterIconCls: PropTypes.string,
    useSelectAll: PropTypes.bool,
    selectAllText: PropTypes.string,

    /**
     * The message of no matching option.
     */
    noMatchedMsg: PropTypes.string,

    shouldPreventContainerScroll: PropTypes.bool,

    popupChildren: PropTypes.any,

    useDynamicRenderList: PropTypes.bool,
    listHeight: PropTypes.number,
    itemHeight: PropTypes.number,
    scrollBuffer: PropTypes.number,

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

    renderer: PropTypes.func,

    /**
     * Callback function fired when the button is touch-tapped.
     */
    onItemClick: PropTypes.func,

    /**
     * Callback function fired when the popup is open.
     */
    onOpenPopup: PropTypes.func,

    /**
     * Callback function fired when the popup is close.
     */
    onClosePopup: PropTypes.func,

    /**
     * Callback function fired when a menu item is selected.
     */
    onChange: PropTypes.func,

    onWheel: PropTypes.func,
    onFocus: PropTypes.func,
    onBlur: PropTypes.func,
    onMouseOver: PropTypes.func,
    onMouseOut: PropTypes.func,
    isHiddenInputFilter: PropTypes.bool,
    clearHiddenInputFilterInterval: PropTypes.number

};

DropdownSelect.defaultProps = {

    theme: Theme.DEFAULT,
    popupTheme: Theme.DEFAULT,

    placeholder: 'Please select ...',
    rightIconCls: 'fas fa-angle-down',
    data: [],
    disabled: false,
    selectMode: SelectMode.SINGLE_SELECT,

    valueField: 'value',
    displayField: 'text',
    descriptionField: 'desc',

    autoClose: true,
    useFilter: false,
    filterIconCls: 'fas fa-search',
    useSelectAll: false,
    selectAllText: 'Select All',
    shouldPreventContainerScroll: true,
    useDynamicRenderList: false,
    isHiddenInputFilter: false,
    clearHiddenInputFilterInterval: 1000

};

export default DropdownSelect;<|endoftext|>


<commit_before>/**
 * @file: PoliceDog web performance script for client side
 * @author: zhangxiang
 * @updated: 2017.05.29 14:29
 */

(function(){
    let win = window;

    function addHandler(type, callback) {

        if(win.addEventListener) {

            win.addEventListener(type, callback);

        } else if(win.attachEvent) {

            win.addEventListener('on' + type, callback);
        } else {

            win['on' + type] = callback;
        }
    }

    var perf = (function(){
        var perf = null;

        perf = win.performance ? win.performance : (win.wekitPerformance ? win.webkitPerformance : win.msPerformance);

        return perf;
    })();

    var sourceInfo = (function() {
        if(!perf) {
            return null;
        }

        var entries = perf.getEntries();
        var javascriptNum = 0, cssNum = 0, imgNum = 0, javascriptTime = 0, cssTime = 0, imgTime = 0, QueryArr = [];

        entries.forEach(function(data, i){
            var name            = data.name;
            var initiatorType   = data.initiatorType;
            let DNSQuery        = data.domainLookupEnd - data.domainLookupStart;
            let connectTime     = data.connectEnd - data.connectStart;
            let duration        = data.duration;

            QueryArr.push({
                name: name,
                type: initiatorType,
                DNSQuery: DNSQuery,
                duration: duration,
                connectTime: connectTime
            });
        });

        return QueryArr;
    })();

    var loadInfo = (function(){
        if(!perf) {
            return null;
        }

        var report = {}, resource = perf.timing;
        /**
         * to count the DNS Query time
         */
        var DNSquery = resource.domainLookupEnd - resource.domainLookupStart;
        report['DNS Query'] = DNSquery;

        /**
         *to count the TCP connect time
         */
        var TCPconnect = resource.connectEnd - resource.connectStart;
        report['TCP Connect'] = TCPconnect;

        /**
         * to count the TTFB time
         */
        var TTFB = resource.responseStart - resource.navigationStart;
        report['TTFB'] = TTFB;

        /**
         * to count the response time
         */
        var responseTime = resource.responseEnd - resource.responseStart;
        report['Request Time'] = responseTime;

        /**
         * to count white screen time
         */
        var whiteTime = resource.responseStart - resource.navigationStart;
        report['WhiteScreen Time'] = whiteTime;

        /**
         * to count analysis DOM time
         */
        var DOMAnalysis = resource.domContentLoadedEventEnd - resource.navigationStart;
        report['DOM Analysis'] = DOMAnalysis;

        /**
         * to count load time
         */
        var loadTime = resource.loadEventEnd - resource.navigationStart;
        report['Load Time'] = loadTime;

        return report;
    })();

    win.webPerf = {
        perf: perf,
        sourceInfo: sourceInfo,
        loadInfo: loadInfo,
        minimize: function(){

            var sourceInfo = this.sourceInfo, loadInfo = this.loadInfo, data = null;

            Object.keys(loadInfo).map(function(key, val){

                if(val === 0) {
                    delete this[key];
                }
            });

            data = {
                userAgent: navigator.userAgent,
                sourceInfo: sourceInfo,
                loadInfo: loadInfo
            }

            return data;
        }
    };

    /**
     * send data
     */
     addHandler('loaded', function(){

        var scripts         = document.getElementsByTagName('script');
        var thisScriptSrc   = scripts[scripts.length - 1].src;
        var pid             = thisScriptSrc.slice(thisScriptSrc.indexOf('?') + 1).split('=')[1];

        var currentURL      = window.location.href;

        var perfData        = webPerf.minimize();
        perfData.pid        = pid;
        perfData.currentURL = currentURL;
        perfData.timestamp  = new Date().getTime();

        var url = '', query = '?' + JSON.stringify(perfData);

        (new Image()).src = url + query;
     });
})();<commit_msg>add var<commit_after>/**
 * @file: PoliceDog web performance script for client side
 * @author: zhangxiang
 * @updated: 2017.05.29 14:29
 */

(function(){
    var win = window;

    function addHandler(type, callback) {

        if(win.addEventListener) {

            win.addEventListener(type, callback);

        } else if(win.attachEvent) {

            win.addEventListener('on' + type, callback);
        } else {

            win['on' + type] = callback;
        }
    }

    var perf = (function(){
        var perf = null;

        perf = win.performance ? win.performance : (win.wekitPerformance ? win.webkitPerformance : win.msPerformance);

        return perf;
    })();

    var sourceInfo = (function() {
        if(!perf) {
            return null;
        }

        var entries = perf.getEntries();
        var javascriptNum = 0, cssNum = 0, imgNum = 0, javascriptTime = 0, cssTime = 0, imgTime = 0, QueryArr = [];

        entries.forEach(function(data, i){
            var name            = data.name;
            var initiatorType   = data.initiatorType;
            let DNSQuery        = data.domainLookupEnd - data.domainLookupStart;
            let connectTime     = data.connectEnd - data.connectStart;
            let duration        = data.duration;

            QueryArr.push({
                name: name,
                type: initiatorType,
                DNSQuery: DNSQuery,
                duration: duration,
                connectTime: connectTime
            });
        });

        return QueryArr;
    })();

    var loadInfo = (function(){
        if(!perf) {
            return null;
        }

        var report = {}, resource = perf.timing;
        /**
         * to count the DNS Query time
         */
        var DNSquery = resource.domainLookupEnd - resource.domainLookupStart;
        report['DNS Query'] = DNSquery;

        /**
         *to count the TCP connect time
         */
        var TCPconnect = resource.connectEnd - resource.connectStart;
        report['TCP Connect'] = TCPconnect;

        /**
         * to count the TTFB time
         */
        var TTFB = resource.responseStart - resource.navigationStart;
        report['TTFB'] = TTFB;

        /**
         * to count the response time
         */
        var responseTime = resource.responseEnd - resource.responseStart;
        report['Request Time'] = responseTime;

        /**
         * to count white screen time
         */
        var whiteTime = resource.responseStart - resource.navigationStart;
        report['WhiteScreen Time'] = whiteTime;

        /**
         * to count analysis DOM time
         */
        var DOMAnalysis = resource.domContentLoadedEventEnd - resource.navigationStart;
        report['DOM Analysis'] = DOMAnalysis;

        /**
         * to count load time
         */
        var loadTime = resource.loadEventEnd - resource.navigationStart;
        report['Load Time'] = loadTime;

        return report;
    })();

    win.webPerf = {
        perf: perf,
        sourceInfo: sourceInfo,
        loadInfo: loadInfo,
        minimize: function(){

            var sourceInfo = this.sourceInfo, loadInfo = this.loadInfo, data = null;

            Object.keys(loadInfo).map(function(key, val){

                if(val === 0) {
                    delete this[key];
                }
            });

            data = {
                userAgent: navigator.userAgent,
                sourceInfo: sourceInfo,
                loadInfo: loadInfo
            }

            return data;
        }
    };

    /**
     * send data
     */
     addHandler('loaded', function(){

        var scripts         = document.getElementsByTagName('script');
        var thisScriptSrc   = scripts[scripts.length - 1].src;
        var pid             = thisScriptSrc.slice(thisScriptSrc.indexOf('?') + 1).split('=')[1];

        var currentURL      = window.location.href;

        var perfData        = webPerf.minimize();
        perfData.pid        = pid;
        perfData.currentURL = currentURL;
        perfData.timestamp  = new Date().getTime();

        var url = '', query = '?' + JSON.stringify(perfData);

        (new Image()).src = url + query;
     });
})();<|endoftext|>


<commit_before>(function () {
    "use strict";

    function ScriptsEditController($scope, $routeParams, $timeout, appState, editorState, navigationService, assetsService, codefileResource, contentEditingHelper, notificationsService, localizationService) {

        var vm = this;
        var currentPosition = null;
        var localizeSaving = localizationService.localize("general_saving");

        vm.page = {};
        vm.page.loading = true;
        vm.page.menu = {};
        vm.page.menu.currentSection = appState.getSectionState("currentSection");
        vm.page.menu.currentNode = null;
        vm.page.saveButtonState = "init";

        vm.script = {};

        // bind functions to view model
        vm.save = save;

        /* Function bound to view model */

        function save() {

            vm.page.saveButtonState = "busy";

            vm.script.content = vm.editor.getValue();

            contentEditingHelper.contentEditorPerformSave({
                statusMessage: localizeSaving,
                saveMethod: codefileResource.save,
                scope: $scope,
                content: vm.script,
                // We do not redirect on failure for scripts - this is because it is not possible to actually save the script
                // when server side validation fails - as opposed to content where we are capable of saving the content
                // item if server side validation fails
                redirectOnFailure: false,
                rebindCallback: function (orignal, saved) {}
            }).then(function (saved) {

                localizationService.localize("speechBubbles_scriptSavedHeader").then(function (headerValue) {
                    localizationService.localize("speechBubbles_scriptSavedText").then(function(msgValue) {
                        notificationsService.success(headerValue, msgValue);
                    });
                });

                vm.page.saveButtonState = "success";
                vm.script = saved;

                //sync state
                editorState.set(vm.script);

                // sync tree
                navigationService.syncTree({ tree: "scripts", path: vm.script.virtualPath, forceReload: true }).then(function (syncArgs) {
                    vm.page.menu.currentNode = syncArgs.node;
                });

            }, function (err) {

                vm.page.saveButtonState = "error";

                localizationService.localize("speechBubbles_validationFailedHeader").then(function (headerValue) {
                    localizationService.localize("speechBubbles_validationFailedMessage").then(function(msgValue) {
                        notificationsService.error(headerValue, msgValue);
                    });
                });

            });

        }

        /* Local functions */

        function init() {

            //we need to load this somewhere, for now its here.
            assetsService.loadCss("lib/ace-razor-mode/theme/razor_chrome.css");

            if ($routeParams.create) {
                codefileResource.getScaffold().then(function (script) {
                    ready(script);
                });
            } else {
                codefileResource.getByPath('scripts', $routeParams.id).then(function (script) {
                    ready(script);
                });
            }

        }

        function ready(script) {

            vm.page.loading = false;

            vm.script = script;

            //sync state
            editorState.set(vm.script);

            navigationService.syncTree({ tree: "scripts", path: vm.script.virtualPath, forceReload: true }).then(function (syncArgs) {
                vm.page.menu.currentNode = syncArgs.node;
            });

            vm.aceOption = {
                mode: "javascript",
                theme: "chrome",
                showPrintMargin: false,
                advanced: {
                    fontSize: '14px'
                },
                onLoad: function(_editor) {

                    vm.editor = _editor;

                    // initial cursor placement
                    // Keep cursor in name field if we are create a new script
                    // else set the cursor at the bottom of the code editor
                    if(!$routeParams.create) {
                        $timeout(function(){
                            vm.editor.navigateFileEnd();
                            vm.editor.focus();
                        });
                    }

            	}
            }

        }

        init();

    }

    angular.module("umbraco").controller("Umbraco.Editors.Scripts.EditController", ScriptsEditController);
})();<commit_msg>Changed key for saving scripts - as it mentioned 'script view' Whats that?! So changed to more generic file<commit_after>(function () {
    "use strict";

    function ScriptsEditController($scope, $routeParams, $timeout, appState, editorState, navigationService, assetsService, codefileResource, contentEditingHelper, notificationsService, localizationService) {

        var vm = this;
        var currentPosition = null;
        var localizeSaving = localizationService.localize("general_saving");

        vm.page = {};
        vm.page.loading = true;
        vm.page.menu = {};
        vm.page.menu.currentSection = appState.getSectionState("currentSection");
        vm.page.menu.currentNode = null;
        vm.page.saveButtonState = "init";

        vm.script = {};

        // bind functions to view model
        vm.save = save;

        /* Function bound to view model */

        function save() {

            vm.page.saveButtonState = "busy";

            vm.script.content = vm.editor.getValue();

            contentEditingHelper.contentEditorPerformSave({
                statusMessage: localizeSaving,
                saveMethod: codefileResource.save,
                scope: $scope,
                content: vm.script,
                // We do not redirect on failure for scripts - this is because it is not possible to actually save the script
                // when server side validation fails - as opposed to content where we are capable of saving the content
                // item if server side validation fails
                redirectOnFailure: false,
                rebindCallback: function (orignal, saved) {}
            }).then(function (saved) {

                localizationService.localize("speechBubbles_fileSavedHeader").then(function (headerValue) {
                    localizationService.localize("speechBubbles_fileSavedText").then(function(msgValue) {
                        notificationsService.success(headerValue, msgValue);
                    });
                });

                vm.page.saveButtonState = "success";
                vm.script = saved;

                //sync state
                editorState.set(vm.script);

                // sync tree
                navigationService.syncTree({ tree: "scripts", path: vm.script.virtualPath, forceReload: true }).then(function (syncArgs) {
                    vm.page.menu.currentNode = syncArgs.node;
                });

            }, function (err) {

                vm.page.saveButtonState = "error";

                localizationService.localize("speechBubbles_validationFailedHeader").then(function (headerValue) {
                    localizationService.localize("speechBubbles_validationFailedMessage").then(function(msgValue) {
                        notificationsService.error(headerValue, msgValue);
                    });
                });

            });

        }

        /* Local functions */

        function init() {

            //we need to load this somewhere, for now its here.
            assetsService.loadCss("lib/ace-razor-mode/theme/razor_chrome.css");

            if ($routeParams.create) {
                codefileResource.getScaffold().then(function (script) {
                    ready(script);
                });
            } else {
                codefileResource.getByPath('scripts', $routeParams.id).then(function (script) {
                    ready(script);
                });
            }

        }

        function ready(script) {

            vm.page.loading = false;

            vm.script = script;

            //sync state
            editorState.set(vm.script);

            navigationService.syncTree({ tree: "scripts", path: vm.script.virtualPath, forceReload: true }).then(function (syncArgs) {
                vm.page.menu.currentNode = syncArgs.node;
            });

            vm.aceOption = {
                mode: "javascript",
                theme: "chrome",
                showPrintMargin: false,
                advanced: {
                    fontSize: '14px'
                },
                onLoad: function(_editor) {

                    vm.editor = _editor;

                    // initial cursor placement
                    // Keep cursor in name field if we are create a new script
                    // else set the cursor at the bottom of the code editor
                    if(!$routeParams.create) {
                        $timeout(function(){
                            vm.editor.navigateFileEnd();
                            vm.editor.focus();
                        });
                    }

            	}
            }

        }

        init();

    }

    angular.module("umbraco").controller("Umbraco.Editors.Scripts.EditController", ScriptsEditController);
})();<|endoftext|>


<commit_before>//==============================================================================
function Point(x,y) {
    this.x  = x || 0;
    this.y = y || 0;
}
//==============================================================================

/**
 * storage class for animation data
 */
function Animation(framemap, framenumb, cols, rows, framewidth, frameheight, bordersize, initialFrame ) {
    this._currentframe = initialFrame || 0;
    this._frames = [];
    this._framemap = framemap;
    this._framewidth = framewidth;
    this._frameheight = frameheight;
    this._borderwidth = bordersize;

    /**
     * currently oscillates, can be changed to provide custom frame updating
     * on a per AnimatedSprite basis
     */
    this._frameupdate= function() {

	this._currentframe += 1;
	if( this._currentframe >= this._frames.length ) { this._currentframe = -(this._currentframe-1); }

    }

    this.initFrames = function(framenumb) {
	    var i = 0;
	    var done = false;
	    var top = new Point(0,0);

	    for (var row  = 0; row < rows && !done; row++) {
		for (var col = 0; col < cols && !done; col++) {
		    top = new Point( col * (frameheight+1)+(col+1)*bordersize, row * (framewidth+1) +(row+1)* bordersize);
		    console.log(col*frameheight,(col+1)*bordersize);
		    this._frames.push ( top );
		    i+=1;
		    if( i >= framenumb ) { done = true; }
		}
	    }
    }
    this.initFrames( framenumb );

    this.draw = function(ctx, dx, dy, dWidth, dHeight) {
	//absolute value of current frame index is used, allowing for negative frame counts
	var curframe = this._currentframe<0? -1 * this._currentframe : this._currentframe;
	var frametop = this._frames[curframe];
	Pender.ctx.drawImage( this._framemap, frametop.x, frametop.y, this._framewidth, this._frameheight, dx, dy, this._framewidth, this._frameheight   );
	this._frameupdate();
    }
}

function AnimatedSprite(anim) {

    this._animation = anim;

    this.init = function (framemap, framenumb, cols, rows, framewidth, frameheight) {
	var i = 0;
	var done = false;
	var top = new Point(0,0);

	//initialize
	this._framemap = framemap;
	this._framewidth = framewidth;
	this._frameheight = frameheight;
	/*
	for (var row  = 0; row < rows && !done; row++) {
	    for (var col = 0; col < cols && !done; col++) {
		i+=1;
		if( i >= framenumb ) { done = true; }
		var top = new Point(col * frameheight+col+1, row * framewidth+row+1);
		var bot = new Point(top.x + frameheight, top.y + framewidth);

		this._frames.push ( [top,bot] );
	    }
	}*/
	this._frames;

    }

}

//==============================================================================

function Cat() {

    this.frame = 0;

    //this.xspeed = 0.01 * Math.floor(Math.random()*5);
    //this.yspeed = 0.01 * Math.floor(Math.random()*5);

    this.xpos = 50;
    this.ypos = 50;

    //this.rotation = 0.0;

    //this.scalefactor = 0.5;

    this.drawme = function () {

        if (this.frame > 10) { this.frame = 0; }

    //    this.xpos += this.xspeed;
    //    this.ypos += this.yspeed;
    //    if (this.xpos < -1.0 || this.xpos > 1.0) {
    //        this.xspeed *= -1;
    //    }
    //    if (this.ypos < -1.0 || this.ypos > 1.0) {
    //        this.yspeed *= -1;
    //    }

        this.frame += 1;
      //  Canvas.scale(0.5, 0.5);
        Canvas.translate(10,10);
        Canvas.translate(this.xpos, this.ypos);
        Canvas.drawImage(this.frame, 0, 0);

    };

}

//==============================================================================

//==============================================================================

//==============================================================================
function init() {
    console.log("loading images");

    var i = Pender.loadImage( "client/assets/build_bot_map.png" );

    console.log(i);
   // var i = Pender.loadImage( "client/assets/build_bot_map.png" );
    //console.log(Pender);
}

function draw() {

}<commit_msg>testing drawImage<commit_after>//==============================================================================
function Point(x,y) {
    this.x  = x || 0;
    this.y = y || 0;
}
//==============================================================================

/**
 * storage class for animation data
 */
function Animation(framemap, framenumb, cols, rows, framewidth, frameheight, bordersize, initialFrame ) {
    this._currentframe = initialFrame || 0;
    this._frames = [];
    this._framemap = framemap;
    this._framewidth = framewidth;
    this._frameheight = frameheight;
    this._borderwidth = bordersize;

    /**
     * currently oscillates, can be changed to provide custom frame updating
     * on a per AnimatedSprite basis
     */
    this._frameupdate= function() {

	this._currentframe += 1;
	if( this._currentframe >= this._frames.length ) { this._currentframe = -(this._currentframe-1); }

    }

    this.initFrames = function(framenumb) {
	    var i = 0;
	    var done = false;
	    var top = new Point(0,0);

	    for (var row  = 0; row < rows && !done; row++) {
		for (var col = 0; col < cols && !done; col++) {
		    top = new Point( col * (frameheight+1)+(col+1)*bordersize, row * (framewidth+1) +(row+1)* bordersize);
		    console.log(col*frameheight,(col+1)*bordersize);
		    this._frames.push ( top );
		    i+=1;
		    if( i >= framenumb ) { done = true; }
		}
	    }
    }
    this.initFrames( framenumb );

    this.draw = function(ctx, dx, dy, dWidth, dHeight) {
	//absolute value of current frame index is used, allowing for negative frame counts
	var curframe = this._currentframe<0? -1 * this._currentframe : this._currentframe;
	var frametop = this._frames[curframe];
	Pender.ctx.drawImage( this._framemap, frametop.x, frametop.y, this._framewidth, this._frameheight, dx, dy, this._framewidth, this._frameheight   );
	this._frameupdate();
    }
}

function AnimatedSprite(anim) {

    this._animation = anim;

    this.init = function (framemap, framenumb, cols, rows, framewidth, frameheight) {
	var i = 0;
	var done = false;
	var top = new Point(0,0);

	//initialize
	this._framemap = framemap;
	this._framewidth = framewidth;
	this._frameheight = frameheight;
	/*
	for (var row  = 0; row < rows && !done; row++) {
	    for (var col = 0; col < cols && !done; col++) {
		i+=1;
		if( i >= framenumb ) { done = true; }
		var top = new Point(col * frameheight+col+1, row * framewidth+row+1);
		var bot = new Point(top.x + frameheight, top.y + framewidth);

		this._frames.push ( [top,bot] );
	    }
	}*/
	this._frames;

    }

}

//==============================================================================

function Cat() {

    this.frame = 0;

    //this.xspeed = 0.01 * Math.floor(Math.random()*5);
    //this.yspeed = 0.01 * Math.floor(Math.random()*5);

    this.xpos = 50;
    this.ypos = 50;

    //this.rotation = 0.0;

    //this.scalefactor = 0.5;

    this.drawme = function () {

        if (this.frame > 10) { this.frame = 0; }

    //    this.xpos += this.xspeed;
    //    this.ypos += this.yspeed;
    //    if (this.xpos < -1.0 || this.xpos > 1.0) {
    //        this.xspeed *= -1;
    //    }
    //    if (this.ypos < -1.0 || this.ypos > 1.0) {
    //        this.yspeed *= -1;
    //    }

        this.frame += 1;
      //  Canvas.scale(0.5, 0.5);
        Canvas.translate(10,10);
        Canvas.translate(this.xpos, this.ypos);
        Canvas.drawImage(this.frame, 0, 0);

    };

}

//==============================================================================

//==============================================================================

//==============================================================================
function init() {
    console.log("loading images");

    var i = Pender.loadImage( "client/assets/build_bot_map.png" );

    console.log(i);
   // var i = Pender.loadImage( "client/assets/build_bot_map.png" );
    //console.log(Pender);
}

function draw() {

}<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Document, Page } from 'react-pdf/dist/entry.webpack';
import Navbar from './navbar';

class Loader extends Component {
    render () {
        return (
LOAD
)
    }
}

export default class App extends Component {
  state = {
    numPages: null,
    pageNumber: 1,
    view_more: 1,
    zoomlevel: 1.2
  }

  onDocumentLoad = ({ numPages }) => {
    this.setState({ numPages });
  }

  onDocumentFail() {
    return (

Une erreur est survenue, souhaitez-vous

             télécharger

      le document ?
)
  }

  view_more() {
    this.setState({view_more: this.state.view_more + 1})
  }

  zoomin(){
    this.setState({zoomlevel: this.state.zoomlevel + 0.1})
  }

  zoomout(){
    this.setState({zoomlevel: this.state.zoomlevel - 0.1})
  }

  render() {
    const { pageNumber, numPages, view_more, zoomlevel} = this.state;

    const renderPages = Math.min(5 * view_more, numPages);

    var render_not_full = ""
    if (renderPages < numPages) {
        render_not_full = (
            <button className="viewer-show-more btn" onClick={this.view_more.bind(this)}>
                Ce document à {numPages - renderPages} pages supplémentaires. Cliquez ici pour la suite.
            </button>
        );
    }

    var document_data = document.getElementById('document_data').dataset

    return (

        <Navbar zoomin={this.zoomin.bind(this)}
                zoomout={this.zoomout.bind(this)}
                docname={document_data.name}
                docid={document_data.id}
                course_name={document_data.coursename}
                original={document_data.original}
                pdf={document_data.pdf}
                has_perm={document_data.hasperm}
        />
        <Document
          className="viewer-document"
          file={document_data.url}
          loading={<Loader />}
          onLoadSuccess={this.onDocumentLoad}
          error={this.onDocumentFail()}
        >
            {
            Array.from(
              new Array(renderPages),
              (el, index) => (
                <Page
                  key={`page_${index + 1}`}
                  pageNumber={index + 1}
                  renderTextLayer={false}
                  scale={zoomlevel}
                />

              ),
            )
            }
        </Document>
        {render_not_full}

    );
  }
}
<commit_msg>Viewer errors<commit_after>import React, { Component } from 'react';
import { Document, Page } from 'react-pdf/dist/entry.webpack';
import Navbar from './navbar';

class Loader extends Component {
    render () {
        return (

Chargement en cours...
)
    }
}

export default class App extends Component {
  state = {
    numPages: null,
    pageNumber: 1,
    view_more: 1,
    zoomlevel: 1.2
  }

  onDocumentLoad = ({ numPages }) => {
    this.setState({ numPages });
  }

  onDocumentFail() {
    return (

        On dirait que ton browser n'arrive pas à afficher ce document...

        Ce n'est pas grave, tu peux quand même le

             télécharger.
)
  }

  view_more() {
    this.setState({view_more: this.state.view_more + 1})
  }

  zoomin(){
    this.setState({zoomlevel: this.state.zoomlevel + 0.1})
  }

  zoomout(){
    this.setState({zoomlevel: this.state.zoomlevel - 0.1})
  }

  render() {
    const { pageNumber, numPages, view_more, zoomlevel} = this.state;

    const renderPages = Math.min(5 * view_more, numPages);

    var render_not_full = ""
    if (renderPages < numPages) {
        render_not_full = (
            <button className="viewer-show-more btn" onClick={this.view_more.bind(this)}>
                Ce document à {numPages - renderPages} pages supplémentaires. Cliquez ici pour la suite.
            </button>
        );
    }

    var document_data = document.getElementById('document_data').dataset

    return (

        <Navbar zoomin={this.zoomin.bind(this)}
                zoomout={this.zoomout.bind(this)}
                docname={document_data.name}
                docid={document_data.id}
                course_name={document_data.coursename}
                original={document_data.original}
                pdf={document_data.pdf}
                has_perm={document_data.hasperm}
        />
        <Document
          className="viewer-document"
          file={document_data.url}
          loading={<Loader />}
          onLoadSuccess={this.onDocumentLoad}
          error={this.onDocumentFail()}
        >
            {
            Array.from(
              new Array(renderPages),
              (el, index) => (
                <Page
                  key={`page_${index + 1}`}
                  pageNumber={index + 1}
                  renderTextLayer={false}
                  scale={zoomlevel}
                />

              ),
            )
            }
        </Document>
        {render_not_full}

    );
  }
}
<|endoftext|>