util.js 68 KB

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