<commit_before>/**
  Copyright 2011 Christian Iversen <ci@sikkerhed.org>

  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation
  files (the "Software"), to deal in the Software without
  restriction, including without limitation the rights to use,
  copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following
  conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  OTHER DEALINGS IN THE SOFTWARE.
**/

var _int = __inherit(number, "int");

var __py2js_int = _int;

_int.prototype.__init__ = function(i) {
    if (arguments.length == 2) {
        this._obj = parseInt(i, arguments[1]);
    } else {
        this._obj = parseInt(i, 10);
    }
};

_int.prototype._isnumeric_float = false;

_int.prototype.__int__ = function () {
    return this;
};

_int.prototype.__str__ = function () {
    return str.__call__(this._obj);
};

_int.prototype.__repr__ = _int.prototype.__str__;

_int.prototype.__hash__ = function () {
    return this._obj;
};

_int.prototype.__invert__ = function() {
    return _int.__call__(~this._obj);
};

_int.prototype.__div__ = function(x) {
    if (!x._isnumeric_)
        throw py_builtins.TypeError.__call__("Cannot divide int and non-int");
    if (x._obj === 0)
        throw py_builtins.ZeroDivisionError.__call__("integer division or modulo by zero");
    return _float.__call__(this._obj / x._obj);
};

_int.prototype.__floordiv__ = function(x) {
    if (!x._isnumeric_)
        throw py_builtins.TypeError.__call__("Cannot operate on int and non-int");
    if (x._obj === 0)
        throw py_builtins.ZeroDivisionError.__call__("integer division or modulo by zero");
    return _int.__call__(Math.floor(this._obj / x._obj));
};

_int.prototype.__mod__ = function(x) {
    if (!x._isnumeric_)
        throw py_builtins.TypeError.__call__("Cannot find remainder of int and non-int");
    return _int.__call__(this._obj % x._obj);
};

_int.prototype.__pow__ = function(x) {
    if (!x._isnumeric_)
        throw py_builtins.TypeError.__call__("Cannot exponentiate int and non-int");
    return _int.__call__(Math.pow(this._obj, x._obj));
};

_int.prototype.__bitand__ = function(x) {
    if (!x._isnumeric_)
        throw py_builtins.TypeError.__call__("Cannot operate on int and non-int");
    return _int.__call__(this._obj & x._obj);
};

_int.prototype.__bitor__ = function(x) {
    if (!x._isnumeric_)
        throw py_builtins.TypeError.__call__("Cannot operate on int and non-int");
    return _int.__call__(this._obj | x._obj);
};

_int.prototype.__bitxor__ = function(x) {
    if (!x._isnumeric_)
        throw py_builtins.TypeError.__call__("Cannot operate on int and non-int");
    return _int.__call__(this._obj ^ x._obj);
};

_int.prototype.__lshift__ = function(x) {
    if (!x._isnumeric_)
        throw py_builtins.TypeError.__call__("Cannot operate on int and non-int");
    return _int.__call__(this._obj << x._obj);
};

_int.prototype.__rshift__ = function(x) {
    if (!x._isnumeric_)
        throw py_builtins.TypeError.__call__("Cannot operate on int and non-int");
    return _int.__call__(this._obj >> x._obj);
};

_int.prototype.__div__ = function(x) {
    if (!x._isnumeric_)
        throw py_builtins.TypeError.__call__("Cannot exponentiate number and number-int");
    return _float.__call__(this._obj / x._obj);
};

_int.prototype.__idiv__      = _int.prototype.__div__;

_int.prototype.__ilshift__   = _int.prototype.__lshift__;
_int.prototype.__irshift__   = _int.prototype.__rshift__;
_int.prototype.__ibitand__   = _int.prototype.__bitand__;
_int.prototype.__ibitor__    = _int.prototype.__bitor__;
_int.prototype.__ibitxor__   = _int.prototype.__bitxor__;
_int.prototype.__ifloordiv__ = _int.prototype.__floordiv__;

var $c0 = _int.__call__(0);
var $c1 = _int.__call__(1);
var $c2 = _int.__call__(2);
var $c3 = _int.__call__(3);
var $c4 = _int.__call__(4);
var $c5 = _int.__call__(5);
var $c6 = _int.__call__(6);
var $c7 = _int.__call__(7);
var $c8 = _int.__call__(8);
var $c9 = _int.__call__(9);
<commit_msg> * Fixed int constructor: allow calling int() on pythonic objects, use obj.__int__ to construct the integer value<commit_after>/**
  Copyright 2011 Christian Iversen <ci@sikkerhed.org>

  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation
  files (the "Software"), to deal in the Software without
  restriction, including without limitation the rights to use,
  copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following
  conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  OTHER DEALINGS IN THE SOFTWARE.
**/

var _int = __inherit(number, "int");

var __py2js_int = _int;

_int.prototype.__init__ = function(i) {
    if (arguments.length == 2) {
        this._obj = parseInt(i, arguments[1]);
    } else {
        this._obj = parseInt(i, 10);
    }
};

var ___int_real__ = _int.__call__;

_int.__call__ = function(obj) {
    if (js(isinstance(obj, object))) {
        return obj.__int__();
    } else {
        return ___int_real__(obj);
    }
}

_int.prototype._isnumeric_float = false;

_int.prototype.__int__ = function () {
    return this;
};

_int.prototype.__str__ = function () {
    return str.__call__(this._obj);
};

_int.prototype.__repr__ = _int.prototype.__str__;

_int.prototype.__hash__ = function () {
    return this._obj;
};

_int.prototype.__invert__ = function() {
    return _int.__call__(~this._obj);
};

_int.prototype.__div__ = function(x) {
    if (!x._isnumeric_)
        throw py_builtins.TypeError.__call__("Cannot divide int and non-int");
    if (x._obj === 0)
        throw py_builtins.ZeroDivisionError.__call__("integer division or modulo by zero");
    return _float.__call__(this._obj / x._obj);
};

_int.prototype.__floordiv__ = function(x) {
    if (!x._isnumeric_)
        throw py_builtins.TypeError.__call__("Cannot operate on int and non-int");
    if (x._obj === 0)
        throw py_builtins.ZeroDivisionError.__call__("integer division or modulo by zero");
    return _int.__call__(Math.floor(this._obj / x._obj));
};

_int.prototype.__mod__ = function(x) {
    if (!x._isnumeric_)
        throw py_builtins.TypeError.__call__("Cannot find remainder of int and non-int");
    return _int.__call__(this._obj % x._obj);
};

_int.prototype.__pow__ = function(x) {
    if (!x._isnumeric_)
        throw py_builtins.TypeError.__call__("Cannot exponentiate int and non-int");
    return _int.__call__(Math.pow(this._obj, x._obj));
};

_int.prototype.__bitand__ = function(x) {
    if (!x._isnumeric_)
        throw py_builtins.TypeError.__call__("Cannot operate on int and non-int");
    return _int.__call__(this._obj & x._obj);
};

_int.prototype.__bitor__ = function(x) {
    if (!x._isnumeric_)
        throw py_builtins.TypeError.__call__("Cannot operate on int and non-int");
    return _int.__call__(this._obj | x._obj);
};

_int.prototype.__bitxor__ = function(x) {
    if (!x._isnumeric_)
        throw py_builtins.TypeError.__call__("Cannot operate on int and non-int");
    return _int.__call__(this._obj ^ x._obj);
};

_int.prototype.__lshift__ = function(x) {
    if (!x._isnumeric_)
        throw py_builtins.TypeError.__call__("Cannot operate on int and non-int");
    return _int.__call__(this._obj << x._obj);
};

_int.prototype.__rshift__ = function(x) {
    if (!x._isnumeric_)
        throw py_builtins.TypeError.__call__("Cannot operate on int and non-int");
    return _int.__call__(this._obj >> x._obj);
};

_int.prototype.__div__ = function(x) {
    if (!x._isnumeric_)
        throw py_builtins.TypeError.__call__("Cannot exponentiate number and number-int");
    return _float.__call__(this._obj / x._obj);
};

_int.prototype.__idiv__      = _int.prototype.__div__;

_int.prototype.__ilshift__   = _int.prototype.__lshift__;
_int.prototype.__irshift__   = _int.prototype.__rshift__;
_int.prototype.__ibitand__   = _int.prototype.__bitand__;
_int.prototype.__ibitor__    = _int.prototype.__bitor__;
_int.prototype.__ibitxor__   = _int.prototype.__bitxor__;
_int.prototype.__ifloordiv__ = _int.prototype.__floordiv__;

var $c0 = _int.__call__(0);
var $c1 = _int.__call__(1);
var $c2 = _int.__call__(2);
var $c3 = _int.__call__(3);
var $c4 = _int.__call__(4);
var $c5 = _int.__call__(5);
var $c6 = _int.__call__(6);
var $c7 = _int.__call__(7);
var $c8 = _int.__call__(8);
var $c9 = _int.__call__(9);
<|endoftext|>


<commit_before>"use strict";

/**
 * Points's constructor
 * @constructor
 */
function Point (x, y, bulge) {
    if (!(this instanceof Point))
        throw 'this function in a constructor. Use new to call it';

    this.x = x || 0;
    this.y = y || 0;
    this.bulge = bulge || 0;
}

/**
 * Set x
 * @param {Number} x
 */
Point.prototype.setX = function setX(x) {
    this.x = x;
};

/**
 * Set Y
 * @param {Number} y
 */
Point.prototype.setY = function setY(y) {
    this.y = y;
};

/**
 * Set the bulge
 * @param {number} bulge
 */
Point.prototype.setBulge = function setBulge(bulge) {
    this.bulge = bulge;
};

/**
 * Return if the point is inside a polygon or not
 * @param   {[Point]} points
 * @returns {Boolean}
 */
Point.prototype.isInside = function isInside(points) {
    var i, j, c = false;
    for( i = 0, j = points.length-1; i < points.length; j = i++ ) {
        if( ( ( points[i].y > this.y ) != ( points[j].y > this.y ) ) &&
            ( this.x < ( points[j].x - points[i].x ) * ( this.y - points[i].y ) / ( points[j].y - points[i].y ) + points[i].x ) ) {
            c = !c;
        }
    }
    return c;
};

/**
 * Return the nearest point
 * @param   {[Point]}   points
 * @returns {Point}     nearestPoint
 */
Point.prototype.findNearest = function findNearest(points){
    var minDist  = 0,
        nearest = new Point();

    points.forEach(function (point, pi){
        var distCur  = Math.sqrt(Math.pow(this.x-point.x, 2)+Math.pow(this.y-point.y, 2));
        minDist      = distCur <= minDist ? distCur : (pi == 0 ? distCur : minDist);
        nearest      = distCur <= minDist ? point : nearest;
    },this);

    return nearest;
};

module.exports = Point;
<commit_msg>removing setters and optimization of isInside () method<commit_after>"use strict";

/**
 * Points's constructor
 * @constructor
 */
function Point (x, y, bulge) {
    if (!(this instanceof Point))
        throw 'this function in a constructor. Use new to call it';

    this.x = x || 0;
    this.y = y || 0;
    this.bulge = bulge || 0;
}

/**
 * Return if the point is inside a polygon or not
 * @param   {[Point]} points
 * @returns {Boolean}
 */
Point.prototype.isInside = function isInside(points) {
    var i, j, c = false;
    for( i = 0, j = points.length-1; i < points.length; j = i++ ) {
        if( ( ( points[i].y > this.y ) != ( points[j].y > this.y ) ) &&
            ( this.x < ( points[j].x - points[i].x ) * ( this.y - points[i].y ) / ( points[j].y - points[i].y ) + points[i].x ) ) {
            c = !c;
        }
    }
    return c;
};

/**
 * Return the nearest point
 * @param   {[Point]}   points
 * @returns {Point}     nearestPoint
 */
Point.prototype.findNearest = function findNearest(points){
    var minDist = 0,
        nearest = new Point();

    for (var pi = 0; pi < points.length; pi ++ ){
        var distCur  = Math.sqrt(Math.pow(this.x-points[pi].x, 2)+Math.pow(this.y-points[pi].y, 2));
        minDist      = distCur <= minDist ? distCur : (pi == 0 ? distCur : minDist);
        nearest      = distCur <= minDist ? points[pi] : nearest;
    }

    return nearest;
};

