]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/QnA/js/qna.js
Better QnA ajax insert - work in progress
[quix0rs-gnu-social.git] / plugins / QnA / js / qna.js
1
2 var QnA = {
3
4     // hide all the 'close' and 'best' buttons for this question
5
6     // @fixme: Should use ID
7     close: function(closeButt) {
8         notice = $(closeButt).closest('li.hentry.notice.question');
9         notice.find('input[name=best],[name=close]').hide();
10         notice.find('textarea').hide();
11         notice.find('li.notice-answer-placeholder').hide();
12         notice.find('#answer-form').hide();
13     },
14
15     init: function() {
16
17         var that = this;
18
19         QnA.NoticeInlineAnswerSetup();
20
21         $('input[name=close]').live('click', function() {
22             that.close(this);
23         });
24         $('input[name=best]').live('click', function() {
25             that.close(this);
26         });
27     },
28
29     /**
30      * Open up a question's inline answer box.
31      *
32      * @param {jQuery} notice: jQuery object containing one notice
33      */
34     NoticeInlineAnswerTrigger: function(notice) {
35         console.log('NoticeInlineAnswerTrigger - begin');
36
37         // Find the question notice we're answering...
38         var id = $($('.notice_id', notice)[0]).text();
39         console.log("parent notice id = " + id);
40         var parentNotice = notice;
41
42         // See if the form's already there...
43         var answerForm = $('#answer-form', parentNotice);
44
45         if (answerForm) {
46             console.log("Found the answer form.");
47         } else {
48             console.log("Did not find the answer form.");
49         }
50
51         var placeholder = parentNotice.find('li.notice-answer-placeholder');
52
53         // Pull the parents threaded list and we'll add on the end of it.
54         var list = $('ul.threaded-replies', notice);
55
56         if (list) {
57             console.log("Found the " + list.length + " notice place holders.");
58         } else {
59             console.log("Found the notice answer placeholder");
60         }
61
62         if (list.length == 0) {
63             console.log("list length = 0 adding <ul>");
64             list = $('<ul class="notices threaded-replies xoxo"></ul>');
65             notice.append(list);
66         } else if (list.length == 2) {
67             // remove duplicate ul added by util.js
68             list.last().remove();
69         }
70
71         var answerItem = $('li.notice-answer', list);
72
73         var nextStep = function() {
74             console.log("nextStep - enter");
75
76             // Set focus...
77             var text = answerForm.find('textarea');
78
79             if (text.length == 0) {
80                 throw "No textarea";
81             }
82
83             $('body').click(function(e) {
84                 console.log("got click");
85
86                 var openAnswers = $('li.notice-answer');
87                     if (openAnswers.length > 0) {
88                         console.log("Found and open answer to close");
89                         var target = $(e.target);
90                         openAnswers.each(function() {
91                             console.log("found an open answer");
92                             // Did we click outside this one?
93                             var answerItem = $(this);
94                             if (answerItem.has(e.target).length == 0) {
95                                 var textarea = answerItem.find('.notice_data-text:first');
96                                 var cur = $.trim(textarea.val());
97                                 // Only close if there's been no edit.
98                                 if (cur == '' || cur == textarea.data('initialText')) {
99                                     var parentNotice = answerItem.closest('li.notice');
100                                     answerItem.remove();
101                                     parentNotice.find('li.notice-answer-placeholder').show();
102                                 }
103                             }
104                         });
105                     }
106                 });
107
108             text.focus();
109             console.log('finished dealing with body click');
110         };
111
112         placeholder.hide();
113
114         if (answerItem.length > 0) {
115             console.log('answerItem length > 0');
116             // Update the existing form...
117             nextStep();
118         } else {
119
120              // Create the answer form entry at the end
121
122              if (answerItem.length == 0) {
123                  console.log("QQQQQ no notice-answer li");
124                  answerItem = $('<li class="notice-answer"></li>');
125
126                  var intermediateStep = function(formMaster) {
127                      console.log("Intermediate step");
128                      var formEl = document._importNode(formMaster, true);
129                      answerItem.append(formEl);
130                      console.log("appending answerItem");
131                      list.append(answerItem); // *after* the placeholder
132                      console.log("appended answerItem");
133                      console.log(answerItem);
134                      var form = answerForm = $(formEl);
135                      QnA.AnswerFormSetup(form);
136
137                      nextStep();
138                  };
139
140                  if (QnA.AnswerFormMaster) {
141                      // We've already saved a master copy of the form.
142                      // Clone it in!
143                      intermediateStep(QnA.AnswerFormMaster);
144                  } else {
145                      // Fetch a fresh copy of the answer form over AJAX.
146                      // Warning: this can have a delay, which looks bad.
147                      // @fixme this fallback may or may not work
148                      var url = $('#answer-action').attr('value');
149
150                      console.log("fetching new form via HXR");
151
152                      $.get(url, {ajax: 1}, function(data, textStatus, xhr) {
153                          intermediateStep($('form', data)[0]);
154                      });
155                  }
156              }
157          }
158          console.log('NoticeInlineAnswerTrigger - exit');
159
160      },
161
162     /**
163      * Setup function -- DOES NOT apply immediately.
164      *
165      * Sets up event handlers for inline reply mini-form placeholders.
166      * Uses 'live' rather than 'bind', so applies to future as well as present items.
167      */
168     NoticeInlineAnswerSetup: function() {
169         console.log("NoticeInlineAnswerSetup - begin");
170         $('li.notice-answer-placeholder input.placeholder')
171             .live('focus', function() {
172                 var notice = $(this).closest('li.notice');
173                 QnA.NoticeInlineAnswerTrigger(notice);
174                 return false;
175             });
176         console.log("NoticeInlineAnswerSetup - exit");
177     },
178
179     AnswerFormSetup: function(form) {
180         console.log("AnswerFormSetup");
181         $('input[type=submit]').live('click', function() {
182             console.log("AnswerFormSetup click");
183             QnA.FormAnswerXHR(form);
184         });
185     },
186
187
188    /**
189      * Setup function -- DOES NOT trigger actions immediately.
190      *
191      * Sets up event handlers for special-cased async submission of the
192      * notice-posting form, including some pre-post validation.
193      *
194      * Unlike FormXHR() this does NOT submit the form immediately!
195      * It sets up event handlers so that any method of submitting the
196      * form (click on submit button, enter, submit() etc) will trigger
197      * it properly.
198      *
199      * Also unlike FormXHR(), this system will use a hidden iframe
200      * automatically to handle file uploads via <input type="file">
201      * controls.
202      *
203      * @fixme tl;dr
204      * @fixme vast swaths of duplicate code and really long variable names clutter this function up real bad
205      * @fixme error handling is unreliable
206      * @fixme cookieValue is a global variable, but probably shouldn't be
207      * @fixme saving the location cache cookies should be split out
208      * @fixme some error messages are hardcoded english: needs i18n
209      * @fixme special-case for bookmarklet is confusing and uses a global var "self". Is this ok?
210      *
211      * @param {jQuery} form: jQuery object whose first element is a form
212      *
213      * @access public
214      */
215     FormAnswerXHR: function(form) {
216         console.log("FormAanwerXHR - begin");
217         //SN.C.I.NoticeDataGeo = {};
218         form.append('<input type="hidden" name="ajax" value="1"/>');
219         console.log("appended ajax flag");
220
221         // Make sure we don't have a mixed HTTP/HTTPS submission...
222         form.attr('action', SN.U.RewriteAjaxAction(form.attr('action')));
223         console.log("rewrote action");
224
225         /**
226          * Show a response feedback bit under the new-notice dialog.
227          *
228          * @param {String} cls: CSS class name to use ('error' or 'success')
229          * @param {String} text
230          * @access private
231          */
232         var showFeedback = function(cls, text) {
233             form.append(
234                 $('<p class="form_response"></p>')
235                     .addClass(cls)
236                     .text(text)
237             );
238         };
239
240         /**
241          * Hide the previous response feedback, if any.
242          */
243         var removeFeedback = function() {
244             form.find('.form_response').remove();
245         };
246
247         console.log("doing ajax");
248
249         form.ajaxForm({
250             dataType: 'xml',
251             timeout: '60000',
252             beforeSend: function(formData) {
253                 console.log("beforeSend");
254                 if (form.find('.notice_data-text:first').val() == '') {
255                     form.addClass(SN.C.S.Warning);
256                     return false;
257                 }
258                 form
259                     .addClass(SN.C.S.Processing)
260                     .find('.submit')
261                         .addClass(SN.C.S.Disabled)
262                         .attr(SN.C.S.Disabled, SN.C.S.Disabled);
263
264                 SN.U.normalizeGeoData(form);
265
266                 return true;
267             },
268             error: function (xhr, textStatus, errorThrown) {
269                 form
270                     .removeClass(SN.C.S.Processing)
271                     .find('.submit')
272                         .removeClass(SN.C.S.Disabled)
273                         .removeAttr(SN.C.S.Disabled, SN.C.S.Disabled);
274                 removeFeedback();
275                 if (textStatus == 'timeout') {
276                     // @fixme i18n
277                     showFeedback('error', 'Sorry! We had trouble sending your notice. The servers are overloaded. Please try again, and contact the site administrator if this problem persists.');
278                 }
279                 else {
280                     var response = SN.U.GetResponseXML(xhr);
281                     if ($('.'+SN.C.S.Error, response).length > 0) {
282                         form.append(document._importNode($('.'+SN.C.S.Error, response)[0], true));
283                     }
284                     else {
285                         if (parseInt(xhr.status) === 0 || jQuery.inArray(parseInt(xhr.status), SN.C.I.HTTP20x30x) >= 0) {
286                             form
287                                 .resetForm()
288                                 .find('.attach-status').remove();
289                             SN.U.FormNoticeEnhancements(form);
290                         }
291                         else {
292                             // @fixme i18n
293                             showFeedback('error', '(Sorry! We had trouble sending your notice ('+xhr.status+' '+xhr.statusText+'). Please report the problem to the site administrator if this happens again.');
294                         }
295                     }
296                 }
297             },
298             success: function(data, textStatus) {
299                 console.log("FormAnswerHXR success");
300                 removeFeedback();
301                 var errorResult = $('#'+SN.C.S.Error, data);
302                 if (errorResult.length > 0) {
303                     showFeedback('error', errorResult.text());
304                 }
305                 else {
306
307                     // New notice post was successful. If on our timeline, show it!
308                     var notice = document._importNode($('li', data)[0], true);
309
310                     var notices = $('#notices_primary .notices:first');
311                     var replyItem = form.closest('li.notice-reply');
312
313                     if (replyItem.length > 0) {
314                         console.log("I found a reply li to append to");
315                         // If this is an inline reply, remove the form...
316                         var list = form.closest('.threaded-replies');
317                         var placeholder = list.find('.notice-answer-placeholder');
318                         replyItem.remove();
319
320                         var id = $(notice).attr('id');
321                         console.log("got notice id " + id);
322                         if ($("#"+id).length == 0) {
323                             console.log("inserting before placeholder");
324                             $(notice).insertBefore(placeholder);
325                         } else {
326                             // Realtime came through before us...
327                         }
328
329                         // ...and show the placeholder form.
330                         placeholder.show();
331                         console.log('qqqq made it this far')
332                     } else if (notices.length > 0 && SN.U.belongsOnTimeline(notice)) {
333                         // Not a reply. If on our timeline, show it at the top!
334                         if ($('#'+notice.id).length === 0) {
335                             console.log("couldn't find a notice id for " + notice.id);
336                             var notice_irt_value = form.find('#inreplyto').val();
337                             var notice_irt = '#notices_primary #notice-'+notice_irt_value;
338                             console.log("notice_irt value = " + notice_irt_value);
339                             if($('body')[0].id == 'conversation') {
340                                 console.log("found conversation");
341                                 if(notice_irt_value.length > 0 && $(notice_irt+' .notices').length < 1) {
342                                     $(notice_irt).append('<ul class="notices"></ul>');
343                                 }
344                                 $($(notice_irt+' .notices')[0]).append(notice);
345                             }
346                             else {
347                                 console.log("prepending notice")
348                                 notices.prepend(notice);
349                             }
350                             $('#'+notice.id)
351                                 .css({display:'none'})
352                                 .fadeIn(2500);
353                         }
354                     } else {
355                         // Not on a timeline that this belongs on?
356                         // Just show a success message.
357                         // @fixme inline
358                         showFeedback('success', $('title', data).text());
359                     }
360
361                     //form.resetForm();
362                     //SN.U.FormNoticeEnhancements(form);
363                 }
364             },
365             complete: function(xhr, textStatus) {
366                 form
367                     .removeClass(SN.C.S.Processing)
368                     .find('.submit')
369                         .removeAttr(SN.C.S.Disabled)
370                         .removeClass(SN.C.S.Disabled);
371
372                 form.find('[name=lat]').val(SN.C.I.NoticeDataGeo.NLat);
373                 form.find('[name=lon]').val(SN.C.I.NoticeDataGeo.NLon);
374                 form.find('[name=location_ns]').val(SN.C.I.NoticeDataGeo.NLNS);
375                 form.find('[name=location_id]').val(SN.C.I.NoticeDataGeo.NLID);
376                 form.find('[name=notice_data-geo]').attr('checked', SN.C.I.NoticeDataGeo.NDG);
377             }
378         });
379     }
380
381 };
382
383 $(document).ready(function() {
384     QnA.init();
385 });