<commit_before>function onPlayerStateChange(event)
{
    if (playerMode != 'admin') {
        return this;
    }

	var params = new Object();
	params.status = event.data;

	if (event.data != 0) {
		params.currentTime = player.getCurrentTime();
		livePlayer.sendParameters(params);
	} else {
		livePlayer.seekNextVideo(params);
	}
}

var livePlayer;
var connection;
var playlistId;
var videoId;

LivePlayer = function()
{
	this.initialize = function(currentPlaylistId)
	{
		playlistId = currentPlaylistId;
		this.getPlaylistScores(currentPlaylistId);

		$('#up-vote a').unbind('click');
		$('#up-vote a').click(function(event) {
			event.preventDefault();
			var playlistId = this.getCurrentPlaylistId();

			$.post(voteUrl, {
				playlist: playlistId,
				vote: 'up',
				current: 1
			}, function(response) {
				this.playlistScoresUpdate(response);
			}.bind(this));
		}.bind(this));

		$('#down-vote a').unbind('click');
		$('#down-vote a').click(function(event) {
			event.preventDefault();
			var playlistId = this.getCurrentPlaylistId();

			$.post(voteUrl, {
				playlist: playlistId,
				vote: 'down',
				current: 1
			}, function(response) {
				this.playlistScoresUpdate(response);
			}.bind(this));
		}.bind(this));
	},

	this.synchronizePlayerState = function(params)
	{
		if (params.action == 'update_scores') {
			var scores = JSON.parse(params.scores);
			this.updatePlaylistScores(scores);
		}

		if (playerMode == 'admin') {
            return this;
        }

        switch(params.status) {
            case 1:
                //this.checkCurrentVideoId(params);

                player.seekTo(params.currentTime);
                player.playVideo();

            break;

            case 2:
                //this.checkCurrentVideoId(params);

                player.seekTo(params.currentTime);
                player.pauseVideo();

            break;

            case 0:
                player.loadVideoById({
                    videoId: params.videoId
                });

                this.initialize(params.playlistId);

            break;
        }
	},

	this.getCurrentPlaylistId = function()
	{
		return playlistId;
	},

	this.getCurrentVideoId = function()
	{
		return videoId;
	},

	this.checkCurrentVideoId = function(params)
	{
		var videoId = this.getCurrentVideoId();
		if (videoId != params.currentVideo) {
			player.loadVideoById({
				videoId: params.currentVideo
			});
		}
	},

	this.seekNextVideo = function(params)
	{
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: nextVideoUrl,
            data: { 'volume' : player.getVolume() }
        }).done(function(data) {
            player.loadVideoById({
                videoId: data.videoId
            });

            player.setVolume(data.videoVolume);

            params.playlistId = data.playlistId;
            params.videoId = data.videoId;

            this.sendParameters(params);

            this.initialize(data.playlistId);
        }.bind(this));
	},

	this.sendParameters = function(params)
	{
		json = JSON.stringify(params);
		connection.send(json);
	},

	this.getPlaylistScores = function(playlistId)
	{
		$.get(scoreUrl, {
			playlist: playlistId
        }, function(response) {
			scores = JSON.parse(response);
			this.updatePlaylistScores(scores);
		}.bind(this));
	},

	this.updatePlaylistScores = function(scores)
	{
		$('#up-score').text('(' + scores.upVotes + ')');
		$('#down-score').text('(' + scores.downVotes + ')');
		$('#video-score').text('Score : ' + scores.votesRatio);

		if (scores.votesRatio <= -2 && playerMode == 'admin') {
			var params = new Object();
			params.status = 0;

			livePlayer.seekNextVideo(params);
		}
	},

	this.playlistScoresUpdate = function(data)
	{
		scores = JSON.parse(data);
		this.updatePlaylistScores(scores);

		var params = new Object();
		params.action	= 'update_scores';
		params.scores	= data;

		this.sendParameters(params);
	},

    this.getReplaceForm = function()
    {
        $('#replace-video-modal').on('show', function () {
            $('.loader').show();
            $('#replace-video-modal .modal-content').html('');

            $.ajax({
                type: 'GET',
                dataType: 'html',
                url: replaceUrl
            }).done(function(html) {
                $('#replace-video-modal .modal-content').html(html);
                $('.loader').hide();
            });
        });
    }
};
<commit_msg>Live - Synchronisation du volume à la fin de chaque vidéo (issue #61)<commit_after>function onPlayerStateChange(event)
{
    if (playerMode != 'admin') {
        return this;
    }

	var params = new Object();
	params.status = event.data;

	if (event.data != 0) {
		params.currentTime = player.getCurrentTime();
		livePlayer.sendParameters(params);
	} else {
		livePlayer.seekNextVideo(params);
	}
}

var livePlayer;
var connection;
var playlistId;
var videoId;

LivePlayer = function()
{
	this.initialize = function(currentPlaylistId)
	{
		playlistId = currentPlaylistId;
		this.getPlaylistScores(currentPlaylistId);

		$('#up-vote a').unbind('click');
		$('#up-vote a').click(function(event) {
			event.preventDefault();
			var playlistId = this.getCurrentPlaylistId();

			$.post(voteUrl, {
				playlist: playlistId,
				vote: 'up',
				current: 1
			}, function(response) {
				this.playlistScoresUpdate(response);
			}.bind(this));
		}.bind(this));

		$('#down-vote a').unbind('click');
		$('#down-vote a').click(function(event) {
			event.preventDefault();
			var playlistId = this.getCurrentPlaylistId();

			$.post(voteUrl, {
				playlist: playlistId,
				vote: 'down',
				current: 1
			}, function(response) {
				this.playlistScoresUpdate(response);
			}.bind(this));
		}.bind(this));
	},

	this.synchronizePlayerState = function(params)
	{
		if (params.action == 'update_scores') {
			var scores = JSON.parse(params.scores);
			this.updatePlaylistScores(scores);
		}

		if (playerMode == 'admin') {
            return this;
        }

        switch(params.status) {
            case 1:
                player.seekTo(params.currentTime);
                player.playVideo();

            break;

            case 2:
                player.seekTo(params.currentTime);
                player.pauseVideo();

            break;

            case 0:
                player.loadVideoById({
                    videoId: params.videoId,
                    volume: params.videoVolume
                });

                this.initialize(params.playlistId);

            break;
        }
	},

	this.getCurrentPlaylistId = function()
	{
		return playlistId;
	},

	this.getCurrentVideoId = function()
	{
		return videoId;
	},

	this.checkCurrentVideoId = function(params)
	{
		var videoId = this.getCurrentVideoId();
		if (videoId != params.currentVideo) {
			player.loadVideoById({
				videoId: params.currentVideo
			});
		}
	},

	this.seekNextVideo = function(params)
	{
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: nextVideoUrl,
            data: { 'volume' : player.getVolume() }
        }).done(function(data) {
            player.loadVideoById({
                videoId: data.videoId
            });

            params.playlistId = data.playlistId;
            params.videoId = data.videoId;

            player.setVolume(data.videoVolume);
            params.videoVolume = data.videoVolume;

            this.sendParameters(params);

            this.initialize(data.playlistId);
        }.bind(this));
	},

	this.sendParameters = function(params)
	{
		json = JSON.stringify(params);
		connection.send(json);
	},

	this.getPlaylistScores = function(playlistId)
	{
		$.get(scoreUrl, {
			playlist: playlistId
        }, function(response) {
			scores = JSON.parse(response);
			this.updatePlaylistScores(scores);
		}.bind(this));
	},

	this.updatePlaylistScores = function(scores)
	{
		$('#up-score').text('(' + scores.upVotes + ')');
		$('#down-score').text('(' + scores.downVotes + ')');
		$('#video-score').text('Score : ' + scores.votesRatio);

		if (scores.votesRatio <= -2 && playerMode == 'admin') {
			var params = new Object();
			params.status = 0;

			livePlayer.seekNextVideo(params);
		}
	},

	this.playlistScoresUpdate = function(data)
	{
		scores = JSON.parse(data);
		this.updatePlaylistScores(scores);

		var params = new Object();
		params.action	= 'update_scores';
		params.scores	= data;

		this.sendParameters(params);
	},

    this.getReplaceForm = function()
    {
        $('#replace-video-modal').on('show', function () {
            $('.loader').show();
            $('#replace-video-modal .modal-content').html('');

            $.ajax({
                type: 'GET',
                dataType: 'html',
                url: replaceUrl
            }).done(function(html) {
                $('#replace-video-modal .modal-content').html(html);
                $('.loader').hide();
            });
        });
    }
};
<|endoftext|>


<commit_before>// Copyright 2015 Yahoo! Inc.
// Copyrights licensed under the Mit License. See the accompanying LICENSE file for terms.

var Base = require('../base');

var Version = require('./version');
var Device = require('./device');
var Document = require('./document');
var ViewPort = require('./viewPort');
var Screenshot = require('./screenshot');
var Dom = require('./dom');

/**
 * @class Structure
 * @extends Base
 * @module Configuration
 * @submodule Structure
 *
 * @property {Version} _version
 * @property {Device} _device
 * @property {Document} _document
 * @property {ViewPort} _viewPort
 * @property {Screenshot} _screenshot
 * @property {Dom} _dom
 */
