<commit_before>/**
 * DashboardCTA component.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * WordPress dependencies
 */
import { useCallback } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

/**
 * Internal dependencies
 */
import Data from 'googlesitekit-data';
import {
	showErrorNotification,
} from '../../../../../util';
import GenericError from '../../../../../components/legacy-notifications/generic-error';
import { CORE_MODULES } from '../../../../../googlesitekit/modules/datastore/constants';
import { CORE_LOCATION } from '../../../../../googlesitekit/datastore/location/constants';
import Button from '../../../../../components/Button';
import Link from '../../../../../components/Link';
import IdeaHubIcon from '../../../../../../svg/idea-hub.svg';
import BulbIcon from '../../../../../../svg/bulb.svg';
const { useSelect, useDispatch } = Data;

function DashboardCTA() {
	const { connected, active } = useSelect( ( select ) => select( CORE_MODULES ).getModule( 'idea-hub' ) );
	const { activateModule } = useDispatch( CORE_MODULES );
	const { navigateTo } = useDispatch( CORE_LOCATION );

	const onClick = useCallback( async () => {
		const { error, response } = await activateModule( 'idea-hub' );

		if ( ! error ) {
			navigateTo( response.moduleReauthURL );
		} else {
			showErrorNotification( GenericError, {
				id: `idea-hub-setup-error`,
				title: __( 'Internal Server Error', 'google-site-kit' ),
				description: error.message,
				format: 'small',
				type: 'win-error',
			} );
		}
	}, [ activateModule, navigateTo ] );

	return (

				<IdeaHubIcon height="144" width="144" />

					{ __( 'Get new topics based on what people are searching for with Idea Hub', 'google-site-kit' ) }

					<BulbIcon
						className="googlesitekit-idea-hub__dashboard-cta__learnmore-bulb"
						width="16px"
						height="16px"
					/>

					<Link
						className="googlesitekit-idea-hub__dashboard-cta__learnmore"
						href="https://sitekit.withgoogle.com/documentation/idea-hub-module/">
						{ __( 'Learn more', 'google-site-kit' ) }
					</Link>

				<Button onClick={ onClick }>
					{
						active && ! connected
							? __( 'Complete set up', 'google-site-kit' )
							: __( 'Set up', 'google-site-kit' )
					}
				</Button>

	);
}

export default DashboardCTA;
<commit_msg>Remove px from height and width attributes.<commit_after>/**
 * DashboardCTA component.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * WordPress dependencies
 */
import { useCallback } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

/**
 * Internal dependencies
 */
import Data from 'googlesitekit-data';
import {
	showErrorNotification,
} from '../../../../../util';
import GenericError from '../../../../../components/legacy-notifications/generic-error';
import { CORE_MODULES } from '../../../../../googlesitekit/modules/datastore/constants';
import { CORE_LOCATION } from '../../../../../googlesitekit/datastore/location/constants';
import Button from '../../../../../components/Button';
import Link from '../../../../../components/Link';
import IdeaHubIcon from '../../../../../../svg/idea-hub.svg';
import BulbIcon from '../../../../../../svg/bulb.svg';
const { useSelect, useDispatch } = Data;

function DashboardCTA() {
	const { connected, active } = useSelect( ( select ) => select( CORE_MODULES ).getModule( 'idea-hub' ) );
	const { activateModule } = useDispatch( CORE_MODULES );
	const { navigateTo } = useDispatch( CORE_LOCATION );

	const onClick = useCallback( async () => {
		const { error, response } = await activateModule( 'idea-hub' );

		if ( ! error ) {
			navigateTo( response.moduleReauthURL );
		} else {
			showErrorNotification( GenericError, {
				id: `idea-hub-setup-error`,
				title: __( 'Internal Server Error', 'google-site-kit' ),
				description: error.message,
				format: 'small',
				type: 'win-error',
			} );
		}
	}, [ activateModule, navigateTo ] );

	return (

				<IdeaHubIcon height="144" width="144" />

					{ __( 'Get new topics based on what people are searching for with Idea Hub', 'google-site-kit' ) }

					<BulbIcon
						className="googlesitekit-idea-hub__dashboard-cta__learnmore-bulb"
						width="16"
						height="16"
					/>

					<Link
						className="googlesitekit-idea-hub__dashboard-cta__learnmore"
						href="https://sitekit.withgoogle.com/documentation/idea-hub-module/">
						{ __( 'Learn more', 'google-site-kit' ) }
					</Link>

				<Button onClick={ onClick }>
					{
						active && ! connected
							? __( 'Complete set up', 'google-site-kit' )
							: __( 'Set up', 'google-site-kit' )
					}
				</Button>

	);
}

export default DashboardCTA;
<|endoftext|>


<commit_before>/*
 * jQuery Panel Hashtag Navigation 1.0
 * https://github.com/elationbase/jquery.ebPanelNavHashtag
 * Copyright 2013, elationbase
 * A complete navigation system with horizontal and vertical layouts and hashtag enabled
 * Free to use under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
*/
$.fn.ebPanelNavHashtag = function( options ) {

	var theW = $(window).width(); //console.log(theW);
	var theH = $(window).height(); //console.log(theH);
	var headerH = $("header").innerHeight(); //console.log(headerH);
	var dataHash;
	var settings = $.extend({
		wrapperClass: ".eb-wrapper",
		panelClass: ".eb-panel",
		homePanel: "#eb-panel1",
		linkClass: ".eb-link-item",
		navClass: ".eb-nav-item",
		headerHeight: headerH,
		layout: "horizontal", // Options: horizontal, vertical
		rememberPanel: false,
		easing : "swing",
		transitionTime: 500,
		onStart: function() {},
		onEnd: function() {}
	 }, options );

	function intialSet () {
		$(settings.wrapperClass).css({height:theH,width:theW});
		$(settings.panelClass).css({width:theW,height:theH-headerH,top:headerH});
	};
	intialSet ();

	if (settings.rememberPanel === true) {
		var oldPanel = window.location.hash; //console.log(oldPanel);
		if(oldPanel != ''){
			settings.homePanel = oldPanel;
		}
	} else {
		history.pushState(null, null, '#');
	};

	if (settings.layout === "horizontal") {
		$(settings.panelClass).css({left: "100%"});
		$(settings.homePanel).addClass("eb-active").css({left: "0"});
		var activeAni = {left: "-100%"},
		    offAni = {left:"100%", display:"none"},
		    locationAni = {left: "0%"}
	};
	if (settings.layout === "vertical") {
		$(settings.panelClass).css({top: "-100%"});
		$(settings.homePanel).addClass("eb-active").css({top: headerH});
		var activeAni = {top: "100%"},
		    offAni = {top:"-100%", display:"none"},
		    locationAni = {top: headerH}
	};

	function changePanel(location) {
		settings.onStart.call(this);
		$(".eb-active").stop(true).animate(activeAni, settings.transitionTime, settings.easing, function() {
			$(this).removeClass("eb-active").css(offAni);
		});
		$(location).stop(true).addClass("eb-move").show().animate(locationAni, settings.transitionTime, settings.easing, function() {
			$(this).toggleClass("eb-move eb-active");
			settings.onEnd.call(this);
		});
	};
	function locationHashChanged() {
		dataHash = document.location.hash; //console.log(dataHash);
		changePanel(dataHash);
	};

	window.onhashchange = locationHashChanged;

	var linksItems = $(settings.linkClass + ", " + settings.navClass + " a"); //console.log(linksItems);
	linksItems.on("click", function(event){
		event.preventDefault();
		dataHash = $(this).attr("data-hash"); //console.log(dataHash);
		if ( !$(dataHash).hasClass("eb-active") ) {
			linksItems.removeClass("eb-nav-active");
			$(this).addClass("eb-nav-active");
			window.location.hash = dataHash;
		}
	});

	$(window).on('resize', function(){
		theW = $(window).width();
		theH = $(window).height();
		headerH = $("header").innerHeight();
		intialSet ();
	});

};
<commit_msg>Added control when data-hash is undefine<commit_after>/*
 * jQuery Panel Hashtag Navigation 1.0
 * https://github.com/elationbase/jquery.ebPanelNavHashtag
 * Copyright 2013, elationbase
 * A complete navigation system with horizontal and vertical layouts and hashtag enabled
 * Free to use under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
*/
$.fn.ebPanelNavHashtag = function( options ) {

	var theW = $(window).width(); //console.log(theW);
	var theH = $(window).height(); //console.log(theH);
	var headerH = $("header").innerHeight(); //console.log(headerH);
	var dataHash;
	var settings = $.extend({
		wrapperClass: ".eb-wrapper",
		panelClass: ".eb-panel",
		homePanel: "#eb-panel1",
		linkClass: ".eb-link-item",
		navClass: ".eb-nav-item",
		headerHeight: headerH,
		layout: "horizontal", // Options: horizontal, vertical
		rememberPanel: false,
		easing : "swing",
		transitionTime: 500,
		onStart: function() {},
		onEnd: function() {}
	 }, options );

	function intialSet () {
		$(settings.wrapperClass).css({height:theH,width:theW});
		$(settings.panelClass).css({width:theW,height:theH-headerH,top:headerH});
	};
	intialSet ();

	if (settings.rememberPanel === true) {
		var oldPanel = window.location.hash; //console.log(oldPanel);
		if(oldPanel != ''){
			settings.homePanel = oldPanel;
		}
	} else {
		history.pushState(null, null, '#');
	};

	if (settings.layout === "horizontal") {
		$(settings.panelClass).css({left: "100%"});
		$(settings.homePanel).addClass("eb-active").css({left: "0"});
		var activeAni = {left: "-100%"},
		    offAni = {left:"100%", display:"none"},
		    locationAni = {left: "0%"}
	};
	if (settings.layout === "vertical") {
		$(settings.panelClass).css({top: "-100%"});
		$(settings.homePanel).addClass("eb-active").css({top: headerH});
		var activeAni = {top: "100%"},
		    offAni = {top:"-100%", display:"none"},
		    locationAni = {top: headerH}
	};

	function changePanel(location) {
		settings.onStart.call(this);
		$(".eb-active").stop(true).animate(activeAni, settings.transitionTime, settings.easing, function() {
			$(this).removeClass("eb-active").css(offAni);
		});
		$(location).stop(true).addClass("eb-move").show().animate(locationAni, settings.transitionTime, settings.easing, function() {
			$(this).toggleClass("eb-move eb-active");
			settings.onEnd.call(this);
		});
	};
	function locationHashChanged() {
		dataHash = document.location.hash; //console.log(dataHash);
		changePanel(dataHash);
	};

	window.onhashchange = locationHashChanged;

	var linksItems = $(settings.linkClass + ", " + settings.navClass + " a"); //console.log(linksItems);
	linksItems.on("click", function(event){
		event.preventDefault();
		dataHash = $(this).attr("data-hash"); //console.log(dataHash);
		if ( !$(dataHash).hasClass("eb-active") && typeof dataHash != 'undefined' ) {
			linksItems.removeClass("eb-nav-active");
			$(this).addClass("eb-nav-active");
			window.location.hash = dataHash;
		}
	});

	$(window).on('resize', function(){
		theW = $(window).width();
		theH = $(window).height();
		headerH = $("header").innerHeight();
		intialSet ();
	});

};
<|endoftext|>


