-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathui.js
788 lines (725 loc) · 25.8 KB
/
ui.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
/**
* ui.js contains all functions that alter the user interface.
*
* @author Christoph Burschka <[email protected]>
* @year 2014
* @license GPL3+
*/
var ui = {
userLinks: {},
sortedNicks: [],
dom: null,
userStatus: {},
messages: [],
colorPicker: null,
autoScroll: true,
sounds: {},
urlFragment: window.location.hash,
/**
* Initialize the module:
* - store references to frequently accessed DOM elements.
* - build dynamically generated elements, and set form values.
* - initialize event listeners.
*/
init: function() {
this.dom = {
loginContainer: $('#loginContainer'),
roomContainer: $('#roomContainer'),
colorCodesContainer: $('#colorCodesContainer'),
inputField: $('#inputField'),
content: $('#content'),
chatList: $('#chatList'),
onlineList: $('#onlineList'),
roomSelection: $('#roomSelection'),
statusIcon: $('#statusIcon'),
autoScrollIcon: $('#autoScrollIcon'),
messageLengthCounter: $('#messageLengthCounter'),
menu: {
help: $('#helpContainer'),
onlineList: $('#onlineListContainer'),
settings: $('#settingsContainer'),
},
emoticonSidebarContainer: $('#emoticonSidebarContainer'),
emoticonTrayContainer: $('#emoticonTrayContainer'),
styleSheets: $('link.alternate-style'),
};
this.title = $(document).attr('title');
this.loadSounds();
this.initializePage();
this.initializeEvents();
},
/**
* Load the sound files.
*/
loadSounds: function() {
for (var i in config.sounds) {
var sound = config.sounds[i];
this.sounds[sound] = new buzz.sound(config.soundURL + sound, {formats: ['ogg', 'mp3'], preload: true});
}
},
/**
* Create dynamic page elements.
*/
initializePage: function() {
this.setStyle(config.settings.activeStyle);
// Build and fill the emoticon containers.
var bars = config.ui.emoticonSidebars
for (var set in bars) {
this.dom.menu['emoticon-' + set] = $(
'<div id="emoticon-' + set + '" class="menuContainer emoticon-sidebar box">'
+ '<h3>' + bars[set].title + '</h3>'
+ '<div id="emoticonsList-' + set + '" class="emoticon-list-sidebar" dir="ltr"></div></div>'
).appendTo(this.dom.emoticonSidebarContainer);
$(
'<button class="tray toggleMenu" id="emoticon-' + set + 'Button" title="' + bars[set].title + '">' + bars[set].title + '</button>'
).css('background-image', 'url("' + config.markup.emoticons[set].baseURL + bars[set].icon + '")')
.appendTo(ui.dom.emoticonTrayContainer);
}
for (var set in config.markup.emoticons) {
var html = '';
for (var code in config.markup.emoticons[set].codes) {
html += '<a href="javascript:void(\'' + code.replace('\'', '\\\'', 'g')
+ '\');" class="insert-text" title="'
+ code + '">' + '<img src="' + config.markup.emoticons[set].baseURL
+ config.markup.emoticons[set].codes[code] + '" alt="'
+ code + '" /></a>';
}
$('#emoticonsList-' + set).html(html);
}
// Build the color palette picker.
var html = '';
for (var color in config.markup.colorCodes) {
var code = config.markup.colorCodes[color]
html += '<a href="javascript:void(\'' + code + '\');" title="' + code
+ '" class="colorCode" style="background-color:' + code + '"></a>';
}
$('#colorCodesContainer').html(html);
var sounds = [new Option('---', '')];
for (var sound in this.sounds) sounds.push(new Option(sound, sound));
$('#settingsContainer select.soundSelect').html(sounds);
// Set the form values.
$('#settingsContainer .settings').val(function() {
return chat.getSetting(this.id.substring('settings-'.length));
});
this.setTextColorPicker(config.settings.textColor);
$('#settingsContainer input.settings[type=checkbox]').prop('checked', function() {
return chat.getSetting(this.id.substring('settings-'.length));
});
$('#settings-notifications\\.triggers').val(config.settings.notifications.triggers.join(', '));
// Open the last active sidebar.
if (!this.dom.menu[config.settings.activeMenu]) {
config.settings.activeMenu = 'onlineList';
}
this.toggleMenu(config.settings.activeMenu, true);
// Set the volume.
chat.setAudioVolume(config.settings.notifications.soundVolume);
$('#audioButton').toggleClass('off', !config.settings.notifications.soundEnabled);
},
/**
* Initialize the event listeners.
*/
initializeEvents: function() {
// Inserting BBCode tags.
var insertBBCode = function(tag, arg) {
arg = arg ? '=' + arg : '';
var v = ['[' + tag + arg + ']', '[/' + tag + ']'];
chat.insertText(v);
return true;
};
// The input field listens for <return>, <up>, <down> and BBCodes.
this.dom.inputField.on({
keypress: this.onKeyMap({
// 9: <tab>
9: function() { return ui.autocomplete(); },
// 13: <return> (unless shift is down)
13: function(e,x) {
if (!e.shiftKey) {
chat.executeInput($(x).val())
$(x).val('');
return true;
}
},
// 38: <arrow-up> (if the field is empty, or ctrl is down)
38: function(e,x) { return (e.ctrlKey || !$(x).val()) && chat.historyUp(); },
// 40: <arrow-down> (if ctrl is down)
40: function(e) { return e.ctrlKey && chat.historyDown(); },
// 98, 105, 117, 117: b,i,s,u
98: function(e) { return e.ctrlKey && insertBBCode('b'); },
105: function(e) { return e.ctrlKey && insertBBCode('i'); },
115: function(e) { return e.ctrlKey && insertBBCode('s'); },
117: function(e) { return e.ctrlKey && insertBBCode('u'); },
}),
// after any keystroke, update the message length counter.
keyup: function() { ui.updateMessageLengthCounter(); }
});
// The room selection menu listens for changes.
this.dom.roomSelection.change(function() {
if (this.value) chat.commands.join(this.value);
else chat.commands.part();
});
$(window).on('hashchange', function() {
if (ui.urlFragment != window.location.hash) {
ui.urlFragment = window.location.hash;
if (ui.urlFragment) chat.commands.join(ui.urlFragment.substring(1));
else chat.commands.part();
}
});
// Log in with the button or pressing enter.
$('#fakeLoginForm').submit(function(e) {
chat.commands.connect({user: $('#loginUser').val(), pass: $('#loginPass').val()});
e.preventDefault();
});
$('#trayContainer button.toggleMenu').click(function() {
ui.toggleMenu(this.id.substring(0, this.id.length - 'Button'.length));
});
// BBCode buttons.
$('.insert-text').click(function() { chat.insertText(this.title); });
$('.insert-bbcode').click(function() {
if ($(this).hasClass('insert-bbcode-arg'))
var arg = prompt('This BBCode tag requires an argument:', '');
insertBBCode(this.value.toLowerCase(), arg || '');
});
// Open the color tray.
$('#colorBBCode').click(function() {
ui.colorPicker = ui.colorPicker != 'bbcode' ? 'bbcode' : null;
ui.dom.colorCodesContainer[ui.colorPicker == 'bbcode' ? 'fadeIn' : 'fadeOut'](500);
});
this.mouseHold($('#textColor'), 500,
function() {
config.settings.fullColor = true;
$('#settings-textColor').click();
},
function() {
if (config.settings.fullColor && config.settings.textColor != '') {
$('#settings-textColor').click();
}
else {
ui.colorPicker = ui.colorPicker != 'setting' ? 'setting' : null;
ui.dom.colorCodesContainer[ui.colorPicker == 'setting' ? 'fadeIn' : 'fadeOut'](500);
}
}
);
// The color tray has two modes (setting and bbcode).
$('.colorCode').click(function() {
if (ui.colorPicker == 'bbcode') {
insertBBCode('color', this.title);
$('#colorBBCode').click();
}
else if (ui.colorPicker == 'setting') {
$('#textColor').mouseup();
config.settings.fullColor = false;
$('#settings-textColor').val(this.title).change();
}
});
// Clear the text color setting.
$('#textColorClear').click(function() {
config.settings.fullColor = false;
chat.setSetting('textColor', '');
ui.setTextColorPicker('');
});
$('#settings-textColor').change(function() {
ui.setTextColorPicker($(this).val())
});
// Listen for changes in the style menu.
$('#styleSelection').change(
function() { ui.setStyle($(this).val()); }
).val(config.settings.activeStyle);
// Instantly save changed settings in the cookie.
$('#settingsContainer .settings').change(function() {
var value = this.type == 'checkbox' ? this.checked : this.value;
chat.setSetting(this.id.substring('settings-'.length), value);
});
$('#settings-notifications\\.triggers').change(function() {
var value = this.value.split(/[\s,;]+/);
chat.setSetting(this.id.substring('settings-'.length), value);
});
// Attempt to maintain the scroll position when changing message heights.
var toggler = function(selector) {
// Find the message at the top of the viewport...
var i = ui.getMessageAt(ui.dom.chatList.prop('scrollTop'));
$(selector).toggle();
ui.updateHeights();
if (i) {
// ... and scroll to it again (snap to bottom if appropriate).
ui.dom.chatList.prop('scrollTop', ui.messages[i].offset);
ui.scrollDown();
}
}
$('#settings-markup\\.images').change(function() {
toggler('img.rescale, span.image-alt');
});
$('#settings-markup\\.emoticons').change(function() {
toggler('img.emoticon, span.emote-alt');
});
$('#settings-markup\\.colors').change(function() {
if (this.checked) visual.addColor(ui.dom.chatList);
else visual.removeColor(ui.dom.chatList);
ui.dom.inputField.css('color', this.checked && config.settings.textColor || '');
});
// Instantly apply sound volume.
$('.soundVolume').change(function() {
chat.setAudioVolume(this.value);
});
// /quit button.
$('#logoutButton').click(function() {
chat.commands.quit();
});
$('#audioButton').click(function() {
var audio = !config.settings.notifications.soundEnabled;
chat.setSetting('notifications.soundEnabled', audio);
$(this).toggleClass('off', !audio);
});
// scrolling up the chat list turns off auto-scrolling.
this.dom.chatList.scroll(function() {
ui.checkAutoScroll();
return true;
});
},
/**
* Instantly delete the entire message log.
*/
clearMessages: function() {
this.messages = [];
xmpp.historyEnd = {};
this.dom.chatList.html('');
},
/**
* Change the connection status:
* - unset the online list when leaving a room.
* - change the status icon.
* - toggle between login form and room selection menu.
*/
setStatus: function(status) {
// status options are: online, waiting, offline, prejoin.
if (status != 'online') ui.updateRoom('', {});
if (status == 'prejoin') status = 'online';
this.dom.statusIcon.attr('class', status).attr('title');
this.dom.loginContainer[status == 'online' ? 'fadeOut' : 'fadeIn'](500);
this.dom.roomContainer[status == 'online' ? 'fadeIn' : 'fadeOut'](500);
},
/**
* Change the active stylesheet.
*/
setStyle: function(style) {
config.settings.activeStyle = style;
this.dom.styleSheets.prop('disabled', 'disabled');
this.dom.styleSheets
.filter(function() { return this.title == style; })
.removeAttr('disabled');
chat.saveSettings();
},
/**
* This changes the value and appearance of the persistent color button.
*/
setTextColorPicker: function(color) {
$('#textColor')
.css('color', color || '')
.text(color || 'None')
.css('background-color', color ? visual.hex2rgba(color, 0.3) : '');
this.dom.inputField.css('color', config.settings.markup.colors && color || '');
if (color) $('#settings-textColor').val(color);
$('#textColorClear').css('display', color ? 'inline-block' : 'none');
},
/**
* Close the active sidebar and (if needed) open a different one.
*/
toggleMenu: function(newMenu, init) {
var speed = init ? 0 : 'slow';
var oldMenu = init ? null : config.settings.activeMenu;
if (oldMenu) this.dom.menu[oldMenu].animate({width: 'hide'}, 'slow');
var width = 20;
if (oldMenu != newMenu) {
var px = this.dom.menu[newMenu].css('width');
width += parseInt(px.substring(0,px.length-2)) + 8;
}
this.dom.chatList.animate({right : width + 'px'}, speed, function() {
var maxWidth = ui.dom.chatList.width() - 30;
var maxHeight = ui.dom.chatList.height() - 20;
$('img.rescale').each(function() { visual.rescale($(this), maxWidth, maxHeight); });
});
if (oldMenu != newMenu) {
this.dom.menu[newMenu].animate({width: 'show'}, speed);
config.settings.activeMenu = newMenu;
}
else config.settings.activeMenu = null;
chat.saveSettings();
},
/**
* Create an informational message.
* The first two arguments are passed straight to visual.formatText().
*
* @param {string} text The message to display (should be in strings.js)
* @param {Object} variables (optional) The variables to insert into the text.
* @param {string} classes (optional) Any classes (space-separated) to add.
* The common ones are verbose (message will be suppressed if
* verbosity is off) or error (message will be colored red).
*/
messageAddInfo: function(text, variables, classes) {
// If the second argument is a string, we skipped the variables.
if (!classes && typeof variables == 'string') {
classes = variables;
variables = false;
}
// Suppress verbose messages.
if (0 <= (' ' + classes + ' ').indexOf(' verbose ')) {
if (!config.settings.verbose) return;
}
else if (0 <= (' ' + classes + ' ').indexOf(' error ')) {
this.playSound('error');
}
text = visual.formatText(text, variables);
var message = visual.formatMessage({
body: text, type: 'local',
user: {nick: config.ui.chatBotName, role: 'bot', affiliation: 'bot'}
}, true);
message.html.find('.body').addClass(classes).addClass('message-bot');
this.messageAppend(message);
return message;
},
/**
* Append a delayed (room history) message.
*
* @param {Object} message. Must have user, time, room and body keys.
*/
messageDelayed: function(message) {
var entry = visual.formatMessage(message);
entry.html.addClass('delayed');
entry.html.find('.dateTime').after(
' <span class="log-room log-room-' + message.room.id + '">['
+ visual.format.room(message.room)
+ ']</span>'
);
this.messageInsert(entry);
},
/**
* Insert a (rendered) message at an arbitrary point (using the timestamp).
*
* This is only used for delayed messages.
*/
messageInsert: function(message) {
var c = this.messages.length;
if (message.timestamp < this.messages[0].timestamp) {
message.offset = 0;
this.messages[0].html.before(message.html);
this.messages = [message].concat(this.messages);
}
else for (var i = 1; i <= c; i++) {
if (i == this.messages.length || message.timestamp < this.messages[i].timestamp) {
message.offset = this.messages[i].offset;
this.messages[i-1].html.after(message.html);
this.messages.splice(i, 0, message);
break;
}
}
$(message.html).css({display:'block'});
this.updateHeights(i);
this.scrollDown();
},
/**
* Append a rendered message to the end of the chat list.
*/
messageAppend: function(message) {
message.offset = ui.dom.chatList.prop('scrollHeight');
this.messages.push(message);
this.dom.chatList.append(message.html);
$(message.html).fadeIn(function() {
ui.scrollDown();
});
this.scrollDown();
if (message.message.user.nick != xmpp.nick.current)
this.blinkTitle(message.message.user.nick);
},
/**
* Refresh the room selection menu.
*/
refreshRooms: function(rooms) {
var room = this.dom.roomSelection.val();
$('option', this.dom.roomSelection).remove();
var options = [new Option('---', '')];
for (var id in rooms) {
options.push(new Option(rooms[id].title, id));
}
this.dom.roomSelection.html(options).val(room);
},
/**
* Add a user to the online list.
*/
userAdd: function(user, animate) {
var userLink = $('<div class="row"><span class="user-roster">'
+ visual.format.user(user) + '</span></div>');
if (user.jid)
$('span.user-roster', userLink).addClass(visual.jidClass(user.jid));
if (user.nick == xmpp.nick.current) {
$('span.user-roster', userLink).addClass('user-self');
this.dom.onlineList.find('span.user-self').removeClass('user-self');
}
if (!this.userLinks[user.nick]) {
for (var i = 0; i < this.sortedNicks.length; i++)
if (user.nick.toLowerCase() < this.sortedNicks[i].toLowerCase())
break;
if (i < this.sortedNicks.length)
userLink.insertBefore(this.userLinks[this.sortedNicks[i]]);
else
userLink.appendTo(this.dom.onlineList);
this.sortedNicks.splice(i, 0, user.nick);
if (animate) userLink.slideDown(1000);
}
else userLink.replaceAll(this.userLinks[user.nick])
userLink.css('display', 'block');
this.userLinks[user.nick] = userLink;
},
/**
* Remove a user from the online list.
*/
userRemove: function(user) {
if (this.userLinks[user.nick]) {
this.userLinks[user.nick].slideUp(1000).remove();
for (var i = 0; i < this.sortedNicks.length; i++) {
if (this.sortedNicks[i] == user.nick) {
this.sortedNicks.splice(i, 1);
break;
}
}
delete this.userLinks[user.nick];
}
},
/**
* Update the current URL fragment.
*/
updateFragment: function(room) {
ui.urlFragment = '#' + (room || '');
window.location.hash = ui.urlFragment;
},
/**
* Remove the online list with a new roster, and set the room selection menu.
*/
updateRoom: function(room, roster) {
this.title = (room ? xmpp.room.available[room].title + ' - ' : '') + config.ui.title;
$(document).attr('title', this.title);
var self = this;
this.dom.roomSelection.val(room);
// If no roster is given, only update the menu.
if (!roster) return;
this.dom.onlineList.slideUp(function() {
$(this).html('');
self.userLinks = {};
self.userStatus = {};
self.sortedNicks = [];
for (var nick in roster) {
self.userAdd(roster[nick], false);
}
$(this).slideDown();
});
},
/**
* Recalculate the vertical positions of all messages.
*
* @start (optional) the first offset to recalculate.
*/
updateHeights: function(start) {
var offset = ui.messages[start-1] ? ui.messages[start-1].offset : 0;
for (var i = start || 1; i < ui.messages.length; i++) {
offset += ui.messages[i].html.height();
ui.messages[i].offset = offset;
}
},
/**
* Find the message at a given offset in the history via binary search.
*
* @return the index of the first message starting after the offset.
*/
getMessageAt: function(offset) {
var a = 0;
var b = ui.messages.length - 1;
if (b < 0) return null;
while (a + 1 < b) {
var c = (a + b) / 2 | 0;
if (ui.messages[c].offset < offset) a = c;
else b = c;
}
return b;
},
/**
* Helper function: Route a keystroke to a callback function.
*
* @param {Object} callbacks. Functions for each keycode to listen for.
* Should return true if the event should be terminated.
* @return true if the event should be terminated.
*/
onKeyMap: function(callbacks) {
return function(e) {
var c = e.which || e.keyCode;
if (callbacks[c] && callbacks[c](e, this)) {
try {
e.preventDefault();
} catch(ex) {
e.returnValue = false;
}
return false;
}
return true;
}
},
/**
* Recalculate the input field length, and update the counter.
* When a maximum length is set, count down to it.
*/
updateMessageLengthCounter: function() {
var length = this.dom.inputField.val().length;
if (config.ui.maxMessageLength) {
var content = (config.ui.maxMessageLength - length);
this.dom.messageLengthCounter.css('color', content < 0 ? 'red' : '');
this.dom.messageLengthCounter.text(content);
}
else this.dom.messageLengthCounter.text(this.dom.inputField.val().length);
},
/**
* Scroll to the bottom of the chat list if autoscrolling is enabled.
*/
scrollDown: function() {
// Only autoscroll if we are at the bottom.
if(this.autoScroll) {
this.autoScrolled = true;
this.dom.chatList[0].scrollTop = this.dom.chatList[0].scrollHeight;
this.autoScrolled = false;
}
},
/**
* Recalculate auto-scrolling mode: If the user initiated the scroll event
* (determined by this.autoScrolled being false), and the view is >=1/3 of
* a screen from the bottom (magic number), then auto-scrolling should
* be disabled.
*/
checkAutoScroll: function() {
if (this.autoScrolled) return;
var chatListHeight = parseInt($(this.dom.chatList).css('height'));
var autoScroll = this.dom.chatList.scrollTop() + 1.3*chatListHeight >= this.dom.chatList.prop('scrollHeight');
if (this.autoScroll != autoScroll) {
this.autoScroll = autoScroll;
this.dom.autoScrollIcon.attr('class', autoScroll ? 'on' : 'off');
}
},
/**
* Trigger a particular sound event.
*/
playSound: function(event) {
if (!config.settings.notifications.soundEnabled || !config.settings.notifications.soundVolume)
return;
var sound = config.settings.notifications.sounds[event];
return sound && this.sounds[sound] && (this.sounds[sound].play() || true);
},
/**
* Trigger the correct message sound event.
* Only one sound is played, in order:
* 1. keyword alert, 2. /msg, 3. sender alert, 4. incoming.
*/
playSoundMessage: function(message) {
var mention = (message.body.indexOf(xmpp.nick.current) >= 0
|| message.body.indexOf(xmpp.user) >= 0);
var sender = false;
for (var i in config.settings.notifications.triggers) {
mention = mention || (0 <= message.body.indexOf(config.settings.notifications.triggers[i]));
sender = sender || (0 <= message.user.nick.indexOf(config.settings.notifications.triggers[i]));
}
if (mention && this.playSound('mention')) return;
if (message.type == 'chat' && this.playSound('msg')) return;
if (sender && this.playSound('mention')) return;
this.playSound('receive');
},
/**
* Blink.
*/
blinkTitle: function(string) {
window.clearInterval(this.blinker);
string = string ? ' ' + string + ' - ' : '';
var speed = config.settings.notifications.blinkSpeed; // faster than you would believe.
var delay = Math.ceil(1000 / speed);
var number = Math.ceil(1000 * config.settings.notifications.blinkLength / delay);
if (!number) return;
var state = false;
this.blinker = window.setInterval(function() {
if (!number) {
$(document).attr('title', ui.title);
return window.clearInterval(ui.blinker);
}
$(document).attr('title', (state ? '[@ ]' : '[ @]') + string + ui.title);
state = !state;
number--;
}, delay);
},
/**
* Autocomplete partial nicknames or commands with Tab.
*/
autocomplete: function() {
// Search algorithm for the longest common prefix of all matching strings.
var prefixSearch = function(prefix, words) {
var results = [];
for (var i in words) {
if (words[i].substring(0, prefix.length) == prefix) {
results.push(words[i]);
}
}
if (results.length > 1) {
var result = results[0];
// For each match, cut down to the longest common prefix.
for (var i in results) {
for (var j in results[i]) {
if (result[j] != results[i][j]) break;
}
result = result.substring(0, j);
}
results = result ? [result] : [];
}
if (results.length == 1) {
return results[0];
}
else return '';
};
var inputField = this.dom.inputField;
inputField.focus();
var start = inputField[0].selectionStart;
var end = inputField[0].selectionEnd;
if (start != end) return false;
var old = inputField.val();
var prefix = old.substring(0, start).match(/(^|\s)((\S|\\\s)*)$/)[2];
// Look for commands or nicknames.
if (prefix[0] == '/') {
var result = '/' + prefixSearch(prefix.substring(1), Object.keys(chat.commands).concat(Object.keys(config.settings.macros)));
}
else {
var result = prefixSearch(prefix, Object.keys(this.userLinks));
}
if (result) {
inputField.val(old.substring(0, start - prefix.length) + result + old.substring(start, old.length));
inputField[0].selectionStart = start - prefix.length + result.length;
inputField[0].selectionEnd = inputField[0].selectionStart;
}
return true;
},
/**
* Attach variable events for clicking or holding an element.
*/
mouseHold: function(element, duration, fnHold, fnClick) {
var timeout = 0;
var held = false;
fnHold = fnHold.bind(element);
fnClick = fnClick.bind(element);
element.on({
mousedown: function() {
timeout = setTimeout(function() {
held = true;
fnHold();
}, duration);
},
mouseup: function() {
clearTimeout(timeout);
if (!held) fnClick();
held = false;
},
mouseleave: function() {
clearTimeout(timeout);
held = false;
}
});
}
};