<commit_before>// Copyright 2018-2020, University of Colorado Boulder

/**
 * Standard PhET button for 'refresh'.
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */

import InstanceRegistry from '../../../phet-core/js/documentation/InstanceRegistry.js';
import merge from '../../../phet-core/js/merge.js';
import RectangularPushButton from '../../../sun/js/buttons/RectangularPushButton.js';
import FontAwesomeNode from '../../../sun/js/FontAwesomeNode.js';
import PhetColorScheme from '../PhetColorScheme.js';
import sceneryPhet from '../sceneryPhet.js';

class RefreshButton extends RectangularPushButton {

  /**
   * @param {Object} [options]
   */
  constructor( options ) {

    options = merge( {
      baseColor: PhetColorScheme.BUTTON_YELLOW,
      iconScale: 1
    }, options );

    assert && assert( !options.content, 'RefreshButton sets content' );
    options.content = new FontAwesomeNode( 'refresh', {
      scale: options.iconScale
    } );

    super( options );

    // support for binder documentation, stripped out in builds and only runs when ?binder is specified
    assert && phet.chipper.queryParameters.binder && InstanceRegistry.registerDataURL( 'scenery-phet', 'RefreshButton', this );
  }
}

sceneryPhet.register( 'RefreshButton', RefreshButton );
export default RefreshButton;<commit_msg>change RefreshButton API from iconScale to iconHeight, https://github.com/phetsims/scenery-phet/issues/685<commit_after>// Copyright 2018-2020, University of Colorado Boulder

/**
 * Standard PhET button for 'refresh'.
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */

import InstanceRegistry from '../../../phet-core/js/documentation/InstanceRegistry.js';
import merge from '../../../phet-core/js/merge.js';
import Path from '../../../scenery/js/nodes/Path.js';
import syncAltSolidShape from '../../../sherpa/js/fontawesome-5/syncAltSolidShape.js';
import RectangularPushButton from '../../../sun/js/buttons/RectangularPushButton.js';
import PhetColorScheme from '../PhetColorScheme.js';
import sceneryPhet from '../sceneryPhet.js';

class RefreshButton extends RectangularPushButton {

  /**
   * @param {Object} [options]
   */
  constructor( options ) {

    options = merge( {
      baseColor: PhetColorScheme.BUTTON_YELLOW,
      iconHeight: 35
    }, options );

    assert && assert( !options.content, 'RefreshButton sets content' );
    options.content = new Path( syncAltSolidShape, {
      fill: 'black'
    } );
    options.content.setScaleMagnitude( options.iconHeight / options.content.height );

    super( options );

    // support for binder documentation, stripped out in builds and only runs when ?binder is specified
    assert && phet.chipper.queryParameters.binder && InstanceRegistry.registerDataURL( 'scenery-phet', 'RefreshButton', this );
  }
}

sceneryPhet.register( 'RefreshButton', RefreshButton );
export default RefreshButton;<|endoftext|>


