<commit_before>// convert mongo db object style to middle style used by plist.js
var when = require('when');
var request = require('request');
var settings = require("../../../settings");
var log = require("../../log");

var PLIST_DEPLOY = settings.staticPlistSubmittingService || "http://ws.ubicall.com/webservice/check_ivr_version.php?url=";
var PLIST_HOST = settings.staticPlistHostingUrl || "https://designer.ubicall.com/plist/";

var oldApiRegex = /^http:\/\/ws.ubicall.com/;

var REQUEST_METHOD = oldApiRegex.test(PLIST_DEPLOY) ? 'get' : 'post';

var g_flow;
var plistMapper = {
    "choicesscreen": {name: "Choice", type: "String"},
    "gridscreen": {name: "Grid", type: "String"},
    "InfoScreen": {name: "Info", type: "String"},
    "formscreen": {name: "Form", type: "String"},
    "type": {name: "ScreenType", type: "String"},
    "choices": {name: "choices", type: "Array"},
    "t": {name: "ChoiceText", type: "String"},
    "wi": {name: "ScreenName", type: "String"},
    "wt": {name: "ChoiceType", type: "String"},
    "form_screen_name": {name: "ScreenTitle", type: "String"},
    "form_screen_title": {name: "FormTitle", type: "String"},
    "form_screen_items": {name: "FormFields", type: "Array"},
    "fieldLabel": {name: "FieldLabel", type: "String"},
    "fieldType": {name: "FieldType", type: "String"},
    "isMandatory": {name: "isMandatory", type: "String"},
    "keyboard": {name: "Keyboard", type: "String"},
    "placeholder": {name: "Placeholder", type: "String"},
    "Values": {name: "Values", type: "String"},
    "screen_name": {name: "ScreenTitle", type: "String"},
    "screen_content": {name: "ContentText", type: "String"},
    "url": {name: "URL", type: "String"},
    "grid_url": {name: "UrlImage", type: "String"},
    "url_title": {name: "ChoiceText", type: "String"},
    "call": {name: "Call", type: "String"},
    "title": {name: "ChoiceText", type: "String"},
    "queue": {name: "QueueDestination", type: "String"}
};

function getNodeWithId(_id) {//get first one , id attribute doesn't duplicate
    return g_flow.Nodes.filter(function (node) {
        return (_id && node.hasOwnProperty('id') && node.id == _id);
    })[0];
}

function isNodeValid(Node) {
    if (Node && Node.hasOwnProperty('type')) {
        return true;
    }
    return false;
}

function mapElement(that) {
    var rObj = {};
    for (var k in that) {
        if (that.hasOwnProperty(k) && plistMapper.hasOwnProperty(k)) {
            if (plistMapper[k].name == 'choices') {
                rObj[plistMapper[k].name] = that.choices.map(mapElement);
                rObj[plistMapper[k].name].forEach(function (choice, index) {
                    var Node = getNodeWithId(that.wires[index][0]);
                    choice.ChoiceType = plistMapper[Node.type].name;
                    if (Node.type == 'url') {
                        choice.url = Node.url;
                        delete choice.ScreenName;
                    } else if (Node.type == 'call') {
                        choice.QueueDestination = Node.queue.id;
                        // delete choice.ScreenName;
                        choice.ScreenName = that.wires[index][0];
                    } else {
                        choice.ScreenName = that.wires[index][0];
                    }
                });
            } else if (plistMapper[k].name == 'FormFields') {
                rObj[plistMapper[k].name] = that.form_screen_items.map(mapElement);
                // var Node = getNodeWithId(that.wires[0][0]);
                // if(Node && Node.type == 'call'){
                //   rObj.QueueDestination = Node.queue.id;
                // }
            } else {
                rObj[plistMapper[k].name] = k == 'type' ? plistMapper[that[k]].name : that[k];
            }
        }
    }
    return rObj;
}

module.exports = {
    extractFlow: function (flow) {
        return when.promise(function (resolve) {
            var __flow = {};
            try {
                //remove unnecessary parts from mongo db object
                var _flow = JSON.parse(JSON.stringify(flow, function (key, value) {
                    return key !== '_id' && key !== '__v' && key !== 'created' && key !== 'deploy' ? value : undefined;
                }));

                g_flow = _flow;
                __flow.key = _flow.key;
                __flow.Version = _flow.version;
                __flow.Font = "Default";

                var startNode = _flow.Nodes.filter(function (node) {
                    // TODO : if it has no start point through exception
                    return (node.hasOwnProperty('type') && node.type == 'start');
                })[0];

                var startId = startNode.wires[0][0];

                //get meta data from start node
                var startNodeMeta = startNode.meta || [];
                startNodeMeta.forEach(function (met) {
                    __flow[met.key] = met['value'] || "Default";
                });

                //End meta extraction
                var initial = getNodeWithId(startId);
                var rest_of_flow = _flow.Nodes.filter(function (node) {
                    return (node.type != 'start' && node.type != 'tab');
                });
                __flow.Initial = plistMapper[initial.type].name;
                __flow.MainScreen = [initial].map(mapElement)[0];
                rest_of_flow.forEach(function (node) {
                    __flow[node.id] = mapElement(node);
                });
            } catch (ex) {
                resolve([]);
            }
            resolve(__flow);
        });
    },
    deployFlowOnline: function (licence, version) {
        return when.promise(function (resolve, reject) {
            var deployURL = oldApiRegex.test(PLIST_DEPLOY) ? (PLIST_DEPLOY + PLIST_HOST + licence + "/" + version) : (PLIST_DEPLOY + licence + "/" + version);
            log.info("Deploy to : " + REQUEST_METHOD + " " + deployURL);

            request({ url : deployURL, method : REQUEST_METHOD },function (err, response, body) {
                if(err){
                  log.error(err);
                  return resolve(null);
                }else if (!err && response.statusCode == 200) {
                  return resolve(body);
                } else {
                  log.error(body);
                  return resolve(null);
                }
            });
        });
    }
}
<commit_msg>designer changes to apply change in ivr , help end Ubicall/node-red-contrib-ivr#20<commit_after>// convert mongo db object style to middle style used by plist.js
var when = require('when');
var request = require('request');
var settings = require("../../../settings");
var log = require("../../log");

var PLIST_DEPLOY = settings.staticPlistSubmittingService || "http://ws.ubicall.com/webservice/check_ivr_version.php?url=";
var PLIST_HOST = settings.staticPlistHostingUrl || "https://designer.ubicall.com/plist/";

var oldApiRegex = /^http:\/\/ws.ubicall.com/;

var REQUEST_METHOD = oldApiRegex.test(PLIST_DEPLOY) ? 'get' : 'post';

var g_flow;
var plistMapper = {
    "choicesscreen": {name: "Choice", type: "String"},
    "gridscreen": {name: "Grid", type: "String"},
    "InfoScreen": {name: "Info", type: "String"},
    "formscreen": {name: "Form", type: "String"},
    "type": {name: "ScreenType", type: "String"},
    "choices": {name: "choices", type: "Array"},
    "t": {name: "ChoiceText", type: "String"},
    "wi": {name: "ScreenName", type: "String"},
    "wt": {name: "ChoiceType", type: "String"},
    "form_screen_name": {name: "ScreenTitle", type: "String"},
    "form_screen_title": {name: "FormTitle", type: "String"},
    "form_screen_items": {name: "FormFields", type: "Array"},
    "form_type": {name: "Callback", type: "String"},
    "form_dest": {name: "Destination", type: "String"},
    "fieldLabel": {name: "FieldLabel", type: "String"},
    "fieldType": {name: "FieldType", type: "String"},
    "isMandatory": {name: "isMandatory", type: "String"},
    "keyboard": {name: "Keyboard", type: "String"},
    "placeholder": {name: "Placeholder", type: "String"},
    "Values": {name: "Values", type: "String"},
    "screen_name": {name: "ScreenTitle", type: "String"},
    "screen_content": {name: "ContentText", type: "String"},
    "url": {name: "URL", type: "String"},
    "grid_url": {name: "UrlImage", type: "String"},
    "url_title": {name: "ChoiceText", type: "String"},
    "call": {name: "Call", type: "String"},
    "title": {name: "ChoiceText", type: "String"},
    "queue": {name: "QueueDestination", type: "String"}
};

function getNodeWithId(_id) {//get first one , id attribute doesn't duplicate
    return g_flow.Nodes.filter(function (node) {
        return (_id && node.hasOwnProperty('id') && node.id == _id);
    })[0];
}

function isNodeValid(Node) {
    if (Node && Node.hasOwnProperty('type')) {
        return true;
    }
    return false;
}

function mapElement(that) {
    var rObj = {};
    for (var k in that) {
        if (that.hasOwnProperty(k) && plistMapper.hasOwnProperty(k)) {
            if (plistMapper[k].name == 'choices') {
                rObj[plistMapper[k].name] = that.choices.map(mapElement);
                rObj[plistMapper[k].name].forEach(function (choice, index) {
                    var Node = getNodeWithId(that.wires[index][0]);
                    choice.ChoiceType = plistMapper[Node.type].name;
                    if (Node.type == 'url') {
                        choice.url = Node.url;
                        delete choice.ScreenName;
                    } else if (Node.type == 'call') {
                        choice.QueueDestination = Node.queue.id;
                        // delete choice.ScreenName;
                        choice.ScreenName = that.wires[index][0];
                    } else {
                        choice.ScreenName = that.wires[index][0];
                    }
                });
            } else if (plistMapper[k].name == 'FormFields') {
                rObj[plistMapper[k].name] = that.form_screen_items.map(mapElement);
                // var Node = getNodeWithId(that.wires[0][0]);
                // if(Node && Node.type == 'call'){
                //   rObj.QueueDestination = Node.queue.id;
                // }
            } else {
                rObj[plistMapper[k].name] = k == 'type' ? plistMapper[that[k]].name : that[k];
            }
        }
    }
    return rObj;
}

