<commit_before>/*
Copyright (c) : 2010-2016 ITER Organization,
CS 90 046
13067 St. Paul-lez-Durance Cedex
France

This product is part of ITER CODAC software.
For the terms and conditions of redistribution or use of this software
refer to the file ITER-LICENSE.TXT located in the top level directory
of the distribution package.
*/

importPackage(Packages.org.csstudio.opibuilder.scriptUtil);
importPackage(Packages.java.lang)

	// getting the current cbs level for this screen
	var current_level = widget.getMacroValue("LEVEL");
	var depth = getLevelDepth(current_level);
	var level = "";

	// getting the type of OPI: USER or ALARM
	var opi_type = widget.getMacroValue("OPI_TYPE");
	if (opi_type == null || opi_type != "ALARM") {
		opi_type = "USER";
	}

	// getting the input xml file path
	var xml_input = widget.getMacroValue("INPUT");
	// getting the navigation xml file from the user navigation folder
	if (xml_input == null) {
		xml_input = "../navigation/Navigation.xml";
	}
	// loading XML document and getting the root element
	// the result is a JDOM Element
	var root = FileUtil.loadXMLFile(xml_input, widget);
	if (root) {
		// browsing the CBS tree structure starting from 0 to max depth
		listCBS(root, 0, depth);
	}

// ---

// recursive list function on CBS tree
function listCBS(current, depth, max_depth){
	var cbs = current.getChildren();
	if (cbs) {
		var itr = cbs.iterator();
		while (itr.hasNext() && depth <= max_depth) {
		    var elt = itr.next();
		    if (isEltCurrentCBS(elt)) {
			    if (depth == 0){
				    // adding the Home button for level 0 - ITER overview
			    	addHomeButton(elt);
			    } else {
			    	// adding an Up button for intermediate levels
			    	addUpButton(elt);
			    }

		    	if (depth == max_depth && elt.getChildren().size()) {
		    		// adding Mimic buttons
				    addMimicButtons(elt);
		    	} else {
			    	listCBS(elt, depth+1, max_depth);
			    	depth = max_depth + 1;
			    	if (!elt.getChildren().size()) {
			    		// repeat parent Mimic buttons
			    		addMimicButtons(current);
			    	}
		    	}
	    	}
		}
	}
}

function getLevelDepth(current_level) {
	if (current_level == "" || !current_level) {
		// CBS 0 is not specified or empty name
		return 0;
	}
	// getting the number of levels
	// for instance UTIL-S15-AG07 has 3 CBS levels - ITER is CBS0
	var words = current_level.split("-");
	return words.length - 1;
}

function isEltCurrentCBS(elt) {
	if (getLevelDepth(current_level) == 0) {
		return true;
	}

	var iLevel = level + elt.getAttributeValue("name");
	if (iLevel && current_level.startsWith(iLevel)) {
	  	level = iLevel + "-";
	  	return true;
	 }
	 return false;
}

function getGeneralNavigationContainer() {
	return display.getWidget("GENERAL NAVIGATION BAR");
}

function getGeneralNavigationContainerHeight() {
	return getGeneralNavigationContainer().getPropertyValue("height");
}

function getGeneralNavigationContainerWidth() {
	return getGeneralNavigationContainer().getPropertyValue("width");
}

function getMimicNavigationContainer() {
	return display.getWidget("MIMIC SPECIFIC - NAVIGATION AREA");
}

function getMimicNavigationContainerHeight() {
	return getMimicNavigationContainer().getPropertyValue("height");
}

function getMimicNavigationContainerWidth() {
	return getMimicNavigationContainer().getPropertyValue("width");
}

function getLineOneNavigationContainer() {
	return getMimicNavigationContainer().getWidget("OneLineNavigation");
}

function getLineTwoNavigationContainer() {
	return getMimicNavigationContainer().getWidget("TwoLineNavigation");
}

function addHomeButton(elt) {
	//if no name defined, ITER is the default cbs name
	var cbs_name = !elt.getAttributeValue("name") ? "ITER" : elt.getAttributeValue("name");

	//creating the linking container that display the HOME button
	var linkingContainer = createHomeButtonContainer();
	if (linkingContainer) {
	    // reading attribute from element using JDOM
	    // adding macros CBS and OPI_FILE to the container
		linkingContainer.addMacro("CBS", cbs_name);
		linkingContainer.addMacro("OPI_FILE", getOPI_FILE(elt));
		linkingContainer.addMacro("ALARM_ROOT", getALARM_ROOT(elt));
		addOPImacros(linkingContainer, elt);

		// adding the linking container to the navigation widget
		getGeneralNavigationContainer().addChildToRight(linkingContainer);

		// setting the navigation button properties
	 	var button = getGeneralNavigationContainer().getWidget(cbs_name);
	 	button.setPropertyValue("height", getGeneralNavigationContainerHeight());
	 	button.setPropertyValue("width", getGeneralNavigationContainerWidth()/3);
		setButton(button, elt);
	}
}

function createHomeButtonContainer() {
	var height = getGeneralNavigationContainerHeight();
	var width = getGeneralNavigationContainerWidth()/3;
	return createButtonContainer("NavigationHomeButton.opi", width, height);
}

function addUpButton(elt) {
	var iLevel = level.substr(0, level.length-1);

	//creating the linking container that display the Up button
	var linkingContainer = createUpButtonContainer();
	if (linkingContainer) {
	    // reading attribute from element using JDOM
	    // adding macros CBS and OPI_FILE to the container
		linkingContainer.addMacro("CBS", elt.getAttributeValue("name"));
		linkingContainer.addMacro("CBS_PATH", iLevel);
		linkingContainer.addMacro("OPI_FILE", getOPI_FILE(elt));
		linkingContainer.addMacro("ALARM_ROOT", getALARM_ROOT(elt));
		addOPImacros(linkingContainer, elt);

		// adding the linking container to the navigation widget
		getGeneralNavigationContainer().addChildToRight(linkingContainer);

		// setting the navigation button properties
	 	var button = getGeneralNavigationContainer().getWidget(iLevel);
	 	button.setPropertyValue("height", getGeneralNavigationContainerHeight());
	 	button.setPropertyValue("width", (getGeneralNavigationContainerWidth()*2/3)/5);
		setButton(button, elt);
	}
}

function createUpButtonContainer() {
	var height = getGeneralNavigationContainerHeight();
	var width = getGeneralNavigationContainerWidth();
	var home = getGeneralNavigationContainerWidth()/3;
	return createButtonContainer("NavigationUpButton.opi", (width - home)/5, height);
}

function addMimicButtons(root) {
	var cbs = root.getChildren();

	var container = getMimicNavigationContainer();

	var nbButtons = cbs.size();
	var nbButtonsPerLine = 10;

	// default button size for maximum 10 buttons on one line
	var height = getMimicNavigationContainerHeight();
	var width = (getMimicNavigationContainerWidth()/nbButtonsPerLine)-1;

	// if more than 10 buttons required, 2 lines of buttons are needed
	if (nbButtons > nbButtonsPerLine) {
		container = getLineOneNavigationContainer();
		height = height/2;
		// if more than 20 buttons, they have to fit on 2 lines
		if (nbButtons > (2 * nbButtonsPerLine)) {
			nbButtonsPerLine = Math.ceil(nbButtons/2);
			width = getMimicNavigationContainerWidth()/nbButtonsPerLine - 1;
		}
	} else {
		// cleaning the one and two line child containers are they are not needed
		container.removeAllChildren();
	}

	// iterating over all children in XML
	var i = 0;
	var itr = cbs.iterator();
	while (itr.hasNext()) {
	    var elt = itr.next();

	    if (elt.getAttributeValue("name")) {
			//creating the linking container that display the mimic specific buttons
			var linkingContainer = createButtonContainer("NavigationMimicButton.opi", width, height);

			if (i == nbButtonsPerLine) {
				container = getLineTwoNavigationContainer();
			}

		    // reading attribute from element using JDOM
		    // adding macros CBS and OPI_FILE to the container
			linkingContainer.addMacro("CBS", elt.getAttributeValue("name"));
			linkingContainer.addMacro("OPI_FILE", getOPI_FILE(elt));
			linkingContainer.addMacro("ALARM_ROOT", getALARM_ROOT(elt));
			addOPImacros(linkingContainer, elt);

			// adding the linking container to the navigation widget
			container.addChildToRight(linkingContainer);

		    // reading value of children in XML using JDOM
			// setting navigation button properties
		 	var button = container.getWidget(elt.getAttributeValue("name"));
		 	button.setPropertyValue("height", height);
		 	button.setPropertyValue("width", width);
			setButton(button, elt);

		 	i+=1;
		 }
	}
}

function getOPI_FILE(elt) {
	var attribute = "";
	if (opi_type == "USER") {
		// getting the opi file from the navigation xml configuration file
		attribute = elt.getAttributeValue("opi_file");

		if (attribute && attribute.search(".opi") > 0) {
	    	// suppressing the extension .opi
	    	return attribute.substring(0, attribute.search(".opi"));
	    }
	    return attribute;
    } else {
    	// getting the opi file from a macro
		attribute = widget.getMacroValue("OPI_FILE");
	    return attribute;
    }
}

function getALARM_ROOT(elt) {
    return elt.getAttributeValue("alarm_root");
}

