ui.js 26 KB

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