<commit_before>angular.module('dogfeed', ['ngRSS', 'ngSockethubClient', 'ngRemoteStorage']).

/**
 * routes
 */
config(['$routeProvider',
function ($routeProvider) {
  $routeProvider.
    when('/', {
      templateUrl: "feeds.html"
    }).
    otherwise({
      redirectTo: "/"
    });
}]).

/**
 * remoteStorage & sockethub connect
 */
run(['SockethubSettings', 'SH', '$rootScope', 'RS', '$timeout',
function (settings, SH, $rootScope, RS, $timeout) {
  if (!RS.isConnected()) {
    $timeout(function () {
      if (!RS.isConnected()) {
        $rootScope.$broadcast('message', {message: 'remotestorage-connect', timeout: false});
      }
    }, 1000);
  }
}]).

run(['SockethubSettings', 'SH', '$rootScope', 'RS',
function (settings, SH, $rootScope, RS) {
  RS.call('sockethub', 'getConfig', ['']).then(function (cfg) {
    console.log('GOT SH CONFIG: ', cfg);
    if (!cfg) {
      //cfg = settings.conn;
      cfg.host = 'silverbucket.net';
      cfg.port = 443;
      cfg.path = '/sockethub';
      cfg.tls = true;
    }

    console.log('USING SH CONFIG: ', cfg);
    //$rootScope.$broadcast('message', {type: 'clear'});
    // connect to sockethub and register
    settings.save('conn', cfg);
    $rootScope.$broadcast('message', {
          message: 'attempting to connect to sockethub',
          type: 'info',
          timeout: false
    });
    SH.connect({register: true}).then(function () {
      //console.log('connected to sockethub');
      $rootScope.$broadcast('message', {
            message: 'connected to sockethub',
            type: 'success',
            timeout: true
      });
    }, function (err) {
      console.log('error connecting to sockethub: ', err);
      $rootScope.$broadcast('SockethubConnectFailed', {message: err});
    });
  }, function (err) {
    console.log("RS.call error: ",err);
  });
}]).

/**
 * emitters
 */
run(['$rootScope',
function ($rootScope) {
  $rootScope.$on('showModalAddFeed', function(event, args) {
    backdrop_setting = true;
    if ((typeof args === 'object') && (typeof args.locked !== 'undefined')) {
      if (args.locked) {
        backdrop_setting = "static";
      }
    }
    $("#modalAddFeed").modal({
      show: true,
      keyboard: true,
      backdrop: backdrop_setting
    });
  });

  $rootScope.$on('closeModalAddFeed', function(event, args) {
    $("#modalAddFeed").modal('hide');
  });
}]).

/**
 * filter: urlEncode
 */
filter('urlEncode', [
function() {
  return function (text, length, end) {
    return encodeURIComponent(escape(text));
  };
}]).

///////////////////////////////////////////////////////////////////////////
//
// CONTROLLERS
//
///////////////////////////////////////////////////////////////////////////

/**
 * controller: titlebarCtrl
 */
controller('titlebarCtrl',
['$scope', '$rootScope', 'SockethubSettings', 'RS',
function ($scope, $rootScope, settings, RS) {
  $scope.addFeed = function () {
    $rootScope.$broadcast('showModalAddFeed', {locked: false});
  };
  $scope.sockethubSettings = function () {
    $rootScope.$broadcast('showModalSockethubSettings', {locked: false});
  };

  $scope.$watch('settings.connected', function (newVal, oldVal) {
    if (settings.connected) {
      settings.conn.port = Number(settings.conn.port);
      RS.call('sockethub', 'writeConfig', [settings.conn]).then(function () {
        console.log("Sockethub config saved to remoteStorage");
      }, function (err) {
        console.log('Failed saving Sockethub config to remoteStorage: ', err);
      });
    }
  });
}]).

///////////////////////////////////////////////////////////////////////////
//
// DIRECTIVES
//
///////////////////////////////////////////////////////////////////////////

/**
 * directive: message
 */
directive('message',
['$rootScope', '$timeout',
function ($rootScope, $timeout) {
  return {
    restrict: 'A',
    template: '
'+
              '  {{m.title}} ' +
              '  {{m.message}}' +
              '
',
    link: function (scope) {
      scope.haveMessage = false;
      scope.m = {type: '', title: '', message: ''};

      var presets = {
        'remotestorage-connect': {
          type: 'error',
          title : 'Connect to remoteStorage',
          message: 'First things first. You must connect to your remoteStorage'
        },
        'sockethub-config': {
          type: 'error',
          title: 'Sockethub configuration needed',
          message: 'You must fill in your Sockethub connection details'
        },
        'sockethub-connect': {
          type: 'error',
          title: 'Sockethub connection error',
          message: 'Unable to connect to Sockethub please check your configuration and try again'
        },
        'sockethub-register': {
          type: 'error',
          title: 'Sockethub registration problem',
          message: 'We were unable to register with your Sockethub instance'
        },
        'xmpp-connect': {
          type: 'error',
          title: 'XMPP connection failed',
          message: 'There was a problem connecting to the XMPP server, please verify you settings'
        },
        'unknown': {
          type: 'error',
          title: 'An unknown error has occurred',
          message: ''
        }
      };

      $rootScope.$on('message', function (event, e) {
        //console.log('message event: ', e);

        var timeout = (typeof e.timeout === 'boolean') ? e.timeout : true;
        scope.haveMessage = false;

        if (typeof e === 'undefined') {
          e = 'no error specified';
        }

        if (e.type === 'clear') {
          scope.haveMessage = false;
          scope.m = {type: '', title: '', message: ''};
          return;
        } else if (typeof presets[e.message] !== 'undefined') {
          scope.m = presets[e.message];
        } else if (typeof e.message === 'string') {
          if (e.type === 'success') {
            scope.m.title = 'Success';
          } else if (e.type === 'info') {
            scope.m.title = 'Info';
          } else {
            scope.m.title = "Error";
          }
          scope.m.message = e.message;
          scope.m.type = e.type;
        }
        //console.log('done processing: ', scope.m);

        scope.haveMessage = true;
        if (timeout) {
          $timeout(function () {
            scope.haveMessage = false;
            scope.m = {type: '', title: '', message: ''};
          }, 4000);
        }
      });
    }
  };
}]);

<commit_msg>potential fix for #37<commit_after>angular.module('dogfeed', ['ngRSS', 'ngSockethubClient', 'ngRemoteStorage']).

/**
 * routes
 */
config(['$routeProvider',
function ($routeProvider) {
  $routeProvider.
    when('/', {
      templateUrl: "feeds.html"
    }).
    otherwise({
      redirectTo: "/"
    });
}]).

/**
 * remoteStorage & sockethub connect
 */
run(['SockethubSettings', 'SH', '$rootScope', 'RS', '$timeout',
function (settings, SH, $rootScope, RS, $timeout) {
  if (!RS.isConnected()) {
    $timeout(function () {
      if (!RS.isConnected()) {
        $rootScope.$broadcast('message', {message: 'remotestorage-connect', timeout: false});
      }
    }, 1000);
  }
}]).

run(['SockethubSettings', 'SH', '$rootScope', 'RS',
function (settings, SH, $rootScope, RS) {
  RS.call('sockethub', 'getConfig', ['']).then(function (cfg) {
    console.log('GOT SH CONFIG: ', cfg);
    if (!cfg) {
      cfg = {};
      //cfg = settings.conn;
      cfg.host = 'silverbucket.net';
      cfg.port = 443;
      cfg.path = '/sockethub';
      cfg.tls = true;
    }

    console.log('USING SH CONFIG: ', cfg);
    //$rootScope.$broadcast('message', {type: 'clear'});
    // connect to sockethub and register
    settings.save('conn', cfg);
    $rootScope.$broadcast('message', {
          message: 'attempting to connect to sockethub',
          type: 'info',
          timeout: false
    });
    SH.connect({register: true}).then(function () {
      //console.log('connected to sockethub');
      $rootScope.$broadcast('message', {
            message: 'connected to sockethub',
            type: 'success',
            timeout: true
      });
    }, function (err) {
      console.log('error connecting to sockethub: ', err);
      $rootScope.$broadcast('SockethubConnectFailed', {message: err});
    });
  }, function (err) {
    console.log("RS.call error: ",err);
  });
}]).

/**
 * emitters
 */
run(['$rootScope',
function ($rootScope) {
  $rootScope.$on('showModalAddFeed', function(event, args) {
    backdrop_setting = true;
    if ((typeof args === 'object') && (typeof args.locked !== 'undefined')) {
      if (args.locked) {
        backdrop_setting = "static";
      }
    }
    $("#modalAddFeed").modal({
      show: true,
      keyboard: true,
      backdrop: backdrop_setting
    });
  });

  $rootScope.$on('closeModalAddFeed', function(event, args) {
    $("#modalAddFeed").modal('hide');
  });
}]).

/**
 * filter: urlEncode
 */
filter('urlEncode', [
function() {
  return function (text, length, end) {
    return encodeURIComponent(escape(text));
  };
}]).

///////////////////////////////////////////////////////////////////////////
//
// CONTROLLERS
//
///////////////////////////////////////////////////////////////////////////

/**
 * controller: titlebarCtrl
 */
controller('titlebarCtrl',
['$scope', '$rootScope', 'SockethubSettings', 'RS',
function ($scope, $rootScope, settings, RS) {
  $scope.addFeed = function () {
    $rootScope.$broadcast('showModalAddFeed', {locked: false});
  };
  $scope.sockethubSettings = function () {
    $rootScope.$broadcast('showModalSockethubSettings', {locked: false});
  };

  $scope.$watch('settings.connected', function (newVal, oldVal) {
    if (settings.connected) {
      settings.conn.port = Number(settings.conn.port);
      RS.call('sockethub', 'writeConfig', [settings.conn]).then(function () {
        console.log("Sockethub config saved to remoteStorage");
      }, function (err) {
        console.log('Failed saving Sockethub config to remoteStorage: ', err);
      });
    }
  });
}]).

///////////////////////////////////////////////////////////////////////////
//
// DIRECTIVES
//
///////////////////////////////////////////////////////////////////////////

/**
 * directive: message
 */
directive('message',
['$rootScope', '$timeout',
function ($rootScope, $timeout) {
  return {
    restrict: 'A',
    template: '
'+
              '  {{m.title}} ' +
              '  {{m.message}}' +
              '
',
    link: function (scope) {
      scope.haveMessage = false;
      scope.m = {type: '', title: '', message: ''};

      var presets = {
        'remotestorage-connect': {
          type: 'error',
          title : 'Connect to remoteStorage',
          message: 'First things first. You must connect to your remoteStorage'
        },
        'sockethub-config': {
          type: 'error',
          title: 'Sockethub configuration needed',
          message: 'You must fill in your Sockethub connection details'
        },
        'sockethub-connect': {
          type: 'error',
          title: 'Sockethub connection error',
          message: 'Unable to connect to Sockethub please check your configuration and try again'
        },
        'sockethub-register': {
          type: 'error',
          title: 'Sockethub registration problem',
          message: 'We were unable to register with your Sockethub instance'
        },
        'xmpp-connect': {
          type: 'error',
          title: 'XMPP connection failed',
          message: 'There was a problem connecting to the XMPP server, please verify you settings'
        },
        'unknown': {
          type: 'error',
          title: 'An unknown error has occurred',
          message: ''
        }
      };

      $rootScope.$on('message', function (event, e) {
        //console.log('message event: ', e);

        var timeout = (typeof e.timeout === 'boolean') ? e.timeout : true;
        scope.haveMessage = false;

        if (typeof e === 'undefined') {
          e = 'no error specified';
        }

        if (e.type === 'clear') {
          scope.haveMessage = false;
          scope.m = {type: '', title: '', message: ''};
          return;
        } else if (typeof presets[e.message] !== 'undefined') {
          scope.m = presets[e.message];
        } else if (typeof e.message === 'string') {
          if (e.type === 'success') {
            scope.m.title = 'Success';
          } else if (e.type === 'info') {
            scope.m.title = 'Info';
          } else {
            scope.m.title = "Error";
          }
          scope.m.message = e.message;
          scope.m.type = e.type;
        }
        //console.log('done processing: ', scope.m);

        scope.haveMessage = true;
        if (timeout) {
          $timeout(function () {
            scope.haveMessage = false;
            scope.m = {type: '', title: '', message: ''};
          }, 4000);
        }
      });
    }
  };
}]);

