<commit_before>#!/usr/bin/env node

const { GitProcess } = require('dugite');
const minimist = require('minimist');
const path = require('path');
const semver = require('semver');

const { ELECTRON_DIR } = require('../../lib/utils');
const notesGenerator = require('./notes.js');

const semverify = version => version.replace(/^origin\//, '').replace('x', '0').replace(/-/g, '.');

const runGit = async (args) => {
  const response = await GitProcess.exec(args, ELECTRON_DIR);
  if (response.exitCode !== 0) {
    throw new Error(response.stderr.trim());
  }
  return response.stdout.trim();
};

const tagIsSupported = tag => tag && !tag.includes('nightly') && !tag.includes('unsupported');
const tagIsBeta = tag => tag.includes('beta');
const tagIsStable = tag => tagIsSupported(tag) && !tagIsBeta(tag);

const getTagsOf = async (point) => {
  return (await runGit(['tag', '--merged', point]))
    .split('\n')
    .map(tag => tag.trim())
    .filter(tag => semver.valid(tag))
    .sort(semver.compare);
};

const getTagsOnBranch = async (point) => {
  const masterTags = await getTagsOf('master');
  if (point === 'master') {
    return masterTags;
  }

  const masterTagsSet = new Set(masterTags);
  return (await getTagsOf(point)).filter(tag => !masterTagsSet.has(tag));
};

const getBranchOf = async (point) => {
  const branches = (await runGit(['branch', '-a', '--contains', point]))
    .split('\n')
    .map(branch => branch.trim())
    .filter(branch => !!branch);
  const current = branches.find(branch => branch.startsWith('* '));
  return current ? current.slice(2) : branches.shift();
};

const getAllBranches = async () => {
  return (await runGit(['branch', '--remote']))
    .split('\n')
    .map(branch => branch.trim())
    .filter(branch => !!branch)
    .filter(branch => branch !== 'origin/HEAD -> origin/master')
    .sort();
};

const getStabilizationBranches = async () => {
  return (await getAllBranches())
    .filter(branch => /^origin\/\d+-\d+-x$/.test(branch));
};

const getPreviousStabilizationBranch = async (current) => {
  const stabilizationBranches = (await getStabilizationBranches())
    .filter(branch => branch !== current && branch !== `origin/${current}`);

  if (!semver.valid(current)) {
    // since we don't seem to be on a stabilization branch right now,
    // pick a placeholder name that will yield the newest branch
    // as a comparison point.
    current = 'v999.999.999';
  }

  let newestMatch = null;
  for (const branch of stabilizationBranches) {
    if (semver.gte(semverify(branch), semverify(current))) {
      continue;
    }
    if (newestMatch && semver.lte(semverify(branch), semverify(newestMatch))) {
      continue;
    }
    newestMatch = branch;
  }
  return newestMatch;
};

const getPreviousPoint = async (point) => {
  const currentBranch = await getBranchOf(point);
  const currentTag = (await getTagsOf(point)).filter(tag => tagIsSupported(tag)).pop();
  const currentIsStable = tagIsStable(currentTag);

  try {
    // First see if there's an earlier tag on the same branch
    // that can serve as a reference point.
    let tags = (await getTagsOnBranch(`${point}^`)).filter(tag => tagIsSupported(tag));
    if (currentIsStable) {
      tags = tags.filter(tag => tagIsStable(tag));
    }
    if (tags.length) {
      return tags.pop();
    }
  } catch (error) {
    console.log('error', error);
  }

  // Otherwise, use the newest stable release that preceeds this branch.
  // To reach that you may have to walk past >1 branch, e.g. to get past
  // 2-1-x which never had a stable release.
  let branch = currentBranch;
  while (branch) {
    const prevBranch = await getPreviousStabilizationBranch(branch);
    const tags = (await getTagsOnBranch(prevBranch)).filter(tag => tagIsStable(tag));
    if (tags.length) {
      return tags.pop();
    }
    branch = prevBranch;
  }
};

async function getReleaseNotes (range, newVersion, explicitLinks) {
  const rangeList = range.split('..') || ['HEAD'];
  const to = rangeList.pop();
  const from = rangeList.pop() || (await getPreviousPoint(to));

  if (!newVersion) {
    newVersion = to;
  }

  console.log(`Generating release notes between ${from} and ${to} for version ${newVersion}`);
  const notes = await notesGenerator.get(from, to, newVersion);
  const ret = {
    text: notesGenerator.render(notes, explicitLinks)
  };

  if (notes.unknown.length) {
    ret.warning = `You have ${notes.unknown.length} unknown release notes. Please fix them before releasing.`;
  }

  return ret;
}

async function main () {
  const opts = minimist(process.argv.slice(2), {
    boolean: ['explicit-links', 'help'],
    string: ['version']
  });
  opts.range = opts._.shift();
  if (opts.help || !opts.range) {
    const name = path.basename(process.argv[1]);
    console.log(`
easy usage: ${name} version

full usage: ${name} [begin..]end [--version version] [--explicit-links]

 * 'begin' and 'end' are two git references -- tags, branches, etc --
   from which the release notes are generated.
 * if omitted, 'begin' defaults to the previous tag in end's branch.
 * if omitted, 'version' defaults to 'end'. Specifying a version is
   useful if you're making notes on a new version that isn't tagged yet.
 * 'explicit-links' makes every note's issue, commit, or pull an MD link

For example, these invocations are equivalent:
  ${process.argv[1]} v4.0.1
  ${process.argv[1]} v4.0.0..v4.0.1 --version v4.0.1
`);
    return 0;
  }

  const notes = await getReleaseNotes(opts.range, opts.version, opts['explicit-links']);
  console.log(notes.text);
  if (notes.warning) {
    throw new Error(notes.warning);
  }
}

if (process.mainModule === module) {
  main().catch((err) => {
    console.error('Error Occurred:', err);
    process.exit(1);
  });
}

module.exports = getReleaseNotes;
<commit_msg>fix: support 10-x-y in the release notes generator (#23709)<commit_after>#!/usr/bin/env node

const { GitProcess } = require('dugite');
const minimist = require('minimist');
const path = require('path');
const semver = require('semver');

const { ELECTRON_DIR } = require('../../lib/utils');
const notesGenerator = require('./notes.js');

const semverify = version => version.replace(/^origin\//, '').replace(/[xy]/g, '0').replace(/-/g, '.');

const runGit = async (args) => {
  const response = await GitProcess.exec(args, ELECTRON_DIR);
  if (response.exitCode !== 0) {
    throw new Error(response.stderr.trim());
  }
  return response.stdout.trim();
};

const tagIsSupported = tag => tag && !tag.includes('nightly') && !tag.includes('unsupported');
const tagIsBeta = tag => tag.includes('beta');
const tagIsStable = tag => tagIsSupported(tag) && !tagIsBeta(tag);

const getTagsOf = async (point) => {
  return (await runGit(['tag', '--merged', point]))
    .split('\n')
    .map(tag => tag.trim())
    .filter(tag => semver.valid(tag))
    .sort(semver.compare);
};

const getTagsOnBranch = async (point) => {
  const masterTags = await getTagsOf('master');
  if (point === 'master') {
    return masterTags;
  }

  const masterTagsSet = new Set(masterTags);
  return (await getTagsOf(point)).filter(tag => !masterTagsSet.has(tag));
};

const getBranchOf = async (point) => {
  const branches = (await runGit(['branch', '-a', '--contains', point]))
    .split('\n')
    .map(branch => branch.trim())
    .filter(branch => !!branch);
  const current = branches.find(branch => branch.startsWith('* '));
  return current ? current.slice(2) : branches.shift();
};

const getAllBranches = async () => {
  return (await runGit(['branch', '--remote']))
    .split('\n')
    .map(branch => branch.trim())
    .filter(branch => !!branch)
    .filter(branch => branch !== 'origin/HEAD -> origin/master')
    .sort();
};

const getStabilizationBranches = async () => {
  return (await getAllBranches())
    .filter(branch => /^origin\/\d+-\d+-x$/.test(branch) || /^origin\/\d+-x-y$/.test(branch));
};

const getPreviousStabilizationBranch = async (current) => {
  const stabilizationBranches = (await getStabilizationBranches())
    .filter(branch => branch !== current && branch !== `origin/${current}`);

  if (!semver.valid(current)) {
    // since we don't seem to be on a stabilization branch right now,
    // pick a placeholder name that will yield the newest branch
    // as a comparison point.
    current = 'v999.999.999';
  }

  let newestMatch = null;
  for (const branch of stabilizationBranches) {
    if (semver.gte(semverify(branch), semverify(current))) {
      continue;
    }
    if (newestMatch && semver.lte(semverify(branch), semverify(newestMatch))) {
      continue;
    }
    newestMatch = branch;
  }
  return newestMatch;
};

const getPreviousPoint = async (point) => {
  const currentBranch = await getBranchOf(point);
  const currentTag = (await getTagsOf(point)).filter(tag => tagIsSupported(tag)).pop();
  const currentIsStable = tagIsStable(currentTag);

  try {
    // First see if there's an earlier tag on the same branch
    // that can serve as a reference point.
    let tags = (await getTagsOnBranch(`${point}^`)).filter(tag => tagIsSupported(tag));
    if (currentIsStable) {
      tags = tags.filter(tag => tagIsStable(tag));
    }
    if (tags.length) {
      return tags.pop();
    }
  } catch (error) {
    console.log('error', error);
  }

  // Otherwise, use the newest stable release that preceeds this branch.
  // To reach that you may have to walk past >1 branch, e.g. to get past
  // 2-1-x which never had a stable release.
  let branch = currentBranch;
  while (branch) {
    const prevBranch = await getPreviousStabilizationBranch(branch);
    const tags = (await getTagsOnBranch(prevBranch)).filter(tag => tagIsStable(tag));
    if (tags.length) {
      return tags.pop();
    }
    branch = prevBranch;
  }
};

async function getReleaseNotes (range, newVersion, explicitLinks) {
  const rangeList = range.split('..') || ['HEAD'];
  const to = rangeList.pop();
  const from = rangeList.pop() || (await getPreviousPoint(to));

  if (!newVersion) {
    newVersion = to;
  }

  console.log(`Generating release notes between ${from} and ${to} for version ${newVersion}`);
  const notes = await notesGenerator.get(from, to, newVersion);
  const ret = {
    text: notesGenerator.render(notes, explicitLinks)
  };

  if (notes.unknown.length) {
    ret.warning = `You have ${notes.unknown.length} unknown release notes. Please fix them before releasing.`;
  }

  return ret;
}

async function main () {
  const opts = minimist(process.argv.slice(2), {
    boolean: ['explicit-links', 'help'],
    string: ['version']
  });
  opts.range = opts._.shift();
  if (opts.help || !opts.range) {
    const name = path.basename(process.argv[1]);
    console.log(`
easy usage: ${name} version

full usage: ${name} [begin..]end [--version version] [--explicit-links]

 * 'begin' and 'end' are two git references -- tags, branches, etc --
   from which the release notes are generated.
 * if omitted, 'begin' defaults to the previous tag in end's branch.
 * if omitted, 'version' defaults to 'end'. Specifying a version is
   useful if you're making notes on a new version that isn't tagged yet.
 * 'explicit-links' makes every note's issue, commit, or pull an MD link

For example, these invocations are equivalent:
  ${process.argv[1]} v4.0.1
  ${process.argv[1]} v4.0.0..v4.0.1 --version v4.0.1
`);
    return 0;
  }

  const notes = await getReleaseNotes(opts.range, opts.version, opts['explicit-links']);
  console.log(notes.text);
  if (notes.warning) {
    throw new Error(notes.warning);
  }
}

if (process.mainModule === module) {
  main().catch((err) => {
    console.error('Error Occurred:', err);
    process.exit(1);
  });
}

module.exports = getReleaseNotes;
<|endoftext|>


<commit_before>angular.module('yds').directive('ydsWorkbenchNew', ['$ocLazyLoad', '$timeout', '$uibModal', 'Data', 'Basket',
    function ($ocLazyLoad, $timeout, $uibModal, Data, Basket) {
        return {
            restrict: 'E',
            scope: {
                lang: '@',
                userId: '@'
            },
            templateUrl: ((typeof Drupal != 'undefined') ? Drupal.settings.basePath + Drupal.settings.yds_project.modulePath + '/' : '') + 'templates/workbench-new.html',
            link: function (scope, element) {
                scope.ydsAlert = "";
                var editorContainer = angular.element(element[0].querySelector('.highcharts-editor-container'));

                //if userId is undefined or empty, stop the execution of the directive
                if (_.isUndefined(scope.userId) || scope.userId.trim().length == 0) {
                    scope.ydsAlert = "The YDS component is not properly configured." +
                        "Please check the corresponding documentation section";
                    return false;
                }

                //check if the language attr is defined, else assign default value
                if (_.isUndefined(scope.lang) || scope.lang.trim() == "")
                    scope.lang = "en";

                // Set user ID in the Basket service so the modal can access it
                Basket.setUserId(scope.userId);

                var editorOptions = {
                    features: "import templates customize export",
                    importer: {
                        options: "plugins",
                        plugins: [
                            "BasketImport"
                        ]
                    }
                };

                // Load the required CSS & JS files for the Editor
                $ocLazyLoad.load({
                    files: [
                        "css/highcharts-editor.min.css",
                        "lib/highcharts-editor.js"
                    ],
                    cache: true
                }).then(function () {
                    // Add plugin for basket import
                    addBasketImportPlugin();

                    // Start the Highcharts Editor
                    highed.ready(function () {
                        highed.Editor(editorContainer[0], editorOptions);
                    });
                });

                /**
                 * Install the Basket Import plugin for Highcharts Editor
                 */
                var addBasketImportPlugin = function() {
                    highed.plugins.import.install('BasketImport', {
                        description: "Standard Basket Import",
                        treatAs: "csv",
                        suppressURL: true,
                        fetchAs: false,
                        request: function(url, options, fn) {
                            // Show modal and give it function to call with data
                            openModal(fn);
                        }
                    });
                };

                var openModal = function (fn) {
                    var modalInstance = $uibModal.open({
                        animation: true,
                        ariaLabelledBy: "modal-title",
                        ariaDescribedBy: "modal-body",
                        templateUrl: "templates/workbench/workbench-modal.html",
                        controller: "WorkbenchModalController"
                    });

                    // Process result of modal
                    modalInstance.result.then(function (data) {
                        // console.log(data);

                        fn(false, data.chartConfig);
                    }, function () {
                        console.log("Modal dismissed at: " + new Date());
                    });
                };
            }
        }
    }
]);
<commit_msg>Make Editor plugin add library items list before import button<commit_after>angular.module('yds').directive('ydsWorkbenchNew', ['$ocLazyLoad', '$timeout', '$compile', '$uibModal', 'Data', 'Basket',
    function ($ocLazyLoad, $timeout, $compile, $uibModal, Data, Basket) {
        return {
            restrict: 'E',
            scope: {
                lang: '@',
                userId: '@'
            },
            templateUrl: ((typeof Drupal != 'undefined') ? Drupal.settings.basePath + Drupal.settings.yds_project.modulePath + '/' : '') + 'templates/workbench-new.html',
            link: function (scope, element) {
                scope.ydsAlert = "";
                var editorContainer = angular.element(element[0].querySelector('.highcharts-editor-container'));

                //if userId is undefined or empty, stop the execution of the directive
                if (_.isUndefined(scope.userId) || scope.userId.trim().length == 0) {
                    scope.ydsAlert = "The YDS component is not properly configured." +
                        "Please check the corresponding documentation section";
                    return false;
                }

                //check if the language attr is defined, else assign default value
                if (_.isUndefined(scope.lang) || scope.lang.trim() == "")
                    scope.lang = "en";

                // Set user ID in the Basket service so the modal can access it
                Basket.setUserId(scope.userId);

                var editorOptions = {
                    features: "import templates customize export",
                    importer: {
                        options: "plugins",
                        plugins: [
                            "My Library"
                        ]
                    }
                };

                // Load the required CSS & JS files for the Editor
                $ocLazyLoad.load({
                    files: [
                        "css/highcharts-editor.min.css",
                        "lib/highcharts-editor.js"
                    ],
                    cache: true
                }).then(function () {
                    // Add plugin for basket import
                    addBasketImportPlugin();

                    // Start the Highcharts Editor
                    highed.ready(function () {
                        highed.Editor(editorContainer[0], editorOptions);

                        // Get div which contains the parameters of our plugin
                        var divResults = $(".highed-plugin-details").children(".highed-customizer-table");

                        // Replace the parameters table with a span that says "Loading"
                        $(divResults).replaceWith("Loading Library Items...");

                        // Get basket items to show in a list
                        Basket.getBasketItems(scope.userId, "dataset")
                            .then(function(response) {
                                // Get items from response and put them in scope
                                scope.libraryItems = response.items;
                                // console.log(scope.libraryItems);

                                // Compile the template which will show all the items with ng-repeat
                                var templateHtml = "
{{ item.title }}
";

                                var compiledList = $compile(templateHtml)(scope);

                                // Replace the loading span with the compiled list of items
                                $("#library_item_loading_span").replaceWith(compiledList);
                            });
                    });
                });

                /**
                 * Install the Library Import plugin for Highcharts Editor
                 */
                var addBasketImportPlugin = function() {
                    highed.plugins.import.install('My Library', {
                        description: "Select an item from the library to import to the chart",
                        treatAs: "csv",
                        suppressURL: true,
                        fetchAs: false,
                        options: {
                            val1: {
                                type: 'string',
                                label: 'String value',
                                default: 'a string 1234'
                            }
                        },
                        request: function(url, options, fn) {
                            // Show modal and give it function to call with data
                            openModal(fn);
                        }
                    });
                };

                var openModal = function (fn) {
                    var modalInstance = $uibModal.open({
                        animation: true,
                        ariaLabelledBy: "modal-title",
                        ariaDescribedBy: "modal-body",
                        templateUrl: "templates/workbench/workbench-modal.html",
                        controller: "WorkbenchModalController"
                    });

                    // Process result of modal
                    modalInstance.result.then(function (data) {
                        // console.log(data);

                        fn(false, data.chartConfig);
                    }, function () {
                        console.log("Modal dismissed at: " + new Date());
                    });
                };
            }
        }
    }
]);
<|endoftext|>


<commit_before>'use strict';
angular.module('ionic-notification', ['ionic'])

  .provider('ionicNotification', function () {

    function closeNotification(item) {
        item = $(item);
        if (item.length === 0) return;
        if (item.hasClass('notification-item-removing')) return;
        var container = $('.notifications');

        var itemHeight = item.outerHeight();
        item.css('height', itemHeight + 'px')
        transition(item, 0);
        var clientLeft = item[0].clientLeft;

        item.css('height', '0px')
        transition(item,'')
        item.addClass('notification-item-removing');

        if (item.data('f7NotificationOnClose')) item.data('f7NotificationOnClose')();

        if (container.find('.notification-item:not(.notification-item-removing)').length === 0) {
            transform(container, '');
        }

        addClass(item, 'notification-hidden')
        transitionEnd(item, function () {
            item.remove();
            if (container.find('.notification-item').length === 0) {
                container.hide();
            }
        });
    }
    function transition(element, duration) {
        if (typeof duration !== 'string') {
            duration = duration + 'ms';
        }
        for (var i = 0; i < element.length; i++) {
            var elStyle = element[i].style;
            elStyle.webkitTransitionDuration = elStyle.MsTransitionDuration = elStyle.msTransitionDuration = elStyle.MozTransitionDuration = elStyle.OTransitionDuration = elStyle.transitionDuration = duration;
        }
        return element;
    }

    function addClass(element, className) {
        if (typeof className === 'undefined') {
            return element;
        }
        var classes = className.split(' ');
        for (var i = 0; i < classes.length; i++) {
            for (var j = 0; j < element.length; j++) {
                if (typeof element[j].classList !== 'undefined') element[j].classList.add(classes[i]);
            }
        }
        return element;
    }
    function transform(element, transform) {
        for (var i = 0; i < element.length; i++) {
            var elStyle = element[i].style;
            elStyle.webkitTransform = elStyle.MsTransform = elStyle.msTransform = elStyle.MozTransform = elStyle.OTransform = elStyle.transform = transform;
        }
        return element;
    }
    function transitionEnd(element, callback) {
        var events = ['webkitTransitionEnd', 'transitionend', 'oTransitionEnd', 'MSTransitionEnd', 'msTransitionEnd'],
            i, j, dom = element;
        function fireCallBack(e) {
            /*jshint validthis:true */
            if (e.target !== element) return;
            callback.call(element, e);
            for (i = 0; i < events.length; i++) {
                dom.off(events[i], fireCallBack);
            }
        }
        if (callback) {
            for (i = 0; i < events.length; i++) {
                dom.on(events[i], fireCallBack);
            }
        }
        return element;
    }

    this.$get = ['$compile', '$document', '$interval', '$rootScope', '$timeout',
      function ($compile, $document, $interval, $rootScope, $timeout) {
        return {

          show: function (params) {
            var _tempNotificationElement;
            if (!params) return;
            if (typeof params.title        === 'undefined') params.title        = "";
            if (typeof params.subtitle     === 'undefined') params.subtitle     = "";
            if (typeof params.message      === 'undefined') params.message      = "";
            if (typeof params.media        === 'undefined') params.media        = "";
            if (typeof params.closeIcon    === 'undefined') params.closeIcon    = true;
            if (typeof params.closeOnClick === 'undefined') params.closeOnClick = true;

            if (!_tempNotificationElement) _tempNotificationElement = document.createElement('div');
            var container = $('.notifications');
            if (container.length === 0) {
                $('body').append('

');
                container = $('.notifications');
            }
            var list = container.children('ul');

            var itemHTML;
            if (params.custom) {
                itemHTML = '
' + params.custom + '
';
            }
            else {
                itemHTML = '

' +
                                (params.media ?
                                '
' +
                                    params.media +
                                '
' : '') +
                                '
' +
                                    '
' +
                                        (params.title ? '
' + params.title + '
' : '') +
                                        (params.closeIcon ? '

' : '') +
                                    '
' +
                                    (params.subtitle ? '
' + params.subtitle + '
' : '') +
                                    (params.message ? '
' + params.message + '
' : '') +
                                '
' +
                            '

';
            }
            _tempNotificationElement.innerHTML = itemHTML;

            var item = $(_tempNotificationElement).children();
            item.on('click', function (e) {
                var close = false;
                if ($(e.target).is('.close-notification') || $(e.target).parents('.close-notification').length > 0) {
                    close = true;
                }
                else {
                    if (params.onClick) params.onClick(e, item[0]);
                    if (params.closeOnClick) close = true;
                }
                if (close) closeNotification(item[0]);
            });

            list.prepend(item[0]);
            container.show();

            var itemHeight = item.outerHeight();
            item.css('marginTop', -itemHeight + 'px');

            transition(item, 0);

            var clientLeft = item[0].clientLeft;
            transition(item, '');
            item.css('marginTop', '0px');

            transform(container, 'translate3d(0, 0,0)')
            item.removeClass('notification-hidden');

            return item[0];
          },
          hideAll: function () {
            closeNotification(".notification-item")
          }
        };

      }
    ];
  });<commit_msg>replaced $ with angular element<commit_after>'use strict';
angular.module('ionic-notification', ['ionic'])

  .provider('ionicNotification', function () {

    function closeNotification(item) {
        item = angular.element(item);
        if (item.length === 0) return;
        if (item.hasClass('notification-item-removing')) return;
        // var container = $('.notifications');
        var container = angular.element($document[0].querySelector('.notifications'))

        // var itemHeight = item.outerHeight();
        var itemHeight = outerHeight(item);
        item.css('height', itemHeight + 'px')
        transition(item, 0);
        // var clientLeft = item[0].clientLeft;

        item.css('height', '0px')
        transition(item,'')
        item.addClass('notification-item-removing');

        if (item.data('f7NotificationOnClose')) item.data('f7NotificationOnClose')();

        if (container.find('.notification-item:not(.notification-item-removing)').length === 0) {
            transform(container, '');
        }

        addClass(item, 'notification-hidden')
        transitionEnd(item, function () {
            item.remove();
            if (container.find('.notification-item').length === 0) {
                hide(container);
            }
        });
    }
    function transition(element, duration) {
        if (typeof duration !== 'string') {
            duration = duration + 'ms';
        }
        for (var i = 0; i < element.length; i++) {
            var elStyle = element[i].style;
            elStyle.webkitTransitionDuration = elStyle.MsTransitionDuration = elStyle.msTransitionDuration = elStyle.MozTransitionDuration = elStyle.OTransitionDuration = elStyle.transitionDuration = duration;
        }
        return element;
    }

    function addClass(element, className) {
        if (typeof className === 'undefined') {
            return element;
        }
        var classes = className.split(' ');
        for (var i = 0; i < classes.length; i++) {
            for (var j = 0; j < element.length; j++) {
                if (typeof element[j].classList !== 'undefined') element[j].classList.add(classes[i]);
            }
        }
        return element;
    }
    function transform(element, transform) {
        for (var i = 0; i < element.length; i++) {
            var elStyle = element[i].style;
            elStyle.webkitTransform = elStyle.MsTransform = elStyle.msTransform = elStyle.MozTransform = elStyle.OTransform = elStyle.transform = transform;
        }
        return element;
    }
    function transitionEnd(element, callback) {
        var events = ['webkitTransitionEnd', 'transitionend', 'oTransitionEnd', 'MSTransitionEnd', 'msTransitionEnd'],
            i, j, dom = element;
        function fireCallBack(e) {
            /*jshint validthis:true */
            if (e.target !== element) return;
            callback.call(element, e);
            for (i = 0; i < events.length; i++) {
                dom.off(events[i], fireCallBack);
            }
        }
        if (callback) {
            for (i = 0; i < events.length; i++) {
                dom.on(events[i], fireCallBack);
            }
        }
        return element;
    }
    function show(element) {
        for (var i = 0; i < element.length; i++) {
            element[i].style.display = 'block';
        }
        return element;
    }
    function hide(element) {
        for (var i = 0; i < element.length; i++) {
            element[i].style.display = 'none';
        }
        return element;
    }

    function outerHeight(element, includeMargins) {
        if (element.length > 0) {
            if (includeMargins)
                return element[0].offsetHeight + parseFloat(element.css('margin-top')) + parseFloat(element.css('margin-bottom'));
            else
                return element[0].offsetHeight;
        }
        else return null;
    }

    this.$get = ['$compile', '$document', '$interval', '$rootScope', '$timeout',
      function ($compile, $document, $interval, $rootScope, $timeout) {
        return {

          show: function (params) {

            if (!params) return;
            if (typeof params.title        === 'undefined') params.title        = "";
            if (typeof params.subtitle     === 'undefined') params.subtitle     = "";
            if (typeof params.message      === 'undefined') params.message      = "";
            if (typeof params.media        === 'undefined') params.media        = "";
            if (typeof params.closeIcon    === 'undefined') params.closeIcon    = true;
            if (typeof params.closeOnClick === 'undefined') params.closeOnClick = true;

            var _tempNotificationElement = angular.element("

")
            // _tempNotificationElement.append("

");

            if (!_tempNotificationElement) _tempNotificationElement = document.createElement('div');
            // var container = $('.notifications');
            var container = angular.element($document[0].querySelector('.notifications'))
            if (container.length === 0) {
                var body = angular.element($document[0].querySelector('body'))
                body.append('

');
                container = angular.element($document[0].querySelector('.notifications'))
            }
            var list = container.children('ul');

            var itemHTML;
            if (params.custom) {
                itemHTML = '
' + params.custom + '
';
            }
            else {
                itemHTML = '

' +
                                (params.media ?
                                '
' +
                                    params.media +
                                '
' : '') +
                                '
' +
                                    '
' +
                                        (params.title ? '
' + params.title + '
' : '') +
                                        (params.closeIcon ? '

' : '') +
                                    '
' +
                                    (params.subtitle ? '
' + params.subtitle + '
' : '') +
                                    (params.message ? '
' + params.message + '
' : '') +
                                '
' +
                            '

';
            }
            // _tempNotificationElement.innerHTML = itemHTML;
            _tempNotificationElement.append(itemHTML);

            // var item = $(_tempNotificationElement).children();
            var item = angular.element(_tempNotificationElement).children();
            item.on('click', function (e) {
                var close = false;
                if (angular.element(e.target).is('.close-notification') || angular.element(e.target).parents('.close-notification').length > 0) {
                    close = true;
                }
                else {
                    if (params.onClick) params.onClick(e, item[0]);
                    if (params.closeOnClick) close = true;
                }
                if (close) closeNotification(item[0]);
            });

            list.prepend(item[0]);
            show(container);

            // var itemHeight = item.outerHeight();
            var itemHeight = outerHeight(item);
            item.css('marginTop', -itemHeight + 'px');

            transition(item, 0);

            // var clientLeft = item[0].clientLeft;
            transition(item, '');
            item.css('marginTop', '0px');

            transform(container, 'translate3d(0, 0,0)')
            item.removeClass('notification-hidden');

            return item[0];
          },
          hideAll: function () {
            closeNotification(".notification-item")
          }
        };

      }
    ];
  });<|endoftext|>


<commit_before>/**
 * Created by andreas on 02.05.14.
 */
goog.provide('avnav.gui.Navpage');
goog.require('avnav.gui.Handler');
goog.require('avnav.gui.Page');

/**
 *
 * @constructor
 * @extends {avnav.gui.Page}
 */
avnav.gui.Navpage=function(){
    goog.base(this,'navpage');
    /** @private */
    this.options_=null;
    /**
     * @private
     * @type {number}
     */
    this.timer=0;
    var self=this;
    $(document).on(avnav.nav.NavEvent.EVENT_TYPE, function(ev,evdata){
       self.navEvent(evdata);
    });
};
goog.inherits(avnav.gui.Navpage,avnav.gui.Page);

/**
 * get the mapholder
 * @private
 * @returns {avnav.map.MapHolder}
 */
avnav.gui.Navpage.prototype.getMap=function(){
    if (!this.gui) return null;
    return this.gui.map;
};

avnav.gui.Navpage.prototype.showPage=function(options){
    if (!this.gui) return;
    this.fillDisplayFromGps();
    if (options) this.options_=options;
    else {
        if (! this.options_){
            alert("invalid navpage call - no chart selected");
            return;
        }
    }
    //chartbase: optional url for charts
    //list: the base url
    var chartbase=this.options_.charturl;
    var list=this.options_.url;
    if (! chartbase){
        chartbase=list;
    }
    if (! list.match(/^http:/)){
        if (list.match(/^\//)){
            list=window.location.href.replace(/^([^\/:]*:\/\/[^\/]*).*/,'$1')+list;
        }
        else {
            list=window.location.href.replace(/[?].*/,'').replace(/[^\/]*$/,'')+"/"+list;
        }
    }
    var url=list+"/avnav.xml";
    var self=this;
    $.ajax({
        url:url,
        dataType: 'xml',
        cache: false,
        success: function(data){
            self.getMap().initMap('avi_map_navpage',data,chartbase);
        },
        error: function(ev){
            alert("unable to load charts "+ev.responseText);
        }
    });
    this.buttonUpdate(true);
};

avnav.gui.Navpage.prototype.buttonUpdate=function(startTimer){
    //TODO: make this more generic
    var markerLock=this.navobject.isMarkerLocked();
    this.handleToggleButton('#avb_LockMarker',markerLock);
    var gpsLock=this.gui.map.getGpsLock();
    this.handleToggleButton('#avb_LockPos',gpsLock);
    var self=this;
    if (startTimer) this.timer=window.setTimeout(function(){
        self.buttonUpdate(true),
            self.gui.properties.getProperties().buttonUpdateTime
    });
};

avnav.gui.Navpage.prototype.hidePage=function(){
    if (this.timer) window.clearTimeout(this.timer);
};
/**
 *
 */
avnav.gui.Navpage.prototype.localInit=function(){
    $('#leftBottomMarker').click({page:this},function(ev){
        var marker=ev.data.page.navobject.getRawData(avnav.nav.NavEventType.NAV).markerLatlon;
        ev.data.page.gui.map.setCenter(marker);
    });
    $('#leftBottomPosition').click({page:this},function(ev){
        var gps=ev.data.page.navobject.getRawData(avnav.nav.NavEventType.GPS);
        if (gps.valid) ev.data.page.gui.map.setCenter(gps);
    });
};

/**
 * @private
 * @param {Array.<string>} opt_names
 */
avnav.gui.Navpage.prototype.fillDisplayFromGps=function(opt_names){
    if (! this.navobject) return;
    var names=opt_names||this.navobject.getValueNames();
    for (var i=0;i< names.length;i++){
        this.getDiv().find('.avd_'+names[i]).text(this.navobject.getValue(names[i]));
    }
    if (this.navobject.getRawData(avnav.nav.NavEventType.GPS).valid){
        $('#boatPositionStatus').attr('src',this.gui.properties.getProperties().statusOkImage);
    }
    else {
        $('#boatPositionStatus').attr('src',this.gui.properties.getProperties().statusErrorImage);
    }
};

/**
 *
 * @param {avnav.nav.NavEvent} evdata
 */
avnav.gui.Navpage.prototype.navEvent=function(evdata){
    if (! this.visible) return;
    this.fillDisplayFromGps(evdata.changedNames);
};

//-------------------------- Buttons ----------------------------------------

avnav.gui.Navpage.prototype.btnZoomIn=function (button,ev){
    log("ZoomIn clicked");
    this.getMap().changeZoom(1);
};

avnav.gui.Navpage.prototype.btnZoomOut=function (button,ev){
    log("ZoomOut clicked");
    this.getMap().changeZoom(-1);
};
avnav.gui.Navpage.prototype.btnLockPos=function (button,ev){
    var nLock=! this.gui.map.getGpsLock();
    this.gui.map.setGpsLock(nLock);
    this.handleToggleButton(button,nLock);
    log("LockPos clicked");
};
avnav.gui.Navpage.prototype.btnLockMarker=function (button,ev){
    var nLock=! this.gui.map.getMarkerLock();
    this.gui.map.setMarkerLock(nLock);
    this.handleToggleButton(button,nLock);
    log("LockMarker clicked");
};
avnav.gui.Navpage.prototype.btnCancelNav=function (button,ev){
    log("CancelNav clicked");
    this.gui.showPage('mainpage');
};

/**
 * create the page instance
 */
(function(){
    //create an instance of the status page handler
    var page=new avnav.gui.Navpage();
}());

<commit_msg>correct invalid merge<commit_after>/**
 * Created by andreas on 02.05.14.
 */
goog.provide('avnav.gui.Navpage');
goog.require('avnav.gui.Handler');
goog.require('avnav.gui.Page');

/**
 *
 * @constructor
 * @extends {avnav.gui.Page}
 */
avnav.gui.Navpage=function(){
    goog.base(this,'navpage');
    /** @private */
    this.options_=null;
    /**
     * @private
     * @type {number}
     */
    this.timer=0;
    var self=this;
    $(document).on(avnav.nav.NavEvent.EVENT_TYPE, function(ev,evdata){
       self.navEvent(evdata);
    });
};
goog.inherits(avnav.gui.Navpage,avnav.gui.Page);

/**
 * get the mapholder
 * @private
 * @returns {avnav.map.MapHolder}
 */
avnav.gui.Navpage.prototype.getMap=function(){
    if (!this.gui) return null;
    return this.gui.map;
};

avnav.gui.Navpage.prototype.showPage=function(options){
    if (!this.gui) return;
    this.fillDisplayFromGps();
    if (options) this.options_=options;
    else {
        if (! this.options_){
            alert("invalid navpage call - no chart selected");
            return;
        }
    }
    //chartbase: optional url for charts
    //list: the base url
    var chartbase=this.options_.charturl;
    var list=this.options_.url;
    if (! chartbase){
        chartbase=list;
    }
    if (! list.match(/^http:/)){
        if (list.match(/^\//)){
            list=window.location.href.replace(/^([^\/:]*:\/\/[^\/]*).*/,'$1')+list;
        }
        else {
            list=window.location.href.replace(/[?].*/,'').replace(/[^\/]*$/,'')+"/"+list;
        }
    }
    var url=list+"/avnav.xml";
    var self=this;
    $.ajax({
        url:url,
        dataType: 'xml',
        cache: false,
        success: function(data){
            self.getMap().initMap('avi_map_navpage',data,chartbase);
        },
        error: function(ev){
            alert("unable to load charts "+ev.responseText);
        }
    });
    this.buttonUpdate(true);
};

avnav.gui.Navpage.prototype.buttonUpdate=function(startTimer){
    //TODO: make this more generic
    var markerLock=this.gui.map.getMarkerLock();
    this.handleToggleButton('#avb_LockMarker',markerLock);
    var gpsLock=this.gui.map.getGpsLock();
    this.handleToggleButton('#avb_LockPos',gpsLock);
    var self=this;
    if (startTimer) this.timer=window.setTimeout(function(){
        self.buttonUpdate(true),
            self.gui.properties.getProperties().buttonUpdateTime
    });
};

avnav.gui.Navpage.prototype.hidePage=function(){
    if (this.timer) window.clearTimeout(this.timer);
};
/**
 *
 */
avnav.gui.Navpage.prototype.localInit=function(){
    $('#leftBottomMarker').click({page:this},function(ev){
        var marker=ev.data.page.navobject.getRawData(avnav.nav.NavEventType.NAV).markerLatlon;
        ev.data.page.gui.map.setCenter(marker);
    });
    $('#leftBottomPosition').click({page:this},function(ev){
        var gps=ev.data.page.navobject.getRawData(avnav.nav.NavEventType.GPS);
        if (gps.valid) ev.data.page.gui.map.setCenter(gps);
    });
};

/**
 * @private
 * @param {Array.<string>} opt_names
 */
avnav.gui.Navpage.prototype.fillDisplayFromGps=function(opt_names){
    if (! this.navobject) return;
    var names=opt_names||this.navobject.getValueNames();
    for (var i=0;i< names.length;i++){
        this.getDiv().find('.avd_'+names[i]).text(this.navobject.getValue(names[i]));
    }
    if (this.navobject.getRawData(avnav.nav.NavEventType.GPS).valid){
        $('#boatPositionStatus').attr('src',this.gui.properties.getProperties().statusOkImage);
    }
    else {
        $('#boatPositionStatus').attr('src',this.gui.properties.getProperties().statusErrorImage);
    }
};

/**
 *
 * @param {avnav.nav.NavEvent} evdata
 */
avnav.gui.Navpage.prototype.navEvent=function(evdata){
    if (! this.visible) return;
    this.fillDisplayFromGps(evdata.changedNames);
};

//-------------------------- Buttons ----------------------------------------

avnav.gui.Navpage.prototype.btnZoomIn=function (button,ev){
    log("ZoomIn clicked");
    this.getMap().changeZoom(1);
};

avnav.gui.Navpage.prototype.btnZoomOut=function (button,ev){
    log("ZoomOut clicked");
    this.getMap().changeZoom(-1);
};
avnav.gui.Navpage.prototype.btnLockPos=function (button,ev){
    var nLock=! this.gui.map.getGpsLock();
    this.gui.map.setGpsLock(nLock);
    this.handleToggleButton(button,nLock);
    log("LockPos clicked");
};
avnav.gui.Navpage.prototype.btnLockMarker=function (button,ev){
    var nLock=! this.gui.map.getMarkerLock();
    this.gui.map.setMarkerLock(nLock);
    this.handleToggleButton(button,nLock);
    log("LockMarker clicked");
};
avnav.gui.Navpage.prototype.btnCancelNav=function (button,ev){
    log("CancelNav clicked");
    this.gui.showPage('mainpage');
};

/**
 * create the page instance
 */
(function(){
    //create an instance of the status page handler
    var page=new avnav.gui.Navpage();
}());

<|endoftext|>


<commit_before>// DOM-backed VNode
import { VNode } from "./vnode";

//import { q } from "./qname";

import { filter, take, compose, into } from "./transducers";

// import self!
import * as cx from "./dom";

export const __inode_type = "dom";

const wsre = /^[\t\n\r ]*$/;
const ignoreWS = x => x.nodeType != 3 || !wsre.test(x.textContent);
const l3re = /^l3-(e?)(a?)(x?)(r?)(l?)(m?)(p?)(c?)()()(d?)()()(f?)$/;
const getL3Type = (name) => {
	return parseInt(name.replace(l3re,function(){
		for(var i=1;i<arguments.length;i++){
			if(arguments[i]) return i;
		}
	})) | 0;
};

const getQName = (inode,indexInParent) => {
	var nodeType = inode.nodeType;
	var nodeName = inode.nodeName;
	if(nodeType == 1) {
		var l3Type = getL3Type(nodeName);
		//let type = l3Type | nodeType;
		var isL3 = l3Type !== 0;
		var attrs = inode.attributes;
		return isL3 ? attrs.name : nodeName;
	} else {
		return indexInParent + 1;
	}
};

const _last = x => x[x.length - 1];

// -----------------------
// Core API
// -----------------------

export function ivalue(type, value){
	return value;
}

export function vnode(inode, parent, depth, indexInParent) {
	var nodeType = inode.nodeType;
	var nodeName = inode.nodeName;
	let isElem = nodeType == 1;
	var l3Type = isElem ? getL3Type(nodeName) : 0;
	let type = l3Type | nodeType;
	var isL3 = isElem && l3Type !== 0;
	var attrs = isElem ? inode.attributes : null;
	var name, key, value;
	if(type == 1){
		// if l3, nodeType != type
		name = isL3 ? attrs.name : nodeName;
	} else if(type == 2) {
		// no-op?
		key = inode.name;
	} else if (type == 5) {
		// no-op?
	} else if (type == 6) {
		// no-op?
	} else if(type == 3 || type == 8 || type == 12){
		value = isL3 ? inode.textContent : inode.data;
	}
	// return vnode
	return new VNode(
		cx,
		inode,
		type,
		name,
		key,
		value,
		parent,
		depth,
		indexInParent
	);
}

export function emptyINode(type, name, attrs) {
	if(type == 9) {
		// XMLDocument doesn't make sense, right?
		return document.createDocumentFragment();
	} else if(type == 11) {
		return document.createDocumentFragment();
	} else {
		// TODO l3, persistent attrs?
		var elem = document.createElement(name);
		for(var k in attrs){
			elem.attributes[k] = attrs[k];
		}
	}
}

export function emptyAttrMap(init){
	return init || {};
}

/*
export function get(inode,idx,type){
	type = type || _inferType(inode);
	if(type == 1 || type == 9){
		return _get(inode.$children,idx);
	}
	return inode[idx];
}
*/
export function next(pinode, node, type){
	//var idx = node.indexInParent;
	let inode = node.inode;
	if(type == 1 || type == 9 || type == 11) {
		// ignore WS-only!
		var nxt = inode.nextSibling;
		while(nxt && !ignoreWS(nxt)){
			nxt = inode.nextSibling;
		}
		return nxt || undefined;
	}
}

export function push(inode,kv,type){
	if(type == 1 || type == 9  || type == 11){
		inode.appendChild(kv[1]);
	}
	return inode;
}

export function set(inode /*,key,val,type*/){
	// used to restore immutable parents, never modifies mutable
	return inode;
}

export function removeChild(inode,child,type){
	if(type == 1 || type == 9 || type == 11){
		// TODO removeChild et al.
		inode.removeChild(child);
	}
	return inode;
}

export function cached() {
}

export function keys(inode,type){
	if(type == 1 || type == 9 || type == 11) {
		let children = into(inode.childNodes,filter(ignoreWS),[]), len = children.length, keys = [];
		for(let i = 0; i<len; i++){
			keys[i] = getQName(children[i],i);
		}
		return keys;
	}
	// TODO l3
	//if(type == 5) return range(inode.length).toArray();
	//if(type == 6) return Object.keys(inode);
	return [];
}

export function values(inode,type){
	if(type == 1 || type == 9 || type == 11) return filter(inode.childNodes,ignoreWS);
	//if (type == 2) return [[inode.$name,inode.$value]];
	//if(type == 6) return Object.values(inode);
	//if (type == 8) return [inode.$comment];
	return inode;
}

export function finalize(inode){
	return inode;
}

export function setAttribute(inode,key,val){
	if(inode.nodeType == 1) inode.attributes[key]  = val;
	return inode;
}

export function getAttribute(inode,key){
	if(inode.nodeType == 1) return inode.attributes[key];
}

export function count(inode, type){
	if(type == 1 || type == 9 || type == 11){
		return into(inode.childNodes,filter(ignoreWS),[]).length;
	}
	// TODO l3
	return 0;
}

export function first(inode,type){
	if(type == 1 || type == 9 || type == 11){
		return into(inode.childNodes,compose(filter(ignoreWS),take(1)),[])[0];
	}
}

export function last(inode,type){
	if(type == 1 || type == 9 || type == 11) return _last(Array.from(filter(inode.childNodes,ignoreWS)));
}

export function attrEntries(inode){
	if(inode.nodeType == 1) {
		var i = [];
		try {
			for(var a of inode.attributes){
				i[a.name] = a.value;
			}
		} catch(err) {
			// whatever
		}
		return i;
	}
	return [];
}

export function modify(inode/*, node, ref, type*/){
	return inode;
}

export const getType = inode => {
	var nodeType = inode.nodeType;
	var nodeName = inode.nodeName;
	let isElem = nodeType == 1;
	return isElem ? getL3Type(nodeName) | 1 : nodeType;
};
/*
export function nodesList(node) {
	var list = [];
	var next = nextNode(node);
	do {
		list.push(next);
		next = next && nextNode(next);
	} while (next);
	return list;
}
*/
<commit_msg>cleanup<commit_after>// DOM-backed VNode
import { VNode } from "./vnode";

//import { q } from "./qname";

import { filter, take, compose, into } from "./transducers";

// import self!
import * as cx from "./dom";

export const __inode_type = "dom";

const wsre = /^[\t\n\r ]*$/;
const ignoreWS = x => x.nodeType != 3 || !wsre.test(x.textContent);
const l3re = /^l3-(e?)(a?)(x?)(r?)(l?)(m?)(p?)(c?)()()(d?)()()(f?)$/;
const getL3Type = (name) => {
	return parseInt(name.replace(l3re,function(){
		for(var i=1;i<arguments.length;i++){
			if(arguments[i]) return i;
		}
	})) | 0;
};

const getQName = (inode,indexInParent) => {
	var nodeType = inode.nodeType;
	var nodeName = inode.nodeName;
	if(nodeType == 1) {
		var l3Type = getL3Type(nodeName);
		//let type = l3Type | nodeType;
		var isL3 = l3Type !== 0;
		var attrs = inode.attributes;
		return isL3 ? attrs.name : nodeName;
	} else {
		return indexInParent + 1;
	}
};

const _last = x => x[x.length - 1];

// -----------------------
// Core API
// -----------------------

export function ivalue(type, value){
	return value;
}

export function vnode(inode, parent, depth, indexInParent) {
	var nodeType = inode.nodeType;
	var nodeName = inode.nodeName;
	let isElem = nodeType == 1;
	var l3Type = isElem ? getL3Type(nodeName) : 0;
	let type = l3Type | nodeType;
	var isL3 = isElem && l3Type !== 0;
	var attrs = isElem ? inode.attributes : null;
	var name, key, value;
	if(type == 1){
		// if l3, nodeType != type
		name = isL3 ? attrs.name : nodeName;
	} else if(type == 2) {
		// no-op?
		key = inode.name;
	} else if (type == 5) {
		// no-op?
	} else if (type == 6) {
		// no-op?
	} else if(type == 3 || type == 8 || type == 12){
		value = isL3 ? inode.textContent : inode.data;
	}
	// return vnode
	return new VNode(
		cx,
		inode,
		type,
		name,
		key,
		value,
		parent,
		depth,
		indexInParent
	);
}

export function emptyINode(type, name, attrs) {
	if(type == 9) {
		// XMLDocument doesn't make sense, right?
		return document.createDocumentFragment();
	} else if(type == 11) {
		return document.createDocumentFragment();
	} else {
		// TODO l3, persistent attrs?
		var elem = document.createElement(name);
		for(var k in attrs){
			elem.attributes[k] = attrs[k];
		}
	}
}

export function emptyAttrMap(init){
	return init || {};
}

/*
export function get(inode,idx,type){
	type = type || _inferType(inode);
	if(type == 1 || type == 9){
		return _get(inode.$children,idx);
	}
	return inode[idx];
}
*/
export function next(pinode, node, type){
	//var idx = node.indexInParent;
	let inode = node.inode;
	if(type == 1 || type == 9 || type == 11) {
		// ignore WS-only!
		var nxt = inode.nextSibling;
		while(nxt && !ignoreWS(nxt)){
			nxt = inode.nextSibling;
		}
		return nxt || undefined;
	}
}

export function push(inode,kv,type){
	if(type == 1 || type == 9  || type == 11){
		inode.appendChild(kv[1]);
	}
	return inode;
}

export function set(inode /*,key,val,type*/){
	// used to restore immutable parents, never modifies mutable
	return inode;
}

export function removeChild(inode,child,type){
	if(type == 1 || type == 9 || type == 11){
		// TODO removeChild et al.
		inode.removeChild(child);
	}
	return inode;
}

export function cached() {
}

export function keys(inode,type){
	if(type == 1 || type == 9 || type == 11) {
		let children = into(inode.childNodes,filter(ignoreWS),[]), len = children.length, keys = [];
		for(let i = 0; i<len; i++){
			keys[i] = getQName(children[i],i);
		}
		return keys;
	}
	// TODO l3
	//if(type == 5) return range(inode.length).toArray();
	//if(type == 6) return Object.keys(inode);
	return [];
}

export function values(inode,type){
	if(type == 1 || type == 9 || type == 11) return filter(inode.childNodes,ignoreWS);
	//if (type == 2) return [[inode.$name,inode.$value]];
	//if(type == 6) return Object.values(inode);
	//if (type == 8) return [inode.$comment];
	return inode;
}

export function finalize(inode){
	return inode;
}

export function setAttribute(inode,key,val){
	if(inode.nodeType == 1) inode.attributes[key]  = val;
	return inode;
}

export function getAttribute(inode,key){
	if(inode.nodeType == 1) return inode.attributes[key];
}

export function count(inode, type){
	if(type == 1 || type == 9 || type == 11){
		return into(inode.childNodes,filter(ignoreWS),[]).length;
	}
	// TODO l3
	return 0;
}

export function first(inode,type){
	if(type == 1 || type == 9 || type == 11){
		return into(inode.childNodes,compose(filter(ignoreWS),take(1)),[])[0];
	}
}

export function last(inode,type){
	if(type == 1 || type == 9 || type == 11) return _last(Array.from(filter(inode.childNodes,ignoreWS)));
}

export function attrEntries(inode){
	if(inode.nodeType == 1) {
		var i = [];
		try {
			for(var a of inode.attributes){
				i[a.name] = a.value;
			}
		} catch(err) {
			// whatever
		}
		return i;
	}
	return [];
}

export function modify(inode/*, node, ref, type*/){
	return inode;
}

export const getType = inode => {
	var nodeType = inode.nodeType;
	var nodeName = inode.nodeName;
	let isElem = nodeType == 1;
	return isElem ? getL3Type(nodeName) | 1 : nodeType;
};
<|endoftext|>


<commit_before>import R from 'ramda'
import { Subject } from 'rx'
import urlUtil from 'url'
import fetch from 'node-fetch'
import zlib from 'mz/zlib'
import encodeForm from 'form-urlencoded'
import createDebug from 'debug'

const debug = createDebug('sa:Submitter')

const DEFAULT_TIMEOUT = 10000
const MODES = {
  track: { debug: false, dryRun: false },
  debug: { debug: true, dryRun: false },
  dryRun: { debug: true, dryRun: true },
}

class Submitter extends Subject {
  static composeDebugUrl(url) {
    return urlUtil.format(R.merge(urlUtil.parse(url), { pathname: '/debug' }))
  }

  constructor({ url, gzip = true, mode = 'track', timeout = DEFAULT_TIMEOUT }) {
    super()

    if (typeof arguments[0] === 'string') { // eslint-disable-line prefer-rest-params
      url = arguments[0] // eslint-disable-line no-param-reassign, prefer-rest-params
    }

    if (url == null) {
      throw new Error('Url is not provided')
    }

    if (MODES[mode] == null) {
      throw new Error(`Unknown mode: ${mode}`)
    }

    Object.assign(this, { url, gzip, timeout }, MODES[mode])

    if (this.debug) {
      this.url = Submitter.composeDebugUrl(url)
    }

    debug('Config: %o', this)
  }

  catch(callback) {
    this.subscribe(
      R.identity,
      callback,
      R.identity
    )
  }

  async onNext(data) {
    debug('onNext(%o)', data)

    if (data == null) {
      debug('Skiped due to empty data')
      return
    }

    const messages = Array.isArray(data) ? data : [data]

    if (messages.length === 0) {
      debug('Skiped due to empty batch data')
      return
    }

    try {
      await this.submit(messages)
      debug('Submit succeeded')
      super.onNext(null)
    } catch (ex) {
      debug('Submit error: %o', ex)
      this.onError(ex)
    }
  }

  async submit(messages) {
    const payloadText = new Buffer(JSON.stringify(messages), 'utf8')
    const dataListBuffer = await (this.gzip ? zlib.gzip(payloadText) : payloadText)
    const body = encodeForm({
      data_list: dataListBuffer.toString('base64'),
      gzip: this.gzip ? 1 : 0,
    })

    const headers = {
      'User-Agent': 'SensorsAnalytics Node SDK',
      'Content-Type': 'application/x-www-form-urlencoded',
      'Dry-Run': this.dryRun ? 'true' : undefined,
    }

    debug('Post to %s', this.url)
    debug('Headers: %o', headers)
    debug('Body: %o', body)

    debug('Posting...')
    const response = await fetch(this.url, { method: 'POST', headers, body, timeout: this.timeout })
    debug('Post complete')

    if (response.ok) {
      debug('Suceeded: %d', response.status)
      return
    }

    debug('Error: %s', response.status)

    const errorMessage = await response.text()
    throw new Error(errorMessage)
  }
}

export default Submitter
<commit_msg>track submit call<commit_after>import R from 'ramda'
import { Subject } from 'rx'
import urlUtil from 'url'
import fetch from 'node-fetch'
import zlib from 'mz/zlib'
import encodeForm from 'form-urlencoded'
import createDebug from 'debug'

const debug = createDebug('sa:Submitter')

const DEFAULT_TIMEOUT = 10000
const MODES = {
  track: { debug: false, dryRun: false },
  debug: { debug: true, dryRun: false },
  dryRun: { debug: true, dryRun: true },
}

class Submitter extends Subject {
  static composeDebugUrl(url) {
    return urlUtil.format(R.merge(urlUtil.parse(url), { pathname: '/debug' }))
  }

  constructor({ url, gzip = true, mode = 'track', timeout = DEFAULT_TIMEOUT }) {
    super()

    if (typeof arguments[0] === 'string') { // eslint-disable-line prefer-rest-params
      url = arguments[0] // eslint-disable-line no-param-reassign, prefer-rest-params
    }

    if (url == null) {
      throw new Error('Url is not provided')
    }

    if (MODES[mode] == null) {
      throw new Error(`Unknown mode: ${mode}`)
    }

    Object.assign(this, { url, gzip, timeout }, MODES[mode])

    if (this.debug) {
      this.url = Submitter.composeDebugUrl(url)
    }

    debug('Config: %o', this)
  }

  catch(callback) {
    this.subscribe(
      R.identity,
      callback,
      R.identity
    )
  }

  async onNext(data) {
    debug('onNext(%o)', data)

    if (data == null) {
      debug('Skiped due to empty data')
      return
    }

    const messages = Array.isArray(data) ? data : [data]

    if (messages.length === 0) {
      debug('Skiped due to empty batch data')
      return
    }

    try {
      await this.submit(messages)
      debug('Submit succeeded')
      super.onNext(null)
    } catch (ex) {
      debug('Submit error: %o', ex)
      this.onError(ex)
    }
  }

  async submit(messages) {
    debug('submit(%j)', messages)
    const payloadText = new Buffer(JSON.stringify(messages), 'utf8')
    const dataListBuffer = await (this.gzip ? zlib.gzip(payloadText) : payloadText)
    const body = encodeForm({
      data_list: dataListBuffer.toString('base64'),
      gzip: this.gzip ? 1 : 0,
    })

    const headers = {
      'User-Agent': 'SensorsAnalytics Node SDK',
      'Content-Type': 'application/x-www-form-urlencoded',
      'Dry-Run': this.dryRun ? 'true' : undefined,
    }

    debug('Post to %s', this.url)
    debug('Headers: %o', headers)
    debug('Body: %o', body)

    debug('Posting...')
    const response = await fetch(this.url, { method: 'POST', headers, body, timeout: this.timeout })
    debug('Post complete')

    if (response.ok) {
      debug('Suceeded: %d', response.status)
      return
    }

    debug('Error: %s', response.status)

    const errorMessage = await response.text()
    throw new Error(errorMessage)
  }
}

export default Submitter
<|endoftext|>


<commit_before>import * as Viz from "viz.js";
import * as d3 from "d3-selection";
import {extractElementData, createElementWithAttributes} from "./element";
import {convertToPathData} from "./svg";
import {pathTweenPoints} from "./tweening";
import {isEdgeElement} from "./data";
import {getEdgeTitle} from "./data";

var worker = new Worker("../src/dotWorker.js");

export default function(src, callback) {

    var graphvizInstance = this;
    var engine = this._engine;
    var totalMemory = this._totalMemory;
    var keyMode = this._keyMode;
    var tweenPaths = this._tweenPaths;
    var tweenShapes = this._tweenShapes;
    var tweenPrecision = this._tweenPrecision;
    var growEnteringEdges = this._growEnteringEdges;
    var dictionary = {};
    var prevDictionary = this._dictionary || {};
    var nodeDictionary = {};
    var prevNodeDictionary = this._nodeDictionary || {};

    function extractData(element, index = 0, parentData) {

        var datum = extractElementData(element);

        datum.parent = parentData;
        datum.children = [];
        var tag = datum.tag;
        if (tag == '#text') {
            datum.text = element.text();
        } else if (tag == '#comment') {
            datum.comment = element.text();
        }
        var children = d3.selectAll(element.node().childNodes);
        if (keyMode == 'index') {
            datum.key = index;
        } else if (tag[0] != '#') {
            if (keyMode == 'id') {
                datum.key = element.attr('id');
            } else if (keyMode == 'title') {
                element.select('title');
                var title = element.select('title');
                if (!title.empty()) {
                    datum.key = element.select('title').text();
                }
            }
        }
        if (datum.key == null) {
            if (tweenShapes) {
                if (tag == 'ellipse' || tag == 'polygon') {
                    tag = 'path';
                }
            }
            datum.key = tag + '-' + index;
        }
        var id = (parentData ? parentData.id + '.' : '') + datum.key;
        datum.id = id;
        dictionary[id] = datum;
        var prevDatum = prevDictionary[id];
        if (tweenShapes && id in prevDictionary) {
            if ((prevDatum.tag == 'polygon' || prevDatum.tag == 'ellipse') && (prevDatum.tag != datum.tag || datum.tag == 'polygon')) {
                datum.alternativeOld = convertToPathData(prevDatum, datum);
                datum.alternativeNew = convertToPathData(datum, prevDatum);
            }
        }
        if (tweenPaths && prevDatum && (prevDatum.tag == 'path' || (datum.alternativeOld && datum.alternativeOld.tag == 'path'))) {
            var attribute_d = (datum.alternativeNew || datum).attributes.d;
            if (datum.alternativeOld) {
                var oldNode = createElementWithAttributes(datum.alternativeOld);
            } else {
                var oldNode = createElementWithAttributes(prevDatum);
            }
            (datum.alternativeOld || (datum.alternativeOld = {})).points = pathTweenPoints(oldNode, attribute_d, tweenPrecision);
        }

        var childTagIndexes = {};
        children.each(function () {
            if (this !== null) {
                var childTag = this.nodeName;
                if (childTag == 'ellipse' || childTag == 'polygon') {
                    childTag = 'path';
                }
                if (childTagIndexes[childTag] == null) {
                    childTagIndexes[childTag] = 0;
                }
                var childIndex = childTagIndexes[childTag]++;
                var childData = extractData(d3.select(this), childIndex, datum);
                if (childData) {
                    datum.children.push(childData);
                }
            }
        });
        return datum;
    }

    function postProcessData(datum) {

        var id = datum.id;
        var tag = datum.tag;
        var prevDatum = prevDictionary[id];
        if (growEnteringEdges && datum.parent) {
            if (datum.parent.attributes.class == 'node') {
                if (tag == 'title') {
                    var child = datum.children[0];
                    var nodeId = child.text;
                    nodeDictionary[nodeId] = datum.parent;
                }
            }
        }
        if (growEnteringEdges && !prevDatum && datum.parent) {
            if (isEdgeElement(datum)) {
                if (tag == 'path' || tag == 'polygon') {
                    if (tag == 'polygon') {
                        var path = datum.parent.children.find(function (e) {
                            return e.tag == 'path';
                        });
                        datum.totalLength = path.totalLength;
                    }
                    var title = getEdgeTitle(datum);
                    var child = title.children[0];
                    var nodeIds = child.text.split('->');
                    if (nodeIds.length != 2) {
                        nodeIds = child.text.split('--');
                    }
                    var startNodeId = nodeIds[0];
                    var startNode = nodeDictionary[startNodeId];
                    var prevStartNode = prevNodeDictionary[startNodeId];
                    if (prevStartNode) {
                        var startShape = startNode.children[3];
                        if (startShape.tag == 'g' && startShape.children[0].tag == 'a') {
                            startShape = startShape.children[0].children[1];
                        }
                        var prevStartShape = prevStartNode.children[3];
                        if (prevStartShape.tag == 'g' && prevStartShape.children[0].tag == 'a') {
                            prevStartShape = prevStartShape.children[0].children[1];
                        }
                        if (startShape.tag != 'polygon' && startShape.tag != 'ellipse') {
                            throw Error('Unexpected tag: ' + startShape.tag + '. Please file an issue at https://github.com/magjac/d3-graphviz/issues');
                        }
                        if (prevStartShape.tag != 'polygon' && prevStartShape.tag != 'ellipse') {
                            throw Error('Unexpected tag: ' + prevStartShape.tag + '. Please file an issue at https://github.com/magjac/d3-graphviz/issues');
                        }
                        datum.offset = {
                            x: prevStartShape.center.x - startShape.center.x,
                            y: prevStartShape.center.y - startShape.center.y,
                        }
                    }
                }
            }
        }
        datum.children.forEach(function (childData) {
            postProcessData(childData);
        });
        return datum;
    }

    var vizOptions = {
        format: "svg",
        engine: engine,
        totalMemory: totalMemory,
    };
    if (this._worker) {
        worker.postMessage({
            dot: src,
            options: vizOptions,
        });

        worker.onmessage = function(event) {
            switch (event.data.type) {
            case "done":
                return layoutDone.call(graphvizInstance, event.data.svg);
            }
        };
    } else {
        layoutDone.call(this, Viz(src, vizOptions));
    }

    function layoutDone(svgDoc) {
        this._dispatch.call("layoutEnd", this);

        var newDoc = d3.selection()
          .append('div')
          .attr('display', 'none');

        newDoc
            .html(svgDoc);

        var newSvg = newDoc
          .select('svg');

        var data = extractData(newSvg);
        var data = postProcessData(data);
        this._data = data;
        this._dictionary = dictionary;
        this._nodeDictionary = nodeDictionary;
        newDoc.remove();

        this._extractData = extractData;
        if (callback) {
            callback.call(this);
        }
    }

    return this;
};
<commit_msg>Start layout worker when creating graphviz instance<commit_after>import * as Viz from "viz.js";
import * as d3 from "d3-selection";
import {extractElementData, createElementWithAttributes} from "./element";
import {convertToPathData} from "./svg";
import {pathTweenPoints} from "./tweening";
import {isEdgeElement} from "./data";
import {getEdgeTitle} from "./data";

export default function(src, callback) {

    var graphvizInstance = this;
    var worker = this._worker;
    var engine = this._engine;
    var totalMemory = this._totalMemory;
    var keyMode = this._keyMode;
    var tweenPaths = this._tweenPaths;
    var tweenShapes = this._tweenShapes;
    var tweenPrecision = this._tweenPrecision;
    var growEnteringEdges = this._growEnteringEdges;
    var dictionary = {};
    var prevDictionary = this._dictionary || {};
    var nodeDictionary = {};
    var prevNodeDictionary = this._nodeDictionary || {};

    function extractData(element, index = 0, parentData) {

        var datum = extractElementData(element);

        datum.parent = parentData;
        datum.children = [];
        var tag = datum.tag;
        if (tag == '#text') {
            datum.text = element.text();
        } else if (tag == '#comment') {
            datum.comment = element.text();
        }
        var children = d3.selectAll(element.node().childNodes);
        if (keyMode == 'index') {
            datum.key = index;
        } else if (tag[0] != '#') {
            if (keyMode == 'id') {
                datum.key = element.attr('id');
            } else if (keyMode == 'title') {
                element.select('title');
                var title = element.select('title');
                if (!title.empty()) {
                    datum.key = element.select('title').text();
                }
            }
        }
        if (datum.key == null) {
            if (tweenShapes) {
                if (tag == 'ellipse' || tag == 'polygon') {
                    tag = 'path';
                }
            }
            datum.key = tag + '-' + index;
        }
        var id = (parentData ? parentData.id + '.' : '') + datum.key;
        datum.id = id;
        dictionary[id] = datum;
        var prevDatum = prevDictionary[id];
        if (tweenShapes && id in prevDictionary) {
            if ((prevDatum.tag == 'polygon' || prevDatum.tag == 'ellipse') && (prevDatum.tag != datum.tag || datum.tag == 'polygon')) {
                datum.alternativeOld = convertToPathData(prevDatum, datum);
                datum.alternativeNew = convertToPathData(datum, prevDatum);
            }
        }
        if (tweenPaths && prevDatum && (prevDatum.tag == 'path' || (datum.alternativeOld && datum.alternativeOld.tag == 'path'))) {
            var attribute_d = (datum.alternativeNew || datum).attributes.d;
            if (datum.alternativeOld) {
                var oldNode = createElementWithAttributes(datum.alternativeOld);
            } else {
                var oldNode = createElementWithAttributes(prevDatum);
            }
            (datum.alternativeOld || (datum.alternativeOld = {})).points = pathTweenPoints(oldNode, attribute_d, tweenPrecision);
        }

        var childTagIndexes = {};
        children.each(function () {
            if (this !== null) {
                var childTag = this.nodeName;
                if (childTag == 'ellipse' || childTag == 'polygon') {
                    childTag = 'path';
                }
                if (childTagIndexes[childTag] == null) {
                    childTagIndexes[childTag] = 0;
                }
                var childIndex = childTagIndexes[childTag]++;
                var childData = extractData(d3.select(this), childIndex, datum);
                if (childData) {
                    datum.children.push(childData);
                }
            }
        });
        return datum;
    }

    function postProcessData(datum) {

        var id = datum.id;
        var tag = datum.tag;
        var prevDatum = prevDictionary[id];
        if (growEnteringEdges && datum.parent) {
            if (datum.parent.attributes.class == 'node') {
                if (tag == 'title') {
                    var child = datum.children[0];
                    var nodeId = child.text;
                    nodeDictionary[nodeId] = datum.parent;
                }
            }
        }
        if (growEnteringEdges && !prevDatum && datum.parent) {
            if (isEdgeElement(datum)) {
                if (tag == 'path' || tag == 'polygon') {
                    if (tag == 'polygon') {
                        var path = datum.parent.children.find(function (e) {
                            return e.tag == 'path';
                        });
                        datum.totalLength = path.totalLength;
                    }
                    var title = getEdgeTitle(datum);
                    var child = title.children[0];
                    var nodeIds = child.text.split('->');
                    if (nodeIds.length != 2) {
                        nodeIds = child.text.split('--');
                    }
                    var startNodeId = nodeIds[0];
                    var startNode = nodeDictionary[startNodeId];
                    var prevStartNode = prevNodeDictionary[startNodeId];
                    if (prevStartNode) {
                        var startShape = startNode.children[3];
                        if (startShape.tag == 'g' && startShape.children[0].tag == 'a') {
                            startShape = startShape.children[0].children[1];
                        }
                        var prevStartShape = prevStartNode.children[3];
                        if (prevStartShape.tag == 'g' && prevStartShape.children[0].tag == 'a') {
                            prevStartShape = prevStartShape.children[0].children[1];
                        }
                        if (startShape.tag != 'polygon' && startShape.tag != 'ellipse') {
                            throw Error('Unexpected tag: ' + startShape.tag + '. Please file an issue at https://github.com/magjac/d3-graphviz/issues');
                        }
                        if (prevStartShape.tag != 'polygon' && prevStartShape.tag != 'ellipse') {
                            throw Error('Unexpected tag: ' + prevStartShape.tag + '. Please file an issue at https://github.com/magjac/d3-graphviz/issues');
                        }
                        datum.offset = {
                            x: prevStartShape.center.x - startShape.center.x,
                            y: prevStartShape.center.y - startShape.center.y,
                        }
                    }
                }
            }
        }
        datum.children.forEach(function (childData) {
            postProcessData(childData);
        });
        return datum;
    }

    var vizOptions = {
        format: "svg",
        engine: engine,
        totalMemory: totalMemory,
    };
    if (this._worker) {
        worker.postMessage({
            dot: src,
            options: vizOptions,
        });

        worker.onmessage = function(event) {
            switch (event.data.type) {
            case "done":
                return layoutDone.call(graphvizInstance, event.data.svg);
            }
        };
    } else {
        layoutDone.call(this, Viz(src, vizOptions));
    }

    function layoutDone(svgDoc) {
        this._dispatch.call("layoutEnd", this);

        var newDoc = d3.selection()
          .append('div')
          .attr('display', 'none');

        newDoc
            .html(svgDoc);

        var newSvg = newDoc
          .select('svg');

        var data = extractData(newSvg);
        var data = postProcessData(data);
        this._data = data;
        this._dictionary = dictionary;
        this._nodeDictionary = nodeDictionary;
        newDoc.remove();

        this._extractData = extractData;
        if (callback) {
            callback.call(this);
        }
    }

    return this;
};
<|endoftext|>


<commit_before>/**
 * Created by Jameson on 12/3/2016.
 */
// Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var dataCacheName = 'goRiptaLiteData-v1';
var cacheName = 'goRiptaLitePWA-final-1';
/*Files to cache for the app shell*/
var filesToCache = [
    '/',
    '/src/ride-app/ride-app.html',
    '/src/ride-app/script/parse.js',
    '/src/ride-app/script/app.js'
];

self.addEventListener('install', function(e) {
    console.log('[ServiceWorker] Install');
    e.waitUntil(
        caches.open(cacheName).then(function(cache) {
            console.log('[ServiceWorker] Caching app shell');
            return cache.addAll(filesToCache);
        })
    );
});
/*install the event listener and cache the app shell*/
self.addEventListener('install', function(e){
   console.log('[ServiceWorker] Install');
   e.waitUntil(
       caches.open(cacheName).then(function(cache) {
           console.log('[ServiceWorker] Caching app shell');
           return cache.addAll(filesToCache);
       })
   );
});

/* Activate the even listener and remove any old cache*/
self.addEventListener('activate', function(e){
    console.log('[ServiceWorker] Activate');
    e.waitUntil(
        caches.keys().then(function(keyList){
            return Promise.all(keyList.map(function(key){
                if (key !== cacheName && key !== dataCacheName){
                    console.log('[ServiceWorker] Removing old cache', key);
                    return caches.delete(key);
                }
            }));
        })
    );
    /*
     * Fixes a corner case in which the app wasn't returning the latest data.
     * The code below essentially lets you activate the service worker faster.
     */
    return self.clients.claim();
});

self.addEventListener('fetch', function(e){
    console.log('[Service Worker] Fetch', e.request.url);
    var dataUrl = 'https://riptapi.herokuapp.com/api/tripupdates/route/60';
    if (e.request.url.indexOf(dataUrl) > -1){
        e.respondWith(
            caches.open(dataCacheName).then(function(cache){
                return fetch(e.request).then(function(response){
                    cache.put(e.request.url, response.clone());
                    return response;
                });
            })
        );
    } else {
        e.respondWith(
            caches.match(e.request).then(function(response){
                return response || fetch(e.request);
            })
        );
    }
});
<commit_msg>added  working service-worker.js  **NOTE** you will need to add the call to install the service worker code to app.js, as well as the script tag calling app.js inside the ride-app html<commit_after>/**
 * Created by Jameson on 12/3/2016.
 */
// Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var dataCacheName = 'goRiptaLiteData-v1';
var cacheName = 'goRiptaLitePWA-final-1';
/*Files to cache for the app shell*/
var filesToCache = [
    '/',
    '/src/ride-app/ride-app.html',
    '/src/ride-app/script/parse.js',
    '/src/ride-app/script/app.js'
];

self.addEventListener('install', function(e) {
    console.log('[ServiceWorker] Install');
    e.waitUntil(
        caches.open(cacheName).then(function(cache) {
            console.log('[ServiceWorker] Caching app shell');
            return cache.addAll(filesToCache);
        })
    );
});
/*install the event listener and cache the app shell*/
self.addEventListener('install', function(e){
   console.log('[ServiceWorker] Install');
   e.waitUntil(
       caches.open(cacheName).then(function(cache) {
           console.log('[ServiceWorker] Caching app shell');
           return cache.addAll(filesToCache);
       })
   );
});

/* Activate the even listener and remove any old cache*/
self.addEventListener('activate', function(e){
    console.log('[ServiceWorker] Activate');
    e.waitUntil(
        caches.keys().then(function(keyList){
            return Promise.all(keyList.map(function(key){
                if (key !== cacheName && key !== dataCacheName){
                    console.log('[ServiceWorker] Removing old cache', key);
                    return caches.delete(key);
                }
            }));
        })
    );
    /*
     * Fixes a corner case in which the app wasn't returning the latest data.
     * The code below essentially lets you activate the service worker faster.
     */
    return self.clients.claim();
});

/*Fetching*/
self.addEventListener('fetch', function(e){
    console.log('[Service Worker] Fetch', e.request.url);
    var dataUrl = 'https://riptapi.herokuapp.com/api/tripupdates/route/60';
    if (e.request.url.indexOf(dataUrl) > -1){
        e.respondWith(
            caches.open(dataCacheName).then(function(cache){
                return fetch(e.request).then(function(response){
                    cache.put(e.request.url, response.clone());
                    return response;
                });
            })
        );
    } else {
        e.respondWith(
            caches.match(e.request).then(function(response){
                return response || fetch(e.request);
            })
        );
    }
});
<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import { useIntl } from 'react-intl';
import toString from 'lodash/toString';

const CellValue = ({ type, value }) => {
  const { formatDate, formatTime, formatNumber } = useIntl();
  let formattedValue = value;

  if (type === 'date') {
    formattedValue = formatDate(value, { dateStyle: 'full' });
  }

  if (type === 'datetime') {
    formattedValue = formatDate(value, { dateStyle: 'full', timeStyle: 'short' });
  }

  if (type === 'time') {
    const [hour, minute, second] = value.split(':');
    const date = new Date();
    date.setHours(hour);
    date.setMinutes(minute);
    date.setSeconds(second);

    formattedValue = formatTime(date, {
      numeric: 'auto',
      style: 'short',
    });
  }

  if (['float', 'integer', 'biginteger', 'decimal'].includes(type)) {
    formattedValue = formatNumber(value);
  }

  return toString(formattedValue);
};

CellValue.propTypes = {
  type: PropTypes.string.isRequired,
  value: PropTypes.any.isRequired,
};

export default CellValue;
<commit_msg>show all decimals for numbers of typ floats or decimals<commit_after>import PropTypes from 'prop-types';
import { useIntl } from 'react-intl';
import toString from 'lodash/toString';

const CellValue = ({ type, value }) => {
  const { formatDate, formatTime, formatNumber } = useIntl();
  let formattedValue = value;

  if (type === 'date') {
    formattedValue = formatDate(value, { dateStyle: 'full' });
  }

  if (type === 'datetime') {
    formattedValue = formatDate(value, { dateStyle: 'full', timeStyle: 'short' });
  }

  if (type === 'time') {
    const [hour, minute, second] = value.split(':');
    const date = new Date();
    date.setHours(hour);
    date.setMinutes(minute);
    date.setSeconds(second);

    formattedValue = formatTime(date, {
      numeric: 'auto',
      style: 'short',
    });
  }

  if (['float', 'decimal'].includes(type)) {
    const numberOfDecimals = getNumberOfDecimals(value);

    formattedValue = formatNumber(value, {
      minimumFractionDigits: numberOfDecimals,
      maximumFractionDigits: numberOfDecimals,
    });
  }

  if (['integer', 'biginteger'].includes(type)) {
    formattedValue = formatNumber(value, { maximumFractionDigits: 0 });
  }

  return toString(formattedValue);
};

const getNumberOfDecimals = value => {
  if (value % 1 !== 0) {
    // value has decimals
    return value.toString().split('.')[1].length;
  }

  return 0;
};

CellValue.propTypes = {
  type: PropTypes.string.isRequired,
  value: PropTypes.any.isRequired,
};

export default CellValue;
<|endoftext|>