<commit_before>
function setStatus (iteration) {
  var state = iteration.state = {
    funded: iteration.target <= iteration.sum,
    draft: !iteration.total,
    complete: iteration.total && (iteration.total <= iteration.complete),
    progress: (iteration.complete || 0) / (iteration.total || 1)
  }
  iteration.progress = (iteration.complete || 0) / (iteration.total || 1)

  iteration.status = (
      state.funded  && state.complete  ? 'complete'
    : state.funded  && !state.complete ? 'progress'
    : !state.funded && iteration.sum   ? 'funding'
    :                                    'ready'
  )

  return iteration
}

module.exports = function (iterations, funders) {
  iteration.funders = funders
  iteration.sum = funders.reduce(function (a, b) {
    return a + b.sum
  }, 0)

  setStatus(iteration)

  return iteration
}

module.exports.random = function () {
  var target = 1 + Math.random()
  var sum = Math.min(target, target * Math.random()*1.3)
  var total = 2 + ~~(5*Math.random())
  var complete = ~~Math.min(total, total * Math.random() * (sum < target ? 1.1 : 1.5))

  var tasks = []
  for(var i = 0; i < total; i++) {
    tasks.push({closed: complete > i})
  }

  tasks.sort(function () { return Math.random() - 0.5 })

  return setStatus({
    target   : target,
    sum      : sum,
    total    : total,
    complete : complete,
    progress : complete / total,
    status   : ['created', 'funding', 'progress', 'complete'][~~(Math.random()*4)],
    links    : tasks
  })
}
<commit_msg>convert sum from satoshis into btc<commit_after>
function setStatus (iteration) {
  var state = iteration.state = {
    funded: iteration.target <= iteration.sum,
    draft: !iteration.total,
    complete: iteration.total && (iteration.total <= iteration.complete),
    progress: (iteration.complete || 0) / (iteration.total || 1)
  }
  iteration.progress = (iteration.complete || 0) / (iteration.total || 1)

  iteration.status = (
      state.funded  && state.complete  ? 'complete'
    : state.funded  && !state.complete ? 'progress'
    : !state.funded && iteration.sum   ? 'funding'
    :                                    'ready'
  )

  return iteration
}

module.exports = function (iteration, funders) {
  iteration.funders = funders
  iteration.sum = funders.reduce(function (a, b) {
    return a + b.sum
  }, 0) / 1e8

  setStatus(iteration)

  return iteration
}

module.exports.random = function () {
  var target = 1 + (1*Math.random())
  var sum = Math.min(target, target * Math.random()*1.3)
  var total = 2 + ~~(5*Math.random())
  var complete = ~~Math.min(total, total * Math.random() * (sum < target ? 1.1 : 1.5))

  var tasks = []
  for(var i = 0; i < total; i++) {
    tasks.push({closed: complete > i})
  }

  tasks.sort(function () { return Math.random() - 0.5 })

  return setStatus({
    target   : target,
    sum      : sum,
    total    : total,
    complete : complete,
    progress : complete / total,
    status   : ['created', 'funding', 'progress', 'complete'][~~(Math.random()*4)],
    links    : tasks
  })
}
<|endoftext|>


<commit_before>(function () {
    'use strict';

    define(
        [
            'util/container',
            'services/searchService',
            'services/detailService',
            'services/cachingService',
            'ui/overlay'
        ],
        function (container, searchService, detailService, cachingService, overlay) {
            var simpleApiBaseUrl, options;

            simpleApiBaseUrl = 'https://collections-api.histwest.org.au/service.php/simple';
            options = {
                noCache: false,
                logErrors: false,
                limit: 500,
                ajaxOptions: {
                    xhrFields: {
                        withCredentials: true
                    },
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader('Authorization', 'Basic ' + btoa('research-frontend:NotReallySecret'));
                    }
                }
            };

            return function () {
                container.register('options.service', options);
                container.register('options.shop', {
                    // TODO Disabled until the shop goes live.
                    // baseUrl: 'https://shop.histwest.org.au/index.php/',
                    // path: {
                    //     search: 'catalogsearch/result/',
                    //     digitalPhotographs: 'photographs/digital-photograph.html'
                    // }
                });
                container.register('options.providence', {
                    baseUrl: 'https://collections.histwest.org.au/index.php/',
                    path: {
                        objects: 'editor/objects/ObjectEditor/Summary/'
                    }
                });

                container.register('search.all', cachingService(searchService(simpleApiBaseUrl + '/all_search', options)));
                container.register('search.library', cachingService(searchService(simpleApiBaseUrl + '/library_search', options)));
                container.register('search.photographs', cachingService(searchService(simpleApiBaseUrl + '/photographs_search', options)));
                container.register('search.museum', cachingService(searchService(simpleApiBaseUrl + '/museum_search', options)));
                container.register('search.memorials', cachingService(searchService(simpleApiBaseUrl + '/memorials_search', options)));

                container.register('detail.library', cachingService(detailService(simpleApiBaseUrl + '/library_detail', options)));
                container.register('detail.photographs', cachingService(detailService(simpleApiBaseUrl + '/photographs_detail', options)));
                container.register('detail.museum', cachingService(detailService(simpleApiBaseUrl + '/museum_detail', options)));
                container.register('detail.memorials', cachingService(detailService(simpleApiBaseUrl + '/memorials_detail', options)));

                container.register('ui.overlay', overlay(false));
            };
        }
    );
}());
<commit_msg>Enable shop link in production.<commit_after>(function () {
    'use strict';

    define(
        [
            'util/container',
            'services/searchService',
            'services/detailService',
            'services/cachingService',
            'ui/overlay'
        ],
        function (container, searchService, detailService, cachingService, overlay) {
            var simpleApiBaseUrl, options;

            simpleApiBaseUrl = 'https://collections-api.histwest.org.au/service.php/simple';
            options = {
                noCache: false,
                logErrors: false,
                limit: 500,
                ajaxOptions: {
                    xhrFields: {
                        withCredentials: true
                    },
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader('Authorization', 'Basic ' + btoa('research-frontend:NotReallySecret'));
                    }
                }
            };

            return function () {
                container.register('options.service', options);
                container.register('options.shop', {
                    baseUrl: 'https://shop.histwest.org.au/index.php/',
                    path: {
                        search: 'catalogsearch/result/',
                        digitalPhotographs: 'photographs/digital-photograph.html'
                    }
                });
                container.register('options.providence', {
                    baseUrl: 'https://collections.histwest.org.au/index.php/',
                    path: {
                        objects: 'editor/objects/ObjectEditor/Summary/'
                    }
                });

                container.register('search.all', cachingService(searchService(simpleApiBaseUrl + '/all_search', options)));
                container.register('search.library', cachingService(searchService(simpleApiBaseUrl + '/library_search', options)));
                container.register('search.photographs', cachingService(searchService(simpleApiBaseUrl + '/photographs_search', options)));
                container.register('search.museum', cachingService(searchService(simpleApiBaseUrl + '/museum_search', options)));
                container.register('search.memorials', cachingService(searchService(simpleApiBaseUrl + '/memorials_search', options)));

                container.register('detail.library', cachingService(detailService(simpleApiBaseUrl + '/library_detail', options)));
                container.register('detail.photographs', cachingService(detailService(simpleApiBaseUrl + '/photographs_detail', options)));
                container.register('detail.museum', cachingService(detailService(simpleApiBaseUrl + '/museum_detail', options)));
                container.register('detail.memorials', cachingService(detailService(simpleApiBaseUrl + '/memorials_detail', options)));

                container.register('ui.overlay', overlay(false));
            };
        }
    );
}());
<|endoftext|>


<commit_before><commit_msg>scheduler skeleton<commit_after>import Mailchimp from 'mailchimp-api-v3';
import key from '../mailchimp-key.js';

const mailchimp = new Mailchimp(key);

const MAIN_LIST_ID = '2530fc93d7';
const MEAL_GROUPS_ID = 'aa093740d5';

export const createCampaign = () => {
  // TODO
};

export const setTemplateToCampaign = (campaignId, templateId) => {
  // TODO
};

export const sendCampaignTest = campaignId => {
  // TODO
};

export const scheduleCampaign = date => {
  // TODO
};
<|endoftext|>


<commit_before>(function() {
var t = new Test.TAP.Class();
t.plan(7)

t.testDetach = function() {

    Class("TestClass", {
        methods: {
            one: function () { return 1 }
        }
    })

    Class("SubClass", {
        isa: TestClass,
        methods: {
            two: function () { return 2 }
        }
    })

    var o1 = new SubClass();
    var o2 = new SubClass();
    t.ok(o1.one() == 1 && o1.two() == 2, "Methods return correct results");
    t.ok(o2.one() == 1 && o2.two() == 2, "Methods return correct results");

    o2.detach()

    o2.meta.addMethod("one", function () { return 3 });

    t.ok(o1.one() == 1 && o1.two() == 2, "Methods return correct results for non detached object after detach of object of same class");
    t.ok(o2.one() == 3 && o2.two() == 2, "Methods return correct results in detached object");

    var o3 = o1.meta.instantiate()
    var o4 = o2.meta.instantiate()

    var o5 = new SubClass();

    t.ok(o5.one() == 1 && o5.two() == 2, "Methods of new object return correct results for non detached object after detach of object of same class");
    t.ok(o3.one() == 1 && o3.two() == 2, "Methods of new object return correct results for non detached object after detach of object of same class");
    t.ok(o4.one() == 3 && o4.two() == 2, "Methods of new object return correct results in detached object");

}
return t;
})();<commit_msg><commit_after>(function() {
var t = new Test.TAP.Class();
t.plan(8)

t.testDetach = function() {

    Class("TestClass", {
        methods: {
            one: function () { return 1 }
        }
    })

    Class("SubClass", {
        isa: TestClass,
        methods: {
            two: function () { return 2 }
        }
    })

    var o1 = new SubClass();
    var o2 = new SubClass();
    t.ok(o1.one() == 1 && o1.two() == 2, "Methods return correct results");
    t.ok(o2.one() == 1 && o2.two() == 2, "Methods return correct results");

    o2.detach()

    o2.meta.addMethod("one", function () { return 3 });

    t.ok(o1.one() == 1 && o1.two() == 2, "Methods return correct results for non detached object after detach of object of same class");
    t.ok(o2.one() == 3 && o2.two() == 2, "Methods return correct results in detached object");

    var o3 = o1.meta.instantiate()
    var o4 = o2.meta.instantiate()

    var o5 = new SubClass();

    t.ok(o5.one() == 1 && o5.two() == 2, "Methods of new object return correct results for non detached object after detach of object of same class");
    t.ok(o3.one() == 1 && o3.two() == 2, "Methods of new object return correct results for non detached object after detach of object of same class");
    t.ok(o4.one() == 3 && o4.two() == 2, "Methods of new object return correct results in detached object");

//    TODO
//    SubClass.meta.addMethod('three', function () { return 3 });
//
//    if (typeof o2.three != 'function') {
//    	t.ok(true, "Detached instance is not affected by changes in original class");
//    } else {
//    	t.ok(false, "Detached instance is not affected by changes in original class");
//    }

}
return t;
})();<|endoftext|>


