<commit_before>import React, { Component } from 'react';
import { Animated, Dimensions, Image, StyleSheet, View, Text, TouchableHighlight } from 'react-native';
import { Constants } from 'expo';
import RootNavigation from '../navigation/RootNavigation';

const PAGE_WIDTH = Dimensions.get('window').width;
const PAGES = [
	{
		id: 1,
		message: "",
		moreMessage: "The best solution to finding the proper rest you need.",
		backgroundColor: "#233243"
	},
	{
		id: 2,
		message: "Listen in a quiet place",
		moreMessage: "Important!",
		backgroundColor: "#7E8578"
	},
	{
		id: 3,
		message: "Get super comfey",
		moreMessage: "Like, reaallyyy comfey.",
		backgroundColor: "#C17918"
	},
	{
		id: 4,
		message: "Turn phone off",
		moreMessage: "More best practices in the 'app guide'",
		backgroundColor: "#0B5F6A"
	},
	{
		id: 5,
		message: "Choose meditation",
		moreMessage: "Pick the meditation that works with your schedule.",
		backgroundColor: "#695065"
	}
]

class TourScreen extends Component {

	state = {
    scroll: new Animated.Value(0),
	}

	_getImage(i) {
		switch (i) {
			case 0:
				return require('../assets/images/clouds/tour-page-1.jpg')
				break;
			case 1:
				return require('../assets/images/clouds/tour-page-2.jpg')
				break;
			case 2:
				return require('../assets/images/clouds/tour-page-3.jpg')
				break;
			case 3:
				return require('../assets/images/clouds/tour-page-4.jpg')
				break;
			case 4:
				return require('../assets/images/clouds/tour-page-5.jpg')
				break;
		}
	}

  render() {

    const position = Animated.divide(this.state.scroll, PAGE_WIDTH);
    const backgroundColor = position.interpolate({
      inputRange: PAGES.map((_, i) => i),
      outputRange: PAGES.map(p => p.backgroundColor),
    });

		function renderIf(condition, content) {
	    if (condition) {
	        return content;
	    } else {
	        return null;
	    }
		}

    return (
			<View style={styles.container}>
					<Animated.View style={[ StyleSheet.absoluteFill, { backgroundColor } ]} />

					<Animated.ScrollView
						horizontal
						pagingEnabled
						showsHorizontalScrollIndicator={false}
						scrollEventThrottle={16}
						onScroll={Animated.event(
							[ { nativeEvent: { contentOffset: { x: this.state.scroll } } } ],
						)}
						>

						{PAGES.map((page, i) => (
							<View key={i} style={styles.page}>
								<Image
								style={styles.image}
								source={ this._getImage(i) } />
								<View style={[ styles.card ]}>
									<Text style={styles.moreMessage}>{page.moreMessage}</Text>
									<Text style={styles.message}>{page.message}</Text>
									{renderIf(i===0,
										<View>
											<Image
												style={styles.gesture}
												source={ require('../assets/images/swipe-gesture.png') } />
											<Text style={styles.swipeText}>Swipe to get started</Text>
										</View>
	                )}
									{renderIf(i===4,
										<View style={styles.button}>
											<TouchableHighlight onPress={() => {this.props.handler()}}>
												<Text style={styles.buttonText}>
													Get Started
												</Text>
											</TouchableHighlight>
										</View>
	                )}
								</View>
							</View>
						))}
					</Animated.ScrollView>
			</View>
		);
	}
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  image: {
  	flex: 1,
  	// resizeMode: 'cover',
    width: PAGE_WIDTH
  },
  gesture: {
  	alignSelf: 'center',
  	marginTop: 20,
  	width: 57,
  	height: 78
  },
  message: {
    fontSize: PAGE_WIDTH/12,
    fontWeight: 'bold',
    color: '#fff',
    backgroundColor: 'transparent',
    textAlign: 'center'
  },
  moreMessage: {
    fontSize: PAGE_WIDTH/18,
    color: '#fff',
    fontWeight: 'bold',
    backgroundColor: 'transparent',
    marginTop: 20,
    lineHeight: 25,
    textAlign: 'center'
  },
  swipeText: {
    fontSize: PAGE_WIDTH/22,
    fontWeight: 'bold',
    color: '#fff',
    backgroundColor: 'transparent',
    textAlign: 'center'
  },
  page: {
    width: PAGE_WIDTH,
    paddingTop: Constants.statusBarHeight,
  },
  card: {
    position: 'absolute',
    margin: 12,
    marginTop: PAGE_WIDTH / 3,
    left: 12,
    top: 0,
    right: 0,
    borderRadius: 8,
    paddingHorizontal: 24,
    paddingTop: 16,
    paddingBottom: 300,
  },
  button: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0, 0.5)',
    position: 'absolute',
    margin: 12,
    marginTop: 300,
    alignSelf: 'center',
    borderRadius: 50,
    // paddingLeft: 10,
    // paddingRight: 10
  },
  buttonText: {
    margin: 15,
    marginLeft: 50,
    marginRight: 40,
    color: '#fff',
    fontSize: PAGE_WIDTH/16,
    // fontVariant: ['small-caps'],
  }
});

export default TourScreen;
<commit_msg>Add iSLEEP header to first page of Tour<commit_after>import React, { Component } from 'react';
import { Animated, Dimensions, Image, StyleSheet, View, Text, TouchableHighlight } from 'react-native';
import { Constants } from 'expo';
import RootNavigation from '../navigation/RootNavigation';

const PAGE_WIDTH = Dimensions.get('window').width;
const PAGES = [
	{
		id: 1,
		message: "",
		moreMessage: "The best solution to finding the proper rest you need.",
		backgroundColor: "#233243"
	},
	{
		id: 2,
		message: "Listen in a quiet place",
		moreMessage: "Important!",
		backgroundColor: "#7E8578"
	},
	{
		id: 3,
		message: "Get super comfey",
		moreMessage: "Like, reaallyyy comfey.",
		backgroundColor: "#C17918"
	},
	{
		id: 4,
		message: "Turn phone off",
		moreMessage: "More best practices in the 'app guide'",
		backgroundColor: "#0B5F6A"
	},
	{
		id: 5,
		message: "Choose meditation",
		moreMessage: "Pick the meditation that works with your schedule.",
		backgroundColor: "#695065"
	}
]

class TourScreen extends Component {

	state = {
    scroll: new Animated.Value(0),
	}

	_getImage(i) {
		switch (i) {
			case 0:
				return require('../assets/images/clouds/tour-page-1.jpg')
				break;
			case 1:
				return require('../assets/images/clouds/tour-page-2.jpg')
				break;
			case 2:
				return require('../assets/images/clouds/tour-page-3.jpg')
				break;
			case 3:
				return require('../assets/images/clouds/tour-page-4.jpg')
				break;
			case 4:
				return require('../assets/images/clouds/tour-page-5.jpg')
				break;
		}
	}

  render() {

    const position = Animated.divide(this.state.scroll, PAGE_WIDTH);
    const backgroundColor = position.interpolate({
      inputRange: PAGES.map((_, i) => i),
      outputRange: PAGES.map(p => p.backgroundColor),
    });

		function renderIf(condition, content) {
	    if (condition) {
	        return content;
	    } else {
	        return null;
	    }
		}

    return (
			<View style={styles.container}>
					<Animated.View style={[ StyleSheet.absoluteFill, { backgroundColor } ]} />

					<Animated.ScrollView
						horizontal
						pagingEnabled
						showsHorizontalScrollIndicator={false}
						scrollEventThrottle={16}
						onScroll={Animated.event(
							[ { nativeEvent: { contentOffset: { x: this.state.scroll } } } ],
						)}
						>

						{PAGES.map((page, i) => (
							<View key={i} style={styles.page}>
								<Image
								style={styles.image}
								source={ this._getImage(i) } />
								<View style={[ styles.card ]}>
									{renderIf(i===0,
										<Text style={styles.header}>iSLEEP</Text>
									)}
									<Text style={styles.message}>{page.message}</Text>
									<Text style={styles.moreMessage}>{page.moreMessage}</Text>
									{renderIf(i===0,
										<View>
											<Image
												style={styles.gesture}
												source={ require('../assets/images/swipe-gesture.png') } />
											<Text style={styles.swipeText}>Swipe to get started</Text>
										</View>
	                )}
									{renderIf(i===4,
										<View style={styles.button}>
											<TouchableHighlight onPress={() => {this.props.handler()}}>
												<Text style={styles.buttonText}>
													Get Started
												</Text>
											</TouchableHighlight>
										</View>
	                )}
								</View>
							</View>
						))}
					</Animated.ScrollView>
			</View>
		);
	}
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  image: {
  	flex: 1,
    width: PAGE_WIDTH
  },
  gesture: {
  	alignSelf: 'center',
  	marginTop: 20,
  	width: 57,
  	height: 78
  },
  header: {
    fontSize: PAGE_WIDTH/10,
    fontWeight: 'bold',
    color: '#fff',
    backgroundColor: 'transparent',
    textAlign: 'center'
  },
  message: {
    fontSize: PAGE_WIDTH/12,
    fontWeight: 'bold',
    color: '#fff',
    backgroundColor: 'transparent',
    textAlign: 'center'
  },
  moreMessage: {
    fontSize: PAGE_WIDTH/18,
    color: '#fff',
    fontWeight: 'bold',
    backgroundColor: 'transparent',
    marginTop: 20,
    lineHeight: 25,
    textAlign: 'center'
  },
  swipeText: {
    fontSize: PAGE_WIDTH/22,
    fontWeight: 'bold',
    color: '#fff',
    backgroundColor: 'transparent',
    textAlign: 'center'
  },
  page: {
    width: PAGE_WIDTH,
    paddingTop: Constants.statusBarHeight,
  },
  card: {
    position: 'absolute',
    margin: 12,
    marginTop: PAGE_WIDTH / 3,
    left: 12,
    top: 0,
    right: 0,
    borderRadius: 8,
    paddingHorizontal: 24,
    paddingTop: 16,
    paddingBottom: 300,
  },
  button: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0, 0.5)',
    position: 'absolute',
    margin: 12,
    marginTop: 300,
    alignSelf: 'center',
    borderRadius: 50,
    // paddingLeft: 10,
    // paddingRight: 10
  },
  buttonText: {
    margin: 15,
    marginLeft: 50,
    marginRight: 40,
    color: '#fff',
    fontSize: PAGE_WIDTH/16,
    // fontVariant: ['small-caps'],
  }
});