<commit_before>(function() {

var enableOnReadyConsoleProfile = false;

/* fn: fn,
 * scope: scope,
 * options: options || {},
 * type: [jquery|ext],
 * num: unique number, //used to mark in initDone
 * selector: selector, // null if onContentReady
 * */
var readyElHandlers = []; //for onElement*
var onReadyState;  //if callOnContentReady should skip 'defer' callbacks or execute only 'defer' callbacks
                   //used on initial ready
var deferredStart = null; //used for timing deferred, required here because of multiple chunks
var onReadyIsCalling = false; //true while callOnContentReady is processing onReadyElQueue and we can add more to queue
var onReadyElQueue = []; //queue for onElementReady/Show/Hide/WidthChange calls
var elCacheBySelector = {};

if (!Kwf.isApp) {
    $(document).ready(function() {
        if (!document.body) {
            //this happens if a redirect by changing location in JS is done
            //in that case no contentReady needs to be called
            return;
        }
        var t = Kwf.Utils.BenchmarkBox.now();
        if (enableOnReadyConsoleProfile) console.profile("callOnContentReady body");
        onReadyState = 'callNonDefer';
        Kwf.callOnContentReady(document.body, { action: 'render' });
        onReadyState = 'calledNonDefer';
        if (enableOnReadyConsoleProfile) console.profileEnd();
        Kwf.Utils.BenchmarkBox.time('time', Kwf.Utils.BenchmarkBox.now()-t);
        Kwf.Utils.BenchmarkBox.create({
            counters: Kwf._onReadyStats,
            type: 'onReady'
        });
        setTimeout(function() {
            deferredStart = Kwf.Utils.BenchmarkBox.now();
            if (enableOnReadyConsoleProfile) console.profile("callOnContentReady body deferred");
            onReadyState = 'callDefer';
            Kwf.callOnContentReady(document.body, { action: 'render' });
            onReadyState = 'calledDefer';
        }, 10);

        var timeoutId;
        $(window).resize(function() {
            if (timeoutId) {
                clearTimeout(timeoutId);
            }
            timeoutId = setTimeout(function() {
                Kwf.callOnContentReady(document.body, { action: 'widthChange' } );
            }, 100);
        });
    });
}

/**
 * Register a function that will be called when content is loaded or shown
 * @param callback function (passed arguments: el, options (newRender=bool))
 * @param options supported are: priority (integer, higher number means it's called after all with lower number, default 0)
 */
Kwf.onContentReady = function(fn, options) {
    if (arguments.length == 3) {
        var scope = arguments[1];
        var options = arguments[2];
        options.scope = scope;
    }
    Kwf._addReadyHandler(null, 'contentReady', null, fn, options);
};

var deferHandlerNum = null;
Kwf._addReadyHandler = function(type, onAction, selector, fn, options)
{
    if (!options) options = {};
    if (typeof options.defer == 'undefined') options.defer = true; //default defer=true
    readyElHandlers.push({
        selector: selector,
        fn: fn,
        options: options,
        num: readyElHandlers.length, //unique number
        type: type,
        onAction: onAction
    });
    //if initial call is already done redo for new added handlers
    if (onReadyState == 'calledDefer' || (!(options && options.defer) && onReadyState == 'calledNonDefer')) {
        if (!deferHandlerNum) {
            deferHandlerNum = [];
            setTimeout(function() {
                //additionally added handlers need to be called async so priorty can be used correctly (we wait to get more handlers added)
                //needed for Frontend.defer.js
                var hndlerNum = deferHandlerNum;
                deferHandlerNum = null; //set to null before calling callOnContentReady as that might cause _addReadyHandler calls
                Kwf.callOnContentReady(document.body, { action: 'render', handlerNum: hndlerNum });
            }, 1);
        }
        deferHandlerNum.push(readyElHandlers.length-1);
    }
};

/**
 * @param element the added/changed dom element
 * @param options newRender (bool): if new elements have been added to the dom or just visiblity/width changed
 */
Kwf.callOnContentReady = function(renderedEl, options)
{
    Kwf.Utils.BenchmarkBox.count('callOnContentReady');
    if (!options) options = {};
    if (typeof options.newRender != 'undefined') {
        //backwards compatibility, for callOnContentReady call
        options.action = options.newRender ? 'render' : 'show';
        delete options.newRender;
    }
    if (!options.action) {
        if (typeof console != 'undefined' && console.warn) console.warn('Please set option action on callOnContentReady');
        options.action = 'render';
    }
    if (!renderedEl) {
        if (typeof console != 'undefined' && console.warn) console.warn('Please pass element argument on callOnContentReady');
        renderedEl = document.body;
    }
    if (typeof Ext2 != 'undefined' && Ext2.Element && renderedEl instanceof Ext2.Element) renderedEl = renderedEl.dom;
    if (jQuery && renderedEl instanceof jQuery) {
        renderedEl.each(function(){ Kwf.callOnContentReady(this, options); });
        return;
    }

    //add entries to _onReadyElQueue, depending on renderedEl
    var onActions;
    if (options.action == 'render') {
        onActions = ['render', 'show', 'widthChange', 'contentReady'];
    } else if (options.action == 'show') {
        onActions = ['show', 'widthChange', 'contentReady'];
    } else if (options.action == 'hide') {
        onActions = ['hide'];
    } else if (options.action == 'widthChange') {
        onActions = ['widthChange', 'contentReady'];
    }

    var html = false;
    for (var i = 0; i < readyElHandlers.length; i++) {
        var hndl = readyElHandlers[i];
        if (options.handlerNum && options.handlerNum.indexOf(hndl.num) == -1) {
            continue;
        }

        //onReadyState gets set before callOnContentReady(body)
        //can not be part of options as it would be missing in recursive calls
        if (onReadyState == 'callNonDefer') {
            if (hndl.options.defer) {
                continue;
            }
        } else if (onReadyState == 'callDefer') {
            if (!hndl.options.defer) {
                continue;
            }
        }

        if (hndl.options.checkVisibility) {
            if (renderedEl != document.body && !Kwf.Utils.Element.isVisible(renderedEl)) {
                continue;
            }
            //if checkVisibility is activated, don't skip based on onActions as
            //even a widthChange action could make an element visible (media queries)
        } else {
            if (onActions.indexOf(hndl.onAction) == -1) {
                continue;
            }
        }

        if (options.action == 'render' && !html) {
            var t = Kwf.Utils.BenchmarkBox.now();
            html = renderedEl.innerHTML;
            Kwf.Utils.BenchmarkBox.time('innerHTML', Kwf.Utils.BenchmarkBox.now()-t);
        }

        var useSelectorCache;
        if (options.action != 'render' || !hndl.selector) {
            useSelectorCache = true;
        } else {
            if (onReadyState == 'callDefer' && renderedEl == document.body && elCacheBySelector[hndl.selector]) {
                useSelectorCache = true;
            } else {
                var t = Kwf.Utils.BenchmarkBox.now();
                var m = hndl.selector.match(/^[a-z]*\.([a-z]+)/i);
                //do a stupid text search on the selector, using that we can skip query for many selectors that don't exist in the current el
                if (m && html.indexOf(m[1]) == -1) {
                    useSelectorCache = true;
                    if (!elCacheBySelector[hndl.selector]) {
                        elCacheBySelector[hndl.selector] = [];
                    }
                } else {
                    useSelectorCache = false;
                }
                Kwf.Utils.BenchmarkBox.time('checkInnerHtml', Kwf.Utils.BenchmarkBox.now()-t);
            }
        }
        if (useSelectorCache && elCacheBySelector[hndl.selector]) {
            Kwf.Utils.BenchmarkBox.count('queryCache');
            var els = [];
            for (var j=0; j<elCacheBySelector[hndl.selector].length; j++) {
                if (renderedEl == document.body || $.contains(renderedEl, elCacheBySelector[hndl.selector][j])) {
                    els.push(elCacheBySelector[hndl.selector][j]);
                }
            }
        } else if (!hndl.selector) {
            var els = $.makeArray($(renderedEl));
        } else {
            var t = Kwf.Utils.BenchmarkBox.now();
            var els = $.makeArray($(renderedEl).find(hndl.selector));
            Kwf.Utils.BenchmarkBox.time('query', Kwf.Utils.BenchmarkBox.now() - t);
            if (!elCacheBySelector[hndl.selector]) {
                elCacheBySelector[hndl.selector] = els;
            } else {
                for(var j=0; j<els.length; ++j) {
                    if (elCacheBySelector[hndl.selector].indexOf(els[j]) == -1) {
                        elCacheBySelector[hndl.selector].push(els[j]);
                    }
                }
            }
        }

        for (var j = 0; j< els.length; ++j) {

            var alreadyInQueue = false;
            Kwf._onReadyElQueue.each(function(queueEntry) {
                if (queueEntry.num == hndl.num && els[j] == queueEntry.el) {
                    alreadyInQueue = true;
                }
            });

            if (!alreadyInQueue) {
                var parentsCount = 0;
                var n = els[j];
                while (n = n.parentNode) {
                    parentsCount++;
                }
                Kwf.Utils.BenchmarkBox.count('readyEl');
                onReadyElQueue.push({
                    el: els[j],
                    fn: hndl.fn,
                    options: hndl.options,
                    num: hndl.num,
                    type: hndl.type,
                    callerOptions: options,
                    onAction: hndl.onAction,
                    selector: hndl.selector,
                    priority: hndl.options.priority || 0,
                    parentsCount: parentsCount
                });
            }
        }
    }

    //sort _onReadyElQueue
    var t = Kwf.Utils.BenchmarkBox.now();
    onReadyElQueue.sort(function sortOnReadyElQueue(a, b) {
        if (a.priority != b.priority) {
            return a.priority - b.priority;
        } else {
            if (a.parentsCount != b.parentsCount) {
                return a.parentsCount - b.parentsCount;
            } else {
                return a.num - b.num;
            }
        }
    });
    Kwf.Utils.BenchmarkBox.time('sort', Kwf.Utils.BenchmarkBox.now() - t);

    if (onReadyIsCalling) {
        return;
    }

    onReadyIsCalling = true;

    //call the callback of an element ready handler
    function callQueueFn(queueEntry, config)
    {
        var t = Kwf.Utils.BenchmarkBox.now();
        var el = queueEntry.el;
        if (queueEntry.type == 'ext2') {
            el = Ext2.get(el);
        } else if (queueEntry.type == 'jquery') {
            el = $(el);
        }
        queueEntry.fn.call(queueEntry.options.scope || window, el, config);
        var fnName = queueEntry.fn.name;
        if (!fnName) {
            fnName = 'unknown';
        }

        Kwf.Utils.BenchmarkBox.subTime(
            'on'+queueEntry.onAction.charAt(0).toUpperCase() + queueEntry.onAction.slice(1),
            'fn: '+fnName,
            Kwf.Utils.BenchmarkBox.now()-t
        );
    };

    //process one entry of the readyElQueue
    //own function so it can be called in sync or in deferred chunks
    function processOnReadyElQueueEntry()
    {
        var queueEntry = onReadyElQueue.shift();
        var el = queueEntry.el;
        if (queueEntry.onAction == 'render') {
            if (queueEntry.options.checkVisibility && !Kwf.Utils.Element.isVisible(el)) {
                return;
            }
            if (!el.initDone) el.initDone = {};
            if (el.initDone[queueEntry.num]) {
                return;
            }
            el.initDone[queueEntry.num] = true;
            var config = {};
            var configEl = $(el).find('> input[type="hidden"]');
            if (configEl.length) {
                try {
                    var v = configEl.get(0).value;
                    if (v.substr(0, 1) == '{' || v.substr(0, 1) == '[') {
                        config = $.parseJSON(v);
                    }
                } catch (err) {}
            }
            callQueueFn(queueEntry, config);
        } else if (queueEntry.onAction == 'show') {
            if (Kwf.Utils.Element.isVisible(el)) {
                callQueueFn(queueEntry);
            }
        } else if (queueEntry.onAction == 'hide') {
            if (!Kwf.Utils.Element.isVisible(el)) {
                callQueueFn(queueEntry);
            }
        } else if (queueEntry.onAction == 'widthChange') {
            if (!queueEntry.options.checkVisibility || Kwf.Utils.Element.isVisible(el)) {
                callQueueFn(queueEntry);
            }
        } else if (queueEntry.onAction == 'contentReady') {
            var options = {
                newRender: (queueEntry.callerOptions.action == 'render'),
                action: queueEntry.callerOptions.action
            };
            callQueueFn(queueEntry, options);
        }
    }

    if (onReadyState == 'callDefer') {
        var processNext = function processNext() {
            Kwf.Utils.BenchmarkBox.count('chunks');
            var t = Kwf.Utils.BenchmarkBox.now();
            while (onReadyElQueue.length && Kwf.Utils.BenchmarkBox.now()-t < 50) {
                processOnReadyElQueueEntry();
            }
            if (onReadyElQueue.length) {
                setTimeout(processNext, 1);
            } else {
                onReadyIsCalling = false;
                Kwf.Utils.BenchmarkBox.time('time', Kwf.Utils.BenchmarkBox.now()-deferredStart);
                if (enableOnReadyConsoleProfile) console.profileEnd();
                Kwf.Utils.BenchmarkBox.create({
                    counters: Kwf._onReadyStats,
                    type: 'onReady defer'
                });
            }
        };
        processNext();
    } else {
        while (onReadyElQueue.length) {
            processOnReadyElQueueEntry();
        }
        onReadyIsCalling = false;
    }

};

})();
<commit_msg>fix merge error, var got renamed<commit_after>(function() {

var enableOnReadyConsoleProfile = false;

/* fn: fn,
 * scope: scope,
 * options: options || {},
 * type: [jquery|ext],
 * num: unique number, //used to mark in initDone
 * selector: selector, // null if onContentReady
 * */
var readyElHandlers = []; //for onElement*
var onReadyState;  //if callOnContentReady should skip 'defer' callbacks or execute only 'defer' callbacks
                   //used on initial ready
var deferredStart = null; //used for timing deferred, required here because of multiple chunks
var onReadyIsCalling = false; //true while callOnContentReady is processing onReadyElQueue and we can add more to queue
var onReadyElQueue = []; //queue for onElementReady/Show/Hide/WidthChange calls
var elCacheBySelector = {};

if (!Kwf.isApp) {
    $(document).ready(function() {
        if (!document.body) {
            //this happens if a redirect by changing location in JS is done
            //in that case no contentReady needs to be called
            return;
        }
        var t = Kwf.Utils.BenchmarkBox.now();
        if (enableOnReadyConsoleProfile) console.profile("callOnContentReady body");
        onReadyState = 'callNonDefer';
        Kwf.callOnContentReady(document.body, { action: 'render' });
        onReadyState = 'calledNonDefer';
        if (enableOnReadyConsoleProfile) console.profileEnd();
        Kwf.Utils.BenchmarkBox.time('time', Kwf.Utils.BenchmarkBox.now()-t);
        Kwf.Utils.BenchmarkBox.create({
            counters: Kwf._onReadyStats,
            type: 'onReady'
        });
        setTimeout(function() {
            deferredStart = Kwf.Utils.BenchmarkBox.now();
            if (enableOnReadyConsoleProfile) console.profile("callOnContentReady body deferred");
            onReadyState = 'callDefer';
            Kwf.callOnContentReady(document.body, { action: 'render' });
            onReadyState = 'calledDefer';
        }, 10);

        var timeoutId;
        $(window).resize(function() {
            if (timeoutId) {
                clearTimeout(timeoutId);
            }
            timeoutId = setTimeout(function() {
                Kwf.callOnContentReady(document.body, { action: 'widthChange' } );
            }, 100);
        });
    });
}

/**
 * Register a function that will be called when content is loaded or shown
 * @param callback function (passed arguments: el, options (newRender=bool))
 * @param options supported are: priority (integer, higher number means it's called after all with lower number, default 0)
 */
Kwf.onContentReady = function(fn, options) {
    if (arguments.length == 3) {
        var scope = arguments[1];
        var options = arguments[2];
        options.scope = scope;
    }
    Kwf._addReadyHandler(null, 'contentReady', null, fn, options);
};

var deferHandlerNum = null;
Kwf._addReadyHandler = function(type, onAction, selector, fn, options)
{
    if (!options) options = {};
    if (typeof options.defer == 'undefined') options.defer = true; //default defer=true
    readyElHandlers.push({
        selector: selector,
        fn: fn,
        options: options,
        num: readyElHandlers.length, //unique number
        type: type,
        onAction: onAction
    });
    //if initial call is already done redo for new added handlers
    if (onReadyState == 'calledDefer' || (!(options && options.defer) && onReadyState == 'calledNonDefer')) {
        if (!deferHandlerNum) {
            deferHandlerNum = [];
            setTimeout(function() {
                //additionally added handlers need to be called async so priorty can be used correctly (we wait to get more handlers added)
                //needed for Frontend.defer.js
                var hndlerNum = deferHandlerNum;
                deferHandlerNum = null; //set to null before calling callOnContentReady as that might cause _addReadyHandler calls
                Kwf.callOnContentReady(document.body, { action: 'render', handlerNum: hndlerNum });
            }, 1);
        }
        deferHandlerNum.push(readyElHandlers.length-1);
    }
};

/**
 * @param element the added/changed dom element
 * @param options newRender (bool): if new elements have been added to the dom or just visiblity/width changed
 */
Kwf.callOnContentReady = function(renderedEl, options)
{
    Kwf.Utils.BenchmarkBox.count('callOnContentReady');
    if (!options) options = {};
    if (typeof options.newRender != 'undefined') {
        //backwards compatibility, for callOnContentReady call
        options.action = options.newRender ? 'render' : 'show';
        delete options.newRender;
    }
    if (!options.action) {
        if (typeof console != 'undefined' && console.warn) console.warn('Please set option action on callOnContentReady');
        options.action = 'render';
    }
    if (!renderedEl) {
        if (typeof console != 'undefined' && console.warn) console.warn('Please pass element argument on callOnContentReady');
        renderedEl = document.body;
    }
    if (typeof Ext2 != 'undefined' && Ext2.Element && renderedEl instanceof Ext2.Element) renderedEl = renderedEl.dom;
    if (jQuery && renderedEl instanceof jQuery) {
        renderedEl.each(function(){ Kwf.callOnContentReady(this, options); });
        return;
    }

    //add entries to onReadyElQueue, depending on renderedEl
    var onActions;
    if (options.action == 'render') {
        onActions = ['render', 'show', 'widthChange', 'contentReady'];
    } else if (options.action == 'show') {
        onActions = ['show', 'widthChange', 'contentReady'];
    } else if (options.action == 'hide') {
        onActions = ['hide'];
    } else if (options.action == 'widthChange') {
        onActions = ['widthChange', 'contentReady'];
    }

    var html = false;
    for (var i = 0; i < readyElHandlers.length; i++) {
        var hndl = readyElHandlers[i];
        if (options.handlerNum && options.handlerNum.indexOf(hndl.num) == -1) {
            continue;
        }

        //onReadyState gets set before callOnContentReady(body)
        //can not be part of options as it would be missing in recursive calls
        if (onReadyState == 'callNonDefer') {
            if (hndl.options.defer) {
                continue;
            }
        } else if (onReadyState == 'callDefer') {
            if (!hndl.options.defer) {
                continue;
            }
        }

        if (hndl.options.checkVisibility) {
            if (renderedEl != document.body && !Kwf.Utils.Element.isVisible(renderedEl)) {
                continue;
            }
            //if checkVisibility is activated, don't skip based on onActions as
            //even a widthChange action could make an element visible (media queries)
        } else {
            if (onActions.indexOf(hndl.onAction) == -1) {
                continue;
            }
        }

        if (options.action == 'render' && !html) {
            var t = Kwf.Utils.BenchmarkBox.now();
            html = renderedEl.innerHTML;
            Kwf.Utils.BenchmarkBox.time('innerHTML', Kwf.Utils.BenchmarkBox.now()-t);
        }

        var useSelectorCache;
        if (options.action != 'render' || !hndl.selector) {
            useSelectorCache = true;
        } else {
            if (onReadyState == 'callDefer' && renderedEl == document.body && elCacheBySelector[hndl.selector]) {
                useSelectorCache = true;
            } else {
                var t = Kwf.Utils.BenchmarkBox.now();
                var m = hndl.selector.match(/^[a-z]*\.([a-z]+)/i);
                //do a stupid text search on the selector, using that we can skip query for many selectors that don't exist in the current el
                if (m && html.indexOf(m[1]) == -1) {
                    useSelectorCache = true;
                    if (!elCacheBySelector[hndl.selector]) {
                        elCacheBySelector[hndl.selector] = [];
                    }
                } else {
                    useSelectorCache = false;
                }
                Kwf.Utils.BenchmarkBox.time('checkInnerHtml', Kwf.Utils.BenchmarkBox.now()-t);
            }
        }
        if (useSelectorCache && elCacheBySelector[hndl.selector]) {
            Kwf.Utils.BenchmarkBox.count('queryCache');
            var els = [];
            for (var j=0; j<elCacheBySelector[hndl.selector].length; j++) {
                if (renderedEl == document.body || $.contains(renderedEl, elCacheBySelector[hndl.selector][j])) {
                    els.push(elCacheBySelector[hndl.selector][j]);
                }
            }
        } else if (!hndl.selector) {
            var els = $.makeArray($(renderedEl));
        } else {
            var t = Kwf.Utils.BenchmarkBox.now();
            var els = $.makeArray($(renderedEl).find(hndl.selector));
            Kwf.Utils.BenchmarkBox.time('query', Kwf.Utils.BenchmarkBox.now() - t);
            if (!elCacheBySelector[hndl.selector]) {
                elCacheBySelector[hndl.selector] = els;
            } else {
                for(var j=0; j<els.length; ++j) {
                    if (elCacheBySelector[hndl.selector].indexOf(els[j]) == -1) {
                        elCacheBySelector[hndl.selector].push(els[j]);
                    }
                }
            }
        }

        for (var j = 0; j< els.length; ++j) {

            var alreadyInQueue = false;
            onReadyElQueue.each(function(queueEntry) {
                if (queueEntry.num == hndl.num && els[j] == queueEntry.el) {
                    alreadyInQueue = true;
                }
            });

            if (!alreadyInQueue) {
                var parentsCount = 0;
                var n = els[j];
                while (n = n.parentNode) {
                    parentsCount++;
                }
                Kwf.Utils.BenchmarkBox.count('readyEl');
                onReadyElQueue.push({
                    el: els[j],
                    fn: hndl.fn,
                    options: hndl.options,
                    num: hndl.num,
                    type: hndl.type,
                    callerOptions: options,
                    onAction: hndl.onAction,
                    selector: hndl.selector,
                    priority: hndl.options.priority || 0,
                    parentsCount: parentsCount
                });
            }
        }
    }

    //sort onReadyElQueue
    var t = Kwf.Utils.BenchmarkBox.now();
    onReadyElQueue.sort(function sortOnReadyElQueue(a, b) {
        if (a.priority != b.priority) {
            return a.priority - b.priority;
        } else {
            if (a.parentsCount != b.parentsCount) {
                return a.parentsCount - b.parentsCount;
            } else {
                return a.num - b.num;
            }
        }
    });
    Kwf.Utils.BenchmarkBox.time('sort', Kwf.Utils.BenchmarkBox.now() - t);

    if (onReadyIsCalling) {
        return;
    }

    onReadyIsCalling = true;

    //call the callback of an element ready handler
    function callQueueFn(queueEntry, config)
    {
        var t = Kwf.Utils.BenchmarkBox.now();
        var el = queueEntry.el;
        if (queueEntry.type == 'ext2') {
            el = Ext2.get(el);
        } else if (queueEntry.type == 'jquery') {
            el = $(el);
        }
        queueEntry.fn.call(queueEntry.options.scope || window, el, config);
        var fnName = queueEntry.fn.name;
        if (!fnName) {
            fnName = 'unknown';
        }

        Kwf.Utils.BenchmarkBox.subTime(
            'on'+queueEntry.onAction.charAt(0).toUpperCase() + queueEntry.onAction.slice(1),
            'fn: '+fnName,
            Kwf.Utils.BenchmarkBox.now()-t
        );
    };

    //process one entry of the readyElQueue
    //own function so it can be called in sync or in deferred chunks
    function processOnReadyElQueueEntry()
    {
        var queueEntry = onReadyElQueue.shift();
        var el = queueEntry.el;
        if (queueEntry.onAction == 'render') {
            if (queueEntry.options.checkVisibility && !Kwf.Utils.Element.isVisible(el)) {
                return;
            }
            if (!el.initDone) el.initDone = {};
            if (el.initDone[queueEntry.num]) {
                return;
            }
            el.initDone[queueEntry.num] = true;
            var config = {};
            var configEl = $(el).find('> input[type="hidden"]');
            if (configEl.length) {
                try {
                    var v = configEl.get(0).value;
                    if (v.substr(0, 1) == '{' || v.substr(0, 1) == '[') {
                        config = $.parseJSON(v);
                    }
                } catch (err) {}
            }
            callQueueFn(queueEntry, config);
        } else if (queueEntry.onAction == 'show') {
            if (Kwf.Utils.Element.isVisible(el)) {
                callQueueFn(queueEntry);
            }
        } else if (queueEntry.onAction == 'hide') {
            if (!Kwf.Utils.Element.isVisible(el)) {
                callQueueFn(queueEntry);
            }
        } else if (queueEntry.onAction == 'widthChange') {
            if (!queueEntry.options.checkVisibility || Kwf.Utils.Element.isVisible(el)) {
                callQueueFn(queueEntry);
            }
        } else if (queueEntry.onAction == 'contentReady') {
            var options = {
                newRender: (queueEntry.callerOptions.action == 'render'),
                action: queueEntry.callerOptions.action
            };
            callQueueFn(queueEntry, options);
        }
    }

    if (onReadyState == 'callDefer') {
        var processNext = function processNext() {
            Kwf.Utils.BenchmarkBox.count('chunks');
            var t = Kwf.Utils.BenchmarkBox.now();
            while (onReadyElQueue.length && Kwf.Utils.BenchmarkBox.now()-t < 50) {
                processOnReadyElQueueEntry();
            }
            if (onReadyElQueue.length) {
                setTimeout(processNext, 1);
            } else {
                onReadyIsCalling = false;
                Kwf.Utils.BenchmarkBox.time('time', Kwf.Utils.BenchmarkBox.now()-deferredStart);
                if (enableOnReadyConsoleProfile) console.profileEnd();
                Kwf.Utils.BenchmarkBox.create({
                    counters: Kwf._onReadyStats,
                    type: 'onReady defer'
                });
            }
        };
        processNext();
    } else {
        while (onReadyElQueue.length) {
            processOnReadyElQueueEntry();
        }
        onReadyIsCalling = false;
    }

};

})();
<|endoftext|>