<commit_before>'use strict';

var helper = require('./helpers.authentication.e2e.client.Spec');

describe('deleteCampaigns', function() {
  beforeEach(function() {
    helper.loadApp('/');
  });
  it('should', function() {
    helper.logoutifLoggedIn();
    var signInButton = element(by.id('signIn'));
    signInButton.click();
    var myAndonation = element(by.id('myAndonation'));
    myAndonation.click();
    var titleButton = element.all(by.binding('campaign.title')).first();
    titleButton.click();
    var deleteButton = element(by.id('deleteButton'));
    deleteButton.click();
    var confirmDialog = browser.switchTo().alert();
    expect(confirmDialog.accept).toBeDefined();
    confirmDialog.accept();
    expect(element(by.tagName('table')).isPresent()).toBe(true);
  });
});
<commit_msg>modified the deleteCampaign e2e test<commit_after>'use strict';

var helper = require('./helpers.authentication.e2e.client.Spec');

describe('deleteCampaigns', function() {
  beforeEach(function() {
    helper.loadApp('/');
  });
  it('should', function() {
    helper.logoutifLoggedIn();
    var signInButton = element(by.id('signIn'));
    signInButton.click();
    var myAndonation = element(by.id('myAndonation'));
    myAndonation.click();
    var titleButton = element.all(by.binding('campaign.title')).first().click();
    var titleUrl = titleButton.getAttribute('href');
    element(by.id('editBtn')).click();
    var deleteButton = element(by.id('deleteButton'));
    deleteButton.click();
    var confirmDialog = browser.switchTo().alert();
    expect(confirmDialog.accept).toBeDefined();
    confirmDialog.accept();
    expect(element(by.tagName('table')).isPresent()).toBe(true);
    expect(element.all(by.binding('campaign.title')).first().getAttribute('href')).not.toBe(titleUrl);
  });
});
<|endoftext|>


<commit_before>/* global requirejs */

/**
 * ownCloud - Mail
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Christoph Wurst <christoph@winzerhof-wurst.at>
 * @copyright Christoph Wurst 2015
 */

'use strict';

requirejs.config({
	baseUrl: '/apps/mail/js',
	paths: {
		/**
		 * Application
		 */
		app: 'mail',
		marionette: 'backbone.marionette',
		handlebars: 'handlebars-v1.3.0',
		/**
		 * Libraries
		 */
		domReady: 'node_modules/domready/ready.min',
		//jquery: '../../../core/vendor/jquery/jquery.min',
		storage: 'jquery.storageapi',
		underscore: '../../../core/vendor/underscore/underscore'
	},
	shim: {
		// TODO: remove once min-oc-version is 8.0
		handlebars: {
			exports: 'Handlebars'
		},
		// END TODO
		jquery: {
			exports: '$'
		}
	}
});

require([
	'init',
	'notification'
]);<commit_msg>make baseUrl relative<commit_after>/* global requirejs */

/**
 * ownCloud - Mail
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Christoph Wurst <christoph@winzerhof-wurst.at>
 * @copyright Christoph Wurst 2015
 */

'use strict';

requirejs.config({
	baseUrl: './../../../apps/mail/js',
	paths: {
		/**
		 * Application
		 */
		app: 'mail',
		marionette: 'backbone.marionette',
		handlebars: 'handlebars-v1.3.0',
		/**
		 * Libraries
		 */
		domReady: 'node_modules/domready/ready.min',
		//jquery: '../../../core/vendor/jquery/jquery.min',
		storage: 'jquery.storageapi',
		underscore: '../../../core/vendor/underscore/underscore'
	},
	shim: {
		// TODO: remove once min-oc-version is 8.0
		handlebars: {
			exports: 'Handlebars'
		},
		// END TODO
		jquery: {
			exports: '$'
		}
	}
});

require([
	'init',
	'notification'
]);<|endoftext|>


<commit_before><commit_msg>Suppress crashReporter test on x64 Windows for now<commit_after><|endoftext|>


<commit_before>
import sansSel from "sans-sel";

const names = new Map();

function iterate(root, fn) {
  if (root.children) {
    root.children.forEach((child, i, children) => {
      if (child) iterate(child, fn);
      fn(child, i, children);
    });
  }
}

export default class Component {

  static styles = {
    input: {
      font: "inherit",
      padding: "6px 12px",
      borderRadius: "4px",
      border: "1px solid transparent",
      outline: 0,
    },

    textField: {
      inherit: "input",

      borderColor: "#BDC3C7",
      backgroundColor: "#fff",
    },

    button: {
      inherit: "input",

      color: "#fff",
      borderColor: "#16A085",
      backgroundColor: "#16A085",
      cursor: "pointer",

      hover: {
        backgroundColor: "#1ABC9C",
      },
    },
  };

  static get sansSelNS() {
    if (this.hasOwnProperty("_sansSelNS")) return this._sansSelNS;

    let name = this.name;
    if (names.has(name)) {
      let id = names.get(name) + 1;
      names.set(name, id);
      name = `${name}_${id}`;
    }
    else {
      names.set(name, 0);
    }

    let ss = (Object.getPrototypeOf(this).sansSelNS || sansSel()).namespace(name);
    Object.defineProperty(this, "_sansSelNS", { value: ss });

    if (this.styles) ss.addAll(this.styles);

    return ss;
  }

  static get controller() {
    Object.defineProperty(this, "controller", {
      value: (...args) => {
        return new this(...args);
      },
    });
    return this.controller;
  }

  static get view() {
    Object.defineProperty(this, "view", {
      value(component) {
        const rendered = component.render();

        const renderss = (child) => {
          if (child.tag && child.attrs && child.attrs.ss) {
            child.attrs.className = component.constructor.sansSelNS.render(child.attrs.ss);
            delete child.attrs.ss;
          }
        };

        iterate(rendered, (child, i, children) => {
          if (!child) children[i] = undefined;
          else renderss(child);
        });

        renderss(rendered);
        return rendered;
      },
    });
    return this.view;
  }

  getStyle() {
    const ns = this.constructor.sansSelNS;
    return ns.get(...arguments);
  }

}
<commit_msg>Support mithril nested arrays as children<commit_after>
import sansSel from "sans-sel";

const names = new Map();

function iterate(root, fn) {
  let children = Array.isArray(root) ? root : root.children;
  if (children) {
    children.forEach((child, i, children) => {
      if (child) iterate(child, fn);
      fn(child, i, children);
    });
  }
}

export default class Component {

  static styles = {
    input: {
      font: "inherit",
      padding: "6px 12px",
      borderRadius: "4px",
      border: "1px solid transparent",
      outline: 0,
    },

    textField: {
      inherit: "input",

      borderColor: "#BDC3C7",
      backgroundColor: "#fff",
    },

    button: {
      inherit: "input",

      color: "#fff",
      borderColor: "#16A085",
      backgroundColor: "#16A085",
      cursor: "pointer",

      hover: {
        backgroundColor: "#1ABC9C",
      },
    },
  };

  static get sansSelNS() {
    if (this.hasOwnProperty("_sansSelNS")) return this._sansSelNS;

    let name = this.name;
    if (names.has(name)) {
      let id = names.get(name) + 1;
      names.set(name, id);
      name = `${name}_${id}`;
    }
    else {
      names.set(name, 0);
    }

    let ss = (Object.getPrototypeOf(this).sansSelNS || sansSel()).namespace(name);
    Object.defineProperty(this, "_sansSelNS", { value: ss });

    if (this.styles) ss.addAll(this.styles);

    return ss;
  }

  static get controller() {
    Object.defineProperty(this, "controller", {
      value: (...args) => {
        return new this(...args);
      },
    });
    return this.controller;
  }

  static get view() {
    Object.defineProperty(this, "view", {
      value(component) {
        const rendered = component.render();

        const renderss = (child) => {
          if (child.tag && child.attrs && child.attrs.ss) {
            child.attrs.className = component.constructor.sansSelNS.render(child.attrs.ss);
            delete child.attrs.ss;
          }
        };

        iterate(rendered, (child, i, children) => {
          if (!child) children[i] = undefined;
          else renderss(child);
        });

        renderss(rendered);
        return rendered;
      },
    });
    return this.view;
  }

  getStyle() {
    const ns = this.constructor.sansSelNS;
    return ns.get(...arguments);
  }

}
<|endoftext|>


<commit_before>var browserUI = require('browserUI.js')