<commit_before>/**
 * Tag Manager Account Create Legacy component.
 *
 * Site Kit by Google, Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * WordPress dependencies
 */
import { __ } from '@wordpress/i18n';
import { useCallback } from '@wordpress/element';

/**
 * Internal dependencies
 */
import Data from 'googlesitekit-data';
import ErrorNotice from './ErrorNotice';
import Link from '../../../../components/link';
import Button from '../../../../components/button';
import ProgressBar from '../../../../components/progress-bar';
import { STORE_NAME } from '../../datastore/constants';
import { STORE_NAME as CORE_USER } from '../../../../googlesitekit/datastore/user';
import { escapeURI } from '../../../../util/escape-uri';
const { useSelect, useDispatch } = Data;

export default function AccountCreateLegacy() {
	const accounts = useSelect( ( select ) => select( STORE_NAME ).getAccounts() );
	const isDoingGetAccounts = useSelect( ( select ) => select( STORE_NAME ).isDoingGetAccounts() );
	const userEmail = useSelect( ( select ) => select( CORE_USER ).getEmail() );

	const { resetAccounts } = useDispatch( STORE_NAME );
	const refetchAccountsHandler = useCallback( () => {
		resetAccounts();
	} );

	if ( undefined === accounts || isDoingGetAccounts ) {
		return <ProgressBar />;
	}

	return (

			<ErrorNotice />

				{ __( 'To create a new account, click the button below which will open the Google Tag Manager account creation screen in a new window.', 'google-site-kit' ) }

				{ __( 'Once completed, click the link below to re-fetch your accounts to continue.', 'google-site-kit' ) }

				<Button
					href={ escapeURI`https://tagmanager.google.com/?authuser=${ userEmail }#/admin/accounts/create` }
					target="_blank"
				>
					{ __( 'Create an account', 'google-site-kit' ) }
				</Button>

					<Link onClick={ refetchAccountsHandler }>
						{ __( 'Re-fetch my account', 'google-site-kit' ) }
					</Link>

	);
}
<commit_msg>Update refetch link case for consistency.<commit_after>/**
 * Tag Manager Account Create Legacy component.
 *
 * Site Kit by Google, Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * WordPress dependencies
 */
import { __ } from '@wordpress/i18n';
import { useCallback } from '@wordpress/element';

/**
 * Internal dependencies
 */
import Data from 'googlesitekit-data';
import ErrorNotice from './ErrorNotice';
import Link from '../../../../components/link';
import Button from '../../../../components/button';
import ProgressBar from '../../../../components/progress-bar';
import { STORE_NAME } from '../../datastore/constants';
import { STORE_NAME as CORE_USER } from '../../../../googlesitekit/datastore/user';
import { escapeURI } from '../../../../util/escape-uri';
const { useSelect, useDispatch } = Data;

export default function AccountCreateLegacy() {
	const accounts = useSelect( ( select ) => select( STORE_NAME ).getAccounts() );
	const isDoingGetAccounts = useSelect( ( select ) => select( STORE_NAME ).isDoingGetAccounts() );
	const userEmail = useSelect( ( select ) => select( CORE_USER ).getEmail() );

	const { resetAccounts } = useDispatch( STORE_NAME );
	const refetchAccountsHandler = useCallback( () => {
		resetAccounts();
	} );

	if ( undefined === accounts || isDoingGetAccounts ) {
		return <ProgressBar />;
	}

	return (

			<ErrorNotice />

				{ __( 'To create a new account, click the button below which will open the Google Tag Manager account creation screen in a new window.', 'google-site-kit' ) }

				{ __( 'Once completed, click the link below to re-fetch your accounts to continue.', 'google-site-kit' ) }

				<Button
					href={ escapeURI`https://tagmanager.google.com/?authuser=${ userEmail }#/admin/accounts/create` }
					target="_blank"
				>
					{ __( 'Create an account', 'google-site-kit' ) }
				</Button>

					<Link onClick={ refetchAccountsHandler }>
						{ __( 'Re-fetch My Account', 'google-site-kit' ) }
					</Link>

	);
}
<|endoftext|>


<commit_before>game.GameTimerManager = Object.extend({
    init: function(x, y, settings){
        this.now = new Date().getTime();
        this.lastCreep = new Date().getTime();
        this.paused = false;
        this.alwaysUpdate = true;
    },

    update: function() {
        this.now = new Date().getTime();
        this.goldTimerCheck();
        this.creepTimerCheck();

        return true;
    },

    goldTimerCheck: function(){
        if(Math.round(this.now/1000)%20 ===0 && (this.now - this.lastCreep >= 1000)){
           game.data.gold += (game.data.exp1+1);
           console.log("Current gold: " + game.data.gold);
        }
    },

    creepTimerCheck: function(){
           if(Math.round(this.now/1000)%10 ===0 && (this.now - this.lastCreep >= 1000)){
            this.lastCreep = this.now;
            var creepe = me.pool.pull("EnemyCreep", 1000, 0, {});
            me.game.world.addChild(creepe, 5);
        }
    }
    });

game.HeroDeathManager = Object.extend({
    init: function (x, y, settings) {
        this.alwaysUpdate = true;
    },

    update: function(){
        if(game.data.player.dead){
            me.game.world.removeChild(game.data.player);
            me.state.current().resetPlayer(10, 0);
        }

        return true;
    }
});

game.ExperienceManager = Object.extend({
    init: function (x, y, settings){
        this.alwaysUpdate = true;
        this.gameover = false;
    },

    update: function() {
        if(game.data.win === true && !this.gameover){
         this.gameOver(true);
        }else if(game.data.win === false && !this.gameover){
           this.gameOver(false);
        }

        return true;
    },

    gameOver: function(win) {
        if (win) {
        game.data.exp += 10;
        }else{
            game.data.exp += 1;
        }
        console.log(game.data.exp);
        this.gameover = true;
        me.save.exp = game.data.exp;

    }

    });

game.SpendGold = Object.extend({
     init: function(x, y, settings){
          this.now = new Date ().getTime();
          this.lastBuy = new Date ().getTime ();
          this.paused = false;
          this.alwaysUpdate = true;
      },

     update: function(){
         return true;
     }

     });

  <commit_msg>video 47<commit_after>game.GameTimerManager = Object.extend({
    init: function(x, y, settings){
        this.now = new Date().getTime();
        this.lastCreep = new Date().getTime();
        this.paused = false;
        this.alwaysUpdate = true;
    },

    update: function() {
        this.now = new Date().getTime();
        this.goldTimerCheck();
        this.creepTimerCheck();

        return true;
    },

    goldTimerCheck: function(){
        if(Math.round(this.now/1000)%20 ===0 && (this.now - this.lastCreep >= 1000)){
           game.data.gold += (game.data.exp1+1);
           console.log("Current gold: " + game.data.gold);
        }
    },

    creepTimerCheck: function(){
           if(Math.round(this.now/1000)%10 ===0 && (this.now - this.lastCreep >= 1000)){
            this.lastCreep = this.now;
            var creepe = me.pool.pull("EnemyCreep", 1000, 0, {});
            me.game.world.addChild(creepe, 5);
        }
    }
    });

game.HeroDeathManager = Object.extend({
    init: function (x, y, settings) {
        this.alwaysUpdate = true;
    },

    update: function(){
        if(game.data.player.dead){
            me.game.world.removeChild(game.data.player);
            me.state.current().resetPlayer(10, 0);
        }

        return true;
    }
});

game.ExperienceManager = Object.extend({
    init: function (x, y, settings){
        this.alwaysUpdate = true;
        this.gameover = false;
    },

    update: function() {
        if(game.data.win === true && !this.gameover){
         this.gameOver(true);
        }else if(game.data.win === false && !this.gameover){
           this.gameOver(false);
        }

        return true;
    },

    gameOver: function(win) {
        if (win) {
        game.data.exp += 10;
        }else{
            game.data.exp += 1;
        }
        console.log(game.data.exp);
        this.gameover = true;
        me.save.exp = game.data.exp;

    }

    });

game.SpendGold = Object.extend({
     init: function(x, y, settings){
          this.now = new Date ().getTime();
          this.lastBuy = new Date ().getTime ();
          this.paused = false;
          this.alwaysUpdate = true;
          this.updateWhenPause = true;
          this.buying = false;
      },

     update: function(){
         this.now = new Date().getTime();

         if(me.input.isKeyPressed("buy") && this.now-this.lastBuy >=1000) {
             this.lastBuy = this.now;
             if(!this.buying){
                 this.startBuying();
             }else{
                 this.stopBuying();
             }

         }

         return true;
     },

     startBuying: function() {
         this.buying = true;
         me.State.pause(me.state.PLAY);
     },

     stopBuying: function () {
         this.buying = false;
         me.state.resume(me.state.PLAY);
     }

     });

  <|endoftext|>