<commit_before><commit_msg>componentizd!<commit_after><|endoftext|>


<commit_before>/**
 * Created by zhaoangyouyou on 11/12/2016.
 */
var VoiceTime=0, startTime = 0, endTime = 0;
var voice = {
    localId: '',
    serverId: ''
};

$(function(){
    $("#pushMe").on({
        touchstart: function(e){
            document.getElementById('pushMe').innerText = "发表言论";

            startTime = new Date().getTime();
            wx.startRecord({
                cancel: function () {
                    alert('用户拒绝授权录音');
                }
            });

            e.preventDefault();
        },
        touchmove: function(e){

            /*判断手指是否滑出*/
            var endx, endy;
            var x = document.getElementById('pushMe').offsetLeft, y = document.getElementById('pushMe').offsetTop;
            e.preventDefault();
            endx=e.changedTouches[0].clientX;
            endy=e.changedTouches[0].clientY;
            if(endx < x||endx > (x+205)||endy > (y+75)||endy<y){
                //clearInterval(timeOutEvent);
                document.getElementById('pushMe').innerText = "松开结束";
            }
            else{}

        },
        touchend: function(e){

            endTime = new Date().getTime();

            /*停止录音*/
            wx.stopRecord({
                success: function (res) {
                    voice.localId = res.localId;
                }
            });
            if(voice.localId != '')
            {
                alert("success");

            }

            document.getElementById('pushMe').innerText = "按我";
            e.preventDefault();

            VoiceTime = (endTime - startTime) / 1000;
            /*上传录音到服务器*/
            if (/*voice.localId*/ VoiceTime < 1 ) {
                alert("时间过短，请重新录制!");
                return;
            }

            wx.uploadVoice({
                localId: voice.localId,
                success: function (res) {
                    voice.serverId = res.serverId;
                }
            });

            $.get('http://rabbit.neverstar.top/media_info/write?voice_time=' + VoiceTime);

            VoiceTime = 0;
        }
    })

});