var Structure = Base.extend(

	/**
	 * Structure constructor
	 *
	 * @param {object} options
	 * @param {object|Version} options.version
	 * @param {object|Device} options.device
	 * @param {object|Document} options.document
	 * @param {object|ViewPort} options.viewPort
	 * @param {object|Screenshot} options.screenshot
	 * @param {object|Dom} options.dom
	 * @constructor
	 */
	function (options) {
		this.__super();

		this.setVersion(options.version);
		this.setDevice(options.device);
		this.setDocument(options.document);
		this.setViewPort(options.viewPort);
		this.setScreenshot(options.screenshot);
		this.setDom(options.dom);
	},

	{
		/**
		 * Gets the version of the structure format
		 *
		 * @method getVersion
		 * @return {Version}
		 */
		getVersion: function () {
			return this._version;
		},

		/**
		 * Sets the version of the structure format
		 *
		 * @method setVersion
		 * @param {object|Version} value
		 */
		setVersion: function (value) {
			this._version = this._parseObject(value, Version, 'version');
		},

		/**
		 * Gets the device from where the data was recorded
		 *
		 * @method getDevice
		 * @return {Device}
		 */
		getDevice: function () {
			return this._device;
		},

		/**
		 * Sets the device from where the data was recorded
		 *
		 * @method setDevice
		 * @param {object|Device} value
		 */
		setDevice: function (value) {
			this._device = this._parseObject(value, Device, 'device');
		},

		/**
		 * Gets the document
		 *
		 * @method getDocument
		 * @return {Document}
		 */
		getDocument: function () {
			return this._document;
		},

		/**
		 * Sets the document
		 *
		 * @method setDocument
		 * @param {object|Document} value
		 */
		setDocument: function (value) {
			this._document = this._parseObject(value, Document, 'document');
		},

		/**
		 * Gets the view-port
		 *
		 * @method getViewPort
		 * @return {ViewPort}
		 */
		getViewPort: function () {
			return this._viewPort;
		},

		/**
		 * Sets the view-port
		 *
		 * @method setViewPort
		 * @param {object|ViewPort} value
		 */
		setViewPort: function (value) {
			this._viewPort = this._parseObject(value, ViewPort, 'view-port');
		},

		/**
		 * Gets the screenshot information
		 *
		 * @method getScreenshot
		 * @return {Screenshot}
		 */
		getScreenshot: function () {
			return this._screenshot;
		},

		/**
		 * Sets the screenshot information
		 *
		 * @method setScreenshot
		 * @param {object|Screenshot} value
		 */
		setScreenshot: function (value) {
			this._screenshot = this._parseObject(value, Screenshot, 'screenshot');
		},

		/**
		 * Gets the DOM
		 *
		 * @method getDom
		 * @return {Dom}
		 */
		getDom: function () {
			return this._dom;
		},

		/**
		 * Sets the DOM
		 *
		 * @method setDom
		 * @param {object|Dom} value
		 */
		setDom: function (value) {
			this._dom = this._parseObject(value, Dom, 'DOM');
		}
	},

	{
		/**
		 * @property TYPE
		 * @type {string}
		 * @static
		 */
		TYPE: 'CONFIGURATION_STRUCTURE'
	}
);
<commit_msg>Fix incorrect type description<commit_after>// Copyright 2015 Yahoo! Inc.
// Copyrights licensed under the Mit License. See the accompanying LICENSE file for terms.

var Base = require('../base');

var Version = require('./version');
var Device = require('./device');
var Document = require('./document');
var ViewPort = require('./viewPort');
var Screenshot = require('./screenshot');
var DomElement = require('./dom');

/**
 * @class Structure
 * @extends Base
 * @module Configuration
 * @submodule Structure
 *
 * @property {Version} _version
 * @property {Device} _device
 * @property {Document} _document
 * @property {ViewPort} _viewPort
 * @property {Screenshot} _screenshot
 * @property {DomElement} _dom
 */
var Structure = Base.extend(

	/**
	 * Structure constructor
	 *
	 * @param {object} options
	 * @param {object|Version} options.version
	 * @param {object|Device} options.device
	 * @param {object|Document} options.document
	 * @param {object|ViewPort} options.viewPort
	 * @param {object|Screenshot} options.screenshot
	 * @param {object|DomElement} options.dom
	 * @constructor
	 */
	function (options) {
		this.__super();

		this.setVersion(options.version);
		this.setDevice(options.device);
		this.setDocument(options.document);
		this.setViewPort(options.viewPort);
		this.setScreenshot(options.screenshot);
		this.setDom(options.dom);
	},

	{
		/**
		 * Gets the version of the structure format
		 *
		 * @method getVersion
		 * @return {Version}
		 */
		getVersion: function () {
			return this._version;
		},

		/**
		 * Sets the version of the structure format
		 *
		 * @method setVersion
		 * @param {object|Version} value
		 */
		setVersion: function (value) {
			this._version = this._parseObject(value, Version, 'version');
		},

		/**
		 * Gets the device from where the data was recorded
		 *
		 * @method getDevice
		 * @return {Device}
		 */
		getDevice: function () {
			return this._device;
		},

		/**
		 * Sets the device from where the data was recorded
		 *
		 * @method setDevice
		 * @param {object|Device} value
		 */
		setDevice: function (value) {
			this._device = this._parseObject(value, Device, 'device');
		},

		/**
		 * Gets the document
		 *
		 * @method getDocument
		 * @return {Document}
		 */
		getDocument: function () {
			return this._document;
		},

		/**
		 * Sets the document
		 *
		 * @method setDocument
		 * @param {object|Document} value
		 */
		setDocument: function (value) {
			this._document = this._parseObject(value, Document, 'document');
		},

		/**
		 * Gets the view-port
		 *
		 * @method getViewPort
		 * @return {ViewPort}
		 */
		getViewPort: function () {
			return this._viewPort;
		},

		/**
		 * Sets the view-port
		 *
		 * @method setViewPort
		 * @param {object|ViewPort} value
		 */
		setViewPort: function (value) {
			this._viewPort = this._parseObject(value, ViewPort, 'view-port');
		},

		/**
		 * Gets the screenshot information
		 *
		 * @method getScreenshot
		 * @return {Screenshot}
		 */
		getScreenshot: function () {
			return this._screenshot;
		},

		/**
		 * Sets the screenshot information
		 *
		 * @method setScreenshot
		 * @param {object|Screenshot} value
		 */
		setScreenshot: function (value) {
			this._screenshot = this._parseObject(value, Screenshot, 'screenshot');
		},

		/**
		 * Gets the DOM
		 *
		 * @method getDom
		 * @return {DomElement}
		 */
		getDom: function () {
			return this._dom;
		},

		/**
		 * Sets the DOM
		 *
		 * @method setDom
		 * @param {object|DomElement} value
		 */
		setDom: function (value) {
			this._dom = this._parseObject(value, DomElement, 'DOM');
		}
	},

	{
		/**
		 * @property TYPE
		 * @type {string}
		 * @static
		 */
		TYPE: 'CONFIGURATION_STRUCTURE'
	}
);
<|endoftext|>


<commit_before>import React from 'react';
import * as activityFns from './activityfns.js';
import ActivityDay from './activityday.js';
import '../../styles/activities.css';
import * as DB from '../../constants/database.js';
import app from '../Firebase';

const db = app.firestore();

/**
 * Gets the list of activities from the server.
 *
 * @param {string} tripId The trip ID.
 * @return {ActivityInfo[]} The list of trip activities.
 */
export async function getActivityList(tripId) {
    let tripActivities = [];

    return db.collection(DB.COLLECTION_TRIPS).doc(tripId)
    .collection(DB.COLLECTION_ACTIVITIES).get()
    .then(querySnapshot => {
      querySnapshot.forEach(doc => {
        console.log(doc.data());
        let data = doc.data();
        data['id'] = doc.id;
        data['tripId'] = tripId;

        // TODO: if start date != end date, split into 2 days. (#37)

      // Eliminate nanoseconds, convert to milliseconds.
      data[DB.ACTIVITIES_START_TIME] =
        data[DB.ACTIVITIES_START_TIME]['seconds'] * 1000;
      data[DB.ACTIVITIES_END_TIME] =
        data[DB.ACTIVITIES_END_TIME]['seconds'] * 1000;

      tripActivities.push(data);
    });
    return tripActivities;
  });
}

/**
 * React component for the list of activities.
 *
 * @param {Object} props ReactJS props.
 * @param {string} props.tripId The trip's ID.
 */
class ActivityList extends React.Component {
  /** @override */
  constructor(props) {
    super(props);
    this.state = { days : [] };
  }

  /**
   * @override
   *
   * Get sorted list of activities from the database.
   *
   * This function only queries the database if `this.state` is defined.
   * `this.state` gains an entry with key `days` with the list of activities
   * sorted by date.
   *
   * This function also expects `this.props.tripId` to exist.
   */
  async componentDidMount() {
    if (this.state === null || this.props.tripId === null) { return; }
    let tripActivities = await getActivityList(this.props.tripId);
    if (tripActivities === null) {
      this.setState({days: null});
      return;
    }
    this.setState({days: activityFns.sortByDate(tripActivities)});
    console.log(this.state.days);
  }

  /** @override */
  render() {
    if (this.state === null) { return (

); }
    if (this.state.days === null) {
      return (
An error has occurred :(
 );
    } else if (this.state.days.length === 0) {
      return (
Plan your trip here!
);
    }
    return (

        {this.state.days.map((item, index) => (
          <ActivityDay date={item[0]} activities={item[1]} key={index}/>
        ))}

    );
  }
}

export default ActivityList;
<commit_msg>Remove console logs<commit_after>import React from 'react';
import * as activityFns from './activityfns.js';
import ActivityDay from './activityday.js';
import '../../styles/activities.css';
import * as DB from '../../constants/database.js';
import app from '../Firebase';

const db = app.firestore();

/**
 * Gets the list of activities from the server.
 *
 * @param {string} tripId The trip ID.
 * @return {ActivityInfo[]} The list of trip activities.
 */
export async function getActivityList(tripId) {
    let tripActivities = [];

    return db.collection(DB.COLLECTION_TRIPS).doc(tripId)
    .collection(DB.COLLECTION_ACTIVITIES).get()
    .then(querySnapshot => {
      querySnapshot.forEach(doc => {
        let data = doc.data();
        data['id'] = doc.id;
        data['tripId'] = tripId;

        // TODO: if start date != end date, split into 2 days. (#37)

      // Eliminate nanoseconds, convert to milliseconds.
      data[DB.ACTIVITIES_START_TIME] =
        data[DB.ACTIVITIES_START_TIME]['seconds'] * 1000;
      data[DB.ACTIVITIES_END_TIME] =
        data[DB.ACTIVITIES_END_TIME]['seconds'] * 1000;

      tripActivities.push(data);
    });
    return tripActivities;
  });
}

/**
 * React component for the list of activities.
 *
 * @param {Object} props ReactJS props.
 * @param {string} props.tripId The trip's ID.
 */
class ActivityList extends React.Component {
  /** @override */
  constructor(props) {
    super(props);
    this.state = { days : [] };
  }

  /**
   * @override
   *
   * Get sorted list of activities from the database.
   *
   * This function only queries the database if `this.state` is defined.
   * `this.state` gains an entry with key `days` with the list of activities
   * sorted by date.
   *
   * This function also expects `this.props.tripId` to exist.
   */
  async componentDidMount() {
    if (this.state === null || this.props.tripId === null) { return; }
    let tripActivities = await getActivityList(this.props.tripId);
    if (tripActivities === null) {
      this.setState({days: null});
      return;
    }
    this.setState({days: activityFns.sortByDate(tripActivities)});
  }