export default TourScreen;
<|endoftext|>


<commit_before>/*
    molt, update images according to the window resolution

    Version : 0.1
    Author  : Aurélien Delogu (dev@dreamysource.fr)
    URL     : https://github.com/pyrsmk/molt
    License : MIT
*/

(function(window,document){

    /*
        Get the window's width

        Return
            integer
    */
    window.getWindowWidth=window.getWindowWidth || function(){
        if(typeof(window.innerWidth)=='number'){
            return window.innerWidth;
        }
        else{
            return document.documentElement.clientWidth;
        }
    };

    /*
        Get the window's height

        Return
            integer
    */
    window.getWindowHeight=window.getWindowHeight || function(){
        if(typeof(window.innerHeight)=='number'){
            return window.innerHeight;
        }
        else{
            return document.documentElement.clientHeight;
        }
    };

    /*
        Create a molt image

        Parameters
            string url          : image url
            object dimensions   : image resolutions corresponding to the specified mode
                                  (mode,[width,height]) pair list
            function insert     : insert the node into the DOM
            function update     : update the node

        Return
            molt
    */
    window.molt=window.molt || function(url,dimensions,insert,update){

        /*
            string _url         : image url
            object _dimensions  : image resolutions corresponding to the specified mode
            function _update    : update the node
            object _node        : image node
            string _display     : "current" display property for that image
        */
        var _url,
            _dimensions,
            _update,
            _node,
            _display='inline';

        /*
            Refresh images for that new window size
        */
        var refresh=function(){
            // Guess the current mode
            var w=window.getWindowWidth(),
                mode,
                last;
            for(mode in _dimensions){
                if(w<mode){
                    mode=last;
                    break;
                }
                last=mode;
            }
            // Define node properties
            if(_dimensions[mode].length){
                if(_node.style.display=='none'){
                    _node.style.display=_display;
                }
                _node.width=_dimensions[mode][0];
                _node.height=_dimensions[mode][1];
                var url=_url;
                _node.src=url.replace(/\{mode\}/g,mode).
                              replace(/\{width\}/g,_dimensions[mode][0]).
                              replace(/\{height\}/g,_dimensions[mode][1]);
            }
            else{
                var display=_node.style.display || _display;
                _node.style.display='none';
            }
            // Update node
            _update(_node);
        };

        // Format
        if(!insert){
            insert=function(){};
        }
        if(!update){
            update=function(){};
        }
        // Sort dimensions
        var dims=[];
        for(var mode in dimensions){
            dims[mode]=dimensions[mode];
        }
        // Create node
        var node=document.createElement('img');
        node.alt='';
        // Save data
        _url=url;
        _dimensions=dims;
        _update=update;
        _node=node;
        // Insert it into the DOM
        insert(node);
        // Update node
        refresh();
        // Catch resize event
        if(window.addEventListener){
            window.addEventListener("resize",refresh,false);
        }
        else if(window.attachEvent){
            window.attachEvent("onresize",refresh);
        }
        return window.molt;

    };

})(this,this.document);<commit_msg>Update description<commit_after>/*
    molt, images updater for media devices

    Version : 0.1
    Author  : Aurélien Delogu (dev@dreamysource.fr)
    URL     : https://github.com/pyrsmk/molt
    License : MIT
*/