window.sessionRestore = {
  save: function () {
    var data = {
      version: 2,
      state: JSON.parse(JSON.stringify(tasks.getStringifyableState())),
      saveTime: Date.now()
    }

    // save all tabs that aren't private

    for (var i = 0; i < data.state.tasks.length; i++) {
      data.state.tasks[i].tabs = data.state.tasks[i].tabs.filter(function (tab) {
        return !tab.private
      })
    }

    localStorage.setItem('sessionrestoredata', JSON.stringify(data))
  },
  restore: function () {
    var savedStringData = localStorage.getItem('sessionrestoredata')

    /* the survey should only be shown after an upgrade from an earlier version */
    var shouldShowSurvey = false
    if (savedStringData && !localStorage.getItem('1.8survey')) {
      shouldShowSurvey = true
    }
    localStorage.setItem('1.8survey', 'true')

    try {
      // first run, show the tour
      if (!savedStringData) {
        tasks.setSelected(tasks.add()) // create a new task

        var newTab = tasks.getSelected().tabs.add({
          url: 'https://minbrowser.github.io/min/tour'
        })
        browserUI.addTab(newTab, {
          enterEditMode: false
        })
        return
      }

      var data = JSON.parse(savedStringData)

      // the data isn't restorable
      if ((data.version && data.version !== 2) || (data.state && data.state.tasks && data.state.tasks.length === 0)) {
        tasks.setSelected(tasks.add())

        browserUI.addTab(tasks.getSelected().tabs.add())
        return
      }

      // add the saved tasks

      data.state.tasks.forEach(function (task) {
        // restore the task item
        tasks.add(task)
      })
      tasks.setSelected(data.state.selectedTask)

      // switch to the previously selected tasks

      if (tasks.getSelected().tabs.isEmpty() || (!data.saveTime || Date.now() - data.saveTime < 30000)) {
        browserUI.switchToTask(data.state.selectedTask)
        if (tasks.getSelected().tabs.isEmpty()) {
          tabBar.enterEditMode(tasks.getSelected().tabs.getSelected())
        }
      } else {
        window.createdNewTaskOnStartup = true
        // try to reuse a previous empty task
        var lastTask = tasks.byIndex(tasks.getLength() - 1)
        if (lastTask && lastTask.tabs.isEmpty() && !lastTask.name) {
          browserUI.switchToTask(lastTask.id)
          tabBar.enterEditMode(lastTask.tabs.getSelected())
        } else {
          browserUI.addTask()
        }
      }

      // if this isn't the first run, and the survey popup hasn't been shown yet, show it

      if (shouldShowSurvey) {
        fetch('https://minbrowser.github.io/min/survey/survey.json').then(function (response) {
          return response.json()
        }).then(function (data) {
          setTimeout(function () {
            if (data.available && data.url) {
              if (tasks.getSelected().tabs.isEmpty()) {
                browserUI.navigate(tasks.getSelected().tabs.getSelected(), data.url)
              } else {
                var surveyTab = tasks.getSelected().tabs.add({
                  url: data.url
                })
                browserUI.addTab(surveyTab, {
                  enterEditMode: false
                })
              }
            }}, 200)
        })
      }
    } catch (e) {
      // an error occured while restoring the session data

      console.error('restoring session failed: ', e)

      var backupSavePath = require('path').join(remote.app.getPath('userData'), 'sessionRestoreBackup-' + Date.now() + '.json')

      require('fs').writeFileSync(backupSavePath, savedStringData)

      // destroy any tabs that were created during the restore attempt
      initializeTabState()

      // create a new tab with an explanation of what happened
      var newTask = tasks.add()
      var newSessionErrorTab = tasks.get(newTask).tabs.add({
        url: 'file://' + __dirname + '/pages/sessionRestoreError/index.html?backupLoc=' + encodeURIComponent(backupSavePath)
      })

      browserUI.switchToTask(newTask)
      browserUI.switchToTab(newSessionErrorTab)
    }
  }
}

// TODO make this a preference

sessionRestore.restore()

tasks.on('tab-selected', sessionRestore.save)

setInterval(sessionRestore.save, 12500)
<commit_msg>use file instead of localstorage for session restore<commit_after>var browserUI = require('browserUI.js')

window.sessionRestore = {
  savePath: userDataPath + (platformType === 'windows' ? '\\sessionRestore.json' : '/sessionRestore.json'),
  save: function () {
    var data = {
      version: 2,
      state: JSON.parse(JSON.stringify(tasks.getStringifyableState())),
      saveTime: Date.now()
    }

    // save all tabs that aren't private

    for (var i = 0; i < data.state.tasks.length; i++) {
      data.state.tasks[i].tabs = data.state.tasks[i].tabs.filter(function (tab) {
        return !tab.private
      })
    }

    fs.writeFile(sessionRestore.savePath, JSON.stringify(data), function () {})
  },
  restore: function () {
    var savedStringData
    try {
      savedStringData = fs.readFileSync(sessionRestore.savePath, 'utf-8')
    } catch (e) {
      console.warn('failed to read session restore data', e)
    }
    if (!savedStringData) {
      // migrate from previous version
      savedStringData = localStorage.getItem('sessionrestoredata')
    }

    /* the survey should only be shown after an upgrade from an earlier version */
    var shouldShowSurvey = false
    if (savedStringData && !localStorage.getItem('1.8survey')) {
      shouldShowSurvey = true
    }
    localStorage.setItem('1.8survey', 'true')

    try {
      // first run, show the tour
      if (!savedStringData) {
        tasks.setSelected(tasks.add()) // create a new task

        var newTab = tasks.getSelected().tabs.add({
          url: 'https://minbrowser.github.io/min/tour'
        })
        browserUI.addTab(newTab, {
          enterEditMode: false
        })
        return
      }

      var data = JSON.parse(savedStringData)

      // the data isn't restorable
      if ((data.version && data.version !== 2) || (data.state && data.state.tasks && data.state.tasks.length === 0)) {
        tasks.setSelected(tasks.add())

        browserUI.addTab(tasks.getSelected().tabs.add())
        return
      }

      // add the saved tasks

      data.state.tasks.forEach(function (task) {
        // restore the task item
        tasks.add(task)
      })
      tasks.setSelected(data.state.selectedTask)

      // switch to the previously selected tasks

      if (tasks.getSelected().tabs.isEmpty() || (!data.saveTime || Date.now() - data.saveTime < 30000)) {
        browserUI.switchToTask(data.state.selectedTask)
        if (tasks.getSelected().tabs.isEmpty()) {
          tabBar.enterEditMode(tasks.getSelected().tabs.getSelected())
        }
      } else {
        window.createdNewTaskOnStartup = true
        // try to reuse a previous empty task
        var lastTask = tasks.byIndex(tasks.getLength() - 1)
        if (lastTask && lastTask.tabs.isEmpty() && !lastTask.name) {
          browserUI.switchToTask(lastTask.id)
          tabBar.enterEditMode(lastTask.tabs.getSelected())
        } else {
          browserUI.addTask()
        }
      }

      // if this isn't the first run, and the survey popup hasn't been shown yet, show it

      if (shouldShowSurvey) {
        fetch('https://minbrowser.github.io/min/survey/survey.json').then(function (response) {
          return response.json()
        }).then(function (data) {
          setTimeout(function () {
            if (data.available && data.url) {
              if (tasks.getSelected().tabs.isEmpty()) {
                browserUI.navigate(tasks.getSelected().tabs.getSelected(), data.url)
              } else {
                var surveyTab = tasks.getSelected().tabs.add({
                  url: data.url
                })
                browserUI.addTab(surveyTab, {
                  enterEditMode: false
                })
              }
            } }, 200)
        })
      }
    } catch (e) {
      // an error occured while restoring the session data

      console.error('restoring session failed: ', e)

      var backupSavePath = require('path').join(remote.app.getPath('userData'), 'sessionRestoreBackup-' + Date.now() + '.json')

      fs.writeFileSync(backupSavePath, savedStringData)

      // destroy any tabs that were created during the restore attempt
      initializeTabState()

      // create a new tab with an explanation of what happened
      var newTask = tasks.add()
      var newSessionErrorTab = tasks.get(newTask).tabs.add({
        url: 'file://' + __dirname + '/pages/sessionRestoreError/index.html?backupLoc=' + encodeURIComponent(backupSavePath)
      })

      browserUI.switchToTask(newTask)
      browserUI.switchToTab(newSessionErrorTab)
    }
  }
}

// TODO make this a preference

sessionRestore.restore()

tasks.on('tab-selected', sessionRestore.save)

setInterval(sessionRestore.save, 12500)
<|endoftext|>


<commit_before>import els from '../../elements/de';
import { clearProductFromCart } from '../../helper/cart';
import { checkForWrongCoupon } from '../../helper/coupon';

describe('functional tests cart page', () => {
  it.skip('check for increase / decrease quanitity', () => {
    cy.visit('');

    cy.get(els.allProductCategory)
      .scrollIntoView()
      .should('be.visible')
      .click();
    cy.get(els.productWithManyProps4GridViewName)
      .should('be.visible')
      .click();
    cy.get(els.addToCartButton)
      .should('be.visible')
      .click();
    cy.get(els.cartButton)
      .should('be.visible')
      .click();
    cy.get(els.quantityPicker)
      .should('be.visible')
      .click()
      .type(2)
      .wait(100)
      .focus()
      .blur();
    cy.get('[data-test-id="minPrice: 0 price: 398 currency: EUR"]')
      .should('be.visible');
    cy.get(els.quantityPicker)
      .clear()
      .type(1)
      .wait(100)
      .focus()
      .blur();
    cy.get('[data-test-id="minPrice: 0 price: 199 currency: EUR"]')
      .should('be.visible');
  });

  it('should add second product to cart', () => {
    cy.visit('');
    cy.get(els.basicCategory)
      .scrollIntoView()
      .click();
    cy.get(els.productsWithLongNamesCat)
      .should('be.visible')
      .last()
      .click();
    cy.get(els.productWithVeryLongName5Name)
      .last()
      .should('be.visible')
      .click();
    cy.get(els.addToCartButton)
      .click();
    cy.get(els.cartButton)
      .click();
  });

  it('should check for wrong coupon', () => {
    cy.get(els.couponFieldInput)
      .type('wrongCoupon {enter}');
    checkForWrongCoupon();
  });

  it('should check for right coupon', () => {
    cy.get(els.couponFieldInput)
      .clear()
      .type('test1');
    cy.get(els.couponSubmitButton)
      .click();
    cy.get(els.basicDialogOkButton)
      .click();
    cy.get('[data-test-id="subTotal: 84"]')
      .should('be.visible');
  });

  it('should delete coupon from cart', () => {
    cy.get(els.deleteCouponButton)
      .click();
    cy.get(els.deleteCouponButton)
      .should('not.exist');
  });

  it('should check for products with variants', () => {
    cy.visit('');

    cy.get(els.productVariantsCategory)
      .scrollIntoView()
      .should('be.visible')
      .click();
    cy.get(els.productsWith2VariantsCategory)
      .should('be.visible')
      .last()
      .click();
    cy.get(els.productWithChild1MotherNameProductGrid)
      .should('be.visible')
      .last()
      .click();
    cy.get(els.variantPickerColor)
      .should('be.visible')
      .click();
    cy.get(els.blackColorVariant)
      .should('be.visible')
      .last()
      .click();
    cy.get(els.variantPickerShoeSize)
      .should('be.visible')
      .click();
    cy.get(els.size5ShoeSizeVariant)
      .should('be.visible')
      .last()
      .click()
      .wait(2000);
    cy.get(els.addToCartButton)
      .should('be.visible')
      .click();
    cy.get(els.cartButton)
      .should('be.visible')
      .click();
    cy.get(els.productWithChild1ColorBlackSize5CartItem)
      .should('be.visible');
  });

  it('should check for delete product from cart', () => {
    clearProductFromCart();
  });
});
<commit_msg>PWA-1265 added timeout for test stability<commit_after>import els from '../../elements/de';
import { clearProductFromCart } from '../../helper/cart';
import { checkForWrongCoupon } from '../../helper/coupon';

