<commit_before>
// run the currently selected effect
function runEffect(togglerWindow) {
        $(togglerWindow ).show( "slide",{direction: "left"}, 1500);
};

$(document).ready(function()
{
    $.ajaxSetup ({
        cache: false
    });

    setupCSS();

    // hide toggle windows
    hideToggleWindows();

    // hover effects
    $('#requestInviteButton, #loginButton, #submitRequestInvite, #submitLogin').hover(
        function() {$(this).addClass('ui-state-hover');},
        function() {$(this).removeClass('ui-state-hover');}
     );

    $("#loginForm").ajaxSuccess(function(){
    });

    $("#loginForm").ajaxComplete(function(){
    });

    $("#loginForm").ajaxError(function(){
        alert("Fail");
    });
    $("#loginForm").submit(function(e){
        // validate user via ajax call
        e.preventDefault();
        var url = Routing.generate('Validate');
        var info = {email: $("#login_email_addr").val(), password: $("#password").val()};

        ajaxPost(info, url, function(data){
            $dataArray = data.split(",");
            if($dataArray[0].toLowerCase() === "continue")
            {
                redirectToHomePage(); // redirect to home page
            }
            else
            {
                displayMessage(data, "Alert");
            }
        }, null);
    });

    $('#requestInviteForm').submit(function(e) {
        e.preventDefault();
        var url = Routing.generate('RequestInvite');
        var info = {email: $("#email_addr").val()};
        ajaxPost(info, url, function(data){
            displayMessage(data, "Request Submitted");
        }, null);
    });

    // set effect from log in or request invite buttons
    $("#requestInviteButton, #loginButton, #loginLink").click(function(e) {
        e.preventDefault();
        var thisId = $(this).attr('id');
        var activeToggler_SelectorId = "";
        var hiddenToggler_SelectorId = "";

        if(thisId == "requestInviteButton")
        {
            activeToggler_SelectorId = "#requestInviteToggleWindow";
            hiddenToggler_SelectorId = "#loginToggleWindow";
        }
        else{
            activeToggler_SelectorId = "#loginToggleWindow";
            hiddenToggler_SelectorId = "#requestInviteToggleWindow";
        }

        $(hiddenToggler_SelectorId).hide();
        runEffect(activeToggler_SelectorId);
    });

    $(".aboutLink").click(function(e){
        e.preventDefault();
        eval('displayMessageDialog(aboutMessage, "What is Wishlist?")');
    });

    // a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
    $( "#dialog:ui-dialog" ).dialog( "destroy" );

});

var aboutMessage = "The founders of Wishenda came up with the idea of making this site in hopes that it would help \n\
                    their friends and family out during holidays, birthdays, and any other special occasion.

 \n\
                    Message from the founders:
 \n\
                    'Every year for christmas we would write up our wish lists and wanted an easy way to share it with our close friends and family so that they would know what we want. \n\
                    This gave us the idea to make this site and hope that other people would be able to use it to do the same.'

\n\
                    With Wishenda you know what all of your friends want and they know what you want. Shopping for each other has never been easier!";

function displayMessageDialog(msg, title)
{
    displayMessage(msg, title);
}

function displayMessage(message, title)
{
    $('#dialog-message').html(message);
    $( "#dialog-message" ).dialog({
        title: title,
        position: 'top',
        modal: true,
        height:400,
        width:400,
        buttons: {
                Ok: function() {
                        $( this ).dialog( "close" );
                }
        }
    });
}

function redirectToHomePage()
{
    // redirect to the logged in user's home page
    window.location = $('#homepageLinkPath').val();
}

// run the currently selected effect
function runEffect(togglerWindow) {
    $(togglerWindow ).show( "slide",{direction: "left"}, 1500);
}

function setupCSS()
{
    $(':input').addClass("ui-state-default");
    $(':input').addClass("ui-corner-all");

    $('#requestInviteButton, #loginButton').addClass("ui-state-default");
    $('#requestInviteButton, #loginButton').addClass("ui-corner-all");
}

// hide the toggle windows
function hideToggleWindows()
{
    $('#requestInviteToggleWindow').hide();
    $('#loginToggleWindow').hide();
}
<commit_msg>moved around the functions in frontPage.js so that it would pass the jslint violations<commit_after>function displayMessage(message, title)
{
    $('#dialog-message').html(message);
    $( "#dialog-message" ).dialog({
        title: title,
        position: 'top',
        modal: true,
        height:400,
        width:400,
        buttons: {
                Ok: function() {
                        $( this ).dialog( "close" );
                }
        }
    });
}

// run the currently selected effect
function runEffect(togglerWindow) {
        $(togglerWindow ).show( "slide",{direction: "left"}, 1500);
}

function displayMessageDialog(msg, title)
{
    displayMessage(msg, title);
}

function redirectToHomePage()
{
    // redirect to the logged in user's home page
    window.location = $('#homepageLinkPath').val();
}

function setupCSS()
{
    $(':input').addClass("ui-state-default");
    $(':input').addClass("ui-corner-all");

    $('#requestInviteButton, #loginButton').addClass("ui-state-default");
    $('#requestInviteButton, #loginButton').addClass("ui-corner-all");
}

// hide the toggle windows
function hideToggleWindows()
{
    $('#requestInviteToggleWindow').hide();
    $('#loginToggleWindow').hide();
}

$(document).ready(function()
{
    $.ajaxSetup ({
        cache: false
    });

    setupCSS();

    // hide toggle windows
    hideToggleWindows();

    // hover effects
    $('#requestInviteButton, #loginButton, #submitRequestInvite, #submitLogin').hover(
        function() {$(this).addClass('ui-state-hover');},
        function() {$(this).removeClass('ui-state-hover');}
     );

    $("#loginForm").ajaxSuccess(function(){
    });

    $("#loginForm").ajaxComplete(function(){
    });

    $("#loginForm").ajaxError(function(){
        alert("Fail");
    });
    $("#loginForm").submit(function(e){
        // validate user via ajax call
        e.preventDefault();
        var url = Routing.generate('Validate');
        var info = {email: $("#login_email_addr").val(), password: $("#password").val()};

        ajaxPost(info, url, function(data){
            $dataArray = data.split(",");
            if($dataArray[0].toLowerCase() === "continue")
            {
                redirectToHomePage(); // redirect to home page
            }
            else
            {
                displayMessage(data, "Alert");
            }
        }, null);
    });

    $('#requestInviteForm').submit(function(e) {
        e.preventDefault();
        var url = Routing.generate('RequestInvite');
        var info = {email: $("#email_addr").val()};
        ajaxPost(info, url, function(data){
            displayMessage(data, "Request Submitted");
        }, null);
    });

    // set effect from log in or request invite buttons
    $("#requestInviteButton, #loginButton, #loginLink").click(function(e) {
        e.preventDefault();
        var thisId = $(this).attr('id');
        var activeToggler_SelectorId = "";
        var hiddenToggler_SelectorId = "";

        if(thisId === "requestInviteButton")
        {
            activeToggler_SelectorId = "#requestInviteToggleWindow";
            hiddenToggler_SelectorId = "#loginToggleWindow";
        }
        else{
            activeToggler_SelectorId = "#loginToggleWindow";
            hiddenToggler_SelectorId = "#requestInviteToggleWindow";
        }

        $(hiddenToggler_SelectorId).hide();
        runEffect(activeToggler_SelectorId);
    });

    $(".aboutLink").click(function(e){
        e.preventDefault();
        eval('displayMessageDialog(aboutMessage, "What is Wishlist?")');
    });

    // a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
    $( "#dialog:ui-dialog" ).dialog( "destroy" );

});

var aboutMessage = "The founders of Wishenda came up with the idea of making this site in hopes that it would help \n\
                    their friends and family out during holidays, birthdays, and any other special occasion.

 \n\
                    Message from the founders:
 \n\
                    'Every year for christmas we would write up our wish lists and wanted an easy way to share it with our close friends and family so that they would know what we want. \n\
                    This gave us the idea to make this site and hope that other people would be able to use it to do the same.'

\n\
                    With Wishenda you know what all of your friends want and they know what you want. Shopping for each other has never been easier!";

// run the currently selected effect
function runEffect(togglerWindow) {
    $(togglerWindow ).show( "slide",{direction: "left"}, 1500);
}
<|endoftext|>


<commit_before>var cloneCanvas = function(self) {
	var c = document.createElement('canvas');
	c.width = self.width;
	c.height = self.height;
	var cxt = c.getContext('2d');
	cxt.drawImage(self,0,0);
	return c;
};

function blitImage(ctx, image, sx ,sy, sw, sh, dx, dy, dw, dh) {
	var x; var y;
	for (x=0;x<dw;x++) {
		for (y=0;y<dh;y++) {
			ctx.drawImage(image,Math.floor(sx+x*(sw/dw)),Math.floor(sy+y*(sw/dw)),1,1,dx+x,dy+y,1,1);
		}
	}
}

function createMinecraftHead(player,completed,failed) {
	var skinImage = new Image();
	skinImage.onload = function() {
		var headCanvas = document.createElement('canvas');
		headCanvas.width = 8;
		headCanvas.height = 8;
		var headContext = headCanvas.getContext('2d');
		blitImage(headContext, skinImage,  8,8,8,8, 0,0,8,8);
		blitImage(headContext, skinImage, 40,8,8,8, 0,0,8,8);
		completed(headCanvas);
	};
	skinImage.onerror = function() {
		if (skinImage.src == '//www.minecraft.net/img/char.png') {
			failed();
		} else {
			skinImage.src = '//www.minecraft.net/img/char.png';
		}
	};
	skinImage.src = '//s3.amazonaws.com/MinecraftSkins/' + player + '.png';
}

function resizeImage(img,size) {
	var canvas = document.createElement('canvas');
	canvas.width = size;
	canvas.height = size;
	var ctx = canvas.getContext('2d');
	blitImage(ctx, img, 0,0,img.width,img.height, 0,0,size,size);
	return canvas;
}

var playerHeads = {};

function getMinecraftHead(player,size,completed) {
	var head = playerHeads[player];
	// Synchronous
	if (!completed) {
		return (!head || head.working) ? null : head;
	}

	// Asynchronous
	if (!head) {
		playerHeads[player] = { working: true, hooks: [{f:completed,s:size}] };
		//console.log('Creating head for ',player,'...');
		createMinecraftHead(player, function(head) {
			//console.log('Created head for ',player,': ', head);
			hooks = playerHeads[player].hooks;
			playerHeads[player] = head;
			var i;
			for(i=0;i<hooks.length;i++) {
				hooks[i].f(resizeImage(head,hooks[i].s));
			}
		}, function() {

		});
	} else if (head.working) {
		//console.log('Other process working on head of ',player,', will add myself to hooks...');
		head.hooks[head.hooks.length] = {f:completed,s:size};
	} else {
		completed(resizeImage(head,size));
	}
}

