<commit_before>// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.

import { PageConfig, URLExt } from '@jupyterlab/coreutils';

// This must be after the public path is set.
// This cannot be extracted because the public path is dynamic.
require('./imports.css');

function loadScript(url) {
  return new Promise((resolve, reject) => {
    const newScript = document.createElement('script');
    newScript.onerror = reject;
    newScript.onload = resolve;
    newScript.async = true;
    document.head.appendChild(newScript);
    newScript.src = url;
  });
}

async function loadComponent(url, scope) {
  await loadScript(url);

  // From MIT-licensed https://github.com/module-federation/module-federation-examples/blob/af043acd6be1718ee195b2511adf6011fba4233c/advanced-api/dynamic-remotes/app1/src/App.js#L6-L12
  await __webpack_init_sharing__('default');
  const container = window._JUPYTERLAB[scope];
  // Initialize the container, it may provide shared modules and may need ours
  await container.init(__webpack_share_scopes__.default);
}

async function createModule(scope, module) {
  return window._JUPYTERLAB[scope].get(module)
  .then((factory) => ({ Module: factory() }))
  .catch((error) => {
    console.warn(`Failed to create module. scope: '${scope}' module: '${module}'`);
    return { error };
  });
}

function getModuleOrThrow(data) {
  const { error = null, Module = null } = data;
  if (Module) {
    return Module;
  }
  if (error) {
    throw error;
  }
  throw new Error(`Unexpected module data: ${data}`);
}

/**
 * The main entry point for the application.
 */