<commit_before>/*jshint esversion: 6 */

var React = require('react');
var Input = require('react-bootstrap').Input;
var Modal = require('react-bootstrap').Modal;
var Button = require('react-bootstrap').Button;
import {
  Form,
  FormGroup,
  FormControl,
  ControlLabel,
  HelpBlock,
  Col,
  Radio
} from 'react-bootstrap';
var Glyphicon = require('react-bootstrap').Glyphicon;
var Constants = require('./../../../../constants');
import Actions from './../../../../actions.js';
var $ = require('jquery');
var _ = require('underscore');
var browserHistory = require('react-router').browserHistory;
import WorkspaceStore from './../../workspace-store';
import {calculateMapName} from './../map-name-calculator';

//TODO: validation of the workspace dialog

var SubmapReferencesDialog = React.createClass({
  getInitialState: function() {
    return {open: false};
  },

  _close: function() {
    Actions.closeSubmapReferencesDialog();
  },

  componentDidMount: function() {
    WorkspaceStore.addChangeListener(this._onChange);
  },

  componentWillUnmount: function() {
    WorkspaceStore.removeChangeListener(this._onChange.bind(this));
  },

  _onChange: function() {
    this.setState(WorkspaceStore.getSubmapReferencesDialogState());
  },
  constructMessage : function(){
    if(!this.state.referencingMaps){
      return 'Loading... please wait.'
    }
    if(this.state.referencingMaps.length === 0){
      return 'No map uses this component';
    }
    if(this.state.referencingMaps.length === 1 && this.state.referencingMaps[0]._id === this.state.mapID){
      return 'No other map uses this component';
    }
    var otherMaps = [];
    for(var i = 0; i < this.state.referencingMaps.length; i++){
      if(this.state.referencingMaps[i]._id === this.state.mapID){
        continue;
      } else {
        var href = '/map/' + this.state.referencingMaps[i]._id;
        var name = calculateMapName('Unknown',this.state.referencingMaps[i].user, this.state.referencingMaps[i].purpose,this.state.referencingMaps[i].name );
        otherMaps.push(
{name}
);
      }
    }
    return otherMaps;
  },
  render: function() {
    var show = this.state.open;
    if (!show) {
      return null;
    }
    var currentName = this.state.currentName;
    var message = this.constructMessage();
    return (

        <Modal show={show} onHide={this._close}>
          <Modal.Header closeButton>
            <Modal.Title>
              Other maps referencing submap '{currentName}'.
            </Modal.Title>
          </Modal.Header>
          <Modal.Body>
              {message}
          </Modal.Body>
          <Modal.Footer>
            <Button type="submit" bsStyle="primary" value="Change" onClick={this._close}>Close</Button>
          </Modal.Footer>
        </Modal>

    );
  }
});

module.exports = SubmapReferencesDialog;
<commit_msg>Improve wording<commit_after>/*jshint esversion: 6 */

var React = require('react');
var Input = require('react-bootstrap').Input;
var Modal = require('react-bootstrap').Modal;
var Button = require('react-bootstrap').Button;
import {
  Form,
  FormGroup,
  FormControl,
  ControlLabel,
  HelpBlock,
  Col,
  Radio
} from 'react-bootstrap';
var Glyphicon = require('react-bootstrap').Glyphicon;
var Constants = require('./../../../../constants');
import Actions from './../../../../actions.js';
var $ = require('jquery');
var _ = require('underscore');
var browserHistory = require('react-router').browserHistory;
import WorkspaceStore from './../../workspace-store';
import {calculateMapName} from './../map-name-calculator';

//TODO: validation of the workspace dialog

var SubmapReferencesDialog = React.createClass({
  getInitialState: function() {
    return {open: false};
  },

  _close: function() {
    Actions.closeSubmapReferencesDialog();
  },

  componentDidMount: function() {
    WorkspaceStore.addChangeListener(this._onChange);
  },

  componentWillUnmount: function() {
    WorkspaceStore.removeChangeListener(this._onChange.bind(this));
  },

  _onChange: function() {
    this.setState(WorkspaceStore.getSubmapReferencesDialogState());
  },
  constructMessage : function(){
    if(!this.state.referencingMaps){
      return 'Loading... please wait.'
    }
    if(this.state.referencingMaps.length === 0){
      return 'No map uses this component';
    }
    if(this.state.referencingMaps.length === 1 && this.state.referencingMaps[0]._id === this.state.mapID){
      return 'No other map uses this component';
    }
    var otherMaps = [];
    for(var i = 0; i < this.state.referencingMaps.length; i++){
      if(this.state.referencingMaps[i]._id === this.state.mapID){
        continue;
      } else {
        var href = '/map/' + this.state.referencingMaps[i]._id;
        var name = calculateMapName('Unknown',this.state.referencingMaps[i].user, this.state.referencingMaps[i].purpose,this.state.referencingMaps[i].name );
        otherMaps.push(
{name}
);
      }
    }
    return otherMaps;
  },
  render: function() {
    var show = this.state.open;
    if (!show) {
      return null;
    }
    var currentName = this.state.currentName;
    var message = this.constructMessage();
    return (

        <Modal show={show} onHide={this._close}>
          <Modal.Header closeButton>
            <Modal.Title>
              Other maps using submap '{currentName}'.
            </Modal.Title>
          </Modal.Header>
          <Modal.Body>
              {message}
          </Modal.Body>
          <Modal.Footer>
            <Button type="submit" bsStyle="primary" value="Change" onClick={this._close}>Close</Button>
          </Modal.Footer>
        </Modal>

    );
  }
});

module.exports = SubmapReferencesDialog;
<|endoftext|>


<commit_before>game.GameTimerManager = Object.extend({
	// this is an object but we still need and init function
	init: function(x, y, settings) {
		this.now = new Date().getTime();
		this.lastCreep = new Date().getTime();
		this.paused = false;
		this.alwaysUpdate = true;
		// player shouldnt get more gold if the game is paused

	},
	update: function() {
		 this.now = new Date().getTime();

		 this.goldTimerCheck();

		 this.creepTimerCheck();

		 return true;
	},

	goldTimerCheck: function() {
			 // creep is going to spawn at the same time the gold comes
		 if(Math.round(this.now/1000)%20 ===0 && (this.now - this.lastCreep >= 1000)) {
			game.data.gold += game.data.exp1+1;
			console.log("Current gold: " + game.data.gold);

		 };
	},
	creepTimerCheck: function() {

		 if(Math.round(this.now/1000)%10 ===0 && (this.now - this.lastCreep >= 1000)) {
		 	// checking to see if we have multiples of ten
		 	// this.now - .. makes sure the spawn isnt repeating
		 	this.lastCreep = this.now;
		 	var creepe = me.pool.pull("EnemyCreep", 1000, 0, {});
		 	me.game.world.addChild(creepe, 5);
		 	var friend = me.pool.pull("FriendCreep", 200, 0, {});
		 	me.game.world.addChild(friend, 5);

		 };
	},

});
// this function is going to deal with the deaths
game.HeroDeathManager = Object.extend({
	init: function(x, y, settings){
		this.alwaysUpdate = true;
	},

	update: function() {
		 if(game.data.player.dead) {
		 	me.game.world.removeChild(game.data.player);
		 	me.state.current().resetPlayer(10, 0);

		 }
	}

});

game.ExperienceManager = Object.extend ({
	init: function(x, y, settings) {
		this.alwaysUpdate = true;
		this.gameover = false;
	},

	update: function() {
		// none of these get called until one of the flags are set
		if(game.data.win === true && !this.gameover) {
		//this is going to do something if I win
			this.gameOver(true);
		}
		else if(game.data.win === false && !this.gameover) {
		// this will do something if I loose
			this.gameOver(false);
		}
		return true;
	},

	gameOver: function (win) {
		if (win) {
			game.data.exp += 10;
		}
		else {
			game.data.exp += 1;
		}

		this.gameover = true;
		me.save.exp = game.data.exp;
		// for testing code purposes
		console.log("Juzet is awesome " + me.save.exp);
		me.save.exp2 = 4;
	}
});

