<commit_before>/*
 *  @copyright 2016 Joe McShea
 *  @license under the MIT license:
 *     http://www.opensource.org/licenses/mit-license.php
 */
(function ($) {
    // test is form with client side rendering
    if (typeof (SPClientTemplates) === 'undefined')
        return;

    // test at least one field is configured to use the star rating client side rendering
    if (typeof ($.csrConfig) !== 'object' || typeof ($.csrConfig.starRatingFields) !== 'object' || !$.csrConfig.starRatingFields.length)
        return;

    /*
     * Implementation class for the overrides.
     */
    $.starRatingImpl = {
        /*
         * Implementation for the display form and views.
         */
        displayMethod: function (ctx) {
            $.starRatingImpl.getCss();

            var result = $('<p />');
            result.append($('<div/>', {
                'id': ctx.CurrentFieldSchema.Name,
                //'class': 'csrdemos-stars csrdemos-' + ctx.CurrentFieldValue + 'stars',
                'class': 'csrdemos-stars csrdemos-' + ctx.CurrentItem[ctx.CurrentFieldSchema.Name] + 'stars',
                'data-value': ctx.CurrentItem[ctx.CurrentFieldSchema.Name]
            }));

            return result.html();
        },

        /*
         * Implementation for the new and edit forms.
         */
        inputMethod: function (ctx) {
            $.starRatingImpl.getCss();

            var current = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);

            // construct the html for our control and return it
            var result = $('<p />');
            result.append($('<div/>', {
                'id': current.fieldName,
                'class': 'csrdemos-stars csrdemos-' + ctx.CurrentFieldValue + 'stars',
                'data-value': ctx.CurrentFieldValue,
                'onclick': '$.starRatingImpl.handleClickOnStarRating(event)'
            }));
            result.append($('<span/>', {
                'id': current.fieldName + 'Error',
                'class': 'ms-formvalidation'
            }));

            // register a callback to return the current value
            current.registerGetValueCallback(
                current.fieldName,
                $.starRatingImpl.getFieldValue.bind(null, current.fieldName));

            // register validators
            $.starRatingImpl.registerValidators(current);

            return result.html();
        },

        /*
         * Setup validation handlers on the new and edit forms.
         */
        registerValidators: function (current) {
            // create a validator set
            var fieldValidators = new SPClientForms.ClientValidation.ValidatorSet();
            fieldValidators.RegisterValidator(new starRatingsFieldValidator());

            // if required, add a required field validator
            if (current.fieldSchema.Required) {
                fieldValidators.RegisterValidator(new SPClientForms.ClientValidation.RequiredValidator());
            }

            // register a callback method for the validators
            current.registerValidationErrorCallback(current.fieldName, function (error) {
                $('#' + current.fieldName + 'Error').attr('role', 'alert').html(error.errorMessage);
            });

            // register the validators
            current.registerClientValidator(current.fieldName, fieldValidators);
        },

        /*
         * Return the current value from the data-value attribute of my div.
         */
        getFieldValue: function (fieldName) {
            return $('#' + fieldName).attr('data-value');
        },

        /*
         * Shove a link to the stylesheet into the DOM one time.
         */
        getCss: function () {
            if (!$('body').attr('data-starcssadded')) {
                var css = _spPageContextInfo.siteAbsoluteUrl +
                    '/Style%20Library/starratings.css';
                $('head').append(
                    '<link rel="stylesheet" type="text/css" href="' + css + '">');
                $('body').attr('data-starcssadded', 'true');
            }
        },

        /*
         * Onclick callback; set the current value by determining which star
         * was clicked upon.
         */
        handleClickOnStarRating: function (e) {
            var div = $(e.target);
            var posX = div.offset().left;
            var stars = Math.floor((e.pageX - posX + (div.height() / 2)) / div.height());
            div.attr('class', 'csrdemos-stars');
            div.addClass('csrdemos-' + stars + 'stars');
            div.attr('data-value', stars);
        }
    };

    /*
     * A custom validator is just an object with a Validate method. It takes in the
     * value and returns an error based on whatever criteria it chooses; in this case
     * berating people for a wishy-washy answer (i.e. 3).
     */
    var starRatingsFieldValidator = function () {
        starRatingsFieldValidator.prototype.Validate = function (value) {
            var isError = false;
            var errorMessage = '';

            if (value == '3') {
                isError = true;
                errorMessage = 'Don\'t be mealy-mouthed, take a stand!';
            }

            return new SPClientForms.ClientValidation.ValidationResult(isError, errorMessage);
        };
    };

    /*
     * Create an empty overrides object.
     */
    var starRatingOverrides = {
        Templates: {
            'Fields': {}
        }
    };

    /*
     * Add an overrides object for each field we want to customize.
     */
    $.each($($.csrConfig.starRatingFields), function (i, v) {
        starRatingOverrides.Templates.Fields[v] = {
            'View': $.starRatingImpl.displayMethod,
            'DisplayForm': $.starRatingImpl.displayMethod,
            'NewForm': $.starRatingImpl.inputMethod,
            'EditForm': $.starRatingImpl.inputMethod
        };
    });

    // register my template overrides
    if (typeof _spPageContextInfo != 'undefined' && _spPageContextInfo != null) {
        // MDS is enabled
        var url = (_spPageContextInfo.siteServerRelativeUrl === '/' ? "" : _spPageContextInfo.siteServerRelativeUrl) +
            '/Style%20Library/StarRatingsCSR.js';
        // register a callback to register the templates on partial page loads
        RegisterModuleInit(url.toLowerCase(), function () {
            SPClientTemplates.TemplateManager.RegisterTemplateOverrides(starRatingOverrides);
        });
    }

    // also just register for full page loads (F5/refresh)
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(starRatingOverrides);
})(jQuery);

<commit_msg>feature() - removed validation from star rating<commit_after>/*
 *  @copyright 2016 Joe McShea
 *  @license under the MIT license:
 *     http://www.opensource.org/licenses/mit-license.php
 */
(function ($) {
    // test is form with client side rendering
    if (typeof (SPClientTemplates) === 'undefined')
        return;

    // test at least one field is configured to use the star rating client side rendering
    if (typeof ($.csrConfig) !== 'object' || typeof ($.csrConfig.starRatingFields) !== 'object' || !$.csrConfig.starRatingFields.length)
        return;

    /*
     * Implementation class for the overrides.
     */
    $.starRatingImpl = {
        /*
         * Implementation for the display form and views.
         */
        displayMethod: function (ctx) {
            $.starRatingImpl.getCss();

            var result = $('<p />');
            result.append($('<div/>', {
                'id': ctx.CurrentFieldSchema.Name,
                //'class': 'csrdemos-stars csrdemos-' + $.starRatingImpl.normalizeValue(ctx.CurrentFieldValue) + 'stars',
                'class': 'csrdemos-stars csrdemos-' + $.starRatingImpl.normalizeValue(ctx.CurrentItem[ctx.CurrentFieldSchema.Name]) + 'stars',
                'data-value': ctx.CurrentItem[ctx.CurrentFieldSchema.Name]
            }));

            return result.html();
        },

        /*
         * Implementation for the new and edit forms.
         */
        inputMethod: function (ctx) {
            $.starRatingImpl.getCss();

            var current = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);

            // construct the html for our control and return it
            var result = $('<p />');
            result.append($('<div/>', {
                'id': current.fieldName,
                'class': 'csrdemos-stars csrdemos-' + $.starRatingImpl.normalizeValue(ctx.CurrentFieldValue) + 'stars',
                'data-value': ctx.CurrentFieldValue,
                'onclick': '$.starRatingImpl.handleClickOnStarRating(event)'
            }));
            result.append($('<span/>', {
                'id': current.fieldName + 'Error',
                'class': 'ms-formvalidation'
            }));

            // register a callback to return the current value
            current.registerGetValueCallback(
                current.fieldName,
                $.starRatingImpl.getFieldValue.bind(null, current.fieldName));

            return result.html();
        },

        /*
         * Return the current value from the data-value attribute of my div.
         */
        getFieldValue: function (fieldName) {
            return $.starRatingImpl.normalizeValue($('#' + fieldName).attr('data-value'));
        },

        /*
         * Reduce value to 0 to 5.
         */
        normalizeValue: function (value) {
            var result = parseInt(value);
            if (result > 5) {
                result = 5;
            }
            else if (result < 0) {
                result = 0;
            }
            return result.toString();
        },

        /*
         * Shove a link to the stylesheet into the DOM one time.
         */
        getCss: function () {
            if (!$('body').attr('data-starcssadded')) {
                var css = _spPageContextInfo.siteAbsoluteUrl +
                    '/Style%20Library/starratings.css';
                $('head').append(
                    '<link rel="stylesheet" type="text/css" href="' + css + '">');
                $('body').attr('data-starcssadded', 'true');
            }
        },

        /*
         * Onclick callback; set the current value by determining which star
         * was clicked upon.
         */
        handleClickOnStarRating: function (e) {
            var div = $(e.target);
            var posX = div.offset().left;
            var stars = Math.floor((e.pageX - posX + (div.height() / 2)) / div.height());
            div.attr('class', 'csrdemos-stars');
            div.addClass('csrdemos-' + stars + 'stars');
            div.attr('data-value', stars);
        }
    };

    /*
     * Create an empty overrides object.
     */
    var starRatingOverrides = {
        Templates: {
            'Fields': {}
        }
    };

    /*
     * Add an overrides object for each field we want to customize.
     */
    $.each($($.csrConfig.starRatingFields), function (i, v) {
        starRatingOverrides.Templates.Fields[v] = {
            'View': $.starRatingImpl.displayMethod,
            'DisplayForm': $.starRatingImpl.displayMethod,
            'NewForm': $.starRatingImpl.inputMethod,
            'EditForm': $.starRatingImpl.inputMethod
        };
    });

    // register my template overrides
    if (typeof _spPageContextInfo != 'undefined' && _spPageContextInfo != null) {
        // MDS is enabled
        var url = (_spPageContextInfo.siteServerRelativeUrl === '/' ? "" : _spPageContextInfo.siteServerRelativeUrl) +
            '/Style%20Library/StarRatingsCSR.js';
        // register a callback to register the templates on partial page loads
        RegisterModuleInit(url.toLowerCase(), function () {
            SPClientTemplates.TemplateManager.RegisterTemplateOverrides(starRatingOverrides);
        });
    }

    // also just register for full page loads (F5/refresh)
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(starRatingOverrides);
})(jQuery);

