util.js 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692
  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. 'image/bmp', 'image/webp', 'image/vnd.microsoft.icon'];
  887. if ($.inArray(file.type, imageTypes) == -1) {
  888. // We probably don't know how to show the file.
  889. preview = false;
  890. }
  891. var maxSize = 8 * 1024 * 1024;
  892. if (file.size > maxSize) {
  893. // Don't kill the browser trying to load some giant image.
  894. preview = false;
  895. }
  896. var fileentry = $('<li>')
  897. .attr('class', 'attachment')
  898. .attr('style', 'text-align: center');
  899. if (preview) {
  900. blobAsDataURL(file, function (url) {
  901. var img = $('<img>')
  902. .attr('title', tooltip)
  903. .attr('alt', tooltip)
  904. .attr('src', url)
  905. .attr('style', 'height: 120px');
  906. fileentry.append(img);
  907. fileentry.append($('<br><code>' + file.name + '</code>'));
  908. form.find('.attach-status').append(fileentry);
  909. });
  910. } else {
  911. fileentry.append($('<code>' + file.type + '</code>'));
  912. fileentry.append($('<br><code>' + file.name + '</code>'));
  913. form.find('.attach-status').append(fileentry);
  914. }
  915. },
  916. /**
  917. * Setup function -- DOES NOT trigger actions immediately.
  918. *
  919. * Initializes state for the location-lookup features in the
  920. * new-notice form. Seems to set up some event handlers for
  921. * triggering lookups and using the new values.
  922. *
  923. * @param {jQuery} form
  924. *
  925. * @fixme tl;dr
  926. * @fixme there's not good visual state update here, so users have a
  927. * hard time figuring out if it's working or fixing if it's wrong.
  928. *
  929. */
  930. NoticeLocationAttach: function (form) {
  931. // @fixme this should not be tied to the main notice form, as there may be multiple notice forms...
  932. var NLat = form.find('[name=lat]');
  933. var NLon = form.find('[name=lon]');
  934. var NLNS = form.find('[name=location_ns]').val();
  935. var NLID = form.find('[name=location_id]').val();
  936. var NLN = ''; // @fixme
  937. var NDGe = form.find('[name=notice_data-geo]');
  938. var check = form.find('[name=notice_data-geo]');
  939. var label = form.find('label.notice_data-geo');
  940. function removeNoticeDataGeo(error) {
  941. label
  942. .attr('title', $.trim(label.text()))
  943. .removeClass('checked');
  944. form.find('[name=lat]').val('');
  945. form.find('[name=lon]').val('');
  946. form.find('[name=location_ns]').val('');
  947. form.find('[name=location_id]').val('');
  948. form.find('[name=notice_data-geo]').prop('checked', false);
  949. $.cookie(SN.C.S.NoticeDataGeoCookie, 'disabled', { path: '/' });
  950. if (error) {
  951. form.find('.geo_status_wrapper').removeClass('success').addClass('error');
  952. form.find('.geo_status_wrapper .geo_status').text(error);
  953. } else {
  954. form.find('.geo_status_wrapper').remove();
  955. }
  956. }
  957. function getJSONgeocodeURL(geocodeURL, data) {
  958. SN.U.NoticeGeoStatus(form, 'Looking up place name...');
  959. $.getJSON(geocodeURL, data, function (location) {
  960. var lns, lid, NLN_text;
  961. if (location.location_ns !== undefined) {
  962. form.find('[name=location_ns]').val(location.location_ns);
  963. lns = location.location_ns;
  964. }
  965. if (location.location_id !== undefined) {
  966. form.find('[name=location_id]').val(location.location_id);
  967. lid = location.location_id;
  968. }
  969. if (location.name === undefined) {
  970. NLN_text = data.lat + ';' + data.lon;
  971. } else {
  972. NLN_text = location.name;
  973. }
  974. SN.U.NoticeGeoStatus(form, NLN_text, data.lat, data.lon, location.url);
  975. label
  976. .attr('title', NoticeDataGeo_text.ShareDisable + ' (' + NLN_text + ')');
  977. form.find('[name=lat]').val(data.lat);
  978. form.find('[name=lon]').val(data.lon);
  979. form.find('[name=location_ns]').val(lns);
  980. form.find('[name=location_id]').val(lid);
  981. form.find('[name=notice_data-geo]').prop('checked', true);
  982. var cookieValue = {
  983. NLat: data.lat,
  984. NLon: data.lon,
  985. NLNS: lns,
  986. NLID: lid,
  987. NLN: NLN_text,
  988. NLNU: location.url,
  989. NDG: true
  990. };
  991. $.cookie(SN.C.S.NoticeDataGeoCookie, JSON.stringify(cookieValue), { path: '/' });
  992. });
  993. }
  994. if (check.length > 0) {
  995. if ($.cookie(SN.C.S.NoticeDataGeoCookie) == 'disabled') {
  996. check.prop('checked', false);
  997. } else {
  998. check.prop('checked', true);
  999. }
  1000. var NGW = form.find('.notice_data-geo_wrap');
  1001. var geocodeURL = NGW.attr('data-api');
  1002. label.attr('title', label.text());
  1003. check.change(function () {
  1004. if (check.prop('checked') === true || $.cookie(SN.C.S.NoticeDataGeoCookie) === undefined) {
  1005. label
  1006. .attr('title', NoticeDataGeo_text.ShareDisable)
  1007. .addClass('checked');
  1008. if ($.cookie(SN.C.S.NoticeDataGeoCookie) === undefined || $.cookie(SN.C.S.NoticeDataGeoCookie) == 'disabled') {
  1009. if (navigator.geolocation) {
  1010. SN.U.NoticeGeoStatus(form, 'Requesting location from browser...');
  1011. navigator.geolocation.getCurrentPosition(
  1012. function (position) {
  1013. form.find('[name=lat]').val(position.coords.latitude);
  1014. form.find('[name=lon]').val(position.coords.longitude);
  1015. var data = {
  1016. lat: position.coords.latitude,
  1017. lon: position.coords.longitude,
  1018. token: $('#token').val()
  1019. };
  1020. getJSONgeocodeURL(geocodeURL, data);
  1021. },
  1022. function (error) {
  1023. switch(error.code) {
  1024. case error.PERMISSION_DENIED:
  1025. removeNoticeDataGeo('Location permission denied.');
  1026. break;
  1027. case error.TIMEOUT:
  1028. //$('#' + SN.C.S.NoticeDataGeo).prop('checked', false);
  1029. removeNoticeDataGeo('Location lookup timeout.');
  1030. break;
  1031. }
  1032. },
  1033. {
  1034. timeout: 10000
  1035. }
  1036. );
  1037. } else {
  1038. if (NLat.length > 0 && NLon.length > 0) {
  1039. var data = {
  1040. lat: NLat,
  1041. lon: NLon,
  1042. token: $('#token').val()
  1043. };
  1044. getJSONgeocodeURL(geocodeURL, data);
  1045. } else {
  1046. removeNoticeDataGeo();
  1047. check.remove();
  1048. label.remove();
  1049. }
  1050. }
  1051. } else {
  1052. try {
  1053. var cookieValue = JSON.parse($.cookie(SN.C.S.NoticeDataGeoCookie));
  1054. form.find('[name=lat]').val(cookieValue.NLat);
  1055. form.find('[name=lon]').val(cookieValue.NLon);
  1056. form.find('[name=location_ns]').val(cookieValue.NLNS);
  1057. form.find('[name=location_id]').val(cookieValue.NLID);
  1058. form.find('[name=notice_data-geo]').prop('checked', cookieValue.NDG);
  1059. SN.U.NoticeGeoStatus(form, cookieValue.NLN, cookieValue.NLat, cookieValue.NLon, cookieValue.NLNU);
  1060. label
  1061. .attr('title', NoticeDataGeo_text.ShareDisable + ' (' + cookieValue.NLN + ')')
  1062. .addClass('checked');
  1063. } catch (e) {
  1064. console.log('Parsing error:', e);
  1065. }
  1066. }
  1067. } else {
  1068. removeNoticeDataGeo();
  1069. }
  1070. }).change();
  1071. }
  1072. },
  1073. /**
  1074. * Create or update a geolocation status widget in this notice posting form.
  1075. *
  1076. * @param {jQuery} form
  1077. * @param {String} status
  1078. * @param {String} lat (optional)
  1079. * @param {String} lon (optional)
  1080. * @param {String} url (optional)
  1081. */
  1082. NoticeGeoStatus: function (form, status, lat, lon, url)
  1083. {
  1084. var wrapper = form.find('.geo_status_wrapper');
  1085. if (wrapper.length == 0) {
  1086. wrapper = $('<div class="' + SN.C.S.Success + ' geo_status_wrapper"><button class="close" style="float:right">&#215;</button><div class="geo_status"></div></div>');
  1087. wrapper.find('button.close').click(function () {
  1088. form.find('[name=notice_data-geo]').prop('checked', false).change();
  1089. return false;
  1090. });
  1091. form.append(wrapper);
  1092. }
  1093. var label;
  1094. if (url) {
  1095. label = $('<a></a>').attr('href', url);
  1096. } else {
  1097. label = $('<span></span>');
  1098. }
  1099. label.text(status);
  1100. if (lat || lon) {
  1101. var latlon = lat + ';' + lon;
  1102. label.attr('title', latlon);
  1103. if (!status) {
  1104. label.text(latlon)
  1105. }
  1106. }
  1107. wrapper.find('.geo_status').empty().append(label);
  1108. },
  1109. /**
  1110. * Setup function -- DOES NOT trigger actions immediately.
  1111. *
  1112. * Initializes event handlers for the "Send direct message" link on
  1113. * profile pages, setting it up to display a dialog box when clicked.
  1114. *
  1115. * Unlike the repeat confirmation form, this appears to fetch
  1116. * the form _from the original link target_, so the form itself
  1117. * doesn't need to be in the current document.
  1118. *
  1119. * @fixme breaks ability to open link in new window?
  1120. */
  1121. NewDirectMessage: function () {
  1122. NDM = $('.entity_send-a-message a');
  1123. NDM.attr({'href': NDM.attr('href') + '&ajax=1'});
  1124. NDM.on('click', function () {
  1125. var NDMF = $('.entity_send-a-message form');
  1126. if (NDMF.length === 0) {
  1127. $(this).addClass(SN.C.S.Processing);
  1128. $.get(NDM.attr('href'), null, function (data) {
  1129. $('.entity_send-a-message').append(document._importNode($('form', data)[0], true));
  1130. NDMF = $('.entity_send-a-message .form_notice');
  1131. SN.U.FormNoticeXHR(NDMF);
  1132. SN.U.FormNoticeEnhancements(NDMF);
  1133. NDMF.append('<button class="close">&#215;</button>');
  1134. $('.entity_send-a-message button').click(function () {
  1135. NDMF.hide();
  1136. return false;
  1137. });
  1138. NDM.removeClass(SN.C.S.Processing);
  1139. });
  1140. } else {
  1141. NDMF.show();
  1142. $('.entity_send-a-message textarea').focus();
  1143. }
  1144. return false;
  1145. });
  1146. },
  1147. /**
  1148. * Return a date object with the current local time on the
  1149. * given year, month, and day.
  1150. *
  1151. * @param {number} year: 4-digit year
  1152. * @param {number} month: 0 == January
  1153. * @param {number} day: 1 == 1
  1154. * @return {Date}
  1155. */
  1156. GetFullYear: function (year, month, day) {
  1157. var date = new Date();
  1158. date.setFullYear(year, month, day);
  1159. return date;
  1160. },
  1161. /**
  1162. * Check if the current page is a timeline where the current user's
  1163. * posts should be displayed immediately on success.
  1164. *
  1165. * @fixme this should be done in a saner way, with machine-readable
  1166. * info about what page we're looking at.
  1167. *
  1168. * @param {DOMElement} notice: HTML chunk with formatted notice
  1169. * @return boolean
  1170. */
  1171. belongsOnTimeline: function (notice) {
  1172. var action = $("body").attr('id');
  1173. if (action == 'public') {
  1174. return true;
  1175. }
  1176. var profileLink = $('#nav_profile a').attr('href');
  1177. if (profileLink) {
  1178. var authorUrl = $(notice).find('.h-card.p-author').attr('href');
  1179. if (authorUrl == profileLink) {
  1180. if (action == 'all' || action == 'showstream') {
  1181. // Posts always show on your own friends and profile streams.
  1182. return true;
  1183. }
  1184. }
  1185. }
  1186. // @fixme tag, group, reply timelines should be feasible as well.
  1187. // Mismatch between id-based and name-based user/group links currently complicates
  1188. // the lookup, since all our inline mentions contain the absolute links but the
  1189. // UI links currently on the page use malleable names.
  1190. return false;
  1191. },
  1192. /**
  1193. * Switch to another active input sub-form.
  1194. * This will hide the current form (if any), show the new one, and
  1195. * update the input type tab selection state.
  1196. *
  1197. * @param {String} tag
  1198. */
  1199. switchInputFormTab: function (tag, setFocus) {
  1200. if (typeof setFocus === 'undefined') { setFocus = true; }
  1201. // The one that's current isn't current anymore
  1202. $('.input_form_nav_tab.current').removeClass('current');
  1203. if (tag != null) {
  1204. $('#input_form_nav_' + tag).addClass('current');
  1205. }
  1206. // Don't remove 'current' if we also have the "nonav" class.
  1207. // An example would be the message input form. removing
  1208. // 'current' will cause the form to vanish from the page.
  1209. var nonav = $('.input_form.current.nonav');
  1210. if (nonav.length > 0) {
  1211. return;
  1212. }
  1213. $('.input_form.current').removeClass('current');
  1214. if (tag == null) {
  1215. // we're done here, no new inputform to focus on
  1216. return false;
  1217. }
  1218. var noticeForm = $('#input_form_' + tag)
  1219. .addClass('current')
  1220. .find('.ajax-notice').each(function () {
  1221. var form = $(this);
  1222. SN.Init.NoticeFormSetup(form);
  1223. });
  1224. if (setFocus) {
  1225. noticeForm.find('.notice_data-text').focus();
  1226. }
  1227. return false;
  1228. },
  1229. showMoreMenuItems: function (menuid) {
  1230. $('#' + menuid + ' .more_link').remove();
  1231. var selector = '#' + menuid + ' .extended_menu';
  1232. var extended = $(selector);
  1233. extended.removeClass('extended_menu');
  1234. return void(0);
  1235. },
  1236. /**
  1237. * Show a response feedback bit under a form.
  1238. *
  1239. * @param {Element} form: the new-notice form usually
  1240. * @param {String} cls: CSS class name to use ('error' or 'success')
  1241. * @param {String} text
  1242. * @access public
  1243. */
  1244. showFeedback: function (form, cls, text) {
  1245. form.append(
  1246. $('<p class="form_response"></p>')
  1247. .addClass(cls)
  1248. .text(text)
  1249. );
  1250. },
  1251. addCallback: function (ename, callback) {
  1252. // initialize to array if it's undefined
  1253. if (typeof SN._callbacks[ename] === 'undefined') {
  1254. SN._callbacks[ename] = [];
  1255. }
  1256. SN._callbacks[ename].push(callback);
  1257. },
  1258. runCallbacks: function (ename, data) {
  1259. if (typeof SN._callbacks[ename] === 'undefined') {
  1260. return;
  1261. }
  1262. for (cbname in SN._callbacks[ename]) {
  1263. SN._callbacks[ename][cbname](data);
  1264. }
  1265. }
  1266. },
  1267. E: { /* Events */
  1268. /* SN.E.ajaxNoticePosted, called when a notice has been posted successfully via an AJAX form
  1269. @param form the originating form element
  1270. @param data data from success() callback
  1271. @param textStatus textStatus from success() callback
  1272. */
  1273. ajaxNoticePosted: function (form, data, textStatus) {
  1274. var commandResult = $('#' + SN.C.S.CommandResult, data);
  1275. if (commandResult.length > 0) {
  1276. SN.U.showFeedback(form, 'success', commandResult.text());
  1277. } else {
  1278. // New notice post was successful. If on our timeline, show it!
  1279. var notice = document._importNode($('li', data)[0], true);
  1280. var notices = $('#notices_primary .notices:first');
  1281. var replyItem = form.closest('li.notice-reply');
  1282. if (replyItem.length > 0) {
  1283. // If this is an inline reply, remove the form...
  1284. var list = form.closest('.threaded-replies');
  1285. var id = $(notice).attr('id');
  1286. if ($('#' + id).length == 0) {
  1287. $(notice).insertBefore(replyItem);
  1288. } // else Realtime came through before us...
  1289. replyItem.remove();
  1290. } else if (notices.length > 0 && SN.U.belongsOnTimeline(notice)) {
  1291. // Not a reply. If on our timeline, show it at the top!
  1292. if ($('#' + notice.id).length === 0) {
  1293. var notice_irt_value = form.find('[name=inreplyto]').val();
  1294. var notice_irt = '#notices_primary #notice-' + notice_irt_value;
  1295. if ($('body')[0].id == 'conversation') {
  1296. if (notice_irt_value.length > 0 && $(notice_irt + ' .notices').length < 1) {
  1297. $(notice_irt).append('<ul class="notices"></ul>');
  1298. }
  1299. $($(notice_irt + ' .notices')[0]).append(notice);
  1300. } else {
  1301. notices.prepend(notice);
  1302. }
  1303. $('#' + notice.id)
  1304. .css({display: 'none'})
  1305. .fadeIn(2500);
  1306. SN.U.NoticeWithAttachment($('#' + notice.id));
  1307. SN.U.switchInputFormTab(null);
  1308. }
  1309. } else {
  1310. // Not on a timeline that this belongs on?
  1311. // Just show a success message.
  1312. // @fixme inline
  1313. SN.U.showFeedback(form, 'success', $('title', data).text());
  1314. }
  1315. }
  1316. form.resetForm();
  1317. form.find('[name=inreplyto]').val('');
  1318. form.find('.attach-status').remove();
  1319. SN.U.FormNoticeEnhancements(form);
  1320. SN.U.runCallbacks('notice_posted', {"notice": notice});
  1321. },
  1322. },
  1323. Init: {
  1324. /**
  1325. * If user is logged in, run setup code for the new notice form:
  1326. *
  1327. * - char counter
  1328. * - AJAX submission
  1329. * - location events
  1330. * - file upload events
  1331. */
  1332. NoticeForm: function () {
  1333. if ($('body.user_in').length > 0) {
  1334. // SN.Init.NoticeFormSetup() will get run
  1335. // when forms get displayed for the first time...
  1336. // Initialize the input form field
  1337. $('#input_form_nav .input_form_nav_tab.current').each(function () {
  1338. current_tab_id = $(this).attr('id').substring('input_form_nav_'.length);
  1339. SN.U.switchInputFormTab(current_tab_id, false);
  1340. });
  1341. // Make inline reply forms self-close when clicking out.
  1342. $('body').on('click', function (e) {
  1343. var openReplies = $('li.notice-reply');
  1344. if (openReplies.length > 0) {
  1345. var target = $(e.target);
  1346. openReplies.each(function () {
  1347. // Did we click outside this one?
  1348. var replyItem = $(this);
  1349. if (replyItem.has(e.target).length == 0) {
  1350. var textarea = replyItem.find('.notice_data-text:first');
  1351. var cur = $.trim(textarea.val());
  1352. // Only close if there's been no edit.
  1353. if (cur == '' || cur == textarea.data('initialText')) {
  1354. var parentNotice = replyItem.closest('li.notice');
  1355. replyItem.hide();
  1356. parentNotice.find('li.notice-reply-placeholder').show();
  1357. }
  1358. }
  1359. });
  1360. }
  1361. });
  1362. }
  1363. },
  1364. /**
  1365. * Encapsulate notice form setup for a single form.
  1366. * Plugins can add extra setup by monkeypatching this
  1367. * function.
  1368. *
  1369. * @param {jQuery} form
  1370. */
  1371. NoticeFormSetup: function (form) {
  1372. if (form.data('NoticeFormSetup')) {
  1373. return false;
  1374. }
  1375. SN.U.NoticeLocationAttach(form);
  1376. SN.U.FormNoticeUniqueID(form);
  1377. SN.U.FormNoticeXHR(form);
  1378. SN.U.FormNoticeEnhancements(form);
  1379. SN.U.NoticeDataAttach(form);
  1380. form.data('NoticeFormSetup', true);
  1381. },
  1382. /**
  1383. * Run setup code for notice timeline views items:
  1384. *
  1385. * - AJAX submission for fave/repeat/reply (if logged in)
  1386. * - Attachment link extras ('more' links)
  1387. */
  1388. Notices: function () {
  1389. if ($('body.user_in').length > 0) {
  1390. SN.U.NoticeRepeat();
  1391. SN.U.NoticeReply();
  1392. SN.U.NoticeInlineReplySetup();
  1393. SN.U.NoticeOptionsAjax();
  1394. }
  1395. SN.U.NoticeAttachments();
  1396. },
  1397. /**
  1398. * Run setup code for user & group profile page header area if logged in:
  1399. *
  1400. * - AJAX submission for sub/unsub/join/leave/nudge
  1401. * - AJAX form popup for direct-message
  1402. */
  1403. EntityActions: function () {
  1404. if ($('body.user_in').length > 0) {
  1405. $(document).on('click', '.form_user_subscribe', function () { SN.U.FormXHR($(this)); return false; });
  1406. $(document).on('click', '.form_user_unsubscribe', function () { SN.U.FormXHR($(this)); return false; });
  1407. $(document).on('click', '.form_group_join', function () { SN.U.FormXHR($(this)); return false; });
  1408. $(document).on('click', '.form_group_leave', function () { SN.U.FormXHR($(this)); return false; });
  1409. $(document).on('click', '.form_user_nudge', function () { SN.U.FormXHR($(this)); return false; });
  1410. $(document).on('click', '.form_peopletag_subscribe', function () { SN.U.FormXHR($(this)); return false; });
  1411. $(document).on('click', '.form_peopletag_unsubscribe', function () { SN.U.FormXHR($(this)); return false; });
  1412. $(document).on('click', '.form_user_add_peopletag', function () { SN.U.FormXHR($(this)); return false; });
  1413. $(document).on('click', '.form_user_remove_peopletag', function () { SN.U.FormXHR($(this)); return false; });
  1414. SN.U.NewDirectMessage();
  1415. }
  1416. },
  1417. ProfileSearch: function () {
  1418. if ($('body.user_in').length > 0) {
  1419. $(document).on('click', '.form_peopletag_edit_user_search input.submit', function () {
  1420. SN.U.FormProfileSearchXHR($(this).parents('form')); return false;
  1421. });
  1422. }
  1423. },
  1424. /**
  1425. * Run setup for the ajax people tags editor
  1426. *
  1427. * - show edit button
  1428. * - set event handle for click on edit button
  1429. * - loads people tag autocompletion data if not already present
  1430. * or if it is stale.
  1431. *
  1432. */
  1433. PeopleTags: function () {
  1434. $('.user_profile_tags .editable').append($('<button class="peopletags_edit_button"/>'));
  1435. $(document).on('click', '.peopletags_edit_button', function () {
  1436. var form = $(this).parents('dd').eq(0).find('form');
  1437. // We can buy time from the above animation
  1438. $.ajax({
  1439. url: _peopletagAC,
  1440. dataType: 'json',
  1441. data: {token: $('#token').val()},
  1442. ifModified: true,
  1443. success: function (data) {
  1444. // item.label is used to match
  1445. for (i=0; i < data.length; i++) {
  1446. data[i].label = data[i].tag;
  1447. }
  1448. SN.C.PtagACData = data;
  1449. }
  1450. });
  1451. $(this).parents('ul').eq(0).fadeOut(200, function () {form.fadeIn(200).find('input#tags')});
  1452. });
  1453. $(document).on('click', '.user_profile_tags form .submit', function () {
  1454. SN.U.FormPeopletagsXHR($(this).parents('form')); return false;
  1455. });
  1456. },
  1457. /**
  1458. * Set up any generic 'ajax' form so it submits via AJAX with auto-replacement.
  1459. */
  1460. AjaxForms: function () {
  1461. $(document).on('submit', 'form.ajax', function () {
  1462. SN.U.FormXHR($(this));
  1463. return false;
  1464. });
  1465. $(document).on('click', 'form.ajax input[type=submit]', function () {
  1466. // Some forms rely on knowing which submit button was clicked.
  1467. // Save a hidden input field which'll be picked up during AJAX
  1468. // submit...
  1469. var button = $(this);
  1470. var form = button.closest('form');
  1471. form.find('.hidden-submit-button').remove();
  1472. $('<input class="hidden-submit-button" type="hidden" />')
  1473. .attr('name', button.attr('name'))
  1474. .val(button.val())
  1475. .appendTo(form);
  1476. });
  1477. },
  1478. /**
  1479. * Add logic to any file upload forms to handle file size limits,
  1480. * on browsers that support basic FileAPI.
  1481. */
  1482. UploadForms: function () {
  1483. $('input[type=file]').change(function (event) {
  1484. if (typeof this.files === "object" && this.files.length > 0) {
  1485. var size = 0;
  1486. for (var i = 0; i < this.files.length; i++) {
  1487. size += this.files[i].size;
  1488. }
  1489. var max = SN.U.maxFileSize($(this.form));
  1490. if (max > 0 && size > max) {
  1491. var msg = 'File too large: maximum upload size is %d bytes.';
  1492. alert(msg.replace('%d', max));
  1493. // Clear the files.
  1494. $(this).val('');
  1495. event.preventDefault();
  1496. return false;
  1497. }
  1498. }
  1499. });
  1500. },
  1501. CheckBoxes: function () {
  1502. $("span[class='checkbox-wrapper']").addClass("unchecked");
  1503. $(".checkbox-wrapper").click(function () {
  1504. if ($(this).children("input").prop("checked")) {
  1505. // uncheck
  1506. $(this).children("input").prop("checked", false);
  1507. $(this).removeClass("checked");
  1508. $(this).addClass("unchecked");
  1509. $(this).children("label").text("Private?");
  1510. } else {
  1511. // check
  1512. $(this).children("input").prop("checked", true);
  1513. $(this).removeClass("unchecked");
  1514. $(this).addClass("checked");
  1515. $(this).children("label").text("Private");
  1516. }
  1517. });
  1518. }
  1519. }
  1520. };
  1521. /**
  1522. * Run initialization functions on DOM-ready.
  1523. *
  1524. * Note that if we're waiting on other scripts to load, this won't happen
  1525. * until that's done. To load scripts asynchronously without delaying setup,
  1526. * don't start them loading until after DOM-ready time!
  1527. */
  1528. $(function () {
  1529. SN.Init.AjaxForms();
  1530. SN.Init.UploadForms();
  1531. SN.Init.CheckBoxes();
  1532. if ($('.' + SN.C.S.FormNotice).length > 0) {
  1533. SN.Init.NoticeForm();
  1534. }
  1535. if ($('#content .notices').length > 0) {
  1536. SN.Init.Notices();
  1537. }
  1538. if ($('#content .entity_actions').length > 0) {
  1539. SN.Init.EntityActions();
  1540. }
  1541. if ($('#profile_search_results').length > 0) {
  1542. SN.Init.ProfileSearch();
  1543. }
  1544. if ($('.user_profile_tags .editable').length > 0) {
  1545. SN.Init.PeopleTags();
  1546. }
  1547. });