module.exports = Point;
<|endoftext|>


<commit_before>'use strict';

var utils = require('./utils.js');
var _ = require('lodash');

/**
 * Defines a set of functions usable in all swig templates, are merged into context on render
 * @param  {Object}   swig        Swig engine
 */
module.exports.swigFunctions = function(swig) {

  var self = this;

  this.context = {};
  this.data = {};

  this.paginate = false;
  this.curPage = 1;
  this.maxPage = -1;
  this.pageUrl = 'page-';
  this.cachedData = {};
  this.typeInfo = {};

  this.setData = function(data) {
    self.cachedData = {};
    self.data = data;
  };

  this.setTypeInfo = function(typeInfo) {
    self.typeInfo = typeInfo;
  };

  var getTypes = function() {
    var types = [];

    for(var key in self.typeInfo) {
      if(!self.typeInfo[key].oneOff) {
        types.push({ slug: key, name: self.typeInfo[key].name });
      }
    }

    return types;
  };

  var getCombined = function() {
    var names = [].slice.call(arguments, 0);

    if(self.cachedData[names.join(',')])
    {
      return self.cachedData[names.join(',')];
    }

    var data = {};
    names.forEach(function(name) {
      var tempData = self.data[name] || {};

      if(typeof tempData !== 'object') {
        data = tempData;
        return;
      }

      data = utils.extend(data, tempData);
      data = _.omit(data, function(value, key) { return key.indexOf('_') === 0; });
    });

    self.cachedData[names.join(',')] = data;

    return data;
  };

  var paginate = function(data, perPage, pageName) {
    if(self.curPage === 1 && self.paginate === true)
    {
      throw new Error('Can only paginate one set of data in a template.');
    }

    var items = utils.slice(data, perPage, perPage * (self.curPage-1));
    self.paginate = true;

    self.pageUrl = pageName || self.pageUrl;
    self.maxPage = Math.ceil(_(data).size() / perPage);

    return items;
  };

  var getCurPage = function() {
    return self.curPage;
  };

  var getMaxPage = function() {
    return self.maxPage;
  };

  var getPaginatedPrefix = function() {
    var prefix = './';

    if(self.curPage > 1) {
      prefix = '../';
    }

    return prefix;
  };

  var getPageUrl = function(pageNum) {

    if(pageNum === 1)
    {
      if(self.curPage === 1) {
        return '.';
      } else {
        return '../';
      }
    }

    var prefix = self.pageUrl + '/';

    if(self.curPage > 1) {
      prefix = '../' + self.pageUrl + '/';
    }

    return prefix + pageNum;
  };

  // FUNCTIONS USED FOR PAGINATION HELPING, IGNORE FOR MOST CASES
  this.shouldPaginate = function() {
    return self.curPage <= self.maxPage;
  };

  // Reset initial data
  this.init = function() {
    self.paginate = false;
    self.curPage = 1;
    self.pageUrl = 'page-'
    self.maxPage = -1;
  };

  this.increasePage = function() {
    self.curPage = self.curPage + 1;
  };

  this.getFunctions = function() {
    return {
      get: getCombined,
      getTypes: getTypes,
      paginate: paginate,
      getCurPage: getCurPage,
      getMaxPage: getMaxPage,
      getPageUrl: getPageUrl,
      getPaginatedPrefix: getPaginatedPrefix
    };
  };

  return this;
};<commit_msg>url function<commit_after>'use strict';

var utils = require('./utils.js');
var _ = require('lodash');

var slugger = require('slug');

/**
 * Defines a set of functions usable in all swig templates, are merged into context on render
 * @param  {Object}   swig        Swig engine
 */
module.exports.swigFunctions = function(swig) {

  var self = this;

  this.context = {};
  this.data = {};

  this.paginate = false;
  this.curPage = 1;
  this.maxPage = -1;
  this.pageUrl = 'page-';
  this.cachedData = {};
  this.typeInfo = {};

  var url = function(object) {
    var slug = object.slug ? object.slug : (object.name ? slugger(object.name).toLowerCase() : null);
    var prefix = object._type ? object._type : '';

    var url = '';
    if(prefix) {
      url = '/' + prefix + '/' + slug + '/';
    } else {
      url = '/' + slug + '/';
    }

    return url;
  };

  this.setData = function(data) {
    self.cachedData = {};
    self.data = data;
  };

  this.setTypeInfo = function(typeInfo) {
    self.typeInfo = typeInfo;
  };

  var getTypes = function() {
    var types = [];

    for(var key in self.typeInfo) {
      if(!self.typeInfo[key].oneOff) {
        types.push({ slug: key, name: self.typeInfo[key].name });
      }
    }

    return types;
  };

  var getCombined = function() {
    var names = [].slice.call(arguments, 0);

    if(self.cachedData[names.join(',')])
    {
      return self.cachedData[names.join(',')];
    }

    var data = {};
    names.forEach(function(name) {
      var tempData = self.data[name] || {};

      if(typeof tempData !== 'object') {
        data = tempData;
        data._type = name;
        return;
      }

      tempData = _.omit(tempData, function(value, key) { return key.indexOf('_') === 0; });
      tempData = _.map(tempData, function(value) { value._type = name; return value; });

      data = utils.extend(data, tempData);
    });

    console.log(data);
    self.cachedData[names.join(',')] = data;

    return data;
  };

  var paginate = function(data, perPage, pageName) {
    if(self.curPage === 1 && self.paginate === true)
    {
      throw new Error('Can only paginate one set of data in a template.');
    }

    var items = utils.slice(data, perPage, perPage * (self.curPage-1));
    self.paginate = true;

    self.pageUrl = pageName || self.pageUrl;
    self.maxPage = Math.ceil(_(data).size() / perPage);

    return items;
  };

  var getCurPage = function() {
    return self.curPage;
  };

  var getMaxPage = function() {
    return self.maxPage;
  };

  var getPaginatedPrefix = function() {
    var prefix = './';

    if(self.curPage > 1) {
      prefix = '../';
    }

    return prefix;
  };

  var getPageUrl = function(pageNum) {

    if(pageNum === 1)
    {
      if(self.curPage === 1) {
        return '.';
      } else {
        return '../';
      }
    }

    var prefix = self.pageUrl + '/';

    if(self.curPage > 1) {
      prefix = '../' + self.pageUrl + '/';
    }

    return prefix + pageNum;
  };

  // FUNCTIONS USED FOR PAGINATION HELPING, IGNORE FOR MOST CASES
  this.shouldPaginate = function() {
    return self.curPage <= self.maxPage;
  };

  // Reset initial data
  this.init = function() {
    self.paginate = false;
    self.curPage = 1;
    self.pageUrl = 'page-'
    self.maxPage = -1;
  };

  this.increasePage = function() {
    self.curPage = self.curPage + 1;
  };

  this.getFunctions = function() {
    return {
      get: getCombined,
      getTypes: getTypes,
      paginate: paginate,
      getCurPage: getCurPage,
      getMaxPage: getMaxPage,
      getPageUrl: getPageUrl,
      getPaginatedPrefix: getPaginatedPrefix,
      url: url
    };
  };

  return this;
};<|endoftext|>


<commit_before>/* eslint-disable import/first */
import { LicenseInfo } from '@mui/x-data-grid-pro';

// Remove the license warning from demonstration purposes
LicenseInfo.setLicenseKey(process.env.NEXT_PUBLIC_MUI_LICENSE);

import 'docs/src/modules/components/bootstrap';
// --- Post bootstrap -----
import * as React from 'react';
import { loadCSS } from 'fg-loadcss/src/loadCSS';
import NextHead from 'next/head';
import PropTypes from 'prop-types';
import acceptLanguage from 'accept-language';
import { useRouter } from 'next/router';
import pages from 'docs/src/pages';
import basePages from 'docs/data/base/pages';
import materialPages from 'docs/data/material/pages';
import systemPages from 'docs/data/system/pages';
import PageContext from 'docs/src/modules/components/PageContext';
import GoogleAnalytics from 'docs/src/modules/components/GoogleAnalytics';
import { ThemeProvider } from 'docs/src/modules/components/ThemeContext';
import { pathnameToLanguage, getCookie } from 'docs/src/modules/utils/helpers';
import { LANGUAGES } from 'docs/src/modules/constants';
import { CodeVariantProvider } from 'docs/src/modules/utils/codeVariant';
import {
  UserLanguageProvider,
  useSetUserLanguage,
  useUserLanguage,
} from 'docs/src/modules/utils/i18n';
import DocsStyledEngineProvider from 'docs/src/modules/utils/StyledEngineProvider';
import createEmotionCache from 'docs/src/createEmotionCache';
import findActivePage from 'docs/src/modules/utils/findActivePage';
import FEATURE_TOGGLE from 'docs/src/featureToggle';

// Client-side cache, shared for the whole session of the user in the browser.
const clientSideEmotionCache = createEmotionCache();

// Set the locales that the documentation automatically redirects to.
acceptLanguage.languages(LANGUAGES);