<|endoftext|>


<commit_before>import { Component, createElement } from 'react'
import PropTypes from 'prop-types'
import ResizeObserver from 'resize-observer-polyfill'

import getTypes from './get-types'
import getContentRect from './get-content-rect'

function withContentRect(types) {
  return WrappedComponent =>
    class WithContentRect extends Component {
      static propTypes = {
        client: PropTypes.bool,
        offset: PropTypes.bool,
        scroll: PropTypes.bool,
        bounds: PropTypes.bool,
        margin: PropTypes.bool,
        innerRef: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
        onResize: PropTypes.func,
      }

      state = {
        contentRect: {
          entry: {},
          client: {},
          offset: {},
          scroll: {},
          bounds: {},
          margin: {},
        },
      }

      _animationFrameID = null

      _resizeObserver = null

      _node = null

      componentDidMount() {
        this._resizeObserver = new ResizeObserver(this.measure)
        if (this._node !== null) {
          this._resizeObserver.observe(this._node)
        }
      }

      componentWillUnmount() {
        if (this._resizeObserver !== null) {
          this._resizeObserver.disconnect()
          this._resizeObserver = null
        }
        window.cancelAnimationFrame(this._animationFrameID)
      }

      measure = entries => {
        const contentRect = getContentRect(
          this._node,
          types || getTypes(this.props)
        )

        if (entries) {
          contentRect.entry = entries[0].contentRect
        }

        this._animationFrameID = window.requestAnimationFrame(() => {
          if (this._resizeObserver !== null) {
            this.setState({ contentRect })
          }
        })

        if (typeof this.props.onResize === 'function') {
          this.props.onResize(contentRect)
        }
      }

      _handleRef = node => {
        if (this._resizeObserver !== null) {
          if (node !== null) {
            this._resizeObserver.observe(node)
          } else {
            this._resizeObserver.unobserve(this._node)
          }
        }

        this._node = node

        const { innerRef } = this.props
        if (innerRef) {
          if (typeof innerRef === 'function') {
            innerRef(node);
          } else {
            innerRef.current = node;
          }
        }
      }

      render() {
        const { innerRef, onResize, ...props } = this.props
        return createElement(WrappedComponent, {
          ...props,
          measureRef: this._handleRef,
          measure: this.measure,
          contentRect: this.state.contentRect,
        })
      }
    }
}

export default withContentRect
<commit_msg>Always unobserve prev node, before starting to observe next one.<commit_after>import { Component, createElement } from 'react'
import PropTypes from 'prop-types'
import ResizeObserver from 'resize-observer-polyfill'

import getTypes from './get-types'
import getContentRect from './get-content-rect'

function withContentRect(types) {
  return WrappedComponent =>
    class WithContentRect extends Component {
      static propTypes = {
        client: PropTypes.bool,
        offset: PropTypes.bool,
        scroll: PropTypes.bool,
        bounds: PropTypes.bool,
        margin: PropTypes.bool,
        innerRef: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
        onResize: PropTypes.func,
      }

      state = {
        contentRect: {
          entry: {},
          client: {},
          offset: {},
          scroll: {},
          bounds: {},
          margin: {},
        },
      }

      _animationFrameID = null

      _resizeObserver = null

      _node = null

      componentDidMount() {
        this._resizeObserver = new ResizeObserver(this.measure)
        if (this._node !== null) {
          this._resizeObserver.observe(this._node)
        }
      }

      componentWillUnmount() {
        if (this._resizeObserver !== null) {
          this._resizeObserver.disconnect()
          this._resizeObserver = null
        }
        window.cancelAnimationFrame(this._animationFrameID)
      }

      measure = entries => {
        const contentRect = getContentRect(
          this._node,
          types || getTypes(this.props)
        )

        if (entries) {
          contentRect.entry = entries[0].contentRect
        }

        this._animationFrameID = window.requestAnimationFrame(() => {
          if (this._resizeObserver !== null) {
            this.setState({ contentRect })
          }
        })

        if (typeof this.props.onResize === 'function') {
          this.props.onResize(contentRect)
        }
      }

      _handleRef = node => {
        if (this._resizeObserver !== null && this._node !== null) {
          this._resizeObserver.unobserve(this._node);
        }

        this._node = node

        const { innerRef } = this.props
        if (innerRef) {
          if (typeof innerRef === 'function') {
            innerRef(this._node);
          } else {
            innerRef.current = this._node;
          }
        }

        if (this._resizeObserver !== null && this._node !== null) {
          this._resizeObserver.observe(this._node);
        }
      }

      render() {
        const { innerRef, onResize, ...props } = this.props
        return createElement(WrappedComponent, {
          ...props,
          measureRef: this._handleRef,
          measure: this.measure,
          contentRect: this.state.contentRect,
        })
      }
    }
}

export default withContentRect
<|endoftext|>


<commit_before>import React from 'react';
import { addStoryInGroup, LOW_LEVEL_BLOCKS } from '../../../.storybook/utils';
import { number, select } from '@storybook/addon-knobs/react';
import { Counter, Tooltip, TextBody } from '../../index';

const colors = ['neutral', 'mint', 'aqua', 'violet', 'teal', 'gold', 'ruby'];
const sizes = ['small', 'medium'];

const TooltippedCounter = Tooltip(Counter);

export default {
  title: addStoryInGroup(LOW_LEVEL_BLOCKS, 'Counter'),
};

export const basic = () => (
  <Counter
    count={number('Count', 99)}
    color={select('Color', colors, 'neutral')}
    size={select('Size', sizes, 'medium')}
    maxCount={number('Maximum count', 100)}
  />
);

export const withExtraText = () => (
  <Counter
    count={number('Count', 99)}
    color={select('Color', colors, 'neutral')}
    size={select('Size', sizes, 'medium')}
    maxCount={number('Maximum count', 100)}
  >
    Tasks
  </Counter>
);

withExtraText.story = {
  name: 'With extra text',
};

export const withTooltip = () => (
  <TooltippedCounter
    count={number('Count', 99)}
    color={select('Color', colors, 'neutral')}
    size={select('Size', sizes, 'medium')}
    maxCount={number('Maximum count', 100)}
    tooltip={<TextBody>I am the tooltip</TextBody>}
  >
    tasks
  </TooltippedCounter>
);

withTooltip.story = {
  name: 'With tooltip',
};
<commit_msg>Counter: add Figma designs<commit_after>import React from 'react';
import { addStoryInGroup, LOW_LEVEL_BLOCKS } from '../../../.storybook/utils';
import { number, select } from '@storybook/addon-knobs/react';
import { Counter, Tooltip, TextBody } from '../../index';

const colors = ['neutral', 'mint', 'aqua', 'violet', 'teal', 'gold', 'ruby'];
const sizes = ['small', 'medium'];

const TooltippedCounter = Tooltip(Counter);

export default {
  title: addStoryInGroup(LOW_LEVEL_BLOCKS, 'Counter'),

  parameters: {
    design: {
      type: 'figma',
      url: 'https://www.figma.com/file/LHH25GN90ljQaBEUNMsdJn/Desktop-components?node-id=246%3A985',
    },
  },
};

export const basic = () => (
  <Counter
    count={number('Count', 99)}
    color={select('Color', colors, 'neutral')}
    size={select('Size', sizes, 'medium')}
    maxCount={number('Maximum count', 100)}
  />
);

export const withExtraText = () => (
  <Counter
    count={number('Count', 99)}
    color={select('Color', colors, 'neutral')}
    size={select('Size', sizes, 'medium')}
    maxCount={number('Maximum count', 100)}
  >
    Tasks
  </Counter>
);

withExtraText.story = {
  name: 'With extra text',
};

export const withTooltip = () => (
  <TooltippedCounter
    count={number('Count', 99)}
    color={select('Color', colors, 'neutral')}
    size={select('Size', sizes, 'medium')}
    maxCount={number('Maximum count', 100)}
    tooltip={<TextBody>I am the tooltip</TextBody>}
  >
    tasks
  </TooltippedCounter>
);

