<commit_before>jQuery.support = (function() {

	var support,
		all,
		a,
		select,
		opt,
		input,
		fragment,
		eventName,
		i,
		isSupported,
		div = document.createElement("div");

	// Preliminary tests
	div.setAttribute( "className", "t" );
	div.innerHTML = "  <link/>

a<input type='checkbox'/>";

	all = div.getElementsByTagName("*");
	a = div.getElementsByTagName("a")[ 0 ];

	// Can't get basic test support
	if ( !all || !all.length || !a ) {
		return {};
	}

	// First batch of supports tests
	select = document.createElement("select");
	opt = select.appendChild( document.createElement("option") );
	input = div.getElementsByTagName("input")[ 0 ];

	support = {
		// IE strips leading whitespace when .innerHTML is used
		leadingWhitespace: ( div.firstChild.nodeType === 3 ),

		// Make sure that tbody elements aren't automatically inserted
		// IE will insert them into empty tables
		tbody: !div.getElementsByTagName("tbody").length,

		// Make sure that link elements get serialized correctly by innerHTML
		// This requires a wrapper element in IE
		htmlSerialize: !!div.getElementsByTagName("link").length,

		// Get the style information from getAttribute
		// (IE uses .cssText instead)
		style: /top/.test( a.getAttribute("style") ),

		// Make sure that URLs aren't manipulated
		// (IE normalizes it by default)
		hrefNormalized: ( a.getAttribute("href") === "/a" ),

		// Make sure that element opacity exists
		// (IE uses filter instead)
		// Use a regex to work around a WebKit issue. See #5145
		opacity: /^0.5/.test( a.style.opacity ),

		// Verify style float existence
		// (IE uses styleFloat instead of cssFloat)
		cssFloat: !!a.style.cssFloat,

		// Make sure that if no value is specified for a checkbox
		// that it defaults to "on".
		// (WebKit defaults to "" instead)
		checkOn: ( input.value === "on" ),

		// Make sure that a selected-by-default option has a working selected property.
		// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
		optSelected: opt.selected,

		// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
		getSetAttribute: div.className !== "t",

		// Tests for enctype support on a form(#6743)
		enctype: !!document.createElement("form").enctype,

		// Makes sure cloning an html5 element does not cause problems
		// Where outerHTML is undefined, this still works
		html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",

		// jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode
		boxModel: ( document.compatMode === "CSS1Compat" ),

		// Will be defined later
		submitBubbles: true,
		changeBubbles: true,
		focusinBubbles: false,
		deleteExpando: true,
		noCloneEvent: true,
		inlineBlockNeedsLayout: false,
		shrinkWrapBlocks: false,
		reliableMarginRight: true,
		pixelMargin: true,
		boxSizingReliable: true,
		pixelPosition: false
	};

	// Make sure checked status is properly cloned
	input.checked = true;
	support.noCloneChecked = input.cloneNode( true ).checked;

	// Make sure that the options inside disabled selects aren't marked as disabled
	// (WebKit marks them as disabled)
	select.disabled = true;
	support.optDisabled = !opt.disabled;

	// Test to see if it's possible to delete an expando from an element
	// Fails in Internet Explorer
	try {
		delete div.test;
	} catch( e ) {
		support.deleteExpando = false;
	}

	if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
		div.attachEvent( "onclick", function() {
			// Cloning a node shouldn't copy over any
			// bound event handlers (IE does this)
			support.noCloneEvent = false;
		});
		div.cloneNode( true ).fireEvent("onclick");
	}

	// Check if a radio maintains its value
	// after being appended to the DOM
	input = document.createElement("input");
	input.value = "t";
	input.setAttribute( "type", "radio" );
	support.radioValue = input.value === "t";

	input.setAttribute( "checked", "checked" );

	// #11217 - WebKit loses check when the name is after the checked attribute
	input.setAttribute( "name", "t" );

	div.appendChild( input );
	fragment = document.createDocumentFragment();
	fragment.appendChild( div.lastChild );

	// WebKit doesn't clone checked state correctly in fragments
	support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;

	// Check if a disconnected checkbox will retain its checked
	// value of true after appended to the DOM (IE6/7)
	support.appendChecked = input.checked;

	fragment.removeChild( input );
	fragment.appendChild( div );

	// Technique from Juriy Zaytsev
	// http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
	// We only care about the case where non-standard event systems
	// are used, namely in IE. Short-circuiting here helps us to
	// avoid an eval call (in setAttribute) which can cause CSP
	// to go haywire. See: https://developer.mozilla.org/en/Security/CSP
	if ( div.attachEvent ) {
		for ( i in {
			submit: true,
			change: true,
			focusin: true
		}) {
			eventName = "on" + i;
			isSupported = ( eventName in div );
			if ( !isSupported ) {
				div.setAttribute( eventName, "return;" );
				isSupported = ( typeof div[ eventName ] === "function" );
			}
			support[ i + "Bubbles" ] = isSupported;
		}
	}

	// Run tests that need a body at doc ready
	jQuery(function() {
		var container, div, tds, marginDiv,
			divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;",
			body = document.getElementsByTagName("body")[0];

		if ( !body ) {
			// Return for frameset docs that don't have a body
			return;
		}

		container = document.createElement("div");
		container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px";
		body.insertBefore( container, body.firstChild );

		// Construct the test element
		div = document.createElement("div");
		container.appendChild( div );

		// Check if table cells still have offsetWidth/Height when they are set
		// to display:none and there are still other visible table cells in a
		// table row; if so, offsetWidth/Height are not reliable for use when
		// determining if an element has been hidden directly using
		// display:none (it is still safe to use offsets if a parent element is
		// hidden; don safety goggles and see bug #4512 for more information).
		// (only IE 8 fails this test)
		div.innerHTML = "

	t

";
		tds = div.getElementsByTagName("td");
		isSupported = ( tds[ 0 ].offsetHeight === 0 );

		tds[ 0 ].style.display = "";
		tds[ 1 ].style.display = "none";

		// Check if empty table cells still have offsetWidth/Height
		// (IE <= 8 fail this test)
		support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );

		// Check box-sizing and margin behavior
		div.innerHTML = "";
		div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";
		support.boxSizing = ( div.offsetWidth === 4 );
		support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 );

		// NOTE: To any future maintainer, window.getComputedStyle was used here
		// instead of getComputedStyle because it gave a better gzip size.
		// The difference between window.getComputedStyle and getComputedStyle is
		// 7 bytes
		if ( window.getComputedStyle ) {
			support.pixelMargin = ( window.getComputedStyle( div, null ) || {} ).marginTop !== "1%";
			support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
			support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";

			// Check if div with explicit width and no margin-right incorrectly
			// gets computed margin-right based on width of container. For more
			// info see bug #3333
			// Fails in WebKit before Feb 2011 nightlies
			// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
			marginDiv = document.createElement("div");
			marginDiv.style.cssText = div.style.cssText = divReset;
			marginDiv.style.marginRight = marginDiv.style.width = "0";
			div.style.width = "1px";
			div.appendChild( marginDiv );
			support.reliableMarginRight =
				!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
		}

		if ( typeof div.style.zoom !== "undefined" ) {
			// Check if natively block-level elements act like inline-block
			// elements when setting their display to 'inline' and giving
			// them layout
			// (IE < 8 does this)
			div.innerHTML = "";
			div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
			support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );

			// Check if elements with layout shrink-wrap their children
			// (IE 6 does this)
			div.style.display = "block";
			div.style.overflow = "visible";
			div.innerHTML = "

";
			support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );

			container.style.zoom = 1;
		}

		// Null elements to avoid leaks in IE
		body.removeChild( container );
		container = div = tds = marginDiv = null;
	});

	// Null elements to avoid leaks in IE
	fragment.removeChild( div );
	all = a = select = opt = input = fragment = div = null;

	return support;
})();
<commit_msg>Fix #11757. IE 6/7 can't clean up circular DOM-JS refs.<commit_after>jQuery.support = (function() {

	var support,
		all,
		a,
		select,
		opt,
		input,
		fragment,
		eventName,
		i,
		isSupported,
		clickFn,
		div = document.createElement("div");

	// Preliminary tests
	div.setAttribute( "className", "t" );
	div.innerHTML = "  <link/>