game.SpendGold = Object.extend ({
	init: function(x, y, settings) {
		this.now = new Date().getTime();
		this.lastBuy = new Date().getTime();
		this.paused = false;
		this.alwaysUpdate = true;
		this.updateWhenPaused = true;
		this.buying = false;
	},

	update: function() {
		this.now = new Date().getTime();

		if (me.input.isKeyPressed("buy") && this.now-this.lastBuy >= 1000) {
			this.lastBuy = this.now;
			if (!this.buying) {
				this.startBuying();
			}
			else {
				this.stopBuying();
			}

		}
		return true;
	},
	startBuying: function () {
		this.buying = true;
		game.data.pausePos = me.game.viewport.localToWorld(0, 0);
		game.data.buyscreen = new me.Sprite(game.data.pausePos.x, game.data.pausePos.y, me.loader.getImage('gold-screen'));
		game.data.buyscreen.updateWhenPaused = true;
		game.data.buyscreen.setOpacity(0.8);
		me.game.world.addChild(game.data.buyscreen, 34);
		game.data.player.body.setVelocity(0, 0);
		me.state.pause(me.state.PLAY);
		me.input.bindKey(me.input.KEY.F1, "F1", true);
		me.input.bindKey(me.input.KEY.F2, "F2", true);
		me.input.bindKey(me.input.KEY.F3, "F3", true);
		me.input.bindKey(me.input.KEY.F4, "F4", true);
		me.input.bindKey(me.input.KEY.F5, "F5", true);
		me.input.bindKey(me.input.KEY.F6, "F6", true);
		// this is controlling the functions
		// this is also initiating functions
		this.setBuyText();
	},

	setBuyText: function () {
		game.data.buytext = new (me.Renderable.extend({
			init: function() {
				this._super(me.Renderable, 'init', [game.data.pausePos.x, game.data.pausePos.y, 1, 1]);
				//  300 50
				// making a call to the super function
				this.font = new me.Font("Arial", 26, "white");
				// setting a font on the screen
				this.updateWhenPaused = true;
				this.alwaysUpdate = true;
			},

            draw: function(renderer) {
				this.font.draw(renderer.getContext(), "PRESS F1-F6 TO BUY, B TO EXIT", this.pos.x, this.pos.y);
				// when we are drawing something we are passing in the context of where we are
				this.font.draw(renderer.getContext(), "Skill 1: Increase Damage. Current Level: " + game.data.skill1 + " Cost: " + ((game.data.skill1+1)*10), this.pos.x, this.pos.y + 40);
				this.font.draw(renderer.getContext(), "Skill 2: Run faster. Current Level: " + game.data.skill2 + " Cost: " + ((game.data.skill2+1)*10), this.pos.x, this.pos.y + 80);
				this.font.draw(renderer.getContext(), "Skill 3: Increase Health. Current Level: " + game.data.skill3 + " Cost: " + ((game.data.skill3+1)*10), this.pos.x, this.pos.y + 120);
				this.font.draw(renderer.getContext(), "Q Ability: Speed Burst. Current Level: " + game.data.ability1 + " Cost: " + ((game.data.ability1+1)*10), this.pos.x, this.pos.y + 160);
				this.font.draw(renderer.getContext(), "W Ability: Eat Creep for Health. Current Level: " + game.data.ability2 + " Cost: " + ((game.data.ability2+1)*10), this.pos.x, this.pos.y + 200);
				this.font.draw(renderer.getContext(), "E Ability: Throw your spear. Current Level: " + game.data.ability3+ " Cost: " + ((game.data.ability3+1)*10), this.pos.x, this.pos.y + 240);
			}

		}));
		me.game.world.addChild(game.data.buytext, 35);

	},

	stopBuying: function () {
		this.buying = false;
		me.state.resume(me.state.PLAY);
		game.data.player.body.setVelocity(game.data.playerMoveSpeed, 20);
		me.game.world.removeChild(game.data.buyscreen);
		me.input.unbindKey(me.input.KEY.F1, "F1", true);
		me.input.unbindKey(me.input.KEY.F2, "F2", true);
		me.input.unbindKey(me.input.KEY.F3, "F3", true);
		me.input.unbindKey(me.input.KEY.F4, "F4", true);
		me.input.unbindKey(me.input.KEY.F5, "F5", true);
		me.input.unbindKey(me.input.KEY.F6, "F6", true);
		me.game.world.removeChild(game.data.buytext);
		// these are stopping the functions
		// this is unbinding the functions for when you are not buying
	}
});

<commit_msg>coded and commented 50<commit_after>game.GameTimerManager = Object.extend({
	// this is an object but we still need and init function
	init: function(x, y, settings) {
		this.now = new Date().getTime();
		this.lastCreep = new Date().getTime();
		this.paused = false;
		this.alwaysUpdate = true;
		// player shouldnt get more gold if the game is paused

	},
	update: function() {
		 this.now = new Date().getTime();

		 this.goldTimerCheck();

		 this.creepTimerCheck();

		 return true;
	},

	goldTimerCheck: function() {
			 // creep is going to spawn at the same time the gold comes
		 if(Math.round(this.now/1000)%20 ===0 && (this.now - this.lastCreep >= 1000)) {
			game.data.gold += game.data.exp1+1;
			console.log("Current gold: " + game.data.gold);

		 };
	},
	creepTimerCheck: function() {

		 if(Math.round(this.now/1000)%10 ===0 && (this.now - this.lastCreep >= 1000)) {
		 	// checking to see if we have multiples of ten
		 	// this.now - .. makes sure the spawn isnt repeating
		 	this.lastCreep = this.now;
		 	var creepe = me.pool.pull("EnemyCreep", 1000, 0, {});
		 	me.game.world.addChild(creepe, 5);
		 	var friend = me.pool.pull("FriendCreep", 200, 0, {});
		 	me.game.world.addChild(friend, 5);

		 };
	},

});
// this function is going to deal with the deaths
game.HeroDeathManager = Object.extend({
	init: function(x, y, settings){
		this.alwaysUpdate = true;
	},

	update: function() {
		 if(game.data.player.dead) {
		 	me.game.world.removeChild(game.data.player);
		 	me.state.current().resetPlayer(10, 0);

		 }
	}

});

game.ExperienceManager = Object.extend ({
	init: function(x, y, settings) {
		this.alwaysUpdate = true;
		this.gameover = false;
	},

	update: function() {
		// none of these get called until one of the flags are set
		if(game.data.win === true && !this.gameover) {
		//this is going to do something if I win
			this.gameOver(true);
		}
		else if(game.data.win === false && !this.gameover) {
		// this will do something if I loose
			this.gameOver(false);
		}
		return true;
	},

	gameOver: function (win) {
		if (win) {
			game.data.exp += 10;
		}
		else {
			game.data.exp += 1;
		}

		this.gameover = true;
		me.save.exp = game.data.exp;
		// for testing code purposes
		console.log("Juzet is awesome " + me.save.exp);
		me.save.exp2 = 4;
	}
});

game.SpendGold = Object.extend ({
	init: function(x, y, settings) {
		this.now = new Date().getTime();
		this.lastBuy = new Date().getTime();
		this.paused = false;
		this.alwaysUpdate = true;
		this.updateWhenPaused = true;
		this.buying = false;
	},

	update: function() {
		this.now = new Date().getTime();

		if (me.input.isKeyPressed("buy") && this.now-this.lastBuy >= 1000) {
			this.lastBuy = this.now;
			if (!this.buying) {
				this.startBuying();
			}
			else {
				this.stopBuying();
			}

		}
		this.checkBuyKeys();

		return true;
	},
	startBuying: function () {
		this.buying = true;
		game.data.pausePos = me.game.viewport.localToWorld(0, 0);
		game.data.buyscreen = new me.Sprite(game.data.pausePos.x, game.data.pausePos.y, me.loader.getImage('gold-screen'));
		game.data.buyscreen.updateWhenPaused = true;
		game.data.buyscreen.setOpacity(0.8);
		me.game.world.addChild(game.data.buyscreen, 34);
		game.data.player.body.setVelocity(0, 0);
		me.state.pause(me.state.PLAY);
		me.input.bindKey(me.input.KEY.F1, "F1", true);
		me.input.bindKey(me.input.KEY.F2, "F2", true);
		me.input.bindKey(me.input.KEY.F3, "F3", true);
		me.input.bindKey(me.input.KEY.F4, "F4", true);
		me.input.bindKey(me.input.KEY.F5, "F5", true);
		me.input.bindKey(me.input.KEY.F6, "F6", true);
		// this is controlling the functions
		// this is also initiating functions
		this.setBuyText();
	},

	setBuyText: function () {
		game.data.buytext = new (me.Renderable.extend({
			init: function() {
				this._super(me.Renderable, 'init', [game.data.pausePos.x, game.data.pausePos.y, 1, 1]);
				//  300 50
				// making a call to the super function
				this.font = new me.Font("Arial", 26, "white");
				// setting a font on the screen
				this.updateWhenPaused = true;
				this.alwaysUpdate = true;
			},

            draw: function(renderer) {
				this.font.draw(renderer.getContext(), "PRESS F1-F6 TO BUY, B TO EXIT", this.pos.x, this.pos.y);
				// when we are drawing something we are passing in the context of where we are
				this.font.draw(renderer.getContext(), "Skill 1: Increase Damage. Current Level: " + game.data.skill1 + " Cost: " + ((game.data.skill1+1)*10), this.pos.x, this.pos.y + 40);
				this.font.draw(renderer.getContext(), "Skill 2: Run faster. Current Level: " + game.data.skill2 + " Cost: " + ((game.data.skill2+1)*10), this.pos.x, this.pos.y + 80);
				this.font.draw(renderer.getContext(), "Skill 3: Increase Health. Current Level: " + game.data.skill3 + " Cost: " + ((game.data.skill3+1)*10), this.pos.x, this.pos.y + 120);
				this.font.draw(renderer.getContext(), "Q Ability: Speed Burst. Current Level: " + game.data.ability1 + " Cost: " + ((game.data.ability1+1)*10), this.pos.x, this.pos.y + 160);
				this.font.draw(renderer.getContext(), "W Ability: Eat Creep for Health. Current Level: " + game.data.ability2 + " Cost: " + ((game.data.ability2+1)*10), this.pos.x, this.pos.y + 200);
				this.font.draw(renderer.getContext(), "E Ability: Throw your spear. Current Level: " + game.data.ability3+ " Cost: " + ((game.data.ability3+1)*10), this.pos.x, this.pos.y + 240);
			}

		}));
		me.game.world.addChild(game.data.buytext, 35);

	},

	stopBuying: function () {
		this.buying = false;
		me.state.resume(me.state.PLAY);
		game.data.player.body.setVelocity(game.data.playerMoveSpeed, 20);
		me.game.world.removeChild(game.data.buyscreen);
		me.input.unbindKey(me.input.KEY.F1, "F1", true);
		me.input.unbindKey(me.input.KEY.F2, "F2", true);
		me.input.unbindKey(me.input.KEY.F3, "F3", true);
		me.input.unbindKey(me.input.KEY.F4, "F4", true);
		me.input.unbindKey(me.input.KEY.F5, "F5", true);
		me.input.unbindKey(me.input.KEY.F6, "F6", true);
		me.game.world.removeChild(game.data.buytext);
		// these are stopping the functions
		// this is unbinding the functions for when you are not buying
	},

	checkBuyKeys: function() {
		if (me.input.isKeyPressed("F1")) {
			if(this.checkCost(1)){
				this.makePurchase(1);
			}
		}
		else if (me.input.isKeyPressed("F2")) {
			if(this.checkCost(2)){
				this.makePurchase(2);
			}
		}
		else if (me.input.isKeyPressed("F3")) {
			if(this.checkCost(3)){
				this.makePurchase(3);
			}
		}
		else if (me.input.isKeyPressed("F4")) {
			if(this.checkCost(4)){
				this.makePurchase(4);
			}
		}
		else if (me.input.isKeyPressed("F5")) {
			if(this.checkCost(5)){
				this.makePurchase(5);
			}
		}
		else if (me.input.isKeyPressed("F6")) {
			if(this.checkCost(6)){
				this.makePurchase(6);
			}
		}
	},

	checkCost: function(skill) {
		if(skill===1 && (game.data.gold >= ((game.data.skill1 + 1)*10))) {
			// taking the skill level adding 1 and multiplying it by 10 for the cost
			return true;
		}
		else if(skill===2 && (game.data.gold >= ((game.data.skill2 + 1)*10))) {
			// taking the skill level adding 1 and multiplying it by 0 for the cost
			return true;
		}
		else if(skill===3 && (game.data.gold >= ((game.data.skill3 + 1)*10))) {
			// taking the skill level adding 1 and multiplying it by 10 for the cost
			return true;
		}
		else if(skill===4 && (game.data.gold >= ((game.data.ability1 + 1)*10))) {
			// taking the skill level adding 1 and multiplying it by 10 for the cost
			return true;
		}
		else if(skill===5 && (game.data.gold >= ((game.data.ability2 + 1)*10))) {
			// taking the skill level adding 1 and multiplying it by 10 for the cost
			return true;
		}
		else if(skill===6 && (game.data.gold >= ((game.data.ability3 + 1)*10))) {
			// taking the skill level adding 1 and multiplying it by 10 for the cost
			return true;
		}
		else {
			return false;
		}
	},

	makePurchase: function(skill) {
		if(skill===1) {
			game.data.gold -= ((game.data.skill1 +1)*10);
			game.data.skill1 += 1;
			game.data.player.attack += 1;
		}
		else if(skill===2) {
			game.data.gold -= ((game.data.skill2 +1)*10);
			game.data.skill2 += 1;
		}
		else if(skill===3) {
			game.data.gold -= ((game.data.skill3 +1)*10);
			game.data.skill3 += 1;
		}
		if(skill===4) {
			game.data.gold -= ((game.data.ability1 +1)*10);
			game.data.ability1 += 1;
		}
		if(skill===5) {
			game.data.gold -= ((game.data.ability2 +1)*10);
			game.data.ability2 += 1;
		}
		if(skill===6) {
			game.data.gold -= ((game.data.ability3 +1)*10);
			game.data.ability3 += 1;
		}
	}
});

