<commit_before>/* jshint undef: true, unused: true, browser: true, quotmark: single, curly: true */
(function($) {
    var resultRenderers = {};

    $.registerSiteSearchRenderer = function(classes, groupTitle, renderer) {
        if (typeof classes == 'string') {
            classes = [classes];
        }

        renderer.groupTitle = groupTitle;
        renderer.classes = classes;

        $.each(classes, function(index, className) {
            resultRenderers[className] = renderer;
        });
    };

    $(function() {
        $('.js-site-search').each(function() {
            var $searchForm = $(this),
                $searchField = $searchForm.find('input[name=q]'),
                $resultsList = $('
').appendTo($searchForm).addClass('search-results dropdown-menu').hide(),
                lastTypedQuery, lastRequestedQuery, searchTimeout, searchXHR, hideResultsOnBlur;

            // bind events to search field
            $searchField.attr('autocomplete', 'off');

            $searchField.keyup(function() {
                var query = $searchField.val();

                if (query == lastTypedQuery) {
                    return;
                }

                lastTypedQuery = query;

                // abort any pending search timeout
                if (searchTimeout) {
                    clearTimeout(searchTimeout);
                    searchTimeout = null;
                }

                // execute or clear search
                if (query.length >= 2 && query) {
                    $searchForm.addClass('is-waiting');
                    $resultsList.show();
                    searchTimeout = setTimeout(_doSearch, 300);
                } else {
                    $resultsList.hide().empty();
                    lastRequestedQuery = null;

                    // abort any pending query
                    if (searchXHR) {
                        searchXHR.abort();
                        searchXHR = null;
                    }
                }
            });

            $searchField.focus(function() {
                if (lastRequestedQuery) {
                    $resultsList.show();
                }
            });

            // bind body event to hide results
            $(document).click(function(e) {
                if (!$searchForm.is(e.target) && !$searchForm.has(e.target).length) {
                    $resultsList.hide();
                }
            });

            $(document).keydown(function(e) {
                var waitingToRun = hideResultsOnBlur,
                    activeEl = $(document.activeElement);

                if (!$resultsList.is(':visible') || waitingToRun === true) {
                    return;
                }

                if (activeEl && activeEl != $resultsList && activeEl != $searchForm && !activeEl.closest($searchForm).length && !activeEl.closest($resultsList).length) {
                    hideResultsOnBlur = true;
                    setTimeout(function() {
                        $resultsList.hide();
                        hideResultsOnBlur = false;
                    }, 100);
                }
            });

            // bind form events for keyboard navigation
            $searchForm.keydown(function(e) {
                var isDown = e.which == 40, // 40 = down arrow
                    $resultLinks, lastLinkIndex, currentLinkIndex, nextLinkIndex;

                if (!isDown && e.which != 38) { // 38 = up arrow
                    return;
                }

                e.preventDefault();

                if (!$resultsList.is(':visible')) {
                    return;
                }

                $resultLinks = $resultsList.find('a');
                lastLinkIndex = $resultLinks.length - 1;
                currentLinkIndex = $resultLinks.index($(e.target).closest('a'));

                if (currentLinkIndex == -1) {
                    focusLinkIndex = isDown ? 0 : lastLinkIndex;
                } else {
                    if ( (currentLinkIndex == 0 && !isDown) || (currentLinkIndex == lastLinkIndex && isDown) ) {
                        // return focus to field at ends of results list
                        $searchField.focus();
                        return;
                    }

                    focusLinkIndex = currentLinkIndex + (isDown ? 1 : -1);
                }

                $resultLinks[focusLinkIndex].focus();
            });

            // workflow methods
            function _doSearch() {
                var query = $searchField.val(),
                    params = {
                        q: query,
                        include: 'recordTitle,recordURL'
                    };

                $searchForm.removeClass('is-waiting');

                if (searchXHR) {
                    searchXHR.abort();
                    searchXHR = null;
                }

                if (query == lastRequestedQuery) {
                    return;
                }

                lastRequestedQuery = query;
                $searchForm.addClass('is-loading');
                searchXHR = $.ajax({
                    url: '/search',
                    headers: {
                        Accept: 'application/json'
                    },
                    data: params,
                    success: _renderResults
                });
            }

            function _renderResults(results) {
                $searchForm.removeClass('is-loading');

                if (results.totalResults) {
                    $searchForm.removeClass('no-results');
                    $resultsList.empty();
                    $.each(results.data, function(key, value) {
                        if (!value.length) {
                            return;
                        }

                        var $section = $('
').addClass('results-group');
                        $('
').appendTo($section).addClass('group-title').text(
                            key in resultRenderers ? resultRenderers[key].groupTitle : key
                        );

                        $.each(value.slice(0, 5), function(index, result) {
                            $('
').addClass('search-result').append(
                                (resultRenderers[result.Class] || _defaultResultRenderer)(result)
                            ).appendTo($section);
                        });

                        if (value.length > 5) {
                            $('
').addClass('search-result').append(
                                $('')
                                    .html((value.length - 5) + ' more…')
                                    .attr('href', '/search?q=' + encodeURIComponent(lastRequestedQuery))
                            ).appendTo($section);
                        }

                        $section.appendTo($resultsList);
                    });
                } else {
                    $searchForm.addClass('no-results');
                    $resultsList.html('
No results
');
                }
            }

            function _defaultResultRenderer(result) {
                return $('')
                    .text(result.recordTitle)
                    .attr('href', result.recordURL);
            }

        }); // end form.site-search loop

    });
}(jQuery));<commit_msg>Add secondary CSS classes for bootstrap v4 to site-search<commit_after>/* jshint undef: true, unused: true, browser: true, quotmark: single, curly: true */
(function($) {
    var resultRenderers = {};

    $.registerSiteSearchRenderer = function(classes, groupTitle, renderer) {
        if (typeof classes == 'string') {
            classes = [classes];
        }

        renderer.groupTitle = groupTitle;
        renderer.classes = classes;

        $.each(classes, function(index, className) {
            resultRenderers[className] = renderer;
        });
    };

    $(function() {
        $('.js-site-search').each(function() {
            var $searchForm = $(this),
                $searchField = $searchForm.find('input[name=q]'),
                $resultsList = $('
').appendTo($searchForm).addClass('search-results dropdown-menu').hide(),
                lastTypedQuery, lastRequestedQuery, searchTimeout, searchXHR, hideResultsOnBlur;

            // bind events to search field
            $searchField.attr('autocomplete', 'off');

            $searchField.keyup(function() {
                var query = $searchField.val();

                if (query == lastTypedQuery) {
                    return;
                }

                lastTypedQuery = query;

                // abort any pending search timeout
                if (searchTimeout) {
                    clearTimeout(searchTimeout);
                    searchTimeout = null;
                }

                // execute or clear search
                if (query.length >= 2 && query) {
                    $searchForm.addClass('is-waiting');
                    $resultsList.show();
                    searchTimeout = setTimeout(_doSearch, 300);
                } else {
                    $resultsList.hide().empty();
                    lastRequestedQuery = null;

                    // abort any pending query
                    if (searchXHR) {
                        searchXHR.abort();
                        searchXHR = null;
                    }
                }
            });

            $searchField.focus(function() {
                if (lastRequestedQuery) {
                    $resultsList.show();
                }
            });

            // bind body event to hide results
            $(document).click(function(e) {
                if (!$searchForm.is(e.target) && !$searchForm.has(e.target).length) {
                    $resultsList.hide();
                }
            });

            $(document).keydown(function(e) {
                var waitingToRun = hideResultsOnBlur,
                    activeEl = $(document.activeElement);

                if (!$resultsList.is(':visible') || waitingToRun === true) {
                    return;
                }

                if (activeEl && activeEl != $resultsList && activeEl != $searchForm && !activeEl.closest($searchForm).length && !activeEl.closest($resultsList).length) {
                    hideResultsOnBlur = true;
                    setTimeout(function() {
                        $resultsList.hide();
                        hideResultsOnBlur = false;
                    }, 100);
                }
            });

            // bind form events for keyboard navigation
            $searchForm.keydown(function(e) {
                var isDown = e.which == 40, // 40 = down arrow
                    $resultLinks, lastLinkIndex, currentLinkIndex, nextLinkIndex;

                if (!isDown && e.which != 38) { // 38 = up arrow
                    return;
                }

                e.preventDefault();

                if (!$resultsList.is(':visible')) {
                    return;
                }

                $resultLinks = $resultsList.find('a');
                lastLinkIndex = $resultLinks.length - 1;
                currentLinkIndex = $resultLinks.index($(e.target).closest('a'));

                if (currentLinkIndex == -1) {
                    focusLinkIndex = isDown ? 0 : lastLinkIndex;
                } else {
                    if ( (currentLinkIndex == 0 && !isDown) || (currentLinkIndex == lastLinkIndex && isDown) ) {
                        // return focus to field at ends of results list
                        $searchField.focus();
                        return;
                    }

                    focusLinkIndex = currentLinkIndex + (isDown ? 1 : -1);
                }

                $resultLinks[focusLinkIndex].focus();
            });

            // workflow methods
            function _doSearch() {
                var query = $searchField.val(),
                    params = {
                        q: query,
                        include: 'recordTitle,recordURL'
                    };

                $searchForm.removeClass('is-waiting');

                if (searchXHR) {
                    searchXHR.abort();
                    searchXHR = null;
                }

                if (query == lastRequestedQuery) {
                    return;
                }

                lastRequestedQuery = query;
                $searchForm.addClass('is-loading');
                searchXHR = $.ajax({
                    url: '/search',
                    headers: {
                        Accept: 'application/json'
                    },
                    data: params,
                    success: _renderResults
                });
            }

            function _renderResults(results) {
                $searchForm.removeClass('is-loading');

                if (results.totalResults) {
                    $searchForm.removeClass('no-results');
                    $resultsList.empty();
                    $.each(results.data, function(key, value) {
                        if (!value.length) {
                            return;
                        }

                        var $section = $('
').addClass('results-group');
                        $('
').appendTo($section).addClass('group-title dropdown-header').text(
                            key in resultRenderers ? resultRenderers[key].groupTitle : key
                        );

                        $.each(value.slice(0, 5), function(index, result) {
                            $('
').addClass('search-result').append(
                                (resultRenderers[result.Class] || _defaultResultRenderer)(result).addClass('dropdown-item')
                            ).appendTo($section);
                        });

                        if (value.length > 5) {
                            $('
').addClass('search-result').append(
                                $('')
                                    .html((value.length - 5) + ' more…')
                                    .attr('href', '/search?q=' + encodeURIComponent(lastRequestedQuery))
                            ).appendTo($section);
                        }

                        $section.appendTo($resultsList);
                    });
                } else {
                    $searchForm.addClass('no-results');
                    $resultsList.html('
No results
');
                }
            }

            function _defaultResultRenderer(result) {
                return $('')
                    .text(result.recordTitle)
                    .attr('href', result.recordURL);
            }

        }); // end form.site-search loop

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


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import LogsStore from '../stores/LogsStore';
import MZBenchActions from '../actions/MZBenchActions';
import MZBenchRouter from '../utils/MZBenchRouter';
import BenchLogEntry from './BenchLogEntry.react';
import LoadingSpinner from './LoadingSpinner.react';
import PropTypes from 'prop-types';

const LOGS_PER_PAGE = 100;

class BenchLog extends React.Component {
    constructor(props) {
        super(props);
        this.streamId = 0;
        this.autoSearchHandler = null;
        this.filtered = 0;
        this.state = this._resolveState();
        this.state.tempQ = this.state.form.query;
        this.state.tempK = this.state.form.kind;
        this.state.tempE = this.state.form.errors;
        this.state.logShown = LOGS_PER_PAGE;
        this.followFlag = false;
        this._onChange = this._onChange.bind(this);
        this._onChangeSearch = this._onChangeSearch.bind(this);
        this._onUser = this._onUser.bind(this);
        this._onSystem = this._onSystem.bind(this);
        this._onErrors = this._onErrors.bind(this);
        this._onScroll = this._onScroll.bind(this);
        this._onResize = this._onResize.bind(this);
        this._onFollow = this._onFollow.bind(this);
        this._onTop = this._onTop.bind(this);
        this.lastLogShown = 0;
    }

    componentDidMount() {
        LogsStore.onChange(this._onChange);
        this.streamId = LogsStore.subscribeToLogs(this.props.bench.id);
        window.addEventListener("scroll", this._onScroll);
        window.addEventListener("resize", this._onResize);
        ReactDOM.findDOMNode(this.refs.loglookup).focus();
        this._updateFollowPos();
        this._updateTopPos();
    }

    componentWillUnmount() {
        LogsStore.off(this._onChange);
        LogsStore.unsubscribeFromLogs(this.streamId);
        window.removeEventListener("resize", this._onResize);
        window.removeEventListener("scroll", this._onScroll);
    }

    componentDidUpdate() {
        if (this.state.isFollow) {
            this.goBottom();
        }
        this._updateFollowPos();
        this._updateTopPos();
    }

    render() {
        const url = '/' + (this.state.form.kind == 0 ? 'userlog' : 'log') + '?id=' + this.props.bench.id;
        let classUser = "btn btn-" + (this.state.form.kind == 0 ? "primary":"default");
        let classSystem = "btn btn-" + (this.state.form.kind == 1 ? "primary":"default");
        let classError = "btn btn-" + (this.state.form.errors == 1 ? "danger":"default");
        let currentLog = this.state.form.kind == 1 ? this.state.logs.system : this.state.logs.user;
        let overflow = this.state.form.kind == 1 ? this.state.logs.systemOverflow : this.state.logs.userOverflow;
        let loaded = this.state.form.kind == 1 ? this.state.logs.isSystemLoaded : this.state.logs.isUserLoaded;

        let logAfterQuery = this.state.logAfterQuery;

        let logsToShow = (logAfterQuery.length < this.state.logShown) ? logAfterQuery.length : this.state.logShown;
        this.lastLogShown = logsToShow;

        return (

                <form className="form-inline log-lookup-form">

                      <input ref="loglookup" type="text" className="form-control" onKeyDown={this._onKeyDown.bind(this)} onChange={this._onChangeSearch} value={this.state.tempQ} placeholder="Lookup Logs" />

                    <button type="button" className={classUser} onClick={this._onUser}>User</button>
                    <button type="button" className={classSystem} onClick={this._onSystem}>System</button>

                  <button type="button" className={classError} onClick={this._onErrors}>Errors only</button>
                </form>
                {
                    !loaded ? (<LoadingSpinner>Loading...</LoadingSpinner>) :

                                Raw log

                                {this.props.isBenchActive ? "Follow log" : "Scroll to end"}

                                Top

                                {overflow ?
Warning: due to big size, this log is trimmed
 : null}
                                {!currentLog.length ?
Warning: this log is empty
 :
                                        (!logAfterQuery.length ?
Query not found
 : null)}

                            {this.formatLogs(logsToShow, logAfterQuery)}

                }

        );
    }

    formatLogs(logsToShow, log) {
        let nPages = Math.round(logsToShow / LOGS_PER_PAGE) + 1;
        let form = this.state.form;
        let prefix = form.kind + "-" + form.errors + "-" + form.query + "-";
        let res = [];
        for (var page = 0; page < nPages; page++) {
            res.push(<BenchLogEntry
                        key={prefix + page}
                        log={log}
                        from={page*LOGS_PER_PAGE}
                        to={(page + 1)*LOGS_PER_PAGE}
                        query={this.state.form.query}/>);
        }
        return res;
    }

    filterLogs(form, logs, needRefilter) {
        let filtered = (needRefilter || !this.state) ? 0 : this.filtered;
        var logAfterQuery = (needRefilter || !this.state) ? [] : this.state.logAfterQuery;
        let currentLog = form.kind == 1 ? logs.system : logs.user;
        let query = form.query;
        let errors = form.errors;
        if (needRefilter) this.lastLogShown = 0;
        if (!query && !errors) {
            this.filtered = currentLog.length;
            return currentLog;
        }

        for (; filtered < currentLog.length; filtered++) {
            let line = currentLog[filtered];
            if (!line) break;
            if (query) {
                let fullText = line.time + " " + line.severity + " " + line.text;
                if (fullText.indexOf(query) == -1) continue;
            }
            if (errors && line.severity!="[error]") continue;
            logAfterQuery.push(line);
        };
        this.filtered = filtered;
        return logAfterQuery;
    }

    _onScroll(scrollEvent) {
        this._updateFollowPos();
        this._updateTopPos();
        if (this.updatePage()) return;

        if (this.followFlag) {
            this.followFlag = false;
        } else if(this.state.isFollow) {
            this.setState({isFollow: false});
        }
    }

    _onResize(resizeEvent) {
        this._updateFollowPos();
        this._updateTopPos();
    }

    _updateFollowPos() {
        let logElement = ReactDOM.findDOMNode(this.refs.logwindow);
        if (!logElement) return;
        var rect = logElement.getBoundingClientRect();
        let top = (rect.top > 0) ? rect.top : 0;
        let right = (window.innerWidth - rect.right);
        let followDiv = ReactDOM.findDOMNode(this.refs.followdiv);
        followDiv.style.top = top + 'px';
        followDiv.style.right = right + 'px';
        let followBtn = ReactDOM.findDOMNode(this.refs.followbtn);
        let visible = document.body.scrollHeight > window.innerHeight;
        followBtn.style.visibility = visible ? "visible" : "hidden";
    }

    _updateTopPos() {
        let logElement = ReactDOM.findDOMNode(this.refs.logwindow);
        if (!logElement) return;
        var rect = logElement.getBoundingClientRect();
        let right = (window.innerWidth - rect.right);
        let topBtn = ReactDOM.findDOMNode(this.refs.topbtn);
        topBtn.style.visibility = (document.body.scrollTop > 0 ? 'visible' : 'hidden');
        topBtn.style.right = right + 'px';
    }

    _resolveState() {
        let currentState = this.state ? this.state : {form: {query: "", kind: 0, errors: 0}, logAfterQuery: [], isFollow: false};
        let newForm = LogsStore.getQueryData(this.props.bench.id);
        let needRefilter = (!currentState.form ||
                            currentState.form.query  != newForm.query ||
                            currentState.form.kind   != newForm.kind  ||
                            currentState.form.errors != newForm.errors);
        currentState.form.kind = newForm.kind;
        currentState.form.query = newForm.query;
        currentState.form.errors = newForm.errors;
        currentState.logs = LogsStore.getLogData(this.streamId);
        currentState.logAfterQuery = this.filterLogs(newForm, currentState.logs, needRefilter);
        return currentState;
    }

    _onChange() {
        this.setState(this._resolveState());
        if (this.state.isFollow) this.updatePage();
    }

    _runSearch() {
        this.state.logShown = LOGS_PER_PAGE;
        if (this.autoSearchHandler) {
            clearTimeout(this.autoSearchHandler);
        }
        MZBenchRouter.navigate("/bench/" + this.props.bench.id + "/logs/" +
            (this.state.tempK ? "system": "user") + "/" +
            (this.state.tempE ? "errors": "all") + (this.state.tempQ ? "/" + encodeURIComponent(this.state.tempQ).replace(/'/g, "%27") : ""), {});
    }

    _onKeyDown(event) {
        if (event.key === 'Enter') {
            event.preventDefault();
            this._runSearch();
        }
    }

    _onChangeSearch(event) {
        let state = this.state;
        if (this.autoSearchHandler) {
            clearTimeout(this.autoSearchHandler);
        }
        state.tempQ = event.target.value;
        this.setState(state);
        this.autoSearchHandler = setTimeout(() => this._runSearch(), this.props.autoSearchInterval);
    }

    _onUser() {
        this.state.tempK = 0;
        ReactDOM.findDOMNode(this.refs.loglookup).focus();
        this._runSearch();
    }

    _onSystem() {
        this.state.tempK = 1;
        ReactDOM.findDOMNode(this.refs.loglookup).focus();
        this._runSearch();
    }

    _onFollow(event) {
        event.preventDefault();
        this.setState({isFollow: !this.state.isFollow});
        let logLen = this.state.logAfterQuery.length;
        if (this.state.logShown < logLen) {
            this.setState({logShown: logLen});
        }
        if (this.state.isFollow) this.goBottom();
    }

    _onTop(event) {
        event.preventDefault();
        this.setState({isFollow: false});
        ReactDOM.findDOMNode(this.refs.loglookup).focus();
        this.goTop();
    }

    _onErrors() {
        this.state.tempE = !this.state.tempE;
        ReactDOM.findDOMNode(this.refs.loglookup).focus();
        this._runSearch();
    }

    goBottom() {
        var newValue = document.body.scrollHeight - window.innerHeight;
        if (document.body.scrollTop < newValue) {
            document.body.scrollTop = newValue;
            this.followFlag = true;
        }
    }

    goTop() {
        document.body.scrollTop = 0;
    }

    updatePage () {
        let node = document.body;
        var shouldIncrementPage = (node.scrollTop + window.innerHeight + 2000 > node.scrollHeight);
        let endReached = (this.state.logAfterQuery.length <= this.state.logShown);
        if (shouldIncrementPage && !endReached) {
            this.setState({logShown: this.state.logShown + LOGS_PER_PAGE});
            return true;
        }
        return false;
    }
};

BenchLog.propTypes = {
    bench: PropTypes.object.isRequired,
    autoSearchInterval: PropTypes.number
};

BenchLog.defaultProps = {
    autoSearchInterval: 500
};

export default BenchLog;
<commit_msg>Fix 'Follow log' button for chrome<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import LogsStore from '../stores/LogsStore';
import MZBenchActions from '../actions/MZBenchActions';
import MZBenchRouter from '../utils/MZBenchRouter';
import BenchLogEntry from './BenchLogEntry.react';
import LoadingSpinner from './LoadingSpinner.react';
import PropTypes from 'prop-types';

const LOGS_PER_PAGE = 100;

class BenchLog extends React.Component {
    constructor(props) {
        super(props);
        this.streamId = 0;
        this.autoSearchHandler = null;
        this.filtered = 0;
        this.state = this._resolveState();
        this.state.tempQ = this.state.form.query;
        this.state.tempK = this.state.form.kind;
        this.state.tempE = this.state.form.errors;
        this.state.logShown = LOGS_PER_PAGE;
        this.followFlag = false;
        this._onChange = this._onChange.bind(this);
        this._onChangeSearch = this._onChangeSearch.bind(this);
        this._onUser = this._onUser.bind(this);
        this._onSystem = this._onSystem.bind(this);
        this._onErrors = this._onErrors.bind(this);
        this._onScroll = this._onScroll.bind(this);
        this._onResize = this._onResize.bind(this);
        this._onFollow = this._onFollow.bind(this);
        this._onTop = this._onTop.bind(this);
        this.lastLogShown = 0;
    }

    componentDidMount() {
        LogsStore.onChange(this._onChange);
        this.streamId = LogsStore.subscribeToLogs(this.props.bench.id);
        window.addEventListener("scroll", this._onScroll);
        window.addEventListener("resize", this._onResize);
        ReactDOM.findDOMNode(this.refs.loglookup).focus();
        this._updateFollowPos();
        this._updateTopPos();
    }

    componentWillUnmount() {
        LogsStore.off(this._onChange);
        LogsStore.unsubscribeFromLogs(this.streamId);
        window.removeEventListener("resize", this._onResize);
        window.removeEventListener("scroll", this._onScroll);
    }

    componentDidUpdate() {
        if (this.state.isFollow) {
            this.goBottom();
        }
        this._updateFollowPos();
        this._updateTopPos();
    }

    render() {
        const url = '/' + (this.state.form.kind == 0 ? 'userlog' : 'log') + '?id=' + this.props.bench.id;
        let classUser = "btn btn-" + (this.state.form.kind == 0 ? "primary":"default");
        let classSystem = "btn btn-" + (this.state.form.kind == 1 ? "primary":"default");
        let classError = "btn btn-" + (this.state.form.errors == 1 ? "danger":"default");
        let currentLog = this.state.form.kind == 1 ? this.state.logs.system : this.state.logs.user;
        let overflow = this.state.form.kind == 1 ? this.state.logs.systemOverflow : this.state.logs.userOverflow;
        let loaded = this.state.form.kind == 1 ? this.state.logs.isSystemLoaded : this.state.logs.isUserLoaded;

        let logAfterQuery = this.state.logAfterQuery;

        let logsToShow = (logAfterQuery.length < this.state.logShown) ? logAfterQuery.length : this.state.logShown;
        this.lastLogShown = logsToShow;

        return (

                <form className="form-inline log-lookup-form">

                      <input ref="loglookup" type="text" className="form-control" onKeyDown={this._onKeyDown.bind(this)} onChange={this._onChangeSearch} value={this.state.tempQ} placeholder="Lookup Logs" />

                    <button type="button" className={classUser} onClick={this._onUser}>User</button>
                    <button type="button" className={classSystem} onClick={this._onSystem}>System</button>

                  <button type="button" className={classError} onClick={this._onErrors}>Errors only</button>
                </form>
                {
                    !loaded ? (<LoadingSpinner>Loading...</LoadingSpinner>) :

                                Raw log

                                {this.props.isBenchActive ? "Follow log" : "Scroll to end"}

                                Top

                                {overflow ?
Warning: due to big size, this log is trimmed
 : null}
                                {!currentLog.length ?
Warning: this log is empty
 :
                                        (!logAfterQuery.length ?
Query not found
 : null)}

                            {this.formatLogs(logsToShow, logAfterQuery)}

                }

        );
    }

    formatLogs(logsToShow, log) {
        let nPages = Math.round(logsToShow / LOGS_PER_PAGE) + 1;
        let form = this.state.form;
        let prefix = form.kind + "-" + form.errors + "-" + form.query + "-";
        let res = [];
        for (var page = 0; page < nPages; page++) {
            res.push(<BenchLogEntry
                        key={prefix + page}
                        log={log}
                        from={page*LOGS_PER_PAGE}
                        to={(page + 1)*LOGS_PER_PAGE}
                        query={this.state.form.query}/>);
        }
        return res;
    }

    filterLogs(form, logs, needRefilter) {
        let filtered = (needRefilter || !this.state) ? 0 : this.filtered;
        var logAfterQuery = (needRefilter || !this.state) ? [] : this.state.logAfterQuery;
        let currentLog = form.kind == 1 ? logs.system : logs.user;
        let query = form.query;
        let errors = form.errors;
        if (needRefilter) this.lastLogShown = 0;
        if (!query && !errors) {
            this.filtered = currentLog.length;
            return currentLog;
        }

        for (; filtered < currentLog.length; filtered++) {
            let line = currentLog[filtered];
            if (!line) break;
            if (query) {
                let fullText = line.time + " " + line.severity + " " + line.text;
                if (fullText.indexOf(query) == -1) continue;
            }
            if (errors && line.severity!="[error]") continue;
            logAfterQuery.push(line);
        };
        this.filtered = filtered;
        return logAfterQuery;
    }

    _onScroll(scrollEvent) {
        this._updateFollowPos();
        this._updateTopPos();
        if (this.updatePage()) return;

        if (this.followFlag) {
            this.followFlag = false;
        } else if(this.state.isFollow) {
            this.setState({isFollow: false});
        }
    }

    _onResize(resizeEvent) {
        this._updateFollowPos();
        this._updateTopPos();
    }

    _updateFollowPos() {
        let logElement = ReactDOM.findDOMNode(this.refs.logwindow);
        if (!logElement) return;
        var rect = logElement.getBoundingClientRect();
        let top = (rect.top > 0) ? rect.top : 0;
        let right = (window.innerWidth - rect.right);
        let followDiv = ReactDOM.findDOMNode(this.refs.followdiv);
        followDiv.style.top = top + 'px';
        followDiv.style.right = right + 'px';
        let followBtn = ReactDOM.findDOMNode(this.refs.followbtn);
        let visible = document.body.scrollHeight > window.innerHeight;
        followBtn.style.visibility = visible ? "visible" : "hidden";
    }

    _updateTopPos() {
        let logElement = ReactDOM.findDOMNode(this.refs.logwindow);
        if (!logElement) return;
        var rect = logElement.getBoundingClientRect();
        let right = (window.innerWidth - rect.right);
        let topBtn = ReactDOM.findDOMNode(this.refs.topbtn);
        topBtn.style.visibility = (window.pageYOffset > 0 ? 'visible' : 'hidden');
        topBtn.style.right = right + 'px';
    }

    _resolveState() {
        let currentState = this.state ? this.state : {form: {query: "", kind: 0, errors: 0}, logAfterQuery: [], isFollow: false};
        let newForm = LogsStore.getQueryData(this.props.bench.id);
        let needRefilter = (!currentState.form ||
                            currentState.form.query  != newForm.query ||
                            currentState.form.kind   != newForm.kind  ||
                            currentState.form.errors != newForm.errors);
        currentState.form.kind = newForm.kind;
        currentState.form.query = newForm.query;
        currentState.form.errors = newForm.errors;
        currentState.logs = LogsStore.getLogData(this.streamId);
        currentState.logAfterQuery = this.filterLogs(newForm, currentState.logs, needRefilter);
        return currentState;
    }

    _onChange() {
        this.setState(this._resolveState());
        if (this.state.isFollow) this.updatePage();
    }

    _runSearch() {
        this.state.logShown = LOGS_PER_PAGE;
        if (this.autoSearchHandler) {
            clearTimeout(this.autoSearchHandler);
        }
        MZBenchRouter.navigate("/bench/" + this.props.bench.id + "/logs/" +
            (this.state.tempK ? "system": "user") + "/" +
            (this.state.tempE ? "errors": "all") + (this.state.tempQ ? "/" + encodeURIComponent(this.state.tempQ).replace(/'/g, "%27") : ""), {});
    }

    _onKeyDown(event) {
        if (event.key === 'Enter') {
            event.preventDefault();
            this._runSearch();
        }
    }

    _onChangeSearch(event) {
        let state = this.state;
        if (this.autoSearchHandler) {
            clearTimeout(this.autoSearchHandler);
        }
        state.tempQ = event.target.value;
        this.setState(state);
        this.autoSearchHandler = setTimeout(() => this._runSearch(), this.props.autoSearchInterval);
    }

    _onUser() {
        this.state.tempK = 0;
        ReactDOM.findDOMNode(this.refs.loglookup).focus();
        this._runSearch();
    }

    _onSystem() {
        this.state.tempK = 1;
        ReactDOM.findDOMNode(this.refs.loglookup).focus();
        this._runSearch();
    }

    _onFollow(event) {
        event.preventDefault();
        this.setState({isFollow: !this.state.isFollow});
        let logLen = this.state.logAfterQuery.length;
        if (this.state.logShown < logLen) {
            this.setState({logShown: logLen});
        }
        if (this.state.isFollow) this.goBottom();
    }

    _onTop(event) {
        event.preventDefault();
        this.setState({isFollow: false});
        ReactDOM.findDOMNode(this.refs.loglookup).focus();
        this.goTop();
    }

    _onErrors() {
        this.state.tempE = !this.state.tempE;
        ReactDOM.findDOMNode(this.refs.loglookup).focus();
        this._runSearch();
    }

    goBottom() {
        var newValue = document.body.scrollHeight - window.innerHeight;
        if (window.pageYOffset < newValue) {
            window.scrollTo(0, newValue);
            this.followFlag = true;
        }
    }

    goTop() {
        window.scrollTo(0, 0);
    }

    updatePage () {
        let node = document.body;
        var shouldIncrementPage = (window.pageYOffset + window.innerHeight + 2000 > node.scrollHeight);
        let endReached = (this.state.logAfterQuery.length <= this.state.logShown);
        if (shouldIncrementPage && !endReached) {
            this.setState({logShown: this.state.logShown + LOGS_PER_PAGE});
            return true;
        }
        return false;
    }
};

BenchLog.propTypes = {
    bench: PropTypes.object.isRequired,
    autoSearchInterval: PropTypes.number
};

BenchLog.defaultProps = {
    autoSearchInterval: 500
};

export default BenchLog;
<|endoftext|>


<commit_before>openerp_staff_management_calendar_booking = function(instance) {
	var _t = instance.web._t; // For text translations

	instance.web.views.add('calendar_booking', 'instance.staff_management.BookingCalendar');

	instance.staff_management.BookingCalendar = instance.staff_management.Calendar.extend({

		template: "PersonalScheduleView",

		init:function(){
			this._super.apply(this,arguments);
		},

		// destroy, restore scheduler fonctions
		destroy:function(){
			this._super();
		},

		get_fc_init_options: function () {
			//Documentation here : http://arshaw.com/fullcalendar/docs/
			var self = this;
			return  $.extend({}, this._super(), {

				eventClick: function(event){
					self.open_event_staff(event.id,event.title);
				},
				select: function (start_date, end_date, all_day, _js_event, _view) {
					var data_template = self.get_event_data({
						start: start_date,
						end: end_date,
						allDay: all_day,
					});
					self.slow_create(data_template);
				},
				eventRender: function(event, element) {

					element.text(self.format_hour(event.hour_from)+' '+event.booking_name);
					element.mouseenter(event, function(evt){
						instance.staff_management.tooltip.show($(this), self.get_tooltip_content(evt.data));
					}).mouseleave(instance.staff_management.tooltip.hide);
				},
			});
		},

		get_tooltip_content: function(event){
			var div = $('<div>');
			div.append($('<div>').text(this.format_hour(event.hour_from)+' - '+this.format_hour(event.hour_to)));
			div.append($('<div>').text(event.booking_name));
			div.append($('<div>').text(event.nbr_adult+' '+_t('adults')));
			div.append($('<div>').text(event.nbr_child+' '+_t('children')));
			if(event.meal_included){
				div.append($('<div>').text(_t('Meal included')));
			}
			if(event.observation){
				div.append($('<div>').text(event.observation));
			}
			return div;
		},

		event_data_transform: function(evt) {
			var r = this._super.apply(this,arguments);
			r.booking_name = evt.booking_name;
			r.hour_from = evt.hour_from;
			r.hour_to = evt.hour_to;
			r.observation = evt.observation;
			r.nbr_adult = evt.nbr_adult;
			r.nbr_child = evt.nbr_child;
			r.meal_included = evt.meal_included;
			return r;
		},

		get_title: function () {
			var title = (_.isUndefined(this.field_widget)) ?
					(this.string || this.name) :
					this.field_widget.string || this.field_widget.name || '';
			return _t("Create: ") + title;
		},
		get_form_popup_infos: function() {
			var infos = {
				view_id: false,
				title: this.name,
			};
			if (!(_.isUndefined(this.ViewManager))) {
				infos.view_id = this.ViewManager.get_view_id('form');
			}
			return infos;
		},
		slow_create: function(data){

			var self = this;
			var defaults = {};

			_.each(data, function(val, field_name) {
				defaults['default_' + field_name] = val;
			});

			var pop_infos = self.get_form_popup_infos();
			var pop = new instance.web.form.FormOpenPopup(this);
			var context = new instance.web.CompoundContext(this.dataset.context, defaults);
			pop.show_element(this.dataset.model, null, this.dataset.get_context(defaults), {
				title: this.get_title(),
				disable_multiple_selection: true,
				view_id: pop_infos.view_id,
				// Ensuring we use ``self.dataset`` and DO NOT create a new one.
				create_function: function(data, options) {
					return self.dataset.create(data, options).done(function(r) {
					}).fail(function (r, event) {
					   if (!r.data.message) { //else manage by openerp
							throw new Error(r);
					   }
					});
				},
				read_function: function(id, fields, options) {
					return self.dataset.read_ids.apply(self.dataset, arguments).done(function() {
					}).fail(function (r, event) {
						if (!r.data.message) { //else manage by openerp
							throw new Error(r);
						}
					});
				},
			});
			var form_controller = pop.view_form;
			form_controller.on("load_record", self, function(){
				self.setPopupFieldsAction(pop);
			});
			pop.on('closed', self, function() {
				self.$calendar.fullCalendar('unselect');
			});
			pop.on('create_completed', self, function(id) {
				self.$calendar.fullCalendar('unselect');
				self.$calendar.fullCalendar('refetchEvents');
			});

		},

		open_event_staff: function(id, title) {
			var self = this;
			if (! this.open_popup_action) {
				var index = this.dataset.get_id_index(id);
				this.dataset.index = index;
				if (this.write_right) {
					this.do_switch_view('form', null, { mode: "edit" });
				} else {
					this.do_switch_view('form', null, { mode: "view" });
				}
			}
			else {
				var pop = new instance.web.form.FormOpenPopup(this);
				pop.show_element(this.dataset.model, id, this.dataset.get_context(), {
					title: _.str.sprintf(_t("View: %s"),title),
					view_id: +this.open_popup_action,
					res_id: id,
					target: 'new',
				});

				var form_controller = pop.view_form;
				form_controller.on("load_record", self, function(){
					button_delete = _.str.sprintf("<button class='oe_button oe_bold delme'><span> %s </span></button>",_t("Delete"));

					self.setPopupFieldsAction(pop);
					pop.$el.closest(".modal").find(".modal-footer").prepend(button_delete);

					$('.delme').click(
						function() {
							$('.oe_form_button_cancel').trigger('click');
							self.remove_event(id);
						}
					);
				});

				pop.on("saved", self, function(){
					self.$calendar.fullCalendar('refetchEvents');
				});

			}
			return false;
		},

		setPopupFieldsAction: function(pop){
			var self = this;
			var jdom = pop.$el;

			var fields = [
				// adults
				'staff_nbr_adult',
				'staff_price_adult',
				// children
				'staff_nbr_child',
				'staff_price_child',
				// wheelchairs
				'staff_nbr_wheelchair',
				'staff_price_wheelchair',
				// meals (checkbox not included here)
				'staff_meal_price_adult',
				'staff_meal_price_child'
			];

			var field_values = {};

			for(var i in fields){
				var field = fields[i];
				field_values[field] = this.getPopupFieldValue(pop, field);
				jdom.find('.'+field+' input').keyup({'pop': pop, 'field': field}, function(evt){
					if(evt.data.field.indexOf('staff_meal_price') == 0){
						if(self.getPopupFieldValue(evt.data.pop, evt.data.field) != field_values[evt.data.field]){
							evt.data.pop.view_form.set_values({'meal_included': true});
							field_values[evt.data.field] = self.getPopupFieldValue(evt.data.pop, evt.data.field);
						}
					}
					self.updatePopupTotalPrice(evt.data.pop);
				});
			}

			// meal checkbox
			jdom.find('.staff_meal_included input').change(function(){
				self.updateTotalPrice();
			});

			// meal observation for the checkbox
			var old_field_value = self.getPopupFieldValue(pop, 'staff_meal_observation');
			jdom.find('.staff_meal_observation textarea').keyup(pop, function(evt){
				if($(this).val() != old_field_value){
					evt.data.view_form.set_values({'meal_included': true});
					old_field_value = $(this).val();
				}
			});

		},

		updatePopupTotalPrice: function(pop){
			var totalPrice = 0;

			var nbr_adult = this.getPopupFieldValue(pop, 'staff_nbr_adult');
			var price_adult = this.getPopupFieldValue(pop, 'staff_price_adult');
			totalPrice += nbr_adult * price_adult;

			var nbr_child = this.getPopupFieldValue(pop, 'staff_nbr_child');
			var price_child = this.getPopupFieldValue(pop, 'staff_price_child');
			totalPrice += nbr_child * price_child;

			var nbr_wheelchair = this.getPopupFieldValue(pop, 'staff_nbr_wheelchair');
			var price_wheelchair = this.getPopupFieldValue(pop, 'staff_price_wheelchair');
			totalPrice += nbr_wheelchair * price_wheelchair;

			if(pop.$el.find('.staff_meal_included input').is(':checked')){
				var meal_price_adult = this.getPopupFieldValue(pop, 'staff_meal_price_adult');
				totalPrice += nbr_adult * meal_price_adult;

				var meal_price_child = this.getPopupFieldValue(pop, 'staff_meal_price_child');
				totalPrice += nbr_child * meal_price_child;
			}

			pop.view_form.set_values({'total_price': totalPrice});
		},

		getPopupFieldValue: function(pop, fieldClass){
			var val = parseFloat(pop.$el.find('.'+fieldClass+' input').val());
			if(isNaN(val)){
				return 0;
			}
			return val;
		},

	});

	/*
	instance.web.views.add('staff_booking_form', 'instance.web.StaffFormView');

	instance.web.StaffFormView = instance.web.FormView.extend({

	});
	*/

};
<commit_msg>Bug fix<commit_after>openerp_staff_management_calendar_booking = function(instance) {
	var _t = instance.web._t; // For text translations

	instance.web.views.add('calendar_booking', 'instance.staff_management.BookingCalendar');

	instance.staff_management.BookingCalendar = instance.staff_management.Calendar.extend({

		template: "PersonalScheduleView",

		init:function(){
			this._super.apply(this,arguments);
		},

		// destroy, restore scheduler fonctions
		destroy:function(){
			this._super();
		},

		get_fc_init_options: function () {
			//Documentation here : http://arshaw.com/fullcalendar/docs/
			var self = this;
			return  $.extend({}, this._super(), {

				eventClick: function(event){
					self.open_event_staff(event.id,event.title);
				},
				select: function (start_date, end_date, all_day, _js_event, _view) {
					var data_template = self.get_event_data({
						start: start_date,
						end: end_date,
						allDay: all_day,
					});
					self.slow_create(data_template);
				},
				eventRender: function(event, element) {

					element.text(self.format_hour(event.hour_from)+' '+event.booking_name);
					element.mouseenter(event, function(evt){
						instance.staff_management.tooltip.show($(this), self.get_tooltip_content(evt.data));
					}).mouseleave(instance.staff_management.tooltip.hide);
				},
			});
		},

		get_tooltip_content: function(event){
			var div = $('<div>');
			div.append($('<div>').text(this.format_hour(event.hour_from)+' - '+this.format_hour(event.hour_to)));
			div.append($('<div>').text(event.booking_name));
			div.append($('<div>').text(event.nbr_adult+' '+_t('adults')));
			div.append($('<div>').text(event.nbr_child+' '+_t('children')));
			if(event.meal_included){
				div.append($('<div>').text(_t('Meal included')));
			}
			if(event.observation){
				div.append($('<div>').text(event.observation));
			}
			return div;
		},

		event_data_transform: function(evt) {
			var r = this._super.apply(this,arguments);
			r.booking_name = evt.booking_name;
			r.hour_from = evt.hour_from;
			r.hour_to = evt.hour_to;
			r.observation = evt.observation;
			r.nbr_adult = evt.nbr_adult;
			r.nbr_child = evt.nbr_child;
			r.meal_included = evt.meal_included;
			return r;
		},

		get_title: function () {
			var title = (_.isUndefined(this.field_widget)) ?
					(this.string || this.name) :
					this.field_widget.string || this.field_widget.name || '';
			return _t("Create: ") + title;
		},
		get_form_popup_infos: function() {
			var infos = {
				view_id: false,
				title: this.name,
			};
			if (!(_.isUndefined(this.ViewManager))) {
				infos.view_id = this.ViewManager.get_view_id('form');
			}
			return infos;
		},
		slow_create: function(data){

			var self = this;
			var defaults = {};

			_.each(data, function(val, field_name) {
				defaults['default_' + field_name] = val;
			});

			var pop_infos = self.get_form_popup_infos();
			var pop = new instance.web.form.FormOpenPopup(this);
			var context = new instance.web.CompoundContext(this.dataset.context, defaults);
			pop.show_element(this.dataset.model, null, this.dataset.get_context(defaults), {
				title: this.get_title(),
				disable_multiple_selection: true,
				view_id: pop_infos.view_id,
				// Ensuring we use ``self.dataset`` and DO NOT create a new one.
				create_function: function(data, options) {
					return self.dataset.create(data, options).done(function(r) {
					}).fail(function (r, event) {
					   if (!r.data.message) { //else manage by openerp
							throw new Error(r);
					   }
					});
				},
				read_function: function(id, fields, options) {
					return self.dataset.read_ids.apply(self.dataset, arguments).done(function() {
					}).fail(function (r, event) {
						if (!r.data.message) { //else manage by openerp
							throw new Error(r);
						}
					});
				},
			});
			var form_controller = pop.view_form;
			form_controller.on("load_record", self, function(){
				self.setPopupFieldsAction(pop);
			});
			pop.on('closed', self, function() {
				self.$calendar.fullCalendar('unselect');
			});
			pop.on('create_completed', self, function(id) {
				self.$calendar.fullCalendar('unselect');
				self.$calendar.fullCalendar('refetchEvents');
			});

		},

		open_event_staff: function(id, title) {
			var self = this;
			if (! this.open_popup_action) {
				var index = this.dataset.get_id_index(id);
				this.dataset.index = index;
				if (this.write_right) {
					this.do_switch_view('form', null, { mode: "edit" });
				} else {
					this.do_switch_view('form', null, { mode: "view" });
				}
			}
			else {
				var pop = new instance.web.form.FormOpenPopup(this);
				pop.show_element(this.dataset.model, id, this.dataset.get_context(), {
					title: _.str.sprintf(_t("View: %s"),title),
					view_id: +this.open_popup_action,
					res_id: id,
					target: 'new',
				});

				var form_controller = pop.view_form;
				form_controller.on("load_record", self, function(){
					button_delete = _.str.sprintf("<button class='oe_button oe_bold delme'><span> %s </span></button>",_t("Delete"));

					self.setPopupFieldsAction(pop);
					pop.$el.closest(".modal").find(".modal-footer").prepend(button_delete);

					$('.delme').click(
						function() {
							$('.oe_form_button_cancel').trigger('click');
							self.remove_event(id);
						}
					);
				});

				pop.on("saved", self, function(){
					self.$calendar.fullCalendar('refetchEvents');
				});

			}
			return false;
		},

		setPopupFieldsAction: function(pop){
			var self = this;
			var jdom = pop.$el;

			var fields = [
				// adults
				'staff_nbr_adult',
				'staff_price_adult',
				// children
				'staff_nbr_child',
				'staff_price_child',
				// wheelchairs
				'staff_nbr_wheelchair',
				'staff_price_wheelchair',
				// meals (checkbox not included here)
				'staff_meal_price_adult',
				'staff_meal_price_child'
			];

			var field_values = {};

			for(var i in fields){
				var field = fields[i];
				field_values[field] = this.getPopupFieldValue(pop, field);
				jdom.find('.'+field+' input').keyup({'pop': pop, 'field': field}, function(evt){
					if(evt.data.field.indexOf('staff_meal_price') == 0){
						if(self.getPopupFieldValue(evt.data.pop, evt.data.field) != field_values[evt.data.field]){
							evt.data.pop.view_form.set_values({'meal_included': true});
							field_values[evt.data.field] = self.getPopupFieldValue(evt.data.pop, evt.data.field);
						}
					}
					self.updatePopupTotalPrice(evt.data.pop);
				});
			}

			// meal checkbox
			jdom.find('.staff_meal_included input').change(pop, function(evt){
				self.updatePopupTotalPrice(evt.data);
			});

			// meal observation for the checkbox
			var old_field_value = self.getPopupFieldValue(pop, 'staff_meal_observation');
			jdom.find('.staff_meal_observation textarea').keyup(pop, function(evt){
				if($(this).val() != old_field_value){
					evt.data.view_form.set_values({'meal_included': true});
					old_field_value = $(this).val();
				}
			});

		},

		updatePopupTotalPrice: function(pop){
			var totalPrice = 0;

			var nbr_adult = this.getPopupFieldValue(pop, 'staff_nbr_adult');
			var price_adult = this.getPopupFieldValue(pop, 'staff_price_adult');
			totalPrice += nbr_adult * price_adult;

			var nbr_child = this.getPopupFieldValue(pop, 'staff_nbr_child');
			var price_child = this.getPopupFieldValue(pop, 'staff_price_child');
			totalPrice += nbr_child * price_child;

			var nbr_wheelchair = this.getPopupFieldValue(pop, 'staff_nbr_wheelchair');
			var price_wheelchair = this.getPopupFieldValue(pop, 'staff_price_wheelchair');
			totalPrice += nbr_wheelchair * price_wheelchair;

			if(pop.$el.find('.staff_meal_included input').is(':checked')){
				var meal_price_adult = this.getPopupFieldValue(pop, 'staff_meal_price_adult');
				totalPrice += nbr_adult * meal_price_adult;

				var meal_price_child = this.getPopupFieldValue(pop, 'staff_meal_price_child');
				totalPrice += nbr_child * meal_price_child;
			}

			pop.view_form.set_values({'total_price': totalPrice});
		},

		getPopupFieldValue: function(pop, fieldClass){
			var val = parseFloat(pop.$el.find('.'+fieldClass+' input').val());
			if(isNaN(val)){
				return 0;
			}
			return val;
		},

	});

	/*
	instance.web.views.add('staff_booking_form', 'instance.web.StaffFormView');

	instance.web.StaffFormView = instance.web.FormView.extend({

	});
	*/

};
<|endoftext|>


<commit_before>define([], function Editor() {
    return Object.subclass("Editor", {
        initialize: function(game) {
            this.game = game;
        },

        draw: function(renderer) {
        }
    });
});
<commit_msg>imperative Editor mode<commit_after>define([
    "./../rendering/animation",
    "./../rendering/animationsheet"
], function Editor(
    Animation,
    AnimationSheet
) {

    return Object.subclass("Editor", {
        initialize: function(game) {
            this.game = game;
            this.animation = new Animation(new AnimationSheet("powerups.png", 20, 20), 0.25, [21, 22, 23, 22]);
        },

        update: function(dt) {
            this.animation.update(dt);

            var map = this.game.world.map;
            if(this.game.input.pressed("leftclick")) {
                var tile = map.get(
                    map.positionToCoordinates(this.game.input.position)
                );
                tile.index = (tile.index + 1) % 3;
            }
        },

        draw: function(renderer) {
            var map = this.game.world.map,
                size = map.tileSize,
                index = map.positionToCoordinates(this.game.input.position)
                min = index.mulVector(size)
                max = min.add(size);

            this.animation.draw(renderer, new AABB(min, max));
        }
    });
});
<|endoftext|>


<commit_before>function readoutloud_function(){
	const Cc = Components.classes;
	const Ci = Components.interfaces;
	const Cu = Components.utils;
	const Cr = Components.results;
	//var {Cc, Ci, Cu} = require("chrome");
	var {FileUtils} = Cu.import("resource://gre/modules/FileUtils.jsm");

	var file = Cc['@mozilla.org/file/local;1']
		   .createInstance(Ci.nsILocalFile);

	//file.initWithPath('C:\\temp\\temp.txt');
	//getting platform type
	getPlatform= navigator.platform.toLowerCase().split(" ");
	var platform = getPlatform[0];
	if(platform =='linux'){
		file.initWithPath("/usr/lib/cgi-bin/tts/test.txt");
		if ( file.exists() == false )
			file.create(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 420);
		else
			file.remove(true)
	}else if(platform =='win32' || platform == 'win16') {
		file.initWithPath("C:\\test.txt");
		if ( file.exists() == false )
			file.create(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 420);
	}else{
		alert("The addon is accessible only for Linux and Windows platform. Please Wait!! We are working for other");
		return;
	}

	if(!file.exists()){
	  file.create(file.NORMAL_FILE_TYPE, 0666);
	}

	// WRITE
	var data = content.getSelection();
	var charset = 'UTF-8';
	var fileStream = Cc['@mozilla.org/network/file-output-stream;1'].createInstance(Ci.nsIFileOutputStream);
	fileStream.init(file, FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE | FileUtils.MODE_APPEND, 0x200, false);

	var converterStream = Cc['@mozilla.org/intl/converter-output-stream;1'].createInstance(Ci.nsIConverterOutputStream);

	converterStream.init(fileStream, charset, data.length,Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);
	converterStream.writeString(data);
	converterStream.close();
	fileStream.close();

	//Execute CGI Script
	//document.location = "http://127.0.0.1/test/process.php?q=" + data;
	var url="http://127.0.0.1/test/process.php?q=" + data;
	var win=window.open(url,'_blank');
	win.focus();
	// READ
	var input = {};
	var inputStream = Components.classes["@mozilla.org/network/file-input-stream;1"].createInstance(Components.interfaces.nsIFileInputStream);
	var converter = Components.classes["@mozilla.org/intl/converter-input-stream;1"].createInstance(Components.interfaces.nsIConverterInputStream);
	inputStream.init(file, 0x01, 0444, null);
        converter.init(inputStream, "UTF-8", 0, 0x0000);
	converter.readString(inputStream.available(), input);

	alert(data + ' this is output '+input);

	//Delete The text file
	if(!file.exists()){
	  file.delete(file.NORMAL_FILE_TYPE);
	}
}

<commit_msg>Plugin Fixed for redirection<commit_after>function readoutloud_function(){
	const Cc = Components.classes;
	const Ci = Components.interfaces;
	const Cu = Components.utils;
	const Cr = Components.results;
	//var {Cc, Ci, Cu} = require("chrome");
	var {FileUtils} = Cu.import("resource://gre/modules/FileUtils.jsm");

	var file = Cc['@mozilla.org/file/local;1']
		   .createInstance(Ci.nsILocalFile);

	//file.initWithPath('C:\\temp\\temp.txt');
	//getting platform type
	getPlatform= navigator.platform.toLowerCase().split(" ");
	var platform = getPlatform[0];
	if(platform =='linux'){
		file.initWithPath("/usr/lib/cgi-bin/tts/test.txt");
		if ( file.exists() == false )
			file.create(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 420);
		else
			file.remove(true)
	}else if(platform =='win32' || platform == 'win16') {
		file.initWithPath("C:\\test.txt");
		if ( file.exists() == false )
			file.create(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 420);
	}else{
		alert("The addon is accessible only for Linux and Windows platform. Please Wait!! We are working for other");
		return;
	}

	if(!file.exists()){
	  file.create(file.NORMAL_FILE_TYPE, 0666);
	}

	// WRITE
	var data = content.getSelection();
	var charset = 'UTF-8';
	var fileStream = Cc['@mozilla.org/network/file-output-stream;1'].createInstance(Ci.nsIFileOutputStream);
	fileStream.init(file, FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE | FileUtils.MODE_APPEND, 0x200, false);

	var converterStream = Cc['@mozilla.org/intl/converter-output-stream;1'].createInstance(Ci.nsIConverterOutputStream);

	converterStream.init(fileStream, charset, data.length,Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);
	converterStream.writeString(data);
	converterStream.close();
	fileStream.close();

	//Execute CGI Script
	//document.location = "http://127.0.0.1/test/process.php?q=" + data;
	var url="http://127.0.0.1/test/process.php?q=" + data;
	var win=window.open(url,'_blank');
	//win.focus();
	// READ
	var input = {};
	var inputStream = Components.classes["@mozilla.org/network/file-input-stream;1"].createInstance(Components.interfaces.nsIFileInputStream);
	var converter = Components.classes["@mozilla.org/intl/converter-input-stream;1"].createInstance(Components.interfaces.nsIConverterInputStream);
	inputStream.init(file, 0x01, 0444, null);
        converter.init(inputStream, "UTF-8", 0, 0x0000);
	converter.readString(inputStream.available(), input);

	//alert(data + ' this is output '+input);
	window.setTimeout(function(){win.close()},1000);
	//win.close();
	//Delete The text file
	if(!file.exists()){
	  file.delete(file.NORMAL_FILE_TYPE);
	}
}

<|endoftext|>


<commit_before>/* Omega JS Component Generator
 *
 * Copyright (C) 2013 Mohammed Morsi <mo@morsi.org>
 * Licensed under the AGPLv3+ http://www.gnu.org/licenses/agpl.txt
 */

Omega.Gen = {
  next_id : function(){
    if(!Omega.Gen._next_id) Omega.Gen._next_id = 0;
    Omega.Gen._next_id += 1;
    return Omega.Gen._next_id;
  },

  elliptical_ms : function(enrml, opts){
    /// generate major axis such that maj . enrml = 0
    var tx   = Math.random();
    var ty   = Math.random();
    var tz   = Math.random();
    var tn   = Omega.Math.nrml(tx,ty,tz);
    var maj  = Omega.Math.cp(tx,ty,tz,enrml.x,enrml.y,enrml.z)
    var majn = Omega.Math.nrml(maj[0], maj[1], maj[2]);
    majx = majn[0]; majy = majn[1]; majz = majn[2];

    /// rotate maj axis by 1.57 around nrml to get min
    var min = Omega.Math.rot(majx,majy,majz,1.57,
                             enrml.x,enrml.y,enrml.z)
    minn = Omega.Math.nrml(min[0],min[1],min[2]);
    var minx = minn[0]; var miny = minn[1]; var minz = minn[2];

    return $.extend({dmajx : majx, dmajy : majy, dmajz : majz,
                     dminx : minx, dminy : miny, dminz : minz},
                     opts);
  },

  asteroid_belt : function(ms){
    var locs  = [];
    var path  = Omega.Math.elliptical_path(ms);
    var nlocs = Math.floor(path.length / 30);
    for(var l = 0; l < 30; l++){
      var pp  = path[nlocs * l];
      locs.push(Omega.Gen.loc_from_coords(pp));
    }

    return Omega.Gen.asteroid_field(ui, locs);
  },

  asteroid_field : function(locations){
    var asteroids = [];
    for(var l = 0; l < locations.length; l++){
      var ast = new Omega.Asteroid({id : 'ast' + l,
                  location : locations[l]});
      asteroids.push(ast);
    }
    return asteroids;
  },

  ship : function(opts){
    if(!opts) opts = {};
    if(!opts.id) opts.id = 'ship' + this.next_id();
    if(!opts.type) opts.type = 'corvette';
    if(!opts.hp) opts.hp = 10;
    if(!opts.max_hp) opts.max_hp = 10;
    if(!opts.location)
      opts.location = new Omega.Location();
    if(!opts.location.x) opts.location.x = 0;
    if(!opts.location.y) opts.location.y = 0;
    if(!opts.location.z) opts.location.z = 0;
    if(!opts.location.orientation_x) opts.location.orientation_x = 0;
    if(!opts.location.orientation_y) opts.location.orientation_y = 0;
    if(!opts.location.orientation_z) opts.location.orientation_z = 1;
    if(!opts.location.movement_strategy)
      opts.location.movement_strategy =
        {json_class : 'Motel::MovementStrategies::Stopped'};

    return new Omega.Ship(opts);
  },

  station : function(opts){
    if(!opts) opts = {};
    if(!opts.id) opts.id = 'station' + this.next_id();
    if(!opts.location)
      opts.location = new Omega.Location();
    if(!opts.location.x) opts.location.x = 0;
    if(!opts.location.y) opts.location.y = 0;
    if(!opts.location.z) opts.location.z = 0;
    if(!opts.location.orientation_x) opts.location.orientation_x = 0;
    if(!opts.location.orientation_y) opts.location.orientation_y = 0;
    if(!opts.location.orientation_z) opts.location.orientation_z = 1;
    if(!opts.location.movement_strategy)
      opts.location.movement_strategy =
        {json_class : 'Motel::MovementStrategies::Stopped'};

    return new Omega.Station(opts);
  },

  linear_ms : function(opts){
    var ms = {json_class : 'Motel::MovementStrategies::Linear',
              speed : 100, dx : 1, dy : 0, dz : 0};
    $.extend(ms, opts);
    return ms;
  }
};
<commit_msg>UI: add solar system generator<commit_after>/* Omega JS Component Generator
 *
 * Copyright (C) 2013 Mohammed Morsi <mo@morsi.org>
 * Licensed under the AGPLv3+ http://www.gnu.org/licenses/agpl.txt
 */

Omega.Gen = {
  next_id : function(){
    if(!Omega.Gen._next_id) Omega.Gen._next_id = 0;
    Omega.Gen._next_id += 1;
    return Omega.Gen._next_id;
  },

  elliptical_ms : function(enrml, opts){
    /// generate major axis such that maj . enrml = 0
    var tx   = Math.random();
    var ty   = Math.random();
    var tz   = Math.random();
    var tn   = Omega.Math.nrml(tx,ty,tz);
    var maj  = Omega.Math.cp(tx,ty,tz,enrml.x,enrml.y,enrml.z)
    var majn = Omega.Math.nrml(maj[0], maj[1], maj[2]);
    majx = majn[0]; majy = majn[1]; majz = majn[2];

    /// rotate maj axis by 1.57 around nrml to get min
    var min = Omega.Math.rot(majx,majy,majz,1.57,
                             enrml.x,enrml.y,enrml.z)
    minn = Omega.Math.nrml(min[0],min[1],min[2]);
    var minx = minn[0]; var miny = minn[1]; var minz = minn[2];

    return $.extend({dmajx : majx, dmajy : majy, dmajz : majz,
                     dminx : minx, dminy : miny, dminz : minz},
                     opts);
  },

  asteroid_belt : function(ms){
    var locs  = [];
    var path  = Omega.Math.elliptical_path(ms);
    var nlocs = Math.floor(path.length / 30);
    for(var l = 0; l < 30; l++){
      var pp  = path[nlocs * l];
      locs.push(Omega.Gen.loc_from_coords(pp));
    }

    return Omega.Gen.asteroid_field(ui, locs);
  },

  asteroid_field : function(locations){
    var asteroids = [];
    for(var l = 0; l < locations.length; l++){
      var ast = new Omega.Asteroid({id : 'ast' + l,
                  location : locations[l]});
      asteroids.push(ast);
    }
    return asteroids;
  },

  ship : function(opts){
    if(!opts) opts = {};
    if(!opts.id) opts.id = 'ship' + this.next_id();
    if(!opts.type) opts.type = 'corvette';
    if(!opts.hp) opts.hp = 10;
    if(!opts.max_hp) opts.max_hp = 10;
    if(!opts.location)
      opts.location = new Omega.Location();
    if(!opts.location.x) opts.location.x = 0;
    if(!opts.location.y) opts.location.y = 0;
    if(!opts.location.z) opts.location.z = 0;
    if(!opts.location.orientation_x) opts.location.orientation_x = 0;
    if(!opts.location.orientation_y) opts.location.orientation_y = 0;
    if(!opts.location.orientation_z) opts.location.orientation_z = 1;
    if(!opts.location.movement_strategy)
      opts.location.movement_strategy =
        {json_class : 'Motel::MovementStrategies::Stopped'};

    return new Omega.Ship(opts);
  },

  station : function(opts){
    if(!opts) opts = {};
    if(!opts.id) opts.id = 'station' + this.next_id();
    if(!opts.location)
      opts.location = new Omega.Location();
    if(!opts.location.x) opts.location.x = 0;
    if(!opts.location.y) opts.location.y = 0;
    if(!opts.location.z) opts.location.z = 0;
    if(!opts.location.orientation_x) opts.location.orientation_x = 0;
    if(!opts.location.orientation_y) opts.location.orientation_y = 0;
    if(!opts.location.orientation_z) opts.location.orientation_z = 1;
    if(!opts.location.movement_strategy)
      opts.location.movement_strategy =
        {json_class : 'Motel::MovementStrategies::Stopped'};

    return new Omega.Station(opts);
  },

  linear_ms : function(opts){
    var ms = {json_class : 'Motel::MovementStrategies::Linear',
              speed : 100, dx : 1, dy : 0, dz : 0};
    $.extend(ms, opts);
    return ms;
  },

  solar_system : function(opts){
    if(!opts) opts = {};
    if(!opts.id) opts.id = 'system' + this.next_id();
    if(!opts.location)
      opts.location = new Omega.Location();
    if(!opts.location.x) opts.location.x = 0;
    if(!opts.location.y) opts.location.y = 0;
    if(!opts.location.z) opts.location.z = 0;

    return new Omega.SolarSystem(opts);
  }
};
<|endoftext|>


<commit_before>require('console-polyfill');

var parseUriOptions = {
  strictMode: false,
    key: [
    'source',
    'protocol',
    'authority',
    'userInfo',
    'user',
    'password',
    'host',
    'port',
    'relative',
    'path',
    'directory',
    'file',
    'query',
    'anchor'
  ],
    q: {
    name: 'queryKey',
      parser: /(?:^|&)([^&=]*)=?([^&]*)/g
  },
  parser: {
    strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
      loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
  }
};

function typeName(obj) {
  return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
}

function isType(obj, name) {
  return typeName(obj) === name;
}

function parseUri(str) {
  if (!isType(str, 'string')) {
    throw new Error('received invalid input');
  }

  var o = parseUriOptions;
  var m = o.parser[o.strictMode ? 'strict' : 'loose'].exec(str);
  var uri = {};
  var i = 14;

  while (i--) {
    uri[o.key[i]] = m[i] || '';
  }

  uri[o.q.name] = {};
  uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
    if ($1) {
      uri[o.q.name][$1] = $2;
    }
  });

  return uri;
}

function sanitizeUrl(url) {
  var baseUrlParts = parseUri(url);
  // remove a trailing # if there is no anchor
  if (baseUrlParts.anchor === '') {
    baseUrlParts.source = baseUrlParts.source.replace('#', '');
  }

  url = baseUrlParts.source.replace('?' + baseUrlParts.query, '');
  return url;
}

function traverse(obj, func) {
  var k;
  var v;
  var i;
  var isObj = isType(obj, 'object');
  var isArray = isType(obj, 'array');
  var keys = [];

  if (isObj) {
    for (k in obj) {
      if (obj.hasOwnProperty(k)) {
        keys.push(k);
      }
    }
  } else if (isArray) {
    for (i = 0; i < obj.length; ++i) {
      keys.push(i);
    }
  }

  for (i = 0; i < keys.length; ++i) {
    k = keys[i];
    v = obj[k];
    isObj = isType(v, 'object');
    isArray = isType(v, 'array');
    if (isObj || isArray) {
      obj[k] = traverse(v, func);
    } else {
      obj[k] = func(k, v);
    }
  }

  return obj;
}

function redact(val) {
  val = String(val);
  return new Array(val.length + 1).join('*');
}

// from http://stackoverflow.com/a/8809472/1138191
function uuid4() {
  var d = new Date().getTime();
  var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = (d + Math.random() * 16) % 16 | 0;
    d = Math.floor(d / 16);
    return (c === 'x' ? r : (r & 0x7 | 0x8)).toString(16);
  });
  return uuid;
}

var Util = {
  isType: isType,
  parseUri: parseUri,
  parseUriOptions: parseUriOptions,
  redact: redact,
  sanitizeUrl: sanitizeUrl,
  traverse: traverse,
  typeName: typeName,
  uuid4: uuid4
};

module.exports = Util;
<commit_msg>add Object.create polyfill for IE8<commit_after>require('console-polyfill');

var parseUriOptions = {
  strictMode: false,
    key: [
    'source',
    'protocol',
    'authority',
    'userInfo',
    'user',
    'password',
    'host',
    'port',
    'relative',
    'path',
    'directory',
    'file',
    'query',
    'anchor'
  ],
    q: {
    name: 'queryKey',
      parser: /(?:^|&)([^&=]*)=?([^&]*)/g
  },
  parser: {
    strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
      loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
  }
};

function typeName(obj) {
  return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
}

function isType(obj, name) {
  return typeName(obj) === name;
}

function parseUri(str) {
  if (!isType(str, 'string')) {
    throw new Error('received invalid input');
  }

  var o = parseUriOptions;
  var m = o.parser[o.strictMode ? 'strict' : 'loose'].exec(str);
  var uri = {};
  var i = 14;

  while (i--) {
    uri[o.key[i]] = m[i] || '';
  }

  uri[o.q.name] = {};
  uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
    if ($1) {
      uri[o.q.name][$1] = $2;
    }
  });

  return uri;
}

function sanitizeUrl(url) {
  var baseUrlParts = parseUri(url);
  // remove a trailing # if there is no anchor
  if (baseUrlParts.anchor === '') {
    baseUrlParts.source = baseUrlParts.source.replace('#', '');
  }

  url = baseUrlParts.source.replace('?' + baseUrlParts.query, '');
  return url;
}

function traverse(obj, func) {
  var k;
  var v;
  var i;
  var isObj = isType(obj, 'object');
  var isArray = isType(obj, 'array');
  var keys = [];

  if (isObj) {
    for (k in obj) {
      if (obj.hasOwnProperty(k)) {
        keys.push(k);
      }
    }
  } else if (isArray) {
    for (i = 0; i < obj.length; ++i) {
      keys.push(i);
    }
  }

  for (i = 0; i < keys.length; ++i) {
    k = keys[i];
    v = obj[k];
    isObj = isType(v, 'object');
    isArray = isType(v, 'array');
    if (isObj || isArray) {
      obj[k] = traverse(v, func);
    } else {
      obj[k] = func(k, v);
    }
  }

  return obj;
}

function redact(val) {
  val = String(val);
  return new Array(val.length + 1).join('*');
}

// from http://stackoverflow.com/a/8809472/1138191
function uuid4() {
  var d = new Date().getTime();
  var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = (d + Math.random() * 16) % 16 | 0;
    d = Math.floor(d / 16);
    return (c === 'x' ? r : (r & 0x7 | 0x8)).toString(16);
  });
  return uuid;
}

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create
if (typeof Object.create != 'function') {
  Object.create = (function(undefined) {
    var Temp = function() {};
    return function (prototype, propertiesObject) {
      if(prototype !== null && prototype !== Object(prototype)) {
        throw TypeError('Argument must be an object, or null');
      }
      Temp.prototype = prototype || {};
      var result = new Temp();
      Temp.prototype = null;
      if (propertiesObject !== undefined) {
        Object.defineProperties(result, propertiesObject);
      }

      // to imitate the case of Object.create(null)
      if(prototype === null) {
         result.__proto__ = null;
      }
      return result;
    };
  })();
}

var Util = {
  isType: isType,
  parseUri: parseUri,
  parseUriOptions: parseUriOptions,
  redact: redact,
  sanitizeUrl: sanitizeUrl,
  traverse: traverse,
  typeName: typeName,
  uuid4: uuid4
};

module.exports = Util;
<|endoftext|>


<commit_before>(function ($) {

    $.fn.alertModal = function (options) {

        // Default options
        var settings = $.extend(true, {}, {
            id: 'modal-example',
            size: 'sm',
            title: 'Modal Example',
            content: '',
            timeout: false,
            footer: {
                show: true,
                btnClose: true,
                btnCloseDescr: 'Close',
                btnSave: true,
                btnSaveDescr: 'Save',
                btnSaveLocation: ''
            }
        }, options);

        // Modal HTML
        var modal_confirm = '
\n';
        modal_confirm += '\t
\n';
        modal_confirm += '\t\t
\n';
        modal_confirm += '\t\t\t
\n';
        modal_confirm += '\t\t\t\t<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>\n';
        modal_confirm += '\t\t\t\t
' + settings.title + '
\n';
        modal_confirm += '\t\t\t
\n';
        modal_confirm += '\t\t\t
\n';
        modal_confirm += '\t\t\t\t' + settings.content + '\n';
        modal_confirm += '\t\t\t
\n';
        if (settings.footer.show) {
            modal_confirm += '\t\t\t
\n';
            if (settings.footer.btnClose) {
                modal_confirm += '\t\t\t\t<button type="button" class="btn btn-default" data-dismiss="modal">' + settings.footer.btnCloseDescr + '</button>\n';
            }
            if (settings.footer.btnSave) {
                modal_confirm += '\t\t\t\t<button type="button" class="btn btn-primary" id="btn-save">' + settings.footer.btnSaveDescr + '</button>\n';
            }
            modal_confirm += '\t\t\t
\n';
        }
        modal_confirm += '\t\t
\n';
        modal_confirm += '\t
\n';
        modal_confirm += '
\n';

        if ($(settings.modalId).length > 0) {
            $(settings.modalId).remove();
        }
        $(this).append(modal_confirm);
        $("#" + settings.id).modal();

        if (settings.footer.btnSaveLocation !== "") {
            $("#" + settings.id).on("click", "#btn-save", function () {
                location.href = settings.footer.btnSaveLocation;
            });
        }

        if (settings.timeout) {
            setTimeout(function () {
                $("#" + settings.id).modal("hide");
            }, settings.timeout);
        }
    };

    $.fn.alert = function (options) {

        // Default options
        var settings = $.extend(true, {}, {
            id: 'alert-example',
            type: 'info',
            message: 'Alert Example',
            timeout: false
        }, options);

        // Alert HTML
        var alert_message = '
\n';
        alert_message += '\t<button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>\n';
        alert_message += '\t' + settings.message + '\n';
        alert_message += '
\n';

        if ($("#" + settings.id).length > 0) {
            $("#" + settings.id).remove();
        }
        $(this).append(alert_message);

        if (settings.timeout) {
            removeElementWithTimeout(settings.id, settings.timeout);
        }
    };

    function removeElementWithTimeout(element_id, timeout)
    {
        setTimeout(function () {
            $("#" + element_id).fadeOut(300, function () {
                $("#" + element_id).remove();
            }, timeout);
        });
    }

}(jQuery));

<commit_msg>add type option for alert modal<commit_after>(function ($) {

    $.fn.alertModal = function (options) {

        // Default options
        var settings = $.extend(true, {}, {
            id: 'modal-example',
            size: 'sm',
            title: 'Modal Example',
            content: '',
            type: 'default',
            timeout: false,
            footer: {
                show: true,
                btnClose: true,
                btnCloseDescr: 'Close',
                btnSave: true,
                btnSaveDescr: 'Save',
                btnSaveLocation: ''
            }
        }, options);

        // Modal HTML
        var modal_confirm = '
\n';
        modal_confirm += '\t
\n';
        modal_confirm += '\t\t
\n';
        modal_confirm += '\t\t\t
\n';
        modal_confirm += '\t\t\t\t<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>\n';
        modal_confirm += '\t\t\t\t
' + settings.title + '
\n';
        modal_confirm += '\t\t\t
\n';
        modal_confirm += '\t\t\t
\n';
        modal_confirm += '\t\t\t\t' + settings.content + '\n';
        modal_confirm += '\t\t\t
\n';
        if (settings.footer.show) {
            modal_confirm += '\t\t\t
\n';
            if (settings.footer.btnClose) {
                modal_confirm += '\t\t\t\t<button type="button" class="btn btn-default" data-dismiss="modal">' + settings.footer.btnCloseDescr + '</button>\n';
            }
            if (settings.footer.btnSave) {
                modal_confirm += '\t\t\t\t<button type="button" class="btn btn-primary" id="btn-save">' + settings.footer.btnSaveDescr + '</button>\n';
            }
            modal_confirm += '\t\t\t
\n';
        }
        modal_confirm += '\t\t
\n';
        modal_confirm += '\t
\n';
        modal_confirm += '
\n';

        if ($(settings.modalId).length > 0) {
            $(settings.modalId).remove();
        }
        $(this).append(modal_confirm);
        $("#" + settings.id).modal();

        if (settings.footer.btnSaveLocation !== "") {
            $("#" + settings.id).on("click", "#btn-save", function () {
                location.href = settings.footer.btnSaveLocation;
            });
        }

        if (settings.timeout) {
            setTimeout(function () {
                $("#" + settings.id).modal("hide");
            }, settings.timeout);
        }
    };

    $.fn.alert = function (options) {

        // Default options
        var settings = $.extend(true, {}, {
            id: 'alert-example',
            type: 'info',
            message: 'Alert Example',
            timeout: false
        }, options);

        // Alert HTML
        var alert_message = '
\n';
        alert_message += '\t<button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>\n';
        alert_message += '\t' + settings.message + '\n';
        alert_message += '
\n';

        if ($("#" + settings.id).length > 0) {
            $("#" + settings.id).remove();
        }
        $(this).append(alert_message);

        if (settings.timeout) {
            removeElementWithTimeout(settings.id, settings.timeout);
        }
    };

    function removeElementWithTimeout(element_id, timeout)
    {
        setTimeout(function () {
            $("#" + element_id).fadeOut(300, function () {
                $("#" + element_id).remove();
            }, timeout);
        });
    }

}(jQuery));

<|endoftext|>


<commit_before>const winston = require('winston');

const flatten = (arr) => arr.reduce((a, b) => (
  Array.isArray(b) ? a.concat(flatten(b))
    : a.concat(b)
), []);

const logger = new winston.Logger({
  transports: [
    new winston.transports.Console({
      handleExceptions: true,
      json: true,
    }),
  ],
});

module.exports = { flatten, logger };
<commit_msg>Log to single line<commit_after>const winston = require('winston');

const flatten = (arr) => arr.reduce((a, b) => (
  Array.isArray(b) ? a.concat(flatten(b))
    : a.concat(b)
), []);

const logger = new winston.Logger({
  transports: [
    new winston.transports.Console({
      handleExceptions: true,
      stringify: true,
    }),
  ],
});

module.exports = { flatten, logger };
<|endoftext|>


<commit_before>const { urlToRequest } = require('loader-utils');

function replaceTemplateUrl(variableName, lines, resolver) {
  const regEx = /(^\s*templateUrl:\s*)['"](.*)['"](,*)$/;
  const lineNumbers = lines.reduce(
    (result, line, i) => (/templateUrl/.test(line) ? result.concat(i) : result),
    []
  );
  const resolverFunc = resolver || urlToRequest;

  if (!lineNumbers.length) {
    return lines;
  }

  const templateRequires = lineNumbers
    .map((lineNumber, i) => {
      const [, , templateUrl] = regEx.exec(lines[lineNumber]) || [];

      if (!templateUrl) {
        return null;
      }

      if (resolver && typeof resolver(templateUrl) !== 'string') {
        throw new Error(
          `Expected path resolver to return string for ${templateUrl}`
        );
      }

      const lineReplacement = lines[lineNumber].replace(
        regEx,
        `$1${variableName}${i + 1}$3`
      );

      return {
        templateUrl,
        lineNumber,
        lineReplacement
      };
    })
    .filter(i => i !== null);

  if (templateRequires.length === 0) {
    return lines;
  }

  const updatedLines = lines;

  templateRequires.forEach(x => {
    updatedLines[x.lineNumber] = x.lineReplacement;
  });

  return [
    ...templateRequires.map(
      (x, i) =>
        `const ${variableName}${i + 1} = require('${resolverFunc(
          x.templateUrl
        )}');`
    ),
    ``,
    ...updatedLines
  ];
}

module.exports = {
  replaceTemplateUrl
};
<commit_msg>fix template variable when templateUrl is null<commit_after>const { urlToRequest } = require('loader-utils');

function replaceTemplateUrl(variableName, lines, resolver) {
  const regEx = /(^\s*templateUrl:\s*)['"](.*)['"](,*)$/;
  const lineNumbers = lines.reduce(
    (result, line, i) => (/templateUrl/.test(line) ? result.concat(i) : result),
    []
  );
  const resolverFunc = resolver || urlToRequest;

  if (!lineNumbers.length) {
    return lines;
  }

  const templateRequires = lineNumbers
    .map((lineNumber, i) => {
      const [, , templateUrl] = regEx.exec(lines[lineNumber]) || [];

      if (!templateUrl) {
        return null;
      }

      if (resolver && typeof resolver(templateUrl) !== 'string') {
        throw new Error(
          `Expected path resolver to return string for ${templateUrl}`
        );
      }

      const lineReplacement = lines[lineNumber].replace(
        regEx,
        `$1${variableName}${i + 1}$3`
      );

      const lineVariable = `${variableName}${i + 1}`
      return {
        lineVariable,
        templateUrl,
        lineNumber,
        lineReplacement
      };
    })
    .filter(i => i !== null);

  if (templateRequires.length === 0) {
    return lines;
  }

  const updatedLines = lines;

  templateRequires.forEach(x => {
    updatedLines[x.lineNumber] = x.lineReplacement;
  });

  return [
    ...templateRequires.map(
      (x, i) =>
        `const ${x.lineVariable} = require('${resolverFunc(
          x.templateUrl
        )}');`
    ),
    ``,
    ...updatedLines
  ];
}

module.exports = {
  replaceTemplateUrl
};
<|endoftext|>


<commit_before>/**
 * Determine if an element has a class.
 *
 * @param {HTMLElement} ele
 * @param {string} cls
 */
function hasClass(ele, cls) {
    return !!ele.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
}

/**
 * Add a class to an element.
 *
 * @param {HTMLElement} ele
 * @param {string} cls
 */
function addClass(ele, cls) {
    if (!hasClass(ele, cls)) ele.className += " " + cls;
}

/**
 * Remove a class from an element
 *
 * @param {HTMLElement} ele
 * @param {string} cls
 */
function removeClass(ele, cls) {
    if (hasClass(ele, cls)) {
        var reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
        ele.className = ele.className.replace(reg, " ");
    }
}

export default {
    hasClass,
    addClass,
    removeClass
};
<commit_msg>Added util methods.<commit_after>/**
 * Determine if an element has a class.
 *
 * @param {HTMLElement} ele
 * @param {string} cls
 */
function hasClass(ele, cls) {
    return !!ele.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
}

/**
 * Add a class to an element.
 *
 * @param {HTMLElement} ele
 * @param {string} cls
 */
function addClass(ele, cls) {
    if (!hasClass(ele, cls)) ele.className += " " + cls;
}

/**
 * Remove a class from an element
 *
 * @param {HTMLElement} ele
 * @param {string} cls
 */
function removeClass(ele, cls) {
    if (hasClass(ele, cls)) {
        var reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
        ele.className = ele.className.replace(reg, " ");
    }
}

function fadeIn(el, time, cb) {
    el.style.opacity = 0;

    var last = +new Date();
    var tick = function() {
        el.style.opacity = +el.style.opacity + (new Date() - last) / time;
        last = +new Date();

        if (+el.style.opacity < 1) {
            (window.requestAnimationFrame && requestAnimationFrame(tick)) ||
                setTimeout(tick, 16);
        } else {
            return cb();
        }
    };

    tick();
}

/**
 * Computer the outer height of an element.
 *
 * Source: https://stackoverflow.com/a/47536372
 * @param {HTMLElement} el
 */
function outerHeight(el) {
    let style = window.getComputedStyle(el);
    return [
        "height",
        "padding-top",
        "padding-bottom",
        "margin-top",
        "margin-bottom"
    ]
        .map(key => parseInt(style.getPropertyValue(key), 10))
        .reduce((prev, cur) => prev + cur);
}

function outerWidth(el) {
    let style = window.getComputedStyle(el);
    return [
        "width",
        "padding-left",
        "padding-right",
        "margin-left",
        "margin-right"
    ]
        .map(key => parseInt(style.getPropertyValue(key), 10))
        .reduce((prev, cur) => prev + cur);
}
export default {
    hasClass,
    addClass,
    removeClass,
    fadeIn,
    outerHeight,
    outerWidth
};
<|endoftext|>


<commit_before>const {
  curry,
  map,
  prop,
  pick,
  zip,
  has,
  merge,
  props,
  append
} = require('ramda')

const unwrapArgs = (a) => {
  if (!Array.isArray(a)) return a
  if (a.length === 1) {
    return a[0]
  } else {
    return a
  }
}

const toArray = (a) => {
  return Array.isArray(a) ? a : [a]
}

const toPromise = (v) => {
  if (!v || !v.then) {
    return Promise.resolve(v)
  }

  return v
}

function success (payload = null) {
  return {
    success: true,
    payload
  }
}

function isSuccess (p) {
  return p.success === true
}

function getSuccesses (l) {
  return l.filter((p) => p.success === true)
}

function failure (error = null) {
  let e1 = errorToObject(error)
  if (typeof error === 'string') {
    e1 = {
      message: error
    }
  }
  return {
    success: false,
    error: e1
  }
}

function errorToObject (error) {
  const isError = error instanceof Error
  if (!isError) return error
  const errorProps = Object.getOwnPropertyNames(error)
  const e1 = pick(errorProps, error)
  const e2 = merge(e1, {
    name: error.name
  })
  return e2
}

function isFailure (p) {
  return p.success === false
}

function getFailures (l) {
  return l.filter((p) => p.success === false)
}

const normalizeToSuccess = (p) => {
  if (isProtocol(p)) return p
  return success(p)
}

const normalizeListToSuccess = map(normalizeToSuccess)

const normalizeToFailure = (p) => {
  if (isProtocol(p)) return p
  return failure(p)
}

const isProtocol = (p) => {
  if (!p) return false
  const hasSuccess = has('success')
  const hasPayload = has('payload')
  const hasError = has('error')
  if (hasSuccess(p) && (hasPayload(p) || hasError(p))) return true
  return false
}

const clean = (p) => {
  return pick(['success', 'error', 'payload'], p)
}

module.exports = {
  unwrapArgs,
  toArray,
  toPromise,
  curry,
  map,
  prop,
  pick,
  props,
  zip,
  has,
  append,
  success,
  isSuccess,
  getSuccesses,
  failure,
  isFailure,
  getFailures,
  merge,
  normalizeToSuccess,
  normalizeListToSuccess,
  normalizeToFailure,
  isProtocol,
  clean,
  errorToObject
}
<commit_msg>refactor to all one-line functions<commit_after>const {
  curry,
  map,
  prop,
  pick,
  zip,
  has,
  merge,
  props,
  append,
  filter
} = require('ramda')

const hasSuccess             = has('success')
const hasPayload             = has('payload')
const hasError               = has('error')
const isArray                = Array.isArray
const isString               = s => typeof s === 'string'
const isPromise              = v => !v || !v.then
const isProtocol             = p => p ? hasSuccess(p) && (hasPayload(p) || hasError(p)) : false
const isSuccess              = p => p.success === true
const isFailure              = p => p.success === false
const clean                  = p => pick(['success', 'error', 'payload'], p)

const toError                = e => isString(e) ? { message: e } : e
const toArray                = a => isArray(a) ? a : [a]
const toPromise              = v => isPromise(v) ? Promise.resolve(v) : v

const S                      = { success: true }
const success                = (payload = null) => Object.assign({}, S, { payload })
const F                      = { success: false }
const failure                = (e = null) => Object.assign({}, F, { error: toError(e)})

const isError                = e => e instanceof Error
const errorProps             = e => Object.getOwnPropertyNames(e).concat('name')
const errorToObject          = e => isError(e) ? pick(errorProps(e), e) : e

const unwrapArray            = a => a.length === 1 ? a[0] : a
const unwrapArgs             = a => isArray(a) ? unwrapArray(a) : a
const getSuccesses           = l => filter(isSuccess, l)
const getFailures            = l => filter(isFailure, l)
const normalize              = (fn, p) => isProtocol(p) ? p : fn(p)
const normalizeToSuccess     = p => normalize(success, p)
const normalizeToFailure     = p => normalize(failure, p)
const normalizeListToSuccess = map(normalizeToSuccess)

module.exports = {
  unwrapArgs,
  unwrapArray,
  toArray,
  toPromise,
  curry,
  map,
  prop,
  pick,
  props,
  zip,
  has,
  append,
  success,
  isSuccess,
  getSuccesses,
  failure,
  isFailure,
  getFailures,
  merge,
  normalizeToSuccess,
  normalizeListToSuccess,
  normalizeToFailure,
  isProtocol,
  clean,
  errorToObject
}
<|endoftext|>


<commit_before>import $ from 'jquery'
import sanitizeHtml from 'sanitize-html'
import * as sanitizeOpts from './sanitizeOpts'

export const equationImageSelector = 'img[src^="/math.svg"], img[src^="data:image/svg+xml"]'
const screenshotImageSelector = 'img[src^="/screenshot/"], img[src^="data:image/png"]'

function convertLinksToRelative(html) {
    return html.replace(new RegExp(document.location.origin, 'g'), '')
}

export function sanitize(html) {
    return sanitizeHtml(convertLinksToRelative(html), sanitizeOpts)
}
export function insertToTextAreaAtCursor(field, value) {
    const startPos = field.selectionStart
    const endPos = field.selectionEnd
    let oldValue = field.value
    field.value = oldValue.substring(0, startPos) + value + oldValue.substring(endPos, oldValue.length)
    field.selectionStart = field.selectionEnd = startPos + value.length
}

export function isKey(e, key) {
    return preventIfTrue(e, !e.altKey && !e.shiftKey && !e.ctrlKey && keyOrKeyCode(e, key))
}

export function isCtrlKey(e, key) {
    return preventIfTrue(e, !e.altKey && !e.shiftKey && e.ctrlKey && keyOrKeyCode(e, key))
}

function keyOrKeyCode(e, val) {
    return typeof val === 'string' ? e.key === val : e.keyCode === val
}
function preventIfTrue(e, val) {
    if (val) e.preventDefault()
    return val
}

export function sanitizeContent(answerElement) {
    const $answerElement = $(answerElement)
    const $mathEditor = $answerElement.find('[data-js="mathEditor"]')
    const scrollPos = $(window).scrollTop()
    $mathEditor.hide()
    const text = $answerElement.get(0).innerText
    $mathEditor.show()
    $(window).scrollTop(scrollPos)

    const html = sanitize($answerElement.html())

    const answerConsideredEmpty =
        text.trim().length +
            $answerElement.find(equationImageSelector).length +
            $answerElement.find(screenshotImageSelector).length ===
        0

    return {
        answerHTML: answerConsideredEmpty ? '' : html,
        answerText: text,
        imageCount: existingScreenshotCount($(`<div>${html}</div>`))
    }
}

export function setCursorAfter($img) {
    const range = document.createRange()
    const img = $img.get(0)
    range.setStartAfter(img)
    const sel = window.getSelection()
    sel.removeAllRanges()
    sel.addRange(range)
}

export function existingScreenshotCount($editor) {
    const imageCount = $editor.find('img').length
    const emptyImageCount = $editor.find('img[src=""]').length
    const equationCount = $editor.find(equationImageSelector).length
    return imageCount - equationCount - emptyImageCount
}

export function scrollIntoView($element) {
    const $window = $(window)
    const windowHeight = $window.height() - 40
    const scroll = windowHeight + $window.scrollTop()
    const pos = $element.offset().top + $element.height()
    if (scroll < pos) {
        $window.scrollTop(pos - windowHeight)
    }
}
<commit_msg>Exclude svg images with empty latex<commit_after>import $ from 'jquery'
import sanitizeHtml from 'sanitize-html'
import * as sanitizeOpts from './sanitizeOpts'

export const equationImageSelector =
    'img[src^="/math.svg?latex="]:not(img[src="/math.svg?latex="]), img[src^="data:image/svg+xml"]'
const screenshotImageSelector = 'img[src^="/screenshot/"], img[src^="data:image/png"]'

function convertLinksToRelative(html) {
    return html.replace(new RegExp(document.location.origin, 'g'), '')
}

export function sanitize(html) {
    return sanitizeHtml(convertLinksToRelative(html), sanitizeOpts)
}
export function insertToTextAreaAtCursor(field, value) {
    const startPos = field.selectionStart
    const endPos = field.selectionEnd
    let oldValue = field.value
    field.value = oldValue.substring(0, startPos) + value + oldValue.substring(endPos, oldValue.length)
    field.selectionStart = field.selectionEnd = startPos + value.length
}

export function isKey(e, key) {
    return preventIfTrue(e, !e.altKey && !e.shiftKey && !e.ctrlKey && keyOrKeyCode(e, key))
}

export function isCtrlKey(e, key) {
    return preventIfTrue(e, !e.altKey && !e.shiftKey && e.ctrlKey && keyOrKeyCode(e, key))
}

function keyOrKeyCode(e, val) {
    return typeof val === 'string' ? e.key === val : e.keyCode === val
}
function preventIfTrue(e, val) {
    if (val) e.preventDefault()
    return val
}

export function sanitizeContent(answerElement) {
    const $answerElement = $(answerElement)
    const $mathEditor = $answerElement.find('[data-js="mathEditor"]')
    const scrollPos = $(window).scrollTop()
    $mathEditor.hide()
    const text = $answerElement.get(0).innerText
    $mathEditor.show()
    $(window).scrollTop(scrollPos)

    const html = sanitize($answerElement.html())

    const answerConsideredEmpty =
        text.trim().length +
            $answerElement.find(equationImageSelector).length +
            $answerElement.find(screenshotImageSelector).length ===
        0

    return {
        answerHTML: answerConsideredEmpty ? '' : html,
        answerText: text,
        imageCount: existingScreenshotCount($(`<div>${html}</div>`))
    }
}

export function setCursorAfter($img) {
    const range = document.createRange()
    const img = $img.get(0)
    range.setStartAfter(img)
    const sel = window.getSelection()
    sel.removeAllRanges()
    sel.addRange(range)
}

export function existingScreenshotCount($editor) {
    const imageCount = $editor.find('img').length
    const emptyImageCount = $editor.find('img[src=""]').length
    const equationCount = $editor.find(equationImageSelector).length
    return imageCount - equationCount - emptyImageCount
}

export function scrollIntoView($element) {
    const $window = $(window)
    const windowHeight = $window.height() - 40
    const scroll = windowHeight + $window.scrollTop()
    const pos = $element.offset().top + $element.height()
    if (scroll < pos) {
        $window.scrollTop(pos - windowHeight)
    }
}
<|endoftext|>