function addOPImacros(container, elt) {
	// getting the opi file from the navigation xml configuration file (even for alarms list)
	var attribute = elt.getAttributeValue("opi_file");

	if (attribute) {
		var words = attribute.match(/(?:[^\s']+|'[^']*')+/g);

		var i=0;
		for (i in words) {
			if (words[i].search("=") > 0) {
		    	var macros = words[i].split("=");
		    	// macro format: macro_name=macro_value
		    	var macro_name = macros[0];
		    	var macro_value = (macros[1] == null) ? "" : macros[1];
		       	container.addMacro(macro_name, macro_value);
		    }
		}
	}
}

function createButtonContainer(opi_container, width, height) {
		var linkingContainer = WidgetUtil.createWidgetModel("org.csstudio.opibuilder.widgets.linkingContainer");

		linkingContainer.setPropertyValue("opi_file", opi_container);
		linkingContainer.setPropertyValue("border_style", 0);
		linkingContainer.setPropertyValue("width", width);
		linkingContainer.setPropertyValue("height", height);
		linkingContainer.setPropertyValue("resize_behaviour", 2);

		return linkingContainer;
}

function setButton(button, elt) {
    // reading value of children in XML using JDOM
	// setting navigation button properties
 	button.setPropertyValue("tooltip", elt.getAttributeValue("description") + " ($(number_alarms) alarm(s))");
 	button.setPropertyValue("enabled", elt.getAttributeValue("enabled"));
 	if (elt.getAttributeValue("deprecated") && elt.getAttributeValue("deprecated").search("true") >= 0) {
 		button.setPropertyValue("border_style", 9);
	 	button.setPropertyValue("tooltip", elt.getAttributeValue("description") + " (deprecated)");
	}
}
<commit_msg>Refactoring to decrease the complexity of some functions<commit_after>/*
Copyright (c) : 2010-2016 ITER Organization,
CS 90 046
13067 St. Paul-lez-Durance Cedex
France

This product is part of ITER CODAC software.
For the terms and conditions of redistribution or use of this software
refer to the file ITER-LICENSE.TXT located in the top level directory
of the distribution package.
*/

importPackage(Packages.org.csstudio.opibuilder.scriptUtil);
importPackage(Packages.java.lang)

	// getting the current cbs level for this screen
	var current_level = widget.getMacroValue("LEVEL");
	var depth = getNavigationDepth(current_level);
	var level = "";

	// getting the type of OPI: USER or ALARM
	var opi_type = widget.getMacroValue("OPI_TYPE");
	if (opi_type == null || opi_type != "ALARM") {
		opi_type = "USER";
	}

	// getting the input xml file path
	var xml_input = widget.getMacroValue("INPUT");
	// getting the navigation xml file from the user navigation folder
	if (xml_input == null) {
		xml_input = "../navigation/Navigation.xml";
	}
	// loading XML document and getting the root element
	// the result is a JDOM Element
	var root = FileUtil.loadXMLFile(xml_input, widget);
	if (root) {
		// browsing the CBS tree structure starting from 0 to max depth
		listCBS(root, 0, depth);
	}

// ---

// recursive list function on CBS tree
function listCBS(current, level, depth){
	var cbs = current.getChildren();
	if (cbs) {
		var itr = cbs.iterator();
		while (itr.hasNext() && level <= depth) {
		    var elt = itr.next();
		    if (currentCBS(elt)) {
			    updateGlobalNavigationButtons(elt, level);
			    // continue the parsing of the CBS navigation tree
				listCBS(elt, level + 1, depth);
			    if (lastNavigationLevel(level, depth)) {
			    	updateMimicNavigationButtons(current, elt);
			    }
		    }
		}
	}
}

function getNavigationDepth(current_level) {
	if (current_level == "" || !current_level) {
		// CBS 0 is not specified or empty name
		return 0;
	}
	// getting the number of levels
	// for instance UTIL-S15-AG07 has 3 CBS levels - ITER is CBS0
	var words = current_level.split("-");
	return words.length - 1;
}

function currentCBS(elt) {
	if (getNavigationDepth(current_level) == 0) {
		return true;
	}

	var iLevel = level + elt.getAttributeValue("name");
	if (iLevel && current_level.startsWith(iLevel)) {
	  	level = iLevel + "-";
	  	return true;
	 }
	 return false;
}

function lastNavigationLevel(currentLevel, lastLevel){
	return (currentLevel == lastLevel)
}

function updateGlobalNavigationButtons(thisCBS, level){
	if (level == 0){
	    // adding the Home button for level 0 - ITER overview
		addHomeButton(thisCBS);
	} else {
		// adding an Up button for intermediate levels
		addUpButton(thisCBS);
	}
}

function updateMimicNavigationButtons(parentCBS, thisCBS){
	if (thisCBS.getChildren().size()) {
		// adding Mimic buttons
	    addMimicButtons(thisCBS);
	} else {
		// repeat parent Mimic buttons
		addMimicButtons(parentCBS);
	}
}

function getGeneralNavigationContainer() {
	return display.getWidget("GENERAL NAVIGATION BAR");
}

function getGeneralNavigationContainerHeight() {
	return getGeneralNavigationContainer().getPropertyValue("height");
}

function getGeneralNavigationContainerWidth() {
	return getGeneralNavigationContainer().getPropertyValue("width");
}

function getMimicNavigationContainer() {
	return display.getWidget("MIMIC SPECIFIC - NAVIGATION AREA");
}

function getMimicNavigationContainerHeight() {
	return getMimicNavigationContainer().getPropertyValue("height");
}

function getMimicNavigationContainerWidth() {
	return getMimicNavigationContainer().getPropertyValue("width");
}

function getLineOneNavigationContainer() {
	return getMimicNavigationContainer().getWidget("OneLineNavigation");
}

function getLineTwoNavigationContainer() {
	return getMimicNavigationContainer().getWidget("TwoLineNavigation");
}

function addHomeButton(elt) {
	//if no name defined, ITER is the default cbs name
	var cbs_name = !elt.getAttributeValue("name") ? "ITER" : elt.getAttributeValue("name");

	//creating the linking container that display the HOME button
	var linkingContainer = createHomeButtonContainer();
	if (linkingContainer) {
	    // reading attribute from element using JDOM
	    // adding macros CBS and OPI_FILE to the container
		linkingContainer.addMacro("CBS", cbs_name);
		linkingContainer.addMacro("OPI_FILE", getOPI_FILE(elt));
		linkingContainer.addMacro("ALARM_ROOT", getALARM_ROOT(elt));
		addOPImacros(linkingContainer, elt);

		// adding the linking container to the navigation widget
		getGeneralNavigationContainer().addChildToRight(linkingContainer);

		// setting the navigation button properties
	 	var button = getGeneralNavigationContainer().getWidget(cbs_name);
	 	button.setPropertyValue("height", getGeneralNavigationContainerHeight());
	 	button.setPropertyValue("width", getGeneralNavigationContainerWidth()/3);
		setButton(button, elt);
	}
}

function createHomeButtonContainer() {
	var height = getGeneralNavigationContainerHeight();
	var width = getGeneralNavigationContainerWidth()/3;
	return createButtonContainer("NavigationHomeButton.opi", width, height);
}

function addUpButton(elt) {
	var iLevel = level.substr(0, level.length-1);

	//creating the linking container that display the Up button
	var linkingContainer = createUpButtonContainer();
	if (linkingContainer) {
	    // reading attribute from element using JDOM
	    // adding macros CBS and OPI_FILE to the container
		linkingContainer.addMacro("CBS", elt.getAttributeValue("name"));
		linkingContainer.addMacro("CBS_PATH", iLevel);
		linkingContainer.addMacro("OPI_FILE", getOPI_FILE(elt));
		linkingContainer.addMacro("ALARM_ROOT", getALARM_ROOT(elt));
		addOPImacros(linkingContainer, elt);

		// adding the linking container to the navigation widget
		getGeneralNavigationContainer().addChildToRight(linkingContainer);

		// setting the navigation button properties
	 	var button = getGeneralNavigationContainer().getWidget(iLevel);
	 	button.setPropertyValue("height", getGeneralNavigationContainerHeight());
	 	button.setPropertyValue("width", (getGeneralNavigationContainerWidth()*2/3)/5);
		setButton(button, elt);
	}
}

function createUpButtonContainer() {
	var height = getGeneralNavigationContainerHeight();
	var width = getGeneralNavigationContainerWidth();
	var home = getGeneralNavigationContainerWidth()/3;
	return createButtonContainer("NavigationUpButton.opi", (width - home)/5, height);
}

function addMimicButtons(root) {
	var cbs = root.getChildren();

	var container = getMimicNavigationContainer();

	var nbButtons = cbs.size();
	var nbButtonsPerLine = 10;

	// default button size for maximum 10 buttons on one line
	var height = getMimicNavigationContainerHeight();
	var width = (getMimicNavigationContainerWidth()/nbButtonsPerLine)-1;

	// if more than 10 buttons required, 2 lines of buttons are needed
	if (nbButtons > nbButtonsPerLine) {
		container = getLineOneNavigationContainer();
		height = height/2;
		// if more than 20 buttons, they have to fit on 2 lines
		if (nbButtons > (2 * nbButtonsPerLine)) {
			nbButtonsPerLine = Math.ceil(nbButtons/2);
			width = getMimicNavigationContainerWidth()/nbButtonsPerLine - 1;
		}
	} else {
		// cleaning the one and two line child containers are they are not needed
		container.removeAllChildren();
	}

	// iterating over all children in XML
	var i = 0;
	var itr = cbs.iterator();
	while (itr.hasNext()) {
	    var elt = itr.next();

	    if (elt.getAttributeValue("name")) {
			//creating the linking container that display the mimic specific buttons
			var linkingContainer = createButtonContainer("NavigationMimicButton.opi", width, height);

			if (i == nbButtonsPerLine) {
				container = getLineTwoNavigationContainer();
			}

		    // reading attribute from element using JDOM
		    // adding macros CBS and OPI_FILE to the container
			linkingContainer.addMacro("CBS", elt.getAttributeValue("name"));
			linkingContainer.addMacro("OPI_FILE", getOPI_FILE(elt));
			linkingContainer.addMacro("ALARM_ROOT", getALARM_ROOT(elt));
			addOPImacros(linkingContainer, elt);

			// adding the linking container to the navigation widget
			container.addChildToRight(linkingContainer);

		    // reading value of children in XML using JDOM
			// setting navigation button properties
		 	var button = container.getWidget(elt.getAttributeValue("name"));
		 	button.setPropertyValue("height", height);
		 	button.setPropertyValue("width", width);
			setButton(button, elt);

		 	i+=1;
		 }
	}
}

function getOPI_FILE(elt) {
	var attribute = "";
	if (opi_type == "USER") {
		// getting the opi file from the navigation xml configuration file
		attribute = elt.getAttributeValue("opi_file");

		if (attribute && attribute.search(".opi") > 0) {
	    	// suppressing the extension .opi
	    	return attribute.substring(0, attribute.search(".opi"));
	    }
	    return attribute;
    } else {
    	// getting the opi file from a macro
		attribute = widget.getMacroValue("OPI_FILE");
	    return attribute;
    }
}

function getALARM_ROOT(elt) {
    return elt.getAttributeValue("alarm_root");
}

function addOPImacros(container, elt) {
	// getting the opi file from the navigation xml configuration file (even for alarms list)
	var attribute = elt.getAttributeValue("opi_file");

	if (attribute) {
		var words = attribute.match(/(?:[^\s']+|'[^']*')+/g);

		var i=0;
		for (i in words) {
			if (words[i].search("=") > 0) {
		    	var macros = words[i].split("=");
		    	// macro format: macro_name=macro_value
		    	var macro_name = macros[0];
		    	var macro_value = (macros[1] == null) ? "" : macros[1];
		       	container.addMacro(macro_name, macro_value);
		    }
		}
	}
}

function createButtonContainer(opi_container, width, height) {
		var linkingContainer = WidgetUtil.createWidgetModel("org.csstudio.opibuilder.widgets.linkingContainer");

		linkingContainer.setPropertyValue("opi_file", opi_container);
		linkingContainer.setPropertyValue("border_style", 0);
		linkingContainer.setPropertyValue("width", width);
		linkingContainer.setPropertyValue("height", height);
		linkingContainer.setPropertyValue("resize_behaviour", 2);

		return linkingContainer;
}

function setButton(button, elt) {
    // reading value of children in XML using JDOM
	// setting navigation button properties
 	button.setPropertyValue("tooltip", elt.getAttributeValue("description") + " ($(number_alarms) alarm(s))");
 	button.setPropertyValue("enabled", elt.getAttributeValue("enabled"));
 	if (elt.getAttributeValue("deprecated") && elt.getAttributeValue("deprecated").search("true") >= 0) {
 		button.setPropertyValue("border_style", 9);
	 	button.setPropertyValue("tooltip", elt.getAttributeValue("description") + " (deprecated)");
	}
}
<|endoftext|>


<commit_before>// Copyright 2016 Documize Inc. <legal@documize.com>. All rights reserved.
//
// This software (Documize Community Edition) is licensed under
// GNU AGPL v3 http://www.gnu.org/licenses/agpl-3.0.en.html
//
// You can operate outside the AGPL restrictions by purchasing
// Documize Enterprise Edition and obtaining a commercial license
// by contacting <sales@documize.com>.
//
// https://documize.com

import $ from 'jquery';
import { computed, observer } from '@ember/object';
import { debounce } from '@ember/runloop';
import { inject as service } from '@ember/service';
import Notifier from '../../mixins/notifier';
import ModalMixin from '../../mixins/modal';
import tocUtil from '../../utils/toc';
import Component from '@ember/component';

export default Component.extend(Notifier, ModalMixin, {
	documentService: service('document'),
	searchService: service('search'),
	router: service(),
	appMeta: service(),
	deleteChildren: false,
	blockTitle: "",
	blockExcerpt: "",
	targetSpace: null,
	targetDocs: null,
	targetDoc: null,

	// eslint-disable-next-line ember/no-observers
	onKeywordChange: observer('docSearchFilter',  function() {
		debounce(this, this.searchDocs, 750);
	}),

	emptySearch: computed('docSearchResults', function() {
		return this.get('docSearchResults.length') === 0;
	}),
	canEdit: computed('permissions', 'document', 'pages', function() {
		let constants = this.get('constants');
		let permissions = this.get('permissions');
		let authenticated = this.get('session.authenticated');
		let notEmpty = this.get('pages.length') > 0;

		if (notEmpty && authenticated && permissions.get('documentEdit')
			&& (this.get('document.protection') !== constants.ProtectionType.Locked)) {
				return true;
		}

		// if (notEmpty && authenticated && permissions.get('documentEdit') && this.get('document.protection') === constants.ProtectionType.None) return true;
		// if (notEmpty && authenticated && permissions.get('documentApprove') && this.get('document.protection') === constants.ProtectionType.Review) return true;

		return false;
	}),

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

		this.state = {
			actionablePage: false,
			upDisabled: true,
			downDisabled: true,
			indentDisabled: true,
			outdentDisabled: true,
			pageId: ''
		};
	},

	didReceiveAttrs() {
		this._super(...arguments);
		this.modalInputFocus('#publish-page-modal-' + this.get('page.id'), '#block-title-' + this.get('page.id'));

		this.setState(this.get('page.id'));
	},

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

		let pageId = this.get('page.id');
		let url = this.get('appMeta.appHost') +
			this.get('router').generate('document.index', {queryParams: {currentPageId: pageId}});
		let self = this;

		let clip = new ClipboardJS('#page-copy-link-' + pageId, {
			text: function() {
				self.notifySuccess('Link copied to clipboard');
				return url;
			}
		});

		this.set('clip', clip);
	},

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

		let clip = this.get('clip');
		if (!_.isUndefined(clip)) clip.destroy();
	},

	// Controls what user can do with the toc enty for this page
	setState(pageId) {
		let toc = this.get('pages');
		let page = _.find(toc, function(i) { return i.get('page.id') === pageId; });
		let state = tocUtil.getState(toc, page.get('page'));

		if (!this.get('canEdit')) {
			state.actionablePage = false;
			state.upDisabled = state.downDisabled = state.indentDisabled = state.outdentDisabled = true;
		}

		this.set('state', state);
	},

	actions: {
		onShowSectionWizard(beforePage) {
			this.get('onShowSectionWizard')(beforePage);
		},

		onEdit() {
			let page = this.get('page');

			if (page.get('pageType') == this.get('constants').PageType.Tab) {
				this.get('router').transitionTo('document.section', page.get('id'));
			} else {
				let cb = this.get('onEdit');
				cb();
			}
		},

		onDeletePage() {
			let cb = this.get('onDeletePage');
			cb(this.get('deleteChildren'));

			this.modalClose('#delete-page-modal-' + this.get('page.id'));
		},

		onShowPublishModal() {
			this.modalOpen('#publish-page-modal-' + this.get('page.id'), {"show": true}, '#block-title-' + this.get('page.id'));
		},

		onSavePageAsBlock() {
			let page = this.get('page');
			let titleElem = '#block-title-' + page.get('id');
			let blockTitle = this.get('blockTitle');
			if (_.isEmpty(blockTitle)) {
				$(titleElem).addClass('is-invalid');
				return;
			}

			let excerptElem = '#block-desc-' + page.get('id');
			let blockExcerpt = this.get('blockExcerpt');
			blockExcerpt = blockExcerpt.replace(/\n/g, "");
			if (_.isEmpty(blockExcerpt)) {
				$(excerptElem).addClass('is-invalid');
				return;
			}

			this.get('documentService').getPageMeta(this.get('document.id'), page.get('id')).then((pm) => {
				let block = {
					spaceId: this.get('folder.id'),
					contentType: page.get('contentType'),
					pageType: page.get('pageType'),
					title: blockTitle,
					body: page.get('body'),
					excerpt: blockExcerpt,
					rawBody: pm.get('rawBody'),
					config: pm.get('config'),
					externalSource: pm.get('externalSource')
				};

				let cb = this.get('onSavePageAsBlock');
				cb(block);

				this.set('blockTitle', '');
				this.set('blockExcerpt', '');
				$(titleElem).removeClass('is-invalid');
				$(excerptElem).removeClass('is-invalid');

				this.modalClose('#publish-page-modal-' + this.get('page.id'));

				let refresh = this.get('refresh');
				refresh();
			});
		},

		onShowCopyModal() {
			this.send('onSelectSpace', this.get('folder'));
			this.modalOpen('#copy-page-modal-' + this.get('page.id'), {show:true});
		},

		onShowMoveModal() {
			this.send('onSelectSpace', this.get('folder'));
			this.modalOpen('#move-page-modal-' + this.get('page.id'), {show:true});
		},

		onCopyPage() {
			let targetDoc = this.get('targetDoc');
			if (_.isNull(targetDoc)) return;

			this.modalClose('#copy-page-modal-' + this.get('page.id'));

			this.get('onCopyPage')(targetDoc.get('id'));
			this.get('refresh')();
		},

		onMovePage() {
			let targetDoc = this.get('targetDoc');
			if (_.isNull(targetDoc)) return;

			this.modalClose('#move-page-modal-' + this.get('page.id'));

			this.get('onMovePage')(targetDoc.get('id'));
			this.get('refresh')();
		},

		// Load up documents for selected space and select the first one.
		onSelectSpace(space) {
			this.set('targetSpace', space);

			this.get('documentService').getAllBySpace(space.get('id')).then((docs) => {
				this.set('targetDocs', docs);

				if (space.get('id') === this.get('folder.id')) {
					this.set('targetDoc', this.get('document'));
				} else {
					if (docs.length > 0) {
						this.set('targetDoc', docs[0]);
					}
				}
			});
		},

		onSelectDoc(doc) {
			this.set('targetDoc', doc);
		},

		// Page up -- above pages shunt down
		pageUp() {
			let state = this.get('state');

			if (state.upDisabled || this.get('document.protection') !== this.get('constants').ProtectionType.None) {
				return;
			}

			let pages = this.get('pages');
			let page = _.find(pages, function(i) { return i.get('page.id') === state.pageId; });
			if (!_.isUndefined(page)) page = page.get('page');

			let pendingChanges = tocUtil.moveUp(state, pages, page);
			if (pendingChanges.length > 0) {
				let cb = this.get('onPageSequenceChange');
				cb(state.pageId, pendingChanges);
			}
		},

		// Move down -- pages below shift up
		pageDown() {
			if (!this.get('canEdit')) return;

			let state = this.get('state');
			let pages = this.get('pages');
			let page = _.find(pages, function(i) { return i.get('page.id') === state.pageId; });
			if (!_.isUndefined(page)) page = page.get('page');

			let pendingChanges = tocUtil.moveDown(state, pages, page);
			if (pendingChanges.length > 0) {
				let cb = this.get('onPageSequenceChange');
				cb(state.pageId, pendingChanges);
			}
		},

		// Indent -- changes a page from H2 to H3, etc.
		pageIndent() {
			if (!this.get('canEdit')) return;

			let state = this.get('state');
			let pages = this.get('pages');
			let page = _.find(pages, function(i) { return i.get('page.id') === state.pageId; });
			if (!_.isUndefined(page)) page = page.get('page');

			let pendingChanges = tocUtil.indent(state, pages, page);
			if (pendingChanges.length > 0) {
				let cb = this.get('onPageLevelChange');
				cb(state.pageId, pendingChanges);
			}
		},

		// Outdent -- changes a page from H3 to H2, etc.
		pageOutdent() {
			if (!this.get('canEdit')) return;

			let state = this.get('state');
			let pages = this.get('pages');
			let page = _.find(pages, function(i) { return i.get('page.id') === state.pageId; });
			if (!_.isUndefined(page)) page = page.get('page');

			let pendingChanges = tocUtil.outdent(state, pages, page);
			if (pendingChanges.length > 0) {
				let cb = this.get('onPageLevelChange');
				cb(state.pageId, pendingChanges);
			}
		},

		onExpand() {
			this.set('expanded', !this.get('expanded'));
			this.get('onExpand')(this.get('page.id'), this.get('expanded'));
		},

		onCopyLink() {
			this.set('currentPageId', this.get('page.id'));
		}
	}
});
<commit_msg>Add http scheme for copied links<commit_after>// Copyright 2016 Documize Inc. <legal@documize.com>. All rights reserved.
//
// This software (Documize Community Edition) is licensed under
// GNU AGPL v3 http://www.gnu.org/licenses/agpl-3.0.en.html
//
// You can operate outside the AGPL restrictions by purchasing
// Documize Enterprise Edition and obtaining a commercial license
// by contacting <sales@documize.com>.
//
// https://documize.com

import $ from 'jquery';
import { computed, observer } from '@ember/object';
import { debounce } from '@ember/runloop';
import { inject as service } from '@ember/service';
import Notifier from '../../mixins/notifier';
import ModalMixin from '../../mixins/modal';
import tocUtil from '../../utils/toc';
import Component from '@ember/component';

export default Component.extend(Notifier, ModalMixin, {
	documentService: service('document'),
	searchService: service('search'),
	router: service(),
	appMeta: service(),
	deleteChildren: false,
	blockTitle: "",
	blockExcerpt: "",
	targetSpace: null,
	targetDocs: null,
	targetDoc: null,

	// eslint-disable-next-line ember/no-observers
	onKeywordChange: observer('docSearchFilter',  function() {
		debounce(this, this.searchDocs, 750);
	}),

	emptySearch: computed('docSearchResults', function() {
		return this.get('docSearchResults.length') === 0;
	}),
	canEdit: computed('permissions', 'document', 'pages', function() {
		let constants = this.get('constants');
		let permissions = this.get('permissions');
		let authenticated = this.get('session.authenticated');
		let notEmpty = this.get('pages.length') > 0;

		if (notEmpty && authenticated && permissions.get('documentEdit')
			&& (this.get('document.protection') !== constants.ProtectionType.Locked)) {
				return true;
		}

		// if (notEmpty && authenticated && permissions.get('documentEdit') && this.get('document.protection') === constants.ProtectionType.None) return true;
		// if (notEmpty && authenticated && permissions.get('documentApprove') && this.get('document.protection') === constants.ProtectionType.Review) return true;

		return false;
	}),

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

		this.state = {
			actionablePage: false,
			upDisabled: true,
			downDisabled: true,
			indentDisabled: true,
			outdentDisabled: true,
			pageId: ''
		};
	},

	didReceiveAttrs() {
		this._super(...arguments);
		this.modalInputFocus('#publish-page-modal-' + this.get('page.id'), '#block-title-' + this.get('page.id'));

		this.setState(this.get('page.id'));
	},

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

		let pageId = this.get('page.id');
		let url = window.location.protocol + '//' + this.get('appMeta.appHost') +
			this.get('router').generate('document.index', {queryParams: {currentPageId: pageId}});
		let self = this;

		let clip = new ClipboardJS('#page-copy-link-' + pageId, {
			text: function() {
				self.notifySuccess('Link copied to clipboard');
				return url;
			}
		});

		this.set('clip', clip);
	},

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

		let clip = this.get('clip');
		if (!_.isUndefined(clip)) clip.destroy();
	},

	// Controls what user can do with the toc enty for this page
	setState(pageId) {
		let toc = this.get('pages');
		let page = _.find(toc, function(i) { return i.get('page.id') === pageId; });
		let state = tocUtil.getState(toc, page.get('page'));

		if (!this.get('canEdit')) {
			state.actionablePage = false;
			state.upDisabled = state.downDisabled = state.indentDisabled = state.outdentDisabled = true;
		}

		this.set('state', state);
	},

	actions: {
		onShowSectionWizard(beforePage) {
			this.get('onShowSectionWizard')(beforePage);
		},

		onEdit() {
			let page = this.get('page');

			if (page.get('pageType') == this.get('constants').PageType.Tab) {
				this.get('router').transitionTo('document.section', page.get('id'));
			} else {
				let cb = this.get('onEdit');
				cb();
			}
		},

		onDeletePage() {
			let cb = this.get('onDeletePage');
			cb(this.get('deleteChildren'));

			this.modalClose('#delete-page-modal-' + this.get('page.id'));
		},

		onShowPublishModal() {
			this.modalOpen('#publish-page-modal-' + this.get('page.id'), {"show": true}, '#block-title-' + this.get('page.id'));
		},

		onSavePageAsBlock() {
			let page = this.get('page');
			let titleElem = '#block-title-' + page.get('id');
			let blockTitle = this.get('blockTitle');
			if (_.isEmpty(blockTitle)) {
				$(titleElem).addClass('is-invalid');
				return;
			}

			let excerptElem = '#block-desc-' + page.get('id');
			let blockExcerpt = this.get('blockExcerpt');
			blockExcerpt = blockExcerpt.replace(/\n/g, "");
			if (_.isEmpty(blockExcerpt)) {
				$(excerptElem).addClass('is-invalid');
				return;
			}

			this.get('documentService').getPageMeta(this.get('document.id'), page.get('id')).then((pm) => {
				let block = {
					spaceId: this.get('folder.id'),
					contentType: page.get('contentType'),
					pageType: page.get('pageType'),
					title: blockTitle,
					body: page.get('body'),
					excerpt: blockExcerpt,
					rawBody: pm.get('rawBody'),
					config: pm.get('config'),
					externalSource: pm.get('externalSource')
				};

				let cb = this.get('onSavePageAsBlock');
				cb(block);

				this.set('blockTitle', '');
				this.set('blockExcerpt', '');
				$(titleElem).removeClass('is-invalid');
				$(excerptElem).removeClass('is-invalid');

				this.modalClose('#publish-page-modal-' + this.get('page.id'));

				let refresh = this.get('refresh');
				refresh();
			});
		},

		onShowCopyModal() {
			this.send('onSelectSpace', this.get('folder'));
			this.modalOpen('#copy-page-modal-' + this.get('page.id'), {show:true});
		},

		onShowMoveModal() {
			this.send('onSelectSpace', this.get('folder'));
			this.modalOpen('#move-page-modal-' + this.get('page.id'), {show:true});
		},

		onCopyPage() {
			let targetDoc = this.get('targetDoc');
			if (_.isNull(targetDoc)) return;

			this.modalClose('#copy-page-modal-' + this.get('page.id'));

			this.get('onCopyPage')(targetDoc.get('id'));
			this.get('refresh')();
		},

		onMovePage() {
			let targetDoc = this.get('targetDoc');
			if (_.isNull(targetDoc)) return;

			this.modalClose('#move-page-modal-' + this.get('page.id'));

			this.get('onMovePage')(targetDoc.get('id'));
			this.get('refresh')();
		},

		// Load up documents for selected space and select the first one.
		onSelectSpace(space) {
			this.set('targetSpace', space);

			this.get('documentService').getAllBySpace(space.get('id')).then((docs) => {
				this.set('targetDocs', docs);

				if (space.get('id') === this.get('folder.id')) {
					this.set('targetDoc', this.get('document'));
				} else {
					if (docs.length > 0) {
						this.set('targetDoc', docs[0]);
					}
				}
			});
		},

		onSelectDoc(doc) {
			this.set('targetDoc', doc);
		},

		// Page up -- above pages shunt down
		pageUp() {
			let state = this.get('state');

			if (state.upDisabled || this.get('document.protection') !== this.get('constants').ProtectionType.None) {
				return;
			}

			let pages = this.get('pages');
			let page = _.find(pages, function(i) { return i.get('page.id') === state.pageId; });
			if (!_.isUndefined(page)) page = page.get('page');

			let pendingChanges = tocUtil.moveUp(state, pages, page);
			if (pendingChanges.length > 0) {
				let cb = this.get('onPageSequenceChange');
				cb(state.pageId, pendingChanges);
			}
		},

		// Move down -- pages below shift up
		pageDown() {
			if (!this.get('canEdit')) return;

			let state = this.get('state');
			let pages = this.get('pages');
			let page = _.find(pages, function(i) { return i.get('page.id') === state.pageId; });
			if (!_.isUndefined(page)) page = page.get('page');

			let pendingChanges = tocUtil.moveDown(state, pages, page);
			if (pendingChanges.length > 0) {
				let cb = this.get('onPageSequenceChange');
				cb(state.pageId, pendingChanges);
			}
		},

		// Indent -- changes a page from H2 to H3, etc.
		pageIndent() {
			if (!this.get('canEdit')) return;

			let state = this.get('state');
			let pages = this.get('pages');
			let page = _.find(pages, function(i) { return i.get('page.id') === state.pageId; });
			if (!_.isUndefined(page)) page = page.get('page');

			let pendingChanges = tocUtil.indent(state, pages, page);
			if (pendingChanges.length > 0) {
				let cb = this.get('onPageLevelChange');
				cb(state.pageId, pendingChanges);
			}
		},

		// Outdent -- changes a page from H3 to H2, etc.
		pageOutdent() {
			if (!this.get('canEdit')) return;

			let state = this.get('state');
			let pages = this.get('pages');
			let page = _.find(pages, function(i) { return i.get('page.id') === state.pageId; });
			if (!_.isUndefined(page)) page = page.get('page');

			let pendingChanges = tocUtil.outdent(state, pages, page);
			if (pendingChanges.length > 0) {
				let cb = this.get('onPageLevelChange');
				cb(state.pageId, pendingChanges);
			}
		},

		onExpand() {
			this.set('expanded', !this.get('expanded'));
			this.get('onExpand')(this.get('page.id'), this.get('expanded'));
		},

		onCopyLink() {
			this.set('currentPageId', this.get('page.id'));
		}
	}
});
<|endoftext|>


