<commit_before>
var primitivemap = require('primitivemap')

var CommitLog = require('./commitlog')
var bin = require('./bin')

var EDIT_PUT = 1
var CODE_INDEX = 4

function makeEditBufferPutStringString(code,p1,p2){
	var len1 = Buffer.byteLength(p1)
	var len2 = Buffer.byteLength(p2)
	var b = new Buffer(14+len1+len2)
	bin.writeInt(b,0,b.length)
	b[CODE_INDEX] = code
	bin.writeInt(b,5,len1)
	bin.writeInt(b,9,len2)
	b.write(p1,13)
	b.write(p2,13+len1)
	return b
}

function doPutStringString(w,edit){
	var len1 = bin.readInt(edit,5)
	var len2 = bin.readInt(edit,9)

	var n2 = 13+len1
	w.put(edit.toString('utf8',13,n2),edit.toString('utf8',n2,n2+len2))
}

function makeEditBufferPutIntInt(code,p1,p2){
	var b = new Buffer(14)
	bin.writeInt(b,0,b.length)
	b[CODE_INDEX] = code
	bin.writeInt(b,5,p1)
	bin.writeInt(b,9,p2)
	return b
}

function doPutIntInt(w,edit){
	w.put(bin.readInt(edit,5),bin.readInt(edit,9))
}

function StringStringMap(name, cb){
	var m = this
	var w = this.w = new primitivemap.StringStringMap()
	this.c = new CommitLog(name, function(edit){
		if(edit[CODE_INDEX] === EDIT_PUT){
			doPutStringString(w,edit)
		}else{
			throw new Error('unknown edit type: ' + JSON.stringify(edit))
		}
	},function(){cb(m);})
}

StringStringMap.prototype.put = function(key, value){
	this.w.put(key, value)
	this.c.writeEdit(makeEditBufferPutStringString(EDIT_PUT,key,value))
}

function genericGet(key){
	return this.w.get(key)
}
function genericClose(cb){
	this.c.close(cb)
}
function genericSize(){
	return this.w.size
}

StringStringMap.prototype.get = genericGet
StringStringMap.prototype.close = genericClose
StringStringMap.prototype.size = genericSize

function IntIntMap(name, cb){
	var m = this
	var w = this.w = new primitivemap.IntIntMap()
	this.c = new CommitLog(name, function(edit){
		if(edit[CODE_INDEX] === EDIT_PUT){
			doPutIntInt(w,edit)
		}else{
			throw new Error('unknown edit type: ' + JSON.stringify(edit))
		}
	},function(){cb(m);})
}
IntIntMap.prototype.put = function(key, value){
	this.w.put(key, value)
	this.c.writeEdit(makeEditBufferPutIntInt(EDIT_PUT,key,value))
}
IntIntMap.prototype.get = genericGet
//IntIntMap.prototype.put = genericPut
IntIntMap.prototype.close = genericClose
IntIntMap.prototype.size = genericSize

function IntLongMap(name, cb){
	var m = this
	var w = this.w = new primitivemap.IntLongMap()
	this.c = new CommitLog(name, function(edit){
		if(edit.type === 'put'){
			w.put(edit.key,edit.value)
		}else{
			throw new Error('unknown edit type: ' + JSON.stringify(edit))
		}
	},function(){cb(m);})
}
IntLongMap.prototype.get = genericGet
//IntLongMap.prototype.put = genericPut
IntLongMap.prototype.close = genericClose
IntLongMap.prototype.size = genericSize

exports.makeStringStringMap = function(name,cb){return new StringStringMap(name,cb);}
exports.makeIntIntMap = function(name,cb){return new IntIntMap(name,cb);}
exports.makeIntLongMap = function(name,cb){return new IntLongMap(name,cb);}

<commit_msg>initial commit<commit_after>
var primitivemap = require('primitivemap')

var CommitLog = require('./commitlog')
var bin = require('./bin')

var EDIT_PUT = 1
var CODE_INDEX = 4

function makeEditBufferPutStringString(code,p1,p2){
	var len1 = Buffer.byteLength(p1)
	var len2 = Buffer.byteLength(p2)
	var b = new Buffer(14+len1+len2)
	bin.writeInt(b,0,b.length)
	b[CODE_INDEX] = code
	bin.writeInt(b,5,len1)
	bin.writeInt(b,9,len2)
	b.write(p1,13)
	b.write(p2,13+len1)
	return b
}

function doPutStringString(w,edit){
	var len1 = bin.readInt(edit,5)
	var len2 = bin.readInt(edit,9)

	var n2 = 13+len1
	w.put(edit.toString('utf8',13,n2),edit.toString('utf8',n2,n2+len2))
}

function makeEditBufferPutIntInt(code,p1,p2){
	var b = new Buffer(14)
	bin.writeInt(b,0,b.length)
	b[CODE_INDEX] = code
	bin.writeInt(b,5,p1)
	bin.writeInt(b,9,p2)
	return b
}

function doPutIntInt(w,edit){
	w.put(bin.readInt(edit,5),bin.readInt(edit,9))
}

function makeEditBufferPutIntLong(code,p1,p2){
	var b = new Buffer(18)
	bin.writeInt(b,0,b.length)
	b[CODE_INDEX] = code
	bin.writeInt(b,5,p1)
	bin.writeLong(b,9,p2)
	return b
}

function doPutIntLong(w,edit){
	w.put(bin.readInt(edit,5),bin.readLong(edit,9))
}
function StringStringMap(name, cb){
	var m = this
	var w = this.w = new primitivemap.StringStringMap()
	this.c = new CommitLog(name, function(edit){
		if(edit[CODE_INDEX] === EDIT_PUT){
			doPutStringString(w,edit)
		}else{
			throw new Error('unknown edit type: ' + JSON.stringify(edit))
		}
	},function(){cb(m);})
}

StringStringMap.prototype.put = function(key, value){
	this.w.put(key, value)
	this.c.writeEdit(makeEditBufferPutStringString(EDIT_PUT,key,value))
}

function genericGet(key){
	return this.w.get(key)
}
function genericClose(cb){
	this.c.close(cb)
}
function genericSize(){
	return this.w.size
}

StringStringMap.prototype.get = genericGet
StringStringMap.prototype.close = genericClose
StringStringMap.prototype.size = genericSize

function IntIntMap(name, cb){
	var m = this
	var w = this.w = new primitivemap.IntIntMap()
	this.c = new CommitLog(name, function(edit){
		if(edit[CODE_INDEX] === EDIT_PUT){
			doPutIntInt(w,edit)
		}else{
			throw new Error('unknown edit type: ' + JSON.stringify(edit))
		}
	},function(){cb(m);})
}
IntIntMap.prototype.put = function(key, value){
	this.w.put(key, value)
	this.c.writeEdit(makeEditBufferPutIntInt(EDIT_PUT,key,value))
}
IntIntMap.prototype.get = genericGet
IntIntMap.prototype.close = genericClose
IntIntMap.prototype.size = genericSize

function IntLongMap(name, cb){
	var m = this
	var w = this.w = new primitivemap.IntLongMap()
	this.c = new CommitLog(name, function(edit){
		if(edit.type === 'put'){
			doPutIntLong(w,edit)
		}else{
			throw new Error('unknown edit type: ' + JSON.stringify(edit))
		}
	},function(){cb(m);})
}
IntLongMap.prototype.put = function(key, value){
	this.w.put(key, value)
	this.c.writeEdit(makeEditBufferPutIntLong(EDIT_PUT,key,value))
}
IntLongMap.prototype.get = genericGet
IntLongMap.prototype.close = genericClose
IntLongMap.prototype.size = genericSize

exports.makeStringStringMap = function(name,cb){return new StringStringMap(name,cb);}
exports.makeIntIntMap = function(name,cb){return new IntIntMap(name,cb);}
exports.makeIntLongMap = function(name,cb){return new IntLongMap(name,cb);}

<|endoftext|>


<commit_before>import React, { Component } from 'react'
import configureStore from './store'
import { addLocalizationData } from 'rmw-shell/lib/locales'
import locales from './locales'
import App from 'rmw-shell'
import { Helmet } from 'react-helmet'
import config from './config'
import { withA2HS } from 'a2hs'

addLocalizationData(locales)

class Main extends Component {
  componentDidMount () {
    const { setA2HPState } = this.props
    console.log(this.props)
    // setA2HPState({ isAppInstallable: true })
  }

  render () {
    return

      <Helmet>
        <link async type='text/css' rel='stylesheet' href='https://cdn.firebase.com/libs/firebaseui/3.0.0/firebaseui.css' />
        <link async rel='stylesheet' href='https://fonts.googleapis.com/icon?family=Material+Icons' />
        <link async rel='stylesheet' href='index.css' />
      </Helmet>

      <App appConfig={{ configureStore, ...config }} />

  }
}

export default withA2HS(Main)
<commit_msg>Removed unused variable<commit_after>import React, { Component } from 'react'
import configureStore from './store'
import { addLocalizationData } from 'rmw-shell/lib/locales'
import locales from './locales'
import App from 'rmw-shell'
import { Helmet } from 'react-helmet'
import config from './config'
import { withA2HS } from 'a2hs'

addLocalizationData(locales)

class Main extends Component {
  componentDidMount() {
    //const { setA2HPState } = this.props
    //console.log(this.props)
    // setA2HPState({ isAppInstallable: true })
  }

  render() {
    return

      <Helmet>
        <link async type='text/css' rel='stylesheet' href='https://cdn.firebase.com/libs/firebaseui/3.0.0/firebaseui.css' />
        <link async rel='stylesheet' href='https://fonts.googleapis.com/icon?family=Material+Icons' />
        <link async rel='stylesheet' href='index.css' />
      </Helmet>

      <App appConfig={{ configureStore, ...config }} />

  }
}

export default withA2HS(Main)
<|endoftext|>


<commit_before>import React from 'react';
import {
  Animated,
  Dimensions,
  Easing,
  Modal,
  Platform,
  StyleSheet,
  TouchableWithoutFeedback,
  View,
} from 'react-native';

import PropTypes from 'prop-types';

class Menu extends React.Component {
  static propTypes = {
    button: PropTypes.node.isRequired,
    children: PropTypes.node.isRequired,
    style: View.propTypes.style,
  };

  state = {
    modalOpen: false,
    animationStarted: false,

    top: 0,
    left: 0,

    menuWidth: 0,
    menuHeight: 0,

    buttonWidth: 0,
    buttonHeight: 0,

    menuSizeAnimation: new Animated.ValueXY({ x: 0, y: 0 }),
    opacityAnimation: new Animated.Value(0),
  };

  _animationDuration = 300;
  _menuPaddingVertical = 8;
  _container = null;
  _easing = Easing.bezier(0.4, 0, 0.2, 1);

  // Start menu animation
  _onMenulLayout = e => {
    if (this.state.animationStarted) {
      return;
    }

    const { width, height } = e.nativeEvent.layout;
    const menuHeightWithPadding = height - this._menuPaddingVertical * 2;

    this.setState(
      {
        animationStarted: true,
        menuWidth: width,
        menuHeight: height,
      },
      () => {
        Animated.parallel([
          Animated.timing(this.state.menuSizeAnimation, {
            toValue: { x: width, y: menuHeightWithPadding },
            duration: this._animationDuration,
            easing: this._easing,
          }),
          Animated.timing(this.state.opacityAnimation, {
            toValue: 1,
            duration: this._animationDuration,
            easing: this._easing,
          }),
        ]).start();
      },
    );
  };

  // Save button width and height for menu layout
  _onButtonLayout = e => {
    const { width, height } = e.nativeEvent.layout;
    this.setState({ buttonWidth: width, buttonHeight: height });
  };

  _setContainerRef = ref => {
    this._container = ref;
  };

