<commit_before>describe('after hooking into Angular', function() {
  beforeAll(function() {
    psWhich(angular);
    angular.module('moduleA', []);
    angular.module('moduleB', []);
  });

  it('has undefined info for modules that haven\t been defined', function() {
    expect(psWhich.info.moduleX).toBeUndefined();
  });

  it('has empty arrays for modules that don\'t have anything', function() {
    expect(psWhich.info.moduleA.factories.length).toBe(0);
    expect(psWhich.info.moduleA.values.length).toBe(0);
    expect(psWhich.info.moduleA.constants.length).toBe(0);
    expect(psWhich.info.moduleA.services.length).toBe(0);
    expect(psWhich.info.moduleA.directives.length).toBe(0);
    expect(psWhich.info.moduleA.providers.length).toBe(0);
  });

  it('records factories added to Angular modules', function() {
    function myFactory() { return {}; }

    angular.module('moduleA').factory('f1', myFactory);
    angular.module('moduleA').factory('f2', myFactory);

    angular.module('moduleB').factory('f3', myFactory);

    expect(psWhich.info.moduleA.factories).toEqual(['f1', 'f2']);
    expect(psWhich.info.moduleB.factories).toEqual(['f3']);
  });

  it('records values added to Angular modules', function() {
    angular.module('moduleA').value('v1', 1);
    angular.module('moduleA').value('v2', 2);

    angular.module('moduleB').value('v3', 3);

    expect(psWhich.info.moduleA.values).toEqual(['v1', 'v2']);
    expect(psWhich.info.moduleB.values).toEqual(['v3']);
  });

  it('records constants added to Angular modules', function() {
    angular.module('moduleA').constant('c1', 1);
    angular.module('moduleA').constant('c2', 2);

    angular.module('moduleB').constant('c3', 3);

    expect(psWhich.info.moduleA.constants).toEqual(['c1', 'c2']);
    expect(psWhich.info.moduleB.constants).toEqual(['c3']);
  });

  it('records services added to Angular modules', function() {
    function MyService() {}

    angular.module('moduleA').service('s1', MyService);
    angular.module('moduleA').service('s2', MyService);

    angular.module('moduleB').service('s3', MyService);

    expect(psWhich.info.moduleA.services).toEqual(['s1', 's2']);
    expect(psWhich.info.moduleB.services).toEqual(['s3']);
  });

  it('records directives added to Angular modules', function() {
    function myDirective() { return {}; }

    angular.module('moduleA').directive('d1', myDirective);
    angular.module('moduleA').directive('d2', myDirective);

    angular.module('moduleB').directive('d3', myDirective);

    expect(psWhich.info.moduleA.directives).toEqual(['d1', 'd2']);
    expect(psWhich.info.moduleB.directives).toEqual(['d3']);
  });

  it('records providers added to Angular modules', function() {
    function myProvider() {
      this.$get = function() { return 2; };
    }

    angular.module('moduleA').provider('p1', myProvider);
    angular.module('moduleA').provider('p2', myProvider);

    angular.module('moduleB').provider('p3', myProvider);

    expect(psWhich.info.moduleA.providers).toEqual(['p1', 'p2']);
    expect(psWhich.info.moduleB.providers).toEqual(['p3']);
  });
});<commit_msg>don't depend on test exec order<commit_after>describe('after hooking into Angular', function() {
  beforeAll(function() {
    psWhich(angular);
  });

  it('has undefined info for modules that haven\t been defined', function() {
    expect(psWhich.info.moduleX).toBeUndefined();
  });

  it('has empty arrays for modules that don\'t have anything', function() {
    angular.module('moduleA', []);

    expect(psWhich.info.moduleA.factories.length).toBe(0);
    expect(psWhich.info.moduleA.values.length).toBe(0);
    expect(psWhich.info.moduleA.constants.length).toBe(0);
    expect(psWhich.info.moduleA.services.length).toBe(0);
    expect(psWhich.info.moduleA.directives.length).toBe(0);
    expect(psWhich.info.moduleA.providers.length).toBe(0);
  });

  it('records factories added to Angular modules', function() {
    angular.module('moduleB', []);
    angular.module('moduleC', []);

    function myFactory() { return {}; }

    angular.module('moduleB').factory('f1', myFactory);
    angular.module('moduleB').factory('f2', myFactory);

    angular.module('moduleC').factory('f3', myFactory);

    expect(psWhich.info.moduleB.factories).toEqual(['f1', 'f2']);
    expect(psWhich.info.moduleC.factories).toEqual(['f3']);
  });

  it('records values added to Angular modules', function() {
    angular.module('moduleD', []);
    angular.module('moduleE', []);

    angular.module('moduleD').value('v1', 1);
    angular.module('moduleD').value('v2', 2);

    angular.module('moduleE').value('v3', 3);

    expect(psWhich.info.moduleD.values).toEqual(['v1', 'v2']);
    expect(psWhich.info.moduleE.values).toEqual(['v3']);
  });

  it('records constants added to Angular modules', function() {
    angular.module('moduleF', []);
    angular.module('moduleG', []);

    angular.module('moduleF').constant('c1', 1);
    angular.module('moduleF').constant('c2', 2);

    angular.module('moduleG').constant('c3', 3);

    expect(psWhich.info.moduleF.constants).toEqual(['c1', 'c2']);
    expect(psWhich.info.moduleG.constants).toEqual(['c3']);
  });

  it('records services added to Angular modules', function() {
    angular.module('moduleH', []);
    angular.module('moduleI', []);

    function MyService() {}

    angular.module('moduleH').service('s1', MyService);
    angular.module('moduleH').service('s2', MyService);

    angular.module('moduleI').service('s3', MyService);

    expect(psWhich.info.moduleH.services).toEqual(['s1', 's2']);
    expect(psWhich.info.moduleI.services).toEqual(['s3']);
  });

  it('records directives added to Angular modules', function() {
    angular.module('moduleJ', []);
    angular.module('moduleK', []);

    function myDirective() { return {}; }

    angular.module('moduleJ').directive('d1', myDirective);
    angular.module('moduleJ').directive('d2', myDirective);

    angular.module('moduleK').directive('d3', myDirective);

    expect(psWhich.info.moduleJ.directives).toEqual(['d1', 'd2']);
    expect(psWhich.info.moduleK.directives).toEqual(['d3']);
  });

  it('records providers added to Angular modules', function() {
    angular.module('moduleL', []);
    angular.module('moduleM', []);

    function myProvider() {
      this.$get = function() { return 2; };
    }

    angular.module('moduleL').provider('p1', myProvider);
    angular.module('moduleL').provider('p2', myProvider);

    angular.module('moduleM').provider('p3', myProvider);

    expect(psWhich.info.moduleL.providers).toEqual(['p1', 'p2']);
    expect(psWhich.info.moduleM.providers).toEqual(['p3']);
  });
});<|endoftext|>


<commit_before>import { extend } from 'flarum/extend';
import Button from 'flarum/components/Button';
import DiscussionPage from 'flarum/components/DiscussionPage';
import DiscussionControls from 'flarum/utils/DiscussionControls';

import SubscriptionMenu from './components/SubscriptionMenu';