<commit_msg>这样修bug调试也是会爆的啊<commit_after>/**
 * Created by zhaoangyouyou on 11/12/2016.
 */
var VoiceTime=0, startTime = 0, endTime = 0;
var voice = {
    localId: '',
    serverId: ''
};

$(function(){
    $("#pushMe").on({
        touchstart: function(e){
            document.getElementById('pushMe').innerText = "发表言论";

            startTime = new Date().getTime();
            wx.startRecord({
                cancel: function () {
                    alert('用户拒绝授权录音');
                }
            });

            e.preventDefault();
        },
        touchmove: function(e){

            /*判断手指是否滑出*/
            var endx, endy;
            var x = document.getElementById('pushMe').offsetLeft, y = document.getElementById('pushMe').offsetTop;
            e.preventDefault();
            endx=e.changedTouches[0].clientX;
            endy=e.changedTouches[0].clientY;
            if(endx < x||endx > (x+205)||endy > (y+75)||endy<y){
                //clearInterval(timeOutEvent);
                document.getElementById('pushMe').innerText = "松开结束";
            }
            else{}

        },
        touchend: function(e){

            endTime = new Date().getTime();

            /*停止录音*/
            wx.stopRecord({
                success: function (res) {
                    voice.localId = res.localId;
                    alert(res.localID);
                }
            });

            document.getElementById('pushMe').innerText = "按我";
            e.preventDefault();

            VoiceTime = (endTime - startTime) / 1000;
            /*上传录音到服务器*/
            if (/*voice.localId*/ VoiceTime < 1 ) {
                alert("时间过短，请重新录制!");
                return;
            }

            wx.uploadVoice({
                localId: voice.localId,
                success: function (res) {
                    voice.serverId = res.serverId;
                }
            });

            $.get('http://rabbit.neverstar.top/media_info/write?voice_time=' + VoiceTime);

            VoiceTime = 0;
        }
    })

});

<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import {graphql} from 'react-apollo'
import compose from 'util/compose'
import gql from 'graphql-tag'
import BaseLayout from 'client/components/layout/BaseLayout'
import {
    SimpleButton,
    SimpleDialog,
    Typography,
    TextField,
    Divider,
    DeleteIconButton,
    Chip,
    SimpleList,
    Row,
    Col
} from 'ui/admin'
import FileDrop from 'client/components/FileDrop'
import Util from 'client/util'
import config from 'gen/config'

const {BACKUP_URL} = config

class DbDumpContainer extends React.Component {

    constructor(props) {
        super(props)

        this.state = {
            creatingDump: false,
            creatingMediaDump: false,
            importingDbDump: false,
            importingMediaDump: false,
            importMediaDumpDialog: false,
            importDbDumpDialog: false
        }
    }

    createDump() {
        this.setState({creatingDump: true})
        this.props.createDbDump().then(e => {
            console.log(e)
            this.setState({creatingDump: false})
        })

    }

    createMediaDump() {
        this.setState({creatingMediaDump: true})
        this.props.createMediaDump().then(e => {
            console.log(e)
            this.setState({creatingMediaDump: false})
        })

    }

    importMediaDump() {
        this.setState({importMediaDumpDialog: true})
    }

    importDbDump() {
        this.setState({importDbDumpDialog: true})
    }

    handleConfirmMediaDialog() {
        this.setState({importMediaDumpDialog: false})
    }

    handleConfirmDbDialog() {
        this.setState({importDbDumpDialog: false})
    }

    handleMediaDumpUpload(e) {
        console.log(e)
    }

    download(content, filename, contentType) {
        if (!contentType) contentType = 'application/octet-stream';
        var a = document.createElement('a');
        var blob = new Blob([content], {'type': contentType});
        a.href = window.URL.createObjectURL(blob);
        a.download = filename;
        a.click();
    }

    render() {
        const {dbDumps, mediaDumps} = this.props
        const {creatingDump, creatingMediaDump, importingMediaDump, importMediaDumpDialog, importDbDumpDialog, importingDbDump} = this.state
        return (
            <BaseLayout>
                <Typography variant="h3" gutterBottom>Backups</Typography>

                <Row spacing={4}>
                    <Col md={6}>

                        <SimpleButton variant="contained" color="primary"
                                      showProgress={creatingDump}
                                      onClick={this.createDump.bind(this)}>{creatingDump ? 'Dump is beeing created' : 'Create new db dump'}</SimpleButton>

                        <SimpleButton color="secondary"
                                      disabled={importDbDumpDialog}
                                      showProgress={importingDbDump}
                                      onClick={this.importDbDump.bind(this)}>{importingDbDump ? 'Dump is beeing restored' : 'Restore db dump'}</SimpleButton>

                        {dbDumps && dbDumps.results && dbDumps.results.length > 0 &&
                        <SimpleList items={dbDumps.results.reduce((a, i) => {
                            a.push({
                                primary: i.name,
                                onClick: () => {

                                    const xhr = new XMLHttpRequest

                                    xhr.open("GET", BACKUP_URL + '/dbdumps/' + i.name)
                                    xhr.responseType = 'blob'

                                    xhr.addEventListener("load", (e) => {
                                        if (xhr.status === 200) {

                                            this.download(xhr.response, 'backup.gz', 'application/gzip')
                                        } else {

                                            alert(xhr.responseText)
                                        }
                                    }, false)

                                    xhr.setRequestHeader('Authorization', Util.getAuthToken())
                                    // xhr.overrideMimeType( "application/octet-stream; charset=x-user-defined;" )
                                    xhr.send(null)

                                    // window.location.href = BACKUP_URL + '/dbdumps/' + i.name
                                    //history.push(ADMIN_BASE_URL + '/post/' + post._id)
                                },
                                secondary: Util.formattedDatetime(i.createdAt) + ' - ' + i.size
                            })
                            return a
                        }, [])}/>
                        }
                            </Col>

                            <Col md={6}>

                            <SimpleButton variant="contained" color="primary"
                            disabled={importMediaDumpDialog}
                            showProgress={creatingMediaDump}
                            onClick={this.createMediaDump.bind(this)}>{creatingMediaDump ? 'Dump is beeing created' : 'Create new media dump'}</SimpleButton>

                            <SimpleButton color="secondary"
                            showProgress={importingMediaDump}
                            onClick={this.importMediaDump.bind(this)}>{importingMediaDump ? 'Dump is beeing imported' : 'Import media dump'}</SimpleButton>

                            {mediaDumps && mediaDumps.results && mediaDumps.results.length > 0 &&
                            <SimpleList items={mediaDumps.results.reduce((a, i) => {
                                a.push({
                                    primary: i.name,
                                    onClick: () => {
                                        window.location.href = BACKUP_URL + '/mediadumbs/' + i.name
                                        //history.push(ADMIN_BASE_URL + '/post/' + post._id)
                                    },
                                    secondary: Util.formattedDatetime(i.createdAt) + ' - ' + i.size
                                })
                                return a
                            }, [])}/>
                            }
                            </Col>
                            </Row>

                            <SimpleDialog open={importMediaDumpDialog} onClose={this.handleConfirmMediaDialog.bind(this)}
                            actions={[{key: 'close', label: 'Close'}]}
                            title="Select a media dump file">

                            <FileDrop style={{width: '15rem', height: '10rem'}} accept="application/x-gzip"
                            uploadTo="/graphql/upload/mediadump"
                            label="Drop file here"/>

                            </SimpleDialog>

                            <SimpleDialog open={importDbDumpDialog} onClose={this.handleConfirmDbDialog.bind(this)}
                            actions={[{key: 'close', label: 'Close'}]}
                            title="Select a db dump file">

                            <FileDrop style={{width: '15rem', height: '10rem'}} accept="application/x-gzip"
                            uploadTo="/graphql/upload/dbdump"
                            label="Drop file here"/>

                            </SimpleDialog>

                            </BaseLayout>
                            )
                            }
                        }

                        DbDumpContainer.propTypes = {
                        /* apollo client props */
                        dbDumps: PropTypes.object,
                        createDbDump: PropTypes.func.isRequired,
                        createMediaDump: PropTypes.func.isRequired,
                        loading: PropTypes.bool,
                        mediaDumps: PropTypes.object
                    }

                        const gqlQuery = gql`query{dbDumps{results{name createdAt size}}}`
                        const gqlUpdate = gql`mutation
                        createDbDump($type:String){createDbDump(type:$type){name createdAt size}}`
                        const gqlQueryMedia = gql`query{mediaDumps{results{name createdAt size}}}`
                        const gqlUpdateMedia = gql`mutation
                        createMediaDump($type:String){createMediaDump(type:$type){name createdAt size}}`

                        const DbDumpContainerWithGql = compose(
                        graphql(gqlQuery, {
                        options() {
                        return {
                        fetchPolicy: 'cache-and-network'
                    }
                    },
                        props: ({data: {dbDumps}}) => ({
                        dbDumps
                    })
                    }),
                        graphql(gqlUpdate, {
                        props: ({mutate}) => ({
                        createDbDump: () => {
                        return mutate({
                        variables: {type: 'full'},
                        update: (proxy, {data: {createDbDump}}) => {
                        // Read the data from our cache for this query.
                        const data = proxy.readQuery({query: gqlQuery})
                        // Add our note from the mutation to the end.
                        data.dbDumps.results.unshift(createDbDump)
                        // Write our data back to the cache.
                        proxy.writeQuery({query: gqlQuery, data})
                    }

                    })
                    }
                    })
                    }),
                        graphql(gqlQueryMedia, {
                        options() {
                        return {
                        fetchPolicy: 'cache-and-network'
                    }
                    },
                        props: ({data: {mediaDumps}}) => ({
                        mediaDumps
                    })
                    }),
                        graphql(gqlUpdateMedia, {
                        props: ({mutate}) => ({
                        createMediaDump: () => {
                        return mutate({
                        variables: {type: 'full'},
                        update: (proxy, {data: {createMediaDump}}) => {
                        // Read the data from our cache for this query.
                        const data = proxy.readQuery({query: gqlQueryMedia})
                        // Add our note from the mutation to the end.
                        data.mediaDumps.results.unshift(createMediaDump)
                        // Write our data back to the cache.
                        proxy.writeQuery({query: gqlQueryMedia, data})
                    }

                    })
                    }
                    })
                    })
                        )
                        (DbDumpContainer)

                        /**
                         * Connect the component to
                         * the Redux store.
                         */
                        export default DbDumpContainerWithGql
