ui.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. var
  2. /**
  3. * Minimum time between 2 notifications (ms)
  4. * @const
  5. * @type {number}
  6. **/
  7. NOTIFICATION_COOLDOWN = 30 * 1000 //30 sec
  8. /**
  9. * Maximum time the notification will stay visible (ms)
  10. * @const
  11. * @type {number}
  12. **/
  13. ,NOTIFICATION_DELAY = 5 * 1000 // 5 sec
  14. /** @type {number} */
  15. ,lastNotificationSpawn = 0
  16. ;
  17. function onContextUpdated() {
  18. var chanListFram = document.createDocumentFragment()
  19. ,sortedChans = SLACK.context.self ? Object.keys(SLACK.context.self.channels) : [];
  20. sortedChans.sort(function(a, b) {
  21. if (a[0] !== b[0]) {
  22. return a[0] - b[0];
  23. }
  24. return SLACK.context.getChannel(a).name.localeCompare(SLACK.context.getChannel(b).name);
  25. });
  26. sortedChans.forEach(function(chanId) {
  27. var chan =
  28. /**
  29. * SortedChan does not contains ims ids
  30. * @type {SlackChan|SlackGroup}
  31. **/
  32. (SLACK.context.getChannel(chanId));
  33. if (!chan.archived) {
  34. var chanListItem = createChanListItem(chan);
  35. if (chanListItem)
  36. chanListFram.appendChild(chanListItem);
  37. }
  38. });
  39. var sortedUsers = SLACK.context.users ? Object.keys(SLACK.context.users) : [];
  40. sortedUsers.sort(function(a, b) {
  41. return SLACK.context.users[a].name.localeCompare(SLACK.context.users[b].name);
  42. });
  43. sortedUsers.forEach(function(userId) {
  44. var user = SLACK.context.getMember(userId);
  45. if (!user.deleted) {
  46. var ims = user.ims
  47. ,imsListItem = createImsListItem(ims);
  48. if (imsListItem) {
  49. chanListFram.appendChild(imsListItem);
  50. }
  51. }
  52. });
  53. document.getElementById(R.id.chanList).textContent = "";
  54. document.getElementById(R.id.chanList).appendChild(chanListFram);
  55. setRoomFromHashBang();
  56. updateTitle();
  57. createContextBackground(function(imgData) {
  58. document.getElementById(R.id.context).style.backgroundImage = 'url(' +imgData +')';
  59. });
  60. }
  61. function onTypingUpdated() {
  62. var typing = SLACK.context.typing;
  63. for (var chanId in SLACK.context.self.channels) {
  64. if (!SLACK.context.self.channels[chanId].archived) {
  65. var dom = document.getElementById(chanId);
  66. if (typing[chanId])
  67. dom.classList.add(R.klass.chatList.typing);
  68. else
  69. dom.classList.remove(R.klass.chatList.typing);
  70. }
  71. }
  72. for (var userId in SLACK.context.users) {
  73. var ims = SLACK.context.users[userId].ims;
  74. if (ims && !ims.archived) {
  75. var dom = document.getElementById(ims.id);
  76. if (typing[ims.id])
  77. dom.classList.add(R.klass.chatList.typing);
  78. else
  79. dom.classList.remove(R.klass.chatList.typing);
  80. }
  81. }
  82. updateTypingChat();
  83. }
  84. function updateTypingChat() {
  85. var typing = SLACK.context.typing;
  86. if (SELECTED_ROOM && typing[SELECTED_ROOM.id]) {
  87. var typingUserNames = [], isOutOfSync = false;
  88. for (var i in typing[SELECTED_ROOM.id]) {
  89. var member = SLACK.context.getMember(i);
  90. if (member)
  91. typingUserNames.push(member.name);
  92. else
  93. isOutOfSync = true;
  94. }
  95. if (isOutOfSync)
  96. outOfSync();
  97. document.getElementById(R.id.typing).textContent = locale.areTyping(typingUserNames);
  98. } else {
  99. document.getElementById(R.id.typing).textContent = "";
  100. }
  101. }
  102. function onNetworkStateUpdated(isNetworkWorking) {
  103. isNetworkWorking ? document.body.classList.remove(R.klass.noNetwork) : document.body.classList.add(R.klass.noNetwork);
  104. updateTitle();
  105. }
  106. function onRoomSelected() {
  107. var name = SELECTED_ROOM.name || (SELECTED_ROOM.user ? SELECTED_ROOM.user.name : undefined);
  108. if (!name) {
  109. var members = [];
  110. for (var i in SELECTED_ROOM.members) {
  111. members.push(SELECTED_ROOM.members[i].name);
  112. }
  113. name = members.join(", ");
  114. }
  115. var roomLi = document.getElementById(SELECTED_ROOM.id);
  116. document.getElementById(R.id.currentRoom.title).textContent = name;
  117. onRoomUpdated();
  118. focusInput();
  119. document.getElementById(R.id.message.file.formContainer).classList.add(R.klass.hidden);
  120. markRoomAsRead(SELECTED_ROOM);
  121. if (REPLYING_TO) {
  122. REPLYING_TO = null;
  123. onReplyingToUpdated();
  124. }
  125. if (EDITING) {
  126. EDITING = null;
  127. onReplyingToUpdated();
  128. }
  129. updateTypingChat();
  130. }
  131. function onReplyingToUpdated() {
  132. if (REPLYING_TO) {
  133. document.body.classList.add(R.klass.replyingTo);
  134. var domParent = document.getElementById(R.id.message.replyTo)
  135. ,closeLink = document.createElement("a");
  136. closeLink.addEventListener("click", function() {
  137. REPLYING_TO = null;
  138. onReplyingToUpdated();
  139. });
  140. closeLink.className = R.klass.msg.replyTo.close;
  141. closeLink.textContent = 'x';
  142. domParent.textContent = "";
  143. domParent.appendChild(closeLink);
  144. domParent.appendChild(createMessageDom("reply_" +SELECTED_ROOM.id, REPLYING_TO, true));
  145. focusInput();
  146. } else {
  147. document.body.classList.remove(R.klass.replyingTo);
  148. document.getElementById(R.id.message.replyTo).textContent = "";
  149. focusInput();
  150. }
  151. }
  152. function onEditingUpdated() {
  153. if (EDITING) {
  154. document.body.classList.add(R.klass.replyingTo);
  155. var domParent = document.getElementById(R.id.message.replyTo)
  156. ,closeLink = document.createElement("a");
  157. closeLink.addEventListener("click", function() {
  158. EDITING = null;
  159. onEditingUpdated();
  160. });
  161. closeLink.className = R.klass.msg.replyTo.close;
  162. closeLink.textContent = 'x';
  163. domParent.textContent = "";
  164. domParent.appendChild(closeLink);
  165. domParent.appendChild(createMessageDom("edit_" +SELECTED_ROOM.id, EDITING, true));
  166. document.getElementById(R.id.message.input).value = EDITING.text;
  167. focusInput();
  168. } else {
  169. document.body.classList.remove(R.klass.replyingTo);
  170. document.getElementById(R.id.message.replyTo).textContent = "";
  171. focusInput();
  172. }
  173. }
  174. /**
  175. * @param {string} chanId
  176. * @param {string} msgId
  177. * @param {string} reaction
  178. **/
  179. window['toggleReaction'] = function(chanId, msgId, reaction) {
  180. var hist = SLACK.history[chanId];
  181. if (!hist)
  182. return;
  183. var msg = hist.getMessageById(msgId);
  184. if (msg) {
  185. if (msg.hasReactionForUser(reaction, SLACK.context.self.id)) {
  186. removeReaction(chanId, msgId, reaction);
  187. } else {
  188. addReaction(chanId, msgId, reaction);
  189. }
  190. }
  191. };
  192. /**
  193. * Try to resolve emoji from customized context
  194. * @param {string} emoji
  195. * @return {Element|string}
  196. **/
  197. function tryGetCustomEmoji(emoji) {
  198. var loop = {};
  199. while (!loop[emoji]) {
  200. var emojisrc= SLACK.context.emojis[emoji];
  201. if (emojisrc) {
  202. if (emojisrc.substr(0, 6) == "alias:") {
  203. loop[emoji] = true;
  204. emoji = emojisrc.substr(6);
  205. } else {
  206. var dom = document.createElement("span");
  207. dom.className = R.klass.emoji.custom +' ' +R.klass.emoji.emoji;
  208. dom.style.backgroundImage = "url('" +emojisrc +"')";
  209. return dom;
  210. }
  211. }
  212. return emoji; // Emoji not found, fallback to std emoji
  213. }
  214. return emoji; //loop detected, return first emoji
  215. }
  216. function makeEmojiDom(emojiCode) {
  217. var emoji = tryGetCustomEmoji(emojiCode);
  218. if (typeof emoji === "string" && "makeEmoji" in window)
  219. emoji = window['makeEmoji'](emoji);
  220. return typeof emoji === "string" ? null : emoji;
  221. }
  222. /**
  223. * replace all :emoji: codes with corresponding image
  224. * @param {string} inputString
  225. * @return {string}
  226. **/
  227. function formatEmojis(inputString) {
  228. return inputString.replace(/:([^ \t:]+):/g, function(returnFailed, emoji) {
  229. var emojiDom = makeEmojiDom(emoji);
  230. if (emojiDom) {
  231. var domParent = document.createElement("span");
  232. domParent.className = returnFailed === inputString ? R.klass.emoji.medium : R.klass.emoji.small;
  233. domParent.appendChild(emojiDom);
  234. return domParent.outerHTML;
  235. }
  236. return returnFailed;
  237. });
  238. }
  239. /**
  240. * @param {string} fullText
  241. * @return {string}
  242. **/
  243. function formatSlackText(fullText) {
  244. var msgContents = fullText.split(/\r?\n/g);
  245. for (var msgContentIndex=0, nbMsgContents = msgContents.length; msgContentIndex < nbMsgContents; msgContentIndex++) {
  246. var msgContent = msgContents[msgContentIndex].trim()
  247. ,_msgContent = ""
  248. ,currentMods = {}
  249. ,quote = false
  250. ,i =0
  251. msgContent = msgContent.replace(new RegExp('<([@#]?)([^>]*)>', 'g'),
  252. function(matched, type, entity) {
  253. var sub = entity.split('|');
  254. if (type === '@') {
  255. if (!sub[1]) {
  256. var user = SLACK.context.getMember(sub[0]);
  257. sub[1] = user ? ('@' +user.name) : locale.unknownMember;
  258. } else if ('@' !== sub[1][0]) {
  259. sub[1] = '@' +sub[1];
  260. }
  261. sub[0] = '#' +sub[0];
  262. sub[2] = R.klass.msg.link +' ' +R.klass.msg.linkuser;
  263. } else if (type === '#') {
  264. if (!sub[1]) {
  265. var chan = SLACK.context.getChannel(sub[0]);
  266. sub[1] = chan ? ('#' +chan.name) : locale.unknownChannel;
  267. } else if ('#' !== sub[1][0]) {
  268. sub[1] = '#' +sub[1];
  269. }
  270. sub[0] = '#' +sub[0];
  271. sub[2] = R.klass.msg.link +' ' +R.klass.msg.linkchan;
  272. } else if (sub[0].indexOf("://") !== -1) {
  273. if (!sub[1])
  274. sub[1] = sub[0];
  275. sub[2] = R.klass.msg.link;
  276. } else {
  277. return matched;
  278. }
  279. return '<a href="' +sub[0] +'" class="' +sub[2] +'"' +(!type ? ' target="_blank"' : '') +'>' +sub[1] +'</a>';
  280. });
  281. msgContent = formatEmojis(msgContent);
  282. var msgLength = msgContent.length;
  283. var isAlphadec = function(c) {
  284. return ((c >= 'A' && c <= 'Z') ||
  285. (c >= 'a' && c <= 'z') ||
  286. (c >= '0' && c <= '9') ||
  287. "àèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇߨøÅ寿œ".indexOf(c) !== -1);
  288. }
  289. ,checkEnd = function(str, pos, c) {
  290. while (str[pos]) {
  291. if (isAlphadec(str[pos]) && str[pos] != c && str[pos +1] == c) {
  292. return true;
  293. }
  294. pos++;
  295. }
  296. return false;
  297. } ,appendMod = function(mods) {
  298. if (!Object.keys(currentMods).length)
  299. return "";
  300. return '<span class="' +Object.keys(mods).join(' ') +'">';
  301. };
  302. // Skip trailing
  303. while (i < msgLength && (msgContent[i] === ' ' || msgContent[i] === '\t'))
  304. i++;
  305. if (msgContent.substr(i, 4) === '&gt;') {
  306. quote = true;
  307. i += 4;
  308. }
  309. for (; i < msgLength; i++) {
  310. var c = msgContent[i];
  311. if (c === '<') {
  312. do {
  313. _msgContent += msgContent[i++];
  314. } while (msgContent[i -1] !== '>');
  315. i--;
  316. continue;
  317. }
  318. if (!(currentMods[R.klass.msg.style.bold]) && c === '*' && msgContent[i +1] && checkEnd(msgContent, i, c)) {
  319. if (Object.keys(currentMods).length)
  320. _msgContent += '</span>';
  321. currentMods[R.klass.msg.style.bold] = true;
  322. _msgContent += appendMod(currentMods);
  323. } else if (!(currentMods[R.klass.msg.style.strike]) && c === '~' && msgContent[i +1] && checkEnd(msgContent, i, c)) {
  324. if (Object.keys(currentMods).length)
  325. _msgContent += '</span>';
  326. currentMods[R.klass.msg.style.strike] = true;
  327. _msgContent += appendMod(currentMods);
  328. } else if (!(currentMods[R.klass.msg.style.code]) && c === '`' && msgContent[i +1] && checkEnd(msgContent, i, c)) {
  329. if (Object.keys(currentMods).length)
  330. _msgContent += '</span>';
  331. currentMods[R.klass.msg.style.code] = true;
  332. _msgContent += appendMod(currentMods);
  333. } else if (!(currentMods[R.klass.msg.style.italic]) && c === '_' && msgContent[i +1] && checkEnd(msgContent, i, c)) {
  334. if (Object.keys(currentMods).length)
  335. _msgContent += '</span>';
  336. currentMods[R.klass.msg.style.italic] = true;
  337. _msgContent += appendMod(currentMods);
  338. } else {
  339. var finalFound = false;
  340. _msgContent += c;
  341. do {
  342. if ((currentMods[R.klass.msg.style.bold]) && c !== '*' && msgContent[i +1] === '*') {
  343. delete currentMods[R.klass.msg.style.bold];
  344. finalFound = true;
  345. } else if ((currentMods[R.klass.msg.style.strike]) && c !== '~' && msgContent[i +1] === '~') {
  346. delete currentMods[R.klass.msg.style.strike];
  347. finalFound = true;
  348. } else if ((currentMods[R.klass.msg.style.code]) && c !== '`' && msgContent[i +1] === '`') {
  349. delete currentMods[R.klass.msg.style.code];
  350. finalFound = true;
  351. } else if ((currentMods[R.klass.msg.style.italic]) && c !== '_' && msgContent[i +1] === '_') {
  352. delete currentMods[R.klass.msg.style.italic];
  353. finalFound = true;
  354. } else {
  355. break;
  356. }
  357. c = msgContent[++i];
  358. } while (i < msgLength);
  359. if (finalFound)
  360. _msgContent += '</span>' +appendMod(currentMods);
  361. }
  362. }
  363. if (currentMods) {
  364. // Should not append
  365. _msgContent += '</span>';
  366. }
  367. if (quote)
  368. msgContents[msgContentIndex] = '<span class="' +R.klass.msg.style.quote +'">' +_msgContent +'</span>';
  369. else
  370. msgContents[msgContentIndex] = _msgContent;
  371. }
  372. return msgContents.join('<br/>');
  373. }
  374. /**
  375. * @param {string} channelId
  376. * @param {SlackMessage} msg
  377. * @param {boolean=} skipAttachment
  378. * @return {Element}
  379. **/
  380. function doCreateMeMessageDom(channelId, msg, skipAttachment) {
  381. var dom = doCreateMessageDom(channelId, msg, skipAttachment);
  382. dom.classList.add(R.klass.msg.meMessage);
  383. return dom;
  384. }
  385. /**
  386. * @param {string} channelId
  387. * @param {SlackMessage} msg
  388. * @param {boolean=} skipAttachment
  389. * @return {Element}
  390. **/
  391. function createMessageDom(channelId, msg, skipAttachment) {
  392. var dom = (msg.isMeMessage ?
  393. doCreateMeMessageDom(channelId, msg, skipAttachment):
  394. doCreateMessageDom(channelId, msg, skipAttachment));
  395. if (msg.edited)
  396. dom.classList.add(R.klass.msg.edited);
  397. return dom;
  398. }
  399. /**
  400. * @param {number} unreadhi
  401. * @param {number} unread
  402. **/
  403. function setFavicon(unreadhi, unread) {
  404. if (!unreadhi && !unread)
  405. document.getElementById(R.id.favicon).href = "favicon_ok.png";
  406. else
  407. document.getElementById(R.id.favicon).href = "favicon.png?h="+unreadhi+"&m="+unread;
  408. }
  409. function setNetErrorFavicon() {
  410. document.getElementById(R.id.favicon).href = "favicon_err.png";
  411. }
  412. function updateTitle() {
  413. var hasUnread = 0
  414. ,hasHl = 0
  415. ,title = "";
  416. if (NEXT_RETRY) {
  417. title = '!' +locale.netErrorShort +' - ';
  418. setNetErrorFavicon();
  419. } else {
  420. for (var i in UNREAD_CHANS) {
  421. if (UNREAD_CHANS.hasOwnProperty(i)) {
  422. hasUnread += UNREAD_CHANS[i].unread;
  423. hasHl += UNREAD_CHANS[i].hl;
  424. }
  425. }
  426. if (hasHl)
  427. title = "(!" +hasHl +") - ";
  428. else if (hasUnread)
  429. title = "(" +hasUnread +") - ";
  430. setFavicon(hasHl, hasUnread);
  431. }
  432. title += SLACK.context.team.name;
  433. document.title = title;
  434. }
  435. function spawnNotification() {
  436. if (!("Notification" in window))
  437. {}
  438. else if (Notification.permission === "granted") {
  439. var now = Date.now();
  440. if (lastNotificationSpawn + NOTIFICATION_COOLDOWN < now) {
  441. var n = new Notification(locale.newMessage);
  442. lastNotificationSpawn = now;
  443. setTimeout(function() {
  444. n.close();
  445. }, NOTIFICATION_DELAY);
  446. }
  447. }
  448. else if (Notification.permission !== "denied")
  449. Notification.requestPermission();
  450. }
  451. function onRoomUpdated() {
  452. var chatFrag = document.createDocumentFragment()
  453. ,currentRoomId = SELECTED_ROOM.id
  454. ,prevMsg = null
  455. ,firstTsCombo = 0
  456. ,prevMsgDom = null;
  457. if (SLACK.history[currentRoomId])
  458. SLACK.history[currentRoomId].messages.forEach(function(msg) {
  459. if (!msg.removed) {
  460. var dom = createMessageDom(currentRoomId, msg);
  461. if (prevMsg && prevMsg.userId === msg.userId && msg.userId) {
  462. dom.classList.add(R.klass.msg.same.author);
  463. if (Math.abs(firstTsCombo -msg.ts) < 30)
  464. prevMsgDom.classList.add(R.klass.msg.same.ts);
  465. else
  466. firstTsCombo = msg.ts;
  467. } else
  468. firstTsCombo = msg.ts;
  469. prevMsg = msg;
  470. prevMsgDom = dom;
  471. chatFrag.appendChild(dom);
  472. }
  473. });
  474. var content = document.getElementById(R.id.currentRoom.content);
  475. content.textContent = "";
  476. content.appendChild(chatFrag);
  477. //TODO scroll lock
  478. content.scrollTop = content.scrollHeight -content.clientHeight;
  479. }
  480. function chatClickDelegate(e) {
  481. var target = e.target
  482. ,getMessageId = function(e, target) {
  483. target = target || e.target;
  484. while (target !== e.currentTarget && target) {
  485. if (target.classList.contains(R.klass.msg.item)) {
  486. return target.id;
  487. }
  488. target = target.parentElement;
  489. }
  490. };
  491. while (target !== e.currentTarget && target) {
  492. if (target.classList.contains(R.klass.msg.hover.container)) {
  493. return;
  494. } else if (target.parentElement && target.parentElement.classList.contains(R.klass.msg.hover.container)) {
  495. var messageId = getMessageId(e, target);
  496. if (messageId) {
  497. messageId = parseFloat(messageId.split("_")[1]);
  498. var msg = SLACK.history[SELECTED_ROOM.id].getMessage(messageId);
  499. if (msg && target.classList.contains(R.klass.msg.hover.reply)) {
  500. if (EDITING) {
  501. EDITING = null;
  502. onEditingUpdated();
  503. }
  504. if (REPLYING_TO !== msg) {
  505. REPLYING_TO = msg;
  506. onReplyingToUpdated();
  507. }
  508. } else if (msg && target.classList.contains(R.klass.msg.hover.reaction)) {
  509. EMOJI_BAR.spawn(document.body, function(emoji) {
  510. if (emoji)
  511. addReaction(SELECTED_ROOM.id, msg.id, emoji);
  512. });
  513. } else if (msg && target.classList.contains(R.klass.msg.hover.edit)) {
  514. if (REPLYING_TO) {
  515. REPLYING_TO = null;
  516. onReplyingToUpdated();
  517. }
  518. if (EDITING !== msg) {
  519. EDITING = msg;
  520. onEditingUpdated();
  521. }
  522. } else if (msg && target.classList.contains(R.klass.msg.hover.remove)) {
  523. //TODO promt confirm
  524. if (REPLYING_TO) {
  525. REPLYING_TO = null;
  526. onReplyingToUpdated();
  527. }
  528. if (EDITING) {
  529. EDITING = null;
  530. onEditingUpdated();
  531. }
  532. removeMsg(SELECTED_ROOM, msg);
  533. }
  534. }
  535. return;
  536. }
  537. target = target.parentElement;
  538. }
  539. }
  540. function focusInput() {
  541. document.getElementById(R.id.message.input).focus();
  542. }
  543. function setRoomFromHashBang() {
  544. var hashId = document.location.hash.substr(1)
  545. ,room = SLACK.context.getChannel(hashId)
  546. ,user = SLACK.context.getMember(hashId);
  547. if (room && room !== SELECTED_ROOM)
  548. selectRoom(room);
  549. else if (user && user.ims)
  550. selectRoom(user.ims);
  551. }
  552. document.addEventListener('DOMContentLoaded', function() {
  553. initLang();
  554. document.getElementById(R.id.currentRoom.content).addEventListener("click", chatClickDelegate);
  555. window.addEventListener("hashchange", function(e) {
  556. if (document.location.hash && document.location.hash[0] === '#') {
  557. setRoomFromHashBang();
  558. }
  559. });
  560. document.getElementById(R.id.message.file.cancel).addEventListener("click", function(e) {
  561. e.preventDefault();
  562. document.getElementById(R.id.message.file.error).classList.add(R.klass.hidden);
  563. document.getElementById(R.id.message.file.formContainer).classList.add(R.klass.hidden);
  564. document.getElementById(R.id.message.file.fileInput).value = "";
  565. return false;
  566. });
  567. document.getElementById(R.id.message.file.form).addEventListener("submit", function(e) {
  568. e.preventDefault();
  569. var fileInput = document.getElementById(R.id.message.file.fileInput)
  570. ,filename = fileInput.value;
  571. if (filename) {
  572. filename = filename.substr(filename.lastIndexOf('\\') +1);
  573. uploadFile(SELECTED_ROOM, filename, fileInput.files[0], function(errorMsg) {
  574. var error = document.getElementById(R.id.message.file.error);
  575. if (errorMsg) {
  576. error.textContent = errorMsg;
  577. error.classList.remove(R.klass.hidden);
  578. } else {
  579. error.classList.add(R.klass.hidden);
  580. document.getElementById(R.id.message.file.fileInput).value = "";
  581. document.getElementById(R.id.message.file.formContainer).classList.add(R.klass.hidden);
  582. }
  583. });
  584. }
  585. return false;
  586. });
  587. document.getElementById(R.id.message.file.bt).addEventListener("click", function(e) {
  588. e.preventDefault();
  589. if (SELECTED_ROOM) {
  590. document.getElementById(R.id.message.file.formContainer).classList.remove(R.klass.hidden);
  591. }
  592. return false;
  593. });
  594. document.getElementById(R.id.message.form).addEventListener("submit", function(e) {
  595. e.preventDefault();
  596. var input =document.getElementById(R.id.message.input);
  597. if (SELECTED_ROOM && input.value) {
  598. if (onTextEntered(input.value)) {
  599. input.value = "";
  600. if (REPLYING_TO) {
  601. REPLYING_TO = null;
  602. onReplyingToUpdated();
  603. }
  604. if (EDITING) {
  605. EDITING = null;
  606. onReplyingToUpdated();
  607. }
  608. document.getElementById(R.id.message.slashComplete).textContent = '';
  609. }
  610. }
  611. focusInput();
  612. return false;
  613. });
  614. window.addEventListener('blur', function() {
  615. window.hasFocus = false;
  616. });
  617. window.addEventListener('focus', function() {
  618. window.hasFocus = true;
  619. lastNotificationSpawn = 0;
  620. if (SELECTED_ROOM)
  621. markRoomAsRead(SELECTED_ROOM);
  622. focusInput();
  623. });
  624. var lastKeyDown = 0;
  625. document.getElementById(R.id.message.input).addEventListener('input', function() {
  626. if (SELECTED_ROOM) {
  627. var now = Date.now();
  628. if (lastKeyDown + 3000 < now) {
  629. sendTyping(SELECTED_ROOM);
  630. lastKeyDown = now;
  631. }
  632. var commands = []
  633. ,input = this.value;
  634. if (this.value[0] === '/') {
  635. var endCmd = input.indexOf(' ')
  636. ,inputFinished = endCmd !== -1;
  637. endCmd = endCmd === -1 ? input.length : endCmd;
  638. var inputCmd = input.substr(0, endCmd);
  639. for (var i in SLACK.context.commands.data) {
  640. var currentCmd = SLACK.context.commands.data[i]
  641. if ((!inputFinished && currentCmd.name.substr(0, endCmd) === inputCmd) ||
  642. (inputFinished && currentCmd.name === inputCmd))
  643. commands.push(currentCmd);
  644. }
  645. }
  646. if (commands.length > 5) commands = []; // TODO Do not display to mush at once
  647. commands.sort(function(a, b) { return a.name.localeCompare(b.name); });
  648. var slashDom = document.getElementById(R.id.message.slashComplete)
  649. ,slashFrag = document.createDocumentFragment();
  650. slashDom.textContent = '';
  651. for (var i =0, nbCmd = commands.length; i < nbCmd; i++)
  652. slashFrag.appendChild(createSlashAutocompleteDom(commands[i]));
  653. slashDom.appendChild(slashFrag);
  654. }
  655. });
  656. window.hasFocus = true;
  657. //Emoji closure
  658. (function() {
  659. var emojiButton = document.getElementById(R.id.message.emoji);
  660. if ('makeEmoji' in window) {
  661. var emojiDom = window['makeEmoji']('smile');
  662. if (emojiDom) {
  663. emojiButton.innerHTML = "<span class='" +R.klass.emoji.small +"'>" +emojiDom.outerHTML +"</span>";
  664. } else {
  665. emojiButton.style.backgroundImage = 'url("smile.svg")';
  666. }
  667. emojiDom = window['makeEmoji']('paperclip');
  668. if (emojiDom) {
  669. document.getElementById(R.id.message.file.bt).innerHTML = "<span class='" +R.klass.emoji.small +"'>" +emojiDom.outerHTML +"</span>";
  670. } else {
  671. document.getElementById(R.id.message.file.bt).style.backgroundImage = 'url("public/paperclip.svg")';
  672. }
  673. emojiButton.addEventListener("click", function() {
  674. EMOJI_BAR.spawn(document.body, function(e) {
  675. if (e) document.getElementById(R.id.message.input).value += ":"+e+":";
  676. focusInput();
  677. });
  678. });
  679. } else {
  680. emojiButton.classList.add(R.klass.hidden);
  681. }
  682. })();
  683. startPolling();
  684. });