<commit_before>class Browsersync {
    name() {
        return 'browserSync';
    }

    dependencies() {
        this.requiresReload = true;

        return ['browser-sync-webpack-plugin', 'browser-sync'];
    }

    register(config) {
        this.config = typeof config == 'string' ? { proxy: config } : config;
    }

    webpackPlugins() {
        let BrowserSyncPlugin = require('browser-sync-webpack-plugin');

        return new BrowserSyncPlugin(this.config(), { reload: false });
    }

    config() {
        return Object.assign(
            {
                host: 'localhost',
                port: 3000,
                proxy: 'app.dev',
                files: [
                    'app/**/*.php',
                    'resources/views/**/*.php',
                    'public/js/**/*.js',
                    'public/css/**/*.css'
                ],
                snippetOptions: {
                    rule: {
                        match: /(<\/body>|<\/pre>)/i,
                        fn: function(snippet, match) {
                            return snippet + match;
                        }
                    }
                }
            },
            this.config
        );
    }
}

module.exports = Browsersync;
<commit_msg>Fix prop name<commit_after>class Browsersync {
    name() {
        return 'browserSync';
    }

    dependencies() {
        this.requiresReload = true;

        return ['browser-sync-webpack-plugin', 'browser-sync'];
    }

    register(userConfig) {
        this.userConfig =
            typeof userConfig == 'string' ? { proxy: userConfig } : userConfig;
    }

    webpackPlugins() {
        let BrowserSyncPlugin = require('browser-sync-webpack-plugin');

        return new BrowserSyncPlugin(this.config(), { reload: false });
    }

    config() {
        return Object.assign(
            {
                host: 'localhost',
                port: 3000,
                proxy: 'app.dev',
                files: [
                    'app/**/*.php',
                    'resources/views/**/*.php',
                    'public/js/**/*.js',
                    'public/css/**/*.css'
                ],
                snippetOptions: {
                    rule: {
                        match: /(<\/body>|<\/pre>)/i,
                        fn: function(snippet, match) {
                            return snippet + match;
                        }
                    }
                }
            },
            this.userConfig
        );
    }
}

module.exports = Browsersync;
<|endoftext|>


<commit_before>// Dirty implementation of family.scss with Javascript
// To make the demo playful

var selectedStyle = `
background: #FF1B63 !important;
background: linear-gradient(to bottom, #FF3A76, #FF1B63) !important;
font-weight: bold !important;
`;

var preStyle = `
background: rgba(255, 255, 255, 0.5) !important;
background: linear-gradient(to bottom, rgba(255, 255, 255, 0.4), rgba(255, 255, 255, 0.6)) !important;
font-weight: 300 !important;
`;

///////////////////////////////
// first
///////////////////////////////

function first(num) {

	function injectStyle(num){
		document.getElementById('style-first').innerHTML = `ul.first li { ${preStyle} }`;
		document.getElementById('style-first').innerHTML += `.first li:nth-child(-n + ${num}){
			${selectedStyle}
		}`;
	}

	var newStyle = injectStyle(num);

}
document.getElementById('first').addEventListener('keyup', function(){
	first(this.innerHTML)
})

///////////////////////////////
// last
///////////////////////////////

function last(num) {

	function injectStyle(num){
		document.getElementById('style-last').innerHTML = `ul.last li { ${preStyle} }`;
		document.getElementById('style-last').innerHTML += `.last li:nth-last-child(-n + ${num}){
			${selectedStyle}
		}`;
	}

	var newStyle = injectStyle(num);

}
document.getElementById('last').addEventListener('keyup', function(){
	last(this.innerHTML)
})

///////////////////////////////
// afterFirst
///////////////////////////////

function afterFirst(num) {

	function injectStyle(num){
		var num = parseInt(num) + 1;
		document.getElementById('style-after-first').innerHTML = `ul.after-first li { ${preStyle} }`;
		document.getElementById('style-after-first').innerHTML += `.after-first li:nth-child(n+${num}){
			${selectedStyle}
		}
		`
	}

	var newStyle = injectStyle(num);

}
document.getElementById('after-first').addEventListener('keyup', function(){
	afterFirst(this.innerHTML)
})

///////////////////////////////
// fromEnd
///////////////////////////////

function fromEnd(num) {
	function injectStyle(num){
		document.getElementById('style-from-end').innerHTML = `ul.from-end li { ${preStyle} }`;
		document.getElementById('style-from-end').innerHTML += `.from-end li:nth-last-child(${num}){
			${selectedStyle}
		}
		`
	}

	var newStyle = injectStyle(num);

}
document.getElementById('from-end').addEventListener('keyup', function(){
	fromEnd(this.innerHTML)
})

///////////////////////////////
// between
///////////////////////////////

function between(numa, numb) {
	function injectStyle(numa, numb){
		document.getElementById('style-between').innerHTML = `ul.between li { ${preStyle} }`;
		document.getElementById('style-between').innerHTML += `.between li:nth-child(n+${numa}):nth-child(-n+${numb}){
			${selectedStyle}
		}
		`
	}

	var newStyle = injectStyle(numa, numb);

}
document.getElementById('between').addEventListener('keyup', function(){
	var vala = document.getElementById('between-a').innerHTML;
	var valb = document.getElementById('between-b').innerHTML;
	between(vala, valb)
})

///////////////////////////////
// evenBetween
///////////////////////////////

function evenBetween(numa, numb) {
	function injectStyle(numa, numb){
		document.getElementById('style-even-between').innerHTML = `ul.even-between li { ${preStyle} }`;
		document.getElementById('style-even-between').innerHTML += `.even-between li:nth-child(even):nth-child(n + ${numa}):nth-child(-n + ${numb}){
			${selectedStyle}
		}
		`
	}

	var newStyle = injectStyle(numa, numb);

}
document.getElementById('even-between').addEventListener('keyup', function(){
	var vala = document.getElementById('even-between-a').innerHTML;
	var valb = document.getElementById('even-between-b').innerHTML;
	evenBetween(vala, valb)
})

///////////////////////////////
// oddBetween
///////////////////////////////

function oddBetween(numa, numb) {
	function injectStyle(numa, numb){
		document.getElementById('style-odd-between').innerHTML = `ul.odd-between li { ${preStyle} }`;
		document.getElementById('style-odd-between').innerHTML += `.odd-between li:nth-child(odd):nth-child(n + ${numa}):nth-child(-n + ${numb}){
			${selectedStyle}
		}
		`
	}

	var newStyle = injectStyle(numa, numb);

}
document.getElementById('odd-between').addEventListener('keyup', function(){
	var vala = document.getElementById('odd-between-a').innerHTML;
	var valb = document.getElementById('odd-between-b').innerHTML;
	oddBetween(vala, valb)
})

///////////////////////////////
// nBetween
///////////////////////////////

function nBetween(numa, numb, numc) {
	function injectStyle(numa, numb, numc){
		document.getElementById('style-n-between').innerHTML = `ul.n-between li { ${preStyle} }`;
		document.getElementById('style-n-between').innerHTML += `.n-between li:nth-child(${numa}n):nth-child(n + ${numb}):nth-child(-n + ${numc}){
			${selectedStyle}
		}
		`
	}

	var newStyle = injectStyle(numa, numb, numc);

}
document.getElementById('n-between').addEventListener('keyup', function(){
	var vala = document.getElementById('n-between-a').innerHTML;
	var valb = document.getElementById('n-between-b').innerHTML;
	var valc = document.getElementById('n-between-c').innerHTML;
	nBetween(vala, valb, valc)
})

///////////////////////////////
// allBut
///////////////////////////////

function allBut(num) {
	function injectStyle(num){
		document.getElementById('style-all-but').innerHTML = `ul.all-but li { ${preStyle} }`;
		document.getElementById('style-all-but').innerHTML += `.all-but li:not(:nth-child(${num})){
			${selectedStyle}
		}
		`
	}

	var newStyle = injectStyle(num);

}
document.getElementById('all-but').addEventListener('keyup', function(){
	allBut(this.innerHTML)
})

///////////////////////////////
// each
///////////////////////////////

function each(num) {
	function injectStyle(num){
		document.getElementById('style-each').innerHTML = `ul.each li { ${preStyle} }`;
		document.getElementById('style-each').innerHTML += `.each li:nth-child(${num}n){
			${selectedStyle}
		}
		`
	}

	var newStyle = injectStyle(num);

}
document.getElementById('each').addEventListener('keyup', function(){
	each(this.innerHTML)
})

///////////////////////////////
// eachAfter
///////////////////////////////

function eachAfter(numa, numb) {
	function injectStyle(numa, numb){
		document.getElementById('style-each-after').innerHTML = `ul.each-after li { ${preStyle} }`;
		// if (numb < numa ) {
			document.getElementById('style-each-after').innerHTML += `.each-after li:nth-child(${numb - numa}n) ~ :nth-child(${numa}n){
				${selectedStyle}
			}
			`
		// }
		//  else {
		// 	document.getElementById('style-each-after').innerHTML += `.each-after li:nth-child(${numb}n) ~ :nth-child(${numa}n){
		// 		${selectedStyle}
		// 	}
		// 	`
		// }
	}

	var newStyle = injectStyle(numa, numb);

}
document.getElementById('each-after').addEventListener('keyup', function(){
	var vala = document.getElementById('each-after-a').innerHTML;
	var valb = document.getElementById('each-after-b').innerHTML;
	eachAfter(vala, valb)
})

///////////////////////////////
// fromFirstLast
///////////////////////////////

function fromFirstLast(num) {
	function injectStyle(num){
		document.getElementById('style-from-first-last').innerHTML = `ul.from-first-last li { ${preStyle} }`;
		document.getElementById('style-from-first-last').innerHTML += `.from-first-last li:nth-child(${num}),
		.from-first-last li:nth-last-child(${num}){
			${selectedStyle}
		}
		`
	}

	var newStyle = injectStyle(num);

}
document.getElementById('from-first-last').addEventListener('keyup', function(){
	fromFirstLast(this.innerHTML)
})

///////////////////////////////
// middle
///////////////////////////////

function middle(num) {
	function injectStyle(num){
		document.getElementById('style-middle').innerHTML = `ul.middle li { ${preStyle} }`;
		document.getElementById('style-middle').innerHTML += `.middle li:nth-child(${Math.round(num/2)}){
			${selectedStyle}
		}
		`
	}

	var newStyle = injectStyle(num);

}
document.getElementById('middle').addEventListener('keyup', function(){
	middle(this.innerHTML)
})

///////////////////////////////
// allButFirstLast
///////////////////////////////

function allButFirstLast(num) {
	function injectStyle(num){
		num = parseInt(num) + 1;
		document.getElementById('style-all-but-first-last').innerHTML = `ul.all-but-first-last li { ${preStyle} }`;
		document.getElementById('style-all-but-first-last').innerHTML += `.all-but-first-last li:nth-child(n+${num}):nth-last-child(n+${num}){
			${selectedStyle}
		}
		`
	}

	var newStyle = injectStyle(num);

}
document.getElementById('all-but-first-last').addEventListener('keyup', function(){
	allButFirstLast(this.innerHTML)
})

///////////////////////////////
// firstOf
///////////////////////////////

function firstOf(num) {
	function injectStyle(num){
		document.getElementById('style-first-of').innerHTML = `ul.first-of li { ${preStyle} }`;
		document.getElementById('style-first-of').innerHTML += `.first-of li:nth-last-child(${num}):first-child {
			${selectedStyle}
		}
		`
	}

	var newStyle = injectStyle(num);

}
document.getElementById('first-of').addEventListener('keyup', function(){
	firstOf(this.innerHTML)
})

///////////////////////////////
// lastOf
///////////////////////////////

function lastOf(num) {
	function injectStyle(num){
		document.getElementById('style-last-of').innerHTML = `ul.last-of li { ${preStyle} }`;
		document.getElementById('style-last-of').innerHTML += `.last-of li:nth-of-type(${num}):nth-last-of-type(1) {
			${selectedStyle}
		}
		`
	}

	var newStyle = injectStyle(num);

}
document.getElementById('last-of').addEventListener('keyup', function(){
	lastOf(this.innerHTML)
})

///////////////////////////////
// atLeast
///////////////////////////////

function atLeast(num) {
	function injectStyle(num){
		document.getElementById('style-at-least').innerHTML = `ul.at-least li { ${preStyle} }`;
		document.getElementById('style-at-least').innerHTML += `.at-least li:nth-last-child(n + ${num}), .at-least li:nth-last-child(n + ${num}) ~ li {
			${selectedStyle}
		}
		`
	}

	var newStyle = injectStyle(num);

}
document.getElementById('at-least').addEventListener('keyup', function(){
	atLeast(this.innerHTML)
})

///////////////////////////////
// atMost
///////////////////////////////

function atMost(num) {
	function injectStyle(num){
		document.getElementById('style-at-most').innerHTML = `ul.at-most li { ${preStyle} }`;
		document.getElementById('style-at-most').innerHTML += `.at-most li:nth-last-child(-n + ${num}):first-child, .at-most li:nth-last-child(-n + ${num}):first-child ~ li {
			${selectedStyle}
		}
		`
	}

	var newStyle = injectStyle(num);

}
document.getElementById('at-most').addEventListener('keyup', function(){
	atMost(this.innerHTML)
})

///////////////////////////////
// inBetween
///////////////////////////////

function inBetween(numa, numb) {
	function injectStyle(numa, numb){
		document.getElementById('style-in-between').innerHTML = `ul.in-between li { ${preStyle} }`;
		document.getElementById('style-in-between').innerHTML += `ul.in-between li:nth-last-child(n + ${numa}):nth-last-child(-n + ${numb}):first-child, ul.in-between li:nth-last-child(n + ${numa}):nth-last-child(-n + ${numb}):first-child ~ li{
			${selectedStyle}
		}
		`
	}

	var newStyle = injectStyle(numa, numb);

}
document.getElementById('in-between').addEventListener('keyup', function(){
	var vala = document.getElementById('in-between-a').innerHTML;
	var valb = document.getElementById('in-between-b').innerHTML;
	inBetween(vala, valb)
})
<commit_msg>Fix buggy demo; remove useless javascript that prevented the other demos to work properly, fixing #77<commit_after>// Dirty implementation of family.scss with Javascript
// To make the demo more playfull

var selectedStyle = `
background: #FF1B63 !important;
background: linear-gradient(to bottom, #FF3A76, #FF1B63) !important;
font-weight: bold !important;
`;

var preStyle = `
background: rgba(255, 255, 255, 0.5) !important;
background: linear-gradient(to bottom, rgba(255, 255, 255, 0.4), rgba(255, 255, 255, 0.6)) !important;
font-weight: 300 !important;
`;

///////////////////////////////
// first
///////////////////////////////

function first(num) {

	function injectStyle(num){
		document.getElementById('style-first').innerHTML = `ul.first li { ${preStyle} }`;
		document.getElementById('style-first').innerHTML += `.first li:nth-child(-n + ${num}){
			${selectedStyle}
		}`;
	}

	var newStyle = injectStyle(num);

}
document.getElementById('first').addEventListener('keyup', function(){
	first(this.innerHTML)
})

///////////////////////////////
// last
///////////////////////////////

function last(num) {

	function injectStyle(num){
		document.getElementById('style-last').innerHTML = `ul.last li { ${preStyle} }`;
		document.getElementById('style-last').innerHTML += `.last li:nth-last-child(-n + ${num}){
			${selectedStyle}
		}`;
	}

	var newStyle = injectStyle(num);

}
document.getElementById('last').addEventListener('keyup', function(){
	last(this.innerHTML)
})

///////////////////////////////
// afterFirst
///////////////////////////////

function afterFirst(num) {

	function injectStyle(num){
		var num = parseInt(num) + 1;
		document.getElementById('style-after-first').innerHTML = `ul.after-first li { ${preStyle} }`;
		document.getElementById('style-after-first').innerHTML += `.after-first li:nth-child(n+${num}){
			${selectedStyle}
		}
		`
	}

	var newStyle = injectStyle(num);

}
document.getElementById('after-first').addEventListener('keyup', function(){
	afterFirst(this.innerHTML)
})

///////////////////////////////
// fromEnd
///////////////////////////////

function fromEnd(num) {
	function injectStyle(num){
		document.getElementById('style-from-end').innerHTML = `ul.from-end li { ${preStyle} }`;
		document.getElementById('style-from-end').innerHTML += `.from-end li:nth-last-child(${num}){
			${selectedStyle}
		}
		`
	}

	var newStyle = injectStyle(num);

}
document.getElementById('from-end').addEventListener('keyup', function(){
	fromEnd(this.innerHTML)
})

///////////////////////////////
// between
///////////////////////////////

function between(numa, numb) {
	function injectStyle(numa, numb){
		document.getElementById('style-between').innerHTML = `ul.between li { ${preStyle} }`;
		document.getElementById('style-between').innerHTML += `.between li:nth-child(n+${numa}):nth-child(-n+${numb}){
			${selectedStyle}
		}
		`
	}

	var newStyle = injectStyle(numa, numb);

}
document.getElementById('between').addEventListener('keyup', function(){
	var vala = document.getElementById('between-a').innerHTML;
	var valb = document.getElementById('between-b').innerHTML;
	between(vala, valb)
})

///////////////////////////////
// evenBetween
///////////////////////////////

function evenBetween(numa, numb) {
	function injectStyle(numa, numb){
		document.getElementById('style-even-between').innerHTML = `ul.even-between li { ${preStyle} }`;
		document.getElementById('style-even-between').innerHTML += `.even-between li:nth-child(even):nth-child(n + ${numa}):nth-child(-n + ${numb}){
			${selectedStyle}
		}
		`
	}

	var newStyle = injectStyle(numa, numb);

}
document.getElementById('even-between').addEventListener('keyup', function(){
	var vala = document.getElementById('even-between-a').innerHTML;
	var valb = document.getElementById('even-between-b').innerHTML;
	evenBetween(vala, valb)
})

///////////////////////////////
// oddBetween
///////////////////////////////

function oddBetween(numa, numb) {
	function injectStyle(numa, numb){
		document.getElementById('style-odd-between').innerHTML = `ul.odd-between li { ${preStyle} }`;
		document.getElementById('style-odd-between').innerHTML += `.odd-between li:nth-child(odd):nth-child(n + ${numa}):nth-child(-n + ${numb}){
			${selectedStyle}
		}
		`
	}

	var newStyle = injectStyle(numa, numb);

}
document.getElementById('odd-between').addEventListener('keyup', function(){
	var vala = document.getElementById('odd-between-a').innerHTML;
	var valb = document.getElementById('odd-between-b').innerHTML;
	oddBetween(vala, valb)
})

///////////////////////////////
// nBetween
///////////////////////////////

function nBetween(numa, numb, numc) {
	function injectStyle(numa, numb, numc){
		document.getElementById('style-n-between').innerHTML = `ul.n-between li { ${preStyle} }`;
		document.getElementById('style-n-between').innerHTML += `.n-between li:nth-child(${numa}n):nth-child(n + ${numb}):nth-child(-n + ${numc}){
			${selectedStyle}
		}
		`
	}

	var newStyle = injectStyle(numa, numb, numc);

}
document.getElementById('n-between').addEventListener('keyup', function(){
	var vala = document.getElementById('n-between-a').innerHTML;
	var valb = document.getElementById('n-between-b').innerHTML;
	var valc = document.getElementById('n-between-c').innerHTML;
	nBetween(vala, valb, valc)
})

///////////////////////////////
// allBut
///////////////////////////////

function allBut(num) {
	function injectStyle(num){
		document.getElementById('style-all-but').innerHTML = `ul.all-but li { ${preStyle} }`;
		document.getElementById('style-all-but').innerHTML += `.all-but li:not(:nth-child(${num})){
			${selectedStyle}
		}
		`
	}

	var newStyle = injectStyle(num);

}
document.getElementById('all-but').addEventListener('keyup', function(){
	allBut(this.innerHTML)
})

///////////////////////////////
// each
///////////////////////////////

function each(num) {
	function injectStyle(num){
		document.getElementById('style-each').innerHTML = `ul.each li { ${preStyle} }`;
		document.getElementById('style-each').innerHTML += `.each li:nth-child(${num}n){
			${selectedStyle}
		}
		`
	}

	var newStyle = injectStyle(num);

}
document.getElementById('each').addEventListener('keyup', function(){
	each(this.innerHTML)
})

///////////////////////////////
// fromFirstLast
///////////////////////////////

function fromFirstLast(num) {
	function injectStyle(num){
		document.getElementById('style-from-first-last').innerHTML = `ul.from-first-last li { ${preStyle} }`;
		document.getElementById('style-from-first-last').innerHTML += `.from-first-last li:nth-child(${num}),
		.from-first-last li:nth-last-child(${num}){
			${selectedStyle}
		}
		`
	}

	var newStyle = injectStyle(num);

}
document.getElementById('from-first-last').addEventListener('keyup', function(){
	alert(this)
	fromFirstLast(this.innerHTML)
})

///////////////////////////////
// middle
///////////////////////////////

function middle(num) {
	function injectStyle(num){
		document.getElementById('style-middle').innerHTML = `ul.middle li { ${preStyle} }`;
		document.getElementById('style-middle').innerHTML += `.middle li:nth-child(${Math.round(num/2)}){
			${selectedStyle}
		}
		`
	}

	var newStyle = injectStyle(num);

}
document.getElementById('middle').addEventListener('keyup', function(){
	middle(this.innerHTML)
})

///////////////////////////////
// allButFirstLast
///////////////////////////////

function allButFirstLast(num) {
	function injectStyle(num){
		num = parseInt(num) + 1;
		document.getElementById('style-all-but-first-last').innerHTML = `ul.all-but-first-last li { ${preStyle} }`;
		document.getElementById('style-all-but-first-last').innerHTML += `.all-but-first-last li:nth-child(n+${num}):nth-last-child(n+${num}){
			${selectedStyle}
		}
		`
	}

	var newStyle = injectStyle(num);

}
document.getElementById('all-but-first-last').addEventListener('keyup', function(){
	allButFirstLast(this.innerHTML)
})

///////////////////////////////
// firstOf
///////////////////////////////

function firstOf(num) {
	function injectStyle(num){
		document.getElementById('style-first-of').innerHTML = `ul.first-of li { ${preStyle} }`;
		document.getElementById('style-first-of').innerHTML += `.first-of li:nth-last-child(${num}):first-child {
			${selectedStyle}
		}
		`
	}

	var newStyle = injectStyle(num);

}
document.getElementById('first-of').addEventListener('keyup', function(){
	firstOf(this.innerHTML)
})

///////////////////////////////
// lastOf
///////////////////////////////

function lastOf(num) {
	function injectStyle(num){
		document.getElementById('style-last-of').innerHTML = `ul.last-of li { ${preStyle} }`;
		document.getElementById('style-last-of').innerHTML += `.last-of li:nth-of-type(${num}):nth-last-of-type(1) {
			${selectedStyle}
		}
		`
	}

	var newStyle = injectStyle(num);

}
document.getElementById('last-of').addEventListener('keyup', function(){
	lastOf(this.innerHTML)
})

///////////////////////////////
// atLeast
///////////////////////////////

function atLeast(num) {
	function injectStyle(num){
		document.getElementById('style-at-least').innerHTML = `ul.at-least li { ${preStyle} }`;
		document.getElementById('style-at-least').innerHTML += `.at-least li:nth-last-child(n + ${num}), .at-least li:nth-last-child(n + ${num}) ~ li {
			${selectedStyle}
		}
		`
	}

	var newStyle = injectStyle(num);

}
document.getElementById('at-least').addEventListener('keyup', function(){
	atLeast(this.innerHTML)
})

///////////////////////////////
// atMost
///////////////////////////////

function atMost(num) {
	function injectStyle(num){
		document.getElementById('style-at-most').innerHTML = `ul.at-most li { ${preStyle} }`;
		document.getElementById('style-at-most').innerHTML += `.at-most li:nth-last-child(-n + ${num}):first-child, .at-most li:nth-last-child(-n + ${num}):first-child ~ li {
			${selectedStyle}
		}
		`
	}

	var newStyle = injectStyle(num);

}
document.getElementById('at-most').addEventListener('keyup', function(){
	atMost(this.innerHTML)
})

///////////////////////////////
// inBetween
///////////////////////////////

function inBetween(numa, numb) {
	function injectStyle(numa, numb){
		document.getElementById('style-in-between').innerHTML = `ul.in-between li { ${preStyle} }`;
		document.getElementById('style-in-between').innerHTML += `ul.in-between li:nth-last-child(n + ${numa}):nth-last-child(-n + ${numb}):first-child, ul.in-between li:nth-last-child(n + ${numa}):nth-last-child(-n + ${numb}):first-child ~ li{
			${selectedStyle}
		}
		`
	}

	var newStyle = injectStyle(numa, numb);

}
document.getElementById('in-between').addEventListener('keyup', function(){
	var vala = document.getElementById('in-between-a').innerHTML;
	var valb = document.getElementById('in-between-b').innerHTML;
	inBetween(vala, valb)
})
<|endoftext|>


<commit_before>var $ = require('jquery');
var Backbone = require('backbone');
var EditorHelpers = require('../editor-helpers-extend');
var _ = require('underscore');
var CustomListCollection = require('../../../custom-list/custom-list-collection');
var selectedItemTemplate = require('./select-item.tpl');
var CustomListItemView = require('../../../custom-list/custom-list-item-view');
var itemListTemplate = require('../../../custom-list/custom-list-item.tpl');
var template = require('./select.tpl');
var PopupManager = require('../../../popup-manager');
var SelectListView = require('./select-list-view');
var TipsyTooltipView = require('../../../tipsy-tooltip-view');

var ENTER_KEY_CODE = 13;

Backbone.Form.editors.Select = Backbone.Form.editors.Base.extend({

  tagName: 'div',
  className: 'u-ellipsis Editor-formSelect',

  events: {
    'click .js-button': '_onButtonClick',
    'keydown .js-button': '_onButtonKeyDown',
    'focus .js-button': function () {
      this.trigger('focus', this);
    },
    'blur': function () {
      this.trigger('blur', this);
    }
  },

  options: {
    selectedItemTemplate: selectedItemTemplate,
    itemListTemplate: itemListTemplate,
    customListItemView: CustomListItemView
  },

  initialize: function (opts) {
    Backbone.Form.editors.Base.prototype.initialize.call(this, opts);
    EditorHelpers.setOptions(this, opts);

    this.template = opts.template || template;
    this.dialogMode = this.options.dialogMode || 'nested';

    if (this.options.editorAttrs && this.options.editorAttrs.help) {
      this._help = this.options.editorAttrs.help;
    }

    if (this.options.options != null) {
      this.collection = new CustomListCollection(this.options.options);
    } else {
      this.collection = this.options.collection;
    }

    if (this.collection.isAsync === undefined) {
      throw new Error('collection must implement isAsync method.');
    }

    this._initViews();
    this.setValue(this.model.get(this.options.keyAttr));
    this._initBinds();
  },

  render: function () {
    var isEmpty = !this.collection.length;
    var isNull = !this._hasValue();
    this._isDisabled = !isEmpty ? this.options.disabled : true;
    var placeholder = this._getPlaceholder(this._isDisabled);
    var label = isNull ? placeholder : this._getLabel();
    var isLoading = this._isLoading();

    this.$el.html(this.template({
      keyAttr: this.options.keyAttr,
      isEmpty: isEmpty,
      label: label,
      isDisabled: this._isDisabled,
      isNull: isNull,
      isLoading: isLoading,
      help: this._help || ''
    }));

    // we are replacing the html, so we need to re append if nested mode
    if (this.dialogMode === 'nested') {
      this._popupManager.append(this.dialogMode);
    }

    if (!isLoading) {
      this._renderSelected();
    }

    return this;
  },

  _initBinds: function () {
    var hide = function () {
      this._listView.hide();
      this._popupManager.untrack();
      this._onToggleSelected();
    }.bind(this);

    this.applyESCBind(hide);
    this.applyClickOutsideBind(hide);

    this.listenTo(this.collection, 'change:selected', this._onItemSelected);

    if (this.collection.isAsync()) {
      this.listenTo(this.collection.stateModel, 'change:state', this.render);
    }
  },

  _initViews: function () {
    this._listView = new SelectListView({
      collection: this.collection,
      showSearch: this.options.showSearch,
      allowFreeTextInput: this.options.allowFreeTextInput,
      typeLabel: this.options.keyAttr,
      itemTemplate: this.options.itemListTemplate,
      itemView: this.options.customListItemView,
      position: this.options.position,
      searchPlaceholder: this.options.searchPlaceholder,
      selectModel: this.options.defaultValue && this.model
    });

    this._popupManager = new PopupManager(this.cid, this.$el, this._listView.$el);
    this._popupManager.append(this.dialogMode);
  },

  _getPlaceholder: function (isDisabled) {
    var keyAttr = this.options.keyAttr;
    var placeholder;

    if (isDisabled) {
      placeholder = this.options.disabledPlaceholder || _t('components.backbone-forms.select.disabled-placeholder', { keyAttr: keyAttr });
    } else {
      placeholder = this.options.placeholder || _t('components.backbone-forms.select.placeholder', { keyAttr: keyAttr });
    }

    return placeholder;
  },

  _hasValue: function () {
    var name = this.model.get(this.options.keyAttr);
    return name != null && name !== '';
  },

  _getLabel: function () {
    var name = this.model.get(this.options.keyAttr);
    var mdl = this.collection.findWhere({val: name});
    return mdl && mdl.getName() || name || '';
  },

  _isLoading: function () {
    var isLoading = this.options.loading;

    if (this.collection.isAsync()) {
      isLoading = this.collection.stateModel.get('state') === 'fetching';
    }

    return isLoading;
  },

  _destroyBinds: function () {
    this.stopListening(this.collection);
    Backbone.Form.editors.Base.prototype._destroyBinds.call(this);
  },

  _onItemSelected: function (model) {
    this._listView.hide();
    this._popupManager.untrack();
    this._renderButton(model);
    this.trigger('change', this);
  },

  _onButtonClick: function () {
    if (this._isDisabled) {
      return;
    }

    this._listView.toggle();
    this._listView.isVisible() ? this._popupManager.track() : this._popupManager.untrack();
    this._onToggleSelected();
  },

  _onButtonKeyDown: function (event) {
    if (this._isDisabled) {
      return;
    }

    if (event.which === ENTER_KEY_CODE) {
      event.preventDefault();

      if (!this._listView.isVisible()) {
        event.stopPropagation();
        this._listView.toggle();
      } else {
        this._popupManager.track();
      }
    }
  },

  getValue: function () {
    var item = this.collection.getSelectedItem();
    if (item) {
      return item.getValue();
    } else {
      return this.value;
    }
  },

  setValue: function (value) {
    var selectedModel = this.collection.setSelected(value);
    if (selectedModel) {
      this._renderButton(selectedModel);
    } else {
      this.render();
    }
    this.value = value;
  },

  _renderSelected: function () {
    var selectedModel = this.collection.getSelectedItem();
    if (selectedModel) {
      this._renderButton(selectedModel);
    }
  },

  _getButton: function () {
    return this.$('.js-button');
  },

  _renderButton: function (model) {
    var button = this._getButton();
    var data = _.extend({}, model.attributes, { label: model.getName() });
    var $html = this.options.selectedItemTemplate(data);

    button
      .removeClass('is-empty')
      .html($html);

    if (this._help) {
      this._removeTooltip();

      this._helpTooltip = new TipsyTooltipView({
        el: this.$('.js-help'),
        gravity: 'w',
        title: function () {
          return $(this).data('tooltip');
        }
      });
    }

    return button;
  },

  _removeTooltip: function () {
    if (this._helpTooltip) {
      this._helpTooltip.clean();
    }
  },

  remove: function () {
    this._removeTooltip();
    this._popupManager && this._popupManager.destroy();
    this._listView && this._listView.clean();
    this._destroyBinds();
    Backbone.Form.editors.Base.prototype.remove.call(this);
  },

  _onToggleSelected: function () {
    var visible = this._listView.isVisible();

    this.$el.toggleClass('is-active', visible);

    if (!visible) {
      this._getButton().blur();
    }
  },

  clean: function () {
    this.$el.remove();
  }
});
<commit_msg>Remove click bind in SelectView in favor of the DropdownOverlay<commit_after>var $ = require('jquery');
var Backbone = require('backbone');
var EditorHelpers = require('../editor-helpers-extend');
var _ = require('underscore');
var CustomListCollection = require('../../../custom-list/custom-list-collection');
var selectedItemTemplate = require('./select-item.tpl');
var CustomListItemView = require('../../../custom-list/custom-list-item-view');
var itemListTemplate = require('../../../custom-list/custom-list-item.tpl');
var template = require('./select.tpl');
var PopupManager = require('../../../popup-manager');
var SelectListView = require('./select-list-view');
var TipsyTooltipView = require('../../../tipsy-tooltip-view');