  /** @override */
  render() {
    if (this.state === null) { return (

); }
    if (this.state.days === null) {
      return (
An error has occurred :(
 );
    } else if (this.state.days.length === 0) {
      return (
Plan your trip here!
);
    }
    return (

        {this.state.days.map((item, index) => (
          <ActivityDay date={item[0]} activities={item[1]} key={index}/>
        ))}

    );
  }
}

export default ActivityList;
<|endoftext|>


<commit_before>import React from "react";
import { ArgsTable, Primary } from "@storybook/addon-docs";
import avatarImagePath from "@hig/storybook/storybook-support/fixtures/avatar/chris-reynolds.png";

import Avatar from "../index";
import { sizes } from "../sizes";

import Readme from "../../README.md";

export default {
  title: "Components/Avatar",
  component: Avatar,
  argTypes: {
    size: {
      options: [
        sizes.SMALL_16,
        sizes.MEDIUM_24,
        sizes.MEDIUM_32,
        sizes.LARGE_48,
        sizes.XLARGE_64,
      ],
      control: { type: "select" },
    },
  },
  parameters: {
    docs: {
      page: () => (
        <>
          <Primary />
          <Readme />
          <ArgsTable />
        </>
      ),
    },
  },
};

const Template = (args) => <Avatar {...args} />;

export const Text = Template.bind({});

Text.args = {
  name: "Peter Parker",
  size: sizes.LARGE_48,
};

export const Image = Template.bind({});

Image.args = {
  image: avatarImagePath,
  name: "Bruce Wayne",
  size: sizes.LARGE_48,
};
<commit_msg>feat: use latest theme-data<commit_after>import React from "react";
import { ArgsTable, Primary } from "@storybook/addon-docs";
import avatarImagePath from "@hig/storybook/storybook-support/fixtures/avatar/chris-reynolds.png";

import Avatar from "../index";
import { sizes } from "../sizes";

import Readme from "../../README.md";

export default {
  title: "Components/Avatar",
  component: Avatar,
  argTypes: {
    size: {
      options: [
        sizes.SMALL_16,
        sizes.MEDIUM_24,
        sizes.MEDIUM_32,
        sizes.LARGE_48,
        sizes.XLARGE_64,
      ],
      control: "select",
    },
  },
  parameters: {
    docs: {
      page: () => (
        <>
          <Primary />
          <Readme />
          <ArgsTable />
        </>
      ),
    },
  },
};

const Template = (args) => <Avatar {...args} />;

export const Text = Template.bind({});

Text.args = {
  name: "Peter Parker",
  size: sizes.LARGE_48,
};

export const Image = Template.bind({});

Image.args = {
  image: avatarImagePath,
  name: "Bruce Wayne",
  size: sizes.LARGE_48,
};
<|endoftext|>


<commit_before>import { equal, deepEqual, doesNotThrow, throws } from 'assert';
import html from '../lib/html';
import createTree from '../lib/tree/create';
import validateMemory from './util/validateMemory';

describe('HTML (Tagged template)', function() {
  afterEach(() => validateMemory());

  it('will return null when passed a falsy value', () => {
    equal(html(), null);
    equal(html(null), null);
    equal(html(undefined), null);
    equal(html(0), null);
    equal(html(NaN), null);
    equal(html(false), null);
  });

  it('will support running as a standalone function', () => {
    equal(html('
').nodeName, 'div');
  });

  it('will interpolate a single string value in an attribute', function() {
    const foo = 'foo';
    const span = html`<span class="${foo}" />`;

    equal(span.attributes.class, 'foo');
  });

  it('will interpolate multiple string values in an attribute', function() {
    const foo = 'foo';
    const bar = 'bar';

    const multipleValues = html`<span class="${foo} ${bar}" />`;

    equal(multipleValues.attributes.class, 'foo bar');
  });

  it('will interpolate value-less attributes', function() {
    const checked = 'checked';
    const input = html`<input type="checkbox" ${checked}>`;

    equal(input.attributes.checked, 'checked');
  });

  it('will interpolate multiple type values in an attribute', function() {
    const foo = 'foo';
    const bar = {};

    const multipleValues = html`<span class="${foo} ${bar}" />`;

    equal(multipleValues.attributes.class, 'foo [object Object]');
  });

  it('will interpolate attribute values with text', () => {
    const icon = 'some-icon';
    const vTree = html`<i class="${icon} icon" />`

    deepEqual(vTree, {
      rawNodeName: 'i',
      nodeName: 'i',
      nodeValue: '',
      nodeType: 1,
      key: '',
      childNodes: [],
      attributes: {
        class: 'some-icon icon'
      },
    });
  });

  it('will flatten nested fragments', () => {
    const array = [1];
    const vTree = html`

        ${array.map(i => html`

Some label

          ${i}
        `)}

    `;

    deepEqual(vTree, {
      rawNodeName: 'div',
      nodeName: "div",
      nodeValue: "",
      nodeType: 1,
      key: "",
      childNodes: [{
        rawNodeName: "#text",
        nodeName: "#text",
        nodeValue: "\n        ",
        nodeType: 3,
        key: "",
        childNodes: [],
        attributes: {},
      }, {
        rawNodeName: "p",
        nodeName: "p",
        nodeValue: "",
        nodeType: 1,
        key: "",
        childNodes: [{
          rawNodeName: "#text",
          nodeName: "#text",
          nodeValue: "Some label",
          nodeType: 3,
          key: "",
          childNodes: [],
          attributes: {},
        }],
        attributes: {},
      }, {
        rawNodeName: "#text",
        nodeName: "#text",
        nodeValue: "\n          ",
        nodeType: 3,
        key: "",
        childNodes: [],
        attributes: {},
      }, {
        rawNodeName: "span",
        nodeName: "span",
        nodeValue: "",
        nodeType: 1,
        key: "",
        childNodes: [{
          rawNodeName: "#text",
          nodeName: "#text",
          nodeValue: "1",
          nodeType: 3,
          key: "",
          childNodes: [],
          attributes: {},
        }],
        attributes: {},
      }, {
        rawNodeName: "#text",
        nodeName: "#text",
        nodeValue: "\n      ",
        nodeType: 3,
        key: "",
        childNodes: [],
        attributes: {},
      }],
      attributes: {},
    });
  });

  it('will return a fragment with multiple top level elements w/o values', () => {
    const vTree = html`<span class="has-class" /><span />`;

    deepEqual(vTree, {
      rawNodeName: '#document-fragment',
      nodeName: '#document-fragment',
      nodeValue: '',
      nodeType: 11,
      key: '',
      childNodes: [{
        rawNodeName: 'span',
        nodeName: 'span',
        nodeValue: '',
        nodeType: 1,
        key: '',
        childNodes: [],
        attributes: {
          class: 'has-class',
        },
      }, {
        rawNodeName: 'span',
        nodeName: 'span',
        nodeValue: '',
        nodeType: 1,
        key: '',
        childNodes: [],
        attributes: {},
      }],
      attributes: {},
    });
  });

  it('will return a fragment with multiple top level elements w/ values', () => {
    const className = 'has-class';
    const vTree = html`<span class="${className}" /><span />`;

    deepEqual(vTree, {
      rawNodeName: '#document-fragment',
      nodeName: '#document-fragment',
      nodeValue: '',
      nodeType: 11,
      key: '',
      childNodes: [{
        rawNodeName: 'span',
        nodeName: 'span',
        nodeValue: '',
        nodeType: 1,
        key: '',
        childNodes: [],
        attributes: {
          class: 'has-class',
        },
      }, {
        rawNodeName: 'span',
        nodeName: 'span',
        nodeValue: '',
        nodeType: 1,
        key: '',
        childNodes: [],
        attributes: {},
      }],
      attributes: {},
    });
  });

  it('will support aligning attributes on new lines', function() {
    const multipleValues = html`

    `;

    equal(multipleValues.attributes.class.trim(), 'foo\n        bar');
  });

  it('will support empty string attributes', () => {
    const span = html`<span href="" />`;

    deepEqual(span, {
      rawNodeName: 'span',
      nodeName: 'span',
      nodeType: 1,
      nodeValue: '',
      key: '',
      attributes: { href: '' },
      childNodes: [],
    });
  });

  it('will interpolate a string child', function() {
    const span = html`<span>${'foo'}</span>`;

    deepEqual(span.childNodes[0], {
      rawNodeName: '#text',
      nodeName: '#text',
      nodeType: 3,
      nodeValue: 'foo',
      key: '',
      attributes: {},
      childNodes: [],
    });
  });

  it('will interpolate a string child with html entities', function() {
    const span = html`<span>${'∞'}</span>`;

    deepEqual(span.childNodes[0], {
      rawNodeName: '#text',
      nodeName: '#text',
      nodeType: 3,
      nodeValue: '∞',
      key: '',
      attributes: {},
      childNodes: [],
    });
  });

  it('will interpolate a VTree child', function() {
    const span = html`<span>${createTree('#text', 'foo')}</span>`;

    deepEqual(span.childNodes[0], {
      rawNodeName: '#text',
      nodeName: '#text',
      nodeType: 3,
      nodeValue: 'foo',
      key: '',
      attributes: {},
      childNodes: [],
    });
  });

  it('will interpolate a DOM Node', function() {
    const span = html`<span>${document.createTextNode('foo')}</span>`;

    deepEqual(span.childNodes[0], {
      rawNodeName: '#text',
      nodeName: '#text',
      nodeType: 3,
      nodeValue: 'foo',
      key: '',
      attributes: {},
      childNodes: [],
    });
  });

  it('will interpolate an array of children', function() {
    const fixture = [createTree('#text', 'foo'), createTree('#text', 'bar')];
    const span = html`<span>${fixture}</span>`;

    deepEqual(span, {
      rawNodeName: 'span',
      nodeName: 'span',
      nodeType: 1,
      nodeValue: '',
      key: '',
      attributes: {},
      childNodes: [{
        rawNodeName: '#text',
        nodeName: '#text',
        nodeType: 3,
        nodeValue: 'foo',
        key: '',
        attributes: {},
        childNodes: [],
      }, {
        rawNodeName: '#text',
        nodeName: '#text',
        nodeType: 3,
        nodeValue: 'bar',
        key: '',
        attributes: {},
        childNodes: [],
      }],
    });
  });

  it('will not mess up interpolation if HTML comments are used', () => {
    const fixtures = ['test', 'this'];
    const span = html`${fixtures[1]}
    `;

    deepEqual(span, {
      rawNodeName: 'span',
      nodeName: 'span',
      nodeType: 1,
      nodeValue: '',
      key: '',
      attributes: {},
      childNodes: [{
        rawNodeName: '#text',
        nodeName: '#text',
        nodeType: 3,
        nodeValue: 'this',
        key: '',
        attributes: {},
        childNodes: [],
      }],
    });
  });

  it('will support a custom tag name', () => {
    const Ctor = function() {};
    const vTree = html`<${Ctor} attr="value" />`;

    deepEqual(vTree, {
      rawNodeName: Ctor,
      nodeName: '#document-fragment',
      nodeType: 11,
      nodeValue: '',
      key: '',
      attributes: { attr: 'value' },
      childNodes: [],
    });
  });

  it('supports mixing custom elements and custom components', () => {
    const React = () => {};
    const vTree = html`
      <${React} />
      <web-component />
    `;

    deepEqual(vTree, {
      rawNodeName: '#document-fragment',
      nodeName: '#document-fragment',
      nodeValue: '',
      nodeType: 11,
      key: '',
      childNodes: [{
        rawNodeName: React,
        nodeName: '#document-fragment',
        nodeValue: '',
        nodeType: 11,
        key: '',
        childNodes: [],
        attributes: {},
      }, {
          "attributes": {},
          "childNodes": [],
          "key": "",
          "nodeName": "#text",
          "nodeType": 3,
          "nodeValue": "\n      ",
          "rawNodeName": "#text"
      }, {
        rawNodeName: 'web-component',
        nodeName: 'web-component',
        nodeValue: '',
        nodeType: 1,
        key: '',
        childNodes: [],
        attributes: {},
      }],
      attributes: {},
    });
  });

  describe('Strict mode', () => {
    it('will clean up after an error', () => {
      throws(() => html.strict`
        <web-component>
      `, /Possibly invalid markup. <web-component> is not a self closing tag/);

      // Test a second time to ensure clean up occured before the failure.
      throws(() => html.strict`
        <web-component>
      `, /Possibly invalid markup. <web-component> is not a self closing tag/);
    });

    it('will error if tags cannot self-close', () => {
      throws(() => html.strict`
        <web-component>
      `, /Possibly invalid markup. <web-component> is not a self closing tag/);
    });

    it('will error if the closing tag does not match', () => {
      throws(() => html.strict`
        <web-component></not-component>
      `, /Possibly invalid markup. <web-component> is not a self closing tag/);
    });

    it('will error if tag is not closed', () => {
      throws(() => html.strict`
        <web-component
      `, /Possibly invalid markup. Opening tag was not properly closed/);
    });

    it('will error if tag is not closed along with proper markup', () => {
      throws(() => html.strict`
        <proper></proper>
        <web-component
      `, /Possibly invalid markup. Opening tag was not properly closed/);

      throws(() => html.strict`
        <web-component
        <proper></proper>
      `, /Possibly invalid markup. <web-component> is not a self closing tag/);

      throws(() => html.strict`
        <proper></proper>
        <web-component
        <proper></proper>
      `, /Possibly invalid markup. <web-component> is not a self closing tag/);
    });

    it('will error if tag is not opened', () => {
      throws(() => html.strict`
        web-component>
      `, /Possibly invalid markup. Opening tag was not properly opened/);
    });

    it('will error when a custom component is not closed', () => {
      const Component = () => {};

      throws(() => html.strict`
        <${Component}>
      `, /Possibly invalid markup. <Component> is not a self closing tag/);
    });

    it('will not error on doctype', () => {
      doesNotThrow(() => html.strict`
        <!doctype>

      `);

      const actual = html.strict`
        <!doctype>

      `;

      deepEqual(actual, {
        rawNodeName: 'html',
        nodeName: 'html',
        nodeValue: '',
        nodeType: 1,
        key: '',
        childNodes:
         [ { rawNodeName: 'head',
             nodeName: 'head',
             nodeValue: '',
             nodeType: 1,
             key: '',
             childNodes: [],
             attributes: {} },
           { rawNodeName: 'body',
             nodeName: 'body',
             nodeValue: '',
             nodeType: 1,
             key: '',
             childNodes: [],
             attributes: {} } ],
        attributes: {}
      });
    });

    it('will error if tag is not opened along with proper markup', () => {
      throws(() => html.strict`
        <proper></proper>
        web-component>
      `, /Possibly invalid markup. Opening tag was not properly opened./);

      //throws(() => html.strict`
      //  web-component>
      //  <proper></proper>
      //`, /Possibly invalid markup. <web-component> is not a self closing tag/);

      //throws(() => html.strict`
      //  <proper></proper>
      //  web-component>
      //  <proper></proper>
      //`, /Possibly invalid markup. <web-component> is not a self closing tag/);
    });
  });
});
<commit_msg>Add in test for namespace attributes<commit_after>import { equal, deepEqual, doesNotThrow, throws } from 'assert';
import html from '../lib/html';
import createTree from '../lib/tree/create';
import validateMemory from './util/validateMemory';

describe('HTML (Tagged template)', function() {
  afterEach(() => validateMemory());

  it('will return null when passed a falsy value', () => {
    equal(html(), null);
    equal(html(null), null);
    equal(html(undefined), null);
    equal(html(0), null);
    equal(html(NaN), null);
    equal(html(false), null);
  });

  it('will support running as a standalone function', () => {
    equal(html('
').nodeName, 'div');
  });

  it('will interpolate a single string value in an attribute', function() {
    const foo = 'foo';
    const span = html`<span class="${foo}" />`;

    equal(span.attributes.class, 'foo');
  });

  it('will interpolate multiple string values in an attribute', function() {
    const foo = 'foo';
    const bar = 'bar';

    const multipleValues = html`<span class="${foo} ${bar}" />`;

    equal(multipleValues.attributes.class, 'foo bar');
  });

  it('will support namespace attributes', function() {
    const div = html`<div ns:key="value" />`;

    equal(div.attributes['ns:key'], 'value');
  });

  it('will interpolate value-less attributes', function() {
    const checked = 'checked';
    const input = html`<input type="checkbox" ${checked}>`;

    equal(input.attributes.checked, 'checked');
  });

  it('will interpolate multiple type values in an attribute', function() {
    const foo = 'foo';
    const bar = {};

    const multipleValues = html`<span class="${foo} ${bar}" />`;

    equal(multipleValues.attributes.class, 'foo [object Object]');
  });

  it('will interpolate attribute values with text', () => {
    const icon = 'some-icon';
    const vTree = html`<i class="${icon} icon" />`

    deepEqual(vTree, {
      rawNodeName: 'i',
      nodeName: 'i',
      nodeValue: '',
      nodeType: 1,
      key: '',
      childNodes: [],
      attributes: {
        class: 'some-icon icon'
      },
    });
  });

  it('will flatten nested fragments', () => {
    const array = [1];
    const vTree = html`

        ${array.map(i => html`

Some label

          ${i}
        `)}

    `;

    deepEqual(vTree, {
      rawNodeName: 'div',
      nodeName: "div",
      nodeValue: "",
      nodeType: 1,
      key: "",
      childNodes: [{
        rawNodeName: "#text",
        nodeName: "#text",
        nodeValue: "\n        ",
        nodeType: 3,
        key: "",
        childNodes: [],
        attributes: {},
      }, {
        rawNodeName: "p",
        nodeName: "p",
        nodeValue: "",
        nodeType: 1,
        key: "",
        childNodes: [{
          rawNodeName: "#text",
          nodeName: "#text",
          nodeValue: "Some label",
          nodeType: 3,
          key: "",
          childNodes: [],
          attributes: {},
        }],
        attributes: {},
      }, {
        rawNodeName: "#text",
        nodeName: "#text",
        nodeValue: "\n          ",
        nodeType: 3,
        key: "",
        childNodes: [],
        attributes: {},
      }, {
        rawNodeName: "span",
        nodeName: "span",
        nodeValue: "",
        nodeType: 1,
        key: "",
        childNodes: [{
          rawNodeName: "#text",
          nodeName: "#text",
          nodeValue: "1",
          nodeType: 3,
          key: "",
          childNodes: [],
          attributes: {},
        }],
        attributes: {},
      }, {
        rawNodeName: "#text",
        nodeName: "#text",
        nodeValue: "\n      ",
        nodeType: 3,
        key: "",
        childNodes: [],
        attributes: {},
      }],
      attributes: {},
    });
  });

  it('will return a fragment with multiple top level elements w/o values', () => {
    const vTree = html`<span class="has-class" /><span />`;

    deepEqual(vTree, {
      rawNodeName: '#document-fragment',
      nodeName: '#document-fragment',
      nodeValue: '',
      nodeType: 11,
      key: '',
      childNodes: [{
        rawNodeName: 'span',
        nodeName: 'span',
        nodeValue: '',
        nodeType: 1,
        key: '',
        childNodes: [],
        attributes: {
          class: 'has-class',
        },
      }, {
        rawNodeName: 'span',
        nodeName: 'span',
        nodeValue: '',
        nodeType: 1,
        key: '',
        childNodes: [],
        attributes: {},
      }],
      attributes: {},
    });
  });

  it('will return a fragment with multiple top level elements w/ values', () => {
    const className = 'has-class';
    const vTree = html`<span class="${className}" /><span />`;

    deepEqual(vTree, {
      rawNodeName: '#document-fragment',
      nodeName: '#document-fragment',
      nodeValue: '',
      nodeType: 11,
      key: '',
      childNodes: [{
        rawNodeName: 'span',
        nodeName: 'span',
        nodeValue: '',
        nodeType: 1,
        key: '',
        childNodes: [],
        attributes: {
          class: 'has-class',
        },
      }, {
        rawNodeName: 'span',
        nodeName: 'span',
        nodeValue: '',
        nodeType: 1,
        key: '',
        childNodes: [],
        attributes: {},
      }],
      attributes: {},
    });
  });

  it('will support aligning attributes on new lines', function() {
    const multipleValues = html`

    `;

    equal(multipleValues.attributes.class.trim(), 'foo\n        bar');
  });

  it('will support empty string attributes', () => {
    const span = html`<span href="" />`;

    deepEqual(span, {
      rawNodeName: 'span',
      nodeName: 'span',
      nodeType: 1,
      nodeValue: '',
      key: '',
      attributes: { href: '' },
      childNodes: [],
    });
  });

  it('will interpolate a string child', function() {
    const span = html`<span>${'foo'}</span>`;

    deepEqual(span.childNodes[0], {
      rawNodeName: '#text',
      nodeName: '#text',
      nodeType: 3,
      nodeValue: 'foo',
      key: '',
      attributes: {},
      childNodes: [],
    });
  });

  it('will interpolate a string child with html entities', function() {
    const span = html`<span>${'∞'}</span>`;

    deepEqual(span.childNodes[0], {
      rawNodeName: '#text',
      nodeName: '#text',
      nodeType: 3,
      nodeValue: '∞',
      key: '',
      attributes: {},
      childNodes: [],
    });
  });

  it('will interpolate a VTree child', function() {
    const span = html`<span>${createTree('#text', 'foo')}</span>`;

    deepEqual(span.childNodes[0], {
      rawNodeName: '#text',
      nodeName: '#text',
      nodeType: 3,
      nodeValue: 'foo',
      key: '',
      attributes: {},
      childNodes: [],
    });
  });

  it('will interpolate a DOM Node', function() {
    const span = html`<span>${document.createTextNode('foo')}</span>`;

    deepEqual(span.childNodes[0], {
      rawNodeName: '#text',
      nodeName: '#text',
      nodeType: 3,
      nodeValue: 'foo',
      key: '',
      attributes: {},
      childNodes: [],
    });
  });

  it('will interpolate an array of children', function() {
    const fixture = [createTree('#text', 'foo'), createTree('#text', 'bar')];
    const span = html`<span>${fixture}</span>`;

    deepEqual(span, {
      rawNodeName: 'span',
      nodeName: 'span',
      nodeType: 1,
      nodeValue: '',
      key: '',
      attributes: {},
      childNodes: [{
        rawNodeName: '#text',
        nodeName: '#text',
        nodeType: 3,
        nodeValue: 'foo',
        key: '',
        attributes: {},
        childNodes: [],
      }, {
        rawNodeName: '#text',
        nodeName: '#text',
        nodeType: 3,
        nodeValue: 'bar',
        key: '',
        attributes: {},
        childNodes: [],
      }],
    });
  });

  it('will not mess up interpolation if HTML comments are used', () => {
    const fixtures = ['test', 'this'];
    const span = html`${fixtures[1]}
    `;

    deepEqual(span, {
      rawNodeName: 'span',
      nodeName: 'span',
      nodeType: 1,
      nodeValue: '',
      key: '',
      attributes: {},
      childNodes: [{
        rawNodeName: '#text',
        nodeName: '#text',
        nodeType: 3,
        nodeValue: 'this',
        key: '',
        attributes: {},
        childNodes: [],
      }],
    });
  });

  it('will support a custom tag name', () => {
    const Ctor = function() {};
    const vTree = html`<${Ctor} attr="value" />`;

    deepEqual(vTree, {
      rawNodeName: Ctor,
      nodeName: '#document-fragment',
      nodeType: 11,
      nodeValue: '',
      key: '',
      attributes: { attr: 'value' },
      childNodes: [],
    });
  });

  it('supports mixing custom elements and custom components', () => {
    const React = () => {};
    const vTree = html`
      <${React} />
      <web-component />
    `;

    deepEqual(vTree, {
      rawNodeName: '#document-fragment',
      nodeName: '#document-fragment',
      nodeValue: '',
      nodeType: 11,
      key: '',
      childNodes: [{
        rawNodeName: React,
        nodeName: '#document-fragment',
        nodeValue: '',
        nodeType: 11,
        key: '',
        childNodes: [],
        attributes: {},
      }, {
          "attributes": {},
          "childNodes": [],
          "key": "",
          "nodeName": "#text",
          "nodeType": 3,
          "nodeValue": "\n      ",
          "rawNodeName": "#text"
      }, {
        rawNodeName: 'web-component',
        nodeName: 'web-component',
        nodeValue: '',
        nodeType: 1,
        key: '',
        childNodes: [],
        attributes: {},
      }],
      attributes: {},
    });
  });

  describe('Strict mode', () => {
    it('will clean up after an error', () => {
      throws(() => html.strict`
        <web-component>
      `, /Possibly invalid markup. <web-component> is not a self closing tag/);

      // Test a second time to ensure clean up occured before the failure.
      throws(() => html.strict`
        <web-component>
      `, /Possibly invalid markup. <web-component> is not a self closing tag/);
    });

    it('will error if tags cannot self-close', () => {
      throws(() => html.strict`
        <web-component>
      `, /Possibly invalid markup. <web-component> is not a self closing tag/);
    });

    it('will error if the closing tag does not match', () => {
      throws(() => html.strict`
        <web-component></not-component>
      `, /Possibly invalid markup. <web-component> is not a self closing tag/);
    });

    it('will error if tag is not closed', () => {
      throws(() => html.strict`
        <web-component
      `, /Possibly invalid markup. Opening tag was not properly closed/);
    });

    it('will error if tag is not closed along with proper markup', () => {
      throws(() => html.strict`
        <proper></proper>
        <web-component
      `, /Possibly invalid markup. Opening tag was not properly closed/);

      throws(() => html.strict`
        <web-component
        <proper></proper>
      `, /Possibly invalid markup. <web-component> is not a self closing tag/);

      throws(() => html.strict`
        <proper></proper>
        <web-component
        <proper></proper>
      `, /Possibly invalid markup. <web-component> is not a self closing tag/);
    });

    it('will error if tag is not opened', () => {
      throws(() => html.strict`
        web-component>
      `, /Possibly invalid markup. Opening tag was not properly opened/);
    });

    it('will error when a custom component is not closed', () => {
      const Component = () => {};

      throws(() => html.strict`
        <${Component}>
      `, /Possibly invalid markup. <Component> is not a self closing tag/);
    });

    it('will not error on doctype', () => {
      doesNotThrow(() => html.strict`
        <!doctype>

      `);

      const actual = html.strict`
        <!doctype>

      `;

      deepEqual(actual, {
        rawNodeName: 'html',
        nodeName: 'html',
        nodeValue: '',
        nodeType: 1,
        key: '',
        childNodes:
         [ { rawNodeName: 'head',
             nodeName: 'head',
             nodeValue: '',
             nodeType: 1,
             key: '',
             childNodes: [],
             attributes: {} },
           { rawNodeName: 'body',
             nodeName: 'body',
             nodeValue: '',
             nodeType: 1,
             key: '',
             childNodes: [],
             attributes: {} } ],
        attributes: {}
      });
    });

    it('will error if tag is not opened along with proper markup', () => {
      throws(() => html.strict`
        <proper></proper>
        web-component>
      `, /Possibly invalid markup. Opening tag was not properly opened./);

      //throws(() => html.strict`
      //  web-component>
      //  <proper></proper>
      //`, /Possibly invalid markup. <web-component> is not a self closing tag/);

      //throws(() => html.strict`
      //  <proper></proper>
      //  web-component>
      //  <proper></proper>
      //`, /Possibly invalid markup. <web-component> is not a self closing tag/);
    });
  });
});
<|endoftext|>


<commit_before>"use strict";

var f = require('util').format;

exports['Should correctly connect server to single instance'] = {
  metadata: { requires: { topology: "single" } },

  test: function(configuration, test) {
    var Server = require('../../../lib2/topologies/server')
      , bson = require('bson').BSONPure.BSON;

    // Attempt to connect
    var server = new Server({
        host: configuration.host
      , port: configuration.port
      , bson: new bson()
    })

    // Add event listeners
    server.on('connect', function(server) {
      server.destroy();
      test.done();
    });

    // Start connection
    server.connect();
  }
}

exports['Should correctly connect server to single instance and execute ismaster'] = {
  metadata: { requires: { topology: "single" } },

  test: function(configuration, test) {
    var Server = require('../../../lib2/topologies/server')
      , bson = require('bson').BSONPure.BSON;

    // Attempt to connect
    var server = new Server({
        host: configuration.host
      , port: configuration.port
      , bson: new bson()
    })

    // Add event listeners
    server.on('connect', function(server) {
      server.command('admin.$cmd', {ismaster:true}, function(err, r) {
        test.equal(null, err);
        test.equal(true, r.result.ismaster);
        test.ok(r.connection != null)

        server.destroy();
        test.done();
      });
    });

    // Start connection
    server.connect();
  }
}

exports['Should correctly connect server to single instance and execute ismaster returning raw'] = {
  metadata: { requires: { topology: "single" } },

  test: function(configuration, test) {
    var Server = require('../../../lib2/topologies/server')
      , bson = require('bson').BSONPure.BSON;

    // Attempt to connect
    var server = new Server({
        host: configuration.host
      , port: configuration.port
      , bson: new bson()
    })

    // Add event listeners
    server.on('connect', function(server) {
      server.command('admin.$cmd', {ismaster:true}, {
        raw: true
      }, function(err, r) {
        test.equal(null, err);
        test.ok(r.result instanceof Buffer);
        test.ok(r.connection != null)

        server.destroy();
        test.done();
      });
    });

    // Start connection
    server.connect();
  }
}

exports['Should correctly connect server to single instance and execute insert'] = {
  metadata: { requires: { topology: "single" } },

  test: function(configuration, test) {
    var Server = require('../../../lib2/topologies/server')
      , bson = require('bson').BSONPure.BSON;

    // Attempt to connect
    var server = new Server({
        host: configuration.host
      , port: configuration.port
      , bson: new bson()
    })

    // Add event listeners
    server.on('connect', function(server) {
      server.insert('integration_tests.inserts', {a:1}, function(err, r) {
        test.equal(null, err);
        test.equal(1, r.result.n);

        server.insert('integration_tests.inserts', {a:1}, {ordered:false}, function(err, r) {
          test.equal(null, err);
          test.equal(1, r.result.n);

          server.destroy();
          test.done();
        });
      });
    });

    // Start connection
    server.connect();
  }
}

exports['Should correctly connect server to single instance and execute bulk insert'] = {
  metadata: { requires: { topology: "single" } },

  test: function(configuration, test) {
    var Server = require('../../../lib2/topologies/server')
      , bson = require('bson').BSONPure.BSON;

    // Attempt to connect
    var server = new Server({
        host: configuration.host
      , port: configuration.port
      , bson: new bson()
    })

    // Add event listeners
    server.on('connect', function(server) {
      server.insert('integration_tests.inserts', [{a:1}, {b:1}], function(err, r) {
        test.equal(null, err);
        test.equal(2, r.result.n);

        server.insert('integration_tests.inserts', [{a:1}, {b:1}], {ordered:false}, function(err, r) {
          test.equal(null, err);
          test.equal(2, r.result.n);

          server.destroy();
          test.done();
        });
      });
    });

    // Start connection
    server.connect();
  }
}

exports['Should correctly connect server to single instance and execute insert with w:0'] = {
  metadata: { requires: { topology: "single" } },

  test: function(configuration, test) {
    var Server = require('../../../lib2/topologies/server')
      , bson = require('bson').BSONPure.BSON;

    // Attempt to connect
    var server = new Server({
        host: configuration.host
      , port: configuration.port
      , bson: new bson()
    })

    // Add event listeners
    server.on('connect', function(server) {
      server.insert('integration_tests.inserts', {a:1}, {writeConcern: {w:0}}, function(err, r) {
        test.equal(null, err);
        test.equal(1, r.result.ok);

        server.insert('integration_tests.inserts', {a:1}, {ordered:false, writeConcern: {w:0}}, function(err, r) {
          test.equal(null, err);
          test.equal(1, r.result.ok);

          server.destroy();
          test.done();
        });
      });
    });

    // Start connection
    server.connect();
  }
}

exports['Should correctly connect server to single instance and execute update'] = {
  metadata: { requires: { topology: "single" } },

  test: function(configuration, test) {
    var Server = require('../../../lib2/topologies/server')
      , bson = require('bson').BSONPure.BSON;

    // Attempt to connect
    var server = new Server({
        host: configuration.host
      , port: configuration.port
      , bson: new bson()
    })

    // Add event listeners
    server.on('connect', function(_server) {
      _server.update('integration_tests.inserts_example2', [{
        q: {a: 1}, u: {'$set': {b:1}}, upsert:true
      }], {
        writeConcern: {w:1}, ordered:true
      }, function(err, results) {
        test.equal(null, err);
        test.equal(1, results.result.n);

        _server.destroy();
        test.done();
      });
    });

    // Start connection
    server.connect();
  }
}

exports['Should correctly connect server to single instance and execute remove'] = {
  metadata: { requires: { topology: "single" } },

  test: function(configuration, test) {
    var Server = require('../../../lib2/topologies/server')
      , bson = require('bson').BSONPure.BSON;

    // Attempt to connect
    var server = new Server({
        host: configuration.host
      , port: configuration.port
      , bson: new bson()
    })

    // Add event listeners
    server.on('connect', function(_server) {
      server.insert('integration_tests.remove_example', {a:1}, function(err, r) {
        test.equal(null, err);
        test.equal(true, r.result.ok);

        _server.remove('integration_tests.remove_example', [{q: {a:1}, limit:1}], {
          writeConcern: {w:1}, ordered:true
        }, function(err, results) {
          test.equal(null, err);
          test.equal(1, results.result.n);

          _server.destroy();
          test.done();
        });
      });
    });

    // Start connection
    server.connect();
  }
}
<commit_msg>fixed issue where _execute would not get called correctly on disconnected server when doing Pool.write<commit_after>"use strict";

var f = require('util').format;

exports['Should correctly connect server to single instance'] = {
  metadata: { requires: { topology: "single" } },

  test: function(configuration, test) {
    var Server = require('../../../lib2/topologies/server')
      , bson = require('bson').BSONPure.BSON;

    // Attempt to connect
    var server = new Server({
        host: configuration.host
      , port: configuration.port
      , bson: new bson()
    })

    // Add event listeners
    server.on('connect', function(server) {
      server.destroy();
      test.done();
    });

    // Start connection
    server.connect();
  }
}

exports['Should correctly connect server to single instance and execute ismaster'] = {
  metadata: { requires: { topology: "single" } },

  test: function(configuration, test) {
    var Server = require('../../../lib2/topologies/server')
      , bson = require('bson').BSONPure.BSON;

    // Attempt to connect
    var server = new Server({
        host: configuration.host
      , port: configuration.port
      , bson: new bson()
    })

    // Add event listeners
    server.on('connect', function(server) {
      server.command('admin.$cmd', {ismaster:true}, function(err, r) {
        test.equal(null, err);
        test.equal(true, r.result.ismaster);
        test.ok(r.connection != null)

        server.destroy();
        test.done();
      });
    });

    // Start connection
    server.connect();
  }
}

exports['Should correctly connect server to single instance and execute ismaster returning raw'] = {
  metadata: { requires: { topology: "single" } },

  test: function(configuration, test) {
    var Server = require('../../../lib2/topologies/server')
      , bson = require('bson').BSONPure.BSON;

    // Attempt to connect
    var server = new Server({
        host: configuration.host
      , port: configuration.port
      , bson: new bson()
    })

    // Add event listeners
    server.on('connect', function(server) {
      server.command('admin.$cmd', {ismaster:true}, {
        raw: true
      }, function(err, r) {
        test.equal(null, err);
        test.ok(r.result instanceof Buffer);
        test.ok(r.connection != null)

        server.destroy();
        test.done();
      });
    });

    // Start connection
    server.connect();
  }
}

exports['Should correctly connect server to single instance and execute insert'] = {
  metadata: { requires: { topology: "single" } },

  test: function(configuration, test) {
    var Server = require('../../../lib2/topologies/server')
      , bson = require('bson').BSONPure.BSON;

    // Attempt to connect
    var server = new Server({
        host: configuration.host
      , port: configuration.port
      , bson: new bson()
    })

    // Add event listeners
    server.on('connect', function(server) {
      server.insert('integration_tests.inserts', {a:1}, function(err, r) {
        test.equal(null, err);
        test.equal(1, r.result.n);

        server.insert('integration_tests.inserts', {a:1}, {ordered:false}, function(err, r) {
          test.equal(null, err);
          test.equal(1, r.result.n);

          server.destroy();
          test.done();
        });
      });
    });

    // Start connection
    server.connect();
  }
}

exports['Should correctly connect server to single instance and execute bulk insert'] = {
  metadata: { requires: { topology: "single" } },

  test: function(configuration, test) {
    var Server = require('../../../lib2/topologies/server')
      , bson = require('bson').BSONPure.BSON;

    // Attempt to connect
    var server = new Server({
        host: configuration.host
      , port: configuration.port
      , bson: new bson()
    })

    // Add event listeners
    server.on('connect', function(server) {
      server.insert('integration_tests.inserts', [{a:1}, {b:1}], function(err, r) {
        test.equal(null, err);
        test.equal(2, r.result.n);

        server.insert('integration_tests.inserts', [{a:1}, {b:1}], {ordered:false}, function(err, r) {
          test.equal(null, err);
          test.equal(2, r.result.n);

          server.destroy();
          test.done();
        });
      });
    });

    // Start connection
    server.connect();
  }
}

exports['Should correctly connect server to single instance and execute insert with w:0'] = {
  metadata: { requires: { topology: "single" } },

  test: function(configuration, test) {
    var Server = require('../../../lib2/topologies/server')
      , bson = require('bson').BSONPure.BSON;

    // Attempt to connect
    var server = new Server({
        host: configuration.host
      , port: configuration.port
      , bson: new bson()
    })

    // Add event listeners
    server.on('connect', function(server) {
      server.insert('integration_tests.inserts', {a:1}, {writeConcern: {w:0}}, function(err, r) {
        test.equal(null, err);
        test.equal(1, r.result.ok);

        server.insert('integration_tests.inserts', {a:1}, {ordered:false, writeConcern: {w:0}}, function(err, r) {
          test.equal(null, err);
          test.equal(1, r.result.ok);

          server.destroy();
          test.done();
        });
      });
    });

    // Start connection
    server.connect();
  }
}

exports['Should correctly connect server to single instance and execute update'] = {
  metadata: { requires: { topology: "single" } },

  test: function(configuration, test) {
    var Server = require('../../../lib2/topologies/server')
      , bson = require('bson').BSONPure.BSON;

    // Attempt to connect
    var server = new Server({
        host: configuration.host
      , port: configuration.port
      , bson: new bson()
    })

    // Add event listeners
    server.on('connect', function(_server) {
      _server.update('integration_tests.inserts_example2', [{
        q: {a: 1}, u: {'$set': {b:1}}, upsert:true
      }], {
        writeConcern: {w:1}, ordered:true
      }, function(err, results) {
        test.equal(null, err);
        test.equal(1, results.result.n);

        _server.destroy();
        test.done();
      });
    });

    // Start connection
    server.connect();
  }
}

exports['Should correctly connect server to single instance and execute remove'] = {
  metadata: { requires: { topology: "single" } },

  test: function(configuration, test) {
    var Server = require('../../../lib2/topologies/server')
      , bson = require('bson').BSONPure.BSON;

    // Attempt to connect
    var server = new Server({
        host: configuration.host
      , port: configuration.port
      , bson: new bson()
    })

    // Add event listeners
    server.on('connect', function(_server) {
      server.insert('integration_tests.remove_example', {a:1}, function(err, r) {
        test.equal(null, err);
        test.equal(true, r.result.ok);

        _server.remove('integration_tests.remove_example', [{q: {a:1}, limit:1}], {
          writeConcern: {w:1}, ordered:true
        }, function(err, results) {
          test.equal(null, err);
          test.equal(1, results.result.n);

          _server.destroy();
          test.done();
        });
      });
    });

    // Start connection
    server.connect();
  }
}

/**
 * @ignore
 */
exports['Should correctly recover with multiple restarts'] = {
  metadata: { requires: { topology: ['single'] } },

  // The actual test we wish to run
  test: function(configuration, test) {
    var Server = require('../../../lib2/topologies/server')
      , bson = require('bson').BSONPure.BSON;

    var done = false;

    // Attempt to connect
    var server = new Server({
        host: configuration.host
      , port: configuration.port
      , bson: new bson()
    })

    // Add event listeners
    server.on('connect', function(_server) {
      var count = 1;
      var allDone = 0;
      var ns = "integration_tests.t";

      var execute = function() {
        if(!done) {
          server.insert(ns, {a:1, count: count}, function(err, r) {
            count = count + 1;

            // Execute find
            var cursor = _server.cursor(ns, {
              find: ns, query: {}, batchSize: 2
            });

            // Execute next
            cursor.next(function(err, d) {
              setTimeout(execute, 500);
            });
          })
        } else {
          server.insert(ns, {a:1, count: count}, function(err, r) {
            test.equal(null, err);

            // Execute find
            var cursor = _server.cursor(ns, {
              find: ns, query: {}, batchSize: 2
            });

            // Execute next
            cursor.next(function(err, d) {
              test.equal(null, err);
              server.destroy();
              test.done();
            });
          })
        }
      }

      setTimeout(execute, 500);
    });

    var count = 2

    var restartServer = function() {
      if(count == 0) {
        done = true;
        return;
      }

      count = count - 1;

      configuration.manager.stop().then(function() {
        setTimeout(function() {
          configuration.manager.start().then(function() {
            setTimeout(restartServer, 1000);
          });
        }, 2000);
      });
    }

    setTimeout(restartServer, 1000);
    server.connect();
  }
}
<|endoftext|>


<commit_before>// # Sample app
//
// This is a bit of documentation, try 'Read' above. Code can be written as semi-literate code, see more here <https://en.wikipedia.org/wiki/Literate_programming>

module.meta = {
  id: 'sample-app',
  name: 'Sample Application',
  version: '0.0.1'
};
var da = require('direape@0.1');
da.run(da.parent, 'appedit:html',`

Change me

Try to edit the code.

Choose Edit above, and then

     alter the code on the left side...

  (vi keybindings is enabled,

  so press <tt>i</tt> to insert)

${Object.keys(require('lodash')).join('
')}
`);<commit_msg>Commit sample-app.js via https://appedit.solsort.com/?Edit/js/gh/KodeKunstner/tutorial.<commit_after>// # Hello
//
// This is a bit of documentation, try 'Read' above. Code can be written as semi-literate code, see more here <https://en.wikipedia.org/wiki/Literate_programming>

module.meta = {
  id: 'sample-app',
  name: 'Sample Application',
  version: '0.0.1'
};
var da = require('direape@0.1');
da.run(da.parent, 'appedit:html',`

Change me

Try to edit the code.

Choose Edit above, and then

     alter the code on the left side...

  (vi keybindings is enabled,

  so press <tt>i</tt> to insert)

${Object.keys(require('lodash')).join('
')}
`);<|endoftext|>


<commit_before>//requestAnimationFrame shim
(function() {
    var lastTime = 0;
    var vendors = ['webkit', 'moz'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelAnimationFrame =
          window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
    }

    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function(callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() { callback(currTime + timeToCall); },
              timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };

    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
}());

//Main.js
(function() {
    var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 10000);
    camera.position.z = 500;

    var controls = new THREE.TrackballControls(camera);
    var OBJECTS = [];

    controls.rotateSpeed = 1.0;
    controls.zoomSpeed = 1.2;
    controls.panSpeed = 0.8;

    controls.noZoom = false;
    controls.noPan = false;

    controls.staticMoving = true;
    controls.dynamicDampingFactor = 0.3;

    controls.keys = [ 65, 83, 68 ];

    //controls.addEventListener("change", render);

    // world

    var scene = new THREE.Scene();
    //scene.fog = new THREE.FogExp2(0xcccccc, 0.002);

    var geometry = new THREE.SphereGeometry(30, 40, 18, 0, Math.PI * 2, 0, Math.PI);
    var material =  new THREE.MeshLambertMaterial({ color:0x00ff00, shading: THREE.FlatShading });

    for ( var i = 0; i < 300; i ++ ) {
        var mesh = new THREE.Mesh(geometry, material);
        mesh.position.x = (Math.random() - 0.5) * 1000;
        mesh.position.y = (Math.random() - 0.5) * 1000;
        mesh.position.z = (Math.random() - 0.5) * 1000;
        mesh.updateMatrix();
        mesh.matrixAutoUpdate = true;
        scene.add(mesh);
        OBJECTS.push(mesh);
    }

    // lights

    var lightOne = new THREE.DirectionalLight(0xffffff);
    lightOne.position.set( 1, 1, 1 );
    scene.add(lightOne);

    var lightTwo = new THREE.DirectionalLight(0x002288);
    lightTwo.position.set( -1, -1, -1 );
    scene.add(lightTwo);

    var lightThree = new THREE.AmbientLight(0x222222);
    scene.add(lightThree);

    // renderer

    var renderer = new THREE.WebGLRenderer({ antialias: false });
    //renderer.setClearColor(scene.fog.color, 1);
    renderer.setSize(window.innerWidth, window.innerHeight);

    var $container = $("#container");
    $container.append(renderer.domElement);

    window.addEventListener("resize", onWindowResize, false);

    var onWindowResize = function() {
        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();

        renderer.setSize( window.innerWidth, window.innerHeight );

        controls.handleResize();

        render();

    }

    var animate = function() {
        requestAnimationFrame(animate);
        controls.update();
        render();
    };

    var render = function () {
        for(var n = 0; n < OBJECTS.length; n++)
        {
            OBJECTS[n].rotation.x += 0.06;
            OBJECTS[n].rotation.y += 0.06;
        }

        renderer.render(scene, camera);
    };

    animate();
})(window, jQuery);<commit_msg>remove some spheres<commit_after>//requestAnimationFrame shim
(function() {
    var lastTime = 0;
    var vendors = ['webkit', 'moz'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelAnimationFrame =
          window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
    }

    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function(callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() { callback(currTime + timeToCall); },
              timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };

    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
}());

//Main.js
(function() {
    var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 10000);
    camera.position.z = 500;

    var controls = new THREE.TrackballControls(camera);
    var OBJECTS = [];

    controls.rotateSpeed = 1.0;
    controls.zoomSpeed = 1.2;
    controls.panSpeed = 0.8;

    controls.noZoom = false;
    controls.noPan = false;

    controls.staticMoving = true;
    controls.dynamicDampingFactor = 0.3;

    controls.keys = [ 65, 83, 68 ];

    //controls.addEventListener("change", render);

    // world

    var scene = new THREE.Scene();
    //scene.fog = new THREE.FogExp2(0xcccccc, 0.002);

    var geometry = new THREE.SphereGeometry(30, 25, 23, 0, Math.PI * 2, 0, Math.PI);
    var material =  new THREE.MeshLambertMaterial({ color:0x00ff00, shading: THREE.FlatShading });

    for ( var i = 0; i < 10; i ++ ) {
        var mesh = new THREE.Mesh(geometry, material);
        mesh.position.y = i;//(Math.random() - 0.5) * 1000;
        mesh.position.z = i;//(Math.random() - 0.5) * 1000;
        mesh.scale.x += i * 1;
        mesh.scale.y += i * 1;
        mesh.scale.z += i * 1;
        mesh.position.x = mesh.scale.x * i * 100;//(Math.random() - 0.5) * 1000;
        mesh.updateMatrix();
        mesh.matrixAutoUpdate = true;
        scene.add(mesh);
        OBJECTS.push(mesh);
    }

    // lights

    var lightOne = new THREE.DirectionalLight(0xffffff);
    lightOne.position.set( 1, 1, 1 );
    scene.add(lightOne);

    var lightTwo = new THREE.DirectionalLight(0x002288);
    lightTwo.position.set( -1, -1, -1 );
    scene.add(lightTwo);

    var lightThree = new THREE.AmbientLight(0x222222);
    scene.add(lightThree);

    // renderer

    var renderer = new THREE.WebGLRenderer({ antialias: false });
    //renderer.setClearColor(scene.fog.color, 1);
    renderer.setSize(window.innerWidth, window.innerHeight);

    var $container = $("#container");
    $container.append(renderer.domElement);

    window.addEventListener("resize", onWindowResize, false);

    var onWindowResize = function() {
        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();

        renderer.setSize( window.innerWidth, window.innerHeight );

        controls.handleResize();

        render();

    }

    var animate = function() {
        requestAnimationFrame(animate);
        controls.update();
        render();
    };

    var render = function () {
        for(var n = 0; n < OBJECTS.length; n++)
        {
            OBJECTS[n].rotation.x += 0.06;
            OBJECTS[n].rotation.y += 0.06;
        }

        renderer.render(scene, camera);
    };

    animate();
})(window, jQuery);<|endoftext|>


<commit_before>/**
 * @file TableContent component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component, createRef} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import eventsOn from 'dom-helpers/events/on';
import eventsOff from 'dom-helpers/events/off';

import Table from '../_TableContentTable';

import Theme from '../Theme';
import TableFragment from '../_statics/TableFragment';
import HorizontalAlign from '../_statics/HorizontalAlign';
import SelectMode from '../_statics/SelectMode';
import SelectAllMode from '../_statics/SelectAllMode';
import SortingType from '../_statics/SortingType';

import Util from '../_vendors/Util';
import TableCalculation from '../_vendors/TableCalculation';

class TableContent extends Component {

    static Fragment = TableFragment;
    static Align = HorizontalAlign;
    static Fixed = HorizontalAlign;
    static SelectMode = SelectMode;
    static SelectAllMode = SelectAllMode;
    static SortingType = SortingType;

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.wrapper = createRef();
        this.wrapperEl = null;

    }

    getColumns = () => {

        const {columns} = this.props,
            result = {
                [HorizontalAlign.LEFT]: [],
                [HorizontalAlign.CENTER]: [],
                [HorizontalAlign.RIGHT]: []
            };

        columns.forEach(column => {
            if (column.fixed === true || column.fixed === HorizontalAlign.LEFT) {
                result[HorizontalAlign.LEFT].push(column);
            } else if (column.fixed === HorizontalAlign.RIGHT) {
                result[HorizontalAlign.RIGHT].push(column);
            } else {
                result[HorizontalAlign.CENTER].push(column);
            }
        });

        return result;

    };

    /**
     * sort data by sorting
     * @param data
     * @returns {*[]}
     */
    sortData = (data = this.props.data) => {
        const {sorting, sortingFunc} = this.props;
        return sorting ? TableCalculation.sortTableData(data, sorting, sortingFunc) : data;
    };

    /**
     * slice data by pagination
     * @param data
     * @returns {*[]}
     */
    paginateData = (data = this.props.data) => {

        const {pagination} = this.props;

        if (!pagination) {
            return data;
        }

        const {pageSize, page} = pagination,
            len = data.length;

        let start = page * pageSize,
            stop = start + pageSize;

        start = start < 0 ? 0 : start;
        stop = stop > len ? len : stop;

        return data.slice(start, stop);

    };

    fixLayout = () => {
        if ((this.props.isHeadFixed || this.props.isFootFixed) && this.wrapperEl) {
            TableCalculation.fixLayout(this.wrapperEl);
        }
    };

    componentDidMount() {
        this.wrapperEl = this.wrapper && this.wrapper.current;
        eventsOn(window, 'resize', this.fixLayout);
    }

    componentDidUpdate(prevProps, prevState, snapshot) {
        this.fixLayout();
    }

    componentWillUnmount() {
        eventsOff(window, 'resize', this.fixLayout);
    }

    render() {

        const {
                className, style, data,
                ...restProps
            } = this.props,

            columns = this.getColumns();

        if (!columns) {
            return null;
        }

        const tableData = this.paginateData(this.sortData(data));

        return (

                {
                    columns[HorizontalAlign.LEFT] && columns[HorizontalAlign.LEFT].length > 0 ?

                        :
                        null
                }

                {
                    columns[HorizontalAlign.RIGHT] && columns[HorizontalAlign.RIGHT].length > 0 ?

                        :
                        null
                }

        );

    }
}

TableContent.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * The theme of the table select radio or checkbox.
     */
    selectTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * The select mode of table.
     */
    selectMode: PropTypes.oneOf(Util.enumerateValue(SelectMode)),

    /**
     * The select all mode of table, all or current page.
     */
    selectAllMode: PropTypes.oneOf(Util.enumerateValue(SelectAllMode)),

    /**
     * Children passed into table header.
     */
    columns: PropTypes.arrayOf(PropTypes.shape({

        /**
         * fixed position of column ( true / 'left' / 'right' )
         */
        fixed: PropTypes.oneOfType([PropTypes.bool, PropTypes.oneOf(Util.enumerateValue(HorizontalAlign))]),

        /**
         * width of column
         */
        width: PropTypes.number,

        /**
         * minimum width of column
         */
        minWidth: PropTypes.number,

        /**
         * The class name of header.
         */
        headClassName: PropTypes.string,

        /**
         * Override the styles of header.
         */
        headStyle: PropTypes.object,

        /**
         * The render content in header.
         * (1) string，example： 'id'
         * (2) callback，example：function (colIndex) {return colIndex;}
         */
        headRenderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

        /**
         * align of table header cell
         */
        headAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * column span of table header
         */
        headSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * The class name of td.
         */
        bodyClassName: PropTypes.string,

        /**
         * Override the styles of td.
         */
        bodyStyle: PropTypes.object,

        /**
         * The render content in table.
         * (1) data key，example： 'id'
         * (2) data key tamplate，example：'${id} - ${name}'
         * (3) callback，example：function (rowData, rowIndex, colIndex) {return rowData.id;}
         */
        bodyRenderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

        /**
         * align of table body cell
         */
        bodyAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * column span of table body
         */
        bodySpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * The class name of footer.
         */
        footClassName: PropTypes.string,

        /**
         * Override the styles of footer.
         */
        footStyle: PropTypes.object,

        /**
         * The render content in footer.
         * (1) string，example： 'id'
         * (2) callback，example：function (colIndex) {return colIndex;}
         */
        footRenderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

        /**
         * align of table footer cell
         */
        footAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * column span of table foot
         */
        footSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * If true,this column can be sorted.
         */
        sortable: PropTypes.bool,

        /**
         * Sorting property.
         */
        sortingProp: PropTypes.string,

        defaultSortingType: PropTypes.oneOf(Util.enumerateValue(SortingType))

    })).isRequired,

    data: PropTypes.array,

    /**
     * sorting
     */
    sorting: PropTypes.shape({
        prop: PropTypes.string,
        type: PropTypes.oneOf(Util.enumerateValue(SortingType))
    }),
    defaultSortingType: PropTypes.oneOf(Util.enumerateValue(SortingType)),
    sortingAscIconCls: PropTypes.string,
    sortingDescIconCls: PropTypes.string,
    sortingFunc: PropTypes.func,

    /**
     * pagination
     */
    isPaginated: PropTypes.bool,
    pagination: PropTypes.shape({
        pageSize: PropTypes.number,
        page: PropTypes.number
    }),
    pageSizes: PropTypes.array,

    /**
     * fixed
     */
    isHeadFixed: PropTypes.bool,
    isFootFixed: PropTypes.bool,

    /**
     * callback
     */
    onSortChange: PropTypes.func

};

TableContent.defaultProps = {

    selectMode: SelectMode.SINGLE_SELECT,
    selectAllMode: SelectAllMode.CURRENT_PAGE,

    defaultSortingType: SortingType.ASC,
    sortingAscIconCls: 'fas fa-angle-up',
    sortingDescIconCls: 'fas fa-angle-down',

    isPaginated: true,
    pagination: {
        pageSize: 10,
        page: 0
    },
    pageSizes: [5, 10, 15, 20],

    isHeadFixed: false,
    isFootFixed: false

};

export default TableContent;
<commit_msg>update TableContent<commit_after>/**
 * @file TableContent component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component, createRef} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import eventsOn from 'dom-helpers/events/on';
import eventsOff from 'dom-helpers/events/off';

import ScrollableTable from '../_ScrollableTable';

import Theme from '../Theme';
import TableFragment from '../_statics/TableFragment';
import HorizontalAlign from '../_statics/HorizontalAlign';
import SelectMode from '../_statics/SelectMode';
import SelectAllMode from '../_statics/SelectAllMode';
import SortingType from '../_statics/SortingType';

import Util from '../_vendors/Util';
import TableCalculation from '../_vendors/TableCalculation';

class TableContent extends Component {

    static Fragment = TableFragment;
    static Align = HorizontalAlign;
    static Fixed = HorizontalAlign;
    static SelectMode = SelectMode;
    static SelectAllMode = SelectAllMode;
    static SortingType = SortingType;

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.wrapper = createRef();
        this.wrapperEl = null;

    }

    getColumns = () => {

        const {columns} = this.props,
            result = {
                [HorizontalAlign.LEFT]: [],
                [HorizontalAlign.CENTER]: [],
                [HorizontalAlign.RIGHT]: []
            };

        columns.forEach(column => {
            if (column.fixed === true || column.fixed === HorizontalAlign.LEFT) {
                result[HorizontalAlign.LEFT].push(column);
            } else if (column.fixed === HorizontalAlign.RIGHT) {
                result[HorizontalAlign.RIGHT].push(column);
            } else {
                result[HorizontalAlign.CENTER].push(column);
            }
        });

        return result;

    };

    /**
     * sort data by sorting
     * @param data
     * @returns {*[]}
     */
    sortData = (data = this.props.data) => {
        const {sorting, sortingFunc} = this.props;
        return sorting ? TableCalculation.sortTableData(data, sorting, sortingFunc) : data;
    };

