]> git.mxchange.org Git - friendica.git/blob - view/theme/frio/js/modal.js
fix editing in modal-jot
[friendica.git] / view / theme / frio / js / modal.js
1 // @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPLv3-or-later
2 /**
3  * Contains functions for bootstrap modal handling.
4  */
5 $(document).ready(function () {
6         // Clear bs modal on close.
7         // We need this to prevent that the modal displays old content.
8         $("body, footer").on("hidden.bs.modal", ".modal", function () {
9                 $(this).removeData("bs.modal");
10                 $("#modal-title").empty();
11                 $("#modal-body").empty();
12                 // Remove the file browser from jot (else we would have problems
13                 // with AjaxUpload.
14                 $(".fbrowser").remove();
15                 // Remove the AjaxUpload element.
16                 $(".ajaxbutton-wrapper").remove();
17         });
18
19         // Clear bs modal on close.
20         // We need this to prevent that the modal displays old content.
21         $("body").on("hidden.bs.modal", "#jot-modal", function () {
22                 // Restore cached jot at its hidden position ("#jot-content").
23                 $("#jot-content").append(jotcache);
24                 // Clear the jotcache.
25                 jotcache = "";
26                 // Destroy the attachment linkPreviw for Jot.
27                 if (typeof linkPreview === "object") {
28                         linkPreview.destroy();
29                 }
30         });
31
32         // Add Colorbox for viewing Network page images.
33         //var cBoxClasses = new Array();
34         $("body").on("click", ".wall-item-body a img", function () {
35                 var aElem = $(this).parent();
36                 var imgHref = aElem.attr("href");
37
38                 // We need to make sure we only put a Colorbox on links to Friendica images.
39                 // We'll try to do this by looking for links of the form
40                 // .../photo/ab803d8eg08daf85023adfec08 (with nothing more following), in hopes
41                 // that that will be unique enough.
42                 if (imgHref.match(/\/photo\/[a-fA-F0-9]+(-[0-9]\.[\w]+?)?$/)) {
43                         // Add a unique class to all the images of a certain post, to allow scrolling through
44                         var cBoxClass = $(this).closest(".wall-item-body").attr("id") + "-lightbox";
45                         $(this).addClass(cBoxClass);
46
47                         //                      if( $.inArray(cBoxClass, cBoxClasses) < 0 ) {
48                         //                              cBoxClasses.push(cBoxClass);
49                         //                      }
50
51                         aElem.colorbox({
52                                 maxHeight: "90%",
53                                 photo: true, // Colorbox doesn't recognize a URL that don't end in .jpg, etc. as a photo.
54                                 rel: cBoxClass, //$(this).attr("class").match(/wall-item-body-[\d]+-lightbox/)[0].
55                         });
56                 }
57         });
58
59         // Navbar login.
60         $("body").on("click", "#nav-login", function (e) {
61                 e.preventDefault();
62                 Dialog.show(this.href, this.dataset.originalTitle || this.title);
63         });
64
65         // Jot nav menu..
66         $("body").on("click", "#jot-modal .jot-nav li .jot-nav-lnk", function (e) {
67                 e.preventDefault();
68                 toggleJotNav(this);
69         });
70
71         // Bookmarklet page needs an jot modal which appears automatically.
72         if (window.location.pathname.indexOf("/bookmarklet") >= 0 && $("#jot-modal").length) {
73                 jotShow();
74         }
75
76         // Open filebrowser for elements with the class "image-select"
77         // The following part handles the filebrowser for field_fileinput.tpl.
78         $("body").on("click", ".image-select", function () {
79                 // Set a extra attribute to mark the clicked button.
80                 this.setAttribute("image-input", "select");
81                 Dialog.doImageBrowser("input");
82         });
83
84         // Insert filebrowser images into the input field (field_fileinput.tpl).
85         $("body").on("fbrowser.photo.input", function (e, filename, embedcode, id, img) {
86                 // Select the clicked button by it's attribute.
87                 var elm = $("[image-input='select']");
88                 // Select the input field which belongs to this button.
89                 var input = elm.parent(".input-group").children("input");
90                 // Remove the special indicator attribut from the button.
91                 elm.removeAttr("image-input");
92                 // Insert the link from the image into the input field.
93                 input.val(img);
94         });
95
96         // Generic delegated event to open an anchor URL in a modal.
97         // Used in the hovercard.
98         document.getElementsByTagName("body")[0].addEventListener("click", function (e) {
99                 var target = e.target;
100                 while (target) {
101                         if (target.matches && target.matches("a.add-to-modal")) {
102                                 addToModal(target.href);
103                                 e.preventDefault();
104                                 return false;
105                         }
106
107                         target = target.parentNode || null;
108                 }
109         });
110 });
111
112 // Overwrite Dialog.show from main js to load the filebrowser into a bs modal.
113 Dialog.show = function (url, title) {
114         if (typeof title === "undefined") {
115                 title = "";
116         }
117
118         var modal = $("#modal").modal();
119         modal.find("#modal-header h4").html(title);
120         modal.find("#modal-body").load(url, function (responseText, textStatus) {
121                 if (textStatus === "success" || textStatus === "notmodified") {
122                         modal.show();
123
124                         $(function () {
125                                 Dialog._load(url);
126                         });
127                 }
128         });
129 };
130
131 // Overwrite the function _get_url from main.js.
132 Dialog._get_url = function (type, name, id) {
133         var hash = name;
134         if (id !== undefined) hash = hash + "-" + id;
135         return 'media/' + type + '/browser?mode=none&theme=frio#' + hash;
136 };
137
138 // Does load the filebrowser into the jot modal.
139 Dialog.showJot = function () {
140         var type = "photo";
141         var name = "main";
142
143         var url = Dialog._get_url(type, name);
144         if ($(".modal-body #jot-fbrowser-wrapper .fbrowser").length < 1) {
145                 // Load new content to fbrowser window.
146                 $("#jot-fbrowser-wrapper").load(url, function (responseText, textStatus) {
147                         if (textStatus === "success" || textStatus === "notmodified") {
148                                 $(function () {
149                                         Dialog._load(url);
150                                 });
151                         }
152                 });
153         }
154 };
155
156 // Init the filebrowser after page load.
157 Dialog._load = function (url) {
158         // Get nickname & filebrowser type from the modal content.
159         let filebrowser = document.getElementById("filebrowser");
160
161         // Try to fetch the hash form the url.
162         let match = url.match(/media\/[a-z]+\/.*(#.*)/);
163         if (!filebrowser || match === null) {
164                 return; //not fbrowser
165         }
166
167         // Initialize the filebrowser.
168         loadScript("view/js/ajaxupload.js");
169         loadScript("view/theme/frio/js/module/media/browser.js", function () {
170                 Browser.init(filebrowser.dataset.nickname, filebrowser.dataset.type, match[1]);
171         });
172 };
173
174 /**
175  * Add first element with the class "heading" as modal title
176  *
177  * Note: this should be really done in the template
178  * and is the solution where we havent done it until this
179  * moment or where it isn't possible because of design
180  */
181 function loadModalTitle() {
182         // Clear the text of the title.
183         $("#modal-title").empty();
184
185         // Hide the first element with the class "heading" of the modal body.
186         $("#modal-body .heading").first().hide();
187
188         var title = "";
189
190         // Get the text of the first element with "heading" class.
191         title = $("#modal-body .heading").first().html();
192
193         // for event modals we need some speacial handling
194         if ($("#modal-body .event-wrapper .event-summary").length) {
195                 title = '<i class="fa fa-calendar" aria-hidden="true"></i>&nbsp;';
196                 var eventsum = $("#modal-body .event-wrapper .event-summary").html();
197                 title = title + eventsum;
198         }
199
200         // And append it to modal title.
201         if (title !== "") {
202                 $("#modal-title").append(title);
203         }
204 }
205
206 /**
207  * This function loads html content from a friendica page into a modal.
208  *
209  * @param {string} url The url with html content.
210  * @param {string} id The ID of a html element (can be undefined).
211  * @returns {void}
212  */
213 function addToModal(url, id) {
214         var char = qOrAmp(url);
215
216         url = url + char + "mode=none";
217         var modal = $("#modal").modal();
218
219         // Only search for an element if we have an ID.
220         if (typeof id !== "undefined") {
221                 url = url + " div#" + id;
222         }
223
224         modal.find("#modal-body").load(url, function (responseText, textStatus) {
225                 if (textStatus === "success" || textStatus === "notmodified") {
226                         modal.show();
227
228                         //Get first element with the class "heading"
229                         //and use it as title.
230                         loadModalTitle();
231
232                         // We need to initialize autosize again for new
233                         // modal conent.
234                         autosize($(".modal .text-autosize"));
235                 }
236         });
237 }
238
239 // Add an element (by its id) to a bootstrap modal.
240 function addElmToModal(id) {
241         var elm = $(id).html();
242         var modal = $("#modal").modal();
243
244         modal.find("#modal-body").append(elm).modal.show;
245
246         loadModalTitle();
247 }
248
249 // Function to load the html from the edit post page into
250 // the jot modal.
251 function editpost(url) {
252         // Next to normel posts the post can be an event post. The event posts don't
253         // use the normal Jot modal. For event posts we will use a normal modal
254         // But first we have to test if the url links to an event. So we will split up
255         // the url in its parts.
256         var splitURL = parseUrl(url);
257         // Test if in the url path containing "calendar/event/show". If the path containing this
258         // expression then we will call the addToModal function and exit this function at
259         // this point.
260         if (splitURL.path.indexOf("calendar/event/show") > -1) {
261                 addToModal(splitURL.path);
262                 return;
263         }
264
265         var modal = $("#jot-modal").modal();
266         url = url + " #jot-sections";
267
268         $(".jot-nav .jot-perms-lnk").parent("li").addClass("hidden");
269
270         // For editpost we load the modal html of "jot-sections" of the edit page. So we would have two jot forms in
271         // the page html. To avoid js conflicts we store the original jot in the variable jotcache.
272         // After closing the modal original jot should be restored at its orginal position in the html structure.
273         jotcache = $("#jot-content > #jot-sections");
274
275         // Remove the original Jot as long as the edit Jot is open.
276         jotcache.detach();
277
278         // Add the class "edit" to the modal to have some kind of identifier to
279         // have the possibility to e.g. put special event-listener.
280         $("#jot-modal").addClass("edit-jot");
281
282         jotreset();
283
284         modal.find("#jot-modal-content").load(url, function (responseText, textStatus) {
285                 if (textStatus === "success" || textStatus === "notmodified") {
286                         // get the item type and hide the input for title and category if it isn't needed.
287                         var type = $(responseText).find("#profile-jot-form input[name='type']").val();
288                         if (type === "wall-comment" || type === "remote-comment") {
289                                 // Hide title and category input fields because we don't.
290                                 $("#profile-jot-form #jot-title-wrap").hide();
291                                 $("#profile-jot-form #jot-category-wrap").hide();
292                         }
293
294                         // To make dropzone fileupload work on editing a comment, we need to
295                         // attach a new dropzone to modal
296                         dropzoneJotEdit = new Dropzone( '#jot-text-wrap', {
297                                 paramName: "userfile", // The name that will be used to transfer the file
298                                 maxFilesize: getMBytes('{{$max_imagesize}}'), // MB
299                                 url: "/media/photo/upload?response=url&album=",
300                                 accept: function(file, done) {
301                                         done();
302                                 },
303                                 init: function() {
304                                         this.on("success", function(file, serverResponse) {
305                                                 var target = $('#profile-jot-text')
306                                                 var resp = $(serverResponse).find('div#content').text()
307                                                 if (target.setRangeText) {
308                                                         //if setRangeText function is supported by current browser
309                                                         target.setRangeText(" " + $.trim(resp) + " ")
310                                                 } else {
311                                                         target.focus()
312                                                         document.execCommand('insertText', false /*no UI*/, " " + $.trim(resp) + " ");
313                                                 }
314                                         });
315                                         this.on("complete", function(file) {
316                                                 // Remove just uploaded file from dropzone, makes interface more clear.
317                                                 // Image can be seen in posting-preview
318                                                 // We need preview to get optical feedback about upload-progress.
319                                                 // you see success, when the bb-code link for image is inserted
320                                                 setTimeout(function(){
321                                                         dropzoneJotEdit.removeFile(file);
322                                                 },5000);
323                                         });
324                                 },
325                         });
326
327                         // Enables Copy&Paste for this dropzone
328                         $('#jot-text-wrap').on('paste', function(event){
329                                 const items = (event.clipboardData || event.originalEvent.clipboardData).items;
330                                 items.forEach((item) => {
331                                         if (item.kind === 'file') {
332                                                 // adds the file to your dropzone instance
333                                                 dropzoneJotEdit.addFile(item.getAsFile())
334                                         }
335                                 })
336                         })
337
338
339                         modal.show();
340                         $("#jot-popup").show();
341                         linkPreview = $("#profile-jot-text").linkPreview();
342                 }
343         });
344 }
345
346 // Remove content from the jot modal.
347 function jotreset() {
348         // Clear bs modal on close.
349         // We need this to prevent that the modal displays old content.
350         $("body").on("hidden.bs.modal", "#jot-modal.edit-jot", function () {
351                 $(this).removeData("bs.modal");
352                 $(".jot-nav .jot-perms-lnk").parent("li").removeClass("hidden");
353                 $("#profile-jot-form #jot-title-wrap").show();
354                 $("#profile-jot-form #jot-category-wrap").show();
355
356                 // Remove the "edit-jot" class so we can the standard behavior on close.
357                 $("#jot-modal.edit-jot").removeClass("edit-jot");
358                 $("#jot-modal-content").empty();
359         });
360 }
361
362 // Give the active "jot-nav" list element the class "active".
363 function toggleJotNav(elm) {
364         // Get the ID of the tab panel which should be activated.
365         var tabpanel = elm.getAttribute("aria-controls");
366         var cls = hasClass(elm, "jot-nav-lnk-mobile");
367
368         // Select all li of jot-nav and remove the active class.
369         $(elm).parent("li").siblings("li").removeClass("active");
370         // Add the active class to the parent of the link which was selected.
371         $(elm).parent("li").addClass("active");
372
373         // Minimize all tab content wrapper and activate only the selected
374         // tab panel.
375         $("#profile-jot-form > [role=tabpanel]").addClass("minimize").attr("aria-hidden", "true");
376         $("#" + tabpanel)
377                 .removeClass("minimize")
378                 .attr("aria-hidden", "false");
379
380         // Set the aria-selected states
381         $("#jot-modal .modal-header .nav-tabs .jot-nav-lnk").attr("aria-selected", "false");
382         elm.setAttribute("aria-selected", "true");
383
384         // For some some tab panels we need to execute other js functions.
385         if (tabpanel === "jot-preview-content") {
386                 preview_post();
387                 // Make Share button visivle in preview
388                 $("#jot-preview-share").removeClass("minimize").attr("aria-hidden", "false");
389         } else if (tabpanel === "jot-fbrowser-wrapper") {
390                 $(function () {
391                         Dialog.showJot();
392                 });
393         }
394
395         // If element is a mobile dropdown nav menu we need to change the botton text.
396         if (cls) {
397                 toggleDropdownText(elm);
398         }
399 }
400
401 // Wall Message needs a special handling because in some cases
402 // it redirects you to your own server. In such cases we can't
403 // load it into a modal.
404 function openWallMessage(url) {
405         // Split the the url in its parts.
406         var parts = parseUrl(url);
407
408         // If the host isn't the same we can't load it in a modal.
409         // So we will go to to the url directly.
410         if ("host" in parts && parts.host !== window.location.host) {
411                 window.location.href = url;
412         } else {
413                 // Otherwise load the wall message into a modal.
414                 addToModal(url);
415         }
416 }
417
418 // This function load the content of the edit url into a modal.
419 /// @todo Rename this function because it can be used for more than events.
420 function eventEdit(url) {
421         var char = qOrAmp(url);
422         url = url + char + "mode=none";
423
424         $.get(url, function (data) {
425                 $("#modal-body").empty();
426                 $("#modal-body").append(data);
427         }).done(function () {
428                 loadModalTitle();
429         });
430 }
431 // @license-end