var ENTER_KEY_CODE = 13;

Backbone.Form.editors.Select = Backbone.Form.editors.Base.extend({

  tagName: 'div',
  className: 'u-ellipsis Editor-formSelect',

  events: {
    'click .js-button': '_onButtonClick',
    'keydown .js-button': '_onButtonKeyDown',
    'focus .js-button': function () {
      this.trigger('focus', this);
    },
    'blur': function () {
      this.trigger('blur', this);
    }
  },

  options: {
    selectedItemTemplate: selectedItemTemplate,
    itemListTemplate: itemListTemplate,
    customListItemView: CustomListItemView
  },

  initialize: function (opts) {
    Backbone.Form.editors.Base.prototype.initialize.call(this, opts);
    EditorHelpers.setOptions(this, opts);

    this.template = opts.template || template;
    this.dialogMode = this.options.dialogMode || 'nested';

    if (this.options.editorAttrs && this.options.editorAttrs.help) {
      this._help = this.options.editorAttrs.help;
    }

    if (this.options.options != null) {
      this.collection = new CustomListCollection(this.options.options);
    } else {
      this.collection = this.options.collection;
    }

    if (this.collection.isAsync === undefined) {
      throw new Error('collection must implement isAsync method.');
    }

    this._initViews();
    this.setValue(this.model.get(this.options.keyAttr));
    this._initBinds();
  },

  render: function () {
    var isEmpty = !this.collection.length;
    var isNull = !this._hasValue();
    this._isDisabled = !isEmpty ? this.options.disabled : true;
    var placeholder = this._getPlaceholder(this._isDisabled);
    var label = isNull ? placeholder : this._getLabel();
    var isLoading = this._isLoading();

    this.$el.html(this.template({
      keyAttr: this.options.keyAttr,
      isEmpty: isEmpty,
      label: label,
      isDisabled: this._isDisabled,
      isNull: isNull,
      isLoading: isLoading,
      help: this._help || ''
    }));

    // we are replacing the html, so we need to re append if nested mode
    if (this.dialogMode === 'nested') {
      this._popupManager.append(this.dialogMode);
    }

    if (!isLoading) {
      this._renderSelected();
    }

    return this;
  },

  _initBinds: function () {
    var hide = function () {
      this._listView.hide();
      this._popupManager.untrack();
      this._onToggleSelected();
    }.bind(this);

    this.applyESCBind(hide);

    this.listenTo(this.collection, 'change:selected', this._onItemSelected);

    if (this.collection.isAsync()) {
      this.listenTo(this.collection.stateModel, 'change:state', this.render);
    }
  },

  _initViews: function () {
    this._listView = new SelectListView({
      collection: this.collection,
      showSearch: this.options.showSearch,
      allowFreeTextInput: this.options.allowFreeTextInput,
      typeLabel: this.options.keyAttr,
      itemTemplate: this.options.itemListTemplate,
      itemView: this.options.customListItemView,
      position: this.options.position,
      searchPlaceholder: this.options.searchPlaceholder,
      selectModel: this.options.defaultValue && this.model
    });

    this._popupManager = new PopupManager(this.cid, this.$el, this._listView.$el);
    this._popupManager.append(this.dialogMode);
  },

  _getPlaceholder: function (isDisabled) {
    var keyAttr = this.options.keyAttr;
    var placeholder;

    if (isDisabled) {
      placeholder = this.options.disabledPlaceholder || _t('components.backbone-forms.select.disabled-placeholder', { keyAttr: keyAttr });
    } else {
      placeholder = this.options.placeholder || _t('components.backbone-forms.select.placeholder', { keyAttr: keyAttr });
    }

    return placeholder;
  },

  _hasValue: function () {
    var name = this.model.get(this.options.keyAttr);
    return name != null && name !== '';
  },

  _getLabel: function () {
    var name = this.model.get(this.options.keyAttr);
    var mdl = this.collection.findWhere({val: name});
    return mdl && mdl.getName() || name || '';
  },

  _isLoading: function () {
    var isLoading = this.options.loading;

    if (this.collection.isAsync()) {
      isLoading = this.collection.stateModel.get('state') === 'fetching';
    }

    return isLoading;
  },

  _destroyBinds: function () {
    this.stopListening(this.collection);
    Backbone.Form.editors.Base.prototype._destroyBinds.call(this);
  },

  _onItemSelected: function (model) {
    this._listView.hide();
    this._popupManager.untrack();
    this._renderButton(model);
    this.trigger('change', this);
  },

  _onButtonClick: function () {
    if (this._isDisabled) {
      return;
    }

    this._listView.toggle();
    this._listView.isVisible() ? this._popupManager.track() : this._popupManager.untrack();
    this._onToggleSelected();
  },

  _onButtonKeyDown: function (event) {
    if (this._isDisabled) {
      return;
    }

    if (event.which === ENTER_KEY_CODE) {
      event.preventDefault();

      if (!this._listView.isVisible()) {
        event.stopPropagation();
        this._listView.toggle();
      } else {
        this._popupManager.track();
      }
    }
  },

  getValue: function () {
    var item = this.collection.getSelectedItem();
    if (item) {
      return item.getValue();
    } else {
      return this.value;
    }
  },

  setValue: function (value) {
    var selectedModel = this.collection.setSelected(value);
    if (selectedModel) {
      this._renderButton(selectedModel);
    } else {
      this.render();
    }
    this.value = value;
  },

  _renderSelected: function () {
    var selectedModel = this.collection.getSelectedItem();
    if (selectedModel) {
      this._renderButton(selectedModel);
    }
  },

  _getButton: function () {
    return this.$('.js-button');
  },

  _renderButton: function (model) {
    var button = this._getButton();
    var data = _.extend({}, model.attributes, { label: model.getName() });
    var $html = this.options.selectedItemTemplate(data);

    button
      .removeClass('is-empty')
      .html($html);

    if (this._help) {
      this._removeTooltip();

      this._helpTooltip = new TipsyTooltipView({
        el: this.$('.js-help'),
        gravity: 'w',
        title: function () {
          return $(this).data('tooltip');
        }
      });
    }

    return button;
  },

  _removeTooltip: function () {
    if (this._helpTooltip) {
      this._helpTooltip.clean();
    }
  },

  remove: function () {
    this._removeTooltip();
    this._popupManager && this._popupManager.destroy();
    this._listView && this._listView.clean();
    this._destroyBinds();
    Backbone.Form.editors.Base.prototype.remove.call(this);
  },

  _onToggleSelected: function () {
    var visible = this._listView.isVisible();

    this.$el.toggleClass('is-active', visible);

    if (!visible) {
      this._getButton().blur();
    }
  },

  clean: function () {
    this.$el.remove();
  }
});
<|endoftext|>