<commit_before>document.addEventListener('DOMContentLoaded', () => {
    fetchAndRenderGithubData();
    fetchAndRenderMediumData();
    registerServiceWorker();
    enablePushNotificationsSubscriptions();
});

function fetchAndRenderGithubData() {
    ifm('/github').then((response) => {
        const projects = $('.projects');
        response.forEach((project) => {
            const projectTemplate = $('template#project').innerHTML;
            const rendered = element(template(projectTemplate, project));
            projects.appendChild(rendered);
        });
    });
}

function fetchAndRenderMediumData() {
    ifm('/medium').then((response) => {
        const latestPostTemplate = $('template#latest-post').innerHTML;
        const rendered = element(template(latestPostTemplate, response));
        $('.latest-post-placeholder').replaceWith(rendered);
    });
}

function registerServiceWorker() {
    if ('serviceWorker' in navigator) {
        navigator.serviceWorker.register('sw.js')
            .then(() => console.log('Service worker registered.'))
            .catch((error) => console.error(error));
    }
}
<commit_msg>fetch and display upcoming talk in regular js files<commit_after>document.addEventListener('DOMContentLoaded', () => {
    fetchAndRenderGithubData();
    fetchAndRenderMediumData();
    fetchAndRenderTalkData();
    registerServiceWorker();
    enablePushNotificationsSubscriptions();
});