  show = () => {
    this._container.measureInWindow((x, y) => {
      this.setState({ modalOpen: true, top: y, left: x });
    });
  };

  hide = () => {
    Animated.timing(this.state.opacityAnimation, {
      toValue: 0,
      duration: this._animationDuration,
      easing: this._easing,
    }).start(() =>
      // Reset state
      this.setState({
        modalOpen: false,
        animationStarted: false,
        menuSizeAnimation: new Animated.ValueXY({ x: 0, y: 0 }),
        opacityAnimation: new Animated.Value(0),
      }),
    );
  };

  render() {
    const dimensions = Dimensions.get('screen');

    const { menuSizeAnimation } = this.state;
    const menuSize = {
      width: menuSizeAnimation.x,
      height: menuSizeAnimation.y,
    };

    // Adjust position of menu
    let { left, top } = this.state;
    const transforms = [];

    // If menu hits right
    if (left > dimensions.width - this.state.menuWidth) {
      transforms.push({
        translateX: Animated.multiply(menuSizeAnimation.x, -1),
      });

      left += this.state.buttonWidth;
    }

    // If menu hits bottom
    if (top > dimensions.height - this.state.menuHeight) {
      transforms.push({
        translateY: Animated.multiply(menuSizeAnimation.y, -1),
      });

      top += this.state.buttonHeight - this._menuPaddingVertical * 2;
    }

    const shadowMenuContainerStyle = {
      paddingVertical: this._menuPaddingVertical,
      opacity: this.state.opacityAnimation,
      transform: transforms,
      left,
      top,
    };

    return (
      <View ref={this._setContainerRef} collapsable={false}>
        <View onLayout={this._onButtonLayout}>{this.props.button}</View>

        <Modal
          visible={this.state.modalOpen}
          onRequestClose={this.hide}
          transparent
        >
          <TouchableWithoutFeedback onPress={this.hide}>
            <View style={StyleSheet.absoluteFill}>
              <Animated.View
                onLayout={this._onMenulLayout}
                style={[
                  styles.shadowMenuContainer,
                  shadowMenuContainerStyle,
                  this.props.style,
                ]}
              >
                <Animated.View
                  style={[
                    styles.menuContainer,
                    this.state.animationStarted && menuSize,
                  ]}
                >
                  {this.props.children}
                </Animated.View>
              </Animated.View>
            </View>
          </TouchableWithoutFeedback>
        </Modal>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  shadowMenuContainer: {
    position: 'absolute',
    backgroundColor: 'white',
    borderRadius: 2,
    opacity: 0,

    // Shadow
    ...Platform.select({
      ios: {
        shadowColor: 'black',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.14,
        shadowRadius: 2,
      },
      android: {
        elevation: 2,
      },
    }),
  },

  menuContainer: {
    overflow: 'hidden',
  },
});

export default Menu;
<commit_msg>Simplification of component state<commit_after>import React from 'react';
import {
  Animated,
  Dimensions,
  Easing,
  Modal,
  Platform,
  StyleSheet,
  TouchableWithoutFeedback,
  View,
} from 'react-native';

import PropTypes from 'prop-types';

const STATES = {
  HIDE: 'HIDE',
  SHOW: 'SHOW',
  ANIMATE: 'ANIMATE',
};

class Menu extends React.Component {
  static propTypes = {
    button: PropTypes.node.isRequired,
    children: PropTypes.node.isRequired,
    style: View.propTypes.style,
  };

  state = {
    menuState: STATES.HIDE,

    top: 0,
    left: 0,

    menuWidth: 0,
    menuHeight: 0,

    buttonWidth: 0,
    buttonHeight: 0,

    menuSizeAnimation: new Animated.ValueXY({ x: 0, y: 0 }),
    opacityAnimation: new Animated.Value(0),
  };

  _animationDuration = 300;
  _menuPaddingVertical = 8;
  _container = null;
  _easing = Easing.bezier(0.4, 0, 0.2, 1);

  // Start menu animation
  _onMenulLayout = e => {
    if (this.state.menuState === STATES.ANIMATE) {
      return;
    }

    const { width, height } = e.nativeEvent.layout;
    const menuHeightWithPadding = height - this._menuPaddingVertical * 2;

    this.setState(
      {
        menuState: STATES.ANIMATE,
        menuWidth: width,
        menuHeight: height,
      },
      () => {
        Animated.parallel([
          Animated.timing(this.state.menuSizeAnimation, {
            toValue: { x: width, y: menuHeightWithPadding },
            duration: this._animationDuration,
            easing: this._easing,
          }),
          Animated.timing(this.state.opacityAnimation, {
            toValue: 1,
            duration: this._animationDuration,
            easing: this._easing,
          }),
        ]).start();
      },
    );
  };

  // Save button width and height for menu layout
  _onButtonLayout = e => {
    const { width, height } = e.nativeEvent.layout;
    this.setState({ buttonWidth: width, buttonHeight: height });
  };

  _setContainerRef = ref => {
    this._container = ref;
  };

  show = () => {
    this._container.measureInWindow((x, y) => {
      this.setState({ menuState: STATES.SHOW, top: y, left: x });
    });
  };

  hide = () => {
    Animated.timing(this.state.opacityAnimation, {
      toValue: 0,
      duration: this._animationDuration,
      easing: this._easing,
    }).start(() =>
      // Reset state
      this.setState({
        menuState: STATES.HIDE,
        menuSizeAnimation: new Animated.ValueXY({ x: 0, y: 0 }),
        opacityAnimation: new Animated.Value(0),
      }),
    );
  };

  render() {
    const dimensions = Dimensions.get('screen');

    const { menuSizeAnimation } = this.state;
    const menuSize = {
      width: menuSizeAnimation.x,
      height: menuSizeAnimation.y,
    };

    // Adjust position of menu
    let { left, top } = this.state;
    const transforms = [];

    // If menu hits right
    if (left > dimensions.width - this.state.menuWidth) {
      transforms.push({
        translateX: Animated.multiply(menuSizeAnimation.x, -1),
      });

      left += this.state.buttonWidth;
    }

    // If menu hits bottom
    if (top > dimensions.height - this.state.menuHeight) {
      transforms.push({
        translateY: Animated.multiply(menuSizeAnimation.y, -1),
      });

      top += this.state.buttonHeight - this._menuPaddingVertical * 2;
    }

    const shadowMenuContainerStyle = {
      paddingVertical: this._menuPaddingVertical,
      opacity: this.state.opacityAnimation,
      transform: transforms,
      left,
      top,
    };

    const { menuState } = this.state;
    const animationStarted = menuState === STATES.ANIMATE;
    const modalVisible = menuState === STATES.SHOW || animationStarted;

    return (
      <View ref={this._setContainerRef} collapsable={false}>
        <View onLayout={this._onButtonLayout}>{this.props.button}</View>

        <Modal visible={modalVisible} onRequestClose={this.hide} transparent>
          <TouchableWithoutFeedback onPress={this.hide}>
            <View style={StyleSheet.absoluteFill}>
              <Animated.View
                onLayout={this._onMenulLayout}
                style={[
                  styles.shadowMenuContainer,
                  shadowMenuContainerStyle,
                  this.props.style,
                ]}
              >
                <Animated.View
                  style={[styles.menuContainer, animationStarted && menuSize]}
                >
                  {this.props.children}
                </Animated.View>
              </Animated.View>
            </View>
          </TouchableWithoutFeedback>
        </Modal>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  shadowMenuContainer: {
    position: 'absolute',
    backgroundColor: 'white',
    borderRadius: 2,
    opacity: 0,

    // Shadow
    ...Platform.select({
      ios: {
        shadowColor: 'black',
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.14,
        shadowRadius: 2,
      },
      android: {
        elevation: 2,
      },
    }),
  },

  menuContainer: {
    overflow: 'hidden',
  },
});

export default Menu;
<|endoftext|>


<commit_before>import React, {Component} from 'react'
import {observer} from 'mobx'

class Menu extends Component{
    render(){
        const closeStyle = {
            color: 'darkred'
        }
        let search = this.props.store.search
        let create = this.props.store.create
        let viewAll = this.props.store.viewAll
        return (

{search ? "click again to close" : null}

                        Search records

{create ? "click again to close" : null}

                        Create new donor

{viewAll ? "click again to close" : null}

                        View all donors

        )
    }
     toggleSearch = () => {
         this.props.store.toggleSearch()
     }
     toggleCreate = () => {
         this.props.store.toggleCreate()
     }
     toggleViewAll = () => {
         this.props.store.toggleViewAll()
     }
}

export default Menu<commit_msg>updated menu<commit_after>import React, {Component} from 'react'
import {observer} from 'mobx'

class Menu extends Component{
    render(){
        const closeStyle = {
            color: 'darkred'
        }
        let search = this.props.store.search
        let create = this.props.store.create
        let viewAll = this.props.store.viewAll
        return (

{search ? "click again to close" : null}

                        Search records

{create ? "click again to close" : null}

                        Create new donor

{viewAll ? "click again to close" : null}

                        View all donors

        )
    }
     toggleSearch = () => {
         this.props.store.toggleSearch()
     }
     toggleCreate = () => {
         this.props.store.toggleCreate()
     }
     toggleViewAll = () => {
         this.props.store.toggleViewAll()
     }
}

export default Menu<|endoftext|>


<commit_before>import h from 'hyperscript';
import c from './utils/prefixClass';

class Page {
  constructor() {
    this.flowContent = h(c('.content'));
    this.flowBox = h(c('.flowbox'), this.flowContent);
    this.footer = h(c('.footer'));
    this.background = h(c('.background'));
    this.element = h(c('.page') + c('.page-size'),
      this.background,
      this.flowBox,
      this.footer,
    );
  }
  overflowAmount() {
    const contentH = this.flowContent.offsetHeight;
    const boxH = this.flowBox.offsetHeight;

    if (boxH === 0) {
      throw Error('Bindery: Trying to flow into a box of zero height.');
    }

    return contentH - boxH;
  }
  hasOverflowed() {
    return this.overflowAmount() > -5;
  }

  static isSizeValid() {
    document.body.classList.remove(c('viewing'));

    const testPage = new Page();
    let measureArea = document.querySelector(c('.measure-area'));
    if (!measureArea) measureArea = document.body.appendChild(h(c('.measure-area')));

    measureArea.innerHTML = '';
    measureArea.appendChild(testPage.element);
    const box = testPage.flowBox.getBoundingClientRect();

    measureArea.parentNode.removeChild(measureArea);

    return (box.height > 100) && (box.width > 100); // TODO: Number is arbitrary
  }

  setLeftRight(dir) {
    if (dir === 'left') {
      this.side = dir;
      this.element.classList.remove(c('right'));
      this.element.classList.add(c('left'));
    } else if (dir === 'right') {
      this.side = dir;
      this.element.classList.remove(c('left'));
      this.element.classList.add(c('right'));
    } else {
      throw Error(`Bindery: Setting page to invalid direction${dir}`);
    }
  }

  get suppressErrors() {
    return this.suppress || false;
  }

  set suppressErrors(newVal) {
    this.suppress = newVal;
    if (newVal) {
      this.element.classList.add(c('is-overflowing'));
    } else {
      this.element.classList.remove(c('is-overflowing'));
    }
  }

  get isEmpty() {
    return this.flowContent.textContent.trim() === '';
  }

  get isLeft() {
    return this.side === 'left';
  }

  get isRight() {
    return this.side === 'right';
  }

