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