<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/**
 * tabiframe.js
 *
 * tabiframe implements the <tab-iframe> tab. It's a wrapper
 * around a <iframe mozbrowser>.
 *
 */

define(['js/eventemitter'], function(EventEmitter) {

  'use strict';

  const MIN_ZOOM = 0.5;
  const MAX_ZOOM = 2;

  const IFRAME_EVENTS = [
    'mozbrowserasyncscroll', 'mozbrowserclose', 'mozbrowsercontextmenu',
    'mozbrowsererror', 'mozbrowsericonchange', 'mozbrowserloadend',
    'mozbrowserloadstart', 'mozbrowserlocationchange', 'mozbrowseropenwindow',
    'mozbrowsersecuritychange', 'mozbrowsershowmodalprompt', 'mozbrowsertitlechange',
    'mozbrowserusernameandpasswordrequired'
  ];

  let tabIframeProto = Object.create(HTMLElement.prototype);

  tabIframeProto.setLocation = function(url) {
    if (!this._innerIframe) {
      this._createInnerIframe();
    }
    if (window.IS_PRIVILEGED) {
      this._innerIframe.src = url;
    } else {
      this._innerIframe.src = 'data:,' + url;
    }
  };

  tabIframeProto.willBeVisibleSoon = function() {
    if (window.IS_PRIVILEGED && this._innerIframe) {
      this._innerIframe.setVisible(true);
    }
  };

  tabIframeProto.show = function() {
    this.removeAttribute('hidden');
    if (window.IS_PRIVILEGED && this._innerIframe) {
      this._innerIframe.setVisible(true);
    }
    this.emit('visible');
  };

  tabIframeProto.hide = function() {
    this.setAttribute('hidden', 'true');
    if (window.IS_PRIVILEGED && this._innerIframe) {
      this._innerIframe.setVisible(false);
    }
    this.emit('hidden');
  };

  tabIframeProto.createdCallback = function() {
    this._zoom = 1;
    this._clearTabData();
    EventEmitter.decorate(this);
  };

  tabIframeProto._createInnerIframe = function() {
    let iframe = document.createElement('iframe');
    iframe.setAttribute('mozbrowser', 'true');
    iframe.setAttribute('flex', '1');
    iframe.setAttribute('remote', 'true');
    iframe.setAttribute('mozallowfullscreen', 'true');
    this.appendChild(iframe);
    for (let eventName of IFRAME_EVENTS) {
      iframe.addEventListener(eventName, this);
    }
    this._innerIframe = iframe;
    this._applyZoom();
  };

  tabIframeProto.attachedCallback = function() {
  };

  tabIframeProto.detachedCallback = function() {
    if (this._innerIframe) {
      for (let eventName of IFRAME_EVENTS) {
        this._innerIframe.removeEventListener(eventName, this);
      }
    }
  };

  tabIframeProto.zoomIn = function() {
    this._zoom += 0.1;
    this._zoom = Math.min(MAX_ZOOM, this._zoom);
    this._applyZoom();
  };

  tabIframeProto.zoomOut = function() {
    this._zoom -= 0.1;
    this._zoom = Math.max(MIN_ZOOM, this._zoom);
    this._applyZoom();
  };

  tabIframeProto.resetZoom = function() {
    this._zoom = 1;
    this._applyZoom();
  };

  tabIframeProto._applyZoom = function() {
    if (this._innerIframe && window.IS_PRIVILEGED) {
      this._innerIframe.zoom(this._zoom);
    }
  };

  tabIframeProto.reload = function() {
    if (this._innerIframe) this._innerIframe.reload();
  };

  tabIframeProto.stop = function() {
    if (this._innerIframe) this._innerIframe.stop();
  };

  tabIframeProto.goBack = function() {
    if (this._innerIframe) this._innerIframe.goBack();
  };

  tabIframeProto.goForward = function() {
    if (this._innerIframe) this._innerIframe.goForward();
  };

  tabIframeProto._clearTabData = function() {
    this._loading = false;
    this._title = '';
    this._location = '';
    this._favicon = '';
    this._securityState = 'unsecure';
    this._securityExtendedValidation = false;
  };

  Object.defineProperty(tabIframeProto, 'loading', {
    get: function() {
      return this._loading;
    }
  });

  Object.defineProperty(tabIframeProto, 'title', {
    get: function() {
      return this._title;
    }
  });

  Object.defineProperty(tabIframeProto, 'location', {
    get: function() {
      return this._location;
    }
  });

  Object.defineProperty(tabIframeProto, 'favicon', {
    get: function() {
      return this._favicon;
    }
  });

  Object.defineProperty(tabIframeProto, 'securityState', {
    get: function() {
      return this._securityState;
    }
  });

  Object.defineProperty(tabIframeProto, 'securityExtendedValidation', {
    get: function() {
      return this._securityExtendedValidation;
    }
  });

  tabIframeProto.canGoBack = function() {
    return new Promise((resolve, reject) => {
      if (!this._innerIframe) {
        return resolve(false);
      }
      this._innerIframe.getCanGoBack().onsuccess = r => {
        return resolve(r.target.result);
      };
    });
  };

  tabIframeProto.canGoForward = function() {
    return new Promise((resolve, reject) => {
      if (!this._innerIframe) {
        return resolve(false);
      }
      this._innerIframe.getCanGoForward().onsuccess = r => {
        return resolve(r.target.result);
      };
    });
  };

  tabIframeProto.focus = function() {
    if (this._innerIframe) {
      this._innerIframe.focus();
    }
  };

  tabIframeProto.userInput = '';

  tabIframeProto.handleEvent = function(e) {
    let somethingChanged = true;

    switch (e.type) {
      case 'mozbrowserloadstart':
        this._clearTabData();
        this._loading = true;
        break;
      case 'mozbrowserloadend':
        this._loading = false;
        break;
      case 'mozbrowsertitlechange':
        this._title = e.detail;
        break;
      case 'mozbrowserlocationchange':
        this.userInput = '';
        this._location = e.detail;
        break;
      case 'mozbrowsericonchange':
        this._favicon = e.detail.href;
        break;
      case 'mozbrowsererror':
        this._loading = false;
        break;
      case 'mozbrowsersecuritychange':
        this._securityState = e.detail.state;
        this._securityExtendedValidation = e.detail.extendedValidation;
        break;
      default:
        somethingChanged = false;
    }

    // Forward event
    this.emit(e.type, e, this);
  };

  let TabIframe = document.registerElement('tab-iframe', {prototype: tabIframeProto});
  return TabIframe;
});
<commit_msg>typo fix unsecure -> insecure<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/**
 * tabiframe.js
 *
 * tabiframe implements the <tab-iframe> tab. It's a wrapper
 * around a <iframe mozbrowser>.
 *
 */

define(['js/eventemitter'], function(EventEmitter) {

  'use strict';

  const MIN_ZOOM = 0.5;
  const MAX_ZOOM = 2;

  const IFRAME_EVENTS = [
    'mozbrowserasyncscroll', 'mozbrowserclose', 'mozbrowsercontextmenu',
    'mozbrowsererror', 'mozbrowsericonchange', 'mozbrowserloadend',
    'mozbrowserloadstart', 'mozbrowserlocationchange', 'mozbrowseropenwindow',
    'mozbrowsersecuritychange', 'mozbrowsershowmodalprompt', 'mozbrowsertitlechange',
    'mozbrowserusernameandpasswordrequired'
  ];

  let tabIframeProto = Object.create(HTMLElement.prototype);

  tabIframeProto.setLocation = function(url) {
    if (!this._innerIframe) {
      this._createInnerIframe();
    }
    if (window.IS_PRIVILEGED) {
      this._innerIframe.src = url;
    } else {
      this._innerIframe.src = 'data:,' + url;
    }
  };

  tabIframeProto.willBeVisibleSoon = function() {
    if (window.IS_PRIVILEGED && this._innerIframe) {
      this._innerIframe.setVisible(true);
    }
  };

  tabIframeProto.show = function() {
    this.removeAttribute('hidden');
    if (window.IS_PRIVILEGED && this._innerIframe) {
      this._innerIframe.setVisible(true);
    }
    this.emit('visible');
  };

  tabIframeProto.hide = function() {
    this.setAttribute('hidden', 'true');
    if (window.IS_PRIVILEGED && this._innerIframe) {
      this._innerIframe.setVisible(false);
    }
    this.emit('hidden');
  };

  tabIframeProto.createdCallback = function() {
    this._zoom = 1;
    this._clearTabData();
    EventEmitter.decorate(this);
  };

  tabIframeProto._createInnerIframe = function() {
    let iframe = document.createElement('iframe');
    iframe.setAttribute('mozbrowser', 'true');
    iframe.setAttribute('flex', '1');
    iframe.setAttribute('remote', 'true');
    iframe.setAttribute('mozallowfullscreen', 'true');
    this.appendChild(iframe);
    for (let eventName of IFRAME_EVENTS) {
      iframe.addEventListener(eventName, this);
    }
    this._innerIframe = iframe;
    this._applyZoom();
  };

  tabIframeProto.attachedCallback = function() {
  };

  tabIframeProto.detachedCallback = function() {
    if (this._innerIframe) {
      for (let eventName of IFRAME_EVENTS) {
        this._innerIframe.removeEventListener(eventName, this);
      }
    }
  };

  tabIframeProto.zoomIn = function() {
    this._zoom += 0.1;
    this._zoom = Math.min(MAX_ZOOM, this._zoom);
    this._applyZoom();
  };

  tabIframeProto.zoomOut = function() {
    this._zoom -= 0.1;
    this._zoom = Math.max(MIN_ZOOM, this._zoom);
    this._applyZoom();
  };

  tabIframeProto.resetZoom = function() {
    this._zoom = 1;
    this._applyZoom();
  };

  tabIframeProto._applyZoom = function() {
    if (this._innerIframe && window.IS_PRIVILEGED) {
      this._innerIframe.zoom(this._zoom);
    }
  };

  tabIframeProto.reload = function() {
    if (this._innerIframe) this._innerIframe.reload();
  };

  tabIframeProto.stop = function() {
    if (this._innerIframe) this._innerIframe.stop();
  };

  tabIframeProto.goBack = function() {
    if (this._innerIframe) this._innerIframe.goBack();
  };

  tabIframeProto.goForward = function() {
    if (this._innerIframe) this._innerIframe.goForward();
  };

  tabIframeProto._clearTabData = function() {
    this._loading = false;
    this._title = '';
    this._location = '';
    this._favicon = '';
    this._securityState = 'insecure';
    this._securityExtendedValidation = false;
  };

  Object.defineProperty(tabIframeProto, 'loading', {
    get: function() {
      return this._loading;
    }
  });

  Object.defineProperty(tabIframeProto, 'title', {
    get: function() {
      return this._title;
    }
  });

  Object.defineProperty(tabIframeProto, 'location', {
    get: function() {
      return this._location;
    }
  });

  Object.defineProperty(tabIframeProto, 'favicon', {
    get: function() {
      return this._favicon;
    }
  });

  Object.defineProperty(tabIframeProto, 'securityState', {
    get: function() {
      return this._securityState;
    }
  });

  Object.defineProperty(tabIframeProto, 'securityExtendedValidation', {
    get: function() {
      return this._securityExtendedValidation;
    }
  });

  tabIframeProto.canGoBack = function() {
    return new Promise((resolve, reject) => {
      if (!this._innerIframe) {
        return resolve(false);
      }
      this._innerIframe.getCanGoBack().onsuccess = r => {
        return resolve(r.target.result);
      };
    });
  };

  tabIframeProto.canGoForward = function() {
    return new Promise((resolve, reject) => {
      if (!this._innerIframe) {
        return resolve(false);
      }
      this._innerIframe.getCanGoForward().onsuccess = r => {
        return resolve(r.target.result);
      };
    });
  };

  tabIframeProto.focus = function() {
    if (this._innerIframe) {
      this._innerIframe.focus();
    }
  };

  tabIframeProto.userInput = '';

  tabIframeProto.handleEvent = function(e) {
    let somethingChanged = true;

    switch (e.type) {
      case 'mozbrowserloadstart':
        this._clearTabData();
        this._loading = true;
        break;
      case 'mozbrowserloadend':
        this._loading = false;
        break;
      case 'mozbrowsertitlechange':
        this._title = e.detail;
        break;
      case 'mozbrowserlocationchange':
        this.userInput = '';
        this._location = e.detail;
        break;
      case 'mozbrowsericonchange':
        this._favicon = e.detail.href;
        break;
      case 'mozbrowsererror':
        this._loading = false;
        break;
      case 'mozbrowsersecuritychange':
        this._securityState = e.detail.state;
        this._securityExtendedValidation = e.detail.extendedValidation;
        break;
      default:
        somethingChanged = false;
    }

    // Forward event
    this.emit(e.type, e, this);
  };

  let TabIframe = document.registerElement('tab-iframe', {prototype: tabIframeProto});
  return TabIframe;
});
<|endoftext|>


