1 // @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPLv3-or-later
3 // https://developer.mozilla.org/en-US/docs/Web/API/Element/matches#Polyfill
4 if (!Element.prototype.matches) {
5 Element.prototype.matches =
6 Element.prototype.matchesSelector ||
7 Element.prototype.mozMatchesSelector ||
8 Element.prototype.msMatchesSelector ||
9 Element.prototype.oMatchesSelector ||
10 Element.prototype.webkitMatchesSelector ||
12 var matches = (this.document || this.ownerDocument).querySelectorAll(s),
14 while (--i >= 0 && matches.item(i) !== this) {}
19 function resizeIframe(obj) {
20 _resizeIframe(obj, 0);
23 function _resizeIframe(obj, desth) {
24 var h = obj.style.height;
25 var ch = obj.contentWindow.document.body.scrollHeight;
27 if (h == (ch + 'px')) {
30 if (desth == ch && ch > 0) {
31 obj.style.height = ch + 'px';
33 setTimeout(_resizeIframe, 100, obj, ch);
36 function openClose(theID) {
37 var el = document.getElementById(theID);
39 if (window.getComputedStyle(el).display === "none") {
47 function openMenu(theID) {
48 var el = document.getElementById(theID);
50 if (!el.dataset.display) {
51 el.dataset.display = 'block';
53 el.style.display = el.dataset.display;
57 function closeMenu(theID) {
58 var el = document.getElementById(theID);
60 el.dataset.display = window.getComputedStyle(el).display;
61 el.style.display = "none";
65 function decodeHtml(html) {
66 var txt = document.createElement("textarea");
75 var force_update = false;
78 var totStopped = false;
82 var in_progress = false;
83 var langSelect = false;
84 var commentBusy = false;
85 var last_popup_menu = null;
86 var last_popup_button = null;
87 var lockLoadContent = false;
90 $.ajaxSetup({cache: false});
92 /* setup comment textarea buttons */
93 /* comment textarea buttons needs some "data-*" attributes to work:
94 * data-role="insert-formatting" : to mark the element as a formatting button
95 * data-bbcode="<string>" : name of the bbcode element to insert. insertFormatting() will insert it as "[name][/name]"
96 * data-id="<string>" : id of the comment, used to find other comment-related element, like the textarea
98 $('body').on('click','[data-role="insert-formatting"]', function(e) {
101 var bbcode = o.data('bbcode');
102 var id = o.data('id');
103 if (bbcode == "img") {
104 Dialog.doImageBrowser("comment", id);
108 if (bbcode == "imgprv") {
112 insertFormatting(bbcode, id);
115 /* event from comment textarea button popups */
116 /* insert returned bbcode at cursor position or replace selected text */
117 $("body").on("fbrowser.image.comment", function(e, filename, bbcode, id) {
119 var textarea = document.getElementById("comment-edit-text-" +id);
120 var start = textarea.selectionStart;
121 var end = textarea.selectionEnd;
122 textarea.value = textarea.value.substring(0, start) + bbcode + textarea.value.substring(end, textarea.value.length);
123 $(textarea).trigger('change');
126 /* setup onoff widgets */
127 $(".onoff input").each(function() {
129 id = $(this).attr("id");
130 $("#"+id+"_onoff ." + (val == 0 ? "on":"off")).addClass("hidden");
133 $(".onoff > a").click(function(event) {
134 event.preventDefault();
135 var input = $(this).siblings("input");
136 var val = 1-input.val();
137 var id = input.attr("id");
138 $("#"+id+"_onoff ." + (val == 0 ? "on":"off")).addClass("hidden");
139 $("#"+id+"_onoff ." + (val == 1 ? "on":"off")).removeClass("hidden");
144 function close_last_popup_menu() {
145 if (last_popup_menu) {
146 last_popup_menu.hide();
147 last_popup_menu.off('click', function(e) {e.stopPropagation()});
148 last_popup_button.removeClass("selected");
149 last_popup_menu = null;
150 last_popup_button = null;
153 $('a[rel^="#"]').click(function(e) {
155 var parent = $(this).parent();
156 var isSelected = (last_popup_button && parent.attr('id') == last_popup_button.attr('id'));
157 close_last_popup_menu();
161 menu = $($(this).attr('rel'));
164 if (menu.attr('popup') == "false") {
167 parent.toggleClass("selected");
169 if (menu.css("display") == "none") {
170 last_popup_menu = null;
171 last_popup_button = null;
173 last_popup_menu = menu;
174 last_popup_menu.on('click', function(e) {e.stopPropagation()});
175 last_popup_button = parent;
176 $('#nav-notifications-menu').perfectScrollbar('update');
180 $('html').click(function() {
181 close_last_popup_menu();
185 $("a.popupbox").colorbox({
187 'transition' : 'elastic',
190 $("a.ajax-popupbox").colorbox({
191 'transition' : 'elastic',
195 /* notifications template */
196 var notifications_tpl= unescape($("#nav-notifications-template[rel=template]").html());
197 var notifications_all = unescape($('<div>').append($("#nav-notifications-see-all").clone()).html()); //outerHtml hack
198 var notifications_mark = unescape($('<div>').append($("#nav-notifications-mark-all").clone()).html()); //outerHtml hack
199 var notifications_empty = unescape($("#nav-notifications-menu").html());
201 /* enable perfect-scrollbars for different elements */
202 $('#nav-notifications-menu, aside').perfectScrollbar();
204 /* nav update event */
205 $('nav').bind('nav-update', function(e, data) {
206 var invalid = data.invalid || 0;
208 window.location.href=window.location.href
211 ['net', 'home', 'intro', 'mail', 'events', 'birthdays', 'notify'].forEach(function(type) {
212 var number = data[type];
215 $('#' + type + '-update').removeClass('show');
217 $('#' + type + '-update').addClass('show');
219 $('#' + type + '-update').text(number);
222 var intro = data['intro'];
224 intro = ''; $('#intro-update-li').removeClass('show')
226 $('#intro-update-li').addClass('show')
229 $('#intro-update-li').html(intro);
231 var mail = data['mail'];
233 mail = ''; $('#mail-update-li').removeClass('show')
235 $('#mail-update-li').addClass('show')
238 $('#mail-update-li').html(mail);
240 $(".sidebar-group-li .notify").removeClass("show");
241 $(data.groups).each(function(key, group) {
243 var gcount = group.count;
244 $(".group-"+gid+" .notify").addClass("show").text(gcount);
247 $(".forum-widget-entry .notify").removeClass("show");
248 $(data.forums).each(function(key, forum) {
250 var fcount = forum.count;
251 $(".forum-"+fid+" .notify").addClass("show").text(fcount);
254 if (data.notifications.length == 0) {
255 $("#nav-notifications-menu").html(notifications_empty);
257 var nnm = $("#nav-notifications-menu");
258 nnm.html(notifications_all + notifications_mark);
260 var lastItemStorageKey = "notification-lastitem:" + localUser;
261 var notification_lastitem = parseInt(localStorage.getItem(lastItemStorageKey));
262 var notification_id = 0;
264 // Insert notifs into the notifications-menu
265 $(data.notifications).each(function(key, notif) {
266 var text = notif.message.format('<span class="contactname">' + notif.name + '</span>');
267 var contact = ('<a href="' + notif.url + '"><span class="contactname">' + notif.name + '</span></a>');
268 var seenclass = (notif.seen == 1) ? "notify-seen" : "notify-unseen";
269 var html = notifications_tpl.format(
270 notif.href, // {0} // link to the source
271 notif.photo, // {1} // photo of the contact
272 text, // {2} // preformatted text (autor + text)
273 notif.date, // {3} // date of notification (time ago)
274 seenclass, // {4} // visited status of the notification
275 new Date(notif.timestamp*1000), // {5} // date of notification
276 notif.url, // {6} // profile url of the contact
277 notif.message.format(contact), // {7} // preformatted html (text including author profile url)
278 '' // {8} // Deprecated
283 // Desktop Notifications
284 $(data.notifications.reverse()).each(function(key, e) {
285 notification_id = parseInt(e.timestamp);
286 if (notification_lastitem !== null && notification_id > notification_lastitem && Number(e.seen) === 0) {
287 if (getNotificationPermission() === "granted") {
288 var notification = new Notification(document.title, {
289 body: decodeHtml(e.message.replace('→ ', '').format(e.name)),
292 notification['url'] = e.href;
293 notification.addEventListener("click", function(ev) {
294 window.location = ev.target.url;
300 notification_lastitem = notification_id;
301 localStorage.setItem(lastItemStorageKey, notification_lastitem)
303 $("img[data-src]", nnm).each(function(i, el) {
304 // Add src attribute for images with a data-src attribute
305 // However, don't bother if the data-src attribute is empty, because
306 // an empty "src" tag for an image will cause some browsers
307 // to prefetch the root page of the Friendica hub, which will
308 // unnecessarily load an entire profile/ or network/ page
309 if ($(el).data("src") != '') {
310 $(el).attr('src', $(el).data("src"));
315 var notif = data['notify'];
317 $("#nav-notifications-linkmenu").addClass("on");
319 $("#nav-notifications-linkmenu").removeClass("on");
322 $(data.sysmsgs.notice).each(function(key, message) {
323 $.jGrowl(message, {sticky: true, theme: 'notice'});
325 $(data.sysmsgs.info).each(function(key, message) {
326 $.jGrowl(message, {sticky: false, theme: 'info', life: 5000});
329 // Update the js scrollbars
330 $('#nav-notifications-menu').perfectScrollbar('update');
333 // Asynchronous calls are deferred until the very end of the page load to ease on slower connections
334 window.addEventListener("load", function(){
336 if (typeof acl !== 'undefined') {
341 // Allow folks to stop the ajax page updates with the pause/break key
342 $(document).keydown(function(event) {
343 if (event.keyCode == '8') {
344 var target = event.target || event.srcElement;
345 if (!/input|textarea/i.test(target.nodeName)) {
350 if (event.keyCode == '19' || (event.ctrlKey && event.which == '32')) {
351 event.preventDefault();
352 if (stopped == false) {
357 $('#pause').html('<img src="images/pause.gif" alt="pause" style="border: 1px solid black;" />');
361 } else if (!totStopped) {
366 // Scroll to the next/previous thread when pressing J and K
367 $(document).keydown(function (event) {
368 var threads = $('.thread_level_1');
369 if ((event.keyCode === 74 || event.keyCode === 75) && !$(event.target).is('textarea, input')) {
370 var scrollTop = $(window).scrollTop();
371 if (event.keyCode === 75) {
372 threads = $(threads.get().reverse());
374 threads.each(function(key, item) {
376 var top = $(item).offset().top - 100;
377 if (event.keyCode === 74) {
378 comparison = top > scrollTop + 1;
379 } else if (event.keyCode === 75) {
380 comparison = top < scrollTop - 1;
383 $('html, body').animate({scrollTop: top}, 200);
390 // Set an event listener for infinite scroll
391 if (typeof infinite_scroll !== 'undefined') {
392 $(window).scroll(function(e) {
393 if ($(document).height() != $(window).height()) {
394 // First method that is expected to work - but has problems with Chrome
395 if ($(window).scrollTop() > ($(document).height() - $(window).height() * 1.5))
398 // This method works with Chrome - but seems to be much slower in Firefox
399 if ($(window).scrollTop() > (($("section").height() + $("header").height() + $("footer").height()) - $(window).height() * 1.5)) {
407 function NavUpdate() {
409 var pingCmd = 'ping?format=json' + ((localUser != 0) ? '&f=&uid=' + localUser : '');
410 $.get(pingCmd, function(data) {
412 // send nav-update event
413 $('nav').trigger('nav-update', data.result);
416 ['network', 'profile', 'community', 'notes', 'display', 'contact'].forEach(function (src) {
417 if ($('#live-' + src).length) {
421 if ($('#live-photos').length) {
424 window.location.href = window.location.href;
430 timer = setTimeout(NavUpdate, updateInterval);
433 function updateConvItems(data) {
435 $('.toplevel_item',data).each(function() {
436 var ident = $(this).attr('id');
438 // Add new top-level item.
439 if ($('#' + ident).length == 0 && profile_page == 1) {
440 $('#' + prev).after($(this));
442 // Replace already existing thread.
444 // Find out if the hidden comments are open, so we can keep it that way
445 // if a new comment has been posted
446 var id = $('.hide-comments-total', this).attr('id');
447 if (typeof id != 'undefined') {
448 id = id.split('-')[3];
449 var commentsOpen = $("#collapsed-comments-" + id).is(":visible");
452 $('#' + ident).replaceWith($(this));
454 if (typeof id != 'undefined') {
456 showHideComments(id);
463 $('.like-rotator').hide();
466 $('body').css('cursor', 'auto');
468 /* autocomplete @nicknames */
469 $(".comment-edit-form textarea").editor_autocomplete(baseurl+"/acl");
470 /* autocomplete bbcode */
471 $(".comment-edit-form textarea").bbco_autocomplete('bbcode');
474 function liveUpdate(src) {
475 if ((src == null) || stopped || !profile_uid) {
476 $('.like-rotator').hide(); return;
479 if (($('.comment-edit-text-full').length) || in_progress) {
481 clearTimeout(livetime);
483 livetime = setTimeout(function() {liveUpdate(src)}, 5000);
487 if (livetime != null) {
490 prev = 'live-' + src;
494 if ($(document).scrollTop() == 0) {
498 var orgHeight = $("section").height();
500 var udargs = ((netargs.length) ? '/' + netargs : '');
501 var update_url = 'update_' + src + udargs + '&p=' + profile_uid + '&page=' + profile_page + '&force=' + ((force_update) ? 1 : 0) + '&item=' + update_item;
503 $.get(update_url,function(data) {
505 force_update = false;
508 $('.wall-item-body', data).imagesLoaded(function() {
509 updateConvItems(data);
511 document.dispatchEvent(new Event('postprocess_liveupdate'));
513 // Update the scroll position.
514 $(window).scrollTop($(window).scrollTop() + $("section").height() - orgHeight);
519 function imgbright(node) {
520 $(node).removeClass("drophide").addClass("drop");
523 function imgdull(node) {
524 $(node).removeClass("drop").addClass("drophide");
527 // Since our ajax calls are asynchronous, we will give a few
528 // seconds for the first ajax call (setting like/dislike), then
529 // run the updater to pick up any changes and display on the page.
530 // The updater will turn any rotators off when it's done.
531 // This function will have returned long before any of these
532 // events have completed and therefore there won't be any
533 // visible feedback that anything changed without all this
534 // trickery. This still could cause confusion if the "like" ajax call
535 // is delayed and NavUpdate runs before it completes.
537 function dolike(ident,verb) {
539 $('#like-rotator-' + ident.toString()).show();
540 $.get('like/' + ident.toString() + '?verb=' + verb, NavUpdate);
543 update_item = ident.toString();
546 function dosubthread(ident) {
548 $('#like-rotator-' + ident.toString()).show();
549 $.get('subthread/' + ident.toString(), NavUpdate);
553 function dostar(ident) {
554 ident = ident.toString();
555 $('#like-rotator-' + ident).show();
556 $.get('starred/' + ident, function(data) {
557 if (data.match(/1/)) {
558 $('#starred-' + ident).addClass('starred');
559 $('#starred-' + ident).removeClass('unstarred');
560 $('#star-' + ident).addClass('hidden');
561 $('#unstar-' + ident).removeClass('hidden');
563 $('#starred-' + ident).addClass('unstarred');
564 $('#starred-' + ident).removeClass('starred');
565 $('#star-' + ident).removeClass('hidden');
566 $('#unstar-' + ident).addClass('hidden');
568 $('#like-rotator-' + ident).hide();
572 function doignore(ident) {
573 ident = ident.toString();
574 $('#like-rotator-' + ident).show();
575 $.get('ignored/' + ident, function(data) {
576 if (data.match(/1/)) {
577 $('#ignored-' + ident).addClass('ignored');
578 $('#ignored-' + ident).removeClass('unignored');
579 $('#ignore-' + ident).addClass('hidden');
580 $('#unignore-' + ident).removeClass('hidden');
582 $('#ignored-' + ident).addClass('unignored');
583 $('#ignored-' + ident).removeClass('ignored');
584 $('#ignore-' + ident).removeClass('hidden');
585 $('#unignore-' + ident).addClass('hidden');
587 $('#like-rotator-' + ident).hide();
591 function getPosition(e) {
592 var cursor = {x:0, y:0};
594 if (e.pageX || e.pageY) {
598 if (e.clientX || e.clientY) {
599 cursor.x = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft;
600 cursor.y = e.clientY + (document.documentElement.scrollTop || document.body.scrollTop) - document.documentElement.clientTop;
601 } else if (e.x || e.y) {
609 var lockvisible = false;
611 function lockview(event,id) {
612 event = event || window.event;
613 cursor = getPosition(event);
618 $.get('lockview/' + id, function(data) {
619 $('#panel').html(data);
620 $('#panel').css({'left': cursor.x + 5 , 'top': cursor.y + 5});
626 function lockviewhide() {
631 function post_comment(id) {
634 $('body').css('cursor', 'wait');
635 $("#comment-preview-inp-" + id).val("0");
638 $("#comment-edit-form-" + id).serialize(),
641 $("#comment-edit-wrapper-" + id).hide();
642 $("#comment-edit-text-" + id).val('');
643 var tarea = document.getElementById("comment-edit-text-" + id);
645 commentClose(tarea,id);
650 timer = setTimeout(NavUpdate,10);
655 window.location.href=data.reload;
663 function preview_comment(id) {
664 $("#comment-preview-inp-" + id).val("1");
665 $("#comment-edit-preview-" + id).show();
668 $("#comment-edit-form-" + id).serialize(),
671 $("#comment-edit-preview-" + id).html(data.preview);
672 $("#comment-edit-preview-" + id + " a").click(function() {return false;});
680 function showHideComments(id) {
681 if ($('#collapsed-comments-' + id).is(':visible')) {
682 $('#collapsed-comments-' + id).slideUp();
683 $('#hide-comments-' + id).hide();
684 $('#hide-comments-total-' + id).show();
686 $('#collapsed-comments-' + id).slideDown();
687 $('#hide-comments-' + id).show();
688 $('#hide-comments-total-' + id).hide();
692 function preview_post() {
693 $("#jot-preview").val("1");
694 $("#jot-preview-content").show();
697 $("#profile-jot-form").serialize(),
700 $("#jot-preview-content").html(data.preview);
701 $("#jot-preview-content" + " a").click(function() {return false;});
702 document.dispatchEvent(new Event('postprocess_liveupdate'));
707 $("#jot-preview").val("0");
712 // unpause auto reloads if they are currently stopped
715 $('#pause').html('');
718 // load more network content (used for infinite scroll)
719 function loadScrollContent() {
720 if (lockLoadContent) {
723 lockLoadContent = true;
725 $("#scroll-loader").fadeIn('normal');
727 // the page number to load is one higher than the actual
729 infinite_scroll.pageno+=1;
731 match = $("span.received").last();
732 if (match.length > 0) {
733 received = match[0].innerHTML;
735 received = "0000-00-00 00:00:00";
738 match = $("span.created").last();
739 if (match.length > 0) {
740 created = match[0].innerHTML;
742 created = "0000-00-00 00:00:00";
745 match = $("span.commented").last();
746 if (match.length > 0) {
747 commented = match[0].innerHTML;
749 commented = "0000-00-00 00:00:00";
752 match = $("span.id").last();
753 if (match.length > 0) {
754 id = match[0].innerHTML;
759 // get the raw content from the next page and insert this content
760 // right before "#conversation-end"
761 $.get(infinite_scroll.reload_uri + '&mode=raw&last_received=' + received + '&last_commented=' + commented + '&last_created=' + created + '&last_id=' + id + '&page=' + infinite_scroll.pageno, function(data) {
762 $("#scroll-loader").hide();
763 if ($(data).length > 0) {
764 $(data).insertBefore('#conversation-end');
765 lockLoadContent = false;
767 $("#scroll-end").fadeIn('normal');
770 document.dispatchEvent(new Event('postprocess_liveupdate'));
774 function bin2hex(s) {
775 // Converts the binary representation of data to hex
778 // discuss at: http://phpjs.org/functions/bin2hex
779 // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
780 // + bugfixed by: Onno Marsman
781 // + bugfixed by: Linuxworld
782 // * example 1: bin2hex('Kev');
783 // * returns 1: '4b6576'
784 // * example 2: bin2hex(String.fromCharCode(0x00));
786 var v,i, f = 0, a = [];
790 for (i = 0; i<f; i++) {
791 a[i] = s.charCodeAt(i).toString(16).replace(/^([\da-f])$/,"0$1");
797 function groupChangeMember(gid, cid, sec_token) {
798 $('body .fakelink').css('cursor', 'wait');
799 $.get('group/' + gid + '/' + cid + "?t=" + sec_token, function(data) {
800 $('#group-update-wrapper').html(data);
801 $('body .fakelink').css('cursor', 'auto');
805 function profChangeMember(gid,cid) {
806 $('body .fakelink').css('cursor', 'wait');
807 $.get('profperm/' + gid + '/' + cid, function(data) {
808 $('#prof-update-wrapper').html(data);
809 $('body .fakelink').css('cursor', 'auto');
813 function contactgroupChangeMember(checkbox, gid, cid) {
815 // checkbox.checked is the checkbox state after the click
816 if (checkbox.checked) {
817 url = 'group/' + gid + '/add/' + cid;
819 url = 'group/' + gid + '/remove/' + cid;
821 $('body').css('cursor', 'wait');
824 // Restores previous state in case of error
825 checkbox.checked = !checkbox.checked;
828 $('body').css('cursor', 'auto');
834 function checkboxhighlight(box) {
835 if ($(box).is(':checked')) {
836 $(box).addClass('checkeditem');
838 $(box).removeClass('checkeditem');
842 function notifyMarkAll() {
843 $.get('notify/mark/all', function(data) {
847 timer = setTimeout(NavUpdate,1000);
853 * sprintf in javascript
854 * "{0} and {1}".format('zero','uno');
856 String.prototype.format = function() {
857 var formatted = this;
858 for (var i = 0; i < arguments.length; i++) {
859 var regexp = new RegExp('\\{'+i+'\\}', 'gi');
860 formatted = formatted.replace(regexp, arguments[i]);
865 Array.prototype.remove = function(item) {
866 to=undefined; from=this.indexOf(item);
867 var rest = this.slice((to || from) + 1 || this.length);
868 this.length = from < 0 ? this.length + from : from;
869 return this.push.apply(this, rest);
872 function previewTheme(elm) {
873 theme = $(elm).val();
874 $.getJSON('pretheme?f=&theme=' + theme,function(data) {
875 $('#theme-preview').html('<div id="theme-desc">' + data.desc + '</div><div id="theme-version">' + data.version + '</div><div id="theme-credits">' + data.credits + '</div><a href="' + data.img + '"><img src="' + data.img + '" width="320" height="240" alt="' + theme + '" /></a>');
880 // notification permission settings in localstorage
881 // set by settings page
882 function getNotificationPermission() {
883 if (window["Notification"] === undefined) {
887 if (Notification.permission === 'granted') {
888 var val = localStorage.getItem('notification-permissions');
894 return Notification.permission;
899 * Show a dialog loaded from an url
900 * By defaults this load the url in an iframe in colorbox
901 * Themes can overwrite `show()` function to personalize it
908 * @return object colorbox
910 show : function (url) {
911 var size = Dialog._get_size();
912 return $.colorbox({href: url, iframe:true,innerWidth: size.width+'px',innerHeight: size.height+'px'})
916 * Show the Image browser dialog
919 * @param string id (optional)
922 * The name will be used to build the event name
923 * fired by image browser dialog when the user select
924 * an image. The optional id will be passed as argument
925 * to the event handler
927 doImageBrowser : function (name, id) {
928 var url = Dialog._get_url("image",name,id);
929 return Dialog.show(url);
933 * Show the File browser dialog
936 * @param string id (optional)
939 * The name will be used to build the event name
940 * fired by file browser dialog when the user select
941 * a file. The optional id will be passed as argument
942 * to the event handler
944 doFileBrowser : function (name, id) {
945 var url = Dialog._get_url("file",name,id);
946 return Dialog.show(url);
949 _get_url : function(type, name, id) {
951 if (id !== undefined) {
952 hash = hash + "-" + id;
954 return baseurl + "/fbrowser/"+type+"/?mode=minimal#"+hash;
957 _get_size: function() {
959 width: window.innerWidth-50,
960 height: window.innerHeight-100