<commit_before>/*
	overthrow responsive sidescroller extension
	(c) 2013: Scott Jehl, Filament Group, Inc.
	MIT License
*/

(function( w, o ){

	if( !o || !"querySelector" in w.document ){
		return;
	}

	function sendEvent( elem, evt, args, ieID ){
		// TODO needs IE8 support
		if( document.createEvent ){
			var event = document.createEvent( "Event" );
			event.initEvent( evt, true, true );
			event.overthrow = args;
			elem.dispatchEvent( event );
		}
		else {
			w.document.documentElement[ieID][ evt ] = {
				e: evt,
				overthrow: args
			};
			w.document.documentElement[ evt ]++;
		}
	}

	// NOTE not a general purpose add class, whitespace accounting done externally
	function addClass( element, classStr ) {
		element.setAttribute( "class", element.getAttribute( "class" ).replace( classStr, "" ));
		element.setAttribute( "class", element.getAttribute( "class" ) + classStr );
	}

	// NOTE not a general purpose remove class, whitespace accounting done externally
	function removeClass( element, classStr ) {
		element.setAttribute( "class", element.getAttribute( "class" ).replace( classStr, "" ));
	}

	o.sidescroller = function( elems, options ){

		var scrolls = elems,
			evtPrefix = "overthrow",
			evtNext = evtPrefix + "-next",
			evtPrev = evtPrefix + "-prev",
			disabledClassStr = " disabled",
			snapScroll = options && options.snapScroll,
			rewind = options && options.rewind,
			snapTolerance = options && options.snapTolerance !== undefined ? options.snapTolerance : 30;

		for( var i = 0; i < scrolls.length; i++ ){

			(function(){

				var thisSideScroll = scrolls[ i ],
					thisScroll = scrolls[ i ].querySelector( ".overthrow" ),
					nextPrev = w.document.createElement( "div" ),
					slideNum = 0,
					ieID = "overthrow" + (new Date().getTime()),
					handled = false,
					nextAnchor, prevAnchor;

				// prevent re-init
				if( thisSideScroll.initialized ){
					return;
				}
				thisSideScroll.initialized = true;

				thisSideScroll.setAttribute( "tabindex", "0" );

				// oldIE will need some expando event props
				if( w.document.attachEvent ){
					// these are iterators to trigger a property mutate event in IE8
					w.document.documentElement[ evtPrev ] = 0;
					w.document.documentElement[ evtNext ] = 0;
					// these for for the event data when that property iterates
					w.document.documentElement[ ieID ] = {};
					w.document.documentElement[ ieID ][ evtPrev ] = {};
					w.document.documentElement[ ieID ][ evtNext ] = {};
					thisSideScroll.ieID = ieID;
				}

				nextPrev.className = "sidescroll-nextprev-links";

				nextPrev.innerHTML = "Previous" +
					"Next";

				nextAnchor = nextPrev.querySelector( "a.sidescroll-next" );
				prevAnchor = nextPrev.querySelector( "a.sidescroll-prev" );

				function setSlideWidths(){
					var slides = thisScroll.querySelectorAll( "li" ),
						percent = 100 / slides.length + "%";
					for( var i = 0; i < slides.length; i++ ){
						slides[ i ].style.width = percent;
					}
				}

				function toggleNavigation( event ) {
					// use the active slides value already caluculated when possible
					var active = (event && event.overthrow.active) || getActiveSlides(),
					slides = thisScroll.querySelectorAll( "li" );

					removeClass( nextAnchor, disabledClassStr );
					removeClass( prevAnchor, disabledClassStr );

					if( active[0] == 0 ) {
						addClass( prevAnchor, disabledClassStr );
					} else if( active[active.length - 1] >= slides.length - 1 ) {
						addClass( nextAnchor, disabledClassStr );
					}
				}

				function getActiveSlides( left ){
					var slides = thisScroll.querySelectorAll( "li" ),
						numSlides = slides.length,
						slidesWidth = thisScroll.offsetWidth,
						slideWidth = slides[ 0 ].offsetWidth,
						scrollLeft = left !== undefined ? left : thisScroll.scrollLeft,
						startSlide = Math.round( scrollLeft / slideWidth ),
						valid = true,
						ret = [];

					startSlide = Math.max( 0, startSlide );
					startSlide = Math.min( numSlides, startSlide );

					ret[ 0 ] = startSlide;
					for( var i = 1; i < numSlides; i++ ){
						if( startSlide + (i * slideWidth) < slidesWidth){
							ret.push( startSlide + i);
						}
						else{
							valid = false;
						}
					}
					slideNum = startSlide;
					return ret;
				}

				// expose the getactiveslides function on the overthrow element
				thisSideScroll.getActiveSlides = getActiveSlides;

				function handleClick( evt ){

					var e = evt || w.event;

					if( e.preventDefault ){
						e.preventDefault();
					}
					else{
						e.returnValue = false;
					}

					if( e.type === "keydown" || ( handled === false || handled === e.type ) ){
						handled = e.type;

						o.intercept();
						var slides = thisScroll.querySelectorAll( "li" ),
							target = e.target || e.srcElement,
							slidesWidth = thisScroll.offsetWidth,
							slideWidth = slides[ 0 ].offsetWidth,
							currScroll = thisScroll.scrollLeft,
							slideNum = Math.round( currScroll / slideWidth ),
							next = (e.type !== "keydown" && target.className.indexOf( "next" ) > -1) || e.keyCode === 39,
							newSlide = slideNum + ( next ? 1 : -1 ),
							newScroll = slideWidth * newSlide,
							scrollWidth = thisScroll.scrollWidth - slidesWidth;

						// if can't go left, go to end
						if( rewind ){

							if( newScroll < 0 ){
								newScroll = scrollWidth;
							}
							else if( newScroll > scrollWidth ){
								newScroll = 0;
							}
						}
						else {
							if( newScroll < 0 ){
								newScroll = 0;
							}
							else if( newScroll > scrollWidth ){
								newScroll = scrollWidth;
							}
						}

						var newActive = getActiveSlides( newScroll );

						if( newActive[ 0 ] !== slideNum ){

							o.toss( thisScroll, { left: newScroll } );

							sendEvent(
								thisSideScroll, // elem to receive event
								next ? evtNext : evtPrev, // evt name
								{
									active: newActive, // active slides
									originalEvent: e
								},
								ieID
							);
						}

						setTimeout( function(){ handled = false; }, 900 );
					}
				}

				var scrollStart = false;
				function handleSnap( e ){
					o.intercept();
					var slideWidth = thisScroll.querySelector( "li" ).offsetWidth,
						currScroll = thisScroll.scrollLeft,
						newSlide = Math.round( currScroll / slideWidth );

					if( scrollStart !== false ){
						var distScrolled = currScroll - scrollStart;
						if( Math.abs( distScrolled ) > snapTolerance ){
							newSlide = slideNum + ( distScrolled > 0 ? 1 : -1 );
						}

					}

					var newScroll = slideWidth * newSlide;

					o.toss( thisScroll, { left: newScroll, duration: 20 } );

					if( slideNum !== newSlide ){
						sendEvent(
							thisSideScroll, // elem to receive event
							newSlide > slideNum ? evtNext : evtPrev, // evt name
							{
								active: getActiveSlides( newScroll ), // active slides
								originalEvent: e
							},
							ieID
						);
						slideNum = newSlide;
					}
				}

				var debounce;
				function handleResize( e ){
					clearTimeout(debounce);
					debounce = setTimeout(function(){
						handleSnap( e );
					}, 100);
				}

				var debouncedos;
				function handleScroll( e ){
					if( overthrow.tossing ){
						return;
					}
					if( scrollStart === false ){
						scrollStart = thisScroll.scrollLeft;
					}
					clearTimeout( debouncedos );
					debouncedos = setTimeout(function(){
						if( snapScroll ){
							handleSnap( e );
						} else {
							// NOTE handleSnap triggers the nav events
							toggleNavigation();
						}

						scrollStart = false;
					}, 200);
				}

				function handleKey( e ){
					if( e.keyCode === 39 || e.keyCode === 37 ){
						handleClick( e );
					}
				}

				if( w.document.addEventListener ){
					nextPrev.addEventListener( "click", handleClick, false );
					nextPrev.addEventListener( "touchend", handleClick, false );
					w.addEventListener( "resize", handleResize, false );
					scrolls[ i ].addEventListener( "keydown", handleKey, false );

					thisScroll.addEventListener( "scroll", handleScroll, false );
					thisSideScroll.addEventListener( evtNext, toggleNavigation, false );
					thisSideScroll.addEventListener( evtPrev, toggleNavigation, false );
				}
		 		else if( w.document.attachEvent ){
		 			nextPrev.attachEvent( "onclick", handleClick, false );
					w.attachEvent( "onresize", handleResize, false );
					scrolls[ i ].attachEvent( "onkeydown", handleKey, false );

					thisScroll.attachEvent( "onscroll", handleScroll, false );
					thisSideScroll.attachEvent( evtNext, toggleNavigation, false );
					thisSideScroll.attachEvent( evtPrev, toggleNavigation, false );
		 		}

				thisSideScroll.insertBefore( nextPrev, thisScroll );

				setSlideWidths();

			}());

		}

	};

	o.sidescroller.onEvent = function( evt, elem, callback ){
		function cb( args ){
			var e = {
				type: evt,
				target: elem,
				overthrow: args.overthrow
			};
			callback( e );
		}
		if( w.document.addEventListener ){
			elem.addEventListener( evt, cb );
		}
		else if( w.document.attachEvent ){
			w.document.documentElement.attachEvent( "onpropertychange", function( event ) {
				if( event.propertyName === evt ){
					cb( w.document.documentElement[ elem.ieID ][ evt ] );
				}
			});
		}
	};

}( this, this.overthrow ));<commit_msg>ignore nav toggle on rewind<commit_after>/*
	overthrow responsive sidescroller extension
	(c) 2013: Scott Jehl, Filament Group, Inc.
	MIT License
*/