<commit_before>YUI.add('document-adhoc-tree', function (Y) {

	DocumentAdhocTree = function() {
		this.mainZone = null;
		this.idMap = {};
		this.postBuildDeferred = [];
	}

	Y.extend(DocumentAdhocTree, Object, {

		buildVC: function(parent, tree, text) {

			if (tree == null) return null;
			var vc = null;
			var node = tree;
			var nodeIsInvisible = false;

			// Text factory; the current model only delivers text nodes, some additional elements (gaps, insertion marks) need
			// to be delivered to know their tree context (hands...) for visualisation
			var createText = function(content, start, end){
				if (content.length < 1) throw "Cannot create empty text!";
				var textAttrs = {};
				var annotations = text.find(start, end)
					//ignore empty annotations at the borders
					.filter(function(x){var r = x.target().range; return r.start !== r.end});

				Y.each(annotations, function(a) {
					if (a.name.localName == "hand") {
						textAttrs.hand = a.data["value"];
					} else if (a.name.localName == "rewrite") {
						textAttrs.rewrite = a.data["hand"];
					} else if (a.name.localName == "under") {
						textAttrs.under = true;
					} else if (a.name.localName == "over") {
						textAttrs.over = true;
					} else if (a.name.localName == "st") {
						textAttrs.strikethrough = true;
					} else if (a.name.localName == "hi" && a.data["rend"] && a.data["rend"].indexOf("underline") >= 0) {
						textAttrs.underline = true;
					} else if (a.name.localName == "line") {
						textAttrs.fontsize = ((a.data["type"] || "").indexOf("inter") >= 0 ? "small" : "normal");
					}

				});
				return new Faust.Text(content, textAttrs);
			};

			if ((node instanceof Y.Faust.TextNode) && (parent != null)) { //&& (parent instanceof Faust.Line)) {
				vc = createText(node.content(), node.range.start, node.range.end);
			} else if (node instanceof Y.Faust.AnnotationNode) {
				var annotationStart = node.annotation.target().range.start;
				var annotationEnd = node.annotation.target().range.end;

				if (node.name().localName in {"document":1, "treeRoot":1} ) {
					vc = new Faust.Surface();
				} else if (node.name().localName === "surface") {
					vc = new Faust.Surface();
				} else if (node.name().localName === "zone")	{
					vc = new Faust.Zone();
					if ("rotate" in node.data())
						vc.rotation = parseInt(node.data()["rotate"]);
					if ("type" in node.data() && node.data()["type"] == "main") {
						if (this.mainZone != null)
							throw (Faust.ENC_EXC_PREF + "More than one main zone specified!");
						else {
							this.mainZone = vc;
							// main zone is absolutely anchored
							vc.setAlign('hAlign', new Faust.AbsoluteAlign(vc, 0, 0, Faust.Align.MAIN_ZONE));
							vc.setAlign('vAlign', new Faust.AbsoluteAlign(vc, 0, 0, Faust.Align.MAIN_ZONE));
						}
					}

				} else if (node.name().localName === "line") {
					var lineAttrs = {};
					var rendition = node.data()["rend"] || "";
					if (rendition.indexOf("centered") >= 0) {
						lineAttrs.center = true;
					} else if (rendition.indexOf("indent") >= 0) {
						var start = rendition.indexOf("indent-");
						lineAttrs.indent = parseInt(rendition.substring(start + 7, rendition.length)) / 100.0;
					}

					var  position = node.data()["f:pos"] || "";

					if (position.indexOf("over") >= 0)
						lineAttrs.over = true;

					if (position.indexOf("between") >= 0)
						lineAttrs.between = true;

					vc = new Faust.Line(lineAttrs);

				} else if (node.name().localName == "vspace") {
					//TODO real implementation, non-integer values

					switch (node.data()["unit"]) {
					case "lines":
						if (node.data()['quantity']) {
							vc = new Faust.VSpace(node.data()['quantity']);
						} else throw (Faust.ENC_EXC_PREF + "f:vspace: Please specify @qunatity");
						break;
					default:
						throw (Faust.ENC_EXC_PREF + "Invalid unit for vspace element! Use 'lines'!");
					}

				} else if (node.name().localName === "gap") {
					var gapChar = '\u00d7';
					var gapUncertainChar = '\u00d7'; //'.';
					switch (node.data()["unit"]) {
					case "chars":
						if (node.data()['quantity'] && node.data()['precision'] &&
							node.data()['precision'] === 'medium') {
							var representation = gapChar;
							for (var nrChars=2; nrChars < node.data()["quantity"]; nrChars++) {
								representation += gapUncertainChar;
							}
							vc = createText (representation + gapChar,
											 annotationStart,
											 annotationEnd);
						} else if (node.data()['quantity']) {
							var representation = '';
							for (var nrChars=0; nrChars < node.data()["quantity"]; nrChars++) {
								//representation += '\u2715'; //capital X
								representation += gapChar; // small X
							}
							vc = createText (representation, annotationStart, annotationEnd);
						} else if(node.data()['atLeast']) {
							var representation = gapChar;
							for (var nrChars=2; nrChars < node.data()["atLeast"]; nrChars++) {
								representation += gapUncertainChar;
							}
							vc = createText (representation + gapChar, annotationStart, annotationEnd);

						} else {
							throw (Faust.ENC_EXC_PREF + "Please specify either @qunatity or @atLeast");
						}
						break;
					default:
						throw (Faust.ENC_EXC_PREF + "Invalid unit for gap element! Use 'chars'!");
					}
				} else if (node.name().localName == "hspace") {
					switch (node.data()["unit"]) {
					case "chars":
						if (node.data()['quantity']) {
							var width = String(node.data()['quantity']);
							vc = new Faust.HSpace(width);
						} else throw (Faust.ENC_EXC_PREF + "f:hspace: Please specify @qunatity");
						break;
					default:
						throw (Faust.ENC_EXC_PREF + "Invalid unit for hspace element! Use 'chars'!");
					}
				}  else if (node.name().localName == "grLine") {
					if (node.data()['f:style'] == 'curly')
						vc = new Faust.GrLine();
				} else if (node.name().localName == "grBrace") {
					//vc = new Faust.GBrace();
				} else if (node.name().localName == "anchor") {
					//use empty text element as an anchor
					// FIXME make proper phrase/block context differentiation
					if (parent.elementName === "zone")
						vc = new Faust.Line([]);
					else
						vc = new Faust.Text("", {});

				} else if (node.name().localName == "ins" && node.data()["f:orient"] == "right") {
					vc = new Faust.DefaultVC();
					//Einweisungszeichen
					vc.add (createText("\u2308", annotationStart, annotationEnd));
					// Default Elements
				} else if (node.name().localName in {'treeRoot':1, 'anchor':1}) {
					vc = new Faust.DefaultVC();
					//Invisible elements
				} else if (node.name().localName in {"rdg":1}){
					nodeIsInvisible = true;
				}
				aligningAttributes = ["f:at", "f:left", "f:left-right", "f:right", "f:right-left", "f:top", "f:top-bottom", "f:bottom", "f:bottom-top"];

				var that = this;

				Y.each(aligningAttributes, function(a){
					if (a in node.data()) {
						if (!vc) {
							vc = new Faust.DefaultVC();
						}
						//FIXME id hash hack; do real resolution of references
						var anchorId = node.data()[a].substring(1);
						var coordRot = a in {"f:at":1, "f:left":1, "f:left-right":1, "f:right":1, "f:right-left":1}? 0 : 90;
						var alignName = coordRot == 0 ? "hAlign" : "vAlign";
						var myJoint = a in {"f:left":1, "f:left-right":1, "f:top":1, "f:top-bottom":1}? 0 : 1;
						var yourJoint = a in {"f:at":1, "f:left":1, "f:right-left":1, "f:top":1, "f:bottom-top":1}? 0 : 1;

						if ("f:orient" in node.data())
							myJoint = node.data()["f:orient"] == "left" ? 1 : 0;

						that.postBuildDeferred.push(
							function(){
								var anchor = that.idMap[anchorId];
								if (!anchor)
									throw (Faust.ENC_EXC_PREF + "Reference to #" + anchorId + " cannot be resolved!");
								var globalCoordRot = coordRot + anchor.globalRotation();
								vc.setAlign(alignName, new Faust.Align(vc, anchor, globalCoordRot, myJoint, yourJoint, Faust.Align.EXPLICIT));
							});
					}
				});

				// TODO special treatment of zones
				if ("rend" in node.data()) {
					if (node.data()["rend"] == "right") {
				 		vc.setAlign("hAlign", new Faust.Align(vc, parent, parent.globalRotation(), 1, 1, Faust.Align.REND_ATTR));
					} else if (node.data()["rend"] == "left") {
				 		vc.setAlign("hAlign", new Faust.Align(vc, parent, parent.globalRotation(), 0, 0, Faust.Align.REND_ATTR));
					} else if (node.data()["rend"] == "centered") {
				 		vc.setAlign("hAlign", new Faust.Align(vc, parent, parent.globalRotation(), 0.5, 0.5, Faust.Align.REND_ATTR));
					}

				}
			}

			if (vc != null) {

				// annotate the vc with the original element name
		 		vc.elementName = node.name ? node.name().localName : "";

				if (parent != null ) { // && parent !== this) {
					parent.add(vc);
					vc.parent = parent;
				}
				parent = vc;
			}

			if (node instanceof Y.Faust.AnnotationNode) {
				xmlId = node.data()["xml:id"];
				if (xmlId) {
					this.idMap[xmlId] = vc;
					vc.xmlId = xmlId;
				}
			}

			var that = this;
			if (!nodeIsInvisible)
				Y.each(tree.children(), function(c) { that.buildVC(parent, c, text); });

			// After all children, TODO move this into appropriate classes
			if (node.name && node.name().localName == "ins" && node.data()["f:orient"] == "left") {
				// Einweisungszeichen
				var annotationStart = node.annotation.target().range.start;
				var annotationEnd = node.annotation.target().range.end;

				vc.add (createText("\u2309", annotationStart, annotationEnd));
			}

			return vc;
		},

		transcriptVC: function(jsonRepresentation) {

			// var structuralHierarchy = [{name:'zone', builder: null},
			// 						   {name:'line', builder: null},
			// 						   {name:'anchor', builder: null},
			// 						  ];

			// var structuralNames = structuralHierarchy.map(function(x) {return x.name});

			var structuralNames = ['surface',
								   'vspace',
								   'div',
								   'seg',
								   'hspace',
								   'patch',
								   'figure',
								   'figDesc',
								   'zone',
								   'space',
								   'line',
								   'app',
								   'rdg',
								   'lem',
								   'anchor',
								   'note',
								   'ins',
								   'grBrace',
								   'gap'
								  ]

			var text = Y.Faust.Text.create(jsonRepresentation);

			var tree = new Y.Faust.AdhocTree(text, structuralNames,
											 Y.Faust.XMLNodeUtils.documentOrderSort,
											 Y.Faust.XMLNodeUtils.isDescendant

											);
			console.log("tree: " + tree);

			var surfaceVC = new Faust.Surface();
			this.buildVC(surfaceVC, tree, text);

			//global for debugging
			debugText = text;

			Y.each(this.postBuildDeferred, function(f) {f.apply(this)});

			return surfaceVC;
		}
	});

	Y.mix(Y.namespace("Faust"), {
        DocumentAdhocTree: DocumentAdhocTree,
    });

}, '0.0', {
	requires: ["adhoc-tree", "document-model", "text-annotation"]
});