<|endoftext|>


<commit_before>define([
    'arches',
    'underscore',
    'knockout',
    'knockout-mapping',
    'viewmodels/widget',
    'viewmodels/map-editor',
    'bindings/chosen',
    'bindings/codemirror',
    'codemirror/mode/javascript/javascript',
    'select2',
    'bindings/select2v4',
    'bindings/fadeVisible',
    'bindings/mapbox-gl',
    'bindings/chosen',
    'bindings/color-picker',
    'geocoder-templates'
], function(arches, _, ko, koMapping, WidgetViewModel, MapEditorViewModel) {
    var viewModel = function(params) {
        this.context = params.type;
        this.summaryDetails = [];
        this.defaultValueOptions = [
            {
                "name": "",
                "defaultOptionid": 0,
                "value": ""
            },
            {
                "name": "Drawn Location",
                "defaultOptionid": 1,
                "value": "Drawn Location"
            },
            {
                "name": "Current Device Location",
                "defaultOptionid": 2,
                "value": "Current Device Location"
            }
        ];

        params.configKeys = [
            'basemap',
            'overlayConfigs',
            'zoom',
            'centerX',
            'centerY',
            'geometryTypes',
            'defaultValueType',
            'defaultValue'
        ];

        WidgetViewModel.apply(this, [params]);

        this.geometryTypeList = ko.computed({
            read: function() {
                var geometryTypes = this.geometryTypes() || [];
                return geometryTypes.map(function(type) {
                    return ko.unwrap(type.id);
                });
            },
            write: function(value) {
                this.geometryTypes(value.map(function(type) {
                    return {
                        id: type,
                        text: type
                    };
                }));
            },
            owner: this
        });

        this.displayValue = ko.computed(function() {
            var value = koMapping.toJS(this.value);
            if (!value || !value.features) {
                return 0;
            }
            return value.features.length;
        }, this);

        if (params.widget) params.widgets = [params.widget];

        if (ko.unwrap(this.value) !== null) {
            this.summaryDetails = koMapping.toJS(this.value).features || [];
        }

        if (this.centerX() == 0 && this.centerY() == 0 && this.zoom() == 0) {
            this.centerX(arches.mapDefaultX);
            this.centerY(arches.mapDefaultY);
            this.zoom(arches.mapDefaultZoom);
        }

        this.overlayConfigs = ko.observable(this.config().overlayConfigs);
        this.overlayConfigs.subscribe(function(foo) {
            params.config({
                ...params.config(),
                'overlayConfigs': foo,
            })
        })

        params.basemap = this.basemap;
        params.overlayConfigs = this.overlayConfigs;
        params.zoom = this.zoom;
        params.x = this.centerX;
        params.y = this.centerY;
        params.usePosition = true;

        MapEditorViewModel.apply(this, [params]);
    };
    ko.components.register('map-widget', {
        viewModel: viewModel,
        template: {
            require: 'text!templates/views/components/widgets/map.htm'
        }
    });
    return viewModel;
});
<commit_msg>nit #6729<commit_after>define([
    'arches',
    'underscore',
    'knockout',
    'knockout-mapping',
    'viewmodels/widget',
    'viewmodels/map-editor',
    'bindings/chosen',
    'bindings/codemirror',
    'codemirror/mode/javascript/javascript',
    'select2',
    'bindings/select2v4',
    'bindings/fadeVisible',
    'bindings/mapbox-gl',
    'bindings/chosen',
    'bindings/color-picker',
    'geocoder-templates'
], function(arches, _, ko, koMapping, WidgetViewModel, MapEditorViewModel) {
    var viewModel = function(params) {
        this.context = params.type;
        this.summaryDetails = [];
        this.defaultValueOptions = [
            {
                "name": "",
                "defaultOptionid": 0,
                "value": ""
            },
            {
                "name": "Drawn Location",
                "defaultOptionid": 1,
                "value": "Drawn Location"
            },
            {
                "name": "Current Device Location",
                "defaultOptionid": 2,
                "value": "Current Device Location"
            }
        ];

        params.configKeys = [
            'basemap',
            'overlayConfigs',
            'zoom',
            'centerX',
            'centerY',
            'geometryTypes',
            'defaultValueType',
            'defaultValue'
        ];

        WidgetViewModel.apply(this, [params]);

        this.geometryTypeList = ko.computed({
            read: function() {
                var geometryTypes = this.geometryTypes() || [];
                return geometryTypes.map(function(type) {
                    return ko.unwrap(type.id);
                });
            },
            write: function(value) {
                this.geometryTypes(value.map(function(type) {
                    return {
                        id: type,
                        text: type
                    };
                }));
            },
            owner: this
        });

        this.displayValue = ko.computed(function() {
            var value = koMapping.toJS(this.value);
            if (!value || !value.features) {
                return 0;
            }
            return value.features.length;
        }, this);

        if (params.widget) params.widgets = [params.widget];

        if (ko.unwrap(this.value) !== null) {
            this.summaryDetails = koMapping.toJS(this.value).features || [];
        }

        if (this.centerX() == 0 && this.centerY() == 0 && this.zoom() == 0) {
            this.centerX(arches.mapDefaultX);
            this.centerY(arches.mapDefaultY);
            this.zoom(arches.mapDefaultZoom);
        }

        params.basemap = this.basemap;
        params.overlayConfigs = this.overlayConfigs;
        params.zoom = this.zoom;
        params.x = this.centerX;
        params.y = this.centerY;
        params.usePosition = true;

        MapEditorViewModel.apply(this, [params]);
    };
    ko.components.register('map-widget', {
        viewModel: viewModel,
        template: {
            require: 'text!templates/views/components/widgets/map.htm'
        }
    });
    return viewModel;
});
<|endoftext|>


<commit_before>import React from 'react';
import Panel from 'react-bootstrap/lib/Panel';
import Immutable from 'seamless-immutable';

import WrappedText from 'shared/wrapped-text';
import Resource from 'utils/fixtures/Resource';
import Unit from 'utils/fixtures/Unit';
import { shallowWithIntl } from 'utils/testUtils';
import ResourceInfo from './ResourceInfo';
import ReservationInfo from '../reservation-info';

describe('pages/resource/resource-info/ResourceInfo', () => {
  const defaultProps = {
    isLoggedIn: false,
    resource: Immutable(
      Resource.build({
        description: 'Some description',
        genericTerms: 'some generic terms',
        specificTerms: 'some specific terms',
        maxPricePerHour: '30',
        peopleCapacity: '16',
        type: {
          name: 'workplace',
        },
      })
    ),
    unit: Immutable(Unit.build()),
  };

  function getWrapper(extraProps) {
    return shallowWithIntl(<ResourceInfo {...defaultProps} {...extraProps} />);
  }

  test('renders resource description as WrappedText', () => {
    const wrappedText = getWrapper()
      .find('.app-ResourceInfo__description')
      .find(WrappedText);
    const expectedText = defaultProps.resource.description;

    expect(wrappedText).toHaveLength(1);
    expect(wrappedText.prop('text')).toBe(expectedText);
    expect(wrappedText.prop('openLinksInNewTab')).toBe(true);
  });

  test('renders panels with correct header', () => {
    const panels = getWrapper().find(Panel);

    expect(panels).toHaveLength(2);
    expect(panels.at(0).prop('header')).toBe('ResourceInfo.reservationTitle');
    expect(panels.at(1).prop('header')).toBe('ResourceInfo.additionalInfoTitle');
  });

  test('renders ReservationInfo with correct props', () => {
    const reservationInfo = getWrapper().find(ReservationInfo);
    expect(reservationInfo).toHaveLength(1);
    expect(reservationInfo.prop('isLoggedIn')).toBe(defaultProps.isLoggedIn);
    expect(reservationInfo.prop('resource')).toEqual(defaultProps.resource);
  });

  test('renders the unit name and address', () => {
    const unit = Unit.build({
      addressZip: '99999',
      municipality: 'helsinki',
      name: 'Unit name',
      streetAddress: 'Test street 12',
    });
    const addressSpan = getWrapper({ unit })
      .find('.app-ResourceInfo__address')
      .find('span');

    expect(addressSpan).toHaveLength(3);
    expect(addressSpan.at(0).text()).toBe(unit.name);
    expect(addressSpan.at(1).text()).toBe(unit.streetAddress);
    expect(addressSpan.at(2).text()).toBe('99999 Helsinki');
  });

  test('renders web address', () => {
    const unit = Unit.build({
      id: 'abc:123',
      addressZip: '99999',
      municipality: 'helsinki',
      name: 'Unit name',
      streetAddress: 'Test street 12',
      wwwUrl: 'some-url',
    });
    const link = getWrapper({ unit })
      .find('.app-ResourceInfo__www')
      .find('a');

    expect(link).toHaveLength(1);
    expect(link.prop('href')).toBe(unit.wwwUrl);
    expect(link.prop('target')).toBe('_blank');
  });

  test('renders service map link', () => {
    const unit = Unit.build({
      id: 'abc:123',
      addressZip: '99999',
      municipality: 'helsinki',
      name: 'Unit name',
      streetAddress: 'Test street 12',
      wwwUrl: 'some-url',
    });
    const expected = 'https://palvelukartta.hel.fi/unit/123#!route-details';
    const link = getWrapper({ unit })
      .find('.app-ResourceInfo__servicemap')
      .find('a');

    expect(link).toHaveLength(1);
    expect(link.prop('href')).toBe(expected);
    expect(link.prop('target')).toBe('_blank');
  });

  test('does not render service map link if unit empty', () => {
    const link = getWrapper({ unit: {} })
      .find('.app-ResourceInfo__servicemap')
      .find('a');

    expect(link).toHaveLength(0);
  });
});
<commit_msg>remove deprecated props<commit_after>import React from 'react';
import Panel from 'react-bootstrap/lib/Panel';
import Immutable from 'seamless-immutable';

import WrappedText from 'shared/wrapped-text';
import Resource from 'utils/fixtures/Resource';
import Unit from 'utils/fixtures/Unit';
import { shallowWithIntl } from 'utils/testUtils';
import ResourceInfo from './ResourceInfo';
import ReservationInfo from '../reservation-info';