function fetchAndRenderGithubData() {
    ifm('/github').then((response) => {
        const projects = $('.projects');
        response.forEach((project) => {
            const projectTemplate = $('template#project').innerHTML;
            const rendered = element(template(projectTemplate, project));
            projects.appendChild(rendered);
        });
    });
}

function fetchAndRenderMediumData() {
    ifm('/medium').then((response) => {
        const latestPostTemplate = $('template#latest-post').innerHTML;
        const rendered = element(template(latestPostTemplate, response));
        $('.latest-post-placeholder').replaceWith(rendered);
    });
}

function fetchAndRenderTalkData() {
    mirror('/upcoming-talk').then((response) => {
        response = response || {};
        const upcomingTalkTemplate = $('template#upcoming-talk').innerHTML;
        const rendered = element(template(upcomingTalkTemplate, response));
        $('.upcoming-talk-placeholder').replaceWith(rendered);
    })
}

function registerServiceWorker() {
    if ('serviceWorker' in navigator) {
        navigator.serviceWorker.register('sw.js')
            .then(() => console.log('Service worker registered.'))
            .catch((error) => console.error(error));
    }
}
<|endoftext|>


<commit_before>/*
 * Spreed WebRTC.
 * Copyright (C) 2013-2014 struktur AG
 *
 * This file is part of Spreed WebRTC.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
define(['jquery', 'underscore', 'ua-parser'], function($, _, uaparser) {

	var timeout = 5000;
	var timeout_max = 20000;

	var Connector = function(version) {

		this.version = version;
		this.e = $({});
		this.error = false;
		this.connected = false;
		this.disabled = false;
		this.connecting = null;
		this.connecting_timeout = timeout;

		this.token = null;
		this.queue = [];

		this.roomid = null;

		var ua = uaparser();
		if (ua.os.name && /Spreed Desktop Caller/i.test(ua.ua)) {
			this.userAgent = ua.ua.match(/Spreed Desktop Caller\/([\d.]+)/i)[1] + " (" + ua.os.name + ")";
		} else if (ua.browser.name) {
			this.userAgent = ua.browser.name + " " + ua.browser.major;
		} else {
			this.userAgent = ua.ua;
		}

	};

	Connector.prototype.connect = function(url) {

		//console.log("connect", this.disabled, url);
		if (this.disabled) {
			return;
		}

		this.error = false;
		this.e.triggerHandler("connecting", [url]);
		this.url = url;
		if (this.token) {
			url += ("?t=" + this.token);
			//console.log("Reusing existing token", this.token);
		}
		var conn = this.conn = new WebSocket(url);
		conn.onopen = _.bind(this.onopen, this);
		conn.onerror = _.bind(this.onerror, this);
		conn.onclose = _.bind(this.onclose, this);
		conn.onmessage = _.bind(this.onmessage, this)

		this.connecting = window.setTimeout(_.bind(function() {
			console.warn("Connection timeout out after", this.connecting_timeout);
			if (this.connecting_timeout < timeout_max) {
				this.connecting_timeout += timeout;
			}
			this.e.triggerHandler("error");
			this.reconnect();
		}, this), this.connecting_timeout);

	};

	Connector.prototype.reconnect = function() {

		if (!this.url) {
			return;
		}

		this.close();

		var url = this.url;
		this.url = null;

		setTimeout(_.bind(function() {
			this.connect(url);
		}, this), 200);

	};

	Connector.prototype.close = function() {

		this.connected = false;
		if (this.conn) {
			var conn = this.conn;
			this.conn = null;
			if (!this.error) {
				conn.close();
			}
			conn.onopen = conn.onerror = conn.onclose = conn.onmessage = null;
		}

	};

	Connector.prototype.forgetAndReconnect = function() {

		this.token = null;
		if (this.conn && this.connected) {
			this.conn.close();
		}

	};

	Connector.prototype.room = function(roomid, cb) {

		var was_connected = this.connected;

		if (was_connected) {
			if (this.roomid === roomid) {
				return;
			}
			this.e.triggerHandler("closed", [{
				soft: true
			}]);
		}

		this.roomid = roomid;
		roomid = this.roomid ? this.roomid : "";

		if (cb) {
			cb();
		}

		this.send({
			Type: "Hello",
			Hello: {
				Version: this.version,
				Ua: this.userAgent,
				Id: roomid
			}
		});

		if (was_connected) {
			this.e.triggerHandler("open", [{
				soft: true
			}]);
		}

	};

	Connector.prototype.onopen = function(event) {

		window.clearTimeout(this.connecting);
		this.connecting_timeout = timeout;

		//console.log("onopen", event);
		console.info("Connector on connection open.");
		this.room(this.roomid, _.bind(function() {
			this.connected = true;
		}, this));
		this.e.triggerHandler("open", [event]);

		// Send out stuff which was previously queued.
		var data;
		while (this.queue.length > 0 && this.connected) {
			data = this.queue.shift();
			this.send(data);
		}

	};

	Connector.prototype.onerror = function(event) {

		window.clearTimeout(this.connecting);
		this.connecting_timeout = timeout;

		//console.log("onerror", event);
		console.warn("Connector on connection error.");
		this.error = true;
		this.close();
		this.e.triggerHandler("error", [event]);

	};

	Connector.prototype.onclose = function(event) {

		window.clearTimeout(this.connecting);
		this.connecting_timeout = timeout;

		//console.log("onclose", event);
		console.info("Connector on connection close.", event, this.error);
		this.close();
		if (!this.error) {
			this.e.triggerHandler("close", [event]);
		}
		this.e.triggerHandler("closed", [event]);

	};

	Connector.prototype.onmessage = function(event) {

		//console.log("onmessage", event);
		var msg = JSON.parse(event.data);
		this.e.triggerHandler("received", [msg]);

	};

	Connector.prototype.send = function(data, noqueue) {

		if (!this.connected) {
			if (!noqueue) {
				this.queue.push(data);
				console.warn("Queuing sending data because of not connected.", data);
				return;
			}
		}
		this.conn.send(JSON.stringify(data));

	};

	Connector.prototype.ready = function(func) {
		/* Call a function whenever the Connection is ready */
		this.e.on("open", func);
		if (this.connected) {
			func();
		}
	};

	return Connector;

});
<commit_msg>Fixed event parameters.<commit_after>/*
 * Spreed WebRTC.
 * Copyright (C) 2013-2014 struktur AG
 *
 * This file is part of Spreed WebRTC.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
define(['jquery', 'underscore', 'ua-parser'], function($, _, uaparser) {

	var timeout = 5000;
	var timeout_max = 20000;

	var Connector = function(version) {

		this.version = version;
		this.e = $({});
		this.error = false;
		this.connected = false;
		this.disabled = false;
		this.connecting = null;
		this.connecting_timeout = timeout;

		this.token = null;
		this.queue = [];

		this.roomid = null;

		var ua = uaparser();
		if (ua.os.name && /Spreed Desktop Caller/i.test(ua.ua)) {
			this.userAgent = ua.ua.match(/Spreed Desktop Caller\/([\d.]+)/i)[1] + " (" + ua.os.name + ")";
		} else if (ua.browser.name) {
			this.userAgent = ua.browser.name + " " + ua.browser.major;
		} else {
			this.userAgent = ua.ua;
		}

	};

	Connector.prototype.connect = function(url) {

		//console.log("connect", this.disabled, url);
		if (this.disabled) {
			return;
		}

		this.error = false;
		this.e.triggerHandler("connecting", [url]);
		this.url = url;
		if (this.token) {
			url += ("?t=" + this.token);
			//console.log("Reusing existing token", this.token);
		}
		var conn = this.conn = new WebSocket(url);
		conn.onopen = _.bind(this.onopen, this);
		conn.onerror = _.bind(this.onerror, this);
		conn.onclose = _.bind(this.onclose, this);
		conn.onmessage = _.bind(this.onmessage, this)

		this.connecting = window.setTimeout(_.bind(function() {
			console.warn("Connection timeout out after", this.connecting_timeout);
			if (this.connecting_timeout < timeout_max) {
				this.connecting_timeout += timeout;
			}
			this.e.triggerHandler("error");
			this.reconnect();
		}, this), this.connecting_timeout);

	};

	Connector.prototype.reconnect = function() {

		if (!this.url) {
			return;
		}

		this.close();

		var url = this.url;
		this.url = null;

		setTimeout(_.bind(function() {
			this.connect(url);
		}, this), 200);

	};

	Connector.prototype.close = function() {

		this.connected = false;
		if (this.conn) {
			var conn = this.conn;
			this.conn = null;
			if (!this.error) {
				conn.close();
			}
			conn.onopen = conn.onerror = conn.onclose = conn.onmessage = null;
		}

	};

	Connector.prototype.forgetAndReconnect = function() {

		this.token = null;
		if (this.conn && this.connected) {
			this.conn.close();
		}

	};

	Connector.prototype.room = function(roomid, cb) {

		var was_connected = this.connected;

		if (was_connected) {
			if (this.roomid === roomid) {
				return;
			}
			this.e.triggerHandler("closed", [{
				soft: true
			}]);
		}

		this.roomid = roomid;
		roomid = this.roomid ? this.roomid : "";

		if (cb) {
			cb();
		}

		this.send({
			Type: "Hello",
			Hello: {
				Version: this.version,
				Ua: this.userAgent,
				Id: roomid
			}
		});

		if (was_connected) {
			this.e.triggerHandler("open", [{
				soft: true
			}]);
		}

	};

	Connector.prototype.onopen = function(event) {

		window.clearTimeout(this.connecting);
		this.connecting_timeout = timeout;

		//console.log("onopen", event);
		console.info("Connector on connection open.");
		this.room(this.roomid, _.bind(function() {
			this.connected = true;
		}, this));
		this.e.triggerHandler("open", [null, event]);

		// Send out stuff which was previously queued.
		var data;
		while (this.queue.length > 0 && this.connected) {
			data = this.queue.shift();
			this.send(data);
		}

	};

	Connector.prototype.onerror = function(event) {

		window.clearTimeout(this.connecting);
		this.connecting_timeout = timeout;

		//console.log("onerror", event);
		console.warn("Connector on connection error.");
		this.error = true;
		this.close();
		this.e.triggerHandler("error", [null, event]);

	};

	Connector.prototype.onclose = function(event) {

		window.clearTimeout(this.connecting);
		this.connecting_timeout = timeout;

		//console.log("onclose", event);
		console.info("Connector on connection close.", event, this.error);
		this.close();
		if (!this.error) {
			this.e.triggerHandler("close", [null, event]);
		}
		this.e.triggerHandler("closed", [null, event]);

	};

	Connector.prototype.onmessage = function(event) {

		//console.log("onmessage", event);
		var msg = JSON.parse(event.data);
		this.e.triggerHandler("received", [msg]);

	};

	Connector.prototype.send = function(data, noqueue) {

		if (!this.connected) {
			if (!noqueue) {
				this.queue.push(data);
				console.warn("Queuing sending data because of not connected.", data);
				return;
			}
		}
		this.conn.send(JSON.stringify(data));

	};

	Connector.prototype.ready = function(func) {
		/* Call a function whenever the Connection is ready */
		this.e.on("open", func);
		if (this.connected) {
			func();
		}
	};

	return Connector;

});
<|endoftext|>


