<commit_before>require("./patch-buffer");

var util = require("util");
var EventEmitter = require("events").EventEmitter;

var net = require("net");
var BufferReader = require("buffer-reader");

var packetTypes = {
	PACKET_SERVER_FULL: 0,
	PACKET_SERVER_FULL: 1,
	PACKET_CLIENT_JOIN: 2,
	PACKET_SERVER_ERROR: 3,
	PACKET_CLIENT_COMPANY_INFO: 4,
	PACKET_SERVER_COMPANY_INFO: 5,
	PACKET_SERVER_CHECK_NEWGRFS: 6,
	PACKET_CLIENT_NEWGRFS_CHECKED: 7,
	PACKET_SERVER_NEED_GAME_PASSWORD: 8,
	PACKET_CLIENT_GAME_PASSWORD: 9,
	PACKET_SERVER_NEED_COMPANY_PASSWORD: 10,
	PACKET_CLIENT_COMPANY_PASSWORD: 11,
	PACKET_SERVER_WELCOME: 12,
	PACKET_SERVER_CLIENT_INFO: 13,
	PACKET_CLIENT_GETMAP: 14,
	PACKET_SERVER_WAIT: 15,
	PACKET_SERVER_MAP_BEGIN: 16,
	PACKET_SERVER_MAP_SIZE: 17,
	PACKET_SERVER_MAP_DATA: 18,
	PACKET_SERVER_MAP_DONE: 19,
	PACKET_CLIENT_MAP_OK: 20,
	PACKET_SERVER_JOIN: 21,
	PACKET_SERVER_FRAME: 22,
	PACKET_CLIENT_ACK: 23,
	PACKET_SERVER_SYNC: 24,
	PACKET_CLIENT_COMMAND: 25,
	PACKET_SERVER_COMMAND: 26,
	PACKET_CLIENT_CHAT: 27,
	PACKET_SERVER_CHAT: 28,
	PACKET_CLIENT_RCON: 29,
	PACKET_SERVER_RCON: 30,
	PACKET_CLIENT_MOVE: 31,
	PACKET_SERVER_MOVE: 32,
	PACKET_CLIENT_SET_PASSWORD: 33,
	PACKET_CLIENT_SET_NAME: 34,
	PACKET_SERVER_COMPANY_UPDATE: 35,
	PACKET_SERVER_CONFIG_UPDATE: 36,
	PACKET_SERVER_NEWGAME: 37,
	PACKET_SERVER_SHUTDOWN: 38,
	PACKET_CLIENT_QUIT: 39,
	PACKET_SERVER_QUIT: 40,
	PACKET_CLIENT_ERROR: 41,
	PACKET_SERVER_ERROR_QUIT: 42,
	PACKET_END: 43,
};

function Client() {
	var self = this;

	self.socket = null;

	self.clientId = null;
	self.clients = {};
	self.ackToken = null;
	self.frameCnt = 0;

	self.on("packet", function(packet) {
		self.emit("packet#" + packet.readUInt8(0), packet.slice(1));
	});

	self.on("packet#5", function(buffer) {
		var moreData = !!buffer.readUInt8(1);
		if (!moreData) {
			/*var newGrfBuffer = new Buffer(4);
			newGrfBuffer.writeUInt32LE(0, 0);*/
			var newGrfBuffer = new Buffer([0x46, 0x6B, 0x38, 0x15]);

			var packet = Buffer.concat([
				new Buffer([0x02]),
				new Buffer("1.5.3\0"),
				newGrfBuffer,
				new Buffer("simbot\0"),
				new Buffer([0xFF, 0x00]),
			]);
			self.send(packet);
		}
	});

	self.on("packet#12", function(buffer) {
		self.clientId = buffer.readUInt32LE(0);
	});

	self.on("packet#13", function(buffer) {
		var reader = new BufferReader(buffer);

		var client = {};
		client.id = reader.nextUInt32LE();
		client.playAs = reader.nextUInt8();
		client.name = reader.nextStringZero();

		self.clients[client.id] = client;

		self.send(new Buffer([0x0E]));
	});

	self.on("packet#19", function(buffer) {
		self.send(new Buffer([0x14]));
	});

	self.on("packet#22", function(buffer) {
		var reader = new BufferReader(buffer);

		var frame = reader.nextUInt32LE();
		var frameMax = reader.nextUInt32LE();
		try {
			self.ackToken = reader.nextUInt8();
		}
		catch (e) {

		}

		if (++self.frameCnt >= 100) {
			var frameBuffer = new Buffer(4);
			frameBuffer.writeUInt32LE(frame, 0);

			var packet = Buffer.concat([
				new Buffer([0x17]),
				frameBuffer,
				new Buffer([self.ackToken]),
			]);
			self.send(packet);

			self.frameCnt = 0;
		}
	});

	self.on("packet#28", function(buffer) {
		var reader = new BufferReader(buffer);

		var chat = {
			actionId: reader.nextUInt8(),
			clientId: reader.nextUInt32LE(),
			self: !!reader.nextUInt8(),
			msg: reader.nextStringZero(),
			data: reader.nextUInt64LE(),
		};
		//console.log("chat", chat);

		self.emit("chat", chat);
	});

	EventEmitter.call(self);
}

util.inherits(Client, EventEmitter);

Client.prototype.connect = function(addr, port) {
	var self = this;

	self.socket = net.connect(port, addr);
	self.data = new Buffer(0);

	self.socket.on("connect", function() {
		//console.log("connect");
		self.send(new Buffer([0x04]));
	});

	self.socket.on("data", function(buffer) {
		//console.log("data", buffer);
		self.data = Buffer.concat([self.data, buffer]);
		self.handle();
	});

	self.socket.on("close", function(had_error) {
		//console.log("close", had_error);
	});
};

Client.prototype.send = function(packet) {
	var self = this;

	var lenBuffer = new Buffer(2);
	lenBuffer.writeUInt16LE(packet.length + lenBuffer.length, 0);

	var outBuffer = Buffer.concat([lenBuffer, packet]);
	//console.log("send", outBuffer);
	self.socket.write(outBuffer);
};

Client.prototype.handle = function() {
	var self = this;

	if (self.data.length >= 2) {
		var len = self.data.readUInt16LE(0);
		if (len <= self.data.length) {
			var packet = new Buffer(len - 2);
			self.data.copy(packet, 0, 2, len);
			//console.log("packet", packet);
			self.emit("packet", packet);

			self.data = self.data.slice(len);
			self.handle();
		}
	}
};

Client.prototype.chat = function(msg) {
	var self = this;

	var destBuffer = new Buffer(4);
	destBuffer.writeUInt32LE(1, 0);

	var packet = Buffer.concat([
		new Buffer([0x1B, 0x03, 0x00]),
		destBuffer,
		new Buffer(msg + "\0"),
		new Buffer(8),
	]);
	self.send(packet);
};

Client.prototype.end = function() {
	var self = this;

	var packet = new Buffer([0x27]);
	self.send(packet);
};

module.exports = Client;
<commit_msg>openttd: Client doesn't send into closed socket<commit_after>require("./patch-buffer");

var util = require("util");
var EventEmitter = require("events").EventEmitter;

var net = require("net");
var BufferReader = require("buffer-reader");

var packetTypes = {
	PACKET_SERVER_FULL: 0,
	PACKET_SERVER_FULL: 1,
	PACKET_CLIENT_JOIN: 2,
	PACKET_SERVER_ERROR: 3,
	PACKET_CLIENT_COMPANY_INFO: 4,
	PACKET_SERVER_COMPANY_INFO: 5,
	PACKET_SERVER_CHECK_NEWGRFS: 6,
	PACKET_CLIENT_NEWGRFS_CHECKED: 7,
	PACKET_SERVER_NEED_GAME_PASSWORD: 8,
	PACKET_CLIENT_GAME_PASSWORD: 9,
	PACKET_SERVER_NEED_COMPANY_PASSWORD: 10,
	PACKET_CLIENT_COMPANY_PASSWORD: 11,
	PACKET_SERVER_WELCOME: 12,
	PACKET_SERVER_CLIENT_INFO: 13,
	PACKET_CLIENT_GETMAP: 14,
	PACKET_SERVER_WAIT: 15,
	PACKET_SERVER_MAP_BEGIN: 16,
	PACKET_SERVER_MAP_SIZE: 17,
	PACKET_SERVER_MAP_DATA: 18,
	PACKET_SERVER_MAP_DONE: 19,
	PACKET_CLIENT_MAP_OK: 20,
	PACKET_SERVER_JOIN: 21,
	PACKET_SERVER_FRAME: 22,
	PACKET_CLIENT_ACK: 23,
	PACKET_SERVER_SYNC: 24,
	PACKET_CLIENT_COMMAND: 25,
	PACKET_SERVER_COMMAND: 26,
	PACKET_CLIENT_CHAT: 27,
	PACKET_SERVER_CHAT: 28,
	PACKET_CLIENT_RCON: 29,
	PACKET_SERVER_RCON: 30,
	PACKET_CLIENT_MOVE: 31,
	PACKET_SERVER_MOVE: 32,
	PACKET_CLIENT_SET_PASSWORD: 33,
	PACKET_CLIENT_SET_NAME: 34,
	PACKET_SERVER_COMPANY_UPDATE: 35,
	PACKET_SERVER_CONFIG_UPDATE: 36,
	PACKET_SERVER_NEWGAME: 37,
	PACKET_SERVER_SHUTDOWN: 38,
	PACKET_CLIENT_QUIT: 39,
	PACKET_SERVER_QUIT: 40,
	PACKET_CLIENT_ERROR: 41,
	PACKET_SERVER_ERROR_QUIT: 42,
	PACKET_END: 43,
};