    /**
     * slice data by pagination
     * @param data
     * @returns {*[]}
     */
    paginateData = (data = this.props.data) => {

        const {pagination} = this.props;

        if (!pagination) {
            return data;
        }

        const {pageSize, page} = pagination,
            len = data.length;

        let start = page * pageSize,
            stop = start + pageSize;

        start = start < 0 ? 0 : start;
        stop = stop > len ? len : stop;

        return data.slice(start, stop);

    };

    fixLayout = () => {
        if ((this.props.isHeadFixed || this.props.isFootFixed) && this.wrapperEl) {
            TableCalculation.fixLayout(this.wrapperEl, this.props);
        }
    };

    componentDidMount() {
        this.wrapperEl = this.wrapper && this.wrapper.current;
        eventsOn(window, 'resize', this.fixLayout);
    }

    componentDidUpdate(prevProps, prevState, snapshot) {
        this.fixLayout();
    }

    componentWillUnmount() {
        eventsOff(window, 'resize', this.fixLayout);
    }

    render() {

        const {
                className, style, data,
                ...restProps
            } = this.props,

            columns = this.getColumns();

        if (!columns) {
            return null;
        }

        const tableData = this.paginateData(this.sortData(data));

        return (

                <ScrollableTable {...restProps}
                                 className="table-content-center"
                                 columns={[
                                     ...TableCalculation.handleFixedColumns(columns[HorizontalAlign.LEFT]),
                                     ...columns[HorizontalAlign.CENTER],
                                     ...TableCalculation.handleFixedColumns(columns[HorizontalAlign.RIGHT])
                                 ]}
                                 data={tableData}/>

                {
                    columns[HorizontalAlign.LEFT] && columns[HorizontalAlign.LEFT].length > 0 ?
                        <ScrollableTable {...restProps}
                                         className="table-content-fixed-left"
                                         fixed={HorizontalAlign.LEFT}
                                         columns={columns[HorizontalAlign.LEFT]}
                                         data={tableData}/>
                        :
                        null
                }

                {
                    columns[HorizontalAlign.RIGHT] && columns[HorizontalAlign.RIGHT].length > 0 ?
                        <ScrollableTable {...restProps}
                                         className="table-content-fixed-right"
                                         fixed={HorizontalAlign.RIGHT}
                                         columns={columns[HorizontalAlign.RIGHT]}
                                         data={tableData}/>
                        :
                        null
                }

        );

    }
}

TableContent.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * The theme of the table select radio or checkbox.
     */
    selectTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * The select mode of table.
     */
    selectMode: PropTypes.oneOf(Util.enumerateValue(SelectMode)),