(function( w, o ){

	if( !o || !"querySelector" in w.document ){
		return;
	}

	function sendEvent( elem, evt, args, ieID ){
		// TODO needs IE8 support
		if( document.createEvent ){
			var event = document.createEvent( "Event" );
			event.initEvent( evt, true, true );
			event.overthrow = args;
			elem.dispatchEvent( event );
		}
		else {
			w.document.documentElement[ieID][ evt ] = {
				e: evt,
				overthrow: args
			};
			w.document.documentElement[ evt ]++;
		}
	}

	// NOTE not a general purpose add class, whitespace accounting done externally
	function addClass( element, classStr ) {
		element.setAttribute( "class", element.getAttribute( "class" ).replace( classStr, "" ));
		element.setAttribute( "class", element.getAttribute( "class" ) + classStr );
	}

	// NOTE not a general purpose remove class, whitespace accounting done externally
	function removeClass( element, classStr ) {
		element.setAttribute( "class", element.getAttribute( "class" ).replace( classStr, "" ));
	}

	o.sidescroller = function( elems, options ){

		var scrolls = elems,
			evtPrefix = "overthrow",
			evtNext = evtPrefix + "-next",
			evtPrev = evtPrefix + "-prev",
			disabledClassStr = " disabled",
			snapScroll = options && options.snapScroll,
			rewind = options && options.rewind,
			snapTolerance = options && options.snapTolerance !== undefined ? options.snapTolerance : 30;

		for( var i = 0; i < scrolls.length; i++ ){

			(function(){

				var thisSideScroll = scrolls[ i ],
					thisScroll = scrolls[ i ].querySelector( ".overthrow" ),
					nextPrev = w.document.createElement( "div" ),
					slideNum = 0,
					ieID = "overthrow" + (new Date().getTime()),
					handled = false,
					nextAnchor, prevAnchor;

				// prevent re-init
				if( thisSideScroll.initialized ){
					return;
				}
				thisSideScroll.initialized = true;

				thisSideScroll.setAttribute( "tabindex", "0" );

				// oldIE will need some expando event props
				if( w.document.attachEvent ){
					// these are iterators to trigger a property mutate event in IE8
					w.document.documentElement[ evtPrev ] = 0;
					w.document.documentElement[ evtNext ] = 0;
					// these for for the event data when that property iterates
					w.document.documentElement[ ieID ] = {};
					w.document.documentElement[ ieID ][ evtPrev ] = {};
					w.document.documentElement[ ieID ][ evtNext ] = {};
					thisSideScroll.ieID = ieID;
				}

				nextPrev.className = "sidescroll-nextprev-links";

				nextPrev.innerHTML = "Previous" +
					"Next";

				nextAnchor = nextPrev.querySelector( "a.sidescroll-next" );
				prevAnchor = nextPrev.querySelector( "a.sidescroll-prev" );

				function setSlideWidths(){
					var slides = thisScroll.querySelectorAll( "li" ),
						percent = 100 / slides.length + "%";
					for( var i = 0; i < slides.length; i++ ){
						slides[ i ].style.width = percent;
					}
				}

				function toggleNavigation( event ) {
					if( rewind ) {
						return;
					}

					// use the active slides value already caluculated when possible
					var active = (event && event.overthrow.active) || getActiveSlides(),
					slides = thisScroll.querySelectorAll( "li" );

					removeClass( nextAnchor, disabledClassStr );
					removeClass( prevAnchor, disabledClassStr );

					if( active[0] == 0 ) {
						addClass( prevAnchor, disabledClassStr );
					} else if( active[active.length - 1] >= slides.length - 1 ) {
						addClass( nextAnchor, disabledClassStr );
					}
				}

				function getActiveSlides( left ){
					var slides = thisScroll.querySelectorAll( "li" ),
						numSlides = slides.length,
						slidesWidth = thisScroll.offsetWidth,
						slideWidth = slides[ 0 ].offsetWidth,
						scrollLeft = left !== undefined ? left : thisScroll.scrollLeft,
						startSlide = Math.round( scrollLeft / slideWidth ),
						valid = true,
						ret = [];

					startSlide = Math.max( 0, startSlide );
					startSlide = Math.min( numSlides, startSlide );

					ret[ 0 ] = startSlide;
					for( var i = 1; i < numSlides; i++ ){
						if( startSlide + (i * slideWidth) < slidesWidth){
							ret.push( startSlide + i);
						}
						else{
							valid = false;
						}
					}
					slideNum = startSlide;
					return ret;
				}

				// expose the getactiveslides function on the overthrow element
				thisSideScroll.getActiveSlides = getActiveSlides;

				function handleClick( evt ){

					var e = evt || w.event;

					if( e.preventDefault ){
						e.preventDefault();
					}
					else{
						e.returnValue = false;
					}

					if( e.type === "keydown" || ( handled === false || handled === e.type ) ){
						handled = e.type;

						o.intercept();
						var slides = thisScroll.querySelectorAll( "li" ),
							target = e.target || e.srcElement,
							slidesWidth = thisScroll.offsetWidth,
							slideWidth = slides[ 0 ].offsetWidth,
							currScroll = thisScroll.scrollLeft,
							slideNum = Math.round( currScroll / slideWidth ),
							next = (e.type !== "keydown" && target.className.indexOf( "next" ) > -1) || e.keyCode === 39,
							newSlide = slideNum + ( next ? 1 : -1 ),
							newScroll = slideWidth * newSlide,
							scrollWidth = thisScroll.scrollWidth - slidesWidth;

						// if can't go left, go to end
						if( rewind ){

							if( newScroll < 0 ){
								newScroll = scrollWidth;
							}
							else if( newScroll > scrollWidth ){
								newScroll = 0;
							}
						}
						else {
							if( newScroll < 0 ){
								newScroll = 0;
							}
							else if( newScroll > scrollWidth ){
								newScroll = scrollWidth;
							}
						}

						var newActive = getActiveSlides( newScroll );

						if( newActive[ 0 ] !== slideNum ){

							o.toss( thisScroll, { left: newScroll } );

							sendEvent(
								thisSideScroll, // elem to receive event
								next ? evtNext : evtPrev, // evt name
								{
									active: newActive, // active slides
									originalEvent: e
								},
								ieID
							);
						}

						setTimeout( function(){ handled = false; }, 900 );
					}
				}

				var scrollStart = false;
				function handleSnap( e ){
					o.intercept();
					var slideWidth = thisScroll.querySelector( "li" ).offsetWidth,
						currScroll = thisScroll.scrollLeft,
						newSlide = Math.round( currScroll / slideWidth );

					if( scrollStart !== false ){
						var distScrolled = currScroll - scrollStart;
						if( Math.abs( distScrolled ) > snapTolerance ){
							newSlide = slideNum + ( distScrolled > 0 ? 1 : -1 );
						}

					}

					var newScroll = slideWidth * newSlide;

					o.toss( thisScroll, { left: newScroll, duration: 20 } );

					if( slideNum !== newSlide ){
						sendEvent(
							thisSideScroll, // elem to receive event
							newSlide > slideNum ? evtNext : evtPrev, // evt name
							{
								active: getActiveSlides( newScroll ), // active slides
								originalEvent: e
							},
							ieID
						);
						slideNum = newSlide;
					}
				}

				var debounce;
				function handleResize( e ){
					clearTimeout(debounce);
					debounce = setTimeout(function(){
						handleSnap( e );
					}, 100);
				}

				var debouncedos;
				function handleScroll( e ){
					if( overthrow.tossing ){
						return;
					}
					if( scrollStart === false ){
						scrollStart = thisScroll.scrollLeft;
					}
					clearTimeout( debouncedos );
					debouncedos = setTimeout(function(){
						if( snapScroll ){
							handleSnap( e );
						} else {
							// NOTE handleSnap triggers the nav events
							toggleNavigation();
						}

						scrollStart = false;
					}, 200);
				}

				function handleKey( e ){
					if( e.keyCode === 39 || e.keyCode === 37 ){
						handleClick( e );
					}
				}

				if( w.document.addEventListener ){
					nextPrev.addEventListener( "click", handleClick, false );
					nextPrev.addEventListener( "touchend", handleClick, false );
					w.addEventListener( "resize", handleResize, false );
					scrolls[ i ].addEventListener( "keydown", handleKey, false );

					thisScroll.addEventListener( "scroll", handleScroll, false );
					thisSideScroll.addEventListener( evtNext, toggleNavigation, false );
					thisSideScroll.addEventListener( evtPrev, toggleNavigation, false );
				}
		 		else if( w.document.attachEvent ){
		 			nextPrev.attachEvent( "onclick", handleClick, false );
					w.attachEvent( "onresize", handleResize, false );
					scrolls[ i ].attachEvent( "onkeydown", handleKey, false );

					thisScroll.attachEvent( "onscroll", handleScroll, false );
					thisSideScroll.attachEvent( evtNext, toggleNavigation, false );
					thisSideScroll.attachEvent( evtPrev, toggleNavigation, false );
		 		}

				thisSideScroll.insertBefore( nextPrev, thisScroll );

				setSlideWidths();

			}());

		}

	};

	o.sidescroller.onEvent = function( evt, elem, callback ){
		function cb( args ){
			var e = {
				type: evt,
				target: elem,
				overthrow: args.overthrow
			};
			callback( e );
		}
		if( w.document.addEventListener ){
			elem.addEventListener( evt, cb );
		}
		else if( w.document.attachEvent ){
			w.document.documentElement.attachEvent( "onpropertychange", function( event ) {
				if( event.propertyName === evt ){
					cb( w.document.documentElement[ elem.ieID ][ evt ] );
				}
			});
		}
	};

}( this, this.overthrow ));<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2020 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.nanos.ruler.predicate',
  name: 'PropertyIsClass',

  documentation: 'Returns true if property propName is classOf of',

  extends: 'foam.mlang.predicate.AbstractPredicate',
  implements: ['foam.core.Serializable'],

  javaImports: [
    'foam.core.FObject',
    'static foam.mlang.MLang.*',
    'foam.mlang.predicate.IsClassOf'
  ],
  properties: [
    {
      class: 'String',
      name: 'propName'
    },
    {
      class: 'Class',
      name: 'of',
      documentation: 'class that we want the object to be a class of'
    },
    {
      class: 'Boolean',
      name: 'isNew',
      value: true
    }
  ],
  methods: [
    {
      name: 'f',
      javaCode: `

      if ( getIsNew() ) {
        FObject nu  = (FObject) NEW_OBJ.f(obj);
         return (new IsClassOf(getOf())).f(nu.getProperty(getPropName()));
      }
      FObject old = (FObject) OLD_OBJ.f(obj);
      if ( old != null )
         return (new IsClassOf(getOf())).f(old.getProperty(getPropName()));
      return false;
      `
    }
  ]
});
<commit_msg>Add null check (#4099)<commit_after>/**
 * @license
 * Copyright 2020 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.nanos.ruler.predicate',
  name: 'PropertyIsClass',

  documentation: 'Returns true if property propName is classOf of',

  extends: 'foam.mlang.predicate.AbstractPredicate',
  implements: ['foam.core.Serializable'],

  javaImports: [
    'foam.core.FObject',
    'static foam.mlang.MLang.*',
    'foam.mlang.predicate.IsClassOf'
  ],
  properties: [
    {
      class: 'String',
      name: 'propName'
    },
    {
      class: 'Class',
      name: 'of',
      documentation: 'class that we want the object to be a class of'
    },
    {
      class: 'Boolean',
      name: 'isNew',
      value: true
    }
  ],
  methods: [
    {
      name: 'f',
      javaCode: `

      if ( getIsNew() ) {
        FObject nu  = (FObject) NEW_OBJ.f(obj);
        Object value = nu.getProperty(getPropName());
        return value != null && (new IsClassOf(getOf())).f(value);
      }
      FObject old = (FObject) OLD_OBJ.f(obj);
      if ( old != null ) {
        Object value = old.getProperty(getPropName());
        return value != null && (new IsClassOf(getOf())).f(value);
      }
      return false;
      `
    }
  ]
});
<|endoftext|>