<commit_before>var path = require('path');
var paths = require('./paths');

exports.base = function() {
  return {
    filename: '',
    filenameRelative: '',
    sourceMap: true,
    sourceRoot: '',
    moduleRoot: path.resolve('src').replace(/\\/g, '/'),
    moduleIds: false,
    comments: false,
    compact: false,
    code: true,
    presets: [ 'es2015-loose', 'stage-1'],
    plugins: [
      'syntax-flow',
      'transform-decorators-legacy',
      'transform-flow-strip-types',
      'transform-decorators'
    ]
  };
};

exports.commonjs = function() {
  var options = exports.base();
  options.plugins.push('transform-es2015-modules-commonjs');
  return options;
};

exports.amd = function() {
  var options = exports.base();
  options.plugins.push('transform-es2015-modules-amd');
  return options;
};

exports.system = function() {
  var options = exports.base();
  options.plugins.push('transform-es2015-modules-systemjs');
  return options;
};

exports.es2015 = function() {
  var options = exports.base();
  options.presets = ['stage-1'];
  return options;
};
<commit_msg>chore(depend): remove babel config used for testing<commit_after>var path = require('path');
var paths = require('./paths');

exports.base = function() {
  return {
    filename: '',
    filenameRelative: '',
    sourceMap: true,
    sourceRoot: '',
    moduleRoot: path.resolve('src').replace(/\\/g, '/'),
    moduleIds: false,
    comments: false,
    compact: false,
    code: true,
    presets: [ 'es2015-loose', 'stage-1'],
    plugins: [
      'syntax-flow',
      'transform-decorators-legacy',
      'transform-flow-strip-types'
    ]
  };
};

exports.commonjs = function() {
  var options = exports.base();
  options.plugins.push('transform-es2015-modules-commonjs');
  return options;
};

exports.amd = function() {
  var options = exports.base();
  options.plugins.push('transform-es2015-modules-amd');
  return options;
};

exports.system = function() {
  var options = exports.base();
  options.plugins.push('transform-es2015-modules-systemjs');
  return options;
};

exports.es2015 = function() {
  var options = exports.base();
  options.presets = ['stage-1'];
  return options;
};
<|endoftext|>


<commit_before>module.exports = function (grunt) {
  'use strict';

  function launcher (platform, browser, version) {
    var device = '';

    if (browser === 'iphone') {
      device = 'iPhone';
    }

    if (browser === 'android') {
      device = 'Android';
    }

    return {
      base: 'SauceLabs',
      platform: platform,
      browserName: browser,
      version: version && version.toString() || ''
    };
  }

  var browsers = grunt.option('browsers');
  var sauce = grunt.option('sauce');
  var customLaunchers = {
      chrome_37: launcher('Windows 8.1', 'chrome', 37),
      chrome_36: launcher('Windows 8.1', 'chrome', 36),

      firefox_32: launcher('Windows 8.1', 'firefox', 32),
      firefox_31: launcher('Windows 8.1', 'firefox', 31),

      safari_7: launcher('OS X 10.9', 'safari', 7),
      safari_6: launcher('OS X 10.8', 'safari', 6),

      ios_safari_7_1: launcher('OS X 10.9', 'iphone', 7.1),
      ios_safari_7: launcher('OS X 10.9', 'iphone', 7),
      ios_safari_6_1: launcher('OS X 10.8', 'iphone', 6.1),
      ios_safari_6: launcher('OS X 10.8', 'iphone', 6),

      ie_11: launcher('Windows 8.1', 'internet explorer', 11),
      ie_10: launcher('Windows 8', 'internet explorer', 10),
      ie_9: launcher('Windows 7', 'internet explorer', 9)
    };

  if (sauce) {
    browsers = Object.keys(customLaunchers);
  } else if (browsers) {
    browsers = browsers.split(',');
  } else {
    browsers = ['Chrome'];
  }

  return {
    options: {
      browsers: browsers,

      customLaunchers: customLaunchers,

      files: [
        { pattern: '.tmp/run-unit-tests.js', included: true }
      ],

      frameworks: [
        'mocha',
        'chai'
      ],

      hostname: grunt.option('host') || 'localhost',

      plugins: [
        'karma-chai',
        'karma-chrome-launcher',
        'karma-firefox-launcher',
        'karma-mocha',
        'karma-phantomjs-launcher',
        'karma-sauce-launcher'
      ],

      port: grunt.option('port') || '9876',

      reporters: [
        'progress',
        'saucelabs'
      ],

      saucelabs: {
        testName: 'SkateJS Unit Tests'
      },

      singleRun: !grunt.option('keep-alive'),
    },

    unit: {}
  };
};
<commit_msg>Better custom launcher keys.<commit_after>module.exports = function (grunt) {
  'use strict';

  function launcher (platform, browser, version) {
    var device = '';

    if (browser === 'iphone') {
      device = 'iPhone';
    }

    if (browser === 'android') {
      device = 'Android';
    }

    return {
      base: 'SauceLabs',
      platform: platform,
      browserName: browser,
      version: version && version.toString() || ''
    };
  }

  var browsers = grunt.option('browsers');
  var sauce = grunt.option('sauce');
  var customLaunchers = {
      'Chrome 37': launcher('Windows 8.1', 'chrome', 37),
      'Chrome 36': launcher('Windows 8.1', 'chrome', 36),

      'Firefox 32': launcher('Windows 8.1', 'firefox', 32),
      'Firefox 31': launcher('Windows 8.1', 'firefox', 31),

      'Safari 7': launcher('OS X 10.9', 'safari', 7),
      'Safari 6': launcher('OS X 10.8', 'safari', 6),

      'iOS Safari 7.1': launcher('OS X 10.9', 'iphone', 7.1),
      'iOS Safari 7': launcher('OS X 10.9', 'iphone', 7),
      'iOS Safari 6.1': launcher('OS X 10.8', 'iphone', 6.1),
      'iOS Safari 6': launcher('OS X 10.8', 'iphone', 6),

      'IE 11': launcher('Windows 8.1', 'internet explorer', 11),
      'IE 10': launcher('Windows 8', 'internet explorer', 10),
      'IE 9': launcher('Windows 7', 'internet explorer', 9)
    };

  if (sauce) {
    browsers = Object.keys(customLaunchers);
  } else if (browsers) {
    browsers = browsers.split(',');
  } else {
    browsers = ['Chrome'];
  }

  return {
    options: {
      browsers: browsers,

      customLaunchers: customLaunchers,

      files: [
        { pattern: '.tmp/run-unit-tests.js', included: true }
      ],

      frameworks: [
        'mocha',
        'chai'
      ],

      hostname: grunt.option('host') || 'localhost',

      plugins: [
        'karma-chai',
        'karma-chrome-launcher',
        'karma-firefox-launcher',
        'karma-mocha',
        'karma-phantomjs-launcher',
        'karma-sauce-launcher'
      ],

      port: grunt.option('port') || '9876',

      reporters: [
        'progress',
        'saucelabs'
      ],

      saucelabs: {
        testName: 'SkateJS Unit Tests'
      },

      singleRun: !grunt.option('keep-alive'),
    },

    unit: {}
  };
};
<|endoftext|>


