<commit_before>'use strict';

module.exports = {
    env: {
        'browser': true,
        'commonjs': true,
        'node': true,
        'es6': true
    },
    extends: 'eslint:recommended',
    rules: {
        // Possible Errors
        'comma-dangle': [2, 'never'],
        'no-cond-assign': 2,
        'no-console': 1,
        'no-constant-condition': 2,
        'no-control-regex': 2,
        'no-debugger': 2,
        'no-dupe-args': 2,
        'no-dupe-keys': 2,
        'no-duplicate-case': 2,
        'no-empty': 2,
        'no-empty-character-class': 2,
        'no-ex-assign': 2,
        'no-extra-boolean-cast': 2,
        'no-extra-parens': 0,
        'no-extra-semi': 2,
        'no-func-assign': 2,
        'no-inner-declarations': [2, 'functions'],
        'no-invalid-regexp': 2,
        'no-irregular-whitespace': 2,
        'no-negated-in-lhs': 2,
        'no-obj-calls': 2,
        'no-regex-spaces': 2,
        'no-sparse-arrays': 2,
        'no-unexpected-multiline': 0,
        'no-unreachable': 2,
        'use-isnan': 2,
        'valid-jsdoc': 0,
        'valid-typeof': 2,

        // Best Practices
        'accessor-pairs': 0,
        'array-callback-return': 2,
        'block-scoped-var': 2,
        'complexity': [0, 11],
        'consistent-return': 0,
        'curly': [2, 'all'],
        'default-case': 2,
        'dot-notation': 2,
        'dot-location': [2, 'property'],
        'eqeqeq': [2, 'smart'],
        'guard-for-in': 2,
        'no-alert': 1,
        'no-caller': 2,
        'no-case-declarations': 2,
        'no-div-regex': 2,
        'no-else-return': 2,
        'no-empty-function': 2,
        'no-empty-pattern': 2,
        'no-eq-null': 2,
        'no-eval': 2,
        'no-extend-native': 2,
        'no-extra-bind': 2,
        'no-extra-label': 2,
        'no-fallthrough': 2,
        'no-floating-decimal': 2,
        'no-implicit-coercion': 2,
        'no-implicit-globals': 2,
        'no-implied-eval': 2,
        'no-invalid-this': 0,
        'no-iterator': 2,
        'no-labels': 2,
        'no-lone-blocks': 2,
        'no-loop-func': 2,
        'no-magic-numbers': 0,
        'no-multi-spaces': 2,
        'no-multi-str': 2,
        'no-native-reassign': 2,
        'no-new': 2,
        'no-new-func': 2,
        'no-new-wrappers': 2,
        'no-octal': 2,
        'no-octal-escape': 2,
        'no-param-reassign': 0,
        'no-process-env': 0,
        'no-proto': 2,
        'no-redeclare': 2,
        'no-return-assign': [2, 'always'],
        'no-script-url': 2,
        'no-self-assign': 2,
        'no-self-compare': 2,
        'no-sequences': 2,
        'no-throw-literal': 2,
        'no-unused-expressions': 2,
        'no-useless-call': 2,
        'no-useless-concat': 2,
        'no-void': 2,
        'no-warning-comments': 1,
        'no-with': 2,
        'radix': 2,
        'vars-on-top': 2,
        'wrap-iife': [2, 'inside'],
        'yoda': 2,

        // Strict Mode
        'strict': [2, 'global'],

        // Variables
        'init-declarations': 0,
        'no-catch-shadow': 2,
        'no-delete-var': 2,
        'no-label-var': 2,
        'no-shadow': 0,
        'no-shadow-restricted-names': 2,
        'no-undef': [2, { typeof: true }],
        'no-undef-init': 2,
        'no-undefined': 2,
        'no-unused-vars': 2,
        'no-use-before-define': [2, 'nofunc'],

        // Node.js CommonJS
        // disabled because of https://github.com/eslint/eslint/issues/3420
        // 'callback-return': [1, ['cb', 'callback', 'next', 'done']],
        'global-require': 1,
        'handle-callback-err': 1,
        'no-mixed-requires': [1, {
            'grouping': true
        }],
        'no-new-require': 2,
        'no-path-concat': 2,
        'no-process-exit': 0,
        'no-restricted-imports': 0,
        'no-restricted-modules': 0,
        'no-sync': 0,

        // Stylistic Issues
        'array-bracket-spacing': [2, 'never'],
        'block-spacing': 0,
        'brace-style': [2, '1tbs', {
            'allowSingleLine': false
        }],
        'camelcase': [2, {
            'properties': 'always'
        }],
        'comma-spacing': [2, {
            'before': false,
            'after': true
        }],
        'comma-style': [2, 'last'],
        'computed-property-spacing': [2, 'never'],
        'consistent-this': [2, 'self'],
        'eol-last': 2,
        'func-names': 0,
        'func-style': [0, 'declaration'],
        'id-blacklist': 0,
        'id-length': 0,
        'id-match': 0,
        'indent': [2, 4, {
            'SwitchCase': 1
        }],
        'jsx-quotes': 2,
        'key-spacing': [2, {
            'beforeColon': false,
            'afterColon': true,
            'mode': 'minimum'
        }],
        'keyword-spacing': 2,
        'linebreak-style': [2, 'unix'],
        'lines-around-comment': 0,
        'max-depth': [0, 4],
        'max-len': [0, 80, 4],
        'max-nested-callbacks': [1, 4],
        'max-params': [0, 3],
        'max-statements': [0, 10],
        'new-cap': 2,
        'new-parens': 2,
        'newline-after-var': [2, 'always'],
        'newline-per-chained-call': 0,
        'no-array-constructor': 2,
        'no-bitwise': 0,
        'no-continue': 2,
        'no-inline-comments': 2,
        'no-lonely-if': 2,
        'no-mixed-spaces-and-tabs': 2,
        'no-multiple-empty-lines': [2, {
            'max': 1
        }],
        'no-negated-condition': 2,
        'no-nested-ternary': 2,
        'no-new-object': 2,
        'no-plusplus': 0,
        'no-restricted-syntax': [2, 'WithStatement'],
        'no-spaced-func': 2,
        'no-ternary': 0,
        'no-trailing-spaces': 2,
        'no-underscore-dangle': 0,
        'no-unneeded-ternary': 2,
        'no-whitespace-before-property': 2,
        'object-curly-spacing': [2, 'never'],
        'one-var': [2, 'never'],
        'one-var-declaration-per-line': 2,
        'operator-assignment': [2, 'always'],
        'operator-linebreak': [2, 'after'],
        'padded-blocks': [2, 'never'],
        'quote-props': [2, 'consistent-as-needed'],
        'quotes': [2, 'single'],
        'require-jsdoc': 0,
        'semi': [2, 'always'],
        'semi-spacing': [2, {
            'before': false,
            'after': true
        }],
        'sort-imports': 0,
        'sort-vars': 0,
        'space-before-blocks': [2, 'always'],
        'space-before-function-paren': [2, {
            'anonymous': 'never',
            'named': 'never'
        }],
        'space-in-parens': [2, 'never'],
        'space-infix-ops': 2,
        'space-unary-ops': 2,
        'spaced-comment': [2, 'always', {
            'exceptions': ['*']
        }],
        'wrap-regex': 0,

        // ECMAScript 6
        'arrow-body-style': [0, 'always'],
        'arrow-parens': [2, 'as-needed'],
        'arrow-spacing': [2, {before: true, after: true}],
        'constructor-super': 2,
        'generator-star-spacing': [2, 'both'],
        'no-class-assign': 2,
        'no-confusing-arrow': 2,
        'no-const-assign': 2,
        'no-dupe-class-members': 2,
        'no-new-symbol': 2,
        'no-this-before-super': 2,
        'no-useless-constructor': 2,
        'no-var': 0,
        'object-shorthand': 0,
        'prefer-arrow-callback': 0,
        'prefer-const': 0,
        'prefer-reflect': 0,
        'prefer-rest-params': 0,
        'prefer-spread': 0,
        'prefer-template': 0,
        'require-yield': 0,
        'template-curly-spacing': 2,
        'yield-star-spacing': [2, 'both']
    }
}
<commit_msg>fix(*): object-curly-spacing to always<commit_after>'use strict';