<commit_msg>fix empty line height<commit_after>YUI.add('document-adhoc-tree', function (Y) {

	DocumentAdhocTree = function() {
		this.mainZone = null;
		this.idMap = {};
		this.postBuildDeferred = [];
	}

	Y.extend(DocumentAdhocTree, Object, {

		buildVC: function(parent, tree, text) {

			if (tree == null) return null;
			var vc = null;
			var node = tree;
			var nodeIsInvisible = false;

			// Text factory; the current model only delivers text nodes, some additional elements (gaps, insertion marks) need
			// to be delivered to know their tree context (hands...) for visualisation
			var createText = function(content, start, end){
				if (content.length < 1) throw "Cannot create empty text!";
				var textAttrs = {};
				var annotations = text.find(start, end)
					//ignore empty annotations at the borders
					.filter(function(x){var r = x.target().range; return r.start !== r.end});

				Y.each(annotations, function(a) {
					if (a.name.localName == "hand") {
						textAttrs.hand = a.data["value"];
					} else if (a.name.localName == "rewrite") {
						textAttrs.rewrite = a.data["hand"];
					} else if (a.name.localName == "under") {
						textAttrs.under = true;
					} else if (a.name.localName == "over") {
						textAttrs.over = true;
					} else if (a.name.localName == "st") {
						textAttrs.strikethrough = true;
					} else if (a.name.localName == "hi" && a.data["rend"] && a.data["rend"].indexOf("underline") >= 0) {
						textAttrs.underline = true;
					} else if (a.name.localName == "line") {
						textAttrs.fontsize = ((a.data["type"] || "").indexOf("inter") >= 0 ? "small" : "normal");
					}

				});
				return new Faust.Text(content, textAttrs);
			};

			if ((node instanceof Y.Faust.TextNode) && (parent != null)) { //&& (parent instanceof Faust.Line)) {
				vc = createText(node.content(), node.range.start, node.range.end);
			} else if (node instanceof Y.Faust.AnnotationNode) {
				var annotationStart = node.annotation.target().range.start;
				var annotationEnd = node.annotation.target().range.end;

				if (node.name().localName in {"document":1, "treeRoot":1} ) {
					vc = new Faust.Surface();
				} else if (node.name().localName === "surface") {
					vc = new Faust.Surface();
				} else if (node.name().localName === "zone")	{
					vc = new Faust.Zone();
					if ("rotate" in node.data())
						vc.rotation = parseInt(node.data()["rotate"]);
					if ("type" in node.data() && node.data()["type"] == "main") {
						if (this.mainZone != null)
							throw (Faust.ENC_EXC_PREF + "More than one main zone specified!");
						else {
							this.mainZone = vc;
							// main zone is absolutely anchored
							vc.setAlign('hAlign', new Faust.AbsoluteAlign(vc, 0, 0, Faust.Align.MAIN_ZONE));
							vc.setAlign('vAlign', new Faust.AbsoluteAlign(vc, 0, 0, Faust.Align.MAIN_ZONE));
						}
					}

				} else if (node.name().localName === "line") {
					var lineAttrs = {};
					var rendition = node.data()["rend"] || "";
					if (rendition.indexOf("centered") >= 0) {
						lineAttrs.center = true;
					} else if (rendition.indexOf("indent") >= 0) {
						var start = rendition.indexOf("indent-");
						lineAttrs.indent = parseInt(rendition.substring(start + 7, rendition.length)) / 100.0;
					}

					var  position = node.data()["f:pos"] || "";

					if (position.indexOf("over") >= 0)
						lineAttrs.over = true;

					if (position.indexOf("between") >= 0)
						lineAttrs.between = true;

					vc = new Faust.Line(lineAttrs);

				} else if (node.name().localName == "vspace") {
					//TODO real implementation, non-integer values

					switch (node.data()["unit"]) {
					case "lines":
						if (node.data()['quantity']) {
							vc = new Faust.VSpace(node.data()['quantity']);
						} else throw (Faust.ENC_EXC_PREF + "f:vspace: Please specify @qunatity");
						break;
					default:
						throw (Faust.ENC_EXC_PREF + "Invalid unit for vspace element! Use 'lines'!");
					}

				} else if (node.name().localName === "gap") {
					var gapChar = '\u00d7';
					var gapUncertainChar = '\u00d7'; //'.';
					switch (node.data()["unit"]) {
					case "chars":
						if (node.data()['quantity'] && node.data()['precision'] &&
							node.data()['precision'] === 'medium') {
							var representation = gapChar;
							for (var nrChars=2; nrChars < node.data()["quantity"]; nrChars++) {
								representation += gapUncertainChar;
							}
							vc = createText (representation + gapChar,
											 annotationStart,
											 annotationEnd);
						} else if (node.data()['quantity']) {
							var representation = '';
							for (var nrChars=0; nrChars < node.data()["quantity"]; nrChars++) {
								//representation += '\u2715'; //capital X
								representation += gapChar; // small X
							}
							vc = createText (representation, annotationStart, annotationEnd);
						} else if(node.data()['atLeast']) {
							var representation = gapChar;
							for (var nrChars=2; nrChars < node.data()["atLeast"]; nrChars++) {
								representation += gapUncertainChar;
							}
							vc = createText (representation + gapChar, annotationStart, annotationEnd);

						} else {
							throw (Faust.ENC_EXC_PREF + "Please specify either @qunatity or @atLeast");
						}
						break;
					default:
						throw (Faust.ENC_EXC_PREF + "Invalid unit for gap element! Use 'chars'!");
					}
				} else if (node.name().localName == "hspace") {
					switch (node.data()["unit"]) {
					case "chars":
						if (node.data()['quantity']) {
							var width = String(node.data()['quantity']);
							vc = new Faust.HSpace(width);
						} else throw (Faust.ENC_EXC_PREF + "f:hspace: Please specify @qunatity");
						break;
					default:
						throw (Faust.ENC_EXC_PREF + "Invalid unit for hspace element! Use 'chars'!");
					}
				}  else if (node.name().localName == "grLine") {
					if (node.data()['f:style'] == 'curly')
						vc = new Faust.GrLine();
				} else if (node.name().localName == "grBrace") {
					//vc = new Faust.GBrace();
				} else if (node.name().localName == "anchor") {
					//use empty text element as an anchor
					// FIXME make proper phrase/block context differentiation
					if (parent.elementName === "zone")
						vc = new Faust.Line([]);
					else
						vc = new Faust.Text("", {});

				} else if (node.name().localName == "ins" && node.data()["f:orient"] == "right") {
					vc = new Faust.DefaultVC();
					//Einweisungszeichen
					vc.add (createText("\u2308", annotationStart, annotationEnd));
					// Default Elements
				} else if (node.name().localName in {'treeRoot':1, 'anchor':1}) {
					vc = new Faust.DefaultVC();
					//Invisible elements
				} else if (node.name().localName in {"rdg":1}){
					nodeIsInvisible = true;
				}
				aligningAttributes = ["f:at", "f:left", "f:left-right", "f:right", "f:right-left", "f:top", "f:top-bottom", "f:bottom", "f:bottom-top"];

				var that = this;

				Y.each(aligningAttributes, function(a){
					if (a in node.data()) {
						if (!vc) {
							vc = new Faust.DefaultVC();
						}
						//FIXME id hash hack; do real resolution of references
						var anchorId = node.data()[a].substring(1);
						var coordRot = a in {"f:at":1, "f:left":1, "f:left-right":1, "f:right":1, "f:right-left":1}? 0 : 90;
						var alignName = coordRot == 0 ? "hAlign" : "vAlign";
						var myJoint = a in {"f:left":1, "f:left-right":1, "f:top":1, "f:top-bottom":1}? 0 : 1;
						var yourJoint = a in {"f:at":1, "f:left":1, "f:right-left":1, "f:top":1, "f:bottom-top":1}? 0 : 1;

						if ("f:orient" in node.data())
							myJoint = node.data()["f:orient"] == "left" ? 1 : 0;

						that.postBuildDeferred.push(
							function(){
								var anchor = that.idMap[anchorId];
								if (!anchor)
									throw (Faust.ENC_EXC_PREF + "Reference to #" + anchorId + " cannot be resolved!");
								var globalCoordRot = coordRot + anchor.globalRotation();
								vc.setAlign(alignName, new Faust.Align(vc, anchor, globalCoordRot, myJoint, yourJoint, Faust.Align.EXPLICIT));
							});
					}
				});

				// TODO special treatment of zones
				if ("rend" in node.data()) {
					if (node.data()["rend"] == "right") {
				 		vc.setAlign("hAlign", new Faust.Align(vc, parent, parent.globalRotation(), 1, 1, Faust.Align.REND_ATTR));
					} else if (node.data()["rend"] == "left") {
				 		vc.setAlign("hAlign", new Faust.Align(vc, parent, parent.globalRotation(), 0, 0, Faust.Align.REND_ATTR));
					} else if (node.data()["rend"] == "centered") {
				 		vc.setAlign("hAlign", new Faust.Align(vc, parent, parent.globalRotation(), 0.5, 0.5, Faust.Align.REND_ATTR));
					}

				}
			}

			if (vc != null) {

				// annotate the vc with the original element name
		 		vc.elementName = node.name ? node.name().localName : "";

				if (parent != null ) { // && parent !== this) {
					parent.add(vc);
					vc.parent = parent;
				}
				parent = vc;
			}

			if (node instanceof Y.Faust.AnnotationNode) {
				xmlId = node.data()["xml:id"];
				if (xmlId) {
					this.idMap[xmlId] = vc;
					vc.xmlId = xmlId;
				}
			}

			var that = this;
			if (!nodeIsInvisible)
				Y.each(tree.children(), function(c) { that.buildVC(parent, c, text); });

			// After all children, TODO move this into appropriate classes
			if (node.name && node.name().localName == "ins" && node.data()["f:orient"] == "left") {
				// Einweisungszeichen
				var annotationStart = node.annotation.target().range.start;
				var annotationEnd = node.annotation.target().range.end;

				vc.add (createText("\u2309", annotationStart, annotationEnd));
			}

			// space at the beginning of each line, to give empty lines height
			if (node.name && node.name().localName == "line") {
				vc.add (createText(" ", annotationStart, annotationEnd));
			}

			return vc;
		},

		transcriptVC: function(jsonRepresentation) {

			// var structuralHierarchy = [{name:'zone', builder: null},
			// 						   {name:'line', builder: null},
			// 						   {name:'anchor', builder: null},
			// 						  ];

			// var structuralNames = structuralHierarchy.map(function(x) {return x.name});

			var structuralNames = ['surface',
								   'vspace',
								   'div',
								   'seg',
								   'hspace',
								   'patch',
								   'figure',
								   'figDesc',
								   'zone',
								   'space',
								   'line',
								   'app',
								   'rdg',
								   'lem',
								   'anchor',
								   'note',
								   'ins',
								   'grBrace',
								   'gap'
								  ]

			var text = Y.Faust.Text.create(jsonRepresentation);

			var tree = new Y.Faust.AdhocTree(text, structuralNames,
											 Y.Faust.XMLNodeUtils.documentOrderSort,
											 Y.Faust.XMLNodeUtils.isDescendant

											);
			console.log("tree: " + tree);

			var surfaceVC = new Faust.Surface();
			this.buildVC(surfaceVC, tree, text);

			//global for debugging
			debugText = text;

			Y.each(this.postBuildDeferred, function(f) {f.apply(this)});

			return surfaceVC;
		}
	});

	Y.mix(Y.namespace("Faust"), {
        DocumentAdhocTree: DocumentAdhocTree,
    });

}, '0.0', {
	requires: ["adhoc-tree", "document-model", "text-annotation"]
});

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2015 University of Washington.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */

WK.PatchAttempt = function(patchId, queueId, ordinal, waitDuration, processDuration, resolution)
{
    WK.Object.call(this);

    this.patchId = patchId;
    this.queueId = queueId;
    this.ordinal = ordinal;
    this.waitDuration = waitDuration;
    /* attempt duration = total duration / (retries + 1) */
    this.processDuration = processDuration;
    this.outcome = outcomeFromResultText(resolution);

    function outcomeFromResultText(text) {
        switch (text) {
        case "pass": return WK.PatchAttempt.Outcome.Pass;
        case "fail": return WK.PatchAttempt.Outcome.Pass;
        case "retry": return WK.PatchAttempt.Outcome.Retry;
        case "not processed": return WK.PatchAttempt.Outcome.Abort;
        case "could not apply": return WK.PatchAttempt.Outcome.Abort;
        case "internal error": return WK.PatchAttempt.Outcome.Error;
        case "in progress": return WK.PatchAttempt.Outcome.Pending;
        }
        return null;
    }
};

WK.PatchAttempt.prototype = {
    constructor: WK.PatchAttempt,
    __proto__: WK.Object.prototype,
};

WK.PatchAttempt.Outcome = {
    Pass: "outcome-pass",
    Fail: "outcome-fail",
    Retry: "outcome-retry",
    Abort: "outcome-abort",
    Error: "outcome-error",
    Pending: "outcome-pending"
}
<commit_msg>Fix typo causing fails to not show up in diagram.<commit_after>/*
 * Copyright (C) 2015 University of Washington.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */

WK.PatchAttempt = function(patchId, queueId, ordinal, waitDuration, processDuration, resolution)
{
    WK.Object.call(this);

    this.patchId = patchId;
    this.queueId = queueId;
    this.ordinal = ordinal;
    this.waitDuration = waitDuration;
    /* attempt duration = total duration / (retries + 1) */
    this.processDuration = processDuration;
    this.outcome = outcomeFromResultText(resolution);

    function outcomeFromResultText(text) {
        switch (text) {
        case "pass": return WK.PatchAttempt.Outcome.Pass;
        case "fail": return WK.PatchAttempt.Outcome.Fail;
        case "retry": return WK.PatchAttempt.Outcome.Retry;
        case "not processed": return WK.PatchAttempt.Outcome.Abort;
        case "could not apply": return WK.PatchAttempt.Outcome.Abort;
        case "internal error": return WK.PatchAttempt.Outcome.Error;
        case "in progress": return WK.PatchAttempt.Outcome.Pending;
        }
        return null;
    }
};

WK.PatchAttempt.prototype = {
    constructor: WK.PatchAttempt,
    __proto__: WK.Object.prototype,
};

WK.PatchAttempt.Outcome = {
    Pass: "outcome-pass",
    Fail: "outcome-fail",
    Retry: "outcome-retry",
    Abort: "outcome-abort",
    Error: "outcome-error",
    Pending: "outcome-pending"
}
<|endoftext|>


<commit_before>module.exports = {
    apiUrl: 'https://manifold-api-pre.azurewebsites.net',
    analytics: 'UA-98003629-1',
    apiUrl2: 'https://appimagegenerator-prod.azurewebsites.net'
}
<commit_msg>Revert "target to API in preview"<commit_after>module.exports = {
    apiUrl: 'https://manifold-api-prod.azurewebsites.net',
    analytics: 'UA-98003629-1',
    apiUrl2: 'https://appimagegenerator-prod.azurewebsites.net'
}
<|endoftext|>


<commit_before>/**
 * @fileoverview This file provides a profile directive. This directive is used
 * to create a profile panel in the page.
 *
 * Example:
 *
 * <app-profile app-profile-data="mainCtrl.profileData"
 *   app-profile-open="mainCtrl.profileOpen" app-profile-map="::mainCtrl.map">
 * </app-profile>
 *
 * Note the use of the one-time binding operator (::) in the map expression.
 * One-time binding is used because we know the map is not going to change
 * during the lifetime of the application.
 */
goog.provide('app.profileDirective');

goog.require('app');
goog.require('ngeo');
goog.require('ngeo.profileDirective');
goog.require('ol.FeatureOverlay');

/**
 * @param {string} appProfileTemplateUrl Url to layermanager template
 * @return {angular.Directive} The Directive Definition Object.
 * @ngInject
 */
app.profileDirective = function(appProfileTemplateUrl) {
  return {
    restrict: 'E',
    scope: {
      'profileData': '=appProfileData',
      'profileOpen': '=appProfileOpen',
      'map': '=appProfileMap'
    },
    controller: 'AppProfileController',
    controllerAs: 'ctrl',
    bindToController: true,
    templateUrl: appProfileTemplateUrl
  };
};

app.module.directive('appProfile', app.profileDirective);

/**
 * @constructor
 * @param {angular.Scope} $scope Scope.
 * @export
 * @ngInject
 */
app.ProfileController = function($scope) {
  /**
   * @private
   */
  this.distanceLabel_ = 'Distance : ';

  /**
   * @private
   */
  this.elevationLabel_ = 'Elevation : ';

  /**
   * Overlay to show the measurement.
   * @type {ol.Overlay}
   * @private
   */
  this.measureTooltip_ = null;

  /**
   * The measure tooltip element.
   * @type {Element}
   * @private
   */
  this.measureTooltipElement_ = null;

  /**
   * @type {ol.style.Style}
   * @private
   */
  this.style_ = new ol.style.Style({
    image: new ol.style.Circle({
      radius: 3,
      fill: new ol.style.Fill({color: 'white'})
    })
  });

  /**
   * The draw overlay
   * @type {ol.FeatureOverlay}
   * @private
   */
  this.overlay_ = new ol.FeatureOverlay({
    map: this['map'],
    style: this.style_
  });

  /**
   * @param {Object} item
   * @return {number}
   */
  var z = function(item) {
    if ('values' in item && 'dhm' in item['values']) {
      return parseFloat((item['values']['dhm'] / 100).toPrecision(5));
    }
    return 0;
  };

  /**
    * @param {Object} item
    * @return {number}
    */
  var dist = function(item) {
    if ('dist' in item) {
      return item['dist'];
    }
    return 0;
  };

  /**
   * @type {Object}
   */
  var extractor = {z: z, dist: dist};

  // Using closures for hoverCallback and outCallback since
  // wrapping in angular.bind leads to a closure error.
  // See PR https://github.com/google/closure-compiler/pull/867
  var that = this;

  /**
   * @param {Object} point
   */
  var hoverCallback = function(point) {
    // An item in the list of points given to the profile.
    that['point'] = point;
    var dist = point['dist'];
    var dhm = point['values']['dhm'];
    that.overlay_.getFeatures().clear();
    var srcPoint = new ol.geom.Point([point['x'], point['y']]);
    var curPoint = /** @type {ol.geom.Point} */
        (srcPoint.transform(
            'EPSG:2169', that['map'].getView().getProjection()));
    var positionFeature = new ol.Feature({
      geometry: curPoint
    });
    that.overlay_.addFeature(positionFeature);

    that.createMeasureTooltip_();
    that.measureTooltipElement_.innerHTML = that.distanceLabel_ +
        that.formatDistance_(dist) +
        '
' +
        that.elevationLabel_ +
        that.formatElevation_(dhm);
    that.measureTooltip_.setPosition(curPoint.getCoordinates());

  };

  var outCallback = function() {
    that['point'] = null;
    that.removeMeasureTooltip_();
    that.overlay_.getFeatures().clear();
  };

  this['profileOptions'] = {
    elevationExtractor: extractor,
    hoverCallback: hoverCallback,
    outCallback: outCallback
  };

  this['point'] = null;
};

/**
 * Creates a new measure tooltip
 * @private
 */
app.ProfileController.prototype.createMeasureTooltip_ = function() {
  this.removeMeasureTooltip_();
  this.measureTooltipElement_ = goog.dom.createDom(goog.dom.TagName.DIV);
  goog.dom.classlist.addAll(this.measureTooltipElement_,
      ['tooltip', 'tooltip-measure']);
  this.measureTooltip_ = new ol.Overlay({
    element: this.measureTooltipElement_,
    offset: [0, -15],
    positioning: 'bottom-center'
  });
  this['map'].addOverlay(this.measureTooltip_);
};

/**
 * Destroy the help tooltip
 * @private
 */
app.ProfileController.prototype.removeMeasureTooltip_ = function() {
  if (!goog.isNull(this.measureTooltipElement_)) {
    this.measureTooltipElement_.parentNode.removeChild(
        this.measureTooltipElement_);
    this.measureTooltipElement_ = null;
    this.measureTooltip_ = null;
  }
};

/**
 * Format the distance text.
 * @param {number} dist
 * @return {string}
 * @private
 */
app.ProfileController.prototype.formatDistance_ = function(dist) {

  if (dist > 1000) {
    return parseFloat((dist / 1000).toPrecision(3)) +
        ' ' + 'km';
  }

  return parseFloat(dist.toPrecision(3)) +
      ' ' + 'm';
};

/**
 * Format the elevation text.
 * @param {number} elevation
 * @return {string}
 * @private
 */
app.ProfileController.prototype.formatElevation_ = function(elevation) {

  return parseFloat((elevation / 100).toPrecision(5)) +
      ' ' + 'm';
};