withTooltip.story = {
  name: 'With tooltip',
};
<|endoftext|>


<commit_before>/**
* This file is part of taolin project (http://taolin.fbk.eu)
* Copyright (C) 2008, 2009 FBK Foundation, (http://www.fbk.eu)
* Authors: SoNet Group (see AUTHORS.txt)
*
* Taolin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation version 3 of the License.
*
* Taolin is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Taolin. If not, see <http://www.gnu.org/licenses/>.
*
*/

function openListHistory(cfg, logparams){

    var win = Ext.getCmp('list_history');

    if(win) // if exists
        win.close();

    new ListHistoryWindow(cfg, logparams); // Open a new comment window
}

ListHistoryWindow = function(cfg, logparams) {

    /*
    if (!logparams)
        alert('No logparams!');
    */
    var fm = Ext.util.Format
        ,t = this
        ,helpString = 'Past chats are stored by the chat server and are visible only to you. This feature has been requested by many champions and in fact this feature (chat history) is present in all web chat services (e.g. Google Mail chat). If you have any question about this feature, please contact us at ' + config.contactus;

    t.store = new Ext.data.SimpleStore({
      fields: ['with', 'start']
      ,data: cfg.chats
    });

    t.view = new Ext.DataView({
        store: t.store
        ,tpl: new Ext.XTemplate(
            '<tpl for=".">',
                '
',
                    '
',
                        '
',
                            '',
                              '{[this.cleardate(values.start)]} ({start})',
                            '	',
                        '
',
                    '
',
                '
',
            '</tpl>'
            ,{
                compiled: true
                ,cleardate: function(d){
                    var cd = d.replace('.000000Z','');
                    return Date.parseDate(cd, 'Y-m-d\T\H:i:s').format('F, d Y H:i');
                }
            }
        )
        ,emptyText: '
No chats with her/him
'
        ,loadingText: 'Loading...'
        ,itemSelector: '.chat_history_list_line'
        ,height: 300
    });

    var enablePrevious=true,
        enableNext=true;

    if (!cfg.index) {
      enablePrevious = false;
    }
    if (cfg.index+cfg.items >= cfg.count) {
      enableNext = false;
    }

    ListHistoryWindow.superclass.constructor.call(t, {
        title: 'Chats with '+cfg.user
        ,iconCls: 'chat'
        ,id: 'list_history'
        ,autoHeight: true
        ,width: 500
        ,resizable: true
        //,iconCls:'comment-icon'
        ,constrain: true
        ,items: [{
            html: '
' +
                    'What is this?' +
                '
' +
                '
' + helpString + '
' +
                '
Chats with '+cfg.prettyUser+'
'
            ,border: false
        },{
            items: t.view
            ,border: false
            ,autoScroll: true
        }]
        ,buttons: [{
            text:    'Previous'
            ,handler:function(){
                jabber.listHistory(cfg.user, null, cfg.first);
            }
            ,disabled: !enablePrevious
        },{
            text:    'Next'
            ,handler:function(){
                jabber.listHistory(cfg.user, cfg.last);
            }
            ,disabled: !enableNext
        },{
            text:    'Close'
            ,scope:  this
            ,handler:function(){
                this.close();
            }
        }]
        ,listeners: {
          afterrender: function(){
            $('#list_history .timeago').timeago();
          }
        }
    });

    t.show();
}

Ext.extend(ListHistoryWindow, Ext.Window);
<commit_msg>Solving a bug recently introduced<commit_after>/**
* This file is part of taolin project (http://taolin.fbk.eu)
* Copyright (C) 2008, 2009 FBK Foundation, (http://www.fbk.eu)
* Authors: SoNet Group (see AUTHORS.txt)
*
* Taolin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation version 3 of the License.
*
* Taolin is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Taolin. If not, see <http://www.gnu.org/licenses/>.
*
*/

function openListHistory(cfg, logparams){

    var win = Ext.getCmp('list_history');

    if(win) // if exists
        win.close();

    new ListHistoryWindow(cfg, logparams); // Open a new comment window
}

ListHistoryWindow = function(cfg, logparams) {

    /*
    if (!logparams)
        alert('No logparams!');
    */
    var fm = Ext.util.Format
        ,t = this
        ,helpString = 'Past chats are stored by the chat server and are visible only to you. This feature has been requested by many champions and in fact this feature (chat history) is present in all web chat services (e.g. Google Mail chat). If you have any question about this feature, please contact us at ' + config.contactus;

    cfg.prettyUser = Strophe.getBareJidFromJid(cfg.user);

    t.store = new Ext.data.SimpleStore({
      fields: ['with', 'start']
      ,data: cfg.chats
    });

    t.view = new Ext.DataView({
        store: t.store
        ,tpl: new Ext.XTemplate(
            '<tpl for=".">',
                '
',
                    '
',
                        '
',
                            '',
                              '{[this.cleardate(values.start)]} ({start})',
                            '	',
                        '
',
                    '
',
                '
',
            '</tpl>'
            ,{
                compiled: true
                ,cleardate: function(d){
                    var cd = d.replace('.000000Z','');
                    return Date.parseDate(cd, 'Y-m-d\T\H:i:s').format('F, d Y H:i');
                }
            }
        )
        ,emptyText: '
No chats with her/him
'
        ,loadingText: 'Loading...'
        ,itemSelector: '.chat_history_list_line'
        ,height: 300
    });

    var enablePrevious=true,
        enableNext=true;

    if (!cfg.index) {
      enablePrevious = false;
    }
    if (cfg.index+cfg.items >= cfg.count) {
      enableNext = false;
    }

    ListHistoryWindow.superclass.constructor.call(t, {
        title: 'Chats with '+cfg.user
        ,iconCls: 'chat'
        ,id: 'list_history'
        ,autoHeight: true
        ,width: 500
        ,resizable: true
        //,iconCls:'comment-icon'
        ,constrain: true
        ,items: [{
            html: '
' +
                    'What is this?' +
                '
' +
                '
' + helpString + '
' +
                '
Chats with '+cfg.prettyUser+'
'
            ,border: false
        },{
            items: t.view
            ,border: false
            ,autoScroll: true
        }]
        ,buttons: [{
            text:    'Previous'
            ,handler:function(){
                jabber.listHistory(cfg.user, null, cfg.first);
            }
            ,disabled: !enablePrevious
        },{
            text:    'Next'
            ,handler:function(){
                jabber.listHistory(cfg.user, cfg.last);
            }
            ,disabled: !enableNext
        },{
            text:    'Close'
            ,scope:  this
            ,handler:function(){
                this.close();
            }
        }]
        ,listeners: {
          afterrender: function(){
            $('#list_history .timeago').timeago();
          }
        }
    });

    t.show();
}

Ext.extend(ListHistoryWindow, Ext.Window);
<|endoftext|>


<commit_before>var http = require('http');
debugger;

var webServer = function(req,res) {

	res.writeHead(200, {'Content-Type': 'text/plain'});
	res.end('Hello my sweet!\n');
};

http.createServer(webServer).listen(4112,'127.0.0.1');
http.createServer(webServer).listen(4112,'192.168.1.104');

console.log('Server running at http://127.0.0.1:4112/');
<commit_msg>Added lodash with node install lodash. Appears in node_modules, which we do not need.<commit_after>var http = require('http');
var lodash = require('lodash');

var webServer = function(req,res) {

	res.writeHead(200, {'Content-Type': 'text/plain'});
	var nickname = lodash.without(['sweet','pumpkin'],'pumpkin');

	res.end('Hello my ' + nickname + '!\n');
};

http.createServer(webServer).listen(4112,'127.0.0.1');
http.createServer(webServer).listen(4112,'192.168.1.104');

console.log('Server running at http://127.0.0.1:4112/');
<|endoftext|>