a<input type='checkbox'/>";

	all = div.getElementsByTagName("*");
	a = div.getElementsByTagName("a")[ 0 ];

	// Can't get basic test support
	if ( !all || !all.length || !a ) {
		return {};
	}

	// First batch of supports tests
	select = document.createElement("select");
	opt = select.appendChild( document.createElement("option") );
	input = div.getElementsByTagName("input")[ 0 ];

	support = {
		// IE strips leading whitespace when .innerHTML is used
		leadingWhitespace: ( div.firstChild.nodeType === 3 ),

		// Make sure that tbody elements aren't automatically inserted
		// IE will insert them into empty tables
		tbody: !div.getElementsByTagName("tbody").length,

		// Make sure that link elements get serialized correctly by innerHTML
		// This requires a wrapper element in IE
		htmlSerialize: !!div.getElementsByTagName("link").length,

		// Get the style information from getAttribute
		// (IE uses .cssText instead)
		style: /top/.test( a.getAttribute("style") ),

		// Make sure that URLs aren't manipulated
		// (IE normalizes it by default)
		hrefNormalized: ( a.getAttribute("href") === "/a" ),

		// Make sure that element opacity exists
		// (IE uses filter instead)
		// Use a regex to work around a WebKit issue. See #5145
		opacity: /^0.5/.test( a.style.opacity ),

		// Verify style float existence
		// (IE uses styleFloat instead of cssFloat)
		cssFloat: !!a.style.cssFloat,

		// Make sure that if no value is specified for a checkbox
		// that it defaults to "on".
		// (WebKit defaults to "" instead)
		checkOn: ( input.value === "on" ),

		// Make sure that a selected-by-default option has a working selected property.
		// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
		optSelected: opt.selected,

		// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
		getSetAttribute: div.className !== "t",

		// Tests for enctype support on a form(#6743)
		enctype: !!document.createElement("form").enctype,

		// Makes sure cloning an html5 element does not cause problems
		// Where outerHTML is undefined, this still works
		html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",

		// jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode
		boxModel: ( document.compatMode === "CSS1Compat" ),

		// Will be defined later
		submitBubbles: true,
		changeBubbles: true,
		focusinBubbles: false,
		deleteExpando: true,
		noCloneEvent: true,
		inlineBlockNeedsLayout: false,
		shrinkWrapBlocks: false,
		reliableMarginRight: true,
		pixelMargin: true,
		boxSizingReliable: true,
		pixelPosition: false
	};

	// Make sure checked status is properly cloned
	input.checked = true;
	support.noCloneChecked = input.cloneNode( true ).checked;

	// Make sure that the options inside disabled selects aren't marked as disabled
	// (WebKit marks them as disabled)
	select.disabled = true;
	support.optDisabled = !opt.disabled;

	// Test to see if it's possible to delete an expando from an element
	// Fails in Internet Explorer
	try {
		delete div.test;
	} catch( e ) {
		support.deleteExpando = false;
	}

	if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
		div.attachEvent( "onclick", clickFn = function() {
			// Cloning a node shouldn't copy over any
			// bound event handlers (IE does this)
			support.noCloneEvent = false;
		});
		div.cloneNode( true ).fireEvent("onclick");
		div.detachEvent( "onclick", clickFn );
	}

	// Check if a radio maintains its value
	// after being appended to the DOM
	input = document.createElement("input");
	input.value = "t";
	input.setAttribute( "type", "radio" );
	support.radioValue = input.value === "t";

	input.setAttribute( "checked", "checked" );

	// #11217 - WebKit loses check when the name is after the checked attribute
	input.setAttribute( "name", "t" );

	div.appendChild( input );
	fragment = document.createDocumentFragment();
	fragment.appendChild( div.lastChild );

	// WebKit doesn't clone checked state correctly in fragments
	support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;

	// Check if a disconnected checkbox will retain its checked
	// value of true after appended to the DOM (IE6/7)
	support.appendChecked = input.checked;

	fragment.removeChild( input );
	fragment.appendChild( div );

	// Technique from Juriy Zaytsev
	// http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
	// We only care about the case where non-standard event systems
	// are used, namely in IE. Short-circuiting here helps us to
	// avoid an eval call (in setAttribute) which can cause CSP
	// to go haywire. See: https://developer.mozilla.org/en/Security/CSP
	if ( div.attachEvent ) {
		for ( i in {
			submit: true,
			change: true,
			focusin: true
		}) {
			eventName = "on" + i;
			isSupported = ( eventName in div );
			if ( !isSupported ) {
				div.setAttribute( eventName, "return;" );
				isSupported = ( typeof div[ eventName ] === "function" );
			}
			support[ i + "Bubbles" ] = isSupported;
		}
	}

	// Run tests that need a body at doc ready
	jQuery(function() {
		var container, div, tds, marginDiv,
			divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;",
			body = document.getElementsByTagName("body")[0];

		if ( !body ) {
			// Return for frameset docs that don't have a body
			return;
		}

		container = document.createElement("div");
		container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px";
		body.insertBefore( container, body.firstChild );

		// Construct the test element
		div = document.createElement("div");
		container.appendChild( div );

		// Check if table cells still have offsetWidth/Height when they are set
		// to display:none and there are still other visible table cells in a
		// table row; if so, offsetWidth/Height are not reliable for use when
		// determining if an element has been hidden directly using
		// display:none (it is still safe to use offsets if a parent element is
		// hidden; don safety goggles and see bug #4512 for more information).
		// (only IE 8 fails this test)
		div.innerHTML = "

	t

";
		tds = div.getElementsByTagName("td");
		isSupported = ( tds[ 0 ].offsetHeight === 0 );

		tds[ 0 ].style.display = "";
		tds[ 1 ].style.display = "none";

		// Check if empty table cells still have offsetWidth/Height
		// (IE <= 8 fail this test)
		support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );

		// Check box-sizing and margin behavior
		div.innerHTML = "";
		div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";
		support.boxSizing = ( div.offsetWidth === 4 );
		support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 );

		// NOTE: To any future maintainer, window.getComputedStyle was used here
		// instead of getComputedStyle because it gave a better gzip size.
		// The difference between window.getComputedStyle and getComputedStyle is
		// 7 bytes
		if ( window.getComputedStyle ) {
			support.pixelMargin = ( window.getComputedStyle( div, null ) || {} ).marginTop !== "1%";
			support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
			support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";

			// Check if div with explicit width and no margin-right incorrectly
			// gets computed margin-right based on width of container. For more
			// info see bug #3333
			// Fails in WebKit before Feb 2011 nightlies
			// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
			marginDiv = document.createElement("div");
			marginDiv.style.cssText = div.style.cssText = divReset;
			marginDiv.style.marginRight = marginDiv.style.width = "0";
			div.style.width = "1px";
			div.appendChild( marginDiv );
			support.reliableMarginRight =
				!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
		}

		if ( typeof div.style.zoom !== "undefined" ) {
			// Check if natively block-level elements act like inline-block
			// elements when setting their display to 'inline' and giving
			// them layout
			// (IE < 8 does this)
			div.innerHTML = "";
			div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
			support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );

			// Check if elements with layout shrink-wrap their children
			// (IE 6 does this)
			div.style.display = "block";
			div.style.overflow = "visible";
			div.innerHTML = "

";
			support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );

			container.style.zoom = 1;
		}

		// Null elements to avoid leaks in IE
		body.removeChild( container );
		container = div = tds = marginDiv = null;
	});

	// Null elements to avoid leaks in IE
	fragment.removeChild( div );
	all = a = select = opt = input = fragment = div = null;

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


<commit_before>export const modalStateClasses = ({ isOpened = false, isClosing = false } = {}) => {
  return {
    'modal-in': isOpened && !isClosing,
    'modal-out': isClosing,
  };
};
<commit_msg>v6: React - fix modal state classes<commit_after>export const modalStateClasses = ({ isOpened, isClosing } = {}) => {
  return {
    'modal-in': isOpened.current && !isClosing.current,
    'modal-out': isClosing.current,
  };
};
<|endoftext|>


<commit_before>/**
 *
 * @licstart  The following is the entire license notice for the
 * JavaScript code in this page.
 *
 * The MIT License (MIT)
 *
 * Copyright (C) 2015  Andrew Rogers
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 * @licend  The above is the entire license notice
 * for the JavaScript code in this page.
 *
 */

var CanvasButton=function(el,type){
  // Set sizes if necessary
  if(el.width()<=0)el.width(50);
  if(el.height()<=0)el.height(50);

  el.html('');
  this.el=el;
  this.createCanvas();
  if( !!type ) this.drawButton(type);

  var jq=$(this);
  el.click( function() {
    jq.trigger('click');
  });
};

CanvasButton.prototype.createCanvas=function(){
  var canvas = document.createElement('canvas');
  canvas.width=this.el.width();
  canvas.height=this.el.height();
  this.el.html(canvas);
  if( !document.createElement('canvas').getContext ){
    window.G_vmlCanvasManager.initElement(canvas);
  }
  this.canvas=canvas;
};

CanvasButton.prototype.drawButton=function(type){
  var context = this.canvas.getContext('2d');
  var w=this.canvas.width;
  var h=this.canvas.height;
  var size=w;
  if(h<size)size=h;
  context.translate(w/2, h/2);
  context.scale(size,size);

  type=type.split('.');
  var dir=type[1];
  type=type[0];

  if(type=='arrow'){
    // Draw circle
    context.beginPath();
    context.arc(0, 0, 0.375, 0, 2 * Math.PI, false);
    context.lineWidth = 5;
    context.fillStyle = "#CEF";
    context.fill();// Draw triangle
    context.beginPath();

    // Draw arrow
    switch(dir){
      case 'down':
        context.moveTo(0.05,-0.3);
        context.lineTo(0.05,0.125);
        context.lineTo(0.175,0.125);
        context.lineTo(0,0.3);
        context.lineTo(-0.175,0.125);
        context.lineTo(-0.05,0.125);
        context.lineTo(-0.05,-0.3);
        break;
      case 'up':
        context.moveTo(0.05,0.3);
        context.lineTo(0.05,-0.125);
        context.lineTo(0.175,-0.125);
        context.lineTo(0,-0.3);
        context.lineTo(-0.175,-0.125);
        context.lineTo(-0.05,-0.125);
        context.lineTo(-0.05,0.3);
        break;
      case 'left':
	context.moveTo(0.3,0.05);
	context.lineTo(-0.125,0.05);
        context.lineTo(-0.125,0.175);
        context.lineTo(-0.3,0);
        context.lineTo(-0.125,-0.175);
        context.lineTo(-0.125,-0.05);
        context.lineTo(0.3,-0.05);
        break;
      case 'right':
        context.moveTo(-0.3,0.05);
	context.lineTo(0.125,0.05);
        context.lineTo(0.125,0.175);
        context.lineTo(0.3,0);
        context.lineTo(0.125,-0.175);
        context.lineTo(0.125,-0.05);
        context.lineTo(-0.3,-0.05);
    }
    context.fillStyle="#358";
    context.fill();
  }

  if(type=='triangle'){
    // Draw circle
    context.beginPath();
    context.arc(0, 0, 0.375, 0, 2 * Math.PI, false);
    context.lineWidth = 5;
    context.fillStyle = "#CEF";
    context.fill();

    // Draw triangle
    context.beginPath();
    switch(dir){
      case 'down':
        context.moveTo(-0.25,-0.125);
        context.lineTo(0,0.225);
        context.lineTo(0.25,-0.125);
        break;
      case 'up':
        context.moveTo(-0.25,0.125);
        context.lineTo(0,-0.225);
        context.lineTo(0.25,0.125);
        break;
      case 'left':
        context.moveTo(0.125,-0.25);
        context.lineTo(-0.225,0);
        context.lineTo(0.125,0.25);
        break;
      case 'right':
        context.moveTo(-0.125,-0.25);
        context.lineTo(0.225,0);
        context.lineTo(-0.125,0.25);
    }
    context.fillStyle="#358";
    context.fill();
  }
};
<commit_msg>Added delete.<commit_after>/**
 *
 * @licstart  The following is the entire license notice for the
 * JavaScript code in this page.
 *
 * The MIT License (MIT)
 *
 * Copyright (C) 2015  Andrew Rogers
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 * @licend  The above is the entire license notice
 * for the JavaScript code in this page.
 *
 */

var CanvasButton=function(el,type){
  // Set sizes if necessary
  if(el.width()<=0)el.width(50);
  if(el.height()<=0)el.height(50);

  el.html('');
  this.el=el;
  this.createCanvas();
  if( !!type ) this.drawButton(type);

  var jq=$(this);
  el.click( function() {
    jq.trigger('click');
  });
};

CanvasButton.prototype.createCanvas=function(){
  var canvas = document.createElement('canvas');
  canvas.width=this.el.width();
  canvas.height=this.el.height();
  this.el.html(canvas);
  if( !document.createElement('canvas').getContext ){
    window.G_vmlCanvasManager.initElement(canvas);
  }
  this.canvas=canvas;
};