<commit_before>var opg = opg || {};

// call with a selector for a group that
(function ($, opg) {

    var FOCUSEDCLASS = 'focused',
        SELECTEDCLASS = 'selected';

    var RadioGroup = function(element, opts) {
        this.fieldset = $(element);
        this.formControls = this.fieldset.find('.form-control.radio-vertical');
        this.radios = this.fieldset.find('input');
        this.addEvents();

    };

    RadioGroup.prototype.markSelected = function(radio) {
        var current = this.fieldset.find('.' + SELECTEDCLASS);
        current.removeClass(SELECTEDCLASS);
        radio.addClass(SELECTEDCLASS);
        radio.find('input').prop('checked', true);
    };
    RadioGroup.prototype.markFocused = function(target, state) {
        if (state === 'focused') {
          target.parent().parent().addClass(FOCUSEDCLASS);
        } else {
          target.parent().parent().removeClass(FOCUSEDCLASS);
        }
    };

    RadioGroup.prototype.getClickHandler = function () {
        return function (e) {
            this.markSelected($(e.currentTarget));
        }.bind(this);
    };
    RadioGroup.prototype.getFocusHandler = function (opts) {
        var focusEvent = (opts.level === 'document') ? 'focusin' : 'focus';

        return function (e) {
            var state = (e.type === focusEvent) ? 'focused' : 'blurred';
            this.markFocused($(e.target), state);
        }.bind(this);
    };

    RadioGroup.prototype.addEvents = function () {
        this.clickHandler = this.getClickHandler();
        this.focusHandler = this.getFocusHandler({ 'level' : 'element' });

        this.formControls.on('click', this.clickHandler);
        this.radios.on('focus blur', this.focusHandler);
    };

    opg.RadioGroup = RadioGroup;

})(jQuery, opg);<commit_msg>DD-1018 fixed a bug not setting the selection state for radio buttons when the control is initiated.<commit_after>var opg = opg || {};

// call with a selector for a group that
(function ($, opg) {

    var FOCUSEDCLASS = 'focused',
        SELECTEDCLASS = 'selected';

    var RadioGroup = function(element, opts) {
        this.fieldset = $(element);
        this.formControls = this.fieldset.find('.form-control.radio-vertical');
        this.radios = this.fieldset.find('input');
        this.addEvents();
        this.setInitialSelectedState();
    };

    RadioGroup.prototype.setInitialSelectedState = function() {
        var current = this.fieldset.find('input[type="radio"]:checked');
        if (current.length == 1) {
            this.markSelected(current.parent().parent());
        }
    };
    RadioGroup.prototype.markSelected = function(radio) {
        var current = this.fieldset.find('.' + SELECTEDCLASS);
        current.removeClass(SELECTEDCLASS);
        radio.addClass(SELECTEDCLASS);
        radio.find('input').prop('checked', true);
    };
    RadioGroup.prototype.markFocused = function(target, state) {
        if (state === 'focused') {
          target.parent().parent().addClass(FOCUSEDCLASS);
        } else {
          target.parent().parent().removeClass(FOCUSEDCLASS);
        }
    };

    RadioGroup.prototype.getClickHandler = function () {
        return function (e) {
            this.markSelected($(e.currentTarget));
        }.bind(this);
    };
    RadioGroup.prototype.getFocusHandler = function (opts) {
        var focusEvent = (opts.level === 'document') ? 'focusin' : 'focus';

        return function (e) {
            var state = (e.type === focusEvent) ? 'focused' : 'blurred';
            this.markFocused($(e.target), state);
        }.bind(this);
    };

    RadioGroup.prototype.addEvents = function () {
        this.clickHandler = this.getClickHandler();
        this.focusHandler = this.getFocusHandler({ 'level' : 'element' });

        this.formControls.on('click', this.clickHandler);
        this.radios.on('focus blur', this.focusHandler);
    };

    opg.RadioGroup = RadioGroup;

})(jQuery, opg);<|endoftext|>


<commit_before>describe("tests", () => {
  it("works", () => {
    assert.equal(1, 1);
  });
});
<commit_msg>Remove test test<commit_after><|endoftext|>


<commit_before>import { put, select, call } from 'redux-saga/effects';
import { delay } from 'redux-saga';

import { makeSelectInjected } from '../../AccountProvider/selectors';
import { getWeb3 } from '../../AccountProvider/utils';
import { notifyDelete } from '../actions';
import { loggedInSuccess, noWeb3Danger, noInjectedDanger, firstLogin, notLoggedIn } from '../constants';

import { createTempNotification, createPersistNotification, removeNotification } from './utils';

export function* authNotification({ newAuthState }) {
  const { loggedIn } = newAuthState;
  if (loggedIn) {
    yield* removeNotification({ txId: notLoggedIn.txId });
    yield* removeNotification({ txId: firstLogin.txId });
    yield* createTempNotification(loggedInSuccess);
  }
}

export function* injectedWeb3Notification({ payload: { isLocked } }) {
  if (!isLocked) {
    yield call(delay, 2000);
    const web3 = getWeb3(true);
    const injected = yield select(makeSelectInjected());
    if (!web3) {
      yield* createPersistNotification(noWeb3Danger);
    } else if (!injected) {
      yield* createPersistNotification(noInjectedDanger);
    }
  }
}

export function* injectedWeb3NotificationDismiss({ payload: injected }) {
  if (typeof injected === 'string') {
    yield put(notifyDelete(noWeb3Danger.txId));
  }
}

export function* visitorModeNotification({ payload: { pathname = '' } }) {
  const state = yield select();
  const loggedIn = yield call([state, state.getIn], ['account', 'loggedIn']);
  if (!loggedIn) {
    const isNotificationVisible = !pathname.match(/register|login/);
    if (isNotificationVisible) {
      yield* createPersistNotification(notLoggedIn);
    } else {
      yield* removeNotification({ txId: notLoggedIn.txId });
    }
  }
}
<commit_msg>Show and hide notification about locked metamask<commit_after>import { put, select, call } from 'redux-saga/effects';
import { delay } from 'redux-saga';

import { makeSelectInjected } from '../../AccountProvider/selectors';
import { getWeb3 } from '../../AccountProvider/utils';
import { notifyDelete } from '../actions';
import { loggedInSuccess, noWeb3Danger, noInjectedDanger, firstLogin, notLoggedIn } from '../constants';

import { createTempNotification, createPersistNotification, removeNotification } from './utils';

export function* authNotification({ newAuthState }) {
  const { loggedIn } = newAuthState;
  if (loggedIn) {
    yield* removeNotification({ txId: notLoggedIn.txId });
    yield* removeNotification({ txId: firstLogin.txId });
    yield* createTempNotification(loggedInSuccess);
  }
}

export function* injectedWeb3Notification({ payload: { isLocked } }) {
  if (!isLocked) {
    yield call(delay, 2000);
    const web3 = getWeb3(true);
    if (!web3) {
      yield* createPersistNotification(noWeb3Danger);
    } else {
      while (true) { // eslint-disable-line no-constant-condition
        const injected = yield select(makeSelectInjected());
        if (!injected) {
          yield* createPersistNotification(noInjectedDanger);
        } else {
          yield* removeNotification(noInjectedDanger);
        }

        yield call(delay, 2000);
      }
    }
  }
}

export function* injectedWeb3NotificationDismiss({ payload: injected }) {
  if (typeof injected === 'string') {
    yield put(notifyDelete(noWeb3Danger.txId));
  }
}

export function* visitorModeNotification({ payload: { pathname = '' } }) {
  const state = yield select();
  const loggedIn = yield call([state, state.getIn], ['account', 'loggedIn']);
  if (!loggedIn) {
    const isNotificationVisible = !pathname.match(/register|login/);
    if (isNotificationVisible) {
      yield* createPersistNotification(notLoggedIn);
    } else {
      yield* removeNotification({ txId: notLoggedIn.txId });
    }
  }
}
<|endoftext|>


<commit_before>const API_ENDPOINT = `https://api.canonn.tech`;
const API_LIMIT = 1000;

const capi = axios.create({
	baseURL: API_ENDPOINT,
	headers: {
		'Content-Type': 'application/json',
		'Accept': 'application/json',
	},
});

let sites = {
	apsites: [],
	bmsites: [],
	btsites: [],
	cssites: [],
	fgsites: [],
	fmsites: [],
	gbsites: [],
	gensites: [],
	grsites: [],
	gssites: [],
	gvsites: [],
	gysites: [],
	lssites: [],
	tbsites: [],
	tssites: [],
	twsites: [],
};

const go = async types => {
	const keys = Object.keys(types);
	return (await Promise.all(
			keys.map(type => getSites(type))
	)).reduce((acc, res, i) => {
			acc[keys[i]] = res;
			return acc;
	}, {});
};

const getSites = async type => {
	let records = [];
	let keepGoing = true;
	let API_START = 0;
	while (keepGoing) {
		let response = await reqSites(API_START, type);
		await records.push.apply(records, response.data);
		API_START += API_LIMIT;
		if (response.data.length < API_LIMIT) {
			keepGoing = false;
			return records;
		}
	}
};

const reqSites = async (API_START, type) => {

	let payload = await capi({
		url: `/${type}?_limit=${API_LIMIT}&_start=${API_START}`,
		method: 'get'
	});

	return payload;
};