<commit_before>_kiwi.view.Application = Backbone.View.extend({
    initialize: function () {
        var that = this;

        this.$el = $($('#tmpl_application').html().trim());
        this.el = this.$el[0];

        $(this.model.get('container') || 'body').append(this.$el);

        this.elements = {
            panels:        this.$el.find('.panels'),
            right_bar:     this.$el.find('.right_bar'),
            toolbar:       this.$el.find('.toolbar'),
            controlbox:    this.$el.find('.controlbox'),
            resize_handle: this.$el.find('.memberlists_resize_handle')
        };

        $(window).resize(function() { that.doLayout.apply(that); });
        this.elements.toolbar.resize(function() { that.doLayout.apply(that); });
        this.elements.controlbox.resize(function() { that.doLayout.apply(that); });

        // Change the theme when the config is changed
        _kiwi.global.settings.on('change:theme', this.updateTheme, this);
        this.updateTheme(getQueryVariable('theme'));

        _kiwi.global.settings.on('change:channel_list_style', this.setTabLayout, this);
        this.setTabLayout(_kiwi.global.settings.get('channel_list_style'));

        _kiwi.global.settings.on('change:show_timestamps', this.displayTimestamps, this);
        this.displayTimestamps(_kiwi.global.settings.get('show_timestamps'));

        this.$el.appendTo($('body'));
        this.doLayout();

        $(document).keydown(this.setKeyFocus);

        // Confirmation require to leave the page
        window.onbeforeunload = function () {
            if (_kiwi.gateway.isConnected()) {
                return _kiwi.global.i18n.translate('client_views_application_close_notice').fetch();
            }
        };

        // Keep tabs on the browser having focus
        this.has_focus = true;

        $(window).on('focus', function () {
            that.has_focus = true;
        });
        $(window).on('blur', function () {
            that.has_focus = false;
        });

        this.favicon = new _kiwi.view.Favicon();
        this.initSound();

        this.monitorPanelFallback();
    },

    updateTheme: function (theme_name) {
        // If called by the settings callback, get the correct new_value
        if (theme_name === _kiwi.global.settings) {
            theme_name = arguments[1];
        }

        // If we have no theme specified, get it from the settings
        if (!theme_name) theme_name = _kiwi.global.settings.get('theme') || 'relaxed';

        theme_name = theme_name.toLowerCase();

        // Clear any current theme
        $('[data-theme]:not([disabled])').each(function (idx, link) {
            var $link = $(link);
            $link.attr('rel', 'alternate ' + $link.attr('rel')).attr('disabled', true)[0].disabled = true;
        });

        // Apply the new theme
        var link = $('[data-theme][title=' + theme_name + ']');
        if (link.length > 0) {
            link.attr('rel', 'stylesheet').attr('disabled', false)[0].disabled = false;
        }

        this.doLayout();
    },

    setTabLayout: function (layout_style) {
        // If called by the settings callback, get the correct new_value
        if (layout_style === _kiwi.global.settings) {
            layout_style = arguments[1];
        }

        if (layout_style == 'list') {
            this.$el.addClass('chanlist_treeview');
        } else {
            this.$el.removeClass('chanlist_treeview');
        }

        this.doLayout();
    },

    displayTimestamps: function (show_timestamps) {
        // If called by the settings callback, get the correct new_value
        if (show_timestamps === _kiwi.global.settings) {
            show_timestamps = arguments[1];
        }

        if (show_timestamps) {
            this.$el.addClass('timestamps');
        } else {
            this.$el.removeClass('timestamps');
        }
    },

    // Globally shift focus to the command input box on a keypress
    setKeyFocus: function (ev) {
        // If we're copying text, don't shift focus
        if (ev.ctrlKey || ev.altKey || ev.metaKey) {
            return;
        }

        // If we're typing into an input box somewhere, ignore
        if ((ev.target.tagName.toLowerCase() === 'input') || (ev.target.tagName.toLowerCase() === 'textarea') || $(ev.target).attr('contenteditable')) {
            return;
        }

        $('#kiwi .controlbox .inp').focus();
    },

    doLayout: function () {
        var $kiwi = this.$el;
        var $panels = this.elements.panels;
        var $right_bar = this.elements.right_bar;
        var $toolbar = this.elements.toolbar;
        var $controlbox = this.elements.controlbox;
        var $resize_handle = this.elements.resize_handle;

        if (!$kiwi.is(':visible')) {
            return;
        }

        var css_heights = {
            top: $toolbar.outerHeight(true),
            bottom: $controlbox.outerHeight(true)
        };

        // If any elements are not visible, full size the panals instead
        if (!$toolbar.is(':visible')) {
            css_heights.top = 0;
        }

        if (!$controlbox.is(':visible')) {
            css_heights.bottom = 0;
        }

        // Apply the CSS sizes
        $panels.css(css_heights);
        $right_bar.css(css_heights);
        $resize_handle.css(css_heights);

        // If we have channel tabs on the side, adjust the height
        if ($kiwi.hasClass('chanlist_treeview')) {
            this.$el.find('.tabs', $kiwi).css(css_heights);
        }

        // Determine if we have a narrow window (mobile/tablet/or even small desktop window)
        if ($kiwi.outerWidth() < 420) {
            $kiwi.addClass('narrow');
            if (this.model.rightbar && this.model.rightbar.keep_hidden !== true)
                this.model.rightbar.toggle(true);
        } else {
            $kiwi.removeClass('narrow');
            if (this.model.rightbar && this.model.rightbar.keep_hidden !== false)
                this.model.rightbar.toggle(false);
        }

        // Set the panels width depending on the memberlist visibility
        if (!$right_bar.hasClass('disabled')) {
            // Panels to the side of the memberlist
            $panels.css('right', $right_bar.outerWidth(true));
            // The resize handle sits overlapping the panels and memberlist
            $resize_handle.css('left', $right_bar.position().left - ($resize_handle.outerWidth(true) / 2));
        } else {
            // Memberlist is hidden so panels to the right edge
            $panels.css('right', 0);
            // And move the handle just out of sight to the right
            $resize_handle.css('left', $panels.outerWidth(true));
        }

        var input_wrap_width = parseInt($controlbox.find('.input_tools').outerWidth(), 10);
        $controlbox.find('.input_wrap').css('right', input_wrap_width + 7);
    },

    alertWindow: function (title) {
        if (!this.alertWindowTimer) {
            this.alertWindowTimer = new (function () {
                var that = this;
                var tmr;
                var has_focus = true;
                var state = 0;
                var default_title = _kiwi.app.server_settings.client.window_title || 'Kiwi IRC';
                var title = 'Kiwi IRC';

                this.setTitle = function (new_title) {
                    new_title = new_title || default_title;
                    window.document.title = new_title;
                    return new_title;
                };

                this.start = function (new_title) {
                    // Don't alert if we already have focus
                    if (has_focus) return;

                    title = new_title;
                    if (tmr) return;
                    tmr = setInterval(this.update, 1000);
                };

                this.stop = function () {
                    // Stop the timer and clear the title
                    if (tmr) clearInterval(tmr);
                    tmr = null;
                    this.setTitle();

                    // Some browsers don't always update the last title correctly
                    // Wait a few seconds and then reset
                    setTimeout(this.reset, 2000);
                };

                this.reset = function () {
                    if (tmr) return;
                    that.setTitle();
                };

                this.update = function () {
                    if (state === 0) {
                        that.setTitle(title);
                        state = 1;
                    } else {
                        that.setTitle();
                        state = 0;
                    }
                };

                $(window).focus(function (event) {
                    has_focus = true;
                    that.stop();

                    // Some browsers don't always update the last title correctly
                    // Wait a few seconds and then reset
                    setTimeout(that.reset, 2000);
                });

                $(window).blur(function (event) {
                    has_focus = false;
                });
            })();
        }

        this.alertWindowTimer.start(title);
    },

    barsHide: function (instant) {
        var that = this;

        if (!instant) {
            this.$el.find('.toolbar').slideUp({queue: false, duration: 400, step: $.proxy(this.doLayout, this)});
            $('#kiwi .controlbox').slideUp({queue: false, duration: 400, step: $.proxy(this.doLayout, this)});
        } else {
            this.$el.find('.toolbar').slideUp(0);
            $('#kiwi .controlbox').slideUp(0);
            this.doLayout();
        }
    },

    barsShow: function (instant) {
        var that = this;

        if (!instant) {
            this.$el.find('.toolbar').slideDown({queue: false, duration: 400, step: $.proxy(this.doLayout, this)});
            $('#kiwi .controlbox').slideDown({queue: false, duration: 400, step: $.proxy(this.doLayout, this)});
        } else {
            this.$el.find('.toolbar').slideDown(0);
            $('#kiwi .controlbox').slideDown(0);
            this.doLayout();
        }
    },

    initSound: function () {
        var that = this,
            base_path = this.model.get('base_path');

        $script(base_path + '/assets/libs/soundmanager2/soundmanager2-nodebug-jsmin.js', function() {
            if (typeof soundManager === 'undefined')
                return;

            soundManager.setup({
                url: base_path + '/assets/libs/soundmanager2/',
                flashVersion: 9, // optional: shiny features (default = 8)// optional: ignore Flash where possible, use 100% HTML5 mode
                preferFlash: true,

                onready: function() {
                    that.sound_object = soundManager.createSound({
                        id: 'highlight',
                        url: base_path + '/assets/sound/highlight.mp3'
                    });
                }
            });
        });
    },

    playSound: function (sound_id) {
        if (!this.sound_object) return;

        if (_kiwi.global.settings.get('mute_sounds'))
            return;

        soundManager.play(sound_id);
    },

    showNotification: function(title, message) {
        var icon = this.model.get('base_path') + '/assets/img/ico.png',
            notification;

        if (this.has_focus)
            return;

        // Different versions of Chrome/firefox have different implimentations
        if ('Notification' in window && Notification.permission && Notification.permission === 'granted') {
            notification = new Notification(title, {icon: icon, body: message});

        } else if ('webkitNotifications' in window && webkitNotifications.checkPermission() === 0) {
            notification = window.webkitNotifications.createNotification(icon, title, message);

        } else if ('mozNotification' in navigator) {
            notification = navigator.mozNotification.createNotification(title, message, icon);
        }

        if (!notification) {
            // Couldn't find any notification support
            return;
        }

        setTimeout(function() {
            (notification.cancel || notification.close).call(notification);
        }, 5000);
    },

    monitorPanelFallback: function() {
        var panel_access = [];

        this.model.panels.on('active', function() {
            var panel = _kiwi.app.panels().active,
                panel_index;

            // If the panel is already open, remove it so we can put it back in first place
            panel_index = _.indexOf(panel_access, panel.cid);

            if (panel_index > -1) {
                panel_access.splice(panel_index, 1);
            }

            //Make this panel the most recently accessed
            panel_access.unshift(panel.cid);
        });

        this.model.panels.on('remove', function(panel) {
            // If closing the active panel, switch to the last-accessed panel
            if (panel_access[0] === panel.cid) {
                panel_access.shift();

                //Get the last-accessed panel model now that we removed the closed one
                var model = _.find(_kiwi.app.panels('applets').concat(_kiwi.app.panels('connections')), {cid: panel_access[0]});

                if (model) {
                    model.view.show();
                }
            }
        });
    }
});
<commit_msg>.touch css class when a touch event is seen<commit_after>_kiwi.view.Application = Backbone.View.extend({
    initialize: function () {
        var that = this;

        this.$el = $($('#tmpl_application').html().trim());
        this.el = this.$el[0];

        $(this.model.get('container') || 'body').append(this.$el);

        this.elements = {
            panels:        this.$el.find('.panels'),
            right_bar:     this.$el.find('.right_bar'),
            toolbar:       this.$el.find('.toolbar'),
            controlbox:    this.$el.find('.controlbox'),
            resize_handle: this.$el.find('.memberlists_resize_handle')
        };

        $(window).resize(function() { that.doLayout.apply(that); });
        this.elements.toolbar.resize(function() { that.doLayout.apply(that); });
        this.elements.controlbox.resize(function() { that.doLayout.apply(that); });

        // Change the theme when the config is changed
        _kiwi.global.settings.on('change:theme', this.updateTheme, this);
        this.updateTheme(getQueryVariable('theme'));

        _kiwi.global.settings.on('change:channel_list_style', this.setTabLayout, this);
        this.setTabLayout(_kiwi.global.settings.get('channel_list_style'));

        _kiwi.global.settings.on('change:show_timestamps', this.displayTimestamps, this);
        this.displayTimestamps(_kiwi.global.settings.get('show_timestamps'));

        this.$el.appendTo($('body'));
        this.doLayout();

        $(document).keydown(this.setKeyFocus);

        // Confirmation require to leave the page
        window.onbeforeunload = function () {
            if (_kiwi.gateway.isConnected()) {
                return _kiwi.global.i18n.translate('client_views_application_close_notice').fetch();
            }
        };

        // Keep tabs on the browser having focus
        this.has_focus = true;

        $(window).on('focus', function windowOnFocus() {
            that.has_focus = true;
        });
        $(window).on('blur', function windowOnBlur() {
            that.has_focus = false;
        });

        // If we get a touchstart event, make note of it so we know we're using a touchscreen
        $(window).on('touchstart', function windowOnTouchstart() {
            that.$el.addClass('touch');
            $(window).off('touchstart', windowOnTouchstart);
        });

        this.favicon = new _kiwi.view.Favicon();
        this.initSound();

        this.monitorPanelFallback();
    },

    updateTheme: function (theme_name) {
        // If called by the settings callback, get the correct new_value
        if (theme_name === _kiwi.global.settings) {
            theme_name = arguments[1];
        }

        // If we have no theme specified, get it from the settings
        if (!theme_name) theme_name = _kiwi.global.settings.get('theme') || 'relaxed';

        theme_name = theme_name.toLowerCase();

        // Clear any current theme
        $('[data-theme]:not([disabled])').each(function (idx, link) {
            var $link = $(link);
            $link.attr('rel', 'alternate ' + $link.attr('rel')).attr('disabled', true)[0].disabled = true;
        });

        // Apply the new theme
        var link = $('[data-theme][title=' + theme_name + ']');
        if (link.length > 0) {
            link.attr('rel', 'stylesheet').attr('disabled', false)[0].disabled = false;
        }

        this.doLayout();
    },

    setTabLayout: function (layout_style) {
        // If called by the settings callback, get the correct new_value
        if (layout_style === _kiwi.global.settings) {
            layout_style = arguments[1];
        }

        if (layout_style == 'list') {
            this.$el.addClass('chanlist_treeview');
        } else {
            this.$el.removeClass('chanlist_treeview');
        }

        this.doLayout();
    },

    displayTimestamps: function (show_timestamps) {
        // If called by the settings callback, get the correct new_value
        if (show_timestamps === _kiwi.global.settings) {
            show_timestamps = arguments[1];
        }

        if (show_timestamps) {
            this.$el.addClass('timestamps');
        } else {
            this.$el.removeClass('timestamps');
        }
    },

    // Globally shift focus to the command input box on a keypress
    setKeyFocus: function (ev) {
        // If we're copying text, don't shift focus
        if (ev.ctrlKey || ev.altKey || ev.metaKey) {
            return;
        }

        // If we're typing into an input box somewhere, ignore
        if ((ev.target.tagName.toLowerCase() === 'input') || (ev.target.tagName.toLowerCase() === 'textarea') || $(ev.target).attr('contenteditable')) {
            return;
        }

        $('#kiwi .controlbox .inp').focus();
    },

    doLayout: function () {
        var $kiwi = this.$el;
        var $panels = this.elements.panels;
        var $right_bar = this.elements.right_bar;
        var $toolbar = this.elements.toolbar;
        var $controlbox = this.elements.controlbox;
        var $resize_handle = this.elements.resize_handle;

        if (!$kiwi.is(':visible')) {
            return;
        }

        var css_heights = {
            top: $toolbar.outerHeight(true),
            bottom: $controlbox.outerHeight(true)
        };

        // If any elements are not visible, full size the panals instead
        if (!$toolbar.is(':visible')) {
            css_heights.top = 0;
        }

        if (!$controlbox.is(':visible')) {
            css_heights.bottom = 0;
        }

        // Apply the CSS sizes
        $panels.css(css_heights);
        $right_bar.css(css_heights);
        $resize_handle.css(css_heights);

        // If we have channel tabs on the side, adjust the height
        if ($kiwi.hasClass('chanlist_treeview')) {
            this.$el.find('.tabs', $kiwi).css(css_heights);
        }

        // Determine if we have a narrow window (mobile/tablet/or even small desktop window)
        if ($kiwi.outerWidth() < 420) {
            $kiwi.addClass('narrow');
            if (this.model.rightbar && this.model.rightbar.keep_hidden !== true)
                this.model.rightbar.toggle(true);
        } else {
            $kiwi.removeClass('narrow');
            if (this.model.rightbar && this.model.rightbar.keep_hidden !== false)
                this.model.rightbar.toggle(false);
        }

        // Set the panels width depending on the memberlist visibility
        if (!$right_bar.hasClass('disabled')) {
            // Panels to the side of the memberlist
            $panels.css('right', $right_bar.outerWidth(true));
            // The resize handle sits overlapping the panels and memberlist
            $resize_handle.css('left', $right_bar.position().left - ($resize_handle.outerWidth(true) / 2));
        } else {
            // Memberlist is hidden so panels to the right edge
            $panels.css('right', 0);
            // And move the handle just out of sight to the right
            $resize_handle.css('left', $panels.outerWidth(true));
        }

        var input_wrap_width = parseInt($controlbox.find('.input_tools').outerWidth(), 10);
        $controlbox.find('.input_wrap').css('right', input_wrap_width + 7);
    },

    alertWindow: function (title) {
        if (!this.alertWindowTimer) {
            this.alertWindowTimer = new (function () {
                var that = this;
                var tmr;
                var has_focus = true;
                var state = 0;
                var default_title = _kiwi.app.server_settings.client.window_title || 'Kiwi IRC';
                var title = 'Kiwi IRC';

                this.setTitle = function (new_title) {
                    new_title = new_title || default_title;
                    window.document.title = new_title;
                    return new_title;
                };

                this.start = function (new_title) {
                    // Don't alert if we already have focus
                    if (has_focus) return;

                    title = new_title;
                    if (tmr) return;
                    tmr = setInterval(this.update, 1000);
                };

                this.stop = function () {
                    // Stop the timer and clear the title
                    if (tmr) clearInterval(tmr);
                    tmr = null;
                    this.setTitle();

                    // Some browsers don't always update the last title correctly
                    // Wait a few seconds and then reset
                    setTimeout(this.reset, 2000);
                };

                this.reset = function () {
                    if (tmr) return;
                    that.setTitle();
                };

                this.update = function () {
                    if (state === 0) {
                        that.setTitle(title);
                        state = 1;
                    } else {
                        that.setTitle();
                        state = 0;
                    }
                };

                $(window).focus(function (event) {
                    has_focus = true;
                    that.stop();

                    // Some browsers don't always update the last title correctly
                    // Wait a few seconds and then reset
                    setTimeout(that.reset, 2000);
                });

                $(window).blur(function (event) {
                    has_focus = false;
                });
            })();
        }

        this.alertWindowTimer.start(title);
    },

    barsHide: function (instant) {
        var that = this;

        if (!instant) {
            this.$el.find('.toolbar').slideUp({queue: false, duration: 400, step: $.proxy(this.doLayout, this)});
            $('#kiwi .controlbox').slideUp({queue: false, duration: 400, step: $.proxy(this.doLayout, this)});
        } else {
            this.$el.find('.toolbar').slideUp(0);
            $('#kiwi .controlbox').slideUp(0);
            this.doLayout();
        }
    },

    barsShow: function (instant) {
        var that = this;

        if (!instant) {
            this.$el.find('.toolbar').slideDown({queue: false, duration: 400, step: $.proxy(this.doLayout, this)});
            $('#kiwi .controlbox').slideDown({queue: false, duration: 400, step: $.proxy(this.doLayout, this)});
        } else {
            this.$el.find('.toolbar').slideDown(0);
            $('#kiwi .controlbox').slideDown(0);
            this.doLayout();
        }
    },

    initSound: function () {
        var that = this,
            base_path = this.model.get('base_path');

        $script(base_path + '/assets/libs/soundmanager2/soundmanager2-nodebug-jsmin.js', function() {
            if (typeof soundManager === 'undefined')
                return;

            soundManager.setup({
                url: base_path + '/assets/libs/soundmanager2/',
                flashVersion: 9, // optional: shiny features (default = 8)// optional: ignore Flash where possible, use 100% HTML5 mode
                preferFlash: true,

                onready: function() {
                    that.sound_object = soundManager.createSound({
                        id: 'highlight',
                        url: base_path + '/assets/sound/highlight.mp3'
                    });
                }
            });
        });
    },

    playSound: function (sound_id) {
        if (!this.sound_object) return;

        if (_kiwi.global.settings.get('mute_sounds'))
            return;

        soundManager.play(sound_id);
    },

    showNotification: function(title, message) {
        var icon = this.model.get('base_path') + '/assets/img/ico.png',
            notification;

        if (this.has_focus)
            return;

        // Different versions of Chrome/firefox have different implimentations
        if ('Notification' in window && Notification.permission && Notification.permission === 'granted') {
            notification = new Notification(title, {icon: icon, body: message});

        } else if ('webkitNotifications' in window && webkitNotifications.checkPermission() === 0) {
            notification = window.webkitNotifications.createNotification(icon, title, message);

        } else if ('mozNotification' in navigator) {
            notification = navigator.mozNotification.createNotification(title, message, icon);
        }

        if (!notification) {
            // Couldn't find any notification support
            return;
        }

        setTimeout(function() {
            (notification.cancel || notification.close).call(notification);
        }, 5000);
    },

    monitorPanelFallback: function() {
        var panel_access = [];

        this.model.panels.on('active', function() {
            var panel = _kiwi.app.panels().active,
                panel_index;

            // If the panel is already open, remove it so we can put it back in first place
            panel_index = _.indexOf(panel_access, panel.cid);

            if (panel_index > -1) {
                panel_access.splice(panel_index, 1);
            }

            //Make this panel the most recently accessed
            panel_access.unshift(panel.cid);
        });

        this.model.panels.on('remove', function(panel) {
            // If closing the active panel, switch to the last-accessed panel
            if (panel_access[0] === panel.cid) {
                panel_access.shift();

                //Get the last-accessed panel model now that we removed the closed one
                var model = _.find(_kiwi.app.panels('applets').concat(_kiwi.app.panels('connections')), {cid: panel_access[0]});

                if (model) {
                    model.view.show();
                }
            }
        });
    }
});
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import wrapDisplayName from 'recompose/wrapDisplayName'