CanvasButton.prototype.drawButton=function(type){
  var context = this.canvas.getContext('2d');
  var w=this.canvas.width;
  var h=this.canvas.height;
  var size=w;
  if(h<size)size=h;
  context.translate(w/2, h/2);
  context.scale(size,size);

  type=type.split('.');
  var dir=type[1];
  var subtype=type[1];
  type=type[0];

  if(type=='arrow'){
    // Draw circle
    context.beginPath();
    context.arc(0, 0, 0.375, 0, 2 * Math.PI, false);
    context.lineWidth = 5;
    context.fillStyle = "#CEF";
    context.fill();// Draw triangle
    context.beginPath();

    // Draw arrow
    switch(dir){
      case 'down':
        context.moveTo(0.05,-0.3);
        context.lineTo(0.05,0.125);
        context.lineTo(0.175,0.125);
        context.lineTo(0,0.3);
        context.lineTo(-0.175,0.125);
        context.lineTo(-0.05,0.125);
        context.lineTo(-0.05,-0.3);
        break;
      case 'up':
        context.moveTo(0.05,0.3);
        context.lineTo(0.05,-0.125);
        context.lineTo(0.175,-0.125);
        context.lineTo(0,-0.3);
        context.lineTo(-0.175,-0.125);
        context.lineTo(-0.05,-0.125);
        context.lineTo(-0.05,0.3);
        break;
      case 'left':
	context.moveTo(0.3,0.05);
	context.lineTo(-0.125,0.05);
        context.lineTo(-0.125,0.175);
        context.lineTo(-0.3,0);
        context.lineTo(-0.125,-0.175);
        context.lineTo(-0.125,-0.05);
        context.lineTo(0.3,-0.05);
        break;
      case 'right':
        context.moveTo(-0.3,0.05);
	context.lineTo(0.125,0.05);
        context.lineTo(0.125,0.175);
        context.lineTo(0.3,0);
        context.lineTo(0.125,-0.175);
        context.lineTo(0.125,-0.05);
        context.lineTo(-0.3,-0.05);
    }
    context.fillStyle="#358";
    context.fill();
  }

  if(type=='triangle'){
    // Draw circle
    context.beginPath();
    context.arc(0, 0, 0.375, 0, 2 * Math.PI, false);
    context.lineWidth = 5;
    context.fillStyle = "#CEF";
    context.fill();

    // Draw triangle
    context.beginPath();
    switch(dir){
      case 'down':
        context.moveTo(-0.25,-0.125);
        context.lineTo(0,0.225);
        context.lineTo(0.25,-0.125);
        break;
      case 'up':
        context.moveTo(-0.25,0.125);
        context.lineTo(0,-0.225);
        context.lineTo(0.25,0.125);
        break;
      case 'left':
        context.moveTo(0.125,-0.25);
        context.lineTo(-0.225,0);
        context.lineTo(0.125,0.25);
        break;
      case 'right':
        context.moveTo(-0.125,-0.25);
        context.lineTo(0.225,0);
        context.lineTo(-0.125,0.25);
    }
    context.fillStyle="#358";
    context.fill();
  }

  if(type=='control' && subtype=='delete'){
    // Draw circle
    context.beginPath();
    context.arc(0, 0, 0.375, 0, 2 * Math.PI, false);
    context.lineWidth = 0.1;
    context.fillStyle = "#f00";
    context.fill();

    // Draw X
    context.beginPath();
    context.moveTo(-0.15,-0.15);
    context.lineTo(0.15,0.15);
    context.moveTo(-0.15,0.15);
    context.lineTo(0.15,-0.15);
    context.strokeStyle="#ccc";
    context.stroke();
  }
};
<|endoftext|>


<commit_before>/**
 * @class schematic-js/RegexpValidationPlugin
 * Plugin to validate a field against a regular expression.
 */
define([
    "../util"
], function (
    util
) {
    var module = function (config) {
        var that = this;
        this.message = {code: 0, message: "Failed regular expression match"};
        util.mixin(this, config);

        this.validate = function (property, instance, newValue, schema) {
            var ret = [],
                value = newValue === undefined ? instance[property] : newValue,
                regexp = new RegExp(this.pattern || ".*");
            if (value !== "" && !regexp.test(value)) {
                ret.push(that.message);
            }
            return ret.length ? ret : undefined;
        };
    };
    return module;
});
<commit_msg>Added optional configuration for conditional matching (ie, only match when another value is one of 1 or more values).<commit_after>/**
 * @class schematic-js/RegexpValidationPlugin
 * Plugin to validate a field against a regular expression.
 */
define([
    "../util"
], function (
    util
) {
    var module = function (config) {
        var that = this;
        this.message = {code: 0, message: "Failed regular expression match"};
        util.mixin(this, config);

        this.validate = function (property, instance, newValue, schema) {
            var ret = [],
                value = newValue === undefined ? instance[property] : newValue,
                regexp = new RegExp(this.pattern || ".*"),
                matchWhenValue = this.requiredWhen ? instance[this.requiredWhen.property] : '',
                matchWhenArray = this.requiredWhen ? this.requiredWhen.values : [''];

            if (util.indexOf(matchWhenValue, matchWhenArray) > -1) {
                if (value !== "" && !regexp.test(value)) {
                    ret.push(that.message);
                }
            }
            return ret.length ? ret : undefined;
        };
    };
    return module;
});
<|endoftext|>


<commit_before>const vscode = require('vscode');

const THEME_CONFIGURATION_ID = 'markdown-preview-github-styles';
const THEME_CONFIGURATION_KEY = 'colorTheme';

const THEME_CONFIGURATION_VALUES = {
    'auto': true,
    'system': true,
    'light': true,
    'dark': true
}
const THEME_CONFIGURATION_AUTO = 'auto';

let settings = vscode.workspace.getConfiguration(THEME_CONFIGURATION_ID, null);

function getColorTheme() {
    return validThemeConfigurationValue(settings.get(THEME_CONFIGURATION_KEY))
}

function validThemeConfigurationValue(theme) {
    return !THEME_CONFIGURATION_VALUES[theme]
        ? THEME_CONFIGURATION_AUTO
        : theme;
}

exports.activate = function() {
    vscode.workspace.onDidChangeConfiguration(function(e) {
        if (e.affectsConfiguration(`${THEME_CONFIGURATION_ID}.${THEME_CONFIGURATION_KEY}`)) {
            settings = vscode.workspace.getConfiguration(THEME_CONFIGURATION_ID, null);
        }
    });

    return {
        extendMarkdownIt(md) {
            return md.use(plugin);
        }
    };
}

function plugin(md) {
    const render = md.renderer.render;
    md.renderer.render = function() {
        return `<div class="markdown-body markdown-${getColorTheme()}">\n${render.apply(md.renderer, arguments)}\n</div>`;
    };
    return md;
}
<commit_msg>Remove extension setting global<commit_after>const vscode = require('vscode');

const THEME_CONFIGURATION_ID = 'markdown-preview-github-styles';
const THEME_CONFIGURATION_KEY = 'colorTheme';

const THEME_CONFIGURATION_VALUES = {
    'auto': true,
    'system': true,
    'light': true,
    'dark': true
}
const THEME_CONFIGURATION_AUTO = 'auto';

function getColorTheme() {
    const settings = vscode.workspace.getConfiguration(THEME_CONFIGURATION_ID, null);
    return validThemeConfigurationValue(settings.get(THEME_CONFIGURATION_KEY))
}

function validThemeConfigurationValue(theme) {
    return !THEME_CONFIGURATION_VALUES[theme]
        ? THEME_CONFIGURATION_AUTO
        : theme;
}

exports.activate = function() {
    return {
        extendMarkdownIt(md) {
            return md.use(plugin);
        }
    };
}

function plugin(md) {
    const render = md.renderer.render;
    md.renderer.render = function() {
        return `<div class="markdown-body markdown-${getColorTheme()}">\n${render.apply(md.renderer, arguments)}\n</div>`;
    };
    return md;
}
<|endoftext|>


<commit_before>export default function playground(frontendData, pluginData, Component, componentPath) {
  console.log(pluginData);
}
<commit_msg>added some logging to the frontend plugin<commit_after>export default function playground(frontendData, pluginData, Component, componentPath) {
  console.log(pluginData);
  console.log(Component);
  console.log(componentPath);
}
<|endoftext|>


<commit_before>$(document).ready(function() {
  console.log("document ready");

  createGame();
  loadEventListener(); // for button to reload the game
});

var human = "X";
var ai = "O";
var currentTurn = human;
var blankCells = 9;
var game; // 3x3 array

// initialize game with empty 3x3 board
function createGame() {
  game = new Array(3);
  for (var i = 0; i < game.length; i++) {
    game[i] = new Array(3);
    for (var j = 0; j < game[i].length; j++) {
      game[i][j] = ""
    }
  }
}

function reloadGame() {
  currentTurn = human;
  blankCells = 9;
  clearTable();
  createGame();
}

function clearTable() {
  $("td").empty();
  // empty();
}

function loadEventListener() {
  $("#reload").click(function() {
    reloadGame();
  });
}

function nextTurn() {
  console.log("next turn");
  if (currentTurn === human) {
    currentTurn = ai;
  } else {
    currentTurn = human;
  }
}