var canonnEd3d_all = {

	//Define Categories and Static Data
	systemsData: {
		categories: {
			"Sites": {
				"201": {
					name: "Amphora Plants (AP)",
					color: randomColor().replace('#', '').toString()
				},
				"202": {
					name: "Bark Mounds (BM)",
					color: randomColor().replace('#', '').toString()
				},
				"203": {
					name: "Brain Trees (BT)",
					color: randomColor().replace('#', '').toString()
				},
				"204": {
					name: "Crystalline Shards (CS)",
					color: randomColor().replace('#', '').toString()
				},
				"205": {
					name: "Fungal Gourds (FG)",
					color: randomColor().replace('#', '').toString()
				},
				"206": {
					name: "Fumaroles (FM)",
					color: randomColor().replace('#', '').toString()
				},
				"207": {
					name: "Generation Ships (GEN)",
					color: randomColor().replace('#', '').toString()
				},
				"208": {
					name: "Guardian Beacons (GB)",
					color: randomColor().replace('#', '').toString()
				},
				"209": {
					name: "Guardian Ruins (GR)",
					color: randomColor().replace('#', '').toString()
				},
				"210": {
					name: "Guardian Structures (GS)",
					color: randomColor().replace('#', '').toString()
				},
				"211": {
					name: "Gas Vents (GV)",
					color: randomColor().replace('#', '').toString()
				},
				"212": {
					name: "Geysers (GY)",
					color: randomColor().replace('#', '').toString()
				},
				"213": {
					name: "Lava Spouts (LS)",
					color: randomColor().replace('#', '').toString()
				},
				"214": {
					name: "Thargoid Barnacles (TB)",
					color: randomColor().replace('#', '').toString()
				},
				"215": {
					name: "Thargoid Structures (TS)",
					color: randomColor().replace('#', '').toString()
				},
				"216": {
					name: "Tube Worms (TW)",
					color: randomColor().replace('#', '').toString()
				}
			},
			'Unknown Type': {
				'2000': {
					name: 'Unknown Site',
					color: '800000',
				},
			},
		},
		systems: []
	},

	formatSites: async function(data, resolvePromise) {
		sites = await go(data);

		let siteTypes = Object.keys(data);

		for (var i = 0; i < siteTypes.length; i++) {
			for (var d = 0; d < sites[siteTypes[i]].length; d++) {
				let siteData = sites[siteTypes[i]];
				if (siteData[d].system.systemName && siteData[d].system.systemName.replace(' ', '').length > 1) {
					var poiSite = {};
					poiSite['name'] = siteData[d].system.systemName;

					//Check Site Type and match categories
					if (siteTypes[i] == 'apsites') {
						poiSite['cat'] = [201];
					} else if (siteTypes[i] == 'bmsites') {
						poiSite['cat'] = [202];
					} else if (siteTypes[i] == 'btsites') {
						poiSite['cat'] = [203];
					} else if (siteTypes[i] == 'cssites') {
						poiSite['cat'] = [204];
					} else if (siteTypes[i] == 'fgsites') {
						poiSite['cat'] = [205];
					} else if (siteTypes[i] == 'fmsites') {
						poiSite['cat'] = [206];
					} else if (siteTypes[i] == 'gensites') {
						poiSite['cat'] = [207];
					} else if (siteTypes[i] == 'gbsites') {
						poiSite['cat'] = [208];
					} else if (siteTypes[i] == 'grsites') {
						poiSite['cat'] = [209];
					} else if (siteTypes[i] == 'gssites') {
						poiSite['cat'] = [210];
					} else if (siteTypes[i] == 'gvsites') {
						poiSite['cat'] = [211];
					} else if (siteTypes[i] == 'gysites') {
						poiSite['cat'] = [212];
					} else if (siteTypes[i] == 'lssites') {
						poiSite['cat'] = [213];
					} else if (siteTypes[i] == 'tbsites') {
						poiSite['cat'] = [214];
					} else if (siteTypes[i] == 'tssites') {
						poiSite['cat'] = [215];
					} else if (siteTypes[i] == 'twsites') {
						poiSite['cat'] = [216];
					} else {
						poiSite['cat'] = [2000];
					}

					poiSite['coords'] = {
						x: parseFloat(siteData[d].system.edsmCoordX),
						y: parseFloat(siteData[d].system.edsmCoordY),
						z: parseFloat(siteData[d].system.edsmCoordZ),
					};

					// We can then push the site to the object that stores all systems
					canonnEd3d_all.systemsData.systems.push(poiSite);
				}
			}
		}
		document.getElementById("loading").style.display = "none";
		resolvePromise();
	},

	init: function () {

		//Sites
		var p1 = new Promise(function (resolve, reject) {
			canonnEd3d_all.formatSites(sites, resolve);
		});

		Promise.all([p1]).then(function () {
			Ed3d.init({
				container: 'edmap',
				json: canonnEd3d_all.systemsData,
				withFullscreenToggle: false,
				withHudPanel: true,
				hudMultipleSelect: true,
				effectScaleSystem: [20, 500],
				startAnim: false,
				showGalaxyInfos: true,
				cameraPos: [25, 14100, -12900],
				systemColor: '#FF9D00'
			});
		});
	}
};<commit_msg>Tweak all map menu layout<commit_after>const API_ENDPOINT = `https://api.canonn.tech`;
const API_LIMIT = 1000;

const capi = axios.create({
	baseURL: API_ENDPOINT,
	headers: {
		'Content-Type': 'application/json',
		'Accept': 'application/json',
	},
});

let sites = {
	apsites: [],
	bmsites: [],
	btsites: [],
	cssites: [],
	fgsites: [],
	fmsites: [],
	gbsites: [],
	gensites: [],
	grsites: [],
	gssites: [],
	gvsites: [],
	gysites: [],
	lssites: [],
	tbsites: [],
	tssites: [],
	twsites: [],
};

const go = async types => {
	const keys = Object.keys(types);
	return (await Promise.all(
			keys.map(type => getSites(type))
	)).reduce((acc, res, i) => {
			acc[keys[i]] = res;
			return acc;
	}, {});
};

const getSites = async type => {
	let records = [];
	let keepGoing = true;
	let API_START = 0;
	while (keepGoing) {
		let response = await reqSites(API_START, type);
		await records.push.apply(records, response.data);
		API_START += API_LIMIT;
		if (response.data.length < API_LIMIT) {
			keepGoing = false;
			return records;
		}
	}
};

const reqSites = async (API_START, type) => {

	let payload = await capi({
		url: `/${type}?_limit=${API_LIMIT}&_start=${API_START}`,
		method: 'get'
	});

	return payload;
};

var canonnEd3d_all = {

	//Define Categories and Static Data
	systemsData: {
		categories: {
			"Sites": {
				"201": {
					name: "(AP) Amphora Plants",
					color: randomColor().replace('#', '').toString()
				},
				"202": {
					name: "(BM) Bark Mounds",
					color: randomColor().replace('#', '').toString()
				},
				"203": {
					name: "(BT) Brain Trees",
					color: randomColor().replace('#', '').toString()
				},
				"204": {
					name: "(CS) Crystalline Shards",
					color: randomColor().replace('#', '').toString()
				},
				"205": {
					name: "(FG) Fungal Gourds",
					color: randomColor().replace('#', '').toString()
				},
				"206": {
					name: "(FM) Fumaroles",
					color: randomColor().replace('#', '').toString()
				},
				"207": {
					name: "(GEN) Generation Ships",
					color: randomColor().replace('#', '').toString()
				},
				"208": {
					name: "(GB) Guardian Beacons",
					color: randomColor().replace('#', '').toString()
				},
				"209": {
					name: "(GR) Guardian Ruins",
					color: randomColor().replace('#', '').toString()
				},
				"210": {
					name: "(GS) Guardian Structures",
					color: randomColor().replace('#', '').toString()
				},
				"211": {
					name: "(GV) Gas Vents",
					color: randomColor().replace('#', '').toString()
				},
				"212": {
					name: "(GY) Geysers",
					color: randomColor().replace('#', '').toString()
				},
				"213": {
					name: "(LS) Lava Spouts",
					color: randomColor().replace('#', '').toString()
				},
				"214": {
					name: "(TB) Thargoid Barnacles",
					color: randomColor().replace('#', '').toString()
				},
				"215": {
					name: "(TS) Thargoid Structure",
					color: randomColor().replace('#', '').toString()
				},
				"216": {
					name: "(TW) Tube Worms",
					color: randomColor().replace('#', '').toString()
				}
			},
			'Unknown Type': {
				'2000': {
					name: 'Unknown Site',
					color: '800000',
				},
			},
		},
		systems: []
	},

	formatSites: async function(data, resolvePromise) {
		sites = await go(data);

		let siteTypes = Object.keys(data);

		for (var i = 0; i < siteTypes.length; i++) {
			for (var d = 0; d < sites[siteTypes[i]].length; d++) {
				let siteData = sites[siteTypes[i]];
				if (siteData[d].system.systemName && siteData[d].system.systemName.replace(' ', '').length > 1) {
					var poiSite = {};
					poiSite['name'] = siteData[d].system.systemName;

					//Check Site Type and match categories
					if (siteTypes[i] == 'apsites') {
						poiSite['cat'] = [201];
					} else if (siteTypes[i] == 'bmsites') {
						poiSite['cat'] = [202];
					} else if (siteTypes[i] == 'btsites') {
						poiSite['cat'] = [203];
					} else if (siteTypes[i] == 'cssites') {
						poiSite['cat'] = [204];
					} else if (siteTypes[i] == 'fgsites') {
						poiSite['cat'] = [205];
					} else if (siteTypes[i] == 'fmsites') {
						poiSite['cat'] = [206];
					} else if (siteTypes[i] == 'gensites') {
						poiSite['cat'] = [207];
					} else if (siteTypes[i] == 'gbsites') {
						poiSite['cat'] = [208];
					} else if (siteTypes[i] == 'grsites') {
						poiSite['cat'] = [209];
					} else if (siteTypes[i] == 'gssites') {
						poiSite['cat'] = [210];
					} else if (siteTypes[i] == 'gvsites') {
						poiSite['cat'] = [211];
					} else if (siteTypes[i] == 'gysites') {
						poiSite['cat'] = [212];
					} else if (siteTypes[i] == 'lssites') {
						poiSite['cat'] = [213];
					} else if (siteTypes[i] == 'tbsites') {
						poiSite['cat'] = [214];
					} else if (siteTypes[i] == 'tssites') {
						poiSite['cat'] = [215];
					} else if (siteTypes[i] == 'twsites') {
						poiSite['cat'] = [216];
					} else {
						poiSite['cat'] = [2000];
					}

					poiSite['coords'] = {
						x: parseFloat(siteData[d].system.edsmCoordX),
						y: parseFloat(siteData[d].system.edsmCoordY),
						z: parseFloat(siteData[d].system.edsmCoordZ),
					};

					// We can then push the site to the object that stores all systems
					canonnEd3d_all.systemsData.systems.push(poiSite);
				}
			}
		}
		document.getElementById("loading").style.display = "none";
		resolvePromise();
	},

	init: function () {

		//Sites
		var p1 = new Promise(function (resolve, reject) {
			canonnEd3d_all.formatSites(sites, resolve);
		});

		Promise.all([p1]).then(function () {
			Ed3d.init({
				container: 'edmap',
				json: canonnEd3d_all.systemsData,
				withFullscreenToggle: false,
				withHudPanel: true,
				hudMultipleSelect: true,
				effectScaleSystem: [20, 500],
				startAnim: false,
				showGalaxyInfos: true,
				cameraPos: [25, 14100, -12900],
				systemColor: '#FF9D00'
			});
		});
	}
};<|endoftext|>


<commit_before>/*!
 * jQuery UI Selectmenu @VERSION
 * http://jqueryui.com
 *
 * Copyright 2013 jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/selectmenu
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 *	jquery.ui.position.js
 *	jquery.ui.menu.js
 */
