<commit_before>var invariant = require('react/lib/invariant');
var RouteHandler = require('./RouteHandler');

var Configuration = {

  getDefaultProps() {
    return {
      handler: RouteHandler
    };
  },

  render() {
    invariant(
      false,
      '%s elements are for router configuration only and should not be rendered',
      this.constructor.displayName
    );
  }

};

module.exports = Configuration;
<commit_msg>Fix require path<commit_after>var invariant = require('react/lib/invariant');
var RouteHandler = require('./components/RouteHandler');

var Configuration = {

  getDefaultProps() {
    return {
      handler: RouteHandler
    };
  },

  render() {
    invariant(
      false,
      '%s elements are for router configuration only and should not be rendered',
      this.constructor.displayName
    );
  }

};

module.exports = Configuration;
<|endoftext|>


<commit_before>var delete_contact = function(id) {
    Hm_Ajax.request(
        [{'name': 'hm_ajax_hook', 'value': 'ajax_delete_contact'},
        {'name': 'contact_id', 'value': id}],
        function(res) { $('.contact_row_'+id).remove(); }
    );
};

var add_contact_from_message_view = function() {
    var contact = $('#add_contact').val();
    if (contact) {
        Hm_Ajax.request(
            [{'name': 'hm_ajax_hook', 'value': 'ajax_add_contact'},
            {'name': 'contact_value', 'value': contact}],
            function(res) { $('.add_contact_controls').toggle(); }
        );
    }
};