function getMinecraftTime(servertime) {
	servertime = parseInt(servertime);
	var day = servertime >= 0 && servertime < 13700;
	return {
		servertime: servertime,
		days: parseInt((servertime+8000) / 24000),

		// Assuming it is day at 8:00
		hours: (parseInt(servertime / 1000)+8) % 24,
		minutes: parseInt(((servertime / 1000) % 1) * 60),
		seconds: parseInt(((((servertime / 1000) % 1) * 60) % 1) * 60),

		day: day,
		night: !day
	};
}
<commit_msg>Drop accessory face overlay - hardly seems used and causes white faces<commit_after>var cloneCanvas = function(self) {
	var c = document.createElement('canvas');
	c.width = self.width;
	c.height = self.height;
	var cxt = c.getContext('2d');
	cxt.drawImage(self,0,0);
	return c;
};

function blitImage(ctx, image, sx ,sy, sw, sh, dx, dy, dw, dh) {
	ctx.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh);
//	var x; var y;
//	for (x=0;x<dw;x++) {
//		for (y=0;y<dh;y++) {
//			ctx.drawImage(image,Math.floor(sx+x*(sw/dw)),Math.floor(sy+y*(sw/dw)),1,1,dx+x,dy+y,1,1);
//		}
//	}
}

function createMinecraftHead(player,completed,failed) {
	var skinImage = new Image();
	skinImage.onload = function() {
		var headCanvas = document.createElement('canvas');
		headCanvas.width = 8;
		headCanvas.height = 8;
		var headContext = headCanvas.getContext('2d');
		blitImage(headContext, skinImage,  8,8,8,8, 0,0,8,8);
		// Turn off accessory face overlay - causes white faces, and very few skins seem to have them anyway
		//blitImage(headContext, skinImage, 40,8,8,8, 0,0,8,8);
		completed(headCanvas);
	};
	skinImage.onerror = function() {
		if (skinImage.src == '//www.minecraft.net/img/char.png') {
			failed();
		} else {
			skinImage.src = '//www.minecraft.net/img/char.png';
		}
	};
	skinImage.src = '//s3.amazonaws.com/MinecraftSkins/' + player + '.png';
}

function resizeImage(img,size) {
	var canvas = document.createElement('canvas');
	canvas.width = size;
	canvas.height = size;
	var ctx = canvas.getContext('2d');
	blitImage(ctx, img, 0,0,img.width,img.height, 0,0,size,size);
	return canvas;
}

var playerHeads = {};

function getMinecraftHead(player,size,completed) {
	var head = playerHeads[player];
	// Synchronous
	if (!completed) {
		return (!head || head.working) ? null : head;
	}

	// Asynchronous
	if (!head) {
		playerHeads[player] = { working: true, hooks: [{f:completed,s:size}] };
		//console.log('Creating head for ',player,'...');
		createMinecraftHead(player, function(head) {
			//console.log('Created head for ',player,': ', head);
			hooks = playerHeads[player].hooks;
			playerHeads[player] = head;
			var i;
			for(i=0;i<hooks.length;i++) {
				hooks[i].f(resizeImage(head,hooks[i].s));
			}
		}, function() {

		});
	} else if (head.working) {
		//console.log('Other process working on head of ',player,', will add myself to hooks...');
		head.hooks[head.hooks.length] = {f:completed,s:size};
	} else {
		completed(resizeImage(head,size));
	}
}

function getMinecraftTime(servertime) {
	servertime = parseInt(servertime);
	var day = servertime >= 0 && servertime < 13700;
	return {
		servertime: servertime,
		days: parseInt((servertime+8000) / 24000),

		// Assuming it is day at 8:00
		hours: (parseInt(servertime / 1000)+8) % 24,
		minutes: parseInt(((servertime / 1000) % 1) * 60),
		seconds: parseInt(((((servertime / 1000) % 1) * 60) % 1) * 60),

		day: day,
		night: !day
	};
}
<|endoftext|>


<commit_before>/*global webpackIsomorphicTools*/
import path from "path";
import { createElement } from "react";
import { renderToString, renderToStaticMarkup } from "react-dom/server";

import {
  runBeforeRoutes,
  prepareRoutesWithTransitionHooks,
  ROUTE_NAME_404_NOT_FOUND
} from "gluestick-shared";

import { match, RouterContext } from "react-router";
import errorHandler from "./errorHandler";
import Body from "./Body";
import getHead from "./getHead";
import getRenderRequirementsFromEntrypoints from "./getRenderRequirementsFromEntrypoints";

// E-mail support
import Oy from "oy-vey";
const HTML5 = "<!DOCTYPE html>";

import { getLogger } from "./logger";
const logger = getLogger();
import showHelpText, { MISSING_404_TEXT } from "./helpText";

process.on("unhandledRejection", (reason) => {
  const message = reason.message || reason.statusText || reason;
  logger.error(reason, "Unhandled promise rejection:", message);
});

module.exports = async function (req, res) {
  try {

    // Forward all request headers from the browser into http requests made by node
    const config = require(path.join(process.cwd(), "src", "config", "application")).default;
    const Entry = require(path.join(process.cwd(), "src/config/.entry")).default;
    const { Index, store, getRoutes, fileName } = getRenderRequirementsFromEntrypoints(req, res, config);

    const routes = prepareRoutesWithTransitionHooks(getRoutes(store));

    match({routes: routes, location: req.path}, async (error, redirectLocation, renderProps) => {
      try {
        if (error) {
          errorHandler(req, res, error);
        }
        else if (redirectLocation) {
          res.redirect(302, redirectLocation.pathname + redirectLocation.search);
        }
        else if (renderProps) {

          // If we have a matching route, set up a routing context so
          // that we render the proper page. On the client side, you
          // embed the router itself, on the server you embed a routing
          // context.
          // [https://github.com/reactjs/react-router/blob/master/docs/guides/ServerRendering.md]
          await runBeforeRoutes(store, renderProps || {}, {isServer: true, request: req});

          const routerContext = createElement(RouterContext, renderProps);

          // grab the main component which is capable of loading routes
          // and hot loading them if in development mode
          const radiumConfig = { userAgent: req.headers["user-agent"] };

          const main = createElement(Entry, {store, routerContext, config, radiumConfig, getRoutes});

          // gather attributes that were included on the route in order to
          // determine whether to render as an e-mail or not
          const routeAttrs = getEmailAttributes(renderProps.routes);
          const isEmail = routeAttrs.email;
          const reactRenderFunc = isEmail ? renderToStaticMarkup : renderToString;

          // grab the react generated body stuff. This includes the
          // script tag that hooks up the client side react code.
          const currentState = store.getState();
          const body = createElement(Body, {html: reactRenderFunc(main), entryPoint: fileName, config: config, initialState: currentState, isEmail: isEmail});
          const head = isEmail ? null : getHead(config, fileName, webpackIsomorphicTools.assets()); // eslint-disable-line webpackIsomorphicTools

          // Grab the html from the project which is stored in the root
          // folder named Index.js. Pass the body and the head to that
          // component. `head` includes stuff that we want the server to
          // always add inside the <head> tag.
          //
          // Bundle it all up into a string, add the doctype and deliver
          const rootElement = createElement(Index, {body: body, head: head});

          // Set status code
          if (renderProps.routes[renderProps.routes.length - 1].name === ROUTE_NAME_404_NOT_FOUND) {
            res.status(404);
          }
          else {
            // Use the error's status code that was set on GlueStick's internal
            // state object if one exists
            const errorStatus = getErrorStatusCode(currentState);
            if (errorStatus !== null) {
              res.status(errorStatus);
            }
            else {
              res.status(200);
            }
          }

          if (isEmail) {
            const generateCustomTemplate = ({bodyContent}) => { return `${bodyContent}`; };
            res.send(routeAttrs.docType + "\n" + Oy.renderTemplate(rootElement, {}, generateCustomTemplate));
          }
          else {
            res.send(routeAttrs.docType + "\n" + reactRenderFunc(rootElement));
          }
        }
        else {
          // This is only hit if there is no 404 handler in the react routes. A
          // not found handler is included by default in new projects.
          showHelpText(MISSING_404_TEXT);
          res.status(404).send("Not Found");
        }
      }
      catch (error) {
        // Render any error that was set on GlueStick's internal state object if one exists
        const errorStatus = getErrorStatusCode(store.getState());
        if (errorStatus !== null) {
          res.status(errorStatus).send("An error occurred.");
        }
        else {
          errorHandler(req, res, error);
        }
      }
    });
  }
  catch (error) {
    errorHandler(req, res, error);
  }
};

function getEmailAttributes (routes) {
  const lastRoute = routes[routes.length - 1];
  const email = lastRoute.email || false;
  const docType = lastRoute.docType || HTML5;
  return { email, docType };
}

function getErrorStatusCode (state) {
  if (state._gluestick.hasOwnProperty("statusCode")) {
    return state._gluestick.error;
  }
  return null;
}

<commit_msg>Error is no longer set on the state<commit_after>/*global webpackIsomorphicTools*/
import path from "path";
import { createElement } from "react";
import { renderToString, renderToStaticMarkup } from "react-dom/server";

import {
  runBeforeRoutes,
  prepareRoutesWithTransitionHooks,
  ROUTE_NAME_404_NOT_FOUND
} from "gluestick-shared";

import { match, RouterContext } from "react-router";
import errorHandler from "./errorHandler";
import Body from "./Body";
import getHead from "./getHead";
import getRenderRequirementsFromEntrypoints from "./getRenderRequirementsFromEntrypoints";

// E-mail support
import Oy from "oy-vey";
const HTML5 = "<!DOCTYPE html>";

import { getLogger } from "./logger";
const logger = getLogger();
import showHelpText, { MISSING_404_TEXT } from "./helpText";

process.on("unhandledRejection", (reason) => {
  const message = reason.message || reason.statusText || reason;
  logger.error(reason, "Unhandled promise rejection:", message);
});