(function( $, undefined ) {

$.widget( "ui.selectmenu", {
	version: "@VERSION",
	defaultElement: "<select>",
	options: {
		appendTo: null,
		icons: {
			button: "ui-icon-triangle-1-s"
		},
		position: {
			my: "left top",
			at: "left bottom",
			collision: "none"
		},

		// callbacks
		change: null,
		close: null,
		focus: null,
		open: null,
		select: null
	},

	_create: function() {
		var selectmenuId = this.element.uniqueId().attr( "id" );
		this.ids = {
			element: selectmenuId,
			button: selectmenuId + "-button",
			menu: selectmenuId + "-menu"
		};

		this._drawButton();
		this._drawMenu();

		this._on( document, this._documentClick );

		if ( this.options.disabled ) {
			this.disable();
		}
	},

	_drawButton: function() {
		var tabindex = this.element.attr( "tabindex" );

		// Fix existing label
		this.label = $( "label[for='" + this.ids.element + "']" ).attr( "for", this.ids.button );
		this._on( this.label, {
			click: function( event ) {
				this.button.focus();
				event.preventDefault();
			}
		});

		// Hide original select tag
		this.element.hide();

		// Create button
		this.button = $( "<span>", {
			"class": "ui-selectmenu-button ui-widget ui-state-default ui-corner-all",
			tabindex: tabindex || this.options.disabled ? -1 : 0,
			id: this.ids.button,
			width: this.element.outerWidth(),
			role: "combobox",
			"aria-expanded": "false",
			"aria-autocomplete": "list",
			"aria-owns": this.ids.menu,
			"aria-haspopup": "true"
		})
		.insertAfter( this.element );

		$( "<span>", {
			"class": "ui-icon " + this.options.icons.button
		}).prependTo( this.button );

		this.buttonText = $( "<span>", {
			"class": "ui-selectmenu-text"
		})
		.appendTo( this.button );
		this._setText( this.buttonText, this.element.find( "option:selected" ).text() );

		this._on( this.button, this._buttonEvents );
		this._hoverable( this.button );
		this._focusable( this.button );
	},

	_drawMenu: function() {
		var menuInstance,
			that = this;

		// Create menu portion, append to body
		this.menu = $( "<ul>", {
			"aria-hidden": "true",
			"aria-labelledby": this.ids.button,
			id: this.ids.menu
		});

		// Wrap menu
		this.menuWrap = $( "<div>", {
				"class": "ui-selectmenu-menu",
				width: this.button.outerWidth()
			})
			.append( this.menu )
			.appendTo( this._appendTo() );

		// Init menu widget
		menuInstance = this.menu.menu({
			select: function( event, ui ) {
				var item = ui.item.data( "ui-selectmenu-item" );

				that._select( item, event );

				if ( that.isOpen ) {
					event.preventDefault();
					that.close( event );
				}
			},
			focus: function( event, ui ) {
				var item = ui.item.data( "ui-selectmenu-item" );

				// prevent inital focus from firing and checks if its a newly focused item
				if ( !that.isOpen && that.focusIndex !== undefined && item.index !== that.focusIndex ) {
					that._trigger( "focus", event, { item: item } );
					if ( !that.isOpen ) {
						that._select( item, event );
					}
				}
				that.focusIndex = item.index;

				that.button.attr( "aria-activedescendant", that.menuItems.eq( item.index ).attr( "id" ) );
			},
			role: "listbox"
		})
		.menu( "instance" );

		// adjust menu styles to dropdown
		this.menu.addClass( "ui-corner-bottom" ).removeClass( "ui-corner-all" );

		// Make sure focus stays on selected item
		menuInstance.delay = 999999999;
		// Unbind uneeded Menu events
		menuInstance._off( this.menu, "mouseleave" );
	},

	refresh: function() {
		this.menu.empty();

		var item,
			options = this.element.find( "option" );
		if ( options.length ) {
			this._readOptions( options );
			this._renderMenu( this.menu, this.items );

			this.menu.menu( "refresh" );
			this.menuItems = this.menu.find( "li" ).not( ".ui-selectmenu-optgroup" ).find( "a" );

			item = this._getSelectedItem();

			// Make sure menu is selected item aware
			this.menu.menu( "focus", null, item );
			this._setAria( item.data( "ui-selectmenu-item" ) );

			// Set disabled state
			this._setOption( "disabled", this._getCreateOptions().disabled );
		}
	},

	open: function( event ) {
		if ( this.options.disabled ) {
			return;
		}
		if ( !this.menuItems ) {
			this.refresh();
		}

		this.isOpen = true;
		this._toggleAttr();
		this.menuWrap.position( $.extend( { of: this.button }, this.options.position ) );

		this._trigger( "open", event );
	},

	close: function( event ) {
		if ( !this.isOpen ) {
			return;
		}

		this.isOpen = false;
		this._toggleAttr();

		// Check if we have an item to select
		if ( this.menuItems ) {
			this.menu.menu( "focus", null, this._getSelectedItem() );
		}

		this._trigger( "close", event );
	},

	widget: function() {
		return this.button;
	},

	menuWidget: function() {
		return this.menu;
	},

	_renderMenu: function( ul, items ) {
		var that = this,
			currentOptgroup = "";

		$.each( items, function( index, item ) {
			if ( item.optgroup !== currentOptgroup ) {
				$( "<li>", {
					"class": "ui-selectmenu-optgroup" + ( item.element.parent( "optgroup" ).attr( "disabled" ) ? " ui-state-disabled" : "" ),
					text: item.optgroup
				}).appendTo( ul );
				currentOptgroup = item.optgroup;
			}
			that._renderItem( ul, item );
		});
	},

	_renderItem: function( ul, item ) {
		var li = $( "<li>" ).data( "ui-selectmenu-item", item ),
			a = $( "<a>", { href: "#" });

		if ( item.disabled ) {
			li.addClass( "ui-state-disabled" );
		}
		this._setText( a, item.label );

		return li.append( a ).appendTo( ul );
	},

	_setText: function( element, value ) {
		if ( value ) {
			element.text( value );
		} else {
			element.html( " " );
		}
	},

	_move: function( direction, event ) {
		if ( direction === "first" || direction === "last" ) {
			// Set focus manually for first or last item
			this.menu.menu( "focus", event, this.menuItems[ direction ]() );
		} else {
			// Move to and focus next or prev item
			this.menu.menu( direction, event );
		}
	},

	_getSelectedItem: function() {
		return this.menuItems.eq( this.element[ 0 ].selectedIndex ).parent( "li" );
	},

	_toggle: function( event ) {
		if ( this.isOpen ) {
			this.close( event );
		} else {
			this.open( event );
		}
	},

	_documentClick: {
		click: function( event ) {
			if ( this.isOpen && !$( event.target ).closest( "li.ui-state-disabled, li.ui-selectmenu-optgroup, #" + this.ids.button ).length ) {
				this.close( event );
			}
		}
	},

	_buttonEvents: {
		focus: function() {
			// Init Menu on first focus
			this.refresh();
			// Reset focus class as its removed by ui.widget._setOption
			this.button.addClass( "ui-state-focus" );
			this._off( this.button, "focus" );
		},
		click: function( event ) {
			this._toggle( event );
			event.preventDefault();
		},
		keydown: function( event ) {
			var prevDef = true;
			switch ( event.keyCode ) {
				case $.ui.keyCode.TAB:
				case $.ui.keyCode.ESCAPE:
					if ( this.isOpen ) {
						this.close( event );
					}
					prevDef = false;
					break;
				case $.ui.keyCode.ENTER:
					if ( this.isOpen ) {
						this.menu.menu( "select", event );
					}
					break;
				case $.ui.keyCode.UP:
					if ( event.altKey ) {
						this._toggle( event );
					} else {
						this._move( "previous", event );
					}
					break;
				case $.ui.keyCode.DOWN:
					if ( event.altKey ) {
						this._toggle( event );
					} else {
						this._move( "next", event );
					}
					break;
				case $.ui.keyCode.SPACE:
					if ( this.isOpen ) {
						this.menu.menu( "select", event );
					} else {
						this._toggle( event );
					}
					break;
				case $.ui.keyCode.LEFT:
					this._move( "previous", event );
					break;
				case $.ui.keyCode.RIGHT:
					this._move( "next", event );
					break;
				case $.ui.keyCode.HOME:
				case $.ui.keyCode.PAGE_UP:
					this._move( "first", event );
					break;
				case $.ui.keyCode.END:
				case $.ui.keyCode.PAGE_DOWN:
					this._move( "last", event );
					break;
				default:
					this.menu.trigger( event );
					prevDef = false;
			}
			if ( prevDef ) {
				event.preventDefault();
			}
		}
	},

	_select: function( item, event ) {
		var oldIndex = this.element[ 0 ].selectedIndex;
		// Change native select element
		this.element[ 0 ].selectedIndex = item.index;
		this._setText( this.buttonText, item.label );
		this._setAria( item );
		this._trigger( "select", event, { item: item } );

		if ( item.index !== oldIndex ) {
			this._trigger( "change", event, { item: item } );
		}
	},

	_setAria: function( item ) {
		var link = this.menuItems.eq( item.index ),
			id = link.attr( "id" );

		this.button.attr({
			"aria-labelledby": id,
			"aria-activedescendant": id
		});
		this.menu.attr( "aria-activedescendant", id );
	},

	_setOption: function( key, value ) {
		if ( key === "icons" ) {
			this.button.find( "span.ui-icon" )
				.removeClass( this.options.icons.button )
				.addClass( value.button );
		}

		this._super( key, value );

		if ( key === "appendTo" ) {
			this.menuWrap.appendTo( this._appendTo() );
		}
		if ( key === "disabled" ) {
			this.menu.menu( "option", "disabled", value );
			this.button
				.toggleClass( "ui-state-disabled", !!value )
				.attr( "aria-disabled", value );

			if ( value ) {
				this.element.attr( "disabled", "disabled" );
				this.button.attr( "tabindex", -1 );
				this.close();
			} else {
				this.element.removeAttr( "disabled" );
				this.button.attr( "tabindex", 0 );
			}
		}
	},

	_appendTo: function() {
		var element = this.options.appendTo;

		if ( element ) {
			element = element.jquery || element.nodeType ?
				$( element ) :
				this.document.find( element ).eq( 0 );
		}

		if ( !element ) {
			element = this.element.closest( ".ui-front" );
		}

		if ( !element.length ) {
			element = this.document[0].body;
		}

		return element;
	},

	_toggleAttr: function(){
		this.button.toggleClass( "ui-corner-top", this.isOpen ).toggleClass( "ui-corner-all", !this.isOpen );
		this.menuWrap.toggleClass( "ui-selectmenu-open", this.isOpen );
		this.menu.attr( "aria-hidden", !this.isOpen);
		this.button.attr( "aria-expanded", this.isOpen);
	},

	_getCreateOptions: function() {
		return { disabled: !!this.element.attr( "disabled" ) };
	},

	_readOptions: function( options ) {
		var data = [];
		options.each( function( index, item ) {
			var option = $( item ),
				optgroup = option.parent( "optgroup" );
			data.push({
				element: option,
				index: index,
				value: option.attr( "value" ),
				label: option.text(),
				optgroup: optgroup.attr( "label" ) || "",
				disabled: optgroup.attr( "disabled" ) || option.attr( "disabled" )
			});
		});
		this.items = data;
	},

	_destroy: function() {
		this.menuWrap.remove();
		this.button.remove();
		this.element.show();
		this.element.removeUniqueId();
		this.label.attr( "for", this.ids.element );
	}
});

}( jQuery ));
<commit_msg>Selectmenu: use guard clause for option length checking in refresh<commit_after>/*!
 * jQuery UI Selectmenu @VERSION
 * http://jqueryui.com
 *
 * Copyright 2013 jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/selectmenu
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 *	jquery.ui.position.js
 *	jquery.ui.menu.js
 */