  setPreference(dir) {
    if (dir === 'left') this.alwaysLeft = true;
    if (dir === 'right') this.alwaysRight = true;
  }
}

export default Page;
<commit_msg>Potential fix for isEmpty<commit_after>import h from 'hyperscript';
import c from './utils/prefixClass';

class Page {
  constructor() {
    this.flowContent = h(c('.content'));
    this.flowBox = h(c('.flowbox'), this.flowContent);
    this.footer = h(c('.footer'));
    this.background = h(c('.background'));
    this.element = h(c('.page') + c('.page-size'),
      this.background,
      this.flowBox,
      this.footer,
    );
  }
  overflowAmount() {
    const contentH = this.flowContent.offsetHeight;
    const boxH = this.flowBox.offsetHeight;

    if (boxH === 0) {
      throw Error('Bindery: Trying to flow into a box of zero height.');
    }

    return contentH - boxH;
  }
  hasOverflowed() {
    return this.overflowAmount() > -5;
  }

  static isSizeValid() {
    document.body.classList.remove(c('viewing'));

    const testPage = new Page();
    let measureArea = document.querySelector(c('.measure-area'));
    if (!measureArea) measureArea = document.body.appendChild(h(c('.measure-area')));

    measureArea.innerHTML = '';
    measureArea.appendChild(testPage.element);
    const box = testPage.flowBox.getBoundingClientRect();

    measureArea.parentNode.removeChild(measureArea);

    return (box.height > 100) && (box.width > 100); // TODO: Number is arbitrary
  }

  setLeftRight(dir) {
    if (dir === 'left') {
      this.side = dir;
      this.element.classList.remove(c('right'));
      this.element.classList.add(c('left'));
    } else if (dir === 'right') {
      this.side = dir;
      this.element.classList.remove(c('left'));
      this.element.classList.add(c('right'));
    } else {
      throw Error(`Bindery: Setting page to invalid direction${dir}`);
    }
  }

  get suppressErrors() {
    return this.suppress || false;
  }

  set suppressErrors(newVal) {
    this.suppress = newVal;
    if (newVal) {
      this.element.classList.add(c('is-overflowing'));
    } else {
      this.element.classList.remove(c('is-overflowing'));
    }
  }

  get isEmpty() {
    return (
      this.flowContent.textContent.trim() === ''
      && this.flowBox.offsetHeight < 1
    );
  }

  get isLeft() {
    return this.side === 'left';
  }

  get isRight() {
    return this.side === 'right';
  }

  setPreference(dir) {
    if (dir === 'left') this.alwaysLeft = true;
    if (dir === 'right') this.alwaysRight = true;
  }
}

export default Page;
<|endoftext|>


<commit_before>//
// Copyright (c) 2016 Satoshi Nakajima (https://github.com/snakajima)
// License: The MIT License
//

import React, { Component } from 'react';
import DragContext from './DragContext';
import Element from './Element';
//import Selection from './Selection';
import MathEx from './MathEx';

class Page extends Component {
  constructor(props) {
    super();
    this.onDrop = this.onDrop.bind(this);
    this.onDragOver = this.onDragOver.bind(this);
    this.onClick = this.onClick.bind(this);
  }

  onClick(e) {
    if (!this.props.main) {
      window.store.dispatch({type:'selectPage', pageIndex:this.props.pageIndex});
    } else {
      //console.log("Page.onClick");
      window.store.dispatch({type:'selectElement', selection:{ids:new Set()}});
    }
  }

  onDrop(e) {
    console.log('Page:onDrop');
    const context = DragContext.getContext();
    const margin = this.props.margin || 0
    const scale = (this.props.width - margin * 2)/ this.props.dimension.width;
    window.store.dispatch({
        type:'movePageElement', pageIndex:context.pageIndex,
        handle:context.handle,
        id:context.id, scale:scale, index:context.index, params:context.params,
        dx:e.clientX-context.x, dy:e.clientY-context.y});
  }

  onDragOver(e) {
    console.log('Page:onDragOver');
    if (DragContext.getContext().pageIndex === this.props.pageIndex) {
        e.preventDefault();
    }
  }

  static applyTransformElement(element, delta) {
    if (delta) {
      var e = Object.assign({}, element);
      if (delta.translate) {
        e.x += delta.translate[0];
        e.y += delta.translate[1];
      }
      if (MathEx.hasValue(delta.rotate)) {
        e.rotate = MathEx.valueOf(e.rotate, 0) + delta.rotate;
      }
      if (delta.scale) {
        const r = e.scale || [1, 1];
        e.scale = [r[0] * delta.scale[0], r[1] * delta.scale[1]];
      }
      if (MathEx.hasValue(delta.opacity)) {
        e.opacity = delta.opacity;
      }
      if (delta.timing) {
        e.timing = delta.timing;
      }
      return e;
    }
    return element;
  }

  static applyTransform(elements, deltas) {
    return elements.map((element)=>{
      return Page.applyTransformElement(element, deltas[element.id]);
    });
  }

  static extractDelta(base, element, delta=true) {
    var obj={};
    if (base.x !== element.x || base.y !== element.y) {
      obj.translate = [MathEx.round(element.x-base.x),
                       MathEx.round(element.y-base.y)];
    }
    if (base.rotate !== element.rotate) {
      obj.rotate = MathEx.valueOf(element.rotate, 0)
      if (delta) {
        obj.rotate -= MathEx.valueOf(base.rotate, 0)
      }
    }
    if (base.scale !== element.scale) {
      obj.scale = element.scale || [1, 1];
      if (delta) {
        const r = base.scale || [1,1];
        obj.scale[0] /= r[0];
        obj.scale[1] /= r[1];
      }
    }
    if (base.opacity !== element.opacity) {
       obj.opacity = element.opacity;
    }
    const t0 = MathEx.valueOf(base.timing, [0,1]);
    const t1 = MathEx.valueOf(element.timing, [0,1]);
    if (t0[0] !== t1[0] && t0[1] !== t1[1]) {
       obj.timing = t1;
    }

    return Object.keys(obj).length > 0 ? obj : null;
  }

  render() {
    const elements = Page.applyTransform(this.props.sceneElements, this.props.page);
    const margin = MathEx.valueOf(this.props.margin, 0);
    const width = this.props.width - margin * 2;
    const scale = width / this.props.dimension.width;
    const height = this.props.dimension.height * scale;
    //const selection = this.props.selection || {ids:new Set()}
    return (

            {elements.map((element, index)=>{ return <Element key={index} index={index} pageIndex={this.props.pageIndex} element={element} main={this.props.main}
              scale={scale} />})}

            {/*elements.reduce((selections, element, index)=>{
                             if (selection.ids.has(element.id)) {
                               selections.push(<Selection key={index+1000} index={index}
                                             pageIndex={this.props.pageIndex}
                                             element={element} main={this.props.main}
                                             selectionStyle={this.props.selection.style}
                                             scale={scale} />);
                             }
                             return selections;
                    }, [])*/}

    );
  }
}

export default Page;
<commit_msg>fix extractData<commit_after>//
// Copyright (c) 2016 Satoshi Nakajima (https://github.com/snakajima)
// License: The MIT License
//

import React, { Component } from 'react';
import DragContext from './DragContext';
import Element from './Element';
//import Selection from './Selection';
import MathEx from './MathEx';

class Page extends Component {
  constructor(props) {
    super();
    this.onDrop = this.onDrop.bind(this);
    this.onDragOver = this.onDragOver.bind(this);
    this.onClick = this.onClick.bind(this);
  }

  onClick(e) {
    if (!this.props.main) {
      window.store.dispatch({type:'selectPage', pageIndex:this.props.pageIndex});
    } else {
      //console.log("Page.onClick");
      window.store.dispatch({type:'selectElement', selection:{ids:new Set()}});
    }
  }

  onDrop(e) {
    console.log('Page:onDrop');
    const context = DragContext.getContext();
    const margin = this.props.margin || 0
    const scale = (this.props.width - margin * 2)/ this.props.dimension.width;
    window.store.dispatch({
        type:'movePageElement', pageIndex:context.pageIndex,
        handle:context.handle,
        id:context.id, scale:scale, index:context.index, params:context.params,
        dx:e.clientX-context.x, dy:e.clientY-context.y});
  }

  onDragOver(e) {
    console.log('Page:onDragOver');
    if (DragContext.getContext().pageIndex === this.props.pageIndex) {
        e.preventDefault();
    }
  }

  static applyTransformElement(element, delta) {
    if (delta) {
      var e = Object.assign({}, element);
      if (delta.translate) {
        e.x += delta.translate[0];
        e.y += delta.translate[1];
      }
      if (MathEx.hasValue(delta.rotate)) {
        e.rotate = MathEx.valueOf(e.rotate, 0) + delta.rotate;
      }
      if (delta.scale) {
        const r = e.scale || [1, 1];
        e.scale = [r[0] * delta.scale[0], r[1] * delta.scale[1]];
      }
      if (MathEx.hasValue(delta.opacity)) {
        e.opacity = delta.opacity;
      }
      if (delta.timing) {
        e.timing = delta.timing;
      }
      return e;
    }
    return element;
  }

  static applyTransform(elements, deltas) {
    return elements.map((element)=>{
      return Page.applyTransformElement(element, deltas[element.id]);
    });
  }

  static extractDelta(base, element, delta=true) {
    var obj={};
    if (base.x !== element.x || base.y !== element.y) {
      obj.translate = [MathEx.round(element.x-base.x),
                       MathEx.round(element.y-base.y)];
    }
    if (base.rotate !== element.rotate) {
      obj.rotate = MathEx.valueOf(element.rotate, 0)
      if (delta) {
        obj.rotate -= MathEx.valueOf(base.rotate, 0)
      }
    }
    if (base.scale !== element.scale) {
      obj.scale = element.scale || [1, 1];
      if (delta) {
        const r = base.scale || [1,1];
        obj.scale[0] /= r[0];
        obj.scale[1] /= r[1];
      }
    }
    if (base.opacity !== element.opacity) {
       obj.opacity = element.opacity;
    }
    const t0 = MathEx.valueOf(base.timing, [0,1]);
    const t1 = MathEx.valueOf(element.timing, [0,1]);
    if (t0[0] !== t1[0] || t0[1] !== t1[1]) {
       obj.timing = t1;
    }

    return Object.keys(obj).length > 0 ? obj : null;
  }