module.exports = async function (req, res) {
  try {

    // Forward all request headers from the browser into http requests made by node
    const config = require(path.join(process.cwd(), "src", "config", "application")).default;
    const Entry = require(path.join(process.cwd(), "src/config/.entry")).default;
    const { Index, store, getRoutes, fileName } = getRenderRequirementsFromEntrypoints(req, res, config);

    const routes = prepareRoutesWithTransitionHooks(getRoutes(store));

    match({routes: routes, location: req.path}, async (error, redirectLocation, renderProps) => {
      try {
        if (error) {
          errorHandler(req, res, error);
        }
        else if (redirectLocation) {
          res.redirect(302, redirectLocation.pathname + redirectLocation.search);
        }
        else if (renderProps) {

          // If we have a matching route, set up a routing context so
          // that we render the proper page. On the client side, you
          // embed the router itself, on the server you embed a routing
          // context.
          // [https://github.com/reactjs/react-router/blob/master/docs/guides/ServerRendering.md]
          await runBeforeRoutes(store, renderProps || {}, {isServer: true, request: req});

          const routerContext = createElement(RouterContext, renderProps);

          // grab the main component which is capable of loading routes
          // and hot loading them if in development mode
          const radiumConfig = { userAgent: req.headers["user-agent"] };

          const main = createElement(Entry, {store, routerContext, config, radiumConfig, getRoutes});

          // gather attributes that were included on the route in order to
          // determine whether to render as an e-mail or not
          const routeAttrs = getEmailAttributes(renderProps.routes);
          const isEmail = routeAttrs.email;
          const reactRenderFunc = isEmail ? renderToStaticMarkup : renderToString;

          // grab the react generated body stuff. This includes the
          // script tag that hooks up the client side react code.
          const currentState = store.getState();
          const body = createElement(Body, {html: reactRenderFunc(main), entryPoint: fileName, config: config, initialState: currentState, isEmail: isEmail});
          const head = isEmail ? null : getHead(config, fileName, webpackIsomorphicTools.assets()); // eslint-disable-line webpackIsomorphicTools

          // Grab the html from the project which is stored in the root
          // folder named Index.js. Pass the body and the head to that
          // component. `head` includes stuff that we want the server to
          // always add inside the <head> tag.
          //
          // Bundle it all up into a string, add the doctype and deliver
          const rootElement = createElement(Index, {body: body, head: head});

          // Set status code
          if (renderProps.routes[renderProps.routes.length - 1].name === ROUTE_NAME_404_NOT_FOUND) {
            res.status(404);
          }
          else {
            // Use the error's status code that was set on GlueStick's internal
            // state object if one exists
            const errorStatus = getErrorStatusCode(currentState);
            if (errorStatus !== null) {
              res.status(errorStatus);
            }
            else {
              res.status(200);
            }
          }

          if (isEmail) {
            const generateCustomTemplate = ({bodyContent}) => { return `${bodyContent}`; };
            res.send(routeAttrs.docType + "\n" + Oy.renderTemplate(rootElement, {}, generateCustomTemplate));
          }
          else {
            res.send(routeAttrs.docType + "\n" + reactRenderFunc(rootElement));
          }
        }
        else {
          // This is only hit if there is no 404 handler in the react routes. A
          // not found handler is included by default in new projects.
          showHelpText(MISSING_404_TEXT);
          res.status(404).send("Not Found");
        }
      }
      catch (error) {
        // Render any error that was set on GlueStick's internal state object if one exists
        const errorStatus = getErrorStatusCode(store.getState());
        if (errorStatus !== null) {
          res.status(errorStatus).send("An error occurred.");
        }
        else {
          errorHandler(req, res, error);
        }
      }
    });
  }
  catch (error) {
    errorHandler(req, res, error);
  }
};

function getEmailAttributes (routes) {
  const lastRoute = routes[routes.length - 1];
  const email = lastRoute.email || false;
  const docType = lastRoute.docType || HTML5;
  return { email, docType };
}

function getErrorStatusCode (state) {
  if (state._gluestick.hasOwnProperty("statusCode")) {
    return state._gluestick.statusCode;
  }
  return null;
}

<|endoftext|>


<commit_before>var Doc;
if (typeof require !== 'undefined') {
  Doc = require('./doc').Doc;
}

// Queries are live requests to the database for particular sets of fields.
//
// The server actively tells the client when there's new data that matches
// a set of conditions.
var Query = exports.Query = function(type, connection, id, collection, query, options, callback) {
  // 'fetch' or 'sub'
  this.type = type;

  this.connection = connection;
  this.id = id;
  this.collection = collection;

  // The query itself. For mongo, this should look something like {"data.x":5}
  this.query = query;

  // has tis query been executed already?
  this.executed = false;

  // Resultant document action for the server. Fetch mode will automatically
  // fetch all results. Subscribe mode will automatically subscribe all
  // results. Results are never unsubscribed.
  this.docMode = options.docMode; // undefined, 'fetch' or 'sub'.

  // Do we repoll the entire query whenever anything changes? (As opposed to
  // just polling the changed item). This needs to be enabled to be able to use
  // ordered queries (sortby:) and paginated queries. Set to undefined, it will
  // be enabled / disabled automatically based on the query's properties.
  this.poll = options.poll;

  // The backend we actually hit. If this isn't defined, it hits the snapshot
  // database. Otherwise this can be used to hit another configured query
  // index.
  this.backend = options.backend || options.source;

  // A list of resulting documents. These are actual documents, complete with
  // data and all the rest. If fetch is false, these documents will not
  // have any data. You should manually call fetch() or subscribe() on them.
  //
  // Calling subscribe() might be a good idea anyway, as you won't be
  // subscribed to the documents by default.
  this.results = [];

  // Do we have some initial data?
  this.ready = false;

  this.callback = callback;
};
Query.prototype.action = 'qsub';

// Helper for subscribe & fetch, since they share the same message format.
//
// This function actually issues the query.
Query.prototype._execute = function() {
  if (!this.connection.canSend || this.executed) return;

  if (this.connection.isConflictingAction(this.collection, this.type)) {
    return;
  }

  if (this.docMode) {
    var collectionVersions = {};
    // Collect the version of all the documents in the current result set so we
    // don't need to be sent their snapshots again.
    var existing = this.connection.getExisting(this.collection);
    if (existing)
      for (var i = 0; i < existing.length; i++) {
        var doc = existing[i];
        // If we're subscribed, the server already knows which version of the doc
        // we have.
        if (!doc.subscribed && doc.action !== 'subscribe') {
          var c = collectionVersions[doc.collection] = collectionVersions[doc.collection] || {};
          c[doc.name] = doc.version;
        }
      }
  }

  var msg = {
    a: 'q' + this.type,
    id: this.id,
    c: this.collection,
    o: {},
    q: this.query,
  };

  if (this.docMode) {
    msg.o.m = this.docMode;
    // This should be omitted if empty, but whatever.
    msg.o.vs = collectionVersions;
  }

  if (this.backend != null) msg.o.b = this.backend;
  if (this.poll !== undefined) msg.o.p = this.poll;

  this.executed = true;
  this.connection.send(msg);
};

// Make a list of documents from the list of server-returned data objects
Query.prototype._dataToDocs = function(data) {
  var results = [];
  var lastType;
  this.connection.bsStart();
  for (var i = 0; i < data.length; i++) {
    var docData = data[i];

    // Types are only put in for the first result in the set and every time the type changes in the list.
    if (docData.type) {
      lastType = docData.type;
    } else {
      docData.type = lastType;
    }

    var doc = this.connection.get(docData.c || this.collection, docData.d, docData);

    // Force the document to know its subscribed if we're in docmode:subscribe.
    if (this.docMode === 'sub') {
      doc.subscribed = true; // Set before setWantSubscribe() so flush doesn't send a subscribe request.
      doc._setWantSubscribe(true); // this will call any subscribe callbacks or whatever.
      doc.emit('subscribe');
      doc._finishSub(true); // this doesn't actually do anything here, but its more correct to have it.
    }

    results.push(doc);
  }
  this.connection.bsEnd();
  return results;
};

// Destroy the query object. Any subsequent messages for the query will be
// ignored by the connection. You should unsubscribe from the query before
// destroying it.
Query.prototype.destroy = function() {
  if (this.connection.canSend && this.type === 'sub') {
    this.connection.send({a:'qunsub', id:this.id});
  }

  this.connection._destroyQuery(this);
};

Query.prototype._onConnectionStateChanged = function(state, reason) {
  if (this.connection.state === 'connecting' || this.connection.state === 'connected') {
    this._execute();
  }
};

// Internal method called from connection to pass server messages to the query.
Query.prototype._onMessage = function(msg) {
  if ((msg.a === 'qfetch') !== (this.type === 'fetch')) {
    if (console) console.warn('Invalid message sent to query', msg, this);
    return;
  }

  if (msg.error) this.emit('error', msg.error);

  switch (msg.a) {
    case 'qfetch':
      var results = msg.data ? this._dataToDocs(msg.data) : undefined;
      if (this.callback) this.callback(msg.error, results, msg.extra);
      // Once a fetch query gets its data, it is destroyed.
      this.connection._destroyQuery(this);
      break;

    case 'q':
      // Query diff data (inserts and removes)
      if (msg.diff) {
        // We need to go through the list twice. First, we'll ingest all the
        // new documents and set them as subscribed.  After that we'll emit
        // events and actually update our list. This avoids race conditions
        // around setting documents to be subscribed & unsubscribing documents
        // in event callbacks.
        for (var i = 0; i < msg.diff.length; i++) {
          var d = msg.diff[i];
          if (d.type === 'insert') d.values = this._dataToDocs(d.values);
        }

        for (var i = 0; i < msg.diff.length; i++) {
          var d = msg.diff[i];
          switch (d.type) {
            case 'insert':
              var newDocs = d.values;
              Array.prototype.splice.apply(this.results, [d.index, 0].concat(newDocs));
              this.emit('insert', newDocs, d.index);
              break;
            case 'remove':
              var howMany = d.howMany || 1;
              var removed = this.results.splice(d.index, howMany);
              this.emit('remove', removed, d.index);
              break;
            case 'move':
              var howMany = d.howMany || 1;
              var docs = this.results.splice(d.from, howMany);
              Array.prototype.splice.apply(this.results, [d.to, 0].concat(docs));
              this.emit('move', docs, d.from, d.to);
              break;
          }
        }
      }

      if (msg.extra !== void 0) {
        this.emit('extra', msg.extra);
      }
      break;
    case 'qsub':
      // This message replaces the entire result set with the set passed.
      if (!msg.error) {
        var previous = this.results;

        // Then add everything in the new result set.
        this.results = this._dataToDocs(msg.data);
        this.extra = msg.extra;

        this.ready = true;
        this.emit('change', this.results, previous);
      }
      if (this.callback) {
        this.callback(msg.error, this.results, this.extra);
        delete this.callback;
      }
      break;
  }
};

// Change the thing we're searching for. This isn't fully supported on the
// backend (it destroys the old query and makes a new one) - but its
// programatically useful and I might add backend support at some point.
Query.prototype.setQuery = function(q) {
  if (this.type !== 'sub') throw new Error('cannot change a fetch query');

  this.query = q;
  if (this.connection.canSend) {
    // There's no 'change' message to send to the server. Just resubscribe.
    this.connection.send({a:'qunsub', id:this.id});
    this._execute();
  }
};

var MicroEvent;
if (typeof require !== 'undefined') {
  MicroEvent = require('./microevent');
}

MicroEvent.mixin(Query);

<commit_msg>rewriting query logic<commit_after>var Doc;
if (typeof require !== 'undefined') {
  Doc = require('./doc').Doc;
}