export default function addSubscriptionControls() {
  extend(DiscussionControls, 'userControls', function(items, discussion, context) {
    if (app.session.user && !(context instanceof DiscussionPage)) {
      const states = {
        none: {label: app.translator.trans('flarum-subscriptions.forum.discussion_controls.follow_button'), icon: 'fas fa-star', save: 'follow'},
        follow: {label: app.translator.trans('flarum-subscriptions.forum.discussion_controls.unfollow_button'), icon: 'far fa-star', save: null},
        ignore: {label: app.translator.trans('flarum-subscriptions.forum.discussion_controls.unignore_button'), icon: 'fas fa-eye', save: null}
      };

      const subscription = discussion.subscription() || 'none';

      items.add('subscription', Button.component({
        icon: states[subscription].icon,
        onclick: discussion.save.bind(discussion, {subscription: states[subscription].save})
      }, states[subscription].label));
    }
  });

  extend(DiscussionPage.prototype, 'sidebarItems', function(items) {
    if (app.session.user) {
      const discussion = this.discussion;

      items.add('subscription', SubscriptionMenu.component({discussion}));
    }
  });
}
<commit_msg>fix: set priority on subscription item (#43)<commit_after>import { extend } from 'flarum/extend';
import Button from 'flarum/components/Button';
import DiscussionPage from 'flarum/components/DiscussionPage';
import DiscussionControls from 'flarum/utils/DiscussionControls';

import SubscriptionMenu from './components/SubscriptionMenu';

export default function addSubscriptionControls() {
  extend(DiscussionControls, 'userControls', function(items, discussion, context) {
    if (app.session.user && !(context instanceof DiscussionPage)) {
      const states = {
        none: {label: app.translator.trans('flarum-subscriptions.forum.discussion_controls.follow_button'), icon: 'fas fa-star', save: 'follow'},
        follow: {label: app.translator.trans('flarum-subscriptions.forum.discussion_controls.unfollow_button'), icon: 'far fa-star', save: null},
        ignore: {label: app.translator.trans('flarum-subscriptions.forum.discussion_controls.unignore_button'), icon: 'fas fa-eye', save: null}
      };

      const subscription = discussion.subscription() || 'none';

      items.add('subscription', Button.component({
        icon: states[subscription].icon,
        onclick: discussion.save.bind(discussion, {subscription: states[subscription].save})
      }, states[subscription].label));
    }
  });

  extend(DiscussionPage.prototype, 'sidebarItems', function(items) {
    if (app.session.user) {
      const discussion = this.discussion;

      items.add('subscription', SubscriptionMenu.component({discussion}), 80);
    }
  });
}
<|endoftext|>


<commit_before>describe('delegated event listeners', function() {
  describe('firing custom events', function() {
    it('fires custom events with detail', function(done) {
      const observer = function(event) {
        document.removeEventListener('test:event', observer);
        assert(event.bubbles);
        assert(event.cancelable);
        assert.equal(event.type, 'test:event');
        assert.deepEqual(event.detail, {id: 42, login: 'hubot'});
        assert.strictEqual(document.body, event.target);
        assert.instanceOf(event, CustomEvent);
        done();
      };
      document.addEventListener('test:event', observer);
      $.fire(document.body, 'test:event', {id: 42, login: 'hubot'});
    });

    it('fires custom events without detail', function(done) {
      const observer = function(event) {
        document.removeEventListener('test:event', observer);
        assert.isUndefined(event.detail);
        assert.instanceOf(event, CustomEvent);
        done();
      };
      document.addEventListener('test:event', observer);
      $.fire(document.body, 'test:event');
    });
  });

  describe('registering event observers', function() {
    it('observes custom events', function(done) {
      const observer = function(event) {
        $.off('test:event', '*', observer);
        assert(event.bubbles);
        assert(event.cancelable);
        assert.equal(event.type, 'test:event');
        assert.deepEqual({id: 42, login: 'hubot'}, event.detail);
        assert.strictEqual(document.body, event.target);
        assert.strictEqual(document.body, this);
        assert.instanceOf(event, CustomEvent);
        done();
      };
      $.on('test:event', '*', observer);
      $.fire(document.body, 'test:event', {id: 42, login: 'hubot'});
    });

    it('removes event observers', function() {
      const observer = function() { assert.fail(); };
      $.on('test:event', '*', observer);
      $.off('test:event', '*', observer);
      $.fire(document.body, 'test:event');
    });
  });

  describe('event propagation', function() {
    before(function() {
      this.parent = document.querySelector('.js-test-parent');
      this.child = document.querySelector('.js-test-child');
    });

    it('fires observers in tree order', function() {
      const order = [];

      const parent = this.parent;
      const one = function(event) {
        assert.strictEqual(this, parent);
        order.push(1);
      };

      const child = this.child;
      const two = function(event) {
        assert.strictEqual(this, child);
        order.push(2);
      };

      $.on('test:event', '.js-test-parent', one);
      $.on('test:event', '.js-test-child', two);
      $.fire(this.child, 'test:event');
      $.off('test:event', '.js-test-parent', one);
      $.off('test:event', '.js-test-child', two);

      assert.deepEqual([2, 1], order);
    });

    it('stops propagation bubbling to parent', function() {
      const one = function(event) { assert.fail(); };
      const two = function(event) { event.stopPropagation(); };
      $.on('test:event', '.js-test-parent', one);
      $.on('test:event', '.js-test-child', two);
      $.fire(this.child, 'test:event');
      $.off('test:event', '.js-test-parent', one);
      $.off('test:event', '.js-test-child', two);
    });

    it('stops immediate propagation', function() {
      const one = function(event) { event.stopImmediatePropagation(); };
      const two = function(event) { assert.fail(); };
      $.on('test:event', '.js-test-child', one);
      $.on('test:event', '.js-test-child', two);
      $.fire(this.child, 'test:event');
      $.off('test:event', '.js-test-child', one);
      $.off('test:event', '.js-test-child', two);
    });

    it('stops immediate propagation but not bubbling', function(done) {
      const one = function(event) { assert.ok(event); done(); };
      const two = function(event) { event.stopImmediatePropagation(); };
      $.on('test:event', '.js-test-parent', one);
      $.on('test:event', '.js-test-child', two);
      $.fire(this.child, 'test:event');
      $.off('test:event', '.js-test-parent', one);
      $.off('test:event', '.js-test-child', two);
    });
  });
});
<commit_msg>Test fire return value.<commit_after>describe('delegated event listeners', function() {
  describe('firing custom events', function() {
    it('fires custom events with detail', function(done) {
      const observer = function(event) {
        document.removeEventListener('test:event', observer);
        assert(event.bubbles);
        assert(event.cancelable);
        assert.equal(event.type, 'test:event');
        assert.deepEqual(event.detail, {id: 42, login: 'hubot'});
        assert.strictEqual(document.body, event.target);
        assert.instanceOf(event, CustomEvent);
        done();
      };
      document.addEventListener('test:event', observer);
      $.fire(document.body, 'test:event', {id: 42, login: 'hubot'});
    });

    it('fires custom events without detail', function(done) {
      const observer = function(event) {
        document.removeEventListener('test:event', observer);
        assert.isUndefined(event.detail);
        assert.instanceOf(event, CustomEvent);
        done();
      };
      document.addEventListener('test:event', observer);
      $.fire(document.body, 'test:event');
    });

    it('returns canceled when default prevented', function() {
      const observer = function(event) { event.preventDefault(); };
      document.addEventListener('test:event', observer);
      const canceled = !$.fire(document.body, 'test:event');
      assert.equal(canceled, true);
    });

    it('returns not canceled when default is not prevented', function(done) {
      const observer = function(event) { assert.ok(event); done(); };
      document.addEventListener('test:event', observer);
      const canceled = !$.fire(document.body, 'test:event');
      assert.equal(canceled, false);
    });
  });

  describe('registering event observers', function() {
    it('observes custom events', function(done) {
      const observer = function(event) {
        $.off('test:event', '*', observer);
        assert(event.bubbles);
        assert(event.cancelable);
        assert.equal(event.type, 'test:event');
        assert.deepEqual({id: 42, login: 'hubot'}, event.detail);
        assert.strictEqual(document.body, event.target);
        assert.strictEqual(document.body, this);
        assert.instanceOf(event, CustomEvent);
        done();
      };
      $.on('test:event', '*', observer);
      $.fire(document.body, 'test:event', {id: 42, login: 'hubot'});
    });

    it('removes event observers', function() {
      const observer = function() { assert.fail(); };
      $.on('test:event', '*', observer);
      $.off('test:event', '*', observer);
      $.fire(document.body, 'test:event');
    });
  });

  describe('event propagation', function() {
    before(function() {
      this.parent = document.querySelector('.js-test-parent');
      this.child = document.querySelector('.js-test-child');
    });

    it('fires observers in tree order', function() {
      const order = [];

      const parent = this.parent;
      const one = function(event) {
        assert.strictEqual(this, parent);
        order.push(1);
      };

      const child = this.child;
      const two = function(event) {
        assert.strictEqual(this, child);
        order.push(2);
      };

      $.on('test:event', '.js-test-parent', one);
      $.on('test:event', '.js-test-child', two);
      $.fire(this.child, 'test:event');
      $.off('test:event', '.js-test-parent', one);
      $.off('test:event', '.js-test-child', two);

      assert.deepEqual([2, 1], order);
    });

    it('stops propagation bubbling to parent', function() {
      const one = function(event) { assert.fail(); };
      const two = function(event) { event.stopPropagation(); };
      $.on('test:event', '.js-test-parent', one);
      $.on('test:event', '.js-test-child', two);
      $.fire(this.child, 'test:event');
      $.off('test:event', '.js-test-parent', one);
      $.off('test:event', '.js-test-child', two);
    });

    it('stops immediate propagation', function() {
      const one = function(event) { event.stopImmediatePropagation(); };
      const two = function(event) { assert.fail(); };
      $.on('test:event', '.js-test-child', one);
      $.on('test:event', '.js-test-child', two);
      $.fire(this.child, 'test:event');
      $.off('test:event', '.js-test-child', one);
      $.off('test:event', '.js-test-child', two);
    });

    it('stops immediate propagation but not bubbling', function(done) {
      const one = function(event) { assert.ok(event); done(); };
      const two = function(event) { event.stopImmediatePropagation(); };
      $.on('test:event', '.js-test-parent', one);
      $.on('test:event', '.js-test-child', two);
      $.fire(this.child, 'test:event');
      $.off('test:event', '.js-test-parent', one);
      $.off('test:event', '.js-test-child', two);
    });
  });
});
<|endoftext|>


<commit_before>/**
 * Created by tpapazoglou on 11/7/2017.
 * Modified by dverver on 18/10/2017: Multiple jpgs as textures. fReader called once not twice for the same file.
 */
'use strict';

var mtlFileContent = '';
var objFileContent = '';
var fbxFileContent = '';
var previewRenderer;

var nObj = 0;
var nMtl = 0;
var nJpg = 0;

function wpunity_read_file(howtoread, file, type, callback, canvas, filename) {
    var content = '';
    var reader = new FileReader();

    if (file) {

        if (howtoread === 'Url')
            reader.readAsDataURL(file);
        else if (howtoread === 'Text')
            reader.readAsText(file);
        else if (howtoread === 'ArrayBuffer')
            reader.readAsArrayBuffer(file);

        // Closure to capture the file information.
        reader.onload = (function(reader) {
            return function() {
                content = reader.result;
                callback(content, type, canvas, filename);
            };
        })(reader);
    } else {
        callback(content, type, canvas, filename);
    }
}

// Callback is fired when obj & mtl inputs have files. Preview is loaded automatically.
// We can expand this for 'fbx' files too.
function wpunity_load_file_callback(content, type, canvas, filename) {

    if(type === 'fbx') {
        fbxFileContent = content ? content : '';
    }

    if(type === 'mtl') {

        mtlFileContent = content ? content : '';
        document.getElementById('mtlFileInput').value = mtlFileContent;

        checkerCompleteReading(type, canvas, filename);
    }

    if(type === 'obj') {

        // Obj as ArrayBuffer (needed for ObjLoader2 and webworkers)
        objFileContent = content ? content : '';

        // Obj as text (needed for ObjLoader in 3D editor)
        var dec = new TextDecoder();
        document.getElementById('objFileInput').value = dec.decode(objFileContent);

        checkerCompleteReading(type, canvas, filename);
    }

    if (content) {
        if(type === 'texture') {

            /*jQuery("#texturePreviewImg").attr('src', '').attr('src', content);*/

            jQuery('#3dAssetForm').append('<input type="hidden" name="textureFileInput['+filename+']" id="textureFileInput" value="' + content + '" />');

            //var textureFileInput = document.getElementsByName('textureFileInput[]');

            // textureFileInput[0] = document.createElement("INPUT");
            // textureFileInput[filename].setAttribute("type", "hidden");
            //textureFileInput[filename].value = content;

            checkerCompleteReading(type, canvas, filename);
        }

        if (objFileContent && mtlFileContent) {

        } else {
            wpunity_reset_sshot_field();
        }

    } else {
        document.getElementById("assetPreviewContainer").innerHTML = "";
    }

    if (jQuery('#producerPanel').is(':visible')) {
        spanProducerChartLabels();
    }

}

function wpunity_extract_file_extension(fn) {
    return fn ? fn.split('.').pop().toLowerCase() : '';
}

function wpunity_clear_asset_files(previewCanvas) {

    if (previewCanvas.renderer) {
        previewCanvas.clearAllAssets();
    }

    document.getElementById("fbxFileInput").value = "";
    document.getElementById("mtlFileInput").value = "";
    document.getElementById("objFileInput").value = "";

    for (var iTexture = 0; iTexture<document.getElementsByName('textureFileInput[]').length; iTexture++)
        document.getElementsByName('textureFileInput[]')[iTexture].value = '';

    document.getElementById("fileUploadInput").value = "";

    document.getElementById("sshotFileInput").value = "";
    /*jQuery("#texturePreviewImg").attr('src', texturePreviewDefaultImg);*/
    jQuery("#sshotPreviewImg").attr('src', sshotPreviewDefaultImg);
    jQuery("#objectPreviewTitle").hide();

    objFileContent = '';
    fbxFileContent = '';
    mtlFileContent = '';

    nObj = 0;
    nMtl = 0;
    nJpg = 0;
}

function wpunity_reset_panels(previewCanvas) {

    // Clear all
    wpunity_clear_asset_files(previewCanvas);

    if (jQuery("ProducerPlotTooltip")) {
        jQuery("div.ProducerPlotTooltip").remove();
    }

    jQuery("#assetDescription").show();
    jQuery("#doorDetailsPanel").hide();
    jQuery("#terrainPanel").hide();
    jQuery("#consumerPanel").hide();
    jQuery("#producerPanel").hide();
    jQuery("#poiImgDetailsPanel").hide();
    jQuery("#poiVideoDetailsPanel").hide();
    jQuery("#objectPreviewTitle").hide();
}

function loadAssetPreviewer(canvas, multipleFilesInputElem) {

    var _handleFileSelect = function ( event  ) {

        // copy because clear asset files in the following clears the total input fields also
        var files = {... event.target.files};

        // Clear the previously loaded
        wpunity_clear_asset_files(canvas);

        //  Read each file and put the string content in an input dom
        for ( var i = 0, file; file = files[ i ]; i++) {
            if ( file.name.indexOf( '\.obj' ) > 0 ) {
                nObj = 1;
                wpunity_read_file('ArrayBuffer' , file, 'obj', wpunity_load_file_callback, canvas);
            }
            if ( file.name.indexOf( '\.mtl' ) > 0 ) {
                nMtl = 1;
                wpunity_read_file('Text', file, 'mtl', wpunity_load_file_callback, canvas );
            }
            if ( file.name.indexOf( '\.jpg' ) > 0 ) {
                nJpg ++;
                wpunity_read_file('Url', file, 'texture', wpunity_load_file_callback, canvas, file.name);
            }
        }

        // var Validator = THREE.OBJLoader2.prototype._getValidator();
        //
        // if ( ! Validator.isValid( fileObj ) ) {
        //
        //     // Add object reset here
        //     alert( 'Unable to load OBJ file from given files.' );
        //
        //     wpunity_clear_asset_files(canvas);
        //
        //     return;
        // }

    };
    multipleFilesInputElem.addEventListener( 'change' , _handleFileSelect, false );

    // Start rendering if even nothing is loaded
    var resizeWindow = function () {
        canvas.resizeDisplayGL();
    };

    var render = function () {
        requestAnimationFrame( render );
        canvas.render();
    };

    window.addEventListener( 'resize', resizeWindow, false );

    canvas.initGL();
    canvas.resizeDisplayGL();
    canvas.initPostGL();

    // kick render loop
    render();
}

function checkerCompleteReading(type, canvas, filename){

    if (nObj==1 && objFileContent!=='' ){

        // Add loader
        jQuery('#previewProgressSlider').show();

        // Make the definition with the obj
        var uint8Array = new Uint8Array( objFileContent );

        var objectDefinition = {
            name: 'userObj',
            objAsArrayBuffer: uint8Array,
            pathTexture: "",
            mtlAsString: null
        };

        if (nMtl == 0) {
            // Start without MTL
            previewCanvas.loadFilesUser(objectDefinition);
        } else {
            if (mtlFileContent!==''){

                objectDefinition.mtlAsString = mtlFileContent;

                if (nJpg==0){
                    // Start without Textures
                    previewCanvas.loadFilesUser(objectDefinition);
                } else {

                    if ( nJpg === jQuery("input[id='textureFileInput']").length) {

                        // Get textureFileInput array with jQuery
                        var textFil = jQuery("input[id='textureFileInput']");

                        // Store here the raw image textures
                        objectDefinition.pathTexture = [];

                        for (var k = 0; k < textFil.length; k++){
                            var myname = textFil[k].name;

                            // do some text processing on the names to remove textureFileInput[ and ] from name
                            myname = myname.replace('textureFileInput[','');
                            myname = myname.replace(']','');

                            objectDefinition.pathTexture[myname] = textFil[k].value;
                        }

                        // Start with textures
                        canvas.loadFilesUser(objectDefinition);
                    }
                }
            }
        }
    }

}

// for the Energy Turbines
function wpunity_create_slider_component(elemId, range, options) {

    if (range) {

        jQuery( elemId ).slider({
            range: range,
            min: options.min,
            max: options.max,
            values: [ options.values[0], options.values[1] ],
            create: function() {
                jQuery( options.valIds[0] ).val(options.values[0]);
                jQuery( options.valIds[1] ).val(options.values[1]);
            },
            slide: function( event, ui ) {
                jQuery( elemId+"-label" ).val( ui.values[ 0 ] + " - " + ui.values[ 1 ] + " " +options.units);

            },
            stop: function( event, ui ) {
                jQuery( options.valIds[0] ).val(ui.values[ 0 ]);
                jQuery( options.valIds[1] ).val(ui.values[ 1 ]);
            }

        });
        jQuery( elemId+"-label" ).val( jQuery( elemId ).slider( "values", 0 ) +
            " - " + jQuery( elemId ).slider( "values", 1 ) + " " + options.units );

    } else {

        jQuery( elemId ).slider({
            min: options.min,
            max: options.max,
            value: options.value,
            create: function() {
                jQuery( options.valId ).val(options.value);
            },
            slide: function( event, ui ) {
                jQuery( elemId+"-label" ).val( ui.value + " " +options.units);
            },
            stop: function( event, ui ) {
                jQuery( options.valId ).val(ui.value);
            }
        });
        jQuery( elemId+"-label" ).val( jQuery( elemId ).slider( "option", "value" ) + " " + options.units );

    }

    if (options.step) {
        jQuery( elemId ).slider({step: options.step});
    }

    return jQuery( elemId ).slider;
}<commit_msg>Fixed #192<commit_after>/**
 * Created by tpapazoglou on 11/7/2017.
 * Modified by dverver on 18/10/2017: Multiple jpgs as textures. fReader called once not twice for the same file.
 */
'use strict';

var mtlFileContent = '';
var objFileContent = '';
var fbxFileContent = '';
var pdbFileContent = '';

var previewRenderer;

var nObj = 0;
var nMtl = 0;
var nJpg = 0;

function wpunity_read_file(howtoread, file, type, callback, canvas, filename) {
    var content = '';
    var reader = new FileReader();

    if (file) {

        if (howtoread === 'Url')
            reader.readAsDataURL(file);
        else if (howtoread === 'Text')
            reader.readAsText(file);
        else if (howtoread === 'ArrayBuffer')
            reader.readAsArrayBuffer(file);

        // Closure to capture the file information.
        reader.onload = (function(reader) {
            return function() {
                content = reader.result;
                callback(content, type, canvas, filename);
            };
        })(reader);
    } else {
        callback(content, type, canvas, filename);
    }
}

// Callback is fired when obj & mtl inputs have files. Preview is loaded automatically.
// We can expand this for 'fbx' files too.
function wpunity_load_file_callback(content, type, canvas, filename) {

    switch (type) {
        case 'fbx':
            fbxFileContent = content ? content : '';
            break;

        case 'mtl':
            mtlFileContent = content ? content : '';
            document.getElementById('mtlFileInput').value = mtlFileContent;
            checkerCompleteReading(type, canvas, filename);

            break;

        case 'obj':
            // Obj as ArrayBuffer (needed for ObjLoader2 and webworkers)
            objFileContent = content ? content : '';

            // Obj as text (needed for ObjLoader in 3D editor)
            var dec = new TextDecoder();
            document.getElementById('objFileInput').value = dec.decode(objFileContent);

            checkerCompleteReading(type, canvas, filename);

            break;

        case 'pdb':
            pdbFileContent = content ? content : '';

            console.log("loaded pdb file");
            break;

    }

    if (content) {
        if(type === 'texture') {

            /*jQuery("#texturePreviewImg").attr('src', '').attr('src', content);*/

            jQuery('#3dAssetForm').append('<input type="hidden" name="textureFileInput['+filename+']" id="textureFileInput" value="' + content + '" />');

            //var textureFileInput = document.getElementsByName('textureFileInput[]');
            // textureFileInput[0] = document.createElement("INPUT");
            // textureFileInput[filename].setAttribute("type", "hidden");
            //textureFileInput[filename].value = content;

            checkerCompleteReading(type, canvas, filename);
        }

        if (objFileContent && mtlFileContent || pdbFileContent) {

        } else {
            wpunity_reset_sshot_field();
        }

    } else {
        document.getElementById("assetPreviewContainer").innerHTML = "";
    }

    if (jQuery('#producerPanel').is(':visible')) {
        spanProducerChartLabels();
    }

}

function wpunity_extract_file_extension(fn) {
    return fn ? fn.split('.').pop().toLowerCase() : '';
}

function wpunity_clear_asset_files(previewCanvas) {

    if (previewCanvas.renderer) {
        previewCanvas.clearAllAssets();
    }

    document.getElementById("fbxFileInput").value = "";
    document.getElementById("mtlFileInput").value = "";
    document.getElementById("objFileInput").value = "";
    document.getElementById("pdbFileInput").value = "";

    for (var iTexture = 0; iTexture<document.getElementsByName('textureFileInput[]').length; iTexture++)
        document.getElementsByName('textureFileInput[]')[iTexture].value = '';

    document.getElementById("fileUploadInput").value = "";

    document.getElementById("sshotFileInput").value = "";
    /*jQuery("#texturePreviewImg").attr('src', texturePreviewDefaultImg);*/
    jQuery("#sshotPreviewImg").attr('src', sshotPreviewDefaultImg);
    jQuery("#objectPreviewTitle").hide();

    objFileContent = '';
    fbxFileContent = '';
    mtlFileContent = '';
    pdbFileContent = '';

    nObj = 0;
    nMtl = 0;
    nJpg = 0;
}

function wpunity_reset_panels(previewCanvas) {

    // Clear all
    wpunity_clear_asset_files(previewCanvas);

    if (jQuery("ProducerPlotTooltip")) {
        jQuery("div.ProducerPlotTooltip").remove();
    }

    jQuery("#assetDescription").show();
    jQuery("#doorDetailsPanel").hide();
    jQuery("#terrainPanel").hide();
    jQuery("#consumerPanel").hide();
    jQuery("#producerPanel").hide();
    jQuery("#poiImgDetailsPanel").hide();
    jQuery("#poiVideoDetailsPanel").hide();
    jQuery("#objectPreviewTitle").hide();
}

function loadAssetPreviewer(canvas, multipleFilesInputElem) {

    var _handleFileSelect = function ( event  ) {

        // copy because clear asset files in the following clears the total input fields also
        var files = {... event.target.files};

        // Clear the previously loaded
        wpunity_clear_asset_files(canvas);

        //  Read each file and put the string content in an input dom
        for ( var i = 0, file; file = files[ i ]; i++) {
            if ( file.name.indexOf( '\.obj' ) > 0 ) {
                nObj = 1;
                wpunity_read_file('ArrayBuffer' , file, 'obj', wpunity_load_file_callback, canvas);
            }
            if ( file.name.indexOf( '\.mtl' ) > 0 ) {
                nMtl = 1;
                wpunity_read_file('Text', file, 'mtl', wpunity_load_file_callback, canvas );
            }
            if ( file.name.indexOf( '\.jpg' ) > 0 ) {
                nJpg ++;
                wpunity_read_file('Url', file, 'texture', wpunity_load_file_callback, canvas, file.name);
            }
        }

        // var Validator = THREE.OBJLoader2.prototype._getValidator();
        //
        // if ( ! Validator.isValid( fileObj ) ) {
        //
        //     // Add object reset here
        //     alert( 'Unable to load OBJ file from given files.' );
        //
        //     wpunity_clear_asset_files(canvas);
        //
        //     return;
        // }

    };
    multipleFilesInputElem.addEventListener( 'change' , _handleFileSelect, false );

    // Start rendering if even nothing is loaded
    var resizeWindow = function () {
        canvas.resizeDisplayGL();
    };

    var render = function () {
        requestAnimationFrame( render );
        canvas.render();
    };

    window.addEventListener( 'resize', resizeWindow, false );

    canvas.initGL();
    canvas.resizeDisplayGL();
    canvas.initPostGL();

    // kick render loop
    render();
}

function checkerCompleteReading(type, canvas, filename){

    if (nObj==1 && objFileContent!=='' ){

        // Add loader
        jQuery('#previewProgressSlider').show();

        // Make the definition with the obj
        var uint8Array = new Uint8Array( objFileContent );

        var objectDefinition = {
            name: 'userObj',
            objAsArrayBuffer: uint8Array,
            pathTexture: "",
            mtlAsString: null
        };

        if (nMtl == 0) {
            // Start without MTL
            previewCanvas.loadFilesUser(objectDefinition);
        } else {
            if (mtlFileContent!==''){

                objectDefinition.mtlAsString = mtlFileContent;

                if (nJpg==0){
                    // Start without Textures
                    previewCanvas.loadFilesUser(objectDefinition);
                } else {

                    if ( nJpg === jQuery("input[id='textureFileInput']").length) {

                        // Get textureFileInput array with jQuery
                        var textFil = jQuery("input[id='textureFileInput']");

                        // Store here the raw image textures
                        objectDefinition.pathTexture = [];

                        for (var k = 0; k < textFil.length; k++){
                            var myname = textFil[k].name;

                            // do some text processing on the names to remove textureFileInput[ and ] from name
                            myname = myname.replace('textureFileInput[','');
                            myname = myname.replace(']','');

                            objectDefinition.pathTexture[myname] = textFil[k].value;
                        }

                        // Start with textures
                        canvas.loadFilesUser(objectDefinition);
                    }
                }
            }
        }
    }
}

// for the Energy Turbines
function wpunity_create_slider_component(elemId, range, options) {

    if (range) {

        jQuery( elemId ).slider({
            range: range,
            min: options.min,
            max: options.max,
            values: [ options.values[0], options.values[1] ],
            create: function() {
                jQuery( options.valIds[0] ).val(options.values[0]);
                jQuery( options.valIds[1] ).val(options.values[1]);
            },
            slide: function( event, ui ) {
                jQuery( elemId+"-label" ).val( ui.values[ 0 ] + " - " + ui.values[ 1 ] + " " +options.units);

            },
            stop: function( event, ui ) {
                jQuery( options.valIds[0] ).val(ui.values[ 0 ]);
                jQuery( options.valIds[1] ).val(ui.values[ 1 ]);
            }

        });
        jQuery( elemId+"-label" ).val( jQuery( elemId ).slider( "values", 0 ) +
            " - " + jQuery( elemId ).slider( "values", 1 ) + " " + options.units );

    } else {

        jQuery( elemId ).slider({
            min: options.min,
            max: options.max,
            value: options.value,
            create: function() {
                jQuery( options.valId ).val(options.value);
            },
            slide: function( event, ui ) {
                jQuery( elemId+"-label" ).val( ui.value + " " +options.units);
            },
            stop: function( event, ui ) {
                jQuery( options.valId ).val(ui.value);
            }
        });
        jQuery( elemId+"-label" ).val( jQuery( elemId ).slider( "option", "value" ) + " " + options.units );

    }

    if (options.step) {
        jQuery( elemId ).slider({step: options.step});
    }

    return jQuery( elemId ).slider;
}<|endoftext|>


<commit_before>import { Component, PropTypes } from "react";
import Moment from "moment";
import { Link } from "react-router";

import Split, { Left, Right } from "../../../../blocks/split";

import { Spinner } from "../../../../components/loading";
import SideBySide from "../../../../components/cards/SideBySide";
import Meta from "../../../../components/meta";

import AccountType from "../../../../components/accountType";
import { TransactionCard } from "../../history/Layout";

export default class Layout extends Component {

  static contextTypes = {
    shouldAnimate: PropTypes.bool,
  }

  formatDate = (date) => {
    return Moment(new Date(date)).add(4, "hours").format("MMM D, YYYY");
  }

  monentize = (value, fixed) => {
    if (typeof value === "number") {
      value = `${value}`;
    }

    if (!value.length) {
      return "$0.00";
    }

    value = value.replace(/[^\d.-]/g, "");

    const decimals = value.split(".")[1];
    if ((decimals && decimals.length >= 2) || fixed) {
      value = Number(value).toFixed(2);
      value = String(value);
    }

    value = value.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return `$${value}`;
  }

  capitalizeFirstLetter = (string) => {
    return string.charAt(0).toUpperCase() + string.slice(1);
  }

  render() {
    const {
      schedule,
      stop,
      state,
      active,
      complete,
      ready,
      entries,
      loadingEntries,
    } = this.props;

    return (

          <Split nav classes={["background--light-primary"]}>

            <Meta title="Giving Schedule" />

            <Right background="//dg0ddngxdz549.cloudfront.net/images/cached/images/remote/http_s3.amazonaws.com/ns.images/all/heroes/newspring/campuses/Florence.1.2x1_1700_850_90_c1.jpg"
              mobile={false}
            />
          </Split>
          <Left scroll classes={["background--light-secondary"]} ref="container">

              {(() => {
                if (process.env.WEB) {
                  return (
                    <Link to="/give/schedules" className="locked-top locked-left soft-double@lap-and-up soft h7 text-dark-secondary plain" >

                      Back
                    </Link>
                  );
                }
              })()}

                  {(() => {
                    if (!schedule || !ready) {
                      // loading
                      return (

                          <Spinner styles={{ width: "40px", height: "40px" }} />

                      );
                    }

                    return (

Started on {this.formatDate(schedule.start)}

{this.capitalizeFirstLetter(schedule.schedule.description.toLowerCase())}

{schedule.details[0].account.name}

{this.monentize(schedule.details[0].amount)}

                        {(() => {
                          const detail = schedule.payment;
                          if (detail && detail.accountNumber) {
                            return (

                                {detail.accountNumber.slice(-4)}

                                {(() => {
                                  if (detail.paymentType && detail.paymentType === "ACH") {
                                    return (
                                      <AccountType width="30px" height="20px" type="Bank" />
                                    );
                                  } else if (detail.paymentType) {
                                    return (
                                      <AccountType width="30px" height="20px" type={detail.paymentType} />
                                    );
                                  }
                                })()}

                            );
                          }
                        })()}
                        {(() => {
                          if (complete) {
                            return (

                                Schedule Completed

                            );
                          }

                          if (active) {
                            return (

                                Stop Contribution

                            );
                          }

                          return (

                              Contribution Stopped

                          );
                        })()}

                          Thank you so much for your contributions! It is because of your generosity that we are able to continue telling stories of the greatness of Jesus and seeing lives changed.

                    );
                  })()}

              {(() => {
                if (!schedule) return null;
                const { transactions } = schedule;
                if (!transactions.length && ready) {
                  return (

                        We didn't find any contributions associated with this schedule.

If you have any questions, please call our Finance Team at 864-965-9990 or contact us  and someone will be happy to assist you.

                  );
                }

                let lastYear = null;
                return (

                    Contributions from this Schedule

                  {transactions.map((transaction, key) => {
                    let { details, person } = transaction;
                    return (

                        {details.map((transactionDetail, i) => {
                          if (!transactionDetail.account) return null;

                          if (Number(transactionDetail.amount) <= 0) return null;

                          const year = Moment(transaction.date).year();
                          if (year != lastYear) {
                            lastYear = year;
                            return (

{year}

                                <TransactionCard
                                  transaction={transaction}
                                  transactionDetail={transactionDetail}
                                  person={person}
                                />

                            );
                          }

                          return (
                            <TransactionCard
                              transaction={transaction}
                              transactionDetail={transactionDetail}
                              key={i}
                              person={person}
                            />
                          );
                        })}

                    );
                  })}

                );
              })()}

                Recent Articles About Giving

              {(() => {
                if (loadingEntries) (

<Spinner />

                );
                return (

                    {entries && entries.map((entry, key) => (

                        <SideBySide
                          classes={["push-bottom@lap-and-up"]}
                          images={entry.content.images}
                          defaultImage={entry.content.images[0].url}
                        >

                            {entry.title}

                          {(() => {
                            if (process.env.WEB) {
                              return (
                                <a
                                  target="_blank"
                                  href={`https://newspring.cc/articles/${entry.meta.urlTitle}`}
                                  className="h6 btn--small btn--dark-tertiary soft-sides@portable one-whole@handheld"
                                >
                                  Read more

                              );
                            }

                            if (process.env.NATIVE) {
                              return (
                                <Link
                                  to={`/articles/${entry.entryId}`}
                                  className="h6 btn--small btn--dark-tertiary soft-sides@portable one-whole@handheld"
                                >
                                  Read more
                                </Link>
                              );
                            }
                          })()}

                        </SideBySide>

                    ))}

                );
              })()}

          </Left>

    );
  }
}

  //

  //
  //
  //

  //
  //       {this.capitalizeFirstLetter(schedule.schedule.description.toLowerCase())}
  //
  //
  //      using my
  //       {schedule.payment.paymentType.toLowerCase()}
  //      ending in
  //       {schedule.payment.accountNumber.slice(-4)}
  //
  //

  //   {(() => {
  //     if (state.isActive) {
  //       return (
  //         <button className="btn--alert btn--thin btn--small" onClick={stop}>
  //           Cancel gift
  //         </button>
  //       )
  //     }
  //   })()}
  //

  //
  //

  //   Thank you so much for your gift! It is because of your generosity we are able to continue telling stories of the greatness of Jesus and seeing peoples lives changed.
  //

<commit_msg>lint schedules details layout<commit_after>import { Component, PropTypes } from "react";
import moment from "moment";
import { Link } from "react-router";

import Split, { Left, Right } from "../../../../blocks/split";

import { Spinner } from "../../../../components/loading";
import SideBySide from "../../../../components/cards/SideBySide";
import Meta from "../../../../components/meta";

import AccountType from "../../../../components/accountType";
import { TransactionCard } from "../../history/Layout";

export default class Layout extends Component {

  static propTypes = {
    schedule: PropTypes.object.isRequired,
    stop: PropTypes.func.isRequired,
    active: PropTypes.bool,
    complete: PropTypes.bool,
    ready: PropTypes.bool,
    entries: PropTypes.array.isRequired,
    loadingEntries: PropTypes.bool,
  }

  formatDate = (date) => (
    Moment(new Date(date)).add(4, "hours").format("MMM D, YYYY");
  )

  monentize = (value, fixed) => {
    let strVal = typeof value === "number" ? `${value}` : value;

    if (!strVal.length) {
      return "$0.00";
    }

    strVal = strVal.replace(/[^\d.-]/g, "");

    const decimals = strVal.split(".")[1];
    if ((decimals && decimals.length >= 2) || fixed) {
      strVal = Number(strVal).toFixed(2);
      strVal = String(strVal);
    }

    strVal = strVal.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return `$${strVal}`;
  }

  capitalizeFirstLetter = (string) => (
    string.charAt(0).toUpperCase() + string.slice(1)
  )

  render() {
    const {
      schedule,
      stop,
      active,
      complete,
      ready,
      entries,
      loadingEntries,
    } = this.props;

    /* eslint-disable max-len */
    return (

        <Split nav classes={["background--light-primary"]}>

          <Meta title="Giving Schedule" />

          <Right
            background="//dg0ddngxdz549.cloudfront.net/images/cached/images/remote/http_s3.amazonaws.com/ns.images/all/heroes/newspring/campuses/Florence.1.2x1_1700_850_90_c1.jpg"
            mobile={false}
          />
        </Split>
        <Left scroll classes={["background--light-secondary"]} ref="container">

            {(() => {
              if (process.env.WEB) {
                return (
                  <Link
                    to="/give/schedules"
                    className={
                      "locked-top locked-left soft-double@lap-and-up " +
                      "soft h7 text-dark-secondary plain"
                    }
                  >

                      Back

                  </Link>
                );
              }
              return null;
            })()}

                {(() => {
                  if (!schedule || !ready) {
                    // loading
                    return (

                        <Spinner styles={{ width: "40px", height: "40px" }} />

                    );
                  }

                  return (

                        Started on {this.formatDate(schedule.start)}

                        {this.capitalizeFirstLetter(schedule.schedule.description.toLowerCase())}

{schedule.details[0].account.name}

                        {this.monentize(schedule.details[0].amount)}

                      {(() => {
                        const detail = schedule.payment;
                        if (detail && detail.accountNumber) {
                          return (

                              {detail.accountNumber.slice(-4)}

                              {(() => {
                                if (detail.paymentType && detail.paymentType === "ACH") {
                                  return (
                                    <AccountType
                                      width="30px"
                                      height="20px"
                                      type="Bank"
                                    />
                                  );
                                } else if (detail.paymentType) {
                                  return (
                                    <AccountType
                                      width="30px"
                                      height="20px"
                                      type={detail.paymentType}
                                    />
                                  );
                                }
                                return null;
                              })()}

                          );
                        }
                        return null;
                      })()}
                      {(() => {
                        if (complete) {
                          return (

                              Schedule Completed

                          );
                        }

                        if (active) {
                          return (

                              Stop Contribution

                          );
                        }

                        return (

                            Contribution Stopped

                        );
                      })()}

                        Thank you so much for your contributions! It is because of your generosity that we are able to continue telling stories of the greatness of Jesus and seeing lives changed.

                  );
                })()}

            {(() => {
              if (!schedule) return null;
              const { transactions } = schedule;
              if (!transactions.length && ready) {
                return (

                      We didn't find any contributions associated with this schedule.

If you have any questions, please call our Finance Team at 864-965-9990 or contact us  and someone will be happy to assist you.

                );
              }

              let lastYear = null;
              return (

                    Contributions from this Schedule

                  {transactions.map((transaction, key) => {
                    const { details, person } = transaction;
                    return (

                        {details.map((transactionDetail, i) => {
                          if (!transactionDetail.account) return null;

                          if (Number(transactionDetail.amount) <= 0) return null;

                          const year = moment(transaction.date).year();
                          if (year !== lastYear) {
                            lastYear = year;
                            return (

{year}

                                <TransactionCard
                                  transaction={transaction}
                                  transactionDetail={transactionDetail}
                                  person={person}
                                />

                            );
                          }

                          return (
                            <TransactionCard
                              transaction={transaction}
                              transactionDetail={transactionDetail}
                              key={i}
                              person={person}
                            />
                          );
                        })}

                    );
                  })}

              );
            })()}

              Recent Articles About Giving

            {(() => {
              if (loadingEntries) {
                return
<Spinner />
;
              }
              return (

                  {entries && entries.map((entry, key) => (

                      <SideBySide
                        classes={["push-bottom@lap-and-up"]}
                        images={entry.content.images}
                        defaultImage={entry.content.images[0].url}
                      >

                          {entry.title}

                        {(() => {
                          if (process.env.WEB) {
                            return (
                              <a
                                rel="noopener noreferrer"
                                target="_blank"
                                href={`https://newspring.cc/articles/${entry.meta.urlTitle}`}
                                className={
                                  "h6 btn--small btn--dark-tertiary " +
                                  "soft-sides@portable one-whole@handheld"
                                }
                              >
                                Read more

                            );
                          }

                          if (process.env.NATIVE) {
                            return (
                              <Link
                                to={`/articles/${entry.entryId}`}
                                className={
                                  "h6 btn--small btn--dark-tertiary " +
                                  "soft-sides@portable one-whole@handheld"
                                }
                              >
                                Read more
                              </Link>
                            );
                          }

                          return null;
                        })()}

                      </SideBySide>

                  ))}

              );
            })()}

        </Left>

    );
  }
  /* eslint-enable max-len */
}

/* eslint-disable */
  //

  //
  //
  //

  //
  //       {this.capitalizeFirstLetter(schedule.schedule.description.toLowerCase())}
  //
  //
  //      using my
  //       {schedule.payment.paymentType.toLowerCase()}
  //      ending in
  //       {schedule.payment.accountNumber.slice(-4)}
  //
  //

  //   {(() => {
  //     if (state.isActive) {
  //       return (
  //         <button className="btn--alert btn--thin btn--small" onClick={stop}>
  //           Cancel gift
  //         </button>
  //       )
  //     }
  //   })()}
  //

  //
  //

  //   Thank you so much for your gift! It is because of your generosity we are able to continue telling stories of the greatness of Jesus and seeing peoples lives changed.
  //

/* eslint-enable */
<|endoftext|>


<commit_before>
var i18nCountries = require('../index.js');

/*
 * Logs title to console
 */
var logBlock = function(title){

  var line = '----------------------------------------------------------------';

  console.log('\n\n' + line);
  console.log(title);
  console.log(line + '\n');

};

/*
 * Logs test to console
 */
var testCountries = function(locale){

  logBlock('COUNTRIES FOR ' + locale);
  console.log(i18nCountries.getCountries(locale));

  logBlock('CONTINENTS FOR ' + locale);
  console.log(i18nCountries.getContinents(locale));

  logBlock('REGIONS FOR US FOR ' + locale);
  console.log(i18nCountries.getRegions(locale,'US'));

  logBlock('CONTINENTS FOR BE (does not exist) FOR ' + locale);
  console.log(i18nCountries.getRegions(locale,'BE'));

};

/*
 * Tests existing locale
 */
testCountries('nl');

/*
 * Tests not existing locale
 */
testCountries('de');
<commit_msg>updated test script<commit_after>
var i18nCountries = require('../index.js');

/*
 * Logs title to console
 */
var logBlock = function(title){

  var line = '----------------------------------------------------------------';

  console.log('\n\n' + line);
  console.log(title);
  console.log(line + '\n');

};

/*
 * Logs test to console
 */
var testCountries = function(locale){

  logBlock('COUNTRIES FOR ' + locale);
  console.log(i18nCountries.getCountries(locale));

  logBlock('CONTINENTS FOR ' + locale);
  console.log(i18nCountries.getContinents(locale));

  logBlock('REGIONS FOR US FOR ' + locale);
  console.log(i18nCountries.getRegions(locale,'US'));

  logBlock('REGIONS FOR BE FOR ' + locale);
  console.log(i18nCountries.getRegions(locale,'BE'));

  logBlock('CONTINENTS FOR NL (does not exist) FOR ' + locale);
  console.log(i18nCountries.getRegions(locale,'NL'));

};

/*
 * Tests existing locale
 */
testCountries('nl');

/*
 * Tests not existing locale
 */
testCountries('de');
<|endoftext|>


<commit_before>/**
 * 新增修改完成调用 modalFormOk方法 编辑弹框组件ref定义为modalForm
 * 高级查询按钮调用 superQuery方法  高级查询组件ref定义为superQueryModal
 * data中url定义 list为查询列表  delete为删除单条记录  deleteBatch为批量删除
 */
import { filterObj } from '@/utils/util';
import { deleteAction, getAction, postAction, downFile, getFileAccessHttpUrl } from '@/api/manage'
import Vue from 'vue'
import { ACCESS_TOKEN } from "@/store/mutation-types"
import {mixinDevice} from '@/utils/mixin.js'

export const JeecgListMixin = {
  mixins: [mixinDevice],
  data(){
    return {
      //token header
      tokenHeader: {'X-Access-Token': Vue.ls.get(ACCESS_TOKEN)},
      /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
      queryParam: {},
      /* 数据源 */
      dataSource:[],
      /* 分页参数 */
      ipagination:{
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条"
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      /* 控制table高度 */
      scroll: {},
      /* 排序参数 */
      isorter:{
        column: 'createTime',
        order: 'desc',
      },
      /* 筛选参数 */
      filters: {},
      /* table加载状态 */
      loading:false,
      /* table选中keys*/
      selectedRowKeys: [],
      /* table选中records*/
      selectionRows: [],
      /* 查询折叠 */
      toggleSearchStatus:false,
      /* 高级查询条件生效状态 */
      superQueryFlag:false,
      /* 高级查询条件 */
      superQueryParams: '',
      /** 高级查询拼接方式 */
      superQueryMatchType: 'and',
      /** 是否加载时就执行 */
      disableMixinCreated: false,
      /* 按钮权限 */
      btnEnableList: '',
    }
  },
  created() {
    if(!this.disableMixinCreated){
      //console.log(' -- mixin created -- ')
      this.loadData();
      //初始化字典配置 在自己页面定义
      this.initDictConfig();
      //初始化按钮权限
      this.initActiveBtnStr();
    }
  },
  mounted () {
    this.initScroll()
  },
  methods:{
    loadData(arg) {
      if(!this.url.list){
        this.$message.error("请设置url.list属性!")
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      var params = this.getQueryParams();//查询条件
      this.loading = true;
      getAction(this.url.list, params).then((res) => {
        if (res.code===200) {
          this.dataSource = res.data.rows;
          this.ipagination.total = res.data.total;
          this.tableAddTotalRow(this.columns, this.dataSource)
        }
        if(res.code===510){
          this.$message.warning(res.data)
        }
        this.loading = false;
      })
    },
    initDictConfig(){
      //console.log("--这是一个假的方法!")
    },
    handleSuperQuery(params, matchType) {
      //高级查询方法
      if(!params){
        this.superQueryParams=''
        this.superQueryFlag = false
      }else{
        this.superQueryFlag = true
        this.superQueryParams=JSON.stringify(params)
        this.superQueryMatchType = matchType
      }
      this.loadData(1)
    },
    getQueryParams() {
      //获取查询条件
      let sqp = {}
      if(this.superQueryParams){
        sqp['superQueryParams']=encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      let searchObj = {}
      searchObj.search = JSON.stringify(this.queryParam);
      var param = Object.assign(sqp, searchObj, this.isorter ,this.filters);
      param.field = this.getQueryField();
      param.currentPage = this.ipagination.current;
      param.pageSize = this.ipagination.pageSize;
      return filterObj(param);
    },
    getQueryField() {
      var str = "id,";
      this.columns.forEach(function (value) {
        str += "," + value.dataIndex;
      });
      return str;
    },

    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
    },
    onClearSelected() {
      this.selectedRowKeys = [];
      this.selectionRows = [];
    },
    searchQuery() {
      this.loadData(1);
    },
    superQuery() {
      this.$refs.superQueryModal.show();
    },
    searchReset() {
      this.queryParam = {}
      this.loadData(1);
    },
    batchSetStatus: function (status) {
      if(!this.url.batchSetStatusUrl){
        this.$message.error("请设置url.batchSetStatusUrl属性!")
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！');
        return;
      } else {
        var ids = "";
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ",";
        }
        var that = this;
        this.$confirm({
          title: "确认操作",
          content: "是否操作选中数据?",
          onOk: function () {
            that.loading = true;
            postAction(that.url.batchSetStatusUrl, {status: status, ids: ids}).then((res) => {
              if(res.code === 200){
                that.loadData();
                that.onClearSelected();
              } else {
                that.$message.warning(res.data.message);
              }
            }).finally(() => {
              that.loading = false;
            });
          }
        });
      }
    },
    batchDel: function () {
      if(!this.url.deleteBatch){
        this.$message.error("请设置url.deleteBatch属性!")
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！');
        return;
      } else {
        var ids = "";
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ",";
        }
        var that = this;
        this.$confirm({
          title: "确认删除",
          content: "是否删除选中数据?",
          onOk: function () {
            that.loading = true;
            deleteAction(that.url.deleteBatch, {ids: ids}).then((res) => {
              if(res.code === 200){
                that.loadData();
                that.onClearSelected();
              } else {
                that.$message.warning(res.data.message);
              }
            }).finally(() => {
              that.loading = false;
            });
          }
        });
      }
    },
    handleDelete: function (id) {
      if(!this.url.delete){
        this.$message.error("请设置url.delete属性!")
        return
      }
      var that = this;
      deleteAction(that.url.delete, {id: id}).then((res) => {
        if(res.code === 200){
          that.loadData();
        } else {
          that.$message.warning(res.data.message);
        }
      });
    },
    handleEdit: function (record) {
      this.$refs.modalForm.edit(record);
      this.$refs.modalForm.title = "编辑";
      this.$refs.modalForm.disableSubmit = false;
    },
    handleAdd: function () {
      this.$refs.modalForm.add();
      this.$refs.modalForm.title = "新增";
      this.$refs.modalForm.disableSubmit = false;
    },
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field;
        this.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
      }
      if(pagination && pagination.current) {
        this.ipagination = pagination;
      }
      this.loadData();
    },
    handleToggleSearch(){
      this.toggleSearchStatus = !this.toggleSearchStatus;
    },
    // 给popup查询使用(查询区域不支持回填多个字段，限制只返回一个字段)
    getPopupField(fields){
      return fields.split(',')[0]
    },
    modalFormOk() {
      // 新增/修改 成功时，重载列表
      this.loadData();
    },
    handleDetail:function(record, type){
      this.$refs.modalDetail.show(record, type);
      this.$refs.modalDetail.title=type+"-详情";
    },
    /* 导出 */
    handleExportXls2(){
      let paramsStr = encodeURI(JSON.stringify(this.getQueryParams()));
      let url = `${window._CONFIG['domianURL']}/${this.url.exportXlsUrl}?paramsStr=${paramsStr}`;
      window.location.href = url;
    },
    handleExportXls(fileName){
      if(!fileName || typeof fileName != "string"){
        fileName = "导出文件"
      }
      let param = {...this.queryParam};
      if(this.selectedRowKeys && this.selectedRowKeys.length>0){
        param['selections'] = this.selectedRowKeys.join(",")
      }
      console.log("导出参数",param)
      downFile(this.url.exportXlsUrl,param).then((data)=>{
        if (!data) {
          this.$message.warning("文件下载失败")
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data],{type: 'application/vnd.ms-excel'}), fileName+'.xls')
        }else{
          let url = window.URL.createObjectURL(new Blob([data],{type: 'application/vnd.ms-excel'}))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName+'.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link); //下载完成移除元素
          window.URL.revokeObjectURL(url); //释放掉blob对象
        }
      })
    },
    /* 导入 */
    handleImportExcel(info){
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        if (info.file.response) {
          // this.$message.success(`${info.file.name} 文件上传成功`);
          if (info.file.response.code === 200) {
            this.$message.success(info.file.response.data || `${info.file.name} 文件上传成功`)
          } else {
            this.$message.warning(info.file.response.data)
          }
          this.loadData()
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.data}.`);
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`文件上传失败: ${info.file.msg} `);
      }
    },
    /* 图片预览 */
    getImgView(text){
      if(text && text.indexOf(",")>0){
        text = text.substring(0,text.indexOf(","))
      }
      return getFileAccessHttpUrl(text)
    },
    /* 文件下载 */
    uploadFile(text){
      if(!text){
        this.$message.warning("未知的文件")
        return;
      }
      if(text.indexOf(",")>0){
        text = text.substring(0,text.indexOf(","))
      }
      let url = getFileAccessHttpUrl(text)
      window.open(url);
    },
    /* 按钮权限 */
    initActiveBtnStr() {
      let funId = Vue.ls.get('funId'); //功能id
      let btnStrList = Vue.ls.get('winBtnStrList'); //按钮功能列表 JSON字符串
      this.btnEnableList = ""; //按钮列表
      if (funId && btnStrList) {
        for (let i = 0; i < btnStrList.length; i++) {
          if (btnStrList[i].funId == funId) {
            if (btnStrList[i].btnStr) {
              this.btnEnableList = btnStrList[i].btnStr;
            }
          }
        }
      }
    },
    /* 初始化表格横向或纵向滚动 */
    initScroll() {
      if (this.isMobile()) {
        this.scroll.y = ''
      } else {
        let basicLength = 274
        let searchWrapperDomLen=0, operatorDomLen=0
        //搜索区域
        let searchWrapperDom = document.getElementsByClassName('table-page-search-wrapper')
        //操作按钮区域
        let operatorDom = document.getElementsByClassName('table-operator')
        if(searchWrapperDom && searchWrapperDom[0]) {
          searchWrapperDomLen = searchWrapperDom[0].offsetHeight
        }
        if(operatorDom && operatorDom[0]) {
          operatorDomLen = operatorDom[0].offsetHeight+10
        }
        this.scroll.y = document.documentElement.clientHeight-searchWrapperDomLen-operatorDomLen-basicLength
      }
    },
    /** 表格增加合计行 */
    tableAddTotalRow(columns, dataSource) {
      if(dataSource.length>0 && this.ipagination.pageSize%10===1) {
        //分页条数为11、21、31等的时候增加合计行
        let numKey = 'rowIndex'
        let totalRow = { [numKey]: '合计' }
        //移除不需要合计的列
        let removeCols = 'action,mBarCode,barCode,unitPrice,purchaseDecimal,operTime,oTime'
        columns.forEach(column => {
          let { key, dataIndex } = column
          if (![key, dataIndex].includes(numKey)) {
            let total = 0
            dataSource.forEach(data => {
              total += Number.parseFloat(data[dataIndex])
            })
            if (Number.isNaN(total)) {
              total = '-'
            } else {
              total = total.toFixed(2)
            }
            if(removeCols.indexOf(dataIndex)>-1) {
              total = '-'
            }
            totalRow[dataIndex] = total
          }
        })
        dataSource.push(totalRow)
      }
    },
    paginationChange(page, pageSize) {
      this.ipagination.current = page
      this.ipagination.pageSize = pageSize
      this.loadData(this.ipagination.current);
    },
    paginationShowSizeChange(current, size) {
      this.ipagination.current = current
      this.ipagination.pageSize = size
      this.loadData(this.ipagination.current);
    }
  }

}<commit_msg>解决合计展示的bug<commit_after>/**
 * 新增修改完成调用 modalFormOk方法 编辑弹框组件ref定义为modalForm
 * 高级查询按钮调用 superQuery方法  高级查询组件ref定义为superQueryModal
 * data中url定义 list为查询列表  delete为删除单条记录  deleteBatch为批量删除
 */
import { filterObj } from '@/utils/util';
import { deleteAction, getAction, postAction, downFile, getFileAccessHttpUrl } from '@/api/manage'
import Vue from 'vue'
import { ACCESS_TOKEN } from "@/store/mutation-types"
import {mixinDevice} from '@/utils/mixin.js'

export const JeecgListMixin = {
  mixins: [mixinDevice],
  data(){
    return {
      //token header
      tokenHeader: {'X-Access-Token': Vue.ls.get(ACCESS_TOKEN)},
      /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
      queryParam: {},
      /* 数据源 */
      dataSource:[],
      /* 分页参数 */
      ipagination:{
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条"
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      /* 控制table高度 */
      scroll: {},
      /* 排序参数 */
      isorter:{
        column: 'createTime',
        order: 'desc',
      },
      /* 筛选参数 */
      filters: {},
      /* table加载状态 */
      loading:false,
      /* table选中keys*/
      selectedRowKeys: [],
      /* table选中records*/
      selectionRows: [],
      /* 查询折叠 */
      toggleSearchStatus:false,
      /* 高级查询条件生效状态 */
      superQueryFlag:false,
      /* 高级查询条件 */
      superQueryParams: '',
      /** 高级查询拼接方式 */
      superQueryMatchType: 'and',
      /** 是否加载时就执行 */
      disableMixinCreated: false,
      /* 按钮权限 */
      btnEnableList: '',
    }
  },
  created() {
    if(!this.disableMixinCreated){
      //console.log(' -- mixin created -- ')
      this.loadData();
      //初始化字典配置 在自己页面定义
      this.initDictConfig();
      //初始化按钮权限
      this.initActiveBtnStr();
    }
  },
  mounted () {
    this.initScroll()
  },
  methods:{
    loadData(arg) {
      if(!this.url.list){
        this.$message.error("请设置url.list属性!")
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      var params = this.getQueryParams();//查询条件
      this.loading = true;
      getAction(this.url.list, params).then((res) => {
        if (res.code===200) {
          this.dataSource = res.data.rows;
          this.ipagination.total = res.data.total;
          this.tableAddTotalRow(this.columns, this.dataSource)
        }
        if(res.code===510){
          this.$message.warning(res.data)
        }
        this.loading = false;
      })
    },
    initDictConfig(){
      //console.log("--这是一个假的方法!")
    },
    handleSuperQuery(params, matchType) {
      //高级查询方法
      if(!params){
        this.superQueryParams=''
        this.superQueryFlag = false
      }else{
        this.superQueryFlag = true
        this.superQueryParams=JSON.stringify(params)
        this.superQueryMatchType = matchType
      }
      this.loadData(1)
    },
    getQueryParams() {
      //获取查询条件
      let sqp = {}
      if(this.superQueryParams){
        sqp['superQueryParams']=encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      let searchObj = {}
      searchObj.search = JSON.stringify(this.queryParam);
      var param = Object.assign(sqp, searchObj, this.isorter ,this.filters);
      param.field = this.getQueryField();
      param.currentPage = this.ipagination.current;
      param.pageSize = this.ipagination.pageSize;
      return filterObj(param);
    },
    getQueryField() {
      var str = "id,";
      this.columns.forEach(function (value) {
        str += "," + value.dataIndex;
      });
      return str;
    },

    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
    },
    onClearSelected() {
      this.selectedRowKeys = [];
      this.selectionRows = [];
    },
    searchQuery() {
      this.loadData(1);
    },
    superQuery() {
      this.$refs.superQueryModal.show();
    },
    searchReset() {
      this.queryParam = {}
      this.loadData(1);
    },
    batchSetStatus: function (status) {
      if(!this.url.batchSetStatusUrl){
        this.$message.error("请设置url.batchSetStatusUrl属性!")
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！');
        return;
      } else {
        var ids = "";
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ",";
        }
        var that = this;
        this.$confirm({
          title: "确认操作",
          content: "是否操作选中数据?",
          onOk: function () {
            that.loading = true;
            postAction(that.url.batchSetStatusUrl, {status: status, ids: ids}).then((res) => {
              if(res.code === 200){
                that.loadData();
                that.onClearSelected();
              } else {
                that.$message.warning(res.data.message);
              }
            }).finally(() => {
              that.loading = false;
            });
          }
        });
      }
    },
    batchDel: function () {
      if(!this.url.deleteBatch){
        this.$message.error("请设置url.deleteBatch属性!")
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！');
        return;
      } else {
        var ids = "";
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ",";
        }
        var that = this;
        this.$confirm({
          title: "确认删除",
          content: "是否删除选中数据?",
          onOk: function () {
            that.loading = true;
            deleteAction(that.url.deleteBatch, {ids: ids}).then((res) => {
              if(res.code === 200){
                that.loadData();
                that.onClearSelected();
              } else {
                that.$message.warning(res.data.message);
              }
            }).finally(() => {
              that.loading = false;
            });
          }
        });
      }
    },
    handleDelete: function (id) {
      if(!this.url.delete){
        this.$message.error("请设置url.delete属性!")
        return
      }
      var that = this;
      deleteAction(that.url.delete, {id: id}).then((res) => {
        if(res.code === 200){
          that.loadData();
        } else {
          that.$message.warning(res.data.message);
        }
      });
    },
    handleEdit: function (record) {
      this.$refs.modalForm.edit(record);
      this.$refs.modalForm.title = "编辑";
      this.$refs.modalForm.disableSubmit = false;
    },
    handleAdd: function () {
      this.$refs.modalForm.add();
      this.$refs.modalForm.title = "新增";
      this.$refs.modalForm.disableSubmit = false;
    },
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field;
        this.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
      }
      if(pagination && pagination.current) {
        this.ipagination = pagination;
      }
      this.loadData();
    },
    handleToggleSearch(){
      this.toggleSearchStatus = !this.toggleSearchStatus;
    },
    // 给popup查询使用(查询区域不支持回填多个字段，限制只返回一个字段)
    getPopupField(fields){
      return fields.split(',')[0]
    },
    modalFormOk() {
      // 新增/修改 成功时，重载列表
      this.loadData();
    },
    handleDetail:function(record, type){
      this.$refs.modalDetail.show(record, type);
      this.$refs.modalDetail.title=type+"-详情";
    },
    /* 导出 */
    handleExportXls2(){
      let paramsStr = encodeURI(JSON.stringify(this.getQueryParams()));
      let url = `${window._CONFIG['domianURL']}/${this.url.exportXlsUrl}?paramsStr=${paramsStr}`;
      window.location.href = url;
    },
    handleExportXls(fileName){
      if(!fileName || typeof fileName != "string"){
        fileName = "导出文件"
      }
      let param = {...this.queryParam};
      if(this.selectedRowKeys && this.selectedRowKeys.length>0){
        param['selections'] = this.selectedRowKeys.join(",")
      }
      console.log("导出参数",param)
      downFile(this.url.exportXlsUrl,param).then((data)=>{
        if (!data) {
          this.$message.warning("文件下载失败")
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data],{type: 'application/vnd.ms-excel'}), fileName+'.xls')
        }else{
          let url = window.URL.createObjectURL(new Blob([data],{type: 'application/vnd.ms-excel'}))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName+'.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link); //下载完成移除元素
          window.URL.revokeObjectURL(url); //释放掉blob对象
        }
      })
    },
    /* 导入 */
    handleImportExcel(info){
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        if (info.file.response) {
          // this.$message.success(`${info.file.name} 文件上传成功`);
          if (info.file.response.code === 200) {
            this.$message.success(info.file.response.data || `${info.file.name} 文件上传成功`)
          } else {
            this.$message.warning(info.file.response.data)
          }
          this.loadData()
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.data}.`);
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`文件上传失败: ${info.file.msg} `);
      }
    },
    /* 图片预览 */
    getImgView(text){
      if(text && text.indexOf(",")>0){
        text = text.substring(0,text.indexOf(","))
      }
      return getFileAccessHttpUrl(text)
    },
    /* 文件下载 */
    uploadFile(text){
      if(!text){
        this.$message.warning("未知的文件")
        return;
      }
      if(text.indexOf(",")>0){
        text = text.substring(0,text.indexOf(","))
      }
      let url = getFileAccessHttpUrl(text)
      window.open(url);
    },
    /* 按钮权限 */
    initActiveBtnStr() {
      let funId = Vue.ls.get('funId'); //功能id
      let btnStrList = Vue.ls.get('winBtnStrList'); //按钮功能列表 JSON字符串
      this.btnEnableList = ""; //按钮列表
      if (funId && btnStrList) {
        for (let i = 0; i < btnStrList.length; i++) {
          if (btnStrList[i].funId == funId) {
            if (btnStrList[i].btnStr) {
              this.btnEnableList = btnStrList[i].btnStr;
            }
          }
        }
      }
    },
    /* 初始化表格横向或纵向滚动 */
    initScroll() {
      if (this.isMobile()) {
        this.scroll.y = ''
      } else {
        let basicLength = 274
        let searchWrapperDomLen=0, operatorDomLen=0
        //搜索区域
        let searchWrapperDom = document.getElementsByClassName('table-page-search-wrapper')
        //操作按钮区域
        let operatorDom = document.getElementsByClassName('table-operator')
        if(searchWrapperDom && searchWrapperDom[0]) {
          searchWrapperDomLen = searchWrapperDom[0].offsetHeight
        }
        if(operatorDom && operatorDom[0]) {
          operatorDomLen = operatorDom[0].offsetHeight+10
        }
        this.scroll.y = document.documentElement.clientHeight-searchWrapperDomLen-operatorDomLen-basicLength
      }
    },
    /** 表格增加合计行 */
    tableAddTotalRow(columns, dataSource) {
      if(dataSource.length>0 && this.ipagination.pageSize%10===1) {
        //分页条数为11、21、31等的时候增加合计行
        let numKey = 'rowIndex'
        let totalRow = { [numKey]: '合计' }
        //移除不需要合计的列
        let removeCols = 'action,mBarCode,barCode,serialNo,unitPrice,purchaseDecimal,operTime,oTime'
        columns.forEach(column => {
          let { key, dataIndex } = column
          if (![key, dataIndex].includes(numKey)) {
            let total = 0
            dataSource.forEach(data => {
              total += Number.parseFloat(data[dataIndex])
            })
            if (Number.isNaN(total)) {
              total = '-'
            } else {
              total = total.toFixed(2)
            }
            if(removeCols.indexOf(dataIndex)>-1) {
              total = '-'
            }
            totalRow[dataIndex] = total
          }
        })
        dataSource.push(totalRow)
      }
    },
    paginationChange(page, pageSize) {
      this.ipagination.current = page
      this.ipagination.pageSize = pageSize
      this.loadData(this.ipagination.current);
    },
    paginationShowSizeChange(current, size) {
      this.ipagination.current = current
      this.ipagination.pageSize = size
      this.loadData(this.ipagination.current);
    }
  }

}<|endoftext|>