async function main() {
  var JupyterLab = require('@jupyterlab/application').JupyterLab;
  var disabled = [];
  var deferred = [];
  var ignorePlugins = [];
  var register = [];

  // This is all the data needed to load and activate plugins. This should be
  // gathered by the server and put onto the initial page template.
  const extension_data = JSON.parse(
    PageConfig.getOption('dynamic_extensions')
  );

  const dynamicPluginPromises = [];
  const dynamicMimePluginPromises = [];
  const dynamicStylePromises = [];

  // Get dynamic plugins
  // TODO: deconflict these with builtins?
  extension_data.map((data) => {
    const loadComponentPromise = loadComponent(
      `${URLExt.join(PageConfig.getOption('fullLabextensionsUrl'), data.name, 'remoteEntry.js')}`,
      data.name
    );
    if (data.plugin) {
      dynamicPluginPromises.push(
        loadComponentPromise.then(() => createModule(data.name, data.plugin))
      );
    }
    if (data.mimePlugin) {
      dynamicMimePluginPromises.push(
        loadComponentPromise.then(() => createModule(data.name, data.mimePlugin))
      );
    }
    if (data.style) {
      dynamicStylePromises.push(
        loadComponentPromise.then(() => createModule(data.name, data.style))
      );
    }
    return loadComponentPromise;
  });

  // Handle the registered mime extensions.
  var mimeExtensions = [];
  var extension;
  var extMod;
  var plugins = [];
  {{#each jupyterlab_mime_extensions}}
  try {
    extMod = require('{{@key}}/{{this}}');
    extension = extMod.default;

    // Handle CommonJS exports.
    if (!extMod.hasOwnProperty('__esModule')) {
      extension = extMod;
    }

    plugins = Array.isArray(extension) ? extension : [extension];
    plugins.forEach(function(plugin) {
      if (PageConfig.Extension.isDeferred(plugin.id)) {
        deferred.push(plugin.id);
        ignorePlugins.push(plugin.id);
      }
      if (PageConfig.Extension.isDisabled(plugin.id)) {
        disabled.push(plugin.id);
        return;
      }
      mimeExtensions.push(plugin);
    });
  } catch (e) {
    console.error(e);
  }
  {{/each}}

  // Add the dyanmic mime extensions.
  const dynamicMimePlugins = await Promise.all(dynamicMimePluginPromises);
  dynamicMimePlugins.forEach(plugin => { mimeExtensions.push(getModuleOrThrow(plugin)); });

  // Handled the registered standard extensions.
  {{#each jupyterlab_extensions}}
  try {
    extMod = require('{{@key}}/{{this}}');
    extension = extMod.default;

    // Handle CommonJS exports.
    if (!extMod.hasOwnProperty('__esModule')) {
      extension = extMod;
    }

    plugins = Array.isArray(extension) ? extension : [extension];
    plugins.forEach(function(plugin) {
      if (PageConfig.Extension.isDeferred(plugin.id)) {
        deferred.push(plugin.id);
        ignorePlugins.push(plugin.id);
      }
      if (PageConfig.Extension.isDisabled(plugin.id)) {
        disabled.push(plugin.id);
        return;
      }
      register.push(plugin);
    });
  } catch (e) {
    console.error(e);
  }
  {{/each}}

  // Add the dynamic extensions.
  const dynamicPlugins = await Promise.all(dynamicPluginPromises);
  dynamicPlugins.forEach(plugin => { register.push(getModuleOrThrow(plugin)) });

  // Wait for the styles to load and check if everything loaded correctly
  (await Promise.all(dynamicStylePromises)).forEach(plugin => getModuleOrThrow(plugin));

  var lab = new JupyterLab({
    mimeExtensions: mimeExtensions,
    disabled: {
      matches: disabled,
      patterns: PageConfig.Extension.disabled
        .map(function (val) { return val.raw; })
    },
    deferred: {
      matches: deferred,
      patterns: PageConfig.Extension.deferred
        .map(function (val) { return val.raw; })
    },
  });
  register.forEach(function(item) { lab.registerPluginModule(item); });
  lab.start({ ignorePlugins: ignorePlugins });
  lab.restored.then(() => {
    console.debug('Example started!');
  });
}

window.addEventListener('load', main);
<commit_msg>Preventing uncaught promise exception when loading extensions<commit_after>// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.

import { PageConfig, URLExt } from '@jupyterlab/coreutils';

// This must be after the public path is set.
// This cannot be extracted because the public path is dynamic.
require('./imports.css');

function loadScript(url) {
  return new Promise((resolve, reject) => {
    const newScript = document.createElement('script');
    newScript.onerror = reject;
    newScript.onload = resolve;
    newScript.async = true;
    document.head.appendChild(newScript);
    newScript.src = url;
  });
}

async function loadComponent(url, scope) {
  await loadScript(url);

  // From MIT-licensed https://github.com/module-federation/module-federation-examples/blob/af043acd6be1718ee195b2511adf6011fba4233c/advanced-api/dynamic-remotes/app1/src/App.js#L6-L12
  await __webpack_init_sharing__('default');
  const container = window._JUPYTERLAB[scope];
  // Initialize the container, it may provide shared modules and may need ours
  await container.init(__webpack_share_scopes__.default);
}

async function createModule(scope, module) {
  return window._JUPYTERLAB[scope].get(module)
  .then((factory) => ({ Module: factory() }))
  .catch((error) => {
    console.warn(`Failed to create module. scope: '${scope}' module: '${module}'`);
    return { error };
  });
}

function getModuleOrThrow(data) {
  const { error = null, Module = null } = data;
  if (Module) {
    return Module;
  }
  if (error) {
    throw error;
  }
  throw new Error(`Unexpected module data: ${data}`);
}

/**
 * The main entry point for the application.
 */
async function main() {
  var JupyterLab = require('@jupyterlab/application').JupyterLab;
  var disabled = [];
  var deferred = [];
  var ignorePlugins = [];
  var register = [];

  // This is all the data needed to load and activate plugins. This should be
  // gathered by the server and put onto the initial page template.
  const extension_data = JSON.parse(
    PageConfig.getOption('dynamic_extensions')
  );

  const dynamicPluginPromises = [];
  const dynamicMimePluginPromises = [];
  const dynamicStylePromises = [];

  // Get dynamic plugins
  // TODO: deconflict these with builtins?
  const loadComponentPromises = extension_data.map((data) => {
    const loadComponentPromise = loadComponent(
      `${URLExt.join(PageConfig.getOption('fullLabextensionsUrl'), data.name, 'remoteEntry.js')}`,
      data.name
    );
    if (data.plugin) {
      dynamicPluginPromises.push(
        loadComponentPromise.then(() => createModule(data.name, data.plugin))
      );
    }
    if (data.mimePlugin) {
      dynamicMimePluginPromises.push(
        loadComponentPromise.then(() => createModule(data.name, data.mimePlugin))
      );
    }
    if (data.style) {
      dynamicStylePromises.push(
        loadComponentPromise.then(() => createModule(data.name, data.style))
      );
    }
    return loadComponentPromise;
  });
  await Promise.all(loadComponentPromises);

  // Handle the registered mime extensions.
  var mimeExtensions = [];
  var extension;
  var extMod;
  var plugins = [];
  {{#each jupyterlab_mime_extensions}}
  try {
    extMod = require('{{@key}}/{{this}}');
    extension = extMod.default;

    // Handle CommonJS exports.
    if (!extMod.hasOwnProperty('__esModule')) {
      extension = extMod;
    }

    plugins = Array.isArray(extension) ? extension : [extension];
    plugins.forEach(function(plugin) {
      if (PageConfig.Extension.isDeferred(plugin.id)) {
        deferred.push(plugin.id);
        ignorePlugins.push(plugin.id);
      }
      if (PageConfig.Extension.isDisabled(plugin.id)) {
        disabled.push(plugin.id);
        return;
      }
      mimeExtensions.push(plugin);
    });
  } catch (e) {
    console.error(e);
  }
  {{/each}}

  // Add the dyanmic mime extensions.
  const dynamicMimePlugins = await Promise.all(dynamicMimePluginPromises);
  dynamicMimePlugins.forEach(plugin => { mimeExtensions.push(getModuleOrThrow(plugin)); });

  // Handled the registered standard extensions.
  {{#each jupyterlab_extensions}}
  try {
    extMod = require('{{@key}}/{{this}}');
    extension = extMod.default;

    // Handle CommonJS exports.
    if (!extMod.hasOwnProperty('__esModule')) {
      extension = extMod;
    }

    plugins = Array.isArray(extension) ? extension : [extension];
    plugins.forEach(function(plugin) {
      if (PageConfig.Extension.isDeferred(plugin.id)) {
        deferred.push(plugin.id);
        ignorePlugins.push(plugin.id);
      }
      if (PageConfig.Extension.isDisabled(plugin.id)) {
        disabled.push(plugin.id);
        return;
      }
      register.push(plugin);
    });
  } catch (e) {
    console.error(e);
  }
  {{/each}}

  // Add the dynamic extensions.
  const dynamicPlugins = await Promise.all(dynamicPluginPromises);
  dynamicPlugins.forEach(plugin => { register.push(getModuleOrThrow(plugin)) });

  // Wait for the styles to load and check if everything loaded correctly
  (await Promise.all(dynamicStylePromises)).forEach(plugin => getModuleOrThrow(plugin));

  var lab = new JupyterLab({
    mimeExtensions: mimeExtensions,
    disabled: {
      matches: disabled,
      patterns: PageConfig.Extension.disabled
        .map(function (val) { return val.raw; })
    },
    deferred: {
      matches: deferred,
      patterns: PageConfig.Extension.deferred
        .map(function (val) { return val.raw; })
    },
  });
  register.forEach(function(item) { lab.registerPluginModule(item); });
  lab.start({ ignorePlugins: ignorePlugins });
  lab.restored.then(() => {
    console.debug('Example started!');
  });
}

window.addEventListener('load', main);
<|endoftext|>


<commit_before>/**
 * @namespace hs.pilsentraffic
 * @memberOf hs
 */
define(['angular', 'ol', 'moment', 'map', 'core', 'styles', 'angularjs-socialshare', 'permalink'],

    function(angular, ol, moment) {
        var time_layer_title = 'Intenzita dopravy v Plzni - květen 2017';

        angular.module('hs.pilsentraffic', ['hs.core', 'hs.map', 'hs.styles', '720kb.socialshare', 'hs.permalink'])

        .directive('hs.pilsentraffic.directive', function() {
            return {
                templateUrl: hsl_path + 'examples/pilsen_traffic/partials/directive.html?bust=' + gitsha
            };
        })

        .directive('hs.pilsentraffic.toolbarButtonDirective', function() {
            return {
                templateUrl: hsl_path + 'examples/pilsen_traffic/partials/toolbar_button_directive.html?bust=' + gitsha
            };
        })

        .service("hs.pilsentraffic.service", ['Core', 'hs.utils.service',
                function(Core, utils) {
                    var me = {
                        /*
                        getUnits: function() {
                            var url = null;
                            url = "http://portal.sdi4apps.eu/SensLog/DataService?Operation=GetUnits&group=gaiatrons&user=admin";
                            if (angular.isDefined(me.xhr) && me.xhr !== null) me.xhr.abort();
                            me.xhr = $.ajax({
                                url: url,
                                cache: false,
                                success: function(r) {
                                    me.unitsReceived(r);
                                    me.xhr = null
                                }
                            });
                        }*/
                    };

                    return me;
                }
            ])
            .controller('hs.pilsentraffic.controller', ['$scope', 'hs.map.service', '$http', 'Core', 'config', 'hs.pilsentraffic.service', 'hs.styles.service', '$timeout', '$rootScope', 'hs.layermanager.WMSTservice', 'hs.layermanager.service', 'Socialshare', 'hs.permalink.service_url',
                function($scope, hsmap, $http, Core, config, service, styles, $timeout, $rootScope, time_service, lm_service, socialshare, permalink_service) {
                    $scope.units = [];
                    var map = hsmap.map;

                    var roadworks_layer = config.default_layers[4];
                    var hs_roadworks_layer = null;

                    $scope.current_date = new Date();

                    $scope.day = moment();

                    $scope.$watch('day', function() {
                        $scope.current_date.setYear($scope.day.year());
                        $scope.current_date.setMonth($scope.day.month());
                        $scope.current_date.setDate($scope.day.date());
                        console.log($scope.day, $scope.current_date);
                        updateTimeLayer();
                    });

                    $scope.setCurrentTime = function(current_hour){
                        $scope.current_hour = current_hour;
                        $scope.current_date.setHours($scope.current_hour);
                        updateTimeLayer()
                    }

                    function getRoadworksLayer(){
                        hs_roadworks_layer = lm_service.getLayerByTitle(time_layer_title);
                        $scope.current_date = new Date(hs_roadworks_layer.min_time);
                        $scope.current_hour = 8;
                        var now = new Date();
                        var hours = now.getHours();
                        //if(hours<8) hours = 8;
                        //if(hours>22) hours = 22;
                        $scope.setCurrentTime(hours);
                    }

                    if(angular.isUndefined(lm_service.getLayerByTitle(time_layer_title)))
                        $rootScope.$on('layermanager.updated', function(data, layer) {
                            if(hs_roadworks_layer == null && layer.get('title') == time_layer_title){
                                getRoadworksLayer()
                            }
                        })
                    else
                        getRoadworksLayer();

                    function updateTimeLayer(){
                        hs_roadworks_layer.date_increment =  $scope.current_date.getTime() - $scope.current_date.getTimezoneOffset() * 60000;
                        time_service.setLayerTime(hs_roadworks_layer);
                    }

                    function shareSocial(provider){
                        socialshare.share({
                            'provider': provider,
                            'attrs': {
                                'socialshareText': getTitle(),
                                'socialshareUrl': permalink_service.getPermalinkUrl(),
                                'socialsharePopupHeight': 600,
                                'socialsharePopupWidth': 500
                            }
                        })
                    }

                    function printPdf(){
                        var doc = new jsPDF({orientation: 'landscape'})
                        var imgData = '';

                        hsmap.map.once('postcompose', function(event) {
                            var canvas = event.context.canvas;
                            var canvas2 = document.createElement("canvas");
                            var width = 1044,
                                height = 668;
                            canvas2.style.width = width + "px";
                            canvas2.style.height = height + "px";
                            canvas2.width = width;
                            canvas2.height = height;
                            var ctx2 = canvas2.getContext("2d");
                            ctx2.drawImage(canvas, canvas.width / 2 - height / 2, canvas.height / 2 - width / 2, width, height, 0, 0, width, height);
                            imgData = canvas2.toDataURL('image/png', 0.8);
                        }, $scope);
                        hsmap.map.renderSync();

                        doc.setFontSize(30);
                        doc.text(55, 25, getTitle());
                        doc.addImage(imgData, 'PNG', 10, 20);
                        console.log(imgData);

                        doc.save('a4.pdf')
                    }

                    function getTitle(){
                        return 'Mapa intenzity dopravy v Plzni';
                    }

                    $scope.printPdf = printPdf;
                    $scope.shareSocial = shareSocial;

                    $scope.$emit('scope_loaded', "PilsenTraffic");
                }
            ]);
    })
<commit_msg>Fill in subject and body fields for social share with email<commit_after>/**
 * @namespace hs.pilsentraffic
 * @memberOf hs
 */
define(['angular', 'ol', 'moment', 'map', 'core', 'styles', 'angularjs-socialshare', 'permalink'],

    function(angular, ol, moment) {
        var time_layer_title = 'Intenzita dopravy v Plzni - květen 2017';

        angular.module('hs.pilsentraffic', ['hs.core', 'hs.map', 'hs.styles', '720kb.socialshare', 'hs.permalink'])

        .directive('hs.pilsentraffic.directive', function() {
            return {
                templateUrl: hsl_path + 'examples/pilsen_traffic/partials/directive.html?bust=' + gitsha
            };
        })

        .directive('hs.pilsentraffic.toolbarButtonDirective', function() {
            return {
                templateUrl: hsl_path + 'examples/pilsen_traffic/partials/toolbar_button_directive.html?bust=' + gitsha
            };
        })

        .service("hs.pilsentraffic.service", ['Core', 'hs.utils.service',
                function(Core, utils) {
                    var me = {
                        /*
                        getUnits: function() {
                            var url = null;
                            url = "http://portal.sdi4apps.eu/SensLog/DataService?Operation=GetUnits&group=gaiatrons&user=admin";
                            if (angular.isDefined(me.xhr) && me.xhr !== null) me.xhr.abort();
                            me.xhr = $.ajax({
                                url: url,
                                cache: false,
                                success: function(r) {
                                    me.unitsReceived(r);
                                    me.xhr = null
                                }
                            });
                        }*/
                    };

                    return me;
                }
            ])
            .controller('hs.pilsentraffic.controller', ['$scope', 'hs.map.service', '$http', 'Core', 'config', 'hs.pilsentraffic.service', 'hs.styles.service', '$timeout', '$rootScope', 'hs.layermanager.WMSTservice', 'hs.layermanager.service', 'Socialshare', 'hs.permalink.service_url',
                function($scope, hsmap, $http, Core, config, service, styles, $timeout, $rootScope, time_service, lm_service, socialshare, permalink_service) {
                    $scope.units = [];
                    var map = hsmap.map;

                    var roadworks_layer = config.default_layers[4];
                    var hs_roadworks_layer = null;

                    $scope.current_date = new Date();

                    $scope.day = moment();

                    $scope.$watch('day', function() {
                        $scope.current_date.setYear($scope.day.year());
                        $scope.current_date.setMonth($scope.day.month());
                        $scope.current_date.setDate($scope.day.date());
                        console.log($scope.day, $scope.current_date);
                        updateTimeLayer();
                    });

                    $scope.setCurrentTime = function(current_hour){
                        $scope.current_hour = current_hour;
                        $scope.current_date.setHours($scope.current_hour);
                        updateTimeLayer()
                    }

                    function getRoadworksLayer(){
                        hs_roadworks_layer = lm_service.getLayerByTitle(time_layer_title);
                        $scope.current_date = new Date(hs_roadworks_layer.min_time);
                        $scope.current_hour = 8;
                        var now = new Date();
                        var hours = now.getHours();
                        //if(hours<8) hours = 8;
                        //if(hours>22) hours = 22;
                        $scope.setCurrentTime(hours);
                    }

                    if(angular.isUndefined(lm_service.getLayerByTitle(time_layer_title)))
                        $rootScope.$on('layermanager.updated', function(data, layer) {
                            if(hs_roadworks_layer == null && layer.get('title') == time_layer_title){
                                getRoadworksLayer()
                            }
                        })
                    else
                        getRoadworksLayer();

                    function updateTimeLayer(){
                        hs_roadworks_layer.date_increment =  $scope.current_date.getTime() - $scope.current_date.getTimezoneOffset() * 60000;
                        time_service.setLayerTime(hs_roadworks_layer);
                    }

                    function shareSocial(provider){
                        var url = permalink_service.getPermalinkUrl();
                        socialshare.share({
                            'provider': provider,
                            'attrs': {
                                'socialshareText': getTitle(),
                                'socialshareSubject': getTitle(),
                                'socialshareBody': getDescription(url),
                                'socialshareUrl': url,
                                'socialsharePopupHeight': 600,
                                'socialsharePopupWidth': 500
                            }
                        })
                    }

                    function printPdf(){
                        var doc = new jsPDF({orientation: 'landscape'})
                        var imgData = '';

                        hsmap.map.once('postcompose', function(event) {
                            var canvas = event.context.canvas;
                            var canvas2 = document.createElement("canvas");
                            var width = 1044,
                                height = 668;
                            canvas2.style.width = width + "px";
                            canvas2.style.height = height + "px";
                            canvas2.width = width;
                            canvas2.height = height;
                            var ctx2 = canvas2.getContext("2d");
                            ctx2.drawImage(canvas, canvas.width / 2 - height / 2, canvas.height / 2 - width / 2, width, height, 0, 0, width, height);
                            imgData = canvas2.toDataURL('image/png', 0.8);
                        }, $scope);
                        hsmap.map.renderSync();

                        doc.setFontSize(30);
                        doc.text(55, 25, getTitle());
                        doc.addImage(imgData, 'PNG', 10, 20);
                        doc.save('a4.pdf')
                    }

                    function getTitle(){
                        return 'Mapa intenzity dopravy v Plzni';
                    }

                    function getDescription(url){
                        return 'Předpokládaná dopravní situace v Plzni dne xx.xx.2017 v 10:00.%0D%0A' + encodeURIComponent(url);
                    }

                    $scope.printPdf = printPdf;
                    $scope.shareSocial = shareSocial;

                    $scope.$emit('scope_loaded', "PilsenTraffic");
                }
            ]);
    })
<|endoftext|>


<commit_before>(function(){
  // init
	document.getElementById("dashboard-items").innerHTML = '
' +
'' + '
' + '
' +
'
' + "Blurbing" + '
' + '
' + "Bio" + '
' +
'' +
'' +
'
' + '
' +
'
' + "Sprinting" + '
' + '
' + "Show critical metadata for each plan" + '
' +
'' +
'
' + '
';
})();
<commit_msg>Delete dashboard-items.js<commit_after><|endoftext|>


<commit_before>'use strict'

const browser = require('webextension-polyfill')
const external = require('./external')
const embedded = require('./embedded')

let client

async function initIpfsClient (opts) {
  await destroyIpfsClient()

  if (opts.ipfsNodeType === 'embedded') {
    client = embedded
  } else {
    client = external
  }

  const instance = await client.init(opts)
  easeApiChanges(instance)
  _reloadIpfsClientDependents() // async (API is present)
  return instance
}

async function destroyIpfsClient () {
  if (client && client.destroy) {
    try {
      await client.destroy()
    } finally {
      client = null
      await _reloadIpfsClientDependents() // sync (API stopped working)
    }
  }
}

function _isWebuiTab (url) {
  const bundled = !url.startsWith('http') && url.includes('/webui/index.html#/')
  const ipns = url.includes('/webui.ipfs.io/#/')
  return bundled || ipns
}

async function _reloadIpfsClientDependents () {
  if (browser.tabs && browser.tabs.query) {
    const tabs = await browser.tabs.query({})
    if (tabs) {
      tabs.forEach((tab) => {
        // detect bundled webui in any of open tabs
        if (_isWebuiTab(tab.url)) {
          browser.tabs.reload(tab.id)
          console.log('[ipfs-companion] reloading bundled webui')
        }
      })
    }
  }
}

// Ensures Companion can be used with backends that provide old and new versions
// of the same API moved into different namespace
function easeApiChanges (ipfs) {
  if (!ipfs) return
  // Handle the move of regular files api to top level
  // https://github.com/ipfs/interface-ipfs-core/pull/378
  // https://github.com/ipfs/js-ipfs/releases/tag/v0.34.0-pre.0
  const movedToTop = ['add', 'addPullStream', 'addReadableStream', 'cat', 'catPullStream', 'catReadableStream', 'get', 'getPullStream', 'getReadableStream']
  movedToTop.forEach(cmd => {
    if (typeof ipfs[cmd] !== 'function' && ipfs.files && ipfs.files[cmd] === 'function') {
      ipfs[cmd] = ipfs.files[cmd]
    }
  })
}

exports.initIpfsClient = initIpfsClient
exports.destroyIpfsClient = destroyIpfsClient
<commit_msg>fix: support ipfs.add and ipfs.files.add<commit_after>'use strict'

const browser = require('webextension-polyfill')
const external = require('./external')
const embedded = require('./embedded')

let client

async function initIpfsClient (opts) {
  await destroyIpfsClient()

  if (opts.ipfsNodeType === 'embedded') {
    client = embedded
  } else {
    client = external
  }

  const instance = await client.init(opts)
  easeApiChanges(instance)
  _reloadIpfsClientDependents() // async (API is present)
  return instance
}

async function destroyIpfsClient () {
  if (client && client.destroy) {
    try {
      await client.destroy()
    } finally {
      client = null
      await _reloadIpfsClientDependents() // sync (API stopped working)
    }
  }
}

function _isWebuiTab (url) {
  const bundled = !url.startsWith('http') && url.includes('/webui/index.html#/')
  const ipns = url.includes('/webui.ipfs.io/#/')
  return bundled || ipns
}

async function _reloadIpfsClientDependents () {
  if (browser.tabs && browser.tabs.query) {
    const tabs = await browser.tabs.query({})
    if (tabs) {
      tabs.forEach((tab) => {
        // detect bundled webui in any of open tabs
        if (_isWebuiTab(tab.url)) {
          browser.tabs.reload(tab.id)
          console.log('[ipfs-companion] reloading bundled webui')
        }
      })
    }
  }
}

// Ensures Companion can be used with backends that provide old and new versions
// of the same API moved into different namespace
function easeApiChanges (ipfs) {
  if (!ipfs) return
  // Handle the move of regular files api to top level
  // https://github.com/ipfs/interface-ipfs-core/pull/378
  // https://github.com/ipfs/js-ipfs/releases/tag/v0.34.0-pre.0
  const movedToTop = ['add', 'addPullStream', 'addReadableStream', 'cat', 'catPullStream', 'catReadableStream', 'get', 'getPullStream', 'getReadableStream']
  movedToTop.forEach(cmd => {
    if (typeof ipfs[cmd] !== 'function' && ipfs.files && typeof ipfs.files[cmd] === 'function') {
      ipfs[cmd] = ipfs.files[cmd]
      console.log(`[ipfs-companion] fixed missing ipfs.${cmd}: added an alias for ipfs.files.${cmd}`)
    }
  })
}

exports.initIpfsClient = initIpfsClient
exports.destroyIpfsClient = destroyIpfsClient
<|endoftext|>


<commit_before>import Ember from 'ember';

var typeOf = Ember.typeOf;
var eA = Ember.A;
var set = Ember.set;
var get = Ember.get;
var on = Ember.on;
var computed = Ember.computed;

/**
 * @typedef {{
 *  label: string,
 *  value: string,
 *  isSelected: boolean,
 *  isDisabled: boolean,
 *  order: number
 * }} dropDownElement
 */
/**
 * Template for list-option
 * @type {dropDownElement}
 */
var dropDownElement = Ember.Object.extend({
  label: '',
  value: '',
  isSelected: false,
  isDisabled: false,
  order: 0
});

export default Ember.Component.extend({

  /**
   * Counter used to determine order of options selection (order-field in the dropDownElement)
   * Greater number - later selection
   * @type {number}
   */
  orderCounter: 1,

  /**
   * Maximum length of the displayVal
   * If its length is greater, it will cut to current value and ' ...' will be added to the end
   * @type {number}
   */
  maxDisplayValLength: 25,

  /**
   * options where isSelected is true
   * @type {dropDownElement[]}
   */
  val: eA([]),

  /**
   * List of options
   * @type {dropDownElement[]}
   */
  options: eA([]),

  /**
   * @type {{value: string, label: string, selected: boolean}}
   */
  attributes: eA([]),

  /**
   * @type {string}
   */
  identifier: '',

  emptySelectionMessage: 'Nothing selected',

  /**
   * String with selected options labels separated with ', '
   * If result string is too long (@see maxDisplayValLength) it's cut and ' ...' is added to the end
   * If nothing is selected, default placeholder is used
   * @type {string}
   */
  displayVal: computed('val.[]', function () {
    var v = get(this, 'val').sortBy('order').mapBy('label');
    if (!v.length) {
      return get(this, 'emptySelectionMessage');
    }
    var output = v.join(', ');
    var maxDisplayValLength = get(this, 'maxDisplayValLength');
    return output.length > maxDisplayValLength - 3 ? output.substring(0, maxDisplayValLength - 3) + ' ...' : output;
  }),

  /**
   * Maximum number of options allowed to select (no limits by default)
   * @type {number}
   */
  allowedToSelect: Number.POSITIVE_INFINITY,

  onInsert: on('willInsertElement', function () {
    this.calculateOptions();
    this.addObserver('options.@each.isSelected', this, this.calculateVal);
    this.addObserver('options.@each.isSelected', this, this.checkSelectedItemsCount);
    this.calculateVal();
    this.checkSelectedItemsCount();
  }),

  onDestroy: on('willDestroyElement', function() {
    this.removeObserver('options.@each.isSelected', this, this.calculateVal);
    this.removeObserver('options.@each.isSelected', this, this.checkSelectedItemsCount);
  }),

  /**
   * Get list of options basing on attributes
   * dropDownElement is used
   * @method calculateOptions
   */
  calculateOptions () {
    set(this, 'options', eA(get(this, 'attributes').map(entryValue => {
      return dropDownElement.create({
        value: entryValue.value,
        label: entryValue.label || entryValue.value,
        isSelected: !!entryValue.selected
      });
    })));
  },

  /**
   * Get value basing on selected options sorted by order-field
   * Triggers on each option select/deselect
   * @method calculateVal
   */
  calculateVal () {
    var filtered = get(this, 'options').filterBy('isSelected');
    set(this, 'val', eA(filtered).sortBy('order'));
  },

  /**
   * If user already selected maximum of allowed options, disable other options
   * If user selected less than minimum of needed options, mark value as invalid
   * If user deselect some option, all disabled options become enabled
   * Triggers on each option select/deselect
   * @method checkSelectedItemsCount
   */
  checkSelectedItemsCount () {
    var allowedToSelect = get(this, 'allowedToSelect');
    var currentlySelected = get(this, 'options').filterBy('isSelected').length;
    var selectionDisabled = allowedToSelect <= currentlySelected;
    eA(get(this, 'options').filterBy('isSelected', false)).setEach('isDisabled', selectionDisabled);
  },

  action: 'checkboxesListUpdate',

  actions: {

    /**
     * Option click-handler
     * toggle selection for current option and increment orderCounter for proper options selection order
     * @param {object} option
     */
    toggleOption (option) {
      if (get(option, 'isDisabled')) {
        return;
      }
      var orderCounter = get(this, 'orderCounter');
      var o = get(this, 'options').findBy('value', get(option, 'value'));
      set(o, 'order', orderCounter);
      o.toggleProperty('isSelected');
      this.incrementProperty('orderCounter');
      this.sendAction('action', get(this, 'identifier'), get(this, 'val'));
    }
  }
});<commit_msg>Remove unsued function<commit_after>import Ember from 'ember';

var eA = Ember.A;
var set = Ember.set;
var get = Ember.get;
var on = Ember.on;
var computed = Ember.computed;

/**
 * @typedef {{
 *  label: string,
 *  value: string,
 *  isSelected: boolean,
 *  isDisabled: boolean,
 *  order: number
 * }} dropDownElement
 */
/**
 * Template for list-option
 * @type {dropDownElement}
 */
var dropDownElement = Ember.Object.extend({
  label: '',
  value: '',
  isSelected: false,
  isDisabled: false,
  order: 0
});

export default Ember.Component.extend({

  /**
   * Counter used to determine order of options selection (order-field in the dropDownElement)
   * Greater number - later selection
   * @type {number}
   */
  orderCounter: 1,

  /**
   * Maximum length of the displayVal
   * If its length is greater, it will cut to current value and ' ...' will be added to the end
   * @type {number}
   */
  maxDisplayValLength: 25,

  /**
   * options where isSelected is true
   * @type {dropDownElement[]}
   */
  val: eA([]),

  /**
   * List of options
   * @type {dropDownElement[]}
   */
  options: eA([]),

  /**
   * @type {{value: string, label: string, selected: boolean}}
   */
  attributes: eA([]),

  /**
   * @type {string}
   */
  identifier: '',

  emptySelectionMessage: 'Nothing selected',

  /**
   * String with selected options labels separated with ', '
   * If result string is too long (@see maxDisplayValLength) it's cut and ' ...' is added to the end
   * If nothing is selected, default placeholder is used
   * @type {string}
   */
  displayVal: computed('val.[]', function () {
    var v = get(this, 'val').sortBy('order').mapBy('label');
    if (!v.length) {
      return get(this, 'emptySelectionMessage');
    }
    var output = v.join(', ');
    var maxDisplayValLength = get(this, 'maxDisplayValLength');
    return output.length > maxDisplayValLength - 3 ? output.substring(0, maxDisplayValLength - 3) + ' ...' : output;
  }),

  /**
   * Maximum number of options allowed to select (no limits by default)
   * @type {number}
   */
  allowedToSelect: Number.POSITIVE_INFINITY,

  onInsert: on('willInsertElement', function () {
    this.calculateOptions();
    this.addObserver('options.@each.isSelected', this, this.calculateVal);
    this.addObserver('options.@each.isSelected', this, this.checkSelectedItemsCount);
    this.calculateVal();
    this.checkSelectedItemsCount();
  }),

  onDestroy: on('willDestroyElement', function() {
    this.removeObserver('options.@each.isSelected', this, this.calculateVal);
    this.removeObserver('options.@each.isSelected', this, this.checkSelectedItemsCount);
  }),

  /**
   * Get list of options basing on attributes
   * dropDownElement is used
   * @method calculateOptions
   */
  calculateOptions () {
    set(this, 'options', eA(get(this, 'attributes').map(entryValue => {
      return dropDownElement.create({
        value: entryValue.value,
        label: entryValue.label || entryValue.value,
        isSelected: !!entryValue.selected
      });
    })));
  },

  /**
   * Get value basing on selected options sorted by order-field
   * Triggers on each option select/deselect
   * @method calculateVal
   */
  calculateVal () {
    var filtered = get(this, 'options').filterBy('isSelected');
    set(this, 'val', eA(filtered).sortBy('order'));
  },

  /**
   * If user already selected maximum of allowed options, disable other options
   * If user selected less than minimum of needed options, mark value as invalid
   * If user deselect some option, all disabled options become enabled
   * Triggers on each option select/deselect
   * @method checkSelectedItemsCount
   */
  checkSelectedItemsCount () {
    var allowedToSelect = get(this, 'allowedToSelect');
    var currentlySelected = get(this, 'options').filterBy('isSelected').length;
    var selectionDisabled = allowedToSelect <= currentlySelected;
    eA(get(this, 'options').filterBy('isSelected', false)).setEach('isDisabled', selectionDisabled);
  },

  action: 'checkboxesListUpdate',

  actions: {

    /**
     * Option click-handler
     * toggle selection for current option and increment orderCounter for proper options selection order
     * @param {object} option
     */
    toggleOption (option) {
      if (get(option, 'isDisabled')) {
        return;
      }
      var orderCounter = get(this, 'orderCounter');
      var o = get(this, 'options').findBy('value', get(option, 'value'));
      set(o, 'order', orderCounter);
      o.toggleProperty('isSelected');
      this.incrementProperty('orderCounter');
      this.sendAction('action', get(this, 'identifier'), get(this, 'val'));
    }
  }
});<|endoftext|>


<commit_before>import Ember from 'ember';
import ComponentVaidation from 'ember-validation/mixins/component';

const { RSVP, get } = Ember;

/**
 * @module
 * @augments ember/Component
 * @augments ember-validation/mixins/component
 */
export default Ember.Component.extend(ComponentVaidation, {

  validationScheme: {},

  layoutName: "components/form-validation",

  /** @type {String} */
  tagName: 'form',

  /** @type {Boolean} */
  isValidating: false,

  /** @type {Boolean} */
  isSubmitting: false,

  /** @type {Boolean} */
  isSubmitted: false,

  /** @type {Boolean} */
  submitError: '',

  /**
   * Focus first invalid input after validaton failed
   * @type {Boolean}
   * @default false
   */
  focusFirstInvalid: false,

  /**
   * Call check() method on didInsertElement
   * @type {Boolean}
   * @default false
   */
  checkFirst: false,

  /**
   * Validate all form on submit
   *
   * @function
   * @param {jQuery.Event} event
   */
  submit(event) {

    event.preventDefault();

    this.setProperties({
      submitError: '',
      isSubmitted: false,
      isValidating: true
    });

    this.validationStart()
      .then(() => {
        this.validate().then(this.validationPassed.bind(this), this.validationFailed.bind(this));
      })
      .finally(this.validationEnd.bind(this));

  },

  /**
   * Called before validation starts.
   * If returned promise rejected - validation will not starts
   *
   * @function
   * @returns {Ember/RSVP.resolve}
   */
  validationStart: () => RSVP.resolve(),

  /**
   * Called after validation was passed
   * Call given `action`
   *
   * @function
   */
  validationPassed() {
    this.hideAllErrors();
    this.submitStart();
    this._invokeAction();
  },

  /**
   * Called after validation was failed
   *
   * @function
   */
  validationFailed(/*errors*/) {
    this.showAllErrors();
    Ember.run.scheduleOnce('afterRender', this, () => {
      if (this.get('focusFirstInvalid')) {
        let mediator = this.get('mediators').find((mediator) => {
          let name = get(mediator, 'errorsName');
          if (name && this.get('errors.' + name + '.length')) {
            return true;
          }
        });

        if (mediator) {
          const view = get(mediator, 'view');

          if (typeof view.focus === 'function') {
            view.focus();
          } else {
            if (/INPUT|TEXTAREA|SELECT/.test(view.element.nodeName)) {
              view.element.focus();
            } else {
              view.$('input,textarea,select').filter(':first').focus();
            }
          }

          this.set('visibleErrors.' + get(mediator, 'errorsName'), true);
        }

      }
    });
  },

  /**
   * Called at the end of validation
   *
   * @function
   */
  validationEnd() {
    this.set('isValidating', false);
  },

  /**
   * Invokes given `action`. Method can be overridden by a child to currying
   * function's arguments.
   *
   * @function
   */
  _invokeAction() {
    const args = [this.submitDone.bind(this), this.submitFailed.bind(this), ...arguments];
    Ember.assert(`You must provide an 'action' action to 'form-validation'`, typeof this.attrs.action === 'function');
    this.attrs.action(...args);
  },

  submitStart() {
    this.set('isSubmitting', true);
  },

  /**
   * Called when submitting done
   *
   * @function
   */
  submitDone() {
    this.set('isSubmitted', true);
    this.submitEnd();
  },

  /**
   * Called when submitting failed
   *
   * @function
   */
  submitFailed(error) {
    this.set('submitError', error);
    this.submitEnd();
  },

  /**
   * Called after submitting complete
   *
   * @function
   */
  submitEnd() {
    this.set('isSubmitting', false);
  },

  /**
   * Make all errors visible
   *
   * @function
   */
  showAllErrors() {
    this.get('mediators').forEach((mediator) => {
      let name = get(mediator, 'errorsName');
      name && this.set('visibleErrors.' + name, true);
    });
  },

  /**
   * Make all errors hidden
   *
   * @function
   */
  hideAllErrors() {
    Object.keys(this.get('visibleErrors')).forEach((errorsName) => {
      this.set('visibleErrors.' + errorsName, true);
    });
  },

  didInsertElement() {
    this._super(...arguments);

    this.$().on('input', () => { this.get('submitError') && Ember.run.later(this, () => { this.set('submitError', ''); }, 300); });

    this.$().on('change keyup', 'input, textarea, select', () => { this.set('isSubmitted', false); });

    if (this.get('checkFirst')) {
      this.check();
    }
  },

  actions: {
    reset() {
      typeof this.attrs.reset === 'function' && this.attrs.reset();
      return true;
    }
  }

});
<commit_msg>Added TODO notice<commit_after>import Ember from 'ember';
import ComponentVaidation from 'ember-validation/mixins/component';

const { RSVP, get } = Ember;

/**
 * @module
 * @augments ember/Component
 * @augments ember-validation/mixins/component
 */
export default Ember.Component.extend(ComponentVaidation, {

  validationScheme: {},

  /**
   * @type {String}
   * @todo: This property with direct path should be removed, but when you try
   *        do it validation somehow become broken. For temporary solution in
   *        components that extended from this component should set this
   *        property to `null` like so: `layoutName: null`.
   */
  layoutName: "components/form-validation",

  /** @type {String} */
  tagName: 'form',

  /** @type {Boolean} */
  isValidating: false,

  /** @type {Boolean} */
  isSubmitting: false,

  /** @type {Boolean} */
  isSubmitted: false,

  /** @type {Boolean} */
  submitError: '',

  /**
   * Focus first invalid input after validaton failed
   * @type {Boolean}
   * @default false
   */
  focusFirstInvalid: false,

  /**
   * Call check() method on didInsertElement
   * @type {Boolean}
   * @default false
   */
  checkFirst: false,

  /**
   * Validate all form on submit
   *
   * @function
   * @param {jQuery.Event} event
   */
  submit(event) {

    event.preventDefault();

    this.setProperties({
      submitError: '',
      isSubmitted: false,
      isValidating: true
    });

    this.validationStart()
      .then(() => {
        this.validate().then(this.validationPassed.bind(this), this.validationFailed.bind(this));
      })
      .finally(this.validationEnd.bind(this));

  },

  /**
   * Called before validation starts.
   * If returned promise rejected - validation will not starts
   *
   * @function
   * @returns {Ember/RSVP.resolve}
   */
  validationStart: () => RSVP.resolve(),

  /**
   * Called after validation was passed
   * Call given `action`
   *
   * @function
   */
  validationPassed() {
    this.hideAllErrors();
    this.submitStart();
    this._invokeAction();
  },

  /**
   * Called after validation was failed
   *
   * @function
   */
  validationFailed(/*errors*/) {
    this.showAllErrors();
    Ember.run.scheduleOnce('afterRender', this, () => {
      if (this.get('focusFirstInvalid')) {
        let mediator = this.get('mediators').find((mediator) => {
          let name = get(mediator, 'errorsName');
          if (name && this.get('errors.' + name + '.length')) {
            return true;
          }
        });

        if (mediator) {
          const view = get(mediator, 'view');

          if (typeof view.focus === 'function') {
            view.focus();
          } else {
            if (/INPUT|TEXTAREA|SELECT/.test(view.element.nodeName)) {
              view.element.focus();
            } else {
              view.$('input,textarea,select').filter(':first').focus();
            }
          }

          this.set('visibleErrors.' + get(mediator, 'errorsName'), true);
        }

      }
    });
  },

  /**
   * Called at the end of validation
   *
   * @function
   */
  validationEnd() {
    this.set('isValidating', false);
  },

  /**
   * Invokes given `action`. Method can be overridden by a child to currying
   * function's arguments.
   *
   * @function
   */
  _invokeAction() {
    const args = [this.submitDone.bind(this), this.submitFailed.bind(this), ...arguments];
    Ember.assert(`You must provide an 'action' action to 'form-validation'`, typeof this.attrs.action === 'function');
    this.attrs.action(...args);
  },

  submitStart() {
    this.set('isSubmitting', true);
  },

  /**
   * Called when submitting done
   *
   * @function
   */
  submitDone() {
    this.set('isSubmitted', true);
    this.submitEnd();
  },

  /**
   * Called when submitting failed
   *
   * @function
   */
  submitFailed(error) {
    this.set('submitError', error);
    this.submitEnd();
  },

  /**
   * Called after submitting complete
   *
   * @function
   */
  submitEnd() {
    this.set('isSubmitting', false);
  },

  /**
   * Make all errors visible
   *
   * @function
   */
  showAllErrors() {
    this.get('mediators').forEach((mediator) => {
      let name = get(mediator, 'errorsName');
      name && this.set('visibleErrors.' + name, true);
    });
  },

  /**
   * Make all errors hidden
   *
   * @function
   */
  hideAllErrors() {
    Object.keys(this.get('visibleErrors')).forEach((errorsName) => {
      this.set('visibleErrors.' + errorsName, true);
    });
  },

  didInsertElement() {
    this._super(...arguments);

    this.$().on('input', () => { this.get('submitError') && Ember.run.later(this, () => { this.set('submitError', ''); }, 300); });

    this.$().on('change keyup', 'input, textarea, select', () => { this.set('isSubmitted', false); });

    if (this.get('checkFirst')) {
      this.check();
    }
  },

  actions: {
    reset() {
      typeof this.attrs.reset === 'function' && this.attrs.reset();
      return true;
    }
  }

});
<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from '../templates/components/sl-modal-header';

/**
 * @module
 * @augments ember/Component
 */
export default Ember.Component.extend({

    // -------------------------------------------------------------------------
    // Dependencies

    // -------------------------------------------------------------------------
    // Attributes

    /** @type {Object} */
    layout: layout,

    /** @type {String} */
    tagName: 'div',

    // -------------------------------------------------------------------------
    // Actions

    // -------------------------------------------------------------------------
    // Events

    // -------------------------------------------------------------------------
    // Properties

    // -------------------------------------------------------------------------
    // Observers

    // -------------------------------------------------------------------------
    // Methods

    /**
     * ariaLabelledBy computed property, the value
     * of this property will be set as
     * the value to the aria-labelledby attribute
     *
     * @function
     * @returns {String}
     */
    ariaLabelledBy: Ember.computed(
        'elementId',
        function() {
            return 'modalTitle' + this.get( 'elementId' );
        }
    )
});
<commit_msg>Closes softlayer/sl-ember-components#509<commit_after>import Ember from 'ember';
import layout from '../templates/components/sl-modal-header';

/**
 * @module
 * @augments ember/Component
 */
export default Ember.Component.extend({

    // -------------------------------------------------------------------------
    // Dependencies

    // -------------------------------------------------------------------------
    // Attributes

    /** @type {Object} */
    layout: layout,

    /** @type {String} */
    tagName: 'div',

    // -------------------------------------------------------------------------
    // Actions

    // -------------------------------------------------------------------------
    // Events

    // -------------------------------------------------------------------------
    // Properties

    // -------------------------------------------------------------------------
    // Observers

    // -------------------------------------------------------------------------
    // Methods

    /**
     * ariaLabelledBy computed property, the value
     * of this property will be set as
     * the value to the aria-labelledby attribute
     *
     * @function
     * @returns {String}
     */
    ariaLabelledBy: Ember.computed(
        'elementId',
        function() {
            const elementId = this.get( 'elementId' );

            if ( elementId ) {
                return 'modalTitle' + elementId;
            }

            return null;
        }
    )
});
<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from '../templates/components/wait-for-render';
import { EVENT_NAME } from '../mixins/wait-for-render';

const { subscribe, unsubscribe } = Ember.Instrumentation;

/**
 * Defer component render until route has been rendered.
 * Route must implement 'wait-for-render' mixin.
 *
 * @example
 * {{#wait-for-render}}
 *     {{component 'foo'}}
 * {{/wait-for-render}}
 *
 * @example
 * {{#wait-for-render for="index"}}
 *     {{component 'foo'}}
 * {{/wait-for-render}}
 *
 * @namespace Buzz
 * @class WaitForRenderComponent
 * @extends Ember.Component
 * @public
 */
export default Ember.Component.extend({

	/**
	 * Component template file.
	 *
	 * @property layout
	 * @type String
	 * @private
	 */
	layout,

	/**
	 * Toggle yield render.
	 *
	 * @property _rendered
	 * @type Boolean
	 * @default false
	 * @private
	 */
	_rendered: false,

	/**
	 * Destination route, it will wait to that route to be fully rendered.
	 * Must match with the route 'this.routeName' property.
	 *
	 * @property for
	 * @type String
	 * @default '*'
	 * @public
	 */
	for: '*',

	/**
	 * Component to show while loading (like a spinner).
	 *
	 * @property loading
	 * @type String
	 * @default null
	 * @public
	 */
	loading: null,

	/**
	 * Stores component instrumentation object.
	 *
	 * @property _subscriber
	 * @type Object
	 * @default null
	 * @public
	 */
	_subscriber: null,

	/**
	 * Subscribe to route events.
	 *
	 * @method didInsertElement
	 * @private
	 */
	didInsertElement: function didInsertElement() {
		this._super(...arguments);

		const subscriber = subscribe(`${EVENT_NAME}.${this.get('for')}`, {
			before: Ember.K,
			after: () => this._render()
		});

		this.set('_subscriber', subscriber);
	},

	/**
	 * Enables component by setting '_rendered' to true.
	 *
	 * @method _render
	 * @private
	 */
	_render() {
		if (this.isDestroyed) {
			return;
		}

		this.set('_rendered', true);
		unsubscribe(this.get('_subscriber'));
	}

});
<commit_msg>removed html wrapper<commit_after>import Ember from 'ember';
import layout from '../templates/components/wait-for-render';
import { EVENT_NAME } from '../mixins/wait-for-render';

const { subscribe, unsubscribe } = Ember.Instrumentation;

/**
 * Defer component render until route has been rendered.
 * Route must implement 'wait-for-render' mixin.
 *
 * @example
 * {{#wait-for-render}}
 *     {{component 'foo'}}
 * {{/wait-for-render}}
 *
 * @example
 * {{#wait-for-render for="index"}}
 *     {{component 'foo'}}
 * {{/wait-for-render}}
 *
 * @namespace Buzz
 * @class WaitForRenderComponent
 * @extends Ember.Component
 * @public
 */
export default Ember.Component.extend({

	/**
	 * Remove parent wrapper.
	 *
	 * @property tagName
	 * @type String
	 * @default ''
	 * @private
	 */
	tagName: '',

	/**
	 * Component template file.
	 *
	 * @property layout
	 * @type String
	 * @private
	 */
	layout,

	/**
	 * Toggle yield render.
	 *
	 * @property _rendered
	 * @type Boolean
	 * @default false
	 * @private
	 */
	_rendered: false,

	/**
	 * Destination route, it will wait to that route to be fully rendered.
	 * Must match with the route 'this.routeName' property.
	 *
	 * @property for
	 * @type String
	 * @default '*'
	 * @public
	 */
	for: '*',

	/**
	 * Component to show while loading (like a spinner).
	 *
	 * @property loading
	 * @type String
	 * @default null
	 * @public
	 */
	loading: null,

	/**
	 * Stores component instrumentation object.
	 *
	 * @property _subscriber
	 * @type Object
	 * @default null
	 * @public
	 */
	_subscriber: null,

	/**
	 * Subscribe to route events.
	 *
	 * @method didInsertElement
	 * @private
	 */
	didInsertElement: function didInsertElement() {
		this._super(...arguments);

		const subscriber = subscribe(`${EVENT_NAME}.${this.get('for')}`, {
			before: Ember.K,
			after: () => this._render()
		});

		this.set('_subscriber', subscriber);
	},

	/**
	 * Enables component by setting '_rendered' to true.
	 *
	 * @method _render
	 * @private
	 */
	_render() {
		if (this.isDestroyed) {
			return;
		}

		this.set('_rendered', true);
		unsubscribe(this.get('_subscriber'));
	}

});
<|endoftext|>


<commit_before>import { later } from '@ember/runloop';
import { Promise } from 'rsvp';

/**
 * Function that returns a promise that resolves after after DOM changes
 * have been flushed and after a browser repaint.
 *
 * @function nextTick
 * @export nextTick
 * @return {Promise} the promise
 */
export function nextTick() {
  return new Promise((resolve) => {
    window.requestAnimationFrame(() => resolve());
  });
}

/**
 * Function that returns a promise that resolves after `ms` milliseconds.
 *
 * @function sleep
 * @export sleep
 * @param {number} ms number of milliseconds after which the promise will resolve
 * @return {Promise} the promise that will resolve after `ms` milliseconds
 */
export function sleep(ms) {
  return new Promise((resolve) => {
    later(() => resolve(), ms);
  });
}

/**
 * Computes the time a css animation will take.
 * Uses `getComputedStyle` to get durations and delays.
 *
 * @function computeTimeout
 * @export computeTimeout
 * @param {Element} element element used calculate the animation duration based on `getComputedStyle`
 * @return {number} the calculated animation duration + delay
 */
export function computeTimeout(element) {
  let {
    transitionDuration,
    transitionDelay,
    animationDuration,
    animationDelay,
    animationIterationCount,
  } = window.getComputedStyle(element);

  // `getComputedStyle` returns durations and delays in the Xs format.
  // Conveniently if `parseFloat` encounters a character other than a sign (+ or -),
  // numeral (0-9), a decimal point, or an exponent, it returns the value up to that point
  // and ignores that character and all succeeding characters.

  let maxDelay = Math.max(
    parseFloat(animationDelay),
    parseFloat(transitionDelay)
  );
  let maxDuration = Math.max(
    parseFloat(animationDuration) * parseFloat(animationIterationCount),
    parseFloat(transitionDuration)
  );

  return (maxDelay + maxDuration) * 1000;
}
<commit_msg>Replace use of RSVP with native Promise<commit_after>import { later } from '@ember/runloop';

/**
 * Function that returns a promise that resolves after DOM changes
 * have been flushed and after a browser repaint.
 *
 * @function nextTick
 * @export nextTick
 * @return {Promise} the promise
 */
export function nextTick() {
  return new Promise((resolve) => {
    window.requestAnimationFrame(() => resolve());
  });
}

/**
 * Function that returns a promise that resolves after `ms` milliseconds.
 *
 * @function sleep
 * @export sleep
 * @param {number} ms number of milliseconds after which the promise will resolve
 * @return {Promise} the promise that will resolve after `ms` milliseconds
 */
export function sleep(ms) {
  return new Promise((resolve) => {
    later(() => resolve(), ms);
  });
}

/**
 * Computes the time a css animation will take.
 * Uses `getComputedStyle` to get durations and delays.
 *
 * @function computeTimeout
 * @export computeTimeout
 * @param {Element} element element used calculate the animation duration based on `getComputedStyle`
 * @return {number} the calculated animation duration + delay
 */
export function computeTimeout(element) {
  let {
    transitionDuration,
    transitionDelay,
    animationDuration,
    animationDelay,
    animationIterationCount,
  } = window.getComputedStyle(element);

  // `getComputedStyle` returns durations and delays in the Xs format.
  // Conveniently if `parseFloat` encounters a character other than a sign (+ or -),
  // numeral (0-9), a decimal point, or an exponent, it returns the value up to that point
  // and ignores that character and all succeeding characters.

  let maxDelay = Math.max(
    parseFloat(animationDelay),
    parseFloat(transitionDelay)
  );
  let maxDuration = Math.max(
    parseFloat(animationDuration) * parseFloat(animationIterationCount),
    parseFloat(transitionDuration)
  );

  return (maxDelay + maxDuration) * 1000;
}
<|endoftext|>


<commit_before>
openerp.web.formats = function(openerp) {
var _t = openerp.web._t;

/**
 * Intersperses ``separator`` in ``str`` at the positions indicated by
 * ``indices``.
 *
 * ``indices`` is an array of relative offsets (from the previous insertion
 * position, starting from the end of the string) at which to insert
 * ``separator``.
 *
 * There are two special values:
 *
 * ``-1``
 *   indicates the insertion should end now
 * ``0``
 *   indicates that the previous section pattern should be repeated (until all
 *   of ``str`` is consumed)
 *
 * @param {String} str
 * @param {Array<Number>} indices
 * @param {String} separator
 * @returns {String}
 */
openerp.web.intersperse = function (str, indices, separator) {
    separator = separator || '';
    var result = [], last = str.length;

    for(var i=0; i<indices.length; ++i) {
        var section = indices[i];
        if (section === -1 || last <= 0) {
            // Done with string, or -1 (stops formatting string)
            break;
        } else if(section === 0 && i === 0) {
            // repeats previous section, which there is none => stop
            break;
        } else if (section === 0) {
            // repeat previous section forever
            //noinspection AssignmentToForLoopParameterJS
            section = indices[--i];
        }
        result.push(str.substring(last-section, last));
        last -= section;
    }

    var s = str.substring(0, last);
    if (s) { result.push(s); }
    return result.reverse().join(separator);
};
/**
 * Insert "thousands" separators in the provided number (which is actually
 * a string)
 *
 * @param {String} num
 * @returns {String}
 */
openerp.web.insert_thousand_seps = function (num) {
    var negative = num[0] === '-';
    num = (negative ? num.slice(1) : num);
    return (negative ? '-' : '') + openerp.web.intersperse(
        num, _t.database.parameters.grouping, _t.database.parameters.thousands_sep);
};

/**
 * removes literal (non-format) text from a date or time pattern, as datejs can
 * not deal with literal text in format strings (whatever the format), whereas
 * strftime allows for literal characters
 *
 * @param {String} value original format
 */
openerp.web.strip_raw_chars = function (value) {
    var isletter = /[a-zA-Z]/, output = [];
    for(var index=0; index < value.length; ++index) {
        var character = value[index];
        if(isletter.test(character) && (index === 0 || value[index-1] !== '%')) {
            continue;
        }
        output.push(character);
    }
    return output.join('');
};
var normalize_format = function (format) {
    return Date.normalizeFormat(openerp.web.strip_raw_chars(format));
};
/**
 * Formats a single atomic value based on a field descriptor
 *
 * @param {Object} value read from OpenERP
 * @param {Object} descriptor union of orm field and view field
 * @param {Object} [descriptor.widget] widget to use to display the value
 * @param {Object} descriptor.type fallback if no widget is provided, or if the provided widget is unknown
 * @param {Object} [descriptor.digits] used for the formatting of floats
 * @param {String} [value_if_empty=''] returned if the ``value`` argument is considered empty
 */
openerp.web.format_value = function (value, descriptor, value_if_empty) {
    // If NaN value, display as with a `false` (empty cell)
    if (typeof value === 'number' && isNaN(value)) {
        value = false;
    }
    //noinspection FallthroughInSwitchStatementJS
    switch (value) {
        case '':
            if (descriptor.type === 'char') {
                return '';
            }
            console.warn('Field', descriptor, 'had an empty string as value, treating as false...');
        case false:
        case Infinity:
        case -Infinity:
            return value_if_empty === undefined ?  '' : value_if_empty;
    }
    var l10n = _t.database.parameters;
    switch (descriptor.widget || descriptor.type) {
        case 'id':
            return value.toString();
        case 'integer':
            return openerp.web.insert_thousand_seps(
                _.str.sprintf('%d', value));
        case 'float':
            var precision = descriptor.digits ? descriptor.digits[1] : 2;
            var formatted = _.str.sprintf('%.' + precision + 'f', value).split('.');
            formatted[0] = openerp.web.insert_thousand_seps(formatted[0]);
            return formatted.join(l10n.decimal_point);
        case 'float_time':
            var pattern = '%02d:%02d';
            if (value < 0) {
                value = Math.abs(value);
                pattern = '-' + pattern;
            }
            return _.str.sprintf(pattern,
                    Math.floor(value),
                    Math.round((value % 1) * 60));
        case 'many2one':
            // name_get value format
            return value[1];
        case 'datetime':
            if (typeof(value) == "string")
                value = openerp.web.auto_str_to_date(value);

            return value.toString(normalize_format(l10n.date_format)
                        + ' ' + normalize_format(l10n.time_format));
        case 'date':
            if (typeof(value) == "string")
                value = openerp.web.auto_str_to_date(value);
            return value.toString(normalize_format(l10n.date_format));
        case 'time':
            if (typeof(value) == "string")
                value = openerp.web.auto_str_to_date(value);
            return value.toString(normalize_format(l10n.time_format));
        case 'selection':
            // Each choice is [value, label]
            if(_.isArray(value)) {
                 value = value[0]
            }
            var result = _(descriptor.selection).detect(function (choice) {
                return choice[0] === value;
            });
            if (result) { return result[1]; }
            return;
        default:
            return value;
    }
};

openerp.web.parse_value = function (value, descriptor, value_if_empty) {
    var date_pattern = normalize_format(_t.database.parameters.date_format),
        time_pattern = normalize_format(_t.database.parameters.time_format);
    switch (value) {
        case false:
        case "":
            return value_if_empty === undefined ?  false : value_if_empty;
    }
    switch (descriptor.widget || descriptor.type) {
        case 'integer':
            var tmp;
            do {
                tmp = value;
                value = value.replace(openerp.web._t.database.parameters.thousands_sep, "");
            } while(tmp !== value);
            tmp = Number(value);
            if (isNaN(tmp))
                throw new Error(value + " is not a correct integer");
            return tmp;
        case 'float':
            var tmp = Number(value);
            if (!isNaN(tmp))
                return tmp;

            var tmp2 = value;
            do {
                tmp = tmp2;
                tmp2 = tmp.replace(openerp.web._t.database.parameters.thousands_sep, "");
            } while(tmp !== tmp2);
            var reformatted_value = tmp.replace(openerp.web._t.database.parameters.decimal_point, ".");
            var parsed = Number(reformatted_value);
            if (isNaN(parsed))
                throw new Error(value + " is not a correct float");
            return parsed;
        case 'float_time':
            var factor = 1;
            if (value[0] === '-') {
                value = value.slice(1);
                factor = -1;
            }
            var float_time_pair = value.split(":");
            if (float_time_pair.length != 2)
                return factor * openerp.web.parse_value(value, {type: "float"});
            var hours = openerp.web.parse_value(float_time_pair[0], {type: "integer"});
            var minutes = openerp.web.parse_value(float_time_pair[1], {type: "integer"});
            return factor * (hours + (minutes / 60));
        case 'progressbar':
            return openerp.web.parse_value(value, {type: "float"});
        case 'datetime':
            var datetime = Date.parseExact(
                    value, (date_pattern + ' ' + time_pattern));
            if (datetime !== null)
                return openerp.web.datetime_to_str(datetime);
            datetime = Date.parse(value);
            if (datetime !== null)
                return openerp.web.datetime_to_str(datetime);
            throw new Error(value + " is not a valid datetime");
        case 'date':
            var date = Date.parseExact(value, date_pattern);
            if (date !== null)
                return openerp.web.date_to_str(date);
            date = Date.parse(value);
            if (date !== null)
                return openerp.web.date_to_str(date);
            throw new Error(value + " is not a valid date");
        case 'time':
            var time = Date.parseExact(value, time_pattern);
            if (time !== null)
                return openerp.web.time_to_str(time);
            time = Date.parse(value);
            if (time !== null)
                return openerp.web.time_to_str(time);
            throw new Error(value + " is not a valid time");
    }
    return value;
};

openerp.web.auto_str_to_date = function(value, type) {
    try {
        return openerp.web.str_to_datetime(value);
    } catch(e) {}
    try {
        return openerp.web.str_to_date(value);
    } catch(e) {}
    try {
        return openerp.web.str_to_time(value);
    } catch(e) {}
    throw new Error("'" + value + "' is not a valid date, datetime nor time");
};

openerp.web.auto_date_to_str = function(value, type) {
    switch(type) {
        case 'datetime':
            return openerp.web.datetime_to_str(value);
        case 'date':
            return openerp.web.date_to_str(value);
        case 'time':
            return openerp.web.time_to_str(value);
        default:
            throw new Error(type + " is not convertible to date, datetime nor time");
    }
};

/**
 * Formats a provided cell based on its field type. Most of the field types
 * return a correctly formatted value, but some tags and fields are
 * special-cased in their handling:
 *
 * * buttons will return an actual ``<button>`` tag with a bunch of error handling
 *
 * * boolean fields will return a checkbox input, potentially disabled
 *
 * * binary fields will return a link to download the binary data as a file
 *
 * @param {Object} row_data record whose values should be displayed in the cell
 * @param {Object} column column descriptor
 * @param {"button"|"field"} column.tag base control type
 * @param {String} column.type widget type for a field control
 * @param {String} [column.string] button label
 * @param {String} [column.icon] button icon
 * @param {Object} [options]
 * @param {String} [options.value_if_empty=''] what to display if the field's value is ``false``
 * @param {Boolean} [options.process_modifiers=true] should the modifiers be computed ?
 * @param {String} [options.model] current record's model
 * @param {Number} [options.id] current record's id
 *
 */
openerp.web.format_cell = function (row_data, column, options) {
    options = options || {};
    var attrs = {};
    if (options.process_modifiers !== false) {
        attrs = column.modifiers_for(row_data);
    }
    if (attrs.invisible) { return ''; }

    if (column.tag === 'button') {
        return _.template('<button type="button" title="<%-title%>" <%=additional_attributes%> >' +
            '<img src="<%-prefix%>/web/static/src/img/icons/<%-icon%>.png" alt="<%-alt%>"/>' +
            '</button>', {
                title: column.string || '',
                additional_attributes: isNaN(row_data["id"].value) && openerp.web.BufferedDataSet.virtual_id_regex.test(row_data["id"].value) ?
                    'disabled="disabled" class="oe-listview-button-disabled"' : '',
                prefix: openerp.connection.prefix,
                icon: column.icon,
                alt: column.string || ''
            });
    }
    if (!row_data[column.id]) {
        return options.value_if_empty === undefined ? '' : options.value_if_empty;
    }

    switch (column.widget || column.type) {
    case "boolean":
        return _.str.sprintf('<input type="checkbox" %s disabled="disabled"/>',
                 row_data[column.id].value ? 'checked="checked"' : '');
    case "binary":
        var text = _t("Download"),
            download_url = _.str.sprintf('/web/binary/saveas?session_id=%s&model=%s&field=%s&id=%d', openerp.connection.session_id, options.model, column.id, options.id);
        if (column.filename) {
            download_url += '&filename_field=' + column.filename;
            if (row_data[column.filename]) {
                text = _.str.sprintf(_t("Download \"%s\""), openerp.web.format_value(
                        row_data[column.filename].value, {type: 'char'}));
            }
        }
        return _.template('<a href="<%-href%>"><%-text%> (%<-size%>)', {
            text: text,
            href: download_url,
            size: row_data[column.id].value
        });
    case 'progressbar':
        return _.template(
            '<progress value="<%-value%>" max="100"><%-value%>%</progress>', {
                value: _.str.sprintf("%.0f", row_data[column.id].value || 0)
            });
    }

    return _.escape(openerp.web.format_value(
            row_data[column.id].value, column, options.value_if_empty));
}

};
<commit_msg>[FIX] render statusbar as selection in listview<commit_after>
openerp.web.formats = function(openerp) {
var _t = openerp.web._t;

/**
 * Intersperses ``separator`` in ``str`` at the positions indicated by
 * ``indices``.
 *
 * ``indices`` is an array of relative offsets (from the previous insertion
 * position, starting from the end of the string) at which to insert
 * ``separator``.
 *
 * There are two special values:
 *
 * ``-1``
 *   indicates the insertion should end now
 * ``0``
 *   indicates that the previous section pattern should be repeated (until all
 *   of ``str`` is consumed)
 *
 * @param {String} str
 * @param {Array<Number>} indices
 * @param {String} separator
 * @returns {String}
 */
openerp.web.intersperse = function (str, indices, separator) {
    separator = separator || '';
    var result = [], last = str.length;

    for(var i=0; i<indices.length; ++i) {
        var section = indices[i];
        if (section === -1 || last <= 0) {
            // Done with string, or -1 (stops formatting string)
            break;
        } else if(section === 0 && i === 0) {
            // repeats previous section, which there is none => stop
            break;
        } else if (section === 0) {
            // repeat previous section forever
            //noinspection AssignmentToForLoopParameterJS
            section = indices[--i];
        }
        result.push(str.substring(last-section, last));
        last -= section;
    }

    var s = str.substring(0, last);
    if (s) { result.push(s); }
    return result.reverse().join(separator);
};
/**
 * Insert "thousands" separators in the provided number (which is actually
 * a string)
 *
 * @param {String} num
 * @returns {String}
 */
openerp.web.insert_thousand_seps = function (num) {
    var negative = num[0] === '-';
    num = (negative ? num.slice(1) : num);
    return (negative ? '-' : '') + openerp.web.intersperse(
        num, _t.database.parameters.grouping, _t.database.parameters.thousands_sep);
};

/**
 * removes literal (non-format) text from a date or time pattern, as datejs can
 * not deal with literal text in format strings (whatever the format), whereas
 * strftime allows for literal characters
 *
 * @param {String} value original format
 */
openerp.web.strip_raw_chars = function (value) {
    var isletter = /[a-zA-Z]/, output = [];
    for(var index=0; index < value.length; ++index) {
        var character = value[index];
        if(isletter.test(character) && (index === 0 || value[index-1] !== '%')) {
            continue;
        }
        output.push(character);
    }
    return output.join('');
};
var normalize_format = function (format) {
    return Date.normalizeFormat(openerp.web.strip_raw_chars(format));
};
/**
 * Formats a single atomic value based on a field descriptor
 *
 * @param {Object} value read from OpenERP
 * @param {Object} descriptor union of orm field and view field
 * @param {Object} [descriptor.widget] widget to use to display the value
 * @param {Object} descriptor.type fallback if no widget is provided, or if the provided widget is unknown
 * @param {Object} [descriptor.digits] used for the formatting of floats
 * @param {String} [value_if_empty=''] returned if the ``value`` argument is considered empty
 */
openerp.web.format_value = function (value, descriptor, value_if_empty) {
    // If NaN value, display as with a `false` (empty cell)
    if (typeof value === 'number' && isNaN(value)) {
        value = false;
    }
    //noinspection FallthroughInSwitchStatementJS
    switch (value) {
        case '':
            if (descriptor.type === 'char') {
                return '';
            }
            console.warn('Field', descriptor, 'had an empty string as value, treating as false...');
        case false:
        case Infinity:
        case -Infinity:
            return value_if_empty === undefined ?  '' : value_if_empty;
    }
    var l10n = _t.database.parameters;
    switch (descriptor.widget || descriptor.type) {
        case 'id':
            return value.toString();
        case 'integer':
            return openerp.web.insert_thousand_seps(
                _.str.sprintf('%d', value));
        case 'float':
            var precision = descriptor.digits ? descriptor.digits[1] : 2;
            var formatted = _.str.sprintf('%.' + precision + 'f', value).split('.');
            formatted[0] = openerp.web.insert_thousand_seps(formatted[0]);
            return formatted.join(l10n.decimal_point);
        case 'float_time':
            var pattern = '%02d:%02d';
            if (value < 0) {
                value = Math.abs(value);
                pattern = '-' + pattern;
            }
            return _.str.sprintf(pattern,
                    Math.floor(value),
                    Math.round((value % 1) * 60));
        case 'many2one':
            // name_get value format
            return value[1];
        case 'datetime':
            if (typeof(value) == "string")
                value = openerp.web.auto_str_to_date(value);

            return value.toString(normalize_format(l10n.date_format)
                        + ' ' + normalize_format(l10n.time_format));
        case 'date':
            if (typeof(value) == "string")
                value = openerp.web.auto_str_to_date(value);
            return value.toString(normalize_format(l10n.date_format));
        case 'time':
            if (typeof(value) == "string")
                value = openerp.web.auto_str_to_date(value);
            return value.toString(normalize_format(l10n.time_format));
        case 'selection': case 'statusbar':
            // Each choice is [value, label]
            if(_.isArray(value)) {
                 value = value[0]
            }
            var result = _(descriptor.selection).detect(function (choice) {
                return choice[0] === value;
            });
            if (result) { return result[1]; }
            return;
        default:
            return value;
    }
};

openerp.web.parse_value = function (value, descriptor, value_if_empty) {
    var date_pattern = normalize_format(_t.database.parameters.date_format),
        time_pattern = normalize_format(_t.database.parameters.time_format);
    switch (value) {
        case false:
        case "":
            return value_if_empty === undefined ?  false : value_if_empty;
    }
    switch (descriptor.widget || descriptor.type) {
        case 'integer':
            var tmp;
            do {
                tmp = value;
                value = value.replace(openerp.web._t.database.parameters.thousands_sep, "");
            } while(tmp !== value);
            tmp = Number(value);
            if (isNaN(tmp))
                throw new Error(value + " is not a correct integer");
            return tmp;
        case 'float':
            var tmp = Number(value);
            if (!isNaN(tmp))
                return tmp;

            var tmp2 = value;
            do {
                tmp = tmp2;
                tmp2 = tmp.replace(openerp.web._t.database.parameters.thousands_sep, "");
            } while(tmp !== tmp2);
            var reformatted_value = tmp.replace(openerp.web._t.database.parameters.decimal_point, ".");
            var parsed = Number(reformatted_value);
            if (isNaN(parsed))
                throw new Error(value + " is not a correct float");
            return parsed;
        case 'float_time':
            var factor = 1;
            if (value[0] === '-') {
                value = value.slice(1);
                factor = -1;
            }
            var float_time_pair = value.split(":");
            if (float_time_pair.length != 2)
                return factor * openerp.web.parse_value(value, {type: "float"});
            var hours = openerp.web.parse_value(float_time_pair[0], {type: "integer"});
            var minutes = openerp.web.parse_value(float_time_pair[1], {type: "integer"});
            return factor * (hours + (minutes / 60));
        case 'progressbar':
            return openerp.web.parse_value(value, {type: "float"});
        case 'datetime':
            var datetime = Date.parseExact(
                    value, (date_pattern + ' ' + time_pattern));
            if (datetime !== null)
                return openerp.web.datetime_to_str(datetime);
            datetime = Date.parse(value);
            if (datetime !== null)
                return openerp.web.datetime_to_str(datetime);
            throw new Error(value + " is not a valid datetime");
        case 'date':
            var date = Date.parseExact(value, date_pattern);
            if (date !== null)
                return openerp.web.date_to_str(date);
            date = Date.parse(value);
            if (date !== null)
                return openerp.web.date_to_str(date);
            throw new Error(value + " is not a valid date");
        case 'time':
            var time = Date.parseExact(value, time_pattern);
            if (time !== null)
                return openerp.web.time_to_str(time);
            time = Date.parse(value);
            if (time !== null)
                return openerp.web.time_to_str(time);
            throw new Error(value + " is not a valid time");
    }
    return value;
};

openerp.web.auto_str_to_date = function(value, type) {
    try {
        return openerp.web.str_to_datetime(value);
    } catch(e) {}
    try {
        return openerp.web.str_to_date(value);
    } catch(e) {}
    try {
        return openerp.web.str_to_time(value);
    } catch(e) {}
    throw new Error("'" + value + "' is not a valid date, datetime nor time");
};

openerp.web.auto_date_to_str = function(value, type) {
    switch(type) {
        case 'datetime':
            return openerp.web.datetime_to_str(value);
        case 'date':
            return openerp.web.date_to_str(value);
        case 'time':
            return openerp.web.time_to_str(value);
        default:
            throw new Error(type + " is not convertible to date, datetime nor time");
    }
};

/**
 * Formats a provided cell based on its field type. Most of the field types
 * return a correctly formatted value, but some tags and fields are
 * special-cased in their handling:
 *
 * * buttons will return an actual ``<button>`` tag with a bunch of error handling
 *
 * * boolean fields will return a checkbox input, potentially disabled
 *
 * * binary fields will return a link to download the binary data as a file
 *
 * @param {Object} row_data record whose values should be displayed in the cell
 * @param {Object} column column descriptor
 * @param {"button"|"field"} column.tag base control type
 * @param {String} column.type widget type for a field control
 * @param {String} [column.string] button label
 * @param {String} [column.icon] button icon
 * @param {Object} [options]
 * @param {String} [options.value_if_empty=''] what to display if the field's value is ``false``
 * @param {Boolean} [options.process_modifiers=true] should the modifiers be computed ?
 * @param {String} [options.model] current record's model
 * @param {Number} [options.id] current record's id
 *
 */
openerp.web.format_cell = function (row_data, column, options) {
    options = options || {};
    var attrs = {};
    if (options.process_modifiers !== false) {
        attrs = column.modifiers_for(row_data);
    }
    if (attrs.invisible) { return ''; }

    if (column.tag === 'button') {
        return _.template('<button type="button" title="<%-title%>" <%=additional_attributes%> >' +
            '<img src="<%-prefix%>/web/static/src/img/icons/<%-icon%>.png" alt="<%-alt%>"/>' +
            '</button>', {
                title: column.string || '',
                additional_attributes: isNaN(row_data["id"].value) && openerp.web.BufferedDataSet.virtual_id_regex.test(row_data["id"].value) ?
                    'disabled="disabled" class="oe-listview-button-disabled"' : '',
                prefix: openerp.connection.prefix,
                icon: column.icon,
                alt: column.string || ''
            });
    }
    if (!row_data[column.id]) {
        return options.value_if_empty === undefined ? '' : options.value_if_empty;
    }

    switch (column.widget || column.type) {
    case "boolean":
        return _.str.sprintf('<input type="checkbox" %s disabled="disabled"/>',
                 row_data[column.id].value ? 'checked="checked"' : '');
    case "binary":
        var text = _t("Download"),
            download_url = _.str.sprintf('/web/binary/saveas?session_id=%s&model=%s&field=%s&id=%d', openerp.connection.session_id, options.model, column.id, options.id);
        if (column.filename) {
            download_url += '&filename_field=' + column.filename;
            if (row_data[column.filename]) {
                text = _.str.sprintf(_t("Download \"%s\""), openerp.web.format_value(
                        row_data[column.filename].value, {type: 'char'}));
            }
        }
        return _.template('<a href="<%-href%>"><%-text%> (%<-size%>)', {
            text: text,
            href: download_url,
            size: row_data[column.id].value
        });
    case 'progressbar':
        return _.template(
            '<progress value="<%-value%>" max="100"><%-value%>%</progress>', {
                value: _.str.sprintf("%.0f", row_data[column.id].value || 0)
            });
    }

    return _.escape(openerp.web.format_value(
            row_data[column.id].value, column, options.value_if_empty));
}

};
<|endoftext|>


<commit_before>var unirest = require('unirest')

module.exports = {
    schema : {
        "name": "API",
        "value": "api",
        "description": "Import Consumers by issuing a GET request to an API",
        "form_fields": {
            "connection": {
                "endpoint": {
                    "name": "endpoint",
                    "required" : true,
                    "type": "text",
                    "description": "The API endpoint. ex: http://myapi.io/users?limit=3000"
                },
                "headers": {
                    "name": "headers",
                    "type": "text",
                    "description": "A comma separated list of headers to send with the request. ex: Authorization:Bearer some-token-key,Content-type:application/json"
                }
            },
            "consumer": {
                "data_property" : {
                    "name": "Data property",
                    "type": "text",
                    "description": "If specified, the consumers will be extracted from this resulting object's property."
                },
                "username": {
                    "name": "username field",
                    "type": "text",
                    "required": true,
                    "description": "The resulting object's property that will be used as the consumers username."
                },
                "custom_id": {
                    "name": "custom_id field",
                    "type": "text",
                    "required": true,
                    "description": "The resulting object's property will be used as the consumers custom_id."
                }
            }
        }
    },
    methods : {
        loadConsumers : function(req,res) {

            var headers = {}
            if(req.param('headers')) {
                var string = req.param('headers')
                var split = string.split(",")
                split.forEach(function(keyVal){
                    var array = keyVal.split(":")
                    headers[array[0]] = array[1]
                })

                console.log("Headers =>",headers)
            }

            var request = unirest.get(req.param('endpoint'))
            request.headers(headers)
            request.end(function (response) {
                if (response.error)  return res.negotiate(response)

                console.log("response.body",response.body)

                var jsonRes = response.body

                return res.json(req.param('data_property') ? jsonRes[req.param('data_property')] : jsonRes)
            })
        }
    }

}
<commit_msg>Changed verbs<commit_after>var unirest = require('unirest')

module.exports = {
    schema : {
        "name": "API",
        "value": "api",
        "description": "Import Consumers by issuing a GET request to an API endpoint",
        "form_fields": {
            "connection": {
                "endpoint": {
                    "name": "endpoint",
                    "required" : true,
                    "type": "text",
                    "description": "The API endpoint. ex: http://myapi.io/users?limit=3000"
                },
                "headers": {
                    "name": "headers",
                    "type": "text",
                    "description": "A comma separated list of headers to send with the request. ex: Authorization:Bearer some-token-key,Content-type:application/json"
                }
            },
            "consumer": {
                "data_property" : {
                    "name": "Data property",
                    "type": "text",
                    "description": "If specified, the consumers will be extracted from this resulting object's property."
                },
                "username": {
                    "name": "username field",
                    "type": "text",
                    "required": true,
                    "description": "The property that will be used as the consumer username."
                },
                "custom_id": {
                    "name": "custom_id field",
                    "type": "text",
                    "required": true,
                    "description": "The property will be used as the consumer custom_id."
                }
            }
        }
    },
    methods : {
        loadConsumers : function(req,res) {

            var headers = {}
            if(req.param('headers')) {
                var string = req.param('headers')
                var split = string.split(",")
                split.forEach(function(keyVal){
                    var array = keyVal.split(":")
                    headers[array[0]] = array[1]
                })

                console.log("Headers =>",headers)
            }

            var request = unirest.get(req.param('endpoint'))
            request.headers(headers)
            request.end(function (response) {
                if (response.error)  return res.negotiate(response)

                console.log("response.body",response.body)

                var jsonRes = response.body

                return res.json(req.param('data_property') ? jsonRes[req.param('data_property')] : jsonRes)
            })
        }
    }

}
<|endoftext|>


<commit_before>/*
 * grunt-aws-lambda
 * https://github.com/Tim-B/grunt-aws-lambda
 *
 * Copyright (c) 2014 Tim-B
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function (grunt) {

    var path = require('path');
    var fs = require('fs');

    // Please see the Grunt documentation for more information regarding task
    // creation: http://gruntjs.com/creating-tasks

    grunt.registerMultiTask('lambda_invoke', 'Invokes a lambda function for testing purposes', function () {

        var options = this.options({
            'handler': 'handler',
            'file_name': 'index.js',
            'event': 'event.json'
        });

        grunt.log.writeln("");

        var done = this.async();

        var context = {
            done: function (error, result) {
                if (error === null) {
                    this.succeed(result);
                } else {
                    this.fail(error);
                }
            },
            succeed: function (result) {
                grunt.log.writeln("");
                grunt.log.writeln("Success!  Message:");
                grunt.log.writeln("------------------");
                grunt.log.writeln(result);
                done(true);
            },
            fail: function (error) {
                grunt.log.writeln("");
                grunt.log.writeln("Failure!  Message:");
                grunt.log.writeln("------------------");
                grunt.log.writeln(error);
                done(false);
            },
            awsRequestId: 'LAMBDA_INVOKE',
            logStreamName: 'LAMBDA_INVOKE',
            clientContext: null,
            identity: null
        };

        var lambda = require(path.resolve(options.file_name));
        var event = JSON.parse(fs.readFileSync(path.resolve(options.event), "utf8"));
        lambda[options.handler](event, context);

    });

};
<commit_msg>Changed reference to 'this' to 'context' in lambda_invoke. Issue was that 'this' was already the grunt 'this' object and in these 2 references we needed 'this' to actually be the 'context' object. Just forced those 2 instances to reference 'context' instead of 'this'.<commit_after>/*
 * grunt-aws-lambda
 * https://github.com/Tim-B/grunt-aws-lambda
 *
 * Copyright (c) 2014 Tim-B
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function (grunt) {

    var path = require('path');
    var fs = require('fs');

    // Please see the Grunt documentation for more information regarding task
    // creation: http://gruntjs.com/creating-tasks

    grunt.registerMultiTask('lambda_invoke', 'Invokes a lambda function for testing purposes', function () {

        var options = this.options({
            'handler': 'handler',
            'file_name': 'index.js',
            'event': 'event.json'
        });

        grunt.log.writeln("");

        var done = this.async();

        var context = {
            done: function (error, result) {
                if (error === null) {
                    context.succeed(result);
                } else {
                    context.fail(error);
                }
            },
            succeed: function (result) {
                grunt.log.writeln("");
                grunt.log.writeln("Success!  Message:");
                grunt.log.writeln("------------------");
                grunt.log.writeln(result);
                done(true);
            },
            fail: function (error) {
                grunt.log.writeln("");
                grunt.log.writeln("Failure!  Message:");
                grunt.log.writeln("------------------");
                grunt.log.writeln(error);
                done(false);
            },
            awsRequestId: 'LAMBDA_INVOKE',
            logStreamName: 'LAMBDA_INVOKE',
            clientContext: null,
            identity: null
        };

        var lambda = require(path.resolve(options.file_name));
        var event = JSON.parse(fs.readFileSync(path.resolve(options.event), "utf8"));
        lambda[options.handler](event, context);

    });

};
<|endoftext|>


<commit_before><commit_msg>Add received body in log<commit_after><|endoftext|>