module.exports = {
    env: {
        'browser': true,
        'commonjs': true,
        'node': true,
        'es6': true
    },
    extends: 'eslint:recommended',
    rules: {
        // Possible Errors
        'comma-dangle': [2, 'never'],
        'no-cond-assign': 2,
        'no-console': 1,
        'no-constant-condition': 2,
        'no-control-regex': 2,
        'no-debugger': 2,
        'no-dupe-args': 2,
        'no-dupe-keys': 2,
        'no-duplicate-case': 2,
        'no-empty': 2,
        'no-empty-character-class': 2,
        'no-ex-assign': 2,
        'no-extra-boolean-cast': 2,
        'no-extra-parens': 0,
        'no-extra-semi': 2,
        'no-func-assign': 2,
        'no-inner-declarations': [2, 'functions'],
        'no-invalid-regexp': 2,
        'no-irregular-whitespace': 2,
        'no-negated-in-lhs': 2,
        'no-obj-calls': 2,
        'no-regex-spaces': 2,
        'no-sparse-arrays': 2,
        'no-unexpected-multiline': 0,
        'no-unreachable': 2,
        'use-isnan': 2,
        'valid-jsdoc': 0,
        'valid-typeof': 2,

        // Best Practices
        'accessor-pairs': 0,
        'array-callback-return': 2,
        'block-scoped-var': 2,
        'complexity': [0, 11],
        'consistent-return': 0,
        'curly': [2, 'all'],
        'default-case': 2,
        'dot-notation': 2,
        'dot-location': [2, 'property'],
        'eqeqeq': [2, 'smart'],
        'guard-for-in': 2,
        'no-alert': 1,
        'no-caller': 2,
        'no-case-declarations': 2,
        'no-div-regex': 2,
        'no-else-return': 2,
        'no-empty-function': 2,
        'no-empty-pattern': 2,
        'no-eq-null': 2,
        'no-eval': 2,
        'no-extend-native': 2,
        'no-extra-bind': 2,
        'no-extra-label': 2,
        'no-fallthrough': 2,
        'no-floating-decimal': 2,
        'no-implicit-coercion': 2,
        'no-implicit-globals': 2,
        'no-implied-eval': 2,
        'no-invalid-this': 0,
        'no-iterator': 2,
        'no-labels': 2,
        'no-lone-blocks': 2,
        'no-loop-func': 2,
        'no-magic-numbers': 0,
        'no-multi-spaces': 2,
        'no-multi-str': 2,
        'no-native-reassign': 2,
        'no-new': 2,
        'no-new-func': 2,
        'no-new-wrappers': 2,
        'no-octal': 2,
        'no-octal-escape': 2,
        'no-param-reassign': 0,
        'no-process-env': 0,
        'no-proto': 2,
        'no-redeclare': 2,
        'no-return-assign': [2, 'always'],
        'no-script-url': 2,
        'no-self-assign': 2,
        'no-self-compare': 2,
        'no-sequences': 2,
        'no-throw-literal': 2,
        'no-unused-expressions': 2,
        'no-useless-call': 2,
        'no-useless-concat': 2,
        'no-void': 2,
        'no-warning-comments': 1,
        'no-with': 2,
        'radix': 2,
        'vars-on-top': 2,
        'wrap-iife': [2, 'inside'],
        'yoda': 2,

        // Strict Mode
        'strict': [2, 'global'],

        // Variables
        'init-declarations': 0,
        'no-catch-shadow': 2,
        'no-delete-var': 2,
        'no-label-var': 2,
        'no-shadow': 0,
        'no-shadow-restricted-names': 2,
        'no-undef': [2, { typeof: true }],
        'no-undef-init': 2,
        'no-undefined': 2,
        'no-unused-vars': 2,
        'no-use-before-define': [2, 'nofunc'],

        // Node.js CommonJS
        // disabled because of https://github.com/eslint/eslint/issues/3420
        // 'callback-return': [1, ['cb', 'callback', 'next', 'done']],
        'global-require': 1,
        'handle-callback-err': 1,
        'no-mixed-requires': [1, {
            'grouping': true
        }],
        'no-new-require': 2,
        'no-path-concat': 2,
        'no-process-exit': 0,
        'no-restricted-imports': 0,
        'no-restricted-modules': 0,
        'no-sync': 0,

        // Stylistic Issues
        'array-bracket-spacing': [2, 'never'],
        'block-spacing': 0,
        'brace-style': [2, '1tbs', {
            'allowSingleLine': false
        }],
        'camelcase': [2, {
            'properties': 'always'
        }],
        'comma-spacing': [2, {
            'before': false,
            'after': true
        }],
        'comma-style': [2, 'last'],
        'computed-property-spacing': [2, 'never'],
        'consistent-this': [2, 'self'],
        'eol-last': 2,
        'func-names': 0,
        'func-style': [0, 'declaration'],
        'id-blacklist': 0,
        'id-length': 0,
        'id-match': 0,
        'indent': [2, 4, {
            'SwitchCase': 1
        }],
        'jsx-quotes': 2,
        'key-spacing': [2, {
            'beforeColon': false,
            'afterColon': true,
            'mode': 'minimum'
        }],
        'keyword-spacing': 2,
        'linebreak-style': [2, 'unix'],
        'lines-around-comment': 0,
        'max-depth': [0, 4],
        'max-len': [0, 80, 4],
        'max-nested-callbacks': [1, 4],
        'max-params': [0, 3],
        'max-statements': [0, 10],
        'new-cap': 2,
        'new-parens': 2,
        'newline-after-var': [2, 'always'],
        'newline-per-chained-call': 0,
        'no-array-constructor': 2,
        'no-bitwise': 0,
        'no-continue': 2,
        'no-inline-comments': 2,
        'no-lonely-if': 2,
        'no-mixed-spaces-and-tabs': 2,
        'no-multiple-empty-lines': [2, {
            'max': 1
        }],
        'no-negated-condition': 2,
        'no-nested-ternary': 2,
        'no-new-object': 2,
        'no-plusplus': 0,
        'no-restricted-syntax': [2, 'WithStatement'],
        'no-spaced-func': 2,
        'no-ternary': 0,
        'no-trailing-spaces': 2,
        'no-underscore-dangle': 0,
        'no-unneeded-ternary': 2,
        'no-whitespace-before-property': 2,
        'object-curly-spacing': [2, 'always'],
        'one-var': [2, 'never'],
        'one-var-declaration-per-line': 2,
        'operator-assignment': [2, 'always'],
        'operator-linebreak': [2, 'after'],
        'padded-blocks': [2, 'never'],
        'quote-props': [2, 'consistent-as-needed'],
        'quotes': [2, 'single'],
        'require-jsdoc': 0,
        'semi': [2, 'always'],
        'semi-spacing': [2, {
            'before': false,
            'after': true
        }],
        'sort-imports': 0,
        'sort-vars': 0,
        'space-before-blocks': [2, 'always'],
        'space-before-function-paren': [2, {
            'anonymous': 'never',
            'named': 'never'
        }],
        'space-in-parens': [2, 'never'],
        'space-infix-ops': 2,
        'space-unary-ops': 2,
        'spaced-comment': [2, 'always', {
            'exceptions': ['*']
        }],
        'wrap-regex': 0,

        // ECMAScript 6
        'arrow-body-style': [0, 'always'],
        'arrow-parens': [2, 'as-needed'],
        'arrow-spacing': [2, {before: true, after: true}],
        'constructor-super': 2,
        'generator-star-spacing': [2, 'both'],
        'no-class-assign': 2,
        'no-confusing-arrow': 2,
        'no-const-assign': 2,
        'no-dupe-class-members': 2,
        'no-new-symbol': 2,
        'no-this-before-super': 2,
        'no-useless-constructor': 2,
        'no-var': 0,
        'object-shorthand': 0,
        'prefer-arrow-callback': 0,
        'prefer-const': 0,
        'prefer-reflect': 0,
        'prefer-rest-params': 0,
        'prefer-spread': 0,
        'prefer-template': 0,
        'require-yield': 0,
        'template-curly-spacing': 2,
        'yield-star-spacing': [2, 'both']
    }
}
<|endoftext|>


<commit_before>const
    Eigen = require('../index.js'),
    PartialPivLU = Eigen.PartialPivLU
    Matrix = Eigen.Matrix,
    should = require('should');

describe('PartialPivLU', function() {
  var mat, mblock, lu, blocklu;

  it('#PartialPivLU() should be a function', function() {
    PartialPivLU.should.be.a.Function;
  });

  beforeEach(function() {
    mat = Matrix(3, 3).set([
      1, 4, 5,
      4, 2, 6,
      5, 6, 3
    ]);
    lu = new PartialPivLU(mat);

    mblock = mat.block(0, 0, 2, 2);
    blocklu = PartialPivLU(mblock);
  });

  it('#PartialPivLU() should be invoked with a Matrix argument', function() {
    lu.should.instanceOf(PartialPivLU);
  });

  it('#PartialPivLU() should be invoked with a MatrixBlock argument', function() {
    blocklu.should.instanceOf(PartialPivLU);
  });

  it('#PartialPivLU() should be invoked with a sequare', function() {
    (function() {
      PartialPivLU(Matrix.Random(2,3));
    }).should.throw("The matrix must be square");

    (function() {
      PartialPivLU(mat.block(0, 0, 2, 3));
    }).should.throw("The matrix must be square");
  });

  it('#permutationP() should return the permutation matrix P', function() {
    PartialPivLU.should.be.a.Function;

    var p = lu.permutationP();
    p.toString().should.equal("0 0 1\n0 1 0\n1 0 0");

    p = blocklu.permutationP();
    p.toString().should.equal("0 1\n1 0");
  });
});
<commit_msg>test: update 'PartialPivLU.permutationP()' testing<commit_after>const
    Eigen = require('../index.js'),
    PartialPivLU = Eigen.PartialPivLU
    Matrix = Eigen.Matrix,
    should = require('should');

describe('PartialPivLU', function() {
  var mat, mblock, lu, blocklu;

  it('#PartialPivLU() should be a function', function() {
    PartialPivLU.should.be.a.Function;
  });

  beforeEach(function() {
    mat = Matrix(3, 3).set([
      1, 4, 5,
      4, 2, 6,
      5, 6, 3
    ]);
    lu = new PartialPivLU(mat);

    mblock = mat.block(0, 0, 2, 2);
    blocklu = PartialPivLU(mblock);
  });

  it('#PartialPivLU() should be invoked with a Matrix argument', function() {
    lu.should.instanceOf(PartialPivLU);
  });

  it('#PartialPivLU() should be invoked with a MatrixBlock argument', function() {
    blocklu.should.instanceOf(PartialPivLU);
  });

  it('#PartialPivLU() should be invoked with a sequare', function() {
    (function() {
      PartialPivLU(Matrix.Random(2,3));
    }).should.throw("The matrix must be square");

    (function() {
      PartialPivLU(mat.block(0, 0, 2, 3));
    }).should.throw("The matrix must be square");
  });

  it('#permutationP() should return the permutation matrix P', function() {
    lu.permutationP.should.be.a.Function;
    blocklu.permutationP.should.be.a.Function;

    var p = lu.permutationP();
    p.toString().should.equal("0 0 1\n0 1 0\n1 0 0");

    p = blocklu.permutationP();
    p.toString().should.equal("0 1\n1 0");
  });
});
<|endoftext|>


