util.js 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682
  1. /*
  2. * StatusNet - a distributed open-source microblogging tool
  3. * Copyright (C) 2008, StatusNet, Inc.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * @category UI interaction
  19. * @package StatusNet
  20. * @author Sarven Capadisli <csarven@status.net>
  21. * @author Evan Prodromou <evan@status.net>
  22. * @author Brion Vibber <brion@status.net>
  23. * @copyright 2009,2010 StatusNet, Inc.
  24. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
  25. * @link http://status.net/
  26. */
  27. var SN = { // StatusNet
  28. C: { // Config
  29. I: { // Init
  30. CounterBlackout: false,
  31. MaxLength: 140,
  32. PatternUsername: /^[0-9a-zA-Z\-_.]*$/,
  33. HTTP20x30x: [200, 201, 202, 203, 204, 205, 206, 300, 301, 302, 303, 304, 305, 306, 307],
  34. },
  35. /**
  36. * @fixme are these worth the trouble? They seem to mostly just duplicate
  37. * themselves while slightly obscuring the actual selector, so it's hard
  38. * to pop over to the HTML and find something.
  39. *
  40. * In theory, minification could reduce them to shorter variable names,
  41. * but at present that doesn't happen with yui-compressor.
  42. */
  43. S: { // Selector
  44. Disabled: 'disabled',
  45. Warning: 'warning',
  46. Error: 'error',
  47. Success: 'success',
  48. Processing: 'processing',
  49. CommandResult: 'command_result',
  50. FormNotice: 'form_notice',
  51. NoticeDataGeo: 'notice_data-geo',
  52. NoticeDataGeoCookie: 'NoticeDataGeo',
  53. NoticeDataGeoSelected: 'notice_data-geo_selected',
  54. }
  55. },
  56. V: { // Variables
  57. },
  58. /**
  59. * list of callbacks, categorized into _callbacks['event_name'] = [ callback_function_1, callback_function_2 ]
  60. *
  61. * @access private
  62. */
  63. _callbacks: {},
  64. /**
  65. * Map of localized message strings exported to script from the PHP
  66. * side via Action::getScriptMessages().
  67. *
  68. * Retrieve them via SN.msg(); this array is an implementation detail.
  69. *
  70. * @access private
  71. */
  72. messages: {},
  73. /**
  74. * Grabs a localized string that's been previously exported to us
  75. * from server-side code via Action::getScriptMessages().
  76. *
  77. * @example alert(SN.msg('coolplugin-failed'));
  78. *
  79. * @param {String} key: string key name to pull from message index
  80. * @return matching localized message string
  81. */
  82. msg: function (key) {
  83. if (SN.messages[key] === undefined) {
  84. return '[' + key + ']';
  85. }
  86. return SN.messages[key];
  87. },
  88. U: { // Utils
  89. /**
  90. * Setup function -- DOES NOT trigger actions immediately.
  91. *
  92. * Sets up event handlers on the new notice form.
  93. *
  94. * @param {jQuery} form: jQuery object whose first matching element is the form
  95. * @access private
  96. */
  97. FormNoticeEnhancements: function (form) {
  98. if ($.data(form[0], 'ElementData') === undefined) {
  99. var MaxLength = form.find('.count').text();
  100. if (MaxLength === undefined) {
  101. MaxLength = SN.C.I.MaxLength;
  102. }
  103. $.data(form[0], 'ElementData', {MaxLength: MaxLength});
  104. SN.U.Counter(form);
  105. var NDT = form.find('.notice_data-text:first');
  106. NDT.on('keyup', function (e) {
  107. SN.U.Counter(form);
  108. });
  109. var delayedUpdate = function (e) {
  110. // Cut and paste events fire *before* the operation,
  111. // so we need to trigger an update in a little bit.
  112. // This would be so much easier if the 'change' event
  113. // actually fired every time the value changed. :P
  114. window.setTimeout(function () {
  115. SN.U.Counter(form);
  116. }, 50);
  117. };
  118. // Note there's still no event for mouse-triggered 'delete'.
  119. NDT.on('cut', delayedUpdate)
  120. .on('paste', delayedUpdate);
  121. } else {
  122. form.find('.count').text($.data(form[0], 'ElementData').MaxLength);
  123. }
  124. },
  125. /**
  126. * To be called from event handlers on the notice import form.
  127. * Triggers an update of the remaining-characters counter.
  128. *
  129. * Additional counter updates will be suppressed during the
  130. * next half-second to avoid flooding the layout engine with
  131. * updates, followed by another automatic check.
  132. *
  133. * The maximum length is pulled from data established by
  134. * FormNoticeEnhancements.
  135. *
  136. * @param {jQuery} form: jQuery object whose first element is the notice posting form
  137. * @access private
  138. */
  139. Counter: function (form) {
  140. SN.C.I.FormNoticeCurrent = form;
  141. var MaxLength = $.data(form[0], 'ElementData').MaxLength;
  142. if (MaxLength <= 0) {
  143. return;
  144. }
  145. var remaining = MaxLength - SN.U.CharacterCount(form);
  146. var counter = form.find('.count');
  147. if (remaining.toString() != counter.text()) {
  148. if (!SN.C.I.CounterBlackout || remaining === 0) {
  149. if (counter.text() != String(remaining)) {
  150. counter.text(remaining);
  151. }
  152. if (remaining < 0) {
  153. form.addClass(SN.C.S.Warning);
  154. } else {
  155. form.removeClass(SN.C.S.Warning);
  156. }
  157. // Skip updates for the next 500ms.
  158. // On slower hardware, updating on every keypress is unpleasant.
  159. if (!SN.C.I.CounterBlackout) {
  160. SN.C.I.CounterBlackout = true;
  161. SN.C.I.FormNoticeCurrent = form;
  162. window.setTimeout("SN.U.ClearCounterBlackout(SN.C.I.FormNoticeCurrent);", 500);
  163. }
  164. }
  165. }
  166. },
  167. /**
  168. * Pull the count of characters in the current edit field.
  169. * Plugins replacing the edit control may need to override this.
  170. *
  171. * @param {jQuery} form: jQuery object whose first element is the notice posting form
  172. * @return number of chars
  173. */
  174. CharacterCount: function (form) {
  175. return form.find('.notice_data-text:first').val().length;
  176. },
  177. /**
  178. * Called internally after the counter update blackout period expires;
  179. * runs another update to make sure we didn't miss anything.
  180. *
  181. * @param {jQuery} form: jQuery object whose first element is the notice posting form
  182. * @access private
  183. */
  184. ClearCounterBlackout: function (form) {
  185. // Allow keyup events to poke the counter again
  186. SN.C.I.CounterBlackout = false;
  187. // Check if the string changed since we last looked
  188. SN.U.Counter(form);
  189. },
  190. /**
  191. * Helper function to rewrite default HTTP form action URLs to HTTPS
  192. * so we can actually fetch them when on an SSL page in ssl=sometimes
  193. * mode.
  194. *
  195. * It would be better to output URLs that didn't hardcode protocol
  196. * and hostname in the first place...
  197. *
  198. * @param {String} url
  199. * @return string
  200. */
  201. RewriteAjaxAction: function (url) {
  202. // Quick hack: rewrite AJAX submits to HTTPS if they'd fail otherwise.
  203. if (document.location.protocol === 'https:' && url.substr(0, 5) === 'http:') {
  204. return url.replace(/^http:\/\/[^:\/]+/, 'https://' + document.location.host);
  205. }
  206. return url;
  207. },
  208. FormNoticeUniqueID: function (form) {
  209. var oldId = form.attr('id');
  210. var newId = 'form_notice_' + Math.floor(Math.random()*999999999);
  211. var attrs = ['name', 'for', 'id'];
  212. for (var key in attrs) {
  213. if (form.attr(attrs[key]) === undefined) {
  214. continue;
  215. }
  216. form.attr(attrs[key], form.attr(attrs[key]).replace(oldId, newId));
  217. }
  218. for (var key in attrs) {
  219. form.find("[" + attrs[key] + "*='" + oldId + "']").each(function () {
  220. if ($(this).attr(attrs[key]) === undefined) {
  221. return; // since we're inside the each(function () { ... });
  222. }
  223. var newAttr = $(this).attr(attrs[key]).replace(oldId, newId);
  224. $(this).attr(attrs[key], newAttr);
  225. });
  226. }
  227. },
  228. /**
  229. * Grabs form data and submits it asynchronously, with 'ajax=1'
  230. * parameter added to the rest.
  231. *
  232. * If a successful response includes another form, that form
  233. * will be extracted and copied in, replacing the original form.
  234. * If there's no form, the first paragraph will be used.
  235. *
  236. * This will automatically be applied on the 'submit' event for
  237. * any form with the 'ajax' class.
  238. *
  239. * @fixme can sometimes explode confusingly if returnd data is bogus
  240. * @fixme error handling is pretty vague
  241. * @fixme can't submit file uploads
  242. *
  243. * @param {jQuery} form: jQuery object whose first element is a form
  244. * @param function onSuccess: something extra to do on success
  245. *
  246. * @access public
  247. */
  248. FormXHR: function (form, onSuccess) {
  249. $.ajax({
  250. type: 'POST',
  251. dataType: 'xml',
  252. url: SN.U.RewriteAjaxAction(form.attr('action')),
  253. data: form.serialize() + '&ajax=1',
  254. beforeSend: function (xhr) {
  255. form
  256. .addClass(SN.C.S.Processing)
  257. .find('.submit')
  258. .addClass(SN.C.S.Disabled)
  259. .prop(SN.C.S.Disabled, true);
  260. },
  261. error: function (xhr, textStatus, errorThrown) {
  262. // If the server end reported an error from StatusNet,
  263. // find it -- otherwise we'll see what was reported
  264. // from the browser.
  265. var errorReported = null;
  266. if (xhr.responseXML) {
  267. errorReported = $('#error', xhr.responseXML).text();
  268. }
  269. window.alert(errorReported || errorThrown || textStatus);
  270. // Restore the form to original state.
  271. // Hopefully. :D
  272. form
  273. .removeClass(SN.C.S.Processing)
  274. .find('.submit')
  275. .removeClass(SN.C.S.Disabled)
  276. .prop(SN.C.S.Disabled, false);
  277. },
  278. success: function (data, textStatus) {
  279. if ($('form', data)[0] !== undefined) {
  280. var form_new = document._importNode($('form', data)[0], true);
  281. form.replaceWith(form_new);
  282. if (onSuccess) {
  283. onSuccess();
  284. }
  285. } else if ($('p', data)[0] !== undefined) {
  286. form.replaceWith(document._importNode($('p', data)[0], true));
  287. if (onSuccess) {
  288. onSuccess();
  289. }
  290. } else {
  291. window.alert('Unknown error.');
  292. }
  293. }
  294. });
  295. },
  296. /**
  297. * Setup function -- DOES NOT trigger actions immediately.
  298. *
  299. * Sets up event handlers for special-cased async submission of the
  300. * notice-posting form, including some pre-post validation.
  301. *
  302. * Unlike FormXHR() this does NOT submit the form immediately!
  303. * It sets up event handlers so that any method of submitting the
  304. * form (click on submit button, enter, submit() etc) will trigger
  305. * it properly.
  306. *
  307. * Also unlike FormXHR(), this system will use a hidden iframe
  308. * automatically to handle file uploads via <input type="file">
  309. * controls.
  310. *
  311. * @fixme tl;dr
  312. * @fixme vast swaths of duplicate code and really long variable names clutter this function up real bad
  313. * @fixme error handling is unreliable
  314. * @fixme cookieValue is a global variable, but probably shouldn't be
  315. * @fixme saving the location cache cookies should be split out
  316. * @fixme some error messages are hardcoded english: needs i18n
  317. *
  318. * @param {jQuery} form: jQuery object whose first element is a form
  319. *
  320. * @access public
  321. */
  322. FormNoticeXHR: function (form) {
  323. SN.C.I.NoticeDataGeo = {};
  324. form.append('<input type="hidden" name="ajax" value="1"/>');
  325. // Make sure we don't have a mixed HTTP/HTTPS submission...
  326. form.attr('action', SN.U.RewriteAjaxAction(form.attr('action')));
  327. /**
  328. * Hide the previous response feedback, if any.
  329. */
  330. var removeFeedback = function () {
  331. form.find('.form_response').remove();
  332. };
  333. form.ajaxForm({
  334. dataType: 'xml',
  335. timeout: '60000',
  336. beforeSend: function (formData) {
  337. if (form.find('.notice_data-text:first').val() == '') {
  338. form.addClass(SN.C.S.Warning);
  339. return false;
  340. }
  341. form
  342. .addClass(SN.C.S.Processing)
  343. .find('.submit')
  344. .addClass(SN.C.S.Disabled)
  345. .prop(SN.C.S.Disabled, true);
  346. SN.U.normalizeGeoData(form);
  347. return true;
  348. },
  349. error: function (xhr, textStatus, errorThrown) {
  350. form
  351. .removeClass(SN.C.S.Processing)
  352. .find('.submit')
  353. .removeClass(SN.C.S.Disabled)
  354. .prop(SN.C.S.Disabled, false);
  355. removeFeedback();
  356. if (textStatus == 'timeout') {
  357. // @fixme i18n
  358. SN.U.showFeedback(form, 'error', 'Sorry! We had trouble sending your notice. The servers are overloaded. Please try again, and contact the site administrator if this problem persists.');
  359. } else {
  360. var response = SN.U.GetResponseXML(xhr);
  361. if ($('.' + SN.C.S.Error, response).length > 0) {
  362. form.append(document._importNode($('.' + SN.C.S.Error, response)[0], true));
  363. } else {
  364. if (parseInt(xhr.status) === 0 || $.inArray(parseInt(xhr.status), SN.C.I.HTTP20x30x) >= 0) {
  365. form
  366. .resetForm()
  367. .find('.attach-status').remove();
  368. SN.U.FormNoticeEnhancements(form);
  369. } else {
  370. // @fixme i18n
  371. SN.U.showFeedback(form, 'error', '(Sorry! We had trouble sending your notice (' + xhr.status + ' ' + xhr.statusText + '). Please report the problem to the site administrator if this happens again.');
  372. }
  373. }
  374. }
  375. },
  376. success: function (data, textStatus) {
  377. removeFeedback();
  378. var errorResult = $('#' + SN.C.S.Error, data);
  379. if (errorResult.length > 0) {
  380. SN.U.showFeedback(form, 'error', errorResult.text());
  381. } else {
  382. SN.E.ajaxNoticePosted(form, data, textStatus);
  383. }
  384. },
  385. complete: function (xhr, textStatus) {
  386. form
  387. .removeClass(SN.C.S.Processing)
  388. .find('.submit')
  389. .prop(SN.C.S.Disabled, false)
  390. .removeClass(SN.C.S.Disabled);
  391. form.find('[name=lat]').val(SN.C.I.NoticeDataGeo.NLat);
  392. form.find('[name=lon]').val(SN.C.I.NoticeDataGeo.NLon);
  393. form.find('[name=location_ns]').val(SN.C.I.NoticeDataGeo.NLNS);
  394. form.find('[name=location_id]').val(SN.C.I.NoticeDataGeo.NLID);
  395. form.find('[name=notice_data-geo]').prop('checked', SN.C.I.NoticeDataGeo.NDG);
  396. }
  397. });
  398. },
  399. FormProfileSearchXHR: function (form) {
  400. $.ajax({
  401. type: 'POST',
  402. dataType: 'xml',
  403. url: form.attr('action'),
  404. data: form.serialize() + '&ajax=1',
  405. beforeSend: function (xhr) {
  406. form
  407. .addClass(SN.C.S.Processing)
  408. .find('.submit')
  409. .addClass(SN.C.S.Disabled)
  410. .prop(SN.C.S.Disabled, true);
  411. },
  412. error: function (xhr, textStatus, errorThrown) {
  413. window.alert(errorThrown || textStatus);
  414. },
  415. success: function (data, textStatus) {
  416. var results_placeholder = $('#profile_search_results');
  417. if ($('ul', data)[0] !== undefined) {
  418. var list = document._importNode($('ul', data)[0], true);
  419. results_placeholder.replaceWith(list);
  420. } else {
  421. var _error = $('<li/>').append(document._importNode($('p', data)[0], true));
  422. results_placeholder.html(_error);
  423. }
  424. form
  425. .removeClass(SN.C.S.Processing)
  426. .find('.submit')
  427. .removeClass(SN.C.S.Disabled)
  428. .prop(SN.C.S.Disabled, false);
  429. }
  430. });
  431. },
  432. FormPeopletagsXHR: function (form) {
  433. $.ajax({
  434. type: 'POST',
  435. dataType: 'xml',
  436. url: form.attr('action'),
  437. data: form.serialize() + '&ajax=1',
  438. beforeSend: function (xhr) {
  439. form.find('.submit')
  440. .addClass(SN.C.S.Processing)
  441. .addClass(SN.C.S.Disabled)
  442. .prop(SN.C.S.Disabled, true);
  443. },
  444. error: function (xhr, textStatus, errorThrown) {
  445. window.alert(errorThrown || textStatus);
  446. },
  447. success: function (data, textStatus) {
  448. var results_placeholder = form.parents('.entity_tags');
  449. if ($('.entity_tags', data)[0] !== undefined) {
  450. var tags = document._importNode($('.entity_tags', data)[0], true);
  451. $(tags).find('.editable').append($('<button class="peopletags_edit_button"/>'));
  452. results_placeholder.replaceWith(tags);
  453. } else {
  454. results_placeholder.find('p').remove();
  455. results_placeholder.append(document._importNode($('p', data)[0], true));
  456. form.removeClass(SN.C.S.Processing)
  457. .find('.submit')
  458. .removeClass(SN.C.S.Disabled)
  459. .prop(SN.C.S.Disabled, false);
  460. }
  461. }
  462. });
  463. },
  464. normalizeGeoData: function (form) {
  465. SN.C.I.NoticeDataGeo.NLat = form.find('[name=lat]').val();
  466. SN.C.I.NoticeDataGeo.NLon = form.find('[name=lon]').val();
  467. SN.C.I.NoticeDataGeo.NLNS = form.find('[name=location_ns]').val();
  468. SN.C.I.NoticeDataGeo.NLID = form.find('[name=location_id]').val();
  469. SN.C.I.NoticeDataGeo.NDG = form.find('[name=notice_data-geo]').prop('checked'); // @fixme (does this still need to be fixed somehow?)
  470. var cookieValue = $.cookie(SN.C.S.NoticeDataGeoCookie);
  471. if (cookieValue !== undefined && cookieValue != 'disabled') {
  472. cookieValue = JSON.parse(cookieValue);
  473. SN.C.I.NoticeDataGeo.NLat = form.find('[name=lat]').val(cookieValue.NLat).val();
  474. SN.C.I.NoticeDataGeo.NLon = form.find('[name=lon]').val(cookieValue.NLon).val();
  475. if (cookieValue.NLNS) {
  476. SN.C.I.NoticeDataGeo.NLNS = form.find('[name=location_ns]').val(cookieValue.NLNS).val();
  477. SN.C.I.NoticeDataGeo.NLID = form.find('[name=location_id]').val(cookieValue.NLID).val();
  478. } else {
  479. form.find('[name=location_ns]').val('');
  480. form.find('[name=location_id]').val('');
  481. }
  482. }
  483. if (cookieValue == 'disabled') {
  484. SN.C.I.NoticeDataGeo.NDG = form.find('[name=notice_data-geo]').prop('checked', false).prop('checked');
  485. } else {
  486. SN.C.I.NoticeDataGeo.NDG = form.find('[name=notice_data-geo]').prop('checked', true).prop('checked');
  487. }
  488. },
  489. /**
  490. * Fetch an XML DOM from an XHR's response data.
  491. *
  492. * Works around unavailable responseXML when document.domain
  493. * has been modified by Meteor or other tools, in some but not
  494. * all browsers.
  495. *
  496. * @param {XMLHTTPRequest} xhr
  497. * @return DOMDocument
  498. */
  499. GetResponseXML: function (xhr) {
  500. try {
  501. return xhr.responseXML;
  502. } catch (e) {
  503. return (new DOMParser()).parseFromString(xhr.responseText, "text/xml");
  504. }
  505. },
  506. /**
  507. * Setup function -- DOES NOT trigger actions immediately.
  508. *
  509. * Sets up event handlers on all visible notice's option <a> elements
  510. * with the "popup" class so they behave as expected with AJAX.
  511. *
  512. * (without javascript the link goes to a page that expects you to verify
  513. * the action through a form)
  514. *
  515. * @access private
  516. */
  517. NoticeOptionsAjax: function () {
  518. $(document).on('click', '.notice-options > a.popup', function (e) {
  519. e.preventDefault();
  520. var noticeEl = $(this).closest('.notice');
  521. $.ajax({
  522. url: $(this).attr('href'),
  523. data: {ajax: 1},
  524. success: function (data, textStatus, xhr) {
  525. SN.U.NoticeOptionPopup(data, noticeEl);
  526. },
  527. });
  528. return false;
  529. });
  530. },
  531. NoticeOptionPopup: function (data, noticeEl) {
  532. title = $('head > title', data).text();
  533. body = $('body', data).html();
  534. dialog = $(body).dialog({
  535. height: "auto",
  536. width: "auto",
  537. modal: true,
  538. resizable: true,
  539. title: title,
  540. });
  541. },
  542. /**
  543. * Setup function -- DOES NOT trigger actions immediately.
  544. *
  545. * Sets up event handlers on all visible notice's reply buttons to
  546. * tweak the new-notice form with needed variables and focus it
  547. * when pushed.
  548. *
  549. * (This replaces the default reply button behavior to submit
  550. * directly to a form which comes back with a specialized page
  551. * with the form data prefilled.)
  552. *
  553. * @access private
  554. */
  555. NoticeReply: function () {
  556. $(document).on('click', '#content .notice_reply', function (e) {
  557. e.preventDefault();
  558. var notice = $(this).closest('li.notice');
  559. SN.U.NoticeInlineReplyTrigger(notice);
  560. return false;
  561. });
  562. },
  563. /**
  564. * Stub -- kept for compat with plugins for now.
  565. * @access private
  566. */
  567. NoticeReplyTo: function (notice) {
  568. },
  569. /**
  570. * Open up a notice's inline reply box.
  571. *
  572. * @param {jQuery} notice: jQuery object containing one notice
  573. * @param {String} initialText
  574. */
  575. NoticeInlineReplyTrigger: function (notice, initialText) {
  576. // Find the notice we're replying to...
  577. var id = $($('.notice_id', notice)[0]).text();
  578. var replyForm;
  579. var parentNotice = notice;
  580. var stripForm = true; // strip a couple things out of reply forms that are inline
  581. var list = notice.find('.threaded-replies');
  582. if (list.length == 0) {
  583. list = notice.closest('.threaded-replies');
  584. }
  585. if (list.length == 0) {
  586. list = $('<ul class="notices threaded-replies xoxo"></ul>');
  587. notice.append(list);
  588. list = notice.find('.threaded-replies');
  589. }
  590. var nextStep = function () {
  591. // Override...?
  592. replyForm.find('input[name=inreplyto]').val(id);
  593. if (stripForm) {
  594. // Don't do this for old-school reply form, as they don't come back!
  595. replyForm.find('#notice_to').prop('disabled', true).hide();
  596. replyForm.find('#notice_private').prop('disabled', true).hide();
  597. replyForm.find('label[for=notice_to]').hide();
  598. replyForm.find('label[for=notice_private]').hide();
  599. }
  600. replyItem.show();
  601. // Set focus...
  602. var text = replyForm.find('textarea');
  603. if (text.length == 0) {
  604. throw "No textarea";
  605. }
  606. var replyto = '';
  607. if (initialText) {
  608. replyto = initialText + ' ';
  609. }
  610. text.val(replyto + text.val().replace(new RegExp(replyto, 'i'), ''));
  611. text.data('initialText', $.trim(initialText));
  612. text.focus();
  613. if (text[0].setSelectionRange) {
  614. var len = text.val().length;
  615. text[0].setSelectionRange(len, len);
  616. }
  617. };
  618. // Create the reply form entry
  619. var replyItem = $('li.notice-reply', list);
  620. if (replyItem.length == 0) {
  621. replyItem = $('<li class="notice-reply"></li>');
  622. }
  623. replyForm = replyItem.children('form');
  624. if (replyForm.length == 0) {
  625. // Let's try another trick to avoid fetching by URL
  626. var noticeForm = $('#input_form_status > form');
  627. if (noticeForm.length == 0) {
  628. // No notice form found on the page, so let's just
  629. // fetch a fresh copy of the notice form over AJAX.
  630. $.ajax({
  631. url: SN.V.urlNewNotice,
  632. data: {ajax: 1, inreplyto: id},
  633. success: function (data, textStatus, xhr) {
  634. var formEl = document._importNode($('form', data)[0], true);
  635. replyForm = $(formEl);
  636. replyItem.append(replyForm);
  637. list.append(replyItem);
  638. SN.Init.NoticeFormSetup(replyForm);
  639. nextStep();
  640. },
  641. });
  642. // We do everything relevant in 'success' above
  643. return;
  644. }
  645. replyForm = noticeForm.clone();
  646. SN.Init.NoticeFormSetup(replyForm);
  647. replyItem.append(replyForm);
  648. list.append(replyItem);
  649. }
  650. // replyForm is set, we're not fetching by URL...
  651. // Next setp is to configure in-reply-to etc.
  652. nextStep();
  653. },
  654. /**
  655. * Setup function -- DOES NOT apply immediately.
  656. *
  657. * Uses 'on' rather than 'live' or 'bind', so applies to future as well as present items.
  658. */
  659. NoticeInlineReplySetup: function () {
  660. // Expand conversation links
  661. $(document).on('click', 'li.notice-reply-comments a', function () {
  662. var url = $(this).attr('href');
  663. var area = $(this).closest('.threaded-replies');
  664. $.ajax({
  665. url: url,
  666. data: {ajax: 1},
  667. success: function (data, textStatus, xhr) {
  668. var replies = $('.threaded-replies', data);
  669. if (replies.length) {
  670. area.replaceWith(document._importNode(replies[0], true));
  671. }
  672. },
  673. });
  674. return false;
  675. });
  676. },
  677. /**
  678. * Setup function -- DOES NOT trigger actions immediately.
  679. *
  680. * Sets up event handlers for repeat forms to toss up a confirmation
  681. * popout before submitting.
  682. *
  683. * Uses 'on' rather than 'live' or 'bind', so applies to future as well as present items.
  684. *
  685. */
  686. NoticeRepeat: function () {
  687. $('body').on('click', '.form_repeat', function (e) {
  688. e.preventDefault();
  689. SN.U.NoticeRepeatConfirmation($(this));
  690. return false;
  691. });
  692. },
  693. /**
  694. * Shows a confirmation dialog box variant of the repeat button form.
  695. * This seems to use a technique where the repeat form contains
  696. * _both_ a standalone button _and_ text and buttons for a dialog.
  697. * The dialog will close after its copy of the form is submitted,
  698. * or if you click its 'close' button.
  699. *
  700. * The dialog is created by duplicating the original form and changing
  701. * its style; while clever, this is hard to generalize and probably
  702. * duplicates a lot of unnecessary HTML output.
  703. *
  704. * @fixme create confirmation dialogs through a generalized interface
  705. * that can be reused instead of hardcoded text and styles.
  706. *
  707. * @param {jQuery} form
  708. */
  709. NoticeRepeatConfirmation: function (form) {
  710. var submit_i = form.find('.submit');
  711. var submit = submit_i.clone();
  712. submit
  713. .addClass('submit_dialogbox')
  714. .removeClass('submit');
  715. form.append(submit);
  716. submit.on('click', function () { SN.U.FormXHR(form); return false; });
  717. submit_i.hide();
  718. form
  719. .addClass('dialogbox')
  720. .append('<button class="close" title="' + SN.msg('popup_close_button') + '">&#215;</button>')
  721. .closest('.notice-options')
  722. .addClass('opaque');
  723. form.find('button.close').click(function () {
  724. $(this).remove();
  725. form
  726. .removeClass('dialogbox')
  727. .closest('.notice-options')
  728. .removeClass('opaque');
  729. form.find('.submit_dialogbox').remove();
  730. form.find('.submit').show();
  731. return false;
  732. });
  733. },
  734. /**
  735. * Setup function -- DOES NOT trigger actions immediately.
  736. *
  737. * Goes through all notices currently displayed and sets up attachment
  738. * handling if needed.
  739. */
  740. NoticeAttachments: function () {
  741. $('.notice a.attachment').each(function () {
  742. SN.U.NoticeWithAttachment($(this).closest('.notice'));
  743. });
  744. },
  745. /**
  746. * Setup function -- DOES NOT trigger actions immediately.
  747. *
  748. * Sets up special attachment link handling if needed. Currently this
  749. * consists only of making the "more" button used for OStatus message
  750. * cropping turn into an auto-expansion button that loads the full
  751. * text from an attachment file.
  752. *
  753. * @param {jQuery} notice
  754. */
  755. NoticeWithAttachment: function (notice) {
  756. if (notice.find('.attachment').length === 0) {
  757. return;
  758. }
  759. $(document).on('click','.attachment.more',function () {
  760. var m = $(this);
  761. m.addClass(SN.C.S.Processing);
  762. $.get(m.attr('href'), {ajax: 1}, function (data) {
  763. m.parent('.e-content').html($(data).find('#attachment_view .e-content').html());
  764. });
  765. return false;
  766. });
  767. },
  768. /**
  769. * Setup function -- DOES NOT trigger actions immediately.
  770. *
  771. * Sets up event handlers for the file-attachment widget in the
  772. * new notice form. When a file is selected, a box will be added
  773. * below the text input showing the filename and, if supported
  774. * by the browser, a thumbnail preview.
  775. *
  776. * This preview box will also allow removing the attachment
  777. * prior to posting.
  778. *
  779. * @param {jQuery} form
  780. */
  781. NoticeDataAttach: function (form) {
  782. var i;
  783. var NDA = form.find('input[type=file]');
  784. NDA.change(function (event) {
  785. form.find('.attach-status').remove();
  786. var filename = $(this).val();
  787. if (!filename) {
  788. // No file -- we've been tricked!
  789. return false;
  790. }
  791. var attachStatus = $('<div class="attach-status ' + SN.C.S.Success + '"><code></code> <button class="close">&#215;</button></div>');
  792. attachStatus.find('code').text(filename);
  793. attachStatus.find('button').click(function () {
  794. attachStatus.remove();
  795. NDA.val('');
  796. return false;
  797. });
  798. form.append(attachStatus);
  799. if (typeof this.files === "object") {
  800. // Some newer browsers will let us fetch the files for preview.
  801. for (i = 0; i < this.files.length; i++) {
  802. SN.U.PreviewAttach(form, this.files[i]);
  803. }
  804. }
  805. });
  806. },
  807. /**
  808. * Get PHP's MAX_FILE_SIZE setting for this form;
  809. * used to apply client-side file size limit checks.
  810. *
  811. * @param {jQuery} form
  812. * @return int max size in bytes; 0 or negative means no limit
  813. */
  814. maxFileSize: function (form) {
  815. var max = $(form).find('input[name=MAX_FILE_SIZE]').attr('value');
  816. if (max) {
  817. return parseInt(max);
  818. }
  819. return 0;
  820. },
  821. /**
  822. * For browsers with FileAPI support: make a thumbnail if possible,
  823. * and append it into the attachment display widget.
  824. *
  825. * Known good:
  826. * - Firefox 3.6.6, 4.0b7
  827. * - Chrome 8.0.552.210
  828. *
  829. * Known ok metadata, can't get contents:
  830. * - Safari 5.0.2
  831. *
  832. * Known fail:
  833. * - Opera 10.63, 11 beta (no input.files interface)
  834. *
  835. * @param {jQuery} form
  836. * @param {File} file
  837. *
  838. * @todo use configured thumbnail size
  839. * @todo detect pixel size?
  840. * @todo should we render a thumbnail to a canvas and then use the smaller image?
  841. */
  842. PreviewAttach: function (form, file) {
  843. var tooltip = file.type + ' ' + Math.round(file.size / 1024) + 'KB';
  844. var preview = true;
  845. var blobAsDataURL;
  846. if (window.createObjectURL !== undefined) {
  847. /**
  848. * createObjectURL lets us reference the file directly from an <img>
  849. * This produces a compact URL with an opaque reference to the file,
  850. * which we can reference immediately.
  851. *
  852. * - Firefox 3.6.6: no
  853. * - Firefox 4.0b7: no
  854. * - Safari 5.0.2: no
  855. * - Chrome 8.0.552.210: works!
  856. */
  857. blobAsDataURL = function (blob, callback) {
  858. callback(window.createObjectURL(blob));
  859. };
  860. } else if (window.FileReader !== undefined) {
  861. /**
  862. * FileAPI's FileReader can build a data URL from a blob's contents,
  863. * but it must read the file and build it asynchronously. This means
  864. * we'll be passing a giant data URL around, which may be inefficient.
  865. *
  866. * - Firefox 3.6.6: works!
  867. * - Firefox 4.0b7: works!
  868. * - Safari 5.0.2: no
  869. * - Chrome 8.0.552.210: works!
  870. */
  871. blobAsDataURL = function (blob, callback) {
  872. var reader = new FileReader();
  873. reader.onload = function (event) {
  874. callback(reader.result);
  875. };
  876. reader.readAsDataURL(blob);
  877. };
  878. } else {
  879. preview = false;
  880. }
  881. var imageTypes = ['image/png', 'image/jpeg', 'image/gif', 'image/svg+xml'];
  882. if ($.inArray(file.type, imageTypes) == -1) {
  883. // We probably don't know how to show the file.
  884. preview = false;
  885. }
  886. var maxSize = 8 * 1024 * 1024;
  887. if (file.size > maxSize) {
  888. // Don't kill the browser trying to load some giant image.
  889. preview = false;
  890. }
  891. if (preview) {
  892. blobAsDataURL(file, function (url) {
  893. var img = $('<img>')
  894. .attr('title', tooltip)
  895. .attr('alt', tooltip)
  896. .attr('src', url)
  897. .attr('style', 'height: 120px');
  898. form.find('.attach-status').append(img);
  899. });
  900. } else {
  901. var img = $('<div></div>').text(tooltip);
  902. form.find('.attach-status').append(img);
  903. }
  904. },
  905. /**
  906. * Setup function -- DOES NOT trigger actions immediately.
  907. *
  908. * Initializes state for the location-lookup features in the
  909. * new-notice form. Seems to set up some event handlers for
  910. * triggering lookups and using the new values.
  911. *
  912. * @param {jQuery} form
  913. *
  914. * @fixme tl;dr
  915. * @fixme there's not good visual state update here, so users have a
  916. * hard time figuring out if it's working or fixing if it's wrong.
  917. *
  918. */
  919. NoticeLocationAttach: function (form) {
  920. // @fixme this should not be tied to the main notice form, as there may be multiple notice forms...
  921. var NLat = form.find('[name=lat]');
  922. var NLon = form.find('[name=lon]');
  923. var NLNS = form.find('[name=location_ns]').val();
  924. var NLID = form.find('[name=location_id]').val();
  925. var NLN = ''; // @fixme
  926. var NDGe = form.find('[name=notice_data-geo]');
  927. var check = form.find('[name=notice_data-geo]');
  928. var label = form.find('label.notice_data-geo');
  929. function removeNoticeDataGeo(error) {
  930. label
  931. .attr('title', $.trim(label.text()))
  932. .removeClass('checked');
  933. form.find('[name=lat]').val('');
  934. form.find('[name=lon]').val('');
  935. form.find('[name=location_ns]').val('');
  936. form.find('[name=location_id]').val('');
  937. form.find('[name=notice_data-geo]').prop('checked', false);
  938. $.cookie(SN.C.S.NoticeDataGeoCookie, 'disabled', { path: '/' });
  939. if (error) {
  940. form.find('.geo_status_wrapper').removeClass('success').addClass('error');
  941. form.find('.geo_status_wrapper .geo_status').text(error);
  942. } else {
  943. form.find('.geo_status_wrapper').remove();
  944. }
  945. }
  946. function getJSONgeocodeURL(geocodeURL, data) {
  947. SN.U.NoticeGeoStatus(form, 'Looking up place name...');
  948. $.getJSON(geocodeURL, data, function (location) {
  949. var lns, lid, NLN_text;
  950. if (location.location_ns !== undefined) {
  951. form.find('[name=location_ns]').val(location.location_ns);
  952. lns = location.location_ns;
  953. }
  954. if (location.location_id !== undefined) {
  955. form.find('[name=location_id]').val(location.location_id);
  956. lid = location.location_id;
  957. }
  958. if (location.name === undefined) {
  959. NLN_text = data.lat + ';' + data.lon;
  960. } else {
  961. NLN_text = location.name;
  962. }
  963. SN.U.NoticeGeoStatus(form, NLN_text, data.lat, data.lon, location.url);
  964. label
  965. .attr('title', NoticeDataGeo_text.ShareDisable + ' (' + NLN_text + ')');
  966. form.find('[name=lat]').val(data.lat);
  967. form.find('[name=lon]').val(data.lon);
  968. form.find('[name=location_ns]').val(lns);
  969. form.find('[name=location_id]').val(lid);
  970. form.find('[name=notice_data-geo]').prop('checked', true);
  971. var cookieValue = {
  972. NLat: data.lat,
  973. NLon: data.lon,
  974. NLNS: lns,
  975. NLID: lid,
  976. NLN: NLN_text,
  977. NLNU: location.url,
  978. NDG: true
  979. };
  980. $.cookie(SN.C.S.NoticeDataGeoCookie, JSON.stringify(cookieValue), { path: '/' });
  981. });
  982. }
  983. if (check.length > 0) {
  984. if ($.cookie(SN.C.S.NoticeDataGeoCookie) == 'disabled') {
  985. check.prop('checked', false);
  986. } else {
  987. check.prop('checked', true);
  988. }
  989. var NGW = form.find('.notice_data-geo_wrap');
  990. var geocodeURL = NGW.attr('data-api');
  991. label.attr('title', label.text());
  992. check.change(function () {
  993. if (check.prop('checked') === true || $.cookie(SN.C.S.NoticeDataGeoCookie) === undefined) {
  994. label
  995. .attr('title', NoticeDataGeo_text.ShareDisable)
  996. .addClass('checked');
  997. if ($.cookie(SN.C.S.NoticeDataGeoCookie) === undefined || $.cookie(SN.C.S.NoticeDataGeoCookie) == 'disabled') {
  998. if (navigator.geolocation) {
  999. SN.U.NoticeGeoStatus(form, 'Requesting location from browser...');
  1000. navigator.geolocation.getCurrentPosition(
  1001. function (position) {
  1002. form.find('[name=lat]').val(position.coords.latitude);
  1003. form.find('[name=lon]').val(position.coords.longitude);
  1004. var data = {
  1005. lat: position.coords.latitude,
  1006. lon: position.coords.longitude,
  1007. token: $('#token').val()
  1008. };
  1009. getJSONgeocodeURL(geocodeURL, data);
  1010. },
  1011. function (error) {
  1012. switch(error.code) {
  1013. case error.PERMISSION_DENIED:
  1014. removeNoticeDataGeo('Location permission denied.');
  1015. break;
  1016. case error.TIMEOUT:
  1017. //$('#' + SN.C.S.NoticeDataGeo).prop('checked', false);
  1018. removeNoticeDataGeo('Location lookup timeout.');
  1019. break;
  1020. }
  1021. },
  1022. {
  1023. timeout: 10000
  1024. }
  1025. );
  1026. } else {
  1027. if (NLat.length > 0 && NLon.length > 0) {
  1028. var data = {
  1029. lat: NLat,
  1030. lon: NLon,
  1031. token: $('#token').val()
  1032. };
  1033. getJSONgeocodeURL(geocodeURL, data);
  1034. } else {
  1035. removeNoticeDataGeo();
  1036. check.remove();
  1037. label.remove();
  1038. }
  1039. }
  1040. } else {
  1041. try {
  1042. var cookieValue = JSON.parse($.cookie(SN.C.S.NoticeDataGeoCookie));
  1043. form.find('[name=lat]').val(cookieValue.NLat);
  1044. form.find('[name=lon]').val(cookieValue.NLon);
  1045. form.find('[name=location_ns]').val(cookieValue.NLNS);
  1046. form.find('[name=location_id]').val(cookieValue.NLID);
  1047. form.find('[name=notice_data-geo]').prop('checked', cookieValue.NDG);
  1048. SN.U.NoticeGeoStatus(form, cookieValue.NLN, cookieValue.NLat, cookieValue.NLon, cookieValue.NLNU);
  1049. label
  1050. .attr('title', NoticeDataGeo_text.ShareDisable + ' (' + cookieValue.NLN + ')')
  1051. .addClass('checked');
  1052. } catch (e) {
  1053. console.log('Parsing error:', e);
  1054. }
  1055. }
  1056. } else {
  1057. removeNoticeDataGeo();
  1058. }
  1059. }).change();
  1060. }
  1061. },
  1062. /**
  1063. * Create or update a geolocation status widget in this notice posting form.
  1064. *
  1065. * @param {jQuery} form
  1066. * @param {String} status
  1067. * @param {String} lat (optional)
  1068. * @param {String} lon (optional)
  1069. * @param {String} url (optional)
  1070. */
  1071. NoticeGeoStatus: function (form, status, lat, lon, url)
  1072. {
  1073. var wrapper = form.find('.geo_status_wrapper');
  1074. if (wrapper.length == 0) {
  1075. wrapper = $('<div class="' + SN.C.S.Success + ' geo_status_wrapper"><button class="close" style="float:right">&#215;</button><div class="geo_status"></div></div>');
  1076. wrapper.find('button.close').click(function () {
  1077. form.find('[name=notice_data-geo]').prop('checked', false).change();
  1078. return false;
  1079. });
  1080. form.append(wrapper);
  1081. }
  1082. var label;
  1083. if (url) {
  1084. label = $('<a></a>').attr('href', url);
  1085. } else {
  1086. label = $('<span></span>');
  1087. }
  1088. label.text(status);
  1089. if (lat || lon) {
  1090. var latlon = lat + ';' + lon;
  1091. label.attr('title', latlon);
  1092. if (!status) {
  1093. label.text(latlon)
  1094. }
  1095. }
  1096. wrapper.find('.geo_status').empty().append(label);
  1097. },
  1098. /**
  1099. * Setup function -- DOES NOT trigger actions immediately.
  1100. *
  1101. * Initializes event handlers for the "Send direct message" link on
  1102. * profile pages, setting it up to display a dialog box when clicked.
  1103. *
  1104. * Unlike the repeat confirmation form, this appears to fetch
  1105. * the form _from the original link target_, so the form itself
  1106. * doesn't need to be in the current document.
  1107. *
  1108. * @fixme breaks ability to open link in new window?
  1109. */
  1110. NewDirectMessage: function () {
  1111. NDM = $('.entity_send-a-message a');
  1112. NDM.attr({'href': NDM.attr('href') + '&ajax=1'});
  1113. NDM.on('click', function () {
  1114. var NDMF = $('.entity_send-a-message form');
  1115. if (NDMF.length === 0) {
  1116. $(this).addClass(SN.C.S.Processing);
  1117. $.get(NDM.attr('href'), null, function (data) {
  1118. $('.entity_send-a-message').append(document._importNode($('form', data)[0], true));
  1119. NDMF = $('.entity_send-a-message .form_notice');
  1120. SN.U.FormNoticeXHR(NDMF);
  1121. SN.U.FormNoticeEnhancements(NDMF);
  1122. NDMF.append('<button class="close">&#215;</button>');
  1123. $('.entity_send-a-message button').click(function () {
  1124. NDMF.hide();
  1125. return false;
  1126. });
  1127. NDM.removeClass(SN.C.S.Processing);
  1128. });
  1129. } else {
  1130. NDMF.show();
  1131. $('.entity_send-a-message textarea').focus();
  1132. }
  1133. return false;
  1134. });
  1135. },
  1136. /**
  1137. * Return a date object with the current local time on the
  1138. * given year, month, and day.
  1139. *
  1140. * @param {number} year: 4-digit year
  1141. * @param {number} month: 0 == January
  1142. * @param {number} day: 1 == 1
  1143. * @return {Date}
  1144. */
  1145. GetFullYear: function (year, month, day) {
  1146. var date = new Date();
  1147. date.setFullYear(year, month, day);
  1148. return date;
  1149. },
  1150. /**
  1151. * Check if the current page is a timeline where the current user's
  1152. * posts should be displayed immediately on success.
  1153. *
  1154. * @fixme this should be done in a saner way, with machine-readable
  1155. * info about what page we're looking at.
  1156. *
  1157. * @param {DOMElement} notice: HTML chunk with formatted notice
  1158. * @return boolean
  1159. */
  1160. belongsOnTimeline: function (notice) {
  1161. var action = $("body").attr('id');
  1162. if (action == 'public') {
  1163. return true;
  1164. }
  1165. var profileLink = $('#nav_profile a').attr('href');
  1166. if (profileLink) {
  1167. var authorUrl = $(notice).find('.h-card.p-author').attr('href');
  1168. if (authorUrl == profileLink) {
  1169. if (action == 'all' || action == 'showstream') {
  1170. // Posts always show on your own friends and profile streams.
  1171. return true;
  1172. }
  1173. }
  1174. }
  1175. // @fixme tag, group, reply timelines should be feasible as well.
  1176. // Mismatch between id-based and name-based user/group links currently complicates
  1177. // the lookup, since all our inline mentions contain the absolute links but the
  1178. // UI links currently on the page use malleable names.
  1179. return false;
  1180. },
  1181. /**
  1182. * Switch to another active input sub-form.
  1183. * This will hide the current form (if any), show the new one, and
  1184. * update the input type tab selection state.
  1185. *
  1186. * @param {String} tag
  1187. */
  1188. switchInputFormTab: function (tag, setFocus) {
  1189. if (typeof setFocus === 'undefined') { setFocus = true; }
  1190. // The one that's current isn't current anymore
  1191. $('.input_form_nav_tab.current').removeClass('current');
  1192. if (tag != null) {
  1193. $('#input_form_nav_' + tag).addClass('current');
  1194. }
  1195. // Don't remove 'current' if we also have the "nonav" class.
  1196. // An example would be the message input form. removing
  1197. // 'current' will cause the form to vanish from the page.
  1198. var nonav = $('.input_form.current.nonav');
  1199. if (nonav.length > 0) {
  1200. return;
  1201. }
  1202. $('.input_form.current').removeClass('current');
  1203. if (tag == null) {
  1204. // we're done here, no new inputform to focus on
  1205. return false;
  1206. }
  1207. var noticeForm = $('#input_form_' + tag)
  1208. .addClass('current')
  1209. .find('.ajax-notice').each(function () {
  1210. var form = $(this);
  1211. SN.Init.NoticeFormSetup(form);
  1212. });
  1213. if (setFocus) {
  1214. noticeForm.find('.notice_data-text').focus();
  1215. }
  1216. return false;
  1217. },
  1218. showMoreMenuItems: function (menuid) {
  1219. $('#' + menuid + ' .more_link').remove();
  1220. var selector = '#' + menuid + ' .extended_menu';
  1221. var extended = $(selector);
  1222. extended.removeClass('extended_menu');
  1223. return void(0);
  1224. },
  1225. /**
  1226. * Show a response feedback bit under a form.
  1227. *
  1228. * @param {Element} form: the new-notice form usually
  1229. * @param {String} cls: CSS class name to use ('error' or 'success')
  1230. * @param {String} text
  1231. * @access public
  1232. */
  1233. showFeedback: function (form, cls, text) {
  1234. form.append(
  1235. $('<p class="form_response"></p>')
  1236. .addClass(cls)
  1237. .text(text)
  1238. );
  1239. },
  1240. addCallback: function (ename, callback) {
  1241. // initialize to array if it's undefined
  1242. if (typeof SN._callbacks[ename] === 'undefined') {
  1243. SN._callbacks[ename] = [];
  1244. }
  1245. SN._callbacks[ename].push(callback);
  1246. },
  1247. runCallbacks: function (ename, data) {
  1248. if (typeof SN._callbacks[ename] === 'undefined') {
  1249. return;
  1250. }
  1251. for (cbname in SN._callbacks[ename]) {
  1252. SN._callbacks[ename][cbname](data);
  1253. }
  1254. }
  1255. },
  1256. E: { /* Events */
  1257. /* SN.E.ajaxNoticePosted, called when a notice has been posted successfully via an AJAX form
  1258. @param form the originating form element
  1259. @param data data from success() callback
  1260. @param textStatus textStatus from success() callback
  1261. */
  1262. ajaxNoticePosted: function (form, data, textStatus) {
  1263. var commandResult = $('#' + SN.C.S.CommandResult, data);
  1264. if (commandResult.length > 0) {
  1265. SN.U.showFeedback(form, 'success', commandResult.text());
  1266. } else {
  1267. // New notice post was successful. If on our timeline, show it!
  1268. var notice = document._importNode($('li', data)[0], true);
  1269. var notices = $('#notices_primary .notices:first');
  1270. var replyItem = form.closest('li.notice-reply');
  1271. if (replyItem.length > 0) {
  1272. // If this is an inline reply, remove the form...
  1273. var list = form.closest('.threaded-replies');
  1274. var id = $(notice).attr('id');
  1275. if ($('#' + id).length == 0) {
  1276. $(notice).insertBefore(replyItem);
  1277. } // else Realtime came through before us...
  1278. replyItem.remove();
  1279. } else if (notices.length > 0 && SN.U.belongsOnTimeline(notice)) {
  1280. // Not a reply. If on our timeline, show it at the top!
  1281. if ($('#' + notice.id).length === 0) {
  1282. var notice_irt_value = form.find('[name=inreplyto]').val();
  1283. var notice_irt = '#notices_primary #notice-' + notice_irt_value;
  1284. if ($('body')[0].id == 'conversation') {
  1285. if (notice_irt_value.length > 0 && $(notice_irt + ' .notices').length < 1) {
  1286. $(notice_irt).append('<ul class="notices"></ul>');
  1287. }
  1288. $($(notice_irt + ' .notices')[0]).append(notice);
  1289. } else {
  1290. notices.prepend(notice);
  1291. }
  1292. $('#' + notice.id)
  1293. .css({display: 'none'})
  1294. .fadeIn(2500);
  1295. SN.U.NoticeWithAttachment($('#' + notice.id));
  1296. SN.U.switchInputFormTab(null);
  1297. }
  1298. } else {
  1299. // Not on a timeline that this belongs on?
  1300. // Just show a success message.
  1301. // @fixme inline
  1302. SN.U.showFeedback(form, 'success', $('title', data).text());
  1303. }
  1304. }
  1305. form.resetForm();
  1306. form.find('[name=inreplyto]').val('');
  1307. form.find('.attach-status').remove();
  1308. SN.U.FormNoticeEnhancements(form);
  1309. SN.U.runCallbacks('notice_posted', {"notice": notice});
  1310. },
  1311. },
  1312. Init: {
  1313. /**
  1314. * If user is logged in, run setup code for the new notice form:
  1315. *
  1316. * - char counter
  1317. * - AJAX submission
  1318. * - location events
  1319. * - file upload events
  1320. */
  1321. NoticeForm: function () {
  1322. if ($('body.user_in').length > 0) {
  1323. // SN.Init.NoticeFormSetup() will get run
  1324. // when forms get displayed for the first time...
  1325. // Initialize the input form field
  1326. $('#input_form_nav .input_form_nav_tab.current').each(function () {
  1327. current_tab_id = $(this).attr('id').substring('input_form_nav_'.length);
  1328. SN.U.switchInputFormTab(current_tab_id, false);
  1329. });
  1330. // Make inline reply forms self-close when clicking out.
  1331. $('body').on('click', function (e) {
  1332. var openReplies = $('li.notice-reply');
  1333. if (openReplies.length > 0) {
  1334. var target = $(e.target);
  1335. openReplies.each(function () {
  1336. // Did we click outside this one?
  1337. var replyItem = $(this);
  1338. if (replyItem.has(e.target).length == 0) {
  1339. var textarea = replyItem.find('.notice_data-text:first');
  1340. var cur = $.trim(textarea.val());
  1341. // Only close if there's been no edit.
  1342. if (cur == '' || cur == textarea.data('initialText')) {
  1343. var parentNotice = replyItem.closest('li.notice');
  1344. replyItem.hide();
  1345. parentNotice.find('li.notice-reply-placeholder').show();
  1346. }
  1347. }
  1348. });
  1349. }
  1350. });
  1351. }
  1352. },
  1353. /**
  1354. * Encapsulate notice form setup for a single form.
  1355. * Plugins can add extra setup by monkeypatching this
  1356. * function.
  1357. *
  1358. * @param {jQuery} form
  1359. */
  1360. NoticeFormSetup: function (form) {
  1361. if (form.data('NoticeFormSetup')) {
  1362. return false;
  1363. }
  1364. SN.U.NoticeLocationAttach(form);
  1365. SN.U.FormNoticeUniqueID(form);
  1366. SN.U.FormNoticeXHR(form);
  1367. SN.U.FormNoticeEnhancements(form);
  1368. SN.U.NoticeDataAttach(form);
  1369. form.data('NoticeFormSetup', true);
  1370. },
  1371. /**
  1372. * Run setup code for notice timeline views items:
  1373. *
  1374. * - AJAX submission for fave/repeat/reply (if logged in)
  1375. * - Attachment link extras ('more' links)
  1376. */
  1377. Notices: function () {
  1378. if ($('body.user_in').length > 0) {
  1379. SN.U.NoticeRepeat();
  1380. SN.U.NoticeReply();
  1381. SN.U.NoticeInlineReplySetup();
  1382. SN.U.NoticeOptionsAjax();
  1383. }
  1384. SN.U.NoticeAttachments();
  1385. },
  1386. /**
  1387. * Run setup code for user & group profile page header area if logged in:
  1388. *
  1389. * - AJAX submission for sub/unsub/join/leave/nudge
  1390. * - AJAX form popup for direct-message
  1391. */
  1392. EntityActions: function () {
  1393. if ($('body.user_in').length > 0) {
  1394. $(document).on('click', '.form_user_subscribe', function () { SN.U.FormXHR($(this)); return false; });
  1395. $(document).on('click', '.form_user_unsubscribe', function () { SN.U.FormXHR($(this)); return false; });
  1396. $(document).on('click', '.form_group_join', function () { SN.U.FormXHR($(this)); return false; });
  1397. $(document).on('click', '.form_group_leave', function () { SN.U.FormXHR($(this)); return false; });
  1398. $(document).on('click', '.form_user_nudge', function () { SN.U.FormXHR($(this)); return false; });
  1399. $(document).on('click', '.form_peopletag_subscribe', function () { SN.U.FormXHR($(this)); return false; });
  1400. $(document).on('click', '.form_peopletag_unsubscribe', function () { SN.U.FormXHR($(this)); return false; });
  1401. $(document).on('click', '.form_user_add_peopletag', function () { SN.U.FormXHR($(this)); return false; });
  1402. $(document).on('click', '.form_user_remove_peopletag', function () { SN.U.FormXHR($(this)); return false; });
  1403. SN.U.NewDirectMessage();
  1404. }
  1405. },
  1406. ProfileSearch: function () {
  1407. if ($('body.user_in').length > 0) {
  1408. $(document).on('click', '.form_peopletag_edit_user_search input.submit', function () {
  1409. SN.U.FormProfileSearchXHR($(this).parents('form')); return false;
  1410. });
  1411. }
  1412. },
  1413. /**
  1414. * Run setup for the ajax people tags editor
  1415. *
  1416. * - show edit button
  1417. * - set event handle for click on edit button
  1418. * - loads people tag autocompletion data if not already present
  1419. * or if it is stale.
  1420. *
  1421. */
  1422. PeopleTags: function () {
  1423. $('.user_profile_tags .editable').append($('<button class="peopletags_edit_button"/>'));
  1424. $(document).on('click', '.peopletags_edit_button', function () {
  1425. var form = $(this).parents('dd').eq(0).find('form');
  1426. // We can buy time from the above animation
  1427. $.ajax({
  1428. url: _peopletagAC,
  1429. dataType: 'json',
  1430. data: {token: $('#token').val()},
  1431. ifModified: true,
  1432. success: function (data) {
  1433. // item.label is used to match
  1434. for (i=0; i < data.length; i++) {
  1435. data[i].label = data[i].tag;
  1436. }
  1437. SN.C.PtagACData = data;
  1438. }
  1439. });
  1440. $(this).parents('ul').eq(0).fadeOut(200, function () {form.fadeIn(200).find('input#tags')});
  1441. });
  1442. $(document).on('click', '.user_profile_tags form .submit', function () {
  1443. SN.U.FormPeopletagsXHR($(this).parents('form')); return false;
  1444. });
  1445. },
  1446. /**
  1447. * Set up any generic 'ajax' form so it submits via AJAX with auto-replacement.
  1448. */
  1449. AjaxForms: function () {
  1450. $(document).on('submit', 'form.ajax', function () {
  1451. SN.U.FormXHR($(this));
  1452. return false;
  1453. });
  1454. $(document).on('click', 'form.ajax input[type=submit]', function () {
  1455. // Some forms rely on knowing which submit button was clicked.
  1456. // Save a hidden input field which'll be picked up during AJAX
  1457. // submit...
  1458. var button = $(this);
  1459. var form = button.closest('form');
  1460. form.find('.hidden-submit-button').remove();
  1461. $('<input class="hidden-submit-button" type="hidden" />')
  1462. .attr('name', button.attr('name'))
  1463. .val(button.val())
  1464. .appendTo(form);
  1465. });
  1466. },
  1467. /**
  1468. * Add logic to any file upload forms to handle file size limits,
  1469. * on browsers that support basic FileAPI.
  1470. */
  1471. UploadForms: function () {
  1472. $('input[type=file]').change(function (event) {
  1473. if (typeof this.files === "object" && this.files.length > 0) {
  1474. var size = 0;
  1475. for (var i = 0; i < this.files.length; i++) {
  1476. size += this.files[i].size;
  1477. }
  1478. var max = SN.U.maxFileSize($(this.form));
  1479. if (max > 0 && size > max) {
  1480. var msg = 'File too large: maximum upload size is %d bytes.';
  1481. alert(msg.replace('%d', max));
  1482. // Clear the files.
  1483. $(this).val('');
  1484. event.preventDefault();
  1485. return false;
  1486. }
  1487. }
  1488. });
  1489. },
  1490. CheckBoxes: function () {
  1491. $("span[class='checkbox-wrapper']").addClass("unchecked");
  1492. $(".checkbox-wrapper").click(function () {
  1493. if ($(this).children("input").prop("checked")) {
  1494. // uncheck
  1495. $(this).children("input").prop("checked", false);
  1496. $(this).removeClass("checked");
  1497. $(this).addClass("unchecked");
  1498. $(this).children("label").text("Private?");
  1499. } else {
  1500. // check
  1501. $(this).children("input").prop("checked", true);
  1502. $(this).removeClass("unchecked");
  1503. $(this).addClass("checked");
  1504. $(this).children("label").text("Private");
  1505. }
  1506. });
  1507. }
  1508. }
  1509. };
  1510. /**
  1511. * Run initialization functions on DOM-ready.
  1512. *
  1513. * Note that if we're waiting on other scripts to load, this won't happen
  1514. * until that's done. To load scripts asynchronously without delaying setup,
  1515. * don't start them loading until after DOM-ready time!
  1516. */
  1517. $(function () {
  1518. SN.Init.AjaxForms();
  1519. SN.Init.UploadForms();
  1520. SN.Init.CheckBoxes();
  1521. if ($('.' + SN.C.S.FormNotice).length > 0) {
  1522. SN.Init.NoticeForm();
  1523. }
  1524. if ($('#content .notices').length > 0) {
  1525. SN.Init.Notices();
  1526. }
  1527. if ($('#content .entity_actions').length > 0) {
  1528. SN.Init.EntityActions();
  1529. }
  1530. if ($('#profile_search_results').length > 0) {
  1531. SN.Init.ProfileSearch();
  1532. }
  1533. if ($('.user_profile_tags .editable').length > 0) {
  1534. SN.Init.PeopleTags();
  1535. }
  1536. });