// Queries are live requests to the database for particular sets of fields.
//
// The server actively tells the client when there's new data that matches
// a set of conditions.
var Query = exports.Query = function(type, connection, id, collection, query, options, callback) {
  // 'fetch' or 'sub'
  this.type = type;

  this.connection = connection;
  this.id = id;
  this.collection = collection;

  // The query itself. For mongo, this should look something like {"data.x":5}
  this.query = query;

  // has tis query been executed already?
  this.executed = false;

  // Resultant document action for the server. Fetch mode will automatically
  // fetch all results. Subscribe mode will automatically subscribe all
  // results. Results are never unsubscribed.
  this.docMode = options.docMode; // undefined, 'fetch' or 'sub'.

  // Do we repoll the entire query whenever anything changes? (As opposed to
  // just polling the changed item). This needs to be enabled to be able to use
  // ordered queries (sortby:) and paginated queries. Set to undefined, it will
  // be enabled / disabled automatically based on the query's properties.
  this.poll = options.poll;

  // The backend we actually hit. If this isn't defined, it hits the snapshot
  // database. Otherwise this can be used to hit another configured query
  // index.
  this.backend = options.backend || options.source;

  // A list of resulting documents. These are actual documents, complete with
  // data and all the rest. If fetch is false, these documents will not
  // have any data. You should manually call fetch() or subscribe() on them.
  //
  // Calling subscribe() might be a good idea anyway, as you won't be
  // subscribed to the documents by default.
  this.results = [];

  // Do we have some initial data?
  this.ready = false;

  this.callback = callback;
};
Query.prototype.action = 'qsub';

// Helper for subscribe & fetch, since they share the same message format.
//
// This function actually issues the query.
Query.prototype._execute = function() {
  if (!this.connection.canSend || this.executed) return;

  if (this.connection.isConflictingAction(this.collection, this.type)) {
    return;
  }

  if (this.docMode) {
    var collectionVersions = {};
    // Collect the version of all the documents in the current result set so we
    // don't need to be sent their snapshots again.
    var existing = this.connection.getExisting(this.collection);
    if (existing)
      for (var i = 0; i < existing.length; i++) {
        var doc = existing[i];
        // If we're subscribed, the server already knows which version of the doc
        // we have.
        if (!doc.subscribed && doc.action !== 'subscribe') {
          var c = collectionVersions[doc.collection] = collectionVersions[doc.collection] || {};
          c[doc.name] = doc.version;
        }
      }
  }

  var msg = {
    a: 'q' + this.type,
    id: this.id,
    c: this.collection,
    o: {},
    q: this.query,
  };

  if (this.docMode) {
    msg.o.m = this.docMode;
    // This should be omitted if empty, but whatever.
    msg.o.vs = collectionVersions;
  }

  if (this.backend != null) msg.o.b = this.backend;
  if (this.poll !== undefined) msg.o.p = this.poll;

  this.executed = true;
  this.connection.send(msg);
};

// Make a list of documents from the list of server-returned data objects
Query.prototype._dataToDocs = function(data) {
  var results = [];
  var lastType;
  this.connection.bsStart();
  for (var i = 0; i < data.length; i++) {
    var docData = data[i];

    // Types are only put in for the first result in the set and every time the type changes in the list.
    if (docData.type) {
      lastType = docData.type;
    } else {
      docData.type = lastType;
    }

    var doc = this.connection.get(docData.c || this.collection, docData.d, docData);

    // Force the document to know its subscribed if we're in docmode:subscribe.
    if (this.docMode === 'sub') {
      doc.subscribed = true; // Set before setWantSubscribe() so flush doesn't send a subscribe request.
      doc.emit('subscribe');
      doc._finishSub(true); // this doesn't actually do anything here, but its more correct to have it.
    }

    results.push(doc);
  }
  this.connection.bsEnd();
  return results;
};

// Destroy the query object. Any subsequent messages for the query will be
// ignored by the connection. You should unsubscribe from the query before
// destroying it.
Query.prototype.destroy = function() {
  if (this.connection.canSend && this.type === 'sub') {
    this.connection.send({a:'qunsub', id:this.id});
  }

  this.connection._destroyQuery(this);
};

Query.prototype._onConnectionStateChanged = function(state, reason) {
  if (this.connection.state === 'connecting' || this.connection.state === 'connected') {
    this._execute();
  }
};

// Internal method called from connection to pass server messages to the query.
Query.prototype._onMessage = function(msg) {
  if ((msg.a === 'qfetch') !== (this.type === 'fetch')) {
    if (console) console.warn('Invalid message sent to query', msg, this);
    return;
  }

  if (msg.error) this.emit('error', msg.error);

  switch (msg.a) {
    case 'qfetch':
      var results = msg.data ? this._dataToDocs(msg.data) : undefined;
      if (this.callback) this.callback(msg.error, results, msg.extra);
      // Once a fetch query gets its data, it is destroyed.
      this.connection._destroyQuery(this);
      break;

    case 'q':
      // Query diff data (inserts and removes)
      if (msg.diff) {
        // We need to go through the list twice. First, we'll ingest all the
        // new documents and set them as subscribed.  After that we'll emit
        // events and actually update our list. This avoids race conditions
        // around setting documents to be subscribed & unsubscribing documents
        // in event callbacks.
        for (var i = 0; i < msg.diff.length; i++) {
          var d = msg.diff[i];
          if (d.type === 'insert') d.values = this._dataToDocs(d.values);
        }

        for (var i = 0; i < msg.diff.length; i++) {
          var d = msg.diff[i];
          switch (d.type) {
            case 'insert':
              var newDocs = d.values;
              Array.prototype.splice.apply(this.results, [d.index, 0].concat(newDocs));
              this.emit('insert', newDocs, d.index);
              break;
            case 'remove':
              var howMany = d.howMany || 1;
              var removed = this.results.splice(d.index, howMany);
              this.emit('remove', removed, d.index);
              break;
            case 'move':
              var howMany = d.howMany || 1;
              var docs = this.results.splice(d.from, howMany);
              Array.prototype.splice.apply(this.results, [d.to, 0].concat(docs));
              this.emit('move', docs, d.from, d.to);
              break;
          }
        }
      }

      if (msg.extra !== void 0) {
        this.emit('extra', msg.extra);
      }
      break;
    case 'qsub':
      // This message replaces the entire result set with the set passed.
      if (!msg.error) {
        var previous = this.results;

        // Then add everything in the new result set.
        this.results = this._dataToDocs(msg.data);
        this.extra = msg.extra;

        this.ready = true;
        this.emit('change', this.results, previous);
      }
      if (this.callback) {
        this.callback(msg.error, this.results, this.extra);
        delete this.callback;
      }
      break;
  }
};

// Change the thing we're searching for. This isn't fully supported on the
// backend (it destroys the old query and makes a new one) - but its
// programatically useful and I might add backend support at some point.
Query.prototype.setQuery = function(q) {
  if (this.type !== 'sub') throw new Error('cannot change a fetch query');

  this.query = q;
  if (this.connection.canSend) {
    // There's no 'change' message to send to the server. Just resubscribe.
    this.connection.send({a:'qunsub', id:this.id});
    this._execute();
  }
};

var MicroEvent;
if (typeof require !== 'undefined') {
  MicroEvent = require('./microevent');
}

MicroEvent.mixin(Query);

<|endoftext|>


<commit_before>/**
 * @file xsdwebform.parser.log.js
 * XSD Schema to HTML5 Web Form
 * @author George Bouris <gb@eworx.gr>
 * @copyright Copyright (C) 2017 EEA, Eworx, George Bouris. All rights reserved.
 */

'use strict';

/**
 * Class XSDWebFormParserLog
 * Parser for XSD Schema Tags
 * Static
 */
class XSDWebFormParserLog {
	/**
	 * Class constructor
	 */
	constructor() {
		this.htmlOutput = `<!DOCTYPE html>

`;
	}
	/**
	 * showLog
	 */
	showLogs(sender) {
		if (!sender.verbose)
			console.log("");

		// process.stdout.write(sender.htmlOutput.HTMLObjects[0]);
		if (sender.verbose) {
			console.log("\n\n\x1b[0m\x1b[32mHTML OBJECTS: \x1b[0m\x1b[36m");
			this.htmlOutput  += `<h2>HTML OBJECTS: </h2>\n`;

			console.log("\x1b[0m\x1b[2m");
			this.htmlOutput  += `<div style="padding: 8px;font-size:13px;color: #fff;">\n<ul>\n`;
			sender.htmlOutput.HTMLObjects.forEach( (item) => {
				item.itemObject.groups.forEach( (gitem) => {
					gitem.itemObject.items.forEach( (eitem) => {
						console.log(eitem.toString().substring(0, 40) + "...");
						this.htmlOutput  += `<li style="padding: 8px;">${eitem.toString().substring(0, 80) .replace(/</g, '<').replace(/>/g, '>')}..</li>\n`;
					});
				});
			});
			this.htmlOutput  += `</ul>\n</div>\n`;
		} else {
			console.log("");
		}
		console.log("\x1b[0m");
		console.log(new Date());

		this.htmlOutput  += `\n<BR><BR><div style="font-size:14px;color:#777">${new Date()}</div>\n`;

		console.log("\n\x1b[2m\x1b[33m==================================================================================================================================================\n\x1b[0m");
	}

	/**
	 * logXSD
	 * @param xObject
	 */
	logXSD(xObject) {
		console.log("\n\n\x1b[2m\x1b[36m__________________________________________________________________________________________________________________________________________________\n\x1b[0m");
		console.log(`                                                             \x1b[1m\x1b[36mFILE : ${xObject.xfile} \x1b[0m\n`);
		console.log("\x1b[2m\x1b[36m__________________________________________________________________________________________________________________________________________________\n\x1b[0m\n\n");

		this.htmlOutput  += `<h2><span style="color:#777">XSD File:</span> ${xObject.xfile}</h2>\n`;
	}

	/**
	 * logHTML
	 * @param xObject
	 */
	logHTML(xObject) {
		console.log("\n\n\x1b[2m\x1b[33m__________________________________________________________________________________________________________________________________________________\n\x1b[0m");
		console.log(`                                                             \x1b[1m\x1b[33mFILE : ${xObject.hfile} \x1b[0m\n`);
		console.log("\x1b[2m\x1b[33m__________________________________________________________________________________________________________________________________________________\n\x1b[0m\n\n");

		this.htmlOutput  += `<h2><span style="color:#777">XML File:</span> ${xObject.hfile}</h2>\n`;
	}