<commit_msg>Small improvments<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import {graphql} from 'react-apollo'
import compose from 'util/compose'
import gql from 'graphql-tag'
import BaseLayout from 'client/components/layout/BaseLayout'
import {
    SimpleButton,
    SimpleDialog,
    Typography,
    TextField,
    Divider,
    DeleteIconButton,
    Chip,
    SimpleList,
    Row,
    Col
} from 'ui/admin'
import FileDrop from 'client/components/FileDrop'
import Util from 'client/util'
import config from 'gen/config'

const {BACKUP_URL} = config

class DbDumpContainer extends React.Component {

    constructor(props) {
        super(props)

        this.state = {
            creatingDump: false,
            creatingMediaDump: false,
            importingDbDump: false,
            importingMediaDump: false,
            importMediaDumpDialog: false,
            importDbDumpDialog: false
        }
    }

    createDump() {
        this.setState({creatingDump: true})
        this.props.createDbDump().then(e => {
            console.log(e)
            this.setState({creatingDump: false})
        })

    }

    createMediaDump() {
        this.setState({creatingMediaDump: true})
        this.props.createMediaDump().then(e => {
            console.log(e)
            this.setState({creatingMediaDump: false})
        })

    }

    importMediaDump() {
        this.setState({importMediaDumpDialog: true})
    }

    importDbDump() {
        this.setState({importDbDumpDialog: true})
    }

    handleConfirmMediaDialog() {
        this.setState({importMediaDumpDialog: false})
    }

    handleConfirmDbDialog() {
        this.setState({importDbDumpDialog: false})
    }

    handleMediaDumpUpload(e) {
        console.log(e)
    }

    download(content, filename, contentType)
    {
        if(!contentType) contentType = 'application/octet-stream';
        var a = document.createElement('a');
        var blob = new Blob([content], {'type':contentType});
        a.href = window.URL.createObjectURL(blob);
        a.download = filename;
        a.click();
    }

    render() {
        const {dbDumps, mediaDumps} = this.props
        const {creatingDump, creatingMediaDump, importingMediaDump, importMediaDumpDialog, importDbDumpDialog, importingDbDump} = this.state
        return (
            <BaseLayout>
                <Typography variant="h3" gutterBottom>Backups</Typography>

                <Row spacing={4}>
                    <Col md={6}>

                        <SimpleButton variant="contained" color="primary"
                                      showProgress={creatingDump}
                                      onClick={this.createDump.bind(this)}>{creatingDump ? 'Dump is beeing created' : 'Create new db dump'}</SimpleButton>

                        <SimpleButton color="secondary"
                                      disabled={importDbDumpDialog}
                                      showProgress={importingDbDump}
                                      onClick={this.importDbDump.bind(this)}>{importingDbDump ? 'Dump is beeing restored' : 'Restore db dump'}</SimpleButton>

                        {dbDumps && dbDumps.results && dbDumps.results.length > 0 &&
                        <SimpleList items={dbDumps.results.reduce((a, i) => {
                            a.push({
                                primary: i.name,
                                onClick: () => {

                                    const xhr = new XMLHttpRequest

                                    xhr.open("GET", BACKUP_URL + '/dbdumps/' + i.name)
                                    xhr.responseType = 'blob'

                                    xhr.addEventListener("load", () => {
                                        if( xhr.status === 200) {

                                            this.download(xhr.response, 'backup.gz', 'application/gzip')
                                        }else{

                                            alert(xhr.responseText)
                                        }
                                    }, false)

                                    xhr.setRequestHeader('Authorization', Util.getAuthToken())
                                    // xhr.overrideMimeType( "application/octet-stream; charset=x-user-defined;" )
                                    xhr.send(null)

                                },
                                secondary: Util.formattedDatetime(i.createdAt) + ' - ' + i.size
                            })
                            return a
                        }, [])}/>
                        }
                    </Col>

                    <Col md={6}>

                        <SimpleButton variant="contained" color="primary"
                                      disabled={importMediaDumpDialog}
                                      showProgress={creatingMediaDump}
                                      onClick={this.createMediaDump.bind(this)}>{creatingMediaDump ? 'Dump is beeing created' : 'Create new media dump'}</SimpleButton>

                        <SimpleButton color="secondary"
                                      showProgress={importingMediaDump}
                                      onClick={this.importMediaDump.bind(this)}>{importingMediaDump ? 'Dump is beeing imported' : 'Import media dump'}</SimpleButton>

                        {mediaDumps && mediaDumps.results && mediaDumps.results.length > 0 &&
                        <SimpleList items={mediaDumps.results.reduce((a, i) => {
                            a.push({
                                primary: i.name,
                                onClick: () => {
                                    window.location.href = BACKUP_URL + '/mediadumbs/' + i.name
                                    //history.push(ADMIN_BASE_URL + '/post/' + post._id)
                                },
                                secondary: Util.formattedDatetime(i.createdAt) + ' - ' + i.size
                            })
                            return a
                        }, [])}/>
                        }
                    </Col>
                </Row>

                <SimpleDialog open={importMediaDumpDialog} onClose={this.handleConfirmMediaDialog.bind(this)}
                              actions={[{key: 'close', label: 'Close'}]}
                              title="Select a media dump file">

                    <FileDrop style={{width: '15rem', height: '10rem'}} accept="application/x-gzip"
                              uploadTo="/graphql/upload/mediadump"
                              label="Drop file here"/>

                </SimpleDialog>

                <SimpleDialog open={importDbDumpDialog} onClose={this.handleConfirmDbDialog.bind(this)}
                              actions={[{key: 'close', label: 'Close'}]}
                              title="Select a db dump file">

                    <FileDrop style={{width: '15rem', height: '10rem'}} accept="application/x-gzip"
                              uploadTo="/graphql/upload/dbdump"
                              label="Drop file here"/>

                </SimpleDialog>

            </BaseLayout>
        )
    }
}

DbDumpContainer.propTypes = {
    /* apollo client props */
    dbDumps: PropTypes.object,
    createDbDump: PropTypes.func.isRequired,
    createMediaDump: PropTypes.func.isRequired,
    loading: PropTypes.bool,
    mediaDumps: PropTypes.object
}

const gqlQuery = gql`query{dbDumps{results{name createdAt size}}}`
const gqlUpdate = gql`mutation createDbDump($type:String){createDbDump(type:$type){name createdAt size}}`
const gqlQueryMedia = gql`query{mediaDumps{results{name createdAt size}}}`
const gqlUpdateMedia = gql`mutation createMediaDump($type:String){createMediaDump(type:$type){name createdAt size}}`

const DbDumpContainerWithGql = compose(
    graphql(gqlQuery, {
        options() {
            return {
                fetchPolicy: 'cache-and-network'
            }
        },
        props: ({data: {dbDumps}}) => ({
            dbDumps
        })
    }),
    graphql(gqlUpdate, {
        props: ({mutate}) => ({
            createDbDump: () => {
                return mutate({
                    variables: {type: 'full'},
                    update: (proxy, {data: {createDbDump}}) => {
                        // Read the data from our cache for this query.
                        const data = proxy.readQuery({query: gqlQuery})
                        // Add our note from the mutation to the end.
                        data.dbDumps.results.unshift(createDbDump)
                        // Write our data back to the cache.
                        proxy.writeQuery({query: gqlQuery, data})
                    }

                })
            }
        })
    }),
    graphql(gqlQueryMedia, {
        options() {
            return {
                fetchPolicy: 'cache-and-network'
            }
        },
        props: ({data: {mediaDumps}}) => ({
            mediaDumps
        })
    }),
    graphql(gqlUpdateMedia, {
        props: ({mutate}) => ({
            createMediaDump: () => {
                return mutate({
                    variables: {type: 'full'},
                    update: (proxy, {data: {createMediaDump}}) => {
                        // Read the data from our cache for this query.
                        const data = proxy.readQuery({query: gqlQueryMedia})
                        // Add our note from the mutation to the end.
                        data.mediaDumps.results.unshift(createMediaDump)
                        // Write our data back to the cache.
                        proxy.writeQuery({query: gqlQueryMedia, data})
                    }

                })
            }
        })
    })
)
(DbDumpContainer)

/**
 * Connect the component to
 * the Redux store.
 */
export default DbDumpContainerWithGql
<|endoftext|>


<commit_before>var debug = require('debug'),
  log = debug('bshed:client')

var React = require('react')

var app = require('./app'),
  navigate = require('./actions/navigate')

// needed for onTouchTap
require('react-tap-event-plugin')()

// assets
require('./assets/styles/index.less')

var mountNode = document.getElementById('bshed') // render node
var dehydratedState = window.BSHED // sent from server
window.React = React // For chrome dev tool support