<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require tether
//= require bootstrap-sprockets
//= require turbolinks
//= require_tree .
<commit_msg>Disabling turbolinks due to https://github.com/turbolinks/turbolinks/issues/75 https://github.com/taw/magic-search-engine/issues/43<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require tether
//= require bootstrap-sprockets
//= require_tree .
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2013 salesforce.com, inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function lib(w) { //eslint-disable-line no-unused-vars
    'use strict';
    w || (w = window);

    var SCROLLER = w.__S || (w.__S = {}),
        PLUGINS  = SCROLLER.plugins || (SCROLLER.plugins = {}),
        Logger   = SCROLLER.Logger,

        CONFIG_DEFAULTS = {
            labelNoData  : 'No more data to display',
            labelIdle    : '',
            labelLoading : 'Loading more...',
            autoFillPage : false,
            threshold    : 0
        },
        CLASS_LOADING = 'loading',
        CLASS_IDLE    = 'il',

        // when zoomed, values become fractional and precision
        // is lost depending on how browsers handle it.
        // In this case, number of pixles left to scroll can be off a bit.
        // The offset is mostly less than 5.
        MIN_LOADING_THRESHOLD = 5;

    function InfiniteLoading () {}

    InfiniteLoading.prototype = {
        init: function () {
            this._mergeInfiniteLoading();
            this.on('_initialize', this._initializeInfiniteLoading);

            // Allows a forced reflow of this scroller through the firing of a global custom event, "FORCEREFLOW"
            document.addEventListener("FORCEREFLOW", function() { this._forceReflow(); }.bind(this));
        },
        _mergeInfiniteLoading: function () {
            this.opts.infiniteLoadingConfig = this._mergeConfigOptions(
                CONFIG_DEFAULTS,
                this.opts.infiniteLoadingConfig
            );
        },
        _createInfiniteLoadingMarkup: function () {
            var il_container = w.document.createElement('div'),
                label        = document.createElement('span'),
                idleLabel    = this.opts.infiniteLoadingConfig.labelIdle;

            label.className        = CLASS_IDLE;
            label.textContent      = idleLabel;
            il_container.className = 'infinite-loading';

            il_container.appendChild(label);

            return il_container;
        },
        _initializeInfiniteLoading: function () {
            var ilConfig       = this.opts.infiniteLoadingConfig,
                thresholdCheck = this.opts.gpuOptimization ? this._checkItemsthreshold : this._checkLoadingThreshold;

            if (!this.opts.infiniteLoading || !ilConfig.dataProvider) {
                Logger.log('warn', 'InfiniteLoading will not work because there is no data provider or is not activated');
                return;
            }

            if (!(ilConfig.hasTemplate && ilConfig.templateIsManualLoad)) {
                this.on('scrollMove', thresholdCheck);
                this.on('scrollEnd', thresholdCheck);
                this._itemsThreshold = this.items && this.items.length || 10;
            }
            else if (ilConfig.hasTemplate) {
                ilConfig.templateSetManualTriggerFn(function() {
                    this._triggerInfiniteLoadingDataProvider();
                }.bind(this));
            }

            this._appendInfiniteLoading();
            this._setSize();

            // option to automatically trigger data provider when a scrollbar
            // doesnt exist even though there are more data to load
            if (ilConfig.autoFillPage) {
                // initial loading might not fire a refresh event when user loads
                // data before rendering
                thresholdCheck.call(this);
                this.on('_refresh', thresholdCheck);
            }
        },
        _appendInfiniteLoading: function () {
            var ilConfig = this.opts.infiniteLoadingConfig;
            if (!ilConfig.hasTemplate) {
                var il_container = this._createInfiniteLoadingMarkup(),
                    target       = this.scroller;

                target.appendChild(il_container);

                this.ilDOM   = il_container;
                this.ilLabel = il_container.firstChild;
                this._ilSize = il_container.offsetHeight; //relayout
            }
            else {
                this.ilDOM = ilConfig.templateContainer;
            }
        },
        _setState: function (loading) {
            this._loading = loading;
            var ilConfig = this.opts.infiniteLoadingConfig;
            if (ilConfig.hasTemplate) {
                ilConfig.templateSetLoadingFn(loading);
            }
            else {
                if (loading) {
                    this.ilDOM.classList.add(CLASS_LOADING);
                    this.ilLabel.textContent = this.opts.infiniteLoadingConfig.labelLoading;
                } else {
                    this.ilDOM.classList.remove(CLASS_LOADING);
                    this.ilLabel.textContent = this.opts.infiniteLoadingConfig.labelIdle;
                }
            }
        },
        _appendData: function (items) {
            var docfrag = w.document.createDocumentFragment(),
                scrollerContainer = this.scroller,
                container = this.ilDOM;

            items.forEach(function (i) {
                docfrag.appendChild(i);
            });

            scrollerContainer.insertBefore(docfrag, container);
        },
        _getCustomAppendedElements: function () {
            return 2;
        },
        _triggerInfiniteLoadingDataProvider: function () {
            var self            = this,
                ilDataProvider  = this.opts.infiniteLoadingConfig.dataProvider,
                callback        = function() {
                    self._infiniteLoadingTriggerCallback.apply(self, arguments);
                    Logger.log('InfiniteLoading callback called');
                };

            if (ilDataProvider) {
                Logger.log('fetching data');
                this._ilFetchingData = true;
                this._setState(true/*loading*/);
                ilDataProvider(callback);
            } else {
                this._infiniteLoadingTriggerCallback('noop');
            }
        },
        _infiniteLoadingTriggerCallback: function (payload) {
            if (payload) {
                var data = payload instanceof Array ? payload: payload.data;
                if (data && data.length) {
                    this.appendItems(payload);
                }

                if (payload === 'refresh' || payload.refresh) {
                    this.refresh();
                }

                if (payload === 'nomoredata' || payload.noMoreData) {
                    this.lockFetchData();
                }

                if (payload.labelIdle) {
                    this.opts.infiniteLoadingConfig.labelIdle = payload.labelIdle;
                }

                if (payload.labelLoading) {
                    this.opts.infiniteLoadingConfig.labelLoading = payload.labelLoading;
                }
            }

            this._setState(false/*loading*/);
            w.requestAnimationFrame(function() {
                this._ilFetchingData = false;
            }.bind(this));
        },
        // This check is done when surfaceManager is enabled
        _checkItemsthreshold: function () {
            if (this._ilNoMoreData || this._ilFetchingData) {
                return;
            }

            var lastIndex  = this._positionedSurfacesLast().contentIndex,
                count      = this.items.length - 1,
                threshold  = this._itemsThreshold;

            if (count - lastIndex < threshold) {
                this._triggerInfiniteLoadingDataProvider();
            }
        },
        // This check is done when surfaceManager is disabled
        _checkLoadingThreshold: function (action, x, y) {
            if (this._ilNoMoreData || this._ilFetchingData) {
                return;
            }

            var config = this.opts.infiniteLoadingConfig,
                pos, size, wrapper;

            x || (x = this.x);
            y || (y = this.y);

            if (this.scrollVertical) {
                pos     = y;
                size    = this.scrollerHeight;
                wrapper = this.wrapperHeight;
            } else {
                pos     = x;
                size    = this.scrollerWidth;
                wrapper = this.wrapperWidth;
            }

            var scrollable = size - wrapper; // Total scrollable pixels
            var left = scrollable + pos; // Remaining px to scroll

            // Make sure that the provided thershold is never bigger
            // than the scrollable pixels to avoid extra provider calls
            var threshold = config.threshold < scrollable ? config.threshold : 0;
            threshold = Math.max(threshold, MIN_LOADING_THRESHOLD);

            Logger.log('left: ', left, 'tr: ', threshold);

            // If we have pixels to scroll
            // and less than the threshold trigger provider.
            if (this.distY !== 0 && left <= threshold) {
                Logger.log('triggerDataProvider');
                this._triggerInfiniteLoadingDataProvider();
            }
        },
        /**
         * Forces this scroller to reflow after the next aura rendering cycle.
         * This is used as a workaround for a browser bug where scroller's position is improperly rendered.
         * W-3410155
         */
        _forceReflow: function() {
            this.scroller.style.position = 'fixed';
            window.setTimeout(function() {
                this.scroller.style.position = '';
            }.bind(this), 0);
        },
        _setNoMoreData: function(noMoreData) {
            this._ilNoMoreData = noMoreData;
            var ilConfig = this.opts.infiniteLoadingConfig;
            if (ilConfig.hasTemplate) {
                ilConfig.templateSetHasMoreDataFn(!this._ilNoMoreData);
            }
        },
        /* PUBLIC API */
        fetchData: function () {
            this._triggerInfiniteLoadingDataProvider();
        },
        unlockFetchData: function () {
            this._setNoMoreData(false);
            this._ilFetchingData = false;
        },
        lockFetchData: function () {
            this._setNoMoreData(true);
        },
        updateLabels:function(payload) {
            if (typeof (payload.labelIdle) !== "undefined") {
                this.opts.infiniteLoadingConfig.labelIdle = payload.labelIdle;
            }
            if (typeof (payload.labelLoading) !== "undefined") {
                this.opts.infiniteLoadingConfig.labelLoading = payload.labelLoading;
            }
            // in order to redraw the label we have to call _setState
            this._setState(this._loading);
        }
    };

    PLUGINS.InfiniteLoading = InfiniteLoading;

}
<commit_msg>Remove _forceReflowEventListener on destroy to prevent leaks.<commit_after>/*
 * Copyright (C) 2013 salesforce.com, inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function lib(w) { //eslint-disable-line no-unused-vars
    'use strict';
    w || (w = window);

    var SCROLLER = w.__S || (w.__S = {}),
        PLUGINS  = SCROLLER.plugins || (SCROLLER.plugins = {}),
        Logger   = SCROLLER.Logger,

        CONFIG_DEFAULTS = {
            labelNoData  : 'No more data to display',
            labelIdle    : '',
            labelLoading : 'Loading more...',
            autoFillPage : false,
            threshold    : 0
        },
        CLASS_LOADING = 'loading',
        CLASS_IDLE    = 'il',

        // when zoomed, values become fractional and precision
        // is lost depending on how browsers handle it.
        // In this case, number of pixles left to scroll can be off a bit.
        // The offset is mostly less than 5.
        MIN_LOADING_THRESHOLD = 5;

    function InfiniteLoading () {}

    InfiniteLoading.prototype = {
        init: function () {
            this._mergeInfiniteLoading();
            this.on('_initialize', this._initializeInfiniteLoading);

            // Allows a forced reflow of this scroller through the firing of a global custom event, "FORCEREFLOW"
            this._reflowHandler = this._forceReflow.bind(this);
            document.addEventListener("FORCEREFLOW", this._reflowHandler);
        },
        destroy: function () {
        	document.removeEventListener("FORCEREFLOW", this._reflowHandler);
        },
        _mergeInfiniteLoading: function () {
            this.opts.infiniteLoadingConfig = this._mergeConfigOptions(
                CONFIG_DEFAULTS,
                this.opts.infiniteLoadingConfig
            );
        },
        _createInfiniteLoadingMarkup: function () {
            var il_container = w.document.createElement('div'),
                label        = document.createElement('span'),
                idleLabel    = this.opts.infiniteLoadingConfig.labelIdle;

            label.className        = CLASS_IDLE;
            label.textContent      = idleLabel;
            il_container.className = 'infinite-loading';

            il_container.appendChild(label);

            return il_container;
        },
        _initializeInfiniteLoading: function () {
            var ilConfig       = this.opts.infiniteLoadingConfig,
                thresholdCheck = this.opts.gpuOptimization ? this._checkItemsthreshold : this._checkLoadingThreshold;

            if (!this.opts.infiniteLoading || !ilConfig.dataProvider) {
                Logger.log('warn', 'InfiniteLoading will not work because there is no data provider or is not activated');
                return;
            }

            if (!(ilConfig.hasTemplate && ilConfig.templateIsManualLoad)) {
                this.on('scrollMove', thresholdCheck);
                this.on('scrollEnd', thresholdCheck);
                this._itemsThreshold = this.items && this.items.length || 10;
            }
            else if (ilConfig.hasTemplate) {
                ilConfig.templateSetManualTriggerFn(function() {
                    this._triggerInfiniteLoadingDataProvider();
                }.bind(this));
            }

            this._appendInfiniteLoading();
            this._setSize();

            // option to automatically trigger data provider when a scrollbar
            // doesnt exist even though there are more data to load
            if (ilConfig.autoFillPage) {
                // initial loading might not fire a refresh event when user loads
                // data before rendering
                thresholdCheck.call(this);
                this.on('_refresh', thresholdCheck);
            }
        },
        _appendInfiniteLoading: function () {
            var ilConfig = this.opts.infiniteLoadingConfig;
            if (!ilConfig.hasTemplate) {
                var il_container = this._createInfiniteLoadingMarkup(),
                    target       = this.scroller;

                target.appendChild(il_container);

                this.ilDOM   = il_container;
                this.ilLabel = il_container.firstChild;
                this._ilSize = il_container.offsetHeight; //relayout
            }
            else {
                this.ilDOM = ilConfig.templateContainer;
            }
        },
        _setState: function (loading) {
            this._loading = loading;
            var ilConfig = this.opts.infiniteLoadingConfig;
            if (ilConfig.hasTemplate) {
                ilConfig.templateSetLoadingFn(loading);
            }
            else {
                if (loading) {
                    this.ilDOM.classList.add(CLASS_LOADING);
                    this.ilLabel.textContent = this.opts.infiniteLoadingConfig.labelLoading;
                } else {
                    this.ilDOM.classList.remove(CLASS_LOADING);
                    this.ilLabel.textContent = this.opts.infiniteLoadingConfig.labelIdle;
                }
            }
        },
        _appendData: function (items) {
            var docfrag = w.document.createDocumentFragment(),
                scrollerContainer = this.scroller,
                container = this.ilDOM;

            items.forEach(function (i) {
                docfrag.appendChild(i);
            });

            scrollerContainer.insertBefore(docfrag, container);
        },
        _getCustomAppendedElements: function () {
            return 2;
        },
        _triggerInfiniteLoadingDataProvider: function () {
            var self            = this,
                ilDataProvider  = this.opts.infiniteLoadingConfig.dataProvider,
                callback        = function() {
                    self._infiniteLoadingTriggerCallback.apply(self, arguments);
                    Logger.log('InfiniteLoading callback called');
                };

            if (ilDataProvider) {
                Logger.log('fetching data');
                this._ilFetchingData = true;
                this._setState(true/*loading*/);
                ilDataProvider(callback);
            } else {
                this._infiniteLoadingTriggerCallback('noop');
            }
        },
        _infiniteLoadingTriggerCallback: function (payload) {
            if (payload) {
                var data = payload instanceof Array ? payload: payload.data;
                if (data && data.length) {
                    this.appendItems(payload);
                }

                if (payload === 'refresh' || payload.refresh) {
                    this.refresh();
                }

                if (payload === 'nomoredata' || payload.noMoreData) {
                    this.lockFetchData();
                }

                if (payload.labelIdle) {
                    this.opts.infiniteLoadingConfig.labelIdle = payload.labelIdle;
                }

                if (payload.labelLoading) {
                    this.opts.infiniteLoadingConfig.labelLoading = payload.labelLoading;
                }
            }

            this._setState(false/*loading*/);
            w.requestAnimationFrame(function() {
                this._ilFetchingData = false;
            }.bind(this));
        },
        // This check is done when surfaceManager is enabled
        _checkItemsthreshold: function () {
            if (this._ilNoMoreData || this._ilFetchingData) {
                return;
            }

            var lastIndex  = this._positionedSurfacesLast().contentIndex,
                count      = this.items.length - 1,
                threshold  = this._itemsThreshold;

            if (count - lastIndex < threshold) {
                this._triggerInfiniteLoadingDataProvider();
            }
        },
        // This check is done when surfaceManager is disabled
        _checkLoadingThreshold: function (action, x, y) {
            if (this._ilNoMoreData || this._ilFetchingData) {
                return;
            }

            var config = this.opts.infiniteLoadingConfig,
                pos, size, wrapper;

            x || (x = this.x);
            y || (y = this.y);

            if (this.scrollVertical) {
                pos     = y;
                size    = this.scrollerHeight;
                wrapper = this.wrapperHeight;
            } else {
                pos     = x;
                size    = this.scrollerWidth;
                wrapper = this.wrapperWidth;
            }

            var scrollable = size - wrapper; // Total scrollable pixels
            var left = scrollable + pos; // Remaining px to scroll

            // Make sure that the provided thershold is never bigger
            // than the scrollable pixels to avoid extra provider calls
            var threshold = config.threshold < scrollable ? config.threshold : 0;
            threshold = Math.max(threshold, MIN_LOADING_THRESHOLD);

            Logger.log('left: ', left, 'tr: ', threshold);

            // If we have pixels to scroll
            // and less than the threshold trigger provider.
            if (this.distY !== 0 && left <= threshold) {
                Logger.log('triggerDataProvider');
                this._triggerInfiniteLoadingDataProvider();
            }
        },
        /**
         * Forces this scroller to reflow after the next aura rendering cycle.
         * This is used as a workaround for a browser bug where scroller's position is improperly rendered.
         * W-3410155
         */
        _forceReflow: function() {
            this.scroller.style.position = 'fixed';
            window.setTimeout(function() {
                this.scroller.style.position = '';
            }.bind(this), 0);
        },
        _setNoMoreData: function(noMoreData) {
            this._ilNoMoreData = noMoreData;
            var ilConfig = this.opts.infiniteLoadingConfig;
            if (ilConfig.hasTemplate) {
                ilConfig.templateSetHasMoreDataFn(!this._ilNoMoreData);
            }
        },
        /* PUBLIC API */
        fetchData: function () {
            this._triggerInfiniteLoadingDataProvider();
        },
        unlockFetchData: function () {
            this._setNoMoreData(false);
            this._ilFetchingData = false;
        },
        lockFetchData: function () {
            this._setNoMoreData(true);
        },
        updateLabels:function(payload) {
            if (typeof (payload.labelIdle) !== "undefined") {
                this.opts.infiniteLoadingConfig.labelIdle = payload.labelIdle;
            }
            if (typeof (payload.labelLoading) !== "undefined") {
                this.opts.infiniteLoadingConfig.labelLoading = payload.labelLoading;
            }
            // in order to redraw the label we have to call _setState
            this._setState(this._loading);
        }
    };

    PLUGINS.InfiniteLoading = InfiniteLoading;

}
<|endoftext|>