	/**
	 * showItemLog - ShowLog
	 * @param xsdItem
	 */
	showItemLog(xsdItem, verbose) {

		let xspace = "  ";
		for (let i = 0; i < xsdItem.level; i++) {
			xspace += "\t";
		}

		console.log(`${xspace}\x1b[0m\x1b[31m▓▓▓▓▓▓▓▓▓▓▓▓▓\x1b[0m`);
		process.stdout.write(`${xspace}\x1b[2m▓▓▓▓ \x1b[0m\x1b[2mL:${xsdItem.level} \x1b[2m▓▓▓▓\x1b[0m\x1b[31m⇢\x1b[0m `);
		this.htmlOutput  += `

Level ${xsdItem.level}
`;

		if (xsdItem.children) {
			process.stdout.write(`\x1b[1m${xsdItem.name}`);
			this.htmlOutput  += `<li class="xsdc" style="width:200px;color:rgb(0, 51, 153);background-color:#fff;">${xsdItem.name}\t<span>line ${xsdItem.line}</span></li>\n`;

			if (xsdItem.attr.name) {
				process.stdout.write(` - ${xsdItem.attr.name}`);
				this.htmlOutput  += `<li class="xsdc" style="width:300px;font-size:14px;color:rgb(204, 0, 0);background-color:#fafafa;"><b>${xsdItem.attr.name}</b></li>\n`;

				if (verbose) {
					if (xsdItem.name === "xs:element") {
						let txmlItem = xsdItem.toString();
						txmlItem = txmlItem.split("\n").join("");
						txmlItem = txmlItem.split("<").join(xspace + `\n${xspace}\x1b[2m▓▓▓▓▓▓▓▓▓▓▓▓▓  \x1b[2m<`);

						let pos1 = txmlItem.indexOf("<xs:documentation>");
						if (pos1 > 0) {
							let pos2 = txmlItem.indexOf("</xs:documentation>");
							txmlItem = txmlItem.substring(0, pos1) + "<xs:documentation> ..." + txmlItem.substring(pos2);
						}
						process.stdout.write(`\x1b[2m${txmlItem}`);
					}
				}
			} else if (xsdItem.attr.value) {
				process.stdout.write(`\n${xspace}\x1b[2m▓▓▓▓▓▓▓▓▓▓▓▓▓  \x1b[2m${xsdItem.attr.value}\x1b[0m`);
				this.htmlOutput  += `<li class="xsdc"style="width:300px;font-size:12px;color:#333;background-color:#eee;"><b>${xsdItem.attr.value}</b></li>\n`;
			} else if (xsdItem.attr.ref) {
				process.stdout.write(`\n${xspace}\x1b[2m▓▓▓▓▓▓▓▓▓▓▓▓▓  \x1b[2m\x1b[36mRef: \x1b[1m\x1b[36m${xsdItem.attr.ref}\x1b[0m`);
				this.htmlOutput  += `<li class="xsdc"style="width:300px;font-size:12px;color:#333;background-color:#eee;">Ref: ${xsdItem.attr.ref}</li>\n`;
			}

			process.stdout.write(`\n\x1b[2m${xspace}▓▓▓▓▓▓▓▓▓▓▓▓▓`);

			if (xsdItem.name === "xs:documentation" && xsdItem.xparent.name === "xs:annotation") {
				let txmlItem = xsdItem.val.toString().trim();
				if (txmlItem.length > 60)
					txmlItem = txmlItem.substring(0, 60) + "...";
				process.stdout.write(` \x1b[2m\x1b[37m ${txmlItem}\x1b[0m\n${xspace}\x1b[2m▓▓▓▓▓▓▓▓▓▓▓▓▓`);
			}

			if (xsdItem.xparent) {
				console.log(`\x1b[2m\x1b[32m  parent ::\x1b[1m ${xsdItem.xparent.name}\x1b[0m`);
				if (xsdItem.xparent.attr.name) {
					console.log(`${xspace}\x1b[2m▓▓▓▓▓▓▓▓▓▓▓▓▓ \x1b[2m\x1b[32m par.name ::\x1b[1m ${xsdItem.xparent.attr.name}\x1b[0m`);
				}
			}
		}

		if (xsdItem.level === 0)
			console.log(" ");

		this.htmlOutput  += `</ul>\n`;

		process.stdout.write(`\x1b[2m${xspace}         ▒▒`);
	}

	/**
	 * logXsdTag - Log XSD Element Tag
	 * @param item
	 */
	logXsdTag(item) {
		console.log(`\x1b[0m\x1b[31m⇣\x1b[2m Found Tag \x1b[33m${item}\x1b[0m`);
		this.htmlOutput  += `<div style="width:98%;z-index:-1;padding:4px 8px;font-size:12px;position:absolute;color:#eee;background-color:#242424;">Found Tag >> ${item}</div>\n`;
	}

	/**
	 * logTODO - Log XSD Element Tag
	 * @param msg
	 */
	logTODO(msg) {
		console.log(`\x1b[1m\x1b[31mTODO: \x1b[0m${msg}\x1b[0m`);
	}

	/**
	 * logHtmlTag - Log HTML Element Tag
	 * @param item
	 */
	logHtmlTag(item, sender) {
		if (sender.verbose) {
			console.log(`\x1b[0m\x1b[31m⇣\n\x1b[2mParsing HTML Tag ⇢ \x1b[33m${item.name}\x1b[0m\n`);
			this.htmlOutput  += `
Parsing HTML Tag >> ${item.name} :: ${item.attr.element  || item.attr.name || ' '}
\n`;
		}
	}

	/**
	 * getHtmlLog
	 */
	getHtmlLog() {
		return this.htmlOutput  + `

		 `;
	}

}

module.exports = XSDWebFormParserLog;<commit_msg>Updated LOG files<commit_after>/**
 * @file xsdwebform.parser.log.js
 * XSD Schema to HTML5 Web Form
 * @author George Bouris <gb@eworx.gr>
 * @copyright Copyright (C) 2017 EEA, Eworx, George Bouris. All rights reserved.
 */

'use strict';

/**
 * Class XSDWebFormParserLog
 * Parser for XSD Schema Tags
 * Static
 */
class XSDWebFormParserLog {
	/**
	 * Class constructor
	 */
	constructor() {
		this.htmlOutput = `<!DOCTYPE html>

`;
	}
	/**
	 * showLog
	 */
	showLogs(sender) {
		if (!sender.verbose)
			console.log("");

		// process.stdout.write(sender.htmlOutput.HTMLObjects[0]);
		if (sender.verbose) {
			console.log("\n\n\x1b[0m\x1b[32mHTML OBJECTS: \x1b[0m\x1b[36m");
			this.htmlOutput  += `<h2>HTML OBJECTS: </h2>\n`;

			console.log("\x1b[0m\x1b[2m");
			this.htmlOutput  += `<div style="padding: 8px;font-size:13px;color: #fff;">\n<ul>\n`;
			sender.htmlOutput.HTMLObjects.forEach( (item) => {
				item.itemObject.groups.forEach( (gitem) => {
					gitem.itemObject.items.forEach( (eitem) => {
						console.log(eitem.toString().substring(0, 40) + "...");
						this.htmlOutput  += `<li style="padding: 8px;">${eitem.toString().substring(0, 80) .replace(/</g, '<').replace(/>/g, '>')}..</li>\n`;
					});
				});
			});
			this.htmlOutput  += `</ul>\n</div>\n`;
		} else {
			console.log("");
		}
		console.log("\x1b[0m");
		console.log(new Date());

		this.htmlOutput  += `\n<BR><BR><div style="font-size:14px;color:#777">${new Date()}</div>\n`;

		console.log("\n\x1b[2m\x1b[33m==================================================================================================================================================\n\x1b[0m");
	}

	/**
	 * logXSD
	 * @param xObject
	 */
	logXSD(xObject) {
		console.log("\n\n\x1b[2m\x1b[36m__________________________________________________________________________________________________________________________________________________\n\x1b[0m");
		console.log(`                                                             \x1b[1m\x1b[36mFILE : ${xObject.xfile} \x1b[0m\n`);
		console.log("\x1b[2m\x1b[36m__________________________________________________________________________________________________________________________________________________\n\x1b[0m\n\n");

		this.htmlOutput  += `<h2><span style="color:#777">XSD File:</span> ${xObject.xfile}</h2>\n`;
	}

	/**
	 * logHTML
	 * @param xObject
	 */
	logHTML(xObject) {
		console.log("\n\n\x1b[2m\x1b[33m__________________________________________________________________________________________________________________________________________________\n\x1b[0m");
		console.log(`                                                             \x1b[1m\x1b[33mFILE : ${xObject.hfile} \x1b[0m\n`);
		console.log("\x1b[2m\x1b[33m__________________________________________________________________________________________________________________________________________________\n\x1b[0m\n\n");

		this.htmlOutput  += `<h2><span style="color:#777">XML File:</span> ${xObject.hfile}</h2>\n`;
	}

	/**
	 * showItemLog - ShowLog
	 * @param xsdItem
	 */
	showItemLog(xsdItem, verbose) {

		let xspace = "  ";
		for (let i = 0; i < xsdItem.level; i++) {
			xspace += "\t";
		}

		console.log(`${xspace}\x1b[0m\x1b[31m▓▓▓▓▓▓▓▓▓▓▓▓▓\x1b[0m`);
		process.stdout.write(`${xspace}\x1b[2m▓▓▓▓ \x1b[0m\x1b[2mL:${xsdItem.level} \x1b[2m▓▓▓▓\x1b[0m\x1b[31m⇢\x1b[0m `);
		this.htmlOutput  += `

Level ${xsdItem.level}
`;

		if (xsdItem.children) {
			process.stdout.write(`\x1b[1m${xsdItem.name}`);
			this.htmlOutput  += `<li class="xsdc" style="width:200px;color:rgb(0, 51, 153);background-color:#fff;">${xsdItem.name}\t<span>line ${xsdItem.line}</span></li>\n`;

			if (xsdItem.attr.name) {
				process.stdout.write(` - ${xsdItem.attr.name}`);
				this.htmlOutput  += `<li class="xsdc" style="border-radius:0;width:300px;font-size:14px;color:rgb(204, 0, 0);background-color:#fafafa;"><b>${xsdItem.attr.name}</b></li>\n`;

				if (verbose) {
					if (xsdItem.name === "xs:element") {
						let txmlItem = xsdItem.toString();
						txmlItem = txmlItem.split("\n").join("");
						txmlItem = txmlItem.split("<").join(xspace + `\n${xspace}\x1b[2m▓▓▓▓▓▓▓▓▓▓▓▓▓  \x1b[2m<`);

						let pos1 = txmlItem.indexOf("<xs:documentation>");
						if (pos1 > 0) {
							let pos2 = txmlItem.indexOf("</xs:documentation>");
							txmlItem = txmlItem.substring(0, pos1) + "<xs:documentation> ..." + txmlItem.substring(pos2);
						}
						process.stdout.write(`\x1b[2m${txmlItem}`);
					}
				}
			} else if (xsdItem.attr.value) {
				process.stdout.write(`\n${xspace}\x1b[2m▓▓▓▓▓▓▓▓▓▓▓▓▓  \x1b[2m${xsdItem.attr.value}\x1b[0m`);
				this.htmlOutput  += `<li class="xsdc"style="border-radius:0;width:300px;font-size:12px;color:#333;background-color:#dee6f7;"><b>${xsdItem.attr.value}</b></li>\n`;
			} else if (xsdItem.attr.ref) {
				process.stdout.write(`\n${xspace}\x1b[2m▓▓▓▓▓▓▓▓▓▓▓▓▓  \x1b[2m\x1b[36mRef: \x1b[1m\x1b[36m${xsdItem.attr.ref}\x1b[0m`);
				this.htmlOutput  += `<li class="xsdc"style="border-radius:0;width:300px;font-size:12px;color:#333;background-color:#dee6f7;">Ref: ${xsdItem.attr.ref}</li>\n`;
			}

			process.stdout.write(`\n\x1b[2m${xspace}▓▓▓▓▓▓▓▓▓▓▓▓▓`);

			if (xsdItem.name === "xs:documentation" && xsdItem.xparent.name === "xs:annotation") {
				let txmlItem = xsdItem.val.toString().trim();
				if (txmlItem.length > 60)
					txmlItem = txmlItem.substring(0, 60) + "...";
				process.stdout.write(` \x1b[2m\x1b[37m ${txmlItem}\x1b[0m\n${xspace}\x1b[2m▓▓▓▓▓▓▓▓▓▓▓▓▓`);
			}

			if (xsdItem.xparent) {
				console.log(`\x1b[2m\x1b[32m  parent ::\x1b[1m ${xsdItem.xparent.name}\x1b[0m`);
				if (xsdItem.xparent.attr.name) {
					console.log(`${xspace}\x1b[2m▓▓▓▓▓▓▓▓▓▓▓▓▓ \x1b[2m\x1b[32m par.name ::\x1b[1m ${xsdItem.xparent.attr.name}\x1b[0m`);
				}
			}
		}

		if (xsdItem.level === 0)
			console.log(" ");

		this.htmlOutput  += `</ul>\n`;

		process.stdout.write(`\x1b[2m${xspace}         ▒▒`);
	}