<commit_before>/*
  tableRowDeleteButton

  call on a button inside a th, provide a UI for deleting rows
*/
;(function($, undefined) {
    var repaint;
    $.fn.tableRowDeleteButton = function() {
        if ( repaint === undefined ) {
            repaint = function(button) {
                if ( button.closest('table').children('tbody').children('tr.selected:not(.updating)').length > 0 ) {
                    button.removeClass('disabled');
                    button.removeAttr('disabled');
                } else {
                    button.addClass('disabled');
                    button.attr('disabled', true);
                }
            }
        }
        var buttons = this;
        buttons.each(function() {
            var button = $(this);
            var tbody = button.closest('table').children('tbody');

            tbody.children('tr').children(':nth-child(' + (button.closest('th').index() + 1) + ')').addClass('row-selector');

            tbody.on('click.tableRowDeleteButton', 'td.row-selector', function(event) {
                $(event.currentTarget).parent().toggleClass('selected');
                repaint(button);
            });

            button.on('click.tableRowDeleteButton', function() {
                if ( ! button.hasClass('disabled') ) {
                    var rows = tbody.children('.selected:not(.updating)');
		    if ( window.confirm("Delete these " + rows.length + " records?") ) {
                        rows.each(function(i, row) {
                            if ( $(row).dbRow('option', 'type') === 'add' ) {
                                if ( $(row).dbRow('getState') === 'dirty'
                                     || $(row).dbRow('getState') === 'error' ) {
                                    tbody.parent().dbGrid('removeRow', $(row));
                                } else {
                                    $(row).removeClass('selected');
                                }
                            } else {
                                $(row).dbRow('delete', true);
                            }
                        });
                        repaint(button);
                    }
                }
            });

            button.on('mousedown.tableRowDeleteButton', function() {
                button.addClass('clicking');
                button.one('mouseup.tableRowDeleteButton mouseleave.tableRowDeleteButton', function() {
                    button.removeClass('clicking');
                });
            });

            tbody.parent().on('dbRowStateChange.tableRowDeleteButton', repaint.bind(this, button));

            repaint(button);
        });
        return buttons;
    }
})(jQuery);<commit_msg>Comments<commit_after>/*
  tableRowDeleteButton

  call on a button inside a th, provide a UI for deleting rows
  depends on dbGrid for delete functionality

  each tbody cell in the column containing the button gains class "row-selector", and becomes clickable.
  selected row gain the "selected" class, and are deleted if the user clicks the button, then confirms.
*/
;(function($, undefined) {
    var repaint;

    $.fn.tableRowDeleteButton = function() {

        // Initialise the repaint function
        if ( repaint === undefined ) {
            repaint = function(button) {
                if ( button.closest('table').children('tbody').children('tr.selected:not(.updating)').length > 0 ) {
                    button.removeClass('disabled');
                    button.removeAttr('disabled');
                } else {
                    button.addClass('disabled');
                    button.attr('disabled', true); // Possibly should use $().prop(), but that breaks theadFixed
                }
            }
        }

        var buttons = this;
        buttons.each(function() {
            var button = $(this);
            var tbody = button.closest('table').children('tbody');

            // Add row selector class to all tbody cells in this column
            tbody.children('tr').children(':nth-child(' + (button.closest('th').index() + 1) + ')')
                .addClass('row-selector');

            // Delegated event listener for selecting a row
            tbody.on('click.tableRowDeleteButton', 'td.row-selector', function(event) {
                $(event.currentTarget).parent().toggleClass('selected');
                repaint(button);
            });

            // Event listener for clicking the delete button
            button.on('click.tableRowDeleteButton', function() {
                if ( ! button.hasClass('disabled') ) {
                    var rows = tbody.children('.selected:not(.updating)');
		    if ( window.confirm("Delete these " + rows.length + " records?") ) {
                        rows.each(function(i, row) {
                            if ( $(row).dbRow('option', 'type') === 'add' ) {
                                if ( $(row).dbRow('getState') === 'dirty'
                                     || $(row).dbRow('getState') === 'error' ) {
                                    // No db interaction if row has not been "added"
                                    tbody.parent().dbGrid('removeRow', $(row));
                                } else {
                                    // Do not remove unmodified "add" row
                                    $(row).removeClass('selected');
                                }
                            } else {
                                $(row).dbRow('delete', true);
                            }
                        });
                        repaint(button);
                    }
                }
            });

            // Event listeners to animate the "click" action with class "clicking"
            button.on('mousedown.tableRowDeleteButton', function() {
                button.addClass('clicking');
                button.one('mouseup.tableRowDeleteButton mouseleave.tableRowDeleteButton', function() {
                    button.removeClass('clicking');
                });
            });

            tbody.parent().on('dbRowStateChange.tableRowDeleteButton', repaint.bind(this, button));

            repaint(button);
        });

        // Enable jQuery plugin chaining
        return buttons;
    }
})(jQuery);<|endoftext|>


<commit_before>import React from 'react';
import FocusTrap from 'focus-trap-react';
import {Cropper} from 'react-image-cropper';
import changeUserData from '../../../actions/user/userprofile/changeUserData';
import { Button, Icon, Modal, Container, Segment, Menu,Label,Input,Divider, TextArea} from 'semantic-ui-react';

class ChangePictureModal extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            openModal: false,
            activeTrap: false
        };

        this.handleOpen = this.handleOpen.bind(this);
        this.handleClose = this.handleClose.bind(this);
        this.unmountTrap = this.unmountTrap.bind(this);
        this.uploadCroppedPicture = this.uploadCroppedPicture.bind(this);
    }

    handleOpen(){
        $('#app').attr('aria-hidden','true');
        this.setState({
            modalOpen:true,
            activeTrap:true
        });
    }

    handleClose(){
        $('#app').attr('aria-hidden','false');
        this.setState({
            modalOpen:false,
            activeTrap: false
        });
    }

    unmountTrap(){
        if(this.state.activeTrap){
            this.setState({ activeTrap: false });
            $('#app').attr('aria-hidden','false');
        }
    }

    uploadCroppedPicture(e) {
        let payload = {};
        Object.assign(payload, this.props.user);
        payload.picture = this.refs.cropper.crop({ maxWidth: 170 });
        if(payload.picture.length > 50){ //check if this is a picture or not - if not, the base64 repesentation is about 5 chars
            this.context.executeAction(changeUserData, payload);
            this.handleClose();
        } else {
            this.handleClose();
            swal({
                title: 'A wild error has been spotted!',
                text: 'There it is. You catched it! - Seems like we can not handle your picture. Please try another one.',
                type: 'error',
                confirmButtonClass: 'ui primary button',
                buttonsStyling: false
            });
        }
    }

    render() {
        return (
          <Modal trigger={
                  <Button tabIndex='-1' id="ChangePictureModalOpenButton" aria-hidden={this.state.modalOpen} basic onClick={this.handleOpen} style={{'display': 'none'}}/>
                 }
              open={this.state.modalOpen}
              onClose={this.handleClose}
              size="large"
              role="dialog"
              id="ChangePictureModal"
              aria-labelledby="ChangePictureModalHeader"
              aria-describedby="ChangePictureModalDescription"
              tabIndex="0">
              <FocusTrap
                  id='focus-trap-ChangePictureModal'
                  className = "header"
                  active={this.state.activeTrap}
                  focusTrapOptions={{
                      onDeactivate: this.unmountTrap,
                      clickOutsideDeactivates: false,
                      initialFocus: '#ChangePictureModalCancelButton',
                  }}>
                  <Modal.Header className="ui left aligned" as="h1" id="ChangePictureModalHeader">
                      Crop your image
                  </Modal.Header>
                  <Modal.Content>
                      <Divider />
                      <TextArea className="sr-only" id="ChangePictureModalDescription" value="This modal is used to crop and save a picture meant to be used as a user-profile picture." />
                      <Cropper src={this.props.filePath} ref="cropper" fixedRatio={true} rate={1}/>
                      <Divider />
                      <Modal.Actions className="ui center aligned" as="div" style={{'text-align': 'right'}}>
                        <Button id="ChangePictureModalCancelButton" color='red' tabIndex="0" type="button" aria-label="Cancel" onClick={this.handleClose} icon="minus circle" labelPosition='left' content="Cancel"/>
                        <Button color="green" tabIndex="0" type="button" aria-label="Save" onClick={this.uploadCroppedPicture} icon="save" labelPosition='left' content="Save"/>
                      </Modal.Actions>
                  </Modal.Content>
              </FocusTrap>
          </Modal>
        );
    }
}

ChangePictureModal.contextTypes = {
    executeAction: React.PropTypes.func.isRequired
};

export default ChangePictureModal;
<commit_msg>Resolved react warning<commit_after>import React from 'react';
import FocusTrap from 'focus-trap-react';
import {Cropper} from 'react-image-cropper';
import changeUserData from '../../../actions/user/userprofile/changeUserData';
import { Button, Icon, Modal, Container, Segment, Menu,Label,Input,Divider, TextArea} from 'semantic-ui-react';

class ChangePictureModal extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            openModal: false,
            activeTrap: false
        };

        this.handleOpen = this.handleOpen.bind(this);
        this.handleClose = this.handleClose.bind(this);
        this.unmountTrap = this.unmountTrap.bind(this);
        this.uploadCroppedPicture = this.uploadCroppedPicture.bind(this);
    }

    handleOpen(){
        $('#app').attr('aria-hidden','true');
        this.setState({
            modalOpen:true,
            activeTrap:true
        });
    }

    handleClose(){
        $('#app').attr('aria-hidden','false');
        this.setState({
            modalOpen:false,
            activeTrap: false
        });
    }

    unmountTrap(){
        if(this.state.activeTrap){
            this.setState({ activeTrap: false });
            $('#app').attr('aria-hidden','false');
        }
    }

    uploadCroppedPicture(e) {
        let payload = {};
        Object.assign(payload, this.props.user);
        payload.picture = this.refs.cropper.crop({ maxWidth: 170 });
        if(payload.picture.length > 50){ //check if this is a picture or not - if not, the base64 repesentation is about 5 chars
            this.context.executeAction(changeUserData, payload);
            this.handleClose();
        } else {
            this.handleClose();
            swal({
                title: 'A wild error has been spotted!',
                text: 'There it is. You catched it! - Seems like we can not handle your picture. Please try another one.',
                type: 'error',
                confirmButtonClass: 'ui primary button',
                buttonsStyling: false
            });
        }
    }

    render() {
        return (
          <Modal trigger={
                  <Button tabIndex='-1' id="ChangePictureModalOpenButton" aria-hidden={this.state.modalOpen} basic onClick={this.handleOpen} style={{'display': 'none'}}/>
                 }
              open={this.state.modalOpen}
              onClose={this.handleClose}
              size="large"
              role="dialog"
              id="ChangePictureModal"
              aria-labelledby="ChangePictureModalHeader"
              aria-describedby="ChangePictureModalDescription"
              tabIndex="0">
              <FocusTrap
                  id='focus-trap-ChangePictureModal'
                  className = "header"
                  active={this.state.activeTrap}
                  focusTrapOptions={{
                      onDeactivate: this.unmountTrap,
                      clickOutsideDeactivates: false,
                      initialFocus: '#ChangePictureModalCancelButton',
                  }}>
                  <Modal.Header className="ui left aligned" as="h1" id="ChangePictureModalHeader">
                      Crop your image
                  </Modal.Header>
                  <Modal.Content>
                      <Divider />
                      <TextArea className="sr-only" id="ChangePictureModalDescription" value="This modal is used to crop and save a picture meant to be used as a user-profile picture." />
                      <Cropper src={this.props.filePath} ref="cropper" fixedRatio={true} rate={1}/>
                      <Divider />
                      <Modal.Actions className="ui center aligned" as="div" style={{'textAlign': 'right'}}>
                        <Button id="ChangePictureModalCancelButton" color='red' tabIndex="0" type="button" aria-label="Cancel" onClick={this.handleClose} icon="minus circle" labelPosition='left' content="Cancel"/>
                        <Button color="green" tabIndex="0" type="button" aria-label="Save" onClick={this.uploadCroppedPicture} icon="save" labelPosition='left' content="Save"/>
                      </Modal.Actions>
                  </Modal.Content>
              </FocusTrap>
          </Modal>
        );
    }
}

ChangePictureModal.contextTypes = {
    executeAction: React.PropTypes.func.isRequired
};

export default ChangePictureModal;
<|endoftext|>


<commit_before>import React from 'react';
import { connect } from 'react-redux';
import TableRow from './TableRow';
import Pagination from './Pagination';
import Button from './Button';
import FilterInput from './FilterInput';
import TableHeaderItem from './TableHeaderItem';

import { selectRow, deleteRow, changePage, setFilter, setSortDef } from './../actions/table';

const UNSELECTED = -1;

class Table extends React.Component {

  constructor(props) {
    super(props);

    this.onAddNewRow = this.onAddNewRow.bind(this);
    this.onDeleteRow = this.onDeleteRow.bind(this);
    this.onEditRow = this.onEditRow.bind(this);
    this.onSelectRow = this.onSelectRow.bind(this);
    this.onChangePageIndex = this.onChangePageIndex.bind(this);
    this.onHandleFilter = this.onHandleFilter.bind(this);
    this.onHandleSortColumn = this.onHandleSortColumn.bind(this);
  }