const startAnimationName = 'onAutofillStart'
const endAnimationName = 'onAutofillCancel'

const isWebkit = () => navigator.userAgent.indexOf('WebKit') !== -1

const emptyAnimation = animationName => {
  return `
    @keyframes ${animationName} {
      from {/**/}
      to {/**/}
    }
  `
}

const injectStyle = style => {
  const styleElement = document.createElement('style')

  document.head.appendChild(styleElement)

  let styleSheet = styleElement.sheet

  styleSheet.insertRule(style, styleSheet.cssRules.length)
}

function injectKeyFrames() {
  const autofillStartEmptyKeyframesStyle = emptyAnimation(startAnimationName)
  const autofillEndEmptyKeyframesStyle = emptyAnimation(endAnimationName)

  injectStyle(autofillStartEmptyKeyframesStyle)
  injectStyle(autofillEndEmptyKeyframesStyle)
}

function injectAutofillHook() {
  const autofillHook = `
    input:-webkit-autofill {
      // Expose a hook for JavaScript when autofill is shown.
      // JavaScript can capture 'animationstart' events
      animation-name: ${startAnimationName};

      // Make the backgound color become yellow _really slowly_
      transition: background-color 50000s ease-in-out 0s;
    }
  `

  const notAutofillHook = `
    input:not(:-webkit-autofill) {
      // Expose a hook for JavaScript when autofill is no longer shown.
      // JavaScript can capture 'animationstart' events
      animation-name: ${endAnimationName};
    }`

  injectStyle(autofillHook)
  injectStyle(notAutofillHook)
}