	/**
	 * logXsdTag - Log XSD Element Tag
	 * @param item
	 */
	logXsdTag(item) {
		console.log(`\x1b[0m\x1b[31m⇣\x1b[2m Found Tag \x1b[33m${item}\x1b[0m`);
		this.htmlOutput  += `<div class="ftag">Found Tag >> ${item}</div>\n`;
	}

	/**
	 * logTODO - Log XSD Element Tag
	 * @param msg
	 */
	logTODO(msg) {
		console.log(`\x1b[1m\x1b[31mTODO: \x1b[0m${msg}\x1b[0m`);
	}

	/**
	 * logHtmlTag - Log HTML Element Tag
	 * @param item
	 */
	logHtmlTag(item, sender) {
		if (sender.verbose) {
			console.log(`\x1b[0m\x1b[31m⇣\n\x1b[2mParsing HTML Tag ⇢ \x1b[33m${item.name}\x1b[0m\n`);
			this.htmlOutput  += `<div class="phtmlt">Parsing HTML Tag >> <b>${item.name}</b> :: <b>${item.attr.element  || item.attr.name || ' '}</b></div>\n`;
		}
	}

	/**
	 * getHtmlLog
	 */
	getHtmlLog() {
		return this.htmlOutput  + `

		 `;
	}

}

module.exports = XSDWebFormParserLog;<|endoftext|>


<commit_before>(function() {

	document.observe('chinachu:reload', function() {
		document.stopObserving('chinachu:reload', arguments.callee);
		document.stopObserving('chinachu:reserves',  viewProgram);
		document.stopObserving('chinachu:recording', viewProgram);
		document.stopObserving('chinachu:recorded',  viewProgram);
	});

	var param = {
		color       : {
			anime      : '#fcbde1',
			information: '#bdfce8',
			news       : '#d7fcbd',
			sports     : '#bdf1fc',
			variety    : '#fbfcbd',
			drama      : '#fce1c4',
			music      : '#bdc9fc',
			cinema     : '#d6bdfc',
			etc        : '#eeeeee'
		}
	};

	// ビュー: プログラム
	function viewProgram() {
		if (app.chinachu.recorded.length === 0) return;

		$('program-view-main-status-head').update();
		$('program-view-main-status-list').update();
		$('program-view-main-status-att').update();
		$('program-view-sub').update();

		param.cur = new Date().getTime();

		var program = app.f.getProgramById(app.query.id);

		if (program === null) {
			$('program-view-main-head').update('番組が見つかりません');
			return this;
		}

		// title
		$('program-view-main-head').update(program.title);

		// meta
		$('program-view-main-meta').update(
			dateFormat(new Date(program.start), 'yyyy/mm/dd HH:MM') + ' – ' +
			dateFormat(new Date(program.end), 'HH:MM') +
			' (' + (program.seconds / 60) + '分間) #' + program.id +
			'
' + program.category + ' / ' + program.channel.type + ': ' +
			'' + program.channel.name + '' +
			''
		);

		// detail
		$('program-view-main-detail').update(program.detail || '説明なし');

		$('program-view-sub').insert('ルールを作成');

		if (program._isReserves) {
			$('program-view-main-status-head').insert('この番組は予約済みです');
		}

		if (!program._isReserves && !program._isRecorded && !program._isRecording) {
			$('program-view-sub').insert('手動予約');
		}

		if (program._isRecording) {
			$('program-view-sub').insert('録画中止');
		}

		if (program._isReserves && !program._isRecorded && program.isManualReserved) {
			$('program-view-sub').insert('手動予約の取消');
		}

		if (program._isRecording) {
			$('program-view-main-status-head').insert('この番組は現在録画中です');

			$('program-view-main-status-list').insert(
				'
' +
				'
プロセスID

' + program.pid + '
' +
				'
コマンド

' + program.command + '
' +
				'
保存先パス

' + program.recorded + '
' +
				'
チューナー名 (番号)

' + program.tuner.name + ' (' + program.tuner.n + ')
' +
				'
スクランブル

' + (program.tuner.isScrambling ? 'はい' : 'いいえ') + '
' +
				'
'
			);
		}

		if (app.chinachu.status.feature.streamer && program._isRecording && !program.tuner.isScrambling) {
			$('program-view-sub').insert(
				'ストリーミング再生'
			);
		}

		if (program._isRecorded) {
			$('program-view-main-status-head').insert('この番組は録画済みです');

			$('program-view-main-status-list').insert(
				'
' +
				'
コマンド

' + program.command + '
' +
				'
保存先パス

' + program.recorded + '
' +
				'
チューナー名 (番号)

' + program.tuner.name + ' (' + program.tuner.n + ')
' +
				'
スクランブル

' + (program.tuner.isScrambling ? 'はい' : 'いいえ') + '
' +
				'
'
			);

			$('program-view-main-status-att').insert(
				'この番組情報は録画履歴に保存されています。' +
				'削除するには、クリーンアップか' +
				'個別に録画履歴の削除' +
				'を実行してください。'
			);

			$('program-view-sub').insert('録画履歴の削除');
		}

		if (program._isRecorded) {
			new Ajax.Request('./api/recorded/' + program.id + '/file.json', {
				method: 'get',
				onSuccess: function(t) {
					if (app.chinachu.status.feature.filer) {
						$('program-view-sub').insert(
							'録画ファイルの削除'
						);
					}

					if (app.chinachu.status.feature.streamer && !program.tuner.isScrambling) {
						$('program-view-sub').insert(
							'ストリーミング再生'
						);
					}

					$('program-view-main-status-list').insert(
						'
' +
						'
ファイルサイズ

' + (t.responseJSON.size / 1024 / 1024 / 1024 / 1).toFixed(2) + 'GB
' +
						'
'
					);
				}.bind(this),
				onFailure: function(t) {
					if (t.status === 410) {
						$('program-view-main-status-att').insert(
							'
※この番組の録画ファイルは移動または削除されています。
'
						);
					}
				}
			});
		}

		if (app.chinachu.status.feature.previewer && program._isRecording) {
			new Ajax.Request('./api/recording/' + program.id + '/preview.txt', {
				method    : 'get',
				parameters: {width: 640, height: 360, nonce: new Date().getTime()},
				onSuccess : function(t) {
					$('content-body').style.backgroundImage = 'url(' + t.responseText + ')';
				}
			});
		}
	}
	viewProgram();
	document.observe('chinachu:reserves',  viewProgram);
	document.observe('chinachu:recording', viewProgram);
	document.observe('chinachu:recorded',  viewProgram);

})();
<commit_msg>WUI/Client: 録画済番組のプレビュー表示<commit_after>(function() {

	document.observe('chinachu:reload', function() {
		document.stopObserving('chinachu:reload', arguments.callee);
		document.stopObserving('chinachu:reserves',  viewProgram);
		document.stopObserving('chinachu:recording', viewProgram);
		document.stopObserving('chinachu:recorded',  viewProgram);
	});

	var param = {
		color       : {
			anime      : '#fcbde1',
			information: '#bdfce8',
			news       : '#d7fcbd',
			sports     : '#bdf1fc',
			variety    : '#fbfcbd',
			drama      : '#fce1c4',
			music      : '#bdc9fc',
			cinema     : '#d6bdfc',
			etc        : '#eeeeee'
		}
	};

	// ビュー: プログラム
	function viewProgram() {
		if (app.chinachu.recorded.length === 0) return;

		$('program-view-main-status-head').update();
		$('program-view-main-status-list').update();
		$('program-view-main-status-att').update();
		$('program-view-sub').update();

		param.cur = new Date().getTime();

		var program = app.f.getProgramById(app.query.id);

		if (program === null) {
			$('program-view-main-head').update('番組が見つかりません');
			return this;
		}

		// title
		$('program-view-main-head').update(program.title);

		// meta
		$('program-view-main-meta').update(
			dateFormat(new Date(program.start), 'yyyy/mm/dd HH:MM') + ' – ' +
			dateFormat(new Date(program.end), 'HH:MM') +
			' (' + (program.seconds / 60) + '分間) #' + program.id +
			'
' + program.category + ' / ' + program.channel.type + ': ' +
			'' + program.channel.name + '' +
			''
		);

		// detail
		$('program-view-main-detail').update(program.detail || '説明なし');

		$('program-view-sub').insert('ルールを作成');

		if (program._isReserves) {
			$('program-view-main-status-head').insert('この番組は予約済みです');
		}

		if (!program._isReserves && !program._isRecorded && !program._isRecording) {
			$('program-view-sub').insert('手動予約');
		}

		if (program._isRecording) {
			$('program-view-sub').insert('録画中止');
		}

		if (program._isReserves && !program._isRecorded && program.isManualReserved) {
			$('program-view-sub').insert('手動予約の取消');
		}

		if (program._isRecording) {
			$('program-view-main-status-head').insert('この番組は現在録画中です');

			$('program-view-main-status-list').insert(
				'
' +
				'
プロセスID

' + program.pid + '
' +
				'
コマンド

' + program.command + '
' +
				'
保存先パス

' + program.recorded + '
' +
				'
チューナー名 (番号)

' + program.tuner.name + ' (' + program.tuner.n + ')
' +
				'
スクランブル

' + (program.tuner.isScrambling ? 'はい' : 'いいえ') + '
' +
				'
'
			);
		}

		if (app.chinachu.status.feature.streamer && program._isRecording && !program.tuner.isScrambling) {
			$('program-view-sub').insert(
				'ストリーミング再生'
			);
		}

		if (program._isRecorded) {
			$('program-view-main-status-head').insert('この番組は録画済みです');

			$('program-view-main-status-list').insert(
				'
' +
				'
コマンド

' + program.command + '
' +
				'
保存先パス

' + program.recorded + '
' +
				'
チューナー名 (番号)

' + program.tuner.name + ' (' + program.tuner.n + ')
' +
				'
スクランブル

' + (program.tuner.isScrambling ? 'はい' : 'いいえ') + '
' +
				'
'
			);

			$('program-view-main-status-att').insert(
				'この番組情報は録画履歴に保存されています。' +
				'削除するには、クリーンアップか' +
				'個別に録画履歴の削除' +
				'を実行してください。'
			);

			$('program-view-sub').insert('録画履歴の削除');
		}

		if (program._isRecorded) {
			new Ajax.Request('./api/recorded/' + program.id + '/file.json', {
				method: 'get',
				onSuccess: function(t) {
					if (app.chinachu.status.feature.filer) {
						$('program-view-sub').insert(
							'録画ファイルの削除'
						);
					}

					if (app.chinachu.status.feature.streamer && !program.tuner.isScrambling) {
						$('program-view-sub').insert(
							'ストリーミング再生'
						);
					}

					$('program-view-main-status-list').insert(
						'
' +
						'
ファイルサイズ

' + (t.responseJSON.size / 1024 / 1024 / 1024 / 1).toFixed(2) + 'GB
' +
						'
'
					);
				}.bind(this),
				onFailure: function(t) {
					if (t.status === 410) {
						$('program-view-main-status-att').insert(
							'
※この番組の録画ファイルは移動または削除されています。
'
						);
					}
				}
			});
		}

		if (app.chinachu.status.feature.previewer && program._isRecording) {
			new Ajax.Request('./api/recording/' + program.id + '/preview.txt', {
				method    : 'get',
				parameters: {width: 640, height: 360, nonce: new Date().getTime()},
				onSuccess : function(t) {
					$('content-body').style.backgroundImage = 'url(' + t.responseText + ')';
				}
			});
		}

		if (app.chinachu.status.feature.previewer && program._isRecorded) {
			new Ajax.Request('./api/recorded/' + program.id + '/preview.txt', {
				method    : 'get',
				parameters: {width: 640, height: 360, pos: 32},
				onSuccess : function(t) {
					$('content-body').style.backgroundImage = 'url(' + t.responseText + ')';
				}
			});
		}
	}
	viewProgram();
	document.observe('chinachu:reserves',  viewProgram);
	document.observe('chinachu:recording', viewProgram);
	document.observe('chinachu:recorded',  viewProgram);

})();
<|endoftext|>