<commit_before>(function($) {

  /**
   * FlipClock Russian Language Pack
   *
   * This class will used to translate tokens into the Russian language.
   *
   */

  FlipClock.Lang.French = {

    'years'   : 'лет',
    'months'  : 'месяцев',
    'days'    : 'дней',
    'hours'   : 'часов',
    'minutes' : 'минут',
    'seconds' : 'секунд'

  };

  /* Create various aliases for convenience */

  FlipClock.Lang['ru']      = FlipClock.Lang.French;
  FlipClock.Lang['ru-ru']   = FlipClock.Lang.French;
  FlipClock.Lang['russian']  = FlipClock.Lang.French;

}(jQuery));<commit_msg>Russian translation (small fix)<commit_after>(function($) {

  /**
   * FlipClock Russian Language Pack
   *
   * This class will used to translate tokens into the Russian language.
   *
   */

  FlipClock.Lang.Russian = {

    'years'   : 'лет',
    'months'  : 'месяцев',
    'days'    : 'дней',
    'hours'   : 'часов',
    'minutes' : 'минут',
    'seconds' : 'секунд'

  };

  /* Create various aliases for convenience */

  FlipClock.Lang['ru']      = FlipClock.Lang.Russian;
  FlipClock.Lang['ru-ru']   = FlipClock.Lang.Russian;
  FlipClock.Lang['russian']  = FlipClock.Lang.Russian;

}(jQuery));<|endoftext|>