(function( $, undefined ) {

$.widget( "ui.selectmenu", {
	version: "@VERSION",
	defaultElement: "<select>",
	options: {
		appendTo: null,
		icons: {
			button: "ui-icon-triangle-1-s"
		},
		position: {
			my: "left top",
			at: "left bottom",
			collision: "none"
		},

		// callbacks
		change: null,
		close: null,
		focus: null,
		open: null,
		select: null
	},

	_create: function() {
		var selectmenuId = this.element.uniqueId().attr( "id" );
		this.ids = {
			element: selectmenuId,
			button: selectmenuId + "-button",
			menu: selectmenuId + "-menu"
		};

		this._drawButton();
		this._drawMenu();

		this._on( document, this._documentClick );

		if ( this.options.disabled ) {
			this.disable();
		}
	},

	_drawButton: function() {
		var tabindex = this.element.attr( "tabindex" );

		// Fix existing label
		this.label = $( "label[for='" + this.ids.element + "']" ).attr( "for", this.ids.button );
		this._on( this.label, {
			click: function( event ) {
				this.button.focus();
				event.preventDefault();
			}
		});

		// Hide original select tag
		this.element.hide();

		// Create button
		this.button = $( "<span>", {
			"class": "ui-selectmenu-button ui-widget ui-state-default ui-corner-all",
			tabindex: tabindex || this.options.disabled ? -1 : 0,
			id: this.ids.button,
			width: this.element.outerWidth(),
			role: "combobox",
			"aria-expanded": "false",
			"aria-autocomplete": "list",
			"aria-owns": this.ids.menu,
			"aria-haspopup": "true"
		})
		.insertAfter( this.element );

		$( "<span>", {
			"class": "ui-icon " + this.options.icons.button
		}).prependTo( this.button );

		this.buttonText = $( "<span>", {
			"class": "ui-selectmenu-text"
		})
		.appendTo( this.button );
		this._setText( this.buttonText, this.element.find( "option:selected" ).text() );

		this._on( this.button, this._buttonEvents );
		this._hoverable( this.button );
		this._focusable( this.button );
	},

	_drawMenu: function() {
		var menuInstance,
			that = this;

		// Create menu portion, append to body
		this.menu = $( "<ul>", {
			"aria-hidden": "true",
			"aria-labelledby": this.ids.button,
			id: this.ids.menu
		});

		// Wrap menu
		this.menuWrap = $( "<div>", {
				"class": "ui-selectmenu-menu",
				width: this.button.outerWidth()
			})
			.append( this.menu )
			.appendTo( this._appendTo() );

		// Init menu widget
		menuInstance = this.menu.menu({
			select: function( event, ui ) {
				var item = ui.item.data( "ui-selectmenu-item" );

				that._select( item, event );

				if ( that.isOpen ) {
					event.preventDefault();
					that.close( event );
				}
			},
			focus: function( event, ui ) {
				var item = ui.item.data( "ui-selectmenu-item" );

				// prevent inital focus from firing and checks if its a newly focused item
				if ( !that.isOpen && that.focusIndex !== undefined && item.index !== that.focusIndex ) {
					that._trigger( "focus", event, { item: item } );
					if ( !that.isOpen ) {
						that._select( item, event );
					}
				}
				that.focusIndex = item.index;

				that.button.attr( "aria-activedescendant", that.menuItems.eq( item.index ).attr( "id" ) );
			},
			role: "listbox"
		})
		.menu( "instance" );

		// adjust menu styles to dropdown
		this.menu.addClass( "ui-corner-bottom" ).removeClass( "ui-corner-all" );

		// Make sure focus stays on selected item
		menuInstance.delay = 999999999;
		// Unbind uneeded Menu events
		menuInstance._off( this.menu, "mouseleave" );
	},

	refresh: function() {
		this.menu.empty();

		var item,
			options = this.element.find( "option" );

		if ( !options.length ) {
			return;
		}

		this._readOptions( options );
		this._renderMenu( this.menu, this.items );

		this.menu.menu( "refresh" );
		this.menuItems = this.menu.find( "li" ).not( ".ui-selectmenu-optgroup" ).find( "a" );

		item = this._getSelectedItem();

		// Make sure menu is selected item aware
		this.menu.menu( "focus", null, item );
		this._setAria( item.data( "ui-selectmenu-item" ) );

		// Set disabled state
		this._setOption( "disabled", this._getCreateOptions().disabled );
	},

	open: function( event ) {
		if ( this.options.disabled ) {
			return;
		}
		if ( !this.menuItems ) {
			this.refresh();
		}

		this.isOpen = true;
		this._toggleAttr();
		this.menuWrap.position( $.extend( { of: this.button }, this.options.position ) );

		this._trigger( "open", event );
	},

	close: function( event ) {
		if ( !this.isOpen ) {
			return;
		}

		this.isOpen = false;
		this._toggleAttr();

		// Check if we have an item to select
		if ( this.menuItems ) {
			this.menu.menu( "focus", null, this._getSelectedItem() );
		}

		this._trigger( "close", event );
	},

	widget: function() {
		return this.button;
	},

	menuWidget: function() {
		return this.menu;
	},

	_renderMenu: function( ul, items ) {
		var that = this,
			currentOptgroup = "";

		$.each( items, function( index, item ) {
			if ( item.optgroup !== currentOptgroup ) {
				$( "<li>", {
					"class": "ui-selectmenu-optgroup" + ( item.element.parent( "optgroup" ).attr( "disabled" ) ? " ui-state-disabled" : "" ),
					text: item.optgroup
				}).appendTo( ul );
				currentOptgroup = item.optgroup;
			}
			that._renderItem( ul, item );
		});
	},

	_renderItem: function( ul, item ) {
		var li = $( "<li>" ).data( "ui-selectmenu-item", item ),
			a = $( "<a>", { href: "#" });

		if ( item.disabled ) {
			li.addClass( "ui-state-disabled" );
		}
		this._setText( a, item.label );

		return li.append( a ).appendTo( ul );
	},

	_setText: function( element, value ) {
		if ( value ) {
			element.text( value );
		} else {
			element.html( " " );
		}
	},

	_move: function( direction, event ) {
		if ( direction === "first" || direction === "last" ) {
			// Set focus manually for first or last item
			this.menu.menu( "focus", event, this.menuItems[ direction ]() );
		} else {
			// Move to and focus next or prev item
			this.menu.menu( direction, event );
		}
	},

	_getSelectedItem: function() {
		return this.menuItems.eq( this.element[ 0 ].selectedIndex ).parent( "li" );
	},

	_toggle: function( event ) {
		if ( this.isOpen ) {
			this.close( event );
		} else {
			this.open( event );
		}
	},

	_documentClick: {
		click: function( event ) {
			if ( this.isOpen && !$( event.target ).closest( "li.ui-state-disabled, li.ui-selectmenu-optgroup, #" + this.ids.button ).length ) {
				this.close( event );
			}
		}
	},

	_buttonEvents: {
		focus: function() {
			// Init Menu on first focus
			this.refresh();
			// Reset focus class as its removed by ui.widget._setOption
			this.button.addClass( "ui-state-focus" );
			this._off( this.button, "focus" );
		},
		click: function( event ) {
			this._toggle( event );
			event.preventDefault();
		},
		keydown: function( event ) {
			var prevDef = true;
			switch ( event.keyCode ) {
				case $.ui.keyCode.TAB:
				case $.ui.keyCode.ESCAPE:
					if ( this.isOpen ) {
						this.close( event );
					}
					prevDef = false;
					break;
				case $.ui.keyCode.ENTER:
					if ( this.isOpen ) {
						this.menu.menu( "select", event );
					}
					break;
				case $.ui.keyCode.UP:
					if ( event.altKey ) {
						this._toggle( event );
					} else {
						this._move( "previous", event );
					}
					break;
				case $.ui.keyCode.DOWN:
					if ( event.altKey ) {
						this._toggle( event );
					} else {
						this._move( "next", event );
					}
					break;
				case $.ui.keyCode.SPACE:
					if ( this.isOpen ) {
						this.menu.menu( "select", event );
					} else {
						this._toggle( event );
					}
					break;
				case $.ui.keyCode.LEFT:
					this._move( "previous", event );
					break;
				case $.ui.keyCode.RIGHT:
					this._move( "next", event );
					break;
				case $.ui.keyCode.HOME:
				case $.ui.keyCode.PAGE_UP:
					this._move( "first", event );
					break;
				case $.ui.keyCode.END:
				case $.ui.keyCode.PAGE_DOWN:
					this._move( "last", event );
					break;
				default:
					this.menu.trigger( event );
					prevDef = false;
			}
			if ( prevDef ) {
				event.preventDefault();
			}
		}
	},

	_select: function( item, event ) {
		var oldIndex = this.element[ 0 ].selectedIndex;
		// Change native select element
		this.element[ 0 ].selectedIndex = item.index;
		this._setText( this.buttonText, item.label );
		this._setAria( item );
		this._trigger( "select", event, { item: item } );

		if ( item.index !== oldIndex ) {
			this._trigger( "change", event, { item: item } );
		}
	},

	_setAria: function( item ) {
		var link = this.menuItems.eq( item.index ),
			id = link.attr( "id" );

		this.button.attr({
			"aria-labelledby": id,
			"aria-activedescendant": id
		});
		this.menu.attr( "aria-activedescendant", id );
	},

	_setOption: function( key, value ) {
		if ( key === "icons" ) {
			this.button.find( "span.ui-icon" )
				.removeClass( this.options.icons.button )
				.addClass( value.button );
		}

		this._super( key, value );

		if ( key === "appendTo" ) {
			this.menuWrap.appendTo( this._appendTo() );
		}
		if ( key === "disabled" ) {
			this.menu.menu( "option", "disabled", value );
			this.button
				.toggleClass( "ui-state-disabled", !!value )
				.attr( "aria-disabled", value );

			if ( value ) {
				this.element.attr( "disabled", "disabled" );
				this.button.attr( "tabindex", -1 );
				this.close();
			} else {
				this.element.removeAttr( "disabled" );
				this.button.attr( "tabindex", 0 );
			}
		}
	},

	_appendTo: function() {
		var element = this.options.appendTo;

		if ( element ) {
			element = element.jquery || element.nodeType ?
				$( element ) :
				this.document.find( element ).eq( 0 );
		}

		if ( !element ) {
			element = this.element.closest( ".ui-front" );
		}

		if ( !element.length ) {
			element = this.document[0].body;
		}

		return element;
	},

	_toggleAttr: function(){
		this.button.toggleClass( "ui-corner-top", this.isOpen ).toggleClass( "ui-corner-all", !this.isOpen );
		this.menuWrap.toggleClass( "ui-selectmenu-open", this.isOpen );
		this.menu.attr( "aria-hidden", !this.isOpen);
		this.button.attr( "aria-expanded", this.isOpen);
	},

	_getCreateOptions: function() {
		return { disabled: !!this.element.attr( "disabled" ) };
	},

	_readOptions: function( options ) {
		var data = [];
		options.each( function( index, item ) {
			var option = $( item ),
				optgroup = option.parent( "optgroup" );
			data.push({
				element: option,
				index: index,
				value: option.attr( "value" ),
				label: option.text(),
				optgroup: optgroup.attr( "label" ) || "",
				disabled: optgroup.attr( "disabled" ) || option.attr( "disabled" )
			});
		});
		this.items = data;
	},

	_destroy: function() {
		this.menuWrap.remove();
		this.button.remove();
		this.element.show();
		this.element.removeUniqueId();
		this.label.attr( "for", this.ids.element );
	}
});

}( jQuery ));
<|endoftext|>


<commit_before>import lookup from './lookup.js';
import bootstrapTests from '../../test-util/bootstrap-tests.js';
import syncify from '../../test-util/syncify.js';
import { expectMediaHoundImage } from '../../test-util/expect-image.js';

beforeAll(() => bootstrapTests());

test('lookup is exported as a function', () => {
  expect(typeof lookup === 'function').toBe(true);
});