function Client() {
	var self = this;

	self.socket = null;
	self.open = false;

	self.clientId = null;
	self.clients = {};
	self.ackToken = null;
	self.frameCnt = 0;

	self.on("packet", function(packet) {
		self.emit("packet#" + packet.readUInt8(0), packet.slice(1));
	});

	self.on("packet#5", function(buffer) {
		var moreData = !!buffer.readUInt8(1);
		if (!moreData) {
			/*var newGrfBuffer = new Buffer(4);
			newGrfBuffer.writeUInt32LE(0, 0);*/
			var newGrfBuffer = new Buffer([0x46, 0x6B, 0x38, 0x15]);

			var packet = Buffer.concat([
				new Buffer([0x02]),
				new Buffer("1.5.3\0"),
				newGrfBuffer,
				new Buffer("simbot\0"),
				new Buffer([0xFF, 0x00]),
			]);
			self.send(packet);
		}
	});

	self.on("packet#12", function(buffer) {
		self.clientId = buffer.readUInt32LE(0);
	});

	self.on("packet#13", function(buffer) {
		var reader = new BufferReader(buffer);

		var client = {};
		client.id = reader.nextUInt32LE();
		client.playAs = reader.nextUInt8();
		client.name = reader.nextStringZero();

		self.clients[client.id] = client;

		self.send(new Buffer([0x0E]));
	});

	self.on("packet#19", function(buffer) {
		self.send(new Buffer([0x14]));
	});

	self.on("packet#22", function(buffer) {
		var reader = new BufferReader(buffer);

		var frame = reader.nextUInt32LE();
		var frameMax = reader.nextUInt32LE();
		try {
			self.ackToken = reader.nextUInt8();
		}
		catch (e) {

		}

		if (++self.frameCnt >= 100) {
			var frameBuffer = new Buffer(4);
			frameBuffer.writeUInt32LE(frame, 0);

			var packet = Buffer.concat([
				new Buffer([0x17]),
				frameBuffer,
				new Buffer([self.ackToken]),
			]);
			self.send(packet);

			self.frameCnt = 0;
		}
	});

	self.on("packet#28", function(buffer) {
		var reader = new BufferReader(buffer);

		var chat = {
			actionId: reader.nextUInt8(),
			clientId: reader.nextUInt32LE(),
			self: !!reader.nextUInt8(),
			msg: reader.nextStringZero(),
			data: reader.nextUInt64LE(),
		};
		//console.log("chat", chat);

		self.emit("chat", chat);
	});

	EventEmitter.call(self);
}

util.inherits(Client, EventEmitter);

Client.prototype.connect = function(addr, port) {
	var self = this;

	self.socket = net.connect(port, addr);
	self.data = new Buffer(0);

	self.socket.on("connect", function() {
		self.open = true;
		self.emit("connect");
		//console.log("connect");
		self.send(new Buffer([0x04]));
	});

	self.socket.on("data", function(buffer) {
		//console.log("data", buffer);
		self.data = Buffer.concat([self.data, buffer]);
		self.handle();
	});

	self.socket.on("error", function(err) {
		self.emit("error", err);
	});

	self.socket.on("close", function(had_error) {
		//console.log("close", had_error);
		self.emit("close");
	});
};

Client.prototype.send = function(packet) {
	var self = this;

	if (self.open) {
		var lenBuffer = new Buffer(2);
		lenBuffer.writeUInt16LE(packet.length + lenBuffer.length, 0);

		var outBuffer = Buffer.concat([lenBuffer, packet]);
		//console.log("send", outBuffer);
		self.socket.write(outBuffer);
	}
};

Client.prototype.handle = function() {
	var self = this;

	if (self.data.length >= 2) {
		var len = self.data.readUInt16LE(0);
		if (len <= self.data.length) {
			var packet = new Buffer(len - 2);
			self.data.copy(packet, 0, 2, len);
			//console.log("packet", packet);
			self.emit("packet", packet);

			self.data = self.data.slice(len);
			self.handle();
		}
	}
};

Client.prototype.chat = function(msg) {
	var self = this;

	var destBuffer = new Buffer(4);
	destBuffer.writeUInt32LE(1, 0);

	var packet = Buffer.concat([
		new Buffer([0x1B, 0x03, 0x00]),
		destBuffer,
		new Buffer(msg + "\0"),
		new Buffer(8),
	]);
	self.send(packet);
};

Client.prototype.end = function() {
	var self = this;

	var packet = new Buffer([0x27]);
	self.send(packet);
};

module.exports = Client;
<|endoftext|>


<commit_before>/*!
 * Pikaday jQuery plugin.
 *
 * Copyright © 2013 David Bushell | BSD & MIT license | https://github.com/dbushell/Pikaday
 */

(function (root, factory)
{
    'use strict';

    if (typeof exports === 'object') {
        // CommonJS module
        factory(require('jquery'), require('../pikaday'));
    } else if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery', 'pikaday'], factory);
    } else {
        // Browser globals
        factory(root.jQuery, root.Pikaday);
    }
}(this, function ($, Pikaday)
{
    'use strict';

    $.fn.pikaday = function()
    {
        var args = arguments;

        if (!args || !args.length) {
            args = [{ }];
        }

        return this.each(function()
        {
            var self   = $(this),
                plugin = self.data('pikaday');

            if (!(plugin instanceof Pikaday)) {
                if (typeof args[0] === 'object') {
                    var options = $.extend({}, args[0]);
                    options.field = self[0];
                    self.data('pikaday', new Pikaday(options));
                }
            } else {
                if (typeof args[0] === 'string' && typeof plugin[args[0]] === 'function') {
                    plugin[args[0]].apply(plugin, Array.prototype.slice.call(args,1));
                }
            }
        });
    };

}));
<commit_msg>remove data after pikaday destroy - fixes #382<commit_after>/*!
 * Pikaday jQuery plugin.
 *
 * Copyright © 2013 David Bushell | BSD & MIT license | https://github.com/dbushell/Pikaday
 */

(function (root, factory)
{
    'use strict';

    if (typeof exports === 'object') {
        // CommonJS module
        factory(require('jquery'), require('../pikaday'));
    } else if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery', 'pikaday'], factory);
    } else {
        // Browser globals
        factory(root.jQuery, root.Pikaday);
    }
}(this, function ($, Pikaday)
{
    'use strict';

    $.fn.pikaday = function()
    {
        var args = arguments;

        if (!args || !args.length) {
            args = [{ }];
        }

        return this.each(function()
        {
            var self   = $(this),
                plugin = self.data('pikaday');

            if (!(plugin instanceof Pikaday)) {
                if (typeof args[0] === 'object') {
                    var options = $.extend({}, args[0]);
                    options.field = self[0];
                    self.data('pikaday', new Pikaday(options));
                }
            } else {
                if (typeof args[0] === 'string' && typeof plugin[args[0]] === 'function') {
                    plugin[args[0]].apply(plugin, Array.prototype.slice.call(args,1));

                    if (args[0] === 'destroy') {
                        self.removeData('pikaday');
                    }
                }
            }
        });
    };

}));
<|endoftext|>


<commit_before>/**
 * Created by chenm on 2016/7/14.
 */
import React, { Component, PropTypes } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import LangList from '../LangList';

import s from './LanguagePage.scss';
import Paper from 'material-ui/Paper';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';

class LanguagePage extends Component {
  render() {
    return (

          <Paper>
            <TextField hintText="Choose languages you are good at or learning"
                       fullWidth={true}
                       underlineShow={false}
                       inputStyle={{padding: '0 16px', boxSizing: 'border-box'}}
                       hintStyle={{padding: '0 16px'}}
            />
            <LangList/>

              <RaisedButton label="DONE" primary={true}/>
              <RaisedButton label="CANCEL"/>

          </Paper>

    )
  }
}