<commit_before>var engine;
if (typeof E === 'undefined') {
    engine = global.engine;
} else {
    engine = E;
    global = window;
}

/**
 * Clone object. True prototypal inheritance.
 *
 * @public
 * @param {object} The, to be cloned, object.
 */
engine.clone = function (object) {

    // create an empty function
    function O() {}

    // set prototype to given object
    O.prototype = object;

    // create new instance of empty function
    return new O();
};

/**
 * Get a value from a property "path" (dot.notation).
 * path('Object.key.key.value'[, {'key': {'key': {'value': 123}}}]);
 *
 * @public
 * @param {string} The path in "dot" notation.
 * @param {object} The data object, which is used to search the path.
 * @param {booloean} Stop search, or try to search in the global.
 */
engine.path = function (path, scope, stop) {

    if (!path) {
        return;
    }

    var o = path;
    path = path.split('.');
    scope = scope || this;

    // find keys in paths or return
    for (var i = 0; i < path.length; ++i) {
        if (!(scope = scope[path[i]])) {
            return stop ? null : this.path(o, global, true);
        }
    }

    return scope;
};

/**
 * Create a flat object {key1: {key2: "value"}} => {"key1.key2": "value"}
 *
 * @public
 * @param {string} The object, which is flattened.
 */
engine.flat = function (object) {
    var output = {};
    var value;
    var newKey;

    // recusrive handler
    function step(obj, prev) {
        for (var key in obj) {
            value = obj[key];
            newKey = prev + key;

            if (typeof value === 'object' && value !== null && !Array.isArray(value)) {

                if (Object.keys(value).length) {
                    step(value, newKey + '.');
                    continue;
                }
            }

            output[newKey] = value;
        }
    }

    // start recursive loop
    step(object, '');

    return output;
};

/**
 * Unflatten dot-notation keys {"key1.key2": "value"} => {key1: {key2: "value"}}
 *
 * @public
 * @param {string} The object, which is unflattened.
 */
engine.deep = function (object) {
    var result = {};
    var parentObj = result;
    var key;
    var subkeys;
    var subkey;
    var last;
    var keys = Object.keys(object);

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

        key = keys[i];
        subkeys = key.split('.');
        last = subkeys.pop();

        for (var ii = 0; ii < subkeys.length; ++ii) {
            subkey = subkeys[ii];
            parentObj[subkey] = typeof parentObj[subkey] === 'undefined' ? {} : parentObj[subkey];
            parentObj = parentObj[subkey];
        }

        parentObj[last] = object[key];
        parentObj = result;
    }

    return result;
};

/**
 * Convert array like object into real Arrays.
 *
 * @public
 * @param {object} The object, which is converted to an array.
 */
engine.toArray = function (object) {
    return Array.prototype.slice.call(object);
};

/**
 * Retruns a random string.
 *
 * @public
 * @param {number} The length of the random string.
 */
engine.uid = function (len) {
    len = len || 23;
    for (var i = 0, random = ''; i < len; ++i) {
        random += '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'[0 | Math.random() * 62];
    }
    return random;
};
<commit_msg>moved "checkRoleAccess" to utils module<commit_after>var engine;
if (typeof E === 'undefined') {
    engine = global.engine;
} else {
    engine = E;
    global = window;
}

/**
 * Clone object. True prototypal inheritance.
 *
 * @public
 * @param {object} The, to be cloned, object.
 */
engine.clone = function (object) {

    // create an empty function
    function O() {}

    // set prototype to given object
    O.prototype = object;

    // create new instance of empty function
    return new O();
};

/**
 * Get a value from a property "path" (dot.notation).
 * path('Object.key.key.value'[, {'key': {'key': {'value': 123}}}]);
 *
 * @public
 * @param {string} The path in "dot" notation.
 * @param {object} The data object, which is used to search the path.
 * @param {booloean} Stop search, or try to search in the global.
 */
engine.path = function (path, scope, stop) {

    if (!path) {
        return;
    }

    var o = path;
    path = path.split('.');
    scope = scope || this;

    // find keys in paths or return
    for (var i = 0; i < path.length; ++i) {
        if (!(scope = scope[path[i]])) {
            return stop ? undefined : engine.path(o, global, true);
        }
    }

    return scope;
};

/**
 * Create a flat object {key1: {key2: "value"}} => {"key1.key2": "value"}
 *
 * @public
 * @param {string} The object, which is flattened.
 */
engine.flat = function (object) {
    var output = {};
    var value;
    var newKey;

    // recusrive handler
    function step(obj, prev) {
        for (var key in obj) {
            value = obj[key];
            newKey = prev + key;

            if (typeof value === 'object' && value !== null && !Array.isArray(value)) {

                if (Object.keys(value).length) {
                    step(value, newKey + '.');
                    continue;
                }
            }

            output[newKey] = value;
        }
    }

    // start recursive loop
    step(object, '');

    return output;
};

/**
 * Unflatten dot-notation keys {"key1.key2": "value"} => {key1: {key2: "value"}}
 *
 * @public
 * @param {string} The object, which is unflattened.
 */
engine.deep = function (object) {
    var result = {};
    var parentObj = result;
    var key;
    var subkeys;
    var subkey;
    var last;
    var keys = Object.keys(object);

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

        key = keys[i];
        subkeys = key.split('.');
        last = subkeys.pop();

        for (var ii = 0; ii < subkeys.length; ++ii) {
            subkey = subkeys[ii];
            parentObj[subkey] = typeof parentObj[subkey] === 'undefined' ? {} : parentObj[subkey];
            parentObj = parentObj[subkey];
        }

        parentObj[last] = object[key];
        parentObj = result;
    }

    return result;
};

/**
 * Convert array like object into real Arrays.
 *
 * @public
 * @param {object} The object, which is converted to an array.
 */
engine.toArray = function (object) {
    return Array.prototype.slice.call(object);
};

/**
 * Retruns a random string.
 *
 * @public
 * @param {number} The length of the random string.
 */
engine.uid = function (len) {
    len = len || 23;
    for (var i = 0, random = ''; i < len; ++i) {
        random += '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'[0 | Math.random() * 62];
    }
    return random;
};

/**
 * Check the role access for a cache item.
 *
 * @private
 * @param {object} The cached item.
 * @param {string} The role name.
 */
engine.roleAccess = function (item, role) {

    var roles = item._roles || item.roles || {};

    if (roles['*'] || roles[role]) {
        return true;
    }
}
<|endoftext|>


<commit_before>/**
 * @file xsdwebform.parser.xsd.js
 * XSD Schema to HTML5 Web Form
 * @author George Bouris <gb@eworx.gr>
 * @copyright Copyright (C) 2017 EEA, Eworx, George Bouris. All rights reserved.
 */
'use strict';

import XSDWebFormParserError from './xsdwebform.parser.error.js';

/**
 * Class XSDWebFormParserTags
 * Parser for XSD Schema Tags
 */
class XSDWebFormParserTags {
	/**
	 * Class constructor
	 */
	constructor() {
		this.ELEMENT_TYPES = {
			"xs:element": this.parseElement,
			"xs:import": this.parseImport,
			"xs:simpleType": this.parseSimpleType,
			"xs:complexType": this.parseComplexType,
			"xs:sequence": this.parseSequence,
			"xs:all": this.parseAll,
			"xs:attribute": this.parseAttribute,
			"xs:restriction": this.parseRestriction,
			"xs:annotation": this.parseAnnotation,
			"xs:documentation": this.parseDocumentation,
			"xs:enumeration": this.parseEnumeration,
			"xs:minInclusive": this.parseMinInclusive,
			"xs:maxInclusive": this.parseMaxInclusive,
			"xs:union": this.parseUnion,
			"xs:pattern": this.parsePattern,
			"xs:whiteSpace": this.parseWhiteSpace,
			"xs:minLength": this.parseMinLength,
			"xs:maxLength": this.parseMaxLength,
			"xs:totalDigits": this.parseTotalDigits,
			"dd:multiValueDelim": this.parseMultiValueDelim,
			"dd2:Keyword": this.parseKeyword,
			"dd2:Definition": this.parseDefinition,
			"dd3:Methodology": this.parseMethodology
		};
		this.showLog = false;
		this.verbose = false;
	}

	/**
	 * xsdParse - Parse inner XML Document
	 * @param xsdItem
	 */
	xsdParse(xsdItem) {
		if (this.showLog)
			this.logger.showItemLog(xsdItem, this.verbose);
		// Loop through Tag's childNodes
		if (xsdItem.children) {
			for (let i = 0, l = xsdItem.children.length; i < l; i++) {
				if (xsdItem.children[i].type === "element") {
					try {
						// Parse Tag Tag
						this.parseXSDItem(xsdItem.children[i].name);
						xsdItem.children[i].xparent = xsdItem;
						xsdItem.children[i].level = xsdItem.level + 1;
						// Recursive call
						this.xsdParse(xsdItem.children[i]);
					} catch (err) {
						XSDWebFormParserError.reportError(err);
					}
				}
			}
		}
	}