describe('functional tests cart page', () => {
  it.skip('check for increase / decrease quanitity', () => {
    cy.visit('');

    cy.get(els.allProductCategory)
      .scrollIntoView()
      .should('be.visible')
      .click();
    cy.get(els.productWithManyProps4GridViewName)
      .should('be.visible')
      .click();
    cy.get(els.addToCartButton)
      .should('be.visible')
      .click();
    cy.get(els.cartButton)
      .should('be.visible')
      .click();
    cy.get(els.quantityPicker)
      .should('be.visible')
      .click()
      .type(2)
      .wait(100)
      .focus()
      .blur();
    cy.get('[data-test-id="minPrice: 0 price: 398 currency: EUR"]')
      .should('be.visible');
    cy.get(els.quantityPicker)
      .clear()
      .type(1)
      .wait(100)
      .focus()
      .blur();
    cy.get('[data-test-id="minPrice: 0 price: 199 currency: EUR"]')
      .should('be.visible');
  });

  it('should add second product to cart', () => {
    cy.visit('');
    cy.get(els.basicCategory)
      .scrollIntoView()
      .click();
    cy.get(els.productsWithLongNamesCat)
      .should('be.visible')
      .last()
      .click();
    cy.get(els.productWithVeryLongName5Name)
      .last()
      .should('be.visible')
      .click();
    cy.get(els.addToCartButton)
      .click();
    cy.get(els.cartButton)
      .click();
  });

  it('should check for wrong coupon', () => {
    cy.get(els.couponFieldInput)
      .type('wrongCoupon {enter}');
    checkForWrongCoupon();
  });

  it('should check for right coupon', () => {
    cy.get(els.couponFieldInput)
      .clear()
      .type('test1');
    cy.get(els.couponSubmitButton)
      .click();
    cy.get(els.basicDialogOkButton)
      .click();
    cy.get('[data-test-id="subTotal: 84"]')
      .should('be.visible');
  });

  it('should delete coupon from cart', () => {
    cy.get(els.deleteCouponButton)
      .click();
    cy.get(els.deleteCouponButton)
      .should('not.exist');
  });

  it('should check for products with variants', () => {
    cy.visit('');

    cy.get(els.productVariantsCategory)
      .scrollIntoView()
      .should('be.visible')
      .click();
    cy.get(els.productsWith2VariantsCategory)
      .should('be.visible')
      .last()
      .click();
    cy.get(els.productWithChild1MotherNameProductGrid)
      .should('be.visible')
      .last()
      .click()
      .wait(2000);
    cy.get(els.variantPickerColor)
      .should('be.visible')
      .click()
      .wait(2000);
    cy.get(els.blackColorVariant)
      .should('be.visible')
      .last()
      .click()
      .wait(2000);
    cy.get(els.variantPickerShoeSize)
      .should('be.visible')
      .click()
      .wait(2000);
    cy.get(els.size5ShoeSizeVariant)
      .should('be.visible')
      .last()
      .click()
      .wait(2000);
    cy.get(els.addToCartButton)
      .should('be.visible')
      .click()
      .wait(2000);
    cy.get(els.cartButton)
      .should('be.visible')
      .click()
      .wait(2000);
    cy.get(els.productWithChild1ColorBlackSize5CartItem)
      .should('be.visible');
  });

  it('should check for delete product from cart', () => {
    clearProductFromCart();
  });
});
<|endoftext|>


<commit_before>'use strict';
const   express = require('express'),
        app = express(),
        EventEmitter = require('events'),
        pageRenderer = new EventEmitter(),
        gapi = require('../../lib/gapi.js'),
        usersTable = require('../../models/db.js').users;

app.get('/googleauth', (req, res) => {

    let methodCompletedCount = 0;
    let user = {};

    gapi.client.getToken(req.query.code, (err, tokens) => {

        if (!err) {

            gapi.client.setCredentials(tokens);
            pageRenderer.emit('credentialsAreSet');

        }

    });

    pageRenderer.on('credentialsAreSet', () => {

        getUserGooglePlusProfile(user);
        getUserGoogleContacts(user, '', '', true);

    });

    pageRenderer.on('methodCompleted', () => {

        methodCompletedCount += 1;

        if (methodCompletedCount === 2) {

            usersTable.add(user);
            app.locals.me = { email: user.email };
            res.render('./app/blocks/eventchoice');

        }

    });

});

function getUserGooglePlusProfile(user, tokenz) {
    // Retrieving google plus info of user
    gapi.google.plus('v1').people.get({

        userId: 'me',
        auth: gapi.client,
        params: {

            fields: ['emails', 'displayName', 'image', 'name/givenName']

        }

    }, (err, response) => {

        if (err) {

            console.log(err);
            throw err;

        }

        else {

            console.log(response);
            user.displayname = response.displayName || 'user';
            user.firstname = response.name.givenName;
            user.lastname = response.name.familyName;
            user.pw = '';
            user.googlelogin = true;
            user.image = (response.image && response.image.url) ? response.image.url : 'images/gen-green.png';
            user.imagebig = (response.image && response.image.url) ? response.image.url.replace(/\?sz=50/, '?sz=128') : 'images/gen-green.png';
            user.email = response.emails[0].value;
            user.bio = '';

            pageRenderer.emit('methodCompleted');

        }

    });

}

function getUserGoogleContacts(user, pagetoken, currentcontacts, shouldgetcontacts) {

    let contacts = (currentcontacts) ? currentcontacts : [];
    let shouldGetContacts = shouldgetcontacts;

    if (shouldGetContacts) {

        let optionsForPeopleApiRequest = {

            'resourceName': 'people/me',
            'pageSize': 500,
            'auth': gapi.client,
            'requestMask.includeField': 'person.names,person.email_addresses'

        };

        let pageToken = (pagetoken) ? pagetoken : '';

        if (pageToken) {

            optionsForPeopleApiRequest.pageToken = pageToken;

        }

        gapi.google.people('v1').people.connections.list(optionsForPeopleApiRequest, (err, response) => {

            // handle err and response
            if (err) {

                console.log(err);

            }

            else {

                let shouldGetContacts = (response.connections) ? response.connections.length === 500 : false;
                let pageToken = response.nextPageToken || '';
                let newContacts = (response.connections) ? response.connections.filter(contact => contact.emailAddresses)
                    .map(contact => {
                        return {
                            name: (contact.names) ? contact.names[0].displayName : '',
                            email: contact.emailAddresses[0].value
                        };
                    }) : [];
                contacts = contacts.concat(newContacts);
                getUserGoogleContacts(user, pageToken, contacts, shouldGetContacts);

            }

        });

    }

    else {

        user.contacts = JSON.stringify(contacts);
        pageRenderer.emit('methodCompleted');

    }

}

module.exports = app;
<commit_msg>fix: remove console log for debug<commit_after>'use strict';
const   express = require('express'),
        app = express(),
        EventEmitter = require('events'),
        pageRenderer = new EventEmitter(),
        gapi = require('../../lib/gapi.js'),
        usersTable = require('../../models/db.js').users;

app.get('/googleauth', (req, res) => {

    let methodCompletedCount = 0;
    let user = {};

    gapi.client.getToken(req.query.code, (err, tokens) => {

        if (!err) {

            gapi.client.setCredentials(tokens);
            pageRenderer.emit('credentialsAreSet');

        }

    });

    pageRenderer.on('credentialsAreSet', () => {

        getUserGooglePlusProfile(user);
        getUserGoogleContacts(user, '', '', true);

    });

    pageRenderer.on('methodCompleted', () => {

        methodCompletedCount += 1;

        if (methodCompletedCount === 2) {

            usersTable.add(user);
            app.locals.me = { email: user.email };
            res.render('./app/blocks/eventchoice');

        }

    });

});

function getUserGooglePlusProfile(user, tokenz) {
    // Retrieving google plus info of user
    gapi.google.plus('v1').people.get({

        userId: 'me',
        auth: gapi.client,
        params: {

            fields: ['emails', 'displayName', 'image', 'name/givenName']

        }

    }, (err, response) => {

        if (err) {

            console.log(err);
            throw err;

        }

        else {

            user.displayname = response.displayName || 'user';
            user.firstname = response.name.givenName;
            user.lastname = response.name.familyName;
            user.pw = '';
            user.googlelogin = true;
            user.image = (response.image && response.image.url) ? response.image.url : 'images/gen-green.png';
            user.imagebig = (response.image && response.image.url) ? response.image.url.replace(/\?sz=50/, '?sz=128') : 'images/gen-green.png';
            user.email = response.emails[0].value;
            user.bio = '';

            pageRenderer.emit('methodCompleted');

        }

    });

}