    /**
     * The select all mode of table, all or current page.
     */
    selectAllMode: PropTypes.oneOf(Util.enumerateValue(SelectAllMode)),

    /**
     * Children passed into table header.
     */
    columns: PropTypes.arrayOf(PropTypes.shape({

        /**
         * fixed position of column ( true / 'left' / 'right' )
         */
        fixed: PropTypes.oneOfType([PropTypes.bool, PropTypes.oneOf(Util.enumerateValue(HorizontalAlign))]),

        /**
         * width of column
         */
        width: PropTypes.number,

        /**
         * minimum width of column
         */
        minWidth: PropTypes.number,

        /**
         * The class name of header.
         */
        headClassName: PropTypes.string,

        /**
         * Override the styles of header.
         */
        headStyle: PropTypes.object,

        /**
         * The render content in header.
         * (1) string，example： 'id'
         * (2) callback，example：function (colIndex) {return colIndex;}
         */
        headRenderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

        /**
         * align of table header cell
         */
        headAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * column span of table header
         */
        headSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * The class name of td.
         */
        bodyClassName: PropTypes.string,

        /**
         * Override the styles of td.
         */
        bodyStyle: PropTypes.object,

        /**
         * The render content in table.
         * (1) data key，example： 'id'
         * (2) data key tamplate，example：'${id} - ${name}'
         * (3) callback，example：function (rowData, rowIndex, colIndex) {return rowData.id;}
         */
        bodyRenderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

        /**
         * align of table body cell
         */
        bodyAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * column span of table body
         */
        bodySpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * The class name of footer.
         */
        footClassName: PropTypes.string,

        /**
         * Override the styles of footer.
         */
        footStyle: PropTypes.object,

        /**
         * The render content in footer.
         * (1) string，example： 'id'
         * (2) callback，example：function (colIndex) {return colIndex;}
         */
        footRenderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

        /**
         * align of table footer cell
         */
        footAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * column span of table foot
         */
        footSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * If true,this column can be sorted.
         */
        sortable: PropTypes.bool,

        /**
         * Sorting property.
         */
        sortingProp: PropTypes.string,

        defaultSortingType: PropTypes.oneOf(Util.enumerateValue(SortingType))

    })).isRequired,