const registerAutofill = () => {
  const autofillInjected =
    window.__klarna_ui_components && window.__klarna_ui_components.isAutofillInjected

  if (!autofillInjected && isWebkit()) {
    injectKeyFrames()
    injectAutofillHook()

    if (window.__klarna_ui_components) {
      window.__klarna_ui_components.isAutofillInjected = true
    } else {
      window.__klarna_ui_components = { isAutofillInjected: true }
    }
  }
}

export default autofillProps => Target => {
  class WithAutofillProps extends Component {
    constructor() {
      super()

      registerAutofill()

      this.state = { autofill: false }
    }

    handleAnimation(animationName) {
      switch (animationName) {
        case startAnimationName:
          return this.setState({ autofill: true })

        case endAnimationName:
          return this.setState({ autofill: false })
      }
    }

    render() {
      const { autofill } = this.state

      return (
        <Target
          onAnimationStart={this.handleAnimation.bind(this)}
          {...this.props}
          {...autofill && autofillProps}
        />
      )
    }
  }

  WithAutofillProps.displayName = wrapDisplayName(Target, 'withAutofillProps')

  return WithAutofillProps
}
<commit_msg>create only one style element to inject to<commit_after>import React, { Component } from 'react'
import wrapDisplayName from 'recompose/wrapDisplayName'

const startAnimationName = 'onAutofillStart'
const endAnimationName = 'onAutofillCancel'
const styleElementId = 'autofill-style'

const isWebkit = () => navigator.userAgent.indexOf('WebKit') !== -1

const emptyAnimation = animationName => {
  return `
    @keyframes ${animationName} {
      from {/**/}
      to {/**/}
    }
  `
}

const injectStyle = style => {
  let styleElement = document.getElementById(styleElementId)

  if (!styleElement) {
    styleElement = document.createElement('style')
    styleElement.id = styleElementId
    document.head.appendChild(styleElement)
  }

  let styleSheet = styleElement.sheet

  styleSheet.insertRule(style, styleSheet.cssRules.length)
}

function injectKeyFrames() {
  const autofillStartEmptyKeyframesStyle = emptyAnimation(startAnimationName)
  const autofillEndEmptyKeyframesStyle = emptyAnimation(endAnimationName)

  injectStyle(autofillStartEmptyKeyframesStyle)
  injectStyle(autofillEndEmptyKeyframesStyle)
}

function injectAutofillHook() {
  const autofillHook = `
    input:-webkit-autofill {
      // Expose a hook for JavaScript when autofill is shown.
      // JavaScript can capture 'animationstart' events
      animation-name: ${startAnimationName};

      // Make the backgound color become yellow _really slowly_
      transition: background-color 50000s ease-in-out 0s;
    }
  `

  const notAutofillHook = `
    input:not(:-webkit-autofill) {
      // Expose a hook for JavaScript when autofill is no longer shown.
      // JavaScript can capture 'animationstart' events
      animation-name: ${endAnimationName};
    }`

  injectStyle(autofillHook)
  injectStyle(notAutofillHook)
}

const registerAutofill = () => {
  const autofillInjected =
    window.__klarna_ui_components && window.__klarna_ui_components.isAutofillInjected

  if (!autofillInjected && isWebkit()) {
    injectKeyFrames()
    injectAutofillHook()

    if (window.__klarna_ui_components) {
      window.__klarna_ui_components.isAutofillInjected = true
    } else {
      window.__klarna_ui_components = { isAutofillInjected: true }
    }
  }
}

export default autofillProps => Target => {
  class WithAutofillProps extends Component {
    constructor() {
      super()

      registerAutofill()

      this.state = { autofill: false }
    }

    handleAnimation(animationName) {
      switch (animationName) {
        case startAnimationName:
          return this.setState({ autofill: true })

        case endAnimationName:
          return this.setState({ autofill: false })
      }
    }

    render() {
      const { autofill } = this.state

      return (
        <Target
          onAnimationStart={this.handleAnimation.bind(this)}
          {...this.props}
          {...autofill && autofillProps}
        />
      )
    }
  }

  WithAutofillProps.displayName = wrapDisplayName(Target, 'withAutofillProps')

  return WithAutofillProps
}
<|endoftext|>


<commit_before>const GLTFParser = Hilo3d.GLTFParser;

describe('GLTFParser', () => {
    it('create', () => {
        const parser = new GLTFParser;
        parser.isGLTFParser.should.be.true();
        parser.className.should.equal('GLTFParser');
    });

    it('register & unregister ExtensionHandler', () => {
        const parser = new GLTFParser;
        should(parser.getExtensionHandler('hello')).be.undefined();

        GLTFParser.registerExtensionHandler('hello', {
            parse(){

            }
        });
        should(parser.getExtensionHandler('hello')).not.be.undefined();
        should(parser.getExtensionHandler('hello2')).be.undefined();

        GLTFParser.unregisterExtensionHandler('hello');
        should(parser.getExtensionHandler('hello')).be.undefined();
    });
});<commit_msg>test: update GLTFParser test<commit_after>const GLTFParser = Hilo3d.GLTFParser;

describe('GLTFParser', () => {
    it('create', () => {
        const parser = new GLTFParser;
        parser.isGLTFParser.should.be.true();
        parser.className.should.equal('GLTFParser');
    });

    it('register & unregister ExtensionHandler', () => {
        const parser = new GLTFParser;
        should(parser.getExtensionHandler('hello')).be.undefined();

        GLTFParser.registerExtensionHandler('hello', {
            parse() {

            }
        });
        should(parser.getExtensionHandler('hello')).not.be.undefined();
        should(parser.getExtensionHandler('hello2')).be.undefined();

        GLTFParser.unregisterExtensionHandler('hello');
        should(parser.getExtensionHandler('hello')).be.undefined();
    });

    it('getImageType', () => {
        const parser = new GLTFParser();
        parser.json = {
            images: [{
                mimeType: 'image/jpeg'
            }, {
                mimeType: 'image/ktx'
            }, {
                mimeType: 'image/hdr'
            }, {}, null]
        };
        parser.getImageType(0).should.equal('');
        parser.getImageType(1).should.equal('ktx');
        parser.getImageType(2).should.equal('');
        parser.getImageType(3).should.equal('');
        parser.getImageType(4).should.equal('');
    });
});<|endoftext|>


<commit_before>var url = "https://fathomless-spire-32996.herokuapp.com/trivia/";
// var url = "http://localhost:3000/trivia/";
var method = "GET";
var async = true;
var request = new XMLHttpRequest();

$(document).ready(function() {

    var rnd = randomIntFromInterval(1, 700);

    request.onload = function () {

        if (request.status === 200) {
            var results = JSON.parse(request.responseText);
            if (results) {
                console.log('Question found: ', results );

                $('#questionnumber').text(results.id);
                $('#category').text(results.category.length > 0 ? results.category : '-');
                $('#question').text(results.question);
                $('#answer').text(results.answer);

            // not found
            } else {

                console.log('Question NOT found')
                $('#question').text(rnd + ' Not Found');

            }

        } else {

            console.log('Question NOT found')
            $('#question').text(rnd + ' Not Found');
        }

    }

    console.log('requesting: ', url + rnd);

    request.open(method, url + rnd, async);
    request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    request.send('');

    function randomIntFromInterval(min,max) {
        return Math.floor(Math.random()*(max-min+1)+min);
    }
});

function submit() {

    var url = "http://localhost:3000/trivia/";
    var id = $('#questionnumber').text();
    var method = 'PUT';

    if (id === '') {
        method = 'POST';
    } else {
        url = url + id;
    }

    var payload = {
        category: $('#category').text(),
        question: $('#question').text(),
        answer: $('#answer').text()
    };

    var request = new XMLHttpRequest();
    request.open(method, url);
    request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    request.send(JSON.stringify(payload));
}
    <commit_msg>url for post<commit_after>var url = "https://fathomless-spire-32996.herokuapp.com/trivia/";
// var url = "http://localhost:3000/trivia/";
var method = "GET";
var async = true;
var request = new XMLHttpRequest();

$(document).ready(function() {

    var rnd = randomIntFromInterval(1, 700);

    request.onload = function () {

        if (request.status === 200) {
            var results = JSON.parse(request.responseText);
            if (results) {
                console.log('Question found: ', results );

                $('#questionnumber').text(results.id);
                $('#category').text(results.category.length > 0 ? results.category : '-');
                $('#question').text(results.question);
                $('#answer').text(results.answer);

            // not found
            } else {

                console.log('Question NOT found')
                $('#question').text(rnd + ' Not Found');

            }

        } else {

            console.log('Question NOT found')
            $('#question').text(rnd + ' Not Found');
        }

    }

    console.log('requesting: ', url + rnd);

    request.open(method, url + rnd, async);
    request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    request.send('');

    function randomIntFromInterval(min,max) {
        return Math.floor(Math.random()*(max-min+1)+min);
    }
});

function submit() {

    var id = $('#questionnumber').text();
    var method = 'PUT';

    if (id === '') {
        method = 'POST';
    } else {
        url = url + id;
    }

    var payload = {
        category: $('#category').text(),
        question: $('#question').text(),
        answer: $('#answer').text()
    };

    var request = new XMLHttpRequest();
    request.open(method, url);
    request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    request.send(JSON.stringify(payload));
}
    <|endoftext|>


<commit_before>import React from 'react';
import {observable, observe} from "mobx";
import {observer, inject} from 'mobx-react';
import {Link} from 'react-router-dom';
import loki from 'lokijs';
import Interactive from 'react-interactive';
import API from '../SpreadsheetData';
import {Loading} from '../Snippets';
import s from '../../styles/style';
import './packs.scss';

@inject((stores, props, context) => props) @observer
export default class PackSimulator extends React.Component {
  @observable loaded = false
  @observable cards = []
  @observable set = ""
  @observable packs = 1

  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);

    for(let i = 0; i < 9; i++) {
      this.cards.push(<div key={i} className="card" style={{backgroundImage: `url("${API.base_image+API.card_back}")`}}>
);
    }
  }

  render() {
    if (this.loaded == false) {
      API.LoadDB([{'cards': 'attacks'}, {'cards': 'battlegear'}, {'cards': 'creatures'}, {'cards': 'locations'}, {'cards': 'mugic'}])
      .then(() => {
        this.setupDB();
        this.loaded = true;
      });
      return (<Loading />);
    }

    let setsInput = [];
    let i = 1;
    for (const set in API.sets) {
      setsInput.push(<option key={i++} value={set}>{API.sets[set]}</option>);
      if (i>11) break;
    }

    return (

      <Interactive as={Link} {...s.link}
       to={`/EnterTheCode/`}>Enter The Code</Interactive>

      <form onSubmit={this.handleSubmit}>
        Packs:
          <input name="packs" type="number"
            value={this.packs}
            min="1" max="24"
            style={{width: "32px", padding: '0px'}}
            onChange={(e) => {if(e.target.value>24) e.target.value=24; this.handleChange(e)}} />

        <select name="set" value={this.set} onChange={this.handleChange}>
          <option defaultValue="selected" hidden style={{fontStyle: 'italic'}}>Select a Set</option>
          {setsInput}
        </select>

        <input disabled={!this.set} type="submit" value="Open Packs" />
      </form>

{this.cards}

);
  }

  handleChange(event) {
    const target = event.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name;
    this[name] = value;
  }

  handleSubmit(event) {
    event.preventDefault();
    event.stopPropagation();

    let cards = []; // Returned list of card divs
    let card_names = []; // Prevent duplicates in pack
    let key = 0; // React key iterator uniqueness

    let pview = this.filter.addDynamicView('set');

    const randomRare = () => {
      let randomNumber = Math.floor(Math.random() * 24) + 1;
      if (randomNumber == 24) return "Ultra Rare";
      else if (randomNumber % 3 == 0) return "Super Rare";
      else return "Rare";
    };

    const gendisp = (avg) => {
      let min = parseInt(avg) - 10;
      if (min < 0) min = 0;
      return (Math.floor(Math.random() * 5)) * 5 + min;
    }
    const geneng = (avg) => {
      let min = parseInt(avg) - 5;
      if (min < 0) min = 0;
      return (Math.floor(Math.random() * 3)) * 5 + min;
    }

    const gencard = (results, i) => {
      let id = Math.floor(Math.random() * results.length);
      let card = results[id];

      if (!card) {
        cards.push(<div key={i} className="card" style={{backgroundImage: `url("${API.base_image+API.card_back}")`}}>
);
        return;
      }

      if (card_names.indexOf(card.gsx$name) > -1 && card.gsx$exclusive.includes("Starter")) {
        return gencard(results, i);
      }
      card_names.push(card.gsx$name);

      if (card.gsx$type != "Creatures") {
        cards.push(<div key={key++} className="card" style={{backgroundImage: `url("${API.base_image + (card.gsx$image||API.card_back)}")`}}>
);
      }
      else {
        const courage = gendisp(card.gsx$courage);
        const power = gendisp(card.gsx$power);
        const wisdom = gendisp(card.gsx$wisdom);
        const speed = gendisp(card.gsx$speed);
        const energy = geneng(card.gsx$energy);
        cards.push(<div key={key++} className="card" style={{backgroundImage: `url("${API.base_image + (card.gsx$image||API.card_back)}")`}}>

            {courage}
            {power}
            {wisdom}
            {speed}
            {energy}

);
      }

    }

    const genrarity = (rarity, num) => {
      pview.applyFind({'gsx$set': this.set})
        .applyFind({'gsx$rarity': rarity});
      let results = pview.data();
      for (let i=0; i<num; i++) gencard(results, i);
      pview.removeFilters();
    }

    // AU sets have 6 common and 3 rare+
    // DOP to FUN had 4 common, 3 uncommon, 2 rare+
    // OP1 had 3 cards per pack, Premium Packs had 6 cards per pack.
    let newSets = ["AU", "FAS"];
    let weirdSets = ["OP1", "PE1"];

      for (let i = 0; i < this.packs; i++) {
        // Before AU sets
        if (newSets.indexOf(this.set) == -1 && weirdSets.indexOf(this.set) == -1) {
          genrarity('Common', 4);
          genrarity('Uncommon', 3);
          genrarity('Rare', 1);
          genrarity(randomRare(), 1);
        }
        // AU sets and after
        else if (weirdSets.indexOf(this.set) == -1) {
          genrarity('Common', 6);
          genrarity('Rare', 2);
          genrarity(randomRare(), 1);
        }
        else if (this.set === "OP1") {
          genrarity("Common", 2);
          let randomWeird = Math.floor(Math.random() * 75) + 1;
          let weirdRarity = "";
          if (randomWeird == 75)
            weirdRarity = "Ultra Rare";
          else if (randomWeird < 19)
            weirdRarity = "Super Rare";
          else if (randomWeird < 44)
            weirdRarity = "Rare";
          else
            weirdRarity = "Uncommon";
          genrarity(weirdRarity, 1);
        }
        else if (this.set === "PE1") {
          genrarity("Super Rare", 5);
          genrarity("Ultra Rare", 1);
        }
        card_names = [];
    }

    this.filter.removeDynamicView('set');

    this.cards = cards;
  }

  setupDB() {
    let filter = (new loki("filter.db")).addCollection('filter');

    // Sort data descending alphabetically
    var pview = filter.addDynamicView('alphabetical');
    pview.applySimpleSort('gsx$name');

    let temp;

    temp = API.cards.attacks.find();
    temp.forEach((v) => delete v.$loki);
    filter.insert(temp);

    temp = API.cards.battlegear.find();
    temp.forEach((v) => delete v.$loki);
    filter.insert(temp);

    temp = API.cards.creatures.find();
    temp.forEach((v) => delete v.$loki);
    filter.insert(temp);

    temp = API.cards.locations.find();
    temp.forEach((v) => delete v.$loki);
    filter.insert(temp);

    temp = API.cards.mugic.find();
    temp.forEach((v) => delete v.$loki);
    filter.insert(temp);

    this.filter = filter;
  }

}
<commit_msg>bracketed OP1 if/elses<commit_after>import React from 'react';
import {observable, observe} from "mobx";
import {observer, inject} from 'mobx-react';
import {Link} from 'react-router-dom';
import loki from 'lokijs';
import Interactive from 'react-interactive';
import API from '../SpreadsheetData';
import {Loading} from '../Snippets';
import s from '../../styles/style';
import './packs.scss';