export default withStyles(LanguagePage, s);
<commit_msg>Link data to languagepage<commit_after>/**
 * Created by chenm on 2016/7/14.
 */
import React, { Component, PropTypes } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import LangList from '../LangList';

import s from './LanguagePage.scss';
import Paper from 'material-ui/Paper';
import TextField from 'material-ui/TextField';
import $ from 'jquery';

// let langData = [
//   {
//     name: "JavaScript",
//     isSelected: false,
//     level: 0,
//     repoNum: 4000000
//   },
//   {
//     name: "C++",
//     isSelected: true,
//     level: 1,
//     repoNum: 2131200
//   },
//   {
//     name: "Java",
//     isSelected: false,
//     level: 0,
//     repoNum: 2100000
//   }
// ];
//
// let allLanguage = [
//   {
//     name: 'Java',
//     repoNum: 210000,
//   },
//   {
//     name: "JavaScript",
//     repoNum: 4000000
//   },
//   {
//     name: "C++",
//     repoNum: 2131200
//   },
//   {
//     name: "Ruby",
//     repoNum: 2012400
//   }
// ];
//
// let userLanguage = [
//   {
//     name: 'Java',
//     level: 1
//   }
// ];

class LanguagePage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      user: "RickChem",
      langData: []
    }
  }

  componentDidMount() {
    let user = this.state.user;
    let langData = [];
    let allLang = [];

    // Get all language
    $.ajax('/api/language/all', {async: false})
      .done(((allLanguages) => {
        // console.log(allLanguages);
        allLang = allLanguages;
      }).bind(this));

    // Get user language
    $.ajax('/api/home/langList', {async: false, data:{user: user}})
      .done(((userLanguages) => {

        // Delete selected language
        langData = allLang.filter((lang) => {
          let result = true;
          userLanguages.forEach((l) => {
            if(l.name == lang.name) {
              result = false;
              // console.log(lang.name);
            }
          });
          return result;
        });

        // console.log(langData);
        this.setState({langData: langData});

      }).bind(this))
  }

  render() {
    return (

          <Paper>
            <TextField hintText="Choose languages you are good at or learning"
                       fullWidth={true}
                       underlineShow={false}
                       inputStyle={{padding: '0 16px', boxSizing: 'border-box'}}
                       hintStyle={{padding: '0 16px'}}
            />
            <LangList langData={this.state.langData} user={this.state.user} ref="list"/>
          </Paper>

    )
  }
}

export default withStyles(LanguagePage, s);
<|endoftext|>


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

var Plugin = {}

var plugins = {}
var trigger_prefix = '.'

var register_trigger = function (trigger, plugin, action) {

}

Plugin.load = function (name) {
  if (plugins[name]) {
    console.error('Plugin exists')
    return
  }

  var p = require('./' + name)
  plugins[name] = { trigger: p.trigger, action: p.action }

  console.log('Plugin (' + name + ') loaded...')
}

Plugin.reload = function (name) {
  if (Plugin.unload(name)) {
    Plugin.load(name)
  }
}

Plugin.unload = function (name) {
  if (plugins[name]) {
    delete plugins[name];

    var tmp_name = require.resolve('./' + name)
    delete require.cache[tmp_name]

    console.log(name + ' unloaded...')
    return 1
  }

  console.log('couldnt unload')
  return 0
}

module.exports = function (bot, config) {
  trigger_prefix = config.trigger_prefix

  bot.addListener('message', function (user, channel, text, message) {
    if (text.charAt(0) != trigger_prefix) {
      console.log('Aint nobody got time for this...')
      return
    }

    var text = text.replace(/\s+/g, ' ')
    var args = text.substring(1).split(' ')

    if (args[0] == 'plugin') {
      if (args[1] == 'load') {
        Plugin.load(args[2])
      }
      else if (args[1] == 'unload') {
        Plugin.unload(args[2])
      }
      else if (args[1] == 'reload') {
        Plugin.reload(args[2])
      }
    }
    else {
      for (key in plugins) {
        if (plugins[key].trigger == args[0]) {
          bot.say(channel, plugins[key].action())
        }
      }
    }
  })

  console.log('Trigger prefix: ' + config.trigger_prefix)
}
<commit_msg>Extract trigger registration function<commit_after>var fs = require('fs')

var Plugin = {}

var plugins = {}
var trigger_prefix = '.'

var register_trigger = function (plugin) {
  plugins[name] = {
    trigger: plugin.trigger,
    action: plugin.action
  }
}

Plugin.load = function (name) {
  if (plugins[name]) {
    console.error('Plugin exists')
    return
  }

  var plugin = require('./' + name)

  register_trigger(plugin)

  console.log('Plugin (' + name + ') loaded...')
}

Plugin.reload = function (name) {
  if (Plugin.unload(name)) {
    Plugin.load(name)
  }
}

Plugin.unload = function (name) {
  if (plugins[name]) {
    delete plugins[name];

    var tmp_name = require.resolve('./' + name)
    delete require.cache[tmp_name]

    console.log(name + ' unloaded...')
    return 1
  }

  console.log('couldnt unload')
  return 0
}

module.exports = function (bot, config) {
  trigger_prefix = config.trigger_prefix

  bot.addListener('message', function (user, channel, text, message) {
    if (text.charAt(0) != trigger_prefix) {
      console.log('Aint nobody got time for this...')
      return
    }

    var text = text.replace(/\s+/g, ' ')
    var args = text.substring(1).split(' ')

    if (args[0] == 'plugin') {
      if (args[1] == 'load') {
        Plugin.load(args[2])
      }
      else if (args[1] == 'unload') {
        Plugin.unload(args[2])
      }
      else if (args[1] == 'reload') {
        Plugin.reload(args[2])
      }
    }
    else {
      for (key in plugins) {
        if (plugins[key].trigger == args[0]) {
          bot.say(channel, plugins[key].action())
        }
      }
    }
  })

  console.log('Trigger prefix: ' + config.trigger_prefix)
}
<|endoftext|>


<commit_before>import {QueryBuilder} from 'react-querybuilder';
import React, {Component} from 'react';
import { Button, Glyphicon, Well, Modal, Tabs, Tab, Grid, Row, Col, Alert, FormGroup, Checkbox, ControlLabel, FormControl, HelpBlock} from 'react-bootstrap';
import CreateDataViewDialog from '../Dialogs/createDataView';
import CreateAlertViewDialog from '../Dialogs/createAlertView';
const {Footer, Body, Header, Title} = Modal;
/* eslint-disable react/prop-types*/

const fields = [
    { name: 'location', label: 'Location', value: {} },
    { name: 'time', label: 'Time' },
    { name: 'keyword', label: 'Keyword' },
    { name: 'user', label: 'User' },
    { name: 'source', label: 'Source' },
    { name: 'hasMedia', label: 'Has Attachment', value: false }
];

const CSSClass = {

    combinators: 'form-control', // <select> control for combinators
    addRule: 'btn btn-primary', // <button> to add a Rule
    addGroup: 'btn btn-primary', // <button> to add a RuleGroup
    removeGroup: 'btn btn-danger', // <button> to remove a RuleGroup

    rule: String, //
 containing the Rule
    fields: 'form-control', // <select> control for fields
    operators: 'form-control', // <select> control for operators
    value: 'form-control', // <input> for the field value
    removeRule: 'btn btn-danger' // <button> to remove a Rule
};

function getEditor({field, operator, value, onChange}) {
    if (field == 'hasMedia') {
        // return empty control - we don't need another
        return (

        );
    }
    if (field == 'source') {
        return (
            <select className='form-control'>
                <option value="any">Any</option>
                <option value="twitter">Twitter</option>
                <option value="facebook">Facebook</option>
                <option value="instagram">Instagram</option>
            </select>
        )
    }
    if (field == 'time' && operator == 'last') {
        return (
            <select className='form-control'>
                <option value="last-15m">15 mins</option>
                <option value="last-h">1 hour</option>
                <option value="last-12h">12 hours</option>
                <option value="last-day">Day</option>
                <option value="last-week">Week</option>
            </select>
        )
    }
    if (field == 'keyword' && operator == 'equals') {
        return (
            <select className='form-control'>
                <option value="k-a">keyword-a</option>
                <option value="k-b">keyword-b</option>
                <option value="k-c">keyword-c</option>
                <option value="k-d">keyword-d</option>
                <option value="k-e">keyword-e</option>
            </select>
        )
    }
    if (field == 'keyword' && operator == 'savedList') {
        return (
            <select className='form-control'>
                <option value="s-a">Stores</option>
                <option value="s-b">Parties</option>
                <option value="s-c">Holidays</option>
                <option value="s-d">Sports</option>
                <option value="s-e">Schools</option>
            </select>
        )
    }
    if (field == 'location') {
        if (operator == 'na')
            return (

            );
        else return (
            <select className='form-control'>
                <option value="global">Global</option>
                <option value="map1">Current Viewport (Map1) </option>
                <optgroup label="System">
                    <option value="l-a">London Airports</option>
                    <option value="l-b">London Boroughs</option>
                </optgroup>
                <optgroup label="Locals">
                    <option value="m25">M25</option>
                    <option value="in-cafe">Internet Cafes</option>
                </optgroup>
            </select>
        )
    }
    return (
        <input type="text" className="form-control" style={{ width: '30%', minWidth: '120px', display: 'inline-block' }}/>
    )
}