<commit_before>import React from 'react'
import Modal from '../modal'
import GenericForm from '../genericform'
import { setup_fields, service_definition } from '../service'
import Loading from '../loading'
import rpc from 'app/rpc'
import { merge } from 'app/utils'

const RuleList = React.createClass({
  componentDidMount(){
    let self=this
    $(this.refs.form).find('.checkbox.toggle').checkbox({
      onChecked(ev){
        console.log("Activated rule name %o", this.name)
        self.props.activateRule(this.name)
      },
      onUnchecked(ev){
        console.log("Dectivated rule name %o", this.name)
        self.props.deactivateRule(this.name)
      }
    })
  },
  render(){
    const props = this.props
    if (props.rules.length == 0)
      return ()
    return (

Rule presets

          Here you can activate preset rules. Custom rules can be activated at the
          rules section

        {props.rules.map( (r) => (

              <input type="checkbox" className="toggle" defaultChecked={r.is_active} name={r.id}/>
              {r.name}

{r.description}

        ))}

    )
  }
})

const SetupComponent=React.createClass({
  getInitialState(){
    let fields=undefined
    if (this.props.service_catalog){
      fields = this.get_fields()
    }
    return {fields,
      values:
        Object.assign({name: this.props.service.name}, this.props.service.config),
      changed_rules: [],
      rules: undefined
    }
  },
  handleActivateRule(id){
    let rules = this.state.rules.map( (r) => {
      if (r.id == id ){
        return merge(r, {is_active: true})
      }
      return r
    })
    let changed_rules=this.state.changed_rules.concat([id])
    console.log("updated rules: %o", rules)
    this.setState({rules, changed_rules})
  },
  handleDeactivateRule(id){
    let rules = this.state.rules.map( (r) => {
      if (r.id == id ){
        return merge(r, {is_active: false})
      }
      return r
    })
    console.log("updated rules: %o", rules)
    let changed_rules=this.state.changed_rules.concat([id])
    this.setState({rules, changed_rules})
  },
  handleAccept : function(ev){
    ev && ev.preventDefault()

    let form = this.refs.form.refs.form
    if ( $(form).form('validate form' ) ){
      //console.log("Ok %o", this.state.values)
      let operations={}
      let values = this.state.values
      this.get_fields().map( (f) => {
        let v = values[f.name]
        if (v)
          operations[f.name]=v
      })
      //console.log(operations)
      let name = operations.name
      delete operations.name
      let description = operations.description
      delete operations.description
      this.props.onUpdate( this.props.service.uuid, {
        name: name,
        description: description,
        config: operations
      } )
      // Save changed rules
      console.log("Save rules %o %o", this.state.changed_rules, this.state.rules)
      this.state.rules.find( (rule) => {
        if (this.state.changed_rules.indexOf(rule.id)>=0){
          console.log("Save rule %o", rule)
          this.props.onSaveRule(rule)
        }
      })
      this.props.onClose()
    }
  },
  handleUpdateForm : function(data){
    this.setState({values:data})
  },
  get_fields(){
    if (this.state && this.state.fields)
      return this.state.fields
    return setup_fields(this.props.service, this.props.service_catalog)
  },
  componentDidMount(){
    let filter = { traits: this.props.service.traits }
    console.log(filter)
    Promise.all([
      rpc.call("rules.templates", filter),
      rpc.call("rules.list", { service: this.props.service.uuid })
    ]).then( ([templates, rules]) => {
      console.log(templates, rules)
      const decorated_templates = templates.map( (t) => {
        let r = rules.find( (r) => t.id == r.from_template )
        console.log("Found rule: %o", r)
        t = merge(t, {service: this.props.service.uuid, is_active: false, from_template: t.id } )
        if (r){
          return merge( t, {is_active: r.is_active, uuid: r.uuid} )
        }
        return t
      })
      console.log(decorated_templates)
      this.setState({rules: decorated_templates})
    })
  },
  render(){
    const rules=this.state.rules || []

    let props=this.props
    let state=this.state
    if (!props.service_catalog)
      return (
        <Loading>
        Service catalog
        </Loading>
      )
    let fields = state.fields
    if (!fields)
      fields=this.get_fields()
    let servicedef=service_definition(this.props.service.type, this.props.service_catalog)
    return (
      <Modal onClose={props.onClose}>

          Update settings for {props.service.name}

          {servicedef.description || "No description at service definition"}

          <GenericForm ref="form" fields={fields} updateForm={this.handleUpdateForm} onSubmit={this.handleAccept}/>

        <RuleList rules={rules} activateRule={this.handleActivateRule} deactivateRule={this.handleDeactivateRule}/>

          <button className="ui ok yellow button" onClick={this.handleAccept}>Accept</button>

      </Modal>
    )
  }
})

export default SetupComponent
<commit_msg>Fix cant toggel rule templates some times<commit_after>import React from 'react'
import Modal from '../modal'
import GenericForm from '../genericform'
import { setup_fields, service_definition } from '../service'
import Loading from '../loading'
import rpc from 'app/rpc'
import { merge } from 'app/utils'

const RuleList = React.createClass({
  componentDidMount(){
    this.updateToggles( $(this.refs.form).find('.checkbox.toggle') )
  },
  updateToggles(sel){
    let self=this
    $(sel).checkbox({
      onChecked(ev){
        console.log("Activated rule name %o", this.name)
        self.props.activateRule(this.name)
      },
      onUnchecked(ev){
        console.log("Dectivated rule name %o", this.name)
        self.props.deactivateRule(this.name)
      }
    })
  },
  componentDidUpdate(newprops){
    this.updateToggles( $(this.refs.form).find('.checkbox.toggle') )
  },
  render(){
    const props = this.props
    if (props.rules.length == 0)
      return ()
    return (

Rule presets

          Here you can activate preset rules. Custom rules can be activated at the
          rules section

        {props.rules.map( (r) => (

              <input type="checkbox" className="toggle" defaultChecked={r.is_active} name={r.id}/>
              {r.name}

{r.description}

        ))}

    )
  }
})