@inject((stores, props, context) => props) @observer
export default class PackSimulator extends React.Component {
  @observable loaded = false
  @observable cards = []
  @observable set = ""
  @observable packs = 1

  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);

    for(let i = 0; i < 9; i++) {
      this.cards.push(<div key={i} className="card" style={{backgroundImage: `url("${API.base_image+API.card_back}")`}}>
);
    }
  }

  render() {
    if (this.loaded == false) {
      API.LoadDB([{'cards': 'attacks'}, {'cards': 'battlegear'}, {'cards': 'creatures'}, {'cards': 'locations'}, {'cards': 'mugic'}])
      .then(() => {
        this.setupDB();
        this.loaded = true;
      });
      return (<Loading />);
    }

    let setsInput = [];
    let i = 1;
    for (const set in API.sets) {
      setsInput.push(<option key={i++} value={set}>{API.sets[set]}</option>);
      if (i>11) break;
    }

    return (

      <Interactive as={Link} {...s.link}
       to={`/EnterTheCode/`}>Enter The Code</Interactive>

      <form onSubmit={this.handleSubmit}>
        Packs:
          <input name="packs" type="number"
            value={this.packs}
            min="1" max="24"
            style={{width: "32px", padding: '0px'}}
            onChange={(e) => {if(e.target.value>24) e.target.value=24; this.handleChange(e)}} />

        <select name="set" value={this.set} onChange={this.handleChange}>
          <option defaultValue="selected" hidden style={{fontStyle: 'italic'}}>Select a Set</option>
          {setsInput}
        </select>

        <input disabled={!this.set} type="submit" value="Open Packs" />
      </form>

{this.cards}

);
  }

  handleChange(event) {
    const target = event.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name;
    this[name] = value;
  }

  handleSubmit(event) {
    event.preventDefault();
    event.stopPropagation();

    let cards = []; // Returned list of card divs
    let card_names = []; // Prevent duplicates in pack
    let key = 0; // React key iterator uniqueness

    let pview = this.filter.addDynamicView('set');

    const randomRare = () => {
      let randomNumber = Math.floor(Math.random() * 24) + 1;
      if (randomNumber == 24) return "Ultra Rare";
      else if (randomNumber % 3 == 0) return "Super Rare";
      else return "Rare";
    };

    const gendisp = (avg) => {
      let min = parseInt(avg) - 10;
      if (min < 0) min = 0;
      return (Math.floor(Math.random() * 5)) * 5 + min;
    }
    const geneng = (avg) => {
      let min = parseInt(avg) - 5;
      if (min < 0) min = 0;
      return (Math.floor(Math.random() * 3)) * 5 + min;
    }

    const gencard = (results, i) => {
      let id = Math.floor(Math.random() * results.length);
      let card = results[id];

      if (!card) {
        cards.push(<div key={i} className="card" style={{backgroundImage: `url("${API.base_image+API.card_back}")`}}>
);
        return;
      }

      if (card_names.indexOf(card.gsx$name) > -1 && card.gsx$exclusive.includes("Starter")) {
        return gencard(results, i);
      }
      card_names.push(card.gsx$name);

      if (card.gsx$type != "Creatures") {
        cards.push(<div key={key++} className="card" style={{backgroundImage: `url("${API.base_image + (card.gsx$image||API.card_back)}")`}}>
);
      }
      else {
        const courage = gendisp(card.gsx$courage);
        const power = gendisp(card.gsx$power);
        const wisdom = gendisp(card.gsx$wisdom);
        const speed = gendisp(card.gsx$speed);
        const energy = geneng(card.gsx$energy);
        cards.push(<div key={key++} className="card" style={{backgroundImage: `url("${API.base_image + (card.gsx$image||API.card_back)}")`}}>

            {courage}
            {power}
            {wisdom}
            {speed}
            {energy}

);
      }

    }

    const genrarity = (rarity, num) => {
      pview.applyFind({'gsx$set': this.set})
        .applyFind({'gsx$rarity': rarity});
      let results = pview.data();
      for (let i=0; i<num; i++) gencard(results, i);
      pview.removeFilters();
    }

    // AU sets have 6 common and 3 rare+
    // DOP to FUN had 4 common, 3 uncommon, 2 rare+
    // OP1 had 3 cards per pack, Premium Packs had 6 cards per pack.
    let newSets = ["AU", "FAS"];
    let weirdSets = ["OP1", "PE1"];

      for (let i = 0; i < this.packs; i++) {
        // Before AU sets
        if (newSets.indexOf(this.set) == -1 && weirdSets.indexOf(this.set) == -1) {
          genrarity('Common', 4);
          genrarity('Uncommon', 3);
          genrarity('Rare', 1);
          genrarity(randomRare(), 1);
        }
        // AU sets and after
        else if (weirdSets.indexOf(this.set) == -1) {
          genrarity('Common', 6);
          genrarity('Rare', 2);
          genrarity(randomRare(), 1);
        }
        else if (this.set === "OP1") {
          genrarity("Common", 2);
          let randomWeird = Math.floor(Math.random() * 75) + 1;
          let weirdRarity = "";
          if (randomWeird == 75) {
            weirdRarity = "Ultra Rare";
          }
          else if (randomWeird < 19) {
            weirdRarity = "Super Rare";
          }
          else if (randomWeird < 44) {
            weirdRarity = "Rare";
          }
          else {
            weirdRarity = "Uncommon";
          }
          genrarity(weirdRarity, 1);
        }
        else if (this.set === "PE1") {
          genrarity("Super Rare", 5);
          genrarity("Ultra Rare", 1);
        }
        card_names = [];
    }

    this.filter.removeDynamicView('set');

    this.cards = cards;
  }

  setupDB() {
    let filter = (new loki("filter.db")).addCollection('filter');

    // Sort data descending alphabetically
    var pview = filter.addDynamicView('alphabetical');
    pview.applySimpleSort('gsx$name');

    let temp;

    temp = API.cards.attacks.find();
    temp.forEach((v) => delete v.$loki);
    filter.insert(temp);

    temp = API.cards.battlegear.find();
    temp.forEach((v) => delete v.$loki);
    filter.insert(temp);

    temp = API.cards.creatures.find();
    temp.forEach((v) => delete v.$loki);
    filter.insert(temp);

    temp = API.cards.locations.find();
    temp.forEach((v) => delete v.$loki);
    filter.insert(temp);

    temp = API.cards.mugic.find();
    temp.forEach((v) => delete v.$loki);
    filter.insert(temp);

    this.filter = filter;
  }

}
<|endoftext|>