  onAddNewRow() {
    if (this.props.onAddRow) {
      this.props.onAddRow();
    }
  }

  onDeleteRow(rowId) {
    let { dispatch } = this.props;
    dispatch(deleteRow(rowId));

    if (this.props.onDeleteRow) {
      this.props.onDeleteRow(rowId);
    }
  }

  onEditRow(rowId) {
    if (this.props.onEditRow) {
      this.props.onEditRow(rowId);
    }
  }

  onSelectRow(rowId) {
    let selectedRowId = (this.props.selectedRowId === rowId) ? UNSELECTED : rowId;
    let { dispatch } = this.props;
    dispatch(selectRow(selectedRowId));

    if (this.props.onSelectRow && typeof(this.props.onSelectRow) === 'function') {
      this.props.onSelectRow(rowId);
    }
  }

  onChangePageIndex(index) {
    if (index < 0) {
      return;
    }

    let { dispatch } = this.props;
    dispatch(changePage(index));
  }

  onHandleFilter(value) {
    let { dispatch } = this.props;
    dispatch(setFilter(value));
  }

  onHandleSortColumn(columnIndex) {
    if (this.props.tools) {
      columnIndex -= 1;
    }

    let sd = this.props.sortDirection;
    if (sd === TableHeaderItem.SORT_NOPE) {
      sd = TableHeaderItem.SORT_ASCENDING;
    }

    let scdv = 1;
    if (this.props.sortColumnIndex === columnIndex) {
      scdv = TableHeaderItem.SORT_CHANGE_DIRECTION;
    }

    let { dispatch } = this.props;
    dispatch(setSortDef(columnIndex, sd * scdv));
  }

  prepRows(records, cp, ps) {
    let rows = [];

    for (let i = 0, cri = cp * ps; cri < records.length && i < ps; i++, cri++) {
      let Row = (
        <TableRow
          data={records[cri]}
          key={`row-${cri}`}
          rowId={cri}
          selected={this.props.selectedRowId === cri}
          tools={this.props.tools}
          onDelete={this.onDeleteRow}
          onEdit={this.onEditRow}
          onSelect={this.onSelectRow}
        />);
      rows.push(Row);
    }

    return rows;
  }

  prepHeader(header, tools) {
    let output = [];

    if (tools && header.length > 0) {
      let th = (<TableHeaderItem key={output.length} colId={output.length} />);
      output.push(th);
    }

    for (let i = 0; i < header.length; i++) {
      let sorted = TableHeaderItem.SORT_NOPE;
      if (i === this.props.sortColumnIndex) {
        sorted = this.props.sortDirection;
      }

      let th = (
        <TableHeaderItem
          sorted={sorted}
          key={output.length}
          colId={output.length}
          title={header[i]}
          onClick={this.onHandleSortColumn}
        />);
      output.push(th);
    }

    return output;
  }

  renderSectionHeader() {
    return (

        <FilterInput onKeyUp={this.onHandleFilter} />

          <Button cn={" btn-primary"} title={"Add new row"} onClick={this.onAddNewRow} />

);
  }

  renderSectionBody(header, rows) {
    return (

              {header}

            {rows}

);
  }

  renderSectionFooter(records, pageCount, pageSize) {
    return (

        {(() => {
          if (records.length > pageSize) {
            return (
              <Pagination
                current={this.props.activePage}
                pageCount={pageCount}
                onChange={this.onChangePageIndex}
              />);
          }
          return '';
        })()}

    );
  }

  render() {
    let pageSize = this.props.pageSize;
    let ap = this.props.activePage;

    let pageCount = Math.ceil(this.props.data.length / pageSize);

    let header = this.prepHeader(this.props.header, this.props.tools);
    let rows = this.prepRows(this.props.data, ap, pageSize);

    return (

        {this.renderSectionHeader()}
        {this.renderSectionBody(header, rows)}
        {this.renderSectionFooter(this.props.data, pageCount, pageSize)}

);
  }
}

Table.defaultProps = {
  activePage: 0,
  pageSize: 10,
  tools: true,
  sortColumnIndex: UNSELECTED,
  sortDirection: TableHeaderItem.SORT_NOPE,
  selectedRowId: UNSELECTED,
  minFilterSize: 3
};

Table.propTypes = {
  activePage: React.PropTypes.number,
  data: React.PropTypes.array.isRequired,
  header: React.PropTypes.arrayOf(React.PropTypes.string),
  tools: React.PropTypes.bool,
  sortDirection: React.PropTypes.number,
  selectedRowId: React.PropTypes.number,
  minFilterSize: React.PropTypes.number,

  onDeleteRow: React.PropTypes.func,
  onAddRow: React.PropTypes.func,
  onEditRow: React.PropTypes.func,
  onSelectRow: React.PropTypes.func
};

function filterRecords(data, filterValue) {
  let records = data;

  if (filterValue !== '') {
    records = data.filter((row) => {
      let value = row.join();
      if (value.indexOf(filterValue) >= 0) {
        return value;
      }

      return false;
    });
  }

  return records;
}

function sortRecords(data, sortColumnIndex, sortDirection) {

    let records = data;
    records.sort((a, b) => {
      let v1 = a[sortColumnIndex];
      let v2 = b[sortColumnIndex];
      return sortDirection * v1.localeCompare(v2);
    });

    return records;
}

function shouldSort(state) {
  return (state.table.sortColumnIndex !== undefined);
}

function shouldFilter(state, ownProps) {
  let filterValue = state.table.filterValue || '';
  let prevFilterValue = state.table.prevFilterValue || '';
  let minFilterSize = ownProps.minFilterSize ? ownProps.minFilterSize : Table.defaultProps.minFilterSize;

  return (filterValue.length >= minFilterSize && filterValue !== prevFilterValue);
}

function mapStateToProps(state, ownProps) {
  let records = state.table.data;
  if (shouldFilter(state, ownProps)) {
    records = filterRecords(state.table.data, state.table.filterValue);
  }

  if (shouldSort(state)) {
    records = sortRecords(records, state.table.sortColumnIndex, state.table.sortDirection);
  }

  return {
    selectedRowId: state.table.selectedRowId,
    data: records,
    header: state.table.header,
    activePage: state.table.activePage,
    sortDirection: state.table.sortDirection || TableHeaderItem.SORT_NOPE,
    sortColumnIndex: state.table.sortColumnIndex === undefined ? UNSELECTED : state.table.sortColumnIndex
  }
}

export default connect(mapStateToProps)(Table);
<commit_msg>eslint warning & errors<commit_after>import React from 'react';
import { connect } from 'react-redux';
import TableRow from './TableRow';
import Pagination from './Pagination';
import Button from './Button';
import FilterInput from './FilterInput';
import TableHeaderItem from './TableHeaderItem';

import { selectRow, deleteRow, changePage, setFilter, setSortDef } from './../actions/table';

const UNSELECTED = -1;

class Table extends React.Component {

  constructor(props) {
    super(props);

    this.onAddNewRow = this.onAddNewRow.bind(this);
    this.onDeleteRow = this.onDeleteRow.bind(this);
    this.onEditRow = this.onEditRow.bind(this);
    this.onSelectRow = this.onSelectRow.bind(this);
    this.onChangePageIndex = this.onChangePageIndex.bind(this);
    this.onHandleFilter = this.onHandleFilter.bind(this);
    this.onHandleSortColumn = this.onHandleSortColumn.bind(this);
  }

  onAddNewRow() {
    if (this.props.onAddRow) {
      this.props.onAddRow();
    }
  }

  onDeleteRow(rowId) {
    let { dispatch } = this.props;
    dispatch(deleteRow(rowId));

    if (this.props.onDeleteRow) {
      this.props.onDeleteRow(rowId);
    }
  }

  onEditRow(rowId) {
    if (this.props.onEditRow) {
      this.props.onEditRow(rowId);
    }
  }

  onSelectRow(rowId) {
    let selectedRowId = (this.props.selectedRowId === rowId) ? UNSELECTED : rowId;
    let { dispatch } = this.props;
    dispatch(selectRow(selectedRowId));

    if (this.props.onSelectRow && typeof this.props.onSelectRow === 'function') {
      this.props.onSelectRow(rowId);
    }
  }

  onChangePageIndex(index) {
    if (index < 0) {
      return;
    }

    let { dispatch } = this.props;
    dispatch(changePage(index));
  }

  onHandleFilter(value) {
    let { dispatch } = this.props;
    dispatch(setFilter(value));
  }

  onHandleSortColumn(columnIndex) {
    if (this.props.tools) {
      columnIndex -= 1;
    }

    let sd = this.props.sortDirection;
    if (sd === TableHeaderItem.SORT_NOPE) {
      sd = TableHeaderItem.SORT_ASCENDING;
    }

    let scdv = 1;
    if (this.props.sortColumnIndex === columnIndex) {
      scdv = TableHeaderItem.SORT_CHANGE_DIRECTION;
    }

    let { dispatch } = this.props;
    dispatch(setSortDef(columnIndex, sd * scdv));
  }

  prepRows(records, cp, ps) {
    let rows = [];

    for (let i = 0, cri = cp * ps; cri < records.length && i < ps; i++, cri++) {
      let Row = (
        <TableRow
          data={records[cri]}
          key={`row-${cri}`}
          rowId={cri}
          selected={this.props.selectedRowId === cri}
          tools={this.props.tools}
          onDelete={this.onDeleteRow}
          onEdit={this.onEditRow}
          onSelect={this.onSelectRow}
        />);
      rows.push(Row);
    }

    return rows;
  }

  prepHeader(header, tools) {
    let output = [];

    if (tools && header.length > 0) {
      let th = (<TableHeaderItem key={output.length} colId={output.length} />);
      output.push(th);
    }

    for (let i = 0; i < header.length; i++) {
      let sorted = TableHeaderItem.SORT_NOPE;
      if (i === this.props.sortColumnIndex) {
        sorted = this.props.sortDirection;
      }

      let th = (
        <TableHeaderItem
          sorted={sorted}
          key={output.length}
          colId={output.length}
          title={header[i]}
          onClick={this.onHandleSortColumn}
        />);
      output.push(th);
    }

    return output;
  }

  renderSectionHeader() {
    return (

        <FilterInput onKeyUp={this.onHandleFilter} />

          <Button cn={" btn-primary"} title={"Add new row"} onClick={this.onAddNewRow} />

);
  }

  renderSectionBody(header, rows) {
    return (

              {header}

            {rows}

);
  }

  renderSectionFooter(records, pageCount, pageSize) {
    return (

        {(() => {
          if (records.length > pageSize) {
            return (
              <Pagination
                current={this.props.activePage}
                pageCount={pageCount}
                onChange={this.onChangePageIndex}
              />);
          }
          return '';
        })()}

    );
  }