	/**
	 * parseXSDItem - Parse XML Tag
	 * @param item
	 */
	parseXSDItem(item) {
		if ((item in this.ELEMENT_TYPES)) {
			(this.ELEMENT_TYPES[item])(item, this);
		} else {
			console.log(`\n\x1b[1m\x1b[31m************* Unknown Tag {${item}} *************\x1b[0m\n`);
			process.stdout.write('\x07');
		}
	}

	/**
	 * parseElement- Parse Element Tag
	 * @param item
	 * @param sender
	 */

	parseElement(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseImport- Parse Import Tag
	 * @param item
	 * @param sender
	 */
	parseImport(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseSimpleType - Parse SimpleType Tag
	 * @param item
	 * @param sender
	 */
	parseSimpleType(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseComplexType - Parse ComplexType Tag
	 * @param item
	 * @param sender
	 */
	parseComplexType(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseSequence - Parse Sequence Tag
	 * @param item
	 * @param sender
	 */
	parseSequence(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseAll - Parse All Tag
	 * @param item
	 * @param sender
	 */
	parseAll(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseAttribute - Parse Attribute Tag
	 * @param item
	 * @param sender
	 */
	parseAttribute(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseRestriction - Parse Restriction Tag
	 * @param item
	 * @param sender
	 */
	parseRestriction(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}
	/**
	 * parseAnnotation - Parse Annotation Tag
	 * @param item
	 * @param sender
	 */

	parseAnnotation(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}
	/**
	 * parseDocumentation - Parse Documentation Tag
	 * @param item
	 * @param sender
	 */

	parseDocumentation(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseEnumeration - Parse Enumeration Tag
	 * @param item
	 * @param sender
	 */
	parseEnumeration(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseMinInclusive - Parse MinInclusive Tag
	 * @param item
	 * @param sender
	 */
	parseMinInclusive(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseMaxInclusive - Parse MaxInclusive Tag
	 * @param item
	 * @param sender
	 */
	parseMaxInclusive(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseUnion - Parse Union Tag
	 * @param item
	 * @param sender
	 */
	parseUnion(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parsePattern - Parse Pattern Tag
	 * @param item
	 * @param sender
	 */
	parsePattern(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseWhiteSpace - Parse WhiteSpace Tag
	 * @param item
	 * @param sender
	 */
	parseWhiteSpace(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseMinLength - Parse MinLength Tag
	 * @param item
	 * @param sender
	 */
	parseMinLength(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseMaxLength - Parse MaxLength Tag
	 * @param item
	 * @param sender
	 */
	parseMaxLength(item, sender) {

		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseTotalDigits - Parse TotalDigits Tag
	 * @param item
	 * @param sender
	 */
	parseTotalDigits(item, sender) {

		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseMultiValueDelim - Parse MultivalueDelim Tag
	 * @param item
	 * @param sender
	 */
	parseMultiValueDelim(item, sender) {

		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseKeyword - Parse Keyword Tag
	 * @param item
	 * @param sender
	 */
	parseKeyword(item, sender) {

		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseDefinition - Parse Definition Tag
	 * @param item
	 * @param sender
	 */
	parseDefinition(item, sender) {

		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseMethodology - Parse Methodology Tag
	 * @param item
	 * @param sender
	 */
	parseMethodology(item, sender) {

		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * setLogger
	 * @param logger
	 */
	setLogger(logger) {
		this.logger = logger;
	}

	/**
	 * setLog  - Show Log
	 * @param bool
	 */
	setLog(bool) {
		this.showLog = bool;
	}

	/**
	 * setVerbose - Show Log verbose
	 * @param bool
	 */
	setVerbose(bool) {
		this.verbose = bool;
	}

	/**
	 * getLog - Show Log
	 */
	getLog() {
		return this.showLog;
	}

	/**
	 * getLog - Show Log
	 */
	getVerbose() {
		return this.verbose;
	}

}

module.exports = XSDWebFormParserTags;<commit_msg>Updated comments in parseXSDItem<commit_after>/**
 * @file xsdwebform.parser.xsd.js
 * XSD Schema to HTML5 Web Form
 * @author George Bouris <gb@eworx.gr>
 * @copyright Copyright (C) 2017 EEA, Eworx, George Bouris. All rights reserved.
 */
'use strict';

import XSDWebFormParserError from './xsdwebform.parser.error.js';

/**
 * Class XSDWebFormParserTags
 * Parser for XSD Schema Tags
 */
class XSDWebFormParserTags {
	/**
	 * Class constructor
	 */
	constructor() {
		this.ELEMENT_TYPES = {
			"xs:element": this.parseElement,
			"xs:import": this.parseImport,
			"xs:simpleType": this.parseSimpleType,
			"xs:complexType": this.parseComplexType,
			"xs:sequence": this.parseSequence,
			"xs:all": this.parseAll,
			"xs:attribute": this.parseAttribute,
			"xs:restriction": this.parseRestriction,
			"xs:annotation": this.parseAnnotation,
			"xs:documentation": this.parseDocumentation,
			"xs:enumeration": this.parseEnumeration,
			"xs:minInclusive": this.parseMinInclusive,
			"xs:maxInclusive": this.parseMaxInclusive,
			"xs:union": this.parseUnion,
			"xs:pattern": this.parsePattern,
			"xs:whiteSpace": this.parseWhiteSpace,
			"xs:minLength": this.parseMinLength,
			"xs:maxLength": this.parseMaxLength,
			"xs:totalDigits": this.parseTotalDigits,
			"dd:multiValueDelim": this.parseMultiValueDelim,
			"dd2:Keyword": this.parseKeyword,
			"dd2:Definition": this.parseDefinition,
			"dd3:Methodology": this.parseMethodology
		};
		this.showLog = false;
		this.verbose = false;
	}

	/**
	 * xsdParse - Parse inner XML Document
	 * @param xsdItem
	 */
	xsdParse(xsdItem) {
		if (this.showLog)
			this.logger.showItemLog(xsdItem, this.verbose);
		// Loop through Tag's childNodes
		if (xsdItem.children) {
			for (let i = 0, l = xsdItem.children.length; i < l; i++) {
				if (xsdItem.children[i].type === "element") {
					try {
						// Parse Tag Tag
						this.parseXSDItem(xsdItem.children[i].name);
						xsdItem.children[i].xparent = xsdItem;
						xsdItem.children[i].level = xsdItem.level + 1;
						// Recursive call
						this.xsdParse(xsdItem.children[i]);
					} catch (err) {
						XSDWebFormParserError.reportError(err);
					}
				}
			}
		}
	}

	/**
	 * parseXSDItem - Parse XML Tag
	 * @param item
	 */
	parseXSDItem(item) {
		if ((item in this.ELEMENT_TYPES)) {
			// Execute hash value=>function
			// i.e. ELEMENT_TYPES["xs:element"] => (this.parseElement)(item, xsdItem, this)
			// Parse XML => Look for xs:element => Execute task this.parseElement
			(this.ELEMENT_TYPES[item])(item, this);
		} else {
			console.log(`\n\x1b[1m\x1b[31m************* Unknown Tag {${item}} *************\x1b[0m\n`);
			process.stdout.write('\x07');
		}
	}

	/**
	 * parseElement- Parse Element Tag
	 * @param item
	 * @param sender
	 */

	parseElement(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseImport- Parse Import Tag
	 * @param item
	 * @param sender
	 */
	parseImport(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseSimpleType - Parse SimpleType Tag
	 * @param item
	 * @param sender
	 */
	parseSimpleType(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseComplexType - Parse ComplexType Tag
	 * @param item
	 * @param sender
	 */
	parseComplexType(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseSequence - Parse Sequence Tag
	 * @param item
	 * @param sender
	 */
	parseSequence(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseAll - Parse All Tag
	 * @param item
	 * @param sender
	 */
	parseAll(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseAttribute - Parse Attribute Tag
	 * @param item
	 * @param sender
	 */
	parseAttribute(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseRestriction - Parse Restriction Tag
	 * @param item
	 * @param sender
	 */
	parseRestriction(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}
	/**
	 * parseAnnotation - Parse Annotation Tag
	 * @param item
	 * @param sender
	 */

	parseAnnotation(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}
	/**
	 * parseDocumentation - Parse Documentation Tag
	 * @param item
	 * @param sender
	 */

	parseDocumentation(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseEnumeration - Parse Enumeration Tag
	 * @param item
	 * @param sender
	 */
	parseEnumeration(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseMinInclusive - Parse MinInclusive Tag
	 * @param item
	 * @param sender
	 */
	parseMinInclusive(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseMaxInclusive - Parse MaxInclusive Tag
	 * @param item
	 * @param sender
	 */
	parseMaxInclusive(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseUnion - Parse Union Tag
	 * @param item
	 * @param sender
	 */
	parseUnion(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parsePattern - Parse Pattern Tag
	 * @param item
	 * @param sender
	 */
	parsePattern(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseWhiteSpace - Parse WhiteSpace Tag
	 * @param item
	 * @param sender
	 */
	parseWhiteSpace(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseMinLength - Parse MinLength Tag
	 * @param item
	 * @param sender
	 */
	parseMinLength(item, sender) {
		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseMaxLength - Parse MaxLength Tag
	 * @param item
	 * @param sender
	 */
	parseMaxLength(item, sender) {

		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseTotalDigits - Parse TotalDigits Tag
	 * @param item
	 * @param sender
	 */
	parseTotalDigits(item, sender) {

		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseMultiValueDelim - Parse MultivalueDelim Tag
	 * @param item
	 * @param sender
	 */
	parseMultiValueDelim(item, sender) {

		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseKeyword - Parse Keyword Tag
	 * @param item
	 * @param sender
	 */
	parseKeyword(item, sender) {

		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseDefinition - Parse Definition Tag
	 * @param item
	 * @param sender
	 */
	parseDefinition(item, sender) {

		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * parseMethodology - Parse Methodology Tag
	 * @param item
	 * @param sender
	 */
	parseMethodology(item, sender) {

		if (sender.showLog)
			sender.logger.logXsdTag(item);
	}

	/**
	 * setLogger
	 * @param logger
	 */
	setLogger(logger) {
		this.logger = logger;
	}

	/**
	 * setLog  - Show Log
	 * @param bool
	 */
	setLog(bool) {
		this.showLog = bool;
	}

	/**
	 * setVerbose - Show Log verbose
	 * @param bool
	 */
	setVerbose(bool) {
		this.verbose = bool;
	}

	/**
	 * getLog - Show Log
	 */
	getLog() {
		return this.showLog;
	}

	/**
	 * getLog - Show Log
	 */
	getVerbose() {
		return this.verbose;
	}

}

module.exports = XSDWebFormParserTags;<|endoftext|>