function getUserGoogleContacts(user, pagetoken, currentcontacts, shouldgetcontacts) {

    let contacts = (currentcontacts) ? currentcontacts : [];
    let shouldGetContacts = shouldgetcontacts;

    if (shouldGetContacts) {

        let optionsForPeopleApiRequest = {

            'resourceName': 'people/me',
            'pageSize': 500,
            'auth': gapi.client,
            'requestMask.includeField': 'person.names,person.email_addresses'

        };

        let pageToken = (pagetoken) ? pagetoken : '';

        if (pageToken) {

            optionsForPeopleApiRequest.pageToken = pageToken;

        }

        gapi.google.people('v1').people.connections.list(optionsForPeopleApiRequest, (err, response) => {

            // handle err and response
            if (err) {

                console.log(err);

            }

            else {

                let shouldGetContacts = (response.connections) ? response.connections.length === 500 : false;
                let pageToken = response.nextPageToken || '';
                let newContacts = (response.connections) ? response.connections.filter(contact => contact.emailAddresses)
                    .map(contact => {
                        return {
                            name: (contact.names) ? contact.names[0].displayName : '',
                            email: contact.emailAddresses[0].value
                        };
                    }) : [];
                contacts = contacts.concat(newContacts);
                getUserGoogleContacts(user, pageToken, contacts, shouldGetContacts);

            }

        });

    }

    else {

        user.contacts = JSON.stringify(contacts);
        pageRenderer.emit('methodCompleted');

    }

}

module.exports = app;
<|endoftext|>


<commit_before>// User service
// Users API resources
// author @sauliuz

var util = require('util');
var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var request = require('request');
var fh = require('fh-mbaas-api');
var validator = require('validator');
var crypto = require('crypto');
var uuid = require('uuid');

// common methods
var helper = require('../utilities/helper.js');

function projectRoutes() {

  var projectRouter = new express.Router();
  projectRouter.use(cors());
  projectRouter.use(bodyParser());

  // API resource to get all projects
  projectRouter.get('/', function(req, res) {

    // initial stage, mock responses
    res.status(200);

    var projectlist = [];
    projectlist.push({'projectname':'Project Name 1','projectid':'5703f9eb5306583d5a000018','current_practice':'Discovery','users':[{"userid": "5703f9eb5306583d5a000118"},{"userid": "5703f9eb5306583d5a000119"}]});
    projectlist.push({'projectname':'Project Name 2','projectid':'5703f9eb5306583d5a000019','current_practice':'Discovery','users':[{"userid": "5703f9eb5306583d5a000118"}]});
    projectlist.push({'projectname':'Project Name 3','projectid':'5703f9eb5306583d5a000020','current_practice':'','project_users':[]});

    res.json({
      status: "success",
      projects: projectlist
    });
  });

  // API resource to retrieve single project details
  projectRouter.get('/:projectid', function(req, res) {

    // initial stage, mock responses
    res.status(200);

    var project = {'projectname':'Project Name 1','projectid':'5703f9eb5306583d5a000018','current_practice':'Discovery',"semat_alphas": {"opportunity": "identified","requirements": "conceived","stakeholders": "recognised","team": "not established","way_of_working": "not established","work": "not established","software_system": "not established"},"users":[{"userid": "5703f9eb5306583d5a000118"}]};

    res.json({
      status: "success",
      project: project
    });
  });

  // API resource to get all projects for specific user
  projectRouter.get('/user/:userid', function(req, res) {

    // initial stage, mock responses
    res.status(200);

    var projectlist = [];
    projectlist.push({'projectname':'Project Name 1','projectid':'5703f9eb5306583d5a000018','current_practice':'Discovery','users':[{"userid": "5703f9eb5306583d5a000118"},{"userid": "5703f9eb5306583d5a000119"}]});
    projectlist.push({'projectname':'Project Name 2','projectid':'5703f9eb5306583d5a000019','current_practice':'Discovery','users':[{"userid": "5703f9eb5306583d5a000118"}]});

    res.json({
      status: "success",
      projects: projectlist
    });
  });

  // API resource to create a new project
  projectRouter.post('/', function(req, res) {

    // initial stage, mock responses
    res.status(200);

    var project = {'projectname':'Project Name 1','projectid':'5703f9eb5306583d5a000018','current_practice':'Discovery',"semat_alphas": {"opportunity": "identified","requirements": "conceived","stakeholders": "recognised","team": "not established","way_of_working": "not established","work": "not established","software_system": "not established"},"users":[{"userid": "5703f9eb5306583d5a000118"}]};

    res.json({
      status: "success",
      project: project
    });
  });

  // API resource to update an existing project
  projectRouter.put('/:projectid', function(req, res) {

    // initial stage, mock responses
    res.status(200);

    var project = {'projectname':'Project Name 1','projectid':'5703f9eb5306583d5a000018','current_practice':'Discovery',"semat_alphas": {"opportunity": "identified","requirements": "conceived","stakeholders": "recognised","team": "not established","way_of_working": "not established","work": "not established","software_system": "not established"},"users":[{"userid": "5703f9eb5306583d5a000118"}]};

    res.json({
      status: "success",
      project: project
    });
  });

  // API resource to delete an existing project
  projectRouter.delete('/:projectid', function(req, res) {

    // initial stage, mock responses
    res.status(200);

    res.json({
      status: "success",
      massage: "project deleted"
    });
  });

  return projectRouter;
};

module.exports = projectRoutes;
// the end
<commit_msg>adding project names and alphas to all project responses<commit_after>// User service
// Users API resources
// author @sauliuz

var util = require('util');
var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var request = require('request');
var fh = require('fh-mbaas-api');
var validator = require('validator');
var crypto = require('crypto');
var uuid = require('uuid');

// common methods
var helper = require('../utilities/helper.js');

function projectRoutes() {

  var projectRouter = new express.Router();
  projectRouter.use(cors());
  projectRouter.use(bodyParser());

  // API resource to get all projects
  projectRouter.get('/', function(req, res) {

    // initial stage, mock responses
    res.status(200);

    var projectlist = [];
    projectlist.push({'projectname':'AB Industries','projectid':'5703f9eb5306583d5a000018','current_practice':'Discovery',"semat_alphas": {"opportunity": "identified","requirements": "conceived","stakeholders": "recognised","team": "not established","way_of_working": "not established","work": "not established","software_system": "not established"},'users':[{"userid": "5703f9eb5306583d5a000118"},{"userid": "5703f9eb5306583d5a000119"}]});
    projectlist.push({'projectname':'Lufthansa','projectid':'5703f9eb5306583d5a000019','current_practice':'Discovery',"semat_alphas": {"opportunity": "identified","requirements": "conceived","stakeholders": "recognised","team": "not established","way_of_working": "not established","work": "not established","software_system": "not established"},'users':[{"userid": "5703f9eb5306583d5a000118"}]});
    projectlist.push({'projectname':'Deloitte Digital','projectid':'5703f9eb5306583d5a000020','current_practice':'',"semat_alphas": {"opportunity": "identified","requirements": "conceived","stakeholders": "recognised","team": "not established","way_of_working": "not established","work": "not established","software_system": "not established"},'users':[{"userid": "5703f9eb5306583d5a000118"}]});

    res.json({
      status: "success",
      projects: projectlist
    });
  });

  // API resource to retrieve single project details
  projectRouter.get('/:projectid', function(req, res) {

    // initial stage, mock responses
    res.status(200);

    projectlist.push({'projectname':'Lufthansa','projectid':'5703f9eb5306583d5a000019','current_practice':'Discovery',"semat_alphas": {"opportunity": "identified","requirements": "conceived","stakeholders": "recognised","team": "not established","way_of_working": "not established","work": "not established","software_system": "not established"},'users':[{"userid": "5703f9eb5306583d5a000118"}]});

    res.json({
      status: "success",
      project: project
    });
  });

  // API resource to get all projects for specific user
  projectRouter.get('/user/:userid', function(req, res) {

    // initial stage, mock responses
    res.status(200);

    var projectlist = [];
    projectlist.push({'projectname':'AB Industries','projectid':'5703f9eb5306583d5a000018','current_practice':'Discovery',"semat_alphas": {"opportunity": "identified","requirements": "conceived","stakeholders": "recognised","team": "not established","way_of_working": "not established","work": "not established","software_system": "not established"},'users':[{"userid": "5703f9eb5306583d5a000118"},{"userid": "5703f9eb5306583d5a000119"}]});
    projectlist.push({'projectname':'Lufthansa','projectid':'5703f9eb5306583d5a000019','current_practice':'Discovery',"semat_alphas": {"opportunity": "identified","requirements": "conceived","stakeholders": "recognised","team": "not established","way_of_working": "not established","work": "not established","software_system": "not established"},'users':[{"userid": "5703f9eb5306583d5a000118"}]});
    projectlist.push({'projectname':'Deloitte Digital','projectid':'5703f9eb5306583d5a000020','current_practice':'',"semat_alphas": {"opportunity": "identified","requirements": "conceived","stakeholders": "recognised","team": "not established","way_of_working": "not established","work": "not established","software_system": "not established"},'users':[{"userid": "5703f9eb5306583d5a000118"}]});

    res.json({
      status: "success",
      projects: projectlist
    });
  });

  // API resource to create a new project
  projectRouter.post('/', function(req, res) {

    // initial stage, mock responses
    res.status(200);

    var project = {'projectname':'Project Name 1','projectid':'5703f9eb5306583d5a000018','current_practice':'Discovery',"semat_alphas": {"opportunity": "identified","requirements": "conceived","stakeholders": "recognised","team": "not established","way_of_working": "not established","work": "not established","software_system": "not established"},"users":[{"userid": "5703f9eb5306583d5a000118"}]};

    res.json({
      status: "success",
      project: project
    });
  });

  // API resource to update an existing project
  projectRouter.put('/:projectid', function(req, res) {

    // initial stage, mock responses
    res.status(200);

    var project = {'projectname':'Project Name 1','projectid':'5703f9eb5306583d5a000018','current_practice':'Discovery',"semat_alphas": {"opportunity": "identified","requirements": "conceived","stakeholders": "recognised","team": "not established","way_of_working": "not established","work": "not established","software_system": "not established"},"users":[{"userid": "5703f9eb5306583d5a000118"}]};

    res.json({
      status: "success",
      project: project
    });
  });

  // API resource to delete an existing project
  projectRouter.delete('/:projectid', function(req, res) {

    // initial stage, mock responses
    res.status(200);

    res.json({
      status: "success",
      massage: "project deleted"
    });
  });

  return projectRouter;
};