<commit_before>(function() {
    "use strict";
    if ("function" !== Date.prototype.format) {
        Date.locale = {};
        Date.locale.en = {
            months: {
                longs: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ],
                shorts: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]
            },
            days: {
                longs: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ],
                shorts: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ]
            },
            suffixes: [ "th", "st", "nd", "rd" ]
        };
        Date.locale.use = Date.locale.use || "en";
        Date.prototype.format = function(pattern) {
            var leadingZeros = function(string, length) {
                length = typeof length === "undefined" ? 2 : length;
                string = string.toString();
                while (string.length < length) {
                    string = "0" + string;
                }
                return string;
            };
            var charValues = {
                Y: function() {
                    return this.getFullYear();
                },
                y: function() {
                    return this.getFullYear() % 100;
                },
                L: function() {
                    var year = this.getFullYear();
                    if (year % 4 === 0 && year % 100 !== 0 || year % 400 === 0) {
                        return 1;
                    }
                    return 0;
                },
                o: function() {
                    return Math.floor(this.getWeekNumber() / 100);
                },
                n: function() {
                    return this.getMonth() + 1;
                },
                m: function() {
                    return leadingZeros(this.format("n"));
                },
                M: function() {
                    return Date.locale[Date.locale.use].months.shorts[this.getMonth()];
                },
                F: function() {
                    return Date.locale[Date.locale.use].months.longs[this.getMonth()];
                },
                t: function() {
                    return new Date(this.getFullYear(), this.getMonth() + 1, 0).getDate();
                },
                W: function() {
                    return this.getWeekNumber() % 100;
                },
                d: function() {
                    return leadingZeros(this.getDate());
                },
                j: function() {
                    return this.getDate();
                },
                D: function() {
                    return Date.locale[Date.locale.use].days.shorts[this.getDay()];
                },
                l: function() {
                    return Date.locale[Date.locale.use].days.longs[this.getDay()];
                },
                N: function() {
                    var dow = this.getDay();
                    return 0 === dow ? 7 : dow;
                },
                S: function() {
                    var suffix = Date.locale[Date.locale.use].suffixes[this.getDate()];
                    return typeof suffix === "undefined" ? Date.locale[Date.locale.use].suffixes[0] : suffix;
                },
                w: function() {
                    return this.getDay();
                },
                z: function() {
                    var ref = new Date(this.getFullYear(), 0, 0);
                    var elapsed = this.getTime() - ref.getTime();
                    return Math.floor(elapsed / 864e5) - 1;
                },
                a: function() {
                    return this.getHours() < 12 ? "am" : "pm";
                },
                A: function() {
                    return this.format("a").toUpperCase();
                },
                B: function() {
                    return Math.floor((this.getUTCSeconds() + this.getUTCMinutes() * 60 + this.getUTCHours() * 3600) / 86.4);
                },
                g: function() {
                    return this.getHours() % 12;
                },
                G: function() {
                    return this.getHours();
                },
                h: function() {
                    return leadingZeros(this.format("g"));
                },
                H: function() {
                    return leadingZeros(this.getHours());
                },
                i: function() {
                    return leadingZeros(this.getMinutes());
                },
                s: function() {
                    return leadingZeros(this.getSeconds());
                },
                u: function() {
                    return leadingZeros(this.getMilliseconds() * 1e3, 6);
                },
                e: function() {
                    return new Date().toString().match(/\((.+)\)/)[1];
                },
                I: function() {
                    var january = new Date(this.getFullYear(), 0);
                    var july = new Date(this.getFullYear(), 6);
                    var maxOffset = Math.max(january.getTimezoneOffset(), july.getTimezoneOffset());
                    return this.getTimezoneOffset() !== maxOffset ? "1" : "0";
                },
                O: function() {
                    return this.format("P").replace(":", "");
                },
                P: function() {
                    var offset = this.getTimezoneOffset();
                    var sign = offset < 0 ? "+" : "-";
                    offset = Math.abs(offset);
                    return sign + leadingZeros(Math.floor(offset / 60)) + ":" + leadingZeros(offset % 60);
                },
                T: function() {
                    return this.format("e");
                },
                Z: function() {
                    return -60 * this.getTimezoneOffset();
                },
                c: function() {
                    return this.format("Y-m-d\\TH:i:sP");
                },
                r: function() {
                    return this.format("D, j M Y H:i:s O");
                },
                U: function() {
                    return Math.floor(this.getTime() / 1e3);
                }
            };
            var that = this;
            return pattern.replace(/\\?(.)/g, function(character) {
                return charValues[character] ? charValues[character].call(that) : character.replace(/^\\(.+)/, "$1");
            });
        };
    }
})();

(function() {
    "use strict";
    if ("function" !== Date.prototype.getWeekNumber) {
        Date.prototype.getWeekNumber = function() {
            var firstDay = new Date(this.getFullYear(), 0, 1);
            var dayOfYear = Math.floor((this.valueOf() - firstDay.valueOf()) / 864e5 + 1);
            var result = Math.floor((dayOfYear - this.getDay() + 10) / 7);
            if (result) {
                return this.getFullYear() * 100 + result;
            }
            return new Date(this.getFullYear(), 0, 0).getWeekNumber();
        };
    }
})();

(function() {
    "use strict";
    if ("function" !== Date.prototype.isValid) {
        Date.prototype.isValid = function() {
            return this.getTime() === this.getTime();
        };
    }
})();<commit_msg>Fix "-00:00" with UTC local<commit_after>(function() {
    "use strict";
    if ("function" !== Date.prototype.format) {
        Date.locale = {};
        Date.locale.en = {
            months: {
                longs: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ],
                shorts: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]
            },
            days: {
                longs: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ],
                shorts: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ]
            },
            suffixes: [ "th", "st", "nd", "rd" ]
        };
        Date.locale.use = Date.locale.use || "en";
        Date.prototype.format = function(pattern) {
            var leadingZeros = function(string, length) {
                length = typeof length === "undefined" ? 2 : length;
                string = string.toString();
                while (string.length < length) {
                    string = "0" + string;
                }
                return string;
            };
            var charValues = {
                Y: function() {
                    return this.getFullYear();
                },
                y: function() {
                    return this.getFullYear() % 100;
                },
                L: function() {
                    var year = this.getFullYear();
                    if (year % 4 === 0 && year % 100 !== 0 || year % 400 === 0) {
                        return 1;
                    }
                    return 0;
                },
                o: function() {
                    return Math.floor(this.getWeekNumber() / 100);
                },
                n: function() {
                    return this.getMonth() + 1;
                },
                m: function() {
                    return leadingZeros(this.format("n"));
                },
                M: function() {
                    return Date.locale[Date.locale.use].months.shorts[this.getMonth()];
                },
                F: function() {
                    return Date.locale[Date.locale.use].months.longs[this.getMonth()];
                },
                t: function() {
                    return new Date(this.getFullYear(), this.getMonth() + 1, 0).getDate();
                },
                W: function() {
                    return this.getWeekNumber() % 100;
                },
                d: function() {
                    return leadingZeros(this.getDate());
                },
                j: function() {
                    return this.getDate();
                },
                D: function() {
                    return Date.locale[Date.locale.use].days.shorts[this.getDay()];
                },
                l: function() {
                    return Date.locale[Date.locale.use].days.longs[this.getDay()];
                },
                N: function() {
                    var dow = this.getDay();
                    return 0 === dow ? 7 : dow;
                },
                S: function() {
                    var suffix = Date.locale[Date.locale.use].suffixes[this.getDate()];
                    return typeof suffix === "undefined" ? Date.locale[Date.locale.use].suffixes[0] : suffix;
                },
                w: function() {
                    return this.getDay();
                },
                z: function() {
                    var ref = new Date(this.getFullYear(), 0, 0);
                    var elapsed = this.getTime() - ref.getTime();
                    return Math.floor(elapsed / 864e5) - 1;
                },
                a: function() {
                    return this.getHours() < 12 ? "am" : "pm";
                },
                A: function() {
                    return this.format("a").toUpperCase();
                },
                B: function() {
                    return Math.floor((this.getUTCSeconds() + this.getUTCMinutes() * 60 + this.getUTCHours() * 3600) / 86.4);
                },
                g: function() {
                    return this.getHours() % 12;
                },
                G: function() {
                    return this.getHours();
                },
                h: function() {
                    return leadingZeros(this.format("g"));
                },
                H: function() {
                    return leadingZeros(this.getHours());
                },
                i: function() {
                    return leadingZeros(this.getMinutes());
                },
                s: function() {
                    return leadingZeros(this.getSeconds());
                },
                u: function() {
                    return leadingZeros(this.getMilliseconds() * 1e3, 6);
                },
                e: function() {
                    return new Date().toString().match(/\((.+)\)/)[1];
                },
                I: function() {
                    var january = new Date(this.getFullYear(), 0);
                    var july = new Date(this.getFullYear(), 6);
                    var maxOffset = Math.max(january.getTimezoneOffset(), july.getTimezoneOffset());
                    return this.getTimezoneOffset() !== maxOffset ? "1" : "0";
                },
                O: function() {
                    return this.format("P").replace(":", "");
                },
                P: function() {
                    var offset = this.getTimezoneOffset();
                    var sign = offset <= 0 ? "+" : "-";
                    offset = Math.abs(offset);
                    return sign + leadingZeros(Math.floor(offset / 60)) + ":" + leadingZeros(offset % 60);
                },
                T: function() {
                    return this.format("e");
                },
                Z: function() {
                    return -60 * this.getTimezoneOffset();
                },
                c: function() {
                    return this.format("Y-m-d\\TH:i:sP");
                },
                r: function() {
                    return this.format("D, j M Y H:i:s O");
                },
                U: function() {
                    return Math.floor(this.getTime() / 1e3);
                }
            };
            var that = this;
            return pattern.replace(/\\?(.)/g, function(character) {
                return charValues[character] ? charValues[character].call(that) : character.replace(/^\\(.+)/, "$1");
            });
        };
    }
})();

(function() {
    "use strict";
    if ("function" !== Date.prototype.getWeekNumber) {
        Date.prototype.getWeekNumber = function() {
            var firstDay = new Date(this.getFullYear(), 0, 1);
            var dayOfYear = Math.floor((this.valueOf() - firstDay.valueOf()) / 864e5 + 1);
            var result = Math.floor((dayOfYear - this.getDay() + 10) / 7);
            if (result) {
                return this.getFullYear() * 100 + result;
            }
            return new Date(this.getFullYear(), 0, 0).getWeekNumber();
        };
    }
})();

(function() {
    "use strict";
    if ("function" !== Date.prototype.isValid) {
        Date.prototype.isValid = function() {
            return this.getTime() === this.getTime();
        };
    }
})();
<|endoftext|>


<commit_before>'use strict';

// MODULES //

var debug = require( 'debug' )( 'build-docs:main' );
var resolve = require( 'path' ).resolve;
var isFunction = require( '@stdlib/assert/is-function' );
var copy = require( '@stdlib/utils/copy' );
var cwd = require( '@stdlib/utils/cwd' );
var menu = require( './../../package-menu' );
var buildPkgs = require( './../../build-packages' );
var defaults = require( './defaults.json' );
var head = require( './head.js' );
var scripts = require( './scripts.js' );

// MAIN //