  render() {
    let pageSize = this.props.pageSize;
    let ap = this.props.activePage;

    let pageCount = Math.ceil(this.props.data.length / pageSize);

    let header = this.prepHeader(this.props.header, this.props.tools);
    let rows = this.prepRows(this.props.data, ap, pageSize);

    return (

        {this.renderSectionHeader()}
        {this.renderSectionBody(header, rows)}
        {this.renderSectionFooter(this.props.data, pageCount, pageSize)}

);
  }
}

Table.defaultProps = {
  activePage: 0,
  pageSize: 10,
  tools: true,
  sortColumnIndex: UNSELECTED,
  sortDirection: TableHeaderItem.SORT_NOPE,
  selectedRowId: UNSELECTED,
  minFilterSize: 3
};

Table.propTypes = {
  activePage: React.PropTypes.number,
  data: React.PropTypes.array.isRequired,
  header: React.PropTypes.arrayOf(React.PropTypes.string),
  tools: React.PropTypes.bool,
  sortDirection: React.PropTypes.number,
  selectedRowId: React.PropTypes.number,
  minFilterSize: React.PropTypes.number,

  onDeleteRow: React.PropTypes.func,
  onAddRow: React.PropTypes.func,
  onEditRow: React.PropTypes.func,
  onSelectRow: React.PropTypes.func
};

function filterRecords(data, filterValue) {
  let records = data;

  if (filterValue !== '') {
    records = data.filter((row) => {
      let value = row.join();
      if (value.indexOf(filterValue) >= 0) {
        return value;
      }

      return false;
    });
  }

  return records;
}

function sortRecords(data, sortColumnIndex, sortDirection) {
  let records = data;
  records.sort((a, b) => {
    let v1 = a[sortColumnIndex];
    let v2 = b[sortColumnIndex];
    return sortDirection * v1.localeCompare(v2);
  });

  return records;
}

function shouldSort(state) {
  return (state.table.sortColumnIndex !== undefined);
}

function shouldFilter(state, ownProps) {
  let filterValue = state.table.filterValue || '';
  let prevFilterValue = state.table.prevFilterValue || '';
  let minFilterSize = ownProps.minFilterSize ?
    ownProps.minFilterSize : Table.defaultProps.minFilterSize;

  return (filterValue.length >= minFilterSize && filterValue !== prevFilterValue);
}

function mapStateToProps(state, ownProps) {
  let records = state.table.data;
  if (shouldFilter(state, ownProps)) {
    records = filterRecords(state.table.data, state.table.filterValue);
  }

  if (shouldSort(state)) {
    records = sortRecords(records, state.table.sortColumnIndex, state.table.sortDirection);
  }

  return {
    selectedRowId: state.table.selectedRowId,
    data: records,
    header: state.table.header,
    activePage: state.table.activePage,
    sortDirection: state.table.sortDirection || TableHeaderItem.SORT_NOPE,
    sortColumnIndex: state.table.sortColumnIndex === undefined ?
      UNSELECTED : state.table.sortColumnIndex
  };
}

export default connect(mapStateToProps)(Table);
<|endoftext|>


<commit_before>import { DragAndDrop } from 'ol/interaction';
import { GPX, IGC,KML,  TopoJSON, GeoJSON } from 'ol/format';
import SparqlJson from 'hs.source.SparqlJson'
import WfsSource from 'hs.source.Wfs'
import 'components/styles/styles.module';
import * as loadingstrategy from 'ol/loadingstrategy';
import {transform, transformExtent, get as getProj} from 'ol/proj';
import { Vector } from 'ol/source';
import VectorLayer from 'ol/layer/Vector';

/**
 * @namespace hs.addLayersVector
 * @memberOf hs
 */
angular.module('hs.addLayersVector', ['hs.styles'])
    /**
    * @memberof hs.ows
    * @ngdoc directive
    * @name hs.addLayersVector
    * @description TODO
    */
   .directive('hs.addLayersVector', ['config', function (config) {
        return {
            template: require('components/add-layers/partials/add-vector-layer.directive.html')
        };
    }])
    /**
    * @memberof hs.addLayersVector
    * @ngdoc service
    * @name hs.addLayersVector.service
    * @description Service handling adding nonwms OWS services or files. Handles also drag and drop addition.
    */
    .service('hs.addLayersVector.service', ['config', 'Core', '$rootScope', 'hs.map.service', 'hs.styles.service', 'hs.utils.service', '$http', 'hs.statusManagerService', 'hs.permalink.urlService',
        function (config, Core, $rootScope, OlMap, styles, utils, $http, statusManagerService, permalink) {
            var me = this;

            /**
            * Load nonwms OWS data and create layer
            * @memberof hs.addLayers
            * @function add
            * @param {String} type Type of data to load (supports Kml, Geojson, Wfs and Sparql)
            * @param {String} url Url of data/service localization
            * @param {String} title Title of new layer
            * @param {String} abstract Abstract of new layer
            * @param {Boolean} extract_styles Extract styles
            * @param {String} srs EPSG code of selected projection (eg. "EPSG:4326")
            * @param {Object} options Other options
            */
            me.add = function (type, url, title, abstract, extract_styles, srs, options) {
                var format;
                var definition = {};
                var src;
                definition.url = url;
                if (angular.isUndefined(options)) {
                    var options = {};
                }

                if (type.toLowerCase() != 'sparql' && angular.isDefined(url)) {
                    url = utils.proxify(url);
                }

                if(type=='kml' || url.toLowerCase().endsWith('kml')){
                    format = new KML({
                        extractStyles: extract_styles
                    });
                    definition.format = "ol.format.KML";
                }
                if(type=='geojson' || url.toLowerCase().endsWith('geojson') || url.toLowerCase().endsWith('json')){
                    format = new GeoJSON();
                    definition.format = "ol.format.GeoJSON";
                }
                if(url.toLowerCase().endsWith('gpx')){
                    format = new GPX();
                    definition.format = "ol.format.GPX";
                }
                if(type.toLowerCase() == "sparql"){
                    definition.format = "hs.format.Sparql";
                }
                if (definition.format == 'hs.format.Sparql') {
                    src = new SparqlJson({
                        geom_attribute: '?geom',
                        url: url,
                        category_field: 'http://www.openvoc.eu/poi#categoryWaze',
                        projection: 'EPSG:3857',
                        minResolution: 1,
                        maxResolution: 38
                        //feature_loaded: function(feature){feature.set('hstemplate', 'hs.geosparql_directive')}
                    });
                } else if (definition.format == 'hs.format.WFS') {
                    src = new WfsSource(options.defOptions);
                } else if (angular.isDefined(options.features)) {
                    src = createVectorSourceFromFeatures(srs, options);
                    OlMap.map.getView().fit(src.getExtent(), OlMap.map.getSize());
                } else {
                    src = createVectorSource(format, url, extract_styles, srs)
                }
                //src.set('loaded', true); Should be set when ajax call finishes
                src.set('from_composition', options.from_composition || false);
                var lyr = new VectorLayer({
                    abstract: abstract,
                    definition: definition,
                    from_composition: options.from_composition || false,
                    opacity: options.opacity || 1,
                    saveState: true,
                    source: src,
                    style: options.style,
                    title: title
                });

                var key = src.on('propertychange', function (event) {
                    if (event.key == 'loaded') {
                        if (event.oldValue == false) {
                            $rootScope.$broadcast('layermanager.layer_loaded', lyr)
                        } else {
                            $rootScope.$broadcast('layermanager.layer_loading', lyr)
                        }
                    };
                })

                var listenerKey = src.on('change', function (e) {
                    if (src.getState() == 'ready' && (angular.isUndefined(src.get('from_composition')) || !src.get('from_composition'))) {
                        if (src.getFeatures().length == 0) return;
                        var extent = src.getExtent(); //src.unByKey(listenerKey);
                        if (!isNaN(extent[0]) && !isNaN(extent[1]) && !isNaN(extent[2]) && !isNaN(extent[3]))
                            OlMap.map.getView().fit(extent, OlMap.map.getSize());
                    }
                });

                if (options.from_composition != true) {
                    OlMap.map.addLayer(lyr);
                }
                return lyr;
            };

            function createVectorSource(format, url, extract_styles, srs){
                var src = new Vector({
                    format: format,
                    url: url,
                    projection: getProj(srs),
                    extractStyles: extract_styles,
                    loader: function (extent, resolution, projection) {
                        this.set('loaded', false);
                        var me = this;
                        $http({ url: url }). //context: this?
                            then(function (response) {
                                var data = response.data;
                                if (data.type == 'GeometryCollection') {
                                    var temp = {
                                        type: "Feature",
                                        geometry: data
                                    };
                                    data = temp;
                                }
                                me.addFeatures(format.readFeatures(data, {
                                    dataProjection: srs,
                                    featureProjection: OlMap.map.getView().getProjection().getCode()
                                }));

                                //TODO probably we should not do this. Have to check when styler is operational
                                src.hasLine = false;
                                src.hasPoly = false;
                                src.hasPoint = false;
                                angular.forEach(src.getFeatures(), function (f) {
                                    if (f.getGeometry()) {
                                        switch (f.getGeometry().getType()) {
                                            case 'LineString' || 'MultiLineString':
                                                src.hasLine = true;
                                                break;
                                            case 'Polygon' || 'MultiPolygon':
                                                src.hasPoly = true;
                                                break;
                                            case 'Point' || 'MultiPoint':
                                                src.hasPoint = true;
                                                break;
                                        }
                                    }
                                })

                                if (src.hasLine || src.hasPoly || src.hasPoint) {
                                    src.styleAble = true;
                                }
                                me.set('loaded', true);

                            }, function (err) {
                                me.error = true;
                                me.errorMessage = err.status;
                                me.set('loaded', true);
                            });
                    },
                    strategy: loadingstrategy.all
                });
                return src;
            }

            function createVectorSourceFromFeatures(srs, options){
                var src = new Vector({
                    projection: srs,
                    features: options.features
                });

                src.hasLine = false;
                src.hasPoly = false;
                src.hasPoint = false;
                angular.forEach(src.getFeatures(), function (f) {
                    if (f.getGeometry()) {
                        switch (f.getGeometry().getType()) {
                            case 'LineString' || 'MultiLineString':
                                src.hasLine = true;
                                break;
                            case 'Polygon' || 'MultiPolygon':
                                src.hasPoly = true;
                                break;
                            case 'Point' || 'MultiPoint':
                                src.hasPoint = true;
                                break;
                        }
                    }
                })

                if (src.hasLine || src.hasPoly || src.hasPoint) {
                    src.styleAble = true;
                }

                return src;
            }
            /**
            * (PRIVATE) Zoom to selected vector layer
            * @memberof hs.addLayers
            * @function zoomToVectorLayer
            * @param {ol.Layer} lyr New layer
            */
            function zoomToVectorLayer(lyr) {
                Core.setMainPanel('layermanager');
                lyr.getSource().on('change', function () { //Event needed because features are loaded asynchronously
                    var extent = lyr.getSource().getExtent();
                    if (extent != null) OlMap.map.getView().fit(extent, OlMap.map.getSize());
                });
            }

            me.checkUrlParamsAndAdd = function(){
                var title = decodeURIComponent(permalink.getParamValue('title')) || 'Layer';
                var abstract = decodeURIComponent(permalink.getParamValue('abstract'));

                if (permalink.getParamValue('geojson_to_connect')) {
                    var url = permalink.getParamValue('geojson_to_connect');
                    var type = 'geojson';
                    if (url.indexOf('gpx') > 0) type = 'gpx';
                    if (url.indexOf('kml') > 0) type = 'kml';
                    var lyr = me.add(type, url, title, abstract, false, 'EPSG:4326');
                    zoomToVectorLayer(lyr);
                }

                if (permalink.getParamValue('kml_to_connect')) {
                    var url = permalink.getParamValue('kml_to_connect');
                    var lyr = me.add('kml', url, title, abstract, true, 'EPSG:4326');
                    zoomToVectorLayer(lyr);
                }
            }

            var dragAndDrop = new DragAndDrop({
                formatConstructors: [
                    GPX,
                    GeoJSON,
                    IGC,
                    KML,
                    TopoJSON
                ]
            });

            $rootScope.$on('map.loaded', function () {
                OlMap.map.addInteraction(dragAndDrop);
                me.checkUrlParamsAndAdd()
            });

            dragAndDrop.on('addfeatures', function (event) {
                if (event.features.length > 0) {
                    var f = new GeoJSON();
                    //TODO Saving to statusmanager should probably be done with statusmanager component throught events
                    var url = '';
                    try {
                        url = statusManagerService.endpointUrl();
                    } catch (ex) { }
                    if (console) console.info(url, config);
                    var options = {};
                    options.features = event.features;

                    $http({
                        url: url,
                        method: 'POST',
                        data: JSON.stringify({
                            project: config.project_name,
                            title: event.file.name,
                            request: 'saveData',
                            dataType: "json",
                            data: f.writeFeatures(event.features, {
                                dataProjection: 'EPSG:4326',
                                featureProjection: OlMap.map.getView().getProjection().getCode()
                            })
                        })
                    }).then(function (response) {
                        data = {};
                        data.url = url + "?request=loadData&id=" + response.data.id;
                        if (console) console.info(data.url, response.data);
                        data.title = event.file.name;
                        data.projection = event.projection;
                        var lyr = me.add('geojson', decodeURIComponent(data.url), data.title || 'Layer', '', true, data.projection, options);
                    }, function (e) {
                        if (console) console.warn(e);
                        data = {};
                        data.title = event.file.name;
                        data.projection = event.projection;
                        var lyr = me.add('geojson', undefined, data.title || 'Layer', '', true, data.projection, options);
                    });
                }
            });
        }
    ])

    /**
    * @memberof hs.addLayersVector
    * @ngdoc controller
    * @name hs.addLayersVector.controller
    */
    .controller('hs.addLayersVector.controller', ['$scope', 'hs.map.service', 'hs.styles.service', 'hs.addLayersVector.service', 'Core',
        function ($scope, OlMap, styles, service, Core) {
            $scope.srs = 'EPSG:4326';
            $scope.title = "";
            $scope.extract_styles = false;

            /**
            * Handler for adding nonwms service, file in template.
            * @memberof hs.addLayersVector.controller
            * @function add
            */
            $scope.add = function () {
                service.add($scope.type, $scope.url, $scope.title, $scope.abstract, $scope.extract_styles, $scope.srs);
                Core.setMainPanel('layermanager');
            }
        }
    ]);
