forked from rchern/StackExchangeScripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSEChatModifications.user.js
1930 lines (1589 loc) · 64 KB
/
SEChatModifications.user.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
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==UserScript==
// @name SE Chat Modifications
// @description A collection of modifications for SE chat rooms
// @include http://chat.meta.stackexchange.com/rooms/*
// @include http://chat.stackexchange.com/rooms/*
// @include http://chat.stackoverflow.com/rooms/*
// @include http://chat.askubuntu.com/rooms/*
// @author @rchern
// ==/UserScript==
/*
* Injects functions into the page so they can freely interact with existing code
*/
function inject() {
for (var i = 0; i < arguments.length; ++i) {
if (typeof(arguments[i]) == 'function') {
var script = document.createElement('script');
script.type = 'text/javascript';
script.textContent = '(' + arguments[i].toString() + ')(jQuery)';
document.body.appendChild(script);
}
}
}
// Inject the support plugins, followed by the main userscript function
inject(livequery, bindas, expressions, function ($) {
// Setup the selector shortcuts
var Selectors = {
'getMessage': function getMessage(id) {
if (id)
validate('number');
return id ? '#message-' + id : '.user-container.mine:last .message:last';
},
'getSignature': function getSignature(match) {
validate('string');
return ".signature:contains('" + match + "') ~ .messages";
},
'getRoom': function getRoom(match) {
validate('string');
return "#my-rooms > li > a[href^='/rooms']:contains('" + match + "')";
}
};
// Setup the highlight and clipping objects
var Highlights = new Storage(),
Clippings = new Storage('chatClips');
// The list of command states that can be returned from a command function, or one of the command utility functions
var CommandState = {
// The command wasn't found
'NotFound': -1,
// The command failed validation or couldn't execute properly
'Failed': 0,
// The command succeeded, and the input should be cleared (where applicable)
'SucceedDoClear': 1,
// The command succeeded, and the input should not be cleared (where applicable)
'SucceedNoClear': 2
};
// Setup the command and onebox mappings
var Commands = {}, Oneboxes = {};
// Create the navigation
var Navigation = new Navigation();
// Setup the main chat extension function, responsible for handling command processing (client-exposed)
var ChatExtension = window.ChatExtension = new function () {
/*
* Defines new chat extension commands, allowing outside functions to plug into the existing userscript infrastructure
*/
this.define = function (name, fn, help) {
name = name.toLowerCase();
if (typeof fn !== 'function')
throw new Error("The function assigned to " + name + " is not a function");
if (Commands[name])
throw new Error("The command " + name + " is already defined");
if (help && typeof help === 'string')
fn.helptext = help;
Commands[name] = fn;
};
/*
* Associates domains with functions that produce pseudo-oneboxes
*/
this.associate = function (domain, fn) {
if (typeof domain === 'string') {
var assignment = domain.match(/^(?:https?:\/\/)?(?:www\.)?([^\/]+).*/i);
if (!assignment)
throw new Error("The domain " + domain + " does not look valid");
domain = assignment[1].toLowerCase();
if (Oneboxes[domain])
throw new Error("The domain " + domain + " is already onebox-associated");
Oneboxes[domain] = fn;
} else if (domain instanceof RegExp) {
if (!Oneboxes['_regex'])
Oneboxes['_regex'] = [];
Oneboxes['_regex'].push({
'pattern': domain,
'handler': fn
});
} else {
throw new Error("The provided domain is not an acceptable type");
}
}
/*
* Executes commands and automatically displays errors in the case of failed function validation
*/
this.execute = function (name, args) {
var result = CommandState.NotFound;
// Check if the command is defined
if (Commands[name]) {
try {
// Attempt to run the command and get the result
result = Commands[name].apply(this, args);
} catch (ex) {
if (ex.message)
ChatExtension.notify(ex.message);
result = CommandState.Failed;
}
}
return result;
};
/*
* Displays a (usually error) notification dialog to the user for the specified period of time, or until a keyboard or mouse press event occurs
*/
this.notify = function (message, delay) {
if (!delay)
delay = 3000;
$('#inputerror').html(message)
.clearQueue()
.fadeIn("slow")
.delay(delay)
.fadeOut("slow")
.hover(
function () {
$(this).clearQueue();
},
function () {
$(this).delay(delay).fadeOut("slow");
}
)
.css({
'max-height': ($(window).height() - 90) + 'px',
'max-width': '60%'
});
};
/*
* Adds styles to the userscript's <style> element, to simplify writing CSS styles for script-injected content
*/
this.style = function (styleObject) {
var userStyle = $('style#user-style'),
styleText = userStyle.length ? userStyle.text() : '';
for (var selector in styleObject) {
styleText = styleText + selector + '{';
for (var style in styleObject[selector]) {
styleText = styleText + style + ':' + styleObject[selector][style] + ';';
}
styleText = styleText + '}';
}
if (!userStyle.length)
userStyle = $('<style id="user-style" />').appendTo('head');
userStyle.text(styleText);
};
this.bind = Navigation.bind;
this.validate = validate;
this.Selectors = Selectors;
this.CommandState = CommandState;
};
function reply(id) {
$('#input').val(':' + id + ' ' + $('#input').val().replace(/^:\d+\s*/, ''));
}
// Define the on ready activities
$(function () {
var input = $('#input'),
page = $(document),
stars = $('#starred-posts');
// Add a handler for Ctrl + Space message resubmission
page.bindAs(0, 'keydown', function (event) {
if (event.which == 32 && isCtrl(event)) {
// Store the value, since the next step removes it
var value = input.val();
$('.message.pending:first a:contains(retry)').click();
input.val(value);
return false;
}
});
// Add a handler to remove the overlay
//*
page.bindAs(0, 'click keydown', function (event) {
var error = $('#inputerror');
if (event.target != error[0]) {
error.stop(true, true).fadeOut('slow');
}
});
//*/
// Add a handler for /commands
input.bindAs(0, 'keydown', function (event) {
var value = input.val();
if (event.which == 13 && value.substring(0, 1) == '/') {
if (value.substring(1, 2) == '/') {
input.val(value.substring(1));
} else {
var args = value.replace(/\s+$/, '').split(' '),
command = args[0].substring(1),
result;
args = Array.prototype.slice.call(args, 1);
result = ChatExtension.execute(command, args);
if (result == CommandState.SucceededDoClear)
input.val('');
else if (result == CommandState.NotFound)
ChatExtension.notify($(getCommands()).before($('<span />').text("Unknown command, try again, or use // to escape commands")));
event.preventDefault();
event.stopImmediatePropagation();
return false;
}
}
});
// Add keyboard navigation handlers
input.bindAs(0, 'keydown', Navigation.launch);
input.bindAs(0, 'focus', Navigation.deselect);
page.bindAs(0, 'click', Navigation.deselect);
page.bindAs(0, 'keydown', Navigation.navigate);
page.bindAs(0, 'keypress', Navigation.suppress);
$('#chat .message').livequery(Navigation.update);
// Add handler for stars list
stars.ajaxComplete(function (event, xhr, settings) {
if (settings.url.search(/^\/chats\/stars\/\d+/) !== 0) {
return;
}
$(this).find('li').each(function () {
var id = this.id.replace(/^summary_/, '');
$('<span title="reply to this message" class="quick-unstar newreply" />').appendTo(this).click(function (event) {
input.focus();
reply(id);
event.stopImmediatePropagation();
});
});
});
// Defer getting the background image until it's available
ChatExtension.style({
'#starred-posts .newreply' : {
'background-image': $('<span class="newreply">').hide()
.appendTo(document.body)
.wrap('<div class="message">')
.css('background-image')
}
});
// Add a handler to update clips across tabs
$(window).bindAs(0, 'focus', function (event) {
Clippings.update();
});
// Highlight persisted highlight items
for (var i = 0; i < Highlights.items.length; ++i) {
addHighlight(Highlights.items[i]);
}
// Add default Vimeo onebox support
ChatExtension.associate('vimeo.com', function (domain, path) {
var id = path.match(/^\/([0-9]+)/) || path.match(/\/channels\/[\d\w]+#([0-9]+)/) || path.match(/\/groups\/[\d\w]+\/videos\/([0-9]+)/);
if (!id || !id[1])
throw new Error("The Vimeo URL " + path + " is unsupported");
id = id[1];
$.ajax({
url: 'http://vimeo.com/api/v2/video/' + id + '.json',
dataType: 'jsonp',
success: function (data) {
// Drop in small preview frame
$('#input').val(data[0].thumbnail_large);
$('#sayit-button').click();
// Wait a bit before dropping in the video title
(function (title, url, name) {
setTimeout(function () {
$('#input').val('[▶ Watch **' + title + '** by ' + name + ' on Vimeo](' + url + ')');
$('#sayit-button').click();
}, 1100);
})(data[0].title, data[0].url, data[0].user_name);
}
});
});
// Show the message ID and timestamp on each message
$("#chat .message:not(.pending):not(.posted)").livequery(function () {
var id = this.id.replace("message-", ""), self = $(this);
if (!self.siblings('#id-' + id).length) {
var timestamp = new Date(self.data('info').time * 1000);
timestamp = "" + timestamp.getHours() + ":" + (timestamp.getMinutes() < 10 ? "0" + timestamp.getMinutes() : timestamp.getMinutes()) + ":" + (timestamp.getSeconds() < 10 ? "0" + timestamp.getSeconds() : timestamp.getSeconds());
self.prev(".timestamp").remove();
self.prepend($('<div />')
.text(id + ' ' + timestamp)
.addClass('timestamp')
.css('line-height', '1.4em')
.attr('id', 'id-' + id));
}
});
// Inject clipboard button and clipboard message link
$('<button class="button" />')
.text('clipboard')
.appendTo('#chat-buttons')
.click(function () {
ChatExtension.execute('clips', []);
return false;
});
$('#chat .message').livequery(function () {
var self = this;
$('<span class="action_clip" />')
.prependTo($(this).find('.meta'))
.attr('title', "Add this message to my clipboard")
.click(function () {
ChatExtension.execute('jot', [self.id.substring(8)]);
});
});
// Hijack image uploader so we can preserve a leading :id
Object.defineProperty(window, 'closeDialog', (function () {
var original;
function transform(url) {
if (!original) {
return;
}
if (!url) {
return original();
}
var text = input.val();
if ((text = /^(:\d+)\s*$/.exec(text)) && !/^:\d+\s*/.test(url)) {
url = text[1] + ' ' + url;
}
original(url);
}
return {
set: function (value) {
original = value;
},
get: function () {
return transform;
}
}
})());
});
// Define the snippet list command
ChatExtension.define('clips', function () {
validate(0);
var delay = 7.5E3, ol;
if (Clippings.items.length) {
ol = $('<ol class="clips_list" />');
for (var i = 0; i < Clippings.items.length; ++i) {
ol.append(createClipItem(i, Clippings.items[i].room, Clippings.items[i].display, true));
}
} else {
ol = $('<span />').text("You do not have any saved clips");
delay = 3E3;
}
ChatExtension.notify(ol, delay);
return CommandState.SucceededDoClear;
});
// Define the delete command
ChatExtension.define('del', function (id) {
if (id)
validate('number');
id = Selectors.getMessage(id) + ' .action-link';
if (!$(id).click().closest('.message').find('.delete').eq(0).click().length)
throw new Error("Unable to delete message");
return CommandState.SucceededNoClear;
});
// Define the edit command
ChatExtension.define('edit', function (id) {
if (id)
validate('number');
id = Selectors.getMessage(id) + ' .action-link';
if (!$(id).click().closest('.message').find('.edit').eq(0).click().length)
throw new Error("Unable to edit message");
return CommandState.SucceededNoClear;
});
// Define the message flag command
ChatExtension.define('flag', function (id) {
validate('number');
$(Selectors.getMessage(id) + ' .flags .img').eq(0).click();
return CommandState.SucceedDoClear;
});
// Define the help command
ChatExtension.define('help', function (command) {
if (!command) {
ChatExtension.notify($('<span />').text('List of recognized commands:').add(getCommands()), 7.5E3);
return;
}
command = command.toLowerCase();
if (!Commands[command])
throw new Error("Unable to get help for unkown command " + command);
if (!Commands[command].helptext)
throw new Error("No additional help for the command " + command);
ChatExtension.notify(Commands[command].helptext);
});
// Define the message history command
ChatExtension.define('history', function (id) {
validate('number');
$('<div class="gm_room_list" />').load('/messages/' + id + '/history #content', function () {
ChatExtension.notify(this, 7.5E3);
});
return CommandState.SucceededDoClear;
});
// Define the highlight display command
ChatExtension.define('hl', function (match) {
if (typeof match == 'undefined') { //no parameters = show list
var ul = $('<ul />').addClass('gm_room_list');
if (Highlights.items.length > 0) {
for (var i = 0; i < Highlights.items.length; i++) {
(function (current) {
$('<a />').click(function () {
$('#input').val('/hl ' + current).focus();
return false;
})
.attr('href', '#')
.text(current)
.wrap('<li />')
.parent()
.appendTo(ul);
})(Highlights.items[i]);
}
} else {
ul = $('<p />').text('Currently there are no highlighted users or messages');
}
ChatExtension.notify(ul, 7.5E3);
} else { //if already in list, remove - else add
match = $.makeArray(arguments).join(' ');
if ($.inArray(match, Highlights.items) >= 0) {
Highlights.remove(match);
removeHighlight(match);
} else {
Highlights.add(match);
addHighlight(match);
}
}
return CommandState.SucceededDoClear;
});
// Define the jump command
ChatExtension.define('jump', function (id) {
validate('number');
var message = $(Selectors.getMessage(id));
if (message.length) {
Navigation.deselect();
Navigation.select(message);
$(document).scrollTop(message.offset().top - 5);
} else {
window.open('http://' + window.location.host + '/transcript/message/' + id + '#' + id);
}
return CommandState.SucceededDoClear;
});
// Define the snippet jotting command
ChatExtension.define('jot', function () {
var first = arguments[0],
second = arguments[1],
room = $('#roomname').text(),
insert, display;
if (isNumber(first) && second === '|') {
insert = 'http://' + window.location.host + '/transcript/message/' + first;
display = $.makeArray(arguments).slice(2).join(' ');
} else if (isNumber(first)) {
validate('number');
insert = 'http://' + window.location.host + '/transcript/message/' + first;
var content = $(Selectors.getMessage(first));
if (content.length !== 1)
throw new Error("The message you're trying to jot down cannot be found");
display = content.find('.content').html();
} else {
display = insert = $.makeArray(arguments).join(' ');
if (insert === '')
throw new Error("You have not entered anything to be jotted down");
}
Clippings.add({
'display': display,
'insert': insert,
'room': room
});
ChatExtension.notify($('<ul class="clips_list" />').append(createClipItem(Clippings.items.length - 1, room, display, false)), 7.5E3);
return CommandState.SucceededDoClear;
});
// Define the show last message command
ChatExtension.define('last', function (match) {
match = $.makeArray(arguments).join(' ');
match = $(Selectors.getSignature(match)).last();
if (!match.length)
throw new Error("Last message cannot be found. Try /load more messages.", 2000);
match.addClass('highlight');
window.setTimeout(function () {
match.removeClass('highlight');
}, 2000);
$.scrollTo(match, 200);
return CommandState.SucceededDoClear;
});
// Define the leave room command
ChatExtension.define('leave', function (match) {
$('#input').val('');
// Determine which room to leave
if (!match) {
// No argument - Leave current room
$('#leave').click();
} else if (isNumber(match)) {
// Numerals - Leave room id
$('#room-' + match).children('.quickleave').click();
} else if (match.toLowerCase() === 'all') {
// all - Leave all rooms
$('#leaveall').click();
} else {
// String - leave room containing string
$(Selectors.getRoom(match) + "~ .quickleave").click();
}
return CommandState.SucceededDoClear;
});
// Define the room list command
ChatExtension.define('list', function (match) {
$.get('/', {
'tab': 'all',
'sort': 'active',
'page': 1,
'filter': match
}, function (data) {
var ul = $('<ul />').addClass('gm_room_list'),
page = $(data),
pageCount = page.filter('.pager').find('a').length;
function processPage() {
var room = $(this).find('h3 .room-name');
var href = room.find("a").attr("href");
var id = this.id.substring(this.id.indexOf('-') + 1);
$('<a />').attr({
'href': href,
'target': '_self'
}).text(id + " - " + room.attr("title"))
.wrap('<li />')
.parent()
.appendTo(ul);
}
page.filter(".roomcard").each(processPage);
if (pageCount >= 2) {
for (var i = 2; i <= pageCount; i++) {
$.get('/', {
'tab': 'all',
'sort': 'active',
'page': i,
'filter': match
}, function (data) {
$(data).filter(".roomcard").each(processPage);
if (i >= pageCount)
ChatExtension.notify(ul, 7.5E3);
});
}
} else {
ChatExtension.notify(ul, 7.5E3);
}
});
return CommandState.SucceededDoClear;
});
// Define the load older messages command
ChatExtension.define('load', function () {
validate(0);
var message = $('.message')[0];
$('#getmore').data('events').click[0].handler(function() {
$(document).scrollTo(message, 400);
});
return CommandState.SucceededDoClear;
});
// Define the /me command
ChatExtension.define('me', function () {
// Don't validate anything, just send the formatted output
$('#input').val('*' + $.trim($.makeArray(arguments).join(' ') + '*'));
$('#sayit-button').click();
return CommandState.SucceededDoClear;
});
// Define the pseudo-onebox command
ChatExtension.define('ob', function (url) {
validate('string');
url = url.match(/^(?:https?:\/\/)?((?:www\.)?([^\/]+))(.*)/i);
if (!url)
throw new Error("Invalid URL " + url);
var handler;
if (!(handler = Oneboxes[url[2]])) {
if (Oneboxes['_regex']) {
for (var i = 0; i < Oneboxes['_regex'].length && !handler; ++i) {
if (Oneboxes['_regex'][i].pattern.test(url[1] + url[3]))
handler = Oneboxes['_regex'][i].handler;
}
}
if (!handler)
throw new Error("The domain " + url[2] + " does not have associated onebox support");
}
handler(url[1], url[3]);
return CommandState.SucceededDoClear;
});
// Define the snippet paste command
ChatExtension.define('paste', function (id) {
validate('number');
$('#input').val(Clippings.items[id].insert);
$('#sayit-button').click();
return CommandState.SucceededDoClear;
});
// Define the user profile command
ChatExtension.define('profile', function () {
match = $.makeArray(arguments).slice(1).join(" ");
var url = matchSite(arguments[0], 'api.') + '/1.0/users/',
currentSite = matchSite(arguments[0]);
$.ajax({
'url': url,
dataType: 'jsonp',
jsonp: 'jsonp',
data: {
filter: match,
pagesize: 50
},
cache: true,
success: function (data) {
var response = '';
function buildOb(data) {
var ob = $('<div />').css({
textAlign: 'left',
padding: '10px 20px 20px',
overflow: 'hidden'
}),
userInfo = $('<div />').css('float', 'left').appendTo(ob),
title = $('<div />').text(', ' + data.location).appendTo(userInfo),
stat = $('<div />').appendTo(userInfo),
name = data.display_name + (data.user_type === 'moderator' ? ' ♦' : '');
$('<a />').attr('href', currentSite + '/users/' + data.user_id)
.addClass('ob-user-username')
.text(name)
.prependTo(title);
// repNumber: Chat function for displaying rep - adds in k for 10k+ reps
$('<span />').addClass('reputation-score').text(repNumber(data.reputation)).appendTo(stat);
$('<img />').css({
float: 'left',
marginRight: 10
}).attr({
src: 'http://www.gravatar.com/avatar/' + data.email_hash + '?s=64&d=identicon',
alt: ''
}).prependTo(ob);
$.ajax({
'url': url + data.user_id + '/tags',
dataType: 'jsonp',
jsonp: 'jsonp',
data: {
pagesize: 8
},
cache: true,
success: function (data) {
var wrapper = $('<div />').appendTo(userInfo).css('margin-top', 4);
for (var i = 0; i < data.tags.length; i++) {
var outer = $('<a />')
.attr('href', currentSite + '/tagged/' + data.tags[i].name)
.appendTo(wrapper).css('text-decoration', 'none');
$('<span />')
.addClass('ob-user-tag')
.text(data.tags[i].name)
.appendTo(outer)
.css({
borderStyle: 'solid',
marginRight: 5
});
}
}
});
var badgeN = 1;
for (var i in data.badge_counts) {
$('<span />').addClass('badge' + badgeN++).appendTo(stat);
$('<span />').addClass('badgecount').text(data.badge_counts[i]).appendTo(stat);
}
return ob;
}
if (data.total === 0) {
response = $('<p />').text('There are no user that match your search');
} else if (data.total === 1) {
$('#input').val(currentSite + '/users/' + data.users[0].user_id);
response = buildOb(data.users[0]);
} else {
response = $('<ul />').addClass('gm_room_list profile');
for (var i = 0; i < data.users.length; i++) {
(function (current) {
var anchor = $('<a />').click(function () {
$('#input').val(currentSite + '/users/' + current.user_id);
ChatExtension.notify(buildOb(current), 7.5E3);
return false;
}).attr('href', '#')
.text(' ' + current.reputation)
.wrap('<li />');
$('<strong />').text(current.display_name + (current.user_type === 'moderator' ? ' ♦' : '')).prependTo(anchor);
$('<img />').attr({
src: 'http://www.gravatar.com/avatar/' + current.email_hash + '?s=14&d=identicon',
alt: ''
}).prependTo(anchor);
anchor.parent().appendTo(response);
})(data.users[i]);
}
if (data.total > 50) {
$('<li />').append($('<h3 />').text('Your query returned too many results. Currently showing the top 50 sorted by reputation')).prependTo(response);
}
}
ChatExtension.notify(response, 7.5E3);
}
});
return CommandState.SucceededDoClear;
});
// Define the message quote command
ChatExtension.define('quote', function (id) {
validate('number');
$('#input').val('http://' + window.location.host + '/transcript/message/' + id + '#' + id);
$('#sayit-button').click();
});
// Define the snippet remove command
ChatExtension.define('rmclip', function (id) {
validate('number');
Clippings.remove(Clippings.items[id]);
return CommandState.SucceededDoClear;
});
// Define the message star command
ChatExtension.define('star', function (id) {
validate('number');
$(Selectors.getMessage(id) + ' .stars .img').eq(0).click();
return CommandState.SucceededDoClear;
});
// Define the room switch command
ChatExtension.define('switch', function (match) {
validate('string');
var rooms = $(Selectors.getRoom(match));
if (rooms.length !== 1) {
throw new Error("Unable to find a single match");
}
window.location = rooms.attr('href');
});
// Define the transcript view command
ChatExtension.define('transcript', function (match) {
var href = '';
if (!match) {
href = $("a.button[href^='/transcript']").attr('href');
} else {
var search = $('#searchbox'),
form = search.parent();
href = form.attr('action') + '?room=' + $("input[name='room']", form).val() + '&' + search.attr('name') + '=' + escape(match);
}
window.open(href);
return CommandState.SucceededDoClear;
});
// Define the update command
ChatExtension.define('update', function () {
validate(0);
try {
window.location = 'http://github.com/rchern/StackExchangeScripts/raw/master/SEChatModifications.user.js';
} catch (ex) {}
return CommandState.SucceededDoClear;
});
/*
* Defines the storage wrapper
*/
function Storage(name) {
this.storageName = name || window.location.pathname + 'chatHighlights';
this.items = [];
/*
* Adds an item to this local storage collection
*/
this.add = function (match) {
if ($.inArray(match, this.items) == -1) {
this.items.push(match);
this.store();
}
};
/*
* Removes an item from this local storage collection
*/
this.remove = function (match) {
var index = $.inArray(match, this.items);
if (index > -1) {
this.items.splice(index, 1);
this.store();
}
};
/*
* Updates the item list of this local storage collection
*/
this.update = function () {
if (localStorage[this.storageName] != null)
this.items = JSON.parse(localStorage[this.storageName]);
};
this.update();
this.store = function () {
localStorage[this.storageName] = JSON.stringify(this.items);
}
}
/*
* Defines the keyboard navigation functionality
*/
function Navigation() {
var active = false,
actions = {
'37': {
'command': 'peek',
'jump': false
},
'39': {
'command': function (target) {
return target.closest('.monologue').hasClass('mine') ? 'edit' : 'reply';
}
},
'67': {
'command': 'jot'
},
'68': {
'command': 'del',
},
'69': {
'command': 'edit'
},
'70': {
'command': 'flag',
},
'72': {
'command': 'history',
'jump': false
},
'74': {