  render() {
    const elements = Page.applyTransform(this.props.sceneElements, this.props.page);
    const margin = MathEx.valueOf(this.props.margin, 0);
    const width = this.props.width - margin * 2;
    const scale = width / this.props.dimension.width;
    const height = this.props.dimension.height * scale;
    //const selection = this.props.selection || {ids:new Set()}
    return (

            {elements.map((element, index)=>{ return <Element key={index} index={index} pageIndex={this.props.pageIndex} element={element} main={this.props.main}
              scale={scale} />})}

            {/*elements.reduce((selections, element, index)=>{
                             if (selection.ids.has(element.id)) {
                               selections.push(<Selection key={index+1000} index={index}
                                             pageIndex={this.props.pageIndex}
                                             element={element} main={this.props.main}
                                             selectionStyle={this.props.selection.style}
                                             scale={scale} />);
                             }
                             return selections;
                    }, [])*/}

    );
  }
}

export default Page;
<|endoftext|>


<commit_before>/* Copyright (c) 2010, Sage Software, 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.
 */

define('Sage/Platform/Mobile/Pane', [
    'dojo/_base/declare',
    'dojo/_base/lang',
    'dojo/_base/array',
    'dojo/_base/Deferred',
    'dojo/topic',
    'dojo/dom-style',
    'dojo/dom-class',
    'dojo/dom-attr',
    'dojox/mobile/FixedSplitterPane',
    './_UiComponent',
    './Toolbar',
    './TitleBar',
    './View'
], function(
    declare,
    lang,
    array,
    Deferred,
    topic,
    domStyle,
    domClass,
    domAttr,
    FixedSplitterPane,
    _UiComponent,
    Toolbar,
    TitleBar
) {
    return declare('Sage.Platform.Mobile.Pane', [FixedSplitterPane, _UiComponent], {
        components: [
            {name: 'top', type: TitleBar, attachEvent: 'onPositionChange:_onToolbarPositionChange', props: {managed: true, visible: false}},
            {name: 'container', tag: 'div', attrs: {'class': 'view-container'}, attachPoint: 'viewContainerNode'}
        ],
        viewContainerNode: null,
        active: null,
        toolbars: null,

        constructor: function() {
            this.toolbars = {};
        },
        _onToolbarPositionChange: function(position, previous) {
            if (previous) domClass.remove(this.domNode, 'has-toolbar-' + previous);

            domClass.add(this.domNode, 'has-toolbar-' + position);
        },
        onStartup: function() {
            this.inherited(arguments);

            array.forEach(this.getComponents(), function(component) {
                if (component.isInstanceOf(Toolbar)) this.toolbars[component.getComponentName()] = component;
            }, this);
        },
        show: function(view) {
            var deferred = new Deferred();

            /* - add the new view to this domNode
             * - do transition, remove old view from domNode ?
             * - or leave view in the container until it is needed elsewhere?
             * - save on dom movement and better back button support?
             *
             * - or have several configurations of views, one for tablets, and one for mobile?
             *   where views are assigned directly to containers?
             */

            /* todo: why does this fix display issue on Android 3.0 tablet? */
            /* - the nodes are not painted correctly without the timeout
             * - some items are not displayed, normally the main view, but can be interacted with
             * - rotating the tablet causes it to paint correctly.
             * - even happens with OpenGL rendering disabled.
             */
            setTimeout(lang.hitch(this, this._transitionTo, view, view.options, deferred));

            return deferred;
        },
        _beforeTransition: function(view, options, previous) {
            if (previous)
            {
                previous.beforeTransitionAway();
            }

            view.beforeTransitionTo();

            for (var name in this.toolbars)
            {
                var toolbar = this.toolbars[name];
                if (toolbar.managed)
                {
                    toolbar.clear();
                    toolbar.show();
                }
            }

            topic.publish('/app/view/transition/before', view, previous, this);
        },
        _afterTransition: function(view, options, previous) {
            var tools = (options && options.tools) || view.get('tools') || {};

            for (var name in this.toolbars)
            {
                var toolbar = this.toolbars[name];
                if (toolbar.managed)
                {
                    toolbar.set('title', view.get('title'));
                    toolbar.set('items', tools[name]);
                }
                else
                {
                    toolbar.update();
                }
            }

            if (previous)
            {
                previous.transitionAway();
            }

            view.transitionTo();

            topic.publish('/app/view/transition/after', view, previous, this);
        },
        _transitionTo: function(view, options, deferred) {
            console.log('transition: %s', view.id);

            if (this.active === view)
            {
                /* todo: fully reset tools here? could update? only issue would be if new tools were passed for same active view. */
                this._beforeTransition(view, options, view);

                /* todo: is `reload` an appropriate name for this? */
                console.log('reload: %s', view.id);

                view.reload();

                this._afterTransition(view, options, view);

                deferred.resolve(true);

                return deferred;
            }

            var previous = this.active;

            domClass.remove(view.domNode, 'is-visible');

            view.placeAt(this.viewContainerNode || this.domNode);

            this._beforeTransition(view, options, previous);

            if (previous)
            {
                domClass.remove(previous.domNode, 'is-visible');
            }

            domClass.add(view.domNode, 'is-visible');

            this.active = view;

            domAttr.set(this.domNode, 'data-active-view', view.id);
            domAttr.set(this.domNode, 'data-active-view-kind', view.customizationSet);

            this._afterTransition(view, options, previous);

            this.resize();

            deferred.resolve(true);
        },
        empty: function() {
            console.log('empty: %s', this.id);

            var deferred = new Deferred(),
                previous = this.active;

            if (previous)
            {
                if (previous.domNode && previous.domNode.parentNode)
                    previous.domNode.parentNode.removeChild(previous.domNode);
            }

            for (var name in this.toolbars)
            {
                var toolbar = this.toolbars[name];

                toolbar.hide();
            }

            this.active = null;

            domAttr.set(this.domNode, 'data-active-view', '');
            domAttr.set(this.domNode, 'data-active-view-kind', '');

            this.resize();

            deferred.resolve(true);

            return deferred;
        },
        resize: function() {
            // do not call base implementation (FixedSplitterPane)
            // only resize active child (for performance)
            if (this.active && this.active.resize)
                this.active.resize();
        }
    });
});<commit_msg>adjusted scene lifecycle.<commit_after>/* Copyright (c) 2010, Sage Software, 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.
 */

define('Sage/Platform/Mobile/Pane', [
    'dojo/_base/declare',
    'dojo/_base/lang',
    'dojo/_base/array',
    'dojo/_base/Deferred',
    'dojo/topic',
    'dojo/dom-style',
    'dojo/dom-class',
    'dojo/dom-attr',
    'dojox/mobile/FixedSplitterPane',
    './_UiComponent',
    './Toolbar',
    './TitleBar',
    './View'
], function(
    declare,
    lang,
    array,
    Deferred,
    topic,
    domStyle,
    domClass,
    domAttr,
    FixedSplitterPane,
    _UiComponent,
    Toolbar,
    TitleBar
) {
    return declare('Sage.Platform.Mobile.Pane', [FixedSplitterPane, _UiComponent], {
        components: [
            {name: 'top', type: TitleBar, attachEvent: 'onPositionChange:_onToolbarPositionChange', props: {managed: true, visible: false}},
            {name: 'container', tag: 'div', attrs: {'class': 'view-container'}, attachPoint: 'viewContainerNode'}
        ],
        viewContainerNode: null,
        active: null,
        toolbars: null,

        constructor: function() {
            this.toolbars = {};
        },
        _onToolbarPositionChange: function(position, previous) {
            if (previous) domClass.remove(this.domNode, 'has-toolbar-' + previous);

            domClass.add(this.domNode, 'has-toolbar-' + position);
        },
        onStartup: function() {
            this.inherited(arguments);

            array.forEach(this.getComponents(), function(component) {
                if (component.isInstanceOf(Toolbar)) this.toolbars[component.getComponentName()] = component;
            }, this);
        },
        show: function(view) {
            var deferred = new Deferred();

            /* - add the new view to this domNode
             * - do transition, remove old view from domNode ?
             * - or leave view in the container until it is needed elsewhere?
             * - save on dom movement and better back button support?
             *
             * - or have several configurations of views, one for tablets, and one for mobile?
             *   where views are assigned directly to containers?
             */

            /* todo: why does this fix display issue on Android 3.0 tablet? */
            /* - the nodes are not painted correctly without the timeout
             * - some items are not displayed, normally the main view, but can be interacted with
             * - rotating the tablet causes it to paint correctly.
             * - even happens with OpenGL rendering disabled.
             */
            setTimeout(lang.hitch(this, this._transitionTo, view, view.options, deferred));

            return deferred;
        },
        _beforeTransition: function(view, options, previous) {
            if (previous)
            {
                previous.beforeTransitionAway();
            }

            view.beforeTransitionTo();

            for (var name in this.toolbars)
            {
                var toolbar = this.toolbars[name];
                if (toolbar.managed)
                {
                    toolbar.clear();
                    toolbar.show();
                }
            }

            topic.publish('/app/view/transition/before', view, previous, this);
        },
        _afterTransition: function(view, options, previous) {
            var tools = (options && options.tools) || view.get('tools') || {};

            for (var name in this.toolbars)
            {
                var toolbar = this.toolbars[name];
                if (toolbar.managed)
                {
                    toolbar.set('title', view.get('title'));
                    toolbar.set('items', tools[name]);
                }
                else
                {
                    toolbar.update();
                }
            }

            if (previous)
            {
                previous.transitionAway();
            }

            view.transitionTo();

            topic.publish('/app/view/transition/after', view, previous, this);
        },
        _transitionTo: function(view, options, deferred) {
            console.log('transition: %s', view.id);

            if (this.active === view)
            {
                /* todo: fully reset tools here? could update? only issue would be if new tools were passed for same active view. */
                this._beforeTransition(view, options, view);

                /* todo: is `reload` an appropriate name for this? */
                console.log('reload: %s', view.id);

                view.reload();

                this._afterTransition(view, options, view);

                deferred.resolve(true);

                return deferred;
            }

            var previous = this.active;

            domClass.remove(view.domNode, 'is-visible');

            view.placeAt(this.viewContainerNode || this.domNode);

            this._beforeTransition(view, options, previous);

            if (previous)
            {
                domClass.remove(previous.domNode, 'is-visible');
            }

            domClass.add(view.domNode, 'is-visible');

            this.active = view;

            this._afterTransition(view, options, previous);

            this.resize();

            deferred.resolve(true);
        },
        empty: function() {
            console.log('empty: %s', this.id);

            var deferred = new Deferred(),
                previous = this.active;

            if (previous)
            {
                if (previous.domNode && previous.domNode.parentNode)
                    previous.domNode.parentNode.removeChild(previous.domNode);
            }

            for (var name in this.toolbars)
            {
                var toolbar = this.toolbars[name];

                toolbar.hide();
            }

            this.active = null;

            this.resize();

            deferred.resolve(true);

            return deferred;
        },
        resize: function() {
            // do not call base implementation (FixedSplitterPane)
            // only resize active child (for performance)
            if (this.active && this.active.resize)
                this.active.resize();
        }
    });
});<|endoftext|>


<commit_before>class ContentComponent {
  constructor() {
    this.element = document.createElement('content-component');
  }

  showMarkDown(markdownText) {
    const reader = new commonmark.Parser();
    const ast = reader.parse(markdownText);
    const writer = new commonmark.HtmlRenderer();
    const result = writer.render(ast);
    this.element.innerHTML = result;
    this.element.scrollTop = 0;
  }

  showElements(elements) {
    this.element.innerHTML = '';
    this.element.scrollTop = 0;
    this._renderElements(null, elements);
  }

  showAPIClass(apiClass) {
    this.element.innerHTML = '';
    this.element.scrollTop = 0;

    this._insertBox().appendChild(apiClass.element);

    this._renderElements('Events', apiClass.events.map(e => e.element));
    this._renderElements('NameSpaces', apiClass.namespaces.map(ns => ns.element));
    this._renderElements('Methods', apiClass.methods.map(method => method.element));
  }

  showAPIMethod(apiMethod) {
    this.showAPIClass(apiMethod.apiClass);
    this._parentBox(apiMethod.element).scrollIntoView();
  }

  showAPIEvent(apiEvent) {
    this.showAPIClass(apiEvent.apiClass);
    this._parentBox(apiEvent.element).scrollIntoView();
  }

  showAPINamespace(apiNamespace) {
    this.showAPIClass(apiNamespace.apiClass);
    this._parentBox(apiNamespace.element).scrollIntoView();
  }

  _parentBox(element) {
    while (element && element.tagName !== 'CONTENT-BOX')
      element = element.parentElement;
    return element;
  }

  _insertBox() {
    const box = document.createElement('content-box');
    this.element.appendChild(box);
    return box;
  }

  _insertDelimeter(container) {
    const delimeter = document.createElement('content-delimeter');
    container.appendChild(delimeter);
    return delimeter;
  }

  _renderElements(title, elements) {
    if (!elements.length)
      return;
    if (title) {
      const header = document.createElement('h3');
      header.textContent = title;
      this.element.appendChild(header);
    }
    const box = this._insertBox();
    let lastDelimeter = null;
    for (const element of elements) {
      box.appendChild(element);
      lastDelimeter = this._insertDelimeter(box);
    }
    lastDelimeter.remove();
  }
}
<commit_msg>fix: properly scroll to focus and methods<commit_after>class ContentComponent {
  constructor() {
    this.element = document.createElement('content-component');
  }

  showMarkDown(markdownText) {
    const reader = new commonmark.Parser();
    const ast = reader.parse(markdownText);
    const writer = new commonmark.HtmlRenderer();
    const result = writer.render(ast);
    this.element.innerHTML = result;
    this.element.scrollTop = 0;
  }

  showElements(elements) {
    this.element.innerHTML = '';
    this.element.scrollTop = 0;
    this._renderElements(null, elements);
  }

  showAPIClass(apiClass) {
    this.element.innerHTML = '';
    this.element.scrollTop = 0;

    this._insertBox().appendChild(apiClass.element);

    this._renderElements('Events', apiClass.events.map(e => e.element));
    this._renderElements('NameSpaces', apiClass.namespaces.map(ns => ns.element));
    this._renderElements('Methods', apiClass.methods.map(method => method.element));
  }

  showAPIMethod(apiMethod) {
    this.showAPIClass(apiMethod.apiClass);
    this._parentBox(apiMethod.element).scrollIntoView();
    apiMethod.element.scrollIntoViewIfNeeded();
  }

  showAPIEvent(apiEvent) {
    this.showAPIClass(apiEvent.apiClass);
    this._parentBox(apiEvent.element).scrollIntoView();
    apiEvent.element.scrollIntoViewIfNeeded();
  }

  showAPINamespace(apiNamespace) {
    this.showAPIClass(apiNamespace.apiClass);
    this._parentBox(apiNamespace.element).scrollIntoView();
    apiNamespace.element.scrollIntoViewIfNeeded();
  }

  _parentBox(element) {
    while (element && element.tagName !== 'CONTENT-BOX')
      element = element.parentElement;
    return element;
  }

  _insertBox() {
    const box = document.createElement('content-box');
    this.element.appendChild(box);
    return box;
  }

  _insertDelimeter(container) {
    const delimeter = document.createElement('content-delimeter');
    container.appendChild(delimeter);
    return delimeter;
  }

  _renderElements(title, elements) {
    if (!elements.length)
      return;
    if (title) {
      const header = document.createElement('h3');
      header.textContent = title;
      this.element.appendChild(header);
    }
    const box = this._insertBox();
    let lastDelimeter = null;
    for (const element of elements) {
      box.appendChild(element);
      lastDelimeter = this._insertDelimeter(box);
    }
    lastDelimeter.remove();
  }
}
<|endoftext|>


<commit_before>import React from 'react';
import Meta from './meta';

export default function Site({meta, bundle, content, style}) {
  meta = meta || Meta.rewind();
  return (

        <meta charSet="utf8" />
        {meta.meta.toComponent()}
        {style &&


<commit_before>import React, { PropTypes } from 'react';

import './Tile.css';

const styles = {
  wrapper: {
    width: 50,
    height: 50,
    border: '5px solid chocolate',
    backgroundColor: 'green',
    position: 'absolute',
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    cursor: 'pointer',
  },
  number: {
    color: 'orange',
  },
};

const Tile = ({
  number,
  left,
  top,
  onClick,
}) => {
  const compStyles = Object.assign({}, styles.wrapper, {
    left,
    top,
  });

  return (

      {number}

  );
};

Tile.propTypes = {
  number: PropTypes.number,
  left: PropTypes.number.isRequired,
  top: PropTypes.number.isRequired,
  onClick: PropTypes.func.isRequired,
};

Tile.defaultProps = {
  number: 0,
};

export default Tile;
<commit_msg>Fix import.<commit_after>import React, { PropTypes } from 'react';

const styles = {
  wrapper: {
    width: 50,
    height: 50,
    border: '5px solid chocolate',
    backgroundColor: 'green',
    position: 'absolute',
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    cursor: 'pointer',
  },
  number: {
    color: 'orange',
  },
};

const Tile = ({
  number,
  left,
  top,
  onClick,
}) => {
  const compStyles = Object.assign({}, styles.wrapper, {
    left,
    top,
  });

  return (

      {number}

  );
};

Tile.propTypes = {
  number: PropTypes.number,
  left: PropTypes.number.isRequired,
  top: PropTypes.number.isRequired,
  onClick: PropTypes.func.isRequired,
};

Tile.defaultProps = {
  number: 0,
};

export default Tile;
<|endoftext|>


<commit_before>/*
Script: MooEditable.Table.js
	Table manipulation

Usage:
   Add the following tags in your html
   <link rel="stylesheet" type="text/css" href="MooEditable.Table.css">
   <script type="text/javascript" src="mootools.js"></script>
   <script type="text/javascript" src="MooEditable.js"></script>
   <script type="text/javascript" src="MooEditable.Table.js"></script>

   <script type="text/javascript">
	window.addEvent('load', function(){
		var mooeditable = $('textarea-1').mooEditable({
			actions: 'bold italic underline strikethrough | table | toggleview'
		});
   </script>

License:
	MIT-style license.

Author:
    Radovan Lozej <radovan lozej gmail com>
*/

MooEditable.UI.TableDialog = function(editor,dialog){
	var html = {
		tableadd :		'columns <input type="text" class="table-c" value="" size="4" /> ' +
						'rows <input type="text" class="table-r" value="" size="4" /> ',
		tableedit : 	'width <input type="text" class="table-w" value="" size="4" /> ' +
						'class <input type="text" class="table-c" value="" size="15" /> ',
		tablerowedit :	'class <input type="text" class="table-c" value="" size="15" /> ',
		tablecoledit :	'width <input type="text" class="table-w" value="" size="4" /> ' +
						'class <input type="text" class="table-c" value="" size="15" /> ' +
						'align <select class="table-a"><option>none</option><option>left</option><option>center</option><option>right</option></select>' +
						'valign <select class="table-va"><option>none</option><option>top</option><option>middle</option><option>bottom</option></select>'
	}
	html[dialog]+= '<button class="dialog-button dialog-ok-button">OK</button>'
		+ '<button class="dialog-button dialog-cancel-button">Cancel</button>';

	var action = {
		tableadd: {
			click : function(e){
				var col = this.el.getElement('.table-c').value.toInt();
				var row = this.el.getElement('.table-r').value.toInt();
				if(!(row>0 && col>0)) return;
				var div,table,tbody,ro = [];
				div = new Element('tdiv');
				table = new Element('table').set('border','0').set('width','100%').inject(div);
				tbody = new Element('tbody').inject(table);
				for(var r = 0;r<row;r++){
					ro[r] = new Element('tr').inject(tbody,'bottom');
					for(var c=0;c<col;c++) new Element('td').set('html',' ').inject(ro[r],'bottom');
				}
				editor.selection.insertContent(div.get('html'));
			}
		},
		tableedit : {
			load : function(e){
				var node = editor.selection.getNode().getParent('table');
				this.el.getElement('.table-w').set('value',node.get('width'));
				this.el.getElement('.table-c').set('value',node.className);
			},
			click : function(e){
				var node = editor.selection.getNode().getParent('table');
				node.set('width',this.el.getElement('.table-w').value);
				node.className = this.el.getElement('.table-c').value;
			}
		},
		tablerowedit : {
			load : function(e){
				var node = editor.selection.getNode().getParent('tr');
				this.el.getElement('.table-c').set('value',node.className);
			},
			click : function(e){
				var node = editor.selection.getNode().getParent('tr');
				node.className = this.el.getElement('.table-c').value;
			}
		},
		tablecoledit : {
			load : function(e){
				var node = editor.selection.getNode();
				if(node.get('tag')!='td') node = node.getParent('td');
				this.el.getElement('.table-w').set('value',node.get('width'));
				this.el.getElement('.table-c').set('value',node.className);
				this.el.getElement('.table-a').set('value',node.get('align'));
				this.el.getElement('.table-va').set('value',node.get('valign'));
			},
			click : function(e){
				var node = editor.selection.getNode();
				if(node.get('tag')!='td') node = node.getParent('td');
				node.set('width',this.el.getElement('.table-w').value);
				node.className = this.el.getElement('.table-c').value;
				node.set('align',this.el.getElement('.table-a').value);
				node.set('valign',this.el.getElement('.table-va').value);
			}
		}
	};

	return new MooEditable.UI.Dialog(html[dialog], {
		'class': 'mooeditable-prompt-dialog',
		onOpen: function(){
			if(action[dialog].load) action[dialog].load.apply(this);
			var input = this.el.getElement('input');
			(function(){ input.focus(); }).delay(10);
		},
		onClick: function(e){
			if (e.target.tagName.toLowerCase() == 'button') e.preventDefault();
			var button = document.id(e.target);
			if (button.hasClass('dialog-cancel-button')) this.close();
			else if (button.hasClass('dialog-ok-button')){
				this.close();
				action[dialog].click.apply(this);
			}
		}
	});
};

MooEditable.Actions.extend({

	tableadd:{
		title: 'Add Table',
		dialogs: {
			prompt: function(editor){
				return MooEditable.UI.TableDialog(editor,'tableadd');
			}
		},
		command: function(){
			this.dialogs.tableadd.prompt.open();
		}
	},

	tableedit:{
		title: 'Edit Table',
		dialogs: {
			prompt: function(editor){
				return MooEditable.UI.TableDialog(editor,'tableedit');
			}
		},
		command: function(){
			if(this.selection.getNode().getParent('table')) this.dialogs.tableedit.prompt.open();
		}
	},

	tablerowadd:{
		title: 'Add Row',
		command: function(){
			var node = this.selection.getNode().getParent('tr');
			if(node) node.clone().inject(node,'after');
		}
	},

	tablerowedit:{
		title: 'Edit Row',
		dialogs: {
			prompt: function(editor){
				return MooEditable.UI.TableDialog(editor,'tablerowedit');
			}
		},
		command: function(){
			if(this.selection.getNode().getParent('table')) this.dialogs.tablerowedit.prompt.open();
		}
	},

	tablerowspan:{
		title: 'Merge Row',
		command: function(){
			var node = this.selection.getNode();
			if(node.get('tag')!='td') node = node.getParent('td');
			if(node){
				var index = node.cellIndex;
				var row = node.getParent().rowIndex;
				if(node.getParent().getParent().childNodes[row+node.rowSpan]) {
					node.getParent().getParent().childNodes[row+node.rowSpan].deleteCell(index);
					node.rowSpan+= 1;
				}
			}
		}
	},

	tablerowdelete:{
		title: 'Delete Row',
		command: function(){
			var node = this.selection.getNode().getParent('tr');
			if(node) node.getParent().deleteRow(node.rowIndex);
		}
	},

	tablecoladd:{
		title: 'Add Column',
		command: function(){
			var node = this.selection.getNode();
			if(node.get('tag')!='td') node = node.getParent('td');
			if(node){
				var index = node.cellIndex;
				var len = node.getParent().getParent().childNodes.length;
				for (var i=0;i<len;i++){
					var ref = node.getParent().getParent().childNodes[i].childNodes[index];
					ref.clone().inject(ref,'after');
				}
			}
		}
	},

	tablecoledit:{
		title: 'Edit Column',
		dialogs: {
			prompt: function(editor){
				return MooEditable.UI.TableDialog(editor,'tablecoledit');
			}
		},
		command: function(){
			if(this.selection.getNode().getParent('table')) this.dialogs.tablecoledit.prompt.open();
		}
	},

	tablecolspan:{
		title: 'Merge Cell',
		command: function(){
			var node = this.selection.getNode();
			if(node.get('tag')!='td') node = node.getParent('td');
			if(node){
				var index = node.cellIndex + 1;
				if(node.getParent().childNodes[index]) {
					node.getParent().deleteCell(index);
					node.colSpan = node.colSpan + 1;
				}
			}
		}
	},

	tablecoldelete:{
		title: 'Delete Column',
		command: function(){
			var node = this.selection.getNode();
			if(node.get('tag')!='td') node = node.getParent('td');
			if(node){
				var len = node.getParent().getParent().childNodes.length;
				var index = node.cellIndex
				var tt = node.getParent().getParent();
				for (var i=0;i<len;i++) tt.childNodes[i].deleteCell(index);
			}
		}
	}

});
<commit_msg>IE6 fix on adding column (ref was not moo extended)<commit_after>/*
Script: MooEditable.Table.js
	Table manipulation

Usage:
   Add the following tags in your html
   <link rel="stylesheet" type="text/css" href="MooEditable.Table.css">
   <script type="text/javascript" src="mootools.js"></script>
   <script type="text/javascript" src="MooEditable.js"></script>
   <script type="text/javascript" src="MooEditable.Table.js"></script>

   <script type="text/javascript">
	window.addEvent('load', function(){
		var mooeditable = $('textarea-1').mooEditable({
			actions: 'bold italic underline strikethrough | table | toggleview'
		});
   </script>

License:
	MIT-style license.

Author:
    Radovan Lozej <radovan lozej gmail com>
*/

MooEditable.UI.TableDialog = function(editor,dialog){
	var html = {
		tableadd :		'columns <input type="text" class="table-c" value="" size="4" /> ' +
						'rows <input type="text" class="table-r" value="" size="4" /> ',
		tableedit : 	'width <input type="text" class="table-w" value="" size="4" /> ' +
						'class <input type="text" class="table-c" value="" size="15" /> ',
		tablerowedit :	'class <input type="text" class="table-c" value="" size="15" /> ',
		tablecoledit :	'width <input type="text" class="table-w" value="" size="4" /> ' +
						'class <input type="text" class="table-c" value="" size="15" /> ' +
						'align <select class="table-a"><option>none</option><option>left</option><option>center</option><option>right</option></select> ' +
						'valign <select class="table-va"><option>none</option><option>top</option><option>middle</option><option>bottom</option></select> '
	}
	html[dialog]+= '<button class="dialog-button dialog-ok-button">OK</button>'
		+ '<button class="dialog-button dialog-cancel-button">Cancel</button>';

	var action = {
		tableadd: {
			click : function(e){
				var col = this.el.getElement('.table-c').value.toInt();
				var row = this.el.getElement('.table-r').value.toInt();
				if(!(row>0 && col>0)) return;
				var div,table,tbody,ro = [];
				div = new Element('tdiv');
				table = new Element('table').set('border','0').set('width','100%').inject(div);
				tbody = new Element('tbody').inject(table);
				for(var r = 0;r<row;r++){
					ro[r] = new Element('tr').inject(tbody,'bottom');
					for(var c=0;c<col;c++) new Element('td').set('html',' ').inject(ro[r],'bottom');
				}
				editor.selection.insertContent(div.get('html'));
			}
		},
		tableedit : {
			load : function(e){
				var node = editor.selection.getNode().getParent('table');
				this.el.getElement('.table-w').set('value',node.get('width'));
				this.el.getElement('.table-c').set('value',node.className);
			},
			click : function(e){
				var node = editor.selection.getNode().getParent('table');
				node.set('width',this.el.getElement('.table-w').value);
				node.className = this.el.getElement('.table-c').value;
			}
		},
		tablerowedit : {
			load : function(e){
				var node = editor.selection.getNode().getParent('tr');
				this.el.getElement('.table-c').set('value',node.className);
			},
			click : function(e){
				var node = editor.selection.getNode().getParent('tr');
				node.className = this.el.getElement('.table-c').value;
			}
		},
		tablecoledit : {
			load : function(e){
				var node = editor.selection.getNode();
				if(node.get('tag')!='td') node = node.getParent('td');
				this.el.getElement('.table-w').set('value',node.get('width'));
				this.el.getElement('.table-c').set('value',node.className);
				this.el.getElement('.table-a').set('value',node.get('align'));
				this.el.getElement('.table-va').set('value',node.get('valign'));
			},
			click : function(e){
				var node = editor.selection.getNode();
				if(node.get('tag')!='td') node = node.getParent('td');
				node.set('width',this.el.getElement('.table-w').value);
				node.className = this.el.getElement('.table-c').value;
				node.set('align',this.el.getElement('.table-a').value);
				node.set('valign',this.el.getElement('.table-va').value);
			}
		}
	};

	return new MooEditable.UI.Dialog(html[dialog], {
		'class': 'mooeditable-prompt-dialog',
		onOpen: function(){
			if(action[dialog].load) action[dialog].load.apply(this);
			var input = this.el.getElement('input');
			(function(){ input.focus(); }).delay(10);
		},
		onClick: function(e){
			if (e.target.tagName.toLowerCase() == 'button') e.preventDefault();
			var button = document.id(e.target);
			if (button.hasClass('dialog-cancel-button')) this.close();
			else if (button.hasClass('dialog-ok-button')){
				this.close();
				action[dialog].click.apply(this);
			}
		}
	});
};

MooEditable.Actions.extend({

	tableadd:{
		title: 'Add Table',
		dialogs: {
			prompt: function(editor){
				return MooEditable.UI.TableDialog(editor,'tableadd');
			}
		},
		command: function(){
			this.dialogs.tableadd.prompt.open();
		}
	},

	tableedit:{
		title: 'Edit Table',
		dialogs: {
			prompt: function(editor){
				return MooEditable.UI.TableDialog(editor,'tableedit');
			}
		},
		command: function(){
			if(this.selection.getNode().getParent('table')) this.dialogs.tableedit.prompt.open();
		}
	},

	tablerowadd:{
		title: 'Add Row',
		command: function(){
			var node = this.selection.getNode().getParent('tr');
			if(node) node.clone().inject(node,'after');
		}
	},

	tablerowedit:{
		title: 'Edit Row',
		dialogs: {
			prompt: function(editor){
				return MooEditable.UI.TableDialog(editor,'tablerowedit');
			}
		},
		command: function(){
			if(this.selection.getNode().getParent('table')) this.dialogs.tablerowedit.prompt.open();
		}
	},

	tablerowspan:{
		title: 'Merge Row',
		command: function(){
			var node = this.selection.getNode();
			if(node.get('tag')!='td') node = node.getParent('td');
			if(node){
				var index = node.cellIndex;
				var row = node.getParent().rowIndex;
				if(node.getParent().getParent().childNodes[row+node.rowSpan]) {
					node.getParent().getParent().childNodes[row+node.rowSpan].deleteCell(index);
					node.rowSpan+= 1;
				}
			}
		}
	},

	tablerowdelete:{
		title: 'Delete Row',
		command: function(){
			var node = this.selection.getNode().getParent('tr');
			if(node) node.getParent().deleteRow(node.rowIndex);
		}
	},

	tablecoladd:{
		title: 'Add Column',
		command: function(){
			var node = this.selection.getNode();
			if(node.get('tag')!='td') node = node.getParent('td');
			if(node){
				var index = node.cellIndex;
				var len = node.getParent().getParent().childNodes.length;
				for (var i=0;i<len;i++){
					var ref = $(node.getParent().getParent().childNodes[i].childNodes[index]);
					ref.clone().inject(ref,'after');
				}
			}
		}
	},

	tablecoledit:{
		title: 'Edit Column',
		dialogs: {
			prompt: function(editor){
				return MooEditable.UI.TableDialog(editor,'tablecoledit');
			}
		},
		command: function(){
			if(this.selection.getNode().getParent('table')) this.dialogs.tablecoledit.prompt.open();
		}
	},

	tablecolspan:{
		title: 'Merge Cell',
		command: function(){
			var node = this.selection.getNode();
			if(node.get('tag')!='td') node = node.getParent('td');
			if(node){
				var index = node.cellIndex + 1;
				if(node.getParent().childNodes[index]) {
					node.getParent().deleteCell(index);
					node.colSpan = node.colSpan + 1;
				}
			}
		}
	},

	tablecoldelete:{
		title: 'Delete Column',
		command: function(){
			var node = this.selection.getNode();
			if(node.get('tag')!='td') node = node.getParent('td');
			if(node){
				var len = node.getParent().getParent().childNodes.length;
				var index = node.cellIndex
				var tt = node.getParent().getParent();
				for (var i=0;i<len;i++) tt.childNodes[i].deleteCell(index);
			}
		}
	}

});
<|endoftext|>


<commit_before>//@flow
import * as React from 'react'
import uuid from 'uuid'

import type { Props as ContentLoaderProps } from './index';

export type WrapProps = {
  children?: React.ChildrenArray<*>
} & ContentLoaderProps

const Wrap = (props: WrapProps): React.Element<*> => {
  let idClip = uuid.v1()
  let idGradient = uuid.v1()

  return (
    <svg
      viewBox={`0 0 ${props.width} ${props.height}`}
      version="1.1"
      style={props.style}
      preserveAspectRatio="xMidYMid meet"
    >
      <rect
        style={{ fill: `url(#${idGradient})` }}
        clipPath={`url(#${idClip})`}
        x="0"
        y="0"
        width={props.width}
        height={props.height}
      />

      <defs>
        <clipPath id={`${idClip}`}>{props.children}</clipPath>

        <linearGradient id={`${idGradient}`}>
          <stop offset="0%" stopColor={props.primaryColor}>
            <animate
              attributeName="offset"
              values="-2; 1"
              dur={`${props.speed}s`}
              repeatCount="indefinite"
            />
          </stop>
          <stop offset="50%" stopColor={props.secondaryColor}>
            <animate
              attributeName="offset"
              values="-1.5; 1.5"
              dur={`${props.speed}s`}
              repeatCount="indefinite"
            />
          </stop>
          <stop offset="100%" stopColor={props.primaryColor}>
            <animate
              attributeName="offset"
              values="-1; 2"
              dur={`${props.speed}s`}
              repeatCount="indefinite"
            />
          </stop>
        </linearGradient>
      </defs>
    </svg>
  )
}

export default Wrap
<commit_msg>Wrap size (#31)<commit_after>//@flow
import * as React from 'react'
import uuid from 'uuid'

import type { Props as ContentLoaderProps } from './index';

export type WrapProps = {
  children?: React.ChildrenArray<*>
} & ContentLoaderProps

const Wrap = (props: WrapProps): React.Element<*> => {
  let idClip = uuid.v1()
  let idGradient = uuid.v1()

  return (
    <svg
      viewBox={`0 0 ${props.width} ${props.height}`}
      width={props.width}
      height={props.height}
      version="1.1"
      style={props.style}
      preserveAspectRatio="xMidYMid meet"
    >
      <rect
        style={{ fill: `url(#${idGradient})` }}
        clipPath={`url(#${idClip})`}
        x="0"
        y="0"
        width={props.width}
        height={props.height}
      />

      <defs>
        <clipPath id={`${idClip}`}>{props.children}</clipPath>

        <linearGradient id={`${idGradient}`}>
          <stop offset="0%" stopColor={props.primaryColor}>
            <animate
              attributeName="offset"
              values="-2; 1"
              dur={`${props.speed}s`}
              repeatCount="indefinite"
            />
          </stop>
          <stop offset="50%" stopColor={props.secondaryColor}>
            <animate
              attributeName="offset"
              values="-1.5; 1.5"
              dur={`${props.speed}s`}
              repeatCount="indefinite"
            />
          </stop>
          <stop offset="100%" stopColor={props.primaryColor}>
            <animate
              attributeName="offset"
              values="-1; 2"
              dur={`${props.speed}s`}
              repeatCount="indefinite"
            />
          </stop>
        </linearGradient>
      </defs>
    </svg>
  )
}

export default Wrap
<|endoftext|>


<commit_before>//     Zepto.js
//     (c) 2010, 2011 Thomas Fuchs
//     Zepto.js may be freely distributed under the MIT license.

(function($){
  var jsonpID = 0,
      isObject = $.isObject,
      key;

  function empty() {}

  $.ajaxJSONP = function(options){
    var jsonpString = 'jsonp' + ++jsonpID,
        script = document.createElement('script');
    window[jsonpString] = function(data){
      options.success(data);
      delete window[jsonpString];
    };
    script.src = options.url.replace(/=\?/, '=' + jsonpString);
    $('head').append(script);
  };

  $.ajaxSettings = {
    type: 'GET',
    beforeSend: empty, success: empty, error: empty, complete: empty,
    accepts: {
      script: 'text/javascript, application/javascript',
      json:   'application/json',
      xml:    'application/xml, text/xml',
      html:   'text/html',
      text:   'text/plain'
    }
  };

  $.ajax = function(options){
    options = options || {};
    var settings = $.extend({}, options);
    for (key in $.ajaxSettings) if (!settings[key]) settings[key] = $.ajaxSettings[key];

    if (/=\?/.test(settings.url)) return $.ajaxJSONP(settings);

    if (!settings.url) settings.url = window.location.toString();
    if (settings.data && !settings.contentType) settings.contentType = 'application/x-www-form-urlencoded';
    if (isObject(settings.data)) settings.data = $.param(settings.data);

    if (settings.type.match(/get/i) && settings.data) {
      var queryString = settings.data;
      if (settings.url.match(/\?.*=/)) {
        queryString = '&' + queryString;
      } else if (queryString[0] != '?') {
        queryString = '?' + queryString;
      }
      settings.url += queryString;
    }

    var mime = settings.accepts[settings.dataType],
        xhr = new XMLHttpRequest();

    settings.headers = $.extend({'X-Requested-With': 'XMLHttpRequest'}, settings.headers || {});
    if (mime) settings.headers['Accept'] = mime;

    xhr.onreadystatechange = function(){
      if (xhr.readyState == 4) {
        var result, error = false;
        if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 0) {
          if (mime == 'application/json' && !(xhr.responseText == '')) {
            try { result = JSON.parse(xhr.responseText); }
            catch (e) { error = e; }
          }
          else result = xhr.responseText;
          if (error) settings.error(xhr, 'parsererror', error);
          else settings.success(result, 'success', xhr);
        } else {
          error = true;
          settings.error(xhr, 'error');
        }
        settings.complete(xhr, error ? 'error' : 'success');
      }
    };

    xhr.open(settings.type, settings.url, true);
    if (settings.beforeSend(xhr, settings) === false) {
      xhr.abort();
      return false;
    }

    if (settings.contentType) settings.headers['Content-Type'] = settings.contentType;
    for (name in settings.headers) xhr.setRequestHeader(name, settings.headers[name]);
    xhr.send(settings.data);

    return xhr;
  };

  // ### $.get
  //
  // Load data from the server using a GET request
  //
  // *Arguments:*
  //
  //     url     — url to which the request is sent
  //     success — callback that is executed if the request succeeds
  //
  // *Example:*
  //
  //     $.get(
  //        '/projects/42',
  //        function (data) {
  //            $('body').append(data);
  //        }
  //     );
  //
  $.get = function(url, success){ $.ajax({ url: url, success: success }) };

  // ### $.post
  //
  // Load data from the server using POST request
  //
  // *Arguments:*
  //
  //     url        — url to which the request is sent
  //     [data]     — data to send to server, can be string or object
  //     [success]  — callback that is executed if the request succeeds
  //     [dataType] — type of expected response
  //                  'json', 'xml', 'html', or 'text'
  //
  // *Example:*
  //
  //     $.post(
  //        '/projects',
  //        { name: 'Zepto.js' },
  //        function (data) {
  //            $('body').append(data);
  //        },
  //        'html'
  //     );
  //
  $.post = function(url, data, success, dataType){
    if ($.isFunction(data)) dataType = dataType || success, success = data, data = null;
    $.ajax({ type: 'POST', url: url, data: data, success: success, dataType: dataType });
  };

  // ### $.getJSON
  //
  // Load JSON from the server using GET request
  //
  // *Arguments:*
  //
  //     url     — url to which the request is sent
  //     success — callback that is executed if the request succeeds
  //
  // *Example:*
  //
  //     $.getJSON(
  //        '/projects/42',
  //        function (json) {
  //            projects.push(json);
  //        }
  //     );
  //
  $.getJSON = function(url, success){ $.ajax({ url: url, success: success, dataType: 'json' }) };

  // ### $.fn.load
  //
  // Load data from the server into an element
  //
  // *Arguments:*
  //
  //     url     — url to which the request is sent
  //     success — callback that is executed if the request succeeds
  //
  // *Examples:*
  //
  //     $('#project_container').get(
  //        '/projects/42',
  //        function () {
  //            alert('Project was successfully loaded');
  //        }
  //     );
  //
  //     $('#project_comments').get(
  //        '/projects/42 #comments',
  //        function () {
  //            alert('Comments was successfully loaded');
  //        }
  //     );
  //
  $.fn.load = function(url, success){
    if (!this.length) return this;
    var self = this, parts = url.split(/\s/), selector;
    if (parts.length > 1) url = parts[0], selector = parts[1];
    $.get(url, function(response){
      self.html(selector ?
        $(document.createElement('div')).html(response).find(selector).html()
        : response);
      success && success();
    });
    return this;
  };

  // ### $.param
  //
  // Encode object as a string for submission
  //
  // *Arguments:*
  //
  //     obj — object to serialize
  //     [v] — root node
  //
  // *Example:*
  //
  //     $.param( { name: 'Zepto.js', version: '0.6' } );
  //
  $.param = function(obj, v){
    var result = [], add = function(key, value){
      result.push(encodeURIComponent(v ? v + '[' + key + ']' : key)
        + '=' + encodeURIComponent(value));
      },
      isObjArray = $.isArray(obj);

    for(key in obj)
      if(isObject(obj[key]))
        result.push($.param(obj[key], (v ? v + '[' + key + ']' : key)));
      else
        add(isObjArray ? '' : key, obj[key]);

    return result.join('&').replace('%20', '+');
  };
})(Zepto);
<commit_msg>Success argument is optional for $.fn.load<commit_after>//     Zepto.js
//     (c) 2010, 2011 Thomas Fuchs
//     Zepto.js may be freely distributed under the MIT license.

(function($){
  var jsonpID = 0,
      isObject = $.isObject,
      key;

  function empty() {}

  $.ajaxJSONP = function(options){
    var jsonpString = 'jsonp' + ++jsonpID,
        script = document.createElement('script');
    window[jsonpString] = function(data){
      options.success(data);
      delete window[jsonpString];
    };
    script.src = options.url.replace(/=\?/, '=' + jsonpString);
    $('head').append(script);
  };

  $.ajaxSettings = {
    type: 'GET',
    beforeSend: empty, success: empty, error: empty, complete: empty,
    accepts: {
      script: 'text/javascript, application/javascript',
      json:   'application/json',
      xml:    'application/xml, text/xml',
      html:   'text/html',
      text:   'text/plain'
    }
  };

  $.ajax = function(options){
    options = options || {};
    var settings = $.extend({}, options);
    for (key in $.ajaxSettings) if (!settings[key]) settings[key] = $.ajaxSettings[key];

    if (/=\?/.test(settings.url)) return $.ajaxJSONP(settings);

    if (!settings.url) settings.url = window.location.toString();
    if (settings.data && !settings.contentType) settings.contentType = 'application/x-www-form-urlencoded';
    if (isObject(settings.data)) settings.data = $.param(settings.data);

    if (settings.type.match(/get/i) && settings.data) {
      var queryString = settings.data;
      if (settings.url.match(/\?.*=/)) {
        queryString = '&' + queryString;
      } else if (queryString[0] != '?') {
        queryString = '?' + queryString;
      }
      settings.url += queryString;
    }

    var mime = settings.accepts[settings.dataType],
        xhr = new XMLHttpRequest();

    settings.headers = $.extend({'X-Requested-With': 'XMLHttpRequest'}, settings.headers || {});
    if (mime) settings.headers['Accept'] = mime;

    xhr.onreadystatechange = function(){
      if (xhr.readyState == 4) {
        var result, error = false;
        if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 0) {
          if (mime == 'application/json' && !(xhr.responseText == '')) {
            try { result = JSON.parse(xhr.responseText); }
            catch (e) { error = e; }
          }
          else result = xhr.responseText;
          if (error) settings.error(xhr, 'parsererror', error);
          else settings.success(result, 'success', xhr);
        } else {
          error = true;
          settings.error(xhr, 'error');
        }
        settings.complete(xhr, error ? 'error' : 'success');
      }
    };

    xhr.open(settings.type, settings.url, true);
    if (settings.beforeSend(xhr, settings) === false) {
      xhr.abort();
      return false;
    }

    if (settings.contentType) settings.headers['Content-Type'] = settings.contentType;
    for (name in settings.headers) xhr.setRequestHeader(name, settings.headers[name]);
    xhr.send(settings.data);

    return xhr;
  };

  // ### $.get
  //
  // Load data from the server using a GET request
  //
  // *Arguments:*
  //
  //     url     — url to which the request is sent
  //     success — callback that is executed if the request succeeds
  //
  // *Example:*
  //
  //     $.get(
  //        '/projects/42',
  //        function (data) {
  //            $('body').append(data);
  //        }
  //     );
  //
  $.get = function(url, success){ $.ajax({ url: url, success: success }) };

  // ### $.post
  //
  // Load data from the server using POST request
  //
  // *Arguments:*
  //
  //     url        — url to which the request is sent
  //     [data]     — data to send to server, can be string or object
  //     [success]  — callback that is executed if the request succeeds
  //     [dataType] — type of expected response
  //                  'json', 'xml', 'html', or 'text'
  //
  // *Example:*
  //
  //     $.post(
  //        '/projects',
  //        { name: 'Zepto.js' },
  //        function (data) {
  //            $('body').append(data);
  //        },
  //        'html'
  //     );
  //
  $.post = function(url, data, success, dataType){
    if ($.isFunction(data)) dataType = dataType || success, success = data, data = null;
    $.ajax({ type: 'POST', url: url, data: data, success: success, dataType: dataType });
  };

  // ### $.getJSON
  //
  // Load JSON from the server using GET request
  //
  // *Arguments:*
  //
  //     url     — url to which the request is sent
  //     success — callback that is executed if the request succeeds
  //
  // *Example:*
  //
  //     $.getJSON(
  //        '/projects/42',
  //        function (json) {
  //            projects.push(json);
  //        }
  //     );
  //
  $.getJSON = function(url, success){ $.ajax({ url: url, success: success, dataType: 'json' }) };

  // ### $.fn.load
  //
  // Load data from the server into an element
  //
  // *Arguments:*
  //
  //     url     — url to which the request is sent
  //     [success] — callback that is executed if the request succeeds
  //
  // *Examples:*
  //
  //     $('#project_container').get(
  //        '/projects/42',
  //        function () {
  //            alert('Project was successfully loaded');
  //        }
  //     );
  //
  //     $('#project_comments').get(
  //        '/projects/42 #comments',
  //        function () {
  //            alert('Comments was successfully loaded');
  //        }
  //     );
  //
  $.fn.load = function(url, success){
    if (!this.length) return this;
    var self = this, parts = url.split(/\s/), selector;
    if (parts.length > 1) url = parts[0], selector = parts[1];
    $.get(url, function(response){
      self.html(selector ?
        $(document.createElement('div')).html(response).find(selector).html()
        : response);
      success && success();
    });
    return this;
  };

  // ### $.param
  //
  // Encode object as a string for submission
  //
  // *Arguments:*
  //
  //     obj — object to serialize
  //     [v] — root node
  //
  // *Example:*
  //
  //     $.param( { name: 'Zepto.js', version: '0.6' } );
  //
  $.param = function(obj, v){
    var result = [], add = function(key, value){
      result.push(encodeURIComponent(v ? v + '[' + key + ']' : key)
        + '=' + encodeURIComponent(value));
      },
      isObjArray = $.isArray(obj);

    for(key in obj)
      if(isObject(obj[key]))
        result.push($.param(obj[key], (v ? v + '[' + key + ']' : key)));
      else
        add(isObjArray ? '' : key, obj[key]);

    return result.join('&').replace('%20', '+');
  };
})(Zepto);
<|endoftext|>


<commit_before>import GameObject from '../GameObject'
import Cell from '../Cell/Cell'
import HashMap from 'hashmap'
import Exception from '../../exceptions/Exception'
import CellNotFoundException from '../../exceptions/CellNotFoundException'

export default class Board extends GameObject {
  /**
   * @param {GameConfig} gameConfig
   */
  constructor (gameConfig) {
    super()

    /** @type {GameConfig} */
    this.gameConfig = gameConfig

    /** @type {HashMap} */
    this.cellsByCoordinate = new HashMap()
  }

  /**
   * @param {CubeCoordinate} coordinate
   * @return {Cell}
   */
  getCellByCoordinate (coordinate) {
    if (!this.cellsByCoordinate.has(coordinate)) {
      throw new CellNotFoundException()
    }

    return this.cellsByCoordinate.get(coordinate)
  }

  /**
   * @param {Player} player
   * @return {Unit[]}
   */
  getUnitsOwnedBy (player) {
    return this.children
      .map(cell => cell.unit)
      .filter(unit => unit !== null && unit.owner === player)
  }

  /**
   * @param {CubeCoordinate} coordinate
   * @param {string} type
   * @return {Cell}
   */
  createChild (coordinate, type) {
    if (this.cellsByCoordinate.has(coordinate)) {
      throw new Exception('Cell cannot be added to Board already having Cell on the same coordinate')
    }
    let distance = Math.max(Math.abs(coordinate.x), Math.abs(coordinate.y), Math.abs(coordinate.z))
    if (distance > this.gameConfig.boardSize) {
      throw new Exception('Cell cannot be added to Board of insufficient size ' + this.gameConfig.boardSize + ' (' + distance + ' needed)')
    }

    let cell = super.createChild(Cell, coordinate, type)
    this.cellsByCoordinate.set(cell.coordinate, cell)

    let self = this
    let neighborCoordinates = cell.coordinate.getRing(1)
    neighborCoordinates.forEach(function (neighborCoordinate) {
      if (self.cellsByCoordinate.has(neighborCoordinate)) {
        let neighbor = self.cellsByCoordinate.get(neighborCoordinate)

        cell.addNeighbor(neighbor)
        neighbor.addNeighbor(cell)
      }
    })

    return cell
  }

  /**
   * @param {Cell} cell
   * @return bool
   */
  removeChild (cell) {
    super.removeChild(cell)
    while (cell.neighbors.length > 0) {
      cell.removeNeighbor(cell.neighbors[0])
    }
    this.cellsByCoordinate.remove(cell.coordinate)
  }
}
<commit_msg>annotation fix and variable rename<commit_after>import GameObject from '../GameObject'
import Cell from '../Cell/Cell'
import HashMap from 'hashmap'
import Exception from '../../exceptions/Exception'
import CellNotFoundException from '../../exceptions/CellNotFoundException'

export default class Board extends GameObject {
  /**
   * @param {GameConfig} gameConfig
   */
  constructor (gameConfig) {
    super()

    /** @type {GameConfig} */
    this.gameConfig = gameConfig

    /** @type {HashMap} */
    this.cellsByCoordinate = new HashMap()
  }

  /**
   * @param {CubeCoordinate} coordinate
   * @return {Cell}
   */
  getCellByCoordinate (coordinate) {
    if (!this.cellsByCoordinate.has(coordinate)) {
      throw new CellNotFoundException()
    }

    return this.cellsByCoordinate.get(coordinate)
  }

  /**
   * @param {Player} player
   * @return {Unit[]}
   */
  getUnitsOwnedBy (player) {
    return this.children
      .map(cell => cell.unit)
      .filter(unit => unit !== null && unit.owner === player)
  }

  /**
   * @param {CubeCoordinate} coordinate
   * @param {CellConfig} config
   * @return {Cell}
   */
  createChild (coordinate, config) {
    if (this.cellsByCoordinate.has(coordinate)) {
      throw new Exception('Cell cannot be added to Board already having Cell on the same coordinate')
    }
    let distance = Math.max(Math.abs(coordinate.x), Math.abs(coordinate.y), Math.abs(coordinate.z))
    if (distance > this.gameConfig.boardSize) {
      throw new Exception('Cell cannot be added to Board of insufficient size ' + this.gameConfig.boardSize + ' (' + distance + ' needed)')
    }

    let cell = super.createChild(Cell, coordinate, config)
    this.cellsByCoordinate.set(cell.coordinate, cell)

    let self = this
    let neighborCoordinates = cell.coordinate.getRing(1)
    neighborCoordinates.forEach(function (neighborCoordinate) {
      if (self.cellsByCoordinate.has(neighborCoordinate)) {
        let neighbor = self.cellsByCoordinate.get(neighborCoordinate)

        cell.addNeighbor(neighbor)
        neighbor.addNeighbor(cell)
      }
    })

    return cell
  }

  /**
   * @param {Cell} cell
   * @return bool
   */
  removeChild (cell) {
    super.removeChild(cell)
    while (cell.neighbors.length > 0) {
      cell.removeNeighbor(cell.neighbors[0])
    }
    this.cellsByCoordinate.remove(cell.coordinate)
  }
}
<|endoftext|>


<commit_before>import Octokat from 'octokat';
import { OAuth } from 'oauthio-web';
import assign from 'object-assign';
import { Promise } from 'es6-promise';
import { OctokatCacheHandler } from './octokat-cache-handler';
import { OctokatHelper } from './octokat-helper';
import { octokat, octokatHelper } from './factory';
import Options from './options';
import { dispatcher } from './dispatcher';

var cacheKey = 'ghir-github-access-token';

var executor = {};
var promise = new Promise((resolve, reject) => {
  executor = {resolve, reject};
});

export default class Auth {

  static gitHubAccessToken;

  static wait() {
    return promise;
  }

  static check(params) {
    var options = assign({}, Options, params);
    console.log('check auth', options);

    var gitHubAccessToken = localStorage.getItem(cacheKey, gitHubAccessToken);

    console.log('cached gitHubAccessToken', gitHubAccessToken);

    if (gitHubAccessToken) {
      return this.withToken(gitHubAccessToken);
    }

    if (! options.noAnonymous) {
      return this.anonymous();
    }

    executor.reject('Not logged in.');

    return Promise.reject('Not logged in.');
  }

  static anonymous() {
    return this.withToken(null);
  }

  static signIn(params) {
    var options = assign({}, Options, params, {
      noAnonymous: true
    });

    return this.check(options).then(
      (result => {
        console.log('result', result);

        return Promise.resolve(result);
      }),
      (err => {

        console.log('err', err);

        OAuth.initialize(options.oAuthIoKey);

        var executor = {};
        var promise = new Promise((resolve, reject) => {
          executor = {resolve, reject};
        });

        OAuth.popup('github')
          .done(result => {
              var gitHubAccessToken = Auth.gitHubAccessToken = result.access_token;
              console.log('github auth success', result);

              dispatcher.auth();

              executor.resolve(this.setToken(gitHubAccessToken));
          })
          .fail(err => {
              console.error('github auth err', err);
              executor.reject(err);
          });

        return promise;
      })
    );
  }

  static setToken(gitHubAccessToken) {
    try {
      localStorage.setItem(cacheKey, gitHubAccessToken);
    }
    catch (e) {}
    return this.withToken(gitHubAccessToken);
  }

  /**
   * @param  {[type]} gitHubAccessToken GitHub access token, else null for guest.
   * @return {[type]}                   [description]
   */
  static withToken(gitHubAccessToken) {
    console.log('with token', gitHubAccessToken);
    var octokatCacheHandler = new OctokatCacheHandler();

    octokat(new Octokat({
      token: gitHubAccessToken,
      cacheHandler: octokatCacheHandler
    }));

    octokatHelper(new OctokatHelper(octokat()));

    var res = { gitHubAccessToken };

    executor.resolve(res);

    return Promise.resolve(res);
  }

  static signOut(params) {
    var options = assign({}, Options, params);

    localStorage.removeItem(cacheKey);

    return this.anonymous();
  }

}
<commit_msg>Commented base URL.<commit_after>import Octokat from 'octokat';
import { OAuth } from 'oauthio-web';
import assign from 'object-assign';
import { Promise } from 'es6-promise';
import { OctokatCacheHandler } from './octokat-cache-handler';
import { OctokatHelper } from './octokat-helper';
import { octokat, octokatHelper } from './factory';
import Options from './options';
import { dispatcher } from './dispatcher';

var cacheKey = 'ghir-github-access-token';

var executor = {};
var promise = new Promise((resolve, reject) => {
  executor = {resolve, reject};
});

export default class Auth {

  static gitHubAccessToken;

  static wait() {
    return promise;
  }

  static check(params) {
    var options = assign({}, Options, params);
    console.log('check auth', options);

    var gitHubAccessToken = localStorage.getItem(cacheKey, gitHubAccessToken);

    console.log('cached gitHubAccessToken', gitHubAccessToken);

    if (gitHubAccessToken) {
      return this.withToken(gitHubAccessToken);
    }

    if (! options.noAnonymous) {
      return this.anonymous();
    }

    executor.reject('Not logged in.');

    return Promise.reject('Not logged in.');
  }

  static anonymous() {
    return this.withToken(null);
  }

  static signIn(params) {
    var options = assign({}, Options, params, {
      noAnonymous: true
    });

    return this.check(options).then(
      (result => {
        console.log('result', result);

        return Promise.resolve(result);
      }),
      (err => {

        console.log('err', err);

        OAuth.initialize(options.oAuthIoKey);

        var executor = {};
        var promise = new Promise((resolve, reject) => {
          executor = {resolve, reject};
        });

        OAuth.popup('github')
          .done(result => {
              var gitHubAccessToken = Auth.gitHubAccessToken = result.access_token;
              console.log('github auth success', result);

              dispatcher.auth();

              executor.resolve(this.setToken(gitHubAccessToken));
          })
          .fail(err => {
              console.error('github auth err', err);
              executor.reject(err);
          });

        return promise;
      })
    );
  }

  static setToken(gitHubAccessToken) {
    try {
      localStorage.setItem(cacheKey, gitHubAccessToken);
    }
    catch (e) {}
    return this.withToken(gitHubAccessToken);
  }

  /**
   * @param  {[type]} gitHubAccessToken GitHub access token, else null for guest.
   * @return {[type]}                   [description]
   */
  static withToken(gitHubAccessToken) {
    console.log('with token', gitHubAccessToken);
    var octokatCacheHandler = new OctokatCacheHandler();

    octokat(new Octokat({
      token: gitHubAccessToken,
      cacheHandler: octokatCacheHandler,
      // rootURL: 'http://localhost:9000/api.github.com'
    }));

    octokatHelper(new OctokatHelper(octokat()));

    var res = { gitHubAccessToken };

    executor.resolve(res);

    return Promise.resolve(res);
  }

  static signOut(params) {
    var options = assign({}, Options, params);

    localStorage.removeItem(cacheKey);

    return this.anonymous();
  }

}
<|endoftext|>