if (process.env.NODE_ENV !== 'production')
  debug.enable('*')

log('rehydrating')
app.rehydrate(dehydratedState, rehydrateCallback)
function rehydrateCallback (err, context) {
  if (err) throw err
  if (process.env.NODE_ENV !== 'production')
    window.context = context

  log('starting router')
  context.getComponentContext().router.run(runCallback)
  function runCallback (Handler, state) {
    context.executeAction(navigate, state, navigateCallback)
    function navigateCallback (err) {
      if (err) console.error(err) // TODO: handle failure~

      log('rendering route')
      React.withContext(context.getComponentContext(), () => {
        React.render(React.createElement(Handler), mountNode, () => log('react rendered'))
      })
    }
  }
}
<commit_msg>refactor client entry point for readability<commit_after>var co = require('co'),
  debug = require('debug'),
  React = require('react'),
  log = debug('bshed:client')

var navigate = require('./actions/navigate'),
  app = require('./app')

// needed for onTouchTap
require('react-tap-event-plugin')()

// assets
require('./assets/styles/index.less')

var mountNode = document.getElementById('bshed') // render node

if (process.env.NODE_ENV !== 'production') {
  window.React = React // For chrome dev tool support
  debug.enable('*')
}

log('rehydrating application')
app.rehydrate(window.BSHED, (err, context) => {
  if (err) throw err
  if (process.env.NODE_ENV !== 'production')
    window.context = context // For debugging

  log('starting router')
  context.getComponentContext().router.run(co.wrap(routerAction(context)))
})

function routerAction (context) {
  return function* (Handler, state) {
    try {
      log('executing navigate action')
      yield context.executeAction(navigate, state)
    } catch (err) {
      console.error('Error executing navigate action', err)
      throw err
    }

    log('rendering application')
    yield render({context, Handler})
  }
}

function render ({context, Handler}={}) {
  return new Promise(resolve => {
    React.withContext(context.getComponentContext(), () => {
      React.render(React.createElement(Handler), mountNode, () => log('application rendered'))
    })
  })
}
<|endoftext|>


<commit_before>/**
 * sameAs Lite
 * jQuery for Symbols pages
 */

var app = {
    mimeType: 'text/html'
};