module.exports = {
    extractFlow: function (flow) {
        return when.promise(function (resolve) {
            var __flow = {};
            try {
                //remove unnecessary parts from mongo db object
                var _flow = JSON.parse(JSON.stringify(flow, function (key, value) {
                    return key !== '_id' && key !== '__v' && key !== 'created' && key !== 'deploy' ? value : undefined;
                }));

                g_flow = _flow;
                __flow.key = _flow.key;
                __flow.Version = _flow.version;
                __flow.Font = "Default";

                var startNode = _flow.Nodes.filter(function (node) {
                    // TODO : if it has no start point through exception
                    return (node.hasOwnProperty('type') && node.type == 'start');
                })[0];

                var startId = startNode.wires[0][0];

                //get meta data from start node
                var startNodeMeta = startNode.meta || [];
                startNodeMeta.forEach(function (met) {
                    __flow[met.key] = met['value'] || "Default";
                });

                //End meta extraction
                var initial = getNodeWithId(startId);
                var rest_of_flow = _flow.Nodes.filter(function (node) {
                    return (node.type != 'start' && node.type != 'tab');
                });
                __flow.Initial = plistMapper[initial.type].name;
                __flow.MainScreen = [initial].map(mapElement)[0];
                rest_of_flow.forEach(function (node) {
                    __flow[node.id] = mapElement(node);
                });
            } catch (ex) {
                resolve([]);
            }
            resolve(__flow);
        });
    },
    deployFlowOnline: function (licence, version) {
        return when.promise(function (resolve, reject) {
            var deployURL = oldApiRegex.test(PLIST_DEPLOY) ? (PLIST_DEPLOY + PLIST_HOST + licence + "/" + version) : (PLIST_DEPLOY + licence + "/" + version);
            log.info("Deploy to : " + REQUEST_METHOD + " " + deployURL);

            request({ url : deployURL, method : REQUEST_METHOD },function (err, response, body) {
                if(err){
                  log.error(err);
                  return resolve(null);
                }else if (!err && response.statusCode == 200) {
                  return resolve(body);
                } else {
                  log.error(body);
                  return resolve(null);
                }
            });
        });
    }
}
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react'
import { injectIntl, intlShape } from 'react-intl'
import Constants from '../constants/Constants'

class MediaType extends React.Component {
  renderFormats (mediaType, maybeFormats) {
    const formats = maybeFormats || []
    const filtered = formats.filter(format => {
      if (mediaType === 'http://data.deichman.no/mediaType#Book' && (formats.length === 1 && formats[ 0 ] === 'http://data.deichman.no/format#Book')) {
        return false
      } else {
        return !(mediaType === 'http://data.deichman.no/mediaType#ComicBook' && (formats.length === 1 && formats[ 0 ] === 'http://data.deichman.no/format#Book'))
      }
    })
    return

      {filtered.map(format => {
        return {this.props.intl.formatMessage({ id: format })}
      })}

  }

  render () {
    const mediaType = this.props.mediaType
    return (

        <img src={`/images/icon-${Constants.mediaTypeIcons[ mediaType.uri ]}.svg`} />

{this.props.intl.formatMessage({ id: mediaType.uri })}

{this.renderFormats(mediaType.uri, mediaType.formats)}

    )
  }
}

MediaType.propTypes = {
  mediaType: PropTypes.object.isRequired,
  intl: intlShape.isRequired
}

export default injectIntl(MediaType)
<commit_msg>Hide media type icon from screen readers etc.<commit_after>import React, { PropTypes } from 'react'
import { injectIntl, intlShape } from 'react-intl'
import Constants from '../constants/Constants'

class MediaType extends React.Component {
  renderFormats (mediaType, maybeFormats) {
    const formats = maybeFormats || []
    const filtered = formats.filter(format => {
      if (mediaType === 'http://data.deichman.no/mediaType#Book' && (formats.length === 1 && formats[ 0 ] === 'http://data.deichman.no/format#Book')) {
        return false
      } else {
        return !(mediaType === 'http://data.deichman.no/mediaType#ComicBook' && (formats.length === 1 && formats[ 0 ] === 'http://data.deichman.no/format#Book'))
      }
    })
    return

      {filtered.map(format => {
        return {this.props.intl.formatMessage({ id: format })}
      })}

  }

  render () {
    const mediaType = this.props.mediaType
    return (

        <img src={`/images/icon-${Constants.mediaTypeIcons[ mediaType.uri ]}.svg`} aria-hidden="true"/>

{this.props.intl.formatMessage({ id: mediaType.uri })}

{this.renderFormats(mediaType.uri, mediaType.formats)}

    )
  }
}

MediaType.propTypes = {
  mediaType: PropTypes.object.isRequired,
  intl: intlShape.isRequired
}

export default injectIntl(MediaType)
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import Reservation from './modals/ReservationModal'
import Login from './modals/LoginModal'
import Modal from 'react-modal'
import * as ModalActions from '../actions/ModalActions'
import CancelReservation from './modals/CancelReservationModal'
import ExtendLoan from './modals/ExtendLoanModal'
import Registration from './modals/RegistrationModal'

const MODAL_COMPONENTS = {
  'CANCEL_RESERVATION': CancelReservation,
  'EXTEND_LOAN': ExtendLoan,
  'LOGIN': Login,
  'REGISTRATION': Registration,
  'RESERVATION': Reservation
}

class ModalRoot extends React.Component {
  render () {
    if (!this.props.modalType) {
      return null
    }
    const SpecificModal = MODAL_COMPONENTS[ this.props.modalType ]
    return (
      <Modal isOpen onRequestClose={this.props.modalActions.hideModal} className="modal-content"
             overlayClassName="modal-overlay">
        <SpecificModal {...this.props.modalProps} />
      </Modal>
    )
  }
}

ModalRoot.propTypes = {
  modalType: PropTypes.string,
  modalProps: PropTypes.object.isRequired,
  modalActions: PropTypes.object.isRequired
}

function mapStateToProps (state) {
  return {
    modalType: state.modal.modalType,
    modalProps: state.modal.modalProps
  }
}