<commit_msg>Fix dragdrop of vector layers<commit_after>import { DragAndDrop } from 'ol/interaction';
import { GPX, IGC, KML, TopoJSON, GeoJSON } from 'ol/format';
import SparqlJson from 'hs.source.SparqlJson'
import WfsSource from 'hs.source.Wfs'
import 'components/styles/styles.module';
import * as loadingstrategy from 'ol/loadingstrategy';
import { transform, transformExtent, get as getProj } from 'ol/proj';
import { Vector } from 'ol/source';
import VectorLayer from 'ol/layer/Vector';

/**
 * @namespace hs.addLayersVector
 * @memberOf hs
 */
angular.module('hs.addLayersVector', ['hs.styles'])
    /**
    * @memberof hs.ows
    * @ngdoc directive
    * @name hs.addLayersVector
    * @description TODO
    */
    .directive('hs.addLayersVector', ['config', function (config) {
        return {
            template: require('components/add-layers/partials/add-vector-layer.directive.html')
        };
    }])
    /**
    * @memberof hs.addLayersVector
    * @ngdoc service
    * @name hs.addLayersVector.service
    * @description Service handling adding nonwms OWS services or files. Handles also drag and drop addition.
    */
    .service('hs.addLayersVector.service', ['config', 'Core', '$rootScope', 'hs.map.service', 'hs.styles.service', 'hs.utils.service', '$http', 'hs.statusManagerService', 'hs.permalink.urlService',
        function (config, Core, $rootScope, OlMap, styles, utils, $http, statusManagerService, permalink) {
            var me = this;

            /**
            * Load nonwms OWS data and create layer
            * @memberof hs.addLayers
            * @function add
            * @param {String} type Type of data to load (supports Kml, Geojson, Wfs and Sparql)
            * @param {String} url Url of data/service localization
            * @param {String} title Title of new layer
            * @param {String} abstract Abstract of new layer
            * @param {Boolean} extract_styles Extract styles
            * @param {String} srs EPSG code of selected projection (eg. "EPSG:4326")
            * @param {Object} options Other options
            */
            me.add = function (type, url, title, abstract, extract_styles, srs, options) {
                var format;
                var definition = {};
                var src;
                definition.url = url;
                if (angular.isUndefined(options)) {
                    var options = {};
                }

                if (type.toLowerCase() != 'sparql' && angular.isDefined(url)) {
                    url = utils.proxify(url);
                }

                if (type == 'kml' ||
                    (angular.isDefined(url) && url.toLowerCase().endsWith('kml'))) {
                    format = new KML({
                        extractStyles: extract_styles
                    });
                    definition.format = "ol.format.KML";
                }
                if (type == 'geojson' ||
                    (angular.isDefined(url) && url.toLowerCase().endsWith('geojson') || url.toLowerCase().endsWith('json'))) {
                    format = new GeoJSON();
                    definition.format = "ol.format.GeoJSON";
                }
                if (angular.isDefined(url) && url.toLowerCase().endsWith('gpx')) {
                    format = new GPX();
                    definition.format = "ol.format.GPX";
                }
                if (type.toLowerCase() == "sparql") {
                    definition.format = "hs.format.Sparql";
                }
                if (definition.format == 'hs.format.Sparql') {
                    src = new SparqlJson({
                        geom_attribute: '?geom',
                        url: url,
                        category_field: 'http://www.openvoc.eu/poi#categoryWaze',
                        projection: 'EPSG:3857',
                        minResolution: 1,
                        maxResolution: 38
                        //feature_loaded: function(feature){feature.set('hstemplate', 'hs.geosparql_directive')}
                    });
                } else if (definition.format == 'hs.format.WFS') {
                    src = new WfsSource(options.defOptions);
                } else if (angular.isDefined(options.features)) {
                    src = createVectorSourceFromFeatures(srs, options);
                    OlMap.map.getView().fit(src.getExtent(), OlMap.map.getSize());
                } else {
                    src = createVectorSource(format, url, extract_styles, srs)
                }
                //src.set('loaded', true); Should be set when ajax call finishes
                src.set('from_composition', options.from_composition || false);
                var lyr = new VectorLayer({
                    abstract: abstract,
                    definition: definition,
                    from_composition: options.from_composition || false,
                    opacity: options.opacity || 1,
                    saveState: true,
                    source: src,
                    style: options.style,
                    title: title
                });

                var key = src.on('propertychange', function (event) {
                    if (event.key == 'loaded') {
                        if (event.oldValue == false) {
                            $rootScope.$broadcast('layermanager.layer_loaded', lyr)
                        } else {
                            $rootScope.$broadcast('layermanager.layer_loading', lyr)
                        }
                    };
                })

                var listenerKey = src.on('change', function (e) {
                    if (src.getState() == 'ready' && (angular.isUndefined(src.get('from_composition')) || !src.get('from_composition'))) {
                        if (src.getFeatures().length == 0) return;
                        var extent = src.getExtent(); //src.unByKey(listenerKey);
                        if (!isNaN(extent[0]) && !isNaN(extent[1]) && !isNaN(extent[2]) && !isNaN(extent[3]))
                            OlMap.map.getView().fit(extent, OlMap.map.getSize());
                    }
                });

                if (options.from_composition != true) {
                    OlMap.map.addLayer(lyr);
                }
                return lyr;
            };

            function createVectorSource(format, url, extract_styles, srs) {
                var src = new Vector({
                    format: format,
                    url: url,
                    projection: getProj(srs),
                    extractStyles: extract_styles,
                    loader: function (extent, resolution, projection) {
                        this.set('loaded', false);
                        var me = this;
                        $http({ url: url }). //context: this?
                            then(function (response) {
                                var data = response.data;
                                if (data.type == 'GeometryCollection') {
                                    var temp = {
                                        type: "Feature",
                                        geometry: data
                                    };
                                    data = temp;
                                }
                                me.addFeatures(format.readFeatures(data, {
                                    dataProjection: srs,
                                    featureProjection: OlMap.map.getView().getProjection().getCode()
                                }));

                                //TODO probably we should not do this. Have to check when styler is operational
                                src.hasLine = false;
                                src.hasPoly = false;
                                src.hasPoint = false;
                                angular.forEach(src.getFeatures(), function (f) {
                                    if (f.getGeometry()) {
                                        switch (f.getGeometry().getType()) {
                                            case 'LineString' || 'MultiLineString':
                                                src.hasLine = true;
                                                break;
                                            case 'Polygon' || 'MultiPolygon':
                                                src.hasPoly = true;
                                                break;
                                            case 'Point' || 'MultiPoint':
                                                src.hasPoint = true;
                                                break;
                                        }
                                    }
                                })

                                if (src.hasLine || src.hasPoly || src.hasPoint) {
                                    src.styleAble = true;
                                }
                                me.set('loaded', true);

                            }, function (err) {
                                me.error = true;
                                me.errorMessage = err.status;
                                me.set('loaded', true);
                            });
                    },
                    strategy: loadingstrategy.all
                });
                return src;
            }

            function createVectorSourceFromFeatures(srs, options) {
                var src = new Vector({
                    projection: srs,
                    features: options.features
                });

                src.hasLine = false;
                src.hasPoly = false;
                src.hasPoint = false;
                angular.forEach(src.getFeatures(), function (f) {
                    if (f.getGeometry()) {
                        switch (f.getGeometry().getType()) {
                            case 'LineString' || 'MultiLineString':
                                src.hasLine = true;
                                break;
                            case 'Polygon' || 'MultiPolygon':
                                src.hasPoly = true;
                                break;
                            case 'Point' || 'MultiPoint':
                                src.hasPoint = true;
                                break;
                        }
                    }
                })

                if (src.hasLine || src.hasPoly || src.hasPoint) {
                    src.styleAble = true;
                }

                return src;
            }
            /**
            * (PRIVATE) Zoom to selected vector layer
            * @memberof hs.addLayers
            * @function zoomToVectorLayer
            * @param {ol.Layer} lyr New layer
            */
            function zoomToVectorLayer(lyr) {
                Core.setMainPanel('layermanager');
                lyr.getSource().on('change', function () { //Event needed because features are loaded asynchronously
                    var extent = lyr.getSource().getExtent();
                    if (extent != null) OlMap.map.getView().fit(extent, OlMap.map.getSize());
                });
            }

            me.checkUrlParamsAndAdd = function () {
                var title = decodeURIComponent(permalink.getParamValue('title')) || 'Layer';
                var abstract = decodeURIComponent(permalink.getParamValue('abstract'));

                if (permalink.getParamValue('geojson_to_connect')) {
                    var url = permalink.getParamValue('geojson_to_connect');
                    var type = 'geojson';
                    if (url.indexOf('gpx') > 0) type = 'gpx';
                    if (url.indexOf('kml') > 0) type = 'kml';
                    var lyr = me.add(type, url, title, abstract, false, 'EPSG:4326');
                    zoomToVectorLayer(lyr);
                }

                if (permalink.getParamValue('kml_to_connect')) {
                    var url = permalink.getParamValue('kml_to_connect');
                    var lyr = me.add('kml', url, title, abstract, true, 'EPSG:4326');
                    zoomToVectorLayer(lyr);
                }
            }

            var dragAndDrop = new DragAndDrop({
                formatConstructors: [
                    GPX,
                    GeoJSON,
                    IGC,
                    KML,
                    TopoJSON
                ]
            });

            if (OlMap.map) {
                OlMap.map.addInteraction(dragAndDrop);
            } else {
                $rootScope.$on('map.loaded', function () {
                    OlMap.map.addInteraction(dragAndDrop);
                    me.checkUrlParamsAndAdd()
                });
            }

            dragAndDrop.on('addfeatures', function (event) {
                if (event.features.length > 0) {
                    var f = new GeoJSON();
                    //TODO Saving to statusmanager should probably be done with statusmanager component throught events
                    var url = '';
                    try {
                        url = statusManagerService.endpointUrl();
                    } catch (ex) { }
                    if (console) console.info(url, config);
                    var options = {};
                    options.features = event.features;

                    $http({
                        url: url,
                        method: 'POST',
                        data: JSON.stringify({
                            project: config.project_name,
                            title: event.file.name,
                            request: 'saveData',
                            dataType: "json",
                            data: f.writeFeatures(event.features, {
                                dataProjection: 'EPSG:4326',
                                featureProjection: OlMap.map.getView().getProjection().getCode()
                            })
                        })
                    }).then(function (response) {
                        var data = {};
                        data.url = url + "?request=loadData&id=" + response.data.id;
                        if (console) console.info(data.url, response.data);
                        data.title = event.file.name;
                        data.projection = event.projection;
                        var lyr = me.add('geojson', decodeURIComponent(data.url), data.title || 'Layer', '', true, data.projection, options);
                    }, function (e) {
                        if (console) console.warn(e);
                        var data = {};
                        data.title = event.file.name;
                        data.projection = event.projection;
                        var lyr = me.add('geojson', undefined, data.title || 'Layer', '', true, data.projection, options);
                    });
                }
            });
        }
    ])

    /**
    * @memberof hs.addLayersVector
    * @ngdoc controller
    * @name hs.addLayersVector.controller
    */
    .controller('hs.addLayersVector.controller', ['$scope', 'hs.map.service', 'hs.styles.service', 'hs.addLayersVector.service', 'Core',
        function ($scope, OlMap, styles, service, Core) {
            $scope.srs = 'EPSG:4326';
            $scope.title = "";
            $scope.extract_styles = false;

            /**
            * Handler for adding nonwms service, file in template.
            * @memberof hs.addLayersVector.controller
            * @function add
            */
            $scope.add = function () {
                service.add($scope.type, $scope.url, $scope.title, $scope.abstract, $scope.extract_styles, $scope.srs);
                Core.setMainPanel('layermanager');
            }
        }
    ]);