function getOperators(field) {
    if (field == 'location') {
        return [{ name: 'within', label: 'within' }, { name: 'na', label: 'n/a' }];
    } else if (field == 'hasMedia') {
        return [{ name: 'true', label: 'Yes' }, { name: 'false', label: 'no' }];
    } else if (field == 'keyword') {
        return [{ name: 'true', label: 'Contains' }, { name: 'false', label: 'Doesn\'t contain' },
            { name: 'equals', label: 'Equals' },{ name: 'savedList', label: 'Saved list' } ];
    } else if (field == 'time') {
        return [{ name: 'before', label: 'Before' }, { name: 'after', label: 'After' },
            { name: 'between', label: 'Between' }, { name: 'last', label: 'Last' }];
    } else return null;

}

const startQuery = {
    combinator: 'and',
    id: '111',
    rules: [
        {
            id: '222',
            field: 'firstName',
            value: 'Test',
            operator: '='
        }
    ]
};

export default class QueryBuilderWindow extends Component {

    constructor(prop) {
        super(prop);
        this.state = { showModalView: false, showModalAlert: false };
        this.close = this.close.bind(this);
        this.open = this.open.bind(this);
         this.openAlert = this.openAlert.bind(this);
    }

    close() {
        this.setState({ showModalView: false });
        this.setState({ showModalAlert: false })
    }

    open() {
        this.setState({ showModalView: true });
    }
    openAlert() {
        this.setState({ showModalAlert: true });
    }
    render() {
        const {showModalView, showModalAlert} = this.state;
        return (

                    <Button bsStyle='default'  ><Glyphicon glyph="cog" /> </Button>
                       <Button bsStyle='info'  ><Glyphicon glyph="question-sign" /> </Button>

                            <Well  >
                                Create your search query
                                <QueryBuilder query={startQuery} fields={fields}
                                    onQueryChange={logQuery} getEditor={getEditor} getOperators={getOperators} controlClassnames= {CSSClass}/>
                            </Well>

                    <Button bsStyle='danger' onClick={this.openAlert}  ><Glyphicon glyph="alert" />  Create Alert </Button>
                    <Button bsStyle='primary' onClick={this.open} ><Glyphicon glyph="eye-open" /> Show in Data View  </Button>

                <Modal show={showModalView} onHide={this.close}>

                        <Title>Create Data View</Title>

                        <CreateDataViewDialog/>

                        <Button  bsStyle="success"onClick={this.close}>Confirm</Button>
                        <Button onClick={this.close}>Close</Button>

                </Modal>
                <Modal show={showModalAlert} onHide={this.close}>

                        <Title>Create Alert</Title>

                        <CreateAlertViewDialog/>

                        <Button  bsStyle="success"onClick={this.close}>Confirm</Button>
                        <Button onClick={this.close}>Close</Button>

                </Modal>

)
    }
}

function logQuery(query) {
    //console.log(query);
}<commit_msg>use better default criteria<commit_after>import {QueryBuilder} from 'react-querybuilder';
import React, {Component} from 'react';
import { Button, Glyphicon, Well, Modal, Tabs, Tab, Grid, Row, Col, Alert, FormGroup, Checkbox, ControlLabel, FormControl, HelpBlock} from 'react-bootstrap';
import CreateDataViewDialog from '../Dialogs/createDataView';
import CreateAlertViewDialog from '../Dialogs/createAlertView';
const {Footer, Body, Header, Title} = Modal;
/* eslint-disable react/prop-types*/

const fields = [
    { name: 'location', label: 'Location', value: {} },
    { name: 'time', label: 'Time' },
    { name: 'keyword', label: 'Keyword' },
    { name: 'user', label: 'User' },
    { name: 'source', label: 'Source' },
    { name: 'hasMedia', label: 'Has Attachment', value: false }
];

const CSSClass = {

    combinators: 'form-control', // <select> control for combinators
    addRule: 'btn btn-primary', // <button> to add a Rule
    addGroup: 'btn btn-primary', // <button> to add a RuleGroup
    removeGroup: 'btn btn-danger', // <button> to remove a RuleGroup

    rule: String, //
 containing the Rule
    fields: 'form-control', // <select> control for fields
    operators: 'form-control', // <select> control for operators
    value: 'form-control', // <input> for the field value
    removeRule: 'btn btn-danger' // <button> to remove a Rule
};

function getEditor({field, operator, value, onChange}) {
    if (field == 'hasMedia') {
        // return empty control - we don't need another
        return (

        );
    }
    if (field == 'source') {
        return (
            <select className='form-control'>
                <option value="any">Any</option>
                <option value="twitter">Twitter</option>
                <option value="facebook">Facebook</option>
                <option value="instagram">Instagram</option>
            </select>
        )
    }
    if (field == 'time' && operator == 'last') {
        return (
            <select className='form-control'>
                <option value="last-15m">15 mins</option>
                <option value="last-h">1 hour</option>
                <option value="last-12h">12 hours</option>
                <option value="last-day">Day</option>
                <option value="last-week">Week</option>
            </select>
        )
    }
    if (field == 'keyword' && operator == 'equals') {
        return (
            <select className='form-control'>
                <option value="k-a">keyword-a</option>
                <option value="k-b">keyword-b</option>
                <option value="k-c">keyword-c</option>
                <option value="k-d">keyword-d</option>
                <option value="k-e">keyword-e</option>
            </select>
        )
    }
    if (field == 'keyword' && operator == 'savedList') {
        return (
            <select className='form-control'>
                <option value="s-a">Stores</option>
                <option value="s-b">Parties</option>
                <option value="s-c">Holidays</option>
                <option value="s-d">Sports</option>
                <option value="s-e">Schools</option>
            </select>
        )
    }
    if (field == 'location') {
        if (operator == 'na')
            return (

            );
        else return (
            <select className='form-control'>
                <option value="global">Global</option>
                <option value="map1">Current Viewport (Map1) </option>
                <optgroup label="System">
                    <option value="l-a">London Airports</option>
                    <option value="l-b">London Boroughs</option>
                </optgroup>
                <optgroup label="Locals">
                    <option value="m25">M25</option>
                    <option value="in-cafe">Internet Cafes</option>
                </optgroup>
            </select>
        )
    }
    return (
        <input type="text" className="form-control" style={{ width: '30%', minWidth: '120px', display: 'inline-block' }}/>
    )
}

function getOperators(field) {
    if (field == 'location') {
        return [{ name: 'within', label: 'within' }, { name: 'na', label: 'n/a' }];
    } else if (field == 'hasMedia') {
        return [{ name: 'true', label: 'Yes' }, { name: 'false', label: 'no' }];
    } else if (field == 'keyword') {
        return [{ name: 'true', label: 'Contains' }, { name: 'false', label: 'Doesn\'t contain' },
            { name: 'equals', label: 'Equals' },{ name: 'savedList', label: 'Saved list' } ];
    } else if (field == 'time') {
        return [{ name: 'before', label: 'Before' }, { name: 'after', label: 'After' },
            { name: 'between', label: 'Between' }, { name: 'last', label: 'Last' }];
    } else return null;

}

const startQuery = {
    combinator: 'and',
    id: '111',
    rules: [
        {
            id: '222',
            field: 'location',
            value: 'within',
            operator: 'global'
        }
    ]
};

export default class QueryBuilderWindow extends Component {

    constructor(prop) {
        super(prop);
        this.state = { showModalView: false, showModalAlert: false };
        this.close = this.close.bind(this);
        this.open = this.open.bind(this);
         this.openAlert = this.openAlert.bind(this);
    }

    close() {
        this.setState({ showModalView: false });
        this.setState({ showModalAlert: false })
    }