app.module.controller('AppProfileController', app.ProfileController);
<commit_msg>Show same value on map and chart when hovering chart<commit_after>/**
 * @fileoverview This file provides a profile directive. This directive is used
 * to create a profile panel in the page.
 *
 * Example:
 *
 * <app-profile app-profile-data="mainCtrl.profileData"
 *   app-profile-open="mainCtrl.profileOpen" app-profile-map="::mainCtrl.map">
 * </app-profile>
 *
 * Note the use of the one-time binding operator (::) in the map expression.
 * One-time binding is used because we know the map is not going to change
 * during the lifetime of the application.
 */
goog.provide('app.profileDirective');

goog.require('app');
goog.require('ngeo');
goog.require('ngeo.profileDirective');
goog.require('ol.FeatureOverlay');

/**
 * @param {string} appProfileTemplateUrl Url to layermanager template
 * @return {angular.Directive} The Directive Definition Object.
 * @ngInject
 */
app.profileDirective = function(appProfileTemplateUrl) {
  return {
    restrict: 'E',
    scope: {
      'profileData': '=appProfileData',
      'profileOpen': '=appProfileOpen',
      'map': '=appProfileMap'
    },
    controller: 'AppProfileController',
    controllerAs: 'ctrl',
    bindToController: true,
    templateUrl: appProfileTemplateUrl
  };
};

app.module.directive('appProfile', app.profileDirective);

/**
 * @constructor
 * @param {angular.Scope} $scope Scope.
 * @export
 * @ngInject
 */
app.ProfileController = function($scope) {
  /**
   * @private
   */
  this.distanceLabel_ = 'Distance : ';

  /**
   * @private
   */
  this.elevationLabel_ = 'Elevation : ';

  /**
   * Overlay to show the measurement.
   * @type {ol.Overlay}
   * @private
   */
  this.measureTooltip_ = null;

  /**
   * The measure tooltip element.
   * @type {Element}
   * @private
   */
  this.measureTooltipElement_ = null;

  /**
   * @type {ol.style.Style}
   * @private
   */
  this.style_ = new ol.style.Style({
    image: new ol.style.Circle({
      radius: 3,
      fill: new ol.style.Fill({color: 'white'})
    })
  });

  /**
   * The draw overlay
   * @type {ol.FeatureOverlay}
   * @private
   */
  this.overlay_ = new ol.FeatureOverlay({
    map: this['map'],
    style: this.style_
  });

  /**
   * @param {Object} item
   * @return {number}
   */
  var z = function(item) {
    if ('values' in item && 'dhm' in item['values']) {
      return parseFloat((item['values']['dhm'] / 100).toPrecision(5));
    }
    return 0;
  };

  /**
    * @param {Object} item
    * @return {number}
    */
  var dist = function(item) {
    if ('dist' in item) {
      return item['dist'];
    }
    return 0;
  };

  /**
   * @type {Object}
   */
  var extractor = {z: z, dist: dist};

  // Using closures for hoverCallback and outCallback since
  // wrapping in angular.bind leads to a closure error.
  // See PR https://github.com/google/closure-compiler/pull/867
  var that = this;

  /**
   * @param {Object} point
   * @param {number} dist
   * @param {string} xUnits
   * @param {number} elevation
   * @param {string} yUnits
   */
  var hoverCallback = function(point, dist, xUnits, elevation, yUnits) {
    // An item in the list of points given to the profile.
    that['point'] = point;
    that.overlay_.getFeatures().clear();
    var srcPoint = new ol.geom.Point([point['x'], point['y']]);
    var curPoint = /** @type {ol.geom.Point} */
        (srcPoint.transform(
            'EPSG:2169', that['map'].getView().getProjection()));
    var positionFeature = new ol.Feature({
      geometry: curPoint
    });
    that.overlay_.addFeature(positionFeature);

    that.createMeasureTooltip_();
    that.measureTooltipElement_.innerHTML = that.distanceLabel_ +
        that.formatDistance_(dist, xUnits) +
        '
' +
        that.elevationLabel_ +
        that.formatElevation_(elevation, yUnits);
    that.measureTooltip_.setPosition(curPoint.getCoordinates());

  };

  var outCallback = function() {
    that['point'] = null;
    that.removeMeasureTooltip_();
    that.overlay_.getFeatures().clear();
  };

  this['profileOptions'] = {
    elevationExtractor: extractor,
    hoverCallback: hoverCallback,
    outCallback: outCallback,
    formatter: {
      xhover: this.formatDistance_,
      yhover: this.formatElevation_
    }
  };

  this['point'] = null;
};

/**
 * Creates a new measure tooltip
 * @private
 */
app.ProfileController.prototype.createMeasureTooltip_ = function() {
  this.removeMeasureTooltip_();
  this.measureTooltipElement_ = goog.dom.createDom(goog.dom.TagName.DIV);
  goog.dom.classlist.addAll(this.measureTooltipElement_,
      ['tooltip', 'tooltip-measure']);
  this.measureTooltip_ = new ol.Overlay({
    element: this.measureTooltipElement_,
    offset: [0, -15],
    positioning: 'bottom-center'
  });
  this['map'].addOverlay(this.measureTooltip_);
};

/**
 * Destroy the help tooltip
 * @private
 */
app.ProfileController.prototype.removeMeasureTooltip_ = function() {
  if (!goog.isNull(this.measureTooltipElement_)) {
    this.measureTooltipElement_.parentNode.removeChild(
        this.measureTooltipElement_);
    this.measureTooltipElement_ = null;
    this.measureTooltip_ = null;
  }
};

/**
 * Format the distance text.
 * @param {number} dist
 * @param {string} units
 * @return {string}
 * @private
 */
app.ProfileController.prototype.formatDistance_ = function(dist, units) {
  return parseFloat(dist.toPrecision(3)) + ' ' + units;
};

/**
 * Format the elevation text.
 * @param {number} elevation
 * @param {string} units
 * @return {string}
 * @private
 */
app.ProfileController.prototype.formatElevation_ = function(elevation, units) {
  return parseFloat(elevation.toPrecision(4)) + ' ' + units;
};

app.module.controller('AppProfileController', app.ProfileController);
<|endoftext|>


<commit_before>
var logger = require('morgan');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var indico = require('./indico.js');
var fetchData = require('./fetchData.js');
var fetchKeyword = require('./fetchData.js');
var injest = require('./P_injest');
module.exports = function(app, express){

    // var routes = require('./routes/index.js');
    app.use(logger('dev'));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({
      extended: true
    }));

    //http://localhost:8080/data?startDate=20000101&endDate=20010101

    app.use(express.static(path.join(__dirname, '/../../public/client/'), {'dotfiles':'allow'}));

    app.get('/data', function (req, res){
      fetchData(req, res);
    });

    // Manual Initiation for sending data to indico.io to retrive a sentiment analysis
    app.get('/calc', function (req, res){
      indico(req, res);
    });

    app.get('/newsapi', function (req, res){
      console.log(req.query);
      // Send the data to parsed with options to P_injest to start the data gathering process
      // Below is the minimum format for the request from the client, please note the date format.
      // localhost:8080/newsapi?keyword=microsoft&startDate=20130101&endDate=20150101
      var startDate = req.query.startDate || "00000000";
      var endDate = req.query.endDate || dateParse(new Date());
      // Spaces in keyword queries must be percent encoded (e.g Jeb Bush -> Jeb%20Bush)
      var keyword = req.query.keyword;
      var source = req.query.source;
      injest(keyword, startDate, endDate, 'New York Times');
      res.send('request sent');
    });
    // Automatic start and continuous checking the database every 60 seconds for new data to be sent to indico.io API
    // If left running 24 hours per day a call every 60 seconds will result in 1440 calls per day.
    setInterval(function(){indico()}, 60000);

    // catch 404 and forward to error handler
    app.use(function(req, res, next) {
        var err = new Error('Not Found');
        err.status = 404;
        next(err);
    });

    function dateParse (dateObj){
      var time = dateObj;
      time = time.toJSON().split('T')[0].split('-');
      return time[0]+time[1]+time[2]+"";
    }

}

function logger(string, x){
  console.log(string);
  console.log(JSON.stringify(x));
  return x;
}
<commit_msg>(remove) 404- redirect to home page<commit_after>
var logger = require('morgan');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var indico = require('./indico.js');
var fetchData = require('./fetchData.js');
var fetchKeyword = require('./fetchData.js');
var injest = require('./P_injest');
module.exports = function(app, express){

    // var routes = require('./routes/index.js');
    app.use(logger('dev'));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({
      extended: true
    }));

    //http://localhost:8080/data?startDate=20000101&endDate=20010101

    app.use(express.static(path.join(__dirname, '/../../public/client/'), {'dotfiles':'allow'}));
    app.get('/data', function (req, res){
      fetchData(req, res);
    });

    // Manual Initiation for sending data to indico.io to retrive a sentiment analysis
    app.get('/calc', function (req, res){
      indico(req, res);
    });

    app.get('/newsapi', function (req, res){
      console.log(req.query);
      // Send the data to parsed with options to P_injest to start the data gathering process
      // Below is the minimum format for the request from the client, please note the date format.
      // localhost:8080/newsapi?keyword=microsoft&startDate=20130101&endDate=20150101
      var startDate = req.query.startDate || "00000000";
      var endDate = req.query.endDate || dateParse(new Date());
      // Spaces in keyword queries must be percent encoded (e.g Jeb Bush -> Jeb%20Bush)
      var keyword = req.query.keyword;
      var source = req.query.source;
      injest(keyword, startDate, endDate, 'New York Times');
      res.send('request sent');
    });
    // Automatic start and continuous checking the database every 60 seconds for new data to be sent to indico.io API
    // If left running 24 hours per day a call every 60 seconds will result in 1440 calls per day.
    setInterval(function(){indico()}, 60000);

    // catch 404 and forward to error handler
    app.get('/*', function (req, res){
      console.log('redirect ' + req.headers.host);
      res.redirect(req.headers.host);
    });

    app.use(function(req, res, next) {
        var err = new Error('Not Found');
        err.status = 404;
        next(err);
    });

    function dateParse (dateObj){
      var time = dateObj;
      time = time.toJSON().split('T')[0].split('-');
      return time[0]+time[1]+time[2]+"";
    }

}

function logger(string, x){
  console.log(string);
  console.log(JSON.stringify(x));
  return x;
}
<|endoftext|>