// accessed from onclick attribute in view.html
function humansMove(id,row,column) {

  // remove prompt to start once player begins game
  $(".start").fadeOut("slow");

  // if cell is already occupied, the move is invalid
  var content = $("#"+id).text();
  if (content.length > 0) {
    $(".dynamic_text").addClass("dynamic_text").html("
Invalid move
");
    return;
  }
  $("#"+id).addClass("x").html("X");

  // populate 2d array with corresponding tile
  game[row][column] = "X";

  // decrement number of blank cells
  blankCells -= 1;
  console.log(blankCells); //check if blank cell decrementing

  var result = checkForWinner(game);
  if (result !== "continue") {
    endTheGame(result);
  }
  nextTurn();
  aiMove(); //undefined still
  result = checkForWinner(game);
  if (result !== "continue") {
    endTheGame(result);
  }
}

// when a draw happens or a winner has been found
function endTheGame(result) {
  if (result === "draw") {
    $(".dynamic_text").addClass("dynamic_text").html("
Draw!
");
  } else if (result === "X") {
    // to check if human can win --hopefully not!
      $(".dynamic_text").addClass("dynamic_text").html("
You win!
");
  } else {
      $(".dynamic_text").addClass("dynamic_text").html("
I win!
");
  }
  // reloadGame(); //allow user to reload game manually by pressing start over button
  return;
}

function checkForWinner(game) {
  // check for horizontal wins, left to right
  for (var row = 0; row < game.length; row++) {
    if (game[row][0] === game[row][1] && game[row][1] === game[row][2]) {
      if (game[row][0] !== "") {
        return game[row][0]; // returns either X or O depending on winning combo
      }
    }
  }
  // check for vertical wins, top to bottom
  for (var col = 0; col < game.length; col++) {
    if (game[0][col] === game[1][col] && game[1][col] === game[2][col]) {
      if (game[0][col] !== "") {
        return game[0][col]; // returns either X or O depending on winning combo
      }
    }
  }
 // check for diagonal wins, top left to bottom right and bottom left to top right
 if ((game[0][0] === game[1][1] && game[1][1] === game[2][2]) || (game[2][0] === game[1][1] && game[1][1] === game[0][2])) {
    if (game[1][1] !== "") {
      return game[1][1]; // returns either X or O depending on winning combo
    }
 }
 // return draw when all cells are filled and no winner is found
 if (blankCells === 0) {
    return "draw";
 }
 // resume playing until game ends in a draw or a winner is found
 return "continue";
}

<commit_msg>add conditions for aiMove fxn where aiMove should not run<commit_after>$(document).ready(function() {
  console.log("document ready");

  createGame();
  loadEventListener(); // for button to reload the game
});

var human = "X";
var ai = "O";
var currentTurn = human;
var blankCells = 9;
var game; // 3x3 array

// initialize game with empty 3x3 board
function createGame() {
  game = new Array(3);
  for (var i = 0; i < game.length; i++) {
    game[i] = new Array(3);
    for (var j = 0; j < game[i].length; j++) {
      game[i][j] = ""
    }
  }
}

function reloadGame() {
  currentTurn = human;
  blankCells = 9;
  clearTable();
  createGame();
}

function clearTable() {
  $("td").empty();
  // empty();
}

function loadEventListener() {
  $("#reload").click(function() {
    reloadGame();
  });
}

function nextTurn() {
  if (currentTurn === human) {
    currentTurn = ai;
  } else {
    currentTurn = human;
  }
}

// accessed from onclick attribute in view.html
function humansMove(id,row,column) {

  // remove prompt to start once player begins game
  $(".start").fadeOut("slow");

  // if cell is already occupied, the move is invalid
  var content = $("#"+id).text();
  if (content.length > 0) {
    $(".dynamic_text").addClass("dynamic_text").html("
Invalid move
");
    return;
  }
  $("#"+id).addClass("x").html("X");

  // populate 2d array with corresponding tile
  game[row][column] = "X";

  // decrement number of blank cells
  blankCells -= 1;
  console.log("blank cells left - " + blankCells); //check if blank cell decrementing

  var result = checkForWinner(game);
  if (result !== "continue") {
    endTheGame(result);
  }
  nextTurn();
  console.log("the current turn - " + currentTurn);
  aiMove(); //undefined still
  result = checkForWinner(game);
  if (result !== "continue") {
    endTheGame(result);
  }
}

function aiMove() {
  // return if it's not the ai's turn -- maybe get rid of this later
  if (currentTurn !== ai) {
    return;
  }
  // return if there are no turns left / no blank cells available
  if (blankCells === 0) {
    return;
  }
}

// when a draw happens or a winner has been found
function endTheGame(result) {
  if (result === "draw") {
    $(".dynamic_text").addClass("dynamic_text").html("
Draw!
");
  } else if (result === "X") {
    // to check if human can win --hopefully not!
      $(".dynamic_text").addClass("dynamic_text").html("
You win!
");
  } else {
      $(".dynamic_text").addClass("dynamic_text").html("
I win!
");
  }
  // reloadGame(); //allow user to reload game manually by pressing start over button
  return;
}

function checkForWinner(game) {
  // check for horizontal wins, left to right
  for (var row = 0; row < game.length; row++) {
    if (game[row][0] === game[row][1] && game[row][1] === game[row][2]) {
      if (game[row][0] !== "") {
        return game[row][0]; // returns either X or O depending on winning combo
      }
    }
  }
  // check for vertical wins, top to bottom
  for (var col = 0; col < game.length; col++) {
    if (game[0][col] === game[1][col] && game[1][col] === game[2][col]) {
      if (game[0][col] !== "") {
        return game[0][col]; // returns either X or O depending on winning combo
      }
    }
  }
 // check for diagonal wins, top left to bottom right and bottom left to top right
 if ((game[0][0] === game[1][1] && game[1][1] === game[2][2]) || (game[2][0] === game[1][1] && game[1][1] === game[0][2])) {
    if (game[1][1] !== "") {
      return game[1][1]; // returns either X or O depending on winning combo
    }
 }
 // return draw when all cells are filled and no winner is found
 if (blankCells === 0) {
    return "draw";
 }
 // resume playing until game ends in a draw or a winner is found
 return "continue";
}

<|endoftext|>


<commit_before>import path from 'path';

import webpack from 'webpack';
import dotenv from 'dotenv';
import MiniCssExtractPlugin from 'mini-css-extract-plugin';

import {version} from '../../package.json';

const postcssPresetEnv = require('postcss-preset-env');

dotenv.config();

process.env.REACT_CISCOSPARK_VERSION = version;

export default (options, env) => {
  const packageJson = require('../../package.json');
  const plugins = [
    new webpack.EnvironmentPlugin([
      'NODE_ENV',
      'CISCOSPARK_CLIENT_ID',
      'REACT_CISCOSPARK_VERSION',
      'WDM_SERVICE_URL',
      'IDBROKER_BASE_URL',
      'CONVERSATION_SERVICE',
      'FEDERATION'
    ]),
    new MiniCssExtractPlugin({filename: '[name].css'}),
    // Adds use strict to prevent catch global namespace issues outside of chunks.
    new webpack.BannerPlugin(`react-ciscospark v${packageJson.version}`)
  ];

  return {
    context: options.context || path.resolve(process.cwd(), 'src'),
    mode: options.mode,
    entry: options.entry,
    output: Object.assign({
      filename: 'bundle.js',
      path: path.resolve(__dirname, '..', '..', 'dist'),
      sourceMapFilename: '[file].map'
    }, options.output),
    devtool: options.devtool,
    devServer: options.devServer,
    plugins: options.plugins ? plugins.concat(options.plugins) : plugins,
    stats: {
      children: false,
      chunks: false,
      modules: false,
      maxModules: 0,
      chunkOrigins: false,
      colors: true
    },
    target: 'web',
    resolve: {
      alias: {
        node_modules: path.resolve(__dirname, '..', '..', 'node_modules')
      },
      mainFields: ['src', 'browser', 'module', 'main'],
      modules: [
        'src',
        path.resolve(__dirname, '..', '..', 'packages', 'node_modules'),
        'node_modules'
      ],
      extensions: ['.js', '.css', '.json', '.scss']
    },
    module: {
      rules: [
        {
          test: /\.js$/,
          include: [
            path.resolve(__dirname, '..', '..', 'packages', 'node_modules'),
            path.resolve(__dirname, '..', '..', 'src'),
            path.resolve(__dirname, '..', '..', 'samples')
          ],
          exclude: [
            '/__fixtures__/',
            '/__mocks__/'
          ],
          use: ['babel-loader']
        },
        {
          test: /\.css$/,
          include: [
            path.resolve(__dirname, '..', '..', 'packages', 'node_modules'),
            path.resolve(__dirname, '..', '..', 'src')
          ],
          use: [
            'style-loader',
            {
              loader: 'css-loader',
              options: {
                camelCase: true,
                modules: true,
                localIdentName: `${env && env.package ? env.package : 'widget'}--[local]--[hash:base64:5]`,
                importLoaders: 1
              }
            },
            {
              loader: 'postcss-loader',
              options: {
                ident: 'postcss',
                plugins: () => [
                  postcssPresetEnv({
                    stage: 0,
                    browsers: ['last 2 versions', 'IE > 10']
                  })
                ]
              }
            }
          ]
        },
        {
          // Do not transform vendor`s CSS with CSS-modules
          test: /\.css$/,
          include: [path.resolve(__dirname, '..', '..', 'node_modules')],
          use: ['style-loader', 'css-loader']
        },
        {
          test: /\.scss$/,
          include: [
            path.resolve(__dirname, '..', '..', 'packages', 'node_modules'),
            path.resolve(__dirname, '..', '..', 'src'),
            path.resolve(__dirname, '..', '..', 'samples'),
            path.resolve(__dirname, '..', '..', 'node_modules')
          ],
          use: [
            {
              loader: MiniCssExtractPlugin.loader
            },
            {
              loader: 'css-loader'
            },
            {
              loader: 'sass-loader'
            }
          ]
        },
        {
          test: /\.woff$|\.woff2$|.ttf$|\.otf$|\.eot$|\.svg$/,
          use: [{
            loader: 'file-loader',
            options: {
              name: 'fonts/[name].[ext]'
            }
          }]
        },
        {
          test: /\.mp3$|\.wav$/,
          use: [{
            loader: 'file-loader',
            query: {
              name: 'media/[name].[ext]'
            }
          }]
        },
        {
          test: /.*\.(gif|png|jpg)$/,
          use: [
            'file-loader?name=[name].[ext]'
          ]
        }
      ]
    },
    node: {
      fs: 'empty'
    }
  };
};
<commit_msg>chore(webpack): change style loader<commit_after>import path from 'path';

import webpack from 'webpack';
import dotenv from 'dotenv';
import MiniCssExtractPlugin from 'mini-css-extract-plugin';

import {version} from '../../package.json';

const postcssPresetEnv = require('postcss-preset-env');

dotenv.config();

process.env.REACT_CISCOSPARK_VERSION = version;

export default (options, env) => {
  const packageJson = require('../../package.json');
  const plugins = [
    new webpack.EnvironmentPlugin([
      'NODE_ENV',
      'CISCOSPARK_CLIENT_ID',
      'REACT_CISCOSPARK_VERSION',
      'WDM_SERVICE_URL',
      'IDBROKER_BASE_URL',
      'CONVERSATION_SERVICE',
      'FEDERATION'
    ]),
    new MiniCssExtractPlugin({filename: '[name].css'}),
    // Adds use strict to prevent catch global namespace issues outside of chunks.
    new webpack.BannerPlugin(`react-ciscospark v${packageJson.version}`)
  ];

  return {
    context: options.context || path.resolve(process.cwd(), 'src'),
    mode: options.mode,
    entry: options.entry,
    output: Object.assign({
      filename: 'bundle.js',
      path: path.resolve(__dirname, '..', '..', 'dist'),
      sourceMapFilename: '[file].map'
    }, options.output),
    devtool: options.devtool,
    devServer: options.devServer,
    plugins: options.plugins ? plugins.concat(options.plugins) : plugins,
    stats: {
      children: false,
      chunks: false,
      modules: false,
      maxModules: 0,
      chunkOrigins: false,
      colors: true
    },
    target: 'web',
    resolve: {
      alias: {
        node_modules: path.resolve(__dirname, '..', '..', 'node_modules')
      },
      mainFields: ['src', 'browser', 'module', 'main'],
      modules: [
        'src',
        path.resolve(__dirname, '..', '..', 'packages', 'node_modules'),
        'node_modules'
      ],
      extensions: ['.js', '.css', '.json', '.scss']
    },
    module: {
      rules: [
        {
          test: /\.js$/,
          include: [
            path.resolve(__dirname, '..', '..', 'packages', 'node_modules'),
            path.resolve(__dirname, '..', '..', 'samples')
          ],
          exclude: [
            '/__fixtures__/',
            '/__mocks__/'
          ],
          use: ['babel-loader']
        },
        {
          test: /\.css$/,
          include: [
            path.resolve(__dirname, '..', '..', 'packages', 'node_modules')
          ],
          use: [
            {
              loader: MiniCssExtractPlugin.loader
            },
            {
              loader: 'css-loader',
              options: {
                camelCase: true,
                modules: true,
                localIdentName: `${env && env.package ? env.package : 'widget'}--[local]--[hash:base64:5]`,
                importLoaders: 1
              }
            },
            {
              loader: 'postcss-loader',
              options: {
                ident: 'postcss',
                plugins: () => [
                  postcssPresetEnv({
                    stage: 0,
                    browsers: ['last 2 versions', 'IE > 10']
                  })
                ]
              }
            }
          ]
        },
        {
          // Do not transform vendor`s CSS with CSS-modules
          test: /\.css$/,
          include: [path.resolve(__dirname, '..', '..', 'node_modules')],
          use: ['style-loader', 'css-loader']
        },
        {
          test: /\.scss$/,
          include: [
            path.resolve(__dirname, '..', '..', 'packages', 'node_modules'),
            path.resolve(__dirname, '..', '..', 'samples')
          ],
          use: [
            {
              // Adding sass converted files to our main.css does not work on IE/Edge
              loader: 'style-loader'
            },
            {
              loader: 'css-loader'
            },
            {
              loader: 'sass-loader'
            }
          ]
        },
        {
          test: /\.woff$|\.woff2$|.ttf$|\.otf$|\.eot$|\.svg$/,
          use: [{
            loader: 'file-loader',
            options: {
              name: 'fonts/[name].[ext]'
            }
          }]
        },
        {
          test: /\.mp3$|\.wav$/,
          use: [{
            loader: 'file-loader',
            query: {
              name: 'media/[name].[ext]'
            }
          }]
        },
        {
          test: /.*\.(gif|png|jpg)$/,
          use: [
            'file-loader?name=[name].[ext]'
          ]
        }
      ]
    },
    node: {
      fs: 'empty'
    }
  };
};
<|endoftext|>


<commit_before>/*! CellEdit 1.0.19
 * ©2016 Elliott Beaty - datatables.net/license
 */

/**
 * @summary     CellEdit
 * @description Make a cell editable when clicked upon
 * @version     1.0.19
 * @file        dataTables.editCell.js
 * @author      Elliott Beaty
 * @contact     elliott@elliottbeaty.com
 * @copyright   Copyright 2016 Elliott Beaty
 *
 * This source file is free software, available under the following license:
 *   MIT license - http://datatables.net/license/mit
 *
 * This source file 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 license files for details.
 *
 * For details please refer to: http://www.datatables.net
 */

jQuery.fn.dataTable.Api.register('MakeCellsEditable()', function (settings) {
    var table = this.table();

    jQuery.fn.extend({
        // UPDATE
        updateEditableCell: function (callingElement) {
            // Need to redeclare table here for situations where we have more than one datatable on the page. See issue6 on github
            var table = $(callingElement).closest("table").DataTable().table();
            var row = table.row($(callingElement).parents('tr'));
            var cell = table.cell($(callingElement).parent());
            var columnIndex = cell.index().column;
            var inputField =getInputField(callingElement);

            // Update
            var newValue = inputField.val();
            if (!newValue && ((settings.allowNulls) && settings.allowNulls != true)) {
                // If columns specified
                if (settings.allowNulls.columns) {
                    // If current column allows nulls
                    if (settings.allowNulls.columns.indexOf(columnIndex) > -1) {
                        _update(newValue);
                    } else {
                        _addValidationCss();
                    }
                    // No columns allow null
                } else if (!newValue) {
                    _addValidationCss();
                }
                //All columns allow null
            } else {
                _update(newValue);
            }
            function _addValidationCss() {
                // Show validation error
                if (settings.allowNulls.errorClass) {
                    $(inputField).addClass(settings.allowNulls.errorClass)
                } else {
                    $(inputField).css({ "border": "red solid 1px" });
                }
            }
            function _update(newValue) {
                var oldValue = cell.data();
                cell.data(newValue);
                //Return cell & row.
                settings.onUpdate(cell, row, oldValue);
            }
            // Get current page
            var currentPageIndex = table.page.info().page;

            //Redraw table
            table.page(currentPageIndex).draw(false);
        },
        // CANCEL
        cancelEditableCell: function (callingElement) {
            var table = $(callingElement.closest("table")).DataTable().table();
            var cell = table.cell($(callingElement).parent());
            // Set cell to it's original value
            cell.data(cell.data());

            // Redraw table
            table.draw();
        }
    });

    // Destroy
    if (settings === "destroy") {
        $(table.body()).off("click", "td");
        table = null;
    }

    if (table != null) {
        // On cell click
        $(table.body()).on('click', 'td', function () {

            var currentColumnIndex = table.cell(this).index().column;

            // DETERMINE WHAT COLUMNS CAN BE EDITED
            if ((settings.columns && settings.columns.indexOf(currentColumnIndex) > -1) || (!settings.columns)) {
                var row = table.row($(this).parents('tr'));
                editableCellsRow = row;

                var cell = table.cell(this).node();
                var oldValue = table.cell(this).data();
                // Sanitize value
                oldValue = sanitizeCellValue(oldValue);

                // Show input
                if (!$(cell).find('input').length && !$(cell).find('select').length && !$(cell).find('textarea').length) {
                    // Input CSS
                    var input = getInputHtml(currentColumnIndex, settings, oldValue);
                    $(cell).html(input.html);
                    if (input.focus) {
                        $('#ejbeatycelledit').focus();
                    }
                }
            }
        });
    }

});

function getInputHtml(currentColumnIndex, settings, oldValue) {
    var inputSetting, inputType, input, inputCss, confirmCss, cancelCss, confirmValue, cancelValue;

    input = {"focus":true,"html":null}

    if(settings.inputTypes){
        $.each(settings.inputTypes, function (index, setting) {
            if (setting.column == currentColumnIndex) {
                inputSetting = setting;
                inputType = inputSetting.type.toLowerCase();
            }
        });
    }

    if (settings.inputCss) { inputCss = settings.inputCss; }
    if (settings.confirmationButton) {
        confirmCss = settings.confirmationButton.confirmCss;
        confirmValue = settings.confirmationButton.confirmValue;
        cancelCss = settings.confirmationButton.cancelCss;
        cancelValue = settings.confirmationButton.cancelValue;
        inputType = inputType + "-confirm";
    }
    switch (inputType) {
        case "list":
            input.html = "<select class='" + inputCss + "' onchange='$(this).updateEditableCell(this);'>";
            $.each(inputSetting.options, function (index, option) {
                if (oldValue == option.value) {
                   input.html = input.html + "<option value='" + option.value + "' selected>" + option.display + "</option>"
                } else {
                   input.html = input.html + "<option value='" + option.value + "' >" + option.display + "</option>"
                }
            });
            input.html = input.html + "</select>";
            input.focus = false;
            break;
        case "list-confirm": // List w/ confirm
            input.html = "<select class='" + inputCss + "'>";
            $.each(inputSetting.options, function (index, option) {
                if (oldValue == option.value) {
                   input.html = input.html + "<option value='" + option.value + "' selected>" + option.display + "</option>"
                } else {
                   input.html = input.html + "<option value='" + option.value + "' >" + option.display + "</option>"
                }
            });
            input.html = input.html + "</select> " + confirmValue + " " + cancelValue + " ";
            input.focus = false;
            break;
        case "datepicker": //Both datepicker options work best when confirming the values
        case "datepicker-confirm":
            // Makesure jQuery UI is loaded on the page
            if (typeof jQuery.ui == 'undefined') {
                alert("jQuery UI is required for the DatePicker control but it is not loaded on the page!");
                break;
            }
            jQuery(".datepick").datepicker("destroy");
            input.html = "<input id='ejbeatycelledit' type='text' name='date' class='datepick " + inputCss + "'   value='" + oldValue + "'></input>  " + confirmValue + " " + cancelValue + "";
            setTimeout(function () { //Set timeout to allow the script to write the input.html before triggering the datepicker
                var icon = "http://jqueryui.com/resources/demos/datepicker/images/calendar.gif";
                // Allow the user to provide icon
                if (typeof inputSetting.options !== 'undefined' && typeof inputSetting.options.icon !== 'undefined') {
                    icon = inputSetting.options.icon;
                }
                var self = jQuery('.datepick').datepicker(
                    {
                        showOn: "button",
                        buttonImage: icon,
                        buttonImageOnly: true,
                        buttonText: "Select date"
                    });
            },100);
            break;
        case "text-confirm": // text input w/ confirm
            input.html = "<input id='ejbeatycelledit' class='" + inputCss + "' value='"+oldValue+"'></input> " + confirmValue + " " + cancelValue + " ";
            break;
        case "undefined-confirm": // text input w/ confirm
            input.html = "<input id='ejbeatycelledit' class='" + inputCss + "' value='" + oldValue + "'></input> " + confirmValue + " " + cancelValue + " ";
            break;
        case "textarea":
        case "textarea-confirm":
            input.html = "<textarea id='ejbeatycelledit' class='" + inputCss + "'>"+oldValue+"</textarea>" + confirmValue + " " + cancelValue + "";
            break;
        default: // text input
            input.html = "<input id='ejbeatycelledit' class='" + inputCss + "' onfocusout='$(this).updateEditableCell(this)' value='" + oldValue + "'></input>";
            break;
    }
    return input;
}

function getInputField(callingElement) {
    // Update datatables cell value
    var inputField;
    switch ($(callingElement).prop('nodeName').toLowerCase()) {
        case 'a': // This means they're using confirmation buttons
            if ($(callingElement).siblings('input').length > 0) {
                inputField = $(callingElement).siblings('input');
            }
            if ($(callingElement).siblings('select').length > 0) {
                inputField = $(callingElement).siblings('select');
            }
            if ($(callingElement).siblings('textarea').length > 0) {
                inputField = $(callingElement).siblings('textarea');
            }
        break;
        default:
            inputField = $(callingElement);
    }
    return inputField;
}

function sanitizeCellValue(cellValue) {
    if (typeof (cellValue) === 'undefined' || cellValue === null || cellValue.length < 1) {
        return "";
    }

    // If not a number
    if (isNaN(cellValue)) {
        // escape single quote
        cellValue = cellValue.replace(/'/g, "'");
    }
    return cellValue;
}
<commit_msg>Use more specific selector to allow nested elements in table cells<commit_after>/*! CellEdit 1.0.19
 * ©2016 Elliott Beaty - datatables.net/license
 */

/**
 * @summary     CellEdit
 * @description Make a cell editable when clicked upon
 * @version     1.0.19
 * @file        dataTables.editCell.js
 * @author      Elliott Beaty
 * @contact     elliott@elliottbeaty.com
 * @copyright   Copyright 2016 Elliott Beaty
 *
 * This source file is free software, available under the following license:
 *   MIT license - http://datatables.net/license/mit
 *
 * This source file 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 license files for details.
 *
 * For details please refer to: http://www.datatables.net
 */

jQuery.fn.dataTable.Api.register('MakeCellsEditable()', function (settings) {
    var table = this.table();

    jQuery.fn.extend({
        // UPDATE
        updateEditableCell: function (callingElement) {
            // Need to redeclare table here for situations where we have more than one datatable on the page. See issue6 on github
            var table = $(callingElement).closest("table").DataTable().table();
            var row = table.row($(callingElement).parents('tr'));
            var cell = table.cell($(callingElement).parents('td'));
            var columnIndex = cell.index().column;
            var inputField =getInputField(callingElement);

            // Update
            var newValue = inputField.val();
            if (!newValue && ((settings.allowNulls) && settings.allowNulls != true)) {
                // If columns specified
                if (settings.allowNulls.columns) {
                    // If current column allows nulls
                    if (settings.allowNulls.columns.indexOf(columnIndex) > -1) {
                        _update(newValue);
                    } else {
                        _addValidationCss();
                    }
                    // No columns allow null
                } else if (!newValue) {
                    _addValidationCss();
                }
                //All columns allow null
            } else {
                _update(newValue);
            }
            function _addValidationCss() {
                // Show validation error
                if (settings.allowNulls.errorClass) {
                    $(inputField).addClass(settings.allowNulls.errorClass)
                } else {
                    $(inputField).css({ "border": "red solid 1px" });
                }
            }
            function _update(newValue) {
                var oldValue = cell.data();
                cell.data(newValue);
                //Return cell & row.
                settings.onUpdate(cell, row, oldValue);
            }
            // Get current page
            var currentPageIndex = table.page.info().page;

            //Redraw table
            table.page(currentPageIndex).draw(false);
        },
        // CANCEL
        cancelEditableCell: function (callingElement) {
            var table = $(callingElement.closest("table")).DataTable().table();
            var cell = table.cell($(callingElement).parent());
            // Set cell to it's original value
            cell.data(cell.data());

            // Redraw table
            table.draw();
        }
    });

    // Destroy
    if (settings === "destroy") {
        $(table.body()).off("click", "td");
        table = null;
    }

    if (table != null) {
        // On cell click
        $(table.body()).on('click', 'td', function () {

            var currentColumnIndex = table.cell(this).index().column;

            // DETERMINE WHAT COLUMNS CAN BE EDITED
            if ((settings.columns && settings.columns.indexOf(currentColumnIndex) > -1) || (!settings.columns)) {
                var row = table.row($(this).parents('tr'));
                editableCellsRow = row;

                var cell = table.cell(this).node();
                var oldValue = table.cell(this).data();
                // Sanitize value
                oldValue = sanitizeCellValue(oldValue);

                // Show input
                if (!$(cell).find('input').length && !$(cell).find('select').length && !$(cell).find('textarea').length) {
                    // Input CSS
                    var input = getInputHtml(currentColumnIndex, settings, oldValue);
                    $(cell).html(input.html);
                    if (input.focus) {
                        $('#ejbeatycelledit').focus();
                    }
                }
            }
        });
    }

});

function getInputHtml(currentColumnIndex, settings, oldValue) {
    var inputSetting, inputType, input, inputCss, confirmCss, cancelCss, confirmValue, cancelValue;

    input = {"focus":true,"html":null}

    if(settings.inputTypes){
        $.each(settings.inputTypes, function (index, setting) {
            if (setting.column == currentColumnIndex) {
                inputSetting = setting;
                inputType = inputSetting.type.toLowerCase();
            }
        });
    }

    if (settings.inputCss) { inputCss = settings.inputCss; }
    if (settings.confirmationButton) {
        confirmCss = settings.confirmationButton.confirmCss;
        confirmValue = settings.confirmationButton.confirmValue;
        cancelCss = settings.confirmationButton.cancelCss;
        cancelValue = settings.confirmationButton.cancelValue;
        inputType = inputType + "-confirm";
    }
    switch (inputType) {
        case "list":
            input.html = "<select class='" + inputCss + "' onchange='$(this).updateEditableCell(this);'>";
            $.each(inputSetting.options, function (index, option) {
                if (oldValue == option.value) {
                   input.html = input.html + "<option value='" + option.value + "' selected>" + option.display + "</option>"
                } else {
                   input.html = input.html + "<option value='" + option.value + "' >" + option.display + "</option>"
                }
            });
            input.html = input.html + "</select>";
            input.focus = false;
            break;
        case "list-confirm": // List w/ confirm
            input.html = "<select class='" + inputCss + "'>";
            $.each(inputSetting.options, function (index, option) {
                if (oldValue == option.value) {
                   input.html = input.html + "<option value='" + option.value + "' selected>" + option.display + "</option>"
                } else {
                   input.html = input.html + "<option value='" + option.value + "' >" + option.display + "</option>"
                }
            });
            input.html = input.html + "</select> " + confirmValue + " " + cancelValue + " ";
            input.focus = false;
            break;
        case "datepicker": //Both datepicker options work best when confirming the values
        case "datepicker-confirm":
            // Makesure jQuery UI is loaded on the page
            if (typeof jQuery.ui == 'undefined') {
                alert("jQuery UI is required for the DatePicker control but it is not loaded on the page!");
                break;
            }
            jQuery(".datepick").datepicker("destroy");
            input.html = "<input id='ejbeatycelledit' type='text' name='date' class='datepick " + inputCss + "'   value='" + oldValue + "'></input>  " + confirmValue + " " + cancelValue + "";
            setTimeout(function () { //Set timeout to allow the script to write the input.html before triggering the datepicker
                var icon = "http://jqueryui.com/resources/demos/datepicker/images/calendar.gif";
                // Allow the user to provide icon
                if (typeof inputSetting.options !== 'undefined' && typeof inputSetting.options.icon !== 'undefined') {
                    icon = inputSetting.options.icon;
                }
                var self = jQuery('.datepick').datepicker(
                    {
                        showOn: "button",
                        buttonImage: icon,
                        buttonImageOnly: true,
                        buttonText: "Select date"
                    });
            },100);
            break;
        case "text-confirm": // text input w/ confirm
            input.html = "<input id='ejbeatycelledit' class='" + inputCss + "' value='"+oldValue+"'></input> " + confirmValue + " " + cancelValue + " ";
            break;
        case "undefined-confirm": // text input w/ confirm
            input.html = "<input id='ejbeatycelledit' class='" + inputCss + "' value='" + oldValue + "'></input> " + confirmValue + " " + cancelValue + " ";
            break;
        case "textarea":
        case "textarea-confirm":
            input.html = "<textarea id='ejbeatycelledit' class='" + inputCss + "'>"+oldValue+"</textarea>" + confirmValue + " " + cancelValue + "";
            break;
        default: // text input
            input.html = "<input id='ejbeatycelledit' class='" + inputCss + "' onfocusout='$(this).updateEditableCell(this)' value='" + oldValue + "'></input>";
            break;
    }
    return input;
}

function getInputField(callingElement) {
    // Update datatables cell value
    var inputField;
    switch ($(callingElement).prop('nodeName').toLowerCase()) {
        case 'a': // This means they're using confirmation buttons
            if ($(callingElement).siblings('input').length > 0) {
                inputField = $(callingElement).siblings('input');
            }
            if ($(callingElement).siblings('select').length > 0) {
                inputField = $(callingElement).siblings('select');
            }
            if ($(callingElement).siblings('textarea').length > 0) {
                inputField = $(callingElement).siblings('textarea');
            }
        break;
        default:
            inputField = $(callingElement);
    }
    return inputField;
}

function sanitizeCellValue(cellValue) {
    if (typeof (cellValue) === 'undefined' || cellValue === null || cellValue.length < 1) {
        return "";
    }

    // If not a number
    if (isNaN(cellValue)) {
        // escape single quote
        cellValue = cellValue.replace(/'/g, "'");
    }
    return cellValue;
}
<|endoftext|>


<commit_before>/*jslint indent: 2, nomen: true, maxlen: 100, sloppy: true, vars: true, white: true, plusplus: true */
/*global require, exports, Backbone, EJS, $, setTimeout, localStorage, ace, Storage, window, _ */
/*global arangoHelper*/

var queryView = Backbone.View.extend({
  el: '#content',

  initialize: function () {
    this.getAQL();
    this.getSystemQueries();
    localStorage.setItem("queryContent", "");
    localStorage.setItem("queryOutput", "");
  },

  events: {
    'click #submitQueryIcon'         : 'submitQuery',
    'click #submitQueryButton'       : 'submitQuery',
    'click #commentText'             : 'commentText',
    'click #undoText'                : 'undoText',
    'click #redoText'                : 'redoText',
    'click #smallOutput'             : 'smallOutput',
    'click #bigOutput'               : 'bigOutput',
    'click #clearOutput'             : 'clearOutput',
    'click #clearInput'              : 'clearInput',
    'click #addAQL'                  : 'addAQL',
    'click #editAQL'                 : 'editAQL',
    'click #save-new-query'          : 'saveAQL',
    'click #save-edit-query'         : 'saveAQL',
    'click #delete-edit-query'       : 'showDeleteField',
    'click #confirmDeleteQuery'      : 'deleteAQL',
    'click #abortDeleteQuery'        : 'hideDeleteField',
    'keydown #new-query-name'        : 'listenKey',
    'change #queryModalSelect'       : 'updateEditSelect',
    'change #querySelect'            : 'importSelected',
    'keypress #aqlEditor'            : 'aqlShortcuts'
  },

  listenKey: function (e) {
    if (e.keyCode === 13) {
      this.saveAQL(e);
    }
  },

  clearOutput: function() {
    var outputEditor = ace.edit("queryOutput");
    outputEditor.setValue('');
  },

  clearInput: function() {
    var inputEditor = ace.edit("aqlEditor");
    inputEditor.setValue('');
  },

  smallOutput: function() {
    var outputEditor = ace.edit("queryOutput");
    outputEditor.getSession().foldAll();
  },

  bigOutput: function() {
    var outputEditor = ace.edit("queryOutput");
    outputEditor.getSession().unfold();
  },

  aqlShortcuts: function (e) {
    if (e.ctrlKey && e.keyCode == 13) {
      this.submitQuery();
    }
  },

  queries: [
  ],

  customQueries: [],

  template: new EJS({url: 'js/templates/queryView.ejs'}),

  render: function() {
    var self = this;
    $(this.el).html(this.template.text);
    var inputEditor = ace.edit("aqlEditor");
    var outputEditor = ace.edit("queryOutput");

    outputEditor.setReadOnly(true);
    outputEditor.setHighlightActiveLine(false);

    inputEditor.getSession().setMode("ace/mode/aql");
    outputEditor.getSession().setMode("ace/mode/json");
    inputEditor.setTheme("ace/theme/merbivore_soft");
    outputEditor.setValue('');

    $('#queryOutput').resizable({
      handles: "s",
      ghost: true,
      stop: function () {
        setTimeout(function (){
          var outputEditor = ace.edit("queryOutput");
          outputEditor.resize();
        },200);
      }
    });

    $('#aqlEditor').resizable({
      handles: "s",
      ghost: true,
      //helper: "resizable-helper",
      stop: function () {
        setTimeout(function (){
          var inputEditor = ace.edit("aqlEditor");
          inputEditor.resize();
        },200);
      }
    });

    $('.queryTooltips').tooltip({
      placement: "top"
    });

    $('#aqlEditor .ace_text-input').focus();
    $.gritter.removeAll();

    if(typeof Storage) {
      var queryContent = localStorage.getItem("queryContent");
      var queryOutput = localStorage.getItem("queryOutput");
      inputEditor.setValue(queryContent);
      outputEditor.setValue(queryOutput);
    }

    var windowHeight = $(window).height() - 250;
    $('#queryOutput').height(windowHeight/3);
    $('#aqlEditor').height(windowHeight/2);

    inputEditor.resize();
    outputEditor.resize();

    this.renderSelectboxes();
    $('#queryDiv').show();

    return this;
  },

  deselect : function (editor) {
    var current = editor.getSelection();
    var currentRow = current.lead.row;
    var currentColumn = current.lead.column;

    current.setSelectionRange({
      start: {
        row: currentRow,
        column: currentColumn
      },
      end: {
        row: currentRow,
        column: currentColumn
      }
    });

    editor.focus();
  },

  addAQL: function () {
    //render options
    $('#new-query-name').val('');
    $('#new-aql-query').modal('show');
    setTimeout(function (){
      $('#new-query-name').focus();
    },500);
  },
  editAQL: function () {
    if (this.customQueries.length === 0) {
      arangoHelper.arangoNotification("No custom queries available");
      return;
    }

    this.hideDeleteField();
    $('#edit-aql-queries').modal('show');
    this.renderSelectboxes(true);
    this.updateEditSelect();
  },
  getAQL: function () {
    if (localStorage.getItem("customQueries")) {
      this.customQueries = JSON.parse(localStorage.getItem("customQueries"));
    }
  },
  showDeleteField: function () {
    $('#reallyDeleteQueryDiv').show();
  },
  hideDeleteField: function () {
    $('#reallyDeleteQueryDiv').hide();
  },
  deleteAQL: function () {
    var queryName = $('#queryModalSelect').val();
    var tempArray = [];

    $.each(this.customQueries, function(k,v) {
      if (queryName !== v.name) {
        tempArray.push({
          name: v.name,
          value: v.value
        });
      }
    });

    this.customQueries = tempArray;
    localStorage.setItem("customQueries", JSON.stringify(this.customQueries));
    $('#edit-aql-queries').modal('hide');
    arangoHelper.arangoNotification("Query deleted");
    this.renderSelectboxes();
  },
  saveAQL: function (e) {

    var self = this;
    var inputEditor = ace.edit("aqlEditor");
    var queryName = $('#new-query-name').val();
    var content = inputEditor.getValue();

    if (e) {
      if (e.target.id === 'save-edit-query') {
        content = $('#edit-aql-textarea').val();
        queryName = $('#queryModalSelect').val();
      }
    }

    if (queryName.trim() === '') {
      arangoHelper.arangoNotification("Illegal query name");
      return;
    }

    //check for already existing entry
    var tempArray = [];
    var quit = false;
    $.each(this.customQueries, function(k,v) {
      if (e.target.id !== 'save-edit-query') {
        if (v.name === queryName) {
          quit = true;
          return;
        }
      }
      if (v.name !== queryName) {
        tempArray.push({
          name: v.name,
          value: v.value
        });
      }
    });

    if (quit === true) {
      arangoHelper.arangoNotification("Name already taken!");
      return;
    }

    this.customQueries = tempArray;

    this.customQueries.push({
      name: queryName,
      value: content
    });

    $('#new-aql-query').modal('hide');
    $('#edit-aql-queries').modal('hide');

    localStorage.setItem("customQueries", JSON.stringify(this.customQueries));
    arangoHelper.arangoNotification("Query saved");
    this.renderSelectboxes();
  },
  updateEditSelect: function () {
    var value = this.getCustomQueryValueByName($('#queryModalSelect').val());
    $('#edit-aql-textarea').val(value);
    $('#edit-aql-textarea').focus();
  },
  getSystemQueries: function() {
    var self = this;
    $.ajax({
      type: "GET",
      cache: false,
      url: "js/arango/aqltemplates.json",
      contentType: "application/json",
      processData: false,
      async: false,
      success: function(data) {
        self.queries = data;
      },
      error: function(data) {
        arangoHelper.arangoNotification("Error while loading system templates");
      }
    });
  },
  getCustomQueryValueByName: function (qName) {
    var returnVal;
    $.each(this.customQueries, function(k,v) {
      if (qName === v.name) {
        returnVal = v.value;
      }
    });
    return returnVal;
  },
  importSelected: function(e) {
    var inputEditor = ace.edit("aqlEditor");
    $.each(this.queries, function(k,v) {
      if ($('#'+e.currentTarget.id).val() === v.name) {
        inputEditor.setValue(v.value);
      }
    });
    $.each(this.customQueries, function(k,v) {
      if ($('#'+e.currentTarget.id).val() === v.name) {
        inputEditor.setValue(v.value);
      }
    });

    this.deselect(ace.edit("aqlEditor"));
  },
  renderSelectboxes: function (modal) {
    this.sortQueries();
    var selector = '';
    if (modal === true) {
      selector = '#queryModalSelect';
      $(selector).empty();
      $.each(this.customQueries, function(k,v) {
        $(selector).append('<option id="'+v.name+'">'+v.name+'</option>');
      });
    }
    else {
      selector = '#querySelect';
      $(selector).empty();
      $(selector).append('<option id="emptyquery">(please select)</option>');

      $(selector).append('<optgroup label="Example queries">');
      $.each(this.queries, function(k,v) {
        $(selector).append('<option id="'+v.name+'">'+v.name+'</option>');
      });
      $(selector).append('</optgroup>');

      if (this.customQueries.length > 0) {
        $(selector).append('<optgroup label="Custom queries">');
        $.each(this.customQueries, function(k,v) {
          $(selector).append('<option id="'+v.name+'">'+v.name+'</option>');
        });
        $(selector).append('</optgroup>');
      }
    }
  },
  undoText: function () {
    var inputEditor = ace.edit("aqlEditor");
    inputEditor.undo();
  },
  redoText: function () {
    var inputEditor = ace.edit("aqlEditor");
    inputEditor.redo();
  },
  commentText: function() {
    var inputEditor = ace.edit("aqlEditor");
    var value;
    var newValue;
    var flag = false;
    var cursorPosition = inputEditor.getCursorPosition();
    var cursorRange = inputEditor.getSelection().getRange();

    var regExp = new RegExp(/\*\//);
    var regExp2 = new RegExp(/\/\*/);

    if (cursorRange.end.row === cursorRange.start.row) {
      //single line comment /* */
      value = inputEditor.getSession().getLine(cursorRange.start.row);
      if (value.search(regExp) === -1 && value.search(regExp2) === -1) {
        newValue = '/*' + value + '*/';
        flag = true;
      }
      else if (value.search(regExp) !== -1 && value.search(regExp2) !== -1) {
        newValue = value.replace(regExp, '').replace(regExp2, '');
        flag = true;
      }
      if (flag === true) {
        inputEditor.find(value, {
          range: cursorRange
        });
        inputEditor.replace(newValue);
      }
    }
    else {
      //multi line comment
      value = inputEditor.getSession().getLines(cursorRange.start.row, cursorRange.end.row);
      var arrayLength = value.length;
      var firstString = value[0];
      var lastString = value[value.length-1];
      var newFirstString;
      var newLastString;

      if (firstString.search(regExp2) === -1 && lastString.search(regExp) === -1) {
        newFirstString = '/*' + firstString;
        newLastString = lastString + '*/';
        flag = true;
      }
      else if (firstString.search(regExp2) !== -1 && lastString.search(regExp) !== -1) {
        newFirstString = firstString.replace(regExp2, '');
        newLastString = lastString.replace(regExp, '');
        flag = true;
      }
      if (flag === true) {
        inputEditor.find(firstString, {
          range: cursorRange
        });
        inputEditor.replace(newFirstString);
        inputEditor.find(lastString, {
          range: cursorRange
        });
        inputEditor.replace(newLastString);
      }
    }
    cursorRange.end.column = cursorRange.end.column + 2;
    inputEditor.getSelection().setSelectionRange(cursorRange, false);
  },
  sortQueries: function() {
    this.queries = _.sortBy(this.queries, 'name' );
    this.customQueries = _.sortBy(this.customQueries, 'name' );
  },
  submitQuery: function() {
    var self = this;
    var inputEditor = ace.edit("aqlEditor");
    var data = {query: inputEditor.getValue()};

    var outputEditor = ace.edit("queryOutput");

    $.ajax({
      type: "POST",
      url: "/_api/cursor",
      data: JSON.stringify(data),
      contentType: "application/json",
      processData: false,
      success: function(data) {
        outputEditor.setValue(arangoHelper.FormatJSON(data.result));
        if(typeof Storage) {
          localStorage.setItem("queryContent", inputEditor.getValue());
          localStorage.setItem("queryOutput", outputEditor.getValue());
        }
      },
      error: function(data) {
        try {
          var temp = JSON.parse(data.responseText);
          outputEditor.setValue('[' + temp.errorNum + '] ' + temp.errorMessage);

          if(typeof Storage) {
            localStorage.setItem("queryContent", inputEditor.getValue());
            localStorage.setItem("queryOutput", outputEditor.getValue());
          }
        }
        catch (e) {
          outputEditor.setValue('ERROR');
        }
      }
    });
    outputEditor.resize();

  }

});
<commit_msg>added aql editor shortcuts<commit_after>/*jslint indent: 2, nomen: true, maxlen: 100, sloppy: true, vars: true, white: true, plusplus: true */
/*global require, exports, Backbone, EJS, $, setTimeout, localStorage, ace, Storage, window, _ */
/*global arangoHelper*/

var queryView = Backbone.View.extend({
  el: '#content',

  initialize: function () {
    this.getAQL();
    this.getSystemQueries();
    localStorage.setItem("queryContent", "");
    localStorage.setItem("queryOutput", "");
  },

  events: {
    'click #submitQueryIcon'         : 'submitQuery',
    'click #submitQueryButton'       : 'submitQuery',
    'click #commentText'             : 'commentText',
    'click #undoText'                : 'undoText',
    'click #redoText'                : 'redoText',
    'click #smallOutput'             : 'smallOutput',
    'click #bigOutput'               : 'bigOutput',
    'click #clearOutput'             : 'clearOutput',
    'click #clearInput'              : 'clearInput',
    'click #addAQL'                  : 'addAQL',
    'click #editAQL'                 : 'editAQL',
    'click #save-new-query'          : 'saveAQL',
    'click #save-edit-query'         : 'saveAQL',
    'click #delete-edit-query'       : 'showDeleteField',
    'click #confirmDeleteQuery'      : 'deleteAQL',
    'click #abortDeleteQuery'        : 'hideDeleteField',
    'keydown #new-query-name'        : 'listenKey',
    'change #queryModalSelect'       : 'updateEditSelect',
    'change #querySelect'            : 'importSelected',
    'keypress #aqlEditor'            : 'aqlShortcuts'
  },

  listenKey: function (e) {
    if (e.keyCode === 13) {
      this.saveAQL(e);
    }
  },

  clearOutput: function() {
    var outputEditor = ace.edit("queryOutput");
    outputEditor.setValue('');
  },

  clearInput: function() {
    var inputEditor = ace.edit("aqlEditor");
    inputEditor.setValue('');
  },

  smallOutput: function() {
    var outputEditor = ace.edit("queryOutput");
    outputEditor.getSession().foldAll();
  },

  bigOutput: function() {
    var outputEditor = ace.edit("queryOutput");
    outputEditor.getSession().unfold();
  },

  aqlShortcuts: function (e) {
    if (e.ctrlKey && e.keyCode === 13) {
      this.submitQuery();
    }
    else if (e.metaKey && !e.ctrlKey && e.keyCode === 13) {
      this.submitQuery();
    }
    else if (e.ctrlKey && e.keyCode === 90) {
      this.undoText();
    }
    else if (e.ctrlKey && e.shiftKey && e.keyCode === 90) {
      this.redeText();
    }

  },

  queries: [
  ],

  customQueries: [],

  template: new EJS({url: 'js/templates/queryView.ejs'}),

  render: function() {
    var self = this;
    $(this.el).html(this.template.text);
    var inputEditor = ace.edit("aqlEditor");
    var outputEditor = ace.edit("queryOutput");

    outputEditor.setReadOnly(true);
    outputEditor.setHighlightActiveLine(false);

    inputEditor.getSession().setMode("ace/mode/aql");
    outputEditor.getSession().setMode("ace/mode/json");
    inputEditor.setTheme("ace/theme/merbivore_soft");
    outputEditor.setValue('');

    $('#queryOutput').resizable({
      handles: "s",
      ghost: true,
      stop: function () {
        setTimeout(function (){
          var outputEditor = ace.edit("queryOutput");
          outputEditor.resize();
        },200);
      }
    });

    $('#aqlEditor').resizable({
      handles: "s",
      ghost: true,
      //helper: "resizable-helper",
      stop: function () {
        setTimeout(function (){
          var inputEditor = ace.edit("aqlEditor");
          inputEditor.resize();
        },200);
      }
    });

    $('.queryTooltips').tooltip({
      placement: "top"
    });

    $('#aqlEditor .ace_text-input').focus();
    $.gritter.removeAll();

    if(typeof Storage) {
      var queryContent = localStorage.getItem("queryContent");
      var queryOutput = localStorage.getItem("queryOutput");
      inputEditor.setValue(queryContent);
      outputEditor.setValue(queryOutput);
    }

    var windowHeight = $(window).height() - 250;
    $('#queryOutput').height(windowHeight/3);
    $('#aqlEditor').height(windowHeight/2);

    inputEditor.resize();
    outputEditor.resize();

    this.renderSelectboxes();
    $('#queryDiv').show();

    return this;
  },

  deselect : function (editor) {
    var current = editor.getSelection();
    var currentRow = current.lead.row;
    var currentColumn = current.lead.column;

    current.setSelectionRange({
      start: {
        row: currentRow,
        column: currentColumn
      },
      end: {
        row: currentRow,
        column: currentColumn
      }
    });

    editor.focus();
  },

  addAQL: function () {
    //render options
    $('#new-query-name').val('');
    $('#new-aql-query').modal('show');
    setTimeout(function (){
      $('#new-query-name').focus();
    },500);
  },
  editAQL: function () {
    if (this.customQueries.length === 0) {
      arangoHelper.arangoNotification("No custom queries available");
      return;
    }

    this.hideDeleteField();
    $('#edit-aql-queries').modal('show');
    this.renderSelectboxes(true);
    this.updateEditSelect();
  },
  getAQL: function () {
    if (localStorage.getItem("customQueries")) {
      this.customQueries = JSON.parse(localStorage.getItem("customQueries"));
    }
  },
  showDeleteField: function () {
    $('#reallyDeleteQueryDiv').show();
  },
  hideDeleteField: function () {
    $('#reallyDeleteQueryDiv').hide();
  },
  deleteAQL: function () {
    var queryName = $('#queryModalSelect').val();
    var tempArray = [];

    $.each(this.customQueries, function(k,v) {
      if (queryName !== v.name) {
        tempArray.push({
          name: v.name,
          value: v.value
        });
      }
    });

    this.customQueries = tempArray;
    localStorage.setItem("customQueries", JSON.stringify(this.customQueries));
    $('#edit-aql-queries').modal('hide');
    arangoHelper.arangoNotification("Query deleted");
    this.renderSelectboxes();
  },
  saveAQL: function (e) {

    var self = this;
    var inputEditor = ace.edit("aqlEditor");
    var queryName = $('#new-query-name').val();
    var content = inputEditor.getValue();

    if (e) {
      if (e.target.id === 'save-edit-query') {
        content = $('#edit-aql-textarea').val();
        queryName = $('#queryModalSelect').val();
      }
    }

    if (queryName.trim() === '') {
      arangoHelper.arangoNotification("Illegal query name");
      return;
    }

    //check for already existing entry
    var tempArray = [];
    var quit = false;
    $.each(this.customQueries, function(k,v) {
      if (e.target.id !== 'save-edit-query') {
        if (v.name === queryName) {
          quit = true;
          return;
        }
      }
      if (v.name !== queryName) {
        tempArray.push({
          name: v.name,
          value: v.value
        });
      }
    });

    if (quit === true) {
      arangoHelper.arangoNotification("Name already taken!");
      return;
    }

    this.customQueries = tempArray;

    this.customQueries.push({
      name: queryName,
      value: content
    });

    $('#new-aql-query').modal('hide');
    $('#edit-aql-queries').modal('hide');

    localStorage.setItem("customQueries", JSON.stringify(this.customQueries));
    arangoHelper.arangoNotification("Query saved");
    this.renderSelectboxes();
  },
  updateEditSelect: function () {
    var value = this.getCustomQueryValueByName($('#queryModalSelect').val());
    $('#edit-aql-textarea').val(value);
    $('#edit-aql-textarea').focus();
  },
  getSystemQueries: function() {
    var self = this;
    $.ajax({
      type: "GET",
      cache: false,
      url: "js/arango/aqltemplates.json",
      contentType: "application/json",
      processData: false,
      async: false,
      success: function(data) {
        self.queries = data;
      },
      error: function(data) {
        arangoHelper.arangoNotification("Error while loading system templates");
      }
    });
  },
  getCustomQueryValueByName: function (qName) {
    var returnVal;
    $.each(this.customQueries, function(k,v) {
      if (qName === v.name) {
        returnVal = v.value;
      }
    });
    return returnVal;
  },
  importSelected: function(e) {
    var inputEditor = ace.edit("aqlEditor");
    $.each(this.queries, function(k,v) {
      if ($('#'+e.currentTarget.id).val() === v.name) {
        inputEditor.setValue(v.value);
      }
    });
    $.each(this.customQueries, function(k,v) {
      if ($('#'+e.currentTarget.id).val() === v.name) {
        inputEditor.setValue(v.value);
      }
    });

    this.deselect(ace.edit("aqlEditor"));
  },
  renderSelectboxes: function (modal) {
    this.sortQueries();
    var selector = '';
    if (modal === true) {
      selector = '#queryModalSelect';
      $(selector).empty();
      $.each(this.customQueries, function(k,v) {
        $(selector).append('<option id="'+v.name+'">'+v.name+'</option>');
      });
    }
    else {
      selector = '#querySelect';
      $(selector).empty();
      $(selector).append('<option id="emptyquery">(please select)</option>');

      $(selector).append('<optgroup label="Example queries">');
      $.each(this.queries, function(k,v) {
        $(selector).append('<option id="'+v.name+'">'+v.name+'</option>');
      });
      $(selector).append('</optgroup>');

      if (this.customQueries.length > 0) {
        $(selector).append('<optgroup label="Custom queries">');
        $.each(this.customQueries, function(k,v) {
          $(selector).append('<option id="'+v.name+'">'+v.name+'</option>');
        });
        $(selector).append('</optgroup>');
      }
    }
  },
  undoText: function () {
    var inputEditor = ace.edit("aqlEditor");
    inputEditor.undo();
  },
  redoText: function () {
    var inputEditor = ace.edit("aqlEditor");
    inputEditor.redo();
  },
  commentText: function() {
    var inputEditor = ace.edit("aqlEditor");
    var value;
    var newValue;
    var flag = false;
    var cursorPosition = inputEditor.getCursorPosition();
    var cursorRange = inputEditor.getSelection().getRange();

    var regExp = new RegExp(/\*\//);
    var regExp2 = new RegExp(/\/\*/);

    if (cursorRange.end.row === cursorRange.start.row) {
      //single line comment /* */
      value = inputEditor.getSession().getLine(cursorRange.start.row);
      if (value.search(regExp) === -1 && value.search(regExp2) === -1) {
        newValue = '/*' + value + '*/';
        flag = true;
      }
      else if (value.search(regExp) !== -1 && value.search(regExp2) !== -1) {
        newValue = value.replace(regExp, '').replace(regExp2, '');
        flag = true;
      }
      if (flag === true) {
        inputEditor.find(value, {
          range: cursorRange
        });
        inputEditor.replace(newValue);
      }
    }
    else {
      //multi line comment
      value = inputEditor.getSession().getLines(cursorRange.start.row, cursorRange.end.row);
      var arrayLength = value.length;
      var firstString = value[0];
      var lastString = value[value.length-1];
      var newFirstString;
      var newLastString;

      if (firstString.search(regExp2) === -1 && lastString.search(regExp) === -1) {
        newFirstString = '/*' + firstString;
        newLastString = lastString + '*/';
        flag = true;
      }
      else if (firstString.search(regExp2) !== -1 && lastString.search(regExp) !== -1) {
        newFirstString = firstString.replace(regExp2, '');
        newLastString = lastString.replace(regExp, '');
        flag = true;
      }
      if (flag === true) {
        inputEditor.find(firstString, {
          range: cursorRange
        });
        inputEditor.replace(newFirstString);
        inputEditor.find(lastString, {
          range: cursorRange
        });
        inputEditor.replace(newLastString);
      }
    }
    cursorRange.end.column = cursorRange.end.column + 2;
    inputEditor.getSelection().setSelectionRange(cursorRange, false);
  },
  sortQueries: function() {
    this.queries = _.sortBy(this.queries, 'name' );
    this.customQueries = _.sortBy(this.customQueries, 'name' );
  },
  submitQuery: function() {
    var self = this;
    var inputEditor = ace.edit("aqlEditor");
    var data = {query: inputEditor.getValue()};

    var outputEditor = ace.edit("queryOutput");

    $.ajax({
      type: "POST",
      url: "/_api/cursor",
      data: JSON.stringify(data),
      contentType: "application/json",
      processData: false,
      success: function(data) {
        outputEditor.setValue(arangoHelper.FormatJSON(data.result));
        if(typeof Storage) {
          localStorage.setItem("queryContent", inputEditor.getValue());
          localStorage.setItem("queryOutput", outputEditor.getValue());
        }
      },
      error: function(data) {
        try {
          var temp = JSON.parse(data.responseText);
          outputEditor.setValue('[' + temp.errorNum + '] ' + temp.errorMessage);

          if(typeof Storage) {
            localStorage.setItem("queryContent", inputEditor.getValue());
            localStorage.setItem("queryOutput", outputEditor.getValue());
          }
        }
        catch (e) {
          outputEditor.setValue('ERROR');
        }
      }
    });
    outputEditor.resize();

  }

});
<|endoftext|>