    data: PropTypes.array,

    /**
     * sorting
     */
    sorting: PropTypes.shape({
        prop: PropTypes.string,
        type: PropTypes.oneOf(Util.enumerateValue(SortingType))
    }),
    defaultSortingType: PropTypes.oneOf(Util.enumerateValue(SortingType)),
    sortingAscIconCls: PropTypes.string,
    sortingDescIconCls: PropTypes.string,
    sortingFunc: PropTypes.func,

    /**
     * pagination
     */
    isPaginated: PropTypes.bool,
    pagination: PropTypes.shape({
        pageSize: PropTypes.number,
        page: PropTypes.number
    }),
    pageSizes: PropTypes.array,

    /**
     * fixed
     */
    isHeadFixed: PropTypes.bool,
    isFootFixed: PropTypes.bool,

    /**
     * callback
     */
    onSortChange: PropTypes.func

};

TableContent.defaultProps = {

    selectMode: SelectMode.SINGLE_SELECT,
    selectAllMode: SelectAllMode.CURRENT_PAGE,

    defaultSortingType: SortingType.ASC,
    sortingAscIconCls: 'fas fa-angle-up',
    sortingDescIconCls: 'fas fa-angle-down',

    isPaginated: true,
    pagination: {
        pageSize: 10,
        page: 0
    },
    pageSizes: [5, 10, 15, 20],

    isHeadFixed: false,
    isFootFixed: false

};

export default TableContent;
<|endoftext|>