<|endoftext|>


<commit_before>// Default Tiff.initialize({ TOTAL_MEMORY: 16777216 });
Tiff.initialize({ TOTAL_MEMORY: 33554432 });

function convert_binary_string_to_buffer( data ){
  var buffer, view, a_byte;

  buffer = new ArrayBuffer( data.length );
  view = new DataView( buffer );

  data.split( '' ).forEach( function( c, i ){
    a_byte = c.charCodeAt();
    view.setUint8( i, a_byte & 0xff );
  });

  return view.buffer;
};

function create_request_for_url( url ){
  var request;

  request = new XMLHttpRequest();
  request.open( 'GET', url, false );
  request.overrideMimeType( 'text\/plain; charset=x-user-defined' );
  request.send( null );

  return request;
};

function get_buffer_from_url( url ){
  var request

  request = create_request_for_url( url );

  if( request.status != 200 ){ return url; };

  return convert_binary_string_to_buffer( request.responseText );
};

convert_buffer_to_dataurl = function( buffer ){
  var tiff;

  try {
    tiff = new Tiff({ buffer: buffer });
    // console.log( 'Opened', 'width: ', tiff.width(), 'height: ', tiff.height(), tiff );
  } catch( e ){
    // console.log( 'Exception', e );
    return;
  }

  return tiff.toDataURL();
};

function redirect_request_to_dataurl( details ){
  var url, buffer, dataURI;

  // console.log( 'Entering', details );
  url = details.url;
  // console.log( 'Loading', details.url );
  buffer = get_buffer_from_url( url );
  // console.log( 'Loaded', buffer.byteLength, 'bytes of data' );
  dataURI = convert_buffer_to_dataurl( buffer );
  // console.log( 'Converted', dataURI );

  return { redirectUrl: dataURI };
};

chrome.webRequest.onBeforeRequest.addListener(
  redirect_request_to_dataurl,
  {
    urls: [ "*://*/*.tiff", "*://*/*.tif", "*://*/*.Tiff", "*://*/*.Tif", "*://*/*.TIFF", "*://*/*.TIF" ],
    types: [ 'main_frame', 'sub_frame', 'image' ]
  },
  [ 'blocking' ]
);<commit_msg>Adds support for catching responses with content type image/tiff.<commit_after>// Default Tiff.initialize({ TOTAL_MEMORY: 16777216 });
Tiff.initialize({ TOTAL_MEMORY: 33554432 });

function convert_binary_string_to_buffer( data ){
  var buffer, view, a_byte;

  buffer = new ArrayBuffer( data.length );
  view = new DataView( buffer );

  data.split( '' ).forEach( function( c, i ){
    a_byte = c.charCodeAt();
    view.setUint8( i, a_byte & 0xff );
  });

  return view.buffer;
};

function create_request_for_url( url ){
  var request;

  request = new XMLHttpRequest();
  request.open( 'GET', url, false );
  request.overrideMimeType( 'text\/plain; charset=x-user-defined' );
  request.send( null );

  return request;
};

function get_buffer_from_url( url ){
  var request

  request = create_request_for_url( url );

  if( request.status != 200 ){ return url; };

  return convert_binary_string_to_buffer( request.responseText );
};

convert_buffer_to_dataurl = function( buffer ){
  var tiff;

  try {
    tiff = new Tiff({ buffer: buffer });
    // console.log( 'Opened', 'width: ', tiff.width(), 'height: ', tiff.height(), tiff );
  } catch( e ){
    // console.log( 'Exception', e );
    return;
  }

  return tiff.toDataURL();
};

function redirect_request_to_dataurl( details ){
  var url, buffer, dataURI;

  // console.log( 'Entering', details );
  url = details.url;
  // console.log( 'Loading', details.url );
  buffer = get_buffer_from_url( url );
  // console.log( 'Loaded', buffer.byteLength, 'bytes of data' );
  dataURI = convert_buffer_to_dataurl( buffer );
  // console.log( 'Converted', dataURI );

  return { redirectUrl: dataURI };
};

function content_type_tiff_header_filter( header ){
  var is_content_type_header, is_of_type_tiff;

  if( !header.name || !header.value ){ return false; }

  is_content_type_header = header.name.toLowerCase() === 'content-type';
  is_of_type_tiff = header.value.toLowerCase().indexOf( 'image/tiff' ) > -1;

  return is_content_type_header && is_of_type_tiff;
};

function content_type_header_is_tiff( headers ){
  var content_type_tiff_headers;

  content_type_tiff_headers = headers.filter( content_type_tiff_header_filter );

  return content_type_tiff_headers.length > 0;
};

function redirect_request_to_dataurl_if_response_content_type_is_tiff( details ){
  if( !content_type_header_is_tiff( details.responseHeaders ) ){ return; }

  console.log( 'Its a tiff!' );
  details.responseHeaders.push({ name: 'Content-Type', value: 'image/png' })

  response = redirect_request_to_dataurl( details );
  response.responseHeaders = details.responseHeaders;

  return response;
};

chrome.webRequest.onBeforeRequest.addListener(
  redirect_request_to_dataurl,
  {
    urls: [ "*://*/*.tiff", "*://*/*.tif", "*://*/*.Tiff", "*://*/*.Tif", "*://*/*.TIFF", "*://*/*.TIF" ],
    types: [ 'main_frame', 'sub_frame', 'image' ]
  },
  [ 'blocking' ]
);

chrome.webRequest.onHeadersReceived.addListener(
  redirect_request_to_dataurl_if_response_content_type_is_tiff,
  {
    urls: [ '<all_urls>' ],
    types: [ 'main_frame', 'sub_frame', 'image' ]
  },
  [ 'blocking', 'responseHeaders' ]
);<|endoftext|>


<commit_before>/* ========================================================================
 * Bootstrap: affix.js v3.3.2
 * http://getbootstrap.com/javascript/#affix
 * ========================================================================
 * Copyright 2011-2015 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */

+function ($) {
  'use strict';

  // AFFIX CLASS DEFINITION
  // ======================

  var Affix = function (element, options) {
    this.options = $.extend({}, Affix.DEFAULTS, options)

    this.$target = $(this.options.target)
      .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
      .on('click.bs.affix.data-api',  $.proxy(this.checkPositionWithEventLoop, this))

    this.$element     = $(element)
    this.affixed      = null
    this.unpin        = null
    this.pinnedOffset = null

    this.checkPosition()
  }

  Affix.VERSION  = '3.3.2'

  Affix.RESET    = 'affix affix-top affix-bottom'

  Affix.DEFAULTS = {
    offset: 0,
    target: window
  }

  Affix.prototype.getState = function (scrollHeight, height, offsetTop, offsetBottom) {
    var scrollTop    = this.$target.scrollTop()
    var position     = this.$element.offset()
    var targetHeight = this.$target.height()

    if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false

    if (this.affixed == 'bottom') {
      if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom'
      return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom'
    }

    var initializing   = this.affixed == null
    var colliderTop    = initializing ? scrollTop : position.top
    var colliderHeight = initializing ? targetHeight : height

    if (offsetTop != null && scrollTop <= offsetTop) return 'top'
    if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom'

    return false
  }

  Affix.prototype.getPinnedOffset = function () {
    if (this.pinnedOffset) return this.pinnedOffset
    this.$element.removeClass(Affix.RESET).addClass('affix')
    var scrollTop = this.$target.scrollTop()
    var position  = this.$element.offset()
    return (this.pinnedOffset = position.top - scrollTop)
  }

  Affix.prototype.checkPositionWithEventLoop = function () {
    setTimeout($.proxy(this.checkPosition, this), 1)
  }

  Affix.prototype.checkPosition = function () {
    if (!this.$element.is(':visible')) return

    var height       = this.$element.height()
    var offset       = this.options.offset
    var offsetTop    = offset.top
    var offsetBottom = offset.bottom
    var scrollHeight = $('body').height()

    if (typeof offset != 'object')         offsetBottom = offsetTop = offset
    if (typeof offsetTop == 'function')    offsetTop    = offset.top(this.$element)
    if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element)

    var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom)

    if (this.affixed != affix) {
      if (this.unpin != null) this.$element.css('top', '')

      var affixType = 'affix' + (affix ? '-' + affix : '')
      var e         = $.Event(affixType + '.bs.affix')

      this.$element.trigger(e)

      if (e.isDefaultPrevented()) return

      this.affixed = affix
      this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null

      this.$element
        .removeClass(Affix.RESET)
        .addClass(affixType)
        .trigger(affixType.replace('affix', 'affixed') + '.bs.affix')
    }

    if (affix == 'bottom') {
      this.$element.offset({
        top: scrollHeight - height - offsetBottom
      })
    }
  }

  // AFFIX PLUGIN DEFINITION
  // =======================

  function Plugin(option) {
    return this.each(function () {
      var $this   = $(this)
      var data    = $this.data('bs.affix')
      var options = typeof option == 'object' && option

      if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  var old = $.fn.affix

  $.fn.affix             = Plugin
  $.fn.affix.Constructor = Affix

  // AFFIX NO CONFLICT
  // =================

  $.fn.affix.noConflict = function () {
    $.fn.affix = old
    return this
  }

  // AFFIX DATA-API
  // ==============

  $(window).on('load', function () {
    $('[data-spy="affix"]').each(function () {
      var $spy = $(this)
      var data = $spy.data()

      data.offset = data.offset || {}

      if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom
      if (data.offsetTop    != null) data.offset.top    = data.offsetTop

      Plugin.call($spy, data)
    })
  })

}(jQuery);
<commit_msg>Affix: $('body') => $(document.body)<commit_after>/* ========================================================================
 * Bootstrap: affix.js v3.3.2
 * http://getbootstrap.com/javascript/#affix
 * ========================================================================
 * Copyright 2011-2015 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */

+function ($) {
  'use strict';

  // AFFIX CLASS DEFINITION
  // ======================

  var Affix = function (element, options) {
    this.options = $.extend({}, Affix.DEFAULTS, options)

    this.$target = $(this.options.target)
      .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
      .on('click.bs.affix.data-api',  $.proxy(this.checkPositionWithEventLoop, this))

    this.$element     = $(element)
    this.affixed      = null
    this.unpin        = null
    this.pinnedOffset = null

    this.checkPosition()
  }

  Affix.VERSION  = '3.3.2'

  Affix.RESET    = 'affix affix-top affix-bottom'

  Affix.DEFAULTS = {
    offset: 0,
    target: window
  }

  Affix.prototype.getState = function (scrollHeight, height, offsetTop, offsetBottom) {
    var scrollTop    = this.$target.scrollTop()
    var position     = this.$element.offset()
    var targetHeight = this.$target.height()

    if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false

    if (this.affixed == 'bottom') {
      if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom'
      return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom'
    }

    var initializing   = this.affixed == null
    var colliderTop    = initializing ? scrollTop : position.top
    var colliderHeight = initializing ? targetHeight : height

    if (offsetTop != null && scrollTop <= offsetTop) return 'top'
    if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom'

    return false
  }

  Affix.prototype.getPinnedOffset = function () {
    if (this.pinnedOffset) return this.pinnedOffset
    this.$element.removeClass(Affix.RESET).addClass('affix')
    var scrollTop = this.$target.scrollTop()
    var position  = this.$element.offset()
    return (this.pinnedOffset = position.top - scrollTop)
  }

  Affix.prototype.checkPositionWithEventLoop = function () {
    setTimeout($.proxy(this.checkPosition, this), 1)
  }

  Affix.prototype.checkPosition = function () {
    if (!this.$element.is(':visible')) return

    var height       = this.$element.height()
    var offset       = this.options.offset
    var offsetTop    = offset.top
    var offsetBottom = offset.bottom
    var scrollHeight = $(document.body).height()

    if (typeof offset != 'object')         offsetBottom = offsetTop = offset
    if (typeof offsetTop == 'function')    offsetTop    = offset.top(this.$element)
    if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element)

    var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom)

    if (this.affixed != affix) {
      if (this.unpin != null) this.$element.css('top', '')

      var affixType = 'affix' + (affix ? '-' + affix : '')
      var e         = $.Event(affixType + '.bs.affix')

      this.$element.trigger(e)

      if (e.isDefaultPrevented()) return

      this.affixed = affix
      this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null

      this.$element
        .removeClass(Affix.RESET)
        .addClass(affixType)
        .trigger(affixType.replace('affix', 'affixed') + '.bs.affix')
    }

    if (affix == 'bottom') {
      this.$element.offset({
        top: scrollHeight - height - offsetBottom
      })
    }
  }

  // AFFIX PLUGIN DEFINITION
  // =======================

  function Plugin(option) {
    return this.each(function () {
      var $this   = $(this)
      var data    = $this.data('bs.affix')
      var options = typeof option == 'object' && option

      if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  var old = $.fn.affix

  $.fn.affix             = Plugin
  $.fn.affix.Constructor = Affix

  // AFFIX NO CONFLICT
  // =================

  $.fn.affix.noConflict = function () {
    $.fn.affix = old
    return this
  }

  // AFFIX DATA-API
  // ==============

  $(window).on('load', function () {
    $('[data-spy="affix"]').each(function () {
      var $spy = $(this)
      var data = $spy.data()

      data.offset = data.offset || {}

      if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom
      if (data.offsetTop    != null) data.offset.top    = data.offsetTop

      Plugin.call($spy, data)
    })
  })

}(jQuery);
<|endoftext|>


<commit_before>'use strict';

require('!style-loader!css-loader!bootstrap/dist/css/bootstrap.min.css');
var css = require('./src/styles/styles.scss');

// media breakpoint - small screen min width
var smallScreenMin = 768;

// default className for NotificationsSystem component
var notificationsSystemClassName = css['notifications-system'];

// default className for NotificationsContainer component
var notificationsContainerClassName = {
  main: css['notifications-container'],
  position: function position(_position) {
    return css['notifications-container--' + _position];
  }
};

// default transition for Notification component
var notificationsContainerTransition = {
  appearTimeout: 1000,
  enterTimeout: 1000,
  leaveTimeout: 1000,
  name: {
    appear: css['notification-appear'],
    appearActive: css['notification-appear-active'],
    enter: css['notification-enter'],
    enterActive: css['notification-enter-active'],
    leave: css['notification-leave'],
    leaveActive: css['notification-leave-active']
  }
};

// default className for Notification component
var notificationClassName = {
  main: css['notification'],
  meta: css['notification-meta'],
  title: css['notification-title'],
  message: css['notification-message'],
  icon: 'fa ' + css['notification-icon'],
  imageContainer: css['notification-image-container'],
  image: css['notification-image'],
  status: function status(_status) {
    return css['notification--' + _status];
  },
  dismissible: css['notification--dismissible'],
  // `fa` corresponds to font-awesome's class name
  buttons: function buttons(count) {
    if (count === 0) {
      return '';
    } else if (count === 1) {
      return css['notification--buttons-1'];
    } else if (count === 2) {
      return css['notification--buttons-2'];
    }
    return css['notification-buttons'];
  },
  button: css['notification-button'],
  buttonText: css['notification-button-text']
};

module.exports = {
  smallScreenMin: smallScreenMin,
  notificationsSystem: {
    className: notificationsSystemClassName
  },
  notificationsContainer: {
    className: notificationsContainerClassName,
    transition: notificationsContainerTransition
  },
  notification: {
    className: notificationClassName
  }
};<commit_msg>update transition time out<commit_after>'use strict';

require('!style-loader!css-loader!bootstrap/dist/css/bootstrap.min.css');
var css = require('./src/styles/styles.scss');

// media breakpoint - small screen min width
var smallScreenMin = 768;

// default className for NotificationsSystem component
var notificationsSystemClassName = css['notifications-system'];

// default className for NotificationsContainer component
var notificationsContainerClassName = {
  main: css['notifications-container'],
  position: function position(_position) {
    return css['notifications-container--' + _position];
  }
};

// default transition for Notification component
var notificationsContainerTransition = {
  appearTimeout: 450,
  enterTimeout: 450,
  leaveTimeout: 450,
  name: {
    appear: css['notification-appear'],
    appearActive: css['notification-appear-active'],
    enter: css['notification-enter'],
    enterActive: css['notification-enter-active'],
    leave: css['notification-leave'],
    leaveActive: css['notification-leave-active']
  }
};

// default className for Notification component
var notificationClassName = {
  main: css['notification'],
  meta: css['notification-meta'],
  title: css['notification-title'],
  message: css['notification-message'],
  icon: 'fa ' + css['notification-icon'],
  imageContainer: css['notification-image-container'],
  image: css['notification-image'],
  status: function status(_status) {
    return css['notification--' + _status];
  },
  dismissible: css['notification--dismissible'],
  // `fa` corresponds to font-awesome's class name
  buttons: function buttons(count) {
    if (count === 0) {
      return '';
    } else if (count === 1) {
      return css['notification--buttons-1'];
    } else if (count === 2) {
      return css['notification--buttons-2'];
    }
    return css['notification-buttons'];
  },
  button: css['notification-button'],
  buttonText: css['notification-button-text']
};

module.exports = {
  smallScreenMin: smallScreenMin,
  notificationsSystem: {
    className: notificationsSystemClassName
  },
  notificationsContainer: {
    className: notificationsContainerClassName,
    transition: notificationsContainerTransition
  },
  notification: {
    className: notificationClassName
  }
};<|endoftext|>