<commit_before>var readlineSync = require('readline-sync');
var request = require('request');
var jsonfile = require('jsonfile');
var path = require('path');
var authcontroller = require('./../src/authcontroller');
var config = require('./../cli-config');

authcontroller.authorize()
    .then(function (response) {
        var config;
        var configFilePath = path.join(__dirname, '/../cli-config.json');

        if (response.statusCode === 201) {
            config = jsonfile.readFileSync(configFilePath);
            config.credentials = response.body;
            config.credentials.received = Date.now();
            jsonfile.writeFileSync(configFilePath, config, {
                spaces: 4
            });
            console.log('Authorization completed successfully.');
        } else {
            console.log(response.body.message);
            console.log('Unexpected response: ' + response.statusCode);
            process.exit(1);
        }
    })
    .catch(function(error) {
        console.log('catcher catch');
        console.error(error);
        process.exit(1);
    });<commit_msg>Update appsngen-cli-login.js<commit_after>var jsonfile = require('jsonfile');
var path = require('path');
var authcontroller = require('./../src/authcontroller');
var config = require('./../cli-config');

authcontroller.authorize()
    .then(function (response) {
        var config;
        var configFilePath = path.join(__dirname, '/../cli-config.json');

        if (response.statusCode === 201) {
            config = jsonfile.readFileSync(configFilePath);
            config.credentials = response.body;
            config.credentials.received = Date.now();
            jsonfile.writeFileSync(configFilePath, config, {
                spaces: 4
            });
            console.log('Authorization completed successfully.');
        } else {
            console.log(response.body.message);
            console.log('Unexpected response: ' + response.statusCode);
            process.exit(1);
        }
    })
    .catch(function(error) {
        console.log('catcher catch');
        console.error(error);
        process.exit(1);
    });
<|endoftext|>