const SetupComponent=React.createClass({
  getInitialState(){
    let fields=undefined
    if (this.props.service_catalog){
      fields = this.get_fields()
    }
    return {fields,
      values:
        Object.assign({name: this.props.service.name}, this.props.service.config),
      changed_rules: [],
      rules: undefined
    }
  },
  handleActivateRule(id){
    let rules = this.state.rules.map( (r) => {
      if (r.id == id ){
        return merge(r, {is_active: true})
      }
      return r
    })
    let changed_rules=this.state.changed_rules.concat([id])
    console.log("updated rules: %o", rules)
    this.setState({rules, changed_rules})
  },
  handleDeactivateRule(id){
    let rules = this.state.rules.map( (r) => {
      if (r.id == id ){
        return merge(r, {is_active: false})
      }
      return r
    })
    console.log("updated rules: %o", rules)
    let changed_rules=this.state.changed_rules.concat([id])
    this.setState({rules, changed_rules})
  },
  handleAccept : function(ev){
    ev && ev.preventDefault()

    let form = this.refs.form.refs.form
    if ( $(form).form('validate form' ) ){
      //console.log("Ok %o", this.state.values)
      let operations={}
      let values = this.state.values
      this.get_fields().map( (f) => {
        let v = values[f.name]
        if (v)
          operations[f.name]=v
      })
      //console.log(operations)
      let name = operations.name
      delete operations.name
      let description = operations.description
      delete operations.description
      this.props.onUpdate( this.props.service.uuid, {
        name: name,
        description: description,
        config: operations
      } )
      // Save changed rules
      console.log("Save rules %o %o", this.state.changed_rules, this.state.rules)
      this.state.rules.find( (rule) => {
        if (this.state.changed_rules.indexOf(rule.id)>=0){
          console.log("Save rule %o", rule)
          this.props.onSaveRule(rule)
        }
      })
      this.props.onClose()
    }
  },
  handleUpdateForm : function(data){
    this.setState({values:data})
  },
  get_fields(){
    if (this.state && this.state.fields)
      return this.state.fields
    return setup_fields(this.props.service, this.props.service_catalog)
  },
  componentDidMount(){
    let filter = { traits: this.props.service.traits }
    console.log(filter)
    Promise.all([
      rpc.call("rules.templates", filter),
      rpc.call("rules.list", { service: this.props.service.uuid })
    ]).then( ([templates, rules]) => {
      console.log(templates, rules)
      const decorated_templates = templates.map( (t) => {
        let r = rules.find( (r) => t.id == r.from_template )
        console.log("Found rule: %o", r)
        t = merge(t, {service: this.props.service.uuid, is_active: false, from_template: t.id } )
        if (r){
          return merge( t, {is_active: r.is_active, uuid: r.uuid} )
        }
        return t
      })
      console.log(decorated_templates)
      this.setState({rules: decorated_templates})
    })
  },
  render(){
    const rules=this.state.rules || []

    let props=this.props
    let state=this.state
    if (!props.service_catalog)
      return (
        <Loading>
        Service catalog
        </Loading>
      )
    let fields = state.fields
    if (!fields)
      fields=this.get_fields()
    let servicedef=service_definition(this.props.service.type, this.props.service_catalog)
    return (
      <Modal onClose={props.onClose}>

          Update settings for {props.service.name}

          {servicedef.description || "No description at service definition"}

          <GenericForm ref="form" fields={fields} updateForm={this.handleUpdateForm} onSubmit={this.handleAccept}/>

        <RuleList rules={rules} activateRule={this.handleActivateRule} deactivateRule={this.handleDeactivateRule}/>

          <button className="ui ok yellow button" onClick={this.handleAccept}>Accept</button>

      </Modal>
    )
  }
})

export default SetupComponent
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

CLASS({
  package: 'foam.tools',
  name: 'GenNative',
  properties: [
    {
      name: 'name',
      help: 'ID of the model to serialize',
    },
    {
      name: 'names',
      help: 'space separated list of files.',
    },
    {
      name: 'blacklist',
      help: 'space separated list of files to not include (which can happen ' +
          'when adding dependencies).',
    },
    {
      name: 'modelFile',
    },
    {
      name: 'outfolder',
      require: true
    },
    {
      name: 'fs',
      factory: function() { return require('fs'); }
    },
    {
      name: 'template',
    },
    {
      name: 'fileExtension',
    },
    {
      name: 'requiredDeps',
      defaultValue: [],
    },
  ],
  methods: [
    function execute() {
      if ( ! this.outfolder) {
        console.log("ERROR: outfolder not specified");
        process.exit(1);
      }

      var blacklist = this.blacklist && this.blacklist.split(' ') || [];
      var names = this.names && this.names.split(' ') || [];
      names = names.concat(this.requiredDeps);
      names.push(
        // Required if a property is imported.
        'ImportedProperty'
      );
      this.name && names.push(this.name);
      names = names.filter(function(n) { return n; });
      var i = 0;
      awhile(function() { return i < names.length },
        aseq(
          aif(!!this.modelFile,
              function(ret) {
                console.log("Reading model from", this.modelFile);
                var data = this.fs.readFileSync(this.modelFile).toString();
                var work = [anop];
                var model = JSONUtil.parse(this.X, data, work);

                if ( work.length > 1 ) {
                  work.push(aconstant(model));
                  aseq.apply(null, work)(ret);
                  return;
                }
                ret(model);
              }.bind(this),
              function(ret) {
                var name = names[i];
                console.log("Loading", name);
                this.X.arequire(name)(ret)
              }.bind(this)),
          function(ret, m) {
            if (m.getPrototype) m = m.getPrototype().model_
            if ( !m ) {
              console.log("ERROR: Could not load model");
              process.exit(1);
            }

            var template = this.template.create()
            var destination =
                this.outfolder + '/' + m.name + '.' + this.fileExtension;
            console.log(
                "Writing", m.id, this.fileExtension, "source to", destination);
            this.fs.writeFileSync(
              destination,
              template.generate(m));

            var requires = [];
            if (m.getAllRequires) {
              m = template.prepModel(m);
              if (m.getAllRequires) {
                requires = requires.concat(m.getAllRequires());
              }
            }
            requires = requires.concat(this.getExtraRequires(m));

            requires.forEach(function(dep) {
              if (dep && names.indexOf(dep) == -1 &&
                  blacklist.indexOf(dep) == -1) {
                console.log('Adding dependency', dep);
                names.push(dep);
              }
            });

            i++;
            ret();
          }.bind(this))
        )(function(){
          process.exit(0);
        });
    },
    function getExtraRequires(m) {
      return [];
    }
  ],
});
<commit_msg>Remove GenNative.<commit_after><|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

CLASS({
  package: 'foam.u2',
  name: 'ElementValue',

  constants: {
    __isValue__: true
  },

  properties: [
    [ 'property', 'value' ],
    [ 'event', 'change' ],
    [ 'firstListener_', true ],
    {
      name: 'element',
      required: true
    },
    {
      name: 'value',
      postSet: function(_, value) { this.element.setAttribute(this.property, value); }
    }
  ],

  listeners: [
    {
      name: 'onAttrValueChange',
      code: function() {
        console.log('pre value change ', this.value);
        this.value = this.element.id$el ?
          this.element.id$el[this.property] :
          this.element.getAttribute(this.property) ;
        console.log('post value change ', this.value);
      }
    }
  ],

  methods: {
    init: function() {
      this.SUPER();
      this.onAttrValueChange();
    },

    get: function() { return this.value; },

    set: function(value) { this.value = value; },

    addListener: function(listener) {
      if ( this.firstListener_ ) {
        if ( this.event )
          this.element.on(this.event, this.onAttrValueChange, false);

        this.firstListener_ = false;
      }
      this.value$.addListener(listener);
    },

    removeListener: function(listener) {
      this.value$.removeListener(listener);
    },

    toString: function() {
      return 'ElementValue(' + this.event + ', ' + this.property + ')';
    }
  }
});
<commit_msg>Removed console logging.<commit_after>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

CLASS({
  package: 'foam.u2',
  name: 'ElementValue',

  constants: {
    __isValue__: true
  },

  properties: [
    [ 'property', 'value' ],
    [ 'event', 'change' ],
    [ 'firstListener_', true ],
    {
      name: 'element',
      required: true
    },
    {
      name: 'value',
      postSet: function(_, value) { this.element.setAttribute(this.property, value); }
    }
  ],

  listeners: [
    {
      name: 'onAttrValueChange',
      code: function() {
        this.value = this.element.id$el ?
          this.element.id$el[this.property] :
          this.element.getAttribute(this.property) ;
      }
    }
  ],

  methods: {
    init: function() {
      this.SUPER();
      this.onAttrValueChange();
    },

    get: function() { return this.value; },

    set: function(value) { this.value = value; },

    addListener: function(listener) {
      if ( this.firstListener_ ) {
        if ( this.event )
          this.element.on(this.event, this.onAttrValueChange, false);

        this.firstListener_ = false;
      }
      this.value$.addListener(listener);
    },

    removeListener: function(listener) {
      this.value$.removeListener(listener);
    },

    toString: function() {
      return 'ElementValue(' + this.event + ', ' + this.property + ')';
    }
  }
});
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

CLASS({
  package: 'foam.u2',
  name: 'PropertyView',

  extends: 'foam.u2.Element',

  requires: [
    'Property',
    'foam.u2.Input'
  ],

  imports: [ 'data$' ],

  properties: [
    {
      name: 'data',
      postSet: function(old, nu) {
        this.bindData_(old, nu);
      },
    },
    {
      name: 'prop'
    },
    {
      name: 'view'
    },
    {
      name: 'child_',
    },
    [ 'nodeName', 'tr' ]
  ],

  methods: [
    function init() {
      var view = this.view || this.prop.toPropertyE();
      var prop = this.prop;

      // TODO: remove check once all views extend View
      view.fromProperty && view.fromProperty(prop);

      this.child_ = view;

      // Will call initE.
      this.SUPER();

      this.bindData_(null, this.data);
    },
    function initE() {
      this.cls('foam-u2-PropertyView').add(this.child_);
    }
  ],

  listeners: [
    function bindData_(old, nu) {
      if (!this.child_) return;
      if (old)
        Events.unlink(old.propertyValue(this.prop.name), this.child_.data$);
      if (nu)
        Events.link(nu.propertyValue(this.prop.name), this.child_.data$);
    },
  ]
});
<commit_msg>u2.PropertyView: Import both data and data$ to ensure that exported 'values' and 'Values' appear on this.<commit_after>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

CLASS({
  package: 'foam.u2',
  name: 'PropertyView',

  extends: 'foam.u2.Element',

  requires: [
    'Property',
    'foam.u2.Input'
  ],

  imports: [
    'data',
    'data$',
  ],

  properties: [
    {
      name: 'prop'
    },
    {
      name: 'view'
    },
    {
      name: 'child_',
    },
    [ 'nodeName', 'tr' ]
  ],

  methods: [
    function init() {
      var view = this.view || this.prop.toPropertyE();
      var prop = this.prop;

      // TODO: remove check once all views extend View
      view.fromProperty && view.fromProperty(prop);

      this.child_ = view;

      // Will call initE.
      this.SUPER();

      this.bindData_(null, this.data);
    },
    function initE() {
      this.cls('foam-u2-PropertyView').add(this.child_);
    }
  ],

  listeners: [
    function bindData_(old, nu) {
      if (!this.child_) return;
      if (old)
        Events.unlink(old.propertyValue(this.prop.name), this.child_.data$);
      if (nu)
        Events.link(nu.propertyValue(this.prop.name), this.child_.data$);
    },
  ]
});
<|endoftext|>