(function(window,document){

    /*
        Get the window's width

        Return
            integer
    */
    window.getWindowWidth=window.getWindowWidth || function(){
        if(typeof(window.innerWidth)=='number'){
            return window.innerWidth;
        }
        else{
            return document.documentElement.clientWidth;
        }
    };

    /*
        Get the window's height

        Return
            integer
    */
    window.getWindowHeight=window.getWindowHeight || function(){
        if(typeof(window.innerHeight)=='number'){
            return window.innerHeight;
        }
        else{
            return document.documentElement.clientHeight;
        }
    };

    /*
        Create a molt image

        Parameters
            string url          : image url
            object dimensions   : image resolutions corresponding to the specified mode
                                  (mode,[width,height]) pair list
            function insert     : insert the node into the DOM
            function update     : update the node

        Return
            molt
    */
    window.molt=window.molt || function(url,dimensions,insert,update){

        /*
            string _url         : image url
            object _dimensions  : image resolutions corresponding to the specified mode
            function _update    : update the node
            object _node        : image node
            string _display     : "current" display property for that image
        */
        var _url,
            _dimensions,
            _update,
            _node,
            _display='inline';

        /*
            Refresh images for that new window size
        */
        var refresh=function(){
            // Guess the current mode
            var w=window.getWindowWidth(),
                mode,
                last;
            for(mode in _dimensions){
                if(w<mode){
                    mode=last;
                    break;
                }
                last=mode;
            }
            // Define node properties
            if(_dimensions[mode].length){
                if(_node.style.display=='none'){
                    _node.style.display=_display;
                }
                _node.width=_dimensions[mode][0];
                _node.height=_dimensions[mode][1];
                var url=_url;
                _node.src=url.replace(/\{mode\}/g,mode).
                              replace(/\{width\}/g,_dimensions[mode][0]).
                              replace(/\{height\}/g,_dimensions[mode][1]);
            }
            else{
                var display=_node.style.display || _display;
                _node.style.display='none';
            }
            // Update node
            _update(_node);
        };

        // Format
        if(!insert){
            insert=function(){};
        }
        if(!update){
            update=function(){};
        }
        // Sort dimensions
        var dims=[];
        for(var mode in dimensions){
            dims[mode]=dimensions[mode];
        }
        // Create node
        var node=document.createElement('img');
        node.alt='';
        // Save data
        _url=url;
        _dimensions=dims;
        _update=update;
        _node=node;
        // Insert it into the DOM
        insert(node);
        // Update node
        refresh();
        // Catch resize event
        if(window.addEventListener){
            window.addEventListener("resize",refresh,false);
        }
        else if(window.attachEvent){
            window.attachEvent("onresize",refresh);
        }
        return window.molt;

    };

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


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

GOVUK.performance = GOVUK.performance || {};

GOVUK.performance.stageprompt = (function () {
  var setup, setupForGoogleAnalytics;

  setup = function (analyticsCallback) {
    var journeyStage = $('[data-journey]').attr('data-journey'),
        journeyHelpers = $('[data-journey-helper]');
    if (journeyStage) {
      analyticsCallback(journeyStage);
    }

    if (journeyHelpers.length) {
      journeyHelpers.on('click', function (event) {
        analyticsCallback($(this).data('journey-helper'));
      });
    }
  };

  setupForGoogleAnalytics = function () {
    setup(GOVUK.performance.sendGoogleAnalyticsEvent);
  };

  return {
    setup: setup,
    setupForGoogleAnalytics: setupForGoogleAnalytics
  };
}());

GOVUK.performance.sendGoogleAnalyticsEvent = function (action) {
  _gaq.push(['_trackEvent', 'stagePrompt', action, undefined, undefined, true]);
};
<commit_msg>Remove redundant if statement<commit_after>var GOVUK = GOVUK || {};

GOVUK.performance = GOVUK.performance || {};

GOVUK.performance.stageprompt = (function () {
  var setup, setupForGoogleAnalytics;

  setup = function (analyticsCallback) {
    var journeyStage = $('[data-journey]').attr('data-journey'),
        journeyHelpers = $('[data-journey-helper]');
    if (journeyStage) {
      analyticsCallback(journeyStage);
    }

    journeyHelpers.on('click', function (event) {
      analyticsCallback($(this).data('journey-helper'));
    });
  };

  setupForGoogleAnalytics = function () {
    setup(GOVUK.performance.sendGoogleAnalyticsEvent);
  };

  return {
    setup: setup,
    setupForGoogleAnalytics: setupForGoogleAnalytics
  };
}());

GOVUK.performance.sendGoogleAnalyticsEvent = function (action) {
  _gaq.push(['_trackEvent', 'stagePrompt', action, undefined, undefined, true]);
};
<|endoftext|>


<commit_before>(function(window, $) {

	var startTests = function() {
		var op = respimage._;

		var saveCache = {};

		// reset stubbing

		module( "method", {
			setup: function() {
				var prop;
				for ( prop in op ) {
					if ( op.hasOwnProperty( prop ) ) {
						saveCache[ prop ] = op[ prop ];
					}
				}
			},

			teardown: function() {
				var prop;
				for ( prop in saveCache ) {
					if ( op.hasOwnProperty(prop) && saveCache[prop] != op[ prop ] ) {
						op[prop] = saveCache[prop];
					}
				}
			}
		});

		test( "respimage: Picture fill is loaded and has its API ready", function() {
			ok( window.respimage );

			ok( window.respimage._ );

			ok( window.respimage._.fillImg );

			ok( window.respimage._.fillImgs );

			ok( window.respimage._.observer );

			ok( window.respimage._.observer.start );

			ok( window.respimage._.observer.stop );

			ok( window.respimage._.observer.disconnect );

			ok( window.respimage._.observer.observe );

		});

		if ( !op.mutationSupport || window.HTMLPictureElement ) {
			return;
		}

		var calledFill = 0;
		var createImgSpy = function( ) {
			var old = op.fillImg;
			calledFill = 0;
			op.fillImg = function() {
				calledFill++;
				return old.apply( this, arguments );
			};
		};

		var runFunctionalNewElementsTests = function( $dom ) {
			var $images = $dom.find( op.sel );

			equal( $images.length, 6 );
			equal( calledFill, 6 );

			$images.each(function() {
				ok( this[ op.ns ]);
			});
		};

		asyncTest( "mutationobserver: functional integration test html", function() {
			var markup = $( "#template").html();

			createImgSpy();

			$("#mutation-fixture").html( markup );

			setTimeout(function() {
				runFunctionalNewElementsTests( $("#mutation-fixture") );
				start();
			}, 9);
		});

		asyncTest( "mutationobserver: functional integration test append", function() {
			var markup = $( "#template").html();

			createImgSpy();

			$("#mutation-fixture").append( markup );

			setTimeout(function() {
				runFunctionalNewElementsTests( $("#mutation-fixture") );
				start();
			}, 9);
		});
	};

	if( window.blanket ) {
		blanket.beforeStartTestRunner({
			callback: function() {
				setTimeout(startTests, QUnit.urlParams.coverage ? 500 : 0); //if blanketjs fails set a higher timeout
			}
		});
	} else {
		startTests();
	}

})( window, jQuery );
<commit_msg>tests for issue #11<commit_after>(function(window, $) {

	var startTests = function() {
		var op = respimage._;

		var saveCache = {};

		// reset stubbing

		module( "method", {
			setup: function() {
				var prop;
				for ( prop in op ) {
					if ( op.hasOwnProperty( prop ) ) {
						saveCache[ prop ] = op[ prop ];
					}
				}
			},

			teardown: function() {
				var prop;
				for ( prop in saveCache ) {
					if ( op.hasOwnProperty(prop) && saveCache[prop] != op[ prop ] ) {
						op[prop] = saveCache[prop];
					}
				}
			}
		});

		test( "respimage: Picture fill is loaded and has its API ready", function() {
			ok( window.respimage );

			ok( window.respimage._ );

			ok( window.respimage._.fillImg );

			ok( window.respimage._.fillImgs );

			ok( window.respimage._.observer );

			ok( window.respimage._.observer.start );

			ok( window.respimage._.observer.stop );

			ok( window.respimage._.observer.disconnect );

			ok( window.respimage._.observer.observe );

		});

		if ( !op.mutationSupport || window.HTMLPictureElement ) {
			return;
		}

		var calledFill = 0;
		var createImgSpy = function( ) {
			var old = op.fillImg;
			calledFill = 0;
			op.fillImg = function() {
				calledFill++;
				return old.apply( this, arguments );
			};
		};

		var runFunctionalNewElementsTests = function( $dom ) {
			var $images = $dom.find( op.sel );

			equal( $images.length, 6 );
			equal( calledFill, 6 );

			$images.each(function() {
				ok( this[ op.ns ]);
			});
		};

		asyncTest( "mutationobserver: functional integration test html", function() {
			var markup = $( "#template").html();

			createImgSpy();

			$("#mutation-fixture").html( markup );

			setTimeout(function() {
				runFunctionalNewElementsTests( $("#mutation-fixture") );
				start();
			}, 9);
		});

		asyncTest( "mutationobserver: changing sizes recalculates candidate", function() {
			var $img = $( "<img sizes='10px' srcset='small.jpg 30w, medium.jpg 99w' />");

			$("#mutation-fixture").append( $img );

			setTimeout(function() {
				var oldCurSrc = $img.prop('currentSrc');
				var oldSrc = $img.prop('src');

				$img.attr('sizes', '100px')

				setTimeout(function(){
					ok(oldCurSrc.indexOf('small.jpg') != -1);
					ok(oldSrc.indexOf('small.jpg') != -1);
					ok($img.prop('currentSrc').indexOf('medium.jpg') != -1);
					ok($img.prop('src').indexOf('medium.jpg') != -1);

					start();
				}, 9);
			}, 9);
		});

		asyncTest( "mutationobserver: functional integration test append", function() {
			var markup = $( "#template").html();

			createImgSpy();

			$("#mutation-fixture").append( markup );

			setTimeout(function() {
				runFunctionalNewElementsTests( $("#mutation-fixture") );
				start();
			}, 9);
		});
	};

	if( window.blanket ) {
		blanket.beforeStartTestRunner({
			callback: function() {
				setTimeout(startTests, QUnit.urlParams.coverage ? 500 : 0); //if blanketjs fails set a higher timeout
			}
		});
	} else {
		startTests();
	}

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


<commit_before>'use strict';

const path = require("path");
const fs = require("fs");

const mkdirp = require("mkdirp");
const async = require("async");
const rimraf = require("rimraf");
const exec = require("child_process").exec;

const installerConfig = require(path.normalize(process.env.PWD + "/../etc/config.js"));
const serviceModule = require("./service");
const mongoModule = require("./mongo");

//set the logger
const logger = require("../utils/utils.js").getLogger();

const SOAJS_RMS = {
	'urac': 'soajs.urac',
	'oauth': 'soajs.oauth',
	'dashboard': 'soajs.dashboard',
	'gateway': "soajs.controller",
	'ui': 'soajs.dashboard.ui'
};

function updateConfigFile(workingDirectory, cb) {
	installerConfig.workingDirectory = workingDirectory;
	let newData = "'use strict';\n\n";
	newData += "module.exports = " + JSON.stringify(installerConfig, null, 2) + ";\n";
	fs.writeFile(path.normalize(process.env.PWD + "/../etc/config.js"), newData, cb);
}

function installConsoleComponents(upgrade, cb) {
	let myPath = installerConfig.workingDirectory + "/node_modules/";
	fs.stat(myPath, (error, stats) => {
		if (error) {
			if (error.code === 'ENOENT' && !stats) {
				//if not found create the directories needed recursively
				mkdirp(myPath, runNPM);
			}
			else {
				return cb(error);
			}
		}
		else {
			runNPM();
		}
	});

	function checkIfModuleIsInstalled(oneRepo, cb){
		if(upgrade){
			return cb(null, false);
		}
		logger.debug("checking if repo is downloaded:", oneRepo);
		fs.stat(path.normalize(myPath + "/" + oneRepo), (error, stats) => {
			if (error) {
				if (error.code === 'ENOENT' && !stats) {
					//not found
					return cb(null, false);
				}
				else {
					return cb(error);
				}
			}
			else {
				return cb(null, true)
			}
		});
	}

	//install repos in component
	function runNPM() {
		logger.debug("\nInstalling SOAJS Console Components ...");
		async.eachOfSeries(SOAJS_RMS, (oneRepo, oneService, mCb) => {
			checkIfModuleIsInstalled(oneRepo, (error, exists) => {
				if(error){
					return mCb(error);
				}

				if(exists){
					return mCb(null, true);
				}

				logger.info(`Installing ${oneService} from NPM ${oneRepo} in ${installerConfig.workingDirectory} ...`);
				logger.debug(`sudo ${process.env.NPM_BIN} install ${oneRepo}`);
				let modInstall = exec(`sudo ${process.env.NPM_BIN} install ${oneRepo}`, {
					cwd: path.normalize(installerConfig.workingDirectory + "/node_modules")
				});

				modInstall.stdout.on('data', (data) => {
					if (data) {
						process.stdout.write(data);
					}
				});

				modInstall.stderr.on('data', (error) => {
					if (error) {
						process.stdout.write(error);
					}
				});

				modInstall.on('close', (code) => {
					if (code === 0) {
						logger.debug(`${oneService} installed!`);
						setTimeout(() => {
							return mCb(null, true);
						}, 500);
					}
					else {
						return mCb("Error installing " + oneService);
					}
				});

			});
		}, (error) => {
			if (error) {
				return cb(error);
			}

			return cb(null, true);
		});
	}
}

function ifNotSudo(callback) {
	if (process.env.PLATFORM === 'Linux' && process.env.LOGNAME !== 'root') {
		let output = "This command requires you run it as Root!\n";
		return callback(output);
	}
	else if(process.env.PLATFORM === 'Darwin' && process.env.LOGNAME !== 'root'){
		let output = "This command requires you run it as: sudo soajs console " + process.env.SOAJS_INSTALLER_COMMAND;
		return callback(output);
	}
}

const consoleModule = {

	/**
	 * This function configures and starts mongodb server stand alone
	 * then it patches the provisioned data in mongdb server
	 * then it installs all of SOAJS Console components
	 * then it starts all the SOAJS Console components
	 * @param args
	 * @param callback
	 */
	'install': (args, callback) => {
		if (args.length === 0) {
			return callback("Please provide where you want to install the SOAJS Console. Ex: soajs console install %folder_path%");
		}

		//clean up the path ...
		if (args[0].includes("node_modules")) {
			let myPath = args[0].split(path.sep);
			if (myPath[myPath.length - 1] === 'node_modules') {
				myPath.pop();
				myPath = myPath.join(path.sep);
				args[0] = myPath;
			}
		}

		logger.debug(`Checking provided path: ${args[0]} ...`);
		fs.stat(args[0], (error, stats) => {
			if (error) {
				if (error.code === 'ENOENT' && !stats) {
					//create the working directory
					mkdirp(path.normalize(args[0] + "/node_modules/"), (error) => {
						if (error) {
							return callback("Unable to work in provided folder path (might be permissions): " + args[0]);
						}
						updateConfiguration();
					});
				}
				else {
					return callback(error);
				}
			}
			else {
				updateConfiguration();
			}
		});

		function updateConfiguration() {
			logger.debug(`Configuring installer ...`);

			//update the configuration file
			installerConfig.workingDirectory = args[0];
			updateConfigFile(args[0], (error) => {
				if (error) {
					return callback("Unable to update Installer configuration file, please try again!");
				}

				//install and start mongo
				launchMongo();
			});
		}

		function launchMongo() {
			logger.debug(`Configuring MongoDB Server ...`);
			mongoModule.install([], (error, response) => {
				if (error) {
					return callback(error);
				}

				logger.debug(response);
				setTimeout(() => {
					logger.debug(`Starting MongoDB Server ...`);
					mongoModule.start([], (error, response) => {
						if (error) {
							return callback(error);
						}

						logger.debug(response);
						setTimeout(() => {

							logger.debug(`Importing Data in MongoDB Server ...`);
							mongoModule.patch([], (error, response) => {
								if (error) {
									return callback(error);
								}

								logger.debug(response);
								installSOAJSConsole();
							});
						}, 10000); //wait for mongo to become ready
					});
				}, 100);
			});
		}

		function installSOAJSConsole() {
			logger.debug(`Installing SOAJS Console ...`);
			//install all repository content
			installConsoleComponents(false, (error) => {
				if (error) {
					return callback("Error while isntalling the SOAJS Console files!")
				}

				//start microservices
				consoleModule.start(args, (error) => {
					if (error) {
						return callback("Unable to Start the SOAJS Console!");
					}

					return callback(null, "SOAJS Console Started!");
				});
			});
		}
	},

	/**
	 * This function will stop all the services of SOAJS Console
	 * it will then run npm install in the working directory to update all the microservices repos related
	 * then it will start the services of SOAJS Console again
	 * @param args
	 * @param callback
	 */
	'update': (args, callback) => {
		logger.info("Updating SOAJS Console ...\n\n");
		setTimeout(() => {
			//stop microservices
			consoleModule.stop(args, (error) => {
				if (error) {
					return callback("Unable to Stop the SOAJS Console!");
				}

				//update all repository content
				installConsoleComponents(true, (error) => {
					if (error) {
						return callback("Error while updating the SOAJS Console files!")
					}

					//start microservices
					consoleModule.start(args, (error) => {
						if (error) {
							return callback("Unable to Restart the SOAJS Console!");
						}

						return callback(null, "SOAJS Console Updated!");
					});
				});
			});
		}, 2000);
	},

	/**
	 * This function will stop all services of SOAJS Console
	 * it will also stop mongodb and clean up all SOAJS data from the database
	 * Then it will remove all the installed files and folders of SOAJS Console (PURGE Everything)
	 * @param args
	 * @param callback
	 */
	'remove': (args, callback) => {
		logger.info("Removing SOAJS Console ...\n\n");
		setTimeout(() => {
			//stop microservices
			consoleModule.stop(args, (error) => {
				if (error && error.toString() !== `SOAJS Console is not installed!`) {
					return callback("Unable to Stop the SOAJS Console!");
				}

				const mongoModule = require("./mongo.js");
				logger.info("Cleaning up Mongo and stopping it ...");
				setTimeout(() => {
					//remove data from mongodb
					mongoModule.clean([], (error) => {
						if (error && !error.message.includes("failed to connect to server")) {
							return callback("Error while Cleaning provisioned data from mongo!");
						}
						//stop mongodb
						mongoModule.stop([], (error) => {
							if (error) {
								return callback("Error while Stopping MongoDB Server!");
							}

							logger.info("Cleaning up downloaded SOAJS Console ...");
							setTimeout(() => {
								//remove folders of microservices
								async.eachOfSeries(SOAJS_RMS, (oneRepo, oneService, mCb) => {
									logger.debug(`Removing ${oneService} files ...`);
									logger.debug(path.normalize(installerConfig.workingDirectory + "/node_modules/" + SOAJS_RMS[oneService]) + "\n");
									rimraf(path.normalize(installerConfig.workingDirectory + "/node_modules/" + SOAJS_RMS[oneService]), (error) => {
										if (error) {
											logger.error(error);
											return mCb(error);
										}
										logger.debug(`${oneService} --> ${oneRepo}: Removed!`);
										return mCb();
									});
								}, (error) => {
									if (error) {
										return callback("Error Cleaning up SOAJS Console ...");
									}

									//remove working directory
									rimraf(path.normalize(installerConfig.workingDirectory), (error) => {
										if (error) {
											logger.error(error);
											return callback(error);
										}

										//clean up the configuration file
										updateConfigFile('', (error) => {
											logger.info("=========================\nSOAJS Console Removed!\n=========================\n\n");
											setTimeout(() => {
												return callback();
											}, 1000);
										});
									});
								});

							}, 2000);
						});
					});
				}, 2000);
			});

		}, 2000);
	},

	/**
	 * This function restarts all the services of the SOAJS Console
	 * @param args
	 * @param callback
	 */
	'restart': (args, callback) => {
		logger.info("Restarting SOAJS Console ...\n\n");
		setTimeout(() => {
			consoleModule.stop(args, (error) => {
				if (error && error.toString() !== `SOAJS Console is not installed!`) {
					return callback("Unable to Stop the SOAJS Console!");
				}

				consoleModule.start(args, (error) => {
					if (error) {
						return callback("Unable to Restart the SOAJS Console!");
					}

					return callback(null, "SOAJS Console Restarted!");
				});
			});
		}, 2000);
	},

	/**
	 * This command will calculate the needed env variables and
	 * start all the microservices in dashboard environment that the soajs console requires
	 * @param args {Array}
	 * @param callback {Function}
	 */
	'start': (args, callback) => {
		let requestedEnvironment = 'dashboard';

		//check if service is installed and downloaded
		if (!installerConfig.workingDirectory || installerConfig.workingDirectory === '') {
			return callback(`SOAJS Console is not installed!`);
		}

		logger.debug("Checking MongoDB Server ....");
		mongoModule.start([], (error, response) => {
			if (error) {
				return callback(error);
			}

			logger.info("Starting Microservices for SOAJS Console in Dashboard Environment ... \n");
			setTimeout(() => {
				async.eachOfSeries(SOAJS_RMS, (oneRepo, oneService, mCb) => {
					launchMyService(oneService, (error, response) => {
						if (error) {
							return mCb(error);
						}

						if (response && response !== '') {
							logger.debug(response + "\n");
						}
						return mCb(null, true);
					});
				}, (error) => {
					if (error) {
						return callback("Error starting the SOAJS Console");
					}

					logger.info("=========================\nSOAJS Console started!\n=========================\n\n");
					setTimeout(() => {
						return callback();
					}, 1000);
				});
			}, 1000);
		});

		function launchMyService(oneService, mCb) {
			serviceModule.start([oneService, "--env=" + requestedEnvironment], mCb)
		}
	},

	/**
	 * This command will find the process id of all microservices that the soajs console is using and kill them
	 * @param args
	 * @param callback
	 * @returns {*}
	 */
	'stop': (args, callback) => {

		ifNotSudo(callback);

		let requestedEnvironment = 'dashboard';

		//check if service is installed and downloaded
		if (!installerConfig.workingDirectory || installerConfig.workingDirectory === '') {
			return callback(`SOAJS Console is not installed!`);
		}

		logger.info("Stopping Microservices for SOAJS Console in Dashboard Environment ... \n");
		setTimeout(() => {
			async.eachOfSeries(SOAJS_RMS, (oneRepo, oneService, mCb) => {
				launchMyService(oneService, (error, response) => {
					if (error) {
						return mCb(error);
					}

					if (response && response !== '') {
						logger.debug(response + "\n");
					}

					return mCb(null, true);
				});
			}, (error) => {
				if (error) {
					return callback("Error stop the SOAJS Console");
				}

				logger.info("=========================\nSOAJS Console Stopped!\n=========================\n\n");
				setTimeout(() => {
					return callback();
				}, 1000);
			});

		}, 1000);

		function launchMyService(oneService, mCb) {
			serviceModule.stop([oneService, "--env=" + requestedEnvironment], mCb)
		}
	}
};

module.exports = consoleModule;<commit_msg>added extra assertions<commit_after>'use strict';

const path = require("path");
const fs = require("fs");

const mkdirp = require("mkdirp");
const async = require("async");
const rimraf = require("rimraf");
const exec = require("child_process").exec;

const installerConfig = require(path.normalize(process.env.PWD + "/../etc/config.js"));
const serviceModule = require("./service");
const mongoModule = require("./mongo");

//set the logger
const logger = require("../utils/utils.js").getLogger();

const SOAJS_RMS = {
	'urac': 'soajs.urac',
	'oauth': 'soajs.oauth',
	'dashboard': 'soajs.dashboard',
	'gateway': "soajs.controller",
	'ui': 'soajs.dashboard.ui'
};

function updateConfigFile(workingDirectory, cb) {
	installerConfig.workingDirectory = workingDirectory;
	let newData = "'use strict';\n\n";
	newData += "module.exports = " + JSON.stringify(installerConfig, null, 2) + ";\n";
	fs.writeFile(path.normalize(process.env.PWD + "/../etc/config.js"), newData, cb);
}

function installConsoleComponents(upgrade, cb) {
	let myPath = installerConfig.workingDirectory + "/node_modules/";
	fs.stat(myPath, (error, stats) => {
		if (error) {
			if (error.code === 'ENOENT' && !stats) {
				//if not found create the directories needed recursively
				mkdirp(myPath, runNPM);
			}
			else {
				return cb(error);
			}
		}
		else {
			runNPM();
		}
	});

	function checkIfModuleIsInstalled(oneRepo, cb){
		if(upgrade){
			return cb(null, false);
		}
		logger.debug("checking if repo is downloaded:", oneRepo);
		fs.stat(path.normalize(myPath + "/" + oneRepo), (error, stats) => {
			if (error) {
				if (error.code === 'ENOENT' && !stats) {
					//not found
					return cb(null, false);
				}
				else {
					return cb(error);
				}
			}
			else {
				return cb(null, true)
			}
		});
	}

	//install repos in component
	function runNPM() {
		logger.debug("\nInstalling SOAJS Console Components ...");
		async.eachOfSeries(SOAJS_RMS, (oneRepo, oneService, mCb) => {
			checkIfModuleIsInstalled(oneRepo, (error, exists) => {
				if(error){
					return mCb(error);
				}

				if(exists){
					return mCb(null, true);
				}

				logger.info(`Installing ${oneService} from NPM ${oneRepo} in ${installerConfig.workingDirectory} ...`);
				logger.debug(`sudo ${process.env.NPM_BIN} install ${oneRepo}`);
				let modInstall = exec(`sudo ${process.env.NPM_BIN} install ${oneRepo}`, {
					cwd: path.normalize(installerConfig.workingDirectory + "/node_modules")
				});

				modInstall.stdout.on('data', (data) => {
					if (data) {
						process.stdout.write(data);
					}
				});

				modInstall.stderr.on('data', (error) => {
					if (error) {
						process.stdout.write(error);
					}
				});

				modInstall.on('close', (code) => {
					if (code === 0) {
						logger.debug(`${oneService} installed!`);
						setTimeout(() => {
							return mCb(null, true);
						}, 500);
					}
					else {
						return mCb("Error installing " + oneService);
					}
				});

			});
		}, (error) => {
			if (error) {
				return cb(error);
			}

			return cb(null, true);
		});
	}
}

function ifNotSudo(callback) {
	if (process.env.PLATFORM === 'Linux' && process.env.LOGNAME !== 'root') {
		let output = "This command requires you run it as Root!\n";
		return callback(output);
	}
	else if(process.env.PLATFORM === 'Darwin' && process.env.LOGNAME !== 'root'){
		let output = "This command requires you run it as: sudo soajs console " + process.env.SOAJS_INSTALLER_COMMAND;
		return callback(output);
	}
}

const consoleModule = {

	/**
	 * This function configures and starts mongodb server stand alone
	 * then it patches the provisioned data in mongdb server
	 * then it installs all of SOAJS Console components
	 * then it starts all the SOAJS Console components
	 * @param args
	 * @param callback
	 */
	'install': (args, callback) => {
		if (args.length === 0) {
			return callback("Please provide where you want to install the SOAJS Console. Ex: soajs console install %folder_path%");
		}

		//clean up the path ...
		if (args[0].includes("node_modules")) {
			let myPath = args[0].split(path.sep);
			if (myPath[myPath.length - 1] === 'node_modules') {
				myPath.pop();
				myPath = myPath.join(path.sep);
				args[0] = myPath;
			}
		}

		logger.debug(`Checking provided path: ${args[0]} ...`);
		fs.stat(args[0], (error, stats) => {
			if (error) {
				if (error.code === 'ENOENT' && !stats) {
					//create the working directory
					mkdirp(path.normalize(args[0] + "/node_modules/"), (error) => {
						if (error) {
							return callback("Unable to work in provided folder path (might be permissions): " + args[0]);
						}
						updateConfiguration();
					});
				}
				else {
					return callback(error);
				}
			}
			else {
				updateConfiguration();
			}
		});

		function updateConfiguration() {
			logger.debug(`Configuring installer ...`);

			//update the configuration file
			installerConfig.workingDirectory = args[0];
			updateConfigFile(args[0], (error) => {
				if (error) {
					return callback("Unable to update Installer configuration file, please try again!");
				}

				//install and start mongo
				launchMongo();
			});
		}

		function launchMongo() {
			logger.debug(`Configuring MongoDB Server ...`);
			mongoModule.install([], (error, response) => {
				if (error) {
					return callback(error);
				}

				logger.debug(response);
				setTimeout(() => {
					logger.debug(`Starting MongoDB Server ...`);
					mongoModule.start([], (error, response) => {
						if (error) {
							return callback(error);
						}

						logger.debug(response);
						setTimeout(() => {

							logger.debug(`Importing Data in MongoDB Server ...`);
							mongoModule.patch([], (error, response) => {
								if (error) {
									return callback(error);
								}

								logger.debug(response);
								installSOAJSConsole();
							});
						}, 10000); //wait for mongo to become ready
					});
				}, 100);
			});
		}

		function installSOAJSConsole() {
			logger.debug(`Installing SOAJS Console ...`);
			//install all repository content
			installConsoleComponents(false, (error) => {
				if (error) {
					return callback("Error while isntalling the SOAJS Console files!")
				}

				//start microservices
				consoleModule.start(args, (error) => {
					if (error) {
						return callback("Unable to Start the SOAJS Console!");
					}

					return callback(null, "SOAJS Console Started!");
				});
			});
		}
	},

	/**
	 * This function will stop all the services of SOAJS Console
	 * it will then run npm install in the working directory to update all the microservices repos related
	 * then it will start the services of SOAJS Console again
	 * @param args
	 * @param callback
	 */
	'update': (args, callback) => {
		logger.info("Updating SOAJS Console ...\n\n");
		setTimeout(() => {
			//stop microservices
			consoleModule.stop(args, (error) => {
				if (error) {
					return callback("Unable to Stop the SOAJS Console!");
				}

				//update all repository content
				installConsoleComponents(true, (error) => {
					if (error) {
						return callback("Error while updating the SOAJS Console files!")
					}

					//start microservices
					consoleModule.start(args, (error) => {
						if (error) {
							return callback("Unable to Restart the SOAJS Console!");
						}

						return callback(null, "SOAJS Console Updated!");
					});
				});
			});
		}, 2000);
	},

	/**
	 * This function will stop all services of SOAJS Console
	 * it will also stop mongodb and clean up all SOAJS data from the database
	 * Then it will remove all the installed files and folders of SOAJS Console (PURGE Everything)
	 * @param args
	 * @param callback
	 */
	'remove': (args, callback) => {
		if (!installerConfig.workingDirectory || installerConfig.workingDirectory === '') {
			return callback(`SOAJS Console is not installed!`);
		}

		logger.info("Removing SOAJS Console ...\n\n");
		setTimeout(() => {
			//stop microservices
			consoleModule.stop(args, (error) => {
				if (error && error.toString() !== `SOAJS Console is not installed!`) {
					return callback("Unable to Stop the SOAJS Console!");
				}

				const mongoModule = require("./mongo.js");
				logger.info("Cleaning up Mongo and stopping it ...");
				setTimeout(() => {
					//remove data from mongodb
					mongoModule.clean([], (error) => {
						if (error && !error.message.includes("failed to connect to server")) {
							return callback("Error while Cleaning provisioned data from mongo!");
						}
						//stop mongodb
						mongoModule.stop([], (error) => {
							if (error) {
								return callback("Error while Stopping MongoDB Server!");
							}

							logger.info("Cleaning up downloaded SOAJS Console ...");
							setTimeout(() => {
								//remove folders of microservices
								async.eachOfSeries(SOAJS_RMS, (oneRepo, oneService, mCb) => {
									logger.debug(`Removing ${oneService} files ...`);
									logger.debug(path.normalize(installerConfig.workingDirectory + "/node_modules/" + SOAJS_RMS[oneService]) + "\n");
									rimraf(path.normalize(installerConfig.workingDirectory + "/node_modules/" + SOAJS_RMS[oneService]), (error) => {
										if (error) {
											logger.error(error);
											return mCb(error);
										}
										logger.debug(`${oneService} --> ${oneRepo}: Removed!`);
										return mCb();
									});
								}, (error) => {
									if (error) {
										return callback("Error Cleaning up SOAJS Console ...");
									}

									//remove working directory
									rimraf(path.normalize(installerConfig.workingDirectory), (error) => {
										if (error) {
											logger.error(error);
											return callback(error);
										}

										//clean up the configuration file
										updateConfigFile('', (error) => {
											logger.info("=========================\nSOAJS Console Removed!\n=========================\n\n");
											setTimeout(() => {
												return callback();
											}, 1000);
										});
									});
								});

							}, 2000);
						});
					});
				}, 2000);
			});

		}, 2000);
	},

	/**
	 * This function restarts all the services of the SOAJS Console
	 * @param args
	 * @param callback
	 */
	'restart': (args, callback) => {
		if (!installerConfig.workingDirectory || installerConfig.workingDirectory === '') {
			return callback(`SOAJS Console is not installed!`);
		}

		logger.info("Restarting SOAJS Console ...\n\n");
		setTimeout(() => {
			consoleModule.stop(args, (error) => {
				if (error && error.toString() !== `SOAJS Console is not installed!`) {
					return callback("Unable to Stop the SOAJS Console!");
				}

				consoleModule.start(args, (error) => {
					if (error) {
						return callback("Unable to Restart the SOAJS Console!");
					}

					return callback(null, "SOAJS Console Restarted!");
				});
			});
		}, 2000);
	},

	/**
	 * This command will calculate the needed env variables and
	 * start all the microservices in dashboard environment that the soajs console requires
	 * @param args {Array}
	 * @param callback {Function}
	 */
	'start': (args, callback) => {
		let requestedEnvironment = 'dashboard';

		//check if service is installed and downloaded
		if (!installerConfig.workingDirectory || installerConfig.workingDirectory === '') {
			return callback(`SOAJS Console is not installed!`);
		}

		logger.debug("Checking MongoDB Server ....");
		mongoModule.start([], (error, response) => {
			if (error) {
				return callback(error);
			}

			logger.info("Starting Microservices for SOAJS Console in Dashboard Environment ... \n");
			setTimeout(() => {
				async.eachOfSeries(SOAJS_RMS, (oneRepo, oneService, mCb) => {
					launchMyService(oneService, (error, response) => {
						if (error) {
							return mCb(error);
						}

						if (response && response !== '') {
							logger.debug(response + "\n");
						}
						return mCb(null, true);
					});
				}, (error) => {
					if (error) {
						return callback("Error starting the SOAJS Console");
					}

					logger.info("=========================\nSOAJS Console started!\n=========================\n\n");
					setTimeout(() => {
						return callback();
					}, 1000);
				});
			}, 1000);
		});

		function launchMyService(oneService, mCb) {
			serviceModule.start([oneService, "--env=" + requestedEnvironment], mCb)
		}
	},

	/**
	 * This command will find the process id of all microservices that the soajs console is using and kill them
	 * @param args
	 * @param callback
	 * @returns {*}
	 */
	'stop': (args, callback) => {

		ifNotSudo(callback);

		let requestedEnvironment = 'dashboard';

		//check if service is installed and downloaded
		if (!installerConfig.workingDirectory || installerConfig.workingDirectory === '') {
			return callback(`SOAJS Console is not installed!`);
		}

		logger.info("Stopping Microservices for SOAJS Console in Dashboard Environment ... \n");
		setTimeout(() => {
			async.eachOfSeries(SOAJS_RMS, (oneRepo, oneService, mCb) => {
				launchMyService(oneService, (error, response) => {
					if (error) {
						return mCb(error);
					}

					if (response && response !== '') {
						logger.debug(response + "\n");
					}

					return mCb(null, true);
				});
			}, (error) => {
				if (error) {
					return callback("Error stop the SOAJS Console");
				}

				logger.info("=========================\nSOAJS Console Stopped!\n=========================\n\n");
				setTimeout(() => {
					return callback();
				}, 1000);
			});

		}, 1000);

		function launchMyService(oneService, mCb) {
			serviceModule.stop([oneService, "--env=" + requestedEnvironment], mCb)
		}
	}
};

module.exports = consoleModule;<|endoftext|>


<commit_before><commit_msg>removed unreliable grayscale color generation. replaced with static list of acceptable colors<commit_after><|endoftext|>


<commit_before>define([
	"intern!object",
	"intern/chai!assert",
	"dojo/on",
	"delite/handlebars",
	"delite/register",
	"delite/Widget",
	"delite/handlebars!./templates/SimpleHandleBarsButton.html",
	"delite/handlebars!./templates/HandlebarsButton.html",
	"delite/handlebars!./templates/SvgWidget.html"
], function (registerSuite, assert, on, handlebars, register, Widget, simpleHBTmpl, buttonHBTmpl, svgTmpl) {
	var container, myButton;
	registerSuite({

		name: "handlebars",

		setup: function () {
			container = document.createElement("div");
			document.body.appendChild(container);
		},

		load: function () {
			// Test that function returned from delite/handlebars! creates the template correctly
			var TestButton = register("handlebars-button", [HTMLButtonElement, Widget], {
				iconClass: "originalClass",
				label: "original label",
				buildRendering: simpleHBTmpl
			});
			myButton = new TestButton();
			assert.strictEqual(myButton.tagName.toLowerCase(), "button", "root node exists");
			assert.strictEqual(myButton.firstChild.tagName.toLowerCase(), "span", "icon node exists too");
			assert.strictEqual(myButton.firstChild.className, "d-reset originalClass", "icon class set");
			assert.strictEqual(myButton.textContent.trim(), "original label", "label set");
		},

		update: function () {
			myButton.label = "new label";
			assert.strictEqual(myButton.textContent.trim(), "new label", "label updated");

			myButton.iconClass = "newClass";
			assert.strictEqual(myButton.firstChild.className, "d-reset newClass", "icon class set");

		},

		"data-attach-point": function () {
			// Testing that data-attach-point works

			var TestHtml = register("handlebars-data-attach-point", [HTMLElement, Widget], {
				buildRendering: handlebars.compile(
						"<template data-attach-point='root,root2'>" +
						"<button data-attach-point='myButton, myButton2'>hi</button>" +
						"</template>"
				)
			});

			var node = new TestHtml();

			assert.strictEqual(node.root.tagName.toLowerCase(), "handlebars-data-attach-point", "node.root");
			assert.strictEqual(node.root2.tagName.toLowerCase(), "handlebars-data-attach-point", "node.root");
			assert.strictEqual(node.myButton.tagName.toLowerCase(), "button", "node.myButton");
			assert.strictEqual(node.myButton2.tagName.toLowerCase(), "button", "node.myButton2");
		},

		branching: function () {
			var NoLabelButton = register("handlebars-no-label-button", [HTMLButtonElement, Widget], {
				iconClass: "originalClass",
				showLabel: false,
				label: "original label",
				buildRendering: buttonHBTmpl
			});
			myButton = new NoLabelButton();
			assert.strictEqual(myButton.tagName.toLowerCase(), "button", "root node exists");
			assert.strictEqual(myButton.firstChild.tagName.toLowerCase(), "span", "icon node exists too");
			assert.strictEqual(myButton.firstChild.className, "d-reset originalClass", "icon class set");
			assert.strictEqual(myButton.textContent.trim(), "", "no label");
			myButton.label = "new label";
			assert.strictEqual(myButton.textContent.trim(), "", "still no label");

			// Test true if condition
			var LabelButton = register("handlebars-label-button", [HTMLButtonElement, Widget], {
				iconClass: "originalClass",
				showLabel: true,
				label: "original label",
				buildRendering: buttonHBTmpl
			});
			myButton = new LabelButton();
			assert.strictEqual(myButton.tagName.toLowerCase(), "button", "root node exists");
			assert.strictEqual(myButton.firstChild.tagName.toLowerCase(), "span", "icon node exists too");
			assert.strictEqual(myButton.firstChild.className, "d-reset originalClass", "icon class set");
			assert.strictEqual(myButton.textContent.trim(), "original label", "label");

			// Make sure that changes still work
			myButton.label = "new label";
			assert.strictEqual(myButton.textContent.trim(), "new label", "label updated");

		},

		"special props": function () {
			var SpecialPropsWidget = register("handlebars-special-props", [HTMLElement, Widget], {
				inputClass: "originalClass",	// attribute called "class" but property called "className"
				inputValue: "original value",	// must be set as property
				role: "originalRole",			// must be set as attribute
				buildRendering: handlebars.compile(
						"<template><input class='{{inputClass}}' value='{{inputValue}}' " +
						"role='{{role}}'/></template>"
				)
			});
			var mySpecialPropsWidget = new SpecialPropsWidget();
			var input = mySpecialPropsWidget.children[0];

			assert.strictEqual(input.value, "original value", "value set as property");
			assert.strictEqual(input.className, "originalClass",
				"class set even though property is called className, not class");
			assert.strictEqual(input.getAttribute("role"), "originalRole", "role set as attribute");

			mySpecialPropsWidget.mix({
				inputClass: "newClass",
				inputValue: "new value",
				role: "newRole"
			});
			assert.strictEqual(input.value, "new value", "value changed");
			assert.strictEqual(input.className, "newClass", "class changed");
			assert.strictEqual(input.getAttribute("role"), "newRole", "role changed");

			// TODO: implement and then test reverse binding, from input.value --> widget.value?
		},

		"special characters": function () {
			// Test that special characters are escaped.  This is actually testing template.js.
			var TestList = register("handlebars-ul", [HTMLUListElement, Widget], {
				label: "bill'\\",
				buildRendering: handlebars.compile(
					"

\"\\{{label}}\n\twas \n\there'

")
			});
			var myList = new TestList();
			assert.strictEqual(myList.tagName.toLowerCase(), "ul", "root node exists");
			assert.strictEqual(myList.firstChild.tagName.toLowerCase(), "li", "child exists");
			assert.strictEqual(myList.firstChild.getAttribute("foo"), "a.b('c,d')", "single quotes prop");
			assert.strictEqual(myList.firstChild.getAttribute("bar"), "\\\"hello\"", "double quotes, backslash prop");
			assert.strictEqual(myList.firstChild.textContent, "\"\\bill'\\\n\twas \n\there'", "node text");
		},

		events: function () {
			// Test that listeners like onclick work.
			/* global g:true */
			g = 1;
			var TestClick = register("handlebars-events", [ HTMLElement, Widget], {
				buildRendering: handlebars.compile(
					"<template>click me</template>")
			});
			var myClick = new TestClick();
			myClick.placeAt(container);
			on.emit(myClick.firstChild, "click", {});
			assert.strictEqual(g, 2, "click handler fired");
		},

		"widgets in templates": function () {
			register("handlebars-heading", [HTMLElement, Widget], {
				text: "",
				buildRendering: handlebars.compile("<handlebars-heading>{{text}}</handlebars-heading>")
			});

			// This widget uses sub-widgets handlebars-button (defined in first test) and also handlebars-heading.
			var ComplexWidget = register("handlebars-widgets-in-template", [HTMLElement, Widget], {
				heading: "original heading",
				content: "original content",
				buttonLabel: "original button label",
				buildRendering: handlebars.compile(
					"<handlebars-widgets-in-template>" +
						"<handlebars-heading text='{{heading}}'></handlebars-heading>" +
						"{{content}}" +
						"<button is='handlebars-button' label='{{buttonLabel}}'></button>" +
					"</handlebars-widgets-in-template>"
				)
			});

			var myComplexWidget = new ComplexWidget(),
				headingWidget = myComplexWidget.getElementsByTagName("handlebars-heading")[0],
				buttonWidget = myComplexWidget.getElementsByTagName("button")[0];
			assert.ok(headingWidget.buildRendering, "heading widget was instantiated");
			assert.strictEqual(headingWidget.textContent, "original heading",
				"heading widget got title from main widget");
			assert.ok(buttonWidget.buildRendering, "button widget was instantiated");
			assert.strictEqual(buttonWidget.textContent.trim(), "original button label",
				"button widget got label from main widget");

			myComplexWidget.mix({
				heading: "new heading",
				buttonLabel: "new button label"
			});
			assert.strictEqual(headingWidget.textContent, "new heading", "heading changed");
			assert.strictEqual(buttonWidget.textContent.trim(), "new button label", "button changed");
		},

		html: function () {
			// Testing that parsing still works if ending tags are missing

			var TestHtml = register("handlebars-html", [HTMLUListElement, Widget], {
				buildRendering: handlebars.compile("

1

<input>
")
			});

			var node = new TestHtml();
			assert.strictEqual(node.tagName.toLowerCase(), "ul", "root node exists");

			node = node.firstChild;
			assert.strictEqual(node.tagName.toLowerCase(), "li", "first li exists");
			assert.strictEqual(node.textContent, "1", "first li value");

			node = node.nextSibling;
			assert.strictEqual(node.tagName.toLowerCase(), "li", "second li exists");

			node = node.firstChild;
			assert.strictEqual(node.tagName.toLowerCase(), "input", "input exists");
		},

		svg: function () {
			// Testing template with embedded SVG, for:
			//		1. xmlns attribute recognized, calls createElementNS() not createElement()
			//		2. class attribute still works
			//		3. tags of SVG nodes are lowercase
			//		4. attribute names are case sensitive

			var TestSvg = register("handlebars-svg", [HTMLElement, Widget], {
				buildRendering: svgTmpl
			});

			var node = new TestSvg();
			assert.strictEqual(node.tagName.toLowerCase(), "handlebars-svg", "root node exists");

			node = node.firstChild;
			assert.strictEqual(node.tagName, "svg", "svg node exists");
			assert.strictEqual(node.getAttribute("class"), "svg-root-class", "svg node class attribute");
			assert.strictEqual(node.getAttribute("viewBox"), "0 0 30 30", "viewBox");
			assert.strictEqual(node.namespaceURI, "http://www.w3.org/2000/svg", "svg.namespaceURI");

			node = node.firstChild;
			assert.strictEqual(node.tagName, "rect", "rect node exists");
			assert.strictEqual(node.namespaceURI, "http://www.w3.org/2000/svg", "rect.namespaceURI");
		},

		whitespace: function () {
			var WhiteSpace = register("handlebars-whitespace-one", [HTMLElement, Widget], {
				buildRendering: handlebars.compile(
					"<template>\nhello world\n</template>"
				)
			});
			var ws = new WhiteSpace();
			assert.strictEqual(ws.childNodes.length, 3, "middle whitespace preserved, start/end whitespace deleted");

			var WhiteSpaceNbsp = register("handlebars-whitespace-two", [HTMLElement, Widget], {
				buildRendering: handlebars.compile(
					"<template> hello world </template>"
				)
			});
			var wsn = new WhiteSpaceNbsp();
			assert.strictEqual(wsn.childNodes.length, 5, "all &nbsp preserved");

			var WhiteSpaceComments = register("handlebars-whitespace-three", [HTMLElement, Widget], {
				buildRendering: handlebars.compile(
					"<template>\n\nhello world\n</template>"
				)
			});
			var wsc = new WhiteSpaceComments();
			assert.strictEqual(wsc.childNodes.length, 3, "comments don't break trimming");

			var WhiteSpacePre = register("handlebars-whitespace-pre", [HTMLElement, Widget], {
				buildRendering: handlebars.compile(
					"<template>
\thello\n\tworld
</template>"
				)
			});
			var wsp = new WhiteSpacePre();
			assert.strictEqual(wsp.innerHTML, "
\thello\n\tworld
", "pre whitespace preserved");
		},

		"self closing tags": function () {
			var SelfClosing = register("handlebars-self-closing", [HTMLElement, Widget], {
				buildRendering: handlebars.compile(
					"<template>Hello
<input>world</template>"
				)
			});
			var sc = new SelfClosing();
			assert.strictEqual(sc.childNodes.length, 4, "# of child nodes");
		},

		nestedProperties: function () {
			// Testing that nested properties work, with the caveat that updates are only detected if
			// the top level property is changed.
			// Also tests that undefined values convert to "" rather than "undefined".

			var TestNested = register("handlebars-nested", [HTMLElement, Widget], {
				item: {
					first: "Bob"
				},

				buildRendering: handlebars.compile(
					"Hello {{item.first}} {{item.last}}!")
			});

			var node = new TestNested();
			assert.strictEqual(node.className, "", "class #1");
			assert.strictEqual(node.textContent.trim(), "Hello Bob !", "textContent #1");

			node.item = {
				first: "Tom"
			};
			assert.strictEqual(node.className, "", "class #2");
			assert.strictEqual(node.textContent.trim(), "Hello Tom !", "textContent #2");

			node.item = {
				first: "Fred",
				last: "Smith",
				className: "blue"
			};
			assert.strictEqual(node.className, "blue", "class #3");
			assert.strictEqual(node.textContent.trim(), "Hello Fred Smith!", "textContent #3");
		},

		teardown: function () {
			container.parentNode.removeChild(container);
		}
	});
});
<commit_msg>Examples of poor man's solution to show/hide nodes in template. Refs #183 tangentially.<commit_after>define([
	"intern!object",
	"intern/chai!assert",
	"dojo/on",
	"delite/handlebars",
	"delite/register",
	"delite/Widget",
	"delite/handlebars!./templates/SimpleHandleBarsButton.html",
	"delite/handlebars!./templates/HandlebarsButton.html",
	"delite/handlebars!./templates/SvgWidget.html"
], function (registerSuite, assert, on, handlebars, register, Widget, simpleHBTmpl, buttonHBTmpl, svgTmpl) {
	var container, myButton;
	registerSuite({

		name: "handlebars",

		setup: function () {
			container = document.createElement("div");
			document.body.appendChild(container);
		},

		load: function () {
			// Test that function returned from delite/handlebars! creates the template correctly
			var TestButton = register("handlebars-button", [HTMLButtonElement, Widget], {
				iconClass: "originalClass",
				label: "original label",
				buildRendering: simpleHBTmpl
			});
			myButton = new TestButton();
			assert.strictEqual(myButton.tagName.toLowerCase(), "button", "root node exists");
			assert.strictEqual(myButton.firstChild.tagName.toLowerCase(), "span", "icon node exists too");
			assert.strictEqual(myButton.firstChild.className, "d-reset originalClass", "icon class set");
			assert.strictEqual(myButton.textContent.trim(), "original label", "label set");
		},

		update: function () {
			myButton.label = "new label";
			assert.strictEqual(myButton.textContent.trim(), "new label", "label updated");

			myButton.iconClass = "newClass";
			assert.strictEqual(myButton.firstChild.className, "d-reset newClass", "icon class set");

		},

		"data-attach-point": function () {
			// Testing that data-attach-point works

			var TestHtml = register("handlebars-data-attach-point", [HTMLElement, Widget], {
				buildRendering: handlebars.compile(
						"<template data-attach-point='root,root2'>" +
						"<button data-attach-point='myButton, myButton2'>hi</button>" +
						"</template>"
				)
			});

			var node = new TestHtml();

			assert.strictEqual(node.root.tagName.toLowerCase(), "handlebars-data-attach-point", "node.root");
			assert.strictEqual(node.root2.tagName.toLowerCase(), "handlebars-data-attach-point", "node.root");
			assert.strictEqual(node.myButton.tagName.toLowerCase(), "button", "node.myButton");
			assert.strictEqual(node.myButton2.tagName.toLowerCase(), "button", "node.myButton2");
		},

		branching: function () {
			var NoLabelButton = register("handlebars-no-label-button", [HTMLButtonElement, Widget], {
				iconClass: "originalClass",
				showLabel: false,
				label: "original label",
				buildRendering: buttonHBTmpl
			});
			myButton = new NoLabelButton();
			assert.strictEqual(myButton.tagName.toLowerCase(), "button", "root node exists");
			assert.strictEqual(myButton.firstChild.tagName.toLowerCase(), "span", "icon node exists too");
			assert.strictEqual(myButton.firstChild.className, "d-reset originalClass", "icon class set");
			assert.strictEqual(myButton.textContent.trim(), "", "no label");
			myButton.label = "new label";
			assert.strictEqual(myButton.textContent.trim(), "", "still no label");

			// Test true if condition
			var LabelButton = register("handlebars-label-button", [HTMLButtonElement, Widget], {
				iconClass: "originalClass",
				showLabel: true,
				label: "original label",
				buildRendering: buttonHBTmpl
			});
			myButton = new LabelButton();
			assert.strictEqual(myButton.tagName.toLowerCase(), "button", "root node exists");
			assert.strictEqual(myButton.firstChild.tagName.toLowerCase(), "span", "icon node exists too");
			assert.strictEqual(myButton.firstChild.className, "d-reset originalClass", "icon class set");
			assert.strictEqual(myButton.textContent.trim(), "original label", "label");

			// Make sure that changes still work
			myButton.label = "new label";
			assert.strictEqual(myButton.textContent.trim(), "new label", "label updated");

		},

		"special props": function () {
			var SpecialPropsWidget = register("handlebars-special-props", [HTMLElement, Widget], {
				inputClass: "originalClass",	// attribute called "class" but property called "className"
				inputValue: "original value",	// must be set as property
				role: "originalRole",			// must be set as attribute
				buildRendering: handlebars.compile(
						"<template><input class='{{inputClass}}' value='{{inputValue}}' " +
						"role='{{role}}'/></template>"
				)
			});
			var mySpecialPropsWidget = new SpecialPropsWidget();
			var input = mySpecialPropsWidget.children[0];

			assert.strictEqual(input.value, "original value", "value set as property");
			assert.strictEqual(input.className, "originalClass",
				"class set even though property is called className, not class");
			assert.strictEqual(input.getAttribute("role"), "originalRole", "role set as attribute");

			mySpecialPropsWidget.mix({
				inputClass: "newClass",
				inputValue: "new value",
				role: "newRole"
			});
			assert.strictEqual(input.value, "new value", "value changed");
			assert.strictEqual(input.className, "newClass", "class changed");
			assert.strictEqual(input.getAttribute("role"), "newRole", "role changed");

			// TODO: implement and then test reverse binding, from input.value --> widget.value?
		},

		"special characters": function () {
			// Test that special characters are escaped.  This is actually testing template.js.
			var TestList = register("handlebars-ul", [HTMLUListElement, Widget], {
				label: "bill'\\",
				buildRendering: handlebars.compile(
					"

\"\\{{label}}\n\twas \n\there'

")
			});
			var myList = new TestList();
			assert.strictEqual(myList.tagName.toLowerCase(), "ul", "root node exists");
			assert.strictEqual(myList.firstChild.tagName.toLowerCase(), "li", "child exists");
			assert.strictEqual(myList.firstChild.getAttribute("foo"), "a.b('c,d')", "single quotes prop");
			assert.strictEqual(myList.firstChild.getAttribute("bar"), "\\\"hello\"", "double quotes, backslash prop");
			assert.strictEqual(myList.firstChild.textContent, "\"\\bill'\\\n\twas \n\there'", "node text");
		},

		events: function () {
			// Test that listeners like onclick work.
			/* global g:true */
			g = 1;
			var TestClick = register("handlebars-events", [ HTMLElement, Widget], {
				buildRendering: handlebars.compile(
					"<template>click me</template>")
			});
			var myClick = new TestClick();
			myClick.placeAt(container);
			on.emit(myClick.firstChild, "click", {});
			assert.strictEqual(g, 2, "click handler fired");
		},

		"widgets in templates": function () {
			register("handlebars-heading", [HTMLElement, Widget], {
				text: "",
				buildRendering: handlebars.compile("<handlebars-heading>{{text}}</handlebars-heading>")
			});

			// This widget uses sub-widgets handlebars-button (defined in first test) and also handlebars-heading.
			var ComplexWidget = register("handlebars-widgets-in-template", [HTMLElement, Widget], {
				heading: "original heading",
				content: "original content",
				buttonLabel: "original button label",
				buildRendering: handlebars.compile(
					"<handlebars-widgets-in-template>" +
						"<handlebars-heading text='{{heading}}'></handlebars-heading>" +
						"{{content}}" +
						"<button is='handlebars-button' label='{{buttonLabel}}'></button>" +
					"</handlebars-widgets-in-template>"
				)
			});

			var myComplexWidget = new ComplexWidget(),
				headingWidget = myComplexWidget.getElementsByTagName("handlebars-heading")[0],
				buttonWidget = myComplexWidget.getElementsByTagName("button")[0];
			assert.ok(headingWidget.buildRendering, "heading widget was instantiated");
			assert.strictEqual(headingWidget.textContent, "original heading",
				"heading widget got title from main widget");
			assert.ok(buttonWidget.buildRendering, "button widget was instantiated");
			assert.strictEqual(buttonWidget.textContent.trim(), "original button label",
				"button widget got label from main widget");

			myComplexWidget.mix({
				heading: "new heading",
				buttonLabel: "new button label"
			});
			assert.strictEqual(headingWidget.textContent, "new heading", "heading changed");
			assert.strictEqual(buttonWidget.textContent.trim(), "new button label", "button changed");
		},

		html: function () {
			// Testing that parsing still works if ending tags are missing

			var TestHtml = register("handlebars-html", [HTMLUListElement, Widget], {
				buildRendering: handlebars.compile("

1

<input>
")
			});

			var node = new TestHtml();
			assert.strictEqual(node.tagName.toLowerCase(), "ul", "root node exists");

			node = node.firstChild;
			assert.strictEqual(node.tagName.toLowerCase(), "li", "first li exists");
			assert.strictEqual(node.textContent, "1", "first li value");

			node = node.nextSibling;
			assert.strictEqual(node.tagName.toLowerCase(), "li", "second li exists");

			node = node.firstChild;
			assert.strictEqual(node.tagName.toLowerCase(), "input", "input exists");
		},

		svg: function () {
			// Testing template with embedded SVG, for:
			//		1. xmlns attribute recognized, calls createElementNS() not createElement()
			//		2. class attribute still works
			//		3. tags of SVG nodes are lowercase
			//		4. attribute names are case sensitive

			var TestSvg = register("handlebars-svg", [HTMLElement, Widget], {
				buildRendering: svgTmpl
			});

			var node = new TestSvg();
			assert.strictEqual(node.tagName.toLowerCase(), "handlebars-svg", "root node exists");

			node = node.firstChild;
			assert.strictEqual(node.tagName, "svg", "svg node exists");
			assert.strictEqual(node.getAttribute("class"), "svg-root-class", "svg node class attribute");
			assert.strictEqual(node.getAttribute("viewBox"), "0 0 30 30", "viewBox");
			assert.strictEqual(node.namespaceURI, "http://www.w3.org/2000/svg", "svg.namespaceURI");

			node = node.firstChild;
			assert.strictEqual(node.tagName, "rect", "rect node exists");
			assert.strictEqual(node.namespaceURI, "http://www.w3.org/2000/svg", "rect.namespaceURI");
		},

		whitespace: function () {
			var WhiteSpace = register("handlebars-whitespace-one", [HTMLElement, Widget], {
				buildRendering: handlebars.compile(
					"<template>\nhello world\n</template>"
				)
			});
			var ws = new WhiteSpace();
			assert.strictEqual(ws.childNodes.length, 3, "middle whitespace preserved, start/end whitespace deleted");

			var WhiteSpaceNbsp = register("handlebars-whitespace-two", [HTMLElement, Widget], {
				buildRendering: handlebars.compile(
					"<template> hello world </template>"
				)
			});
			var wsn = new WhiteSpaceNbsp();
			assert.strictEqual(wsn.childNodes.length, 5, "all &nbsp preserved");

			var WhiteSpaceComments = register("handlebars-whitespace-three", [HTMLElement, Widget], {
				buildRendering: handlebars.compile(
					"<template>\n\nhello world\n</template>"
				)
			});
			var wsc = new WhiteSpaceComments();
			assert.strictEqual(wsc.childNodes.length, 3, "comments don't break trimming");

			var WhiteSpacePre = register("handlebars-whitespace-pre", [HTMLElement, Widget], {
				buildRendering: handlebars.compile(
					"<template>
\thello\n\tworld
</template>"
				)
			});
			var wsp = new WhiteSpacePre();
			assert.strictEqual(wsp.innerHTML, "
\thello\n\tworld
", "pre whitespace preserved");
		},

		"self closing tags": function () {
			var SelfClosing = register("handlebars-self-closing", [HTMLElement, Widget], {
				buildRendering: handlebars.compile(
					"<template>Hello
<input>world</template>"
				)
			});
			var sc = new SelfClosing();
			assert.strictEqual(sc.childNodes.length, 4, "# of child nodes");
		},

		nestedProperties: function () {
			// Testing that nested properties work, with the caveat that updates are only detected if
			// the top level property is changed.
			// Also tests that undefined values convert to "" rather than "undefined".

			var TestNested = register("handlebars-nested", [HTMLElement, Widget], {
				item: {
					first: "Bob"
				},

				buildRendering: handlebars.compile(
					"Hello {{item.first}} {{item.last}}!")
			});

			var node = new TestNested();
			assert.strictEqual(node.className, "", "class #1");
			assert.strictEqual(node.textContent.trim(), "Hello Bob !", "textContent #1");

			node.item = {
				first: "Tom"
			};
			assert.strictEqual(node.className, "", "class #2");
			assert.strictEqual(node.textContent.trim(), "Hello Tom !", "textContent #2");

			node.item = {
				first: "Fred",
				last: "Smith",
				className: "blue"
			};
			assert.strictEqual(node.className, "blue", "class #3");
			assert.strictEqual(node.textContent.trim(), "Hello Fred Smith!", "textContent #3");
		},

		hide: function () {
			// Testing poor man's solution to hide nodes depending on boolean widget property.

			// Template.js doesn't have any provisions for creating/removing attributes, and all falsy
			// attributes are converted to an empty string, so the attribute setting will be either hide="true"
			// or hide="".
			container.insertAdjacentHTML("beforeend",
				"");

			var TestNested = register("handlebars-hide", [HTMLElement, Widget], {
				hideSpan: true,
				buildRendering: handlebars.compile("hello world")
			});

			var node = new TestNested();
			node.placeAt(container);
			assert.strictEqual(getComputedStyle(node).display, "none", "hidden");

			node.hideSpan = false;
			assert.strictEqual(getComputedStyle(node).display, "inline", "not hidden");
		},

		show: function () {
			// Testing poor man's solution to show nodes depending on boolean widget property

			// Template.js doesn't have any provisions for creating/removing attributes, and all falsy
			// attributes are converted to an empty string, so the attribute setting will be either show="true"
			// or show="".  I thought [show=''] as a CSS selector would work but for some reason it doesn't.
			container.insertAdjacentHTML("beforeend",
				"");

			var TestNested = register("handlebars-show", [HTMLElement, Widget], {
				showSpan: true,
				buildRendering: handlebars.compile("hello world")
			});

			var node = new TestNested();
			node.placeAt(container);
			assert.strictEqual(getComputedStyle(node).display, "inline", "not hidden");

			node.showSpan = false;
			assert.strictEqual(getComputedStyle(node).display, "none", "hidden");
		},

		teardown: function () {
			container.parentNode.removeChild(container);
		}
	});
});
<|endoftext|>


<commit_before>import jsx from '../src/jsx.js';

describe('jsx', () => {
  it('shound return a object', () => {
    let object = {
      nodeName: 'div',
      attributes: { id: 'app' },
      children: [ 'Hello World!' ]
    };

    expect(jsx('div', { id: 'app' }, 'Hello World!')).toEqual(object);
    expect(jsx('div', null)).toEqual({nodeName: 'div', attributes: null, children: null});
  });

  it('should support element children', () => {
    let object = {
      nodeName: 'div',
      attributes: null,
      children: [
        {
          nodeName: 'div',
          attributes: { id: 'app' },
          children: [ 'Hello World!' ]
        }
      ]
    };

    expect(jsx('div', null, jsx('div', { id: 'app' }, 'Hello World!'))).toEqual(object);
  });
});
<commit_msg>Update Test<commit_after>import { createElement } from '../src/fiber.js';

describe('jsx', () => {
  it('shound return a object', () => {
    let object = {
      nodeName: 'div',
      attributes: { id: 'app' },
      children: [ 'Hello World!' ]
    };

    expect(createElement('div', { id: 'app' }, 'Hello World!')).toEqual(object);
    expect(createElement('div', null)).toEqual({nodeName: 'div', attributes: null, children: null});
  });

  it('should support element children', () => {
    let object = {
      nodeName: 'div',
      attributes: null,
      children: [
        {
          nodeName: 'div',
          attributes: { id: 'app' },
          children: [ 'Hello World!' ]
        }
      ]
    };

    expect(createElement('div', null, createElement('div', { id: 'app' }, 'Hello World!'))).toEqual(object);
  });
});
<|endoftext|>