module.exports = projectRoutes;
// the end
<|endoftext|>


<commit_before>function Newsletter(router, translator, admin) {

    var self = this;

    this.initSend = function(router) {
        $(document).on('click', '[data-type=send]', function() {
            var form = $(this).parents('form');
            var data = form.serialize();
            var sent = form.find('[data-newsletter-sent]');
            var route = $(this).attr('data-route');
            var id = form.attr('data-id');
            var url = router.generate(route, { id: id });
            if(sent.length == 0) {
               self.sendNewsletter(data, url, form);
            } else {
                var text = sent.attr('data-sent-text');
                console.log(text);
                var sendAgain = confirm(text);
                if(sendAgain == true) {
                    self.sendNewsletter(data, url, form);
                }
            }
        });
    };

    this.sendNewsletter = function(data, url, form) {
        admin.openLoadingOverlay();
        $.ajax({
            type: 'POST',
            data: data,
            url: url,
            success: function() {
                admin.closeLoadingOverlay();
                admin.overlayMessage(translator.trans('newsletter.action.sent.success'), 'info');
                admin.overlayClose();
            },
            error: function() {
                admin.closeLoadingOverlay();
                admin.overlayMessage(translator.trans('newsletter.action.sent.error'), 'error');
                admin.overlayClose();
            }
        });
    };

    this.initAddEmail = function() {
        $("#addEmail").click(function () {
            var url = $("#addEmailForm").attr('action');
            var email = $('input[name="enhavo_newsletter_subscriber[email]"]').val();
            data = $("#addEmailForm").serialize();
            admin.openLoadingOverlay();
            $.post(url, data, function (response) {
                admin.closeLoadingOverlay();
                $("#addEmailForm").get(0).reset();

                var code = $.now()+email;
            })
                .fail(function(jqXHR) {
                    admin.closeLoadingOverlay();
                    var data = JSON.parse(jqXHR.responseText);

                    if(data.code == 400) {
                        var getErrors = function(data, errors) {
                            if(typeof errors == 'undefined') {
                                errors = [];
                            }

                            for (var key in data) {
                                if(data.hasOwnProperty(key)) {

                                    if(key == 'errors') {
                                        for (var error in data[key]) {
                                            if (data[key].hasOwnProperty(error) && typeof data[key][error] == 'string') {
                                                errors.push(data[key][error]);
                                            }
                                        }
                                    }

                                    if (typeof data[key] == 'object') {
                                        getErrors(data[key], errors);
                                    }

                                }
                            }

                            return errors
                        };

                        var errors = getErrors(data.errors);
                        alert(errors[0]);
                    } else {
                        alert("Error")
                    }
                });
            return false;
        });
    };

    var init = function() {
        self.initAddEmail();
        self.initSend(router);
    };

    init();
}<commit_msg>login overlayMessage changed, console logs removed, validation for userBundle added, changedPasswordController changed<commit_after>function Newsletter(router, translator, admin) {

    var self = this;

    this.initSend = function(router) {
        $(document).on('click', '[data-type=send]', function() {
            var form = $(this).parents('form');
            var data = form.serialize();
            var sent = form.find('[data-newsletter-sent]');
            var route = $(this).attr('data-route');
            var id = form.attr('data-id');
            var url = router.generate(route, { id: id });
            if(sent.length == 0) {
               self.sendNewsletter(data, url, form);
            } else {
                var text = sent.attr('data-sent-text');
                var sendAgain = confirm(text);
                if(sendAgain == true) {
                    self.sendNewsletter(data, url, form);
                }
            }
        });
    };

    this.sendNewsletter = function(data, url, form) {
        admin.openLoadingOverlay();
        $.ajax({
            type: 'POST',
            data: data,
            url: url,
            success: function() {
                admin.closeLoadingOverlay();
                admin.overlayMessage(translator.trans('newsletter.action.sent.success'), 'info');
                admin.overlayClose();
            },
            error: function() {
                admin.closeLoadingOverlay();
                admin.overlayMessage(translator.trans('newsletter.action.sent.error'), 'error');
                admin.overlayClose();
            }
        });
    };

    this.initAddEmail = function() {
        $("#addEmail").click(function () {
            var url = $("#addEmailForm").attr('action');
            var email = $('input[name="enhavo_newsletter_subscriber[email]"]').val();
            data = $("#addEmailForm").serialize();
            admin.openLoadingOverlay();
            $.post(url, data, function (response) {
                admin.closeLoadingOverlay();
                $("#addEmailForm").get(0).reset();

                var code = $.now()+email;
            })
                .fail(function(jqXHR) {
                    admin.closeLoadingOverlay();
                    var data = JSON.parse(jqXHR.responseText);

                    if(data.code == 400) {
                        var getErrors = function(data, errors) {
                            if(typeof errors == 'undefined') {
                                errors = [];
                            }

                            for (var key in data) {
                                if(data.hasOwnProperty(key)) {

                                    if(key == 'errors') {
                                        for (var error in data[key]) {
                                            if (data[key].hasOwnProperty(error) && typeof data[key][error] == 'string') {
                                                errors.push(data[key][error]);
                                            }
                                        }
                                    }

                                    if (typeof data[key] == 'object') {
                                        getErrors(data[key], errors);
                                    }

                                }
                            }

                            return errors
                        };

                        var errors = getErrors(data.errors);
                        alert(errors[0]);
                    } else {
                        alert("Error")
                    }
                });
            return false;
        });
    };

    var init = function() {
        self.initAddEmail();
        self.initSend(router);
    };

    init();
}<|endoftext|>


<commit_before>(function (global) {
  'use strict';

  // Constructor
  function MenuButton (button) {
    // Save a reference to the element
    this.button = button;

    // Add (initial) button semantics
    this.button.setAttribute('aria-haspopup', 'true');
    this.button.setAttribute('aria-expanded', 'false');

    // Get the menu
    this.menuId = this.button.getAttribute('data-opens-menu');
    this.menu = document.getElementById(this.menuId) || false;

    // If the menu doesn't exist
    // exit with an error referencing the missing
    // menu's id
    if (!this.menu) {
      console.error(`#${this.menuId} menu missing`);
      return;
    }

    // Add menu semantics
    this.menu.setAttribute('role', 'menu');

    // Hide menu initially
    this.menu.hidden = true;

    // Get the menu items
    this.menuItems = this.menu.querySelectorAll('button');
    this.firstItem = this.menuItems[0];
    this.lastItem = this.menuItems[this.menuItems.length - 1];

    [].forEach.call(this.menuItems, menuItem => {
      // Add menu item semantics
      menuItem.setAttribute('role', 'menuitem');

      // Prevent tab focus on menu items
      menuItem.setAttribute('tabindex', '-1');

      // Handle key presses for menuItem
      menuItem.addEventListener('keydown', e => {
        // Go to next/previous item if it exists
        // or loop around
        let adjacent;
        if (e.keyCode == 40) {
          e.preventDefault();
          adjacent = menuItem.nextElementSibling
                     || this.firstItem;
          adjacent.focus();
        }
        if (e.keyCode == 38) {
          e.preventDefault();
          adjacent = menuItem.previousElementSibling
                     || this.lastItem;
          adjacent.focus();
        }

        // Close on escape or tab
        if (e.keyCode == 27 || e.keyCode == 9) {
          this.toggle();
        }
        // If escape, refocus menu button
        if (e.keyCode == 27) {
          this.button.focus();
        }
      });

      menuItem.addEventListener('click', () => {
        this.close();
        this.button.focus();
      });
    });

    // Handle button click
    this.button.addEventListener('click', () => {
      this.toggle();
    });

    // Also toggle on keydown
    this.button.addEventListener('keydown', e => {
      if (e.keyCode == 40) {
        if (this.menu.hidden) {
          this.toggle();
        } else {
          this.firstItem.focus();
        }
      }
    });
  }

  // Open method
  MenuButton.prototype.open = function () {
    this.button.setAttribute('aria-expanded', 'true');
    this.menu.hidden = false;
    this.menuItems[0].focus();
  };

  // Close method
  MenuButton.prototype.close = function () {
    this.button.setAttribute('aria-expanded', 'false');
    this.menu.hidden = true;
    return this;
  };

  // Toggle method
  MenuButton.prototype.toggle = function () {
    let expanded = this.button.getAttribute('aria-expanded') === 'true';
    expanded ? this.close() : this.open();
  };

  // Export MenuButton
  if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
    module.exports = MenuButton;
  } else if (typeof define === 'function' && define.amd) {
    define('MenuButton', [], function () {
      return MenuButton;
    });
  } else if (typeof global === 'object') {
    // attach to window
    global.MenuButton = MenuButton;
  }
}(this));
<commit_msg>Saved a few bytes on using proper booleans<commit_after>(function (global) {
  'use strict';

  // Constructor
  function MenuButton (button) {
    // Save a reference to the element
    this.button = button;

    // Add (initial) button semantics
    this.button.setAttribute('aria-haspopup', true);
    this.button.setAttribute('aria-expanded', false);

    // Get the menu
    this.menuId = this.button.getAttribute('data-opens-menu');
    this.menu = document.getElementById(this.menuId) || false;

    // If the menu doesn't exist
    // exit with an error referencing the missing
    // menu's id
    if (!this.menu) {
      console.error(`#${this.menuId} menu missing`);
      return;
    }

    // Add menu semantics
    this.menu.setAttribute('role', 'menu');

    // Hide menu initially
    this.menu.hidden = true;

    // Get the menu items
    this.menuItems = this.menu.querySelectorAll('button');
    this.firstItem = this.menuItems[0];
    this.lastItem = this.menuItems[this.menuItems.length - 1];

    [].forEach.call(this.menuItems, menuItem => {
      // Add menu item semantics
      menuItem.setAttribute('role', 'menuitem');

      // Prevent tab focus on menu items
      menuItem.setAttribute('tabindex', '-1');

      // Handle key presses for menuItem
      menuItem.addEventListener('keydown', e => {
        // Go to next/previous item if it exists
        // or loop around
        let adjacent;
        if (e.keyCode == 40) {
          e.preventDefault();
          adjacent = menuItem.nextElementSibling
                     || this.firstItem;
          adjacent.focus();
        }
        if (e.keyCode == 38) {
          e.preventDefault();
          adjacent = menuItem.previousElementSibling
                     || this.lastItem;
          adjacent.focus();
        }

        // Close on escape or tab
        if (e.keyCode == 27 || e.keyCode == 9) {
          this.toggle();
        }
        // If escape, refocus menu button
        if (e.keyCode == 27) {
          this.button.focus();
        }
      });

      menuItem.addEventListener('click', () => {
        this.close();
        this.button.focus();
      });
    });

    // Handle button click
    this.button.addEventListener('click', () => {
      this.toggle();
    });

    // Also toggle on keydown
    this.button.addEventListener('keydown', e => {
      if (e.keyCode == 40) {
        if (this.menu.hidden) {
          this.toggle();
        } else {
          this.firstItem.focus();
        }
      }
    });
  }

  // Open method
  MenuButton.prototype.open = function () {
    this.button.setAttribute('aria-expanded', true);
    this.menu.hidden = false;
    this.menuItems[0].focus();
  };

  // Close method
  MenuButton.prototype.close = function () {
    this.button.setAttribute('aria-expanded', false);
    this.menu.hidden = true;
    return this;
  };

  // Toggle method
  MenuButton.prototype.toggle = function () {
    let expanded = this.button.getAttribute('aria-expanded') === 'true';
    expanded ? this.close() : this.open();
  };

  // Export MenuButton
  if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
    module.exports = MenuButton;
  } else if (typeof define === 'function' && define.amd) {
    define('MenuButton', [], function () {
      return MenuButton;
    });
  } else if (typeof global === 'object') {
    // attach to window
    global.MenuButton = MenuButton;
  }
}(this));
<|endoftext|>