function LanguageNegotiation() {
  const setUserLanguage = useSetUserLanguage();
  const router = useRouter();
  const userLanguage = useUserLanguage();

  React.useLayoutEffect(() => {
    const { userLanguage: userLanguageUrl, canonicalAs } = pathnameToLanguage(router.asPath);

    // Only consider a redirection if coming to the naked folder.
    if (userLanguageUrl === 'en') {
      const preferedLanguage =
        LANGUAGES.find((lang) => lang === getCookie('userLanguage')) ||
        acceptLanguage.get(navigator.language) ||
        userLanguage;

      if (userLanguage !== preferedLanguage) {
        window.location =
          preferedLanguage === 'en' ? canonicalAs : `/${preferedLanguage}${canonicalAs}`;
      }
    }

    if (userLanguage !== userLanguageUrl) {
      setUserLanguage(userLanguageUrl);
    }
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  return null;
}

let reloadInterval;

// Avoid infinite loop when "Upload on reload" is set in the Chrome sw dev tools.
function lazyReload() {
  clearInterval(reloadInterval);
  reloadInterval = setInterval(() => {
    if (document.hasFocus()) {
      window.location.reload();
    }
  }, 100);
}

// Inspired by
// https://developers.google.com/web/tools/workbox/guides/advanced-recipes#offer_a_page_reload_for_users
function forcePageReload(registration) {
  // console.log('already controlled?', Boolean(navigator.serviceWorker.controller));

  if (!navigator.serviceWorker.controller) {
    // The window client isn't currently controlled so it's a new service
    // worker that will activate immediately.
    return;
  }

  // console.log('registration waiting?', Boolean(registration.waiting));
  if (registration.waiting) {
    // SW is waiting to activate. Can occur if multiple clients open and
    // one of the clients is refreshed.
    registration.waiting.postMessage('skipWaiting');
    return;
  }

  function listenInstalledStateChange() {
    registration.installing.addEventListener('statechange', (event) => {
      // console.log('statechange', event.target.state);
      if (event.target.state === 'installed' && registration.waiting) {
        // A new service worker is available, inform the user
        registration.waiting.postMessage('skipWaiting');
      } else if (event.target.state === 'activated') {
        // Force the control of the page by the activated service worker.
        lazyReload();
      }
    });
  }

  if (registration.installing) {
    listenInstalledStateChange();
    return;
  }

  // We are currently controlled so a new SW may be found...
  // Add a listener in case a new SW is found,
  registration.addEventListener('updatefound', listenInstalledStateChange);
}

async function registerServiceWorker() {
  if (
    'serviceWorker' in navigator &&
    process.env.NODE_ENV === 'production' &&
    window.location.host.indexOf('mui.com') !== -1
  ) {
    // register() automatically attempts to refresh the sw.js.
    const registration = await navigator.serviceWorker.register('/sw.js');
    // Force the page reload for users.
    forcePageReload(registration);
  }
}

let dependenciesLoaded = false;

function loadDependencies() {
  if (dependenciesLoaded) {
    return;
  }

  dependenciesLoaded = true;

  loadCSS(
    'https://fonts.googleapis.com/icon?family=Material+Icons|Material+Icons+Two+Tone',
    document.querySelector('#material-icon-font'),
  );
}

if (typeof window !== 'undefined' && process.env.NODE_ENV === 'production') {
  // eslint-disable-next-line no-console
  console.log(
    `%c

███╗   ███╗ ██╗   ██╗ ██████╗
████╗ ████║ ██║   ██║   ██╔═╝
██╔████╔██║ ██║   ██║   ██║
██║╚██╔╝██║ ██║   ██║   ██║
██║ ╚═╝ ██║ ╚██████╔╝ ██████╗
╚═╝     ╚═╝  ╚═════╝  ╚═════╝

Tip: you can access the documentation \`theme\` object directly in the console.
`,
    'font-family:monospace;color:#1976d2;font-size:12px;',
  );
}
function AppWrapper(props) {
  const { children, emotionCache, pageProps } = props;

  const router = useRouter();

  React.useEffect(() => {
    loadDependencies();
    registerServiceWorker();

    // Remove the server-side injected CSS.
    const jssStyles = document.querySelector('#jss-server-side');
    if (jssStyles) {
      jssStyles.parentElement.removeChild(jssStyles);
    }
  }, []);

  const asPathWithoutLang = router.asPath.replace(/^\/[a-zA-Z]{2}\//, '/');
  let productPages = pages;
  if (asPathWithoutLang.startsWith('/base')) {
    productPages = basePages;
  }
  if (asPathWithoutLang.startsWith('/material')) {
    productPages = materialPages;
  }
  if (asPathWithoutLang.startsWith('/system') && FEATURE_TOGGLE.enable_system_scope) {
    productPages = systemPages;
  }

  const activePage = findActivePage(productPages, router.pathname);

  let fonts = [];
  if (asPathWithoutLang.match(/onepirate/)) {
    fonts = [
      'https://fonts.googleapis.com/css?family=Roboto+Condensed:700|Work+Sans:300,400&display=swap',
    ];
  }

  return (
    <React.Fragment>
      <NextHead>
        <meta name="viewport" content="initial-scale=1, width=device-width" />
        {fonts.map((font) => (
          <link rel="stylesheet" href={font} key={font} />
        ))}
      </NextHead>
      <UserLanguageProvider defaultUserLanguage={pageProps.userLanguage}>
        <LanguageNegotiation />
        <CodeVariantProvider>
          <PageContext.Provider value={{ activePage, pages: productPages }}>
            <ThemeProvider>
              <DocsStyledEngineProvider cacheLtr={emotionCache}>
                {children}
                <GoogleAnalytics />
              </DocsStyledEngineProvider>
            </ThemeProvider>
          </PageContext.Provider>
        </CodeVariantProvider>
      </UserLanguageProvider>
    </React.Fragment>
  );
}

AppWrapper.propTypes = {
  children: PropTypes.node.isRequired,
  emotionCache: PropTypes.object.isRequired,
  pageProps: PropTypes.object.isRequired,
};

export default function MyApp(props) {
  const { Component, emotionCache = clientSideEmotionCache, pageProps } = props;

  return (
    <AppWrapper emotionCache={emotionCache} pageProps={pageProps}>
      <Component {...pageProps} />
    </AppWrapper>
  );
}

MyApp.propTypes = {
  Component: PropTypes.elementType.isRequired,
  emotionCache: PropTypes.object,
  pageProps: PropTypes.object.isRequired,
};

MyApp.getInitialProps = async ({ ctx, Component }) => {
  let pageProps = {};

  if (Component.getInitialProps) {
    pageProps = await Component.getInitialProps(ctx);
  }

  return {
    pageProps: {
      userLanguage: ctx.query.userLanguage || 'en',
      ...pageProps,
    },
  };
};

// Track fraction of actual events to prevent exceeding event quota.
// Filter sessions instead of individual events so that we can track multiple metrics per device.
const disableWebVitalsReporting = Math.random() > 0.0001;
export function reportWebVitals({ id, name, label, value }) {
  if (disableWebVitalsReporting) {
    return;
  }

  window.ga('send', 'event', {
    eventCategory: label === 'web-vital' ? 'Web Vitals' : 'Next.js custom metric',
    eventAction: name,
    eventValue: Math.round(name === 'CLS' ? value * 1000 : value), // values must be integers
    eventLabel: id, // id unique to current page load
    nonInteraction: true, // avoids affecting bounce rate.
  });
}
<commit_msg>[docs] Prefer useEnhancedEffect to avoid server side warnings (#30977)<commit_after>/* eslint-disable import/first */
import { LicenseInfo } from '@mui/x-data-grid-pro';

// Remove the license warning from demonstration purposes
LicenseInfo.setLicenseKey(process.env.NEXT_PUBLIC_MUI_LICENSE);

import 'docs/src/modules/components/bootstrap';
// --- Post bootstrap -----
import * as React from 'react';
import { loadCSS } from 'fg-loadcss/src/loadCSS';
import NextHead from 'next/head';
import PropTypes from 'prop-types';
import acceptLanguage from 'accept-language';
import { useRouter } from 'next/router';
import { unstable_useEnhancedEffect as useEnhancedEffect } from '@mui/utils';
import pages from 'docs/src/pages';
import basePages from 'docs/data/base/pages';
import materialPages from 'docs/data/material/pages';
import systemPages from 'docs/data/system/pages';
import PageContext from 'docs/src/modules/components/PageContext';
import GoogleAnalytics from 'docs/src/modules/components/GoogleAnalytics';
import { ThemeProvider } from 'docs/src/modules/components/ThemeContext';
import { pathnameToLanguage, getCookie } from 'docs/src/modules/utils/helpers';
import { LANGUAGES } from 'docs/src/modules/constants';
import { CodeVariantProvider } from 'docs/src/modules/utils/codeVariant';
import {
  UserLanguageProvider,
  useSetUserLanguage,
  useUserLanguage,
} from 'docs/src/modules/utils/i18n';
import DocsStyledEngineProvider from 'docs/src/modules/utils/StyledEngineProvider';
import createEmotionCache from 'docs/src/createEmotionCache';
import findActivePage from 'docs/src/modules/utils/findActivePage';
import FEATURE_TOGGLE from 'docs/src/featureToggle';

// Client-side cache, shared for the whole session of the user in the browser.
const clientSideEmotionCache = createEmotionCache();

// Set the locales that the documentation automatically redirects to.
acceptLanguage.languages(LANGUAGES);

function LanguageNegotiation() {
  const setUserLanguage = useSetUserLanguage();
  const router = useRouter();
  const userLanguage = useUserLanguage();

  useEnhancedEffect(() => {
    const { userLanguage: userLanguageUrl, canonicalAs } = pathnameToLanguage(router.asPath);

    // Only consider a redirection if coming to the naked folder.
    if (userLanguageUrl === 'en') {
      const preferedLanguage =
        LANGUAGES.find((lang) => lang === getCookie('userLanguage')) ||
        acceptLanguage.get(navigator.language) ||
        userLanguage;

      if (userLanguage !== preferedLanguage) {
        window.location =
          preferedLanguage === 'en' ? canonicalAs : `/${preferedLanguage}${canonicalAs}`;
      }
    }

    if (userLanguage !== userLanguageUrl) {
      setUserLanguage(userLanguageUrl);
    }
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  return null;
}

let reloadInterval;

// Avoid infinite loop when "Upload on reload" is set in the Chrome sw dev tools.
function lazyReload() {
  clearInterval(reloadInterval);
  reloadInterval = setInterval(() => {
    if (document.hasFocus()) {
      window.location.reload();
    }
  }, 100);
}

// Inspired by
// https://developers.google.com/web/tools/workbox/guides/advanced-recipes#offer_a_page_reload_for_users
function forcePageReload(registration) {
  // console.log('already controlled?', Boolean(navigator.serviceWorker.controller));

  if (!navigator.serviceWorker.controller) {
    // The window client isn't currently controlled so it's a new service
    // worker that will activate immediately.
    return;
  }

  // console.log('registration waiting?', Boolean(registration.waiting));
  if (registration.waiting) {
    // SW is waiting to activate. Can occur if multiple clients open and
    // one of the clients is refreshed.
    registration.waiting.postMessage('skipWaiting');
    return;
  }

  function listenInstalledStateChange() {
    registration.installing.addEventListener('statechange', (event) => {
      // console.log('statechange', event.target.state);
      if (event.target.state === 'installed' && registration.waiting) {
        // A new service worker is available, inform the user
        registration.waiting.postMessage('skipWaiting');
      } else if (event.target.state === 'activated') {
        // Force the control of the page by the activated service worker.
        lazyReload();
      }
    });
  }

  if (registration.installing) {
    listenInstalledStateChange();
    return;
  }

  // We are currently controlled so a new SW may be found...
  // Add a listener in case a new SW is found,
  registration.addEventListener('updatefound', listenInstalledStateChange);
}

async function registerServiceWorker() {
  if (
    'serviceWorker' in navigator &&
    process.env.NODE_ENV === 'production' &&
    window.location.host.indexOf('mui.com') !== -1
  ) {
    // register() automatically attempts to refresh the sw.js.
    const registration = await navigator.serviceWorker.register('/sw.js');
    // Force the page reload for users.
    forcePageReload(registration);
  }
}

let dependenciesLoaded = false;

function loadDependencies() {
  if (dependenciesLoaded) {
    return;
  }

  dependenciesLoaded = true;

  loadCSS(
    'https://fonts.googleapis.com/icon?family=Material+Icons|Material+Icons+Two+Tone',
    document.querySelector('#material-icon-font'),
  );
}

if (typeof window !== 'undefined' && process.env.NODE_ENV === 'production') {
  // eslint-disable-next-line no-console
  console.log(
    `%c

███╗   ███╗ ██╗   ██╗ ██████╗
████╗ ████║ ██║   ██║   ██╔═╝
██╔████╔██║ ██║   ██║   ██║
██║╚██╔╝██║ ██║   ██║   ██║
██║ ╚═╝ ██║ ╚██████╔╝ ██████╗
╚═╝     ╚═╝  ╚═════╝  ╚═════╝

Tip: you can access the documentation \`theme\` object directly in the console.
`,
    'font-family:monospace;color:#1976d2;font-size:12px;',
  );
}
function AppWrapper(props) {
  const { children, emotionCache, pageProps } = props;

  const router = useRouter();

  React.useEffect(() => {
    loadDependencies();
    registerServiceWorker();

    // Remove the server-side injected CSS.
    const jssStyles = document.querySelector('#jss-server-side');
    if (jssStyles) {
      jssStyles.parentElement.removeChild(jssStyles);
    }
  }, []);

  const asPathWithoutLang = router.asPath.replace(/^\/[a-zA-Z]{2}\//, '/');
  let productPages = pages;
  if (asPathWithoutLang.startsWith('/base')) {
    productPages = basePages;
  }
  if (asPathWithoutLang.startsWith('/material')) {
    productPages = materialPages;
  }
  if (asPathWithoutLang.startsWith('/system') && FEATURE_TOGGLE.enable_system_scope) {
    productPages = systemPages;
  }

  const activePage = findActivePage(productPages, router.pathname);

  let fonts = [];
  if (asPathWithoutLang.match(/onepirate/)) {
    fonts = [
      'https://fonts.googleapis.com/css?family=Roboto+Condensed:700|Work+Sans:300,400&display=swap',
    ];
  }

  return (
    <React.Fragment>
      <NextHead>
        <meta name="viewport" content="initial-scale=1, width=device-width" />
        {fonts.map((font) => (
          <link rel="stylesheet" href={font} key={font} />
        ))}
      </NextHead>
      <UserLanguageProvider defaultUserLanguage={pageProps.userLanguage}>
        <LanguageNegotiation />
        <CodeVariantProvider>
          <PageContext.Provider value={{ activePage, pages: productPages }}>
            <ThemeProvider>
              <DocsStyledEngineProvider cacheLtr={emotionCache}>
                {children}
                <GoogleAnalytics />
              </DocsStyledEngineProvider>
            </ThemeProvider>
          </PageContext.Provider>
        </CodeVariantProvider>
      </UserLanguageProvider>
    </React.Fragment>
  );
}

AppWrapper.propTypes = {
  children: PropTypes.node.isRequired,
  emotionCache: PropTypes.object.isRequired,
  pageProps: PropTypes.object.isRequired,
};

export default function MyApp(props) {
  const { Component, emotionCache = clientSideEmotionCache, pageProps } = props;

  return (
    <AppWrapper emotionCache={emotionCache} pageProps={pageProps}>
      <Component {...pageProps} />
    </AppWrapper>
  );
}

MyApp.propTypes = {
  Component: PropTypes.elementType.isRequired,
  emotionCache: PropTypes.object,
  pageProps: PropTypes.object.isRequired,
};

MyApp.getInitialProps = async ({ ctx, Component }) => {
  let pageProps = {};

  if (Component.getInitialProps) {
    pageProps = await Component.getInitialProps(ctx);
  }

  return {
    pageProps: {
      userLanguage: ctx.query.userLanguage || 'en',
      ...pageProps,
    },
  };
};

// Track fraction of actual events to prevent exceeding event quota.
// Filter sessions instead of individual events so that we can track multiple metrics per device.
const disableWebVitalsReporting = Math.random() > 0.0001;
export function reportWebVitals({ id, name, label, value }) {
  if (disableWebVitalsReporting) {
    return;
  }

  window.ga('send', 'event', {
    eventCategory: label === 'web-vital' ? 'Web Vitals' : 'Next.js custom metric',
    eventAction: name,
    eventValue: Math.round(name === 'CLS' ? value * 1000 : value), // values must be integers
    eventLabel: id, // id unique to current page load
    nonInteraction: true, // avoids affecting bounce rate.
  });
}
<|endoftext|>


<commit_before>import Vue from 'vue'
import VueAnalytics from 'vue-analytics/src'

if (process.BROWSER_BUILD) {

    // VueAnalytics.install(Vue, {
    //     // debug: true,
    // });

    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
    ga('create', 'UA-89526435-1', 'auto');
    ga('require', 'linkid', {
        'cookieName': '_ela',
        'duration': 300,
        'levels': 10
    });
}<commit_msg>Don't include VueAnalytics on Docs<commit_after>if (process.BROWSER_BUILD) {
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
    ga('create', 'UA-89526435-1', 'auto');
    ga('require', 'linkid', {
        'cookieName': '_ela',
        'duration': 300,
        'levels': 10
    });
}<|endoftext|>


<commit_before>goog.provide('app.BaselayerSelectorController');
goog.provide('app.baselayerSelectorDirective');

goog.require('app');
goog.require('ngeo.BackgroundLayerMgr');
goog.require('ol.Attribution');
goog.require('ol.layer.Tile');
goog.require('ol.source.BingMaps');
goog.require('ol.source.OSM');
goog.require('ol.source.WMTS');
goog.require('ol.source.XYZ');
goog.require('ol.tilegrid.WMTS');

/**
 * This directive is used to display a map baselayer selector.
 *
 * @return {angular.Directive} The directive specs.
 * @ngInject
 */
app.baselayerSelectorDirective = function() {
  return {
    restrict: 'E',
    controller: 'AppBaselayerSelectorController',
    controllerAs: 'bglayerCtrl',
    bindToController: true,
    scope: {
      'map': '=appBaselayerSelectorMap'
    },
    templateUrl: '/static/partials/map/baselayerselector.html'
  };
};

app.module.directive('appBaselayerSelector', app.baselayerSelectorDirective);

/**
 * @param {angular.$http} $http
 * @param {ngeo.BackgroundLayerMgr} ngeoBackgroundLayerMgr Background layer
 *     manager.
 * @param {appx.mapApiKeys} mapApiKeys Set of map API keys.
 * @param {app.Alerts} appAlerts
 * @param {app.Authentication} appAuthentication
 * @constructor
 * @struct
 * @ngInject
 */
app.BaselayerSelectorController = function($http, ngeoBackgroundLayerMgr,
  mapApiKeys, appAlerts, appAuthentication) {

  /**
   * @type {angular.$http}
   * @private
   */
  this.http_ = $http;

  /**
   * @type {ngeo.BackgroundLayerMgr}
   * @private
   */
  this.bgLayerMgr_ = ngeoBackgroundLayerMgr;

  /**
   * @type {string}
   * @private
   */
  this.ignApiKey_ = mapApiKeys['ign'];

  /**
   * @type {string}
   * @private
   */
  this.bingApiKey_ = mapApiKeys['bing'];

  /**
   * @type {app.Alerts}
   * @private
   */
  this.alerts_ = appAlerts;

  /**
   * @type {ol.Map}
   * @export
   */
  this.map;

  /**
   * @type {Object<string, ol.layer.Tile>}
   * @private
   */
  this.cachedLayers_ = {};

  /**
   * @type {ol.format.WMTSCapabilities}
   * @private
   */
  this.wmtsParser_;

  /**
   * @type {Object}
   * @export
   */
  this.currentBgLayerSpec;

  /**
   * @type {Array.<Object>}
   * @export
   */
  this.bgLayerSpecs = app.BaselayerSelectorController.BG_LAYER_SPECS.filter(
    (layer) => {
      return appAuthentication.isAuthenticated() || !layer['auth'];
    }
  );

  this.setLayer(this.bgLayerSpecs[0]);
};

/**
 * @const
 * @type {Array.<Object>}
 */
app.BaselayerSelectorController.BG_LAYER_SPECS = [{
  'name': 'esri'
}, {
  'name': 'osm'
}, {
  'name': 'bing'
}, {
  'name': 'ign maps'
}, {
  'name': 'ign ortho'
}, {
  'name': 'swisstopo',
  'auth': true
}];

/**
 * Function called when the user selects a new background layer in the
 * dropdown. Called by the ng-click directive used in the partial.
 * @param {Object} layerSpec Layer specification object.
 * @export
 */
app.BaselayerSelectorController.prototype.setLayer = function(layerSpec) {
  this.currentBgLayerSpec = layerSpec;
  const layer = this.createLayer_(layerSpec['name']);
  if (layer) {
    this.bgLayerMgr_.set(this.map, layer);
  }
};

/**
 * @param {string} layerName Layer name.
 * @return {ol.layer.Tile} The layer.
 * @private
 */
app.BaselayerSelectorController.prototype.createLayer_ = function(layerName) {
  if (layerName in this.cachedLayers_) {
    return this.cachedLayers_[layerName];
  }
  let source;
  switch (layerName) {
    case 'esri':
      source = this.createEsriSource_();
      break;
    case 'bing':
      source = new ol.source.BingMaps({
        key: this.bingApiKey_,
        imagerySet: 'AerialWithLabels'
      });
      break;
    case 'ign maps':
      source = this.createIgnSource_('GEOGRAPHICALGRIDSYSTEMS.MAPS');
      break;
    case 'ign ortho':
      source = this.createIgnSource_('ORTHOIMAGERY.ORTHOPHOTOS');
      break;
    case 'swisstopo':
      source = this.createSwisstopoSource_('ch.swisstopo.pixelkarte-farbe');
      break;
    case 'osm':
    default:
      source = new ol.source.OSM();
      break;
  }
  const layer = new ol.layer.Tile({source: source});
  this.cachedLayers_[layerName] = layer;
  return layer;
};

/**
 * @param {string} layer IGN layer name.
 * @return {ol.source.WMTS}
 * @private
 */
app.BaselayerSelectorController.prototype.createIgnSource_ = function(layer) {
  const resolutions = [];
  const matrixIds = [];
  const proj3857 = ol.proj.get('EPSG:3857');
  const maxResolution = ol.extent.getWidth(proj3857.getExtent()) / 256;

  for (let i = 0; i < 18; i++) {
    matrixIds[i] = i.toString();
    resolutions[i] = maxResolution / Math.pow(2, i);
  }

  const tileGrid = new ol.tilegrid.WMTS({
    origin: [-20037508, 20037508],
    resolutions: resolutions,
    matrixIds: matrixIds
  });

  return new ol.source.WMTS({
    url: '//wxs.ign.fr/' + this.ignApiKey_ + '/wmts',
    layer: layer,
    matrixSet: 'PM',
    format: 'image/jpeg',
    projection: 'EPSG:3857',
    tileGrid: tileGrid,
    style: 'normal',
    attributions: [new ol.Attribution({
      html: '' +
          ''
    })]
  });
};

/**
 * @param {string} layer Swisstopo layer name.
 * @return {ol.source.XYZ}
 * @private
 */
app.BaselayerSelectorController.prototype.createSwisstopoSource_ = function(layer) {
  return new ol.source.XYZ({
    attributions: [
      new ol.Attribution({
        html: 'swisstopo'
      })
    ],
    urls: ['10', '11', '12', '13', '14'].map((i) => {
      return 'https://wmts' + i + '.geo.admin.ch/1.0.0/' + layer + '/default/current' +
        '/3857/{z}/{x}/{y}.jpeg';
    }),
    maxZoom: 17
  });
};

/**
 * @return {ol.source.XYZ}
 * @private
 */
app.BaselayerSelectorController.prototype.createEsriSource_ = function() {
  return new ol.source.XYZ({
    attributions: [
      new ol.Attribution({
        html: 'Esri'
      })
    ],
    url: 'https://server.arcgisonline.com/arcgis/rest/services/World_Topo_Map/MapServer/WMTS?' +
      'layer=World_Topo_Map&style=default&tilematrixset=GoogleMapsCompatible&Service=WMTS&' +
      'Request=GetTile&Version=1.0.0&Format=image%2Fjpeg&TileMatrix={z}&TileCol={x}&TileRow={y}'
  });
};

app.module.controller('AppBaselayerSelectorController', app.BaselayerSelectorController);
<commit_msg>add opentopomap, remove default osm<commit_after>goog.provide('app.BaselayerSelectorController');
goog.provide('app.baselayerSelectorDirective');

goog.require('app');
goog.require('ngeo.BackgroundLayerMgr');
goog.require('ol.Attribution');
goog.require('ol.layer.Tile');
goog.require('ol.source.BingMaps');
goog.require('ol.source.OSM');
goog.require('ol.source.WMTS');
goog.require('ol.source.XYZ');
goog.require('ol.tilegrid.WMTS');

/**
 * This directive is used to display a map baselayer selector.
 *
 * @return {angular.Directive} The directive specs.
 * @ngInject
 */
app.baselayerSelectorDirective = function() {
  return {
    restrict: 'E',
    controller: 'AppBaselayerSelectorController',
    controllerAs: 'bglayerCtrl',
    bindToController: true,
    scope: {
      'map': '=appBaselayerSelectorMap'
    },
    templateUrl: '/static/partials/map/baselayerselector.html'
  };
};

app.module.directive('appBaselayerSelector', app.baselayerSelectorDirective);

/**
 * @param {angular.$http} $http
 * @param {ngeo.BackgroundLayerMgr} ngeoBackgroundLayerMgr Background layer
 *     manager.
 * @param {appx.mapApiKeys} mapApiKeys Set of map API keys.
 * @param {app.Alerts} appAlerts
 * @param {app.Authentication} appAuthentication
 * @constructor
 * @struct
 * @ngInject
 */
app.BaselayerSelectorController = function($http, ngeoBackgroundLayerMgr,
  mapApiKeys, appAlerts, appAuthentication) {

  /**
   * @type {angular.$http}
   * @private
   */
  this.http_ = $http;

  /**
   * @type {ngeo.BackgroundLayerMgr}
   * @private
   */
  this.bgLayerMgr_ = ngeoBackgroundLayerMgr;

  /**
   * @type {string}
   * @private
   */
  this.ignApiKey_ = mapApiKeys['ign'];

  /**
   * @type {string}
   * @private
   */
  this.bingApiKey_ = mapApiKeys['bing'];

  /**
   * @type {app.Alerts}
   * @private
   */
  this.alerts_ = appAlerts;

  /**
   * @type {ol.Map}
   * @export
   */
  this.map;

  /**
   * @type {Object<string, ol.layer.Tile>}
   * @private
   */
  this.cachedLayers_ = {};

  /**
   * @type {ol.format.WMTSCapabilities}
   * @private
   */
  this.wmtsParser_;

  /**
   * @type {Object}
   * @export
   */
  this.currentBgLayerSpec;

  /**
   * @type {Array.<Object>}
   * @export
   */
  this.bgLayerSpecs = app.BaselayerSelectorController.BG_LAYER_SPECS.filter(
    (layer) => {
      return appAuthentication.isAuthenticated() || !layer['auth'];
    }
  );

  this.setLayer(this.bgLayerSpecs[0]);
};

/**
 * @const
 * @type {Array.<Object>}
 */
app.BaselayerSelectorController.BG_LAYER_SPECS = [{
  'name': 'esri'
}, {
  'name': 'opentopomap'
}, {
  'name': 'bing'
}, {
  'name': 'ign maps'
}, {
  'name': 'ign ortho'
}, {
  'name': 'swisstopo',
  'auth': true
}];

/**
 * Function called when the user selects a new background layer in the
 * dropdown. Called by the ng-click directive used in the partial.
 * @param {Object} layerSpec Layer specification object.
 * @export
 */
app.BaselayerSelectorController.prototype.setLayer = function(layerSpec) {
  this.currentBgLayerSpec = layerSpec;
  const layer = this.createLayer_(layerSpec['name']);
  if (layer) {
    this.bgLayerMgr_.set(this.map, layer);
  }
};

/**
 * @param {string} layerName Layer name.
 * @return {ol.layer.Tile} The layer.
 * @private
 */
app.BaselayerSelectorController.prototype.createLayer_ = function(layerName) {
  if (layerName in this.cachedLayers_) {
    return this.cachedLayers_[layerName];
  }
  let source;
  switch (layerName) {
    case 'esri':
      source = this.createEsriSource_();
      break;
    case 'bing':
      source = new ol.source.BingMaps({
        key: this.bingApiKey_,
        imagerySet: 'AerialWithLabels'
      });
      break;
    case 'ign maps':
      source = this.createIgnSource_('GEOGRAPHICALGRIDSYSTEMS.MAPS');
      break;
    case 'ign ortho':
      source = this.createIgnSource_('ORTHOIMAGERY.ORTHOPHOTOS');
      break;
    case 'swisstopo':
      source = this.createSwisstopoSource_('ch.swisstopo.pixelkarte-farbe');
      break;
    case 'opentopomap':
      source = this.createOpenTopoMapSource_();
      break;
    default:
      source = new ol.source.OSM();
      break;
  }
  const layer = new ol.layer.Tile({source: source});
  this.cachedLayers_[layerName] = layer;
  return layer;
};

/**
 * @param {string} layer IGN layer name.
 * @return {ol.source.WMTS}
 * @private
 */
app.BaselayerSelectorController.prototype.createIgnSource_ = function(layer) {
  const resolutions = [];
  const matrixIds = [];
  const proj3857 = ol.proj.get('EPSG:3857');
  const maxResolution = ol.extent.getWidth(proj3857.getExtent()) / 256;

  for (let i = 0; i < 18; i++) {
    matrixIds[i] = i.toString();
    resolutions[i] = maxResolution / Math.pow(2, i);
  }

  const tileGrid = new ol.tilegrid.WMTS({
    origin: [-20037508, 20037508],
    resolutions: resolutions,
    matrixIds: matrixIds
  });

  return new ol.source.WMTS({
    url: '//wxs.ign.fr/' + this.ignApiKey_ + '/wmts',
    layer: layer,
    matrixSet: 'PM',
    format: 'image/jpeg',
    projection: 'EPSG:3857',
    tileGrid: tileGrid,
    style: 'normal',
    attributions: [new ol.Attribution({
      html: '' +
          ''
    })]
  });
};

/**
 * @param {string} layer Swisstopo layer name.
 * @return {ol.source.XYZ}
 * @private
 */
app.BaselayerSelectorController.prototype.createSwisstopoSource_ = function(layer) {
  return new ol.source.XYZ({
    attributions: [
      new ol.Attribution({
        html: 'swisstopo'
      })
    ],
    urls: ['10', '11', '12', '13', '14'].map((i) => {
      return 'https://wmts' + i + '.geo.admin.ch/1.0.0/' + layer + '/default/current' +
        '/3857/{z}/{x}/{y}.jpeg';
    }),
    maxZoom: 17
  });
};

/**
 * @return {ol.source.XYZ}
 * @private
 */
app.BaselayerSelectorController.prototype.createEsriSource_ = function() {
  return new ol.source.XYZ({
    attributions: [
      new ol.Attribution({
        html: 'Esri'
      })
    ],
    url: 'https://server.arcgisonline.com/arcgis/rest/services/World_Topo_Map/MapServer/WMTS?' +
      'layer=World_Topo_Map&style=default&tilematrixset=GoogleMapsCompatible&Service=WMTS&' +
      'Request=GetTile&Version=1.0.0&Format=image%2Fjpeg&TileMatrix={z}&TileCol={x}&TileRow={y}'
  });
};

/**
 * @return {ol.source.XYZ}
 * @private
 */
app.BaselayerSelectorController.prototype.createOpenTopoMapSource_ = () => {
  return new ol.source.XYZ({
    attributions: [
      new ol.Attribution({
        html: '© OpenStreetMap | ' +
              '© OpenTopoMap'
      })
    ],
    url: '//{a-c}.tile.opentopomap.org/{z}/{x}/{y}.png'
  });
};

app.module.controller('AppBaselayerSelectorController', app.BaselayerSelectorController);
<|endoftext|>


<commit_before>var notifications = null;
var maxNotifTimstamp = 0;

function bindNotifEvents(element){ console.log("bindNotifEvents");
	$(".notifList"+element+" a.notif").off().on("click",function (e)
	{
		markAsRead( $(this).data("id") );
		hash = $(this).data("href");
		elem = $(this).parent();
		//elem.removeClass('animated bounceInRight').addClass("animated bounceOutRight");
		//elem.removeClass("enable");
		var thisJQ = this;
		setTimeout(function(){
          //  elem.addClass("read");
            //elem.removeClass('animated bounceOutRight');
            if(e.which==2)
				window.open(baseUrl+hash, '_blank');
			else{
				console.log("objtype", $(thisJQ).data("objtype"));
				if($(thisJQ).data("objtype") == "proposals" ||
					$(thisJQ).data("objtype") == "actions" || $(thisJQ).data("objtype") == "resolutions"){
					var objType = $(thisJQ).data("objtype");
					 uiCoop.getCoopDataPreview(objType.substr(0, objType.length-1), $(thisJQ).data("objid"));
				}else{
	            	urlCtrl.loadByHash(hash);
	            }
			}
            //notifCount();
        }, 200);
	});
	$('.tooltips').tooltip();
	$(".notifList"+element+" li").mouseenter(function(){
		$(this).find(".removeBtn").show();
	}).mouseleave(function(){
		$(this).find(".removeBtn").hide();
	})
}
function updateNotification(action, element, id)
{
	var action = action;
	var all = true;
	data = new Object;
	if(id != null){
		var notifId=id;
		all=false;
		data.id=id
	} else {
		data.action=action;
		data.all=all;
	}
	//ajax remove Notifications by AS Id
	$.ajax({
        type: "POST",
        url: baseUrl+"/"+moduleId+"/notification/update",
        data: data,
        dataType : 'json'
    })
    .done( function (data) {
    	mylog.dir(data);
        if ( data && data.result ) {
        	if(action=="seen"){
        		$(".notifList"+element+" li.notifLi").addClass("seen");
        		notifCount();
        	}else{
        		if(all)
        			$(".notifList"+element+" li.notifLi").addClass("read");
        		else
        			$(".notifList"+element+" li.notif_"+notifId).addClass("read");
        	}
        	mylog.log("notification cleared ",data);
        } else {
            toastr.error("no notifications found ");
        }

    });
}
function markAllAsSeen(){
	updateNotification("seen","");
}
function markAsRead(id){
	updateNotification("read","", id);
}
function markAllAsRead(element)
{
	updateNotification("read",element);
}
function removeNotification(id)
{ // Ancienne markAsRead
	mylog.log("markAsRead",id);
	//ajax remove Notifications by AS Id
	$.ajax({
        type: "POST",
        url: baseUrl+"/"+moduleId+"/notification/marknotificationasread",
        data: { "id" : id },
        dataType : 'json'
    })
    .done( function (data) {
    	//mylog.dir(data);
        if ( data && data.result ) {
        	$("li.notif_"+id).remove();
        	mylog.log("notification cleared ",data);
        } else {
            toastr.error("no notifications found ");
        }
        notifCount();
    });
}

function removeAllNotifications()
{
	//Ancienne markAllAsRead
	$.ajax({
        type: "POST",
        url: baseUrl+"/"+moduleId+"/notification/removeall",
        dataType : 'json'
    })
    .done( function (data) {
    	mylog.dir(data);
        if ( data && data.result ) {
	        refreshNotifications(userId,"citoyens","","menuTop");
        	//$(".notifList li.notifLi").remove();
        	//mylog.log("notifications cleared ",data);
        	//$(".sb-toggle-right").trigger("click");
        } else {
            toastr.error("no notifications found ");
        }
        notifCount();
    });

}

function refreshNotifications(elementId,elementType,element,event)
{
	//ajax get Notifications
	$(".pageslide-list.header .btn-primary i.fa-refresh").addClass("fa-spin");
	mylog.log("refreshNotifications", maxNotifTimstamp);
	var element = element;
	if(typeof event != "undefined" && event)
		var event=event;
	else
		var event=null;
	$.ajax({
        type: "GET",
        url: baseUrl+"/"+moduleId+"/notification/getnotifications/type/"+elementType+"/id/"+elementId+"?ts="+maxNotifTimstamp
    })
    .done(function (data) { mylog.log("REFRESH NOTIF : "); mylog.dir(data);
        if (data) {
        	buildNotifications(data.notif, element,event);
        	if(data.coop > 0){
        		$(".btn-dashboard-dda").show();
        		$(".coopNotifs").html(data.coop).show(100);
        	}
        	else{
        		//$(".btn-dashboard-dda").hide();
        		//$(".coopNotifs").html("");
        	}
        } else {
            toastr.error("no notifications found ");
        }
        $(".pageslide-list.header .btn-primary i.fa-refresh").removeClass("fa-spin");
    }).fail(function(){
    	toastr.error("error notifications");
        $(".pageslide-list.header .btn-primary i.fa-refresh").removeClass("fa-spin");
    });
}
/*function markAllNotificationsAsSeen()
{
	$.ajax({
        type: "POST",
        data:{"action":"seen","all":true}
        url: baseUrl+"/"+moduleId+"/notification/update"
    })
    .done(function (data) { //mylog.log("REFRESH NOTIF : "); mylog.dir(data);
        if (data) {
        	countNotif(true);
        } else {
            //toastr.error("no notifications found ");
        }
        $(".pageslide-list.header .btn-primary i.fa-refresh").removeClass("fa-spin");
    }).fail(function(){
    	toastr.error("error notifications");
        $(".pageslide-list.header .btn-primary i.fa-refresh").removeClass("fa-spin");
    });

}*/
function buildNotifications(list, element, event)
{	mylog.log("buildNotifications");
	mylog.log(list);
	//element="";
//	if(isPodView)
//		element="Element";
//	mylog.info("buildNotifications"+element+"()");
	mylog.log(typeof list);
	if(event==null)
		$(".notifList"+element).html("");
	else
		notifHtml="";
	if(typeof list != "undefined" && typeof list == "object"){
		$.each( list , function( notifKey , notifObj )
		{
			console.log("build notif", notifObj);
			var url = (typeof notifObj.notify != "undefined") ? notifObj.notify.url : "#";
			//convert url to hash for loadByHash
			if(url.indexOf("communecter/")>0){
				url=url.split("communecter/");
				url=url[1];
			}
			url = "#"+url.replace(/\//g, ".");
			//var moment = require('moment');
			momentNotif=notifObj.timeAgo;
			/*moment.lang('fr');
			if(typeof notifObj.updated != "undefined")
				momentNotif=moment(new Date( parseInt(notifObj.updated.sec)*1000 )).fromNow();
			else if(typeof notifObj.created != "undefined")
				momentNotif=moment(new Date( parseInt(notifObj.created.sec)*1000 )).fromNow();
			else
				momentNotif="";*/
			//if(typeof notifObj.timestamp != "undefined")
			//	momentNotif=moment(new Date( parseInt(notifObj.timestamp.sec)*1000 )).fromNow();
			var icon = (typeof notifObj.notify != "undefined") ? notifObj.notify.icon : "fa-bell";
			var displayName = (typeof notifObj.notify != "undefined") ? notifObj.notify.displayName : "Undefined notification";
			//console.log(notifObj);
			//console.log(userId);
			//console.log(notifObj.notify);
			//console.log(notifObj.notify.id[userId]);
			var isSeen = (typeof notifObj.notify.id[userId] != "undefined" && typeof notifObj.notify.id[userId].isUnseen != "undefined") ? "" : "seen";
			var isRead = (typeof notifObj.notify.id[userId] != "undefined" && typeof notifObj.notify.id[userId].isUnread != "undefined") ? "" : "read";

			var notifObjType = (typeof notifObj.object != "undefined" && typeof notifObj.object.type != "undefined") ?
								notifObj.object.type : "";

			var notifObjId = (typeof notifObj.object != "undefined" && typeof notifObj.object.id != "undefined") ?
								notifObj.object.id : "";

			str = "
"+
					""+
						"
"+
							""+
								''+
							"" +
						"
"+
						"
"+
							''+
								displayName+
							"" +

							""+momentNotif+""+
						"
"+
					""+
					""+
							''+
						"" +
				  "
";
			if(event==null){
				$(".notifList"+element).append(str);
				$(".notif_"+notifKey).removeClass('hide').addClass("animated bounceInRight enable col-md-12 col-sm-12 col-xs-12");
			}else{
				notifHtml+=str;
			}
			if( notifObj.timestamp > maxNotifTimstamp )
				maxNotifTimstamp = notifObj.timestamp;
		});
		if(event != null){
			$(".notifList"+element).html(notifHtml);
			$(".notifLi").addClass("col-md-12 col-sm-12 col-xs-12");
		}
		setTimeout( function(){
	    	notifCount(false, element);
	    	bindNotifEvents(element);
	    	//bindLBHLinks();
	    }, 800);
		//bindNotifEvents();
	}
}

function notifCount(upNotifUnseen, element)
{ 	var countNotif = $(".notifList"+element+" li.enable").length;
	var countNotifSeen = $(".notifList"+element+" li.seen").length;
	var countNotifUnseen = countNotif-countNotifSeen;
	if(upNotifUnseen)
		countNotifUnseen=0;
	mylog.log(" !!!! notifCount", countNotif, "element :",element);
	mylog.log(" !!!! notifCount upNotifUnseen", upNotifUnseen, "countNotif ", countNotif, "countNotifSeen ", countNotifSeen);

	mylog.log(" !! ", ".notifList"+element+" li.enable");

	$(".notifCount").html( countNotif );
	mylog.log(".notifCount).html(", countNotif);

	if(countNotif == 0)
		$(".notifList"+element).html("
 "+trad["noMoreNotifs"]+"
");
	//if(element==""){

		mylog.log("if( countNotifUnseen", countNotifUnseen, " > 0");
		if( countNotifUnseen > 0)
		{
		    $(".notifications-count"+element).html(countNotifUnseen);
			$('.notifications-count'+element).removeClass('hide');
			$('.notifications-count'+element).addClass('animated bounceIn');
			$('.notifications-count'+element).addClass('badge-success');
			$('.notifications-count'+element).removeClass('badge-tranparent');
			$(".markAllAsRead").show();
		} else {
			//$('.notifications-count').addClass('hide');
			$(".notifications-count"+element).html("");
			$('.notifications-count'+element).addClass('hide');
			$('.notifications-count'+element).removeClass('badge-success');
			$('.notifications-count'+element).addClass('badge-tranparent');
			$(".markAllAsRead").hide();
		}
	//}
}<commit_msg>clear notif<commit_after>var notifications = null;
var maxNotifTimstamp = 0;

function bindNotifEvents(element){ console.log("bindNotifEvents");
	$(".notifList"+element+" a.notif").off().on("click",function (e)
	{
		markAsRead( $(this).data("id") );
		hash = $(this).data("href");
		elem = $(this).parent();
		//elem.removeClass('animated bounceInRight').addClass("animated bounceOutRight");
		//elem.removeClass("enable");
		var thisJQ = this;
		setTimeout(function(){
          //  elem.addClass("read");
            //elem.removeClass('animated bounceOutRight');
            if(e.which==2)
				window.open(baseUrl+hash, '_blank');
			else{
				console.log("objtype", $(thisJQ).data("objtype"));
				if($(thisJQ).data("objtype") == "proposals" ||
					$(thisJQ).data("objtype") == "actions" || $(thisJQ).data("objtype") == "resolutions"){
					var objType = $(thisJQ).data("objtype");
					 uiCoop.getCoopDataPreview(objType.substr(0, objType.length-1), $(thisJQ).data("objid"));
				}else{
	            	urlCtrl.loadByHash(hash);
	            }
			}
            //notifCount();
        }, 200);
	});
	$('.tooltips').tooltip();
	$(".notifList"+element+" li").mouseenter(function(){
		$(this).find(".removeBtn").show();
	}).mouseleave(function(){
		$(this).find(".removeBtn").hide();
	})
}
function updateNotification(action, element, id)
{
	var action = action;
	var all = true;
	data = new Object;
	if(id != null){
		var notifId=id;
		all=false;
		data.id=id
	} else {
		data.action=action;
		data.all=all;
	}
	//ajax remove Notifications by AS Id
	$.ajax({
        type: "POST",
        url: baseUrl+"/"+moduleId+"/notification/update",
        data: data,
        dataType : 'json'
    })
    .done( function (data) {
    	mylog.dir(data);
        if ( data && data.result ) {
        	if(action=="seen"){
        		$(".notifList"+element+" li.notifLi").addClass("seen");
        		notifCount();
        	}else{
        		if(all)
        			$(".notifList"+element+" li.notifLi").addClass("read");
        		else
        			$(".notifList"+element+" li.notif_"+notifId).addClass("read");
        	}
        	mylog.log("notification cleared ",data);
        } else {
            toastr.error("no notifications found ");
        }

    });
}
function markAllAsSeen(){
	updateNotification("seen","");
}
function markAsRead(id){
	updateNotification("read","", id);
}
function markAllAsRead(element)
{
	updateNotification("read",element);
}
function removeNotification(id)
{ // Ancienne markAsRead
	mylog.log("markAsRead",id);
	//ajax remove Notifications by AS Id
	$.ajax({
        type: "POST",
        url: baseUrl+"/"+moduleId+"/notification/marknotificationasread",
        data: { "id" : id },
        dataType : 'json'
    })
    .done( function (data) {
    	//mylog.dir(data);
        if ( data && data.result ) {
        	$("li.notif_"+id).remove();
        	mylog.log("notification cleared ",data);
        } else {
            toastr.error("no notifications found ");
        }
        notifCount();
    });
}

function removeAllNotifications()
{
	//Ancienne markAllAsRead
	$.ajax({
        type: "POST",
        url: baseUrl+"/"+moduleId+"/notification/removeall",
        dataType : 'json'
    })
    .done( function (data) {
    	mylog.dir(data);
        if ( data && data.result ) {
	        refreshNotifications(userId,"citoyens","","menuTop");
        	//$(".notifList li.notifLi").remove();
        	//mylog.log("notifications cleared ",data);
        	//$(".sb-toggle-right").trigger("click");
        } else {
            toastr.error("no notifications found ");
        }
        notifCount();
    });

}

function refreshNotifications(elementId,elementType,element,event)
{
	//ajax get Notifications
	$(".pageslide-list.header .btn-primary i.fa-refresh").addClass("fa-spin");
	mylog.log("refreshNotifications", maxNotifTimstamp);
	var element = element;
	if(typeof event != "undefined" && event)
		var event=event;
	else
		var event=null;
	$.ajax({
        type: "GET",
        url: baseUrl+"/"+moduleId+"/notification/getnotifications/type/"+elementType+"/id/"+elementId+"?ts="+maxNotifTimstamp
    })
    .done(function (data) { mylog.log("REFRESH NOTIF : "); mylog.dir(data);
        if (data) {
        	buildNotifications(data.notif, element,event);
        	if(data.coop > 0){
        		$(".btn-dashboard-dda").show();
        		$(".coopNotifs").html(data.coop).show(100);
        	}
        	else{
        		//$(".btn-dashboard-dda").hide();
        		//$(".coopNotifs").html("");
        	}
        } else {
            toastr.error("no notifications found ");
        }
        $(".pageslide-list.header .btn-primary i.fa-refresh").removeClass("fa-spin");
    }).fail(function(){
    	toastr.error("error notifications");
        $(".pageslide-list.header .btn-primary i.fa-refresh").removeClass("fa-spin");
    });
}
/*function markAllNotificationsAsSeen()
{
	$.ajax({
        type: "POST",
        data:{"action":"seen","all":true}
        url: baseUrl+"/"+moduleId+"/notification/update"
    })
    .done(function (data) { //mylog.log("REFRESH NOTIF : "); mylog.dir(data);
        if (data) {
        	countNotif(true);
        } else {
            //toastr.error("no notifications found ");
        }
        $(".pageslide-list.header .btn-primary i.fa-refresh").removeClass("fa-spin");
    }).fail(function(){
    	toastr.error("error notifications");
        $(".pageslide-list.header .btn-primary i.fa-refresh").removeClass("fa-spin");
    });

}*/
function buildNotifications(list, element, event)
{	mylog.log("buildNotifications");
	mylog.log(list);
	//element="";
//	if(isPodView)
//		element="Element";
//	mylog.info("buildNotifications"+element+"()");
	mylog.log(typeof list);
	if(event==null)
		$(".notifList"+element).html("");
	else
		notifHtml="";
	if(typeof list != "undefined" && typeof list == "object"){
		$.each( list , function( notifKey , notifObj )
		{
			//console.log("build notif", notifObj);
			var url = (typeof notifObj.notify != "undefined") ? notifObj.notify.url : "#";
			//convert url to hash for loadByHash
			if(url.indexOf("communecter/")>0){
				url=url.split("communecter/");
				url=url[1];
			}
			url = "#"+url.replace(/\//g, ".");
			//var moment = require('moment');
			momentNotif=notifObj.timeAgo;
			/*moment.lang('fr');
			if(typeof notifObj.updated != "undefined")
				momentNotif=moment(new Date( parseInt(notifObj.updated.sec)*1000 )).fromNow();
			else if(typeof notifObj.created != "undefined")
				momentNotif=moment(new Date( parseInt(notifObj.created.sec)*1000 )).fromNow();
			else
				momentNotif="";*/
			//if(typeof notifObj.timestamp != "undefined")
			//	momentNotif=moment(new Date( parseInt(notifObj.timestamp.sec)*1000 )).fromNow();
			var icon = (typeof notifObj.notify != "undefined") ? notifObj.notify.icon : "fa-bell";
			var displayName = (typeof notifObj.notify != "undefined") ? notifObj.notify.displayName : "Undefined notification";
			//console.log(notifObj);
			//console.log(userId);
			//console.log(notifObj.notify);
			//console.log(notifObj.notify.id[userId]);
			var isSeen = (typeof notifObj.notify.id[userId] != "undefined" && typeof notifObj.notify.id[userId].isUnseen != "undefined") ? "" : "seen";
			var isRead = (typeof notifObj.notify.id[userId] != "undefined" && typeof notifObj.notify.id[userId].isUnread != "undefined") ? "" : "read";

			var notifObjType = (typeof notifObj.object != "undefined" && typeof notifObj.object.type != "undefined") ?
								notifObj.object.type : "";

			var notifObjId = (typeof notifObj.object != "undefined" && typeof notifObj.object.id != "undefined") ?
								notifObj.object.id : "";

			str = "
"+
					""+
						"
"+
							""+
								''+
							"" +
						"
"+
						"
"+
							''+
								displayName+
							"" +

							""+momentNotif+""+
						"
"+
					""+
					""+
							''+
						"" +
				  "
";
			if(event==null){
				$(".notifList"+element).append(str);
				$(".notif_"+notifKey).removeClass('hide').addClass("animated bounceInRight enable col-md-12 col-sm-12 col-xs-12");
			}else{
				notifHtml+=str;
			}
			if( notifObj.timestamp > maxNotifTimstamp )
				maxNotifTimstamp = notifObj.timestamp;
		});
		if(event != null){
			$(".notifList"+element).html(notifHtml);
			$(".notifLi").addClass("col-md-12 col-sm-12 col-xs-12");
		}
		setTimeout( function(){
	    	notifCount(false, element);
	    	bindNotifEvents(element);
	    	//bindLBHLinks();
	    }, 800);
		//bindNotifEvents();
	}
}

function notifCount(upNotifUnseen, element)
{ 	var countNotif = $(".notifList"+element+" li.enable").length;
	var countNotifSeen = $(".notifList"+element+" li.seen").length;
	var countNotifUnseen = countNotif-countNotifSeen;
	if(upNotifUnseen)
		countNotifUnseen=0;
	mylog.log(" !!!! notifCount", countNotif, "element :",element);
	mylog.log(" !!!! notifCount upNotifUnseen", upNotifUnseen, "countNotif ", countNotif, "countNotifSeen ", countNotifSeen);

	mylog.log(" !! ", ".notifList"+element+" li.enable");

	$(".notifCount").html( countNotif );
	mylog.log(".notifCount).html(", countNotif);

	if(countNotif == 0)
		$(".notifList"+element).html("
 "+trad["noMoreNotifs"]+"
");
	//if(element==""){

		mylog.log("if( countNotifUnseen", countNotifUnseen, " > 0");
		if( countNotifUnseen > 0)
		{
		    $(".notifications-count"+element).html(countNotifUnseen);
			$('.notifications-count'+element).removeClass('hide');
			$('.notifications-count'+element).addClass('animated bounceIn');
			$('.notifications-count'+element).addClass('badge-success');
			$('.notifications-count'+element).removeClass('badge-tranparent');
			$(".markAllAsRead").show();
		} else {
			//$('.notifications-count').addClass('hide');
			$(".notifications-count"+element).html("");
			$('.notifications-count'+element).addClass('hide');
			$('.notifications-count'+element).removeClass('badge-success');
			$('.notifications-count'+element).addClass('badge-tranparent');
			$(".markAllAsRead").hide();
		}
	//}
}<|endoftext|>


<commit_before>import * as commonApi from '../../api/common';
import * as api from '../../api/todo';

describe('getGiphy', () => {
    let text;
    let url;

    beforeAll(() => {
        text = 'text';
        url = 'url';
    });

    it('calls the giphy api with correct parameters', () => {
        spyOn(commonApi, 'get').and.returnValue(Promise.resolve({data: {images: {'fixed_height': {url}}}}));

        return api.getGiphy(text).then(() => {
            expect(commonApi.get)
                .toHaveBeenCalledWith(`http://api.giphy.com/v1/gifs/translate?s=${encodeURIComponent(text)}&api_key=dc6zaTOxFJmzC`);
        });
    });

    it('parses the response from the giphy api and pulls off the fixed_height url', () => {
        spyOn(commonApi, 'get').and.returnValue(Promise.resolve({data: {images: {'fixed_height': {url}}}}));

        return api.getGiphy(text).then(response => {
            expect(response).toEqual(url);
        });
    });
});
<commit_msg>fix todo api test<commit_after>import * as commonApi from '../../api/common';
import * as api from '../../api/todo';

describe('getGiphy', () => {
    let text;
    let url;

    beforeAll(() => {
        text = 'text';
        url = 'url';
    });

    it('calls the giphy api with correct parameters', () => {
        spyOn(commonApi, 'get').and.returnValue(Promise.resolve({data: {images: {'fixed_height': {url}}}}));

        return api.getGiphy(text).then(() => {
            expect(commonApi.get)
                .toHaveBeenCalledWith(`//api.giphy.com/v1/gifs/translate?s=${encodeURIComponent(text)}&api_key=dc6zaTOxFJmzC`);
        });
    });

    it('parses the response from the giphy api and pulls off the fixed_height url', () => {
        spyOn(commonApi, 'get').and.returnValue(Promise.resolve({data: {images: {'fixed_height': {url}}}}));

        return api.getGiphy(text).then(response => {
            expect(response).toEqual(url);
        });
    });
});
<|endoftext|>


<commit_before>import {inject, bindable, customElement, BindingEngine, LogManager} from 'aurelia-framework';
import {ModelObserver} from './helpers/model-observer';

@inject(BindingEngine)
@customElement('chart')
@bindable('data')
@bindable('options')
@bindable('type')
@bindable('height')
@bindable('width')
@bindable('throttle')
export class ChartElement {
    supportedChartTypes = [
        'Line',
        'Bar',
        'Radar',
        'PolarArea',
        'Pie',
        'Doughnut'
    ];

    constructor(bindingEngine){
        this._modelObserver = new ModelObserver(this, bindingEngine);
        this._logger = LogManager.getLogger('chartjs');
        this._canRedraw = true;
        this.throttle = 500;
        this._isThrottling = false;
    }

    bind(bindingContext){
        this.options = this.options || {};
        this.height = this.height || 400;
        this.width = this.width || 500;
        this.throttle = Math.min(this.throttle, 250);

        this.canvasElement.height = this.height;
        this.canvasElement.width = this.width;
    }

    attached(){
        this._createChart();

        this._modelObserver.observeProperty('height', this._refreshChart);
        this._modelObserver.observeProperty('width', this._refreshChart);
        this._modelObserver.observeProperty('options', this._updateChart);
        this._modelObserver.observeProperty('data', this._updatechart);

        this._watchChartData();
    }

    _watchChartData(){
        if(this.data != null) {
            this._modelObserver.observeCollection(this.data.datasets, this._updateChart);
            this._modelObserver.observeCollection(this.data.labels, this._updateChart);
            for(var ds of this.data.datasets) {
                this._modelObserver.observeCollection(ds.data, this._updateChart);
            }
        }
    }

    _createChart(){
        if(this._canRedraw === true) {
            if(this._isSupportedChartType() === true) {
                try {
                    var canvas = this.canvasElement;
                    var context = canvas.getContext('2d');
                    context.clearRect(0,0,canvas.width, canvas.height);
                    this._chart = new Chart(context)[this.type](this.data, this.options);
                } catch(e) {
                    this._logger.error(e);
                }
            }

            this._canRedraw = false;
            this._beginThrottling();
        }
    }

    _refreshChart(){
        this._chart.destroy();

        this.canvasElement.height = this.height;
        this.canvasElement.width = this.width;

        this._createChart();
    }

    _updateChart(){
        this._chart.update();
    }

    _refreshChartData(){
        this._chart.destroy();

        this._modelObserver.disposeCollectionSubscriptions();
        this._watchChartData();

        this._refreshChart();
    }

    _hardRefresh(){
        if(this._chart != null) {
            this._chart.destroy();

            this.canvasElement.height = this.height;
            this.canvasElement.width = this.width;

            this._createChart();
        }
    }

    _isSupportedChartType(){
        if(this.supportedChartTypes.indexOf(this.type) === -1) {
            this._logger.error('unsupported chart type');
            return false;
        }

        return true;
    }

    _beginThrottling(){
        if(this._isThrottling === false) {
            this._isThrottling = true;
            setTimeout(function(){
                this._canRedraw = true;
                this._isThrottling = false;
            }.bind(this), this.throttle);
        }
    }

    detached(){
        this._modelObserver.dispose();
    }
}<commit_msg>simplified, now user can just access chartElement.chart to access actual ChartJS object<commit_after>import {inject, bindable, customElement, BindingEngine, LogManager} from 'aurelia-framework';
import {ModelObserver} from './helpers/model-observer';

@inject(BindingEngine)
@customElement('chart')
@bindable('data')
@bindable('options')
@bindable('type')
@bindable('height')
@bindable('width')
@bindable('throttle')
export class ChartElement {
    supportedChartTypes = [
        'Line',
        'Bar',
        'Radar',
        'PolarArea',
        'Pie',
        'Doughnut'
    ];

    constructor(bindingEngine){
        this._modelObserver = new ModelObserver(this, bindingEngine);
        this._logger = LogManager.getLogger('chartjs');
        this._canRedraw = true;
        this.throttle = 500;
        this._isThrottling = false;
    }

    bind(bindingContext){
        this.options = this.options || {};
        this.height = this.height || 400;
        this.width = this.width || 500;
        this.throttle = Math.min(this.throttle, 250);

        this.canvasElement.height = this.height;
        this.canvasElement.width = this.width;
    }

    attached(){
        this._createChart();
    }

    _createChart(){
        if(this._canRedraw === true) {
            if(this._isSupportedChartType() === true) {
                try {
                    var canvas = this.canvasElement;
                    var context = canvas.getContext('2d');
                    context.clearRect(0,0,canvas.width, canvas.height);
                    this.chart = new Chart(context)[this.type](this.data, this.options);
                } catch(e) {
                    this._logger.error(e);
                }
            }

            this._canRedraw = false;
            this._beginThrottling();
        }
    }

    _isSupportedChartType(){
        if(this.supportedChartTypes.indexOf(this.type) === -1) {
            this._logger.error('unsupported chart type');
            return false;
        }

        return true;
    }

    _beginThrottling(){
        if(this._isThrottling === false) {
            this._isThrottling = true;
            setTimeout(function(){
                this._canRedraw = true;
                this._isThrottling = false;
            }.bind(this), this.throttle);
        }
    }

    detached(){
        this._modelObserver.dispose();
    }
}<|endoftext|>


<commit_before>import path from 'path';
import dotenv from 'dotenv';
import Config from '../libs/Config';

process.env.NODE_ENV = process.env.NODE_ENV || 'development';

dotenv.config();

const config = new Config({ envPrefix: 'OORS_SERVER_CONFIG' });

config.add({
  rootDir: '',
  rootURL: config.ref(() => `http://${config.get('hostname')}:${config.get('port')}`),
  isDev: process.env.NODE_ENV === 'development',
  port: 3000,
  hostname: 'localhost',
  middlewares: {
    useragent: {},
    cors: {},
    helmet: {},
    morgan: {
      params: 'dev',
      enabled: config.ref('isDev'),
    },
    compression: {
      enabled: config.ref(() => !config.get('isDev')),
    },
    bodyParserJSON: {
      params: { limit: '20mb' },
    },
    bodyParserURLEncoded: {},
    cookieParser: {
      params: {
        secret: 'THIS_IS_MY_SECRET',
      },
    },
    statusMonitor: {},
    isMethod: {},
    validationErrorHandler: {},
    boomErrorHandler: {
      params: {
        isDev: config.ref('isDev'),
      },
    },
    errorHandler: {
      params: {
        isDev: config.ref('isDev'),
      },
    },
  },
  modules: {
    'oors.mongoDb': {
      connections: [
        {
          name: 'default',
          url: 'mongodb://localhost:27017/oors',
        },
      ],
    },
    'oors.user': {
      rootURL: config.ref('rootURL'),
      jwtSecret: 'MY_JWT_SECRET',
      jwtConfig: {
        expiresIn: '1d',
      },
      mockUserMiddlewarePivot: {
        before: 'graphql',
      },
      passportMiddlewarePivot: 'cookieParser',
      mockUserConfig: {
        enabled: config.ref('isDev'),
        path: '/graphql',
        params: {}, // no params means an empty query - just load any db user
      },
      passportConfig: {
        enabled: false,
      },
    },
    'oors.mailer': {
      transport: {
        jsonTransport: true,
      },
      saveToDisk: true,
      emailsDir: config.ref(() => path.resolve(config.get('rootDir'), './emails')),
      templatesDir: '',
      middlewarePivot: {
        before: 'isMethod',
      },
    },
    'oors.fileStorage': {
      uploadDir: config.ref(() => path.resolve(config.get('rootDir'), './uploads')),
    },
    'oors.graphQL': {
      graphiql: {
        params: {
          subscriptionsEndpoint: config.ref(
            () => `ws://${config.get('hostname')}:${config.get('port')}/subscriptions`,
          ),
        },
      },
    },
    'oors.router': {
      middlewarePivot: {
        after: 'isMethod',
      },
    },
    'oors.logger': {
      logsDir: config.ref(() => path.resolve(config.get('rootDir'), './logs')),
    },
  },
});

export default config;
<commit_msg>[oors-presets] updated logger config<commit_after>import path from 'path';
import dotenv from 'dotenv';
import Config from '../libs/Config';

process.env.NODE_ENV = process.env.NODE_ENV || 'development';

dotenv.config();

const config = new Config({ envPrefix: 'OORS_SERVER_CONFIG' });

config.add({
  rootDir: '',
  rootURL: config.ref(() => `http://${config.get('hostname')}:${config.get('port')}`),
  isDev: process.env.NODE_ENV === 'development',
  port: 3000,
  hostname: 'localhost',
  middlewares: {
    useragent: {},
    cors: {},
    helmet: {},
    morgan: {
      params: 'dev',
      enabled: config.ref('isDev'),
    },
    compression: {
      enabled: config.ref(() => !config.get('isDev')),
    },
    bodyParserJSON: {
      params: { limit: '20mb' },
    },
    bodyParserURLEncoded: {},
    cookieParser: {
      params: {
        secret: 'THIS_IS_MY_SECRET',
      },
    },
    statusMonitor: {},
    isMethod: {},
    validationErrorHandler: {},
    boomErrorHandler: {
      params: {
        isDev: config.ref('isDev'),
      },
    },
    errorHandler: {
      params: {
        isDev: config.ref('isDev'),
      },
    },
  },
  modules: {
    'oors.mongoDb': {
      connections: [
        {
          name: 'default',
          url: 'mongodb://localhost:27017/oors',
        },
      ],
    },
    'oors.user': {
      rootURL: config.ref('rootURL'),
      jwtSecret: 'MY_JWT_SECRET',
      jwtConfig: {
        expiresIn: '1d',
      },
      mockUserMiddlewarePivot: {
        before: 'graphql',
      },
      passportMiddlewarePivot: 'cookieParser',
      mockUserConfig: {
        enabled: config.ref('isDev'),
        path: '/graphql',
        params: {}, // no params means an empty query - just load any db user
      },
      passportConfig: {
        enabled: false,
      },
    },
    'oors.mailer': {
      transport: {
        jsonTransport: true,
      },
      saveToDisk: true,
      emailsDir: config.ref(() => path.resolve(config.get('rootDir'), './emails')),
      templatesDir: '',
      middlewarePivot: {
        before: 'isMethod',
      },
    },
    'oors.fileStorage': {
      uploadDir: config.ref(() => path.resolve(config.get('rootDir'), './uploads')),
    },
    'oors.graphQL': {
      graphiql: {
        params: {
          subscriptionsEndpoint: config.ref(
            () => `ws://${config.get('hostname')}:${config.get('port')}/subscriptions`,
          ),
        },
      },
    },
    'oors.router': {
      middlewarePivot: {
        after: 'isMethod',
      },
    },
    'oors.logger': {},
  },
});

export default config;
<|endoftext|>


<commit_before>import {last, isEqual, omit} from 'lodash';

const isNodeEqual = (x, y) => {
    const xBase = 'children' in x ? omit(x, 'children') : x;
    const yBase = 'children' in y ? omit(y, 'children') : y;

    return isEqual(xBase, yBase);
};

const mergeNode = (x, y) => {
    if ('value' in x) {
        return {
            ...x,
            value: x.value + y.value
        };
    }

    return x;
};

const attachNode = (parent, node) => {
    const previousSibling = last(parent.children);

    if (previousSibling && isNodeEqual(previousSibling, node)) {
        /* eslint-disable no-param-reassign */
        parent.children[parent.children.length - 1] = mergeNode(previousSibling, node);
        /* eslint-enable no-param-reassign */
    }
    else {
        parent.children.push(node);
    }

    return last(parent.children);
};

export default pathList => {
    const root = {type: 'root', children: []};

    for (const path of pathList) {
        path.reduce(
            (parent, node, i) => {
                const nodeToUse = i === path.length - 1 ? {...node} : {...node, children: []};
                return attachNode(parent, nodeToUse);
            },
            root
        );
    }

    return root;
};
<commit_msg>Fix an issue where backToTree unexpected merges mark nodes<commit_after>import {last, isEqual, omit} from 'lodash';

const areNodesMeregable = (x, y) => {
    if (x.type !== y.type) {
        return false;
    }

    if (x.type === 'text') {
        return true;
    }

    if (!x.children || !y.children) {
        return false;
    }

    const xBase = 'children' in x ? omit(x, 'children') : x;
    const yBase = 'children' in y ? omit(y, 'children') : y;

    return isEqual(xBase, yBase);
};

const mergeNode = (x, y) => {
    if ('value' in x) {
        return {
            ...x,
            value: x.value + y.value
        };
    }

    return x;
};

const attachNode = (parent, node) => {
    const previousSibling = last(parent.children);

    if (previousSibling && areNodesMeregable(previousSibling, node)) {
        /* eslint-disable no-param-reassign */
        parent.children[parent.children.length - 1] = mergeNode(previousSibling, node);
        /* eslint-enable no-param-reassign */
    }
    else {
        parent.children.push(node);
    }

    return last(parent.children);
};

export default pathList => {
    const root = {type: 'root', children: []};

    for (const path of pathList) {
        path.reduce(
            (parent, node, i) => {
                const nodeToUse = i === path.length - 1 ? {...node} : {...node, children: []};
                return attachNode(parent, nodeToUse);
            },
            root
        );
    }

    return root;
};
<|endoftext|>


<commit_before>var util = require("../../util");
var kvn = require("../../kvn");

module.exports = function (category, action, label, value) {
  try {
    category = kvn(category);
    action   = kvn(action);
    label    = kvn(label);

    if (!util.isValidString(category)) { return; }
    if (!util.isValidString(action)) { return; }
    if (!util.isObject(self._gaq) || !util.isFunction(self._gaq.push)) { return; }
    if (util.isFunction(self.ga)) { return; } // let ga manage the tracking

    self._gaq.push(["trackEvent", category, action, label, value]);
    console.log("SUCCESS Bighorn.track piwik", category, action, label, value);
  } catch (e) {
    console.log("ERROR Bighorn.track piwik", category, action, label, value, e.message);
  }
};
<commit_msg>Fix gaq log message<commit_after>var util = require("../../util");
var kvn = require("../../kvn");

module.exports = function (category, action, label, value) {
  try {
    category = kvn(category);
    action   = kvn(action);
    label    = kvn(label);

    if (!util.isValidString(category)) { return; }
    if (!util.isValidString(action)) { return; }
    if (!util.isObject(self._gaq) || !util.isFunction(self._gaq.push)) { return; }
    if (util.isFunction(self.ga)) { return; } // let ga manage the tracking

    self._gaq.push(["trackEvent", category, action, label, value]);
    console.log("SUCCESS Bighorn.track gaq", category, action, label, value);
  } catch (e) {
    console.log("ERROR Bighorn.track gaq", category, action, label, value, e.message);
  }
};
<|endoftext|>


<commit_before>var Backbone = require('backbone');

module.exports = Backbone.Model.extend({

  defaults: {
    schema: {}
  },

  initialize: function (attrs, opts) {
    if (!opts.columnOptionsFactory) throw new Error('columnOptionsFactory is required');

    this._columnOptionsFactory = opts.columnOptionsFactory;
  },

  updateSchema: function () {
    var columnOptions = this._columnOptionsFactory.create(this.get('column'));
    var aggregatedColumnOptions = this._columnOptionsFactory.create(this.get('aggregation_column'));
    var helpMsg = this._columnOptionsFactory.unavailableColumnsHelpMessage();

    this.schema = {
      title: {
        type: 'Text',
        text: _t('editor.widgets.widgets-form.data.title'),
        validators: ['required']
      },
      enabler: {
        type: 'EnablerEditor',
        title: '', // Needed in order to "hide" that part
        label: 'whatever', // label instead of title
        editor: {
           type: 'Select',
           options: ['wadus', 'harr', 'aliño'],
           editorAttrs: {
              showLabel: false
           }
        }
     },
      column: {
        type: 'Select',
        title: _t('editor.widgets.widgets-form.data.aggregate-by'),
        options: columnOptions,
        help: helpMsg,
        editorAttrs: {
          disabled: this._columnOptionsFactory.areColumnsUnavailable()
        }
      },
      aggregation: {
        type: 'Select',
        title: _t('editor.widgets.widgets-form.data.operation'),
        options: [
          {val: 'sum', label: _t('editor.widgets.widgets-form.aggregation-options.sum')},
          {val: 'count', label: _t('editor.widgets.widgets-form.aggregation-options.count')},
          {val: 'avg', label: _t('editor.widgets.widgets-form.aggregation-options.avg')},
          {val: 'min', label: _t('editor.widgets.widgets-form.aggregation-options.min')},
          {val: 'max', label: _t('editor.widgets.widgets-form.aggregation-options.max')}
        ],
        editorAttrs: {
          showSearch: false
        }
      },
      aggregation_column: {
        type: 'Select',
        title: _t('editor.widgets.widgets-form.data.operation-column'),
        options: aggregatedColumnOptions,
        help: helpMsg,
        editorAttrs: {
          disabled: this._columnOptionsFactory.areColumnsUnavailable()
        }
      },
      suffix: {
        title: _t('editor.widgets.widgets-form.data.suffix'),
        type: 'Text'
      },
      prefix: {
        title: _t('editor.widgets.widgets-form.data.prefix'),
        type: 'Text'
      }
    };
  },

  canSave: function () {
    var column = this.get('column');
    var aggregationColumn = this.get('aggregation_column');

    // Columns might not be available until table is fetched
    return !!(column && aggregationColumn);
  }

});
<commit_msg>Removed enabler from category data schema model<commit_after>var Backbone = require('backbone');

module.exports = Backbone.Model.extend({

  defaults: {
    schema: {}
  },

  initialize: function (attrs, opts) {
    if (!opts.columnOptionsFactory) throw new Error('columnOptionsFactory is required');

    this._columnOptionsFactory = opts.columnOptionsFactory;
  },

  updateSchema: function () {
    var columnOptions = this._columnOptionsFactory.create(this.get('column'));
    var aggregatedColumnOptions = this._columnOptionsFactory.create(this.get('aggregation_column'));
    var helpMsg = this._columnOptionsFactory.unavailableColumnsHelpMessage();

    this.schema = {
      title: {
        type: 'Text',
        text: _t('editor.widgets.widgets-form.data.title'),
        validators: ['required']
      },
      column: {
        type: 'Select',
        title: _t('editor.widgets.widgets-form.data.aggregate-by'),
        options: columnOptions,
        help: helpMsg,
        editorAttrs: {
          disabled: this._columnOptionsFactory.areColumnsUnavailable()
        }
      },
      aggregation: {
        type: 'Select',
        title: _t('editor.widgets.widgets-form.data.operation'),
        options: [
          {val: 'sum', label: _t('editor.widgets.widgets-form.aggregation-options.sum')},
          {val: 'count', label: _t('editor.widgets.widgets-form.aggregation-options.count')},
          {val: 'avg', label: _t('editor.widgets.widgets-form.aggregation-options.avg')},
          {val: 'min', label: _t('editor.widgets.widgets-form.aggregation-options.min')},
          {val: 'max', label: _t('editor.widgets.widgets-form.aggregation-options.max')}
        ],
        editorAttrs: {
          showSearch: false
        }
      },
      aggregation_column: {
        type: 'Select',
        title: _t('editor.widgets.widgets-form.data.operation-column'),
        options: aggregatedColumnOptions,
        help: helpMsg,
        editorAttrs: {
          disabled: this._columnOptionsFactory.areColumnsUnavailable()
        }
      },
      suffix: {
        title: _t('editor.widgets.widgets-form.data.suffix'),
        type: 'Text'
      },
      prefix: {
        title: _t('editor.widgets.widgets-form.data.prefix'),
        type: 'Text'
      }
    };
  },

  canSave: function () {
    var column = this.get('column');
    var aggregationColumn = this.get('aggregation_column');

    // Columns might not be available until table is fetched
    return !!(column && aggregationColumn);
  }

});
<|endoftext|>