    open() {
        this.setState({ showModalView: true });
    }
    openAlert() {
        this.setState({ showModalAlert: true });
    }
    render() {
        const {showModalView, showModalAlert} = this.state;
        return (

                    <Button bsStyle='default'  ><Glyphicon glyph="cog" /> </Button>
                       <Button bsStyle='info'  ><Glyphicon glyph="question-sign" /> </Button>

                            <Well  >
                                Create your search query
                                <QueryBuilder query={startQuery} fields={fields}
                                    onQueryChange={logQuery} getEditor={getEditor} getOperators={getOperators} controlClassnames= {CSSClass}/>
                            </Well>

                    <Button bsStyle='danger' onClick={this.openAlert}  ><Glyphicon glyph="alert" />  Create Alert </Button>
                    <Button bsStyle='primary' onClick={this.open} ><Glyphicon glyph="eye-open" /> Show in Data View  </Button>

                <Modal show={showModalView} onHide={this.close}>

                        <Title>Create Data View</Title>

                        <CreateDataViewDialog/>

                        <Button  bsStyle="success"onClick={this.close}>Confirm</Button>
                        <Button onClick={this.close}>Close</Button>

                </Modal>
                <Modal show={showModalAlert} onHide={this.close}>

                        <Title>Create Alert</Title>

                        <CreateAlertViewDialog/>

                        <Button  bsStyle="success"onClick={this.close}>Confirm</Button>
                        <Button onClick={this.close}>Close</Button>

                </Modal>

)
    }
}

function logQuery(query) {
    //console.log(query);
}<|endoftext|>


<commit_before>var React = require('react/addons');
var TestFunctions = require('./__test-functions__');
var { renderIntoDocument } = React.addons.TestUtils;
var rewire = require('rewire');
var d3 = require('d3');
var GetBarHeight = require('../../mixins/get-bar-height');
var GetBarY = require('../../mixins/get-bar-y');
var IsActive = require('../../mixins/is-active');
var SeriesMouseInteraction = require('../../mixins/series-mouse-interaction');

describe('BarSeries', () => {
  var Component = rewire('../bar-series');
  Component.__get__('VerticalBar', TestFunctions.getComponent('rect'));

  TestFunctions.isOfExpectedType(Component, 'g', 'bar-series');

  TestFunctions.hasExpectedMixins(Component, [
    GetBarHeight,
    GetBarY,
    IsActive,
    SeriesMouseInteraction
  ]);

  TestFunctions.hasExpectedDefaultProps(Component, {
    barSpacing: 2,
    className: '',
    data: [],
    dispatcher: d3.dispatch(),
    height: 0,
    id: '',
    interaction: 'mouseOver',
    scaleY: Function,
    style: {},
    tickWidth: 0,
    width: 0,
    zeroY: 0
  });

  TestFunctions.hasExpectedInitialState(Component, {
    activeDatum: {},
    activeIndex: -1
  });

  describe('given function getBarProps()', () => {
    var component = renderIntoDocument(<Component />);
    it('returns all bar props from a single function', () => {
      var barProps = component.getBarProps({
        scaleY: d3.scale.linear().domain([0, 100]).range([0, 100]),
        zeroY: 0
      }, {}, {value: 100}, 10);
      expect(barProps.hasOwnProperty('active')).toBeTruthy();
      expect(barProps.hasOwnProperty('height')).toBeTruthy();
      expect(barProps.hasOwnProperty('width')).toBeTruthy();
      expect(barProps.hasOwnProperty('x')).toBeTruthy();
      expect(barProps.hasOwnProperty('y')).toBeTruthy();
    });
  });

  describe('given function getBarX()', () => {
    var component = renderIntoDocument(<Component />);
    it('returns a floored x value for each child component', () => {
      expect(component.getBarX(10, 1)).toEqual(10);
      expect(component.getBarX(10, 5)).toEqual(50);
      expect(component.getBarX(10.7, 1)).toEqual(10);
    });
  });

  TestFunctions.hasExpectedPropsOnDOMNode(Component, {
    style: {fill: '#000'}
  });
});
<commit_msg>added missing mixin to bar series test<commit_after>var React = require('react/addons');
var TestFunctions = require('./__test-functions__');
var { renderIntoDocument } = React.addons.TestUtils;
var rewire = require('rewire');
var d3 = require('d3');
var GetBarHeight = require('../../mixins/get-bar-height');
var GetBarY = require('../../mixins/get-bar-y');
var IsActive = require('../../mixins/is-active');
var SeriesMouseInteraction = require('../../mixins/series-mouse-interaction');

describe('BarSeries', () => {
  var Component = rewire('../bar-series');
  Component.__get__('VerticalBar', TestFunctions.getComponent('rect'));

  TestFunctions.isOfExpectedType(Component, 'g', 'bar-series');

  TestFunctions.hasExpectedMixins(Component, [
    GetBarHeight,
    GetBarWidth,
    GetBarY,
    IsActive,
    SeriesMouseInteraction
  ]);

  TestFunctions.hasExpectedDefaultProps(Component, {
    barSpacing: 2,
    className: '',
    data: [],
    dispatcher: d3.dispatch(),
    height: 0,
    id: '',
    interaction: 'mouseOver',
    scaleY: Function,
    style: {},
    tickWidth: 0,
    width: 0,
    zeroY: 0
  });

  TestFunctions.hasExpectedInitialState(Component, {
    activeDatum: {},
    activeIndex: -1
  });

  describe('given function getBarProps()', () => {
    var component = renderIntoDocument(<Component />);
    it('returns all bar props from a single function', () => {
      var barProps = component.getBarProps({
        scaleY: d3.scale.linear().domain([0, 100]).range([0, 100]),
        zeroY: 0
      }, {}, {value: 100}, 10);
      expect(barProps.hasOwnProperty('active')).toBeTruthy();
      expect(barProps.hasOwnProperty('height')).toBeTruthy();
      expect(barProps.hasOwnProperty('width')).toBeTruthy();
      expect(barProps.hasOwnProperty('x')).toBeTruthy();
      expect(barProps.hasOwnProperty('y')).toBeTruthy();
    });
  });

  describe('given function getBarX()', () => {
    var component = renderIntoDocument(<Component />);
    it('returns a rounded-down x value for each child component', () => {
      expect(component.getBarX(10, 1)).toEqual(10);
      expect(component.getBarX(10, 5)).toEqual(50);
      expect(component.getBarX(10.7, 1)).toEqual(10);
    });
  });

  TestFunctions.hasExpectedPropsOnDOMNode(Component, {
    style: {fill: '#000'}
  });
});
<|endoftext|>


<commit_before>import React from 'react';
import { boolean, number, select } from '@storybook/addon-knobs/react';
import {
  DataGrid,
  Heading4,
  IconMenu,
  MenuItem,
  Link,
  StatusBullet,
  TextSmall,
  Tooltip,
  Button,
  ButtonGroup,
} from '../../index';

import { rows1, rows2 } from '../../static/data/datagrid';

const TooltippedStatusBullet = Tooltip(StatusBullet);

const handleRowSelectionChange = selectedRows => {
  console.log(`onSelectionChange - selected row indexes: ${selectedRows}`);
};

export default {
  title: 'DataGrids',

  parameters: {
    info: {
      propTablesExclude: [Button, ButtonGroup, Heading4, IconMenu, Link, MenuItem, TextSmall],
    },
  },
};

export const basic = () => (
  <DataGrid
    bordered={boolean('Bordered', false)}
    selectable={boolean('Selectable', true)}
    comparableId={1}
    onSelectionChange={handleRowSelectionChange}
    checkboxSize={select('Checkbox size', ['small', 'medium', 'large'], 'small')}
    processing={boolean('Processing', false)}
  >
    <DataGrid.HeaderRowOverlay
      numSelectedRowsLabel={numSelectedRows => (numSelectedRows === 1 ? 'sélectionné' : 'sélectionnés')}
    >
      <Button size="small" level="primary" label="Marks as paid" />
      <ButtonGroup segmented marginHorizontal={3}>
        <Button size="small" label="Book" />
        <Button size="small" label="Merge" />
      </ButtonGroup>
      <Button size="small" level="destructive" label="Delete" />
    </DataGrid.HeaderRowOverlay>

    <DataGrid.HeaderRow>
      <DataGrid.HeaderCell flex="min-width" />
      <DataGrid.HeaderCell onClick={() => console.log('onClick: column sort')} sorted="asc">
        Invoice
      </DataGrid.HeaderCell>
      <DataGrid.HeaderCell onClick={() => console.log('onClick: column sort')} align="right">
        Amount
      </DataGrid.HeaderCell>
      <DataGrid.HeaderCell flex="2" onClick={() => console.log('onClick: column sort')}>
        Customer
      </DataGrid.HeaderCell>
      <DataGrid.HeaderCell onClick={() => console.log('onClick: column sort')}>Due date</DataGrid.HeaderCell>
      <DataGrid.HeaderCell flex="min-width" />
    </DataGrid.HeaderRow>
    {rows1.map((row, index) => {
      return (
        <DataGrid.BodyRow key={index} onClick={event => console.log('onClick:', row.column5, event)}>
          <DataGrid.Cell align="center" flex="min-width">
            <TooltippedStatusBullet
              color={row.column1}
              tooltip={<TextSmall>Overdue</TextSmall>}
              tooltipColor={row.column1}
              tooltipSize="small"
              size="medium"
            />
          </DataGrid.Cell>
          <DataGrid.Cell>
            <Link href="#" inherit={false}>
              {row.column5}
            </Link>{' '}
          </DataGrid.Cell>
          <DataGrid.Cell align="right" strong>
            {' '}
            {`€ ${row.column3}`}
          </DataGrid.Cell>
          <DataGrid.Cell flex="2">{row.column2}</DataGrid.Cell>
          <DataGrid.Cell soft>{row.column4}</DataGrid.Cell>
          <DataGrid.Cell align="right" flex="min-width" preventOverflow={false}>
            <IconMenu position="top-right">
              <MenuItem label="Duplicate row" onClick={() => console.log('onClick: duplicate row')} />
              <MenuItem label="Inactive row" onClick={() => console.log('onClick: inactivate row')} />
              <MenuItem label="Remove row" onClick={() => console.log('onClick: remove row')} />
            </IconMenu>
          </DataGrid.Cell>
        </DataGrid.BodyRow>
      );
    })}
  </DataGrid>
);