describe('pages/resource/resource-info/ResourceInfo', () => {
  const defaultProps = {
    isLoggedIn: false,
    resource: Immutable(
      Resource.build({
        description: 'Some description',
        genericTerms: 'some generic terms',
        specificTerms: 'some specific terms',
        maxPricePerHour: '30',
        peopleCapacity: '16',
        type: {
          name: 'workplace',
        },
      })
    ),
    unit: Immutable(Unit.build()),
  };

  function getWrapper(extraProps) {
    return shallowWithIntl(<ResourceInfo {...defaultProps} {...extraProps} />);
  }

  test('renders resource description as WrappedText', () => {
    const wrappedText = getWrapper()
      .find('.app-ResourceInfo__description')
      .find(WrappedText);
    const expectedText = defaultProps.resource.description;

    expect(wrappedText).toHaveLength(1);
    expect(wrappedText.prop('text')).toBe(expectedText);
    expect(wrappedText.prop('openLinksInNewTab')).toBe(true);
  });

  test('renders panels with correct header text', () => {
    const panels = getWrapper().find(Panel);

    expect(panels).toHaveLength(2);
    expect(panels.at(0).prop('header')).toBe('ResourceInfo.reservationTitle');
    expect(panels.at(1).prop('header')).toBe('ResourceInfo.additionalInfoTitle');
  });

  test('renders ReservationInfo with correct props', () => {
    const reservationInfo = getWrapper().find(ReservationInfo);
    expect(reservationInfo).toHaveLength(1);
    expect(reservationInfo.prop('isLoggedIn')).toBe(defaultProps.isLoggedIn);
    expect(reservationInfo.prop('resource')).toEqual(defaultProps.resource);
  });

  test('renders the unit name and address', () => {
    const unit = Unit.build({
      addressZip: '99999',
      municipality: 'helsinki',
      name: 'Unit name',
      streetAddress: 'Test street 12',
    });
    const addressSpan = getWrapper({ unit })
      .find('.app-ResourceInfo__address')
      .find('span');

    expect(addressSpan).toHaveLength(3);
    expect(addressSpan.at(0).text()).toBe(unit.name);
    expect(addressSpan.at(1).text()).toBe(unit.streetAddress);
    expect(addressSpan.at(2).text()).toBe('99999 Helsinki');
  });

  test('renders web address', () => {
    const unit = Unit.build({
      id: 'abc:123',
      addressZip: '99999',
      municipality: 'helsinki',
      name: 'Unit name',
      streetAddress: 'Test street 12',
      wwwUrl: 'some-url',
    });
    const link = getWrapper({ unit })
      .find('.app-ResourceInfo__www')
      .find('a');

    expect(link).toHaveLength(1);
    expect(link.prop('href')).toBe(unit.wwwUrl);
    expect(link.prop('target')).toBe('_blank');
  });

  test('renders service map link', () => {
    const unit = Unit.build({
      id: 'abc:123',
      addressZip: '99999',
      municipality: 'helsinki',
      name: 'Unit name',
      streetAddress: 'Test street 12',
      wwwUrl: 'some-url',
    });
    const expected = 'https://palvelukartta.hel.fi/unit/123#!route-details';
    const link = getWrapper({ unit })
      .find('.app-ResourceInfo__servicemap')
      .find('a');

    expect(link).toHaveLength(1);
    expect(link.prop('href')).toBe(expected);
    expect(link.prop('target')).toBe('_blank');
  });

  test('does not render service map link if unit empty', () => {
    const link = getWrapper({ unit: {} })
      .find('.app-ResourceInfo__servicemap')
      .find('a');

    expect(link).toHaveLength(0);
  });
});
<|endoftext|>


<commit_before>;(function($, $$){

	if( !$ ){ return } // no jquery => don't need this

	// allow calls on a jQuery selector by proxying calls to $.cytoscape
	// e.g. $("#foo").cytoscape(options) => $.cytoscape(options) on #foo
	$.fn.cytoscape = function(opts){
		var $this = $(this);

		// get object
		if( opts === "get" ){
			var reg = $$.getRegistrationForInstance( $this[0] );
			return reg.cy;
		}

		// bind to ready
		else if( $$.is.fn(opts) ){
			//debugger;

			var ready = opts;
			var domEle = $this[0];
			var reg = $$.getRegistrationForInstance( domEle );

			if( !reg ){
				reg = $$.registerInstance( domEle );
			}

			if( reg && reg.cy && reg.cy.ready() ){
				// already ready so just trigger now
				reg.cy.trigger("ready", [], ready);

			} else {
				// not yet ready, so add to readies list

				reg.readies.push( ready );
			}

		}

		// proxy to create instance
		else if( $$.is.plainObject(opts) ){
			return $this.each(function(){
				var options = $.extend({}, opts, {
					container: $(this)[0]
				});

				cytoscape(options);
			});
		}

		// proxy a function call
		else {
			var domEle = $this[0];
			var rets = [];
			var args = [];
			for(var i = 1; i < arguments.length; i++){
				args[i - 1] = arguments[i];
			}

			$this.each(function(){
				var reg = $$.getRegistrationForInstance( domEle );
				var cy = reg.cy;
				var fnName = opts;

				if( cy && $$.is.fn( cy[fnName] ) ){
					var ret = cy[fnName].apply(cy, args);
					rets.push(ret);
				}
			});

			// if only one instance, don't need to return array
			if( rets.length === 1 ){
				rets = rets[0];
			} else if( rets.length == 0 ){
				rets = $(this);
			}

			return rets;
		}

	};

	// allow access to the global cytoscape object under jquery for legacy reasons
	$.cytoscape = cytoscape;

	// use short alias (cy) if not already defined
	if( $.fn.cy == null && $.cy == null ){
		$.fn.cy = $.fn.cytoscape;
		$.cy = $.cytoscape;
	}

	// allow jquery mobile style init
	$(function(){ // on ready

		function parse($this, attr){
			var str = $this.attr( attr );
			var ret;

			try {
				ret = $.parseJSON( attr );
			} catch(e){
				ret = undefined;
			}
		}

		$('[data-role="cytoscape"]').each(function(){
			var $this = $(this);

			// NB core init options must be added here if they are going to be supported
			// with jquery-mobile-like syntax
			var options = {
				showOverlay: parse($this, 'data-show-overlay'),
				layout: parse($this, 'data-layout'),
				zoom: parse($this, 'data-zoom'),
				minZoom: parse($this, 'data-min-zoom'),
				maxZoom: parse($this, 'data-max-zoom'),
				pan: parse($this, 'data-pan'),
				renderer: parse($this, 'data-renderer'),
				style: parse($this, 'data-style'),
				elements: parse($this, 'data-elements')
			};

			$this.cytoscape( options );
		});
	});

})(typeof jQuery !== 'undefined' ? jQuery : null , cytoscape);
<commit_msg>remove jquery mobile style init; too error prone for the kinds of json that would need to be passed via html attrs; close #317<commit_after>;(function($, $$){

	if( !$ ){ return } // no jquery => don't need this

	// allow calls on a jQuery selector by proxying calls to $.cytoscape
	// e.g. $("#foo").cytoscape(options) => $.cytoscape(options) on #foo
	$.fn.cytoscape = function(opts){
		var $this = $(this);

		// get object
		if( opts === "get" ){
			var reg = $$.getRegistrationForInstance( $this[0] );
			return reg.cy;
		}

		// bind to ready
		else if( $$.is.fn(opts) ){
			//debugger;

			var ready = opts;
			var domEle = $this[0];
			var reg = $$.getRegistrationForInstance( domEle );

			if( !reg ){
				reg = $$.registerInstance( domEle );
			}

			if( reg && reg.cy && reg.cy.ready() ){
				// already ready so just trigger now
				reg.cy.trigger("ready", [], ready);

			} else {
				// not yet ready, so add to readies list

				reg.readies.push( ready );
			}

		}

		// proxy to create instance
		else if( $$.is.plainObject(opts) ){
			return $this.each(function(){
				var options = $.extend({}, opts, {
					container: $(this)[0]
				});

				cytoscape(options);
			});
		}

		// proxy a function call
		else {
			var domEle = $this[0];
			var rets = [];
			var args = [];
			for(var i = 1; i < arguments.length; i++){
				args[i - 1] = arguments[i];
			}

			$this.each(function(){
				var reg = $$.getRegistrationForInstance( domEle );
				var cy = reg.cy;
				var fnName = opts;

				if( cy && $$.is.fn( cy[fnName] ) ){
					var ret = cy[fnName].apply(cy, args);
					rets.push(ret);
				}
			});

			// if only one instance, don't need to return array
			if( rets.length === 1 ){
				rets = rets[0];
			} else if( rets.length == 0 ){
				rets = $(this);
			}

			return rets;
		}

	};

	// allow access to the global cytoscape object under jquery for legacy reasons
	$.cytoscape = cytoscape;

	// use short alias (cy) if not already defined
	if( $.fn.cy == null && $.cy == null ){
		$.fn.cy = $.fn.cytoscape;
		$.cy = $.cytoscape;
	}

})(typeof jQuery !== 'undefined' ? jQuery : null , cytoscape);
<|endoftext|>