/**
* Builds documentation.
*
* @param {Callback} clbk - callback
* @throws {TypeError} callback argument must be a function
*
* @example
* build( clbk );
*
* function clbk( error ) {
*     if ( error ) {
*         throw error;
*     }
* }
*/
function build( clbk ) {
	var opts;
	if ( !isFunction( clbk ) ) {
		throw new TypeError( 'invalid input argument. Callback argument must be a function. Value: `'+clbk+'`.' );
	}
	opts = copy( defaults );
	menu( opts, onMenu );

	/**
	* Callback invoked upon creating a menu fragment.
	*
	* @private
	* @param {(Error|null)} error - error object
	* @param {Object} menu - menu
	* @returns {void}
	*/
	function onMenu( error, menu ) {
		var bopts;
		var dest;
		if ( error ) {
			debug( 'Encountered an error when generating a package menu: %s', error.message );
			return clbk( error );
		}
		dest = resolve( cwd(), opts.out );
		bopts = {
			'head': head+'\n<style>'+menu.css+'</style>\n<style>\n.slideout-menu {\n\tfont-family: "Lato", "Helvetica Neue";\n\tfont-weight: 200;\n}\n</style>',
			'prepend': menu.html,
			'append': scripts.join( '\n' ),
			'mount': opts.mount
		};

		buildPkgs( dest, bopts, onBuild );
	} // end FUNCTION onMenu()

	/**
	* Callback invoked upon building packages.
	*
	* @private
	* @param {(Error|null)} error - error object
	* @returns {void}
	*/
	function onBuild( error ) {
		if ( error ) {
			debug( 'Encountered an error when building packages: %s', error.message );
			return clbk( error );
		}
		clbk();
	} // end FUNCTION onBuild()
} // end FUNCTION build()

// EXPORTS //

module.exports = build;
<commit_msg>Copy options<commit_after>'use strict';

// MODULES //

var debug = require( 'debug' )( 'build-docs:main' );
var resolve = require( 'path' ).resolve;
var isFunction = require( '@stdlib/assert/is-function' );
var copy = require( '@stdlib/utils/copy' );
var cwd = require( '@stdlib/utils/cwd' );
var menu = require( './../../package-menu' );
var buildPkgs = require( './../../build-packages' );
var defaults = require( './defaults.json' );
var head = require( './head.js' );
var scripts = require( './scripts.js' );

// MAIN //

/**
* Builds documentation.
*
* @param {Callback} clbk - callback
* @throws {TypeError} callback argument must be a function
*
* @example
* build( clbk );
*
* function clbk( error ) {
*     if ( error ) {
*         throw error;
*     }
* }
*/
function build( clbk ) {
	var mopts;
	var opts;
	if ( !isFunction( clbk ) ) {
		throw new TypeError( 'invalid input argument. Callback argument must be a function. Value: `'+clbk+'`.' );
	}
	opts = copy( defaults );
	mopts = {
		'title': opts.title,
		'url': opts.url,
		'mount': opts.mount
	};
	menu( mopts, onMenu );

	/**
	* Callback invoked upon creating a menu fragment.
	*
	* @private
	* @param {(Error|null)} error - error object
	* @param {Object} menu - menu
	* @returns {void}
	*/
	function onMenu( error, menu ) {
		var bopts;
		var dest;
		if ( error ) {
			debug( 'Encountered an error when generating a package menu: %s', error.message );
			return clbk( error );
		}
		dest = resolve( cwd(), opts.out );
		bopts = {
			'head': head+'\n<style>'+menu.css+'</style>\n<style>\n.slideout-menu {\n\tfont-family: "Lato", "Helvetica Neue";\n\tfont-weight: 200;\n}\n</style>',
			'prepend': menu.html,
			'append': scripts.join( '\n' ),
			'mount': opts.mount
		};

		buildPkgs( dest, bopts, onBuild );
	} // end FUNCTION onMenu()

	/**
	* Callback invoked upon building packages.
	*
	* @private
	* @param {(Error|null)} error - error object
	* @returns {void}
	*/
	function onBuild( error ) {
		if ( error ) {
			debug( 'Encountered an error when building packages: %s', error.message );
			return clbk( error );
		}
		clbk();
	} // end FUNCTION onBuild()
} // end FUNCTION build()

// EXPORTS //

module.exports = build;
<|endoftext|>