export const withFooter = () => (
  <DataGrid
    bordered={boolean('Bordered', false)}
    selectable={boolean('Selectable', true)}
    comparableId={1}
    onSelectionChange={handleRowSelectionChange}
    processing={boolean('Processing', false)}
  >
    <DataGrid.HeaderRowOverlay>
      <Button size="small" level="primary" label="Marks as paid" />
      <ButtonGroup segmented marginHorizontal={3}>
        <Button size="small" label="Book" />
        <Button size="small" label="Merge" />
      </ButtonGroup>
      <Button size="small" level="destructive" label="Delete" />
    </DataGrid.HeaderRowOverlay>

    <DataGrid.HeaderRow>
      <DataGrid.HeaderCell flex="min-width" />
      <DataGrid.HeaderCell onClick={() => console.log('onClick: column sort')} sorted="asc">
        Invoice
      </DataGrid.HeaderCell>
      <DataGrid.HeaderCell onClick={() => console.log('onClick: column sort')} align="right">
        Amount
      </DataGrid.HeaderCell>
      <DataGrid.HeaderCell flex="2" onClick={() => console.log('onClick: column sort')}>
        Customer
      </DataGrid.HeaderCell>
      <DataGrid.HeaderCell onClick={() => console.log('onClick: column sort')}>Due date</DataGrid.HeaderCell>
      <DataGrid.HeaderCell flex="min-width" />
    </DataGrid.HeaderRow>
    {rows2.map((row, index) => {
      return (
        <DataGrid.BodyRow key={index} onClick={event => console.log('onClick:', row.column5, event)}>
          <DataGrid.Cell align="center" flex="min-width">
            <TooltippedStatusBullet
              color={row.column1}
              tooltip={<TextSmall>Overdue</TextSmall>}
              tooltipColor={row.column1}
              tooltipSize="small"
              size="medium"
            />
          </DataGrid.Cell>
          <DataGrid.Cell>
            <Link href="#" inherit={false}>
              {row.column5}
            </Link>{' '}
          </DataGrid.Cell>
          <DataGrid.Cell align="right" strong>
            {' '}
            {`€ ${row.column3}`}
          </DataGrid.Cell>
          <DataGrid.Cell flex="2">{row.column2}</DataGrid.Cell>
          <DataGrid.Cell soft>{row.column4}</DataGrid.Cell>
          <DataGrid.Cell align="right" flex="min-width" preventOverflow={false}>
            <IconMenu position="top-right">
              <MenuItem label="Duplicate row" onClick={() => console.log('onClick: duplicate row')} />
              <MenuItem label="Inactive row" onClick={() => console.log('onClick: inactivate row')} />
              <MenuItem label="Remove row" onClick={() => console.log('onClick: remove row')} />
            </IconMenu>
          </DataGrid.Cell>
        </DataGrid.BodyRow>
      );
    })}
    <DataGrid.FooterRow backgroundColor="neutral">
      <DataGrid.Cell align="right">{`${rows1.length} rows in total`}</DataGrid.Cell>
    </DataGrid.FooterRow>
  </DataGrid>
);

withFooter.story = {
  name: 'With footer',
};

export const withStickyColumns = () => (
  <DataGrid
    bordered={boolean('Bordered', false)}
    selectable={boolean('Selectable', true)}
    stickyFromLeft={number('Sticky from left', 3)}
    stickyFromRight={number('Sticky from right', 1)}
    comparableId={1}
    onSelectionChange={handleRowSelectionChange}
    processing={boolean('Processing', false)}
  >
    <DataGrid.HeaderRowOverlay>
      <Button size="small" level="primary" label="Marks as paid" />
      <ButtonGroup segmented marginHorizontal={3}>
        <Button size="small" label="Book" />
        <Button size="small" label="Merge" />
      </ButtonGroup>
      <Button size="small" level="destructive" label="Delete" />
    </DataGrid.HeaderRowOverlay>

    <DataGrid.HeaderRow>
      <DataGrid.HeaderCell flex="min-width" />
      <DataGrid.HeaderCell onClick={() => console.log('onClick: column sort')} sorted="asc">
        Invoice
      </DataGrid.HeaderCell>
      <DataGrid.HeaderCell onClick={() => console.log('onClick: column sort')} align="right">
        Amount
      </DataGrid.HeaderCell>
      <DataGrid.HeaderCell flex="2" onClick={() => console.log('onClick: column sort')}>
        Customer
      </DataGrid.HeaderCell>
      <DataGrid.HeaderCell onClick={() => console.log('onClick: column sort')}>Due date</DataGrid.HeaderCell>
      <DataGrid.HeaderCell flex="min-width" />
    </DataGrid.HeaderRow>
    {rows1.map((row, index) => {
      return (
        <DataGrid.BodyRow key={index} onClick={event => console.log('onClick:', row.column5, event)}>
          <DataGrid.Cell align="center" flex="min-width">
            <TooltippedStatusBullet
              color={row.column1}
              tooltip={<TextSmall>Overdue</TextSmall>}
              tooltipColor={row.column1}
              tooltipSize="small"
              size="medium"
            />
          </DataGrid.Cell>
          <DataGrid.Cell>
            <Link href="#" inherit={false}>
              {row.column5}
            </Link>{' '}
          </DataGrid.Cell>
          <DataGrid.Cell align="right" strong>
            {' '}
            {`€ ${row.column3}`}
          </DataGrid.Cell>
          <DataGrid.Cell flex="2">{row.column2}</DataGrid.Cell>
          <DataGrid.Cell soft>{row.column4}</DataGrid.Cell>
          <DataGrid.Cell align="right" flex="min-width" preventOverflow={false}>
            <IconMenu position="top-right">
              <MenuItem label="Duplicate row" onClick={() => console.log('onClick: duplicate row')} />
              <MenuItem label="Inactive row" onClick={() => console.log('onClick: inactivate row')} />
              <MenuItem label="Remove row" onClick={() => console.log('onClick: remove row')} />
            </IconMenu>
          </DataGrid.Cell>
        </DataGrid.BodyRow>
      );
    })}
  </DataGrid>
);

withStickyColumns.story = {
  name: 'With sticky columns',
};

