util.js 72 KB

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