<commit_before>$(document).ready(function () {

    var imageNavThumbs = $('#thumbnails .img img');

    // hide thumbnav if there is only one image to view
    if( imageNavThumbs.size() <= 1 ){
        $('#thumbnails').hide();
    }

    // regular images present
    if ( $('#image-viewer').length) {
        imageNavThumbs.each(function(index, el) {
            // switch image src onclick
            $(el).on("click", function() {
                var index = $('#thumbnails .img img').index(el);
                var imageSrc = $('#imageUrls a').get(index);
                if(typeof imageSrc !== 'undefined') {
                    $('#image-viewer .img img').attr("src", imageSrc)
                }
            });
        });

    }

    // deepzoom images present
    if ($('#zoom-viewer').length) {
        var viewer;
        // activate deepzoom functionality for first image
        activateDeepZoom(0)
        // switch zoom image onclick
        imageNavThumbs.each(function(index, el) {
            $(el).on("click", function() { activateDeepZoom(el); });
        });
    }

    function activateDeepZoom(el) {
        var index = imageNavThumbs.index(el);
        var deepZoomElement = $('#deepZoomUrls a').get(index);
        if (typeof deepZoomElement !== 'undefined') {
            var deepZoomUrl = $(deepZoomElement).attr("href");
            if(typeof viewer === 'undefined') {
                Seadragon.Config.imagePath = "/assets/common/javascripts/seadragon/img/";
                Seadragon.Config.autoHideControls = false;
                viewer = new Seadragon.Viewer("zoom-viewer");
            }
            viewer.openDzi({
                "url":deepZoomUrl,
                "width":1800,
                "height":1400,
                "tileSize":256,
                "tileOverlap":0,
                "tileFormat":"jpg"});
        }
    }

    if ($('#rightsUrl').length) {
        var rights = $('#rightsUrl').find('a').attr('href'), icon='', img = new Image();

        if (rights != 'undefined') {
            switch (rights) {
                case 'http://creativecommons.org/publicdomain/mark/1.0/':
                    icon = 'cc_publicdomain_mark.png';
                    break;
                case 'http://creativecommons.org/publicdomain/zero/1.0/':
                    icon = 'cc_publicdomain_zero.png';
                    break;
                case 'http://creativecommons.org/licenses/by/3.0/':
                    icon = 'cc_by.png';
                    break;
                case 'http://creativecommons.org/licenses/by-nd/3.0/':
                    icon = 'cc_by-nd-3.0.png';
                    break;
                case 'http://creativecommons.org/licenses/by-nc-sa/3.0/':
                    icon = 'cc_by-nc-sa-3.0.png';
                    break;
                case 'http://creativecommons.org/licenses/by-sa/3.0/nl/':
                    icon = 'cc_by-sa-3.0.png';
                    break;
                case 'http://creativecommons.org/licenses/by-sa/3.0':
                    icon = 'cc_by-sa-3.0.png';
                    break;
                case 'http://creativecommons.org/licenses/by-nc/3.0':
                    icon = 'cc_by-nc-3.0.png';
                    break;
                case 'http://creativecommons.org/licenses/by-nc-nd/3.0':
                    icon = 'cc_by-nc-nd-3.0.png';
                    break;
                case 'http://www.europeana.eu/rights/rr-f/':
                    icon = 'eu_free_access.jpg';
                    break;
                case 'http://www.europeana.eu/rights/rr-p/':
                    icon = 'eu_paid_access.jpg';
                    break;
                case 'http://www.europeana.eu/rights/rr-r/':
                    icon = 'eu_restricted_access.jpg';
                    break;
                default:
                    icon = '';
            }
            if (icon != '') {
                img.src = '/assets/common/images/rights/'+icon;
                $('#rightsUrl').find('a').append(img);
            }
        }
    }

    // Endpoint to retrieve related items for this object
    var mltEndpoint = '/organizations/' + Thing.orgId + '/api/search?id=' + Thing.hubId + '&format=json&mlt=true';

    if(jsLabels.objTitle.length && $('#object-title-big').length) {
        $('#object-title-big').html(jsLabels.objTitle);
    }

    // Make the request for the related objects. If this is a Collection or a Museum, then this request will fail.
    // Use the bad request to change the layout to accomodate a Museum or Collection view definition
    try {
    $.ajax({
        type: "GET",
        url: mltEndpoint,
        success: function(data){
            var rItems = data.result.relatedItems.item, html = '', tmp, org, owner, id, uri;
            if (rItems) {
                $('.object-title').toggleClass('hide');
                html = '
' + jsLabels.relatedItems + '
';
                $.each(rItems, function (i, item) {
                    tmp = item.fields['delving_hubId'].split('_');
                    org = tmp[0];
                    owner = tmp[1];
                    id = tmp[2];
                    uri = "/" + org + "/" + owner + "/" + id + "?mlt=true";
                    html += '
';
                    html += '';
                    html += '

'+item.fields['delving_title'].trunc(40)+'
';
                    if (item.fields['dc_creator']) {
                        html += '
'+jsLabels.creator+': '+item.fields['dc_creator']+'
';
                    }
                    if (item.fields['europeana_collectionTitle']) {
                        html += '
'+jsLabels.collection+': '+item.fields['europeana_collectionTitle']+'
';
                    }
                    html += '

';
                });
                html += "
";
                $('#related-items').html(html);
            }
        },
        error: function(){
//            $('.object-data').removeClass('span8');
        }
    });
    } catch(e) {
        //..do nothing
    }
});<commit_msg>rights switch .. remove trailing slash from rights url for conformity<commit_after>$(document).ready(function () {

    var imageNavThumbs = $('#thumbnails .img img');

    // hide thumbnav if there is only one image to view
    if( imageNavThumbs.size() <= 1 ){
        $('#thumbnails').hide();
    }

    // regular images present
    if ( $('#image-viewer').length) {
        imageNavThumbs.each(function(index, el) {
            // switch image src onclick
            $(el).on("click", function() {
                var index = $('#thumbnails .img img').index(el);
                var imageSrc = $('#imageUrls a').get(index);
                if(typeof imageSrc !== 'undefined') {
                    $('#image-viewer .img img').attr("src", imageSrc)
                }
            });
        });

    }

    // deepzoom images present
    if ($('#zoom-viewer').length) {
        var viewer;
        // activate deepzoom functionality for first image
        activateDeepZoom(0)
        // switch zoom image onclick
        imageNavThumbs.each(function(index, el) {
            $(el).on("click", function() { activateDeepZoom(el); });
        });
    }

    function activateDeepZoom(el) {
        var index = imageNavThumbs.index(el);
        var deepZoomElement = $('#deepZoomUrls a').get(index);
        if (typeof deepZoomElement !== 'undefined') {
            var deepZoomUrl = $(deepZoomElement).attr("href");
            if(typeof viewer === 'undefined') {
                Seadragon.Config.imagePath = "/assets/common/javascripts/seadragon/img/";
                Seadragon.Config.autoHideControls = false;
                viewer = new Seadragon.Viewer("zoom-viewer");
            }
            viewer.openDzi({
                "url":deepZoomUrl,
                "width":1800,
                "height":1400,
                "tileSize":256,
                "tileOverlap":0,
                "tileFormat":"jpg"});
        }
    }

    if ($('#rightsUrl').length) {
        var rights = stripTrailingSlash($('#rightsUrl').find('a').attr('href')), icon='', img = new Image();
        if (rights != 'undefined') {
            switch (rights) {
                case 'http://creativecommons.org/publicdomain/mark/1.0':
                    icon = 'cc_publicdomain_mark.png';
                    break;
                case 'http://creativecommons.org/publicdomain/zero/1.0':
                    icon = 'cc_publicdomain_zero.png';
                    break;
                case 'http://creativecommons.org/licenses/by/3.0':
                    icon = 'cc_by.png';
                    break;
                case 'http://creativecommons.org/licenses/by-nd/3.0':
                    icon = 'cc_by-nd-3.0.png';
                    break;
                case 'http://creativecommons.org/licenses/by-nc-sa/3.0':
                    icon = 'cc_by-nc-sa-3.0.png';
                    break;
                case 'http://creativecommons.org/licenses/by-sa/3.0/nl':
                    icon = 'cc_by-sa-3.0.png';
                    break;
                case 'http://creativecommons.org/licenses/by-sa/3.0':
                    icon = 'cc_by-sa-3.0.png';
                    break;
                case 'http://creativecommons.org/licenses/by-nc/3.0':
                    icon = 'cc_by-nc-3.0.png';
                    break;
                case 'http://creativecommons.org/licenses/by-nc-nd/3.0':
                    icon = 'cc_by-nc-nd-3.0.png';
                    break;
                case 'http://www.europeana.eu/rights/rr-f':
                    icon = 'eu_free_access.jpg';
                    break;
                case 'http://www.europeana.eu/rights/rr-p':
                    icon = 'eu_paid_access.jpg';
                    break;
                case 'http://www.europeana.eu/rights/rr-r':
                    icon = 'eu_restricted_access.jpg';
                    break;
                default:
                    icon = '';
            }
            if (icon != '') {
                img.src = '/assets/common/images/rights/'+icon;
                $('#rightsUrl').find('a').append(img);
            }
        }
    }

    // Endpoint to retrieve related items for this object
    var mltEndpoint = '/organizations/' + Thing.orgId + '/api/search?id=' + Thing.hubId + '&format=json&mlt=true';

    if(jsLabels.objTitle.length && $('#object-title-big').length) {
        $('#object-title-big').html(jsLabels.objTitle);
    }

    // Make the request for the related objects. If this is a Collection or a Museum, then this request will fail.
    // Use the bad request to change the layout to accomodate a Museum or Collection view definition
    try {
    $.ajax({
        type: "GET",
        url: mltEndpoint,
        success: function(data){
            var rItems = data.result.relatedItems.item, html = '', tmp, org, owner, id, uri, title;
            if (rItems) {

                $('.object-title').toggleClass('hide');
                html = '
' + jsLabels.relatedItems + '
';
                $.each(rItems, function (i, item) {

                    tmp = item.fields['delving_hubId'].split('_');
                    org = tmp[0];
                    owner = tmp[1];
                    id = tmp[2];
                    uri = "/" + org + "/" + owner + "/" + id + "?mlt=true";
                    // clean up title since sometimes it contains html
                    title = item.fields['delving_title'].replace(/<\/?[a-z][a-z0-9]*[^<>]*>/ig, "");

                    html += '
';
                    html += '';
                    html += '

'+ title.trunc(40) +'
';
                    if (item.fields['dc_creator']) {
                        html += '
'+jsLabels.creator+': '+item.fields['dc_creator']+'
';
                    }
                    if (item.fields['europeana_collectionTitle']) {
                        html += '
'+jsLabels.collection+': '+item.fields['europeana_collectionTitle']+'
';
                    }
                    html += '

';
                });
                html += "
";
                $('#related-items').html(html);
            }
        },
        error: function(){
//            $('.object-data').removeClass('span8');
        }
    });
    } catch(e) {
        //..do nothing
    }
});