export const advanced = () => (
  <DataGrid
    bordered={boolean('Bordered', false)}
    selectable={boolean('Selectable', true)}
    stickyFromLeft={number('Sticky from left', 3)}
    stickyFromRight={number('Sticky from right', 1)}
    comparableId={1}
    onSelectionChange={handleRowSelectionChange}
    processing={boolean('Processing', false)}
  >
    <DataGrid.HeaderRowOverlay>
      <Button size="small" level="primary" label="Marks as paid" />
      <ButtonGroup segmented marginHorizontal={3}>
        <Button size="small" label="Book" />
        <Button size="small" label="Merge" />
      </ButtonGroup>
      <Button size="small" level="destructive" label="Delete" />
    </DataGrid.HeaderRowOverlay>

    <DataGrid.HeaderRow>
      <DataGrid.HeaderCell flex="min-width" />
      <DataGrid.HeaderCell onClick={() => console.log('onClick: column sort')} sorted="asc">
        Invoice
      </DataGrid.HeaderCell>
      <DataGrid.HeaderCell onClick={() => console.log('onClick: column sort')} align="right">
        Amount
      </DataGrid.HeaderCell>
      <DataGrid.HeaderCell flex="2" onClick={() => console.log('onClick: column sort')}>
        Customer
      </DataGrid.HeaderCell>
      <DataGrid.HeaderCell onClick={() => console.log('onClick: column sort')}>Due date</DataGrid.HeaderCell>
      <DataGrid.HeaderCell flex="min-width" />
    </DataGrid.HeaderRow>
    {rows1.map((row, index) => {
      return (
        <DataGrid.BodyRow key={index} onClick={event => console.log('onClick:', row.column5, event)}>
          <DataGrid.Cell align="center" flex="min-width">
            <TooltippedStatusBullet
              color={row.column1}
              tooltip={<TextSmall>Overdue</TextSmall>}
              tooltipColor={row.column1}
              tooltipSize="small"
              size="medium"
            />
          </DataGrid.Cell>
          <DataGrid.Cell>
            <Link href="#" inherit={false}>
              {row.column5}
            </Link>{' '}
          </DataGrid.Cell>
          <DataGrid.Cell align="right" strong>
            {' '}
            {`€ ${row.column3}`}
          </DataGrid.Cell>
          <DataGrid.Cell flex="2">{row.column2}</DataGrid.Cell>
          <DataGrid.Cell soft>{row.column4}</DataGrid.Cell>
          <DataGrid.Cell align="right" flex="min-width" preventOverflow={false}>
            <IconMenu position="top-right">
              <MenuItem label="Duplicate row" onClick={() => console.log('onClick: duplicate row')} />
              <MenuItem label="Inactive row" onClick={() => console.log('onClick: inactivate row')} />
              <MenuItem label="Remove row" onClick={() => console.log('onClick: remove row')} />
            </IconMenu>
          </DataGrid.Cell>
        </DataGrid.BodyRow>
      );
    })}
    <DataGrid.FooterRow backgroundColor="neutral">
      <DataGrid.Cell flex="min-width" />
      <DataGrid.Cell align="right" soft>
        <Heading4>Total Excl Btw</Heading4>
      </DataGrid.Cell>
      <DataGrid.Cell align="right" strong>
        € 13460.52
      </DataGrid.Cell>
      <DataGrid.Cell flex="2" />
      <DataGrid.Cell />
      <DataGrid.Cell flex="min-width" />
    </DataGrid.FooterRow>

    <DataGrid.FooterRow backgroundColor="neutral">
      <DataGrid.Cell flex="min-width" />
      <DataGrid.Cell align="right" soft>
        <Heading4>+ VAT</Heading4>
      </DataGrid.Cell>
      <DataGrid.Cell align="right" strong>
        € 2826.71
      </DataGrid.Cell>
      <DataGrid.Cell flex="2" />
      <DataGrid.Cell />
      <DataGrid.Cell flex="min-width" />
    </DataGrid.FooterRow>

    <DataGrid.FooterRow backgroundColor="neutral">
      <DataGrid.Cell flex="min-width" />
      <DataGrid.Cell align="right" soft>
        <Heading4>Total Incl Btw</Heading4>
      </DataGrid.Cell>
      <DataGrid.Cell align="right" strong backgroundColor="white" border="around">
        € 16287.23
      </DataGrid.Cell>
      <DataGrid.Cell flex="2" />
      <DataGrid.Cell />
      <DataGrid.Cell flex="min-width" />
    </DataGrid.FooterRow>
  </DataGrid>
);
<commit_msg>Update stories<commit_after>import React from 'react';
import { boolean, number, select } from '@storybook/addon-knobs/react';
import {
  DataGrid,
  Heading4,
  IconMenu,
  MenuItem,
  Link,
  StatusBullet,
  TextSmall,
  Tooltip,
  Button,
  ButtonGroup,
} from '../../index';

import { rows1, rows2 } from '../../static/data/datagrid';

const TooltippedStatusBullet = Tooltip(StatusBullet);

const handleRowSelectionChange = selectedRows => {
  console.log(`onSelectionChange - selected row indexes: ${selectedRows}`);
};

export default {
  title: 'DataGrids',

  parameters: {
    info: {
      propTablesExclude: [Button, ButtonGroup, Heading4, IconMenu, Link, MenuItem, TextSmall],
    },
  },
};

export const basic = () => (
  <DataGrid
    bordered={boolean('Bordered', false)}
    selectable={boolean('Selectable', true)}
    comparableId={1}
    onSelectionChange={handleRowSelectionChange}
    checkboxSize={select('Checkbox size', ['small', 'medium', 'large'], 'small')}
    processing={boolean('Processing', false)}
  >
    <DataGrid.HeaderRowOverlay
      numSelectedRowsLabel={numSelectedRows => (numSelectedRows === 1 ? 'sélectionné' : 'sélectionnés')}
    >
      <Button size="small" level="primary" label="Marks as paid" />
      <ButtonGroup segmented marginHorizontal={3}>
        <Button size="small" label="Book" />
        <Button size="small" label="Merge" />
      </ButtonGroup>
      <Button size="small" level="destructive" label="Delete" />
    </DataGrid.HeaderRowOverlay>

    <DataGrid.HeaderRow>
      <DataGrid.HeaderCell flex="min-width" />
      <DataGrid.HeaderCell onClick={() => console.log('onClick: column sort')} sorted="asc">
        Invoice
      </DataGrid.HeaderCell>
      <DataGrid.HeaderCell onClick={() => console.log('onClick: column sort')} align="right">
        Amount
      </DataGrid.HeaderCell>
      <DataGrid.HeaderCell flex="5" onClick={() => console.log('onClick: column sort')}>
        Customer
      </DataGrid.HeaderCell>
      <DataGrid.HeaderCell onClick={() => console.log('onClick: column sort')}>Due date</DataGrid.HeaderCell>
      <DataGrid.HeaderCell flex="min-width" />
    </DataGrid.HeaderRow>
    {rows1.map((row, index) => {
      return (
        <DataGrid.BodyRow key={index} onClick={event => console.log('onClick:', row.column5, event)}>
          <DataGrid.Cell align="center" flex="min-width">
            <TooltippedStatusBullet
              color={row.column1}
              tooltip={<TextSmall>Overdue</TextSmall>}
              tooltipColor={row.column1}
              tooltipSize="small"
              size="medium"
            />
          </DataGrid.Cell>
          <DataGrid.Cell>
            <Link href="#" inherit={false}>
              {row.column5}
            </Link>{' '}
          </DataGrid.Cell>
          <DataGrid.Cell align="right" strong>
            {' '}
            {`€ ${row.column3}`}
          </DataGrid.Cell>
          <DataGrid.Cell flex="5">{row.column2}</DataGrid.Cell>
          <DataGrid.Cell soft>{row.column4}</DataGrid.Cell>
          <DataGrid.Cell align="right" flex="min-width" preventOverflow={false}>
            <IconMenu position="top-right">
              <MenuItem label="Duplicate row" onClick={() => console.log('onClick: duplicate row')} />
              <MenuItem label="Inactive row" onClick={() => console.log('onClick: inactivate row')} />
              <MenuItem label="Remove row" onClick={() => console.log('onClick: remove row')} />
            </IconMenu>
          </DataGrid.Cell>
        </DataGrid.BodyRow>
      );
    })}
  </DataGrid>
);

export const withFooter = () => (
  <DataGrid
    bordered={boolean('Bordered', false)}
    selectable={boolean('Selectable', true)}
    comparableId={1}
    onSelectionChange={handleRowSelectionChange}
    processing={boolean('Processing', false)}
  >
    <DataGrid.HeaderRowOverlay>
      <Button size="small" level="primary" label="Marks as paid" />
      <ButtonGroup segmented marginHorizontal={3}>
        <Button size="small" label="Book" />
        <Button size="small" label="Merge" />
      </ButtonGroup>
      <Button size="small" level="destructive" label="Delete" />
    </DataGrid.HeaderRowOverlay>

    <DataGrid.HeaderRow>
      <DataGrid.HeaderCell flex="min-width" />
      <DataGrid.HeaderCell onClick={() => console.log('onClick: column sort')} sorted="asc">
        Invoice
      </DataGrid.HeaderCell>
      <DataGrid.HeaderCell onClick={() => console.log('onClick: column sort')} align="right">
        Amount
      </DataGrid.HeaderCell>
      <DataGrid.HeaderCell flex="2" onClick={() => console.log('onClick: column sort')}>
        Customer
      </DataGrid.HeaderCell>
      <DataGrid.HeaderCell onClick={() => console.log('onClick: column sort')}>Due date</DataGrid.HeaderCell>
      <DataGrid.HeaderCell flex="min-width" />
    </DataGrid.HeaderRow>
    {rows2.map((row, index) => {
      return (
        <DataGrid.BodyRow key={index} onClick={event => console.log('onClick:', row.column5, event)}>
          <DataGrid.Cell align="center" flex="min-width">
            <TooltippedStatusBullet
              color={row.column1}
              tooltip={<TextSmall>Overdue</TextSmall>}
              tooltipColor={row.column1}
              tooltipSize="small"
              size="medium"
            />
          </DataGrid.Cell>
          <DataGrid.Cell>
            <Link href="#" inherit={false}>
              {row.column5}
            </Link>{' '}
          </DataGrid.Cell>
          <DataGrid.Cell align="right" strong>
            {' '}
            {`€ ${row.column3}`}
          </DataGrid.Cell>
          <DataGrid.Cell flex="2">{row.column2}</DataGrid.Cell>
          <DataGrid.Cell soft>{row.column4}</DataGrid.Cell>
          <DataGrid.Cell align="right" flex="min-width" preventOverflow={false}>
            <IconMenu position="top-right">
              <MenuItem label="Duplicate row" onClick={() => console.log('onClick: duplicate row')} />
              <MenuItem label="Inactive row" onClick={() => console.log('onClick: inactivate row')} />
              <MenuItem label="Remove row" onClick={() => console.log('onClick: remove row')} />
            </IconMenu>
          </DataGrid.Cell>
        </DataGrid.BodyRow>
      );
    })}
    <DataGrid.FooterRow backgroundColor="neutral">
      <DataGrid.Cell align="right">{`${rows1.length} rows in total`}</DataGrid.Cell>
    </DataGrid.FooterRow>
  </DataGrid>
);

