forked from huyz/google-plus-me
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gpme.js
1466 lines (1278 loc) · 50.9 KB
/
gpme.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
/*
# Filename: gpme.js
# {{{1
# Platforms: Google Chrome
# Depends:
* Web: http://huyz.us/google-plus-me/
# Source: https://github.com/huyz/google-plus-me
# Author: Huy Z http://huyz.us/
# Updated on: 2011-07-23
# Created on: 2011-07-11
#
# Installation:
# Like any other browser extension.
#
# Usage:
# Click on the titlebar of each shared post.
# [NOT YET ENABLED: Or use the 'o' keyboard shortcut.]
#
# Thanks:
# This extension takes some ideas from
# https://github.com/mohamedmansour/google-plus-extension/
# http://code.google.com/p/buzz-plus/
# https://github.com/wittman/googleplusplus_hide_comments .
# Copyright (C) 2011 Huy Z
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/****************************************************************************
* Constants
***************************************************************************/
//// For more class constants, see foldItem() in classes array
// We can't just use '.a-b-f-i-oa' cuz clicking link to the *current* page will
// refresh the contentPane
var _ID_CONTENT_PANE = '#contentPane';
var C_NOTIFICATIONS_MARKER = 'MJI2hd';
var C_SPARKS_MARKER = 'a-b-OL';
var C_SINGLE_POST_MARKER = 'a-Wf-i-M';
var C_PROFILE_PANE = 'a-p-M-T-hk-xc';
var C_STREAM = 'a-b-f-i-oa';
var _C_STREAM = '.a-b-f-i-oa';
var _FEEDBACK_LINK = '.a-eo-eg';
var C_FEEDBACK = 'tk3N6e-e-vj';
var _C_SELECTED = '.a-f-oi-Ai';
var _C_ITEM = '.a-b-f-i';
var _C_CONTENT = '.a-b-f-i-p';
var _C_HANGOUT_PLACEHOLDER = '.a-b-f-i-Qi-Nd'; // Maybe more than just hangout?
var S_PHOTO = '.a-f-i-p-U > a.a-f-i-do';
var _C_TITLE = '.gZgCtb';
var _C_PERMS = '.a-b-f-i-aGdrWb'; // Candidates: a-b-f-i-aGdrWb a-b-f-i-lj62Ve
var _C_MUTED = '.a-b-f-i-gg-eb';
var C_DATE = 'a-b-f-i-Ad-Ub';
var _C_DATE = '.a-b-f-i-Ad-Ub';
var _C_DATE_CSS = '.a-f-i-Ad-Ub';
var _C_COMMENTS_ALL_CONTAINER = '.a-b-f-i-Xb';
var C_COMMENTS_ALL_CONTAINER = 'a-b-f-i-Xb';
var C_COMMENTS_OLD_CONTAINER = 'a-b-f-i-cf-W-xb';
var _C_COMMENTS_OLD_CONTAINER = '.a-b-f-i-cf-W-xb';
var _C_COMMENTS_OLD = '.a-b-f-i-gc-cf-Xb-h';
var _C_COMMENTS_OLD_NAMES = '.a-b-f-i-cf-W-xb .a-b-f-i-je-oa-Vb';
var C_COMMENTS_SHOWN_CONTAINER = 'a-b-f-i-Xb-oa';
var _C_COMMENTS_SHOWN_CONTAINER = '.a-b-f-i-Xb-oa';
var _C_COMMENTS_SHOWN = '.a-b-f-i-W-r';
var _C_COMMENTS_SHOWN_NAMES = '.a-b-f-i-W-r a.a-f-i-W-Zb';
var C_COMMENTS_SHOWN_CONTENT = 'a-f-i-ZP25p';
var C_COMMENTS_MORE_CONTAINER = 'a-b-f-i-Sb-W-xb';
var _C_COMMENTS_MORE_CONTAINER = '.a-b-f-i-Sb-W-xb';
var _C_COMMENTS_MORE = '.a-b-f-i-gc-Sb-Xb-h';
var _C_COMMENTS_MORE_NAMES = '.a-b-f-i-Sb-W-xb .a-b-f-i-je-oa-Vb';
//var _C_COMMENTS_CONTAINER = '.a-b-f-i-Xb-oa';
var _C_COMMENT_EDITOR = '.a-b-f-i-Pb-W-t';
var _ID_STATUS_BG = '#gbi1a';
var _ID_STATUS_FG = '#gbi1';
var C_STATUS_BG_OFF = 'gbid';
var C_STATUS_FG_OFF = 'gbids';
var _C_SHARE_LINE = '.a-f-i-bg';
var _C_EMBEDDED_VIDEO = '.ea-S-Bb-jn > div';
var S_PROFILE_POSTS = 'div[id$="-posts-page"]';
var _C_COMMENT_CONTAINERS =
[ _C_COMMENTS_OLD_CONTAINER, _C_COMMENTS_SHOWN_CONTAINER, _C_COMMENTS_MORE_CONTAINER ];
var C_COMMENTCOUNT_NOHILITE = 'gpme-comment-count-nohilite';
// XXX We assume there is no substring match problem because
// it doesn't look like any class names would be a superstring of these
var COMMENT_CONTAINER_REGEXP = new RegExp('\\b(?:' + C_COMMENTS_OLD_CONTAINER + '|' + C_COMMENTS_SHOWN_CONTAINER + '|' + C_COMMENTS_MORE_CONTAINER + '|' + C_COMMENTS_SHOWN_CONTENT + ')\\b');
var DISABLED_PAGES_URL_REGEXP = new RegExp(/\/(posts|notifications|sparks)\//);
var DISABLED_PAGES_CLASSES = [
C_NOTIFICATIONS_MARKER,
C_SPARKS_MARKER,
C_SINGLE_POST_MARKER
];
/****************************************************************************
* Init
***************************************************************************/
// list or expanded mode (like on GReader)
var displayMode;
// In list mode, an item that was opened but may need to be reclosed
// once the location.href is corrected
var $lastTentativeOpen = null;
var $lastPreviewedItem = null;
var lastCommentCountUpdateTimers = {};
// Shared DOM: the titlebar
var titlebarTpl = document.createElement('div');
titlebarTpl.setAttribute('class', 'gpme-titlebar');
titlebarTpl.innerHTML = '<div class="' + C_FEEDBACK + '"><div class="gpme-fold-icon gpme-fold-icon-unfolded-left">\u25bc</div><div class="gpme-fold-icon gpme-fold-icon-unfolded-right">\u25bc</div><span class="gpme-title"></span></div>';
var $titlebarTpl = $(titlebarTpl);
$titlebarTpl.click(onTitlebarClick);
var commentbarTpl = document.createElement('div');
commentbarTpl.setAttribute('class', 'gpme-commentbar');
commentbarTpl.innerHTML = '<div class="' + C_FEEDBACK + '"><div class="gpme-fold-icon gpme-comments-fold-icon-unfolded gpme-comments-fold-icon-unfolded-top">\u25bc</div><div class="gpme-fold-icon gpme-comments-fold-icon-unfolded-bottom">\u25bc</div><span class="gpme-comments-title"></span></div>';
var $commentbarTpl = $(commentbarTpl);
$commentbarTpl.click(onCommentbarClick);
var postWrapperTpl = document.createElement('div');
postWrapperTpl.className = 'gpme-post-wrapper';
var clickWall = document.createElement('div');
clickWall.className = 'gpme-disable-clicks';
clickWall.style.position = 'absolute';
clickWall.style.height = '100%';
clickWall.style.width = '100%';
clickWall.style.zIndex = '12'; // higher than .gpme-folded .a-f-i-Ia-D
clickWall.style.display = 'none';
var previewTriangleSpan = document.createElement('span');
previewTriangleSpan.className = 'gpme-preview-triangle';
previewTriangleSpan.style.backgroundImage = 'url(' + chrome.extension.getURL('/images/preview-triangle.png') + ')';
postWrapperTpl.appendChild(clickWall);
postWrapperTpl.appendChild(previewTriangleSpan);
var $postWrapperTpl = $(postWrapperTpl);
var commentsWrapperTpl = document.createElement('div');
commentsWrapperTpl.className = 'gpme-comments-wrapper';
var $commentsWrapperTpl = $(commentsWrapperTpl);
// For instant previews, hoverIntent
var hoverIntentConfig = {
handlerIn: showPreview, // function = onMouseOver callback (REQUIRED)
delayIn: 400, // number = milliseconds delay before onMouseOver
handlerOut: hidePreview, // function = onMouseOut callback (REQUIRED)
delayOut: 350, // number = milliseconds delay before onMouseOut
exclusiveSet: null // name of exclusiveSet to which the target belongs
};
// Duration of clickwall.
// NOTE: timeout must be less than jquery.hoverIntent's overTimeout, otherwise
// the preview will go away.
var clickWallTimeout = 300;
/****************************************************************************
* Utility
***************************************************************************/
/**
* For debugging
*/
function trace(msg) {
//console.log(typeof msg == 'object' ? msg instanceof jQuery ? msg.get() : msg : 'g+me: ' + msg);
}
function debug(msg) {
console.debug(typeof msg == 'object' ? msg instanceof jQuery ? msg.get() : msg : 'g+me.' + msg);
}
function warn(msg) {
console.warn(typeof msg == 'object' ? msg instanceof jQuery ? msg.get() : msg : 'g+me.' + msg);
}
function error(msg) {
console.error(typeof msg == 'object' ? msg instanceof jQuery ? msg.get() : msg : 'g+me.' + msg);
}
/**
* Check if should enable on certain pages
* @param $subtree: Optional, to force checking of DOM in cases when the
* href is not yet correct and the Ajax updates are pending
*/
function isEnabledOnThisPage($subtree) {
if (typeof $subtree == 'undefined')
return ! DISABLED_PAGES_URL_REGEXP.test(window.location.href);
for (var c in DISABLED_PAGES_CLASSES) {
if ($subtree.hasClass(DISABLED_PAGES_CLASSES[c]) || $subtree.find('.' + DISABLED_PAGES_CLASSES[c]).length) {
debug("isEnabledOnThisPage: disabling because match on " + DISABLED_PAGES_CLASSES[c]);
return false;
}
}
return true;
}
/**
* Shorten date text to give more room for snippet
* FIXME: English-specific
*/
function abbreviateDate(text) {
return text.replace(/\s*\(edited.*?\)/, '').replace(/Yesterday/g, 'Yest.');
}
/**
* Iterates through all the comment containers and calls the callback
*/
function foreachCommentContainer($subtree, callback) {
for (var container in _C_COMMENT_CONTAINERS) {
var $container = $subtree.find(_C_COMMENT_CONTAINERS[container]);
if ($container.length)
callback($container);
}
}
/**
* Queries background page for options
*/
function getOptionsFromBackground(callback) {
chrome.extension.sendRequest({action: 'gpmeGetModeOption'}, function(response) {
displayMode = response;
callback();
});
}
/**
* Returns a throttle function kk2
* */
/****************************************************************************
* Event Handlers
***************************************************************************/
/**
* Responds to DOM updates from G+ to handle change in status of new notifications shown to the user
*/
function onStatusUpdated(e) {
debug("onStatusUpdated");
chrome.extension.sendRequest({action: 'gpmeStatusUpdate', count: parseInt(e.target.innerText, 10)});
}
/**
* Responds to changes in the history state
*/
function onTabUpdated() {
trace("event: Chrome says that tab was updated");
// Restrict to non-single-post Google+ pages
if (!isEnabledOnThisPage())
return;
// If list mode, make sure the correct last opened entry is unfolded, now
// that we know that window.location.href is correct
if (displayMode == 'list')
unfoldLastOpenInListMode();
}
/**
* Responds to a reconstruction of the content pane, e.g.
* when the user clicks on the link that points to the same
* page we're already on, or when switching from About to Posts
* on a profile page.
*/
function onContentPaneUpdated(e) {
// We're only interested in the insertion of entire content pane
trace("event: DOMNodeInserted within onContentPaneUpdated");
var $subtree = $(e.target);
if (isEnabledOnThisPage($subtree))
updateAllItems($subtree);
// (Re-)create handler for insertions into the stream
// No longer needed: we'll just handle it in the single DOMNodeInserted event handler
//$stream = $(e.target).find(_C_STREAM).bind('DOMNodeInserted', onStreamUpdated);
}
/**
* Responds to DOM updates from G+ to handle incoming items.
* Calls updateItem()
*/
function onStreamUpdated(e) {
if (! isEnabledOnThisPage())
return;
trace("event: DOMNodeInserted within stream");
debug("onStreamUpdated: DOMNodeInserted for item id=" + e.target.id + " class='" + e.target.className);
updateItem($(e.target));
}
/**
* Responds to DOM updates from G+ to handle changes to old comment counts
*/
function onCommentsUpdated(e, $item) {
var id = e.target.id;
var className = e.target.className;
//trace("event: DOM insertion or deletion of comments");
debug("onCommentsUpdated: DOM insertion/deletion of comments for item id=" + id + " class='" + e.target.className + "'");
// We may be getting events just from a jquery find for comments,
// before things are set up.
if (! $item.hasClass('gpme-enh'))
return;
/*
// If the user is editing, we should unfold comments
if ($target.hasClass(C_COMMENTS_ALL_CONTAINER) && $target.find(_C_COMMENT_EDITOR).length && $item.hasClass('gpme-comments-folded')) {
unfoldComments(true, $item);
}
*/
updateItemComments($item);
}
/**
* Responds to click on post titlebar.
* Calls toggleItemFolded()
*/
function onTitlebarClick() {
// NOTE: event arg doesn't seem to work for me
var $item = $(this).parent();
debug("onTitlebarClick: " + $item.attr('id'));
toggleItemFolded($item);
}
/**
* Responds to click on post titlebar.
* Calls toggleItemFolded()
*/
function onCommentbarClick() {
// NOTE: event arg doesn't seem to work for me
var $item = $(this).closest(_C_ITEM);
debug("onCommentbarClick: " + $item.attr('id'));
toggleCommentsFolded($item);
}
/**
* Responds to the keypress for open/close item.
* Calls toggleItemFolded()
*/
function onFoldKey(e, attempt) {
debug("onFoldKey attempt=" + (typeof attempt == 'undefined' ? 0 : attempt));
// Find selected item
var $selectedItem = $(_C_SELECTED);
if ($selectedItem.length == 1) {
if (! toggleItemFolded($selectedItem.first())) {
// If we couldn't fold, then movement was in motion, we try again in a bit
if (typeof(attempt) == 'undefined')
attempt = 0;
if (attempt < 4) {
setTimeout(function() {
onFoldKey(e, attempt + 1);
}, 200);
}
}
}
}
/**
* Responds to changes in mode option
*/
function onModeOptionUpdated(newMode) {
debug("onModeOptionUpdated: new mode=" + newMode);
if (! isEnabledOnThisPage())
return;
// If mode has changed
var oldMode = displayMode;
displayMode = newMode;
if (typeof(oldMode) == 'undefined' || displayMode != oldMode)
refreshAllFolds();
}
/**
* Responds to reset all
*/
function onResetAll() {
debug("onResetAll");
var oldMode = displayMode;
for (var i in localStorage) {
if (i.indexOf('gpme_') === 0)
localStorage.removeItem(i);
}
getOptionsFromBackground(function() {
// If mode has changed
debug("onResetAll: oldMode=" + oldMode + " newMode=" + displayMode);
if (typeof(oldMode) == 'undefined' || displayMode != oldMode)
refreshAllFolds();
});
}
/****************************************************************************
* DOM enhancements & folding according to state
***************************************************************************/
/**
* Injects styles in current document
*/
function injectCSS() {
var linkNode = document.createElement('link');
linkNode.rel = 'stylesheet';
linkNode.type = 'text/css';
linkNode.href = chrome.extension.getURL('gpme.css') + '?' + new Date().getTime();
document.getElementsByTagName('head')[0].appendChild(linkNode);
// Apparently, the background-position is incorrect for a user.
// Maybe the notification status displays something differently for him
// early in the loading of the page.
// Let's hardcode the coords, only in this situation
function hardcodeCoords($node) {
return window.getComputedStyle($node.get(0)).cssText.
replace(/(background-position:\s+-?0\s*(?:px)?\s+)-394\s*px/, '$1 0 -274px').
replace(/(background-position:)\s+-37\s*px\s+-394\s*px/, '$1 -26px -274px');
}
// Copy G+ notification status bg style because original is by ID.
// We use a convoluted manner of copying styles in case G+ changes
// the CSS image sprite.
// XXX There must be an easier way than to getComputedStyle()
var styleNode = document.createElement('style');
styleNode.setAttribute('type', 'text/css');
var statusNode, statusOff, cssText;
$statusNode = $(_ID_STATUS_BG);
if ($statusNode.length) {
// We have to temporarily remove the class 'gbid' (turns bg to
// gray), which seems to be there by default.
statusOff = $statusNode.hasClass(C_STATUS_BG_OFF);
if (statusOff)
$statusNode.removeClass(C_STATUS_BG_OFF);
styleNode.appendChild(document.createTextNode('.gpme-comment-count-bg { ' +
hardcodeCoords($statusNode) + ' } '));
$statusNode.addClass(C_STATUS_BG_OFF);
styleNode.appendChild(document.createTextNode('.gpme-comment-count-bg.' + C_COMMENTCOUNT_NOHILITE + ' { ' +
hardcodeCoords($statusNode) + ' } '));
if (! statusOff)
$statusNode.removeClass(C_STATUS_BG_OFF);
}
// Copy G+ notification status fg style because original is by ID
$statusNode = $(_ID_STATUS_FG);
if ($statusNode.length) {
// We have to temporarily remove the class 'gbids' (turns bg to
// gray), which seems to be there by default.
statusOff = $statusNode.hasClass(C_STATUS_FG_OFF);
if (statusOff)
$statusNode.removeClass(C_STATUS_FG_OFF);
styleNode.appendChild(document.createTextNode('.gpme-comment-count-fg { ' +
hardcodeCoords($statusNode) + ' } '));
$statusNode.addClass(C_STATUS_FG_OFF);
styleNode.appendChild(document.createTextNode('.gpme-comment-count-fg.' + C_COMMENTCOUNT_NOHILITE + ' { ' +
hardcodeCoords($statusNode) + ' } '));
if (! statusOff)
$statusNode.removeClass(C_STATUS_FG_OFF);
}
document.getElementsByTagName('head')[0].appendChild(styleNode);
}
/**
* Injects code to make the Feedback button work
*/
function injectNewFeedbackLink() {
//var $link = $('.a-eo-eg');
//alert($link.attr('onclick'));
//$link.attr('onclick', 'alert("shit");');
//$link.click(function(event) { alert("yes"); if (confirm("sheeet")) return appfeedback.startFeedback(event); else return false; });
//$link.click(function(event) { alert("yes") });
//$link.attr('onclick', 'alert("yes");');
//alert($link.attr('onclick'));
}
/**
* Refresh fold/unfolded display of items.
* Called by onModeOptionUpdated() and onResetAll()
*/
function refreshAllFolds() {
// Force refresh of folding
updateAllItems();
// If going to expanded mode, we want to unfold the last item opened in list mode
if (displayMode == 'expanded') {
var id = localStorage.getItem("gpme_post_last_open_" + window.location.href);
if (id !== null) {
var $item = $('#' + id);
//debug("onModeOptionUpdated: last open id=" + id + " $item.length=" + $item.length);
if ($item.length == 1) {
unfoldItem(false, $item);
}
}
}
}
/**
* Update all the items in the current page.
* Is called by main() and onModeOptionUpdated()
*/
function updateAllItems($subtree) {
//debug("updateAllItems");
// Default to updating all divs in contentpane,
// but sometimes we know which one was just inserted by
// an Ajax refresh
if (typeof $subtree == 'undefined')
$subtree = $(_C_STREAM);
// Update all items
$subtree.find(_C_ITEM).each(function(i, item) {
debug("updateAllItems #" + i);
i++;
updateItem($(item));
});
// If list mode, make sure the correct last opened entry is unfolded, but
// only when we know that window.location.href is correct
if (typeof $subtree == 'undefined' && displayMode == 'list')
unfoldLastOpenInListMode();
}
/**
* In list mode, unfold the last opened entry, refolding any wrongly unfolded entry
* NOTE: At this point, location.href may or may not be correct.
*/
function unfoldLastOpenInListMode() {
//debug("unfoldLastOpenInListMode: href=" + window.location.href);
var lastOpenId = localStorage.getItem("gpme_post_last_open_" + window.location.href);
// Undo any incorrectly-unfolded item
// NOTE: lastOpenId could be null, which means this is a page that wasn't visited
// before in list mode or a page that had all items closed; we still want to close
// the incorrectly-opened item
// FIXME: we still get the flash of an open-then-closed item
// XXX Strange: if I search lastTentativeOpen by id, I may be hiding an entry that
// won't be shown. Would be interesting to investigate further, as it probably
// has to do with the way the DOM updates happen with G+.
if ($lastTentativeOpen !== null && $lastTentativeOpen.attr('id') != lastOpenId) {
//debug("unfoldLastOpenInListMode: unfolding " + $lastTentativeOpen.attr('id'));
foldItem(false, $lastTentativeOpen);
$lastTentativeOpen = null;
}
if (lastOpenId !== null) {
// We explicitly open in order to close any previously opened item
// FIXME: this favors the oldest instead of the most recent opened item
unfoldItem(false, $('#' + lastOpenId));
}
}
/**
* Updates fold/unfold appropriately, except in list mode where the
* caller is responsible for unfolding the appropriate item.
*/
function updateItem($item) {
var id = $item.attr('id');
debug("updateItem: " + id);
var enhanceItem = ! $item.hasClass('gpme-enh');
if (enhanceItem) {
// Add titlebar
var $itemContent = $item.find(_C_CONTENT);
if ($itemContent.length != 1) {
if ($item.find(_C_HANGOUT_PLACEHOLDER).length) {
setTimeout(function() { updateItem($item); }, 100 );
} else {
error("updateItem: Can't find content of item " + id + " hits=" + $itemContent.length);
error($item.html());
}
return;
}
// NOTE: we have to change the class before inserting or we'll get more
// events and infinite recursion.
//debug("updateItem: enhancing");
$item.addClass('gpme-enh');
// Add hover event handler
$item.hoverIntent(hoverIntentConfig);
//$item.hover(showPreview, hidePreview);
var $titlebar = $titlebarTpl.clone(true);
$titlebar.insertBefore($itemContent);
// Insert container for post content so that we can turn it into an instant
// preview
var $wrapper = $postWrapperTpl.clone().insertAfter($titlebar);
$wrapper.append($itemContent);
// Structure commentbar:
// "a-b-f-i-Xb"
// "gpme-commentbar"
var $allCommentContainer = $item.find(_C_COMMENTS_ALL_CONTAINER);
// It's possible not to have comments at all on posts with comments
// disabled or on photo-tagging posts
if ($allCommentContainer.length) {
var $commentbar = $commentbarTpl.clone(true);
$allCommentContainer.prepend($commentbar);
// Insert wrapper for comments container so that we can hide it without
// triggering DOMSubtreeModified events on the container
$wrapper = $commentsWrapperTpl.clone().insertAfter($commentbar);
foreachCommentContainer($allCommentContainer, function($container) {
$wrapper.append($container);
});
}
}
// Refresh fold of post
var itemFolded = false;
if (displayMode == 'list') {
// Check if it's supposed to be unfolded
// NOTE: the href may be incorrect at this point if the user is clicking on a new
// stream link and the updates are coming in through AJAX *before* a tabUpdated event
var lastOpenId = localStorage.getItem("gpme_post_last_open_" + window.location.href);
if (lastOpenId !== null && id == lastOpenId) {
unfoldItem(false, $item);
// Record this operation because we may have to undo it once location.href is
// known to be correct
$lastTentativeOpen = $item;
} else {
foldItem(false, $item);
itemFolded = true;
}
} else if (displayMode == 'expanded') {
itemFolded = localStorage.getItem("gpme_post_folded_" + id);
// Fold if necessary
if (itemFolded !== null) {
foldItem(false, $item);
} else {
unfoldItem(false, $item);
}
}
// Refresh fold of comments if visible
if (! itemFolded) {
if (localStorage.getItem("gpme_comments_folded_" + id))
foldComments(false, $item);
else
unfoldComments(false, $item);
}
// Start listening to updates to comments.
// We need to listen all the time since comments can come in or out.
if (enhanceItem) {
// We must have one throttle function per comment section within item.
var commentsUpdateHandler = $.throttle(200, 50, function(e) { onCommentsUpdated(e, $item); });
//var commentsUpdateHandler = function(e) { onCommentsUpdated(e, $item) };
foreachCommentContainer($item.find('.gpme-comments-wrapper'), function($container) {
$container.bind('DOMSubtreeModified', function(e) {
// We have to filter out junk before we call the throttle function; otherwise
// the last callback call will have junk arguments.
var id = e.target.id;
// Some optimizations, especially to prevent lag when typing comments.
if (id && id.charAt(0) == ':' || ! isEnabledOnThisPage())
return;
var className = e.target.className;
// If the target has id, then it's probably a comment
if (! id && ! COMMENT_CONTAINER_REGEXP.test(className))
return;
// Finally call our throttled callback
commentsUpdateHandler(e);
});
});
}
}
/**
* Updates the display of comments
*/
function updateItemComments($item) {
if ($item.hasClass('gpme-comments-folded')) {
foldComments(false, $item);
} else {
unfoldComments(false, $item);
}
}
/****************************************************************************
* Post Folding/unfolding logic
***************************************************************************/
/**
* Toggle viewable state of the content of an item.
* This is only called as a result of a user action.
* Calls foldItem() or unfoldItem().
* @return true if toggling worked
*/
function toggleItemFolded($item) {
var $post = $item.find('.gpme-post-wrapper');
//debug("toggleItemFolded: length=" + $posts.length);
if ($post.length != 1) {
// It is possible to not have a proper match during keyboard scrolling
// (hit 'j' and 'o' in quick succession)
//debug("toggleItemFolded: improper match: " + $posts.length);
return false;
}
var id = $item.attr('id');
if ($item.hasClass('gpme-folded')) {
// If in list mode, we need to fold the previous one
if (displayMode == 'list') {
lastOpenId = localStorage.getItem('gpme_post_last_open_' + window.location.href);
//debug("unfoldItem: last open id=" + lastOpenId);
if (lastOpenId !== null && lastOpenId != id) {
//debug("unfoldItem: href=" + window.location.href + " id =" + id + " lastOpenId=" + lastOpenId);
var $lastItem = $('#' + lastOpenId);
if ($lastItem.length && $lastItem.hasClass('gpme-enh')) {
foldItem(true, $lastItem);
}
}
}
unfoldItem(true, $item, $post);
// Since this thread is a result of an interactive toggle, we record last open
debug("toggleItemFolded: href=" + window.location.href);
debug("toggleItemFolded: gpme_post_last_open_" + window.location.href + "->id = " + id);
localStorage.setItem("gpme_post_last_open_" + window.location.href, id);
} else {
foldItem(true, $item, $post);
// Since this thread is a result of an interactive toggle, we delete last open
if (localStorage.getItem("gpme_post_last_open_" + window.location.href) == id)
localStorage.removeItem("gpme_post_last_open_" + window.location.href);
}
return true;
}
/**
* Fold item, and give titlebar summary content if necessary
* @param $post: Optional if you have it
*/
function foldItem(interactive, $item, $post) {
if (typeof($post) == 'undefined') {
$post = $item.find('.gpme-post-wrapper');
if ($post.length != 1) {
error("foldItem: Can't find post content node");
error($item);
return;
}
}
var id = $item.attr('id');
// Persist for expanded mode
debug("foldItem: id=" + id);
if (displayMode == 'expanded')
localStorage.setItem("gpme_post_folded_" + id, true);
// Visual changes
//$post.fadeOut().hide(); // This causes race-condition when double-toggling quickly.
$post.hide();
$item.addClass('gpme-folded');
$item.removeClass('gpme-unfolded');
//debug("foldItem: id=" + id + " folded=" + $item.hasClass('gpme-folded') + " post.class=" + $post.attr('class') + " should be folded!");
// If interactive folding and comments are showing, record the comment count
var commentCount = countComments($item);
if (interactive && ! $item.hasClass('gpme-comments-folded'))
saveSeenCommentCount(id, commentCount);
// Attached or pending title
var $subtree;
// If not yet done, put content in titlebar
var $title = $subtree = $item.find('.gpme-title');
if (! $title.hasClass('gpme-has-content')) {
$title.addClass('gpme-has-content');
var $srcTitle = $item.find(_C_TITLE);
if ($srcTitle.length != 1) {
error("foldItem: can't find post content title node");
error($item);
} else {
// NOTE: don't just take the first div inside post content title because
// sometimes the hangout 'Live' icons is there
var $clonedTitle = $subtree = $srcTitle.clone();
var $srcPhoto = $item.find(S_PHOTO);
if ($srcPhoto.length) {
$clonedTitle.prepend($srcPhoto.clone());
}
// Insert fold icon
$clonedTitle.prepend('<span class="gpme-fold-icon">\u25b6</span>');
// Take out permissions
var $perms = $clonedTitle.find(_C_PERMS);
if ($perms.length > 0) {
$perms.remove();
} else {
error("foldItem: can't find permissions div");
error($clonedTitle);
}
// Put in snippet, trying differing things
var classes = [
'.a-b-f-i-u-ki', // poster text
'.a-b-f-i-p-R', // original poster text (and for one's own post, just "Edit")
'.a-b-f-S-oa', // poster link (must come after .a-b-f-i-p-R, which sometimes it's just "Edit")
'.a-f-i-ie-R', // hangout text
'.w0wKhb', // "A was tagged in B"
'.ea-S-pa-qa', // photo caption
'.a-f-i-p-qb .a-b-h-Jb', // photo album
'.ea-S-R-h', // title of shared link
'.ea-S-Xj-Cc' // text of shared link
];
for (var c in classes) {
var $snippet = $item.find(classes[c]);
if (! $snippet.length)
continue;
// We want to ignore link shares that only have the text Edit
// <span class="a-Ja-h a-f-i-Ka-Ja a-b-f-i-Ka">Edit</span>
if (classes[c] == '.a-b-f-i-u-ki' || classes[c] == '.a-b-f-i-p-R') {
$snippet = $snippet.clone();
$snippet.find('.a-b-f-i-Ka').remove();
}
var text = $snippet.text();
if (text.match(/\S/)) {
if (classes[c] == '.a-f-i-ie-R') {
// FIXME: English-specific
text = text.replace(/.*hung out\s*/, '');
}
$snippet = $('<span class="gpme-snippet"></span');
$snippet.text(text); // We have to add separately to properly escape HTML tags
$clonedTitle.append($snippet);
break;
}
}
// Add comment-count container
$clonedTitle.prepend('<div class="gpme-comment-count-container" style="display:none">' +
'<span class="gpme-comment-count-bg ' + C_COMMENTCOUNT_NOHILITE + '"></span>' +
'<span class="gpme-comment-count-fg ' + C_COMMENTCOUNT_NOHILITE + '"></span></div>');
// Take out date marker so that G+ doesn't update the wrong copy
var $clonedDate = $clonedTitle.find(_C_DATE);
if (! $clonedDate.length) {
error("foldItem: Can't find date marker");
error($clonedTitle);
} else {
$clonedDate.removeClass(C_DATE);
// If any, move "- Muted" to right after date and before the " - "
$clonedTitle.find(_C_MUTED).insertAfter($clonedDate);
// Inject the summary title
$title.append($clonedTitle);
// Stop propagation of click from the name
// NOTE: done here coz it can't be done on a detached node.
$clonedTitle.find('a').click(function(e) {
e.stopPropagation();
});
// For first page display, the date is there, but for updates, the date isn't there yet.
// So check, and try again later in case of updates.
var attempt = 40;
(function insertTitleWhenDateUpdated($date) {
attempt--;
if ($date.length && $date.text() != '#' || attempt < 0) {
var dateText = '';
if (attempt < 0) {
error("insertTitleWhenDateUpdated: gave up on getting the date for id=" + id);
} else {
dateText = abbreviateDate($date.text());
}
// Strip out the A link because we don't want to make it clickable
// Not only does clicking it somehow opens a new window, but we need
// the clicking space especially with instant previews
$clonedDate.text(dateText);
} else {
var $srcDateA = $item.find(_C_DATE + ' a');
if ($srcDateA.length) {
// Try again later in a little bit
setTimeout(function() { insertTitleWhenDateUpdated($srcDateA); }, 50);
} else {
error("insertTitleWhenDateUpdated: can't find the source date div");
error($srcDateA);
}
}
})($clonedDate.find('a'));
}
}
}
/* Gonna be harder than this :)
// If interactive, then we want to stop any playing youtube video
// by undoing what clicking play does
var $embed = $post.find(_C_EMBEDDED_VIDEO + '> iframe');
if ($embed.length) {
var $embedParent = $embed.parent();
$embedParent.find('img').show();
$embedParent.find('div').show();
$embedParent.attr({ 'aria-pressed': '', 'aria-selected': '', 'aria-expanded': '' }).
removeClass('ea-S-Pa ea-S-Ya'); // Classes not important -- probably on affects iframe
$embed.remove();
}
*/
// Show possibly-hidden comments so that they appear in the preview (but don't persist)
var $comments = $item.find('.gpme-comments-wrapper');
if ($comments.length) {
$comments.show();
}
// Updated the count in the subtree
updateCommentCount(id, $subtree, commentCount);
}
/**
* For both list and expanded mode, unfolds the item.
* @param $post: Optional if you have it
*/
function unfoldItem(interactive, $item, $post) {
if (typeof($post) == 'undefined') {
$post = $item.find('.gpme-post-wrapper');
if ($post.length != 1) {
//debug("unfoldItem: $posts.length=" + $posts.length);
return;
}
}
var id = $item.attr('id');
debug("unfoldItem: id=" + id);
// Persist for expanded mode
if (displayMode == 'expanded')
localStorage.removeItem("gpme_post_folded_" + id);
// Visual changes
$post.show();
$item.removeClass('gpme-folded');
$item.addClass('gpme-unfolded');
// Refresh fold of comments
// NOTE: this must be done after the CSS classes are updated
if (localStorage.getItem("gpme_comments_folded_" + id))
foldComments(false, $item);
else
unfoldComments(false, $item);
if (interactive && ! $item.hasClass('gpme-comments-folded'))
deleteSeenCommentCount(id);
// Scroll into view because on a short web page for list mode because
// the closing of another post can move the post we're trying to open
if (displayMode == 'list')
$item.scrollintoview();
}
/****************************************************************************
* Comment folding/unfolding logic
***************************************************************************/
/**
* Toggle viewable state of the comments of an item.
* This is only called as a result of a user action.
* Calls foldComments() or unfoldComments().
* @return true if toggling worked
*/
function toggleCommentsFolded($item) {
var $comments = $item.find('.gpme-comments-wrapper');
//debug("toggleCommentsFolded: length=" + $posts.length);
if ($comments.length != 1) {
error("toggleCommentsFolded: Can't find comments");
error($item);
return false;
}