function stripTrailingSlash(str) {
    if(str.substr(-1) == '/') {
        return str.substr(0, str.length - 1);
    }
    return str;
}<|endoftext|>


<commit_before>import { centerStyles } from './styles';
import { configure, addDecorator } from '@storybook/react';
import { withBackgrounds } from '@storybook/addon-backgrounds';
import { withInfo } from '@storybook/addon-info';
import { withKnobs } from '@storybook/addon-knobs';
import { withOptions } from '@storybook/addon-options';
import pkg from '../package.json';
import PropTable from '../stories/components/propTable';
import styles from '@sambego/storybook-styles';

// addon-background
addDecorator(
  withBackgrounds([
    { name: 'White', value: '#ffffff', default: true },
    { name: 'Aqua lightest', value: '#e6f2ff' },
    { name: 'Neutral', value: '#f7f7fa' },
    { name: 'Gold lightest', value: '#ffeecc' },
    { name: 'Mint lightest', value: '#d3f2f2' },
    { name: 'Ruby lightest', value: '#ffe2d9' },
    { name: 'Teal lightest', value: '#e1ecfa' },
    { name: 'Violet lightest', value: '#f0f0ff' },
    { name: 'Teal darkest', value: '#2a3b4d' },
  ]),
);

// addon-info
addDecorator(
  withInfo({
    inline: true,
    source: true,
    styles: stylesheet => {
      stylesheet.infoBody = {
        color: '#2a3b4d',
        fontFamily: 'Inter-UI-Regular',
        fontSize: '14px',
        margin: '48px 0',
        padding: '0',
      };

      stylesheet.header = {
        h1: {
          fontFamily: 'Inter-UI-Medium',
          fontSize: '24px',
          fontWeight: 500,
          lineHeight: '30px',
          margin: 0,
        },
        h2: {
          color: '#82828c',
          fontFamily: 'Inter-UI-Medium',
          fontSize: '18px',
          fontWeight: 500,
          lineHeight: '24px',
          margin: '24px 0 10px 0',
        },
        body: {
          borderBottom: '1px solid #c0c0c4',
          paddingTop: 10,
          marginBottom: 10,
        },
      };

      stylesheet.source = {
        h1: {
          borderBottom: '1px solid #c0c0c4',
          color: '#82828c',
          fontFamily: 'Inter-UI-Medium',
          margin: '24px 0 10px 0',
          fontWeight: 500,
          fontSize: '18px',
          lineHeight: '24px',
          padding: '12px 0',
        },
      };

      stylesheet.propTableHead = {
        color: '#344b63',
        fontFamily: 'Inter-UI-Medium',
        fontWeight: 500,
        fontSize: '16px',
        lineHeight: '21px',
        margin: '20px 0 0 0',
      };

      return stylesheet;
    },
    TableComponent: PropTable,
  }),
);

// addon-knobs
addDecorator(withKnobs);

// addon-options
addDecorator(
  withOptions({
    addonPanelInRight: true,
    enableShortcuts: false,
    name: `UI Version ${pkg.version}`,
    url: 'https://teamleader.design',
  }),
);

// addon-styles
addDecorator(styles({ ...centerStyles }));

const req = require.context('../stories', true, /\.js$/);

configure(() => {
  req.keys().forEach(filename => req(filename));
}, module);
<commit_msg>:recycle: remove addDecorator in favour of addParameters<commit_after>import { centerStyles } from './styles';
import { configure, addDecorator, addParameters } from '@storybook/react';
import { withInfo } from '@storybook/addon-info';
import { withKnobs } from '@storybook/addon-knobs';
import pkg from '../package.json';
import PropTable from '../stories/components/propTable';
import styles from '@sambego/storybook-styles';

// global parameters
addParameters({
  options: {
    addonPanelInRight: true,
    enableShortcuts: false,
    name: `UI Version ${pkg.version}`,
    url: 'https://teamleader.design',
  },
  backgrounds: [
    { name: 'White', value: '#ffffff', default: true },
    { name: 'Aqua lightest', value: '#e6f2ff' },
    { name: 'Neutral', value: '#f7f7fa' },
    { name: 'Gold lightest', value: '#ffeecc' },
    { name: 'Mint lightest', value: '#d3f2f2' },
    { name: 'Ruby lightest', value: '#ffe2d9' },
    { name: 'Teal lightest', value: '#e1ecfa' },
    { name: 'Violet lightest', value: '#f0f0ff' },
    { name: 'Teal darkest', value: '#2a3b4d' },
  ],
});

// addon-info
addDecorator(
  withInfo({
    inline: true,
    source: true,
    styles: stylesheet => {
      stylesheet.infoBody = {
        color: '#2a3b4d',
        fontFamily: 'Inter-UI-Regular',
        fontSize: '14px',
        margin: '48px 0',
        padding: '0',
      };

      stylesheet.header = {
        h1: {
          fontFamily: 'Inter-UI-Medium',
          fontSize: '24px',
          fontWeight: 500,
          lineHeight: '30px',
          margin: 0,
        },
        h2: {
          color: '#82828c',
          fontFamily: 'Inter-UI-Medium',
          fontSize: '18px',
          fontWeight: 500,
          lineHeight: '24px',
          margin: '24px 0 10px 0',
        },
        body: {
          borderBottom: '1px solid #c0c0c4',
          paddingTop: 10,
          marginBottom: 10,
        },
      };

      stylesheet.source = {
        h1: {
          borderBottom: '1px solid #c0c0c4',
          color: '#82828c',
          fontFamily: 'Inter-UI-Medium',
          margin: '24px 0 10px 0',
          fontWeight: 500,
          fontSize: '18px',
          lineHeight: '24px',
          padding: '12px 0',
        },
      };

      stylesheet.propTableHead = {
        color: '#344b63',
        fontFamily: 'Inter-UI-Medium',
        fontWeight: 500,
        fontSize: '16px',
        lineHeight: '21px',
        margin: '20px 0 0 0',
      };

      return stylesheet;
    },
    TableComponent: PropTable,
  }),
);

// addon-knobs
addDecorator(withKnobs);

// addon-styles
addDecorator(styles({ ...centerStyles }));

const req = require.context('../stories', true, /\.js$/);

configure(() => {
  req.keys().forEach(filename => req(filename));
}, module);
<|endoftext|>