<commit_before>define(function (require, exports, module)
{
    "use strict";

    var EditorManager        = brackets.getModule("editor/EditorManager"),
    ExtensionUtils           = brackets.getModule("utils/ExtensionUtils"),
    Strings                  = brackets.getModule("strings"),
	DocumentManager          = brackets.getModule("document/DocumentManager"),
    QuickFormToolTemplate    = require("text!ui/QuickFormToolTemplate.html");

	var untitledhtml5index = 1;
    var untitledcssindex = 1;
    var untitledjsindex = 1;

    function quickFormToolProvider()
    {
        try
        {

            var $element = $(Mustache.render(QuickFormToolTemplate, Strings));

            $element.find(".qft-form").click(function () { quickFormTool("form"); });
            $element.find(".qft-textfield").click(function () { quickFormTool("textfield"); });
            $element.find(".qft-textarea").click(function () { quickFormTool("textarea"); });
            $element.find(".qft-button").click(function () { quickFormTool("button"); });
            $element.find(".qft-checkbox").click(function () { quickFormTool("checkbox"); });
            $element.find(".qft-radiobutton").click(function () { quickFormTool("radiobutton"); });
            $element.find(".qft-listmenu").click(function () { quickFormTool("listmenu"); });
            $element.find(".qft-imagebutton").click(function () { quickFormTool("imagebutton"); });
            $element.find(".qft-imagefield").click(function () { quickFormTool("imagefield"); });
            $element.find(".qft-filefield").click(function () { quickFormTool("filefield"); });
            $element.find(".qft-hiddenfield").click(function () { quickFormTool("hiddenfield"); });
			$element.find(".qft-link").click(function () { quickFormTool("link"); });

            $element.find(".qft-html5audio").click(function () { quickFormTool("html5audio"); });
            $element.find(".qft-html5video").click(function () { quickFormTool("html5video"); });
            $element.find(".qft-embedflash").click(function () { quickFormTool("embedflash"); });

			$element.find(".qft-html5file").click(function () { quickFormTool("html5file"); });
			$element.find(".qft-cssfile").click(function () { quickFormTool("cssfile"); });
			$element.find(".qft-jsfile").click(function () { quickFormTool("jsfile"); });
			$element.find(".qftnotify").click(function () { $element.find(".qftblock").toggleClass("qftblock-exp");
                                                            $element.find(".qftnotify").toggleClass("qftnotify-exp"); });
			$element.find(".qft-unpin").click(function () {$element.find(".qftblock").toggleClass("qftblock-exp");

                                                         $element.find(".qft-unpin").toggleClass("qft-pin"); });

            $($element).insertBefore("#editor-holder");
        }
        catch(e)
        {
            alert("Error: " + e);
        }
    }
    var loadfunction = quickFormToolProvider();
    function quickFormTool(_class)
    {
        try
		{
            if (true)
            {
                switch (_class)
                {
                    case "form":
                        handleCommand("<form action=\"\" method=\"get\"></form>");
                    break;

                    case "textfield":
                        handleCommand("<input type=\"text\" name=\"textfield\" size=\"25\" value=\"TextField\">");
                    break;

                    case "textarea":
                        handleCommand("<textarea name=\"\" cols=\"25\" rows=\"5\">TextArea</textarea>");
                    break;

                    case "button":
                        handleCommand("<input type=\"button\" name=\"button\" value=\"Button\">");
                    break;

                    case "checkbox":
                        handleCommand("<input type=\"checkbox\" name=\"checkbox\" value=\"CheckBox\">");
                    break;

                    case "radiobutton":
                        handleCommand("<input type=\"radio\" name=\"radiogroup\" value=\"RadioButton\">");
                    break;

                    case "listmenu":
                        handleCommand("<select name=\"selectoptions\">\n\t<option value=\"option1\">Option 1</option>\n\t<option value=\"option2\">Option 2</option>\n</select>");
                    break;

                    case "imagebutton":
                        handleCommand("<input type=\"image\" name=\"\" src=\"\" width=\"\" height=\"\">");
                    break;

                    case "imagefield":
                        handleCommand("");
                    break;

                    case "filefield":
                        handleCommand("<input type=\"file\" name=\"filefield\">");
                    break;

                    case "hiddenfield":
                        handleCommand("<input type=\"hidden\" name=\"hiddenfield\" value=\"hiddenfieldvalue\">");
                    break;

					case "link":
                        handleCommand("");
                    break;

                    case "html5audio":
                        handleCommand("<audio controls>\n\t<source src=\"audio.ogg\" type=\"audio/ogg\">\n\t<source src=\"audio.mp3\" type=\"audio/mpeg\">\n\tYour browser does not support the audio element.\n</audio> ");
                    break;

                    case "html5video":
                        handleCommand("<video width=\"320\" height=\"240\" controls>\n\t<source src=\"movie.mp4\" type=\"video/mp4\">\n\t<source src=\"movie.ogg\" type=\"video/ogg\">\n\tYour browser does not support the video tag.\n</video>");
                    break;

                    case "embedflash":
                        handleCommand("<object data=\"flashfile.swf\" width=\"\" height=\"\"></object>");
                    break;

					case "html5file":
                        var doc = DocumentManager.createUntitledDocument(untitledhtml5index++, ".html");
						handleFileNew(doc);
						handleCommand(html5page);
					break;

					case "cssfile":
                        makeCSSFile();
					break;

					case "jsfile":
                        makeJSFile();
                    break;
                }
            }
        }
        catch(e)
        {
            alert("Error: " + e);
        }
    };

    function makeCSSFile()
    {
        var doc = DocumentManager.createUntitledDocument(untitledcssindex++, ".css");
        handleCommand("<link rel=\"stylesheet\" href=\"Untitled-" + untitledcssindex + ".css\">");
        handleFileNew(doc);
        handleCommand("html\n{\n\t\n\}\n");
    }
    function makeJSFile()
    {
        var doc = DocumentManager.createUntitledDocument(untitledjsindex++, ".js");
        handleCommand("


<commit_before>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @noflow
 */

'use strict';

const path = require('path');
const assert = require('assert');
const babel = require('@babel/core');
const {
  copyFile,
  writeFile,
  rmdirRecursive,
  mkdirRecursive,
  readdirRecursive,
} = require('./utils');

if (require.main === module) {
  rmdirRecursive('./dist');
  mkdirRecursive('./dist');

  copyFile('./LICENSE', './dist/LICENSE');
  copyFile('./README.md', './dist/README.md');
  writeFile('./dist/package.json', buildPackageJSON());

  const srcFiles = readdirRecursive('./src', { ignoreDir: /^__.*__$/ });
  for (const filepath of srcFiles) {
    if (filepath.endsWith('.js')) {
      buildJSFile(filepath);
    }
  }
}

function buildJSFile(filepath) {
  const srcPath = path.join('./src', filepath);
  const destPath = path.join('./dist', filepath);
  const cjs = babel.transformFileSync(srcPath, { envName: 'cjs' });
  const mjs = babel.transformFileSync(srcPath, { envName: 'mjs' });

  copyFile(srcPath, destPath + '.flow');
  writeFile(destPath, cjs.code);
  writeFile(destPath.replace(/\.js$/, '.mjs'), mjs.code);
}

function buildPackageJSON() {
  const packageJSON = require('../package.json');
  delete packageJSON.scripts;
  delete packageJSON.devDependencies;

  const { version } = packageJSON;
  const match = /^[0-9]+\.[0-9]+\.[0-9]+-?([^.]*)/.exec(version);
  assert(match, 'Version does not match semver spec.');
  const tag = match[1];
  assert(!tag || tag === 'rc', 'Only "rc" tag is supported.');

  assert(!packageJSON.publishConfig, 'Can not override "publishConfig".');
  packageJSON.publishConfig = { tag: tag || 'latest' };
  return JSON.stringify(packageJSON, null, 2);
}
<commit_msg>build: Add new lines to "*.js" and "*.mjs" files (#1892)<commit_after>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @noflow
 */

'use strict';

const path = require('path');
const assert = require('assert');
const babel = require('@babel/core');
const {
  copyFile,
  writeFile,
  rmdirRecursive,
  mkdirRecursive,
  readdirRecursive,
} = require('./utils');

if (require.main === module) {
  rmdirRecursive('./dist');
  mkdirRecursive('./dist');

  copyFile('./LICENSE', './dist/LICENSE');
  copyFile('./README.md', './dist/README.md');
  writeFile('./dist/package.json', buildPackageJSON());

  const srcFiles = readdirRecursive('./src', { ignoreDir: /^__.*__$/ });
  for (const filepath of srcFiles) {
    if (filepath.endsWith('.js')) {
      buildJSFile(filepath);
    }
  }
}

function babelBuild(srcPath, envName) {
  return babel.transformFileSync(srcPath, { envName }).code + '\n';
}

function buildJSFile(filepath) {
  const srcPath = path.join('./src', filepath);
  const destPath = path.join('./dist', filepath);

  copyFile(srcPath, destPath + '.flow');
  writeFile(destPath, babelBuild(srcPath, 'cjs'));
  writeFile(destPath.replace(/\.js$/, '.mjs'), babelBuild(srcPath, 'mjs'));
}

function buildPackageJSON() {
  const packageJSON = require('../package.json');
  delete packageJSON.scripts;
  delete packageJSON.devDependencies;

  const { version } = packageJSON;
  const match = /^[0-9]+\.[0-9]+\.[0-9]+-?([^.]*)/.exec(version);
  assert(match, 'Version does not match semver spec.');
  const tag = match[1];
  assert(!tag || tag === 'rc', 'Only "rc" tag is supported.');

  assert(!packageJSON.publishConfig, 'Can not override "publishConfig".');
  packageJSON.publishConfig = { tag: tag || 'latest' };
  return JSON.stringify(packageJSON, null, 2);
}
<|endoftext|>


<commit_before>const { app } = require('electron')
const chokidar = require('chokidar')
const fs = require('fs')
const { spawn } = require('child_process')
const path = require('path')

// Main file poses a special case, as its changes are
// only effective when the process is restarted (hard reset)
const appPath = app.getAppPath()
const config = require(path.join(appPath, 'package.json'))
const mainFile = path.join(appPath, config.main || 'index.js')
const ignoredPaths = [mainFile, /node_modules|[/\\]\./]

/**
 * Creates a callback for hard resets.
 *
 * @param {String} eXecutable path to electron executable
 * @param {String} hardResetMethod method to restart electron
 * @returns {Function} handler to pass to chokidar
 */
const createHardresetHandler = (eXecutable, hardResetMethod, argv) =>
  () => {
    // Detaching child is useful when in Windows to let child
    // live after the parent is killed
    let args = (argv || []).concat([appPath])
    let child = spawn(eXecutable, args, {
      detached: true,
      stdio: 'inherit'
    })
    child.unref()
    // Kamikaze!

    // In cases where an app overrides the default closing or quiting actions
    // firing an `app.quit()` may not actually quit the app. In these cases
    // you can use `app.exit()` to gracefully close the app.
    if (hardResetMethod === 'exit') {
      app.exit()
    } else {
      app.quit()
    }
  }

/**
 * Creates main chokidar watcher for soft resets.
 *
 * @param {String|Array<String>} glob path, glob, or array to pass to chokidar
 * @param {Object} options chokidar options
 */
const createWatcher = (glob, options = {}) => {
  // Watch everything but the node_modules folder and main file
  // main file changes are only effective if hard reset is possible
  let opts = Object.assign({ ignored: ignoredPaths }, options)
  return chokidar.watch(glob, opts)
}

module.exports = (glob, options = {}) => {
  let browserWindows = []
  let watcher = createWatcher(glob, options)
  let hardWatcher = createWatcher(mainFile, options)

  // Callback function to be executed:
  // I) soft reset: reload browser windows
  let softResetHandler = () => browserWindows.forEach(bw => bw.webContents.reloadIgnoringCache())
  // II) hard reset: restart the whole electron process
  let eXecutable = options.electron
  let hardResetHandler = createHardresetHandler(eXecutable, options.hardResetMethod, options.argv)

  // Add each created BrowserWindow to list of maintained items
  app.on('browser-window-created', (e, bw) => {
    browserWindows.push(bw)

    // Remove closed windows from list of maintained items
    bw.on('closed', function () {
      let i = browserWindows.indexOf(bw) // Must use current index
      browserWindows.splice(i, 1)
    })
  })

  // Enable default soft reset
  watcher.on('change', softResetHandler)

  // Preparing hard reset if electron executable is given in options
  // A hard reset is only done when the main file has changed
  if (eXecutable && fs.existsSync(eXecutable)) {
    if (options.forceHardReset === true) {
      // Watch every file for hard reset and not only the main file
      hardWatcher.add(glob)
      // Stop our default soft reset
      watcher.close()
    }

    hardWatcher.on('change', hardResetHandler)
  } else {
    console.log('Electron could not be found. No hard resets for you!')
  }
}
<commit_msg>Fix hard reset problem (fixes #57).<commit_after>const { app } = require('electron')
const chokidar = require('chokidar')
const fs = require('fs')
const { spawn } = require('child_process')
const path = require('path')

// Main file poses a special case, as its changes are
// only effective when the process is restarted (hard reset)
const appPath = app.getAppPath()
const config = require(path.join(appPath, 'package.json'))
const mainFile = path.join(appPath, config.main || 'index.js')
const ignoredPaths = /node_modules|[/\\]\./

/**
 * Creates a callback for hard resets.
 *
 * @param {String} eXecutable path to electron executable
 * @param {String} hardResetMethod method to restart electron
 * @returns {Function} handler to pass to chokidar
 */
const createHardresetHandler = (eXecutable, hardResetMethod, argv) =>
  () => {
    // Detaching child is useful when in Windows to let child
    // live after the parent is killed
    let args = (argv || []).concat([appPath])
    let child = spawn(eXecutable, args, {
      detached: true,
      stdio: 'inherit'
    })
    child.unref()
    // Kamikaze!

    // In cases where an app overrides the default closing or quiting actions
    // firing an `app.quit()` may not actually quit the app. In these cases
    // you can use `app.exit()` to gracefully close the app.
    if (hardResetMethod === 'exit') {
      app.exit()
    } else {
      app.quit()
    }
  }

module.exports = (glob, options = {}) => {
  let browserWindows = []
  let watcher = chokidar.watch(glob, Object.assign({ ignored: [ignoredPaths, mainFile] }, options))

  // Callback function to be executed:
  // I) soft reset: reload browser windows
  let softResetHandler = () => browserWindows.forEach(bw => bw.webContents.reloadIgnoringCache())
  // II) hard reset: restart the whole electron process
  let eXecutable = options.electron
  let hardResetHandler = createHardresetHandler(eXecutable, options.hardResetMethod, options.argv)

  // Add each created BrowserWindow to list of maintained items
  app.on('browser-window-created', (e, bw) => {
    browserWindows.push(bw)

    // Remove closed windows from list of maintained items
    bw.on('closed', function () {
      let i = browserWindows.indexOf(bw) // Must use current index
      browserWindows.splice(i, 1)
    })
  })

  // Enable default soft reset
  watcher.on('change', softResetHandler)

  // Preparing hard reset if electron executable is given in options
  // A hard reset is only done when the main file has changed
  if (eXecutable && fs.existsSync(eXecutable)) {
    let hardWatcher = chokidar.watch(mainFile, Object.assign({ ignored: [ignoredPaths] }, options))

    if (options.forceHardReset === true) {
      // Watch every file for hard reset and not only the main file
      hardWatcher.add(glob)
      // Stop our default soft reset
      watcher.close()
    }

    hardWatcher.once('change', hardResetHandler)
  } else {
    console.log('Electron could not be found. No hard resets for you!')
  }
}
<|endoftext|>


<commit_before>(function() {
    var httpsEnabled = window.location.protocol == "https:";
    var url = (httpsEnabled ? 'wss://' : 'ws://') + window.location.host + window.location.pathname + 'ws';
    var protocols = ["gotty"];
    var autoReconnect = -1;

    var openWs = function() {
        var ws = new WebSocket(url, protocols);

        var term;

        var pingTimer;

        ws.onopen = function(event) {
            ws.send(gotty_auth_token);

            pingTimer = setInterval(sendPing, 30 * 1000, ws);

            hterm.defaultStorage = new lib.Storage.Local();
            hterm.defaultStorage.clear();

            term = new hterm.Terminal();

            term.getPrefs().set("send-encoding", "raw");

            term.onTerminalReady = function() {
                var io = term.io.push();

                io.onVTKeystroke = function(str) {
                    ws.send("0" + str);
                };

                io.sendString = io.onVTKeystroke;

                io.onTerminalResize = function(columns, rows) {
                    ws.send(
                        "2" + JSON.stringify(
                            {
                                columns: columns,
                                rows: rows,
                            }
                        )
                    )
                };

                term.installKeyboard();
            };

            term.decorate(document.getElementById("terminal"));
        };

        ws.onmessage = function(event) {
            data = event.data.slice(1);
            switch(event.data[0]) {
            case '0':
                term.io.writeUTF16(data);
                break;
            case '1':
                // pong
            case '2':
                term.setWindowTitle(data);
                break;
            case '3':
                preferences = JSON.parse(data);
                Object.keys(preferences).forEach(function(key) {
                    console.log("Setting " + key + ": " +  preferences[key]);
                    term.getPrefs().set(key, preferences[key]);
                });
                break;
            case '4':
                autoReconnect = JSON.parse(data);
                console.log("Enabling reconnect: " + autoReconnect + " seconds")
                break;
            }
        };

        ws.onclose = function(event) {
            if (term) {
                term.uninstallKeyboard();
                term.io.showOverlay("Connection Closed", null);
            }
            clearInterval(pingTimer);
            if (autoReconnect > 0) {
                setTimeout(openWs, autoReconnect * 1000);
            }
        };
    }

    var sendPing = function(ws) {
        ws.send("1");
    }

    openWs();
})()
<commit_msg>Do not want a warning message about zoom<commit_after>(function() {
    var httpsEnabled = window.location.protocol == "https:";
    var url = (httpsEnabled ? 'wss://' : 'ws://') + window.location.host + window.location.pathname + 'ws';
    var protocols = ["gotty"];
    var autoReconnect = -1;

    var openWs = function() {
        var ws = new WebSocket(url, protocols);

        var term;

        var pingTimer;

        ws.onopen = function(event) {
            ws.send(gotty_auth_token);

            pingTimer = setInterval(sendPing, 30 * 1000, ws);

            // Do not want a warning message about zoom
            hterm.zoomWarningMessage = '';

            hterm.defaultStorage = new lib.Storage.Local();
            hterm.defaultStorage.clear();

            term = new hterm.Terminal();

            term.getPrefs().set("send-encoding", "raw");

            term.onTerminalReady = function() {
                var io = term.io.push();

                io.onVTKeystroke = function(str) {
                    ws.send("0" + str);
                };

                io.sendString = io.onVTKeystroke;

                io.onTerminalResize = function(columns, rows) {
                    ws.send(
                        "2" + JSON.stringify(
                            {
                                columns: columns,
                                rows: rows,
                            }
                        )
                    )
                };

                term.installKeyboard();
            };

            term.decorate(document.getElementById("terminal"));
        };

        ws.onmessage = function(event) {
            data = event.data.slice(1);
            switch(event.data[0]) {
            case '0':
                term.io.writeUTF16(data);
                break;
            case '1':
                // pong
            case '2':
                term.setWindowTitle(data);
                break;
            case '3':
                preferences = JSON.parse(data);
                Object.keys(preferences).forEach(function(key) {
                    console.log("Setting " + key + ": " +  preferences[key]);
                    term.getPrefs().set(key, preferences[key]);
                });
                break;
            case '4':
                autoReconnect = JSON.parse(data);
                console.log("Enabling reconnect: " + autoReconnect + " seconds")
                break;
            }
        };

        ws.onclose = function(event) {
            if (term) {
                term.uninstallKeyboard();
                term.io.showOverlay("Connection Closed", null);
            }
            clearInterval(pingTimer);
            if (autoReconnect > 0) {
                setTimeout(openWs, autoReconnect * 1000);
            }
        };
    }

    var sendPing = function(ws) {
        ws.send("1");
    }

    openWs();
})()
<|endoftext|>


<commit_before>//imports

var express = require('express'),
//    mongoose = require('mongoose'),
    stylus = require('stylus'),
    jade = require('jade'),
    logger = require('morgan');
    bodyParser = require('body-parser');

var env = process.env.NODE_ENV = process.env.NODE_ENV || 'development';

var app = express();

//CONFIG

var path = require('path');
var rootPath = path.normalize(__dirname);

//config object
var configObj = {
    development : {
        db : "",
        rootPath: rootPath,
        port: process.env.Port || 2194
    },
    production : {
        db : "",
        rootPath: rootPath,
        port: process.env.Port || 80
    }
};

var config = configObj[env];
console.log(config);

function compile(str, path){
    return stylus(str).set('filename', path);
}

app.set('views', config.rootPath + "/app/views");
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(bodyParser());
app.use(stylus.middleware({
    src: config.rootPath + '/public',
    compile: compile
}));
app.use(express.static(config.rootPath + '/public'));

//routes

app.get('/partials/*', function(req,res){
    res.render('../../public/app/'+req.params[0]);
});

app.post('/create', function(req,res){
    postContent = {
        content: req.body.content,
        upTime: req.body.upTime,
        language: req.body.language,
        postDate : null
    };

    //validatePost

    validatePostLang = function(lang){
        if (lang === 'normal' ||
            lang === 'c' ||
            lang === 'c#' ||
            lang === 'java' ||
            lang === 'javascript' ||
            lang === 'json' ||
            lang === 'ruby' ||
            lang === 'ruby-rails' ||
            lang === 'c++' ||
            lang === 'vb' ||
            lang === 'F#' ||
            lang === 'html' ||
            lang === 'css' ||
            lang === 'stylus' ||
            lang === 'jade' ||
            lang === 'python' ||
            lang === 'sql' ||
            lang === 'md' ||
            lang === 'assembly'
            )
        {
            return true;
        }else {
            return false;
        }
    };
    console.log(validatePostLang);

    if(postContent.content === '' || postContent.upTime < 5 || !validatePostLang(postContent.language)){
        console.log(postContent);
        console.log(postContent.content === '' );
        console.log(postContent.upTime < 5);
        console.log(!validatePostLang(postContent.lang));
        console.error('failed');
        res.send({success:false});
    }
    else {
        postContent.postDate = new Date();

        console.log(postContent);
        //save paste to db and return a page withcurrent paste.

        res.send({success:true});
    }
});

app.get('/paste', function(req,res){

});

app.get('/:id', function(req,res){

});

app.get('*', function(req, res){
    res.render('index', {
        pageTitle:'Index'
    });
});

// busisness, i guess

//networking

app.listen(config.port);
console.log('Listening on port ' + config.port);
<commit_msg>Just testing something here.<commit_after>//imports

var express = require('express'),
//    mongoose = require('mongoose'),
    stylus = require('stylus'),
    jade = require('jade'),
    logger = require('morgan');
    bodyParser = require('body-parser');

var env = process.env.NODE_ENV || 'development';

var app = express();

//CONFIG

var path = require('path');
var rootPath = path.normalize(__dirname);

//config object
var configObj = {
    development : {
        db : "",
        rootPath: rootPath,
        port: process.env.Port || 2194
    },
    production : {
        db : "",
        rootPath: rootPath,
        port: process.env.Port || 80
    }
};

var config = configObj[env];
console.log(config);

function compile(str, path){
    return stylus(str).set('filename', path);
}

app.set('views', config.rootPath + "/app/views");
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(bodyParser());
app.use(stylus.middleware({
    src: config.rootPath + '/public',
    compile: compile
}));
app.use(express.static(config.rootPath + '/public'));

//routes

app.get('/partials/*', function(req,res){
    res.render('../../public/app/'+req.params[0]);
});

app.post('/create', function(req,res){
    postContent = {
        content: req.body.content,
        upTime: req.body.upTime,
        language: req.body.language,
        postDate : null
    };

    //validatePost

    validatePostLang = function(lang){
        if (lang === 'normal' ||
            lang === 'c' ||
            lang === 'c#' ||
            lang === 'java' ||
            lang === 'javascript' ||
            lang === 'json' ||
            lang === 'ruby' ||
            lang === 'ruby-rails' ||
            lang === 'c++' ||
            lang === 'vb' ||
            lang === 'F#' ||
            lang === 'html' ||
            lang === 'css' ||
            lang === 'stylus' ||
            lang === 'jade' ||
            lang === 'python' ||
            lang === 'sql' ||
            lang === 'md' ||
            lang === 'assembly'
            )
        {
            return true;
        }else {
            return false;
        }
    };
    console.log(validatePostLang);

    if(postContent.content === '' || postContent.upTime < 5 || !validatePostLang(postContent.language)){
        console.log(postContent);
        console.log(postContent.content === '' );
        console.log(postContent.upTime < 5);
        console.log(!validatePostLang(postContent.lang));
        console.error('failed');
        res.send({success:false});
    }
    else {
        postContent.postDate = new Date();

        console.log(postContent);
        //save paste to db and return a page withcurrent paste.

        res.send({success:true});
    }
});

app.get('/paste', function(req,res){

});

app.get('/:id', function(req,res){

});

app.get('*', function(req, res){
    res.render('index', {
        pageTitle:'Index'
    });
});

// busisness, i guess

//networking

app.listen(config.port);
console.log('Listening on port ' + config.port);
<|endoftext|>


<commit_before>var app = require('app');
var BrowserWindow = require('browser-window');
var Menu = require('menu');

require('crash-reporter').start();

var mainWindow = null;
var menu = null;

app.on('window-all-closed', function () {
  //if (process.platform !== 'darwin') {
    app.quit();
  //}
});

app.on('ready', function () {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600
  });

  mainWindow.loadUrl('file://' + __dirname + '/index.html');
  mainWindow.focus();

  mainWindow.on('closed', function () {
    mainWindow = null;
  });

  if (process.platform === 'darwin') {
    var osxTemplate = [
      {
        label: 'Electron',
        submenu: [
          {
            label: 'About Electron',
            selector: 'orderFrontStandardAboutPanel:'
          },
          {
            type: 'separator'
          },
          {
            label: 'Services',
            submenu: []
          },
          {
            type: 'separator'
          },
          {
            label: 'Hide Electron',
            accelerator: 'Command+H',
            selector: 'hide:'
          },
          {
            label: 'Hide Others',
            accelerator: 'Command+Shift+H',
            selector: 'hideOtherApplications:'
          },
          {
            label: 'Show All',
            selector: 'unhideAllApplications:'
          },
          {
            type: 'separator'
          },
          {
            label: 'Quit',
            accelerator: 'Command+Q',
            click: function() { app.quit(); }
          },
        ]
      },
      {
        label: 'Edit',
        submenu: [
          {
            label: 'Undo',
            accelerator: 'Command+Z',
            selector: 'undo:'
          },
          {
            label: 'Redo',
            accelerator: 'Shift+Command+Z',
            selector: 'redo:'
          },
          {
            type: 'separator'
          },
          {
            label: 'Cut',
            accelerator: 'Command+X',
            selector: 'cut:'
          },
          {
            label: 'Copy',
            accelerator: 'Command+C',
            selector: 'copy:'
          },
          {
            label: 'Paste',
            accelerator: 'Command+V',
            selector: 'paste:'
          },
          {
            label: 'Select All',
            accelerator: 'Command+A',
            selector: 'selectAll:'
          },
        ]
      },
      {
        label: 'Page',
        submenu: [
          {
            label: 'Home',
            click: function () {
              mainWindow.webContents.send('transitionTo', 'home');
            }
          },
          {
            label: 'About',
            click: function () {
              mainWindow.webContents.send('transitionTo', 'about');
            }
          },
          {
            label: 'Contact',
            click: function () {
              mainWindow.webContents.send('transitionTo', 'contact');
            }
          }
        ]
      },
      {
        label: 'View',
        submenu: [
          {
            label: 'Reload',
            accelerator: 'Command+R',
            click: function() { mainWindow.restart(); }
          },
          {
            label: 'Toggle Fullscreen',
            click: function() {
              mainWindow.setFullScreen(!mainWindow.isFullScreen());
            }
          },
          {
            label: 'Toggle DevTools',
            accelerator: 'Alt+Command+I',
            click: function() { mainWindow.toggleDevTools(); }
          },
        ]
      },
      {
        label: 'Window',
        submenu: [
          {
            label: 'Minimize',
            accelerator: 'Command+M',
            selector: 'performMiniaturize:'
          },
          {
            label: 'Close',
            accelerator: 'Command+W',
            selector: 'performClose:'
          },
          {
            type: 'separator'
          },
          {
            label: 'Bring All to Front',
            selector: 'arrangeInFront:'
          },
        ]
      },
    ];

    menu = Menu.buildFromTemplate(osxTemplate);
    Menu.setApplicationMenu(menu);
  } else {
    var template = [
      {
        label: '&File',
        submenu: [
          {
            label: '&Open',
            accelerator: 'Ctrl+O',
          },
          {
            label: '&Close',
            accelerator: 'Ctrl+W',
            click: function() { mainWindow.close(); }
          },
        ]
      },
      {
        label: 'Page',
        submenu: [
          {
            label: 'Home',
            click: function () {
              mainWindow.webContents.send('transitionTo', 'home');
            }
          },
          {
            label: 'About',
            click: function () {
              mainWindow.webContents.send('transitionTo', 'about');
            }
          },
          {
            label: 'Contact',
            click: function () {
              mainWindow.webContents.send('transitionTo', 'contact');
            }
          }
        ]
      },
      {
        label: '&View',
        submenu: [
          {
            label: '&Reload',
            accelerator: 'Ctrl+R',
            click: function() { mainWindow.restart(); }
          },
          {
            label: 'Toggle &Fullscreen',
            click: function() {
              mainWindow.setFullScreen(!mainWindow.isFullScreen());
            }
          },
          {
            label: '&Toggle DevTools',
            accelerator: 'Alt+Ctrl+I',
            click: function() { mainWindow.toggleDevTools(); }
          },
        ]
      },
    ];

    menu = Menu.buildFromTemplate(template);
    mainWindow.setMenu(menu);
  }
});
<commit_msg>Simple Dock menu for OS X<commit_after>var app = require('app');
var BrowserWindow = require('browser-window');
var Menu = require('menu');

require('crash-reporter').start();

var mainWindow = null;
var menu = null;

app.on('window-all-closed', function () {
  //if (process.platform !== 'darwin') {
    app.quit();
  //}
});

app.on('ready', function () {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600
  });

  mainWindow.loadUrl('file://' + __dirname + '/index.html');
  mainWindow.focus();

  mainWindow.on('closed', function () {
    mainWindow = null;
  });

  // Dock Menu (OSX)
  if (process.platform === 'darwin') {
    var dockMenu = Menu.buildFromTemplate([
      { label: 'New Window', click: function() { console.log('New Window'); } },
      { label: 'New Window with Settings', submenu: [
        { label: 'Basic' },
        { label: 'Pro'},
      ]},
      { label: 'New Command...'},
    ]);
    app.dock.setMenu(dockMenu);
  }

  // Application Menu
  if (process.platform === 'darwin') {
    var osxTemplate = [
      {
        label: 'Electron',
        submenu: [
          {
            label: 'About Electron',
            selector: 'orderFrontStandardAboutPanel:'
          },
          {
            type: 'separator'
          },
          {
            label: 'Services',
            submenu: []
          },
          {
            type: 'separator'
          },
          {
            label: 'Hide Electron',
            accelerator: 'Command+H',
            selector: 'hide:'
          },
          {
            label: 'Hide Others',
            accelerator: 'Command+Shift+H',
            selector: 'hideOtherApplications:'
          },
          {
            label: 'Show All',
            selector: 'unhideAllApplications:'
          },
          {
            type: 'separator'
          },
          {
            label: 'Quit',
            accelerator: 'Command+Q',
            click: function() { app.quit(); }
          },
        ]
      },
      {
        label: 'Edit',
        submenu: [
          {
            label: 'Undo',
            accelerator: 'Command+Z',
            selector: 'undo:'
          },
          {
            label: 'Redo',
            accelerator: 'Shift+Command+Z',
            selector: 'redo:'
          },
          {
            type: 'separator'
          },
          {
            label: 'Cut',
            accelerator: 'Command+X',
            selector: 'cut:'
          },
          {
            label: 'Copy',
            accelerator: 'Command+C',
            selector: 'copy:'
          },
          {
            label: 'Paste',
            accelerator: 'Command+V',
            selector: 'paste:'
          },
          {
            label: 'Select All',
            accelerator: 'Command+A',
            selector: 'selectAll:'
          },
        ]
      },
      {
        label: 'Page',
        submenu: [
          {
            label: 'Home',
            click: function () {
              mainWindow.webContents.send('transitionTo', 'home');
            }
          },
          {
            label: 'About',
            click: function () {
              mainWindow.webContents.send('transitionTo', 'about');
            }
          },
          {
            label: 'Contact',
            click: function () {
              mainWindow.webContents.send('transitionTo', 'contact');
            }
          }
        ]
      },
      {
        label: 'View',
        submenu: [
          {
            label: 'Reload',
            accelerator: 'Command+R',
            click: function() { mainWindow.restart(); }
          },
          {
            label: 'Toggle Fullscreen',
            click: function() {
              mainWindow.setFullScreen(!mainWindow.isFullScreen());
            }
          },
          {
            label: 'Toggle DevTools',
            accelerator: 'Alt+Command+I',
            click: function() { mainWindow.toggleDevTools(); }
          },
        ]
      },
      {
        label: 'Window',
        submenu: [
          {
            label: 'Minimize',
            accelerator: 'Command+M',
            selector: 'performMiniaturize:'
          },
          {
            label: 'Close',
            accelerator: 'Command+W',
            selector: 'performClose:'
          },
          {
            type: 'separator'
          },
          {
            label: 'Bring All to Front',
            selector: 'arrangeInFront:'
          },
        ]
      },
    ];

    menu = Menu.buildFromTemplate(osxTemplate);
    Menu.setApplicationMenu(menu);
  } else {
    var template = [
      {
        label: '&File',
        submenu: [
          {
            label: '&Open',
            accelerator: 'Ctrl+O',
          },
          {
            label: '&Close',
            accelerator: 'Ctrl+W',
            click: function() { mainWindow.close(); }
          },
        ]
      },
      {
        label: 'Page',
        submenu: [
          {
            label: 'Home',
            click: function () {
              mainWindow.webContents.send('transitionTo', 'home');
            }
          },
          {
            label: 'About',
            click: function () {
              mainWindow.webContents.send('transitionTo', 'about');
            }
          },
          {
            label: 'Contact',
            click: function () {
              mainWindow.webContents.send('transitionTo', 'contact');
            }
          }
        ]
      },
      {
        label: '&View',
        submenu: [
          {
            label: '&Reload',
            accelerator: 'Ctrl+R',
            click: function() { mainWindow.restart(); }
          },
          {
            label: 'Toggle &Fullscreen',
            click: function() {
              mainWindow.setFullScreen(!mainWindow.isFullScreen());
            }
          },
          {
            label: '&Toggle DevTools',
            accelerator: 'Alt+Ctrl+I',
            click: function() { mainWindow.toggleDevTools(); }
          },
        ]
      },
    ];

    menu = Menu.buildFromTemplate(template);
    mainWindow.setMenu(menu);
  }
});
<|endoftext|>


<commit_before>
/*!
 * Skeleton.js - I18n
 * Copyright(c) 2012 Rubén Norte <rubennorte@gmail.com>
 * MIT Licensed
 */

define([
  'require',
  'backbone',
  'underscore',
  'underscore.string',
  './util/url'
], function(require, Backbone, _, _s, url){

  'use strict';

  var rLocale = /^([a-zA-Z]{2})([\-_]([a-zA-Z]{2}))?$/,
      rStrictLocale = /^([a-z]{2})([_]([A-Z]{2}))?$/;

  var LOCALE_FORMAT_ERROR = 'The locale must have a valid format ' +
    '(e.g. en, es_ES)';

  /**
   * Skeleton I18n module definition
   */
  var I18n = _.extend({}, Backbone.Events, {

    // Current locale
    _locale: null,

    // Default locale
    _defaultLocale: null,

    // The object containing the current locale translations
    _translations: {},

    // The object containing counters for all missing translations
    _missingTranslations: {},

    // List of all available locales.
    // If null, the existence of each locale file is not verified before
    // trying to load it
    _availableLocales: null,

    // Relative path to the locale directory
    _loadPath: '',

    /**
     * Translates the specified parameter.
     * If it's an object, we assume that the object keys are the language code
     * and the object values are the translations for that language.
     * Otherwise, search the translation for that key in the stored translations
     */
    t: function(text){
      var locale = this.getLocale(),
          language = this.getLanguage();

      if (typeof text === 'boolean'){
        text = text ? 'true' : 'false';
      } else if (typeof text === 'number'){
        text = '' + text;
      }

      switch (typeof(text)){
        case 'string':
          // If text is a string, search in translation object
          if (!this._translations[text] && !this._missingTranslations[text]){
            // The translation is not found, so increment the counter for
            // that key in the missing translations object
            this._missingTranslations[text] =
              (this._missingTranslations[text] || 0) + 1;
            this._translations[text] = text;
            console.info('skeleton/i18n', 'Missing translation for key', text);
          }

          // Set the translated text as the value in the translations object or
          // the translation key itself (if the translation is missing)
          text = this._translations[text] || text;
          break;

        case 'object':
          if (text){
            // If text is an object (and not null), get the translations from it according
            // to the current locale
            if (locale in text){
              text = text[locale];
            } else if (language in text){
              text = text[language];
            } else if (this._defaultLocale in text){
              text = text[this._defaultLocale];
            }
          }
          break;

        case 'function':
          // If text is a function, get the result of this function passing
          // the locale as a parameter
          text = text(this._locale);
          break;
      }

      // If text is a string and the key is not the only specified parameter, return interpolated
      if (typeof text === 'string' && arguments.length > 1){
        return _s.sprintf.apply(null, arguments);
      }

      return text;
    },

    /**
     * Returns the system locale according to the information provided
     * by the navigator
     */
    getSystemLocale: function(fn){
      if (!navigator){
        return fn(null, this.getDefaultLocale());
      }

      // Phonegap support
      if (navigator.globalization && typeof navigator.globalization.getLocaleName === 'function'){
        navigator.globalization.getLocaleName(function(locale){
          fn(null, locale);
        }, function(err){
          fn(err);
        });
        return;
      }

      var locale = toPOSIXLocale(navigator.language);
      fn(null, locale);
    },

    getDefaultLocale: function(){
      return this._defaultLocale;
    },

    /**
     * Returns the current locale
     */
    getLocale: function(){
      return this._locale;
    },

    /**
     * Returns the current language
     */
    getLanguage: function(){
      return this._locale.substr(0,2);
    },

    /**
     * Returns the current region
     */
    getRegion: function(){
      return this._locale.substr(3,2);
    },

    /**
     * Returns true if exists any valid locale file for the specified locale
     */
    isLocaleAvailable: function(locale){
      if (!this._availableLocales){
        return undefined;
      }

      var language = locale.substr(0,2),
          languageAvailable = _(this._availableLocales).include(language);

      if (languageAvailable){
        return true;
      }

      return locale.length === 5 && _(this._availableLocales).include(locale);
    },

    /**
     * Sets the current locale. The translation object can be passed or
     * it will be loaded from a JSON in the load path. When the locale is set
     * and the translations are loaded, callback function is invoked
     */
    setLocale: function(locale, translations, callback){
      if (!rLocale.test(locale)){
        throw new Error(LOCALE_FORMAT_ERROR + ': ' + locale);
      }

      locale = toPOSIXLocale(locale);

      // Check if translations object is defined
      if (typeof(translations) === 'function'){
        callback = translations;
        translations = null;
      }

      // If the locale is the current one, return immediatelly
      if (locale === this.getLocale()){
        return callback && callback();
      }

      if (translations){
        // If the translations are defined, we don't have to load them and can
        // set the locale inmediately
        this._setLocaleAndTranslations(locale, translations, callback);
      } else {
        // Otherwise, we have to load them (as AMD modules to cache)
        var language = locale.substr(0,2),
            region = locale.substr(3,2),
            localeFiles = [];

        if (!this._availableLocales ||
            _(this._availableLocales).include(language)){
          localeFiles.push('json!' + this._getLocaleUrl(language));
        }

        if (region &&
            (!this._availableLocales || _(this._availableLocales).include(locale))){
          localeFiles.push('json!' + this._getLocaleUrl(locale));
        }

        if (localeFiles.length === 0){
          if (callback){
            callback('The specified locale is not available: ' + locale);
          }
          return false;
        }

        this._loadLocaleFiles(locale, localeFiles, callback);
      }
    },

    /**
     * Sets the available locale files in the project
     */
    setAvailableLocales: function(availableLocales){
      _(availableLocales).each(function(availableLocale){
        if (!rStrictLocale.test(availableLocale)){
          throw new Error(LOCALE_FORMAT_ERROR + ': ' + availableLocale);
        }
      });
      var prevAvailableLocales = this._availableLocales;
      this._availableLocales = availableLocales;
      this.trigger('change:availableLocales', this, availableLocales, prevAvailableLocales);
    },

    /**
     * Sets the default locale
     */
    setDefaultLocale: function(locale){
      if (!rStrictLocale.test(locale)){
        throw new Error(LOCALE_FORMAT_ERROR + ': ' + locale);
      }

      var prevLocale = this._defaultLocale;
      this._defaultLocale = locale;
      this.trigger('change:defaultLocale', this, locale, prevLocale);
    },

    /**
     * Sets the locale file load path
     */
    setLoadPath: function(path){
      this._loadPath = path;
    },

    // Returns the URL of the JSON containing the translations for the specified
    // locale
    _getLocaleUrl: function(locale){
      return url.join(_.result(this, '_loadPath'), locale + '.json');
    },

    // Assigns the locale, the translations object and invokes the callback
    _setLocaleAndTranslations: function(locale, translations, callback){
      if (this._locale !== locale || !_.isEqual(this._translations, translations)){
        console.info('skeleton/i18n', 'Locale set to', locale);
        this._locale = locale;
        this._translations = translations;
        this._missingTranslations = {};
        this.trigger('change:locale', this);
      }
      if (callback){
        callback(null, locale);
      }
    },

    // Loads the locale files and merges the translation objects
    // into one
    _loadLocaleFiles: function(locale, localeFiles, callback){
      var self = this;

      var results = 0;
      var resultTranslations = _.map(localeFiles, function(){
        return {};
      });

      var onResponse = function(){
        results++;
        if (results === resultTranslations.length){
          var translations = {};
          _.each(resultTranslations, function(current){
            translations = _.extend(translations, current);
          });
          self._setLocaleAndTranslations(locale, translations, callback);
        }
      };

      _.each(localeFiles, function(localeFile, index){
        require([localeFile], function(localeTranslations){
          resultTranslations[index] = localeTranslations;
          onResponse();
        }, function(){
          onResponse();
        });
      });
    }

  });

  function toPOSIXLocale(locale){
    if (!locale){
      return locale;
    }

    if (locale.length === 2){
      return locale.toLowerCase();
    }

    return locale.substr(0,2).toLowerCase() + '_' +
      locale.substr(3,2).toUpperCase();
  }

  return I18n;

});
<commit_msg>Fixes #1. Fixes translation of keys with interpolated values.<commit_after>
/*!
 * Skeleton.js - I18n
 * Copyright(c) 2012 Rubén Norte <rubennorte@gmail.com>
 * MIT Licensed
 */

define([
  'require',
  'backbone',
  'underscore',
  'underscore.string',
  './util/url'
], function(require, Backbone, _, _s, url){

  'use strict';

  var rLocale = /^([a-zA-Z]{2})([\-_]([a-zA-Z]{2}))?$/,
      rStrictLocale = /^([a-z]{2})([_]([A-Z]{2}))?$/;

  var LOCALE_FORMAT_ERROR = 'The locale must have a valid format ' +
    '(e.g. en, es_ES)';

  /**
   * Skeleton I18n module definition
   */
  var I18n = _.extend({}, Backbone.Events, {

    // Current locale
    _locale: null,

    // Default locale
    _defaultLocale: null,

    // The object containing the current locale translations
    _translations: {},

    // The object containing counters for all missing translations
    _missingTranslations: {},

    // List of all available locales.
    // If null, the existence of each locale file is not verified before
    // trying to load it
    _availableLocales: null,

    // Relative path to the locale directory
    _loadPath: '',

    /**
     * Translates the specified parameter.
     * If it's an object, we assume that the object keys are the language code
     * and the object values are the translations for that language.
     * Otherwise, search the translation for that key in the stored translations
     */
    t: function(text){
      var locale = this.getLocale(),
          language = this.getLanguage();

      if (typeof text === 'boolean'){
        text = text ? 'true' : 'false';
      } else if (typeof text === 'number'){
        text = '' + text;
      }

      switch (typeof(text)){
        case 'string':
          // If text is a string, search in translation object
          if (!this._translations[text] && !this._missingTranslations[text]){
            // The translation is not found, so increment the counter for
            // that key in the missing translations object
            this._missingTranslations[text] =
              (this._missingTranslations[text] || 0) + 1;
            this._translations[text] = text;
            console.info('skeleton/i18n', 'Missing translation for key', text);
          }

          // Set the translated text as the value in the translations object or
          // the translation key itself (if the translation is missing)
          text = this._translations[text] || text;
          break;

        case 'object':
          if (text){
            // If text is an object (and not null), get the translations from it according
            // to the current locale
            if (locale in text){
              text = text[locale];
            } else if (language in text){
              text = text[language];
            } else if (this._defaultLocale in text){
              text = text[this._defaultLocale];
            }
          }
          break;

        case 'function':
          // If text is a function, get the result of this function passing
          // the locale as a parameter
          text = text(this._locale);
          break;
      }

      // If text is a string and the key is not the only specified parameter, return interpolated
      if (typeof text === 'string' && arguments.length > 1){
        arguments[0] = text;
        return _s.sprintf.apply(null, arguments);
      }

      return text;
    },

    /**
     * Returns the system locale according to the information provided
     * by the navigator
     */
    getSystemLocale: function(fn){
      if (!navigator){
        return fn(null, this.getDefaultLocale());
      }

      // Phonegap support
      if (navigator.globalization && typeof navigator.globalization.getLocaleName === 'function'){
        navigator.globalization.getLocaleName(function(locale){
          fn(null, locale);
        }, function(err){
          fn(err);
        });
        return;
      }

      var locale = toPOSIXLocale(navigator.language);
      fn(null, locale);
    },

    getDefaultLocale: function(){
      return this._defaultLocale;
    },

    /**
     * Returns the current locale
     */
    getLocale: function(){
      return this._locale;
    },

    /**
     * Returns the current language
     */
    getLanguage: function(){
      return this._locale.substr(0,2);
    },

    /**
     * Returns the current region
     */
    getRegion: function(){
      return this._locale.substr(3,2);
    },

    /**
     * Returns true if exists any valid locale file for the specified locale
     */
    isLocaleAvailable: function(locale){
      if (!this._availableLocales){
        return undefined;
      }

      var language = locale.substr(0,2),
          languageAvailable = _(this._availableLocales).include(language);

      if (languageAvailable){
        return true;
      }

      return locale.length === 5 && _(this._availableLocales).include(locale);
    },

    /**
     * Sets the current locale. The translation object can be passed or
     * it will be loaded from a JSON in the load path. When the locale is set
     * and the translations are loaded, callback function is invoked
     */
    setLocale: function(locale, translations, callback){
      if (!rLocale.test(locale)){
        throw new Error(LOCALE_FORMAT_ERROR + ': ' + locale);
      }

      locale = toPOSIXLocale(locale);

      // Check if translations object is defined
      if (typeof(translations) === 'function'){
        callback = translations;
        translations = null;
      }

      // If the locale is the current one, return immediatelly
      if (locale === this.getLocale()){
        return callback && callback();
      }

      if (translations){
        // If the translations are defined, we don't have to load them and can
        // set the locale inmediately
        this._setLocaleAndTranslations(locale, translations, callback);
      } else {
        // Otherwise, we have to load them (as AMD modules to cache)
        var language = locale.substr(0,2),
            region = locale.substr(3,2),
            localeFiles = [];

        if (!this._availableLocales ||
            _(this._availableLocales).include(language)){
          localeFiles.push('json!' + this._getLocaleUrl(language));
        }

        if (region &&
            (!this._availableLocales || _(this._availableLocales).include(locale))){
          localeFiles.push('json!' + this._getLocaleUrl(locale));
        }

        if (localeFiles.length === 0){
          if (callback){
            callback('The specified locale is not available: ' + locale);
          }
          return false;
        }

        this._loadLocaleFiles(locale, localeFiles, callback);
      }
    },

    /**
     * Sets the available locale files in the project
     */
    setAvailableLocales: function(availableLocales){
      _(availableLocales).each(function(availableLocale){
        if (!rStrictLocale.test(availableLocale)){
          throw new Error(LOCALE_FORMAT_ERROR + ': ' + availableLocale);
        }
      });
      var prevAvailableLocales = this._availableLocales;
      this._availableLocales = availableLocales;
      this.trigger('change:availableLocales', this, availableLocales, prevAvailableLocales);
    },

    /**
     * Sets the default locale
     */
    setDefaultLocale: function(locale){
      if (!rStrictLocale.test(locale)){
        throw new Error(LOCALE_FORMAT_ERROR + ': ' + locale);
      }

      var prevLocale = this._defaultLocale;
      this._defaultLocale = locale;
      this.trigger('change:defaultLocale', this, locale, prevLocale);
    },

    /**
     * Sets the locale file load path
     */
    setLoadPath: function(path){
      this._loadPath = path;
    },

    // Returns the URL of the JSON containing the translations for the specified
    // locale
    _getLocaleUrl: function(locale){
      return url.join(_.result(this, '_loadPath'), locale + '.json');
    },

    // Assigns the locale, the translations object and invokes the callback
    _setLocaleAndTranslations: function(locale, translations, callback){
      if (this._locale !== locale || !_.isEqual(this._translations, translations)){
        console.info('skeleton/i18n', 'Locale set to', locale);
        this._locale = locale;
        this._translations = translations;
        this._missingTranslations = {};
        this.trigger('change:locale', this);
      }
      if (callback){
        callback(null, locale);
      }
    },

    // Loads the locale files and merges the translation objects
    // into one
    _loadLocaleFiles: function(locale, localeFiles, callback){
      var self = this;

      var results = 0;
      var resultTranslations = _.map(localeFiles, function(){
        return {};
      });

      var onResponse = function(){
        results++;
        if (results === resultTranslations.length){
          var translations = {};
          _.each(resultTranslations, function(current){
            translations = _.extend(translations, current);
          });
          self._setLocaleAndTranslations(locale, translations, callback);
        }
      };

      _.each(localeFiles, function(localeFile, index){
        require([localeFile], function(localeTranslations){
          resultTranslations[index] = localeTranslations;
          onResponse();
        }, function(){
          onResponse();
        });
      });
    }

  });

  function toPOSIXLocale(locale){
    if (!locale){
      return locale;
    }

    if (locale.length === 2){
      return locale.toLowerCase();
    }

    return locale.substr(0,2).toLowerCase() + '_' +
      locale.substr(3,2).toUpperCase();
  }

  return I18n;

});
<|endoftext|>