test('lookup takes an ids array (1 item) using mhid', async () => {
  const res = await lookup({
    ids: ['mhmovPeR81SeVnIPqEFsr36NYUqfqHuXzO9lDuQkq72G']
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(1);
});

test('lookup takes an ids array (1 item) using altId', async () => {
  const res = await lookup({
    ids: ['mhmov-gladiator']
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(1);
});

test('lookup takes an ids array (1 item) using MSI', async () => {
  const res = await lookup({
    ids: ['IMDB::tt0238380']
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(1);
});

test('lookup takes an ids array (3 items) that are 3 different pieces of content using mhid', async () => {
  const res = await lookup({
    ids: [
      'mhmovPeR81SeVnIPqEFsr36NYUqfqHuXzO9lDuQkq72G',
      'mhmovAyp87luMBe75zACCmd4RgqsRysexXsll2N7HqxJ',
      'mhmovrxL89X8RDcdkAsNfVzMuL1oSjjgYv9g9ixuW2IT'
    ]
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(3);
});

test('lookup takes an ids array (3 items) that are 3 different pieces of content using altId', async () => {
  const res = await lookup({
    ids: [
      'mhmov-gladiator',
      'mhmov-shakespeare-in-love',
      'mhmov-being-john-malkovich'
    ]
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(3);
});

test('lookup takes an ids array (3 items) that are 3 different pieces of content using MSI', async () => {
  const res = await lookup({
    ids: [
      'Vudu:Movie:32275',
      'IMDB::tt0238380',
      'iTunes:Movie:570128788'
    ]
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(3);
});

test('lookup takes an ids array (3 items) that are 3 different pieces of content using mhid, altId, and MSI', async () => {
  const res = await lookup({
    ids: [
      'mhmovPeR81SeVnIPqEFsr36NYUqfqHuXzO9lDuQkq72G',
      'mhmov-shakespeare-in-love',
      'iTunes:Movie:570128788'
    ]
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(3);
});

test('lookup takes an ids array (3 items) that are all the same piece of content using mhid', async () => {
  const res = await lookup({
    ids: [
      'mhmovPeR81SeVnIPqEFsr36NYUqfqHuXzO9lDuQkq72G',
      'mhmovPeR81SeVnIPqEFsr36NYUqfqHuXzO9lDuQkq72G',
      'mhmovPeR81SeVnIPqEFsr36NYUqfqHuXzO9lDuQkq72G'
    ]
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(3);
});

test('lookup takes an ids array (3 items) that are all the same piece of content using altId', async () => {
  const res = await lookup({
    ids: [
      'mhmov-gladiator',
      'mhmov-gladiator',
      'mhmov-gladiator'
    ]
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(3);
});

test('lookup takes an ids array (3 items) that are all the same piece of content using MSI', async () => {
  const res = await lookup({
    ids: [
      'IMDB::tt0238380',
      'IMDB::tt0238380',
      'IMDB::tt0238380'
    ]
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(3);
});

test('lookup takes an ids array (3 items) that are all the same piece of content using mhid, altId, and MSI', async () => {
  const res = await lookup({
    ids: [
      'mhmovPeR81SeVnIPqEFsr36NYUqfqHuXzO9lDuQkq72G',
      'mhmov-gladiator',
      'IMDB::tt0172495']
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(3);
});

test('lookup can be paged through (default should be 10)', async () => {
  const res = await lookup({
    ids: [
      // 11 movies
      'mhmov-gladiator',
      'mhmov-her',
      'mhmov-the-notebook',
      'mhmov-citizen-kane',
      'mhmov-king-kong',
      'mhmov-back-to-the-future',
      'mhmov-saving-private-ryan',
      'mhmov-dodgeball-a-true-underdog-story',
      'mhmov-hoosiers',
      'mhmov-metropolis',
      'mhmov-the-shawshank-redemption'
    ]
  });

  expect(res.hasMorePages).toBe(true);
  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(10);

  const nextRes = await res.next();

  expect(Array.isArray(nextRes.content)).toBe(true);
  // Requested 11 movies with pageSize of 10, so second page should have 1 movie
  expect(nextRes.content).toHaveLength(1);
  expect(nextRes.hasMorePages).toBe(false);
});

test('lookup can take a pageSize', async () => {
  const res = await lookup({
    ids: [
      // 11 movies
      'mhmov-gladiator',
      'mhmov-her',
      'mhmov-the-notebook',
      'mhmov-citizen-kane',
      'mhmov-king-kong',
      'mhmov-back-to-the-future',
      'mhmov-saving-private-ryan',
      'mhmov-dodgeball-a-true-underdog-story',
      'mhmov-hoosiers',
      'mhmov-metropolis',
      'mhmov-the-shawshank-redemption'
    ],
    pageSize: 7
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(7);
  expect(res.hasMorePages).toBe(true);

  const nextRes = await res.next();

  expect(Array.isArray(nextRes.content)).toBe(true);
  expect(nextRes.content).toHaveLength(4);
  expect(nextRes.hasMorePages).toBe(false);
});

test('looking up an invalid mhid should fail', async () => {
  const syncFunction = await syncify(() => {
    return lookup({
      ids: ['mhmovWRONGWRONGWRONGWRONGWRONGWRONGWRONGWRON']
    });
  });

  expect(syncFunction).toThrow();
});

test('looking up an invalid altId should fail', async () => {
  const syncFunction = await syncify(() => {
    return lookup({
      ids: ['mhmov-invalidsljdkfsjklj']
    });
  });

  expect(syncFunction).toThrow();
});

test('looking up an invalid MSI should return an empty object', async () => {
  const res = await lookup({
    ids: ['IMDB::WRONG']
  });
  expect(res.content.length).toBe(1);
  expect(Object.keys(res.content[0]).length === 0)
});

test('looking up an invalid mhid along with valid mhids should fail', async () => {
  const syncFunction = await syncify(() => {
    return lookup({
      ids: [
        'mhmovPeR81SeVnIPqEFsr36NYUqfqHuXzO9lDuQkq72G',
        'mhmovWRONGWRONGWRONGWRONGWRONGWRONGWRONGWRON'
      ]
    });
  });

  expect(syncFunction).toThrow();
});

test('looking up an invalid altId along with valid altIds should fail', async () => {
  const syncFunction = await syncify(() => {
    return lookup({
      ids: [
        'mhmov-gladiator',
        'mhmov-invalidsljdkfsjklj'
      ]
    });
  });

  expect(syncFunction).toThrow();
});

test('looking up an invalid MSI along with valid MSIs should fail', async () => {
  const res = await lookup({
    ids: [
      'IMDB::tt0238380',
      'IMDB::WRONG'
    ]
  });
  expect(res.content.length).toBe(2);
  expect(Object.keys(res.content[1]).length === 0)
});

test('lookup returns basic metadata if no components are requested', async () => {
  const res = await lookup({
    ids: ['mhmov-gladiator']
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(1);

  const firstPair = res.content[0];
  expect(firstPair).toBeDefined();

  const { object, context } = firstPair;
  expect(context).toEqual({});
  expect(object).toBeDefined();

  expect(object.name).toBe('Gladiator');
  expect(object.altId).toBe('mhmov-gladiator');
  expect(object.mhid).toBe('mhmovPeR81SeVnIPqEFsr36NYUqfqHuXzO9lDuQkq72G');
});

test('lookup takes a simple component', async () => {
  const res = await lookup({
    ids: ['mhmov-gladiator'],
    components: [
      'primaryImage'
    ]
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(1);

  const firstPair = res.content[0];
  expect(firstPair).toBeDefined();

  const { object, context } = firstPair;
  expect(context).toEqual({});
  expect(object).toBeDefined();

  expect(object.name).toBe('Gladiator');
  expect(object.altId).toBe('mhmov-gladiator');
  expect(object.mhid).toBe('mhmovPeR81SeVnIPqEFsr36NYUqfqHuXzO9lDuQkq72G');

  const { primaryImage } = object;
  expectMediaHoundImage(primaryImage.object);
});

test('lookup takes multiple simple components', async () => {
  const res = await lookup({
    ids: ['mhmov-gladiator'],
    components: [
      'primaryImage',
      'secondaryImage'
    ]
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(1);

  const firstPair = res.content[0];
  expect(firstPair).toBeDefined();

  const { object, context } = firstPair;
  expect(context).toEqual({});
  expect(object).toBeDefined();

  expect(object.name).toBe('Gladiator');
  expect(object.altId).toBe('mhmov-gladiator');
  expect(object.mhid).toBe('mhmovPeR81SeVnIPqEFsr36NYUqfqHuXzO9lDuQkq72G');

  const { primaryImage } = object;
  expectMediaHoundImage(primaryImage.object);

  const { secondaryImage } = object;
  expectMediaHoundImage(secondaryImage.object);
});

test('lookup takes a single object component', async () => {
  const res = await lookup({
    ids: ['mhmov-gladiator'],
    components: [
      { name: 'primaryImage' }
    ]
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(1);

  const firstPair = res.content[0];
  expect(firstPair).toBeDefined();

  const { object, context } = firstPair;
  expect(context).toEqual({});
  expect(object).toBeDefined();

  expect(object.name).toBe('Gladiator');
  expect(object.altId).toBe('mhmov-gladiator');
  expect(object.mhid).toBe('mhmovPeR81SeVnIPqEFsr36NYUqfqHuXzO9lDuQkq72G');

  const { primaryImage } = object;
  expectMediaHoundImage(primaryImage.object);
});

test('lookup takes multiple object components', async () => {
  const res = await lookup({
    ids: ['mhmov-gladiator'],
    components: [
      { name: 'primaryImage' },
      { name: 'secondaryImage' }
    ]
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(1);

  const firstPair = res.content[0];
  expect(firstPair).toBeDefined();

  const { object, context } = firstPair;
  expect(context).toEqual({});
  expect(object).toBeDefined();

  expect(object.name).toBe('Gladiator');
  expect(object.altId).toBe('mhmov-gladiator');
  expect(object.mhid).toBe('mhmovPeR81SeVnIPqEFsr36NYUqfqHuXzO9lDuQkq72G');

  const { primaryImage } = object;
  expectMediaHoundImage(primaryImage.object);

  const { secondaryImage } = object;
  expectMediaHoundImage(secondaryImage.object);
});

test('lookup ignores unrecognized components', async () => {
  const res = await lookup({
    ids: ['mhmov-gladiator'],
    components: [
      'wrongComponent'
    ]
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(1);

  const firstPair = res.content[0];
  expect(firstPair).toBeDefined();

  const { object, context } = firstPair;
  expect(context).toEqual({});
  expect(object).toBeDefined();

  expect(object.name).toBe('Gladiator');
  expect(object.altId).toBe('mhmov-gladiator');
  expect(object.mhid).toBe('mhmovPeR81SeVnIPqEFsr36NYUqfqHuXzO9lDuQkq72G');
});

test('lookup ignores unrecognized components but accepts valid ones', async () => {
  const res = await lookup({
    ids: ['mhmov-gladiator'],
    components: [
      'wrongComponent',
      'primaryImage'
    ]
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(1);

  const firstPair = res.content[0];
  expect(firstPair).toBeDefined();

  const { object, context } = firstPair;
  expect(context).toEqual({});
  expect(object).toBeDefined();

  expect(object.name).toBe('Gladiator');
  expect(object.altId).toBe('mhmov-gladiator');
  expect(object.mhid).toBe('mhmovPeR81SeVnIPqEFsr36NYUqfqHuXzO9lDuQkq72G');

  const { primaryImage } = object;
  expectMediaHoundImage(primaryImage.object);
});
<commit_msg>Fixed test message<commit_after>import lookup from './lookup.js';
import bootstrapTests from '../../test-util/bootstrap-tests.js';
import syncify from '../../test-util/syncify.js';
import { expectMediaHoundImage } from '../../test-util/expect-image.js';

beforeAll(() => bootstrapTests());

test('lookup is exported as a function', () => {
  expect(typeof lookup === 'function').toBe(true);
});

test('lookup takes an ids array (1 item) using mhid', async () => {
  const res = await lookup({
    ids: ['mhmovPeR81SeVnIPqEFsr36NYUqfqHuXzO9lDuQkq72G']
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(1);
});

test('lookup takes an ids array (1 item) using altId', async () => {
  const res = await lookup({
    ids: ['mhmov-gladiator']
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(1);
});

test('lookup takes an ids array (1 item) using MSI', async () => {
  const res = await lookup({
    ids: ['IMDB::tt0238380']
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(1);
});

test('lookup takes an ids array (3 items) that are 3 different pieces of content using mhid', async () => {
  const res = await lookup({
    ids: [
      'mhmovPeR81SeVnIPqEFsr36NYUqfqHuXzO9lDuQkq72G',
      'mhmovAyp87luMBe75zACCmd4RgqsRysexXsll2N7HqxJ',
      'mhmovrxL89X8RDcdkAsNfVzMuL1oSjjgYv9g9ixuW2IT'
    ]
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(3);
});

test('lookup takes an ids array (3 items) that are 3 different pieces of content using altId', async () => {
  const res = await lookup({
    ids: [
      'mhmov-gladiator',
      'mhmov-shakespeare-in-love',
      'mhmov-being-john-malkovich'
    ]
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(3);
});

test('lookup takes an ids array (3 items) that are 3 different pieces of content using MSI', async () => {
  const res = await lookup({
    ids: [
      'Vudu:Movie:32275',
      'IMDB::tt0238380',
      'iTunes:Movie:570128788'
    ]
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(3);
});

test('lookup takes an ids array (3 items) that are 3 different pieces of content using mhid, altId, and MSI', async () => {
  const res = await lookup({
    ids: [
      'mhmovPeR81SeVnIPqEFsr36NYUqfqHuXzO9lDuQkq72G',
      'mhmov-shakespeare-in-love',
      'iTunes:Movie:570128788'
    ]
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(3);
});

test('lookup takes an ids array (3 items) that are all the same piece of content using mhid', async () => {
  const res = await lookup({
    ids: [
      'mhmovPeR81SeVnIPqEFsr36NYUqfqHuXzO9lDuQkq72G',
      'mhmovPeR81SeVnIPqEFsr36NYUqfqHuXzO9lDuQkq72G',
      'mhmovPeR81SeVnIPqEFsr36NYUqfqHuXzO9lDuQkq72G'
    ]
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(3);
});

test('lookup takes an ids array (3 items) that are all the same piece of content using altId', async () => {
  const res = await lookup({
    ids: [
      'mhmov-gladiator',
      'mhmov-gladiator',
      'mhmov-gladiator'
    ]
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(3);
});

test('lookup takes an ids array (3 items) that are all the same piece of content using MSI', async () => {
  const res = await lookup({
    ids: [
      'IMDB::tt0238380',
      'IMDB::tt0238380',
      'IMDB::tt0238380'
    ]
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(3);
});

test('lookup takes an ids array (3 items) that are all the same piece of content using mhid, altId, and MSI', async () => {
  const res = await lookup({
    ids: [
      'mhmovPeR81SeVnIPqEFsr36NYUqfqHuXzO9lDuQkq72G',
      'mhmov-gladiator',
      'IMDB::tt0172495']
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(3);
});

test('lookup can be paged through (default should be 10)', async () => {
  const res = await lookup({
    ids: [
      // 11 movies
      'mhmov-gladiator',
      'mhmov-her',
      'mhmov-the-notebook',
      'mhmov-citizen-kane',
      'mhmov-king-kong',
      'mhmov-back-to-the-future',
      'mhmov-saving-private-ryan',
      'mhmov-dodgeball-a-true-underdog-story',
      'mhmov-hoosiers',
      'mhmov-metropolis',
      'mhmov-the-shawshank-redemption'
    ]
  });

  expect(res.hasMorePages).toBe(true);
  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(10);

  const nextRes = await res.next();

  expect(Array.isArray(nextRes.content)).toBe(true);
  // Requested 11 movies with pageSize of 10, so second page should have 1 movie
  expect(nextRes.content).toHaveLength(1);
  expect(nextRes.hasMorePages).toBe(false);
});

test('lookup can take a pageSize', async () => {
  const res = await lookup({
    ids: [
      // 11 movies
      'mhmov-gladiator',
      'mhmov-her',
      'mhmov-the-notebook',
      'mhmov-citizen-kane',
      'mhmov-king-kong',
      'mhmov-back-to-the-future',
      'mhmov-saving-private-ryan',
      'mhmov-dodgeball-a-true-underdog-story',
      'mhmov-hoosiers',
      'mhmov-metropolis',
      'mhmov-the-shawshank-redemption'
    ],
    pageSize: 7
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(7);
  expect(res.hasMorePages).toBe(true);

  const nextRes = await res.next();

  expect(Array.isArray(nextRes.content)).toBe(true);
  expect(nextRes.content).toHaveLength(4);
  expect(nextRes.hasMorePages).toBe(false);
});

test('looking up an invalid mhid should fail', async () => {
  const syncFunction = await syncify(() => {
    return lookup({
      ids: ['mhmovWRONGWRONGWRONGWRONGWRONGWRONGWRONGWRON']
    });
  });

  expect(syncFunction).toThrow();
});

test('looking up an invalid altId should fail', async () => {
  const syncFunction = await syncify(() => {
    return lookup({
      ids: ['mhmov-invalidsljdkfsjklj']
    });
  });

  expect(syncFunction).toThrow();
});

test('looking up an invalid MSI should return an empty object', async () => {
  const res = await lookup({
    ids: ['IMDB::WRONG']
  });
  expect(res.content.length).toBe(1);
  expect(Object.keys(res.content[0]).length === 0)
});

test('looking up an invalid mhid along with valid mhids should fail', async () => {
  const syncFunction = await syncify(() => {
    return lookup({
      ids: [
        'mhmovPeR81SeVnIPqEFsr36NYUqfqHuXzO9lDuQkq72G',
        'mhmovWRONGWRONGWRONGWRONGWRONGWRONGWRONGWRON'
      ]
    });
  });

  expect(syncFunction).toThrow();
});

test('looking up an invalid altId along with valid altIds should fail', async () => {
  const syncFunction = await syncify(() => {
    return lookup({
      ids: [
        'mhmov-gladiator',
        'mhmov-invalidsljdkfsjklj'
      ]
    });
  });

  expect(syncFunction).toThrow();
});

test('looking up an invalid MSI along with valid MSIs should return one empty object', async () => {
  const res = await lookup({
    ids: [
      'IMDB::tt0238380',
      'IMDB::WRONG'
    ]
  });
  expect(res.content.length).toBe(2);
  expect(Object.keys(res.content[1]).length === 0)
});

test('lookup returns basic metadata if no components are requested', async () => {
  const res = await lookup({
    ids: ['mhmov-gladiator']
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(1);

  const firstPair = res.content[0];
  expect(firstPair).toBeDefined();

  const { object, context } = firstPair;
  expect(context).toEqual({});
  expect(object).toBeDefined();

  expect(object.name).toBe('Gladiator');
  expect(object.altId).toBe('mhmov-gladiator');
  expect(object.mhid).toBe('mhmovPeR81SeVnIPqEFsr36NYUqfqHuXzO9lDuQkq72G');
});

test('lookup takes a simple component', async () => {
  const res = await lookup({
    ids: ['mhmov-gladiator'],
    components: [
      'primaryImage'
    ]
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(1);

  const firstPair = res.content[0];
  expect(firstPair).toBeDefined();

  const { object, context } = firstPair;
  expect(context).toEqual({});
  expect(object).toBeDefined();

  expect(object.name).toBe('Gladiator');
  expect(object.altId).toBe('mhmov-gladiator');
  expect(object.mhid).toBe('mhmovPeR81SeVnIPqEFsr36NYUqfqHuXzO9lDuQkq72G');

  const { primaryImage } = object;
  expectMediaHoundImage(primaryImage.object);
});

test('lookup takes multiple simple components', async () => {
  const res = await lookup({
    ids: ['mhmov-gladiator'],
    components: [
      'primaryImage',
      'secondaryImage'
    ]
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(1);

  const firstPair = res.content[0];
  expect(firstPair).toBeDefined();

  const { object, context } = firstPair;
  expect(context).toEqual({});
  expect(object).toBeDefined();

  expect(object.name).toBe('Gladiator');
  expect(object.altId).toBe('mhmov-gladiator');
  expect(object.mhid).toBe('mhmovPeR81SeVnIPqEFsr36NYUqfqHuXzO9lDuQkq72G');

  const { primaryImage } = object;
  expectMediaHoundImage(primaryImage.object);

  const { secondaryImage } = object;
  expectMediaHoundImage(secondaryImage.object);
});

test('lookup takes a single object component', async () => {
  const res = await lookup({
    ids: ['mhmov-gladiator'],
    components: [
      { name: 'primaryImage' }
    ]
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(1);

  const firstPair = res.content[0];
  expect(firstPair).toBeDefined();

  const { object, context } = firstPair;
  expect(context).toEqual({});
  expect(object).toBeDefined();

  expect(object.name).toBe('Gladiator');
  expect(object.altId).toBe('mhmov-gladiator');
  expect(object.mhid).toBe('mhmovPeR81SeVnIPqEFsr36NYUqfqHuXzO9lDuQkq72G');

  const { primaryImage } = object;
  expectMediaHoundImage(primaryImage.object);
});

test('lookup takes multiple object components', async () => {
  const res = await lookup({
    ids: ['mhmov-gladiator'],
    components: [
      { name: 'primaryImage' },
      { name: 'secondaryImage' }
    ]
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(1);

  const firstPair = res.content[0];
  expect(firstPair).toBeDefined();

  const { object, context } = firstPair;
  expect(context).toEqual({});
  expect(object).toBeDefined();

  expect(object.name).toBe('Gladiator');
  expect(object.altId).toBe('mhmov-gladiator');
  expect(object.mhid).toBe('mhmovPeR81SeVnIPqEFsr36NYUqfqHuXzO9lDuQkq72G');

  const { primaryImage } = object;
  expectMediaHoundImage(primaryImage.object);

  const { secondaryImage } = object;
  expectMediaHoundImage(secondaryImage.object);
});

test('lookup ignores unrecognized components', async () => {
  const res = await lookup({
    ids: ['mhmov-gladiator'],
    components: [
      'wrongComponent'
    ]
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(1);

  const firstPair = res.content[0];
  expect(firstPair).toBeDefined();

  const { object, context } = firstPair;
  expect(context).toEqual({});
  expect(object).toBeDefined();

  expect(object.name).toBe('Gladiator');
  expect(object.altId).toBe('mhmov-gladiator');
  expect(object.mhid).toBe('mhmovPeR81SeVnIPqEFsr36NYUqfqHuXzO9lDuQkq72G');
});

test('lookup ignores unrecognized components but accepts valid ones', async () => {
  const res = await lookup({
    ids: ['mhmov-gladiator'],
    components: [
      'wrongComponent',
      'primaryImage'
    ]
  });

  expect(Array.isArray(res.content)).toBe(true);
  expect(res.content).toHaveLength(1);

  const firstPair = res.content[0];
  expect(firstPair).toBeDefined();

  const { object, context } = firstPair;
  expect(context).toEqual({});
  expect(object).toBeDefined();

  expect(object.name).toBe('Gladiator');
  expect(object.altId).toBe('mhmov-gladiator');
  expect(object.mhid).toBe('mhmovPeR81SeVnIPqEFsr36NYUqfqHuXzO9lDuQkq72G');

  const { primaryImage } = object;
  expectMediaHoundImage(primaryImage.object);
});
<|endoftext|>


<commit_before><commit_msg>Get Programming<commit_after><|endoftext|>


<commit_before>/* Eventedit pattern.
 *
 * Options:
 *    errorClass(string): class to set on the end datetime field wrapper, if end date validation fails. ('error')
 *
 * Documentation:
 *   # General
 *
 *   The pattern works with plone.app.event Archetypes and Dexterity forms.
 *
 *   * Start / end validation: The pattern adds a error class, if end is before
 *     start.
 *   * Start / end delta: After changing the start date, the end date is
 *     automatically updated by a delta timespan. The delta is calculated from
 *     the difference of the start and end time, if they are already set.
 *   * Whole day handling: After clicking the whole day checkbox, the start and
 *     end time fields are hidden.
 *   * Open end handling: After clicking the open end checkbox, the end
 *     date/time field is hidden.
 *
 *   # Dexterity form example
 *
 *   {{ example-1 }}
 *
 *   # Archetypes form example
 *
 *   {{ example-2 }}
 *
 * Example: example-1
 *

 *

 *        Start
 *        <input class="pat-pickadate" type="text" name="form.widgets.IEventBasic.start" value="2014-08-14 14:00" />
 *

 *

 *        End
 *        <input class="pat-pickadate" type="text" name="form.widgets.IEventBasic.end" value="2014-08-14 15:30" />
 *

 *

 *        Whole Day
 *        <input type="checkbox" />
 *

 *

 *        Open End
 *        <input type="checkbox" />
 *

 *

 *
 * Example: example-2
 *

 *

 *        Start
 *        <input class="pat-pickadate" type="text" name="startDate" value="2014-08-14 14:00" />
 *

 *

 *        End
 *        <input class="pat-pickadate" type="text" name="endDate" value="2014-08-14 14:30" />
 *

 *

 *        Whole Day
 *        <input type="checkbox" id="wholeDay" />
 *

 *

 *        Open End
 *        <input type="checkbox" id="openEnd" />
 *

 *

 *
 */

define([
  'jquery',
  'mockup-patterns-base',
  'mockup-patterns-pickadate',
], function ($, Base, pickadate) {
  'use strict';

  var EventEdit = Base.extend({
    name: 'eventedit',
    trigger: '.pat-eventedit',
    defaults: {
      errorClass: 'error'
    },
    init: function () {
      var self = this, $el = self.$el, jq_open_end, jq_end, jq_start;
      var jq_whole_day, jq_time;
      jq_whole_day = self.aOrB(
        $('#formfield-form-widgets-IEventBasic-whole_day input', $el),
        $('#archetypes-fieldname-wholeDay input#wholeDay', $el)
      );

      jq_time = self.aOrB(
        $('#formfield-form-widgets-IEventBasic-start .pattern-pickadate-time-wrapper, #formfield-form-widgets-IEventBasic-end .pattern-pickadate-time-wrapper', $el),
        $('#archetypes-fieldname-startDate .pattern-pickadate-time-wrapper, #archetypes-fieldname-endDate .pattern-pickadate-time-wrapper', $el)
      );

      if (jq_whole_day.length > 0 && jq_time.length > 0) {
        jq_whole_day.bind('change', function (e) {
          self.showHideWidget(jq_time, e.target.checked, true);
        });
        self.showHideWidget(jq_time, jq_whole_day.get(0).checked, false);
      }

      // OPEN END INIT
      jq_open_end = self.aOrB(
        $('#formfield-form-widgets-IEventBasic-open_end input', $el),
        $('#archetypes-fieldname-openEnd input#openEnd', $el)
      );
      jq_end = self.aOrB(
        $('#formfield-form-widgets-IEventBasic-end', $el),
        $('#archetypes-fieldname-endDate', $el)
      );
      if (jq_open_end.length > 0) {
        jq_open_end.bind('change', function (e) {
          self.showHideWidget(jq_end, e.target.checked, true);
        });
        self.showHideWidget(jq_end, jq_open_end.get(0).checked, false);
      }

      // START/END SETTING/VALIDATION
      jq_start = self.aOrB(
        $('#formfield-form-widgets-IEventBasic-start', $el),
        $('#archetypes-fieldname-startDate', $el)
      );
      jq_start.each(function () {
        $(this).on('focus', '.picker__input', function () { self.initDelta(); });
        $(this).on('change', '.picker__input', function () { self.updateEndDate(); });
      });
      jq_end.each(function () {
        $(this).on('focus', '.picker__input', function () { self.initDelta(); });
        $(this).on('change', '.picker__input', function () { self.validateEndDate(); });
      });

    },
    aOrB: function (a, b) {
      /* Return element a or element b, depending on which is available.
       * Parameter a and b: CSS selectors.
       * Returns: a jQuery object.
       */
      var ret;
      if ($(a).length > 0) {
        ret = a;
      } else {
        ret = b;
      }
      return $(ret);
    },
    getDateTime: function (datetimewidget) {
      var date, time, datetime;
      date = $('.pattern-pickadate-date-wrapper input[name="_submit"]', datetimewidget).prop('value');
      date = date.split("-");
      time = $('.pattern-pickadate-time-wrapper input[name="_submit"]', datetimewidget).prop('value') || '00:00';
      time = time.split(":");

      // We can't just parse the ``date + 'T' + time`` string, because of
      // Chromium bug: https://code.google.com/p/chromium/issues/detail?id=145198
      // When passing date and time components, the passed date/time is
      // interpreted as local time and not UTC.
      datetime = new Date(
        parseInt(date[0], 10),
        parseInt(date[1], 10) - 1, // you know, javascript's month index starts with 0
        parseInt(date[2], 10),
        parseInt(time[0], 10),
        parseInt(time[1], 10)
      );
      return datetime;
    },
    initDelta: function () {
        var self = this, $el = self.$el, start_datetime, end_datetime;
        start_datetime = self.getDateTime(
          self.aOrB(
            $('#formfield-form-widgets-IEventBasic-start', $el),
            $('#archetypes-fieldname-startDate', $el)
          )
        );
        end_datetime = self.getDateTime(
          self.aOrB(
            $('#formfield-form-widgets-IEventBasic-end', $el),
            $('#archetypes-fieldname-endDate', $el)
          )
        );
        // delta in days
        self.startEndDelta = (end_datetime - start_datetime) / 1000 / 60;
    },
    updateEndDate: function () {
        var self = this, $el = self.$el, jq_start, jq_end, start_date, new_end_date;
        jq_start = self.aOrB(
          $('#formfield-form-widgets-IEventBasic-start', $el),
          $('#archetypes-fieldname-startDate', $el)
        );
        jq_end = self.aOrB(
          $('#formfield-form-widgets-IEventBasic-end', $el),
          $('#archetypes-fieldname-endDate', $el)
        );

        start_date = self.getDateTime(jq_start);
        new_end_date = new Date(start_date);
        new_end_date.setMinutes(start_date.getMinutes() + self.startEndDelta);

        if (new_end_date) {
          $('.pattern-pickadate-date', jq_end).pickadate('picker').set('select', new_end_date);
          $('.pattern-pickadate-time', jq_end).pickatime('picker').set('select', new_end_date);
        }
    },
    validateEndDate: function () {
        var self = this, $el = self.$el, jq_start, jq_end, start_datetime, end_datetime;
        jq_start = self.aOrB(
          $('#formfield-form-widgets-IEventBasic-start', $el),
          $('#archetypes-fieldname-startDate', $el)
        );
        jq_end = self.aOrB(
          $('#formfield-form-widgets-IEventBasic-end', $el),
          $('#archetypes-fieldname-endDate', $el)
        );

        start_datetime = self.getDateTime(jq_start);
        end_datetime = self.getDateTime(jq_end);

        if (end_datetime < start_datetime) {
            jq_end.addClass(self.options.errorClass);
        } else {
            jq_end.removeClass(self.options.errorClass);
        }
    },
    showHideWidget: function (widget, hide, fade) {
        var $widget = $(widget);
        if (hide === true) {
            if (fade === true) { $widget.fadeOut(); }
            else { $widget.hide(); }
        } else {
            if (fade === true) { $widget.fadeIn(); }
            else { $widget.show(); }
        }
    }
  });
  return EventEdit;
});
<commit_msg>Don't listen to focus event in order to set the time delta.<commit_after>/* Eventedit pattern.
 *
 * Options:
 *    errorClass(string): class to set on the end datetime field wrapper, if end date validation fails. ('error')
 *
 * Documentation:
 *   # General
 *
 *   The pattern works with plone.app.event Archetypes and Dexterity forms.
 *
 *   * Start / end validation: The pattern adds a error class, if end is before
 *     start.
 *   * Start / end delta: After changing the start date, the end date is
 *     automatically updated by a delta timespan. The delta is calculated from
 *     the difference of the start and end time, if they are already set.
 *   * Whole day handling: After clicking the whole day checkbox, the start and
 *     end time fields are hidden.
 *   * Open end handling: After clicking the open end checkbox, the end
 *     date/time field is hidden.
 *
 *   # Dexterity form example
 *
 *   {{ example-1 }}
 *
 *   # Archetypes form example
 *
 *   {{ example-2 }}
 *
 * Example: example-1
 *

 *

 *        Start
 *        <input class="pat-pickadate" type="text" name="form.widgets.IEventBasic.start" value="2014-08-14 14:00" />
 *

 *

 *        End
 *        <input class="pat-pickadate" type="text" name="form.widgets.IEventBasic.end" value="2014-08-14 15:30" />
 *

 *

 *        Whole Day
 *        <input type="checkbox" />
 *

 *

 *        Open End
 *        <input type="checkbox" />
 *

 *

 *
 * Example: example-2
 *

 *

 *        Start
 *        <input class="pat-pickadate" type="text" name="startDate" value="2014-08-14 14:00" />
 *

 *

 *        End
 *        <input class="pat-pickadate" type="text" name="endDate" value="2014-08-14 14:30" />
 *

 *

 *        Whole Day
 *        <input type="checkbox" id="wholeDay" />
 *

 *

 *        Open End
 *        <input type="checkbox" id="openEnd" />
 *

 *

 *
 */

define([
  'jquery',
  'mockup-patterns-base',
  'mockup-patterns-pickadate',
], function ($, Base, pickadate) {
  'use strict';

  var EventEdit = Base.extend({
    name: 'eventedit',
    trigger: '.pat-eventedit',
    defaults: {
      errorClass: 'error'
    },
    init: function () {
      var self = this, $el = self.$el, jq_open_end, jq_end, jq_start;
      var jq_whole_day, jq_time;
      jq_whole_day = self.aOrB(
        $('#formfield-form-widgets-IEventBasic-whole_day input', $el),
        $('#archetypes-fieldname-wholeDay input#wholeDay', $el)
      );

      jq_time = self.aOrB(
        $('#formfield-form-widgets-IEventBasic-start .pattern-pickadate-time-wrapper, #formfield-form-widgets-IEventBasic-end .pattern-pickadate-time-wrapper', $el),
        $('#archetypes-fieldname-startDate .pattern-pickadate-time-wrapper, #archetypes-fieldname-endDate .pattern-pickadate-time-wrapper', $el)
      );

      if (jq_whole_day.length > 0 && jq_time.length > 0) {
        jq_whole_day.bind('change', function (e) {
          self.showHideWidget(jq_time, e.target.checked, true);
        });
        self.showHideWidget(jq_time, jq_whole_day.get(0).checked, false);
      }

      // OPEN END INIT
      jq_open_end = self.aOrB(
        $('#formfield-form-widgets-IEventBasic-open_end input', $el),
        $('#archetypes-fieldname-openEnd input#openEnd', $el)
      );
      jq_end = self.aOrB(
        $('#formfield-form-widgets-IEventBasic-end', $el),
        $('#archetypes-fieldname-endDate', $el)
      );
      if (jq_open_end.length > 0) {
        jq_open_end.bind('change', function (e) {
          self.showHideWidget(jq_end, e.target.checked, true);
        });
        self.showHideWidget(jq_end, jq_open_end.get(0).checked, false);
      }

      // START/END SETTING/VALIDATION
      jq_start = self.aOrB(
        $('#formfield-form-widgets-IEventBasic-start', $el),
        $('#archetypes-fieldname-startDate', $el)
      );
      jq_start.each(function () {
        $(this).on('change', '.picker__input', function () { self.updateEndDate(); });
      });
      jq_end.each(function () {
        $(this).on('change', '.picker__input', function () { self.validateEndDate(); });
      });
    },

    aOrB: function (a, b) {
      /* Return element a or element b, depending on which is available.
       * Parameter a and b: CSS selectors.
       * Returns: a jQuery object.
       */
      var ret;
      if ($(a).length > 0) {
        ret = a;
      } else {
        ret = b;
      }
      return $(ret);
    },

    getDateTime: function (datetimewidget) {
      var date, time, datetime;
      date = $('.pattern-pickadate-date-wrapper input[name="_submit"]', datetimewidget).prop('value');
      date = date.split("-");
      time = $('.pattern-pickadate-time-wrapper input[name="_submit"]', datetimewidget).prop('value') || '00:00';
      time = time.split(":");

      // We can't just parse the ``date + 'T' + time`` string, because of
      // Chromium bug: https://code.google.com/p/chromium/issues/detail?id=145198
      // When passing date and time components, the passed date/time is
      // interpreted as local time and not UTC.
      datetime = new Date(
        parseInt(date[0], 10),
        parseInt(date[1], 10) - 1, // you know, javascript's month index starts with 0
        parseInt(date[2], 10),
        parseInt(time[0], 10),
        parseInt(time[1], 10)
      );
      return datetime;
    },

    getTimeDelta: function () {
        // Return time delta between the start and end dates in days
        var self = this, $el = self.$el, start_datetime, end_datetime;
        start_datetime = self.getDateTime(
          self.aOrB(
            $('#formfield-form-widgets-IEventBasic-start', $el),
            $('#archetypes-fieldname-startDate', $el)
          )
        );
        end_datetime = self.getDateTime(
          self.aOrB(
            $('#formfield-form-widgets-IEventBasic-end', $el),
            $('#archetypes-fieldname-endDate', $el)
          )
        );
        return (end_datetime - start_datetime) / 1000 / 60;
    },

    updateEndDate: function () {
        var self = this, $el = self.$el, jq_start, jq_end, start_date, new_end_date;
        jq_start = self.aOrB(
          $('#formfield-form-widgets-IEventBasic-start', $el),
          $('#archetypes-fieldname-startDate', $el)
        );
        jq_end = self.aOrB(
          $('#formfield-form-widgets-IEventBasic-end', $el),
          $('#archetypes-fieldname-endDate', $el)
        );

        start_date = self.getDateTime(jq_start);
        new_end_date = new Date(start_date);
        new_end_date.setMinutes(start_date.getMinutes() + self.getTimeDelta());

        if (new_end_date) {
          $('.pattern-pickadate-date', jq_end).pickadate('picker').set('select', new_end_date);
          $('.pattern-pickadate-time', jq_end).pickatime('picker').set('select', new_end_date);
        }
    },

    validateEndDate: function () {
        var self = this, $el = self.$el, jq_start, jq_end, start_datetime, end_datetime;
        jq_start = self.aOrB(
          $('#formfield-form-widgets-IEventBasic-start', $el),
          $('#archetypes-fieldname-startDate', $el)
        );
        jq_end = self.aOrB(
          $('#formfield-form-widgets-IEventBasic-end', $el),
          $('#archetypes-fieldname-endDate', $el)
        );
        start_datetime = self.getDateTime(jq_start);
        end_datetime = self.getDateTime(jq_end);
        if (end_datetime < start_datetime) {
            jq_end.addClass(self.options.errorClass);
        } else {
            jq_end.removeClass(self.options.errorClass);
        }
    },

    showHideWidget: function (widget, hide, fade) {
        var $widget = $(widget);
        if (hide === true) {
            if (fade === true) { $widget.fadeOut(); }
            else { $widget.hide(); }
        } else {
            if (fade === true) { $widget.fadeIn(); }
            else { $widget.show(); }
        }
    }
  });
  return EventEdit;
});
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Tue Apr 29 2014 22:08:20 GMT-0600 (CST)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '../../../../..',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      'vendor/assets/javascripts/angular.1.2.16.min.js',
      'vendor/assets/javascripts/angular-mocks.js',
      'app/assets/javascripts/angular/**/*.js',
      'app/assets/javascripts/angular/test/unit/*.js'
    ],

    // list of files to exclude
    exclude: [
      'app/assets/javascripts/angular/test/e2e/**',
      'app/assets/javascripts/angular/test/protractorConf.js'
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {

    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Firefox'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
  });
};
<commit_msg>fix the karma config<commit_after>// Karma configuration
// Generated on Tue Apr 29 2014 22:08:20 GMT-0600 (CST)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '../../../../..',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      'vendor/assets/javascripts/angular.js',
      'vendor/assets/javascripts/angular-mocks.js',
      'app/assets/javascripts/angular/**/*.js',
      'app/assets/javascripts/angular/test/unit/*.js'
    ],

    // list of files to exclude
    exclude: [
      'app/assets/javascripts/angular/test/e2e/**',
      'app/assets/javascripts/angular/test/protractorConf.js'
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {

    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Firefox'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
  });
};
<|endoftext|>