function mapDispatchToProps (dispatch) {
  return {
    dispatch: dispatch,
    modalActions: bindActionCreators(ModalActions, dispatch)
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(ModalRoot)
<commit_msg>DEICH-12 Patron client - Add wraper class to modal div<commit_after>import React, { PropTypes } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import Reservation from './modals/ReservationModal'
import Login from './modals/LoginModal'
import Modal from 'react-modal'
import * as ModalActions from '../actions/ModalActions'
import CancelReservation from './modals/CancelReservationModal'
import ExtendLoan from './modals/ExtendLoanModal'
import Registration from './modals/RegistrationModal'

const MODAL_COMPONENTS = {
  'CANCEL_RESERVATION': CancelReservation,
  'EXTEND_LOAN': ExtendLoan,
  'LOGIN': Login,
  'REGISTRATION': Registration,
  'RESERVATION': Reservation
}

class ModalRoot extends React.Component {
  render () {
    if (!this.props.modalType) {
      return null
    }
    console.log('Thomas - '+this.props.modalType);
    const SpecificModal = MODAL_COMPONENTS[ this.props.modalType ]
    const ModalClasses = 'modal-overlay '.concat(this.props.modalType.toLowerCase(), '-modal-wrapper');
    return (
      <Modal isOpen onRequestClose={this.props.modalActions.hideModal} className="modal-content"
             overlayClassName={ModalClasses}>
        <SpecificModal {...this.props.modalProps} />
      </Modal>
    )
  }
}

ModalRoot.propTypes = {
  modalType: PropTypes.string,
  modalProps: PropTypes.object.isRequired,
  modalActions: PropTypes.object.isRequired
}

function mapStateToProps (state) {
  return {
    modalType: state.modal.modalType,
    modalProps: state.modal.modalProps
  }
}

function mapDispatchToProps (dispatch) {
  return {
    dispatch: dispatch,
    modalActions: bindActionCreators(ModalActions, dispatch)
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(ModalRoot)
<|endoftext|>


<commit_before>Modules.VERSION = '2.0.0';

this.__defineGetter__('DownloadsIndicatorView', function() { return window.DownloadsIndicatorView; });
this.__defineGetter__('DownloadsCommon', function() { return window.DownloadsCommon; });

this.downloadsIndicator = {
	notification: null,

	handleEvent: function(e) {
		switch(e.type) {
			case 'popupshowing':
				if(e.target.id == 'downloadsPanel') {
					Listeners.remove(window, 'popupshowing', this);
					Listeners.add(e.target, 'AskingForNodeOwner', this);
				}
				break;

			case 'AskingForNodeOwner':
				e.detail = 'downloads-button';
				e.stopPropagation();
				break;

			case 'FinishedSlimChromeWidth':
				if(this.notification) {
					DownloadsIndicatorView._showEventNotification(this.notification);
					this.notification = null;
				}
				break;
		}
	}
};

Modules.LOADMODULE = function() {
	Piggyback.add('downloadsIndicator', DownloadsIndicatorView, 'showEventNotification', function(aType) {
		// we're already opening to animate, so don't animate again, just replace the previous animation type
		if(downloadsIndicator.notification) {
			downloadsIndicator.notification = aType;
			return false;
		}

		// only pause animation if the button is in our toolbars
		for(let bar of bars) {
			if(this._initialized && DownloadsCommon.animateNotifications
			&& (isAncestor($('downloads-button'), bar) || isAncestor($('downloads-button'), bar._overflowTarget))) {
				// if toolbar is hidden, pause until it is shown
				if(!trueAttribute(bar, 'hover')) {
					downloadsIndicator.notification = aType;
					autoHide.initialShow(bar);
					return false;
				}

				// toolbar is not hidden, so keep showing it until animation is done at least
				autoHide.initialShow(bar);
			}
		}

		return true;
	}, Piggyback.MODE_BEFORE);

	// the downloadsPanel is only created when first called
	if($('downloadsPanel')) {
		Listeners.add($('downloadsPanel'), 'AskingForNodeOwner', downloadsIndicator);
	} else {
		Listeners.add(window, 'popupshowing', downloadsIndicator);
	}

	Listeners.add(window, 'FinishedSlimChromeWidth', downloadsIndicator);
};

Modules.UNLOADMODULE = function() {
	Listeners.remove(window, 'FinishedSlimChromeWidth', downloadsIndicator);
	Listeners.remove($('downloadsPanel'), 'AskingForNodeOwner', downloadsIndicator);
	Listeners.remove(window, 'popupshowing', downloadsIndicator);

	Piggyback.revert('downloadsIndicator', DownloadsIndicatorView, 'showEventNotification');
};
<commit_msg>bugfix issues with downloads indicator<commit_after>Modules.VERSION = '2.1.0';

this.__defineGetter__('DownloadsIndicatorView', function() { return window.DownloadsIndicatorView; });
this.__defineGetter__('DownloadsCommon', function() { return window.DownloadsCommon; });

this.downloadsIndicator = {
	notification: null,

	handleEvent: function(e) {
		switch(e.type) {
			case 'popupshowing':
				if(e.target.id == 'downloadsPanel') {
					Listeners.remove(window, 'popupshowing', this);
					Listeners.add(e.target, 'AskingForNodeOwner', this);
				}
				break;

			case 'AskingForNodeOwner':
				e.detail = 'downloads-button';
				e.stopPropagation();
				break;

			case 'transitionend':
				if(this.notification) {
					DownloadsIndicatorView._showEventNotification(this.notification);
					this.notification = null;
				}
				break;
		}
	},

	init: function() {
		Piggyback.add('downloadsIndicator', DownloadsIndicatorView, 'showEventNotification', (aType) => {
			// we're already opening to animate, so don't animate again, just replace the previous animation type
			if(this.notification) {
				this.notification = aType;
				return false;
			}

			// only pause animation if the button is in our toolbars
			for(let bar of bars) {
				if(bar._autohide
				&& DownloadsIndicatorView._initialized && DownloadsCommon.animateNotifications
				&& (isAncestor($('downloads-button'), bar) || isAncestor($('downloads-button'), bar._overflowTarget))) {
					// if toolbar is hidden, pause until it is shown
					if(!trueAttribute(bar, 'hover')) {
						var selfRemove = (e) => {
							bar._transition.remove(selfRemove);
							this.handleEvent(e);
						};
						bar._transition.add(selfRemove);

						this.notification = aType;
						autoHide.initialShow(bar);
						return false;
					}

					// toolbar is not hidden, so keep showing it until animation is done at least
					autoHide.initialShow(bar);

					break;
				}
			}

			return true;
		}, Piggyback.MODE_BEFORE);

		// the downloadsPanel is only created when first called
		if($('downloadsPanel')) {
			Listeners.add($('downloadsPanel'), 'AskingForNodeOwner', this);
		} else {
			Listeners.add(window, 'popupshowing', this);
		}
	},

	uninit: function() {
		Listeners.remove($('downloadsPanel'), 'AskingForNodeOwner', this);
		Listeners.remove(window, 'popupshowing', this);

		Piggyback.revert('downloadsIndicator', DownloadsIndicatorView, 'showEventNotification');
	}
};

Modules.LOADMODULE = function() {
	downloadsIndicator.init();
};

Modules.UNLOADMODULE = function() {
	downloadsIndicator.uninit();
};
<|endoftext|>


<commit_before>var router = require('express').Router(),
	async = require('async'),
	Game = require('../../models/game'),
	Group = require('../../models/group'),
	Release = require('../../models/release'),
	response = require('../../helpers/response'),
    log = require('../../helpers/logger');

router.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

router.post('/:slug', function(req, res)
{
	req.checkBody('status', 'Status must be one of: "dev", "qa", "stage", "prod"').isStatus();
	req.checkBody('commitId', 'Commit ID must be a valid Git commit has').isCommit();
	req.checkBody('token', 'Token is required').isToken();
	req.checkBody('branch', 'Branch is required and must be a string').isBranch();

	if (req.body.verison)
		req.checkBody('version', 'Not a properly formatted Semantic Version').isSemver();

	var errors = req.validationErrors();

	if (errors)
	{
		log.error("Validation error adding release from token " + req.body.token);
		log.error(errors);

		if (req.body.redirect)
		{
			log.warn('Redirecting to ' + req.body.redirect);
			res.redirect(req.body.redirect);
		}
		else
		{
			res.send({
				success:false,
				data: errors
			});
		}
		return;
	}

	async.waterfall([
		function(done)
		{
			Game.getBySlugOrBundleId(req.params.slug, done).select('-thumbnail');
		},
		function(game, done)
		{
			game.hasPermission(req.body.token, done);
		},
		function(game, done)
		{
			// Better handling of a unique commitId
			Release.getByCommitId(req.body.commitId, function(err, release)
			{
				if (!!req.body.warnUniqueCommit && !!release)
				{
					done('The Commit ID is already taken');
				}
				else
				{
					done(err, game, release);
				}
			});
		},
		function(game, release, done)
		{
			// If we already have a release
			// lets just modify the updated timestamp
			// and leave everything else the same
			if (release)
			{
				release.updated = Date.now();
				release.save(function(err)
				{
					done(err, game);
				});
				return;
			}
			var values = Object.assign({}, values, req.body);
			values.game = game._id;
			delete values.token;
			values.created = values.updated = Date.now();

			// If the capabilities aren't set, inherit the
			// default game capabilities
			if (!values.capabilities)
			{
				values.capabilities = game.capabilities.toObject();
			}
			// Or else update the game defaults
			else
			{
				Object.assign(
					game.capabilities,
					Object.assign({}, values.capabilities)
				);
				game.save();
			}
			var newRelease = new Release(values);
			newRelease.save(function(err, release)
			{
				if (err) return done(err, game);

				game.releases.push(release._id);
				game.updated = Date.now();
				game.save(function(err, result)
				{
					done(err, game);
				});
			});
		},
		function(game, done)
		{
			Release.getByIdsAndStatus(game.releases, "dev", function(err, releases)
			{
				var maxDevReleases = CONFIGURATION.maxDevReleases;
				if (releases.length > maxDevReleases)
				{
					let toSave = [];
					while (toSave.length < maxDevReleases){
						toSave.push(releases.pop());
					}
					releases.forEach(function(release)
					{
						Release.removeById(release._id, function(){});
					});
				}
				done(null, game);
			});
		}
	],
	function(err, result)
	{
		if (err)
		{
			if (req.body.redirect)
			{
				res.redirect(req.body.redirect);
			}
			else
			{
				log.error('Unable to add the release');
				log.error(err);

				res.status(500).send({
					success:false,
					data: 'Unable to add the release'
				});
			}
			return;
		}

		if (req.body.redirect)
		{
			res.redirect(req.body.redirect);
		}
		else
		{
			res.send({
				success: true,
				data: result
			});
		}
	});
});

router.get('/:slugOrBundleId', function(req, res)
{
	req.checkQuery('token').optional().isToken();
	req.checkQuery('status').optional().isStatus();
	req.checkQuery('commitId').optional().isCommit();
	req.checkQuery('version').optional().isSemver();
	if (req.validationErrors())
	{
		return response.call(res, "Invalid arguments");
	}
	Release.getByGame(
		req.params.slugOrBundleId,
		{
			version: req.query.version,
			commitId: req.query.commitId,
			archive: req.query.archive,
			status: req.query.status || 'prod',
			token: req.query.token,
			debug: req.query.debug
		},
		response.bind(res)
	);
});

module.exports = router;
<commit_msg>Moving some logging around again<commit_after>var router = require('express').Router(),
	async = require('async'),
	Game = require('../../models/game'),
	Group = require('../../models/group'),
	Release = require('../../models/release'),
	response = require('../../helpers/response'),
    log = require('../../helpers/logger');

router.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

router.post('/:slug', function(req, res)
{
	req.checkBody('status', 'Status must be one of: "dev", "qa", "stage", "prod"').isStatus();
	req.checkBody('commitId', 'Commit ID must be a valid Git commit has').isCommit();
	req.checkBody('token', 'Token is required').isToken();
	req.checkBody('branch', 'Branch is required and must be a string').isBranch();

	if (req.body.verison)
		req.checkBody('version', 'Not a properly formatted Semantic Version').isSemver();

	var errors = req.validationErrors();

	if (errors)
	{
		log.error("Validation error adding release from token " + req.body.token);
		log.error(errors);

		if (req.body.redirect)
		{
			log.warn('Redirecting to ' + req.body.redirect);
			res.redirect(req.body.redirect);
		}
		else
		{
			res.send({
				success:false,
				data: errors
			});
		}
		return;
	}

	async.waterfall([
		function(done)
		{
			Game.getBySlugOrBundleId(req.params.slug, done).select('-thumbnail');
		},
		function(game, done)
		{
			game.hasPermission(req.body.token, done);
		},
		function(game, done)
		{
			// Better handling of a unique commitId
			Release.getByCommitId(req.body.commitId, function(err, release)
			{
				if (!!req.body.warnUniqueCommit && !!release)
				{
					done('The Commit ID is already taken');
				}
				else
				{
					done(err, game, release);
				}
			});
		},
		function(game, release, done)
		{
			// If we already have a release
			// lets just modify the updated timestamp
			// and leave everything else the same
			if (release)
			{
				release.updated = Date.now();
				release.save(function(err)
				{
					done(err, game);
				});
				return;
			}
			var values = Object.assign({}, values, req.body);
			values.game = game._id;
			delete values.token;
			values.created = values.updated = Date.now();

			// If the capabilities aren't set, inherit the
			// default game capabilities
			if (!values.capabilities)
			{
				values.capabilities = game.capabilities.toObject();
			}
			// Or else update the game defaults
			else
			{
				Object.assign(
					game.capabilities,
					Object.assign({}, values.capabilities)
				);
				game.save();
			}
			var newRelease = new Release(values);
			newRelease.save(function(err, release)
			{
				if (err) return done(err, game);

				game.releases.push(release._id);
				game.updated = Date.now();
				game.save(function(err, result)
				{
					done(err, game);
				});
			});
		},
		function(game, done)
		{
			Release.getByIdsAndStatus(game.releases, "dev", function(err, releases)
			{
				var maxDevReleases = CONFIGURATION.maxDevReleases;
				if (releases.length > maxDevReleases)
				{
					let toSave = [];
					while (toSave.length < maxDevReleases){
						toSave.push(releases.pop());
					}
					releases.forEach(function(release)
					{
						Release.removeById(release._id, function(){});
					});
				}
				done(null, game);
			});
		}
	],
	function(err, result)
	{
		if (err)
		{
			log.error('Unable to add the release for token ' + req.body.token);
			log.error(err);

			if (req.body.redirect)
			{
				res.redirect(req.body.redirect);
			}
			else
			{
				res.status(500).send({
					success:false,
					data: 'Unable to add the release'
				});
			}
			return;
		}

		if (req.body.redirect)
		{
			res.redirect(req.body.redirect);
		}
		else
		{
			res.send({
				success: true,
				data: result
			});
		}
	});
});

router.get('/:slugOrBundleId', function(req, res)
{
	req.checkQuery('token').optional().isToken();
	req.checkQuery('status').optional().isStatus();
	req.checkQuery('commitId').optional().isCommit();
	req.checkQuery('version').optional().isSemver();
	if (req.validationErrors())
	{
		return response.call(res, "Invalid arguments");
	}
	Release.getByGame(
		req.params.slugOrBundleId,
		{
			version: req.query.version,
			commitId: req.query.commitId,
			archive: req.query.archive,
			status: req.query.status || 'prod',
			token: req.query.token,
			debug: req.query.debug
		},
		response.bind(res)
	);
});

module.exports = router;
<|endoftext|>


<commit_before>function submitComment() {
  var text = escapeHtml(document.getElementById("comment-text").value);
  var comments = document.getElementById("comments").innerHTML;
  var comment = '
' + text + '
';
  document.getElementById("comments").innerHTML = comment + comments;
  document.getElementById("comment-text").value = "";

  var href = window.location.href;
  var sha = href.substring(href.lastIndexOf("/") + 1);
  var httpRequest = new XMLHttpRequest();
  httpRequest.open('POST', 'https://gitshame.xyz/post');
  httpRequest.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  httpRequest.send(JSON.stringify({sha: sha, post: text}));
}

function escapeHtml(str) {
  var div = document.createElement('div');
  div.appendChild(document.createTextNode(str));
  return div.innerHTML;
};

function unescapeHtml(escapedStr) {
  var div = document.createElement('div');
  div.innerHTML = escapedStr;
  var child = div.childNodes[0];
  return child ? child.nodeValue : '';
};

function openModal() {
  var el = document.getElementById("modal");
  el.style.visibility = "visible";
}

function closeModal() {
  var el = document.getElementById("modal");
  el.style.visibility = "hidden";
}

function closeModalEvent(event) {
  if (event.target.id == "modal") {
    closeModal();
  }
}

function shame() {
  var link = document.getElementById("link").value;
  var httpRequest = new XMLHttpRequest();
  httpRequest.open('POST', 'https://gitshame.xyz/pygmentize');
  httpRequest.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  httpRequest.send(JSON.stringify({github_link: link}));
  closeModal();
}

function githubLogin(state) {
  var url = 'https://github.com/login/oauth/authorize'
  url += '?' + 'client_id=' + '6de9e53b515a73893674' + '&state=' + state + '&redirect=' + 'https://gitshame.xyz/login'

  var httpRequest = new XMLHttpRequest();
  httpRequest.open('GET', url);
  httpRequest.send();
}
<commit_msg>redirect to github oauth<commit_after>function submitComment() {
  var text = escapeHtml(document.getElementById("comment-text").value);
  var comments = document.getElementById("comments").innerHTML;
  var comment = '
' + text + '
';
  document.getElementById("comments").innerHTML = comment + comments;
  document.getElementById("comment-text").value = "";

  var href = window.location.href;
  var sha = href.substring(href.lastIndexOf("/") + 1);
  var httpRequest = new XMLHttpRequest();
  httpRequest.open('POST', 'https://gitshame.xyz/post');
  httpRequest.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  httpRequest.send(JSON.stringify({sha: sha, post: text}));
}

function escapeHtml(str) {
  var div = document.createElement('div');
  div.appendChild(document.createTextNode(str));
  return div.innerHTML;
};

function unescapeHtml(escapedStr) {
  var div = document.createElement('div');
  div.innerHTML = escapedStr;
  var child = div.childNodes[0];
  return child ? child.nodeValue : '';
};

function openModal() {
  var el = document.getElementById("modal");
  el.style.visibility = "visible";
}

function closeModal() {
  var el = document.getElementById("modal");
  el.style.visibility = "hidden";
}

function closeModalEvent(event) {
  if (event.target.id == "modal") {
    closeModal();
  }
}

function shame() {
  var link = document.getElementById("link").value;
  var httpRequest = new XMLHttpRequest();
  httpRequest.open('POST', 'https://gitshame.xyz/pygmentize');
  httpRequest.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  httpRequest.send(JSON.stringify({github_link: link}));
  closeModal();
}

function githubLogin(state) {
  var url = 'https://github.com/login/oauth/authorize'
  url += '?' + 'client_id=' + '6de9e53b515a73893674' + '&state=' + state + '&redirect=' + 'https://gitshame.xyz/login'

  window.location = url
}
<|endoftext|>


<commit_before>
// sfw_dom.js

function init_SFW_DOM()
{
   set_missing_doc_props();

   // SFW.get_page_xoffset() AND
   // SFW.get_page_yoffset()
   prepare_page_offset_funcs();
   SFW.get_doc_offset       = _get_doc_offset;
   SFW.get_relative_offset  = _get_relative_offset;

   SFW.el_name              = _el_name;
   SFW.find_child_matches   = _find_child_matches;
   SFW.first_child_element  = _first_child_element;
   SFW.next_sibling_element = _next_sibling_element;

   // Sets SFW.get_page_xoffset and SFW.get_page_yoffset
   function prepare_page_offset_funcs()
   {
      if ('pageXOffset' in window)
      {
         SFW.get_page_xoffset = function()  { return window.pageXOffset; };
         SFW.get_page_yoffset = function()  { return window.pageYOffset; };
      }
      else if ('body' in document && 'scrollLeft' in document.body)
      {
         SFW.get_page_xoffset = function()  { return document.body.scrollLeft; };
         SFW.get_page_yoffset = function()  { return document.body.scrollTop;  };
      }
      else
      {
         SFW.get_page_xoffset = SFW.set_page_xoffset = void(0);
         SFW.get_page_yoffset = SFW.set_page_yoffset = void(0);
      }

      SFW.set_page_xoffset = function(v) { document.documentElement.scrollLeft=v; };
      SFW.set_page_yoffset = function(v) { document.documentElement.scrollTop=v; };

      SFW.get_page_offset = function()
      {
         return { osx:SFW.get_page_xoffset(),
                  osy:SFW.get_page_yoffset() };
      };

      SFW.set_page_offset = function(o)
      {
         window.scrollTo(o.osx, o.osy);
      };
   };

   function _get_doc_offset(el)
   {
      if (el===null)
         return {left:0, top:0};

      var os = el.offsetParent ? _get_doc_offset(el.offsetParent) : {left:0,top:0};
      return {left:os.left+el.offsetLeft, top:os.top+el.offsetTop };
   }

   function _get_relative_offset(target, ref)
   {
      var ost = _get_doc_offset(target);
      var osr = _get_doc_offset(ref);
      ost.left -= osr.left;
      ost.top -= ost.top;
      return ost;
   }

   function _el_name(el)
   {
      if ("localName" in el)
         _el_name = function(e) { return e.localName; };
      else if ("baseName" in el)
         _el_name = function(e) { return e.baseName; };
      else
         _el_name = void(0);

      SFW.el_name = _el_name;
      return _el_name(el);
   }

   function _find_child_matches(parent, tag_or_func, first_only, recursive)
   {
      var compfunc;
      if (typeof(tag_or_func)=="function")
         compfunc = tag_or_func;
      else
         compfunc = function(el) {
            return el.nodeType==1 && el.tagName.toLowerCase()==tag_or_func;
         };

      var rval = [];
      var node = parent ? parent.firstChild : null;
      while (node)
      {
         if (compfunc(node))
         {
            if (first_only)
               return node;
            else
               rval.push(node);
         }
         else if (recursive)
         {
            var recur =_find_child_matches(node, compfunc, first_only, true);
            if (recur)
            {
               if (first_only)
                  return recur;
               else
                  rval = rval.concat(recur);
            }
         }
         node = node.nextSibling;
      }
      return rval.length ? rval : null;
   }

   function _first_child_element(el)
   {
      var n = el ? el.firstChild : null;
      if (n)
      {
         if (n.nodeType==1)
            return n;
         else
            return _next_sibling_element(n);
      }
      else
         return null;
   }

   function _next_sibling_element(el)
   {
      if ("nextElementSibling" in el)
         _next_sibling_element = function(e) { return e.nextElementSibling; };
      else
      {
         _next_sibling_element = function(e)
         {
            var n = e.nextSibling;
            while (n)
            {
               if (n.nodeType==1)
                  return n;
               else
                  n = n.nextSibling;
            }
            return null;
         };
      }

      // Also reset the member function, now that the function has been reset:
      SFW.next_sibling_element = _next_sibling_element;
      return _next_sibling_element(el);
   }

   function set_missing_doc_props()
   {
      var html = document.documentElement;
      if (!("head" in document))
         document.head = _find_child_matches(html, "head", true);
      if (!("body" in document))
         document.body = _find_child_matches(html, "body", true);
   }
}
<commit_msg>Save nextsibling for find_child_matches() in case the compare function removes the element.<commit_after>
// sfw_dom.js

function init_SFW_DOM()
{
   set_missing_doc_props();

   // SFW.get_page_xoffset() AND
   // SFW.get_page_yoffset()
   prepare_page_offset_funcs();
   SFW.get_doc_offset       = _get_doc_offset;
   SFW.get_relative_offset  = _get_relative_offset;

   SFW.el_name              = _el_name;
   SFW.find_child_matches   = _find_child_matches;
   SFW.first_child_element  = _first_child_element;
   SFW.next_sibling_element = _next_sibling_element;

   // Sets SFW.get_page_xoffset and SFW.get_page_yoffset
   function prepare_page_offset_funcs()
   {
      if ('pageXOffset' in window)
      {
         SFW.get_page_xoffset = function()  { return window.pageXOffset; };
         SFW.get_page_yoffset = function()  { return window.pageYOffset; };
      }
      else if ('body' in document && 'scrollLeft' in document.body)
      {
         SFW.get_page_xoffset = function()  { return document.body.scrollLeft; };
         SFW.get_page_yoffset = function()  { return document.body.scrollTop;  };
      }
      else
      {
         SFW.get_page_xoffset = SFW.set_page_xoffset = void(0);
         SFW.get_page_yoffset = SFW.set_page_yoffset = void(0);
      }

      SFW.set_page_xoffset = function(v) { document.documentElement.scrollLeft=v; };
      SFW.set_page_yoffset = function(v) { document.documentElement.scrollTop=v; };

      SFW.get_page_offset = function()
      {
         return { osx:SFW.get_page_xoffset(),
                  osy:SFW.get_page_yoffset() };
      };

      SFW.set_page_offset = function(o)
      {
         window.scrollTo(o.osx, o.osy);
      };
   };

   function _get_doc_offset(el)
   {
      if (el===null)
         return {left:0, top:0};

      var os = el.offsetParent ? _get_doc_offset(el.offsetParent) : {left:0,top:0};
      return {left:os.left+el.offsetLeft, top:os.top+el.offsetTop };
   }

   function _get_relative_offset(target, ref)
   {
      var ost = _get_doc_offset(target);
      var osr = _get_doc_offset(ref);
      ost.left -= osr.left;
      ost.top -= ost.top;
      return ost;
   }

   function _el_name(el)
   {
      if ("localName" in el)
         _el_name = function(e) { return e.localName; };
      else if ("baseName" in el)
         _el_name = function(e) { return e.baseName; };
      else
         _el_name = void(0);

      SFW.el_name = _el_name;
      return _el_name(el);
   }

   function _find_child_matches(parent, tag_or_func, first_only, recursive)
   {
      var compfunc;
      if (typeof(tag_or_func)=="function")
         compfunc = tag_or_func;
      else
         compfunc = function(el) {
            return el.nodeType==1 && el.tagName.toLowerCase()==tag_or_func;
         };

      var rval = [];
      var node = parent ? parent.firstChild : null;
      while (node)
      {
         var nextnode = node.nextSibling;
         if (compfunc(node))
         {
            if (first_only)
               return node;
            else
               rval.push(node);
         }
         else if (recursive)
         {
            var recur =_find_child_matches(node, compfunc, first_only, true);
            if (recur)
            {
               if (first_only)
                  return recur;
               else
                  rval = rval.concat(recur);
            }
         }
         node = nextnode;
      }
      return rval.length ? rval : null;
   }

   function _first_child_element(el)
   {
      var n = el ? el.firstChild : null;
      if (n)
      {
         if (n.nodeType==1)
            return n;
         else
            return _next_sibling_element(n);
      }
      else
         return null;
   }

   function _next_sibling_element(el)
   {
      if ("nextElementSibling" in el)
         _next_sibling_element = function(e) { return e.nextElementSibling; };
      else
      {
         _next_sibling_element = function(e)
         {
            var n = e.nextSibling;
            while (n)
            {
               if (n.nodeType==1)
                  return n;
               else
                  n = n.nextSibling;
            }
            return null;
         };
      }

      // Also reset the member function, now that the function has been reset:
      SFW.next_sibling_element = _next_sibling_element;
      return _next_sibling_element(el);
   }

   function set_missing_doc_props()
   {
      var html = document.documentElement;
      if (!("head" in document))
         document.head = _find_child_matches(html, "head", true);
      if (!("body" in document))
         document.body = _find_child_matches(html, "body", true);
   }
}
<|endoftext|>


<commit_before>import { promise } from "lively.lang";
import { addOrChangeCSSDeclaration, addOrChangeLinkedCSS } from "./dom-helper.js";
import { defaultStyle, defaultAttributes, render } from "./morphic-default.js";
import {h} from "virtual-dom";

const defaultCSS = `

.no-html-select {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.halo-guide {
  -webkit-animation: fadein .5s;
}

.smooth-extent {
  -webkit-transition: width .2s, height .2s, transform .2s;
}

.halo-mesh {
  background-color:transparent;
  background-image: linear-gradient(rgba(0,0,0,.1) 2px, transparent 2px),
  linear-gradient(90deg, rgba(0,0,0,.1) 2px, transparent 2px),
  linear-gradient(rgba(0,0,0,.1) 1px, transparent 1px),
  linear-gradient(90deg, rgba(0,0,0,.1) 1px, transparent 1px);
  background-size:100px 100px, 100px 100px, 10px 10px, 10px 10px;
  background-position:-2px -2px, -2px -2px, -1px -1px, -1px -1px;
   -webkit-animation: fadein .5s;
}

.morph {
  /*for aliasing issue in chrome: http://stackoverflow.com/questions/6492027/css-transform-jagged-edges-in-chrome*/
  -webkit-backface-visibility: hidden;

  /*include border size in extent of element*/
  box-sizing: border-box;

  /*don't use dom selection on morphs*/
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.hand {
  z-index: 1;
}

.halo {
  z-index: 2;
}

.center-text {
	text-align: center;
	vertical-align: middle;
}

.halo-item {
  /*FIXME: we shouldn't need to hardcode the size...*/
	line-height: 24px !important;
	text-align: center;
	vertical-align: middle;
}

@-webkit-keyframes fadein { /* Safari and Chrome */
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}

`;

export class Renderer {

  static default() { return this._default || new this() }

  constructor(world, rootNode, domEnvironment) {
    if (!world || !world.isMorph)
      throw new Error(`Trying to initialize renderer with an invalid world morph: ${world}`)
    if (!rootNode || !("nodeType" in rootNode))
      throw new Error(`Trying to initialize renderer with an invalid root node: ${rootNode}`)
    if (!domEnvironment) {
      var doc = rootNode.ownerDocument;
      domEnvironment = {window: System.global, document: doc};
    }
    this.worldMorph = world;
    world._isWorld = true; // for world() method
    world._renderer = this;
    this.rootNode = rootNode;
    this.domNode = null;
    this.domEnvironment = domEnvironment;
    this.renderMap = new WeakMap();
    this.renderWorldLoopProcess = null;
    FontMetric.initDefault(domEnvironment.document);
  }

  clear() {
    this.stopRenderWorldLoop();
    this.domNode && this.domNode.parentNode.removeChild(this.domNode);
    this.domNode = null;
    this.renderMap = new WeakMap();
    FontMetric.removeDefault();
  }

  ensureDefaultCSS() {
    return promise.waitFor(3000, () => this.domNode.ownerDocument)
      .then(doc => Promise.all([
        addOrChangeCSSDeclaration("lively-morphic-css", defaultCSS, doc),
        addOrChangeLinkedCSS("lively-font-awesome", System.decanonicalize("lively.morphic/assets/font-awesome/css/font-awesome.css"), doc)]));
  }

  startRenderWorldLoop() {
    this.worldMorph.renderAsRoot(this);
    this.renderWorldLoopProcess = this.domEnvironment.window.requestAnimationFrame(() =>
      this.startRenderWorldLoop());
    return this;
  }

  stopRenderWorldLoop() {
    this.domEnvironment.window.cancelAnimationFrame(this.renderWorldLoopProcess);
    this.renderWorldLoopProcess = null;
  }

  getNodeForMorph(morph) {
    // Hmm, this also finds dom nodes not associated with this renderer, its
    // domNode... Is this a problem?
    // return this.domNode.ownerDocument.getElementById(morph.id);

    // test, for scoped lookup, fixing the issue mentioned above
    return this.domNode ? this.domNode.querySelector("#" + morph.id) : null;
  }

  getMorphForNode(node) {
    return this.worldMorph ?
      this.worldMorph.withAllSubmorphsDetect(morph => morph.id === node.id) :
      null;
  }

  render(x) {
    if (!x.needsRerender()) {
      var rendered = this.renderMap.get(x);
      if (rendered) return rendered;
    }
    x.aboutToRender();

    var tree = x.render(this);
    this.renderMap.set(x, tree);
    return tree;
  }

  renderMorph(morph) {
    return h("div", {
      ...defaultAttributes(morph),
      style: defaultStyle(morph)
    }, morph.submorphs.map(m => this.render(m)));
  }

  renderText(text) {
    return h("textarea", {
      ...defaultAttributes(text),
      value: text.textString,
      readOnly: text.readOnly,
      placeholder: text.placeholder,
      ...(text._needsSelect && {
        selectionStart: text._selection.start,
        selectionEnd: text._selection.end
      }),
      style: {
        ...defaultStyle(text),
        resize: "none",
        border: 0,
        "white-space": "nowrap",
        padding: "0px",
        "font-family": text.fontFamily,
        "font-size": text.fontSize + "px",
        "color": String(text.fontColor)
      }
    });
  }

  renderImage(image) {
    return h("div", {...defaultAttributes(image),
                     style: defaultStyle(image)},
                    [h("img", {src: image.imageUrl,
                               draggable: false,
                               style: {
                                  "pointer-events": "none",
                                  position: "absolute",
                                  width: "100%", height: "100%"}}),
                    h("div", image.submorphs.map(m => this.render(m)))]);
  }

  renderPath(path) {
    const {transform, transformOrigin, position, WebkitFilter,
           display} = defaultStyle(path),
          {width, height} = path.innerBounds(),
          vertices = renderVertices(path),
          defs = path.gradient && renderGradient(path);
    return h("div", {...defaultAttributes(path),
                     style: {transform, transformOrigin, position,
                             width: width + 'px', height: height + 'px',
                             display, WebkitFilter, "pointer-events": "auto"}},
              h("svg", {namespace: "http://www.w3.org/2000/svg",
                        style: {position: "absolute", "pointer-events": "none"},
                        attributes:
                         {width, height, "viewBox": [-2,-2,width,height].join(" "),
                        ...(path.borderStyle == "dashed" && {"stroke-dasharray": "7 4"})}},
                  [defs].concat(vertices)));
  }
}

function renderVertices(path) {
  var vertices = [];
  for (var i = 0; i < path.vertices.length - 1; i++) {
    var {x: x1, y: y1} = path.vertices[i],
        {x: x2, y: y2} = path.vertices[i+1];
    vertices.push(h("path",
                {namespace: "http://www.w3.org/2000/svg",
                 attributes:
                  {"sroke-width": path.borderWidth,
                   stroke: path.gradient ? "url(#" + path.id + ")" : path.borderColor,
                 d: "M"+x1+","+y1+" "+"L"+x2+","+y2}}));
  }
  return vertices;
}

function renderGradient(path) {
  return h("defs", {namespace: "http://www.w3.org/2000/svg"},
                h("linearGradient", {namespace: "http://www.w3.org/2000/svg",
                                     attributes: {id: path.id,
                                                  gradientUnits: "userSpaceOnUse"}
                                     },
                    path.gradient.map(([k, c]) =>
                        h("stop",
                            {namespace: "http://www.w3.org/2000/svg",
                              attributes:
                                {offset: (k * 100) + "%",
                                 "stop-color": c}}))));
}

export class FontMetric {

  static default() {
    if (!this._fontMetric)
      throw new Error("FontMetric has not yet been initialized!")
    return this._fontMetric;
  }

  static initDefault(doc = typeof document !== "undefined" ? document : null) {
    if (!this._fontMetric) {
      this._fontMetric = new FontMetric();
      this._fontMetric.install(doc, doc.body);
    }
  }

  static removeDefault() {
    if (this._fontMetric) {
      this._fontMetric.uninstall();
      this._fontMetric = null;
    }
  }

  constructor() {
    this.charMap = [];
    this.parentElement = null;
    this.element = null;
  }

  install(doc, parentEl) {
    this.parentElement = parentEl;
    this.element = doc.createElement("div");
    this.setMeasureNodeStyles(this.element.style, true);
    this.parentElement.appendChild(this.element);
  }

  uninstall() {
    if (this.element) {
      this.parentElement.removeChild(this.element);
      this.parentElement = null;
      this.element = null;
    }
  }

  setMeasureNodeStyles(style, isRoot) {
    style.width = style.height = "auto";
    style.left = style.top = "0px";
    style.visibility = "hidden";
    style.position = "absolute";
    style.whiteSpace = "pre";
    style.font = "inherit";
    style.overflow = isRoot ? "hidden" : "visible";
  }

  measure(fontFamily, fontSize, char) {
    var rect = null;
    this.element.innerHTML = char;
    this.element.style.fontFamily = fontFamily;
    this.element.style.fontSize = fontSize + "px";
    try {
      rect = this.element.getBoundingClientRect();
    } catch(e) {
      rect = {width: 0, height:0};
    };
    return {
      height: rect.height,
      width: rect.width
    }
  }

  sizeFor(fontFamily, fontSize, char) {
    if (char.length > 1)
      return this.sizeForStr(fontFamily, fontSize, char);

    if (!this.charMap[fontFamily]) {
      this.charMap[fontFamily] = [];
    }
    if (!this.charMap[fontFamily][fontSize]) {
      this.charMap[fontFamily][fontSize] = [];
    }
    if (!this.charMap[fontFamily][fontSize][char])
      this.charMap[fontFamily][fontSize][char] = this.measure(fontFamily, fontSize, char);
    return this.charMap[fontFamily][fontSize][char];
  }

  sizeForStr(fontFamily, fontSize, str) {
    var height = 0, width = 0;
    for (let line of str.split('\n')) {
      let lineHeight = 0, lineWidth = 0;
      for (let char of line.split('')) {
        let { height: charHeight, width: charWidth } = this.sizeFor(fontFamily, fontSize, char);
        if (charHeight > lineHeight) lineHeight = charHeight;
        lineWidth += charWidth;
      }
      if (lineWidth > width) width = lineWidth;
      height += lineHeight || this.sizeFor(fontFamily, fontSize, " ").height;
    }
    return { height: height, width: width };
  }

  asciiSizes(fontFamily, fontSize) {
    var result = {};
    for (var i = 32; i <= 126; i++) {
      var char = String.fromCharCode(i);
      result[char] = this.sizeFor(fontFamily, fontSize, char)
    }
    return result;
  }
}
<commit_msg>reduce animation time for windows<commit_after>import { promise } from "lively.lang";
import { addOrChangeCSSDeclaration, addOrChangeLinkedCSS } from "./dom-helper.js";
import { defaultStyle, defaultAttributes, render } from "./morphic-default.js";
import {h} from "virtual-dom";

const defaultCSS = `

.no-html-select {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.halo-guide {
  -webkit-animation: fadein .5s;
}

.smooth-extent {
  -webkit-transition: width .15s, height .15s, transform .15s;
}

.halo-mesh {
  background-color:transparent;
  background-image: linear-gradient(rgba(0,0,0,.1) 2px, transparent 2px),
  linear-gradient(90deg, rgba(0,0,0,.1) 2px, transparent 2px),
  linear-gradient(rgba(0,0,0,.1) 1px, transparent 1px),
  linear-gradient(90deg, rgba(0,0,0,.1) 1px, transparent 1px);
  background-size:100px 100px, 100px 100px, 10px 10px, 10px 10px;
  background-position:-2px -2px, -2px -2px, -1px -1px, -1px -1px;
   -webkit-animation: fadein .5s;
}

.morph {
  /*for aliasing issue in chrome: http://stackoverflow.com/questions/6492027/css-transform-jagged-edges-in-chrome*/
  -webkit-backface-visibility: hidden;

  /*include border size in extent of element*/
  box-sizing: border-box;

  /*don't use dom selection on morphs*/
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.hand {
  z-index: 1;
}

.halo {
  z-index: 2;
}

.center-text {
	text-align: center;
	vertical-align: middle;
}

.halo-item {
  /*FIXME: we shouldn't need to hardcode the size...*/
	line-height: 24px !important;
	text-align: center;
	vertical-align: middle;
}

@-webkit-keyframes fadein { /* Safari and Chrome */
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}

`;

export class Renderer {

  static default() { return this._default || new this() }

  constructor(world, rootNode, domEnvironment) {
    if (!world || !world.isMorph)
      throw new Error(`Trying to initialize renderer with an invalid world morph: ${world}`)
    if (!rootNode || !("nodeType" in rootNode))
      throw new Error(`Trying to initialize renderer with an invalid root node: ${rootNode}`)
    if (!domEnvironment) {
      var doc = rootNode.ownerDocument;
      domEnvironment = {window: System.global, document: doc};
    }
    this.worldMorph = world;
    world._isWorld = true; // for world() method
    world._renderer = this;
    this.rootNode = rootNode;
    this.domNode = null;
    this.domEnvironment = domEnvironment;
    this.renderMap = new WeakMap();
    this.renderWorldLoopProcess = null;
    FontMetric.initDefault(domEnvironment.document);
  }

  clear() {
    this.stopRenderWorldLoop();
    this.domNode && this.domNode.parentNode.removeChild(this.domNode);
    this.domNode = null;
    this.renderMap = new WeakMap();
    FontMetric.removeDefault();
  }

  ensureDefaultCSS() {
    return promise.waitFor(3000, () => this.domNode.ownerDocument)
      .then(doc => Promise.all([
        addOrChangeCSSDeclaration("lively-morphic-css", defaultCSS, doc),
        addOrChangeLinkedCSS("lively-font-awesome", System.decanonicalize("lively.morphic/assets/font-awesome/css/font-awesome.css"), doc)]));
  }

  startRenderWorldLoop() {
    this.worldMorph.renderAsRoot(this);
    this.renderWorldLoopProcess = this.domEnvironment.window.requestAnimationFrame(() =>
      this.startRenderWorldLoop());
    return this;
  }

  stopRenderWorldLoop() {
    this.domEnvironment.window.cancelAnimationFrame(this.renderWorldLoopProcess);
    this.renderWorldLoopProcess = null;
  }

  getNodeForMorph(morph) {
    // Hmm, this also finds dom nodes not associated with this renderer, its
    // domNode... Is this a problem?
    // return this.domNode.ownerDocument.getElementById(morph.id);

    // test, for scoped lookup, fixing the issue mentioned above
    return this.domNode ? this.domNode.querySelector("#" + morph.id) : null;
  }

  getMorphForNode(node) {
    return this.worldMorph ?
      this.worldMorph.withAllSubmorphsDetect(morph => morph.id === node.id) :
      null;
  }

  render(x) {
    if (!x.needsRerender()) {
      var rendered = this.renderMap.get(x);
      if (rendered) return rendered;
    }
    x.aboutToRender();

    var tree = x.render(this);
    this.renderMap.set(x, tree);
    return tree;
  }

  renderMorph(morph) {
    return h("div", {
      ...defaultAttributes(morph),
      style: defaultStyle(morph)
    }, morph.submorphs.map(m => this.render(m)));
  }

  renderText(text) {
    return h("textarea", {
      ...defaultAttributes(text),
      value: text.textString,
      readOnly: text.readOnly,
      placeholder: text.placeholder,
      ...(text._needsSelect && {
        selectionStart: text._selection.start,
        selectionEnd: text._selection.end
      }),
      style: {
        ...defaultStyle(text),
        resize: "none",
        border: 0,
        "white-space": "nowrap",
        padding: "0px",
        "font-family": text.fontFamily,
        "font-size": text.fontSize + "px",
        "color": String(text.fontColor)
      }
    });
  }

  renderImage(image) {
    return h("div", {...defaultAttributes(image),
                     style: defaultStyle(image)},
                    [h("img", {src: image.imageUrl,
                               draggable: false,
                               style: {
                                  "pointer-events": "none",
                                  position: "absolute",
                                  width: "100%", height: "100%"}}),
                    h("div", image.submorphs.map(m => this.render(m)))]);
  }

  renderPath(path) {
    const {transform, transformOrigin, position, WebkitFilter,
           display} = defaultStyle(path),
          {width, height} = path.innerBounds(),
          vertices = renderVertices(path),
          defs = path.gradient && renderGradient(path);
    return h("div", {...defaultAttributes(path),
                     style: {transform, transformOrigin, position,
                             width: width + 'px', height: height + 'px',
                             display, WebkitFilter, "pointer-events": "auto"}},
              h("svg", {namespace: "http://www.w3.org/2000/svg",
                        style: {position: "absolute", "pointer-events": "none"},
                        attributes:
                         {width, height, "viewBox": [-2,-2,width,height].join(" "),
                        ...(path.borderStyle == "dashed" && {"stroke-dasharray": "7 4"})}},
                  [defs].concat(vertices)));
  }
}

function renderVertices(path) {
  var vertices = [];
  for (var i = 0; i < path.vertices.length - 1; i++) {
    var {x: x1, y: y1} = path.vertices[i],
        {x: x2, y: y2} = path.vertices[i+1];
    vertices.push(h("path",
                {namespace: "http://www.w3.org/2000/svg",
                 attributes:
                  {"sroke-width": path.borderWidth,
                   stroke: path.gradient ? "url(#" + path.id + ")" : path.borderColor,
                 d: "M"+x1+","+y1+" "+"L"+x2+","+y2}}));
  }
  return vertices;
}

function renderGradient(path) {
  return h("defs", {namespace: "http://www.w3.org/2000/svg"},
                h("linearGradient", {namespace: "http://www.w3.org/2000/svg",
                                     attributes: {id: path.id,
                                                  gradientUnits: "userSpaceOnUse"}
                                     },
                    path.gradient.map(([k, c]) =>
                        h("stop",
                            {namespace: "http://www.w3.org/2000/svg",
                              attributes:
                                {offset: (k * 100) + "%",
                                 "stop-color": c}}))));
}

export class FontMetric {

  static default() {
    if (!this._fontMetric)
      throw new Error("FontMetric has not yet been initialized!")
    return this._fontMetric;
  }

  static initDefault(doc = typeof document !== "undefined" ? document : null) {
    if (!this._fontMetric) {
      this._fontMetric = new FontMetric();
      this._fontMetric.install(doc, doc.body);
    }
  }

  static removeDefault() {
    if (this._fontMetric) {
      this._fontMetric.uninstall();
      this._fontMetric = null;
    }
  }

  constructor() {
    this.charMap = [];
    this.parentElement = null;
    this.element = null;
  }

  install(doc, parentEl) {
    this.parentElement = parentEl;
    this.element = doc.createElement("div");
    this.setMeasureNodeStyles(this.element.style, true);
    this.parentElement.appendChild(this.element);
  }

  uninstall() {
    if (this.element) {
      this.parentElement.removeChild(this.element);
      this.parentElement = null;
      this.element = null;
    }
  }

  setMeasureNodeStyles(style, isRoot) {
    style.width = style.height = "auto";
    style.left = style.top = "0px";
    style.visibility = "hidden";
    style.position = "absolute";
    style.whiteSpace = "pre";
    style.font = "inherit";
    style.overflow = isRoot ? "hidden" : "visible";
  }

  measure(fontFamily, fontSize, char) {
    var rect = null;
    this.element.innerHTML = char;
    this.element.style.fontFamily = fontFamily;
    this.element.style.fontSize = fontSize + "px";
    try {
      rect = this.element.getBoundingClientRect();
    } catch(e) {
      rect = {width: 0, height:0};
    };
    return {
      height: rect.height,
      width: rect.width
    }
  }

  sizeFor(fontFamily, fontSize, char) {
    if (char.length > 1)
      return this.sizeForStr(fontFamily, fontSize, char);

    if (!this.charMap[fontFamily]) {
      this.charMap[fontFamily] = [];
    }
    if (!this.charMap[fontFamily][fontSize]) {
      this.charMap[fontFamily][fontSize] = [];
    }
    if (!this.charMap[fontFamily][fontSize][char])
      this.charMap[fontFamily][fontSize][char] = this.measure(fontFamily, fontSize, char);
    return this.charMap[fontFamily][fontSize][char];
  }

  sizeForStr(fontFamily, fontSize, str) {
    var height = 0, width = 0;
    for (let line of str.split('\n')) {
      let lineHeight = 0, lineWidth = 0;
      for (let char of line.split('')) {
        let { height: charHeight, width: charWidth } = this.sizeFor(fontFamily, fontSize, char);
        if (charHeight > lineHeight) lineHeight = charHeight;
        lineWidth += charWidth;
      }
      if (lineWidth > width) width = lineWidth;
      height += lineHeight || this.sizeFor(fontFamily, fontSize, " ").height;
    }
    return { height: height, width: width };
  }

  asciiSizes(fontFamily, fontSize) {
    var result = {};
    for (var i = 32; i <= 126; i++) {
      var char = String.fromCharCode(i);
      result[char] = this.sizeFor(fontFamily, fontSize, char)
    }
    return result;
  }
}
<|endoftext|>


<commit_before>window.onload = function()
{
   var xmlDoc=null, xslObj=null;

   function start_app()
   {
      prepare_event_handling();
      resize_table_headers();
   }

   function seek_embedded_form()
   {
      var host, forms, form;
      if ((host=document.getElementById("SFW_Content")))
         if ((forms=host.getElementsByTagName("form")))
            if (forms.length && (form=forms[0]))
               if (class_includes(form, "Embedded"))
                  return form;

      return null;
   }

   function prepare_embedded_form(form)
   {
      center_form(form, true);
      form.style.visibility = "visible";
      SchemaFW.focus_on_first_field(form);
   }

   function docs_available()
   {
      if ((xmlDoc = getXMLDocument()))
      {
         var docel = xmlDoc.documentElement;
         if (!docel)
            alert("Missing document element.");

         var msg = docel.tagName=="message" ? docel : docel.selectSingleNode("message");
         if (msg)
         {
            var type = msg.getAttribute("type");
            var message = msg.getAttribute("message");
            var detail = msg.getAttribute("detail");

            var str = null;

            if (type=="signal")
               str = message;
            else
               str = "Notice type " + type + ": " + message;

            if (str)
               alert(str);
            else
               alert("Undefined error.");

            // if (type!="notice")
            //    window.history.back();
         }

         if ((xslObj = new XSL(getXSLDocument())))
         {
            SchemaFW.set_xmldoc(xmlDoc);
            SchemaFW.set_xslobj(xslObj);
         }
      }
   }

   InitializeSchemaFW();

   var form = seek_embedded_form();
   if (form)
      prepare_embedded_form(form);

   if ("sfwvars" in window)
      process_sfwvars(sfwvars);
   else
     getXMLDocs(docs_available);

   start_app();
};

function process_sfwvars(obj)
{
   if ("error" in obj && obj.error==0)
   {
      if ("jump_no_error" in obj)
         window.location = obj.jump_no_error;
   }
}

function prepare_event_handling()
{
   var body = document.getElementsByTagName("body")[0];
   function addEvent(name,f,el)
   {
      var target = el || body;
      if (target.addEventListener)
         target.addEventListener(name,f,true);
      else if ((target=el||document) && target.attachEvent)
         target.attachEvent("on"+name,f);
   }

   function f(ev)
   {
      var e=ev||window.event;
      var t=e.target||e.srcElement;

      if (e.type=="resize")
         resize_table_headers();

      if (!process_dpicker(e,t))
         return false;
      if (!Moveable.process_event(e,t))
         return false;
      if (!SchemaFW.process_event(e,t))
         return false;
      if (!SchemaFW.process_button(e,t))
         return false;

      // I don't like this solution (simply moving to the end),
      // especially since the only thing custom_handler is doing
      // is handling the ESC key.  It should have a better name,
      // and there should be a preempt custom handler as well as
      // a handler for after SchemaFW.process_event().
      //
      // The problem is that this is a bigger design decision:
      // should _new_context() be changed into an object?  How does
      // the context object integrate with the rest of event handling?
      // How do contexts stack?  Too many questions need answers for
      // me to spend the time now when moving this code fixes the
      // problem of closing the context when the situation only calls
      // for closing a dialog.
      if ("custom_handler" in window && window.custom_handler)
      {
         if (!window.custom_handler(e,t))
            return false;
      }

      return event_handler(e,t);
   }

   // ADD EVENTS HERE:
   Events.add_event("click",f);
   Events.add_event("mousedown",f);  // mousedown and mouseup for dragging dialog
   Events.add_event("mouseup",f);
   Events.add_event("keydown",f);
   Events.add_event("keyup",f);
   Events.add_event("keypress",f);
   Events.add_event("focus",f);

   window.onresize = f;
}

function event_handler(e,t)
{
   return true;
}

var center_form = function(form, horizontal_only)
{
   var html = document.documentElement;

   var h_form = form.offsetHeight;
   var w_form = form.offsetWidth;
   var h_window = html.clientHeight;
   var w_window = html.clientWidth;

   var left = w_window/2 - w_form/2;
   form.style.left = SchemaFW.px(left);

   if (!horizontal_only)
   {
      var top = h_window/2 - h_form/2;
      form.style.top = SchemaFW.px(top);
   }

};

function resize_table_headers()
{
   var nlTables = document.getElementsByTagName("table");
   var stop = nlTables.length;
   if (stop)
   {
      for (var i=0; i<stop; ++i)
         if (class_includes(nlTables[i], "Schema"))
         {
            SchemaFW.fix_table_heads(nlTables[i]);
         }
   }
}

<commit_msg>Added form.xmldoc = xmlDoc in two places where form.xmldoc would otherwise not be set as needed.<commit_after>window.onload = function()
{
   var xmlDoc=null, xslObj=null;

   function start_app()
   {
      prepare_event_handling();
      resize_table_headers();
   }

   function seek_embedded_form()
   {
      var host, forms, form;
      if ((host=document.getElementById("SFW_Content")))
         if ((forms=host.getElementsByTagName("form")))
            if (forms.length && (form=forms[0]))
               if (class_includes(form, "Embedded"))
                  return form;

      return null;
   }

   function prepare_embedded_form(form)
   {
      center_form(form, true);
      form.style.visibility = "visible";
      SchemaFW.focus_on_first_field(form);
      if (xmlDoc)
         form.xmldoc = xmlDoc;
   }

   function docs_available()
   {
      if ((xmlDoc = getXMLDocument()))
      {
         var docel = xmlDoc.documentElement;
         if (!docel)
            alert("Missing document element.");

         var form;
         if ((form=seek_embedded_form()))
             form.xmldoc = xmlDoc;

         var msg = docel.tagName=="message" ? docel : docel.selectSingleNode("message");
         if (msg)
         {
            var type = msg.getAttribute("type");
            var message = msg.getAttribute("message");
            var detail = msg.getAttribute("detail");

            var str = null;

            if (type=="signal")
               str = message;
            else
               str = "Notice type " + type + ": " + message;

            if (str)
               alert(str);
            else
               alert("Undefined error.");

            // if (type!="notice")
            //    window.history.back();
         }

         if ((xslObj = new XSL(getXSLDocument())))
         {
            SchemaFW.set_xmldoc(xmlDoc);
            SchemaFW.set_xslobj(xslObj);
         }
      }
   }

   InitializeSchemaFW();

   var form = seek_embedded_form();
   if (form)
      prepare_embedded_form(form);

   if ("sfwvars" in window)
      process_sfwvars(sfwvars);
   else
     getXMLDocs(docs_available);

   start_app();
};

function process_sfwvars(obj)
{
   if ("error" in obj && obj.error==0)
   {
      if ("jump_no_error" in obj)
         window.location = obj.jump_no_error;
   }
}

function prepare_event_handling()
{
   var body = document.getElementsByTagName("body")[0];
   function addEvent(name,f,el)
   {
      var target = el || body;
      if (target.addEventListener)
         target.addEventListener(name,f,true);
      else if ((target=el||document) && target.attachEvent)
         target.attachEvent("on"+name,f);
   }

   function f(ev)
   {
      var e=ev||window.event;
      var t=e.target||e.srcElement;

      if (e.type=="resize")
         resize_table_headers();

      if (!process_dpicker(e,t))
         return false;
      if (!Moveable.process_event(e,t))
         return false;
      if (!SchemaFW.process_event(e,t))
         return false;
      if (!SchemaFW.process_button(e,t))
         return false;

      // I don't like this solution (simply moving to the end),
      // especially since the only thing custom_handler is doing
      // is handling the ESC key.  It should have a better name,
      // and there should be a preempt custom handler as well as
      // a handler for after SchemaFW.process_event().
      //
      // The problem is that this is a bigger design decision:
      // should _new_context() be changed into an object?  How does
      // the context object integrate with the rest of event handling?
      // How do contexts stack?  Too many questions need answers for
      // me to spend the time now when moving this code fixes the
      // problem of closing the context when the situation only calls
      // for closing a dialog.
      if ("custom_handler" in window && window.custom_handler)
      {
         if (!window.custom_handler(e,t))
            return false;
      }

      return event_handler(e,t);
   }

   // ADD EVENTS HERE:
   Events.add_event("click",f);
   Events.add_event("mousedown",f);  // mousedown and mouseup for dragging dialog
   Events.add_event("mouseup",f);
   Events.add_event("keydown",f);
   Events.add_event("keyup",f);
   Events.add_event("keypress",f);
   Events.add_event("focus",f);

   window.onresize = f;
}

function event_handler(e,t)
{
   return true;
}

var center_form = function(form, horizontal_only)
{
   var html = document.documentElement;

   var h_form = form.offsetHeight;
   var w_form = form.offsetWidth;
   var h_window = html.clientHeight;
   var w_window = html.clientWidth;

   var left = w_window/2 - w_form/2;
   form.style.left = SchemaFW.px(left);

   if (!horizontal_only)
   {
      var top = h_window/2 - h_form/2;
      form.style.top = SchemaFW.px(top);
   }

};

function resize_table_headers()
{
   var nlTables = document.getElementsByTagName("table");
   var stop = nlTables.length;
   if (stop)
   {
      for (var i=0; i<stop; ++i)
         if (class_includes(nlTables[i], "Schema"))
         {
            SchemaFW.fix_table_heads(nlTables[i]);
         }
   }
}

<|endoftext|>