<commit_before>/*
 FrostNova Javascript Library v0.3.2
 http://qslee.com/

 Copyright 2011, Qiu-Shi Lee
 Code licensed under the MIT License:
 https://github.com/qiushilee/frostnova/blob/master/LICENSE.txt
*/
var nova=function(){return nova.init.apply(nova,arguments)};nova.init=function(){return new nova.domChain.init(selector)};nova.WIN=window;nova.version="0.3.2";nova.bind=function(a,b){var d=Array.prototype.slice,c=d.apply(arguments,[2]);return function(){return a.apply(b||{},c.concat(d.apply(arguments)))}};nova.isArray=function(){};nova.isString=function(){};nova.isNubmer=function(){};nova.load={};
nova.load=function(a,b){var d=document.createElement("script");d.src=a;d.onloadDone=false;d.onload=function(){d.onloadDone=true;b()};d.onreadystatechange=function(){if(d.readyState==="loaded"||d.readyState==="complete"&&!d.onloadDone){d.onloadDone=true;b()}};document.body.appendChild(d)};nova.ajax={};nova.ajax.XMLHttpFactories=[function(){return new XMLHttpRequest},function(){return new ActiveXObject("Msxml2.XMLHTTP")},function(){return new ActiveXObject("Msxml3.XMLHTTP")},function(){return new ActiveXObject("Microsoft.XMLHTTP")}];
nova.ajax.createXMLHTTPObject=function(){for(var a=false,b=0;b<nova.ajax.XMLHttpFactories.length;b++){try{a=nova.ajax.XMLHttpFactories[b]()}catch(d){continue}break}return a};
nova.ajax.sendRequest=function(a,b,d){var c=nova.ajax.createXMLHTTPObject();if(c){c.open(d?"POST":"GET",a,true);c.setRequestHeader("User-Agent","XMLHTTP/1.0");d&&c.setRequestHeader("Content-type","application/x-www-form-urlencoded");c.onreadystatechange=function(){if(c.readyState==4)c.status!=200&&c.status!=304||b(c)};c.readyState!=4&&c.send(d)}};nova.ajax.get=function(a,b){return nova.ajax.sendRequest(a,b,"GET")};nova.ajax.post=function(a,b){return nova.ajax.sendRequest(a,b,"POST")};nova.dom={};
nova.dom.hasClass=function(){};nova.dom.addClass=function(a,b){if(!nova.dom.hasClass(a,b))a.className===""?a.className=b:a.className+=" "+b};nova.dom.removeClass=function(a,b){a.className=a.className.replace(b,"")};nova.dom.getStyle=function(a,b,d){if(a.currentStyle)return a.currentStyle[d];else if(nova.WIN.getComputedStyle)return document.defaultView.getComputedStyle(a,null).getPropertyValue(b)};
nova.dom.getWidth=function(a){var b,d;b=parseInt(nova.dom.getStyle(a,"margin-left","marginLeft"),10);d=parseInt(nova.dom.getStyle(a,"margin-right","marginRight"),10);return a.offsetWidth+b+d};nova.dom.setCSS=function(a,b){var d=function(e,f){for(var g=0,h=a.length;g<h;g++)a[g].style[e]=f},c;for(c in b)b.hasOwnProperty(c)&&d(c,b[c])};
(function(){var a={byID:function(c,e){if(c===null)return[];return[c.getElementById(e)]},byNodeName:function(c,e){if(c===null)return[];var f,g,h=[],i=c.getElementsByTagName(e);f=0;for(g=i.length;f<g;f++)h.push(i[f]);return h},byClassName:function(c,e){if(c===null)return[];var f,g,h=[],i=c.getElementsByTagName("*");f=0;for(g=i.length;f<g;f++){var k=i[f];k.className.match("\\b"+e+"\\b")&&h.push(k)}return h}},b={id:function(c,e){e=e.split("#")[1];return a.byID(c,e)},tag:function(c,e){return a.byNodeName(c,
e)},"class":function(c,e){e=e.split(".")[1];return a.byClassName(c,e)}},d=function(c){this.selector=c;this.tokens=[];this.tokenize()};d.prototype.tokenize=function(){this.tokens.push(this.selector[0]==="#"?"id":this.selector[0]==="."?"class":"tag");return this.tokens};nova.dom.selector=function(c,e){var f;f=e===undefined?document:e;if(f.querySelectorAll)f=f.querySelectorAll(c);else{var g=(new d(c)).tokens;f=b[g](f,c)}return f};nova.domChain={find:function(c){this.selector=c}}})();nova.ua={};
nova.ua=function(){var a,b=nova.WIN.navigator.userAgent,d,c;d=function(e){a=0;return parseFloat(e.replace(/\./g,function(){return a++==1?"":"."}))};c={ie:0,webkit:0,gecko:0,opera:0,mobile:null,os:null};if(/windows|win32/i.test(b))c.os="win";else if(/macintosh/i.test(b))c.os="mac";else if(/rhino/i.test(b))c.os="rhino";if(/KHTML/.test(b))c.webkit=1;m=b.match(/AppleWebKit\/([^\s]*)/);if(!c.webkit)if((m=b.match(/Opera[\s\/]([^\s]*)/))&&m[1]){c.opera=d(m[1]);if(m=b.match(/Opera Mini[^;]*/))c.mobile=m[0]}else if((m=
b.match(/MSIE\s([^;]*)/))&&m[1])c.ie=d(m[1]);else if(m=b.match(/Gecko\/([^\s]*)/)){c.gecko=1;if((m=b.match(/rv:([^\s\)]*)/))&&m[1])c.gecko=d(m[1])}return c}();(function(){var a=["ua-"+nova.ua.os,"ua-jsenable"];if(nova.ua.ie!==0)a.push("ua-ie"+nova.ua.ie);else if(nova.ua.webkit!==0)a.push("ua-webkit"+nova.ua.webkit);else if(nova.ua.gecko!==0)a.push("ua-gecko"+nova.ua.gecko,"ua-fx");else nova.ua.opera!==0&&a.push("ua-opera"+nova.ua.opera);nova.dom.addClass(nova.dom.selector("html")[0],a.join(" "))})();
nova.Event={};nova.Event.add=function(a,b,d){if(a.addEventListener){a.addEventListener(b,d,false);return true}else if(a.attachEvent){a["e"+b+d]=d;a[b+d]=function(){a["e"+b+d](window.event)};a.attachEvent("on"+b,a[b+d]);return true}return false};nova.Event.remove=function(){return nova.WIN.removeEventListener?function(a,b,d,c){a.removeEventListener(b,d,!!c)}:nova.WIN.detachEvent?function(a,b,d){a.detachEvent("on"+b,d)}:function(){}};nova.ui={};
nova.ui.tab=function(a){a=a||".nova-tab";var b=nova.dom.selector(a+">.hd>li"),d=nova.dom.selector(a+">.bd>li"),c,e,f;c=function(){e=0;for(f=d.length;e<f;e++){nova.dom.removeClass(b[e],"selected");nova.dom.addClass(d[e],"hidden")}};a=function(g){g=g||window.event;g=g.target||g.srcElement;if(nova.dom.hasClass(g,"anchor"))g=g.parentNode;c();nova.dom.addClass(g,"selected");nova.dom.removeClass(d[g.index],"hidden")};e=0;for(f=b.length;e<f;e++){b[e].index=e;nova.Event.add(b[e],"mouseover",a)}c();nova.dom.addClass(b[0],
"selected");nova.dom.removeClass(d[0],"hidden")};nova.ui.slide=function(){};nova.ui.nav=function(){var a=nova.dom.selector(".nova-nav .item"),b,d;b=0;for(d=a.length;b<d;b++){nova.Event.add(a[b],"mouseover",function(){nova.dom.addClass(this,"selected")});nova.Event.add(a[b],"mouseout",function(){nova.dom.removeClass(this,"selected")})}};
nova.ui.flow=function(a){var b=document,d=b.documentElement,c=b.body,e=300,f=200,g=0,h=0,i=0,k=0,l=0,n=true,o,j=b.createElement("div");nova.dom.addClass(j,"nova-ui-flow");j.innerHTML='';nova.dom.setCSS([j],{position:"absolute",zIndex:"100",top:f+"px",left:"2px",width:a.width+"px",height:a.height+"px",visibility:"visible"});c.appendChild(j);var p=function(){width=c.clientWidth;g=d.clientHeight;h=j.offsetHeight;
i=j.offsetWidth;nova.dom.setCSS([j],{left:e+b.body.scrollLeft+"px",top:f+b.body.scrollTop+"px"});if(k)f+=1;else f-=1;if(f<0){k=1;f=0}if(f>=g-h){k=0;f=g-h}if(l)e+=1;else e-=1;if(e<0){l=1;e=0}if(e>=width-i){l=0;e=width-i}};a=function(){if(n){clearInterval(o);n=false}else{o=setInterval(p,30);n=true}};nova.Event.add(j,"mouseover",a);nova.Event.add(j,"mouseout",a);o=setInterval(p,30)};
nova.ui.flowBox=function(a){var b=window,d=document,c=function(h){var i,k=h.offsetTop;b.onscroll=function(){i=d.documentElement.scrollTop||d.body.scrollTop;nova.dom.setCSS([h],{top:i+k+"px"})}},e=d.createElement("div"),f=d.createElement("div"),g=d.createElement("div");e.className="nova-flow-box";f.className="nfb-first";g.className="nfb-second";f.innerHTML='';g.innerHTML='';nova.dom.setCSS([e,g],
{position:"absolute",top:0});nova.dom.setCSS([e],{top:a.top+"px"});e.appendChild(f);e.appendChild(g);d.body.appendChild(e);nova.Event.add(b,"load",function(){nova.dom.setCSS([g],{left:d.body.clientWidth-g.clientWidth+"px"});c(e)})};
<commit_msg>update compile file.<commit_after>/*
 FrostNova Javascript Library v0.3.2
 http://qslee.com/

 Copyright 2011, Qiu-Shi Lee
 Code licensed under the MIT License:
 https://github.com/qiushilee/frostnova/blob/master/LICENSE.txt
*/
var nova=function(){return nova.init.apply(nova,arguments)};nova.init=function(){return new nova.domChain.init(selector)};nova.WIN=window;nova.version="0.3.2";nova.bind=function(a,b){var d=Array.prototype.slice,c=d.apply(arguments,[2]);return function(){return a.apply(b||{},c.concat(d.apply(arguments)))}};nova.isArray=function(){};nova.isString=function(){};nova.isNubmer=function(){};nova.load={};
nova.load=function(a,b){var d=document.createElement("script");d.src=a;d.onloadDone=false;d.onload=function(){d.onloadDone=true;b()};d.onreadystatechange=function(){if(d.readyState==="loaded"||d.readyState==="complete"&&!d.onloadDone){d.onloadDone=true;b()}};document.body.appendChild(d)};nova.ajax={};nova.ajax.XMLHttpFactories=[function(){return new XMLHttpRequest},function(){return new ActiveXObject("Msxml2.XMLHTTP")},function(){return new ActiveXObject("Msxml3.XMLHTTP")},function(){return new ActiveXObject("Microsoft.XMLHTTP")}];
nova.ajax.createXMLHTTPObject=function(){for(var a=false,b=0;b<nova.ajax.XMLHttpFactories.length;b++){try{a=nova.ajax.XMLHttpFactories[b]()}catch(d){continue}break}return a};
nova.ajax.sendRequest=function(a,b,d){var c=nova.ajax.createXMLHTTPObject();if(c){c.open(d?"POST":"GET",a,true);c.setRequestHeader("User-Agent","XMLHTTP/1.0");d&&c.setRequestHeader("Content-type","application/x-www-form-urlencoded");c.onreadystatechange=function(){if(c.readyState==4)c.status!=200&&c.status!=304||b(c)};c.readyState!=4&&c.send(d)}};nova.ajax.get=function(a,b){return nova.ajax.sendRequest(a,b,"GET")};nova.ajax.post=function(a,b){return nova.ajax.sendRequest(a,b,"POST")};nova.dom={};
nova.dom.hasClass=function(){};nova.dom.addClass=function(a,b){if(!nova.dom.hasClass(a,b))a.className===""?a.className=b:a.className+=" "+b};nova.dom.removeClass=function(a,b){a.className=a.className.replace(b,"")};nova.dom.getStyle=function(a,b,d){if(a.currentStyle)return a.currentStyle[d];else if(nova.WIN.getComputedStyle)return document.defaultView.getComputedStyle(a,null).getPropertyValue(b)};
nova.dom.getWidth=function(a){var b,d;b=parseInt(nova.dom.getStyle(a,"margin-left","marginLeft"),10);d=parseInt(nova.dom.getStyle(a,"margin-right","marginRight"),10);return a.offsetWidth+b+d};nova.dom.setCSS=function(a,b){var d=function(e,f){for(var g=0,h=a.length;g<h;g++)a[g].style[e]=f},c;for(c in b)b.hasOwnProperty(c)&&d(c,b[c])};
(function(){var a={byID:function(c,e){if(c===null)return[];return[c.getElementById(e)]},byNodeName:function(c,e){if(c===null)return[];var f,g,h=[],i=c.getElementsByTagName(e);f=0;for(g=i.length;f<g;f++)h.push(i[f]);return h},byClassName:function(c,e){if(c===null)return[];var f,g,h=[],i=c.getElementsByTagName("*");f=0;for(g=i.length;f<g;f++){var j=i[f];j.className.match("\\b"+e+"\\b")&&h.push(j)}return h}},b={id:function(c,e){e=e.split("#")[1];return a.byID(c,e)},tag:function(c,e){return a.byNodeName(c,
e)},"class":function(c,e){e=e.split(".")[1];return a.byClassName(c,e)}},d=function(c){this.selector=c;this.tokens=[];this.tokenize()};d.prototype.tokenize=function(){this.tokens.push(this.selector[0]==="#"?"id":this.selector[0]==="."?"class":"tag");return this.tokens};nova.dom.selector=function(c,e){var f;f=e===undefined?document:e;if(f.querySelectorAll)f=f.querySelectorAll(c);else{var g=(new d(c)).tokens;f=b[g](f,c)}return f};nova.domChain={find:function(c){this.selector=c}}})();nova.ua={};
nova.ua=function(){var a,b=nova.WIN.navigator.userAgent,d,c;d=function(e){a=0;return parseFloat(e.replace(/\./g,function(){return a++==1?"":"."}))};c={ie:0,webkit:0,gecko:0,opera:0,mobile:null,os:null};if(/windows|win32/i.test(b))c.os="win";else if(/macintosh/i.test(b))c.os="mac";else if(/rhino/i.test(b))c.os="rhino";if(/KHTML/.test(b))c.webkit=1;m=b.match(/AppleWebKit\/([^\s]*)/);if(!c.webkit)if((m=b.match(/Opera[\s\/]([^\s]*)/))&&m[1]){c.opera=d(m[1]);if(m=b.match(/Opera Mini[^;]*/))c.mobile=m[0]}else if((m=
b.match(/MSIE\s([^;]*)/))&&m[1])c.ie=d(m[1]);else if(m=b.match(/Gecko\/([^\s]*)/)){c.gecko=1;if((m=b.match(/rv:([^\s\)]*)/))&&m[1])c.gecko=d(m[1])}return c}();(function(){var a=["ua-"+nova.ua.os,"ua-jsenable"];if(nova.ua.ie!==0)a.push("ua-ie"+nova.ua.ie);else if(nova.ua.webkit!==0)a.push("ua-webkit"+nova.ua.webkit);else if(nova.ua.gecko!==0)a.push("ua-gecko"+nova.ua.gecko,"ua-fx");else nova.ua.opera!==0&&a.push("ua-opera"+nova.ua.opera);nova.dom.addClass(nova.dom.selector("html")[0],a.join(" "))})();
nova.Event={};nova.Event.add=function(a,b,d){if(a.addEventListener){a.addEventListener(b,d,false);return true}else if(a.attachEvent){a["e"+b+d]=d;a[b+d]=function(){a["e"+b+d](window.event)};a.attachEvent("on"+b,a[b+d]);return true}return false};nova.Event.remove=function(){return nova.WIN.removeEventListener?function(a,b,d,c){a.removeEventListener(b,d,!!c)}:nova.WIN.detachEvent?function(a,b,d){a.detachEvent("on"+b,d)}:function(){}};nova.ui={};
nova.ui.tab=function(a){a=a||".nova-tab";var b=nova.dom.selector(a+">.hd>li"),d=nova.dom.selector(a+">.bd>li"),c,e,f;c=function(){e=0;for(f=d.length;e<f;e++){nova.dom.removeClass(b[e],"selected");nova.dom.addClass(d[e],"hidden")}};a=function(g){g=g||window.event;g=g.target||g.srcElement;if(nova.dom.hasClass(g,"anchor"))g=g.parentNode;c();nova.dom.addClass(g,"selected");nova.dom.removeClass(d[g.index],"hidden")};e=0;for(f=b.length;e<f;e++){b[e].index=e;nova.Event.add(b[e],"mouseover",a)}c();nova.dom.addClass(b[0],
"selected");nova.dom.removeClass(d[0],"hidden")};nova.ui.slide=function(){};nova.ui.nav=function(){var a=nova.dom.selector(".nova-nav .item"),b,d;b=0;for(d=a.length;b<d;b++){nova.Event.add(a[b],"mouseover",function(){nova.dom.addClass(this,"selected")});nova.Event.add(a[b],"mouseout",function(){nova.dom.removeClass(this,"selected")})}};
nova.ui.flow=function(a){var b=document,d=b.documentElement,c=b.body,e=300,f=200,g=0,h=0,i=0,j=0,l=0,n=true,o,k=b.createElement("div");nova.dom.addClass(k,"nova-ui-flow");k.innerHTML='';nova.dom.setCSS([k],{position:"absolute",zIndex:"100",top:f+"px",left:"2px",width:a.width+"px",height:a.height+"px",visibility:"visible"});c.appendChild(k);var p=function(){width=c.clientWidth;g=d.clientHeight;h=k.offsetHeight;
i=k.offsetWidth;nova.dom.setCSS([k],{left:e+b.body.scrollLeft+"px",top:f+b.body.scrollTop+"px"});if(j)f+=1;else f-=1;if(f<0){j=1;f=0}if(f>=g-h){j=0;f=g-h}if(l)e+=1;else e-=1;if(e<0){l=1;e=0}if(e>=width-i){l=0;e=width-i}};a=function(){if(n){clearInterval(o);n=false}else{o=setInterval(p,30);n=true}};nova.Event.add(k,"mouseover",a);nova.Event.add(k,"mouseout",a);o=setInterval(p,30)};
nova.ui.flowBox=function(a){var b=window,d=document,c=function(j){var l,n=j.offsetTop;b.onscroll=function(){l=d.documentElement.scrollTop||d.body.scrollTop;nova.dom.setCSS([j],{top:l+n+"px"})}},e=d.createElement("div"),f=d.createElement("div"),g=d.createElement("div"),h="",i="";if(a.close){h=d.createElement("span");i=d.createElement("span");nova.dom.setCSS([h,i],{display:"inline-block",width:"32px",cursor:"pointer"});h.innerHTML="\u5173\u95ed";i.innerHTML="\u5173\u95ed"}e.className="nova-flow-box";
f.className="nfb-first";g.className="nfb-second";f.innerHTML='';g.innerHTML='';nova.dom.setCSS([f,g],{textAlign:"center"});f.appendChild(h);g.appendChild(i);nova.dom.setCSS([e,g],{position:"absolute",top:0});nova.dom.setCSS([e],{top:a.top+"px"});e.appendChild(f);e.appendChild(g);d.body.appendChild(e);a=function(j){j=j||b.event;(j.target||j.srcElement).parentNode.innerHTML=
""};nova.Event.add(h,"click",a);nova.Event.add(i,"click",a);nova.Event.add(b,"load",function(){nova.dom.setCSS([g],{left:d.body.clientWidth-g.clientWidth+"px"});c(e)})};
<|endoftext|>