$(document).ready(function() {

    $("#alternate_mime_options .label.alternate_format").click(function (e) {
        e.preventDefault();
        e.stopPropagation();

        //get the required format and remember the mime type
        var mime = app.mimeType = $(this).data('mime');

        // issue an ajax request to the current page for the selected mime type
        // then replace the content of the page with the result
        $.ajax({
            url: '',
            headers: {
                "Accept": mime
            },
            beforeSend: function(xhr) {
                xhr.overrideMimeType(mime);
            },
            success: function (data, textStatus) {

                $result = $('#result');

                if (data) {
                    // clear
                    // $result.html("");
                    $result.text(data);
                    // wrap pre tags around result (only once)
                    if ($result.parent('pre').length === 0) {
                        $result.wrap('

');
                    }

                    // loop over the mime buttons to mark the current one
                    if (app.mimeType) {
                        $labels = $('.label.alternate_format');
                        $labels.removeClass('current');
                        $labels.each(function(){
                            if ($(this).data('mime') == app.mimeType) {
                                $(this).addClass('current');
                                return false; //break
                            }
                        });
                    }
                }

            },
          dataType: "text"
        });

    });

});

// vim: set filetype=javascript expandtab tabstop=4 shiftwidth=4:
<commit_msg>ajax pagination for dumpstore<commit_after>/**
 * sameAs Lite
 * jQuery for Symbols pages
 */

var app = {
    mimeType: 'text/html', // default mime type
    page: 1, //the current page (default = 1)
    getPageContents: function() {
        // issue an ajax request to the current page for the selected mime type
        // then replace the content of the page with the result
        $.ajax({
            url: (app.page > 1 ? '?page=' + app.page : ''),
            headers: {
                "Accept": app.mimeType
            },
            beforeSend: function(xhr) {
                xhr.overrideMimeType(app.mimeType);
            },
            success: function (data, textStatus) {

                $result = $('#result');

                if (data) {
                    // clear
                    // $result.html("");
                    $result.text(data);
                    // wrap pre tags around result (only once)
                    if ($result.parent('pre').length === 0) {
                        $result.wrap('

');
                    }

                    var $items = [];

                    // loop over the mime buttons to mark the current one
                    $items = $('.label.alternate_format');
                    $items.removeClass('current');
                    $items.each(function(){
                        if ($(this).data('mime') == app.mimeType) {
                            $(this).addClass('current');
                            return false; //break
                        }
                    });

                    // loop over the page buttons to mark the current one
                    $items = $('.pagination .label.page');
                    $items.removeClass('current');
                    $items.each(function(){
                        if ($(this).text() == app.page) {
                            $(this).addClass('current');
                            return false; //break
                        }
                    });

                    // mess with the url
                    //window.location.href.replace(/page=\d+/i, "?page=" + app.page);

                    window.history.pushState(data, "SameAs-Lite Result Page " + app.page, "?page=" + app.page);

                }

            },
          dataType: "text"
        });
    }
};

$(document).ready(function() {

    // mime type ajax button
    $("#alternate_mime_options .label.alternate_format").click(function (e) {
        e.preventDefault();
        e.stopPropagation();

        //get the required format and remember the mime type
        app.mimeType = $(this).data('mime');

        app.getPageContents();
    });

    // ajax pagination
    $(".pagination .label.page").click(function (e) {
        e.preventDefault();
        e.stopPropagation();

        app.page = $(this).text();

        app.getPageContents();
    });

});

// vim: set filetype=javascript expandtab tabstop=4 shiftwidth=4:
<|endoftext|>


<commit_before>const { COMMANDS } = require("./constants");
const Command = require("./command");
const { getClass, getObjectFunction } = require("./objects");
const Variable = require("./variable");
const MAGIC = "FG";
const ENCODING = "binary";

const PRIMITIVE_TYPES = {
  5: "BOOLEAN",
  2: "INT",
  3: "FLOAT",
  4: "DOUBLE",
  6: "STRING"
};

class Parser {
  _readMagic() {
    const magic = this._readStringOfLength(MAGIC.length);
    if (magic !== MAGIC) {
      throw new Error("Magic number does not mach. Is this a maki file?");
    }
    return magic;
  }

  _readVersion() {
    // No idea what we're actually expecting here.
    this._i += 2;
  }

  _readTypes() {
    let count = this._readUInt32LE();
    const types = [];
    while (count--) {
      let identifier = "";
      let chunks = 4;
      while (chunks--) {
        identifier += this._readUInt32LE()
          .toString(16)
          .padStart(8, "0");
      }
      const klass = getClass(identifier);
      if (klass == null) {
        throw new Error(`Could not find class for id: ${identifier}`);
      }
      types.push(klass);
    }
    return types;
  }

  _readFunctionsNames({ types }) {
    let count = this._readUInt32LE();
    const functionNames = [];
    while (count--) {
      const classCode = this._readUInt16LE();
      // Offset into our parsed types
      const typeOffset = classCode & 0xff;
      const dummy2 = this._readUInt16LE();
      const name = this._readString();
      const klass = types[typeOffset];
      functionNames.push({
        dummy2,
        name,
        class: klass,
        function: getObjectFunction(klass, name)
      });
    }
    return functionNames;
  }

  _readVariables({ types }) {
    let count = this._readUInt32LE();
    const variables = [];
    while (count--) {
      const typeOffset = this._readUInt8();
      const object = this._readUInt8();
      const subClass = this._readUInt16LE();
      const uinit1 = this._readUInt16LE();
      const uinit2 = this._readUInt16LE();
      const uinit3 = this._readUInt16LE();
      const uinit4 = this._readUInt16LE();
      const global = this._readUInt8();
      const system = this._readUInt8();
      const props = {
        typeOffset,
        object,
        subClass,
        uinit1,
        uinit2,
        uinit3,
        uinit4,
        global,
        system
      };

      if (object) {
        const type = types[typeOffset];
        if (type == null) {
          throw new Error("Invalid type");
        }
        variables.push(new Variable({ ...props, type }));
      } else if (subClass) {
        const type = variables[typeOffset];
        if (type == null) {
          throw new Error("Invalid type");
        }
        variables.push(new Variable({ ...props, type }));
      } else {
        const typeName = PRIMITIVE_TYPES[typeOffset];
        if (typeName == null) {
          throw new Error("Invalid type");
        }
        let value = null;

        switch (typeName) {
          // BOOLEAN
          case PRIMITIVE_TYPES[5]:
          // INT
          case PRIMITIVE_TYPES[2]:
            value = uinit1;
            break;
          case PRIMITIVE_TYPES[3]:
          case PRIMITIVE_TYPES[4]:
            const exponent = (uint2 & 0xff80) >> 7;
            const mantisse = ((0x80 | (uint2 & 0x7f)) << 16) | uint1;
            value = mantisse * 2.0 ** (exponent - 0x96);
            break;
          case PRIMITIVE_TYPES[6]:
            // This will likely get set by constants later on.
            break;
        }
        if (value == null) {
          // throw new Error("Failed to set value");
        }
        const variable = new Variable({ ...props, type: { name: typeName } });
        variable.setValue(value);
        variables.push(variable);
      }
    }
    return variables;
  }

  _readConstants({ variables }) {
    let count = this._readUInt32LE();
    const constants = [];
    while (count--) {
      const i = this._readUInt32LE();
      const variable = variables[i];
      const value = this._readString();
      // TODO: Don't mutate
      variable.setValue(value);
      constants.push({ varNum: i, value });
    }
    return constants;
  }

  _readFunctions() {
    let count = this._readUInt32LE();
    const functions = [];
    while (count--) {
      const varNum = this._readUInt32LE();
      const funcNum = this._readUInt32LE();
      const offset = this._readUInt32LE();
      functions.push({ varNum, offset, funcNum });
    }
    return functions;
  }

  _readCommands(code) {
    let i = 0;
    while (i < code.length) {
      const opCode = code.charCodeAt(i);
      const command = COMMANDS[opCode];
      if (command == null) {
        // console.warn(`Missing command opCode: ${opCode}`);
        i++;
        continue;
      }
      if (command.arg == null) {
        i++;
        continue;
      }
      switch (command.arg) {
        case "var":
          // This is the index into this._debug.variables
          // this._readUInt32LE();
          i += 5;
          break;
        default:
          i += 5;
      }
      // console.log({ command });
    }
  }

  _readUInt32LE() {
    const int = this._buffer.readUInt32LE(this._i);
    this._i += 4;
    return int;
  }

  _readUInt16LE() {
    const int = this._buffer.readUInt16LE(this._i);
    this._i += 2;
    return int;
  }

  _readUInt8() {
    const int = this._buffer.readUInt8(this._i);
    this._i++;
    return int;
  }

  _readStringOfLength(length) {
    const str = this._buffer.toString(ENCODING, this._i, this._i + length);
    this._i += length;
    return str;
  }

  _readString() {
    return this._readStringOfLength(this._readUInt16LE());
  }

  _decodeCode({ types, variables, functionNames, functions }) {
    const length = this._readUInt32LE();
    const commandsBuffer = this._buffer.slice(this._i, this._i + length);
    this._i += length;

    let pos = 0;
    const localFunctions = {};
    const results = [];
    while (pos < commandsBuffer.length) {
      const command = new Command({
        commandsBuffer,
        pos,
        types,
        variables,
        functionNames,
        localFunctions
      });
      pos += command.size;
      results.push(command);
    }
    // TODO: Don't mutate
    Object.values(localFunctions).forEach(localFunction => {
      functions.push(localFunction);
    });

    functions.sort((a, b) => {
      // TODO: Confirm that I have this the right way round
      return a.offset - b.offset;
    });

    return results;
  }

  parse(buffer) {
    this._buffer = buffer;
    this._i = 0;

    const magic = this._readMagic();
    this._readVersion();
    this._readUInt32LE(); // Not sure what we are skipping over here. Just some UInt 32.
    const types = this._readTypes();
    const functionNames = this._readFunctionsNames({ types });
    const variables = this._readVariables({ types });
    const constants = this._readConstants({ variables });
    const functions = this._readFunctions();
    const commands = this._decodeCode({
      types,
      variables,
      functionNames,
      functions
    });
    return {
      magic,
      types,
      functionNames,
      variables,
      constants,
      functions,
      commands
    };
  }
}

function parse(buffer) {
  const parser = new Parser();
  return parser.parse(buffer);
}

module.exports = { parse };
<commit_msg>Throw for invalid primitive types<commit_after>const { COMMANDS } = require("./constants");
const Command = require("./command");
const { getClass, getObjectFunction } = require("./objects");
const Variable = require("./variable");
const MAGIC = "FG";
const ENCODING = "binary";

const PRIMITIVE_TYPES = {
  5: "BOOLEAN",
  2: "INT",
  3: "FLOAT",
  4: "DOUBLE",
  6: "STRING"
};

class Parser {
  _readMagic() {
    const magic = this._readStringOfLength(MAGIC.length);
    if (magic !== MAGIC) {
      throw new Error("Magic number does not mach. Is this a maki file?");
    }
    return magic;
  }

  _readVersion() {
    // No idea what we're actually expecting here.
    this._i += 2;
  }

  _readTypes() {
    let count = this._readUInt32LE();
    const types = [];
    while (count--) {
      let identifier = "";
      let chunks = 4;
      while (chunks--) {
        identifier += this._readUInt32LE()
          .toString(16)
          .padStart(8, "0");
      }
      const klass = getClass(identifier);
      if (klass == null) {
        throw new Error(`Could not find class for id: ${identifier}`);
      }
      types.push(klass);
    }
    return types;
  }

  _readFunctionsNames({ types }) {
    let count = this._readUInt32LE();
    const functionNames = [];
    while (count--) {
      const classCode = this._readUInt16LE();
      // Offset into our parsed types
      const typeOffset = classCode & 0xff;
      const dummy2 = this._readUInt16LE();
      const name = this._readString();
      const klass = types[typeOffset];
      functionNames.push({
        dummy2,
        name,
        class: klass,
        function: getObjectFunction(klass, name)
      });
    }
    return functionNames;
  }

  _readVariables({ types }) {
    let count = this._readUInt32LE();
    const variables = [];
    while (count--) {
      const typeOffset = this._readUInt8();
      const object = this._readUInt8();
      const subClass = this._readUInt16LE();
      const uinit1 = this._readUInt16LE();
      const uinit2 = this._readUInt16LE();
      const uinit3 = this._readUInt16LE();
      const uinit4 = this._readUInt16LE();
      const global = this._readUInt8();
      const system = this._readUInt8();
      const props = {
        typeOffset,
        object,
        subClass,
        uinit1,
        uinit2,
        uinit3,
        uinit4,
        global,
        system
      };

      if (object) {
        const type = types[typeOffset];
        if (type == null) {
          throw new Error("Invalid type");
        }
        variables.push(new Variable({ ...props, type }));
      } else if (subClass) {
        const type = variables[typeOffset];
        if (type == null) {
          throw new Error("Invalid type");
        }
        variables.push(new Variable({ ...props, type }));
      } else {
        const typeName = PRIMITIVE_TYPES[typeOffset];
        if (typeName == null) {
          throw new Error("Invalid type");
        }
        let value = null;

        switch (typeName) {
          // BOOLEAN
          case PRIMITIVE_TYPES[5]:
          // INT
          case PRIMITIVE_TYPES[2]:
            value = uinit1;
            break;
          case PRIMITIVE_TYPES[3]:
          case PRIMITIVE_TYPES[4]:
            const exponent = (uint2 & 0xff80) >> 7;
            const mantisse = ((0x80 | (uint2 & 0x7f)) << 16) | uint1;
            value = mantisse * 2.0 ** (exponent - 0x96);
            break;
          case PRIMITIVE_TYPES[6]:
            // This will likely get set by constants later on.
            break;
          default:
            throw new Error("Invalid primitive type");
        }
        const variable = new Variable({ ...props, type: { name: typeName } });
        variable.setValue(value);
        variables.push(variable);
      }
    }
    return variables;
  }

  _readConstants({ variables }) {
    let count = this._readUInt32LE();
    const constants = [];
    while (count--) {
      const i = this._readUInt32LE();
      const variable = variables[i];
      const value = this._readString();
      // TODO: Don't mutate
      variable.setValue(value);
      constants.push({ varNum: i, value });
    }
    return constants;
  }

  _readFunctions() {
    let count = this._readUInt32LE();
    const functions = [];
    while (count--) {
      const varNum = this._readUInt32LE();
      const funcNum = this._readUInt32LE();
      const offset = this._readUInt32LE();
      functions.push({ varNum, offset, funcNum });
    }
    return functions;
  }

  _readCommands(code) {
    let i = 0;
    while (i < code.length) {
      const opCode = code.charCodeAt(i);
      const command = COMMANDS[opCode];
      if (command == null) {
        // console.warn(`Missing command opCode: ${opCode}`);
        i++;
        continue;
      }
      if (command.arg == null) {
        i++;
        continue;
      }
      switch (command.arg) {
        case "var":
          // This is the index into this._debug.variables
          // this._readUInt32LE();
          i += 5;
          break;
        default:
          i += 5;
      }
      // console.log({ command });
    }
  }

  _readUInt32LE() {
    const int = this._buffer.readUInt32LE(this._i);
    this._i += 4;
    return int;
  }

  _readUInt16LE() {
    const int = this._buffer.readUInt16LE(this._i);
    this._i += 2;
    return int;
  }

  _readUInt8() {
    const int = this._buffer.readUInt8(this._i);
    this._i++;
    return int;
  }

  _readStringOfLength(length) {
    const str = this._buffer.toString(ENCODING, this._i, this._i + length);
    this._i += length;
    return str;
  }

  _readString() {
    return this._readStringOfLength(this._readUInt16LE());
  }

  _decodeCode({ types, variables, functionNames, functions }) {
    const length = this._readUInt32LE();
    const commandsBuffer = this._buffer.slice(this._i, this._i + length);
    this._i += length;

    let pos = 0;
    const localFunctions = {};
    const results = [];
    while (pos < commandsBuffer.length) {
      const command = new Command({
        commandsBuffer,
        pos,
        types,
        variables,
        functionNames,
        localFunctions
      });
      pos += command.size;
      results.push(command);
    }
    // TODO: Don't mutate
    Object.values(localFunctions).forEach(localFunction => {
      functions.push(localFunction);
    });

    functions.sort((a, b) => {
      // TODO: Confirm that I have this the right way round
      return a.offset - b.offset;
    });

    return results;
  }

  parse(buffer) {
    this._buffer = buffer;
    this._i = 0;

    const magic = this._readMagic();
    this._readVersion();
    this._readUInt32LE(); // Not sure what we are skipping over here. Just some UInt 32.
    const types = this._readTypes();
    const functionNames = this._readFunctionsNames({ types });
    const variables = this._readVariables({ types });
    const constants = this._readConstants({ variables });
    const functions = this._readFunctions();
    const commands = this._decodeCode({
      types,
      variables,
      functionNames,
      functions
    });
    return {
      magic,
      types,
      functionNames,
      variables,
      constants,
      functions,
      commands
    };
  }
}

function parse(buffer) {
  const parser = new Parser();
  return parser.parse(buffer);
}

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


<commit_before>// ==UserScript==
// @name        hvSellEquipment
// @name:zh-CN  【HV】出售装备
// @author      Dodying
// @namespace   https://github.com/dodying/Dodying-UserJs
// @supportURL  https://github.com/dodying/Dodying-UserJs/issues
// @icon        http://cdn4.iconfinder.com/data/icons/mood-smiles/80/mood-29-48.png
// @include     http://hentaiverse.org/?s=Character&ss=ch
// @include     http://hentaiverse.org/
// @version     1
// @grant       none
// @run-at      document-end
// ==/UserScript==
if (document.querySelector('#togpane_log')) {
  return;
}
var ReferURL = [
  '1handed',
  '2handed',
  'staff',
  'shield',
  'acloth',
  'alight',
  'aheavy'
];
var left = document.documentElement.clientWidth - 80;
var div = document.createElement('div');
div.id = 'ShowEquip';
div.style = 'color: red;position: absolute;left: ' + left + 'px;top: 30px;z-index: 999;';
div.innerHTML = '<button type="button">显示装备</button><button type="button" style="display:none">出售所有装备</button><button type="button" style="display:none">重载装备</button>';
document.body.appendChild(div);
var script = document.createElement('script');
script.innerHTML = 'function Equiplock(g, f) {var e = f.className == \'il\' || f.className == \'ilp\';var h = f.className == \'ilp\' || f.className == \'iup\';f.className = \'i\' + (e ? \'u\' : \'l\') + (h ? \'p\' : \'\');var i = get_rpcsession();xhr(MAIN_URL + \'rpc/rpc_equip.php?act=toggle_lock&eid=\' + g + \'&val=\' + (e ? 0 : 1));};function xhr(url) {var xhr = \'xhr\' + Math.random().toString();xhr = new XMLHttpRequest();xhr.open(\'GET\', url, true);xhr.send(null);};';
document.body.appendChild(script);
document.querySelector('#ShowEquip button').addEventListener('click', function () {
  if (!document.querySelector('#Equip')) {
    CreateEquipDIV();
    document.querySelector('#ShowEquip button').innerHTML = '隐藏装备';
    document.querySelectorAll('#ShowEquip button') [1].setAttribute('style', '');
    document.querySelectorAll('#ShowEquip button') [2].setAttribute('style', '');
  } else {
    var style = document.querySelector('#Equip').getAttribute('style');
    if (style.indexOf('display: none') < 0) {
      document.querySelector('#Equip').setAttribute('style', style + 'display: none;');
      document.querySelector('#ShowEquip button').innerHTML = '显示装备';
      document.querySelectorAll('#ShowEquip button') [1].setAttribute('style', 'display: none;');
      document.querySelectorAll('#ShowEquip button') [2].setAttribute('style', 'display: none;');
    } else {
      document.querySelector('#Equip').setAttribute('style', style.replace('display: none;', ''));
      document.querySelector('#ShowEquip button').innerHTML = '隐藏装备';
      document.querySelectorAll('#ShowEquip button') [1].setAttribute('style', '');
      document.querySelectorAll('#ShowEquip button') [2].setAttribute('style', '');
    }
  }
});
document.querySelectorAll('#ShowEquip button') [1].addEventListener('click', function () {
  var check = confirm('是否出售所有装备');
  if (check == true) {
    for (var i = 0; i < ReferURL.length; i++) {
      Sell(ReferURL[i]);
    }
  }
});
document.querySelectorAll('#ShowEquip button') [2].addEventListener('click', function () {
  var check = confirm('是否重载装备');
  if (check == true) {
    var temp = document.querySelector('#Equip');
    document.body.removeChild(temp);
    CreateEquipDIV();
  }
});
///////////////////////////////////////////////////////////////
function Sell(refer) {
  var xhr = 'xhr_Sell' + Math.random().toString();
  xhr = new XMLHttpRequest();
  xhr.open('POST', 'http://hentaiverse.org/?s=Bazaar&ss=es&filter=' + refer);
  var parm = 'sell_all=1dca93d84fffb8614cb251bbe9a4e37571c7ff0c';
  xhr.setRequestHeader('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8');
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.send(parm);
}
function CreateEquipDIV() {
  var xhr = 'xhr_CreateEquipDIV' + Math.random().toString();
  xhr = new XMLHttpRequest();
  xhr.open('GET', 'http://hentaiverse.org/?s=Character&ss=in');
  xhr.onload = function () {
    var Equip_html = xhr.responseText.replace(/[\r\n]/g, '').replace(/.*?<div class="eqp/, '<div class="eqp').replace(/<\/div><div class="csps".*/, '').replace(/
<div class="il.*?
<\/div><\/div><\/div><\/div><\/div>/g, '').replace(/on(mouseout|mouseover)=".*?"/g, '').replace(/equips\.lock/g, 'Equiplock').replace(/Crude/g, '1粗糙的').replace(/Fair/g, '2尚可的').replace(/Average/g, '3普通的').replace(/Superior/g, '4优秀的').replace(/Exquisite/g, '5精致的').replace(/Magnificent/g, '6华丽的').replace(/Legendary/g, '7传奇的').replace(/Peerless/g, '8无双的');
    //alert(Equip_html);
    var div1 = document.createElement('div');
    div1.id = 'Equip';
    div1.style = 'position: absolute;left: 230px;top: 210px;z-index: 999;font-size: 14px;background: white;';
    div1.innerHTML = '以下是未锁定的装备' + Equip_html;
    document.body.appendChild(div1);
  }
  xhr.send(null);
}
<commit_msg>v1.00a<commit_after>// ==UserScript==
// @name        hvSellEquipment
// @name:zh-CN  【HV】出售装备
// @author      Dodying
// @namespace   https://github.com/dodying/Dodying-UserJs
// @supportURL  https://github.com/dodying/Dodying-UserJs/issues
// @icon        http://cdn4.iconfinder.com/data/icons/mood-smiles/80/mood-29-48.png
// @include     http://hentaiverse.org/?s=Character&ss=ch
// @include     http://hentaiverse.org/
// @version     1.00a
// @grant       none
// @run-at      document-end
// ==/UserScript==
if (document.querySelector('#togpane_log')) {
  return;
}
var ReferURL = [
  '1handed',
  '2handed',
  'staff',
  'shield',
  'acloth',
  'alight',
  'aheavy'
];
var left = document.documentElement.clientWidth - 80;
var div = document.createElement('div');
div.id = 'ShowEquip';
div.style = 'color: red;position: fixed;right: 5px;top: 30px;z-index: 999;';
div.innerHTML = '<button type="button">Show EQPT</button>
<button type="button" style="display:none">SELL All</button>
<button type="button" style="display:none">Reload</button>';
document.body.appendChild(div);
var script = document.createElement('script');
script.innerHTML = 'function Equiplock(g, f) {var e = f.className == \'il\' || f.className == \'ilp\';var h = f.className == \'ilp\' || f.className == \'iup\';f.className = \'i\' + (e ? \'u\' : \'l\') + (h ? \'p\' : \'\');var i = get_rpcsession();xhr(MAIN_URL + \'rpc/rpc_equip.php?act=toggle_lock&eid=\' + g + \'&val=\' + (e ? 0 : 1));};function xhr(url) {var xhr = \'xhr\' + Math.random().toString();xhr = new XMLHttpRequest();xhr.open(\'GET\', url, true);xhr.send(null);};';
document.body.appendChild(script);
document.querySelector('#ShowEquip button').addEventListener('click', function () {
  if (!document.querySelector('#Equip')) {
    CreateEquipDIV();
    document.querySelector('#ShowEquip button').innerHTML = 'Hide EQPT';
    document.querySelectorAll('#ShowEquip button') [1].setAttribute('style', '');
    document.querySelectorAll('#ShowEquip button') [2].setAttribute('style', '');
  } else {
    var style = document.querySelector('#Equip').getAttribute('style');
    if (style.indexOf('display: none') < 0) {
      document.querySelector('#Equip').setAttribute('style', style + 'display: none;');
      document.querySelector('#ShowEquip button').innerHTML = 'Show EQPT';
      document.querySelectorAll('#ShowEquip button') [1].setAttribute('style', 'display: none;');
      document.querySelectorAll('#ShowEquip button') [2].setAttribute('style', 'display: none;');
    } else {
      document.querySelector('#Equip').setAttribute('style', style.replace('display: none;', ''));
      document.querySelector('#ShowEquip button').innerHTML = 'Hide EQPT';
      document.querySelectorAll('#ShowEquip button') [1].setAttribute('style', '');
      document.querySelectorAll('#ShowEquip button') [2].setAttribute('style', '');
    }
  }
});
document.querySelectorAll('#ShowEquip button') [1].addEventListener('click', function () {
  var check = confirm('Whether to SELL all equipments?\nYou can lock the EQPT you dont want to sell in left panel.');
  if (check == true) {
    for (var i = 0; i < ReferURL.length; i++) {
      Sell(ReferURL[i]);
    }
  }
});
document.querySelectorAll('#ShowEquip button') [2].addEventListener('click', function () {
  var check = confirm('Whether to reload equipments?');
  if (check == true) {
    var temp = document.querySelector('#Equip');
    document.body.removeChild(temp);
    CreateEquipDIV();
  }
});
///////////////////////////////////////////////////////////////
function Sell(refer) {
  var xhr = 'xhr_Sell' + Math.random().toString();
  xhr = new XMLHttpRequest();
  xhr.open('POST', 'http://hentaiverse.org/?s=Bazaar&ss=es&filter=' + refer);
  var parm = 'sell_all=1dca93d84fffb8614cb251bbe9a4e37571c7ff0c';
  xhr.setRequestHeader('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8');
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.send(parm);
}
function CreateEquipDIV() {
  var xhr = 'xhr_CreateEquipDIV' + Math.random().toString();
  xhr = new XMLHttpRequest();
  xhr.open('GET', 'http://hentaiverse.org/?s=Character&ss=in');
  xhr.onload = function () {
    var Equip_html = xhr.responseText.replace(/[\r\n]/g, '').replace(/.*?<div class="eqp/, '<div class="eqp').replace(/<\/div><div class="csps".*/, '').replace(/
<div class="il.*?
<\/div><\/div><\/div><\/div><\/div>/g, '').replace(/on(mouseout|mouseover)=".*?"/g, '').replace(/equips\.lock/g, 'Equiplock').replace(/Crude/g, '1-☆').replace(/Fair/g, '2-★').replace(/Average/g, '3-★☆').replace(/Superior/g, '4-★★').replace(/Exquisite/g, '5-★★☆').replace(/Magnificent/g, '6-★★★').replace(/Legendary/g, '7-★★★☆').replace(/Peerless/g, '8-★★★★');
    //alert(Equip_html);
    var div1 = document.createElement('div');
    div1.id = 'Equip';
    div1.style = 'position: absolute;left: 230px;top: 210px;z-index: 999;font-size: 14px;background: white;';
    div1.innerHTML = 'The following are equipments which is not locked' + Equip_html;
    document.body.appendChild(div1);
  }
  xhr.send(null);
}
<|endoftext|>