withFooter.story = {
  name: 'With footer',
};

export const withStickyColumns = () => (
  <DataGrid
    bordered={boolean('Bordered', false)}
    selectable={boolean('Selectable', true)}
    stickyFromLeft={number('Sticky from left', 3)}
    stickyFromRight={number('Sticky from right', 1)}
    comparableId={1}
    onSelectionChange={handleRowSelectionChange}
    processing={boolean('Processing', false)}
  >
    <DataGrid.HeaderRowOverlay>
      <Button size="small" level="primary" label="Marks as paid" />
      <ButtonGroup segmented marginHorizontal={3}>
        <Button size="small" label="Book" />
        <Button size="small" label="Merge" />
      </ButtonGroup>
      <Button size="small" level="destructive" label="Delete" />
    </DataGrid.HeaderRowOverlay>

    <DataGrid.HeaderRow>
      <DataGrid.HeaderCell flex="min-width" />
      <DataGrid.HeaderCell onClick={() => console.log('onClick: column sort')} sorted="asc">
        Invoice
      </DataGrid.HeaderCell>
      <DataGrid.HeaderCell onClick={() => console.log('onClick: column sort')} align="right">
        Amount
      </DataGrid.HeaderCell>
      <DataGrid.HeaderCell flex="2" onClick={() => console.log('onClick: column sort')}>
        Customer
      </DataGrid.HeaderCell>
      <DataGrid.HeaderCell onClick={() => console.log('onClick: column sort')}>Due date</DataGrid.HeaderCell>
      <DataGrid.HeaderCell flex="min-width" />
    </DataGrid.HeaderRow>
    {rows1.map((row, index) => {
      return (
        <DataGrid.BodyRow key={index} onClick={event => console.log('onClick:', row.column5, event)}>
          <DataGrid.Cell align="center" flex="min-width">
            <TooltippedStatusBullet
              color={row.column1}
              tooltip={<TextSmall>Overdue</TextSmall>}
              tooltipColor={row.column1}
              tooltipSize="small"
              size="medium"
            />
          </DataGrid.Cell>
          <DataGrid.Cell>
            <Link href="#" inherit={false}>
              {row.column5}
            </Link>{' '}
          </DataGrid.Cell>
          <DataGrid.Cell align="right" strong>
            {' '}
            {`€ ${row.column3}`}
          </DataGrid.Cell>
          <DataGrid.Cell flex="2">{row.column2}</DataGrid.Cell>
          <DataGrid.Cell soft>{row.column4}</DataGrid.Cell>
          <DataGrid.Cell align="right" flex="min-width" preventOverflow={false}>
            <IconMenu position="top-right">
              <MenuItem label="Duplicate row" onClick={() => console.log('onClick: duplicate row')} />
              <MenuItem label="Inactive row" onClick={() => console.log('onClick: inactivate row')} />
              <MenuItem label="Remove row" onClick={() => console.log('onClick: remove row')} />
            </IconMenu>
          </DataGrid.Cell>
        </DataGrid.BodyRow>
      );
    })}
  </DataGrid>
);

withStickyColumns.story = {
  name: 'With sticky columns',
};

export const advanced = () => (
  <DataGrid
    bordered={boolean('Bordered', false)}
    selectable={boolean('Selectable', true)}
    stickyFromLeft={number('Sticky from left', 3)}
    stickyFromRight={number('Sticky from right', 1)}
    comparableId={1}
    onSelectionChange={handleRowSelectionChange}
    processing={boolean('Processing', false)}
  >
    <DataGrid.HeaderRowOverlay>
      <Button size="small" level="primary" label="Marks as paid" />
      <ButtonGroup segmented marginHorizontal={3}>
        <Button size="small" label="Book" />
        <Button size="small" label="Merge" />
      </ButtonGroup>
      <Button size="small" level="destructive" label="Delete" />
    </DataGrid.HeaderRowOverlay>

    <DataGrid.HeaderRow>
      <DataGrid.HeaderCell flex="min-width" />
      <DataGrid.HeaderCell onClick={() => console.log('onClick: column sort')} sorted="asc">
        Invoice
      </DataGrid.HeaderCell>
      <DataGrid.HeaderCell onClick={() => console.log('onClick: column sort')} align="right">
        Amount
      </DataGrid.HeaderCell>
      <DataGrid.HeaderCell flex="2" onClick={() => console.log('onClick: column sort')}>
        Customer
      </DataGrid.HeaderCell>
      <DataGrid.HeaderCell onClick={() => console.log('onClick: column sort')}>Due date</DataGrid.HeaderCell>
      <DataGrid.HeaderCell flex="min-width" />
    </DataGrid.HeaderRow>
    {rows1.map((row, index) => {
      return (
        <DataGrid.BodyRow key={index} onClick={event => console.log('onClick:', row.column5, event)}>
          <DataGrid.Cell align="center" flex="min-width">
            <TooltippedStatusBullet
              color={row.column1}
              tooltip={<TextSmall>Overdue</TextSmall>}
              tooltipColor={row.column1}
              tooltipSize="small"
              size="medium"
            />
          </DataGrid.Cell>
          <DataGrid.Cell>
            <Link href="#" inherit={false}>
              {row.column5}
            </Link>{' '}
          </DataGrid.Cell>
          <DataGrid.Cell align="right" strong>
            {' '}
            {`€ ${row.column3}`}
          </DataGrid.Cell>
          <DataGrid.Cell flex="2">{row.column2}</DataGrid.Cell>
          <DataGrid.Cell soft>{row.column4}</DataGrid.Cell>
          <DataGrid.Cell align="right" flex="min-width" preventOverflow={false}>
            <IconMenu position="top-right">
              <MenuItem label="Duplicate row" onClick={() => console.log('onClick: duplicate row')} />
              <MenuItem label="Inactive row" onClick={() => console.log('onClick: inactivate row')} />
              <MenuItem label="Remove row" onClick={() => console.log('onClick: remove row')} />
            </IconMenu>
          </DataGrid.Cell>
        </DataGrid.BodyRow>
      );
    })}
    <DataGrid.FooterRow backgroundColor="neutral">
      <DataGrid.Cell flex="min-width" />
      <DataGrid.Cell align="right" soft>
        <Heading4>Total Excl Btw</Heading4>
      </DataGrid.Cell>
      <DataGrid.Cell align="right" strong>
        € 13460.52
      </DataGrid.Cell>
      <DataGrid.Cell flex="2" />
      <DataGrid.Cell />
      <DataGrid.Cell flex="min-width" />
    </DataGrid.FooterRow>

    <DataGrid.FooterRow backgroundColor="neutral">
      <DataGrid.Cell flex="min-width" />
      <DataGrid.Cell align="right" soft>
        <Heading4>+ VAT</Heading4>
      </DataGrid.Cell>
      <DataGrid.Cell align="right" strong>
        € 2826.71
      </DataGrid.Cell>
      <DataGrid.Cell flex="2" />
      <DataGrid.Cell />
      <DataGrid.Cell flex="min-width" />
    </DataGrid.FooterRow>

    <DataGrid.FooterRow backgroundColor="neutral">
      <DataGrid.Cell flex="min-width" />
      <DataGrid.Cell align="right" soft>
        <Heading4>Total Incl Btw</Heading4>
      </DataGrid.Cell>
      <DataGrid.Cell align="right" strong backgroundColor="white" border="around">
        € 16287.23
      </DataGrid.Cell>
      <DataGrid.Cell flex="2" />
      <DataGrid.Cell />
      <DataGrid.Cell flex="min-width" />
    </DataGrid.FooterRow>
  </DataGrid>
);
<|endoftext|>