<commit_before>/* Javascript for StaffGradedAssignmentXBlock. */
function StaffGradedAssignmentXBlock(runtime, element) {
    function xblock($, _) {
        var uploadUrl = runtime.handlerUrl(element, 'upload_assignment');
        var downloadUrl = runtime.handlerUrl(element, 'download_assignment');
        var annotatedUrl = runtime.handlerUrl(element, 'download_annotated');
        var getStaffGradingUrl = runtime.handlerUrl(element, 'get_staff_grading_data');
        var staffDownloadUrl = runtime.handlerUrl(element, 'staff_download');
        var staffAnnotatedUrl = runtime.handlerUrl(element, 'staff_download_annotated');
        var staffUploadUrl = runtime.handlerUrl(element, 'staff_upload_annotated');
        var enterGradeUrl = runtime.handlerUrl(element, 'enter_grade');
        var removeGradeUrl = runtime.handlerUrl(element, 'remove_grade');
        var template = _.template($(element).find("#sga-tmpl").text());
        var gradingTemplate;

        function render(state) {
            // Add download urls to template context
            state.downloadUrl = downloadUrl;
            state.annotatedUrl = annotatedUrl;
            state.error = state.error ? state.error : false;

            // Render template
            var content = $(element).find("#sga-content").html(template(state));

            // Set up file upload
            $(content).find(".fileupload").fileupload({
                url: uploadUrl,
                add: function(e, data) {
                    var do_upload = $(content).find(".upload").html('');
                    $('<button/>')
                        .text('Upload ' + data.files[0].name)
                        .appendTo(do_upload)
                        .click(function() {
                            do_upload.text("Uploading...");
                            data.submit();
                        });
                },
                progressall: function(e, data) {
                    var percent = parseInt(data.loaded / data.total * 100, 10);
                    $(content).find(".upload").text(
                        "Uploading... " + percent + "%");
                },
                done: function(e, data) {
                    /* When you try to upload a file that exceeds Django's size
                     * limit for file uploads, Django helpfully returns a 200 OK
                     * response with a JSON payload of the form:
                     *
                     *   {'success': '<error message'}
                     *
                     * This is perfectly reasonable.  Unimpeachable even.  Makes
                     * perfect sense.
                     */
                    if (data.result.success !== undefined) {
                        // Actually, this is an error
                        state.error = data.result.success;
                        render(state);
                    }
                    else {
                        render(data.result);
                    }
                }
            });
        }

        function renderStaffGrading(data) {
            $(".grade-modal").hide();

            // Add download urls to template context
            data.downloadUrl = staffDownloadUrl;
            data.annotatedUrl = staffAnnotatedUrl;

            // Render template
            $(element).find("#grade-info")
                .html(gradingTemplate(data))
                .data(data);

            // Map data to table rows
            data.assignments.map(function(assignment) {
                $(element).find("#grade-info #row-" + assignment.module_id)
                    .data(assignment);
            });

            // Set up grade entry modal
            $(element).find(".enter-grade-button")
                .leanModal({closeButton: "#enter-grade-cancel"})
                .on("click", handleGradeEntry);

            // Set up annotated file upload
            $(element).find("#grade-info .fileupload").each(function() {
                var row = $(this).parents("tr");
                var url = staffUploadUrl + "?module_id=" + row.data("module_id");
                $(this).fileupload({
                    url: url,
                    /*
                    add: function(e, data) {
                        var upload = $(this).parents(".upload").html('');
                        $('<button/>')
                            .text('Upload ' + data.files[0].name)
                            .appendTo(upload)
                            .click(function() {
                                upload.text("Uploading...");
                                data.submit();
                            });
                    },
                    */
                    progressall: function(e, data) {
                        var percent = parseInt(data.loaded / data.total * 100, 10);
                        row.find(".upload").text("Uploading... " + percent + "%");
                    },
                    done: function(e, data) {
                        // Add a time delay so user will notice upload finishing
                        // for small files
                        setTimeout(
                            function() { renderStaffGrading(data.result); },
                            3000)
                    }
                });
            });
        }

        /* Click event handler for "enter grade" */
        function handleGradeEntry() {
            var row = $(this).parents("tr");
            var form = $(element).find("#enter-grade-form");
            $(element).find("#student-name").text(row.data("fullname"));
            form.find("#module_id-input").val(row.data("module_id"));
            form.find("#grade-input").val(row.data("score"));
            form.find("#comment-input").text(row.data("comment"));
            form.off("submit").on("submit", function(event) {
                var max_score = row.parents("#grade-info").data("max_score");
                var score = Number(form.find("#grade-input").val());
                event.preventDefault();
                if (isNaN(score)) {
                    form.find(".error").html("
Grade must be a number.");
                }
                else if (score < 0) {
                    form.find(".error").html("
Grade must be positive.");
                }
                else if (score > max_score) {
                    form.find(".error").html("
Maximum score is " + max_score);
                }
                else {
                    // No errors
                    $.post(enterGradeUrl, form.serialize())
                        .success(renderStaffGrading);
                }
            });
            form.find("#remove-grade").on("click", function() {
                var url = removeGradeUrl + "?module_id=" + row.data("module_id");
                $.get(url).success(renderStaffGrading);
            });
        }

        $(function($) { // onLoad
            var block = $(element).find(".sga-block");
            var state = block.attr("data-state");
            render(JSON.parse(state));

            var is_staff = block.attr("data-staff") == "True";
            if (is_staff) {
                gradingTemplate = _.template(
                    $(element).find("#sga-grading-tmpl").text());
                block.find("#grade-submissions-button")
                    .leanModal()
                    .on("click", function() {
                        $.ajax({
                            url: getStaffGradingUrl,
                            success: renderStaffGrading
                        });
                    });
            }
        });
    }

    if (require === undefined) {
        /**
         * The LMS does not use require.js (although it loads it...) and
         * does not already load jquery.fileupload.  (It looks like it uses
         * jquery.ajaxfileupload instead.  But our XBlock uses
         * jquery.fileupload.
         */
        function loadjs(url) {
            $("


<commit_before>angular.module('dogfeed', ['ngRSS', 'ngSockethubClient', 'ngRemoteStorage']).

/**
 * routes
 */
config(['$routeProvider',
function ($routeProvider) {
  $routeProvider.
    when('/', {
      templateUrl: "feeds.html"
    }).
    otherwise({
      redirectTo: "/"
    });
}]).

run(['SockethubSettings', 'SH', '$rootScope', 'RS',
function (settings, SH, $rootScope, RS) {
  var default_cfg = {
    host: 'silverbucket.net',
    port: 443,
    path: '/sockethub',
    tls: true,
    secret: '1234567890'
  };

  function sockethubConnect(cfg) {
    console.log('USING SH CONFIG: ', cfg);
    //$rootScope.$broadcast('message', {type: 'clear'});
    // connect to sockethub and register
    if (settings.save('conn', cfg)) {
      $rootScope.$broadcast('message', {
            message: 'attempting to connect to sockethub',
            type: 'info',
            timeout: false
      });
      SH.connect({register: true}).then(function () {
        //console.log('connected to sockethub');
        $rootScope.$broadcast('message', {
              message: 'connected to sockethub',
              type: 'success',
              timeout: true
        });
      }, function (err) {
        console.log('error connecting to sockethub: ', err);
        $rootScope.$broadcast('SockethubConnectFailed', {message: err});
      });
    } else {
      $rootScope.$broadcast('message', {
            message: 'failed saving sockethub credentials',
            type: 'success',
            timeout: true
      });
    }
  }

  RS.call('sockethub', 'getConfig', ['dogfeed'], 3000).then(function (c) {
    console.log('GOT SH CONFIG: ', c);
    if ((typeof c !== 'object') || (typeof c.host !== 'string')) {
      //cfg = settings.conn;
      c = default_cfg;
    }
    sockethubConnect(c);
  }, function (err) {
    console.log("RS.call error: ",err);
    sockethubConnect(default_cfg);
  });
}]).

/**
 * remoteStorage & sockethub connect
 */
run(['SockethubSettings', 'SH', '$rootScope', 'RS', '$timeout',
function (settings, SH, $rootScope, RS, $timeout) {
  if (!RS.isConnected()) {
    $timeout(function () {
      if (!RS.isConnected()) {
        $rootScope.$broadcast('message', {message: 'remotestorage-connect', timeout: false});
      }
    }, 6000);
  }
}]).

/**
 * emitters
 */
run(['$rootScope',
function ($rootScope) {
  $rootScope.$on('showModalAddFeed', function(event, args) {
    backdrop_setting = true;
    if ((typeof args === 'object') && (typeof args.locked !== 'undefined')) {
      if (args.locked) {
        backdrop_setting = "static";
      }
    }
    $("#modalAddFeed").modal({
      show: true,
      keyboard: true,
      backdrop: backdrop_setting
    });
  });

  $rootScope.$on('closeModalAddFeed', function(event, args) {
    $("#modalAddFeed").modal('hide');
  });
}]).

/**
 * filter: urlEncode
 */
filter('urlEncode', [
function() {
  return function (text, length, end) {
    return encodeURIComponent(escape(text));
  };
}]).

filter('fromNow', [
function() {
  return function(dateString) {
    return new Date(dateString).toDateString(); ///moment(new Date(dateString)).fromNow();
  };
}]).

///////////////////////////////////////////////////////////////////////////
//
// CONTROLLERS
//
///////////////////////////////////////////////////////////////////////////

/**
 * controller: titlebarCtrl
 */
controller('titlebarCtrl',
['$scope', '$rootScope', 'SockethubSettings', 'RS',
function ($scope, $rootScope, settings, RS) {
  $scope.addFeed = function () {
    $rootScope.$broadcast('showModalAddFeed', {locked: false});
  };
  $scope.sockethubSettings = function () {
    $rootScope.$broadcast('showModalSockethubSettings', {locked: false});
  };

  $scope.$watch('settings.connected', function (newVal, oldVal) {
    if (settings.connected) {
      settings.conn.port = Number(settings.conn.port);
      RS.call('sockethub', 'writeConfig', [settings.conn]).then(function () {
        console.log("Sockethub config saved to remoteStorage");
      }, function (err) {
        console.log('Failed saving Sockethub config to remoteStorage: ', err);
      });
    }
  });
}]).

///////////////////////////////////////////////////////////////////////////
//
// DIRECTIVES
//
///////////////////////////////////////////////////////////////////////////

/**
 * directive: message
 */
directive('message',
['$rootScope', '$timeout',
function ($rootScope, $timeout) {
  return {
    restrict: 'A',
    template: '
'+
              '  {{m.title}} ' +
              '  {{m.message}}' +
              '
',
    link: function (scope) {
      scope.haveMessage = false;
      scope.m = {type: '', title: '', message: ''};

      var presets = {
        'remotestorage-connect': {
          type: 'warning',
          title : 'Connect to remoteStorage',
          message: 'No changes will be saved, you must sign in to remoteStorage for persistence'
        },
        'sockethub-config': {
          type: 'warning',
          title: 'Sockethub configuration needed',
          message: 'You must fill in your Sockethub connection details'
        },
        'sockethub-connect': {
          type: 'danger',
          title: 'Sockethub connection error',
          message: 'Unable to connect to Sockethub please check your configuration and try again'
        },
        'sockethub-register': {
          type: 'danger',
          title: 'Sockethub registration problem',
          message: 'We were unable to register with your Sockethub instance'
        },
        'xmpp-connect': {
          type: 'danger',
          title: 'XMPP connection failed',
          message: 'There was a problem connecting to the XMPP server, please verify you settings'
        },
        'unknown': {
          type: 'danger',
          title: 'An unknown error has occurred',
          message: ''
        }
      };

      $rootScope.$on('message', function (event, e) {
        //console.log('message event: ', e);

        var timeout = (typeof e.timeout === 'boolean') ? e.timeout : true;
        scope.haveMessage = false;

        if (typeof e === 'undefined') {
          e = 'no error specified';
        }

        if (e.type === 'clear') {
          scope.haveMessage = false;
          scope.m = {type: '', title: '', message: ''};
          return;
        } else if (typeof presets[e.message] !== 'undefined') {
          scope.m = presets[e.message];
        } else if (typeof e.message === 'string') {
          if (e.type === 'success') {
            scope.m.title = 'Success';
          } else if (e.type === 'info') {
            scope.m.title = 'Info';
          } else {
            scope.m.title = "Danger!";
            e.type = 'danger';
          }
          scope.m.message = e.message;
          scope.m.type = e.type;
        }
        scope.m.timeout = timeout;
        console.log('done processing: ', scope.m);
        scope.haveMessage = true;
        if (timeout) {
          $timeout(function () {
            if (scope.m.timeout) {
              scope.haveMessage = false;
              scope.m = {type: '', title: '', message: '', timeout: true};
            }
          }, 4000);
        }
      });
    }
  };
}]);

<commit_msg>some logging changes and set the defaults to localhost for testing<commit_after>angular.module('dogfeed', ['ngRSS', 'ngSockethubClient', 'ngRemoteStorage']).

/**
 * routes
 */
config(['$routeProvider',
function ($routeProvider) {
  $routeProvider.
    when('/', {
      templateUrl: "feeds.html"
    }).
    otherwise({
      redirectTo: "/"
    });
}]).

run(['SockethubSettings', 'SH', '$rootScope', 'RS',
function (settings, SH, $rootScope, RS) {
  var default_cfg = {
    host: 'localhost',
    port: 10550,
    path: '/sockethub',
    tls: false,
    secret: '1234567890'
  };

  function sockethubConnect(cfg) {
    console.log('USING SH CONFIG: ', cfg);
    //$rootScope.$broadcast('message', {type: 'clear'});
    // connect to sockethub and register
    if (settings.save('conn', cfg)) {
      $rootScope.$broadcast('message', {
            message: 'attempting to connect to sockethub',
            type: 'info',
            timeout: false
      });
      SH.connect({register: true}).then(function () {
        //console.log('connected to sockethub');
        $rootScope.$broadcast('message', {
              message: 'connected to sockethub',
              type: 'success',
              timeout: true
        });
      }, function (err) {
        console.log('error connecting to sockethub: ', err);
        $rootScope.$broadcast('SockethubConnectFailed', {message: err});
      });
    } else {
      $rootScope.$broadcast('message', {
            message: 'failed saving sockethub credentials',
            type: 'success',
            timeout: true
      });
    }
  }

  RS.call('sockethub', 'getConfig', ['dogfeed'], 3000).then(function (c) {
    console.log('GOT SH CONFIG: ', c);
    if ((typeof c !== 'object') || (typeof c.host !== 'string')) {
      //cfg = settings.conn;
      c = default_cfg;
    }
    sockethubConnect(c);
  }, function (err) {
    console.log("RS.call error: ",err);
    sockethubConnect(default_cfg);
  });
}]).

/**
 * remoteStorage & sockethub connect
 */
run(['SockethubSettings', 'SH', '$rootScope', 'RS', '$timeout',
function (settings, SH, $rootScope, RS, $timeout) {
  if (!RS.isConnected()) {
    $timeout(function () {
      if (!RS.isConnected()) {
        $rootScope.$broadcast('message', {message: 'remotestorage-connect', timeout: false});
      }
    }, 6000);
  }
}]).

/**
 * emitters
 */
run(['$rootScope',
function ($rootScope) {
  $rootScope.$on('showModalAddFeed', function(event, args) {
    backdrop_setting = true;
    if ((typeof args === 'object') && (typeof args.locked !== 'undefined')) {
      if (args.locked) {
        backdrop_setting = "static";
      }
    }
    $("#modalAddFeed").modal({
      show: true,
      keyboard: true,
      backdrop: backdrop_setting
    });
  });

  $rootScope.$on('closeModalAddFeed', function(event, args) {
    $("#modalAddFeed").modal('hide');
  });
}]).

/**
 * filter: urlEncode
 */
filter('urlEncode', [
function() {
  return function (text, length, end) {
    return encodeURIComponent(escape(text));
  };
}]).

filter('fromNow', [
function() {
  return function(dateString) {
    return new Date(dateString).toDateString(); ///moment(new Date(dateString)).fromNow();
  };
}]).

///////////////////////////////////////////////////////////////////////////
//
// CONTROLLERS
//
///////////////////////////////////////////////////////////////////////////

/**
 * controller: titlebarCtrl
 */
controller('titlebarCtrl',
['$scope', '$rootScope', 'SockethubSettings', 'RS',
function ($scope, $rootScope, settings, RS) {
  $scope.addFeed = function () {
    $rootScope.$broadcast('showModalAddFeed', {locked: false});
  };
  $scope.sockethubSettings = function () {
    $rootScope.$broadcast('showModalSockethubSettings', {locked: false});
  };

  $scope.$watch('settings.connected', function (newVal, oldVal) {
    if (settings.connected) {
      settings.conn.port = Number(settings.conn.port);
      RS.call('sockethub', 'writeConfig', [settings.conn]).then(function () {
        console.log("Sockethub config saved to remoteStorage");
      }, function (err) {
        console.log('Failed saving Sockethub config to remoteStorage: ', err);
      });
    }
  });
}]).

///////////////////////////////////////////////////////////////////////////
//
// DIRECTIVES
//
///////////////////////////////////////////////////////////////////////////

/**
 * directive: message
 */
directive('message',
['$rootScope', '$timeout',
function ($rootScope, $timeout) {
  return {
    restrict: 'A',
    template: '
'+
              '  {{m.title}} ' +
              '  {{m.message}}' +
              '
',
    link: function (scope) {
      scope.haveMessage = false;
      scope.m = {type: '', title: '', message: ''};

      var presets = {
        'remotestorage-connect': {
          type: 'warning',
          title : 'Connect to remoteStorage',
          message: 'if you want your changes to persist'
        },
        'sockethub-config': {
          type: 'warning',
          title: 'Sockethub configuration needed',
          message: 'You must fill in your Sockethub connection details'
        },
        'sockethub-connect': {
          type: 'danger',
          title: 'Sockethub connection error',
          message: 'Unable to connect to Sockethub please check your configuration and try again'
        },
        'sockethub-register': {
          type: 'danger',
          title: 'Sockethub registration problem',
          message: 'We were unable to register with your Sockethub instance'
        },
        'xmpp-connect': {
          type: 'danger',
          title: 'XMPP connection failed',
          message: 'There was a problem connecting to the XMPP server, please verify you settings'
        },
        'unknown': {
          type: 'danger',
          title: 'An unknown error has occurred',
          message: ''
        }
      };

      $rootScope.$on('message', function (event, e) {
        //console.log('message event: ', e);

        var timeout = (typeof e.timeout === 'boolean') ? e.timeout : true;
        scope.haveMessage = false;

        if (typeof e === 'undefined') {
          e = 'no error specified';
        }

        if (e.type === 'clear') {
          scope.haveMessage = false;
          scope.m = {type: '', title: '', message: ''};
          return;
        } else if (typeof presets[e.message] !== 'undefined') {
          scope.m = presets[e.message];
        } else if (typeof e.message === 'string') {
          if (e.type === 'success') {
            scope.m.title = 'Success';
          } else if (e.type === 'info') {
            scope.m.title = 'Info';
          } else {
            scope.m.title = "Error";
            e.type = 'danger';
          }
          scope.m.message = e.message;
          scope.m.type = e.type;
        }
        scope.m.timeout = timeout;
        console.log('info message event set: ', scope.m);
        scope.haveMessage = true;
        if (timeout) {
          $timeout(function () {
            if (scope.m.timeout) {
              scope.haveMessage = false;
              scope.m = {type: '', title: '', message: '', timeout: true};
            }
          }, 4000);
        }
      });
    }
  };
}]);

<|endoftext|>


<commit_before>function extend(subClass, superClass) {
    var F = function() {};
    F.prototype = superClass.prototype;
    subClass.prototype = new F();
    subClass.prototype.constructor = subClass;
    subClass.superclass = superClass.prototype;
    if(superClass.prototype.constructor == Object.prototype.constructor) {
        superClass.prototype.constructor = superClass;
    }
}

function Element(args) {
    if (arguments.length) {
        this.getready(args);
    }
}

Element.prototype.getready = function (args) {

    this.ID = args.ID;

    //By default, we want to be notified if some event occurs.
    this.isClickable = args.isClickable || true;

    // These are arrays of 2
    this.xOrigin = args.left;
    this.yOrigin = args.top;

    // This is the bounding box. Element has no dimension.
    this.width = args.width;
    this.height = args.height;

    // Element never draws itself by default
    this.drawItself = args.drawItself || false;

    // Element is visible by default
    this.isVisible = args.isVisible || true;

    // These are to be set later
    this.values = {};

    // Set this if the element needs to preserve its background.
    this.preserveBg = args.preserveBg || false;

    if (this.preserveBg === true) {
        // Set this if the element has to save the background now.
        this.backgroundSavePending = true;
    }

    // Specific parameters of the object, to be passed to the wrapper
    this.objParms = args.objParms;

    // See if there is a callback to call when the value is set
    if (args !== undefined) {
        if (typeof (args.onValueSet) === "function") {
            this.onValueSet = args.onValueSet;
        }
    }

};

// Private function
Element.prototype.isInROI = function (x, y) {
    // This is the abstract class.
    return false;
};

Element.prototype.getValues = function () {
    var tempArray = [],
        i;
    for (i in this.values) {
        if (this.values.hasOwnProperty(i)) {
            tempArray.push(i);
        }
    }
    // Returns the keys.
    return tempArray;
};

Element.prototype.getXCoord = function () {
    return this.xOrigin;
};

Element.prototype.getYCoord = function () {
    return this.yOrigin;
};

Element.prototype.getWidth = function () {
    return this.width;
};

Element.prototype.getHeight = function () {
    return this.height;
};

Element.prototype.getValue = function (slot) {
    if (this.values[slot] === undefined) {
        throw new Error("Slot " + slot + " not present or value undefined");
    }
    else {
        return this.values[slot];
    }
};

// Setters
Element.prototype.setValue = function (slot, value) {

    var temp_value = value;

    if (this.values[slot] === undefined) {
        throw new Error("Slot " + slot + " not present or value undefined");
    }

    if (temp_value === this.values[slot]) {
        // Nothing to do.
        return;
    }

    this.values[slot] = temp_value;

    // If the element needs to be refreshed, refresh it now.
    if (this.drawItself === true) {
        this.refresh();
    }

    // Finally, call the callback if there's one.
    if (typeof (this.onValueSet) === "function") {
        this.onValueSet (slot, this.values[slot], this.ID);
    }

};

//TODO this should be changed in isListening, for example
Element.prototype.setClickable = function (isClickable) {
     if (typeof isClickable === "boolean") {
        this.isClickable = isClickable;
     }
};

Element.prototype.getClickable = function () {
    return this.isClickable;
};

Element.prototype.setDrawsItself = function (drawItself) {
    if (typeof drawItself === "boolean") {
        this.drawItself = drawItself;
    }
};

Element.prototype.setTainted = function (tainted) {
    if (typeof tainted === "boolean") {
        this.backgroundSavePending = tainted;
    }
}

// Refresh. This is the basic action.
Element.prototype.refresh = function (drawPrimitive) {

    if (this.preserveBg === true) {
        if (this.backgroundSavePending === true) {
            drawPrimitive.saveBackground (this.xOrigin, this.yOrigin, this.width, this.height);
            this.backgroundSavePending = false;
        }

        else {
            // We want drawClass to refresh the saved background.
            drawPrimitive.restoreBackground();
        }
    }
};

Element.prototype.getName = function () {
    return this.name;
};

Element.prototype.setDrawClass = function (drawClass) {
    this.drawClass = drawClass;
};

Element.prototype.setVisible = function (isVisible) {
    if (typeof isVisible === "boolean") {
        this.isVisible = isVisible;
    }
}

Element.prototype.getVisible = function () {
    return this.isVisible;
}

Element.prototype.onMouseMove = function (x,y) {
    return undefined;
};

Element.prototype.onMouseDown = function (x,y) {
    return undefined;
};

Element.prototype.onMouseUp = function (x,y) {
    return undefined;
};

Element.prototype.setGraphicWrapper = function (wrapper) {
    this.wrapper = wrapper;
}
<commit_msg>Return ID where name was returned.<commit_after>function extend(subClass, superClass) {
    var F = function() {};
    F.prototype = superClass.prototype;
    subClass.prototype = new F();
    subClass.prototype.constructor = subClass;
    subClass.superclass = superClass.prototype;
    if(superClass.prototype.constructor == Object.prototype.constructor) {
        superClass.prototype.constructor = superClass;
    }
}

function Element(args) {
    if (arguments.length) {
        this.getready(args);
    }
}

Element.prototype.getready = function (args) {

    this.ID = args.ID;

    //By default, we want to be notified if some event occurs.
    this.isClickable = args.isClickable || true;

    // These are arrays of 2
    this.xOrigin = args.left;
    this.yOrigin = args.top;

    // This is the bounding box. Element has no dimension.
    this.width = args.width;
    this.height = args.height;

    // Element never draws itself by default
    this.drawItself = args.drawItself || false;

    // Element is visible by default
    this.isVisible = args.isVisible || true;

    // These are to be set later
    this.values = {};

    // Set this if the element needs to preserve its background.
    this.preserveBg = args.preserveBg || false;

    if (this.preserveBg === true) {
        // Set this if the element has to save the background now.
        this.backgroundSavePending = true;
    }

    // Specific parameters of the object, to be passed to the wrapper
    this.objParms = args.objParms;

    // See if there is a callback to call when the value is set
    if (args !== undefined) {
        if (typeof (args.onValueSet) === "function") {
            this.onValueSet = args.onValueSet;
        }
    }

};

// Private function
Element.prototype.isInROI = function (x, y) {
    // This is the abstract class.
    return false;
};

Element.prototype.getValues = function () {
    var tempArray = [],
        i;
    for (i in this.values) {
        if (this.values.hasOwnProperty(i)) {
            tempArray.push(i);
        }
    }
    // Returns the keys.
    return tempArray;
};

Element.prototype.getXCoord = function () {
    return this.xOrigin;
};

Element.prototype.getYCoord = function () {
    return this.yOrigin;
};

Element.prototype.getWidth = function () {
    return this.width;
};

Element.prototype.getHeight = function () {
    return this.height;
};

Element.prototype.getValue = function (slot) {
    if (this.values[slot] === undefined) {
        throw new Error("Slot " + slot + " not present or value undefined");
    }
    else {
        return this.values[slot];
    }
};

// Setters
Element.prototype.setValue = function (slot, value) {

    var temp_value = value;

    if (this.values[slot] === undefined) {
        throw new Error("Slot " + slot + " not present or value undefined");
    }

    if (temp_value === this.values[slot]) {
        // Nothing to do.
        return;
    }

    this.values[slot] = temp_value;

    // If the element needs to be refreshed, refresh it now.
    if (this.drawItself === true) {
        this.refresh();
    }

    // Finally, call the callback if there's one.
    if (typeof (this.onValueSet) === "function") {
        this.onValueSet (slot, this.values[slot], this.ID);
    }

};

//TODO this should be changed in isListening, for example
Element.prototype.setClickable = function (isClickable) {
     if (typeof isClickable === "boolean") {
        this.isClickable = isClickable;
     }
};

Element.prototype.getClickable = function () {
    return this.isClickable;
};

Element.prototype.setDrawsItself = function (drawItself) {
    if (typeof drawItself === "boolean") {
        this.drawItself = drawItself;
    }
};

Element.prototype.setTainted = function (tainted) {
    if (typeof tainted === "boolean") {
        this.backgroundSavePending = tainted;
    }
}

// Refresh. This is the basic action.
Element.prototype.refresh = function (drawPrimitive) {

    if (this.preserveBg === true) {
        if (this.backgroundSavePending === true) {
            drawPrimitive.saveBackground (this.xOrigin, this.yOrigin, this.width, this.height);
            this.backgroundSavePending = false;
        }

        else {
            // We want drawClass to refresh the saved background.
            drawPrimitive.restoreBackground();
        }
    }
};

Element.prototype.getID = function () {
    return this.ID;
};

Element.prototype.setDrawClass = function (drawClass) {
    this.drawClass = drawClass;
};

Element.prototype.setVisible = function (isVisible) {
    if (typeof isVisible === "boolean") {
        this.isVisible = isVisible;
    }
}

Element.prototype.getVisible = function () {
    return this.isVisible;
}

Element.prototype.onMouseMove = function (x,y) {
    return undefined;
};

Element.prototype.onMouseDown = function (x,y) {
    return undefined;
};

Element.prototype.onMouseUp = function (x,y) {
    return undefined;
};

Element.prototype.setGraphicWrapper = function (wrapper) {
    this.wrapper = wrapper;
}
<|endoftext|>


<commit_before>/*!
 * Dragster - drag'n'drop library v1.1.1
 * https://github.com/sunpietro/dragster
 *
 * Copyright 2015 Piotr Nalepa
 * http://blog.piotrnalepa.pl
 *
 * Released under the MIT license
 * https://github.com/sunpietro/dragster/blob/master/LICENSE
 *
 * Date: 2015-05-24T19:00Z
 */
(function(e,t){e.Dragster=function(n){var s="is-dragging",i="is-drag-over",r="dragster-draggable",a="dragster-drag-region",o="dragster-drop-placeholder",l="dragster-temp",c="dragster-temp-container",d="dragster-is-hidden",u="dragster-replacable",f={elementSelector:".dragster-block",regionSelector:".dragster-region",replaceElements:false,updateRegionsHeight:true,minimumRegionHeight:50},m="draggable",p="data-placeholder-position",g={top:false,bottom:false},h,v,L,y,E,C,b,N,B,w,A,H,T,S,M,R,x,q,D,O,X,Y,I,P;for(h in n){if(n.hasOwnProperty(h)){f[h]=n[h]}}Y=function(){return Array.prototype.slice.call(t.querySelectorAll(f.elementSelector))};I=function(e){e.forEach(function(e){var t=M(),n=e.parentNode;if(n.classList.contains(r)){return}n.insertBefore(t,e);n.removeChild(e);t.appendChild(e)})};N=Y();v=Array.prototype.slice.call(t.querySelectorAll(f.regionSelector));if(f.replaceElements){C=t.createElement("div");C.classList.add(d);C.classList.add(c);t.body.appendChild(C)}L=function(e,t){var n=e.parentNode;if(!n||e.classList&&e.classList.contains(a)){return undefined}if(t(e)){return e}return t(n)?n:L(n,t)};D=function(e){var n=Array.prototype.slice.call(t.getElementsByClassName(e));n.forEach(function(e){e.parentNode.removeChild(e)})};O=function(e,n){v.forEach(function(e){e.removeEventListener(n,B.mousemove)});t.body.removeEventListener(n,B.mousemove);if(e){e.classList.remove(s)}Array.prototype.slice.call(t.getElementsByClassName(r)).forEach(function(e){if(!e.firstChild){e.parentNode.removeChild(e)}});D(o);D(l);P()};X=function(){Array.prototype.slice.call(t.getElementsByClassName(u)).forEach(function(e){e.classList.remove(u)})};M=function(){var e=t.createElement("div");e.setAttribute(m,true);e.classList.add(r);return e};x=function(){var e=t.createElement("div");e.classList.add(o);return e};R=function(){var e=t.createElement("div");e.classList.add(l);e.classList.add(d);t.body.appendChild(e);return e};T=function(e,t){if(e&&e.parentNode){e.parentNode.insertBefore(t,e.nextSibling)}};S=function(e,t){if(e&&e.parentNode){e.parentNode.insertBefore(t,e)}};H=function(e){return e.classList&&e.classList.contains(a)};A=function(e){return e.classList&&e.classList.contains(r)};w=function(e){return e.classList&&e.classList.contains(o)};P=function(){if(f.updateRegionsHeight){var n=Array.prototype.slice.call(t.getElementsByClassName(a));n.forEach(function(t){var n=Array.prototype.slice.call(t.querySelectorAll(f.elementSelector)),s=f.minimumRegionHeight;if(n.length){n.forEach(function(t){var n=e.getComputedStyle(t);s+=t.offsetHeight+parseInt(n.marginTop,10)+parseInt(n.marginBottom,10)})}t.style.height=s+"px"})}};B={mousedown:function(e){e.preventDefault();if(e.which===3){return false}var n,i=e.type==="touchstart"?"touchmove":"mousemove";v.forEach(function(e){e.addEventListener(i,B.mousemove)});t.body.addEventListener(i,B.mousemove);b=L(e.target,A);if(!b){return false}n=b.getBoundingClientRect();y=R();y.innerHTML=b.innerHTML;y.style.width=n.width+"px";y.style.height=n.height+"px";E=y.getBoundingClientRect();b.classList.add(s)},mousemove:function(e){e.preventDefault();var n=e.changedTouches?e.changedTouches[0]:e,s=n.view?n.view.pageXOffset:0,i=n.view?n.view.pageYOffset:0,l=n.clientY+i,c=n.clientX+s,m=t.elementFromPoint(n.clientX,n.clientY),h=L(m,A),v,C,N;clearTimeout(q);y.style.top=l+25+"px";y.style.left=c-E.width/2+"px";y.classList.remove(d);if(h&&h!==b){N=x();v=h.getBoundingClientRect();C=v.height/2;X();if(!f.replaceElements){if(l-v.top<C&&!g.top){D(o);N.setAttribute(p,"top");S(h.firstChild,N)}else if(v.bottom-l<C&&!g.bottom){D(o);N.setAttribute(p,"bottom");h.appendChild(N)}}else{h.classList.add(u)}}else if(m.classList.contains(a)&&m.getElementsByClassName(r).length===0&&m.getElementsByClassName(o).length===0){N=x();m.appendChild(N)}else if(m.classList.contains(a)&&m.getElementsByClassName(r).length>0&&m.getElementsByClassName(o).length===0){var B=m.getElementsByClassName(r);N=x();N.setAttribute(p,"bottom");D(o);B[B.length-1].appendChild(N)}else if(!m.classList.contains(a)){if(!f.replaceElements){D(o)}else{X()}}P()},mouseup:function(e){var n=f.replaceElements?u:o,s=t.getElementsByClassName(n)[0],r,a,l=e.type==="touchstart"?"touchmove":"mousemove",d;q=setTimeout(function(){O(b,l)},200);X();if(!b||!s){O(b,l);return false}r=L(s,A);r=r||s;if(b!==r){if(!f.replaceElements){d=M();a=s.getAttribute(p);if(a==="top"){S(r,d)}else{T(r,d)}if(b.firstChild){d.appendChild(b.firstChild)}}else{d=t.getElementsByClassName(c)[0];d.innerHTML=b.innerHTML;b.innerHTML=r.innerHTML;r.innerHTML=d.innerHTML;d.innerHTML=""}r.classList.remove(i)}O(b,l)}};I(N);t.body.addEventListener("mouseup",B.mouseup,false);t.body.addEventListener("touchend",B.mouseup,false);v.forEach(function(e){e.classList.add(a);e.addEventListener("mousedown",B.mousedown,false);e.addEventListener("mouseup",B.mouseup,false);e.addEventListener("touchstart",B.mousedown,false);e.addEventListener("touchend",B.mouseup,false)});return{update:function(){I(Y());P()}}}})(window,window.document);
<commit_msg>updated minified version<commit_after>/*!
 * Dragster - drag'n'drop library v1.1.1
 * https://github.com/sunpietro/dragster
 *
 * Copyright 2015 Piotr Nalepa
 * http://blog.piotrnalepa.pl
 *
 * Released under the MIT license
 * https://github.com/sunpietro/dragster/blob/master/LICENSE
 *
 * Date: 2015-06-24T19:00Z
 */
(function(e,t){e.Dragster=function(n){var r="is-dragging",s="is-drag-over",a="dragster-draggable",i="dragster-drag-region",o="dragster-drop-placeholder",l="dragster-temp",c="dragster-temp-container",d="dragster-is-hidden",f="dragster-replacable",u=function(){},m={elementSelector:".dragster-block",regionSelector:".dragster-region",replaceElements:false,updateRegionsHeight:true,minimumRegionHeight:50,onBeforeDragStart:u,onAfterDragStart:u,onBeforeDragMove:u,onAfterDragMove:u,onBeforeDragEnd:u,onAfterDragEnd:u},g="draggable",p="data-placeholder-position",h={top:false,bottom:false},v,E,L,y,C,B,b,A,N,w,D,H,S,T,M,R,x,q,O,X,Y,I,P,k;for(v in n){if(n.hasOwnProperty(v)){m[v]=n[v]}}I=function(){return Array.prototype.slice.call(t.querySelectorAll(m.elementSelector))};P=function(e){e.forEach(function(e){var t=M(),n=e.parentNode;if(n.classList.contains(a)){return}n.insertBefore(t,e);n.removeChild(e);t.appendChild(e)})};A=I();E=Array.prototype.slice.call(t.querySelectorAll(m.regionSelector));if(m.replaceElements){B=t.createElement("div");B.classList.add(d);B.classList.add(c);t.body.appendChild(B)}L=function(e,t){var n=e.parentNode;if(!n||e.classList&&e.classList.contains(i)){return undefined}if(t(e)){return e}return t(n)?n:L(n,t)};O=function(e){var n=Array.prototype.slice.call(t.getElementsByClassName(e));n.forEach(function(e){e.parentNode.removeChild(e)})};X=function(e,n){E.forEach(function(e){e.removeEventListener(n,N.mousemove)});t.body.removeEventListener(n,N.mousemove);if(e){e.classList.remove(r)}Array.prototype.slice.call(t.getElementsByClassName(a)).forEach(function(e){if(!e.firstChild){e.parentNode.removeChild(e)}});O(o);O(l);k()};Y=function(){Array.prototype.slice.call(t.getElementsByClassName(f)).forEach(function(e){e.classList.remove(f)})};M=function(){var e=t.createElement("div");e.setAttribute(g,true);e.classList.add(a);return e};x=function(){var e=t.createElement("div");e.classList.add(o);return e};R=function(){var e=t.createElement("div");e.classList.add(l);e.classList.add(d);t.body.appendChild(e);return e};S=function(e,t){if(e&&e.parentNode){e.parentNode.insertBefore(t,e.nextSibling)}};T=function(e,t){if(e&&e.parentNode){e.parentNode.insertBefore(t,e)}};H=function(e){return e.classList&&e.classList.contains(i)};D=function(e){return e.classList&&e.classList.contains(a)};w=function(e){return e.classList&&e.classList.contains(o)};k=function(){if(m.updateRegionsHeight){var n=Array.prototype.slice.call(t.getElementsByClassName(i));n.forEach(function(t){var n=Array.prototype.slice.call(t.querySelectorAll(m.elementSelector)),r=m.minimumRegionHeight;if(n.length){n.forEach(function(t){var n=e.getComputedStyle(t);r+=t.offsetHeight+parseInt(n.marginTop,10)+parseInt(n.marginBottom,10)})}t.style.height=r+"px"})}};N={mousedown:function(e){e.preventDefault();if(m.onBeforeDragStart()===false){return false}if(e.which===3){return false}var n,s=e.type==="touchstart"?"touchmove":"mousemove";E.forEach(function(e){e.addEventListener(s,N.mousemove)});t.body.addEventListener(s,N.mousemove);b=L(e.target,D);if(!b){return false}n=b.getBoundingClientRect();y=R();y.innerHTML=b.innerHTML;y.style.width=n.width+"px";y.style.height=n.height+"px";C=y.getBoundingClientRect();b.classList.add(r);m.onAfterDragStart()},mousemove:function(e){e.preventDefault();if(m.onBeforeDragMove()===false){return false}var n=e.changedTouches?e.changedTouches[0]:e,r=n.view?n.view.pageXOffset:0,s=n.view?n.view.pageYOffset:0,l=n.clientY+s,c=n.clientX+r,u=t.elementFromPoint(n.clientX,n.clientY),g=L(u,D),v,E,B;clearTimeout(q);y.style.top=l+25+"px";y.style.left=c-C.width/2+"px";y.classList.remove(d);if(g&&g!==b){B=x();v=g.getBoundingClientRect();E=v.height/2;Y();if(!m.replaceElements){if(l-v.top<E&&!h.top){O(o);B.setAttribute(p,"top");T(g.firstChild,B)}else if(v.bottom-l<E&&!h.bottom){O(o);B.setAttribute(p,"bottom");g.appendChild(B)}}else{g.classList.add(f)}}else if(u.classList.contains(i)&&u.getElementsByClassName(a).length===0&&u.getElementsByClassName(o).length===0){B=x();u.appendChild(B)}else if(u.classList.contains(i)&&u.getElementsByClassName(a).length>0&&u.getElementsByClassName(o).length===0){var A=u.getElementsByClassName(a);B=x();B.setAttribute(p,"bottom");O(o);A[A.length-1].appendChild(B)}else if(!u.classList.contains(i)){if(!m.replaceElements){O(o)}else{Y()}}k();m.onAfterDragMove()},mouseup:function(e){if(m.onBeforeDragEnd()===false){return false}var n=m.replaceElements?f:o,r=t.getElementsByClassName(n)[0],a,i,l=e.type==="touchstart"?"touchmove":"mousemove",d;q=setTimeout(function(){X(b,l)},200);Y();if(!b||!r){X(b,l);return false}a=L(r,D);a=a||r;if(b!==a){if(!m.replaceElements){d=M();i=r.getAttribute(p);if(i==="top"){T(a,d)}else{S(a,d)}if(b.firstChild){d.appendChild(b.firstChild)}}else{d=t.getElementsByClassName(c)[0];d.innerHTML=b.innerHTML;b.innerHTML=a.innerHTML;a.innerHTML=d.innerHTML;d.innerHTML=""}a.classList.remove(s)}X(b,l);m.onAfterDragEnd()}};P(A);t.body.addEventListener("mouseup",N.mouseup,false);t.body.addEventListener("touchend",N.mouseup,false);E.forEach(function(e){e.classList.add(i);e.addEventListener("mousedown",N.mousedown,false);e.addEventListener("mouseup",N.mouseup,false);e.addEventListener("touchstart",N.mousedown,false);e.addEventListener("touchend",N.mouseup,false)});return{update:function(){P(I());k()}}}})(window,window.document);
<|endoftext|>


<commit_before>/* @flow */
/* eslint-disable */
import React from 'react';
import { render, Text, TextStyles, View } from '../src';
import { dump } from '../src/debug';
import { fonts, spacing } from './designSystem';
import Profile from './components/Twitter';
import Space from './components/Space';
import Markdown from './components/Markdown';
import pkg from '../package.json';

type SketchContext = any;

const users = [
  {
    screen_name: 'mxstbr',
    name: 'Max Stoiber',
    description: '⚛ Makes styled-components, react-boilerplate, @KeystoneJS and CarteBlanche. ✌ Open source developer @thethinkmill. ☕ Speciality coffee geek, skier, traveller.',
    location: 'Vienna, Austria',
    url: 'mxstbr.com',
    profile_image_url: 'https://pbs.twimg.com/profile_images/763033229993574400/6frGyDyA_400x400.jpg',
  },
  {
    name: '- ̗̀Jackie ̖́-',
    screen_name: 'jackiesaik',
    description: 'Graphic designer, never won a spelling be. Toronto on weekdays. Go Home Lake on weekends. ╮ (. ● ᴗ ●.) ╭',
    location: 'Toronto, ON',
    url: 'cargocollective.com/jackiesaik',
    profile_image_url: 'https://pbs.twimg.com/profile_images/756488692135526400/JUCawBiW_400x400.jpg',
  },
  {
    screen_name: 'jongold',
    name: 'kerning man',
    description: 'an equal command of technology and form • functional programming (oc)cultist • design tools @airbnbdesign',
    location: 'California',
    url: 'weirdwideweb.jon.gold',
    profile_image_url: 'https://pbs.twimg.com/profile_images/773384639796740096/KdvxyX7M.jpg',
  },
];

const text = `
  # ${pkg.name} ${pkg.version}

  This is an example passing data from the Twitter API to a user profile card.
`;

const Page = () =>
  <View style={{ flexDirection: 'row', flexWrap: 'wrap', width: 600 }}>
    <View>
      <Markdown
        style={{
          width: 480,
        }}
        source={text}
      />
    </View>
    { users.map(user =>
      <Space h={spacing} v={spacing}>
        <Profile user={user} />
      </Space>
    )}
  </View>;

const onRun = (context: SketchContext) => {
  TextStyles.create({ context, clearExistingStyles: true }, fonts);
  render(<Page pkg={pkg} />, context);
};

module.exports = onRun;
<commit_msg>Update image url in examples<commit_after>/* @flow */
/* eslint-disable */
import React from 'react';
import { render, Text, TextStyles, View } from '../src';
import { dump } from '../src/debug';
import { fonts, spacing } from './designSystem';
import Profile from './components/Twitter';
import Space from './components/Space';
import Markdown from './components/Markdown';
import pkg from '../package.json';

type SketchContext = any;

const users = [
  {
    screen_name: 'mxstbr',
    name: 'Max Stoiber',
    description: '⚛ Makes styled-components, react-boilerplate, @KeystoneJS and CarteBlanche. ✌ Open source developer @thethinkmill. ☕ Speciality coffee geek, skier, traveller.',
    location: 'Vienna, Austria',
    url: 'mxstbr.com',
    profile_image_url: 'https://pbs.twimg.com/profile_images/763033229993574400/6frGyDyA_400x400.jpg',
  },
  {
    name: '- ̗̀Jackie ̖́-',
    screen_name: 'jackiesaik',
    description: 'Graphic designer, never won a spelling be. Toronto on weekdays. Go Home Lake on weekends. ╮ (. ● ᴗ ●.) ╭',
    location: 'Toronto, ON',
    url: 'cargocollective.com/jackiesaik',
    profile_image_url: 'https://pbs.twimg.com/profile_images/756488692135526400/JUCawBiW_400x400.jpg',
  },
  {
    screen_name: 'jongold',
    name: 'kerning man',
    description: 'an equal command of technology and form • functional programming (oc)cultist • design tools @airbnbdesign',
    location: 'California',
    url: 'weirdwideweb.jon.gold',
    profile_image_url: 'https://pbs.twimg.com/profile_images/833785170285178881/loBb32g3.jpg',
  },
];

const text = `
  # ${pkg.name} ${pkg.version}

  This is an example passing data from the Twitter API to a user profile card.
`;

const Page = () =>
  <View style={{ flexDirection: 'row', flexWrap: 'wrap', width: 600 }}>
    <View>
      <Markdown
        style={{
          width: 480,
        }}
        source={text}
      />
    </View>
    { users.map(user =>
      <Space h={spacing} v={spacing}>
        <Profile user={user} />
      </Space>
    )}
  </View>;

const onRun = (context: SketchContext) => {
  TextStyles.create({ context, clearExistingStyles: true }, fonts);
  render(<Page pkg={pkg} />, context);
};

module.exports = onRun;
<|endoftext|>


<commit_before>// PLUGIN: Google Maps
var googleCallback;
(function (Popcorn) {

  /**
   * googlemap popcorn plug-in
   * Adds a map to the target div centered on the location specified by the user
   * Options parameter will need a start, end, target, type, zoom, lat and lng, and location
   * -Start is the time that you want this plug-in to execute
   * -End is the time that you want this plug-in to stop executing
   * -Target is the id of the DOM element that you want the map to appear in. This element must be in the DOM
   * -Type [optional] either: HYBRID (default), ROADMAP, SATELLITE, TERRAIN, STREETVIEW
   * -Zoom [optional] defaults to 0
   * -Heading [optional] STREETVIEW orientation of camera in degrees relative to true north (0 north, 90 true east, ect)
   * -Pitch [optional] STREETVIEW vertical orientation of the camera (between 1 and 3 is recommended)
   * -Lat and Lng: the coordinates of the map must be present if location is not specified.
   * -Location: the adress you want the map to display, bust be present if lat and log are not specified.
   * Note: using location requires extra loading time, also not specifying both lat/lng and location will
   * cause and error.
   * @param {Object} options
   *
   * Example:
    var p = Popcorn("#video")
      .googlemap({
       start: 5, // seconds
       end: 15, // seconds
       type: "ROADMAP",
       target: "map",
       lat: 43.665429,
       lng: -79.403323
    } )
  *
  */
  Popcorn.plugin( "googlemap" , (function(){

    var newdiv, i = 1, _mapFired = false, _mapLoaded = false;

    return {
      manifest: {
        about:{
          name: "Popcorn Google Map Plugin",
          version: "0.1",
          author: "@annasob",
          website: "annasob.wordpress.com"
        },
        options:{
          start    : {elem:"input", type:"text", label:"In"},
          end      : {elem:"input", type:"text", label:"Out"},
          target   : "map-container",
          type     : {elem:"select", options:["ROADMAP","SATELLITE", "STREETVIEW", "HYBRID", "TERRAIN"], label:"Type"},
          zoom     : {elem:"input", type:"text", label:"Zoom"},
          lat      : {elem:"input", type:"text", label:"Lat"},
          lng      : {elem:"input", type:"text", label:"Lng"},
          location : {elem:"input", type:"text", label:"Location"},
          heading  : {elem:"input", type:"text", label:"Heading"},
          pitch    : {elem:"input", type:"text", label:"Pitch"}
        }
      },
      _setup : function( options ) {
        // create a new div this way anything in the target div
        // this is later passed on to the maps api
        options._newdiv = document.createElement("div");
        options._newdiv.id = "actualmap"+i;
        options._newdiv.style.width = "100%";
        options._newdiv.style.height = "100%";
        i++;
        if (document.getElementById(options.target)) {
          document.getElementById(options.target).appendChild(options._newdiv);
        }

        // insert google api script once
        if (!_mapFired) {
          _mapFired = true;
          var loadScriptTime = (new Date).getTime();
          var head = document.getElementsByTagName("head")[0];
          var script = document.createElement("script");

          script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=googleCallback";
          script.type = "text/javascript";
          head.insertBefore( script, head.firstChild );
        }
        // callback function fires when the script is run
        googleCallback = function() {
          _mapLoaded = true;
        };
        // If there is no lat/lng, and there is location, geocode the location
        // you can only do this once google.maps exists
        var isGeoReady = function() {
          if ( !_mapLoaded ) {
            setTimeout(function () {
              isGeoReady();
            }, 5);
          } else {
            if (options.location) {
              var geocoder = new google.maps.Geocoder();
              // calls an anonymous function called on separate thread
              geocoder.geocode({ "address": options.location}, function(results, status) {
                if (status === google.maps.GeocoderStatus.OK) {
                  options.lat = results[0].geometry.location.lat();
                  options.lng = results[0].geometry.location.lng();
                  options._location = new google.maps.LatLng(options.lat, options.lng);
                  options._map = new google.maps.Map(options._newdiv, {mapTypeId: google.maps.MapTypeId[options.type] || google.maps.MapTypeId.HYBRID });
                  options._map.getDiv().style.display = "none";
                }
              });
            } else {
              options._location = new google.maps.LatLng(options.lat, options.lng);
              options._map = new google.maps.Map(options._newdiv, {mapTypeId: google.maps.MapTypeId[options.type] || google.maps.MapTypeId.HYBRID });
              options._map.getDiv().style.display = "none";
            }
          }
        };
        isGeoReady();

      },
      /**
       * @member webpage
       * The start function will be executed when the currentTime
       * of the video reaches the start time provided by the
       * options variable
       */
      start: function(event, options){
        // dont do anything if the information didn't come back from google map
        var isReady = function () {
          if (!options._map) {
            setTimeout(function () {
              isReady();
            }, 13);
          } else {
            options._map.getDiv().style.display = "block";
            // reset the location and zoom just in case the user plaid with the map
            options._map.setCenter(options._location);

            // make sure options.zoom is a number
            if ( options.zoom && typeof options.zoom !== "number" ) {
              options.zoom = +options.zoom;
            }

            options.zoom = options.zoom || 0; // default to 0
            options._map.setZoom( options.zoom );

            //Make sure heading is a number
            if ( options.heading && typeof options.heading !== "number" ) {
              options.heading = +options.heading;
            }
            //Make sure pitch is a number
            if ( options.pitch && typeof options.pitch !== "number" ) {
              options.pitch = +options.pitch;
            }

            google.maps.event.trigger(options._map, 'resize');

            if ( options.type === "STREETVIEW" ) {
              // Switch this map into streeview mode
              options._map.setStreetView(
                // Pass a new StreetViewPanorama instance into our map
                new google.maps.StreetViewPanorama( options._newdiv, {
                  position: options._location,
                  pov: {
                    heading: options.heading = options.heading || 0,
                    pitch: options.pitch = options.pitch || 0,
                    zoom: options.zoom
                  }
                })
              );
            }
          }
        };

        isReady();
      },
      /**
       * @member webpage
       * The end function will be executed when the currentTime
       * of the video reaches the end time provided by the
       * options variable
       */
      end: function(event, options){
        // if the map exists hide it do not delete the map just in
        // case the user seeks back to time b/w start and end
        if (options._map) {
          options._map.getDiv().style.display = "none";
        }
      }

    };

  })());

})( Popcorn );
<commit_msg>[#336] simplify googlemap plugin<commit_after>// PLUGIN: Google Maps
var googleCallback;
(function (Popcorn) {

  /**
   * googlemap popcorn plug-in
   * Adds a map to the target div centered on the location specified by the user
   * Options parameter will need a start, end, target, type, zoom, lat and lng, and location
   * -Start is the time that you want this plug-in to execute
   * -End is the time that you want this plug-in to stop executing
   * -Target is the id of the DOM element that you want the map to appear in. This element must be in the DOM
   * -Type [optional] either: HYBRID (default), ROADMAP, SATELLITE, TERRAIN, STREETVIEW
   * -Zoom [optional] defaults to 0
   * -Heading [optional] STREETVIEW orientation of camera in degrees relative to true north (0 north, 90 true east, ect)
   * -Pitch [optional] STREETVIEW vertical orientation of the camera (between 1 and 3 is recommended)
   * -Lat and Lng: the coordinates of the map must be present if location is not specified.
   * -Location: the adress you want the map to display, bust be present if lat and log are not specified.
   * Note: using location requires extra loading time, also not specifying both lat/lng and location will
   * cause and error.
   * @param {Object} options
   *
   * Example:
    var p = Popcorn("#video")
      .googlemap({
       start: 5, // seconds
       end: 15, // seconds
       type: "ROADMAP",
       target: "map",
       lat: 43.665429,
       lng: -79.403323
    } )
  *
  */

  var newdiv, i = 1, _mapFired = false, _mapLoaded = false;

  // callback function fires when the script is run
  googleCallback = function() {
    _mapLoaded = true;
  };
  // insert google api script once
  if (!_mapFired) {
    _mapFired = true;
    var loadScriptTime = (new Date).getTime();
    var head = document.getElementsByTagName("head")[0];
    var script = document.createElement("script");

    script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=googleCallback";
    script.type = "text/javascript";
    head.insertBefore( script, head.firstChild );
  }

  Popcorn.plugin( "googlemap" , function( options ) {
    var newdiv, map, location;

    // create a new div this way anything in the target div
    // this is later passed on to the maps api
    newdiv = document.createElement("div");
    newdiv.id = "actualmap"+i;
    newdiv.style.width = "100%";
    newdiv.style.height = "100%";
    i++;
    if (document.getElementById(options.target)) {
      document.getElementById(options.target).appendChild(newdiv);
    }

    // If there is no lat/lng, and there is location, geocode the location
    // you can only do this once google.maps exists
    var isGeoReady = function() {
      if ( !_mapLoaded ) {
        setTimeout(function () {
          isGeoReady();
        }, 5);
      } else {
        if (options.location) {
          var geocoder = new google.maps.Geocoder();
          // calls an anonymous function called on separate thread
          geocoder.geocode({ "address": options.location}, function(results, status) {
            if (status === google.maps.GeocoderStatus.OK) {
              options.lat = results[0].geometry.location.lat();
              options.lng = results[0].geometry.location.lng();
              location = new google.maps.LatLng(options.lat, options.lng);
              map = new google.maps.Map(newdiv, {mapTypeId: google.maps.MapTypeId[options.type] || google.maps.MapTypeId.HYBRID });
              map.getDiv().style.display = "none";
            }
          });
        } else {
          location = new google.maps.LatLng(options.lat, options.lng);
          map = new google.maps.Map(newdiv, {mapTypeId: google.maps.MapTypeId[options.type] || google.maps.MapTypeId.HYBRID });
          map.getDiv().style.display = "none";
        }
      }
    };
    isGeoReady();

    return {
      /**
       * @member webpage
       * The start function will be executed when the currentTime
       * of the video reaches the start time provided by the
       * options variable
       */
      start: function(event, options){
        // dont do anything if the information didn't come back from google map
        var isReady = function () {
          if (!map) {
            setTimeout(function () {
              isReady();
            }, 13);
          } else {
            map.getDiv().style.display = "block";
            // reset the location and zoom just in case the user plaid with the map
            map.setCenter(location);

            // make sure options.zoom is a number
            if ( options.zoom && typeof options.zoom !== "number" ) {
              options.zoom = +options.zoom;
            }

            options.zoom = options.zoom || 0; // default to 0
            map.setZoom( options.zoom );

            //Make sure heading is a number
            if ( options.heading && typeof options.heading !== "number" ) {
              options.heading = +options.heading;
            }
            //Make sure pitch is a number
            if ( options.pitch && typeof options.pitch !== "number" ) {
              options.pitch = +options.pitch;
            }

            google.maps.event.trigger(map, 'resize');

            if ( options.type === "STREETVIEW" ) {
              // Switch this map into streeview mode
              map.setStreetView(
                // Pass a new StreetViewPanorama instance into our map
                new google.maps.StreetViewPanorama( newdiv, {
                  position: location,
                  pov: {
                    heading: options.heading = options.heading || 0,
                    pitch: options.pitch = options.pitch || 0,
                    zoom: options.zoom
                  }
                })
              );
            }
          }
        };

        isReady();
      },
      /**
       * @member webpage
       * The end function will be executed when the currentTime
       * of the video reaches the end time provided by the
       * options variable
       */
      end: function(event, options){
        // if the map exists hide it do not delete the map just in
        // case the user seeks back to time b/w start and end
        if (map) {
          map.getDiv().style.display = "none";
        }
      }
    };
  },
  {
    about: {
      name: "Popcorn Google Map Plugin",
      version: "0.1",
      author: "@annasob",
      website: "annasob.wordpress.com"
    },
    options: {
      start    : {elem:"input", type:"text", label:"In"},
      end      : {elem:"input", type:"text", label:"Out"},
      target   : "map-container",
      type     : {elem:"select", options:["ROADMAP","SATELLITE", "STREETVIEW", "HYBRID", "TERRAIN"], label:"Type"},
      zoom     : {elem:"input", type:"text", label:"Zoom"},
      lat      : {elem:"input", type:"text", label:"Lat"},
      lng      : {elem:"input", type:"text", label:"Lng"},
      location : {elem:"input", type:"text", label:"Location"},
      heading  : {elem:"input", type:"text", label:"Heading"},
      pitch    : {elem:"input", type:"text", label:"Pitch"}
    }
  });
})( Popcorn );
<|endoftext|>


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

export { default as SetupAccountApproved } from './SetupAccountApproved';
export { default as SetupAccountCreate } from './SetupAccountCreate';
export { default as SetupAccountDisapproved } from './SetupAccountDisapproved';
export { default as SetupAccountNoClient } from './SetupAccountNoClient';
export { default as SetupAccountPending } from './SetupAccountPending';
export { default as SetupAccountSelect } from './SetupAccountSelect';
export { default as SetupMain } from './SetupMain';
export { default as SetupSiteAdd } from './SetupSiteAdd';
export { default as SetupSiteAdded } from './SetupSiteAdded';
<commit_msg>Fix failing test.<commit_after>/**
 * AdSense Setup components.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

export { default as SetupAccountApproved } from './SetupAccountApproved';
export { default as SetupAccountCreate } from './SetupAccountCreate';
export { default as SetupAccountDisapproved } from './SetupAccountDisapproved';
export { default as SetupAccountNoClient } from './SetupAccountNoClient';
export { default as SetupAccountPending } from './SetupAccountPending';
export { default as SetupAccountSelect } from './SetupAccountSelect';
export { default as SetupMain } from './SetupMain';
export { default as SetupSiteAdd } from './SetupSiteAdd';
export { default as SetupSiteAdded } from './SetupSiteAdded';
export { default as v2 } from './v2/SetupMain';
<|endoftext|>