var autocomplete_contact = function(e, class_name, list_div) {
    var key_code = e.keyCode;
    if (key_code >= 37 && key_code <= 40) {
        return;
    }
    var div = $('

');
    var fld_val = $(class_name).val();
    var addresses = fld_val.split(' ');
    var first = '';
    if (addresses.length > 1) {
        fld_val = addresses.pop();
    }
    if (fld_val.length > 2) {
        Hm_Ajax.request(
            [{'name': 'hm_ajax_hook', 'value': 'ajax_autocomplete_contact'},
            {'name': 'contact_value', 'value': fld_val}],
            function(res) {
                if (res.contact_suggestions) {
                    var i;
                    var count = 0;
                    $(list_div).html('');
                    for (i in res.contact_suggestions) {
                        div.html(res.contact_suggestions[i]);
                        if ($(class_name).val().match(div.text())) {
                            continue;
                        }
                        if (count == 0) {
                            first = 'first ';
                        }
                        else {
                            first = '';
                        }
                        count++;
                        $(list_div).append(''+res.contact_suggestions[i]+'');
                    }
                    if (count > 0) {
                        $(list_div).show();
                        setup_autocomplete_events(class_name, list_div, fld_val);
                    }
                }
            }
        );
    }
};

var autocomplete_keyboard_nav = function(event, list_div, class_name, fld_val) {
    var in_list = false;
    if (event.keyCode == 40) {
        if ($(event.target).prop('nodeName') == 'INPUT') {
            $('.first').addClass('selected_menu');
            $('.first').focus();
            in_list = true;
        }
        else {
            $(event.target).removeClass('selected_menu');
            $(event.target).next().addClass('selected_menu');
            $(event.target).next().focus();
            in_list = true;
        }
        return false;
    }
    else if (event.keyCode == 38) {
        if ($(event.target).prev().length) {
            $(event.target).removeClass('selected_menu');
            $(event.target).prev().addClass('selected_menu');
            $(event.target).prev().focus();
            in_list = true;
        }
        else {
            $(class_name).focus();
            $(event.target).removeClass('selected_menu');
        }
        return false;
    }
    else if (event.keyCode == 13) {
        $(class_name).focus();
        $(list_div).hide();
        add_autocomplete(event, class_name, list_div, fld_val);
        return false;
    }
    else if (event.keyCode == 27) {
        $(list_div).html('');
        $(list_div).hide();
        $(class_name).focus();
        return false;
    }
    if (in_list) {
        return false;
    }
    return true;
};

var setup_autocomplete_events = function(class_name, list_div, fld_val) {
    $('.contact_suggestion').click(function() { return add_autocomplete(event, class_name, list_div, fld_val); });
    $(class_name).keydown(function(event) { return autocomplete_keyboard_nav(event, list_div, class_name, fld_val); });
    $('.contact_suggestion').keydown(function(event) { return autocomplete_keyboard_nav(event, list_div, class_name, fld_val); });
    $(document).click(function() { $(list_div).hide(); });
};

var add_autocomplete = function(event, class_name, list_div, fld_val) {
    var new_address = $(event.target).text()
    var existing = $(class_name).val();
    var re = new RegExp(fld_val+'$');
    existing = existing.replace(re, '');
    if (existing.length) {
        existing = existing.replace(/[\s,]+$/, '')+', ';
    }
    $(list_div).html('');
    $(list_div).hide();
    $(class_name).val(existing+new_address);
    $(class_name).focus();
    return false;
};

if (hm_page_name() == 'contacts') {
    $('.delete_contact').click(function() {
        delete_contact($(this).data('id'));
    });
    $('.reset_contact').click(function() {
        window.location.href = '?page=contacts';
    });
}
else if (hm_page_name() == 'compose') {
    $('.compose_to').keyup(function(e) { autocomplete_contact(e, '.compose_to', '#to_contacts'); });
    $('.compose_cc').keyup(function(e) { autocomplete_contact(e, '.compose_cc', '#cc_contacts'); });
    $('.compose_bcc').keyup(function(e) { autocomplete_contact(e, '.compose_bcc', '#bcc_contacts'); });
    $('.compose_to').focus();
}
<commit_msg>allow auto-complete to kick in sooner<commit_after>var delete_contact = function(id) {
    Hm_Ajax.request(
        [{'name': 'hm_ajax_hook', 'value': 'ajax_delete_contact'},
        {'name': 'contact_id', 'value': id}],
        function(res) { $('.contact_row_'+id).remove(); }
    );
};

var add_contact_from_message_view = function() {
    var contact = $('#add_contact').val();
    if (contact) {
        Hm_Ajax.request(
            [{'name': 'hm_ajax_hook', 'value': 'ajax_add_contact'},
            {'name': 'contact_value', 'value': contact}],
            function(res) { $('.add_contact_controls').toggle(); }
        );
    }
};

var autocomplete_contact = function(e, class_name, list_div) {
    var key_code = e.keyCode;
    if (key_code >= 37 && key_code <= 40) {
        return;
    }
    var div = $('

');
    var fld_val = $(class_name).val();
    var addresses = fld_val.split(' ');
    var first = '';
    if (addresses.length > 1) {
        fld_val = addresses.pop();
    }
    if (fld_val.length > 0) {
        Hm_Ajax.request(
            [{'name': 'hm_ajax_hook', 'value': 'ajax_autocomplete_contact'},
            {'name': 'contact_value', 'value': fld_val}],
            function(res) {
                if (res.contact_suggestions) {
                    var i;
                    var count = 0;
                    $(list_div).html('');
                    for (i in res.contact_suggestions) {
                        div.html(res.contact_suggestions[i]);
                        if ($(class_name).val().match(div.text())) {
                            continue;
                        }
                        if (count == 0) {
                            first = 'first ';
                        }
                        else {
                            first = '';
                        }
                        count++;
                        $(list_div).append(''+res.contact_suggestions[i]+'');
                    }
                    if (count > 0) {
                        $(list_div).show();
                        setup_autocomplete_events(class_name, list_div, fld_val);
                    }
                }
            }
        );
    }
};

var autocomplete_keyboard_nav = function(event, list_div, class_name, fld_val) {
    var in_list = false;
    if (event.keyCode == 40) {
        if ($(event.target).prop('nodeName') == 'INPUT') {
            $('.first').addClass('selected_menu');
            $('.first').focus();
            in_list = true;
        }
        else {
            $(event.target).removeClass('selected_menu');
            $(event.target).next().addClass('selected_menu');
            $(event.target).next().focus();
            in_list = true;
        }
        return false;
    }
    else if (event.keyCode == 38) {
        if ($(event.target).prev().length) {
            $(event.target).removeClass('selected_menu');
            $(event.target).prev().addClass('selected_menu');
            $(event.target).prev().focus();
            in_list = true;
        }
        else {
            $(class_name).focus();
            $(event.target).removeClass('selected_menu');
        }
        return false;
    }
    else if (event.keyCode == 13) {
        $(class_name).focus();
        $(list_div).hide();
        add_autocomplete(event, class_name, list_div, fld_val);
        return false;
    }
    else if (event.keyCode == 27) {
        $(list_div).html('');
        $(list_div).hide();
        $(class_name).focus();
        return false;
    }
    if (in_list) {
        return false;
    }
    return true;
};

var setup_autocomplete_events = function(class_name, list_div, fld_val) {
    $('.contact_suggestion').click(function() { return add_autocomplete(event, class_name, list_div, fld_val); });
    $(class_name).keydown(function(event) { return autocomplete_keyboard_nav(event, list_div, class_name, fld_val); });
    $('.contact_suggestion').keydown(function(event) { return autocomplete_keyboard_nav(event, list_div, class_name, fld_val); });
    $(document).click(function() { $(list_div).hide(); });
};

var add_autocomplete = function(event, class_name, list_div, fld_val) {
    var new_address = $(event.target).text()
    var existing = $(class_name).val();
    var re = new RegExp(fld_val+'$');
    existing = existing.replace(re, '');
    if (existing.length) {
        existing = existing.replace(/[\s,]+$/, '')+', ';
    }
    $(list_div).html('');
    $(list_div).hide();
    $(class_name).val(existing+new_address);
    $(class_name).focus();
    return false;
};

if (hm_page_name() == 'contacts') {
    $('.delete_contact').click(function() {
        delete_contact($(this).data('id'));
    });
    $('.reset_contact').click(function() {
        window.location.href = '?page=contacts';
    });
}
else if (hm_page_name() == 'compose') {
    $('.compose_to').keyup(function(e) { autocomplete_contact(e, '.compose_to', '#to_contacts'); });
    $('.compose_cc').keyup(function(e) { autocomplete_contact(e, '.compose_cc', '#cc_contacts'); });
    $('.compose_bcc').keyup(function(e) { autocomplete_contact(e, '.compose_bcc', '#bcc_contacts'); });
    $('.compose_to').focus();
}
<|endoftext|>


<commit_before>import invariant from 'invariant';
import deepEqual from 'deep-equal';
import { PUSH, REPLACE } from './Actions';
import createLocation from './createLocation';

function createRandomKey(length) {
  return Math.random().toString(36).substr(2, length);
}

function locationsAreEqual(a, b) {
  return a.pathname === b.pathname &&
    a.search === b.search &&
    //a.action === b.action && // Different action !== location change.
    a.key === b.key &&
    deepEqual(a.state, b.state);
}

var DefaultKeyLength = 6;

function createHistory(options={}) {
  var { getCurrentLocation, finishTransition, cancelTransition, go, keyLength, getUserConfirmation } = options;

  if (typeof keyLength !== 'number')
    keyLength = DefaultKeyLength;

  var transitionHooks = [];
  var changeListeners = [];
  var location;

  function updateLocation(newLocation) {
    location = newLocation;

    changeListeners.forEach(function (listener) {
      listener(location);
    });
  }

  function addChangeListener(listener) {
    changeListeners.push(listener);
  }

  function removeChangeListener(listener) {
    changeListeners = changeListeners.filter(item => item !== listener);
  }

  function listen(listener) {
    addChangeListener(listener);

    if (location) {
      listener(location);
    } else {
      updateLocation(getCurrentLocation());
    }

    return function () {
      removeChangeListener(listener);
    };
  }

  function registerTransitionHook(hook) {
    if (transitionHooks.indexOf(hook) === -1)
      transitionHooks.push(hook);
  }

  function unregisterTransitionHook(hook) {
    transitionHooks = transitionHooks.filter(item => item !== hook);
  }

  function getTransitionConfirmationMessage() {
    var message = null;

    for (var i = 0, len = transitionHooks.length; i < len && message == null; ++i)
      message = transitionHooks[i].call(this);

    return message;
  }

  function confirmTransition(callback) {
    var message = getTransitionConfirmationMessage();

    if (getUserConfirmation && typeof message === 'string') {
      getUserConfirmation(message, function (ok) {
        callback(ok !== false);
      });
    } else {
      callback(message !== false);
    }
  }

  var pendingLocation;

  function transitionTo(nextLocation) {
    if (location && locationsAreEqual(location, nextLocation))
      return; // Nothing to do.

    invariant(
      pendingLocation == null,
      'transitionTo: Another transition is already in progress'
    );

    pendingLocation = nextLocation;

    confirmTransition(function (ok) {
      pendingLocation = null;

      if (ok) {
        finishTransition(nextLocation);
        updateLocation(nextLocation);
      } else if (cancelTransition) {
        cancelTransition(nextLocation);
      }
    });
  }

  function pushState(state, path) {
    transitionTo(
      createLocation(path, state, PUSH, createKey())
    );
  }

  function replaceState(state, path) {
    transitionTo(
      createLocation(path, state, REPLACE, createKey())
    );
  }

  function goBack() {
    go(-1);
  }

  function goForward() {
    go(1);
  }

  function createKey() {
    return createRandomKey(keyLength);
  }

  function createHref(path) {
    return path;
  }

  return {
    listen,
    registerTransitionHook,
    unregisterTransitionHook,
    getTransitionConfirmationMessage,
    transitionTo,
    pushState,
    replaceState,
    go,
    goBack,
    goForward,
    createKey,
    createHref
  };
}

export default createHistory;
<commit_msg>Add location.key to initial POP event. Closes #9<commit_after>import invariant from 'invariant';
import deepEqual from 'deep-equal';
import { PUSH, REPLACE, POP } from './Actions';
import createLocation from './createLocation';

function createRandomKey(length) {
  return Math.random().toString(36).substr(2, length);
}

function locationsAreEqual(a, b) {
  return a.pathname === b.pathname &&
    a.search === b.search &&
    //a.action === b.action && // Different action !== location change.
    a.key === b.key &&
    deepEqual(a.state, b.state);
}

var DefaultKeyLength = 6;

function createHistory(options={}) {
  var { getCurrentLocation, finishTransition, cancelTransition, go, keyLength, getUserConfirmation } = options;

  if (typeof keyLength !== 'number')
    keyLength = DefaultKeyLength;

  var transitionHooks = [];
  var changeListeners = [];
  var location;

  function updateLocation(newLocation) {
    // if previous location is unknown, we are probably replacing on initial load
    if (!location) {
      location = { ...newLocation, action: POP };
    } else {
      location = newLocation;
    }

    changeListeners.forEach(function (listener) {
      listener(location);
    });
  }

  function addChangeListener(listener) {
    changeListeners.push(listener);
  }

  function removeChangeListener(listener) {
    changeListeners = changeListeners.filter(item => item !== listener);
  }

  function listen(listener) {
    addChangeListener(listener);

    if (location) {
      listener(location);
    } else {
      var locationReplacement = getCurrentLocation();
      replaceState(locationReplacement.state, locationReplacement.pathname + locationReplacement.search);
      //updateLocation(getCurrentLocation());
    }

    return function () {
      removeChangeListener(listener);
    };
  }

  function registerTransitionHook(hook) {
    if (transitionHooks.indexOf(hook) === -1)
      transitionHooks.push(hook);
  }

  function unregisterTransitionHook(hook) {
    transitionHooks = transitionHooks.filter(item => item !== hook);
  }

  function getTransitionConfirmationMessage() {
    var message = null;

    for (var i = 0, len = transitionHooks.length; i < len && message == null; ++i)
      message = transitionHooks[i].call(this);

    return message;
  }

  function confirmTransition(callback) {
    var message = getTransitionConfirmationMessage();

    if (getUserConfirmation && typeof message === 'string') {
      getUserConfirmation(message, function (ok) {
        callback(ok !== false);
      });
    } else {
      callback(message !== false);
    }
  }

  var pendingLocation;

  function transitionTo(nextLocation) {
    if (location && locationsAreEqual(location, nextLocation))
      return; // Nothing to do.

    invariant(
      pendingLocation == null,
      'transitionTo: Another transition is already in progress'
    );

    pendingLocation = nextLocation;

    confirmTransition(function (ok) {
      pendingLocation = null;

      if (ok) {
        finishTransition(nextLocation);
        updateLocation(nextLocation);
      } else if (cancelTransition) {
        cancelTransition(nextLocation);
      }
    });
  }

  function pushState(state, path) {
    transitionTo(
      createLocation(path, state, PUSH, createKey())
    );
  }

  function replaceState(state, path) {
    transitionTo(
      createLocation(path, state, REPLACE, createKey())
    );
  }

  function goBack() {
    go(-1);
  }

  function goForward() {
    go(1);
  }

  function createKey() {
    return createRandomKey(keyLength);
  }

  function createHref(path) {
    return path;
  }

  return {
    listen,
    registerTransitionHook,
    unregisterTransitionHook,
    getTransitionConfirmationMessage,
    transitionTo,
    pushState,
    replaceState,
    go,
    goBack,
    goForward,
    createKey,
    createHref
  };
}

export default createHistory;
<|endoftext|>


<commit_before>var request = require('request');
var exec = require('child_process').exec;

var bot = null;
var lastSyncTime = 0;

exports.init = function(bot_obj) {
    bot = bot_obj;

    bot.slack.on('message', slack_on_message);
}

function slack_on_message(message) {
    if(message.type != 'message') return;

    var channel = bot.slack.getChannelGroupOrDMByID(message.channel);
    if(message.text && message.text.indexOf('!deploy') === 0) {
        var time = new Date().getTime();
        if(time-10000 < lastSyncTime) {
            channel.send('Deploy는 너무 자주 사용할 수 없습니다.');
            return;
        }
        lastSyncTime = time;
        exec('git rev-parse --verify HEAD', function (error, oldver, stderr) {
            channel.send('현재 버전: ' + oldver);
            exec('git pull', function (err, stdout, stderr) {
                channel.send('```\n' + stdout + '\n```');
                exec('git rev-parse --verify HEAD', function (error, newver, stderr) {
                    if(newver != oldver) {
                        channel.send('신규 버전: ' + newver);
                        channel.send('서버 갱신을 시작합니다.');
                        setTimeout(function() {
                            var process = require('process');
                            process.exit(0);
                        }, 1500);
                    } else {
                        channel.send('가장 최신 버전입니다.');
                        //도배 방지
                        lastSyncTime += 30000;
                    }
                });
            });
        });
    }
}

<commit_msg>deploy 모듈 process 종료 수정 #3<commit_after>var request = require('request');
var exec = require('child_process').exec;

var bot = null;
var lastSyncTime = 0;

exports.init = function(bot_obj) {
    bot = bot_obj;

    bot.slack.on('message', slack_on_message);
}

function slack_on_message(message) {
    if(message.type != 'message') return;

    var channel = bot.slack.getChannelGroupOrDMByID(message.channel);
    if(message.text && message.text.indexOf('!deploy') === 0) {
        var time = new Date().getTime();
        if(time-10000 < lastSyncTime) {
            channel.send('Deploy는 너무 자주 사용할 수 없습니다.');
            return;
        }
        lastSyncTime = time;
        exec('git rev-parse --verify HEAD', function (error, oldver, stderr) {
            channel.send('현재 버전: ' + oldver);
            exec('git pull', function (err, stdout, stderr) {
                channel.send('```\n' + stdout + '\n```');
                exec('git rev-parse --verify HEAD', function (error, newver, stderr) {
                    if(newver != oldver) {
                        channel.send('신규 버전: ' + newver);
                        channel.send('서버 갱신을 시작합니다.');
                        setTimeout(function() {
                            process.exit(0);
                        }, 1500);
                    } else {
                        channel.send('가장 최신 버전입니다.');
                        //도배 방지
                        lastSyncTime += 30000;
                    }
                });
            });
        });
    }
}

<|endoftext|>


<commit_before>/* eslint-disable no-jquery/no-global-selector */
( function () {
	'use strict';

	// Remove ?markasread=XYZ from the URL
	var uri = new mw.Uri();
	if ( uri.query.markasread !== undefined ) {
		delete uri.query.markasread;
		delete uri.query.markasreadwiki;
		window.history.replaceState( null, document.title, uri );
	}

	mw.echo = mw.echo || {};
	mw.echo.config = mw.echo.config || {};
	// Set default max prioritized action links per item
	mw.echo.config.maxPrioritizedActions = 2;

	// Activate ooui
	$( function () {
		var selectedWidget,
			echoApi,
			messageController,
			alertController,
			messageModelManager,
			alertModelManager,
			unreadMessageCounter,
			unreadAlertCounter,
			maxNotificationCount = require( './config.json' ).EchoMaxNotificationCount,
			pollingRate = require( './config.json' ).EchoPollForUpdates,
			documentTitle = document.title,
			$existingAlertLink = $( '#pt-notifications-alert a' ),
			$existingMessageLink = $( '#pt-notifications-notice a' ),
			numAlerts = $existingAlertLink.attr( 'data-counter-num' ),
			numMessages = $existingMessageLink.attr( 'data-counter-num' ),
			badgeLabelAlerts = $existingAlertLink.attr( 'data-counter-text' ),
			badgeLabelMessages = $existingMessageLink.attr( 'data-counter-text' ),
			hasUnseenAlerts = $existingAlertLink.hasClass( 'mw-echo-unseen-notifications' ),
			hasUnseenMessages = $existingMessageLink.hasClass( 'mw-echo-unseen-notifications' ),
			// latestMessageNotifTime is the time of most recent notification that came when we called showNotificationSnippet last
			// the function showNotificationSnippet returns the time of the latest notification and latestMessageNotifTime is updated
			latestMessageNotifTime = new Date(),
			latestAlertNotifTime = new Date(),
			alertCount = parseInt( numAlerts ),
			messageCount = parseInt( numMessages ),
			loadingPromise = null,
			// Store links
			links = {
				notifications: $existingAlertLink.attr( 'href' ) || mw.util.getUrl( 'Special:Notifications' ),
				preferences: ( $( '#pt-preferences a' ).attr( 'href' ) || mw.util.getUrl( 'Special:Preferences' ) ) +
					'#mw-prefsection-echo'
			};

		function updateDocumentTitleWithNotificationCount( totalAlertCount, totalMessageCount ) {
			var totalCount = totalAlertCount + totalMessageCount,
				convertedTotalCount,
				newTitle = documentTitle;

			if ( totalCount > 0 ) {
				convertedTotalCount = totalCount <= maxNotificationCount ? totalCount : maxNotificationCount + 1;
				convertedTotalCount = mw.msg( 'echo-badge-count', mw.language.convertNumber( convertedTotalCount ) );
				newTitle = mw.msg( 'parentheses', convertedTotalCount ) + ' ' + documentTitle;
			}
			document.title = newTitle;
		}

		/**
		 * Show notification snippet via mw.notify of notifications which came after highestNotifTime.
		 *
		 * @param {mw.echo.dm.ModelManager} modelManager
		 * @param {Date} highestNotifTime Timestamp of latest notification the last time function was called
		 * @return {Date} Timestamp of latest notification
		 */
		function showNotificationSnippet( modelManager, highestNotifTime ) {
			var timestampAsDate,
				highestTime = new Date();
			highestTime = highestNotifTime;
			modelManager.getLocalNotifications().forEach( function ( notificationItem ) {
				timestampAsDate = new Date( notificationItem.timestamp );
				if ( timestampAsDate > highestNotifTime ) {
					if ( timestampAsDate > highestTime ) {
						highestTime = timestampAsDate;
					}
					if ( !notificationItem.seen ) {
						mw.notify( notificationItem.content.header, { title: mw.msg( 'echo-displaysnippet-title' ) } );
					}
				}
			}
			);
			return highestTime;
		}

		/**
		 * Change the seen state of badges if there are any unseen notifications.
		 *
		 * @param {mw.echo.dm.ModelManager} modelManager
		 * @param {mw.echo.ui.NotificationBadgeWidget} badgeWidget
		 */
		function updateBadgeState( modelManager, badgeWidget ) {
			modelManager.getLocalNotifications().forEach( function ( notificationItem ) {
				if ( !notificationItem.isSeen() ) {
					badgeWidget.updateBadgeSeenState( true );
				}
			} );
		}
		// change document title on initialization only when polling rate(feature flag) is non-zero.
		if ( pollingRate !== 0 && mw.user.options.get( 'echo-show-poll-updates' ) === '1' ) {
			updateDocumentTitleWithNotificationCount( alertCount, messageCount );
		}

		function isLivePollingFeatureEnabledOnWiki() {
			return pollingRate !== 0;
		}

		/**
		 * User has opted in to preference to show notification snippets and update document title with unread count.
		 *
		 * Only useful when isLivePollingFeatureEnabledOnWiki() returns true.
		 *
		 * @return {boolean} User preference
		 */
		function userHasOptedInToLiveNotifications() {
			return mw.user.options.get( 'echo-show-poll-updates' ) === '1';
		}

		function loadEcho() {
			if ( loadingPromise !== null ) {
				return loadingPromise;
			}
			// This part executes only once, either when header icons are clicked or after completion of 60secs whichever occur first.
			echoApi = new mw.echo.api.EchoApi();

			loadingPromise = mw.loader.using( 'ext.echo.ui.desktop' ).then( function () {

				// Overlay
				$( 'body' ).append( mw.echo.ui.$overlay );

				unreadAlertCounter = new mw.echo.dm.UnreadNotificationCounter( echoApi, 'alert', maxNotificationCount );
				alertModelManager = new mw.echo.dm.ModelManager( unreadAlertCounter, { type: 'alert' } );
				alertController = new mw.echo.Controller( echoApi, alertModelManager );

				mw.echo.ui.alertWidget = new mw.echo.ui.NotificationBadgeWidget(
					alertController,
					alertModelManager,
					links,
					{
						numItems: Number( numAlerts ),
						convertedNumber: badgeLabelAlerts,
						hasUnseen: hasUnseenAlerts,
						badgeIcon: 'bell',
						$overlay: mw.echo.ui.$overlay,
						href: $existingAlertLink.attr( 'href' )
					}
				);

				// Replace the link button with the ooui button
				$existingAlertLink.parent().replaceWith( mw.echo.ui.alertWidget.$element );

				alertModelManager.on( 'allTalkRead', function () {
					// If there was a talk page notification, get rid of it
					$( '#pt-mytalk a' )
						.removeClass( 'mw-echo-alert' )
						.text( mw.msg( 'mytalk' ) );
				} );

				// listen to event countChange and change title only if polling rate is non-zero
				if ( isLivePollingFeatureEnabledOnWiki() ) {
					alertModelManager.getUnreadCounter().on( 'countChange', function ( count ) {
						alertController.fetchLocalNotifications().then( function () {
							updateBadgeState( alertModelManager, mw.echo.ui.alertWidget );
							if ( userHasOptedInToLiveNotifications() ) {
								latestAlertNotifTime = showNotificationSnippet( alertModelManager, latestAlertNotifTime );
								alertCount = count;
								updateDocumentTitleWithNotificationCount( count, messageCount );
							}
						} );
					} );
				}

				// Load message button and popup if messages exist
				if ( $existingMessageLink.length ) {
					unreadMessageCounter = new mw.echo.dm.UnreadNotificationCounter( echoApi, 'message', maxNotificationCount );
					messageModelManager = new mw.echo.dm.ModelManager( unreadMessageCounter, { type: 'message' } );
					messageController = new mw.echo.Controller( echoApi, messageModelManager );

					mw.echo.ui.messageWidget = new mw.echo.ui.NotificationBadgeWidget(
						messageController,
						messageModelManager,
						links,
						{
							$overlay: mw.echo.ui.$overlay,
							numItems: Number( numMessages ),
							hasUnseen: hasUnseenMessages,
							badgeIcon: 'tray',
							convertedNumber: badgeLabelMessages,
							href: $existingMessageLink.attr( 'href' )
						}
					);

					// Replace the link button with the ooui button
					$existingMessageLink.parent().replaceWith( mw.echo.ui.messageWidget.$element );

					// listen to event countChange and change title only if polling rate is non-zero
					if ( isLivePollingFeatureEnabledOnWiki() ) {
						messageModelManager.getUnreadCounter().on( 'countChange', function ( count ) {
							messageController.fetchLocalNotifications().then( function () {
								updateBadgeState( messageModelManager, mw.echo.ui.messageWidget );
								if ( userHasOptedInToLiveNotifications() ) {
									latestMessageNotifTime = showNotificationSnippet( messageModelManager, latestMessageNotifTime );
									messageCount = count;
									updateDocumentTitleWithNotificationCount( alertCount, count );
								}
							} );
						} );
					}
				}
			} );
			return loadingPromise;

		}

		// Respond to click on the notification button and load the UI on demand
		$( '.mw-echo-notification-badge-nojs' ).on( 'click', function ( e ) {
			var timeOfClick = mw.now(),
				$badge = $( this ),
				clickedSection = $badge.parent().prop( 'id' ) === 'pt-notifications-alert' ? 'alert' : 'message';
			if ( e.which !== 1 || $badge.data( 'clicked' ) ) {
				return false;
			}

			$badge.data( 'clicked', true );

			// Dim the badge while we load
			$badge.addClass( 'mw-echo-notifications-badge-dimmed' );

			// Fire the notification API requests
			echoApi = new mw.echo.api.EchoApi();
			echoApi.fetchNotifications( clickedSection )
				.then( function ( data ) {
					mw.track( 'timing.MediaWiki.echo.overlay.api', mw.now() - timeOfClick );
					return data;
				} );

			loadEcho().then( function () {
				// Now that the module loaded, show the popup
				selectedWidget = clickedSection === 'alert' ? mw.echo.ui.alertWidget : mw.echo.ui.messageWidget;
				selectedWidget.once( 'finishLoading', function () {
					// Log timing after notifications are shown
					mw.track( 'timing.MediaWiki.echo.overlay', mw.now() - timeOfClick );
				} );
				selectedWidget.popup.toggle( true );
				mw.track( 'timing.MediaWiki.echo.overlay.ooui', mw.now() - timeOfClick );

				if ( hasUnseenAlerts || hasUnseenMessages ) {
					// Clicked on the flyout due to having unread notifications
					mw.track( 'counter.MediaWiki.echo.unseen.click' );
				}
			}, function () {
				// Un-dim badge if loading failed
				$badge.removeClass( 'mw-echo-notifications-badge-dimmed' );
			} );
			// Prevent default
			return false;
		} );

		function pollForNotificationCountUpdates() {
			alertController.refreshUnreadCount();
			messageController.refreshUnreadCount();
			// Make notification update after n*pollingRate(time in secs) where n depends on document.hidden
			setTimeout( pollForNotificationCountUpdates, ( document.hidden ? 5 : 1 ) * pollingRate * 1000 );
		}

		function pollStart() {
			if ( mw.config.get( 'skin' ) !== 'minerva' && pollingRate !== 0 ) {
				// load widgets if not loaded already then start polling
				loadEcho().then( pollForNotificationCountUpdates );
			}
		}

		setTimeout( pollStart, 60 * 1000 );

	} );

}() );
<commit_msg>Render HTML in notification snippet<commit_after>/* eslint-disable no-jquery/no-global-selector */
( function () {
	'use strict';

	// Remove ?markasread=XYZ from the URL
	var uri = new mw.Uri();
	if ( uri.query.markasread !== undefined ) {
		delete uri.query.markasread;
		delete uri.query.markasreadwiki;
		window.history.replaceState( null, document.title, uri );
	}

	mw.echo = mw.echo || {};
	mw.echo.config = mw.echo.config || {};
	// Set default max prioritized action links per item
	mw.echo.config.maxPrioritizedActions = 2;

	// Activate ooui
	$( function () {
		var selectedWidget,
			echoApi,
			messageController,
			alertController,
			messageModelManager,
			alertModelManager,
			unreadMessageCounter,
			unreadAlertCounter,
			maxNotificationCount = require( './config.json' ).EchoMaxNotificationCount,
			pollingRate = require( './config.json' ).EchoPollForUpdates,
			documentTitle = document.title,
			$existingAlertLink = $( '#pt-notifications-alert a' ),
			$existingMessageLink = $( '#pt-notifications-notice a' ),
			numAlerts = $existingAlertLink.attr( 'data-counter-num' ),
			numMessages = $existingMessageLink.attr( 'data-counter-num' ),
			badgeLabelAlerts = $existingAlertLink.attr( 'data-counter-text' ),
			badgeLabelMessages = $existingMessageLink.attr( 'data-counter-text' ),
			hasUnseenAlerts = $existingAlertLink.hasClass( 'mw-echo-unseen-notifications' ),
			hasUnseenMessages = $existingMessageLink.hasClass( 'mw-echo-unseen-notifications' ),
			// latestMessageNotifTime is the time of most recent notification that came when we called showNotificationSnippet last
			// the function showNotificationSnippet returns the time of the latest notification and latestMessageNotifTime is updated
			latestMessageNotifTime = new Date(),
			latestAlertNotifTime = new Date(),
			alertCount = parseInt( numAlerts ),
			messageCount = parseInt( numMessages ),
			loadingPromise = null,
			// Store links
			links = {
				notifications: $existingAlertLink.attr( 'href' ) || mw.util.getUrl( 'Special:Notifications' ),
				preferences: ( $( '#pt-preferences a' ).attr( 'href' ) || mw.util.getUrl( 'Special:Preferences' ) ) +
					'#mw-prefsection-echo'
			};

		function updateDocumentTitleWithNotificationCount( totalAlertCount, totalMessageCount ) {
			var totalCount = totalAlertCount + totalMessageCount,
				convertedTotalCount,
				newTitle = documentTitle;

			if ( totalCount > 0 ) {
				convertedTotalCount = totalCount <= maxNotificationCount ? totalCount : maxNotificationCount + 1;
				convertedTotalCount = mw.msg( 'echo-badge-count', mw.language.convertNumber( convertedTotalCount ) );
				newTitle = mw.msg( 'parentheses', convertedTotalCount ) + ' ' + documentTitle;
			}
			document.title = newTitle;
		}

		/**
		 * Show notification snippet via mw.notify of notifications which came after highestNotifTime.
		 *
		 * @param {mw.echo.dm.ModelManager} modelManager
		 * @param {Date} highestNotifTime Timestamp of latest notification the last time function was called
		 * @return {Date} Timestamp of latest notification
		 */
		function showNotificationSnippet( modelManager, highestNotifTime ) {
			var timestampAsDate,
				highestTime = new Date();
			highestTime = highestNotifTime;
			modelManager.getLocalNotifications().forEach( function ( notificationItem ) {
				timestampAsDate = new Date( notificationItem.timestamp );
				if ( timestampAsDate > highestNotifTime ) {
					if ( timestampAsDate > highestTime ) {
						highestTime = timestampAsDate;
					}
					if ( !notificationItem.seen ) {
						mw.notify( $.parseHTML( notificationItem.content.header ), { title: mw.msg( 'echo-displaysnippet-title' ) } );
					}
				}
			}
			);
			return highestTime;
		}

		/**
		 * Change the seen state of badges if there are any unseen notifications.
		 *
		 * @param {mw.echo.dm.ModelManager} modelManager
		 * @param {mw.echo.ui.NotificationBadgeWidget} badgeWidget
		 */
		function updateBadgeState( modelManager, badgeWidget ) {
			modelManager.getLocalNotifications().forEach( function ( notificationItem ) {
				if ( !notificationItem.isSeen() ) {
					badgeWidget.updateBadgeSeenState( true );
				}
			} );
		}
		// change document title on initialization only when polling rate(feature flag) is non-zero.
		if ( pollingRate !== 0 && mw.user.options.get( 'echo-show-poll-updates' ) === '1' ) {
			updateDocumentTitleWithNotificationCount( alertCount, messageCount );
		}

		function isLivePollingFeatureEnabledOnWiki() {
			return pollingRate !== 0;
		}

		/**
		 * User has opted in to preference to show notification snippets and update document title with unread count.
		 *
		 * Only useful when isLivePollingFeatureEnabledOnWiki() returns true.
		 *
		 * @return {boolean} User preference
		 */
		function userHasOptedInToLiveNotifications() {
			return mw.user.options.get( 'echo-show-poll-updates' ) === '1';
		}

		function loadEcho() {
			if ( loadingPromise !== null ) {
				return loadingPromise;
			}
			// This part executes only once, either when header icons are clicked or after completion of 60secs whichever occur first.
			echoApi = new mw.echo.api.EchoApi();

			loadingPromise = mw.loader.using( 'ext.echo.ui.desktop' ).then( function () {

				// Overlay
				$( 'body' ).append( mw.echo.ui.$overlay );

				unreadAlertCounter = new mw.echo.dm.UnreadNotificationCounter( echoApi, 'alert', maxNotificationCount );
				alertModelManager = new mw.echo.dm.ModelManager( unreadAlertCounter, { type: 'alert' } );
				alertController = new mw.echo.Controller( echoApi, alertModelManager );

				mw.echo.ui.alertWidget = new mw.echo.ui.NotificationBadgeWidget(
					alertController,
					alertModelManager,
					links,
					{
						numItems: Number( numAlerts ),
						convertedNumber: badgeLabelAlerts,
						hasUnseen: hasUnseenAlerts,
						badgeIcon: 'bell',
						$overlay: mw.echo.ui.$overlay,
						href: $existingAlertLink.attr( 'href' )
					}
				);

				// Replace the link button with the ooui button
				$existingAlertLink.parent().replaceWith( mw.echo.ui.alertWidget.$element );

				alertModelManager.on( 'allTalkRead', function () {
					// If there was a talk page notification, get rid of it
					$( '#pt-mytalk a' )
						.removeClass( 'mw-echo-alert' )
						.text( mw.msg( 'mytalk' ) );
				} );

				// listen to event countChange and change title only if polling rate is non-zero
				if ( isLivePollingFeatureEnabledOnWiki() ) {
					alertModelManager.getUnreadCounter().on( 'countChange', function ( count ) {
						alertController.fetchLocalNotifications().then( function () {
							updateBadgeState( alertModelManager, mw.echo.ui.alertWidget );
							if ( userHasOptedInToLiveNotifications() ) {
								latestAlertNotifTime = showNotificationSnippet( alertModelManager, latestAlertNotifTime );
								alertCount = count;
								updateDocumentTitleWithNotificationCount( count, messageCount );
							}
						} );
					} );
				}

				// Load message button and popup if messages exist
				if ( $existingMessageLink.length ) {
					unreadMessageCounter = new mw.echo.dm.UnreadNotificationCounter( echoApi, 'message', maxNotificationCount );
					messageModelManager = new mw.echo.dm.ModelManager( unreadMessageCounter, { type: 'message' } );
					messageController = new mw.echo.Controller( echoApi, messageModelManager );

					mw.echo.ui.messageWidget = new mw.echo.ui.NotificationBadgeWidget(
						messageController,
						messageModelManager,
						links,
						{
							$overlay: mw.echo.ui.$overlay,
							numItems: Number( numMessages ),
							hasUnseen: hasUnseenMessages,
							badgeIcon: 'tray',
							convertedNumber: badgeLabelMessages,
							href: $existingMessageLink.attr( 'href' )
						}
					);

					// Replace the link button with the ooui button
					$existingMessageLink.parent().replaceWith( mw.echo.ui.messageWidget.$element );

					// listen to event countChange and change title only if polling rate is non-zero
					if ( isLivePollingFeatureEnabledOnWiki() ) {
						messageModelManager.getUnreadCounter().on( 'countChange', function ( count ) {
							messageController.fetchLocalNotifications().then( function () {
								updateBadgeState( messageModelManager, mw.echo.ui.messageWidget );
								if ( userHasOptedInToLiveNotifications() ) {
									latestMessageNotifTime = showNotificationSnippet( messageModelManager, latestMessageNotifTime );
									messageCount = count;
									updateDocumentTitleWithNotificationCount( alertCount, count );
								}
							} );
						} );
					}
				}
			} );
			return loadingPromise;

		}

		// Respond to click on the notification button and load the UI on demand
		$( '.mw-echo-notification-badge-nojs' ).on( 'click', function ( e ) {
			var timeOfClick = mw.now(),
				$badge = $( this ),
				clickedSection = $badge.parent().prop( 'id' ) === 'pt-notifications-alert' ? 'alert' : 'message';
			if ( e.which !== 1 || $badge.data( 'clicked' ) ) {
				return false;
			}

			$badge.data( 'clicked', true );

			// Dim the badge while we load
			$badge.addClass( 'mw-echo-notifications-badge-dimmed' );

			// Fire the notification API requests
			echoApi = new mw.echo.api.EchoApi();
			echoApi.fetchNotifications( clickedSection )
				.then( function ( data ) {
					mw.track( 'timing.MediaWiki.echo.overlay.api', mw.now() - timeOfClick );
					return data;
				} );

			loadEcho().then( function () {
				// Now that the module loaded, show the popup
				selectedWidget = clickedSection === 'alert' ? mw.echo.ui.alertWidget : mw.echo.ui.messageWidget;
				selectedWidget.once( 'finishLoading', function () {
					// Log timing after notifications are shown
					mw.track( 'timing.MediaWiki.echo.overlay', mw.now() - timeOfClick );
				} );
				selectedWidget.popup.toggle( true );
				mw.track( 'timing.MediaWiki.echo.overlay.ooui', mw.now() - timeOfClick );

				if ( hasUnseenAlerts || hasUnseenMessages ) {
					// Clicked on the flyout due to having unread notifications
					mw.track( 'counter.MediaWiki.echo.unseen.click' );
				}
			}, function () {
				// Un-dim badge if loading failed
				$badge.removeClass( 'mw-echo-notifications-badge-dimmed' );
			} );
			// Prevent default
			return false;
		} );

		function pollForNotificationCountUpdates() {
			alertController.refreshUnreadCount();
			messageController.refreshUnreadCount();
			// Make notification update after n*pollingRate(time in secs) where n depends on document.hidden
			setTimeout( pollForNotificationCountUpdates, ( document.hidden ? 5 : 1 ) * pollingRate * 1000 );
		}

		function pollStart() {
			if ( mw.config.get( 'skin' ) !== 'minerva' && pollingRate !== 0 ) {
				// load widgets if not loaded already then start polling
				loadEcho().then( pollForNotificationCountUpdates );
			}
		}

		setTimeout( pollStart, 60 * 1000 );

	} );

}() );
<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import React, { createElement } from 'react';
import hoistStatics from 'hoist-non-react-statics';
import { connect } from 'react-redux';
import api from './api';

import { statePropTypes, initState, getStateAccessors, getStateProps } from './componentState';
import { mapStateToViewProps } from './settings';

let newState;

const CMF_PROPS = [
	'didMountActionCreator', // componentDidMount action creator id in registry
	'keepComponentState', // redux state management on unmount
	'view', // view component id in registry
	'willUnMountActionCreator', // componentWillUnmount action creator id in registry
];

export function getComponentName(WrappedComponent) {
	return WrappedComponent.displayName || WrappedComponent.name || 'Component';
}

export function getComponentId(componentId, props) {
	if (typeof componentId === 'function') {
		return componentId(props) || 'default';
	} else if (typeof componentId === 'string') {
		return componentId;
	} else if (props.componentId) {
		return props.componentId;
	}
	return 'default';
}

function getCollection(id) {
	return newState.cmf.collections.get(id);
}

export function getStateToProps({
	componentId,
	ownProps,
	state,
	mapStateToProps,
	WrappedComponent,
}) {
	newState = state;
	const cmfProps = getStateProps(
		state,
		getComponentName(WrappedComponent),
		getComponentId(componentId, ownProps),
	);

	cmfProps.getCollection = getCollection;

	const viewProps = mapStateToViewProps(
		state,
		ownProps,
		getComponentName(WrappedComponent),
		getComponentId(componentId, ownProps),
	);

	let userProps = {};
	if (mapStateToProps) {
		userProps = mapStateToProps(state, ownProps, cmfProps);
	}

	return { ...cmfProps, ...viewProps, ...userProps };
}

export function getDispatchToProps({
	defaultState,
	dispatch,
	componentId,
	mapDispatchToProps,
	ownProps,
	WrappedComponent,
}) {
	const cmfProps = getStateAccessors(
		dispatch,
		getComponentName(WrappedComponent),
		getComponentId(componentId, ownProps),
		defaultState,
	);
	cmfProps.dispatch = dispatch;
	cmfProps.dispatchActionCreator = (actionId, event, data, context) => {
		dispatch(api.action.getActionCreatorFunction(context, actionId)(event, data, context));
	};

	let userProps = {};
	if (mapDispatchToProps) {
		userProps = mapDispatchToProps(dispatch, ownProps, cmfProps);
	}

	return { ...cmfProps, ...userProps };
}

/**
 * this function wrap your component to inject the following:
 * - props.state
 * - props.setState
 * - props.initState (you should never have to call it your self)
 * - props.getCollection
 * - dispatch(action)
 * - dispatchActionCreator(id, event, data, [context])
 *
 * support for the following props
 * - initialState (called by props.initState)
 * - didMountActionCreator (id or array of id)
 * - willUnMountActionCreator (id or array of id)
 * - componentId (or will use uuid)
 * - keepComponentState (boolean, overrides the keepComponentState defined in container)
 * - didMountActionCreator (string called as action creator in didMount)
 * - view (string to inject the settings as props with ref support)
 * @return {ReactComponent}
 */
export default function cmfConnect({
	componentId,
	defaultState,
	keepComponentState,
	mapStateToProps,
	mapDispatchToProps,
	mergeProps,
	...rest
}) {
	return function wrapWithCMF(WrappedComponent) {
		class CMFContainer extends React.Component {
			static displayName = `CMF(${getComponentName(WrappedComponent)})`;
			static propTypes = {
				...WrappedComponent.propTypes,
				...statePropTypes,
			};
			static contextTypes = {
				store: PropTypes.object,
				registry: PropTypes.object,
				router: PropTypes.object,
			};
			static WrappedComponent = WrappedComponent;

			constructor(props, context) {
				super(props, context);
				this.dispatchActionCreator = this.dispatchActionCreator.bind(this);
			}

			componentDidMount() {
				initState(this.props);
				if (this.props.didMountActionCreator) {
					this.dispatchActionCreator(this.props.didMountActionCreator, null, this.props);
				}
			}

			componentWillUnmount() {
				if (this.props.willUnmountActionCreator) {
					this.dispatchActionCreator(this.props.willUnmountActionCreator, null, this.props);
				}
				// if the props.keepComponentState is present we have to stick to it
				if (
					this.props.keepComponentState === false ||
					(this.props.keepComponentState === undefined && !keepComponentState)
				) {
					this.props.deleteState();
				}
			}

			dispatchActionCreator(actionCreatorId, event, data, context) {
				const extendedContext = Object.assign({}, this.context, context);
				this.props.dispatchActionCreator(actionCreatorId, event, data, extendedContext);
			}

			render() {
				const props = Object.assign({ state: defaultState }, this.props, {
					dispatchActionCreator: this.dispatchActionCreator,
				});

				// remove all internal props already used by the container
				CMF_PROPS.forEach((key) => {
					delete props[key];
				});

				return createElement(WrappedComponent, props);
			}
		}
		const Connected = connect(
			(state, ownProps) =>
				getStateToProps({
					componentId,
					defaultState,
					ownProps,
					state,
					mapStateToProps,
					WrappedComponent,
				}),
			(dispatch, ownProps) =>
				getDispatchToProps({
					defaultState,
					dispatch,
					componentId,
					mapDispatchToProps,
					ownProps,
					WrappedComponent,
				}),
			mergeProps,
			{ ...rest },
		)(hoistStatics(CMFContainer, WrappedComponent));
		Connected.CMFContainer = CMFContainer;
		return Connected;
	};
}
<commit_msg>chore(cmf): cmfConnect function depreciation (#760)<commit_after>import PropTypes from 'prop-types';
import React, { createElement } from 'react';
import hoistStatics from 'hoist-non-react-statics';
import { connect } from 'react-redux';
import api from './api';
import deprecated from './deprecated';

import { statePropTypes, initState, getStateAccessors, getStateProps } from './componentState';
import { mapStateToViewProps } from './settings';

let newState;

const CMF_PROPS = [
	'didMountActionCreator', // componentDidMount action creator id in registry
	'keepComponentState', // redux state management on unmount
	'view', // view component id in registry
	'willUnMountActionCreator', // componentWillUnmount action creator id in registry
];

export function getComponentName(WrappedComponent) {
	return WrappedComponent.displayName || WrappedComponent.name || 'Component';
}

export function getComponentId(componentId, props) {
	if (typeof componentId === 'function') {
		return componentId(props) || 'default';
	} else if (typeof componentId === 'string') {
		return componentId;
	} else if (props.componentId) {
		return props.componentId;
	}
	return 'default';
}

function oldGetCollection(id) {
	return newState.cmf.collections.get(id);
}

const getCollection = deprecated(
	oldGetCollection,
	`This function will be deprecated,
	since it permit store access outside cmfConnect mapStateToProps function
	and maybe not executed if cmf connect do not detect ref change to props
	given to the component using this function
	Please bind your collection update to your component using mapStateToProps`,
);

export function getStateToProps({
	componentId,
	ownProps,
	state,
	mapStateToProps,
	WrappedComponent,
}) {
	newState = state;
	const cmfProps = getStateProps(
		state,
		getComponentName(WrappedComponent),
		getComponentId(componentId, ownProps),
	);

	cmfProps.getCollection = getCollection;

	const viewProps = mapStateToViewProps(
		state,
		ownProps,
		getComponentName(WrappedComponent),
		getComponentId(componentId, ownProps),
	);

	let userProps = {};
	if (mapStateToProps) {
		userProps = mapStateToProps(state, ownProps, cmfProps);
	}

	return { ...cmfProps, ...viewProps, ...userProps };
}

export function getDispatchToProps({
	defaultState,
	dispatch,
	componentId,
	mapDispatchToProps,
	ownProps,
	WrappedComponent,
}) {
	const cmfProps = getStateAccessors(
		dispatch,
		getComponentName(WrappedComponent),
		getComponentId(componentId, ownProps),
		defaultState,
	);
	cmfProps.dispatch = dispatch;
	cmfProps.dispatchActionCreator = (actionId, event, data, context) => {
		dispatch(api.action.getActionCreatorFunction(context, actionId)(event, data, context));
	};

	let userProps = {};
	if (mapDispatchToProps) {
		userProps = mapDispatchToProps(dispatch, ownProps, cmfProps);
	}

	return { ...cmfProps, ...userProps };
}

/**
 * this function wrap your component to inject the following:
 * - props.state
 * - props.setState
 * - props.initState (you should never have to call it your self)
 * - props.getCollection
 * - dispatch(action)
 * - dispatchActionCreator(id, event, data, [context])
 *
 * support for the following props
 * - initialState (called by props.initState)
 * - didMountActionCreator (id or array of id)
 * - willUnMountActionCreator (id or array of id)
 * - componentId (or will use uuid)
 * - keepComponentState (boolean, overrides the keepComponentState defined in container)
 * - didMountActionCreator (string called as action creator in didMount)
 * - view (string to inject the settings as props with ref support)
 * @return {ReactComponent}
 */
export default function cmfConnect({
	componentId,
	defaultState,
	keepComponentState,
	mapStateToProps,
	mapDispatchToProps,
	mergeProps,
	...rest
}) {
	return function wrapWithCMF(WrappedComponent) {
		class CMFContainer extends React.Component {
			static displayName = `CMF(${getComponentName(WrappedComponent)})`;
			static propTypes = {
				...WrappedComponent.propTypes,
				...statePropTypes,
			};
			static contextTypes = {
				store: PropTypes.object,
				registry: PropTypes.object,
				router: PropTypes.object,
			};
			static WrappedComponent = WrappedComponent;

			constructor(props, context) {
				super(props, context);
				this.dispatchActionCreator = this.dispatchActionCreator.bind(this);
			}

			componentDidMount() {
				initState(this.props);
				if (this.props.didMountActionCreator) {
					this.dispatchActionCreator(this.props.didMountActionCreator, null, this.props);
				}
			}

			componentWillUnmount() {
				if (this.props.willUnmountActionCreator) {
					this.dispatchActionCreator(this.props.willUnmountActionCreator, null, this.props);
				}
				// if the props.keepComponentState is present we have to stick to it
				if (
					this.props.keepComponentState === false ||
					(this.props.keepComponentState === undefined && !keepComponentState)
				) {
					this.props.deleteState();
				}
			}

			dispatchActionCreator(actionCreatorId, event, data, context) {
				const extendedContext = Object.assign({}, this.context, context);
				this.props.dispatchActionCreator(actionCreatorId, event, data, extendedContext);
			}

			render() {
				const props = Object.assign({ state: defaultState }, this.props, {
					dispatchActionCreator: this.dispatchActionCreator,
				});

				// remove all internal props already used by the container
				CMF_PROPS.forEach((key) => {
					delete props[key];
				});

				return createElement(WrappedComponent, props);
			}
		}
		const Connected = connect(
			(state, ownProps) =>
				getStateToProps({
					componentId,
					defaultState,
					ownProps,
					state,
					mapStateToProps,
					WrappedComponent,
				}),
			(dispatch, ownProps) =>
				getDispatchToProps({
					defaultState,
					dispatch,
					componentId,
					mapDispatchToProps,
					ownProps,
					WrappedComponent,
				}),
			mergeProps,
			{ ...rest },
		)(hoistStatics(CMFContainer, WrappedComponent));
		Connected.CMFContainer = CMFContainer;
		return Connected;
	};
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2017 Sankarsan Kampa
 *                    https://sankarsankampa.com/contact
 *
 * This file is a part of Bastion Discord BOT.
 *                        https://github.com/snkrsnkampa/Bastion
 *
 * This code is licensed under the SNKRSN Shared License. It is free to
 * download, copy, compile, use, study and refer under the terms of the
 * SNKRSN Shared License. You can modify the code only for personal or
 * internal use only. However, you can not redistribute the code without
 * explicitly getting permission fot it.
 *
 * Bastion BOT is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY. See the SNKRSN Shared License for
 * more details.
 *
 * You should have received a copy of the SNKRSN Shared License along
 * with this program. If not, see <https://github.com/snkrsnkampa/Bastion/LICENSE>.
 */

exports.run = function(Bastion, message, args) {
  let modules = getDirSync('./modules/');
  let fields = [];
  for (var i = 0; i < modules.length; i++) {
    commands[modules[i]] = [];
    loadCommands(modules[i]);
    fields.push({
      name: modules[i].toUpperCase(),
      value: Bastion.config.prefix + commands[modules[i]].join(`\n${Bastion.config.prefix}`),
      inline: true
    });
  }

  message.channel.sendMessage('', {embed: {
    color: 15451167,
    title: 'List of Commands',
    description: `To get help/details about a command, type \`${Bastion.config.prefix}help command_name\`\nTo get a complete list of all the commands with details click [here](https://bastion.js.org/commands).`,
    fields: fields,
    footer: {
      text: `Prefix: ${Bastion.config.prefix} | Total Commands: ${Bastion.commands.size}`
    }
  }}).catch(e => {
    Bastion.log.error(e.stack);
  });
};

exports.conf = {
  aliases: ['cmds']
};

exports.help = {
  name: 'commands',
  description: 'Shows the complete list of commands with their aliases.',
  permission: '',
  usage: ['commands']
};

function loadCommands(module) {
  files = fs.readdirSync(`./modules/${module}/`);
  files.forEach(f => {
    let cmd = require(`../../modules/${module}/${f}`);
    commands[module].push(cmd.help.name);
  });
}
<commit_msg>Fixed commands<commit_after>/*
 * Copyright (C) 2017 Sankarsan Kampa
 *                    https://sankarsankampa.com/contact
 *
 * This file is a part of Bastion Discord BOT.
 *                        https://github.com/snkrsnkampa/Bastion
 *
 * This code is licensed under the SNKRSN Shared License. It is free to
 * download, copy, compile, use, study and refer under the terms of the
 * SNKRSN Shared License. You can modify the code only for personal or
 * internal use only. However, you can not redistribute the code without
 * explicitly getting permission fot it.
 *
 * Bastion BOT is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY. See the SNKRSN Shared License for
 * more details.
 *
 * You should have received a copy of the SNKRSN Shared License along
 * with this program. If not, see <https://github.com/snkrsnkampa/Bastion/LICENSE>.
 */

const fs = require('fs');
const getDirSync = require('../../functions/getDirSync').func;
let commands = new Object();

exports.run = function(Bastion, message, args) {
  let modules = getDirSync('./modules/');
  let fields = [];
  for (var i = 0; i < modules.length; i++) {
    commands[modules[i]] = [];
    loadCommands(modules[i]);
    fields.push({
      name: modules[i].toUpperCase(),
      value: Bastion.config.prefix + commands[modules[i]].join(`\n${Bastion.config.prefix}`),
      inline: true
    });
  }

  message.channel.sendMessage('', {embed: {
    color: 15451167,
    title: 'List of Commands',
    description: `To get help/details about a command, type \`${Bastion.config.prefix}help command_name\`\nTo get a complete list of all the commands with details click [here](https://bastion.js.org/commands).`,
    fields: fields,
    footer: {
      text: `Prefix: ${Bastion.config.prefix} | Total Commands: ${Bastion.commands.size}`
    }
  }}).catch(e => {
    Bastion.log.error(e.stack);
  });
};

exports.conf = {
  aliases: ['cmds']
};

exports.help = {
  name: 'commands',
  description: 'Shows the complete list of commands with their aliases.',
  permission: '',
  usage: ['commands']
};

function loadCommands(module) {
  files = fs.readdirSync(`./modules/${module}/`);
  files.forEach(f => {
    let cmd = require(`../../modules/${module}/${f}`);
    commands[module].push(cmd.help.name);
  });
}
<|endoftext|>


<commit_before>
//Funciones que se ejcutan en el index.html

var subastasDeTerceros = [];
var idUsuario;
var misSubastas = [];

function initialize() {
  $('#modalLogin').modal('show');
}

function renderizarSubastas(){
  $.each(subastasDeTerceros[0],function(index, unaSubasta){
    console.log(unaSubasta);
        renderizarUnaSubasta(unaSubasta);
  });
}

function renderizarUnaSubasta(subasta){
  var vistaSubasta = sprintf("
");
  //  var vistaSubasta = sprintf("
");
  if (subasta.mejor_oferta == null) subasta.mejor_oferta = subasta.precio_base;
  vistaSubasta += sprintf("
");
  vistaSubasta += sprintf("
", subasta.id);
  vistaSubasta += sprintf("
%s

$ %s.

Finalizada: %s.

" +
        "<button class=\"btn btn-primary\" onclick=\"ofertar(%s)\"> Ofertar (+ $2)! </button>
",
        subasta.titulo, subasta.mejor_oferta, subasta.terminada, subasta.id);
  vistaSubasta += "

";
  $('#subastasActuales').append(vistaSubasta);

}

/*Cuando oferto,y sale todo bien, cambiar el valor del monto actual*/
function renderizarOfertaEnSubasta(idOferta){
  console.log("A punto de renderizar el cambio del monto actual de la subasta");

}

function ofertar(idSubasta){

  console.log("A punto de ofertar...");
  var oferta = armarOferta(idSubasta);
  $.ajax({
    headers: { 'id-usuario': idUsuario },
    type: "POST",
    contentType: "application/json",
    data: JSON.stringify(oferta),
    url:   location.origin + "/api/subastas/"+ idSubasta + "/ofertas",
    success: function (data) {
      console.log("Se Oferto Correctamente.");
      renderizarOfertaEnSubasta(oferta.id);
    },
    error: function(jqXHR, textStatus, errorThrown){
      console.log("Ofertar - Hubo un error en el servidor");
      console.log(JSON.stringify(jqXHR) + ". " + JSON.stringify(textStatus) + ". " + JSON.stringify(errorThrown));
    }
  });

}

function armarOferta(idSubasta){
  var subasta = $.grep(subastasDeTerceros[0], function(elem){ return elem.id === idSubasta; })[0];
  return {precio: subasta.mejor_oferta+2, comprador: idUsuario};
}

function crearNuevaSubasta(){
  console.log("A punto de crear nueva subasta...");
  var subasta = armarSubasta();
  console.log("contenido del json subasta:" + JSON.stringify(subasta));
  $.ajax({
    headers: { 'id-usuario': idUsuario },
    type: "POST",
    contentType: "application/json",
    data: JSON.stringify(subasta),
    url: location.origin + "/api/subastas",
    success: function (data) {
      console.log("Se Creo al Subasta Correctamente.");
      vaciarForm();
      agregarAlDivMisSubastas(subasta);
      misSubastas.push(subasta);
    },
    error: function(jqXHR, textStatus, errorThrown){
      console.log("Crear Subasta - Hubo un error en el servidor");
      console.log(JSON.stringify(jqXHR) + ". " + JSON.stringify(textStatus) + ". " + JSON.stringify(errorThrown));
    }
  });
}

function armarSubasta(){
  /*Armar algo del estilo:
  {"data":{"vendedor":"Juan",
  "titulo":"venta heladera",
  "terminada":false,
  "precio_base":200.0,
  "mejor_oferta":null,
  "id":9,"duracion":10}}
  */
  return {
      subasta:{
         vendedor: idUsuario,
         titulo: $("#tituloNuevaSubasta").val(),
         duracion: $("#duracionNuevaSubasta").val(),
         /*O si queres poner el tiempo final
         var xMinutesLater = new Date();
         xMinutesLater.setMinutes(xMinutesLater.getMinutes() + $("#duracionNuevaSubasta").val());*/
         precio_base: $("#precioNuevaSubasta").val(),
         terminada: false
       }
     };
}

function vaciarForm(){
  titulo: $("#tituloNuevaSubasta").val("");
  duracion: $("#duracionNuevaSubasta").val("");
  precioBase: $("#precioNuevaSubasta").val("");

}

function agregarAlDivMisSubastas(unaSubasta){
  var vistaSubasta = sprintf("
", unaSubasta.titulo);
  vistaSubasta += sprintf("%s", unaSubasta.titulo);
  vistaSubasta += sprintf("
");
  vistaSubasta += sprintf("<button class=\"btn btn-default\" onclick=\"cancelarSubasta('%s')\">Cancelar Subasta</button>",unaSubasta.titulo);
  vistaSubasta += "

";
  $('#misSubastas').append(vistaSubasta);

}

function login(){
  var nombreUsuario = $("#nombreUsuario").val();
  $("#nombreUsuarioLogueado").text($("#nombreUsuario").val());
  idUsuario = $("#nombreUsuarioLogueado").text();
  $('#modalLogin').modal('toggle');

  mostrarContenido();
}

function mostrarContenido(){
 /* subastasDeTerceros.push({id: 1, titulo:"pelota futbol", montoActual: 20.00});
  subastasDeTerceros.push({id: 2, titulo:"remera", montoActual: 50.00});
  /*Cambiar esas subastas de arriba por una peticion ajax al servidor despues de haberse logueado*/
  $.ajax({
    headers: { 'id-usuario': idUsuario },
    type: "GET",
    contentType: "application/json",
    url: "/api/subastas",
    success: function (data) {
      console.log("Se obtuvieron correctamente las subastas.");
      $.each(data,function(index, unaSubasta){
          subastasDeTerceros.push(unaSubasta);
          renderizarSubastas(); //Descomentar este y borrar el otro renderizar que esta de prueba
      });

    },
    error: function(jqXHR, textStatus, errorThrown){
      console.log("Get de subastas - Hubo un error en el servidor");
      console.log(JSON.stringify(jqXHR) + ". " + JSON.stringify(textStatus) + ". " + JSON.stringify(errorThrown));
    }
  })
}

function cancelarSubasta(titulo){

  $.ajax({
    headers: { 'id-usuario': idUsuario },
    type: "POST",
    url: location.origin + "/api/subastas/" + titulo + "/cancelar",
    success: function (data) {
      console.log("Se Cancelo la Subasta Correctamente.");
      eliminarMiSubasta(titulo);
    },
    error: function(jqXHR, textStatus, errorThrown){
      console.log("Crear Subasta - Hubo un error en el servidor");
      console.log(JSON.stringify(jqXHR) + ". " + JSON.stringify(textStatus) + ". " + JSON.stringify(errorThrown));
    }
  });

}

function eliminarMiSubasta(titulo){
  $("#div"+titulo).remove();
  misSubastas = $.grep(misSubastas, function(elem, index) {
   return elem.titulo != titulo;
  });

}

/* Un comprador A se registra.
    un nombre
    una forma de contacto

Un vendedor crea una subasta, con la siguiente información
Un título
Un precio base (que puede ser cero)
La duración máxima de la subasta
*/

function sprintf( format ){
  for( var i=1; i < arguments.length; i++ ) {
    format = format.replace( /%s/, arguments[i] );
  }
  return format;
}
<commit_msg>armo bien el json para ofertar<commit_after>
//Funciones que se ejcutan en el index.html

var subastasDeTerceros = [];
var idUsuario;
var misSubastas = [];

function initialize() {
  $('#modalLogin').modal('show');
}

function renderizarSubastas(){
  $.each(subastasDeTerceros[0],function(index, unaSubasta){
    console.log(unaSubasta);
        renderizarUnaSubasta(unaSubasta);
  });
}

function renderizarUnaSubasta(subasta){
  var vistaSubasta = sprintf("
");
  //  var vistaSubasta = sprintf("
");
  if (subasta.mejor_oferta == null) subasta.mejor_oferta = subasta.precio_base;
  vistaSubasta += sprintf("
");
  vistaSubasta += sprintf("
", subasta.id);
  vistaSubasta += sprintf("
%s

$ %s.

Finalizada: %s.

" +
        "<button class=\"btn btn-primary\" onclick=\"ofertar(%s)\"> Ofertar (+ $2)! </button>
",
        subasta.titulo, subasta.mejor_oferta.precio, subasta.terminada, subasta.id);
  vistaSubasta += "

";
  $('#subastasActuales').append(vistaSubasta);

}

/*Cuando oferto,y sale todo bien, cambiar el valor del monto actual*/
function renderizarOfertaEnSubasta(idOferta){
  console.log("A punto de renderizar el cambio del monto actual de la subasta");

}

function ofertar(idSubasta){

  console.log("A punto de ofertar...");
  var oferta = armarOferta(idSubasta);
  $.ajax({
    headers: { 'id-usuario': idUsuario },
    type: "POST",
    contentType: "application/json",
    data: JSON.stringify(oferta),
    url:   location.origin + "/api/subastas/"+ idSubasta + "/ofertas",
    success: function (data) {
      console.log("Se Oferto Correctamente.");
      renderizarOfertaEnSubasta(oferta.id);
    },
    error: function(jqXHR, textStatus, errorThrown){
      console.log("Ofertar - Hubo un error en el servidor");
      console.log(JSON.stringify(jqXHR) + ". " + JSON.stringify(textStatus) + ". " + JSON.stringify(errorThrown));
    }
  });

}

function armarOferta(idSubasta){
  var subasta = $.grep(subastasDeTerceros[0], function(elem){ return elem.id === idSubasta; })[0];
  return {oferta:  {precio: subasta.mejor_oferta.precio+2, comprador: idUsuario} };
}

function crearNuevaSubasta(){
  console.log("A punto de crear nueva subasta...");
  var subasta = armarSubasta();
  console.log("contenido del json subasta:" + JSON.stringify(subasta));
  $.ajax({
    headers: { 'id-usuario': idUsuario },
    type: "POST",
    contentType: "application/json",
    data: JSON.stringify(subasta),
    url: location.origin + "/api/subastas",
    success: function (data) {
      console.log("Se Creo al Subasta Correctamente.");
      vaciarForm();
      agregarAlDivMisSubastas(subasta);
      misSubastas.push(subasta);
    },
    error: function(jqXHR, textStatus, errorThrown){
      console.log("Crear Subasta - Hubo un error en el servidor");
      console.log(JSON.stringify(jqXHR) + ". " + JSON.stringify(textStatus) + ". " + JSON.stringify(errorThrown));
    }
  });
}

function armarSubasta(){
  /*Armar algo del estilo:
  {"data":{"vendedor":"Juan",
  "titulo":"venta heladera",
  "terminada":false,
  "precio_base":200.0,
  "mejor_oferta":null,
  "id":9,"duracion":10}}
  */
  return {
      subasta:{
         vendedor: idUsuario,
         titulo: $("#tituloNuevaSubasta").val(),
         duracion: $("#duracionNuevaSubasta").val(),
         /*O si queres poner el tiempo final
         var xMinutesLater = new Date();
         xMinutesLater.setMinutes(xMinutesLater.getMinutes() + $("#duracionNuevaSubasta").val());*/
         precio_base: $("#precioNuevaSubasta").val(),
         terminada: false
       }
     };
}

function vaciarForm(){
  titulo: $("#tituloNuevaSubasta").val("");
  duracion: $("#duracionNuevaSubasta").val("");
  precioBase: $("#precioNuevaSubasta").val("");

}

function agregarAlDivMisSubastas(unaSubasta){
  var vistaSubasta = sprintf("
", unaSubasta.titulo);
  vistaSubasta += sprintf("%s", unaSubasta.titulo);
  vistaSubasta += sprintf("
");
  vistaSubasta += sprintf("<button class=\"btn btn-default\" onclick=\"cancelarSubasta('%s')\">Cancelar Subasta</button>",unaSubasta.titulo);
  vistaSubasta += "

";
  $('#misSubastas').append(vistaSubasta);

}

function login(){
  var nombreUsuario = $("#nombreUsuario").val();
  $("#nombreUsuarioLogueado").text($("#nombreUsuario").val());
  idUsuario = $("#nombreUsuarioLogueado").text();
  $('#modalLogin').modal('toggle');

  mostrarContenido();
}

function mostrarContenido(){
 /* subastasDeTerceros.push({id: 1, titulo:"pelota futbol", montoActual: 20.00});
  subastasDeTerceros.push({id: 2, titulo:"remera", montoActual: 50.00});
  /*Cambiar esas subastas de arriba por una peticion ajax al servidor despues de haberse logueado*/
  $.ajax({
    headers: { 'id-usuario': idUsuario },
    type: "GET",
    contentType: "application/json",
    url: "/api/subastas",
    success: function (data) {
      console.log("Se obtuvieron correctamente las subastas.");
      $.each(data,function(index, unaSubasta){
          subastasDeTerceros.push(unaSubasta);
          renderizarSubastas(); //Descomentar este y borrar el otro renderizar que esta de prueba
      });

    },
    error: function(jqXHR, textStatus, errorThrown){
      console.log("Get de subastas - Hubo un error en el servidor");
      console.log(JSON.stringify(jqXHR) + ". " + JSON.stringify(textStatus) + ". " + JSON.stringify(errorThrown));
    }
  })
}

function cancelarSubasta(titulo){

  $.ajax({
    headers: { 'id-usuario': idUsuario },
    type: "POST",
    url: location.origin + "/api/subastas/" + titulo + "/cancelar",
    success: function (data) {
      console.log("Se Cancelo la Subasta Correctamente.");
      eliminarMiSubasta(titulo);
    },
    error: function(jqXHR, textStatus, errorThrown){
      console.log("Crear Subasta - Hubo un error en el servidor");
      console.log(JSON.stringify(jqXHR) + ". " + JSON.stringify(textStatus) + ". " + JSON.stringify(errorThrown));
    }
  });

}

function eliminarMiSubasta(titulo){
  $("#div"+titulo).remove();
  misSubastas = $.grep(misSubastas, function(elem, index) {
   return elem.titulo != titulo;
  });

}

/* Un comprador A se registra.
    un nombre
    una forma de contacto

Un vendedor crea una subasta, con la siguiente información
Un título
Un precio base (que puede ser cero)
La duración máxima de la subasta
*/

function sprintf( format ){
  for( var i=1; i < arguments.length; i++ ) {
    format = format.replace( /%s/, arguments[i] );
  }
  return format;
}
<|endoftext|>


<commit_before>// $Id$
(function ($) {

/**
 * Internal function to check using Ajax if clean URLs can be enabled on the
 * settings page.
 *
 * This function is not used to verify whether or not clean URLs
 * are currently enabled.
 */
Drupal.behaviors.cleanURLsSettingsCheck = {
  attach: function (context, settings) {
    // This behavior attaches by ID, so is only valid once on a page.
    // Also skip if we are on an install page, as Drupal.cleanURLsInstallCheck will handle
    // the processing.
    if ($('.clean-url-processed, #edit-clean-url.install').size()) {
      return;
    }
    var url = settings.basePath + 'admin/settings/clean-urls/check';
    $.ajax({
      url: location.protocol + '//' + location.host + url,
      dataType: 'json',
      success: function () {
        // Check was successful. Redirect using a "clean URL". This will force the form that allows enabling clean URLs.
        location = settings.basePath +"admin/settings/clean-urls";
      }
    });
    $('#clean-url').addClass('clean-url-processed');
  }
};

/**
 * Internal function to check using Ajax if clean URLs can be enabled on the
 * install page.
 *
 * This function is not used to verify whether or not clean URLs
 * are currently enabled.
 */
Drupal.cleanURLsInstallCheck = function () {
  var url = location.protocol + '//' + location.host + Drupal.settings.basePath + 'admin/settings/clean-urls/check';
  // Submit a synchronous request to avoid database errors associated with
  // concurrent requests during install.
  $.ajax({
    async: false,
    url: url,
    dataType: 'json',
    success: function () {
      // Check was successful.
      $('#edit-clean-url').attr('value', 1);
    }
  });
  $('#edit-clean-url').addClass('clean-url-processed');
};

/**
 * When a field is filled out, apply its value to other fields that will likely
 * use the same value. In the installer this is used to populate the
 * administrator e-mail address with the same value as the site e-mail address.
 */
Drupal.behaviors.copyFieldValue = {
  attach: function (context, settings) {
    for (var sourceId in settings.copyFieldValue) {
      // Get the list of target fields.
      targetIds = settings.copyFieldValue[sourceId];
      if (!$('#'+ sourceId + '.copy-field-values-processed', context).size()) {
        // Add the behavior to update target fields on blur of the primary field.
        sourceField = $('#' + sourceId);
        sourceField.bind('blur', function () {
          for (var delta in targetIds) {
            var targetField = $('#'+ targetIds[delta]);
            if (targetField.val() == '') {
              targetField.val(this.value);
            }
          }
        });
        sourceField.addClass('copy-field-values-processed');
      }
    }
  }
};

/**
 * Show/hide custom format sections on the regional settings page.
 */
Drupal.behaviors.dateTime = {
  attach: function (context, settings) {
    // Show/hide custom format depending on the select's value.
    $('select.date-format:not(.date-time-processed)', context).change(function () {
      $(this).addClass('date-time-processed').parents('div.date-container').children('div.custom-container')[$(this).val() == 'custom' ? 'show' : 'hide']();
    });

    // Attach keyup handler to custom format inputs.
    $('input.custom-format:not(.date-time-processed)', context).addClass('date-time-processed').keyup(function () {
      var input = $(this);
      var url = settings.dateTime.lookup +(settings.dateTime.lookup.match(/\?q=/) ? '&format=' : '?format=') + Drupal.encodeURIComponent(input.val());
      $.getJSON(url, function (data) {
        $('div.description span', input.parent()).html(data);
      });
    });

    // Trigger the event handler to show the form input if necessary.
    $('select.date-format', context).trigger('change');
  }
};

/**
 * Show/hide settings for user configurable time zones depending on whether
 * users are able to set their own time zones or not.
 */
Drupal.behaviors.userTimeZones = {
  attach: function (context, settings) {
    $('#empty-timezone-message-wrapper .description').hide();
    $('#edit-configurable-timezones', context).change(function () {
      $('#empty-timezone-message-wrapper').toggle();
    });
  },
};

/**
 * Show the powered by Drupal image preview
 */
Drupal.behaviors.poweredByPreview = {
  attach: function (context, settings) {
    $('#edit-color, #edit-size').change(function () {
      var path = settings.basePath + 'misc/' + $('#edit-color').val() + '-' + $('#edit-size').val() + '.png';
      $('img.powered-by-preview').attr('src', path);
    });
  }
};

})(jQuery);
<commit_msg>#496922 by sun and Arancaytar: Fix JS Clean URL test to remove phantom redirects.<commit_after>// $Id$
(function ($) {

/**
 * Internal function to check using Ajax if clean URLs can be enabled on the
 * settings page.
 *
 * This function is not used to verify whether or not clean URLs
 * are currently enabled.
 */
Drupal.behaviors.cleanURLsSettingsCheck = {
  attach: function (context, settings) {
    // This behavior attaches by ID, so is only valid once on a page.
    // Also skip if we are on an install page, as Drupal.cleanURLsInstallCheck will handle
    // the processing.
    if (!($('#edit-clean-url').size()) || $('.clean-url-processed, #edit-clean-url.install').size()) {
      return;
    }
    var url = settings.basePath + 'admin/settings/clean-urls/check';
    $.ajax({
      url: location.protocol + '//' + location.host + url,
      dataType: 'json',
      success: function () {
        // Check was successful. Redirect using a "clean URL". This will force the form that allows enabling clean URLs.
        location = settings.basePath +"admin/settings/clean-urls";
      }
    });
    $('#clean-url').addClass('clean-url-processed');
  }
};

/**
 * Internal function to check using Ajax if clean URLs can be enabled on the
 * install page.
 *
 * This function is not used to verify whether or not clean URLs
 * are currently enabled.
 */
Drupal.cleanURLsInstallCheck = function () {
  var url = location.protocol + '//' + location.host + Drupal.settings.basePath + 'admin/settings/clean-urls/check';
  // Submit a synchronous request to avoid database errors associated with
  // concurrent requests during install.
  $.ajax({
    async: false,
    url: url,
    dataType: 'json',
    success: function () {
      // Check was successful.
      $('#edit-clean-url').attr('value', 1);
    }
  });
  $('#edit-clean-url').addClass('clean-url-processed');
};

/**
 * When a field is filled out, apply its value to other fields that will likely
 * use the same value. In the installer this is used to populate the
 * administrator e-mail address with the same value as the site e-mail address.
 */
Drupal.behaviors.copyFieldValue = {
  attach: function (context, settings) {
    for (var sourceId in settings.copyFieldValue) {
      // Get the list of target fields.
      targetIds = settings.copyFieldValue[sourceId];
      if (!$('#'+ sourceId + '.copy-field-values-processed', context).size()) {
        // Add the behavior to update target fields on blur of the primary field.
        sourceField = $('#' + sourceId);
        sourceField.bind('blur', function () {
          for (var delta in targetIds) {
            var targetField = $('#'+ targetIds[delta]);
            if (targetField.val() == '') {
              targetField.val(this.value);
            }
          }
        });
        sourceField.addClass('copy-field-values-processed');
      }
    }
  }
};

/**
 * Show/hide custom format sections on the regional settings page.
 */
Drupal.behaviors.dateTime = {
  attach: function (context, settings) {
    // Show/hide custom format depending on the select's value.
    $('select.date-format:not(.date-time-processed)', context).change(function () {
      $(this).addClass('date-time-processed').parents('div.date-container').children('div.custom-container')[$(this).val() == 'custom' ? 'show' : 'hide']();
    });

    // Attach keyup handler to custom format inputs.
    $('input.custom-format:not(.date-time-processed)', context).addClass('date-time-processed').keyup(function () {
      var input = $(this);
      var url = settings.dateTime.lookup +(settings.dateTime.lookup.match(/\?q=/) ? '&format=' : '?format=') + Drupal.encodeURIComponent(input.val());
      $.getJSON(url, function (data) {
        $('div.description span', input.parent()).html(data);
      });
    });

    // Trigger the event handler to show the form input if necessary.
    $('select.date-format', context).trigger('change');
  }
};

/**
 * Show/hide settings for user configurable time zones depending on whether
 * users are able to set their own time zones or not.
 */
Drupal.behaviors.userTimeZones = {
  attach: function (context, settings) {
    $('#empty-timezone-message-wrapper .description').hide();
    $('#edit-configurable-timezones', context).change(function () {
      $('#empty-timezone-message-wrapper').toggle();
    });
  },
};

/**
 * Show the powered by Drupal image preview
 */
Drupal.behaviors.poweredByPreview = {
  attach: function (context, settings) {
    $('#edit-color, #edit-size').change(function () {
      var path = settings.basePath + 'misc/' + $('#edit-color').val() + '-' + $('#edit-size').val() + '.png';
      $('img.powered-by-preview').attr('src', path);
    });
  }
};

})(jQuery);
<|endoftext|>


<commit_before>//
// Copyright (c) 2016 DrSmugleaf
//

"use strict"
const winston = require("winston")

class VoiceAutoChannel {
  constructor(discord) {
    this.discord = discord

    this.discord.on("presenceUpdate", (oldMember, newMember) => {
      var oldGame = oldMember.presence.game
      var newGame = newMember.presence.game

      if(newGame && newMember.guild.presences.findAll("game", newGame).length >= 2) {
        newMember.guild.createChannel(`BB-${newGame.name}`, "voice")
          .catch(winston.error)
      }

      if(oldGame && oldMember.guild.presences.findAll("game", oldGame).length < 2) {
        if(oldMember.guild.channels.exists("name", `BB-${oldGame.name}`)) {
          var oldChannel = oldMember.guild.channels.find("name", `BB-${oldGame.name}`)
          if(oldChannel.type == "voice" && oldChannel.members.size < 2) oldChannel.delete()
        }
      }
    })
  }
}

module.exports = VoiceAutoChannel
<commit_msg>Fixed AutoVoiceChannel and made it create channels on ready<commit_after>//
// Copyright (c) 2016 DrSmugleaf
//

"use strict"
const Discord = require("discord.js")
const winston = require("winston")

class VoiceAutoChannel {
  constructor(discord) {
    this.discord = discord

    // this.discord.on("presenceUpdate", (oldMember, newMember) => {
    //   var oldGame = oldMember.presence.game
    //   var newGame = newMember.presence.game
    //
    //   winston.info(newGame && newMember.guild.presences.filter(function(value) {
    //     winston.info(value)
    //     return value.game && value.game.name && newGame.name && value.game.name == newGame.name
    //   }))
    //
    //   if(newGame && newMember.guild.presences.filter(function(value) {
    //     return value.game && value.game.name && newGame.name && value.game.name == newGame.name
    //   }).length >= 2) {
    //     newMember.guild.createChannel(`BB-${newGame.name}`, "voice")
    //       .catch(winston.error)
    //   }
    //
    //   if(oldGame && newMember.guild.presences.filter(function(value) {
    //     return value.game && value.game.name && oldGame.name && value.game.name == oldGame.name
    //   }).length < 2) {
    //     if(oldMember.guild.channels.exists("name", `BB-${oldGame.name}`)) {
    //       var oldChannel = oldMember.guild.channels.find("name", `BB-${oldGame.name}`)
    //       if(oldChannel.type == "voice" && oldChannel.members.size < 2) oldChannel.delete()
    //     }
    //   }
    // })

    // this.discord.on("ready", () => {
    //   this.discord.guilds.forEach(function(guild) {
    //     guild.presences.forEach(function(presence) {
    //       if(presence.game && presence.game.name) {
    //         if(guild.presences.slice().some(function(slicedPresence) {
    //           return slicedPresence.game && slicedPresence.game.name == presence.game.name
    //         }))

    // this.discord.on("ready", () => {
    //
    //   this.discord.guilds.forEach(function(guild) {
    //     guild.presences.forEach(function(presence) {
    //       if(presence.game && presence.game.name) {
    //         if(guild.presences.slice().some(function(slicedPresence) {
    //           if(slicedPresence.game && slicedPresence.game.name == presence.game.name) {
    //             winston.info("test")
    //             guild.createChannel(`BB-${presence.game.name}`, "voice")
    //               .catch(winston.error)
    //           }
    //         }))
    //       }
    //     })
    //   })
    //
    // })

    // this.discord.on("ready", () => {
    //
    //   this.discord.guilds.forEach(function(guild) {
    //     guild.presences.forEach(function(presence) {
    //       if(presence.game && presence.game.name) {
    //         if(guild.presences.slice(presence).some(function(slicedPresence) {
    //           if(slicedPresence.game && slicedPresence.game.name == presence.game.name) {
    //             winston.info("test")
    //           }
    //         }))
    //       }
    //     })
    //   })
    // })

    this.discord.on("ready", () => {

      // this.discord.guilds.forEach(function(guild) {
      //   guild.presences.forEach(function(presence) {
      //     if(presence.game && presence.game.name) {
      //       var newPresences = new Discord.Collection(guild.presences)
      //       newPresences.delete(presence)
      //       if(newPresences.some(function(slicedPresence) {
      //         return slicedPresence.game && slicedPresence.game.name == presence.game.name
      //       })) {
      //         winston.info(presence)
      //       }
      //     }
      //   })
      // })

      this.discord.guilds.forEach(function(guild) {

        var presences = {}
        guild.presences.forEach(function(presence) {
          if(presence.game && presence.game.name) {
            const gameName = presence.game.name
            if(presences[gameName]) {
              presences[gameName]++
            } else {
              presences[gameName] = 1
            }
          }
        })

        for(var game in presences) {
          if(presences[game] >= 2 && !guild.channels.exists("name", `BB-${game}`)) {
            winston.info(game)
            guild.createChannel(`BB-${game}`, "voice")
              .catch(winston.error)
          }
        }

      })
    })
  }
}

module.exports = VoiceAutoChannel
<|endoftext|>


<commit_before>let socket = io.connect();
$(document).ready(function(){
    console.log('hello')
    socket.on('message', function (data) {
        console.log('Client said ' + data);
        $('#alerts').html($('#alerts').html() +
        `

 ${data}

        `);
    })

});<commit_msg>meged alert<commit_after>let socket = io.connect();
$(document).ready(function(){
    console.log('hello')
    socket.on('message', function (data) {
        console.log('Client said ' + data);
        $('#alerts').html($('#alerts').html() +
        `

        <button class="close" type="button" data-dismiss="alert">×</button>

Warning!

 Check on resident ASAP!

      <button class="close" type="button" data-dismiss="alert">×</button>

 Tend to resident's needs.

 ${data}

        `);
    })

});<|endoftext|>