Commit 40e7ee1a authored by JC Brand's avatar JC Brand

Initial stab at using ES2015

Mostly replaced ``var`` with ``let`` and ``const``.
Also added a few arrow functions.
parent e1b745b7
{ {
"parserOptions": {
"ecmaVersion": 6
},
"env": { "env": {
"browser": true, "browser": true,
"jasmine": true "jasmine": true
......
...@@ -306,7 +306,7 @@ ...@@ -306,7 +306,7 @@
*/ */
var IQ_id; var IQ_id;
expect(_.filter(_converse.connection.send.calls.all(), function (call) { expect(_.filter(_converse.connection.send.calls.all(), function (call) {
var stanza = call.args[0] var stanza = call.args[0];
if (!(stanza instanceof Element) || stanza.nodeName !== 'iq') { if (!(stanza instanceof Element) || stanza.nodeName !== 'iq') {
return; return;
} }
...@@ -373,7 +373,7 @@ ...@@ -373,7 +373,7 @@
it("shows a list of bookmarks", mock.initConverseWithConnectionSpies(['send'], function (_converse) { it("shows a list of bookmarks", mock.initConverseWithConnectionSpies(['send'], function (_converse) {
var IQ_id; var IQ_id;
expect(_.filter(_converse.connection.send.calls.all(), function (call) { expect(_.filter(_converse.connection.send.calls.all(), function (call) {
var stanza = call.args[0] var stanza = call.args[0];
if (!(stanza instanceof Element) || stanza.nodeName !== 'iq') { if (!(stanza instanceof Element) || stanza.nodeName !== 'iq') {
return; return;
} }
...@@ -421,7 +421,7 @@ ...@@ -421,7 +421,7 @@
mock.initConverseWithConnectionSpies(['send'], function (_converse) { mock.initConverseWithConnectionSpies(['send'], function (_converse) {
var IQ_id; var IQ_id;
expect(_.filter(_converse.connection.send.calls.all(), function (call) { expect(_.filter(_converse.connection.send.calls.all(), function (call) {
var stanza = call.args[0] var stanza = call.args[0];
if (!(stanza instanceof Element) || stanza.nodeName !== 'iq') { if (!(stanza instanceof Element) || stanza.nodeName !== 'iq') {
return; return;
} }
......
...@@ -106,7 +106,7 @@ ...@@ -106,7 +106,7 @@
} }
return test_utils.waitUntil(function () { return test_utils.waitUntil(function () {
return _converse.chatboxviews.keys().length > 1; return _converse.chatboxviews.keys().length > 1;
}, 500) }, 500);
}).then(function () { }).then(function () {
var key = _converse.chatboxviews.keys()[1]; var key = _converse.chatboxviews.keys()[1];
trimmedview = trimmed_chatboxes.get(key); trimmedview = trimmed_chatboxes.get(key);
...@@ -268,7 +268,7 @@ ...@@ -268,7 +268,7 @@
expect(_converse.emit).toHaveBeenCalledWith('chatBoxMaximized', jasmine.any(Object)); expect(_converse.emit).toHaveBeenCalledWith('chatBoxMaximized', jasmine.any(Object));
return test_utils.waitUntil(function () { return test_utils.waitUntil(function () {
return chatview.$el.find('.chat-body').is(':visible'); return chatview.$el.find('.chat-body').is(':visible');
}, 500) }, 500);
}).then(function () { }).then(function () {
expect(chatview.$el.find('.toggle-chatbox-button').hasClass('icon-minus')).toBeTruthy(); expect(chatview.$el.find('.toggle-chatbox-button').hasClass('icon-minus')).toBeTruthy();
expect(chatview.$el.find('.toggle-chatbox-button').hasClass('icon-plus')).toBeFalsy(); expect(chatview.$el.find('.toggle-chatbox-button').hasClass('icon-plus')).toBeFalsy();
...@@ -715,12 +715,12 @@ ...@@ -715,12 +715,12 @@
.then(function () { .then(function () {
return test_utils.waitUntil(function () { return test_utils.waitUntil(function () {
return !chatboxview.model.get('auto_scrolled'); return !chatboxview.model.get('auto_scrolled');
}, 300) }, 300);
}).then(function () { }).then(function () {
chatboxview.$content.scrollTop(0); chatboxview.$content.scrollTop(0);
return test_utils.waitUntil(function () { return test_utils.waitUntil(function () {
return chatboxview.model.get('scrolled'); return chatboxview.model.get('scrolled');
}, 900) }, 900);
}).then(function () { }).then(function () {
_converse.chatboxes.onMessage($msg({ _converse.chatboxes.onMessage($msg({
from: sender_jid, from: sender_jid,
...@@ -736,7 +736,7 @@ ...@@ -736,7 +736,7 @@
expect(msg_txt).toEqual(message); expect(msg_txt).toEqual(message);
return test_utils.waitUntil(function () { return test_utils.waitUntil(function () {
return chatboxview.$('.new-msgs-indicator').is(':visible'); return chatboxview.$('.new-msgs-indicator').is(':visible');
}, 300) }, 300);
}).then(function () { }).then(function () {
expect(chatboxview.model.get('scrolled')).toBe(true); expect(chatboxview.model.get('scrolled')).toBe(true);
expect(chatboxview.$content.scrollTop()).toBe(0); expect(chatboxview.$content.scrollTop()).toBe(0);
...@@ -745,7 +745,7 @@ ...@@ -745,7 +745,7 @@
chatboxview.$content.scrollTop(chatboxview.$content[0].scrollHeight); chatboxview.$content.scrollTop(chatboxview.$content[0].scrollHeight);
return test_utils.waitUntil(function () { return test_utils.waitUntil(function () {
return !chatboxview.$('.new-msgs-indicator').is(':visible'); return !chatboxview.$('.new-msgs-indicator').is(':visible');
}, 300) }, 300);
}).then(done); }).then(done);
})); }));
...@@ -1256,7 +1256,7 @@ ...@@ -1256,7 +1256,7 @@
test_utils.sendMessage(view, message); test_utils.sendMessage(view, message);
return test_utils.waitUntil(function () { return test_utils.waitUntil(function () {
return view.$el.find('.chat-content').find('.chat-message img').length === 2; return view.$el.find('.chat-content').find('.chat-message img').length === 2;
}, 500) }, 500);
}).then(function () { }).then(function () {
expect(view.sendMessage).toHaveBeenCalled(); expect(view.sendMessage).toHaveBeenCalled();
var msg = view.$el.find('.chat-content').find('.chat-message').last().find('.chat-msg-content'); var msg = view.$el.find('.chat-content').find('.chat-message').last().find('.chat-msg-content');
...@@ -1351,7 +1351,7 @@ ...@@ -1351,7 +1351,7 @@
view.model.maximize(); view.model.maximize();
return test_utils.waitUntil(function () { return test_utils.waitUntil(function () {
return view.model.get('chat_state') === 'active'; return view.model.get('chat_state') === 'active';
}, 300) }, 300);
}).then(function () { }).then(function () {
expect(_converse.connection.send).toHaveBeenCalled(); expect(_converse.connection.send).toHaveBeenCalled();
var $stanza = $(_converse.connection.send.calls.argsFor(0)[0].tree()); var $stanza = $(_converse.connection.send.calls.argsFor(0)[0].tree());
...@@ -1496,7 +1496,7 @@ ...@@ -1496,7 +1496,7 @@
expect($stanza.children().get(0).tagName).toBe('composing'); expect($stanza.children().get(0).tagName).toBe('composing');
return test_utils.waitUntil(function () { return test_utils.waitUntil(function () {
return view.model.get('chat_state') === 'paused'; return view.model.get('chat_state') === 'paused';
}, 500) }, 500);
}).then(function () { }).then(function () {
expect(_converse.connection.send).toHaveBeenCalled(); expect(_converse.connection.send).toHaveBeenCalled();
var $stanza = $(_converse.connection.send.calls.argsFor(1)[0].tree()); var $stanza = $(_converse.connection.send.calls.argsFor(1)[0].tree());
...@@ -1618,11 +1618,11 @@ ...@@ -1618,11 +1618,11 @@
return true; return true;
} }
return false; return false;
}, 250) }, 250);
}).then(function () { }).then(function () {
return test_utils.waitUntil(function () { return test_utils.waitUntil(function () {
return view.model.get('chat_state') === 'inactive'; return view.model.get('chat_state') === 'inactive';
}, 250) }, 250);
}).then(function () { }).then(function () {
expect(_converse.connection.send).toHaveBeenCalled(); expect(_converse.connection.send).toHaveBeenCalled();
var $stanza = $(_converse.connection.send.calls.first().args[0].tree()); var $stanza = $(_converse.connection.send.calls.first().args[0].tree());
......
...@@ -43,4 +43,4 @@ ...@@ -43,4 +43,4 @@
endFile: "end-no-dependencies.frag" endFile: "end-no-dependencies.frag"
}, },
mainConfigFile: "config.js" mainConfigFile: "config.js"
}) });
...@@ -6,4 +6,4 @@ ...@@ -6,4 +6,4 @@
startFile: "start.frag", startFile: "start.frag",
endFile: "end.frag" endFile: "end.frag"
} }
}) });
...@@ -29,7 +29,7 @@ ...@@ -29,7 +29,7 @@
tpl_bookmarks_list tpl_bookmarks_list
) { ) {
var $ = converse.env.jQuery, const $ = converse.env.jQuery,
Backbone = converse.env.Backbone, Backbone = converse.env.Backbone,
Strophe = converse.env.Strophe, Strophe = converse.env.Strophe,
$iq = converse.env.$iq, $iq = converse.env.$iq,
...@@ -66,7 +66,7 @@ ...@@ -66,7 +66,7 @@
}, },
generateHeadingHTML: function () { generateHeadingHTML: function () {
var _converse = this.__super__._converse, const _converse = this.__super__._converse,
__ = _converse.__, __ = _converse.__,
html = this.__super__.generateHeadingHTML.apply(this, arguments); html = this.__super__.generateHeadingHTML.apply(this, arguments);
if (_converse.allow_bookmarks) { if (_converse.allow_bookmarks) {
...@@ -92,11 +92,11 @@ ...@@ -92,11 +92,11 @@
* for this room, and if so use it. * for this room, and if so use it.
* Otherwise delegate to the super method. * Otherwise delegate to the super method.
*/ */
var _converse = this.__super__._converse; const _converse = this.__super__._converse;
if (_.isUndefined(_converse.bookmarks) || !_converse.allow_bookmarks) { if (_.isUndefined(_converse.bookmarks) || !_converse.allow_bookmarks) {
return this.__super__.checkForReservedNick.apply(this, arguments); return this.__super__.checkForReservedNick.apply(this, arguments);
} }
var model = _converse.bookmarks.findWhere({'jid': this.model.get('jid')}); const model = _converse.bookmarks.findWhere({'jid': this.model.get('jid')});
if (!_.isUndefined(model) && model.get('nick')) { if (!_.isUndefined(model) && model.get('nick')) {
this.join(model.get('nick')); this.join(model.get('nick'));
} else { } else {
......
...@@ -30,7 +30,7 @@ ...@@ -30,7 +30,7 @@
tpl_spinner tpl_spinner
) { ) {
"use strict"; "use strict";
var $ = converse.env.jQuery, const $ = converse.env.jQuery,
$msg = converse.env.$msg, $msg = converse.env.$msg,
Backbone = converse.env.Backbone, Backbone = converse.env.Backbone,
Strophe = converse.env.Strophe, Strophe = converse.env.Strophe,
...@@ -38,7 +38,7 @@ ...@@ -38,7 +38,7 @@
moment = converse.env.moment, moment = converse.env.moment,
utils = converse.env.utils; utils = converse.env.utils;
var KEY = { const KEY = {
ENTER: 13, ENTER: 13,
FORWARD_SLASH: 47 FORWARD_SLASH: 47
}; };
...@@ -55,8 +55,8 @@ ...@@ -55,8 +55,8 @@
ChatBoxViews: { ChatBoxViews: {
onChatBoxAdded: function (item) { onChatBoxAdded: function (item) {
var _converse = this.__super__._converse; const _converse = this.__super__._converse;
var view = this.get(item.get('id')); let view = this.get(item.get('id'));
if (!view) { if (!view) {
view = new _converse.ChatBoxView({model: item}); view = new _converse.ChatBoxView({model: item});
this.add(item.get('id'), view); this.add(item.get('id'), view);
...@@ -73,7 +73,7 @@ ...@@ -73,7 +73,7 @@
/* The initialize function gets called as soon as the plugin is /* The initialize function gets called as soon as the plugin is
* loaded by converse.js's plugin machinery. * loaded by converse.js's plugin machinery.
*/ */
var _converse = this._converse, const _converse = this._converse,
__ = _converse.__; __ = _converse.__;
_converse.api.settings.update({ _converse.api.settings.update({
...@@ -88,12 +88,11 @@ ...@@ -88,12 +88,11 @@
}, },
}); });
var onWindowStateChanged = function (data) { function onWindowStateChanged (data) {
var state = data.state;
_converse.chatboxviews.each(function (chatboxview) { _converse.chatboxviews.each(function (chatboxview) {
chatboxview.onWindowStateChanged(state); chatboxview.onWindowStateChanged(data.state);
}) });
}; }
_converse.api.listen.on('windowStateChanged', onWindowStateChanged); _converse.api.listen.on('windowStateChanged', onWindowStateChanged);
...@@ -173,7 +172,7 @@ ...@@ -173,7 +172,7 @@
/* This method gets overridden in src/converse-controlbox.js if /* This method gets overridden in src/converse-controlbox.js if
* the controlbox plugin is active. * the controlbox plugin is active.
*/ */
var container = document.querySelector('#conversejs'); const container = document.querySelector('#conversejs');
if (this.el.parentNode !== container) { if (this.el.parentNode !== container) {
container.insertBefore(this.el, container.firstChild); container.insertBefore(this.el, container.firstChild);
} }
...@@ -188,7 +187,7 @@ ...@@ -188,7 +187,7 @@
if (!keep_old) { if (!keep_old) {
this.clearStatusNotification(); this.clearStatusNotification();
} }
var $el = $('<div class="chat-info"></div>').text(message); const $el = $('<div class="chat-info"></div>').text(message);
if (!permanent) { if (!permanent) {
$el.addClass('chat-event'); $el.addClass('chat-event');
} }
...@@ -216,8 +215,8 @@ ...@@ -216,8 +215,8 @@
* Parameters: * Parameters:
* (String) date - An ISO8601 date string. * (String) date - An ISO8601 date string.
*/ */
var day_date = moment(date).startOf('day'); const day_date = moment(date).startOf('day');
var insert = prepend ? this.$content.prepend: this.$content.append; const insert = prepend ? this.$content.prepend: this.$content.append;
insert.call(this.$content, tpl_new_day({ insert.call(this.$content, tpl_new_day({
isodate: day_date.format(), isodate: day_date.format(),
datestring: day_date.format("dddd MMM Do YYYY") datestring: day_date.format("dddd MMM Do YYYY")
...@@ -232,11 +231,9 @@ ...@@ -232,11 +231,9 @@
* Parameters: * Parameters:
* (Object) attrs: An object containing the message attributes. * (Object) attrs: An object containing the message attributes.
*/ */
var that = this; const insert = prepend ? this.$content.prepend : this.$content.append;
var insert = prepend ? this.$content.prepend : this.$content.append; _.flow(($el) => {
_.flow( insert.call(this.$content, $el);
function ($el) {
insert.call(that.$content, $el);
return $el; return $el;
}, },
this.scrollDown.bind(this) this.scrollDown.bind(this)
...@@ -255,11 +252,9 @@ ...@@ -255,11 +252,9 @@
* (Object) attrs: An object containing the message * (Object) attrs: An object containing the message
* attributes. * attributes.
*/ */
var msg_dates, let current_msg_date = moment(attrs.time) || moment;
$first_msg = this.$content.find('.chat-message:first'), const $first_msg = this.$content.find('.chat-message:first'),
first_msg_date = $first_msg.data('isodate'), first_msg_date = $first_msg.data('isodate');
current_msg_date = moment(attrs.time) || moment,
last_msg_date = this.$content.find('.chat-message:last').data('isodate');
if (!first_msg_date) { if (!first_msg_date) {
// This is the first received message, so we insert a // This is the first received message, so we insert a
...@@ -268,6 +263,8 @@ ...@@ -268,6 +263,8 @@
this.insertMessage(attrs); this.insertMessage(attrs);
return; return;
} }
const last_msg_date = this.$content.find('.chat-message:last').data('isodate');
if (current_msg_date.isAfter(last_msg_date) || if (current_msg_date.isAfter(last_msg_date) ||
current_msg_date.isSame(last_msg_date)) { current_msg_date.isSame(last_msg_date)) {
// The new message is after the last message // The new message is after the last message
...@@ -294,16 +291,17 @@ ...@@ -294,16 +291,17 @@
} }
// Find the correct place to position the message // Find the correct place to position the message
current_msg_date = current_msg_date.format(); current_msg_date = current_msg_date.format();
msg_dates = _.map(this.$content.find('.chat-message'), function (el) { const msg_dates = _.map(this.$content.find('.chat-message'), function (el) {
return $(el).data('isodate'); return $(el).data('isodate');
}); });
msg_dates.push(current_msg_date); msg_dates.push(current_msg_date);
msg_dates.sort(); msg_dates.sort();
var idx = msg_dates.indexOf(current_msg_date)-1;
var $latest_message = this.$content.find('.chat-message[data-isodate="'+msg_dates[idx]+'"]:last'); const idx = msg_dates.indexOf(current_msg_date)-1;
_.flow( const $latest_message = this.$content.find('.chat-message[data-isodate="'+msg_dates[idx]+'"]:last');
function ($el) { _.flow(($el) => {
$el.insertAfter($latest_message); $el.insertAfter($latest_message);
return $el;
}, },
this.scrollDown.bind(this) this.scrollDown.bind(this)
)(this.renderMessage(attrs)); )(this.renderMessage(attrs));
...@@ -332,12 +330,11 @@ ...@@ -332,12 +330,11 @@
* Returns: * Returns:
* The DOM element representing the message. * The DOM element representing the message.
*/ */
var msg_time = moment(attrs.time) || moment, let text = attrs.message,
text = attrs.message,
match = text.match(/^\/(.*?)(?: (.*))?$/),
fullname = this.model.get('fullname') || attrs.fullname, fullname = this.model.get('fullname') || attrs.fullname,
template, username; template, username;
const match = text.match(/^\/(.*?)(?: (.*))?$/);
if ((match) && (match[1] === 'me')) { if ((match) && (match[1] === 'me')) {
text = text.replace(/^\/me/, ''); text = text.replace(/^\/me/, '');
template = tpl_action; template = tpl_action;
...@@ -361,7 +358,8 @@ ...@@ -361,7 +358,8 @@
"Output has been shortened."), "Output has been shortened."),
true, true); true, true);
} }
var $msg = $(template( const msg_time = moment(attrs.time) || moment;
const $msg = $(template(
_.extend(this.getExtraMessageTemplateAttributes(attrs), { _.extend(this.getExtraMessageTemplateAttributes(attrs), {
'msgid': attrs.msgid, 'msgid': attrs.msgid,
'sender': attrs.sender, 'sender': attrs.sender,
...@@ -379,13 +377,12 @@ ...@@ -379,13 +377,12 @@
}, },
showHelpMessages: function (msgs, type, spinner) { showHelpMessages: function (msgs, type, spinner) {
var i, msgs_length = msgs.length; _.each(msgs, (msg) => {
for (i=0; i<msgs_length; i++) {
this.$content.append($(tpl_help_message({ this.$content.append($(tpl_help_message({
'type': type||'info', 'type': type||'info',
'message': msgs[i] 'message': msgs
}))); })));
} });
if (spinner === true) { if (spinner === true) {
this.$content.append(tpl_spinner); this.$content.append(tpl_spinner);
} else if (spinner === false) { } else if (spinner === false) {
...@@ -440,7 +437,7 @@ ...@@ -440,7 +437,7 @@
}, },
handleErrorMessage: function (message) { handleErrorMessage: function (message) {
var $message = $('[data-msgid='+message.get('msgid')+']'); const $message = $('[data-msgid='+message.get('msgid')+']');
if ($message.length) { if ($message.length) {
$message.after($('<div class="chat-info chat-error"></div>').text(message.get('message'))); $message.after($('<div class="chat-info chat-error"></div>').text(message.get('message')));
this.scrollDown(); this.scrollDown();
...@@ -488,7 +485,7 @@ ...@@ -488,7 +485,7 @@
*/ */
// TODO: We might want to send to specfic resources. // TODO: We might want to send to specfic resources.
// Especially in the OTR case. // Especially in the OTR case.
var messageStanza = this.createMessageStanza(message); const messageStanza = this.createMessageStanza(message);
_converse.connection.send(messageStanza); _converse.connection.send(messageStanza);
if (_converse.forward_messages) { if (_converse.forward_messages) {
// Forward the message, so that other connected resources are also aware of it. // Forward the message, so that other connected resources are also aware of it.
...@@ -515,13 +512,13 @@ ...@@ -515,13 +512,13 @@
'error' 'error'
); );
} }
var match = text.replace(/^\s*/, "").match(/^\/(.*)\s*$/), msgs; const match = text.replace(/^\s*/, "").match(/^\/(.*)\s*$/);
if (match) { if (match) {
if (match[1] === "clear") { if (match[1] === "clear") {
return this.clearMessages(); return this.clearMessages();
} }
else if (match[1] === "help") { else if (match[1] === "help") {
msgs = [ const msgs = [
'<strong>/help</strong>:'+__('Show this menu')+'', '<strong>/help</strong>:'+__('Show this menu')+'',
'<strong>/me</strong>:'+__('Write in the third person')+'', '<strong>/me</strong>:'+__('Write in the third person')+'',
'<strong>/clear</strong>:'+__('Remove messages')+'' '<strong>/clear</strong>:'+__('Remove messages')+''
...@@ -530,9 +527,10 @@ ...@@ -530,9 +527,10 @@
return; return;
} }
} }
var fullname = _converse.xmppstatus.get('fullname'); let fullname = _converse.xmppstatus.get('fullname');
fullname = _.isEmpty(fullname)? _converse.bare_jid: fullname; fullname = _.isEmpty(fullname)? _converse.bare_jid: fullname;
var message = this.model.messages.create({
const message = this.model.messages.create({
fullname: fullname, fullname: fullname,
sender: 'me', sender: 'me',
time: moment().format(), time: moment().format(),
...@@ -586,10 +584,10 @@ ...@@ -586,10 +584,10 @@
keyPressed: function (ev) { keyPressed: function (ev) {
/* Event handler for when a key is pressed in a chat box textarea. /* Event handler for when a key is pressed in a chat box textarea.
*/ */
var textarea = ev.target, message;
if (ev.keyCode === KEY.ENTER) { if (ev.keyCode === KEY.ENTER) {
ev.preventDefault(); ev.preventDefault();
message = textarea.value; const textarea = ev.target;
const message = textarea.value;
textarea.value = ''; textarea.value = '';
textarea.focus(); textarea.focus();
if (message !== '') { if (message !== '') {
...@@ -608,7 +606,7 @@ ...@@ -608,7 +606,7 @@
/* Event handler for when a send button is clicked in a chat box textarea. /* Event handler for when a send button is clicked in a chat box textarea.
*/ */
ev.preventDefault(); ev.preventDefault();
var textarea = this.el.querySelector('.chat-textarea'), const textarea = this.el.querySelector('.chat-textarea'),
message = textarea.value; message = textarea.value;
textarea.value = ''; textarea.value = '';
...@@ -622,7 +620,7 @@ ...@@ -622,7 +620,7 @@
clearMessages: function (ev) { clearMessages: function (ev) {
if (ev && ev.preventDefault) { ev.preventDefault(); } if (ev && ev.preventDefault) { ev.preventDefault(); }
var result = confirm(__("Are you sure you want to clear the messages from this chat box?")); const result = confirm(__("Are you sure you want to clear the messages from this chat box?"));
if (result === true) { if (result === true) {
this.$content.empty(); this.$content.empty();
this.model.messages.reset(); this.model.messages.reset();
...@@ -632,8 +630,8 @@ ...@@ -632,8 +630,8 @@
}, },
insertIntoTextArea: function (value) { insertIntoTextArea: function (value) {
var $textbox = this.$el.find('textarea.chat-textarea'); const $textbox = this.$el.find('textarea.chat-textarea');
var existing = $textbox.val(); let existing = $textbox.val();
if (existing && (existing[existing.length-1] !== ' ')) { if (existing && (existing[existing.length-1] !== ' ')) {
existing = existing + ' '; existing = existing + ' ';
} }
...@@ -643,7 +641,7 @@ ...@@ -643,7 +641,7 @@
insertEmoticon: function (ev) { insertEmoticon: function (ev) {
ev.stopPropagation(); ev.stopPropagation();
this.$el.find('.toggle-smiley ul').slideToggle(200); this.$el.find('.toggle-smiley ul').slideToggle(200);
var $target = $(ev.target); let $target = $(ev.target);
$target = $target.is('a') ? $target : $target.children('a'); $target = $target.is('a') ? $target : $target.children('a');
this.insertIntoTextArea($target.data('emoticon')); this.insertIntoTextArea($target.data('emoticon'));
}, },
...@@ -662,8 +660,8 @@ ...@@ -662,8 +660,8 @@
}, },
onChatStatusChanged: function (item) { onChatStatusChanged: function (item) {
var chat_status = item.get('chat_status'), const chat_status = item.get('chat_status');
fullname = item.get('fullname'); let fullname = item.get('fullname');
fullname = _.isEmpty(fullname)? item.get('jid'): fullname; fullname = _.isEmpty(fullname)? item.get('jid'): fullname;
if (this.$el.is(':visible')) { if (this.$el.is(':visible')) {
if (chat_status === 'offline') { if (chat_status === 'offline') {
...@@ -738,9 +736,9 @@ ...@@ -738,9 +736,9 @@
if (!this.model.get('image')) { if (!this.model.get('image')) {
return; return;
} }
var width = _converse.chatview_avatar_width; const width = _converse.chatview_avatar_width;
var height = _converse.chatview_avatar_height; const height = _converse.chatview_avatar_height;
var img_src = 'data:'+this.model.get('image_type')+';base64,'+this.model.get('image'), const img_src = 'data:'+this.model.get('image_type')+';base64,'+this.model.get('image'),
canvas = $(tpl_avatar({ canvas = $(tpl_avatar({
'width': width, 'width': width,
'height': height 'height': height
...@@ -749,10 +747,10 @@ ...@@ -749,10 +747,10 @@
if (!(canvas.getContext && canvas.getContext('2d'))) { if (!(canvas.getContext && canvas.getContext('2d'))) {
return this; return this;
} }
var ctx = canvas.getContext('2d'); const ctx = canvas.getContext('2d');
var img = new Image(); // Create new Image object const img = new Image(); // Create new Image object
img.onload = function () { img.onload = function () {
var ratio = img.width/img.height; const ratio = img.width/img.height;
if (ratio < 1) { if (ratio < 1) {
ctx.drawImage(img, 0,0, width, height*(1/ratio)); ctx.drawImage(img, 0,0, width, height*(1/ratio));
} else { } else {
...@@ -810,7 +808,7 @@ ...@@ -810,7 +808,7 @@
}, },
hideNewMessagesIndicator: function () { hideNewMessagesIndicator: function () {
var new_msgs_indicator = this.el.querySelector('.new-msgs-indicator'); const new_msgs_indicator = this.el.querySelector('.new-msgs-indicator');
if (!_.isNull(new_msgs_indicator)) { if (!_.isNull(new_msgs_indicator)) {
new_msgs_indicator.classList.add('hidden'); new_msgs_indicator.classList.add('hidden');
} }
...@@ -831,8 +829,8 @@ ...@@ -831,8 +829,8 @@
}); });
return; return;
} }
var scrolled = true; let scrolled = true;
var is_at_bottom = const is_at_bottom =
(this.$content.scrollTop() + this.$content.innerHeight()) >= (this.$content.scrollTop() + this.$content.innerHeight()) >=
this.$content[0].scrollHeight-10; this.$content[0].scrollHeight-10;
if (is_at_bottom) { if (is_at_bottom) {
......
...@@ -42,14 +42,14 @@ ...@@ -42,14 +42,14 @@
) { ) {
"use strict"; "use strict";
var USERS_PANEL_ID = 'users'; const USERS_PANEL_ID = 'users';
var CHATBOX_TYPE = 'chatbox'; const CHATBOX_TYPE = 'chatbox';
// Strophe methods for building stanzas // Strophe methods for building stanzas
var Strophe = converse.env.Strophe, const Strophe = converse.env.Strophe,
Backbone = converse.env.Backbone, Backbone = converse.env.Backbone,
utils = converse.env.utils; utils = converse.env.utils;
// Other necessary globals // Other necessary globals
var $ = converse.env.jQuery, const $ = converse.env.jQuery,
_ = converse.env._, _ = converse.env._,
fp = converse.env.fp, fp = converse.env.fp,
moment = converse.env.moment; moment = converse.env.moment;
...@@ -188,7 +188,7 @@ ...@@ -188,7 +188,7 @@
/* The initialize function gets called as soon as the plugin is /* The initialize function gets called as soon as the plugin is
* loaded by converse.js's plugin machinery. * loaded by converse.js's plugin machinery.
*/ */
var _converse = this._converse, const _converse = this._converse,
__ = _converse.__; __ = _converse.__;
_converse.api.settings.update({ _converse.api.settings.update({
...@@ -200,12 +200,13 @@ ...@@ -200,12 +200,13 @@
xhr_user_search_url: '' xhr_user_search_url: ''
}); });
var LABEL_CONTACTS = __('Contacts'); const LABEL_CONTACTS = __('Contacts');
_converse.addControlBox = function () { _converse.addControlBox = function () {
return _converse.chatboxes.add({ return _converse.chatboxes.add({
id: 'controlbox', id: 'controlbox',
box_id: 'controlbox', box_id: 'controlbox',
type: 'controlbox',
closed: !_converse.show_controlbox_by_default closed: !_converse.show_controlbox_by_default
}); });
}; };
......
...@@ -30,14 +30,14 @@ ...@@ -30,14 +30,14 @@
// "use strict"; // "use strict";
// Create the FP (functional programming) version of lodash // Create the FP (functional programming) version of lodash
var fp = lodashConverter(_.runInContext()); const fp = lodashConverter(_.runInContext());
// Strophe globals // Strophe globals
var $build = Strophe.$build; const $build = Strophe.$build;
var $iq = Strophe.$iq; const $iq = Strophe.$iq;
var $msg = Strophe.$msg; const $msg = Strophe.$msg;
var $pres = Strophe.$pres; const $pres = Strophe.$pres;
var b64_sha1 = Strophe.SHA1.b64_sha1; const b64_sha1 = Strophe.SHA1.b64_sha1;
Strophe = Strophe.Strophe; Strophe = Strophe.Strophe;
// Use Mustache style syntax for variable interpolation // Use Mustache style syntax for variable interpolation
...@@ -50,7 +50,7 @@ ...@@ -50,7 +50,7 @@
'interpolate': /\{\{([\s\S]+?)\}\}/g 'interpolate': /\{\{([\s\S]+?)\}\}/g
}; };
var _converse = {}; const _converse = {};
_converse.templates = {}; _converse.templates = {};
_.extend(_converse, Backbone.Events); _.extend(_converse, Backbone.Events);
_converse.promises = { _converse.promises = {
...@@ -66,7 +66,7 @@ ...@@ -66,7 +66,7 @@
}; };
_converse.emit = function (name) { _converse.emit = function (name) {
_converse.trigger.apply(this, arguments); _converse.trigger.apply(this, arguments);
var promise = _converse.promises[name]; const promise = _converse.promises[name];
if (!_.isUndefined(promise)) { if (!_.isUndefined(promise)) {
promise.resolve(); promise.resolve();
} }
...@@ -121,7 +121,7 @@ ...@@ -121,7 +121,7 @@
_converse.OPENED = 'opened'; _converse.OPENED = 'opened';
_converse.PREBIND = "prebind"; _converse.PREBIND = "prebind";
var PRETTY_CONNECTION_STATUS = { const PRETTY_CONNECTION_STATUS = {
0: 'ERROR', 0: 'ERROR',
1: 'CONNECTING', 1: 'CONNECTING',
2: 'CONNFAIL', 2: 'CONNFAIL',
...@@ -134,11 +134,11 @@ ...@@ -134,11 +134,11 @@
9: 'REDIRECT' 9: 'REDIRECT'
}; };
var DEFAULT_IMAGE_TYPE = 'image/png'; const DEFAULT_IMAGE_TYPE = 'image/png';
var DEFAULT_IMAGE = "iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAIAAABt+uBvAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3gwHCy455JBsggAABkJJREFUeNrtnM1PE1sUwHvvTD8otWLHST/Gimi1CEgr6M6FEWuIBo2pujDVsNDEP8GN/4MbN7oxrlipG2OCgZgYlxAbkRYw1KqkIDRCSkM7nXvvW8x7vjyNeQ9m7p1p3z1LQk/v/Dhz7vkEXL161cHl9wI5Ag6IA+KAOCAOiAPigDggLhwQB2S+iNZ+PcYY/SWEEP2HAAAIoSAIoihCCP+ngDDGtVotGAz29/cfOXJEUZSOjg6n06lp2sbGRqlUWlhYyGazS0tLbrdbEASrzgksyeYJId3d3el0uqenRxRFAAAA4KdfIIRgjD9+/Pj8+fOpqSndslofEIQwHA6Pjo4mEon//qmFhYXHjx8vLi4ihBgDEnp7e9l8E0Jo165dQ0NDd+/eDYVC2/qsJElDQ0OEkKWlpa2tLZamxAhQo9EIBoOjo6MXL17csZLe3l5FUT59+lQul5l5JRaAVFWNRqN37tw5ceKEQVWRSOTw4cOFQuHbt2+iKLYCIISQLMu3b99OJpOmKAwEAgcPHszn8+vr6wzsiG6UQQhxuVyXLl0aGBgwUW0sFstkMl6v90fo1KyAMMYDAwPnzp0zXfPg4GAqlWo0Gk0MiBAiy/L58+edTqf5Aa4onj59OhaLYYybFRCEMBaL0fNxBw4cSCQStN0QRUBut3t4eJjq6U+dOiVJElVPRBFQIBDo6+ujCqirqyscDlONGykC2lYyYSR6pBoQQapHZwAoHo/TuARYAOrs7GQASFEUqn6aIiBJkhgA6ujooFpUo6iaTa7koFwnaoWadLNe81tbWwzoaJrWrICWl5cZAFpbW6OabVAEtLi4yABQsVjUNK0pAWWzWQaAcrlcswKanZ1VVZUqHYRQEwOq1Wpv3ryhCmh6erpcLjdrNl+v1ycnJ+l5UELI27dvv3//3qxxEADgy5cvExMT9Mznw4cPtFtAdAPFarU6Pj5eKpVM17yxsfHy5cvV1VXazXu62gVBKBQKT58+rdVqJqrFGL948eLdu3dU8/g/H4FBUaJYLAqC0NPTY9brMD4+PjY25mDSracOCABACJmZmXE6nUePHjWu8NWrV48ePSKEsGlAs7Agfd5nenq6Wq0mk0kjDzY2NvbkyRMIIbP2PLvhBUEQ8vl8NpuNx+M+n29bzhVjvLKycv/+/YmJCcazQuwA6YzW1tYmJyf1SY+2trZ/rRk1Go1SqfT69esHDx4UCgVmNaa/zZ/9ABUhRFXVYDB48uTJeDweiUQkSfL7/T9MA2NcqVTK5fLy8vL8/PzU1FSxWHS5XJaM4wGr9sUwxqqqer3eUCgkSZJuUBBCfTRvc3OzXC6vrKxUKhWn02nhCJ5lM4oQQo/HgxD6+vXr58+fHf8sDOp+HQDg8XgclorFU676dKLlo6yWRdItIBwQB8QBcUCtfosRQjRNQwhhjPUC4w46WXryBSHU1zgEQWBz99EFhDGu1+t+v//48ePxeFxRlD179ng8nh0Efgiher2+vr6ur3HMzMysrq7uTJVdACGEurq6Ll++nEgkPB7Pj9jPoDHqOxyqqubz+WfPnuVyuV9XPeyeagAAAoHArVu3BgcHab8CuVzu4cOHpVKJUnfA5GweY+xyuc6cOXPv3r1IJMLAR8iyPDw8XK/Xi8Wiqqqmm5KZgBBC7e3tN27cuHbtGuPVpf7+/lAoNDs7W61WzfVKpgHSSzw3b95MpVKW3MfRaDQSiczNzVUqFRMZmQOIEOL1eq9fv3727FlL1t50URRFluX5+flqtWpWEGAOIFEUU6nUlStXLKSjy759+xwOx9zcnKZpphzGHMzhcDiTydgk9r1w4YIp7RPTAAmCkMlk2FeLf/tIEKbTab/fbwtAhJBoNGrutpNx6e7uPnTokC1eMU3T0um0DZPMkZER6wERQnw+n/FFSxpy7Nix3bt3WwwIIcRgIWnHkkwmjecfRgGx7DtuV/r6+iwGhDHev3+/bQF1dnYaH6E2CkiWZdsC2rt3r8WAHA5HW1ubbQGZcjajgOwTH/4qNko1Wlg4IA6IA+KAOKBWBUQIsfNojyliKIoRRfH9+/dut9umf3wzpoUNNQ4BAJubmwz+ic+OxefzWWlBhJD29nbug7iT5sIBcUAcEAfEAXFAHBAHxOVn+QMrmWpuPZx12gAAAABJRU5ErkJggg=="; const DEFAULT_IMAGE = "iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAIAAABt+uBvAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3gwHCy455JBsggAABkJJREFUeNrtnM1PE1sUwHvvTD8otWLHST/Gimi1CEgr6M6FEWuIBo2pujDVsNDEP8GN/4MbN7oxrlipG2OCgZgYlxAbkRYw1KqkIDRCSkM7nXvvW8x7vjyNeQ9m7p1p3z1LQk/v/Dhz7vkEXL161cHl9wI5Ag6IA+KAOCAOiAPigDggLhwQB2S+iNZ+PcYY/SWEEP2HAAAIoSAIoihCCP+ngDDGtVotGAz29/cfOXJEUZSOjg6n06lp2sbGRqlUWlhYyGazS0tLbrdbEASrzgksyeYJId3d3el0uqenRxRFAAAA4KdfIIRgjD9+/Pj8+fOpqSndslofEIQwHA6Pjo4mEon//qmFhYXHjx8vLi4ihBgDEnp7e9l8E0Jo165dQ0NDd+/eDYVC2/qsJElDQ0OEkKWlpa2tLZamxAhQo9EIBoOjo6MXL17csZLe3l5FUT59+lQul5l5JRaAVFWNRqN37tw5ceKEQVWRSOTw4cOFQuHbt2+iKLYCIISQLMu3b99OJpOmKAwEAgcPHszn8+vr6wzsiG6UQQhxuVyXLl0aGBgwUW0sFstkMl6v90fo1KyAMMYDAwPnzp0zXfPg4GAqlWo0Gk0MiBAiy/L58+edTqf5Aa4onj59OhaLYYybFRCEMBaL0fNxBw4cSCQStN0QRUBut3t4eJjq6U+dOiVJElVPRBFQIBDo6+ujCqirqyscDlONGykC2lYyYSR6pBoQQapHZwAoHo/TuARYAOrs7GQASFEUqn6aIiBJkhgA6ujooFpUo6iaTa7koFwnaoWadLNe81tbWwzoaJrWrICWl5cZAFpbW6OabVAEtLi4yABQsVjUNK0pAWWzWQaAcrlcswKanZ1VVZUqHYRQEwOq1Wpv3ryhCmh6erpcLjdrNl+v1ycnJ+l5UELI27dvv3//3qxxEADgy5cvExMT9Mznw4cPtFtAdAPFarU6Pj5eKpVM17yxsfHy5cvV1VXazXu62gVBKBQKT58+rdVqJqrFGL948eLdu3dU8/g/H4FBUaJYLAqC0NPTY9brMD4+PjY25mDSracOCABACJmZmXE6nUePHjWu8NWrV48ePSKEsGlAs7Agfd5nenq6Wq0mk0kjDzY2NvbkyRMIIbP2PLvhBUEQ8vl8NpuNx+M+n29bzhVjvLKycv/+/YmJCcazQuwA6YzW1tYmJyf1SY+2trZ/rRk1Go1SqfT69esHDx4UCgVmNaa/zZ/9ABUhRFXVYDB48uTJeDweiUQkSfL7/T9MA2NcqVTK5fLy8vL8/PzU1FSxWHS5XJaM4wGr9sUwxqqqer3eUCgkSZJuUBBCfTRvc3OzXC6vrKxUKhWn02nhCJ5lM4oQQo/HgxD6+vXr58+fHf8sDOp+HQDg8XgclorFU676dKLlo6yWRdItIBwQB8QBcUCtfosRQjRNQwhhjPUC4w46WXryBSHU1zgEQWBz99EFhDGu1+t+v//48ePxeFxRlD179ng8nh0Efgiher2+vr6ur3HMzMysrq7uTJVdACGEurq6Ll++nEgkPB7Pj9jPoDHqOxyqqubz+WfPnuVyuV9XPeyeagAAAoHArVu3BgcHab8CuVzu4cOHpVKJUnfA5GweY+xyuc6cOXPv3r1IJMLAR8iyPDw8XK/Xi8Wiqqqmm5KZgBBC7e3tN27cuHbtGuPVpf7+/lAoNDs7W61WzfVKpgHSSzw3b95MpVKW3MfRaDQSiczNzVUqFRMZmQOIEOL1eq9fv3727FlL1t50URRFluX5+flqtWpWEGAOIFEUU6nUlStXLKSjy759+xwOx9zcnKZpphzGHMzhcDiTydgk9r1w4YIp7RPTAAmCkMlk2FeLf/tIEKbTab/fbwtAhJBoNGrutpNx6e7uPnTokC1eMU3T0um0DZPMkZER6wERQnw+n/FFSxpy7Nix3bt3WwwIIcRgIWnHkkwmjecfRgGx7DtuV/r6+iwGhDHev3+/bQF1dnYaH6E2CkiWZdsC2rt3r8WAHA5HW1ubbQGZcjajgOwTH/4qNko1Wlg4IA6IA+KAOKBWBUQIsfNojyliKIoRRfH9+/dut9umf3wzpoUNNQ4BAJubmwz+ic+OxefzWWlBhJD29nbug7iT5sIBcUAcEAfEAXFAHBAHxOVn+QMrmWpuPZx12gAAAABJRU5ErkJggg==";
_converse.log = function (txt, level) { _converse.log = function (txt, level) {
var logger = _.assignIn({ const logger = _.assignIn({
'debug': _.noop, 'debug': _.noop,
'error': _.noop, 'error': _.noop,
'info': _.noop, 'info': _.noop,
...@@ -170,7 +170,7 @@ ...@@ -170,7 +170,7 @@
_converse.initialize = function (settings, callback) { _converse.initialize = function (settings, callback) {
"use strict"; "use strict";
settings = !_.isUndefined(settings) ? settings : {}; settings = !_.isUndefined(settings) ? settings : {};
var init_deferred = new $.Deferred(); const init_deferred = new $.Deferred();
if (!_.isUndefined(_converse.chatboxes)) { if (!_.isUndefined(_converse.chatboxes)) {
// Looks like _converse.initialized was called again without logging // Looks like _converse.initialized was called again without logging
...@@ -182,7 +182,7 @@ ...@@ -182,7 +182,7 @@
_converse._tearDown(); _converse._tearDown();
} }
var unloadevent; let unloadevent;
if ('onpagehide' in window) { if ('onpagehide' in window) {
// Pagehide gets thrown in more cases than unload. Specifically it // Pagehide gets thrown in more cases than unload. Specifically it
// gets thrown when the page is cached and not just // gets thrown when the page is cached and not just
...@@ -225,7 +225,7 @@ ...@@ -225,7 +225,7 @@
moment.locale = moment.lang; moment.locale = moment.lang;
} }
moment.locale(utils.getLocale(settings.i18n, utils.isMomentLocale)); moment.locale(utils.getLocale(settings.i18n, utils.isMomentLocale));
var __ = _converse.__ = utils.__.bind(_converse); const __ = _converse.__ = utils.__.bind(_converse);
_converse.___ = utils.___; _converse.___ = utils.___;
// XEP-0085 Chat states // XEP-0085 Chat states
...@@ -364,7 +364,7 @@ ...@@ -364,7 +364,7 @@
// This can happen when the connection reconnects. // This can happen when the connection reconnects.
return; return;
} }
var stat = _converse.xmppstatus.getStatus(); const stat = _converse.xmppstatus.getStatus();
_converse.idle_seconds++; _converse.idle_seconds++;
if (_converse.csi_waiting_time > 0 && if (_converse.csi_waiting_time > 0 &&
_converse.idle_seconds > _converse.csi_waiting_time && _converse.idle_seconds > _converse.csi_waiting_time &&
...@@ -403,7 +403,7 @@ ...@@ -403,7 +403,7 @@
}; };
this.giveFeedback = function (subject, klass, message) { this.giveFeedback = function (subject, klass, message) {
var els = document.querySelectorAll('.conn-feedback'); const els = document.querySelectorAll('.conn-feedback');
_.forEach(els, function (el) { _.forEach(els, function (el) {
el.classList.add('conn-feedback'); el.classList.add('conn-feedback');
el.textContent = subject; el.textContent = subject;
...@@ -428,7 +428,7 @@ ...@@ -428,7 +428,7 @@
* is being canceled. * is being canceled.
* (String) message - An optional message to the user * (String) message - An optional message to the user
*/ */
var pres = $pres({to: jid, type: "unsubscribed"}); const pres = $pres({to: jid, type: "unsubscribed"});
if (message && message !== "") { pres.c("status").t(message); } if (message && message !== "") { pres.c("status").t(message); }
_converse.connection.send(pres); _converse.connection.send(pres);
}; };
...@@ -543,7 +543,7 @@ ...@@ -543,7 +543,7 @@
this.incrementMsgCounter = function () { this.incrementMsgCounter = function () {
this.msg_counter += 1; this.msg_counter += 1;
var unreadMsgCount = this.msg_counter; const unreadMsgCount = this.msg_counter;
if (document.title.search(/^Messages \(\d+\) /) === -1) { if (document.title.search(/^Messages \(\d+\) /) === -1) {
document.title = "Messages (" + unreadMsgCount + ") " + document.title; document.title = "Messages (" + unreadMsgCount + ") " + document.title;
} else { } else {
...@@ -559,9 +559,9 @@ ...@@ -559,9 +559,9 @@
}; };
this.initStatus = function () { this.initStatus = function () {
var deferred = new $.Deferred(); const deferred = new $.Deferred();
this.xmppstatus = new this.XMPPStatus(); this.xmppstatus = new this.XMPPStatus();
var id = b64_sha1('converse.xmppstatus-'+_converse.bare_jid); const id = b64_sha1('converse.xmppstatus-'+_converse.bare_jid);
this.xmppstatus.id = id; // Appears to be necessary for backbone.browserStorage this.xmppstatus.id = id; // Appears to be necessary for backbone.browserStorage
this.xmppstatus.browserStorage = new Backbone.BrowserStorage[_converse.storage](id); this.xmppstatus.browserStorage = new Backbone.BrowserStorage[_converse.storage](id);
this.xmppstatus.fetch({ this.xmppstatus.fetch({
...@@ -574,7 +574,7 @@ ...@@ -574,7 +574,7 @@
this.initSession = function () { this.initSession = function () {
this.session = new this.Session(); this.session = new this.Session();
var id = b64_sha1('converse.bosh-session'); const id = b64_sha1('converse.bosh-session');
this.session.id = id; // Appears to be necessary for backbone.browserStorage this.session.id = id; // Appears to be necessary for backbone.browserStorage
this.session.browserStorage = new Backbone.BrowserStorage[_converse.storage](id); this.session.browserStorage = new Backbone.BrowserStorage[_converse.storage](id);
this.session.fetch(); this.session.fetch();
...@@ -606,16 +606,15 @@ ...@@ -606,16 +606,15 @@
// XXX: eventually we should be able to just use // XXX: eventually we should be able to just use
// document.visibilityState (when we drop support for older // document.visibilityState (when we drop support for older
// browsers). // browsers).
var state; let state;
var v = "visible", h = "hidden", const event_map = {
event_map = { 'focus': "visible",
'focus': v, 'focusin': "visible",
'focusin': v, 'pageshow': "visible",
'pageshow': v, 'blur': "hidden",
'blur': h, 'focusout': "hidden",
'focusout': h, 'pagehide': "hidden"
'pagehide': h };
};
ev = ev || document.createEvent('Events'); ev = ev || document.createEvent('Events');
if (ev.type in event_map) { if (ev.type in event_map) {
state = event_map[ev.type]; state = event_map[ev.type];
...@@ -626,13 +625,13 @@ ...@@ -626,13 +625,13 @@
_converse.clearMsgCounter(); _converse.clearMsgCounter();
} }
_converse.windowState = state; _converse.windowState = state;
_converse.emit('windowStateChanged', {state: state}) _converse.emit('windowStateChanged', {state: state});
}; };
this.registerGlobalEventHandlers = function () { this.registerGlobalEventHandlers = function () {
// Taken from: // Taken from:
// http://stackoverflow.com/questions/1060008/is-there-a-way-to-detect-if-a-browser-window-is-not-currently-active // http://stackoverflow.com/questions/1060008/is-there-a-way-to-detect-if-a-browser-window-is-not-currently-active
var hidden = "hidden"; let hidden = "hidden";
// Standards: // Standards:
if (hidden in document) { if (hidden in document) {
document.addEventListener("visibilitychange", _.partial(_converse.saveWindowState, _, hidden)); document.addEventListener("visibilitychange", _.partial(_converse.saveWindowState, _, hidden));
...@@ -662,7 +661,7 @@ ...@@ -662,7 +661,7 @@
if (!this.message_carbons || this.session.get('carbons_enabled')) { if (!this.message_carbons || this.session.get('carbons_enabled')) {
return; return;
} }
var carbons_iq = new Strophe.Builder('iq', { const carbons_iq = new Strophe.Builder('iq', {
from: this.connection.jid, from: this.connection.jid,
id: 'enablecarbons', id: 'enablecarbons',
type: 'set' type: 'set'
...@@ -811,9 +810,9 @@ ...@@ -811,9 +810,9 @@
}, },
initialize: function (attributes) { initialize: function (attributes) {
var jid = attributes.jid; const jid = attributes.jid;
var bare_jid = Strophe.getBareJidFromJid(jid).toLowerCase(); const bare_jid = Strophe.getBareJidFromJid(jid).toLowerCase();
var resource = Strophe.getResourceFromJid(jid); const resource = Strophe.getResourceFromJid(jid);
attributes.jid = bare_jid; attributes.jid = bare_jid;
this.set(_.assignIn({ this.set(_.assignIn({
'id': bare_jid, 'id': bare_jid,
...@@ -837,11 +836,11 @@ ...@@ -837,11 +836,11 @@
* reason for the subscription request. * reason for the subscription request.
*/ */
this.save('ask', "subscribe"); // ask === 'subscribe' Means we have ask to subscribe to them. this.save('ask', "subscribe"); // ask === 'subscribe' Means we have ask to subscribe to them.
var pres = $pres({to: this.get('jid'), type: "subscribe"}); const pres = $pres({to: this.get('jid'), type: "subscribe"});
if (message && message !== "") { if (message && message !== "") {
pres.c("status").t(message).up(); pres.c("status").t(message).up();
} }
var nick = _converse.xmppstatus.get('fullname'); const nick = _converse.xmppstatus.get('fullname');
if (nick && nick !== "") { if (nick && nick !== "") {
pres.c('nick', {'xmlns': Strophe.NS.NICK}).t(nick).up(); pres.c('nick', {'xmlns': Strophe.NS.NICK}).t(nick).up();
} }
...@@ -888,7 +887,7 @@ ...@@ -888,7 +887,7 @@
* Parameters: * Parameters:
* (String) message - Optional message to send to the person being authorized * (String) message - Optional message to send to the person being authorized
*/ */
var pres = $pres({to: this.get('jid'), type: "subscribed"}); const pres = $pres({to: this.get('jid'), type: "subscribed"});
if (message && message !== "") { if (message && message !== "") {
pres.c("status").t(message); pres.c("status").t(message);
} }
...@@ -903,23 +902,23 @@ ...@@ -903,23 +902,23 @@
* Also updates the contact's chat_status if the presence has * Also updates the contact's chat_status if the presence has
* higher priority (and is newer). * higher priority (and is newer).
*/ */
var jid = presence.getAttribute('from'), const jid = presence.getAttribute('from'),
chat_status = _.propertyOf(presence.querySelector('show'))('textContent') || 'online', chat_status = _.propertyOf(presence.querySelector('show'))('textContent') || 'online',
resource = Strophe.getResourceFromJid(jid), resource = Strophe.getResourceFromJid(jid),
priority = _.propertyOf(presence.querySelector('priority'))('textContent') || 0,
delay = presence.querySelector('delay[xmlns="'+Strophe.NS.DELAY+'"]'), delay = presence.querySelector('delay[xmlns="'+Strophe.NS.DELAY+'"]'),
timestamp = _.isNull(delay) ? moment().format() : moment(delay.getAttribute('stamp')).format(); timestamp = _.isNull(delay) ? moment().format() : moment(delay.getAttribute('stamp')).format();
let priority = _.propertyOf(presence.querySelector('priority'))('textContent') || 0;
priority = _.isNaN(parseInt(priority, 10)) ? 0 : parseInt(priority, 10); priority = _.isNaN(parseInt(priority, 10)) ? 0 : parseInt(priority, 10);
var resources = _.isObject(this.get('resources')) ? this.get('resources') : {}; const resources = _.isObject(this.get('resources')) ? this.get('resources') : {};
resources[resource] = { resources[resource] = {
'priority': priority, 'priority': priority,
'status': chat_status, 'status': chat_status,
'timestamp': timestamp 'timestamp': timestamp
}; };
var changed = {'resources': resources}; const changed = {'resources': resources};
var hpr = this.getHighestPriorityResource(); const hpr = this.getHighestPriorityResource();
if (priority == hpr.priority && timestamp == hpr.timestamp) { if (priority == hpr.priority && timestamp == hpr.timestamp) {
// Only set the chat status if this is the newest resource // Only set the chat status if this is the newest resource
// with the highest priority // with the highest priority
...@@ -935,7 +934,7 @@ ...@@ -935,7 +934,7 @@
* Also recomputes the chat_status given that there's one less * Also recomputes the chat_status given that there's one less
* resource. * resource.
*/ */
var resources = this.get('resources'); let resources = this.get('resources');
if (!_.isObject(resources)) { if (!_.isObject(resources)) {
resources = {}; resources = {};
} else { } else {
...@@ -954,9 +953,9 @@ ...@@ -954,9 +953,9 @@
* If multiple resources have the same priority, take the * If multiple resources have the same priority, take the
* newest one. * newest one.
*/ */
var resources = this.get('resources'); const resources = this.get('resources');
if (_.isObject(resources) && _.size(resources)) { if (_.isObject(resources) && _.size(resources)) {
var val = _.flow( const val = _.flow(
_.values, _.values,
_.partial(_.sortBy, _, ['priority', 'timestamp']), _.partial(_.sortBy, _, ['priority', 'timestamp']),
_.reverse _.reverse
...@@ -972,7 +971,7 @@ ...@@ -972,7 +971,7 @@
* Parameters: * Parameters:
* (Function) callback * (Function) callback
*/ */
var iq = $iq({type: 'set'}) const iq = $iq({type: 'set'})
.c('query', {xmlns: Strophe.NS.ROSTER}) .c('query', {xmlns: Strophe.NS.ROSTER})
.c('item', {jid: this.get('jid'), subscription: "remove"}); .c('item', {jid: this.get('jid'), subscription: "remove"});
_converse.connection.sendIQ(iq, callback, callback); _converse.connection.sendIQ(iq, callback, callback);
...@@ -985,12 +984,11 @@ ...@@ -985,12 +984,11 @@
model: _converse.RosterContact, model: _converse.RosterContact,
comparator: function (contact1, contact2) { comparator: function (contact1, contact2) {
var name1, name2; const status1 = contact1.get('chat_status') || 'offline';
var status1 = contact1.get('chat_status') || 'offline'; const status2 = contact2.get('chat_status') || 'offline';
var status2 = contact2.get('chat_status') || 'offline';
if (_converse.STATUS_WEIGHTS[status1] === _converse.STATUS_WEIGHTS[status2]) { if (_converse.STATUS_WEIGHTS[status1] === _converse.STATUS_WEIGHTS[status2]) {
name1 = contact1.get('fullname').toLowerCase(); const name1 = contact1.get('fullname').toLowerCase();
name2 = contact2.get('fullname').toLowerCase(); const name2 = contact2.get('fullname').toLowerCase();
return name1 < name2 ? -1 : (name1 > name2? 1 : 0); return name1 < name2 ? -1 : (name1 > name2? 1 : 0);
} else { } else {
return _converse.STATUS_WEIGHTS[status1] < _converse.STATUS_WEIGHTS[status2] ? -1 : 1; return _converse.STATUS_WEIGHTS[status1] < _converse.STATUS_WEIGHTS[status2] ? -1 : 1;
...@@ -1044,7 +1042,7 @@ ...@@ -1044,7 +1042,7 @@
* Returns a promise which resolves once the contacts have been * Returns a promise which resolves once the contacts have been
* fetched. * fetched.
*/ */
var deferred = new $.Deferred(); const deferred = new $.Deferred();
this.fetch({ this.fetch({
add: true, add: true,
success: function (collection) { success: function (collection) {
...@@ -1112,7 +1110,7 @@ ...@@ -1112,7 +1110,7 @@
* (Function) errback - A function to call if an error occured * (Function) errback - A function to call if an error occured
*/ */
name = _.isEmpty(name)? jid: name; name = _.isEmpty(name)? jid: name;
var iq = $iq({type: 'set'}) const iq = $iq({type: 'set'})
.c('query', {xmlns: Strophe.NS.ROSTER}) .c('query', {xmlns: Strophe.NS.ROSTER})
.c('item', { jid: jid, name: name }); .c('item', { jid: jid, name: name });
_.each(groups, function (group) { iq.c('group').t(group).up(); }); _.each(groups, function (group) { iq.c('group').t(group).up(); });
...@@ -1131,12 +1129,12 @@ ...@@ -1131,12 +1129,12 @@
* (Array of Strings) groups - Any roster groups the user might belong to * (Array of Strings) groups - Any roster groups the user might belong to
* (Object) attributes - Any additional attributes to be stored on the user's model. * (Object) attributes - Any additional attributes to be stored on the user's model.
*/ */
var deferred = new $.Deferred(); const deferred = new $.Deferred();
groups = groups || []; groups = groups || [];
name = _.isEmpty(name)? jid: name; name = _.isEmpty(name)? jid: name;
this.sendContactAddIQ(jid, name, groups, this.sendContactAddIQ(jid, name, groups,
function () { function () {
var contact = this.create(_.assignIn({ const contact = this.create(_.assignIn({
ask: undefined, ask: undefined,
fullname: name, fullname: name,
groups: groups, groups: groups,
...@@ -1156,7 +1154,7 @@ ...@@ -1156,7 +1154,7 @@
}, },
subscribeBack: function (bare_jid) { subscribeBack: function (bare_jid) {
var contact = this.get(bare_jid); const contact = this.get(bare_jid);
if (contact instanceof _converse.RosterContact) { if (contact instanceof _converse.RosterContact) {
contact.authorize().subscribe(); contact.authorize().subscribe();
} else { } else {
...@@ -1170,20 +1168,13 @@ ...@@ -1170,20 +1168,13 @@
}, },
getNumOnlineContacts: function () { getNumOnlineContacts: function () {
var count = 0, let ignored = ['offline', 'unavailable'];
ignored = ['offline', 'unavailable'],
models = this.models,
models_length = models.length,
i;
if (_converse.show_only_online_users) { if (_converse.show_only_online_users) {
ignored = _.union(ignored, ['dnd', 'xa', 'away']); ignored = _.union(ignored, ['dnd', 'xa', 'away']);
} }
for (i=0; i<models_length; i++) { return _.sum(this.models.filter(function (model) {
if (!_.includes(ignored, models[i].get('chat_status'))) { return !_.includes(ignored, model.get('chat_status'));
count++; }));
}
}
return count;
}, },
onRosterPush: function (iq) { onRosterPush: function (iq) {
...@@ -1193,8 +1184,8 @@ ...@@ -1193,8 +1184,8 @@
* Parameters: * Parameters:
* (XMLElement) IQ - The IQ stanza received from the XMPP server. * (XMLElement) IQ - The IQ stanza received from the XMPP server.
*/ */
var id = iq.getAttribute('id'); const id = iq.getAttribute('id');
var from = iq.getAttribute('from'); const from = iq.getAttribute('from');
if (from && from !== "" && Strophe.getBareJidFromJid(from) !== _converse.bare_jid) { if (from && from !== "" && Strophe.getBareJidFromJid(from) !== _converse.bare_jid) {
// Receiving client MUST ignore stanza unless it has no from or from = user's bare JID. // Receiving client MUST ignore stanza unless it has no from or from = user's bare JID.
// XXX: Some naughty servers apparently send from a full // XXX: Some naughty servers apparently send from a full
...@@ -1208,8 +1199,7 @@ ...@@ -1208,8 +1199,7 @@
return true; return true;
} }
_converse.connection.send($iq({type: 'result', id: id, from: _converse.connection.jid})); _converse.connection.send($iq({type: 'result', id: id, from: _converse.connection.jid}));
// var items = iq.querySelectorAll('query[xmlns="'+Strophe.NS.ROSTER+'"] item'); const items = sizzle('query[xmlns="'+Strophe.NS.ROSTER+'"] item', iq);
var items = sizzle('query[xmlns="'+Strophe.NS.ROSTER+'"] item', iq);
_.each(items, this.updateContact.bind(this)); _.each(items, this.updateContact.bind(this));
_converse.emit('rosterPush', iq); _converse.emit('rosterPush', iq);
return true; return true;
...@@ -1217,12 +1207,11 @@ ...@@ -1217,12 +1207,11 @@
fetchFromServer: function (callback) { fetchFromServer: function (callback) {
/* Get the roster from the XMPP server */ /* Get the roster from the XMPP server */
var iq = $iq({type: 'get', 'id': _converse.connection.getUniqueId('roster')}) const iq = $iq({type: 'get', 'id': _converse.connection.getUniqueId('roster')})
.c('query', {xmlns: Strophe.NS.ROSTER}); .c('query', {xmlns: Strophe.NS.ROSTER});
var that = this; return _converse.connection.sendIQ(iq, (iq) => {
return _converse.connection.sendIQ(iq, function () { this.onReceivedFromServer(iq);
that.onReceivedFromServer.apply(that, arguments); callback.apply(this, arguments);
callback.apply(that, arguments);
}); });
}, },
...@@ -1230,8 +1219,7 @@ ...@@ -1230,8 +1219,7 @@
/* An IQ stanza containing the roster has been received from /* An IQ stanza containing the roster has been received from
* the XMPP server. * the XMPP server.
*/ */
// var items = iq.querySelectorAll('query[xmlns="'+Strophe.NS.ROSTER+'"] item'); const items = sizzle('query[xmlns="'+Strophe.NS.ROSTER+'"] item', iq);
var items = sizzle('query[xmlns="'+Strophe.NS.ROSTER+'"] item', iq);
_.each(items, this.updateContact.bind(this)); _.each(items, this.updateContact.bind(this));
_converse.emit('roster', iq); _converse.emit('roster', iq);
}, },
...@@ -1240,12 +1228,14 @@ ...@@ -1240,12 +1228,14 @@
/* Update or create RosterContact models based on items /* Update or create RosterContact models based on items
* received in the IQ from the server. * received in the IQ from the server.
*/ */
var jid = item.getAttribute('jid'); const jid = item.getAttribute('jid');
if (this.isSelf(jid)) { return; } if (this.isSelf(jid)) { return; }
var groups = _.map(item.getElementsByTagName('group'), Strophe.getText),
contact = this.get(jid), const contact = this.get(jid),
ask = item.getAttribute("ask"), subscription = item.getAttribute("subscription"),
subscription = item.getAttribute("subscription"); ask = item.getAttribute("ask"),
groups = _.map(item.getElementsByTagName('group'), Strophe.getText);
if (!contact) { if (!contact) {
if ((subscription === "none" && ask === null) || (subscription === "remove")) { if ((subscription === "none" && ask === null) || (subscription === "remove")) {
return; // We're lazy when adding contacts. return; // We're lazy when adding contacts.
...@@ -1279,9 +1269,9 @@ ...@@ -1279,9 +1269,9 @@
* *
* Note: this method gets completely overridden by converse-vcard.js * Note: this method gets completely overridden by converse-vcard.js
*/ */
var bare_jid = Strophe.getBareJidFromJid(presence.getAttribute('from')); const bare_jid = Strophe.getBareJidFromJid(presence.getAttribute('from')),
var nick_el = presence.querySelector('nick[xmlns="'+Strophe.NS.NICK+'"]'); nick_el = presence.querySelector('nick[xmlns="'+Strophe.NS.NICK+'"]');
var user_data = { const user_data = {
jid: bare_jid, jid: bare_jid,
subscription: 'none', subscription: 'none',
ask: null, ask: null,
...@@ -1293,9 +1283,10 @@ ...@@ -1293,9 +1283,10 @@
}, },
handleIncomingSubscription: function (presence) { handleIncomingSubscription: function (presence) {
var jid = presence.getAttribute('from'); const jid = presence.getAttribute('from'),
var bare_jid = Strophe.getBareJidFromJid(jid); bare_jid = Strophe.getBareJidFromJid(jid),
var contact = this.get(bare_jid); contact = this.get(bare_jid);
if (!_converse.allow_contact_requests) { if (!_converse.allow_contact_requests) {
_converse.rejectPresenceSubscription( _converse.rejectPresenceSubscription(
jid, jid,
...@@ -1315,16 +1306,17 @@ ...@@ -1315,16 +1306,17 @@
} else if (contact.get('ask') === "subscribe") { } else if (contact.get('ask') === "subscribe") {
contact.authorize(); contact.authorize();
} }
} else if (!contact) { } else {
this.createRequestingContact(presence); this.createRequestingContact(presence);
} }
} }
}, },
presenceHandler: function (presence) { presenceHandler: function (presence) {
var presence_type = presence.getAttribute('type'); const presence_type = presence.getAttribute('type');
if (presence_type === 'error') { return true; } if (presence_type === 'error') { return true; }
var jid = presence.getAttribute('from'),
const jid = presence.getAttribute('from'),
bare_jid = Strophe.getBareJidFromJid(jid), bare_jid = Strophe.getBareJidFromJid(jid),
resource = Strophe.getResourceFromJid(jid), resource = Strophe.getResourceFromJid(jid),
chat_status = _.propertyOf(presence.querySelector('show'))('textContent') || 'online', chat_status = _.propertyOf(presence.querySelector('show'))('textContent') || 'online',
...@@ -1390,7 +1382,7 @@ ...@@ -1390,7 +1382,7 @@
* Returns a promise which resolves once the groups have been * Returns a promise which resolves once the groups have been
* returned. * returned.
*/ */
var deferred = new $.Deferred(); const deferred = new $.Deferred();
this.fetch({ this.fetch({
silent: true, // We need to first have all groups before silent: true, // We need to first have all groups before
// we can start positioning them, so we set // we can start positioning them, so we set
...@@ -1442,15 +1434,13 @@ ...@@ -1442,15 +1434,13 @@
getMessageAttributes: function (message, delay, original_stanza) { getMessageAttributes: function (message, delay, original_stanza) {
delay = delay || message.querySelector('delay'); delay = delay || message.querySelector('delay');
var type = message.getAttribute('type'), const type = message.getAttribute('type');
body, stamp, time, sender, from, fullname;
if (type === 'error') { const body = (type === 'error') ?
body = _.propertyOf(message.querySelector('error text'))('textContent'); _.propertyOf(message.querySelector('error text'))('textContent') :
} else { _.propertyOf(message.querySelector('body'))('textContent');
body = _.propertyOf(message.querySelector('body'))('textContent');
} const delayed = !_.isNull(delay),
var delayed = !_.isNull(delay),
is_groupchat = type === 'groupchat', is_groupchat = type === 'groupchat',
chat_state = message.getElementsByTagName(_converse.COMPOSING).length && _converse.COMPOSING || chat_state = message.getElementsByTagName(_converse.COMPOSING).length && _converse.COMPOSING ||
message.getElementsByTagName(_converse.PAUSED).length && _converse.PAUSED || message.getElementsByTagName(_converse.PAUSED).length && _converse.PAUSED ||
...@@ -1458,17 +1448,15 @@ ...@@ -1458,17 +1448,15 @@
message.getElementsByTagName(_converse.ACTIVE).length && _converse.ACTIVE || message.getElementsByTagName(_converse.ACTIVE).length && _converse.ACTIVE ||
message.getElementsByTagName(_converse.GONE).length && _converse.GONE; message.getElementsByTagName(_converse.GONE).length && _converse.GONE;
let from;
if (is_groupchat) { if (is_groupchat) {
from = Strophe.unescapeNode(Strophe.getResourceFromJid(message.getAttribute('from'))); from = Strophe.unescapeNode(Strophe.getResourceFromJid(message.getAttribute('from')));
} else { } else {
from = Strophe.getBareJidFromJid(message.getAttribute('from')); from = Strophe.getBareJidFromJid(message.getAttribute('from'));
} }
if (delayed) {
stamp = delay.getAttribute('stamp'); const time = delayed ? delay.getAttribute('stamp') : moment().format();
time = stamp; let sender, fullname;
} else {
time = moment().format();
}
if ((is_groupchat && from === this.get('nick')) || (!is_groupchat && from === _converse.bare_jid)) { if ((is_groupchat && from === this.get('nick')) || (!is_groupchat && from === _converse.bare_jid)) {
sender = 'me'; sender = 'me';
fullname = _converse.xmppstatus.get('fullname') || from; fullname = _converse.xmppstatus.get('fullname') || from;
...@@ -1546,9 +1534,8 @@ ...@@ -1546,9 +1534,8 @@
* This method gets overridden entirely in src/converse-controlbox.js * This method gets overridden entirely in src/converse-controlbox.js
* if the controlbox plugin is active. * if the controlbox plugin is active.
*/ */
var that = this; collection.each((chatbox) => {
collection.each(function (chatbox) { if (this.chatBoxMayBeShown(chatbox)) {
if (that.chatBoxMayBeShown(chatbox)) {
chatbox.trigger('show'); chatbox.trigger('show');
} }
}); });
...@@ -1569,12 +1556,12 @@ ...@@ -1569,12 +1556,12 @@
/* Handler method for all incoming error message stanzas /* Handler method for all incoming error message stanzas
*/ */
// TODO: we can likely just reuse "onMessage" below // TODO: we can likely just reuse "onMessage" below
var from_jid = Strophe.getBareJidFromJid(message.getAttribute('from')); const from_jid = Strophe.getBareJidFromJid(message.getAttribute('from'));
if (utils.isSameBareJID(from_jid, _converse.bare_jid)) { if (utils.isSameBareJID(from_jid, _converse.bare_jid)) {
return true; return true;
} }
// Get chat box, but only create a new one when the message has a body. // Get chat box, but only create a new one when the message has a body.
var chatbox = this.getChatBox(from_jid); const chatbox = this.getChatBox(from_jid);
if (!chatbox) { if (!chatbox) {
return true; return true;
} }
...@@ -1586,14 +1573,14 @@ ...@@ -1586,14 +1573,14 @@
/* Handler method for all incoming single-user chat "message" /* Handler method for all incoming single-user chat "message"
* stanzas. * stanzas.
*/ */
var original_stanza = message,
contact_jid, delay, from_bare_jid, let contact_jid, delay, resource,
from_resource, is_me, msgid, messages,
chatbox, resource,
from_jid = message.getAttribute('from'), from_jid = message.getAttribute('from'),
to_jid = message.getAttribute('to'), to_jid = message.getAttribute('to');
to_resource = Strophe.getResourceFromJid(to_jid),
is_carbon = !_.isNull(message.querySelector('received[xmlns="'+Strophe.NS.CARBONS+'"]')); const original_stanza = message,
to_resource = Strophe.getResourceFromJid(to_jid),
is_carbon = !_.isNull(message.querySelector('received[xmlns="'+Strophe.NS.CARBONS+'"]'));
if (_converse.filter_by_resource && (to_resource && to_resource !== _converse.resource)) { if (_converse.filter_by_resource && (to_resource && to_resource !== _converse.resource)) {
_converse.log( _converse.log(
...@@ -1611,10 +1598,10 @@ ...@@ -1611,10 +1598,10 @@
); );
return true; return true;
} }
var forwarded = message.querySelector('forwarded'); const forwarded = message.querySelector('forwarded');
if (!_.isNull(forwarded)) { if (!_.isNull(forwarded)) {
var forwarded_message = forwarded.querySelector('message'); const forwarded_message = forwarded.querySelector('message');
var forwarded_from = forwarded_message.getAttribute('from'); const forwarded_from = forwarded_message.getAttribute('from');
if (is_carbon && Strophe.getBareJidFromJid(forwarded_from) !== from_jid) { if (is_carbon && Strophe.getBareJidFromJid(forwarded_from) !== from_jid) {
// Prevent message forging via carbons // Prevent message forging via carbons
// //
...@@ -1626,9 +1613,11 @@ ...@@ -1626,9 +1613,11 @@
from_jid = message.getAttribute('from'); from_jid = message.getAttribute('from');
to_jid = message.getAttribute('to'); to_jid = message.getAttribute('to');
} }
from_bare_jid = Strophe.getBareJidFromJid(from_jid);
from_resource = Strophe.getResourceFromJid(from_jid); const from_bare_jid = Strophe.getBareJidFromJid(from_jid),
is_me = from_bare_jid === _converse.bare_jid; from_resource = Strophe.getResourceFromJid(from_jid),
is_me = from_bare_jid === _converse.bare_jid;
if (is_me) { if (is_me) {
// I am the sender, so this must be a forwarded message... // I am the sender, so this must be a forwarded message...
contact_jid = Strophe.getBareJidFromJid(to_jid); contact_jid = Strophe.getBareJidFromJid(to_jid);
...@@ -1638,10 +1627,11 @@ ...@@ -1638,10 +1627,11 @@
resource = from_resource; resource = from_resource;
} }
// Get chat box, but only create a new one when the message has a body. // Get chat box, but only create a new one when the message has a body.
chatbox = this.getChatBox(contact_jid, !_.isNull(message.querySelector('body'))); const chatbox = this.getChatBox(contact_jid, !_.isNull(message.querySelector('body'))),
msgid = message.getAttribute('id'); msgid = message.getAttribute('id');
if (chatbox) { if (chatbox) {
messages = msgid && chatbox.messages.findWhere({msgid: msgid}) || []; const messages = msgid && chatbox.messages.findWhere({msgid: msgid}) || [];
if (_.isEmpty(messages)) { if (_.isEmpty(messages)) {
// Only create the message when we're sure it's not a // Only create the message when we're sure it's not a
// duplicate // duplicate
...@@ -1661,9 +1651,10 @@ ...@@ -1661,9 +1651,10 @@
* gets created. * gets created.
* (Object) attrs - Optional chat box atributes. * (Object) attrs - Optional chat box atributes.
*/ */
var bare_jid = Strophe.getBareJidFromJid(jid); const bare_jid = Strophe.getBareJidFromJid(jid),
var roster_info = {}; roster_item = _converse.roster.get(bare_jid);
var roster_item = _converse.roster.get(bare_jid); let roster_info = {};
if (! _.isUndefined(roster_item)) { if (! _.isUndefined(roster_item)) {
roster_info = { roster_info = {
'fullname': _.isEmpty(roster_item.get('fullname'))? jid: roster_item.get('fullname'), 'fullname': _.isEmpty(roster_item.get('fullname'))? jid: roster_item.get('fullname'),
...@@ -1697,7 +1688,7 @@ ...@@ -1697,7 +1688,7 @@
* (Object) attrs - Optional chat box atributes. * (Object) attrs - Optional chat box atributes.
*/ */
jid = jid.toLowerCase(); jid = jid.toLowerCase();
var chatbox = this.get(Strophe.getBareJidFromJid(jid)); let chatbox = this.get(Strophe.getBareJidFromJid(jid));
if (!chatbox && create) { if (!chatbox && create) {
chatbox = this.createChatBox(jid, attrs); chatbox = this.createChatBox(jid, attrs);
} }
...@@ -1717,7 +1708,7 @@ ...@@ -1717,7 +1708,7 @@
* If the #conversejs element doesn't exist, create it. * If the #conversejs element doesn't exist, create it.
*/ */
if (!this.el) { if (!this.el) {
var el = document.querySelector('#conversejs'); let el = document.querySelector('#conversejs');
if (_.isNull(el)) { if (_.isNull(el)) {
el = document.createElement('div'); el = document.createElement('div');
el.setAttribute('id', 'conversejs'); el.setAttribute('id', 'conversejs');
...@@ -1755,7 +1746,7 @@ ...@@ -1755,7 +1746,7 @@
}, },
getChatBox: function (attrs, create) { getChatBox: function (attrs, create) {
var chatbox = this.model.get(attrs.jid); let chatbox = this.model.get(attrs.jid);
if (!chatbox && create) { if (!chatbox && create) {
chatbox = this.model.create(attrs, { chatbox = this.model.create(attrs, {
'error': function (model, response) { 'error': function (model, response) {
...@@ -1770,7 +1761,7 @@ ...@@ -1770,7 +1761,7 @@
/* Find the chat box and show it (if it may be shown). /* Find the chat box and show it (if it may be shown).
* If it doesn't exist, create it. * If it doesn't exist, create it.
*/ */
var chatbox = this.getChatBox(attrs, true); const chatbox = this.getChatBox(attrs, true);
if (this.chatBoxMayBeShown(chatbox)) { if (this.chatBoxMayBeShown(chatbox)) {
chatbox.trigger('show', true); chatbox.trigger('show', true);
} }
...@@ -1795,7 +1786,7 @@ ...@@ -1795,7 +1786,7 @@
}, },
constructPresence: function (type, status_message) { constructPresence: function (type, status_message) {
var presence; let presence;
type = _.isString(type) ? type : (this.get('status') || _converse.default_state); type = _.isString(type) ? type : (this.get('status') || _converse.default_state);
status_message = _.isString(status_message) ? status_message : undefined; status_message = _.isString(status_message) ? status_message : undefined;
// Most of these presence types are actually not explicitly sent, // Most of these presence types are actually not explicitly sent,
...@@ -1839,14 +1830,14 @@ ...@@ -1839,14 +1830,14 @@
setStatusMessage: function (status_message) { setStatusMessage: function (status_message) {
this.sendPresence(this.getStatus(), status_message); this.sendPresence(this.getStatus(), status_message);
var prev_status = this.get('status_message');
this.save({'status_message': status_message}); this.save({'status_message': status_message});
if (this.xhr_custom_status) { if (this.xhr_custom_status) {
var xhr = new XMLHttpRequest(); const xhr = new XMLHttpRequest();
xhr.open('POST', this.xhr_custom_status_url, true); xhr.open('POST', this.xhr_custom_status_url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.send({'msg': status_message}); xhr.send({'msg': status_message});
} }
const prev_status = this.get('status_message');
if (prev_status === status_message) { if (prev_status === status_message) {
this.trigger("update-status-ui", this); this.trigger("update-status-ui", this);
} }
...@@ -1908,12 +1899,11 @@ ...@@ -1908,12 +1899,11 @@
}, },
onItems: function (stanza) { onItems: function (stanza) {
var that = this; _.each(stanza.querySelectorAll('query item'), (item) => {
_.each(stanza.querySelectorAll('query item'), function (item) {
_converse.connection.disco.info( _converse.connection.disco.info(
item.getAttribute('jid'), item.getAttribute('jid'),
null, null,
that.onInfo.bind(that)); this.onInfo.bind(this));
}); });
}, },
...@@ -1923,11 +1913,10 @@ ...@@ -1923,11 +1913,10 @@
// This isn't an IM server component // This isn't an IM server component
return; return;
} }
var that = this; _.forEach(stanza.querySelectorAll('feature'), (feature) => {
_.forEach(stanza.querySelectorAll('feature'), function (feature) { const namespace = feature.getAttribute('var');
var namespace = feature.getAttribute('var'); this[namespace] = true;
that[namespace] = true; this.create({
that.create({
'var': namespace, 'var': namespace,
'from': stanza.getAttribute('from') 'from': stanza.getAttribute('from')
}); });
...@@ -1950,13 +1939,13 @@ ...@@ -1950,13 +1939,13 @@
}; };
this.fetchLoginCredentials = function () { this.fetchLoginCredentials = function () {
var deferred = new $.Deferred(); const deferred = new $.Deferred();
var xhr = new XMLHttpRequest(); const xhr = new XMLHttpRequest();
xhr.open('GET', _converse.credentials_url, true); xhr.open('GET', _converse.credentials_url, true);
xhr.setRequestHeader('Accept', "application/json, text/javascript"); xhr.setRequestHeader('Accept', "application/json, text/javascript");
xhr.onload = function() { xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 400) { if (xhr.status >= 200 && xhr.status < 400) {
var data = JSON.parse(xhr.responseText); const data = JSON.parse(xhr.responseText);
deferred.resolve({ deferred.resolve({
'jid': data.jid, 'jid': data.jid,
'password': data.password 'password': data.password
...@@ -1975,12 +1964,12 @@ ...@@ -1975,12 +1964,12 @@
}; };
this.startNewBOSHSession = function () { this.startNewBOSHSession = function () {
var xhr = new XMLHttpRequest(); const xhr = new XMLHttpRequest();
xhr.open('GET', _converse.prebind_url, true); xhr.open('GET', _converse.prebind_url, true);
xhr.setRequestHeader('Accept', "application/json, text/javascript"); xhr.setRequestHeader('Accept', "application/json, text/javascript");
xhr.onload = function() { xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 400) { if (xhr.status >= 200 && xhr.status < 400) {
var data = JSON.parse(xhr.responseText); const data = JSON.parse(xhr.responseText);
_converse.connection.attach( _converse.connection.attach(
data.jid, data.sid, data.rid, data.jid, data.sid, data.rid,
_converse.onConnectStatusChanged); _converse.onConnectStatusChanged);
...@@ -1998,8 +1987,8 @@ ...@@ -1998,8 +1987,8 @@
this.restoreBOSHSession = function (jid_is_required) { this.restoreBOSHSession = function (jid_is_required) {
/* Tries to restore a cached BOSH session. */ /* Tries to restore a cached BOSH session. */
if (!this.jid) { if (!this.jid) {
var msg = "restoreBOSHSession: tried to restore a \"keepalive\" session "+ const msg = "restoreBOSHSession: tried to restore a \"keepalive\" session "+
"but we don't have the JID for the user!"; "but we don't have the JID for the user!";
if (jid_is_required) { if (jid_is_required) {
throw new Error(msg); throw new Error(msg);
} else { } else {
...@@ -2094,7 +2083,7 @@ ...@@ -2094,7 +2083,7 @@
} }
this.connection.connect(this.jid.toLowerCase(), null, this.onConnectStatusChanged); this.connection.connect(this.jid.toLowerCase(), null, this.onConnectStatusChanged);
} else if (this.authentication === _converse.LOGIN) { } else if (this.authentication === _converse.LOGIN) {
var password = _.isNil(credentials) ? (_converse.connection.pass || this.password) : credentials.password; const password = _.isNil(credentials) ? (_converse.connection.pass || this.password) : credentials.password;
if (!password) { if (!password) {
if (this.auto_login) { if (this.auto_login) {
throw new Error("initConnection: If you use auto_login and "+ throw new Error("initConnection: If you use auto_login and "+
...@@ -2104,7 +2093,7 @@ ...@@ -2104,7 +2093,7 @@
_converse.disconnect(); _converse.disconnect();
return; return;
} }
var resource = Strophe.getResourceFromJid(this.jid); const resource = Strophe.getResourceFromJid(this.jid);
if (!resource) { if (!resource) {
this.jid = this.jid.toLowerCase() + _converse.generateResource(); this.jid = this.jid.toLowerCase() + _converse.generateResource();
} else { } else {
...@@ -2182,7 +2171,7 @@ ...@@ -2182,7 +2171,7 @@
// If initialize is called for the first time, then this array is empty // If initialize is called for the first time, then this array is empty
// in any case. // in any case.
_converse.pluggable.initialized_plugins = []; _converse.pluggable.initialized_plugins = [];
var whitelist = _converse.core_plugins.concat( const whitelist = _converse.core_plugins.concat(
_converse.whitelisted_plugins); _converse.whitelisted_plugins);
_converse.pluggable.initializePlugins({ _converse.pluggable.initializePlugins({
...@@ -2250,7 +2239,7 @@ ...@@ -2250,7 +2239,7 @@
return _converse.xmppstatus.get('status'); return _converse.xmppstatus.get('status');
}, },
'set': function (value, message) { 'set': function (value, message) {
var data = {'status': value}; const data = {'status': value};
if (!_.includes(_.keys(_converse.STATUS_WEIGHTS), value)) { if (!_.includes(_.keys(_converse.STATUS_WEIGHTS), value)) {
throw new Error('Invalid availability value. See https://xmpp.org/rfcs/rfc3921.html#rfc.section.2.2.2.1'); throw new Error('Invalid availability value. See https://xmpp.org/rfcs/rfc3921.html#rfc.section.2.2.2.1');
} }
...@@ -2282,7 +2271,7 @@ ...@@ -2282,7 +2271,7 @@
} }
}, },
'set': function (key, val) { 'set': function (key, val) {
var o = {}; const o = {};
if (_.isObject(key)) { if (_.isObject(key)) {
_.assignIn(_converse, _.pick(key, _.keys(_converse.default_settings))); _.assignIn(_converse, _.pick(key, _.keys(_converse.default_settings)));
} else if (_.isString("string")) { } else if (_.isString("string")) {
...@@ -2301,8 +2290,8 @@ ...@@ -2301,8 +2290,8 @@
}, },
'contacts': { 'contacts': {
'get': function (jids) { 'get': function (jids) {
var _transform = function (jid) { const _transform = function (jid) {
var contact = _converse.roster.get(Strophe.getBareJidFromJid(jid)); const contact = _converse.roster.get(Strophe.getBareJidFromJid(jid));
if (contact) { if (contact) {
return contact.attributes; return contact.attributes;
} }
...@@ -2324,26 +2313,23 @@ ...@@ -2324,26 +2313,23 @@
}, },
'chats': { 'chats': {
'open': function (jids, attrs) { 'open': function (jids, attrs) {
var chatbox;
if (_.isUndefined(jids)) { if (_.isUndefined(jids)) {
_converse.log("chats.open: You need to provide at least one JID", Strophe.LogLevel.ERROR); _converse.log("chats.open: You need to provide at least one JID", Strophe.LogLevel.ERROR);
return null; return null;
} else if (_.isString(jids)) { } else if (_.isString(jids)) {
chatbox = _converse.getViewForChatBox( return _converse.getViewForChatBox(
_converse.chatboxes.getChatBox(jids, true, attrs).trigger('show') _converse.chatboxes.getChatBox(jids, true, attrs).trigger('show')
); );
return chatbox;
} }
return _.map(jids, function (jid) { return _.map(jids, function (jid) {
chatbox = _converse.getViewForChatBox( return _converse.getViewForChatBox(
_converse.chatboxes.getChatBox(jid, true, attrs).trigger('show') _converse.chatboxes.getChatBox(jid, true, attrs).trigger('show')
); );
return chatbox;
}); });
}, },
'get': function (jids) { 'get': function (jids) {
if (_.isUndefined(jids)) { if (_.isUndefined(jids)) {
var result = []; const result = [];
_converse.chatboxes.each(function (chatbox) { _converse.chatboxes.each(function (chatbox) {
// FIXME: Leaky abstraction from MUC. We need to add a // FIXME: Leaky abstraction from MUC. We need to add a
// base type for chat boxes, and check for that. // base type for chat boxes, and check for that.
...@@ -2400,7 +2386,7 @@ ...@@ -2400,7 +2386,7 @@
}, },
}, },
'waitUntil': function (name) { 'waitUntil': function (name) {
var promise = _converse.promises[name]; const promise = _converse.promises[name];
if (_.isUndefined(promise)) { if (_.isUndefined(promise)) {
return null; return null;
} }
......
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
], factory); ], factory);
}(this, function (converse, tpl_dragresize) { }(this, function (converse, tpl_dragresize) {
"use strict"; "use strict";
var $ = converse.env.jQuery, const $ = converse.env.jQuery,
_ = converse.env._; _ = converse.env._;
function renderDragResizeHandles (_converse, view) { function renderDragResizeHandles (_converse, view) {
......
...@@ -14,7 +14,7 @@ ...@@ -14,7 +14,7 @@
], factory); ], factory);
}(this, function (converse, tpl_chatbox) { }(this, function (converse, tpl_chatbox) {
"use strict"; "use strict";
var _ = converse.env._, const _ = converse.env._,
utils = converse.env.utils; utils = converse.env.utils;
converse.plugins.add('converse-headline', { converse.plugins.add('converse-headline', {
...@@ -28,8 +28,8 @@ ...@@ -28,8 +28,8 @@
ChatBoxViews: { ChatBoxViews: {
onChatBoxAdded: function (item) { onChatBoxAdded: function (item) {
var _converse = this.__super__._converse; const _converse = this.__super__._converse;
var view = this.get(item.get('id')); let view = this.get(item.get('id'));
if (!view && item.get('type') === 'headline') { if (!view && item.get('type') === 'headline') {
view = new _converse.HeadlinesBoxView({model: item}); view = new _converse.HeadlinesBoxView({model: item});
this.add(item.get('id'), view); this.add(item.get('id'), view);
...@@ -45,7 +45,7 @@ ...@@ -45,7 +45,7 @@
/* The initialize function gets called as soon as the plugin is /* The initialize function gets called as soon as the plugin is
* loaded by converse.js's plugin machinery. * loaded by converse.js's plugin machinery.
*/ */
var _converse = this._converse, const _converse = this._converse,
__ = _converse.__; __ = _converse.__;
_converse.HeadlinesBoxView = _converse.ChatBoxView.extend({ _converse.HeadlinesBoxView = _converse.ChatBoxView.extend({
...@@ -89,14 +89,14 @@ ...@@ -89,14 +89,14 @@
} }
}); });
var onHeadlineMessage = function (message) { function onHeadlineMessage (message) {
/* Handler method for all incoming messages of type "headline". */ /* Handler method for all incoming messages of type "headline". */
var from_jid = message.getAttribute('from'); const from_jid = message.getAttribute('from');
if (utils.isHeadlineMessage(message)) { if (utils.isHeadlineMessage(message)) {
if (_.includes(from_jid, '@') && !_converse.allow_non_roster_messaging) { if (_.includes(from_jid, '@') && !_converse.allow_non_roster_messaging) {
return; return;
} }
var chatbox = _converse.chatboxes.create({ const chatbox = _converse.chatboxes.create({
'id': from_jid, 'id': from_jid,
'jid': from_jid, 'jid': from_jid,
'fullname': from_jid, 'fullname': from_jid,
...@@ -106,12 +106,12 @@ ...@@ -106,12 +106,12 @@
_converse.emit('message', {'chatbox': chatbox, 'stanza': message}); _converse.emit('message', {'chatbox': chatbox, 'stanza': message});
} }
return true; return true;
}; }
var registerHeadlineHandler = function () { function registerHeadlineHandler () {
_converse.connection.addHandler( _converse.connection.addHandler(
onHeadlineMessage, null, 'message'); onHeadlineMessage, null, 'message');
}; }
_converse.on('connected', registerHeadlineHandler); _converse.on('connected', registerHeadlineHandler);
_converse.on('reconnected', registerHeadlineHandler); _converse.on('reconnected', registerHeadlineHandler);
} }
......
...@@ -24,7 +24,8 @@ ...@@ -24,7 +24,8 @@
tpl_chats_panel tpl_chats_panel
) { ) {
"use strict"; "use strict";
var $ = converse.env.jQuery,
const $ = converse.env.jQuery,
_ = converse.env._, _ = converse.env._,
utils = converse.env.utils, utils = converse.env.utils,
Backbone = converse.env.Backbone, Backbone = converse.env.Backbone,
...@@ -40,8 +41,8 @@ ...@@ -40,8 +41,8 @@
// New functions which don't exist yet can also be added. // New functions which don't exist yet can also be added.
initChatBoxes: function () { initChatBoxes: function () {
var _converse = this.__super__._converse; const _converse = this.__super__._converse;
var result = this.__super__.initChatBoxes.apply(this, arguments); const result = this.__super__.initChatBoxes.apply(this, arguments);
_converse.minimized_chats = new _converse.MinimizedChats({ _converse.minimized_chats = new _converse.MinimizedChats({
model: _converse.chatboxes model: _converse.chatboxes
}); });
...@@ -49,7 +50,7 @@ ...@@ -49,7 +50,7 @@
}, },
registerGlobalEventHandlers: function () { registerGlobalEventHandlers: function () {
var _converse = this.__super__._converse; const _converse = this.__super__._converse;
$(window).on("resize", _.debounce(function (ev) { $(window).on("resize", _.debounce(function (ev) {
if (_converse.connection.connected) { if (_converse.connection.connected) {
_converse.chatboxviews.trimChats(); _converse.chatboxviews.trimChats();
...@@ -96,7 +97,7 @@ ...@@ -96,7 +97,7 @@
}, },
_show: function () { _show: function () {
var _converse = this.__super__._converse; const _converse = this.__super__._converse;
if (!this.model.get('minimized')) { if (!this.model.get('minimized')) {
this.__super__._show.apply(this, arguments); this.__super__._show.apply(this, arguments);
_converse.chatboxviews.trimChats(this); _converse.chatboxviews.trimChats(this);
......
...@@ -8,7 +8,7 @@ ...@@ -8,7 +8,7 @@
define(["converse-core", "converse-muc"], factory); define(["converse-core", "converse-muc"], factory);
}(this, function (converse) { }(this, function (converse) {
"use strict"; "use strict";
var Backbone = converse.env.Backbone, const Backbone = converse.env.Backbone,
_ = converse.env._; _ = converse.env._;
converse.plugins.add('converse-muc-embedded', { converse.plugins.add('converse-muc-embedded', {
...@@ -23,7 +23,7 @@ ...@@ -23,7 +23,7 @@
onConnected: function () { onConnected: function () {
// Override to avoid storing or fetching chat boxes from session // Override to avoid storing or fetching chat boxes from session
// storage. // storage.
var _converse = this.__super__._converse; const _converse = this.__super__._converse;
this.browserStorage = new Backbone.BrowserStorage[_converse.storage]( this.browserStorage = new Backbone.BrowserStorage[_converse.storage](
converse.env.b64_sha1('converse.chatboxes-'+_converse.bare_jid)); converse.env.b64_sha1('converse.chatboxes-'+_converse.bare_jid));
this.registerMessageHandler(); this.registerMessageHandler();
...@@ -41,7 +41,7 @@ ...@@ -41,7 +41,7 @@
ChatRoomView: { ChatRoomView: {
insertIntoDOM: function () { insertIntoDOM: function () {
if (!document.body.contains(this.el)) { if (!document.body.contains(this.el)) {
var container = document.querySelector('#converse-embedded-chat'); const container = document.querySelector('#converse-embedded-chat');
container.innerHTML = ''; container.innerHTML = '';
container.appendChild(this.el); container.appendChild(this.el);
} }
...@@ -54,7 +54,7 @@ ...@@ -54,7 +54,7 @@
/* The initialize function gets called as soon as the plugin is /* The initialize function gets called as soon as the plugin is
* loaded by converse.js's plugin machinery. * loaded by converse.js's plugin machinery.
*/ */
var _converse = this._converse; const _converse = this._converse;
if (!_.isArray(_converse.auto_join_rooms)) { if (!_.isArray(_converse.auto_join_rooms)) {
throw new Error("converse-muc-embedded: auto_join_rooms must be an Array"); throw new Error("converse-muc-embedded: auto_join_rooms must be an Array");
} }
...@@ -62,7 +62,7 @@ ...@@ -62,7 +62,7 @@
throw new Error("converse-muc-embedded: It doesn't make "+ throw new Error("converse-muc-embedded: It doesn't make "+
"sense to have the auto_join_rooms setting to zero or "+ "sense to have the auto_join_rooms setting to zero or "+
"more then one, since only one chat room can be open "+ "more then one, since only one chat room can be open "+
"at any time.") "at any time.");
} }
} }
}); });
......
...@@ -57,11 +57,11 @@ ...@@ -57,11 +57,11 @@
) { ) {
"use strict"; "use strict";
var ROOMS_PANEL_ID = 'chatrooms'; const ROOMS_PANEL_ID = 'chatrooms';
var CHATROOMS_TYPE = 'chatroom'; const CHATROOMS_TYPE = 'chatroom';
// Strophe methods for building stanzas // Strophe methods for building stanzas
var Strophe = converse.env.Strophe, const Strophe = converse.env.Strophe,
Backbone = converse.env.Backbone, Backbone = converse.env.Backbone,
$iq = converse.env.$iq, $iq = converse.env.$iq,
$build = converse.env.$build, $build = converse.env.$build,
...@@ -71,7 +71,7 @@ ...@@ -71,7 +71,7 @@
sizzle = converse.env.sizzle, sizzle = converse.env.sizzle,
utils = converse.env.utils; utils = converse.env.utils;
// Other necessary globals // Other necessary globals
var $ = converse.env.jQuery, const $ = converse.env.jQuery,
_ = converse.env._, _ = converse.env._,
fp = converse.env.fp, fp = converse.env.fp,
moment = converse.env.moment; moment = converse.env.moment;
...@@ -83,13 +83,13 @@ ...@@ -83,13 +83,13 @@
Strophe.addNamespace('MUC_ROOMCONF', Strophe.NS.MUC + "#roomconfig"); Strophe.addNamespace('MUC_ROOMCONF', Strophe.NS.MUC + "#roomconfig");
Strophe.addNamespace('MUC_USER', Strophe.NS.MUC + "#user"); Strophe.addNamespace('MUC_USER', Strophe.NS.MUC + "#user");
var ROOM_FEATURES = [ const ROOM_FEATURES = [
'passwordprotected', 'unsecured', 'hidden', 'passwordprotected', 'unsecured', 'hidden',
'public', 'membersonly', 'open', 'persistent', 'public', 'membersonly', 'open', 'persistent',
'temporary', 'nonanonymous', 'semianonymous', 'temporary', 'nonanonymous', 'semianonymous',
'moderated', 'unmoderated', 'mam_enabled' 'moderated', 'unmoderated', 'mam_enabled'
]; ];
var ROOM_FEATURES_MAP = { const ROOM_FEATURES_MAP = {
'passwordprotected': 'unsecured', 'passwordprotected': 'unsecured',
'unsecured': 'passwordprotected', 'unsecured': 'passwordprotected',
'hidden': 'public', 'hidden': 'public',
...@@ -103,7 +103,7 @@ ...@@ -103,7 +103,7 @@
'moderated': 'unmoderated', 'moderated': 'unmoderated',
'unmoderated': 'moderated' 'unmoderated': 'moderated'
}; };
var ROOMSTATUS = { const ROOMSTATUS = {
CONNECTED: 0, CONNECTED: 0,
CONNECTING: 1, CONNECTING: 1,
NICKNAME_REQUIRED: 2, NICKNAME_REQUIRED: 2,
...@@ -144,7 +144,7 @@ ...@@ -144,7 +144,7 @@
Features: { Features: {
addClientFeatures: function () { addClientFeatures: function () {
var _converse = this.__super__._converse; const _converse = this.__super__._converse;
this.__super__.addClientFeatures.apply(this, arguments); this.__super__.addClientFeatures.apply(this, arguments);
if (_converse.allow_muc_invitations) { if (_converse.allow_muc_invitations) {
_converse.connection.disco.addFeature('jabber:x:conference'); // Invites _converse.connection.disco.addFeature('jabber:x:conference'); // Invites
...@@ -157,7 +157,7 @@ ...@@ -157,7 +157,7 @@
ChatBoxes: { ChatBoxes: {
model: function (attrs, options) { model: function (attrs, options) {
var _converse = this.__super__._converse; const _converse = this.__super__._converse;
if (attrs.type == CHATROOMS_TYPE) { if (attrs.type == CHATROOMS_TYPE) {
return new _converse.ChatRoom(attrs, options); return new _converse.ChatRoom(attrs, options);
} else { } else {
...@@ -168,7 +168,7 @@ ...@@ -168,7 +168,7 @@
ControlBoxView: { ControlBoxView: {
renderRoomsPanel: function () { renderRoomsPanel: function () {
var _converse = this.__super__._converse; const _converse = this.__super__._converse;
this.roomspanel = new _converse.RoomsPanel({ this.roomspanel = new _converse.RoomsPanel({
'$parent': this.$el.find('.controlbox-panes'), '$parent': this.$el.find('.controlbox-panes'),
'model': new (Backbone.Model.extend({ 'model': new (Backbone.Model.extend({
...@@ -187,7 +187,7 @@ ...@@ -187,7 +187,7 @@
}, },
renderContactsPanel: function () { renderContactsPanel: function () {
var _converse = this.__super__._converse; const _converse = this.__super__._converse;
this.__super__.renderContactsPanel.apply(this, arguments); this.__super__.renderContactsPanel.apply(this, arguments);
if (_converse.allow_muc) { if (_converse.allow_muc) {
this.renderRoomsPanel(); this.renderRoomsPanel();
...@@ -195,7 +195,7 @@ ...@@ -195,7 +195,7 @@
}, },
onConnected: function () { onConnected: function () {
var _converse = this.__super__._converse; const _converse = this.__super__._converse;
this.__super__.onConnected.apply(this, arguments); this.__super__.onConnected.apply(this, arguments);
if (!this.model.get('connected')) { if (!this.model.get('connected')) {
return; return;
...@@ -205,7 +205,7 @@ ...@@ -205,7 +205,7 @@
_converse.features.on('add', this.featureAdded, this); _converse.features.on('add', this.featureAdded, this);
// Features could have been added before the controlbox was // Features could have been added before the controlbox was
// initialized. We're only interested in MUC // initialized. We're only interested in MUC
var feature = _converse.features.findWhere({ const feature = _converse.features.findWhere({
'var': Strophe.NS.MUC 'var': Strophe.NS.MUC
}); });
if (feature) { if (feature) {
...@@ -218,14 +218,14 @@ ...@@ -218,14 +218,14 @@
setMUCDomain: function (domain) { setMUCDomain: function (domain) {
this.roomspanel.model.save({'muc_domain': domain}); this.roomspanel.model.save({'muc_domain': domain});
var $server= this.$el.find('input.new-chatroom-server'); const $server= this.$el.find('input.new-chatroom-server');
if (!$server.is(':focus')) { if (!$server.is(':focus')) {
$server.val(this.roomspanel.model.get('muc_domain')); $server.val(this.roomspanel.model.get('muc_domain'));
} }
}, },
featureAdded: function (feature) { featureAdded: function (feature) {
var _converse = this.__super__._converse; const _converse = this.__super__._converse;
if ((feature.get('var') === Strophe.NS.MUC) && (_converse.allow_muc)) { if ((feature.get('var') === Strophe.NS.MUC) && (_converse.allow_muc)) {
this.setMUCDomain(feature.get('from')); this.setMUCDomain(feature.get('from'));
} }
...@@ -234,8 +234,8 @@ ...@@ -234,8 +234,8 @@
ChatBoxViews: { ChatBoxViews: {
onChatBoxAdded: function (item) { onChatBoxAdded: function (item) {
var _converse = this.__super__._converse; const _converse = this.__super__._converse;
var view = this.get(item.get('id')); let view = this.get(item.get('id'));
if (!view && item.get('type') === CHATROOMS_TYPE) { if (!view && item.get('type') === CHATROOMS_TYPE) {
view = new _converse.ChatRoomView({'model': item}); view = new _converse.ChatRoomView({'model': item});
return this.add(item.get('id'), view); return this.add(item.get('id'), view);
...@@ -250,7 +250,7 @@ ...@@ -250,7 +250,7 @@
/* The initialize function gets called as soon as the plugin is /* The initialize function gets called as soon as the plugin is
* loaded by converse.js's plugin machinery. * loaded by converse.js's plugin machinery.
*/ */
var _converse = this._converse, const _converse = this._converse,
__ = _converse.__, __ = _converse.__,
___ = _converse.___; ___ = _converse.___;
// XXX: Inside plugins, all calls to the translation machinery // XXX: Inside plugins, all calls to the translation machinery
...@@ -402,7 +402,7 @@ ...@@ -402,7 +402,7 @@
* Parameters: * Parameters:
* (XMLElement): The <messsage> stanza * (XMLElement): The <messsage> stanza
*/ */
var body = stanza.querySelector('body') const body = stanza.querySelector('body');
if (_.isNull(body)) { if (_.isNull(body)) {
return; // The message has no text return; // The message has no text
} }
...@@ -446,7 +446,6 @@ ...@@ -446,7 +446,6 @@
}, },
initialize: function () { initialize: function () {
var that = this;
this.model.messages.on('add', this.onMessageAdded, this); this.model.messages.on('add', this.onMessageAdded, this);
this.model.on('show', this.show, this); this.model.on('show', this.show, this);
this.model.on('destroy', this.hide, this); this.model.on('destroy', this.hide, this);
...@@ -461,10 +460,10 @@ ...@@ -461,10 +460,10 @@
this.registerHandlers(); this.registerHandlers();
if (this.model.get('connection_status') !== ROOMSTATUS.ENTERED) { if (this.model.get('connection_status') !== ROOMSTATUS.ENTERED) {
this.getRoomFeatures().always(function () { this.getRoomFeatures().always(() => {
that.join(); this.join();
that.fetchMessages(); this.fetchMessages();
_converse.emit('chatRoomOpened', that); _converse.emit('chatRoomOpened', this);
}); });
} else { } else {
this.fetchMessages(); this.fetchMessages();
...@@ -513,10 +512,10 @@ ...@@ -513,10 +512,10 @@
createOccupantsView: function () { createOccupantsView: function () {
/* Create the ChatRoomOccupantsView Backbone.View /* Create the ChatRoomOccupantsView Backbone.View
*/ */
var model = new _converse.ChatRoomOccupants(); const model = new _converse.ChatRoomOccupants();
model.chatroomview = this; model.chatroomview = this;
this.occupantsview = new _converse.ChatRoomOccupantsView({'model': model}); this.occupantsview = new _converse.ChatRoomOccupantsView({'model': model});
var id = b64_sha1('converse.occupants'+_converse.bare_jid+this.model.get('jid')); const id = b64_sha1('converse.occupants'+_converse.bare_jid+this.model.get('jid'));
this.occupantsview.model.browserStorage = new Backbone.BrowserStorage.session(id); this.occupantsview.model.browserStorage = new Backbone.BrowserStorage.session(id);
this.occupantsview.render(); this.occupantsview.render();
this.occupantsview.model.fetch({add:true}); this.occupantsview.model.fetch({add:true});
...@@ -527,7 +526,7 @@ ...@@ -527,7 +526,7 @@
if (document.querySelector('body').contains(this.el)) { if (document.querySelector('body').contains(this.el)) {
return; return;
} }
var view = _converse.chatboxviews.get("controlbox"); const view = _converse.chatboxviews.get("controlbox");
if (view) { if (view) {
this.$el.insertAfter(view.$el); this.$el.insertAfter(view.$el);
} else { } else {
...@@ -570,7 +569,7 @@ ...@@ -570,7 +569,7 @@
}, },
getExtraMessageClasses: function (attrs) { getExtraMessageClasses: function (attrs) {
var extra_classes = _converse.ChatBoxView.prototype let extra_classes = _converse.ChatBoxView.prototype
.getExtraMessageClasses.apply(this, arguments); .getExtraMessageClasses.apply(this, arguments);
if (this.is_chatroom && attrs.sender === 'them' && if (this.is_chatroom && attrs.sender === 'them' &&
...@@ -649,9 +648,9 @@ ...@@ -649,9 +648,9 @@
* A promise which resolves once the list has been * A promise which resolves once the list has been
* retrieved. * retrieved.
*/ */
var deferred = new $.Deferred(); const deferred = new $.Deferred();
affiliation = affiliation || 'member'; affiliation = affiliation || 'member';
var iq = $iq({to: chatroom_jid, type: "get"}) const iq = $iq({to: chatroom_jid, type: "get"})
.c("query", {xmlns: Strophe.NS.MUC_ADMIN}) .c("query", {xmlns: Strophe.NS.MUC_ADMIN})
.c("item", {'affiliation': affiliation}); .c("item", {'affiliation': affiliation});
_converse.connection.sendIQ(iq, deferred.resolve, deferred.reject); _converse.connection.sendIQ(iq, deferred.resolve, deferred.reject);
...@@ -700,17 +699,17 @@ ...@@ -700,17 +699,17 @@
* (Array) new_list: Array containing the new affiliations * (Array) new_list: Array containing the new affiliations
* (Array) old_list: Array containing the old affiliations * (Array) old_list: Array containing the old affiliations
*/ */
var new_jids = _.map(new_list, 'jid'); const new_jids = _.map(new_list, 'jid');
var old_jids = _.map(old_list, 'jid'); const old_jids = _.map(old_list, 'jid');
// Get the new affiliations // Get the new affiliations
var delta = _.map(_.difference(new_jids, old_jids), function (jid) { let delta = _.map(_.difference(new_jids, old_jids), function (jid) {
return new_list[_.indexOf(new_jids, jid)]; return new_list[_.indexOf(new_jids, jid)];
}); });
if (!exclude_existing) { if (!exclude_existing) {
// Get the changed affiliations // Get the changed affiliations
delta = delta.concat(_.filter(new_list, function (item) { delta = delta.concat(_.filter(new_list, function (item) {
var idx = _.indexOf(old_jids, item.jid); const idx = _.indexOf(old_jids, item.jid);
if (idx >= 0) { if (idx >= 0) {
return item.affiliation !== old_list[idx].affiliation; return item.affiliation !== old_list[idx].affiliation;
} }
...@@ -736,8 +735,8 @@ ...@@ -736,8 +735,8 @@
* (Object) member: Map containing the member's jid and * (Object) member: Map containing the member's jid and
* optionally a reason and affiliation. * optionally a reason and affiliation.
*/ */
var deferred = new $.Deferred(); const deferred = new $.Deferred();
var iq = $iq({to: chatroom_jid, type: "set"}) const iq = $iq({to: chatroom_jid, type: "set"})
.c("query", {xmlns: Strophe.NS.MUC_ADMIN}) .c("query", {xmlns: Strophe.NS.MUC_ADMIN})
.c("item", { .c("item", {
'affiliation': member.affiliation || affiliation, 'affiliation': member.affiliation || affiliation,
...@@ -779,7 +778,7 @@ ...@@ -779,7 +778,7 @@
return _.isUndefined(member.affiliation) || return _.isUndefined(member.affiliation) ||
member.affiliation === affiliation; member.affiliation === affiliation;
}); });
var promises = _.map( const promises = _.map(
members, members,
_.partial(this.sendAffiliationIQ, this.model.get('jid'), affiliation) _.partial(this.sendAffiliationIQ, this.model.get('jid'), affiliation)
); );
...@@ -802,8 +801,8 @@ ...@@ -802,8 +801,8 @@
onSuccess(null); onSuccess(null);
return; return;
} }
var affiliations = _.uniq(_.map(members, 'affiliation')); const affiliations = _.uniq(_.map(members, 'affiliation'));
var promises = _.map(affiliations, _.partial(this.setAffiliation.bind(this), _, members)); const promises = _.map(affiliations, _.partial(this.setAffiliation.bind(this), _, members));
$.when.apply($, promises).done(onSuccess).fail(onError); $.when.apply($, promises).done(onSuccess).fail(onError);
}, },
...@@ -825,8 +824,8 @@ ...@@ -825,8 +824,8 @@
if (_.isString(affiliations)) { if (_.isString(affiliations)) {
affiliations = [affiliations]; affiliations = [affiliations];
} }
var deferred = new $.Deferred(); const deferred = new $.Deferred();
var promises = _.map(affiliations, _.partial(this.requestMemberList, this.model.get('jid'))); const promises = _.map(affiliations, _.partial(this.requestMemberList, this.model.get('jid')));
$.when.apply($, promises).always( $.when.apply($, promises).always(
_.flow(this.marshallAffiliationIQs.bind(this), deferred.resolve) _.flow(this.marshallAffiliationIQs.bind(this), deferred.resolve)
); );
...@@ -851,10 +850,9 @@ ...@@ -851,10 +850,9 @@
* updated or once it's been established there's no need * updated or once it's been established there's no need
* to update the list. * to update the list.
*/ */
var that = this; const deferred = new $.Deferred();
var deferred = new $.Deferred(); this.getJidsWithAffiliations(affiliations).then((old_members) => {
this.getJidsWithAffiliations(affiliations).then(function (old_members) { this.setAffiliations(
that.setAffiliations(
deltaFunc(members, old_members), deltaFunc(members, old_members),
deferred.resolve, deferred.resolve,
deferred.reject deferred.reject
...@@ -875,21 +873,21 @@ ...@@ -875,21 +873,21 @@
// the person to the member list by giving them an // the person to the member list by giving them an
// affiliation of 'member' (if they're not affiliated // affiliation of 'member' (if they're not affiliated
// already), otherwise they won't be able to join. // already), otherwise they won't be able to join.
var map = {}; map[recipient] = 'member'; const map = {}; map[recipient] = 'member';
var deltaFunc = _.partial(this.computeAffiliationsDelta, true, false); const deltaFunc = _.partial(this.computeAffiliationsDelta, true, false);
this.updateMemberLists( this.updateMemberLists(
[{'jid': recipient, 'affiliation': 'member', 'reason': reason}], [{'jid': recipient, 'affiliation': 'member', 'reason': reason}],
['member', 'owner', 'admin'], ['member', 'owner', 'admin'],
deltaFunc deltaFunc
); );
} }
var attrs = { const attrs = {
'xmlns': 'jabber:x:conference', 'xmlns': 'jabber:x:conference',
'jid': this.model.get('jid') 'jid': this.model.get('jid')
}; };
if (reason !== null) { attrs.reason = reason; } if (reason !== null) { attrs.reason = reason; }
if (this.model.get('password')) { attrs.password = this.model.get('password'); } if (this.model.get('password')) { attrs.password = this.model.get('password'); }
var invitation = $msg({ const invitation = $msg({
from: _converse.connection.jid, from: _converse.connection.jid,
to: recipient, to: recipient,
id: _converse.connection.getUniqueId() id: _converse.connection.getUniqueId()
...@@ -928,7 +926,7 @@ ...@@ -928,7 +926,7 @@
if (this.model.get('connection_status') !== ROOMSTATUS.ENTERED) { if (this.model.get('connection_status') !== ROOMSTATUS.ENTERED) {
return; return;
} }
var chat_state = this.model.get('chat_state'); const chat_state = this.model.get('chat_state');
if (chat_state === _converse.GONE) { if (chat_state === _converse.GONE) {
// <gone/> is not applicable within MUC context // <gone/> is not applicable within MUC context
return; return;
...@@ -948,8 +946,8 @@ ...@@ -948,8 +946,8 @@
* Parameters: * Parameters:
* (String) text: The message text to be sent. * (String) text: The message text to be sent.
*/ */
var msgid = _converse.connection.getUniqueId(); const msgid = _converse.connection.getUniqueId();
var msg = $msg({ const msg = $msg({
to: this.model.get('jid'), to: this.model.get('jid'),
from: _converse.connection.jid, from: _converse.connection.jid,
type: 'groupchat', type: 'groupchat',
...@@ -967,8 +965,8 @@ ...@@ -967,8 +965,8 @@
}, },
modifyRole: function(room, nick, role, reason, onSuccess, onError) { modifyRole: function(room, nick, role, reason, onSuccess, onError) {
var item = $build("item", {nick: nick, role: role}); const item = $build("item", {nick: nick, role: role});
var iq = $iq({to: room, type: "set"}).c("query", {xmlns: Strophe.NS.MUC_ADMIN}).cnode(item.node); const iq = $iq({to: room, type: "set"}).c("query", {xmlns: Strophe.NS.MUC_ADMIN}).cnode(item.node);
if (reason !== null) { iq.c("reason", reason); } if (reason !== null) { iq.c("reason", reason); }
return _converse.connection.sendIQ(iq.tree(), onSuccess, onError); return _converse.connection.sendIQ(iq.tree(), onSuccess, onError);
}, },
...@@ -992,7 +990,7 @@ ...@@ -992,7 +990,7 @@
/* Remove all messages from the chat room UI. /* Remove all messages from the chat room UI.
*/ */
if (!_.isUndefined(ev)) { ev.stopPropagation(); } if (!_.isUndefined(ev)) { ev.stopPropagation(); }
var result = confirm(__("Are you sure you want to clear the messages from this room?")); const result = confirm(__("Are you sure you want to clear the messages from this room?"));
if (result === true) { if (result === true) {
this.$content.empty(); this.$content.empty();
} }
...@@ -1013,7 +1011,7 @@ ...@@ -1013,7 +1011,7 @@
if (_converse.muc_disable_moderator_commands) { if (_converse.muc_disable_moderator_commands) {
return this.sendChatRoomMessage(text); return this.sendChatRoomMessage(text);
} }
var match = text.replace(/^\s*/, "").match(/^\/(.*?)(?: (.*))?$/) || [false, '', ''], const match = text.replace(/^\s*/, "").match(/^\/(.*?)(?: (.*))?$/) || [false, '', ''],
args = match[2] && match[2].splitOnce(' ') || [], args = match[2] && match[2].splitOnce(' ') || [],
command = match[1].toLowerCase(); command = match[1].toLowerCase();
switch (command) { switch (command) {
...@@ -1134,12 +1132,12 @@ ...@@ -1134,12 +1132,12 @@
* Parameters: * Parameters:
* (XMLElement) stanza: The message stanza. * (XMLElement) stanza: The message stanza.
*/ */
var configuration_changed = stanza.querySelector("status[code='104']"); const configuration_changed = stanza.querySelector("status[code='104']");
var logging_enabled = stanza.querySelector("status[code='170']"); const logging_enabled = stanza.querySelector("status[code='170']");
var logging_disabled = stanza.querySelector("status[code='171']"); const logging_disabled = stanza.querySelector("status[code='171']");
var room_no_longer_anon = stanza.querySelector("status[code='172']"); const room_no_longer_anon = stanza.querySelector("status[code='172']");
var room_now_semi_anon = stanza.querySelector("status[code='173']"); const room_now_semi_anon = stanza.querySelector("status[code='173']");
var room_now_fully_anon = stanza.querySelector("status[code='173']"); const room_now_fully_anon = stanza.querySelector("status[code='173']");
if (configuration_changed || logging_enabled || logging_disabled || if (configuration_changed || logging_enabled || logging_disabled ||
room_no_longer_anon || room_now_semi_anon || room_now_fully_anon) { room_no_longer_anon || room_now_semi_anon || room_now_fully_anon) {
this.getRoomFeatures(); this.getRoomFeatures();
...@@ -1162,9 +1160,9 @@ ...@@ -1162,9 +1160,9 @@
} else { } else {
nick = this.model.get('nick'); nick = this.model.get('nick');
} }
var room = this.model.get('jid'); const room = this.model.get('jid');
var node = Strophe.getNodeFromJid(room); const node = Strophe.getNodeFromJid(room);
var domain = Strophe.getDomainFromJid(room); const domain = Strophe.getDomainFromJid(room);
return node + "@" + domain + (nick !== null ? "/" + nick : ""); return node + "@" + domain + (nick !== null ? "/" + nick : "");
}, },
...@@ -1172,7 +1170,7 @@ ...@@ -1172,7 +1170,7 @@
/* Register presence and message handlers for this chat /* Register presence and message handlers for this chat
* room * room
*/ */
var room_jid = this.model.get('jid'); const room_jid = this.model.get('jid');
this.removeHandlers(); this.removeHandlers();
this.presence_handler = _converse.connection.addHandler( this.presence_handler = _converse.connection.addHandler(
this.onChatRoomPresence.bind(this), this.onChatRoomPresence.bind(this),
...@@ -1218,7 +1216,7 @@ ...@@ -1218,7 +1216,7 @@
// so we don't send out a presence stanza again. // so we don't send out a presence stanza again.
return this; return this;
} }
var stanza = $pres({ const stanza = $pres({
'from': _converse.connection.jid, 'from': _converse.connection.jid,
'to': this.getRoomJIDAndNick(nick) 'to': this.getRoomJIDAndNick(nick)
}).c("x", {'xmlns': Strophe.NS.MUC}) }).c("x", {'xmlns': Strophe.NS.MUC})
...@@ -1275,19 +1273,18 @@ ...@@ -1275,19 +1273,18 @@
* (XMLElement) stanza: The IQ stanza containing the room * (XMLElement) stanza: The IQ stanza containing the room
* config. * config.
*/ */
var that = this, const $body = this.$('.chatroom-body');
$body = this.$('.chatroom-body');
$body.children().addClass('hidden'); $body.children().addClass('hidden');
// Remove any existing forms // Remove any existing forms
$body.find('form.chatroom-form').remove(); $body.find('form.chatroom-form').remove();
$body.append(tpl_chatroom_form()); $body.append(tpl_chatroom_form());
var $form = $body.find('form.chatroom-form'), const $form = $body.find('form.chatroom-form');
$fieldset = $form.children('fieldset:first'), let $fieldset = $form.children('fieldset:first');
$stanza = $(stanza), const $stanza = $(stanza),
$fields = $stanza.find('field'), $fields = $stanza.find('field'),
title = $stanza.find('title').text(), title = $stanza.find('title').text(),
instructions = $stanza.find('instructions').text(); instructions = $stanza.find('instructions').text();
$fieldset.find('span.spinner').remove(); $fieldset.find('span.spinner').remove();
$fieldset.append($('<legend>').text(title)); $fieldset.append($('<legend>').text(title));
if (instructions && instructions !== title) { if (instructions && instructions !== title) {
...@@ -1300,13 +1297,13 @@ ...@@ -1300,13 +1297,13 @@
$fieldset = $form.children('fieldset:last'); $fieldset = $form.children('fieldset:last');
$fieldset.append('<input type="submit" class="pure-button button-primary" value="'+__('Save')+'"/>'); $fieldset.append('<input type="submit" class="pure-button button-primary" value="'+__('Save')+'"/>');
$fieldset.append('<input type="button" class="pure-button button-cancel" value="'+__('Cancel')+'"/>'); $fieldset.append('<input type="button" class="pure-button button-cancel" value="'+__('Cancel')+'"/>');
$fieldset.find('input[type=button]').on('click', function (ev) { $fieldset.find('input[type=button]').on('click', (ev) => {
ev.preventDefault(); ev.preventDefault();
that.cancelConfiguration(); this.cancelConfiguration();
}); });
$form.on('submit', function (ev) { $form.on('submit', (ev) => {
ev.preventDefault(); ev.preventDefault();
that.saveConfiguration(ev.target); this.saveConfiguration(ev.target);
}); });
}, },
...@@ -1324,7 +1321,7 @@ ...@@ -1324,7 +1321,7 @@
* room configuration. * room configuration.
* The second is the response IQ from the server. * The second is the response IQ from the server.
*/ */
var iq = $iq({to: this.model.get('jid'), type: "set"}) const iq = $iq({to: this.model.get('jid'), type: "set"})
.c("query", {xmlns: Strophe.NS.MUC_OWNER}) .c("query", {xmlns: Strophe.NS.MUC_OWNER})
.c("x", {xmlns: Strophe.NS.XFORM, type: "submit"}); .c("x", {xmlns: Strophe.NS.XFORM, type: "submit"});
_.each(config || [], function (node) { iq.cnode(node).up(); }); _.each(config || [], function (node) { iq.cnode(node).up(); });
...@@ -1343,9 +1340,8 @@ ...@@ -1343,9 +1340,8 @@
* Parameters: * Parameters:
* (HTMLElement) form: The configuration form DOM element. * (HTMLElement) form: The configuration form DOM element.
*/ */
var deferred = new $.Deferred(); const deferred = new $.Deferred();
var that = this; const $inputs = $(form).find(':input:not([type=button]):not([type=submit])'),
var $inputs = $(form).find(':input:not([type=button]):not([type=submit])'),
configArray = []; configArray = [];
$inputs.each(function () { $inputs.each(function () {
configArray.push(utils.webForm2xForm(this)); configArray.push(utils.webForm2xForm(this));
...@@ -1355,11 +1351,10 @@ ...@@ -1355,11 +1351,10 @@
deferred.resolve, deferred.resolve,
deferred.reject deferred.reject
); );
this.$el.find('div.chatroom-form-container').hide( this.$el.find('div.chatroom-form-container').hide((el) => {
function () { $(el).remove();
$(this).remove(); this.renderAfterTransition();
that.renderAfterTransition(); });
});
return deferred.promise(); return deferred.promise();
}, },
...@@ -1374,8 +1369,8 @@ ...@@ -1374,8 +1369,8 @@
* (XMLElement) stanza: IQ stanza from the server, * (XMLElement) stanza: IQ stanza from the server,
* containing the configuration. * containing the configuration.
*/ */
var that = this, var that = this;
deferred = new $.Deferred(); const deferred = new $.Deferred();
this.fetchRoomConfiguration().then(function (stanza) { this.fetchRoomConfiguration().then(function (stanza) {
var configArray = [], var configArray = [],
...@@ -1418,11 +1413,10 @@ ...@@ -1418,11 +1413,10 @@
/* Remove the configuration form without submitting and /* Remove the configuration form without submitting and
* return to the chat view. * return to the chat view.
*/ */
var that = this;
this.$el.find('div.chatroom-form-container').hide( this.$el.find('div.chatroom-form-container').hide(
function () { (el) => {
$(this).remove(); $(el).remove();
that.renderAfterTransition(); this.renderAfterTransition();
}); });
}, },
...@@ -1434,16 +1428,15 @@ ...@@ -1434,16 +1428,15 @@
* Parameters: * Parameters:
* (Function) handler: The handler for the response IQ * (Function) handler: The handler for the response IQ
*/ */
var that = this; const deferred = new $.Deferred();
var deferred = new $.Deferred();
_converse.connection.sendIQ( _converse.connection.sendIQ(
$iq({ $iq({
'to': this.model.get('jid'), 'to': this.model.get('jid'),
'type': "get" 'type': "get"
}).c("query", {xmlns: Strophe.NS.MUC_OWNER}), }).c("query", {xmlns: Strophe.NS.MUC_OWNER}),
function (iq) { (iq) => {
if (handler) { if (handler) {
handler.apply(that, arguments); handler.apply(this, arguments);
} }
deferred.resolve(iq); deferred.resolve(iq);
}, },
...@@ -1456,7 +1449,7 @@ ...@@ -1456,7 +1449,7 @@
/* Fetch the room disco info, parse it and then /* Fetch the room disco info, parse it and then
* save it on the Backbone.Model of this chat rooms. * save it on the Backbone.Model of this chat rooms.
*/ */
var deferred = new $.Deferred(); const deferred = new $.Deferred();
var that = this; var that = this;
_converse.connection.disco.info(this.model.get('jid'), null, _converse.connection.disco.info(this.model.get('jid'), null,
function (iq) { function (iq) {
...@@ -1475,11 +1468,11 @@ ...@@ -1475,11 +1468,11 @@
* <feature var='muc_nonanonymous'/> * <feature var='muc_nonanonymous'/>
* <feature var='urn:xmpp:mam:0'/> * <feature var='urn:xmpp:mam:0'/>
*/ */
var features = { const features = {
'features_fetched': true 'features_fetched': true
}; };
_.each(iq.querySelectorAll('feature'), function (field) { _.each(iq.querySelectorAll('feature'), function (field) {
var fieldname = field.getAttribute('var'); const fieldname = field.getAttribute('var');
if (!fieldname.startsWith('muc_')) { if (!fieldname.startsWith('muc_')) {
if (fieldname === Strophe.NS.MAM) { if (fieldname === Strophe.NS.MAM) {
features.mam_enabled = true; features.mam_enabled = true;
...@@ -1488,7 +1481,7 @@ ...@@ -1488,7 +1481,7 @@
} }
features[fieldname.replace('muc_', '')] = true; features[fieldname.replace('muc_', '')] = true;
}); });
var desc_field = iq.querySelector('field[var="muc#roominfo_description"] value'); const desc_field = iq.querySelector('field[var="muc#roominfo_description"] value');
if (!_.isNull(desc_field)) { if (!_.isNull(desc_field)) {
features.description = desc_field.textContent; features.description = desc_field.textContent;
} }
...@@ -1526,8 +1519,8 @@ ...@@ -1526,8 +1519,8 @@
* chat room with it. * chat room with it.
*/ */
ev.preventDefault(); ev.preventDefault();
var nick_el = ev.target.nick; const nick_el = ev.target.nick;
var nick = nick_el.value; const nick = nick_el.value;
if (!nick) { if (!nick) {
nick_el.classList.add('error'); nick_el.classList.add('error');
return; return;
...@@ -1572,7 +1565,7 @@ ...@@ -1572,7 +1565,7 @@
* Parameters: * Parameters:
* (XMLElement) iq: The received IQ stanza * (XMLElement) iq: The received IQ stanza
*/ */
var nick = $(iq) const nick = $(iq)
.find('query[node="x-roomuser-item"] identity') .find('query[node="x-roomuser-item"] identity')
.attr('name'); .attr('name');
if (!nick) { if (!nick) {
...@@ -1611,12 +1604,12 @@ ...@@ -1611,12 +1604,12 @@
* muc_nickname_from_jid. * muc_nickname_from_jid.
*/ */
if (_converse.muc_nickname_from_jid) { if (_converse.muc_nickname_from_jid) {
var nick = presence.getAttribute('from').split('/')[1]; const nick = presence.getAttribute('from').split('/')[1];
if (nick === this.getDefaultNickName()) { if (nick === this.getDefaultNickName()) {
this.join(nick + '-2'); this.join(nick + '-2');
} else { } else {
var del= nick.lastIndexOf("-"); const del= nick.lastIndexOf("-");
var num = nick.substring(del+1, nick.length); const num = nick.substring(del+1, nick.length);
this.join(nick.substring(0, del+1) + String(Number(num)+1)); this.join(nick.substring(0, del+1) + String(Number(num)+1));
} }
} else { } else {
...@@ -1649,7 +1642,7 @@ ...@@ -1649,7 +1642,7 @@
submitPassword: function (ev) { submitPassword: function (ev) {
ev.preventDefault(); ev.preventDefault();
var password = this.$el.find('.chatroom-form').find('input[type=password]').val(); const password = this.$el.find('.chatroom-form').find('input[type=password]').val();
this.$el.find('.chatroom-form-container').replaceWith(tpl_spinner); this.$el.find('.chatroom-form-container').replaceWith(tpl_spinner);
this.join(this.model.get('nick'), password); this.join(this.model.get('nick'), password);
}, },
...@@ -1683,11 +1676,12 @@ ...@@ -1683,11 +1676,12 @@
* current user. * current user.
* (XMLElement) stanza: The original stanza received. * (XMLElement) stanza: The original stanza received.
*/ */
var code = stat.getAttribute('code'), nick; const code = stat.getAttribute('code');
if (code === '110') { return; } if (code === '110') { return; }
if (code in _converse.muc.info_messages) { if (code in _converse.muc.info_messages) {
return _converse.muc.info_messages[code]; return _converse.muc.info_messages[code];
} }
let nick;
if (!is_self) { if (!is_self) {
if (code in _converse.muc.action_info_messages) { if (code in _converse.muc.action_info_messages) {
nick = Strophe.getResourceFromJid(stanza.getAttribute('from')); nick = Strophe.getResourceFromJid(stanza.getAttribute('from'));
...@@ -1711,11 +1705,11 @@ ...@@ -1711,11 +1705,11 @@
* Parameters: * Parameters:
* (XMLElement) pres: A <presence> stanza. * (XMLElement) pres: A <presence> stanza.
*/ */
var item = sizzle('x[xmlns="'+Strophe.NS.MUC_USER+'"] item', pres).pop(); const item = sizzle('x[xmlns="'+Strophe.NS.MUC_USER+'"] item', pres).pop();
var is_self = pres.querySelector("status[code='110']"); const is_self = pres.querySelector("status[code='110']");
if (is_self && !_.isNil(item)) { if (is_self && !_.isNil(item)) {
var affiliation = item.getAttribute('affiliation'); const affiliation = item.getAttribute('affiliation');
var role = item.getAttribute('role'); const role = item.getAttribute('role');
if (affiliation) { if (affiliation) {
this.model.save({'affiliation': affiliation}); this.model.save({'affiliation': affiliation});
} }
...@@ -1731,33 +1725,33 @@ ...@@ -1731,33 +1725,33 @@
* information. * information.
*/ */
// 1. Get notification messages based on the <status> elements. // 1. Get notification messages based on the <status> elements.
var statuses = x.querySelectorAll('status'); const statuses = x.querySelectorAll('status');
var mapper = _.partial(this.getMessageFromStatus, _, stanza, is_self); const mapper = _.partial(this.getMessageFromStatus, _, stanza, is_self);
var notification = {}; const notification = {};
var messages = _.reject(_.map(statuses, mapper), _.isUndefined); const messages = _.reject(_.map(statuses, mapper), _.isUndefined);
if (messages.length) { if (messages.length) {
notification.messages = messages; notification.messages = messages;
} }
// 2. Get disconnection messages based on the <status> elements // 2. Get disconnection messages based on the <status> elements
var codes = _.invokeMap(statuses, Element.prototype.getAttribute, 'code'); const codes = _.invokeMap(statuses, Element.prototype.getAttribute, 'code');
var disconnection_codes = _.intersection(codes, _.keys(_converse.muc.disconnect_messages)); const disconnection_codes = _.intersection(codes, _.keys(_converse.muc.disconnect_messages));
var disconnected = is_self && disconnection_codes.length > 0; const disconnected = is_self && disconnection_codes.length > 0;
if (disconnected) { if (disconnected) {
notification.disconnected = true; notification.disconnected = true;
notification.disconnection_message = _converse.muc.disconnect_messages[disconnection_codes[0]]; notification.disconnection_message = _converse.muc.disconnect_messages[disconnection_codes[0]];
} }
// 3. Find the reason and actor from the <item> element // 3. Find the reason and actor from the <item> element
var item = x.querySelector('item'); const item = x.querySelector('item');
// By using querySelector above, we assume here there is // By using querySelector above, we assume here there is
// one <item> per <x xmlns='http://jabber.org/protocol/muc#user'> // one <item> per <x xmlns='http://jabber.org/protocol/muc#user'>
// element. This appears to be a safe assumption, since // element. This appears to be a safe assumption, since
// each <x/> element pertains to a single user. // each <x/> element pertains to a single user.
if (!_.isNull(item)) { if (!_.isNull(item)) {
var reason = item.querySelector('reason'); const reason = item.querySelector('reason');
if (reason) { if (reason) {
notification.reason = reason ? reason.textContent : undefined; notification.reason = reason ? reason.textContent : undefined;
} }
var actor = item.querySelector('actor'); const actor = item.querySelector('actor');
if (actor) { if (actor) {
notification.actor = actor ? actor.getAttribute('nick') : undefined; notification.actor = actor ? actor.getAttribute('nick') : undefined;
} }
...@@ -1770,7 +1764,6 @@ ...@@ -1770,7 +1764,6 @@
* parseXUserElement, display any relevant messages and * parseXUserElement, display any relevant messages and
* information to the user. * information to the user.
*/ */
var that = this;
if (notification.disconnected) { if (notification.disconnected) {
this.showDisconnectMessage(notification.disconnection_message); this.showDisconnectMessage(notification.disconnection_message);
if (notification.actor) { if (notification.actor) {
...@@ -1782,8 +1775,8 @@ ...@@ -1782,8 +1775,8 @@
this.model.save('connection_status', ROOMSTATUS.DISCONNECTED); this.model.save('connection_status', ROOMSTATUS.DISCONNECTED);
return; return;
} }
_.each(notification.messages, function (message) { _.each(notification.messages, (message) => {
that.$content.append(tpl_info({'message': message})); this.$content.append(tpl_info({'message': message}));
}); });
if (notification.reason) { if (notification.reason) {
this.showStatusNotification(__('The reason given is: "'+notification.reason+'"'), true); this.showStatusNotification(__('The reason given is: "'+notification.reason+'"'), true);
...@@ -1800,8 +1793,8 @@ ...@@ -1800,8 +1793,8 @@
// XXX: some mangling required to make the returned // XXX: some mangling required to make the returned
// result look like the structure returned by // result look like the structure returned by
// parseXUserElement. Not nice... // parseXUserElement. Not nice...
var nick = Strophe.getResourceFromJid(stanza.getAttribute('from')); const nick = Strophe.getResourceFromJid(stanza.getAttribute('from'));
var stat = stanza.querySelector('status'); const stat = stanza.querySelector('status');
if (stanza.getAttribute('type') === 'unavailable') { if (stanza.getAttribute('type') === 'unavailable') {
if (!_.isNull(stat) && stat.textContent) { if (!_.isNull(stat) && stat.textContent) {
return [{'messages': [__(nick+' has left the room. "'+stat.textContent+'"')]}]; return [{'messages': [__(nick+' has left the room. "'+stat.textContent+'"')]}];
...@@ -1829,10 +1822,10 @@ ...@@ -1829,10 +1822,10 @@
* (XMLElement) stanza: The message or presence stanza * (XMLElement) stanza: The message or presence stanza
* containing the status codes. * containing the status codes.
*/ */
var elements = sizzle('x[xmlns="'+Strophe.NS.MUC_USER+'"]', stanza); const elements = sizzle('x[xmlns="'+Strophe.NS.MUC_USER+'"]', stanza);
var is_self = stanza.querySelectorAll("status[code='110']").length; const is_self = stanza.querySelectorAll("status[code='110']").length;
var iteratee = _.partial(this.parseXUserElement.bind(this), _, stanza, is_self); const iteratee = _.partial(this.parseXUserElement.bind(this), _, stanza, is_self);
var notifications = _.reject(_.map(elements, iteratee), _.isEmpty); let notifications = _.reject(_.map(elements, iteratee), _.isEmpty);
if (_.isEmpty(notifications) && if (_.isEmpty(notifications) &&
_converse.muc_show_join_leave && _converse.muc_show_join_leave &&
stanza.nodeName === 'presence' && stanza.nodeName === 'presence' &&
...@@ -1846,7 +1839,7 @@ ...@@ -1846,7 +1839,7 @@
showErrorMessage: function (presence) { showErrorMessage: function (presence) {
// We didn't enter the room, so we must remove it from the MUC add-on // We didn't enter the room, so we must remove it from the MUC add-on
var error = presence.querySelector('error'); const error = presence.querySelector('error');
if (error.getAttribute('type') === 'auth') { if (error.getAttribute('type') === 'auth') {
if (!_.isNull(error.querySelector('not-authorized'))) { if (!_.isNull(error.querySelector('not-authorized'))) {
this.renderPasswordForm(); this.renderPasswordForm();
...@@ -1901,7 +1894,7 @@ ...@@ -1901,7 +1894,7 @@
* Also make sure then that the chat area and occupants * Also make sure then that the chat area and occupants
* list are both visible. * list are both visible.
*/ */
var spinner = this.el.querySelector('.spinner'); const spinner = this.el.querySelector('.spinner');
if (!_.isNull(spinner)) { if (!_.isNull(spinner)) {
spinner.parentNode.removeChild(spinner); spinner.parentNode.removeChild(spinner);
this.renderAfterTransition(); this.renderAfterTransition();
...@@ -1927,7 +1920,7 @@ ...@@ -1927,7 +1920,7 @@
*/ */
this.saveAffiliationAndRole(pres); this.saveAffiliationAndRole(pres);
var locked_room = pres.querySelector("status[code='201']"); const locked_room = pres.querySelector("status[code='201']");
if (locked_room) { if (locked_room) {
if (this.model.get('auto_configure')) { if (this.model.get('auto_configure')) {
this.autoConfigureChatRoom().then(this.getRoomFeatures.bind(this)); this.autoConfigureChatRoom().then(this.getRoomFeatures.bind(this));
...@@ -1964,7 +1957,7 @@ ...@@ -1964,7 +1957,7 @@
this.showErrorMessage(pres); this.showErrorMessage(pres);
return true; return true;
} }
var is_self = pres.querySelector("status[code='110']"); const is_self = pres.querySelector("status[code='110']");
if (is_self && pres.getAttribute('type') !== 'unavailable') { if (is_self && pres.getAttribute('type') !== 'unavailable') {
this.onOwnChatRoomPresence(pres); this.onOwnChatRoomPresence(pres);
} }
...@@ -2052,8 +2045,8 @@ ...@@ -2052,8 +2045,8 @@
}, },
render: function () { render: function () {
var show = this.model.get('show') || 'online'; const show = this.model.get('show') || 'online';
var new_el = tpl_occupant( const new_el = tpl_occupant(
_.extend( _.extend(
{ 'jid': '', { 'jid': '',
'show': show, 'show': show,
...@@ -2065,7 +2058,7 @@ ...@@ -2065,7 +2058,7 @@
}, this.model.toJSON() }, this.model.toJSON()
) )
); );
var $parents = this.$el.parents(); const $parents = this.$el.parents();
if ($parents.length) { if ($parents.length) {
this.$el.replaceWith(new_el); this.$el.replaceWith(new_el);
this.setElement($parents.first().children('#'+this.model.get('id')), true); this.setElement($parents.first().children('#'+this.model.get('id')), true);
...@@ -2126,10 +2119,10 @@ ...@@ -2126,10 +2119,10 @@
}, },
renderInviteWidget: function () { renderInviteWidget: function () {
var form = this.el.querySelector('form.room-invite'); let form = this.el.querySelector('form.room-invite');
if (this.shouldInviteWidgetBeShown()) { if (this.shouldInviteWidgetBeShown()) {
if (_.isNull(form)) { if (_.isNull(form)) {
var heading = this.el.querySelector('.occupants-heading'); const heading = this.el.querySelector('.occupants-heading');
form = tpl_chatroom_invite({ form = tpl_chatroom_invite({
'label_invitation': __('Invite'), 'label_invitation': __('Invite'),
}); });
...@@ -2145,7 +2138,7 @@ ...@@ -2145,7 +2138,7 @@
}, },
renderRoomFeatures: function () { renderRoomFeatures: function () {
var picks = _.pick(this.chatroomview.model.attributes, ROOM_FEATURES), const picks = _.pick(this.chatroomview.model.attributes, ROOM_FEATURES),
iteratee = function (a, v) { return a || v; }, iteratee = function (a, v) { return a || v; },
el = this.el.querySelector('.chatroom-features'); el = this.el.querySelector('.chatroom-features');
...@@ -2199,7 +2192,7 @@ ...@@ -2199,7 +2192,7 @@
this.renderRoomFeatures, 100, {'leading': false} this.renderRoomFeatures, 100, {'leading': false}
); );
} }
var changed_features = {}; const changed_features = {};
_.each(_.keys(model.changed), function (k) { _.each(_.keys(model.changed), function (k) {
if (!_.isNil(ROOM_FEATURES_MAP[k])) { if (!_.isNil(ROOM_FEATURES_MAP[k])) {
changed_features[ROOM_FEATURES_MAP[k]] = !model.changed[k]; changed_features[ROOM_FEATURES_MAP[k]] = !model.changed[k];
...@@ -2211,13 +2204,13 @@ ...@@ -2211,13 +2204,13 @@
setOccupantsHeight: function () { setOccupantsHeight: function () {
var el = this.el.querySelector('.chatroom-features'); const el = this.el.querySelector('.chatroom-features');
this.el.querySelector('.occupant-list').style.cssText = this.el.querySelector('.occupant-list').style.cssText =
'height: calc(100% - '+el.offsetHeight+'px - 5em);'; 'height: calc(100% - '+el.offsetHeight+'px - 5em);';
}, },
onOccupantAdded: function (item) { onOccupantAdded: function (item) {
var view = this.get(item.get('id')); let view = this.get(item.get('id'));
if (!view) { if (!view) {
view = this.add( view = this.add(
item.get('id'), item.get('id'),
...@@ -2232,8 +2225,8 @@ ...@@ -2232,8 +2225,8 @@
}, },
parsePresence: function (pres) { parsePresence: function (pres) {
var id = Strophe.getResourceFromJid(pres.getAttribute("from")); const id = Strophe.getResourceFromJid(pres.getAttribute("from"));
var data = { const data = {
nick: id, nick: id,
type: pres.getAttribute("type"), type: pres.getAttribute("type"),
states: [] states: []
...@@ -2276,7 +2269,7 @@ ...@@ -2276,7 +2269,7 @@
* otherwise we use the nick. We don't always have both, * otherwise we use the nick. We don't always have both,
* but should have at least one or the other. * but should have at least one or the other.
*/ */
var jid = Strophe.getBareJidFromJid(data.jid); const jid = Strophe.getBareJidFromJid(data.jid);
if (jid !== null) { if (jid !== null) {
return this.model.where({'jid': jid}).pop(); return this.model.where({'jid': jid}).pop();
} else { } else {
...@@ -2291,31 +2284,29 @@ ...@@ -2291,31 +2284,29 @@
* Parameters: * Parameters:
* (XMLElement) pres: The presence stanza * (XMLElement) pres: The presence stanza
*/ */
var data = this.parsePresence(pres); const data = this.parsePresence(pres);
if (data.type === 'error') { if (data.type === 'error') {
return true; return true;
} }
var occupant = this.findOccupant(data); const occupant = this.findOccupant(data);
switch (data.type) { if (data.type === 'unavailable') {
case 'unavailable': if (occupant) { occupant.destroy(); }
if (occupant) { occupant.destroy(); } } else {
break; const jid = Strophe.getBareJidFromJid(data.jid);
default: const attributes = _.extend(data, {
var jid = Strophe.getBareJidFromJid(data.jid); 'jid': jid ? jid : undefined,
var attributes = _.extend(data, { 'resource': data.jid ? Strophe.getResourceFromJid(data.jid) : undefined
'jid': jid ? jid : undefined, });
'resource': data.jid ? Strophe.getResourceFromJid(data.jid) : undefined if (occupant) {
}); occupant.save(attributes);
if (occupant) { } else {
occupant.save(attributes); this.model.create(attributes);
} else { }
this.model.create(attributes);
}
} }
}, },
promptForInvite: function (suggestion) { promptForInvite: function (suggestion) {
var reason = prompt( const reason = prompt(
__(___('You are about to invite %1$s to the chat room "%2$s". '), suggestion.text.label, this.model.get('id')) + __(___('You are about to invite %1$s to the chat room "%2$s". '), suggestion.text.label, this.model.get('id')) +
__("You may optionally include a message, explaining the reason for the invitation.") __("You may optionally include a message, explaining the reason for the invitation.")
); );
...@@ -2327,7 +2318,7 @@ ...@@ -2327,7 +2318,7 @@
inviteFormSubmitted: function (evt) { inviteFormSubmitted: function (evt) {
evt.preventDefault(); evt.preventDefault();
var el = evt.target.querySelector('input.invited-contact'); const el = evt.target.querySelector('input.invited-contact');
this.promptForInvite({ this.promptForInvite({
'target': el, 'target': el,
'text': { 'text': {
...@@ -2344,17 +2335,17 @@ ...@@ -2344,17 +2335,17 @@
}, },
initInviteWidget: function () { initInviteWidget: function () {
var form = this.el.querySelector('form.room-invite'); const form = this.el.querySelector('form.room-invite');
if (_.isNull(form)) { if (_.isNull(form)) {
return; return;
} }
form.addEventListener('submit', this.inviteFormSubmitted.bind(this)); form.addEventListener('submit', this.inviteFormSubmitted.bind(this));
var el = this.el.querySelector('input.invited-contact'); const el = this.el.querySelector('input.invited-contact');
var list = _converse.roster.map(function (item) { const list = _converse.roster.map(function (item) {
var label = item.get('fullname') || item.get('jid'); const label = item.get('fullname') || item.get('jid');
return {'label': label, 'value':item.get('jid')}; return {'label': label, 'value':item.get('jid')};
}); });
var awesomplete = new Awesomplete(el, { const awesomplete = new Awesomplete(el, {
'minChars': 1, 'minChars': 1,
'list': list 'list': list
}); });
...@@ -2401,7 +2392,7 @@ ...@@ -2401,7 +2392,7 @@
'label_show_rooms': __('Show rooms') 'label_show_rooms': __('Show rooms')
}); });
this.renderTab(); this.renderTab();
var controlbox = _converse.chatboxes.get('controlbox'); const controlbox = _converse.chatboxes.get('controlbox');
if (controlbox.get('active-panel') !== ROOMS_PANEL_ID) { if (controlbox.get('active-panel') !== ROOMS_PANEL_ID) {
this.el.classList.add('hidden'); this.el.classList.add('hidden');
} }
...@@ -2409,8 +2400,8 @@ ...@@ -2409,8 +2400,8 @@
}, },
renderTab: function () { renderTab: function () {
var controlbox = _converse.chatboxes.get('controlbox'); const controlbox = _converse.chatboxes.get('controlbox');
var chatrooms = fp.filter( const chatrooms = fp.filter(
_.partial(utils.isOfType, CHATROOMS_TYPE), _.partial(utils.isOfType, CHATROOMS_TYPE),
_converse.chatboxes.models _converse.chatboxes.models
); );
...@@ -2429,7 +2420,7 @@ ...@@ -2429,7 +2420,7 @@
}, },
onDomainChange: function (model) { onDomainChange: function (model) {
var $server = this.$el.find('input.new-chatroom-server'); const $server = this.$el.find('input.new-chatroom-server');
$server.val(model.get('muc_domain')); $server.val(model.get('muc_domain'));
if (_converse.auto_list_rooms) { if (_converse.auto_list_rooms) {
this.updateRoomsList(); this.updateRoomsList();
...@@ -2437,12 +2428,12 @@ ...@@ -2437,12 +2428,12 @@
}, },
onNickChange: function (model) { onNickChange: function (model) {
var $nick = this.$el.find('input.new-chatroom-nick'); const $nick = this.$el.find('input.new-chatroom-nick');
$nick.val(model.get('nick')); $nick.val(model.get('nick'));
}, },
informNoRoomsFound: function () { informNoRoomsFound: function () {
var $available_chatrooms = this.$el.find('#available-chatrooms'); const $available_chatrooms = this.$el.find('#available-chatrooms');
// For translators: %1$s is a variable and will be replaced with the XMPP server name // For translators: %1$s is a variable and will be replaced with the XMPP server name
$available_chatrooms.html('<dt>'+__('No rooms on %1$s',this.model.get('muc_domain'))+'</dt>'); $available_chatrooms.html('<dt>'+__('No rooms on %1$s',this.model.get('muc_domain'))+'</dt>');
$('input#show-rooms').show().siblings('span.spinner').remove(); $('input#show-rooms').show().siblings('span.spinner').remove();
...@@ -2495,9 +2486,9 @@ ...@@ -2495,9 +2486,9 @@
}, },
showRooms: function () { showRooms: function () {
var $available_chatrooms = this.$el.find('#available-chatrooms'); const $available_chatrooms = this.$el.find('#available-chatrooms');
var $server = this.$el.find('input.new-chatroom-server'); const $server = this.$el.find('input.new-chatroom-server');
var server = $server.val(); const server = $server.val();
if (!server) { if (!server) {
$server.addClass('error'); $server.addClass('error');
return; return;
...@@ -2519,7 +2510,7 @@ ...@@ -2519,7 +2510,7 @@
* (XMLElement) stanza: The IQ stanza containing the room * (XMLElement) stanza: The IQ stanza containing the room
* info. * info.
*/ */
var $stanza = $(stanza); const $stanza = $(stanza);
// All MUC features found here: http://xmpp.org/registrar/disco-features.html // All MUC features found here: http://xmpp.org/registrar/disco-features.html
$(el).find('span.spinner').replaceWith( $(el).find('span.spinner').replaceWith(
tpl_room_description({ tpl_room_description({
...@@ -2559,7 +2550,7 @@ ...@@ -2559,7 +2550,7 @@
toggleRoomInfo: function (ev) { toggleRoomInfo: function (ev) {
/* Show/hide extra information about a room in the listing. /* Show/hide extra information about a room in the listing.
*/ */
var target = ev.target, const target = ev.target,
$parent = $(target).parent('dd'), $parent = $(target).parent('dd'),
$div = $parent.find('div.room-info'); $div = $parent.find('div.room-info');
if ($div.length) { if ($div.length) {
...@@ -2579,9 +2570,9 @@ ...@@ -2579,9 +2570,9 @@
name = $(ev.target).text(); name = $(ev.target).text();
jid = $(ev.target).attr('data-room-jid'); jid = $(ev.target).attr('data-room-jid');
} else { } else {
$name = this.$el.find('input.new-chatroom-name'); const $name = this.$el.find('input.new-chatroom-name');
$server= this.$el.find('input.new-chatroom-server'); const $server= this.$el.find('input.new-chatroom-server');
server = $server.val(); const server = $server.val();
name = $name.val().trim(); name = $name.val().trim();
$name.val(''); // Clear the input $name.val(''); // Clear the input
if (name && server) { if (name && server) {
...@@ -2669,7 +2660,7 @@ ...@@ -2669,7 +2660,7 @@
}; };
if (_converse.allow_muc_invitations) { if (_converse.allow_muc_invitations) {
var registerDirectInvitationHandler = function () { const registerDirectInvitationHandler = function () {
_converse.connection.addHandler( _converse.connection.addHandler(
function (message) { function (message) {
_converse.onDirectMUCInvitation(message); _converse.onDirectMUCInvitation(message);
...@@ -2680,7 +2671,7 @@ ...@@ -2680,7 +2671,7 @@
_converse.on('reconnected', registerDirectInvitationHandler); _converse.on('reconnected', registerDirectInvitationHandler);
} }
var autoJoinRooms = function () { function autoJoinRooms () {
/* Automatically join chat rooms, based on the /* Automatically join chat rooms, based on the
* "auto_join_rooms" configuration setting, which is an array * "auto_join_rooms" configuration setting, which is an array
* of strings (room JIDs) or objects (with room JID and other * of strings (room JIDs) or objects (with room JID and other
...@@ -2697,7 +2688,7 @@ ...@@ -2697,7 +2688,7 @@
Strophe.LogLevel.ERROR); Strophe.LogLevel.ERROR);
} }
}); });
}; }
_converse.on('chatBoxesFetched', autoJoinRooms); _converse.on('chatBoxesFetched', autoJoinRooms);
_converse.getChatRoom = function (jid, attrs, fetcher) { _converse.getChatRoom = function (jid, attrs, fetcher) {
...@@ -2724,11 +2715,11 @@ ...@@ -2724,11 +2715,11 @@
} }
}); });
} else if (_.isString(jids)) { } else if (_.isString(jids)) {
var view = _converse.chatboxviews.get(jids); const view = _converse.chatboxviews.get(jids);
if (view) { view.close(); } if (view) { view.close(); }
} else { } else {
_.each(jids, function (jid) { _.each(jids, function (jid) {
var view = _converse.chatboxviews.get(jid); const view = _converse.chatboxviews.get(jid);
if (view) { view.close(); } if (view) { view.close(); }
}); });
} }
...@@ -2759,7 +2750,7 @@ ...@@ -2759,7 +2750,7 @@
attrs = {}; attrs = {};
} }
if (_.isUndefined(jids)) { if (_.isUndefined(jids)) {
var result = []; const result = [];
_converse.chatboxes.each(function (chatbox) { _converse.chatboxes.each(function (chatbox) {
if (chatbox.get('type') === CHATROOMS_TYPE) { if (chatbox.get('type') === CHATROOMS_TYPE) {
result.push(_converse.getViewForChatBox(chatbox)); result.push(_converse.getViewForChatBox(chatbox));
...@@ -2767,7 +2758,7 @@ ...@@ -2767,7 +2758,7 @@
}); });
return result; return result;
} }
var fetcher = _.partial(_converse.chatboxviews.getChatBox.bind(_converse.chatboxviews), _, create); const fetcher = _.partial(_converse.chatboxviews.getChatBox.bind(_converse.chatboxviews), _, create);
if (!attrs.nick) { if (!attrs.nick) {
attrs.nick = Strophe.getNodeFromJid(_converse.bare_jid); attrs.nick = Strophe.getNodeFromJid(_converse.bare_jid);
} }
...@@ -2779,7 +2770,7 @@ ...@@ -2779,7 +2770,7 @@
} }
}); });
var reconnectToChatRooms = function () { function reconnectToChatRooms () {
/* Upon a reconnection event from converse, join again /* Upon a reconnection event from converse, join again
* all the open chat rooms. * all the open chat rooms.
*/ */
...@@ -2791,10 +2782,10 @@ ...@@ -2791,10 +2782,10 @@
view.fetchMessages(); view.fetchMessages();
} }
}); });
}; }
_converse.on('reconnected', reconnectToChatRooms); _converse.on('reconnected', reconnectToChatRooms);
var disconnectChatRooms = function () { function disconnectChatRooms () {
/* When disconnecting, or reconnecting, mark all chat rooms as /* When disconnecting, or reconnecting, mark all chat rooms as
* disconnected, so that they will be properly entered again * disconnected, so that they will be properly entered again
* when fetched from session storage. * when fetched from session storage.
...@@ -2804,7 +2795,7 @@ ...@@ -2804,7 +2795,7 @@
model.save('connection_status', ROOMSTATUS.DISCONNECTED); model.save('connection_status', ROOMSTATUS.DISCONNECTED);
} }
}); });
}; }
_converse.on('reconnecting', disconnectChatRooms); _converse.on('reconnecting', disconnectChatRooms);
_converse.on('disconnecting', disconnectChatRooms); _converse.on('disconnecting', disconnectChatRooms);
} }
......
...@@ -10,7 +10,7 @@ ...@@ -10,7 +10,7 @@
define(["converse-core"], factory); define(["converse-core"], factory);
}(this, function (converse) { }(this, function (converse) {
"use strict"; "use strict";
var utils = converse.env.utils, const utils = converse.env.utils,
Strophe = converse.env.Strophe, Strophe = converse.env.Strophe,
_ = converse.env._; _ = converse.env._;
...@@ -20,11 +20,11 @@ ...@@ -20,11 +20,11 @@
/* The initialize function gets called as soon as the plugin is /* The initialize function gets called as soon as the plugin is
* loaded by converse.js's plugin machinery. * loaded by converse.js's plugin machinery.
*/ */
var _converse = this._converse; const _converse = this._converse;
// For translations // For translations
var __ = _converse.__; const __ = _converse.__;
var ___ = _converse.___; const ___ = _converse.___;
_converse.supports_html5_notification = "Notification" in window; _converse.supports_html5_notification = "Notification" in window;
......
...@@ -19,29 +19,29 @@ ...@@ -19,29 +19,29 @@
"use strict"; "use strict";
// Strophe methods for building stanzas // Strophe methods for building stanzas
var Strophe = converse.env.Strophe, const Strophe = converse.env.Strophe,
utils = converse.env.utils, utils = converse.env.utils,
b64_sha1 = converse.env.b64_sha1; b64_sha1 = converse.env.b64_sha1;
// Other necessary globals // Other necessary globals
var $ = converse.env.jQuery, const $ = converse.env.jQuery,
_ = converse.env._; _ = converse.env._;
var HAS_CSPRNG = ((!_.isUndefined(crypto)) && const HAS_CSPRNG = ((!_.isUndefined(crypto)) &&
((_.isFunction(crypto.randomBytes)) || (_.isFunction(crypto.getRandomValues)) ((_.isFunction(crypto.randomBytes)) || (_.isFunction(crypto.getRandomValues))
)); ));
var HAS_CRYPTO = HAS_CSPRNG && ( const HAS_CRYPTO = HAS_CSPRNG && (
(!_.isUndefined(otr.OTR)) && (!_.isUndefined(otr.OTR)) &&
(!_.isUndefined(otr.DSA)) (!_.isUndefined(otr.DSA))
); );
var UNENCRYPTED = 0; const UNENCRYPTED = 0;
var UNVERIFIED= 1; const UNVERIFIED= 1;
var VERIFIED= 2; const VERIFIED= 2;
var FINISHED = 3; const FINISHED = 3;
var OTR_TRANSLATED_MAPPING = {}; // Populated in initialize const OTR_TRANSLATED_MAPPING = {}; // Populated in initialize
var OTR_CLASS_MAPPING = {}; const OTR_CLASS_MAPPING = {};
OTR_CLASS_MAPPING[UNENCRYPTED] = 'unencrypted'; OTR_CLASS_MAPPING[UNENCRYPTED] = 'unencrypted';
OTR_CLASS_MAPPING[UNVERIFIED] = 'unverified'; OTR_CLASS_MAPPING[UNVERIFIED] = 'unverified';
OTR_CLASS_MAPPING[VERIFIED] = 'verified'; OTR_CLASS_MAPPING[VERIFIED] = 'verified';
...@@ -132,7 +132,7 @@ ...@@ -132,7 +132,7 @@
encrypted_key = this.get('otr_priv_key'); encrypted_key = this.get('otr_priv_key');
if (_.isString(encrypted_key)) { if (_.isString(encrypted_key)) {
instance_tag = this.get('otr_instance_tag'); instance_tag = this.get('otr_instance_tag');
saved_key = otr.DSA.parsePrivate(encrypted_key) saved_key = otr.DSA.parsePrivate(encrypted_key);
if (saved_key && instance_tag) { if (saved_key && instance_tag) {
this.trigger('showHelpMessages', [__('Re-establishing encrypted session')]); this.trigger('showHelpMessages', [__('Re-establishing encrypted session')]);
callback({ callback({
......
...@@ -14,7 +14,7 @@ ...@@ -14,7 +14,7 @@
}(this, function (converse) { }(this, function (converse) {
"use strict"; "use strict";
// Strophe methods for building stanzas // Strophe methods for building stanzas
var Strophe = converse.env.Strophe, const Strophe = converse.env.Strophe,
_ = converse.env._; _ = converse.env._;
converse.plugins.add('converse-ping', { converse.plugins.add('converse-ping', {
...@@ -23,7 +23,7 @@ ...@@ -23,7 +23,7 @@
/* The initialize function gets called as soon as the plugin is /* The initialize function gets called as soon as the plugin is
* loaded by converse.js's plugin machinery. * loaded by converse.js's plugin machinery.
*/ */
var _converse = this._converse; const _converse = this._converse;
_converse.api.settings.update({ _converse.api.settings.update({
ping_interval: 180 //in seconds ping_interval: 180 //in seconds
......
...@@ -32,12 +32,12 @@ ...@@ -32,12 +32,12 @@
"use strict"; "use strict";
// Strophe methods for building stanzas // Strophe methods for building stanzas
var Strophe = converse.env.Strophe, const Strophe = converse.env.Strophe,
Backbone = converse.env.Backbone, Backbone = converse.env.Backbone,
utils = converse.env.utils, utils = converse.env.utils,
$iq = converse.env.$iq; $iq = converse.env.$iq;
// Other necessary globals // Other necessary globals
var $ = converse.env.jQuery, const $ = converse.env.jQuery,
_ = converse.env._; _ = converse.env._;
// Add Strophe Namespaces // Add Strophe Namespaces
......
...@@ -70,7 +70,7 @@ ...@@ -70,7 +70,7 @@
'toggle_state': this.list_model.get('toggle-state'), 'toggle_state': this.list_model.get('toggle-state'),
'desc_rooms': __('Click to toggle the rooms list'), 'desc_rooms': __('Click to toggle the rooms list'),
'label_rooms': __('Open Rooms') 'label_rooms': __('Open Rooms')
}) });
this.hide(); this.hide();
if (this.list_model.get('toggle-state') !== _converse.OPENED) { if (this.list_model.get('toggle-state') !== _converse.OPENED) {
this.$('.open-rooms-list').hide(); this.$('.open-rooms-list').hide();
...@@ -111,7 +111,7 @@ ...@@ -111,7 +111,7 @@
} }
this.removeRoomsListElement(item); this.removeRoomsListElement(item);
var name, bookmark var name, bookmark;
if (item.get('bookmarked')) { if (item.get('bookmarked')) {
bookmark = _.head(_converse.bookmarksview.model.where({'jid': item.get('jid')})); bookmark = _.head(_converse.bookmarksview.model.where({'jid': item.get('jid')}));
name = bookmark.get('name'); name = bookmark.get('name');
......
...@@ -590,7 +590,7 @@ ...@@ -590,7 +590,7 @@
)); ));
} else if (subscription === 'both' || subscription === 'to') { } else if (subscription === 'both' || subscription === 'to') {
this.el.classList.add('current-xmpp-contact'); this.el.classList.add('current-xmpp-contact');
this.el.classList.remove(_.without(['both', 'to'], subscription)[0]) this.el.classList.remove(_.without(['both', 'to'], subscription)[0]);
this.el.classList.add(subscription); this.el.classList.add(subscription);
this.renderRosterItem(item); this.renderRosterItem(item);
} }
......
...@@ -72,9 +72,9 @@ ...@@ -72,9 +72,9 @@
* time. So before opening a chat, we make sure all other * time. So before opening a chat, we make sure all other
* chats are hidden. * chats are hidden.
*/ */
var _converse = this.__super__._converse; const _converse = this.__super__._converse;
var chatbox = this.getChatBox(attrs, true); const chatbox = this.getChatBox(attrs, true);
var hidden = _.isUndefined(attrs.hidden) ? chatbox.get('hidden') : attrs.hidden; const hidden = _.isUndefined(attrs.hidden) ? chatbox.get('hidden') : attrs.hidden;
if ((force || !hidden) && _converse.connection.authenticated) { if ((force || !hidden) && _converse.connection.authenticated) {
_.each(_converse.chatboxviews.xget(chatbox.get('id')), hideChat); _.each(_converse.chatboxviews.xget(chatbox.get('id')), hideChat);
chatbox.save({'hidden': false}); chatbox.save({'hidden': false});
......
...@@ -10,7 +10,7 @@ ...@@ -10,7 +10,7 @@
define(["converse-core", "strophe.vcard"], factory); define(["converse-core", "strophe.vcard"], factory);
}(this, function (converse) { }(this, function (converse) {
"use strict"; "use strict";
var Strophe = converse.env.Strophe, const Strophe = converse.env.Strophe,
$ = converse.env.jQuery, $ = converse.env.jQuery,
_ = converse.env._, _ = converse.env._,
moment = converse.env.moment; moment = converse.env.moment;
...@@ -26,7 +26,7 @@ ...@@ -26,7 +26,7 @@
Features: { Features: {
addClientFeatures: function () { addClientFeatures: function () {
var _converse = this.__super__._converse; const _converse = this.__super__._converse;
this.__super__.addClientFeatures.apply(this, arguments); this.__super__.addClientFeatures.apply(this, arguments);
if (_converse.use_vcards) { if (_converse.use_vcards) {
_converse.connection.disco.addFeature(Strophe.NS.VCARD); _converse.connection.disco.addFeature(Strophe.NS.VCARD);
...@@ -36,8 +36,8 @@ ...@@ -36,8 +36,8 @@
RosterContacts: { RosterContacts: {
createRequestingContact: function (presence) { createRequestingContact: function (presence) {
var _converse = this.__super__._converse; const _converse = this.__super__._converse;
var bare_jid = Strophe.getBareJidFromJid(presence.getAttribute('from')); const bare_jid = Strophe.getBareJidFromJid(presence.getAttribute('from'));
_converse.getVCard( _converse.getVCard(
bare_jid, bare_jid,
_.partial(_converse.createRequestingContactFromVCard, presence), _.partial(_converse.createRequestingContactFromVCard, presence),
...@@ -58,15 +58,15 @@ ...@@ -58,15 +58,15 @@
/* The initialize function gets called as soon as the plugin is /* The initialize function gets called as soon as the plugin is
* loaded by converse.js's plugin machinery. * loaded by converse.js's plugin machinery.
*/ */
var _converse = this._converse; const _converse = this._converse;
_converse.api.settings.update({ _converse.api.settings.update({
use_vcards: true, use_vcards: true,
}); });
_converse.createRequestingContactFromVCard = function (presence, iq, jid, fullname, img, img_type, url) { _converse.createRequestingContactFromVCard = function (presence, iq, jid, fullname, img, img_type, url) {
var bare_jid = Strophe.getBareJidFromJid(jid); const bare_jid = Strophe.getBareJidFromJid(jid);
var nick = $(presence).children('nick[xmlns="'+Strophe.NS.NICK+'"]').text(); const nick = $(presence).children('nick[xmlns="'+Strophe.NS.NICK+'"]').text();
var user_data = { const user_data = {
jid: bare_jid, jid: bare_jid,
subscription: 'none', subscription: 'none',
ask: null, ask: null,
...@@ -82,7 +82,7 @@ ...@@ -82,7 +82,7 @@
}; };
_converse.onVCardError = function (jid, iq, errback) { _converse.onVCardError = function (jid, iq, errback) {
var contact = _converse.roster.get(jid); const contact = _converse.roster.get(jid);
if (contact) { if (contact) {
contact.save({ 'vcard_updated': moment().format() }); contact.save({ 'vcard_updated': moment().format() });
} }
......
...@@ -63,7 +63,7 @@ ...@@ -63,7 +63,7 @@
var div = document.createElement('div'); var div = document.createElement('div');
div.innerHTML = htmlEscapedText; div.innerHTML = htmlEscapedText;
return div.innerText; return div.innerText;
} };
var isImage = function (url) { var isImage = function (url) {
var deferred = new $.Deferred(); var deferred = new $.Deferred();
...@@ -467,13 +467,13 @@ ...@@ -467,13 +467,13 @@
utils.isConverseLocale = function (locale) { utils.isConverseLocale = function (locale) {
if (!_.isString(locale)) { return false; } if (!_.isString(locale)) { return false; }
return _.includes(_.keys(locales || {}), locale) return _.includes(_.keys(locales || {}), locale);
}; };
utils.isMomentLocale = function (locale) { utils.isMomentLocale = function (locale) {
if (!_.isString(locale)) { return false; } if (!_.isString(locale)) { return false; }
return moment.locale() !== moment.locale(locale); return moment.locale() !== moment.locale(locale);
} };
utils.getLocale = function (preferred_locale, isSupportedByLibrary) { utils.getLocale = function (preferred_locale, isSupportedByLibrary) {
if (_.isString(preferred_locale)) { if (_.isString(preferred_locale)) {
...@@ -492,7 +492,7 @@ ...@@ -492,7 +492,7 @@
utils.isOfType = function (type, item) { utils.isOfType = function (type, item) {
return item.get('type') == type; return item.get('type') == type;
} };
utils.isInstance = function (type, item) { utils.isInstance = function (type, item) {
return item instanceof type; return item instanceof type;
...@@ -520,7 +520,7 @@ ...@@ -520,7 +520,7 @@
} }
element.appendChild(frag); // Now, append all elements at once element.appendChild(frag); // Now, append all elements at once
frag = tmp = null; frag = tmp = null;
} };
utils.isPersistableModel = function (model) { utils.isPersistableModel = function (model) {
return model.collection && model.collection.browserStorage; return model.collection && model.collection.browserStorage;
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment