ui.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  1. var
  2. /** @type {SlackMessage|null} */
  3. REPLYING_TO = null
  4. /**
  5. * Minimum time between 2 notifications (ms)
  6. * @const
  7. * @type {number}
  8. **/
  9. ,NOTIFICATION_COOLDOWN = 30 * 1000 //30 sec
  10. /**
  11. * Maximum time the notification will stay visible (ms)
  12. * @const
  13. * @type {number}
  14. **/
  15. ,NOTIFICATION_DELAY = 5 * 1000 // 5 sec
  16. /** @type {number} */
  17. ,lastNotificationSpawn = 0
  18. ;
  19. /**
  20. * @param {SlackChan|SlackGroup} chan
  21. * @return {Element}
  22. **/
  23. function createChanListItem(chan) {
  24. var dom = document.createElement("li")
  25. ,link = document.createElement("a");
  26. dom.id = chan.id;
  27. link.href = '#' +chan.id;
  28. if (chan.id[0] === 'D')
  29. dom.className = R.klass.chatList.entry + " " +R.klass.chatList.typeDirect;
  30. else if (chan.id[0] === 'G')
  31. dom.className = R.klass.chatList.entry + " " +R.klass.chatList.typeGroup;
  32. else if (chan.id[0] === 'C')
  33. dom.className = R.klass.chatList.entry + " " +R.klass.chatList.typeChannel;
  34. link.textContent = chan.name;
  35. dom.appendChild(link);
  36. return dom;
  37. }
  38. /**
  39. * @param {SlackIms} ims
  40. * @return {Element}
  41. **/
  42. function createImsListItem(ims) {
  43. var dom = document.createElement("li")
  44. ,link = document.createElement("a");
  45. dom.id = ims.id;
  46. link.href = '#' +ims.id;
  47. dom.className = R.klass.chatList.entry;
  48. link.textContent = ims.user.name;
  49. dom.appendChild(link);
  50. return dom;
  51. }
  52. function onContextUpdated() {
  53. var chanListFram = document.createDocumentFragment()
  54. ,sortedChans = SLACK.context.self ? Object.keys(SLACK.context.self.channels) : [];
  55. sortedChans.sort(function(a, b) {
  56. if (a[0] !== b[0]) {
  57. return a[0] - b[0];
  58. }
  59. return (SLACK.context.channels[a] || SLACK.context.groups[a]).name.localeCompare((SLACK.context.channels[b] || SLACK.context.groups[b]).name);
  60. });
  61. sortedChans.forEach(function(chanId) {
  62. var chan = SLACK.context.channels[chanId] || SLACK.context.groups[chanId]
  63. ,chanListItem = createChanListItem(chan);
  64. if (chanListItem) {
  65. chanListFram.appendChild(chanListItem);
  66. }
  67. });
  68. var sortedUsers = SLACK.context.users ? Object.keys(SLACK.context.users) : [];
  69. sortedUsers.sort(function(a, b) {
  70. return SLACK.context.users[a].name.localeCompare(SLACK.context.users[b].name);
  71. });
  72. sortedUsers.forEach(function(userId) {
  73. var ims = SLACK.context.users[userId].ims
  74. ,imsListItem = createImsListItem(ims);
  75. if (imsListItem) {
  76. chanListFram.appendChild(imsListItem);
  77. }
  78. });
  79. document.getElementById(R.id.chanList).textContent = "";
  80. document.getElementById(R.id.chanList).appendChild(chanListFram);
  81. setRoomFromHashBang();
  82. updateTitle();
  83. }
  84. function onNetworkStateUpdated(isNetworkWorking) {
  85. isNetworkWorking ? document.body.classList.remove(R.klass.noNetwork) : document.body.classList.add(R.klass.noNetwork);
  86. updateTitle();
  87. }
  88. function onRoomSelected() {
  89. var name = SELECTED_ROOM.name || (SELECTED_ROOM.user ? SELECTED_ROOM.user.name : undefined);
  90. if (!name) {
  91. var members = [];
  92. for (var i in SELECTED_ROOM.members) {
  93. members.push(SELECTED_ROOM.members[i].name);
  94. }
  95. name = members.join(", ");
  96. }
  97. var roomLi = document.getElementById(SELECTED_ROOM.id);
  98. document.getElementById(R.id.currentRoom.title).textContent = name;
  99. onRoomUpdated();
  100. focusInput();
  101. document.getElementById(R.id.message.file.formContainer).classList.add(R.klass.hidden);
  102. markRoomAsRead(SELECTED_ROOM);
  103. if (REPLYING_TO) {
  104. REPLYING_TO = null;
  105. onReplyingToUpdated();
  106. }
  107. }
  108. function onReplyingToUpdated() {
  109. if (REPLYING_TO) {
  110. document.body.classList.add(R.klass.replyingTo);
  111. var domParent = document.getElementById(R.id.message.replyTo)
  112. ,closeLink = document.createElement("a");
  113. closeLink.addEventListener("click", function() {
  114. REPLYING_TO = null;
  115. onReplyingToUpdated();
  116. });
  117. closeLink.className = R.klass.msg.replyTo.close;
  118. closeLink.textContent = 'x';
  119. domParent.textContent = "";
  120. domParent.appendChild(closeLink);
  121. domParent.appendChild(createMessageDom("reply_" +SELECTED_ROOM.id, REPLYING_TO, true));
  122. } else {
  123. document.body.classList.remove(R.klass.replyingTo);
  124. }
  125. }
  126. /**
  127. * @param {string} chanId
  128. * @param {string} msgId
  129. * @param {string} reaction
  130. * @param {Array.<string>} users
  131. * @return {Element|null}
  132. **/
  133. function createReactionDom(chanId, msgId, reaction, users) {
  134. var emojiDom = makeEmojiDom(reaction);
  135. if (emojiDom) {
  136. var dom = document.createElement("li")
  137. ,a = document.createElement("a")
  138. ,emojiContainer = document.createElement("span")
  139. ,userList = document.createElement("span")
  140. ,userNames = [];
  141. for (var i =0, nbUser = users.length; i < nbUser; i++) {
  142. var user = SLACK.context.getMember(users[i]);
  143. if (user)
  144. userNames.push(user.name);
  145. }
  146. userNames.sort();
  147. userList.textContent = userNames.join(", ");
  148. emojiContainer.appendChild(emojiDom);
  149. emojiContainer.className = R.klass.emoji.small;
  150. a.href = "javascript:toggleReaction('" +chanId +"', '" +msgId +"', '" +reaction +"')";
  151. a.appendChild(emojiContainer);
  152. a.appendChild(userList);
  153. dom.className = R.klass.msg.reactions.item;
  154. dom.appendChild(a);
  155. return dom;
  156. }
  157. return null;
  158. }
  159. /**
  160. * @param {string} chanId
  161. * @param {string} msgId
  162. * @param {string} reaction
  163. **/
  164. window['toggleReaction'] = function(chanId, msgId, reaction) {
  165. var hist = SLACK.history[chanId];
  166. if (!hist)
  167. return;
  168. var msg = hist.getMessageById(msgId);
  169. if (msg) {
  170. if (msg.hasReactionForUser(reaction, SLACK.context.self.id)) {
  171. removeReaction(chanId, msgId, reaction);
  172. } else {
  173. addReaction(chanId, msgId, reaction);
  174. }
  175. }
  176. };
  177. /**
  178. * @param {string} channelId
  179. * @param {SlackMessage} msg
  180. * @param {boolean=} skipAttachment
  181. * @return {Element}
  182. **/
  183. function doCreateMessageDom(channelId, msg, skipAttachment) {
  184. var dom = document.createElement("div")
  185. ,ts = document.createElement("div")
  186. ,text = document.createElement("div")
  187. ,author = document.createElement("div")
  188. ,authorImg = document.createElement("img")
  189. ,authorName = document.createElement("span")
  190. ,hover = document.createElement("ul")
  191. ,hoverReply = document.createElement("li")
  192. ,attachments = document.createElement("ul")
  193. ,reactions = document.createElement("ul")
  194. ,sender = msg.raw["user"] ?
  195. SLACK.context.users[msg.raw["user"]] :
  196. SLACK.context.bots[msg.raw["bot_id"]];
  197. dom.id = channelId +"_" +msg.ts;
  198. dom.className = R.klass.msg.item;
  199. ts.className = R.klass.msg.ts;
  200. text.className = R.klass.msg.msg;
  201. author.className = R.klass.msg.author;
  202. authorImg.className = R.klass.msg.authorAvatar;
  203. authorName.className = R.klass.msg.authorname;
  204. hover.className = R.klass.msg.hover.container;
  205. hoverReply.className = R.klass.msg.hover.reply;
  206. ts.innerHTML = formatDate(msg.ts);
  207. text.innerHTML = formatSlackText(msg.raw["text"] || "");
  208. authorName.textContent = sender ? sender.name : (msg.raw["username"] || "?");
  209. if (!sender && !msg.raw["username"])
  210. text.textContent = msg.raw["subtype"] || JSON.stringify(msg.raw);
  211. authorImg.src = sender ? sender.icons.image_48 : "";
  212. author.appendChild(authorImg);
  213. author.appendChild(authorName);
  214. hover.appendChild(hoverReply);
  215. dom.appendChild(author);
  216. dom.appendChild(text);
  217. dom.appendChild(ts);
  218. dom.appendChild(attachments);
  219. dom.appendChild(reactions);
  220. attachments.className = R.klass.msg.attachment.list;
  221. reactions.className = R.klass.msg.reactions.container;
  222. if (skipAttachment !== true) {
  223. if (msg.reactions) for (var reaction in msg.reactions) {
  224. var reac = createReactionDom(channelId, msg.id, reaction, msg.reactions[reaction]);
  225. reac && reactions.appendChild(reac);
  226. }
  227. if (msg.raw["attachments"]) {
  228. msg.raw["attachments"].forEach(function(attachment) {
  229. var domAttachment = createAttachmentDom(channelId, msg, attachment);
  230. if (domAttachment)
  231. attachments.appendChild(domAttachment);
  232. });
  233. }
  234. }
  235. dom.appendChild(hover);
  236. return dom;
  237. }
  238. /**
  239. * @param {string|number} ts seconds between EPOCH and event
  240. * @return {string}
  241. **/
  242. function formatDate(ts) {
  243. if (typeof(ts) !== "string")
  244. ts = parseFloat(ts);
  245. return (new Date(ts * 1000)).toLocaleTimeString();
  246. }
  247. /**
  248. * Try to resolve emoji from customized context
  249. * @param {string} emoji
  250. * @return {Element|string}
  251. **/
  252. function tryGetCustomEmoji(emoji) {
  253. var loop = {};
  254. while (!loop[emoji]) {
  255. var emojisrc= SLACK.context.emojis[emoji];
  256. if (emojisrc) {
  257. if (emojisrc.substr(0, 6) == "alias:") {
  258. loop[emoji] = true;
  259. emoji = emojisrc.substr(6);
  260. } else {
  261. var dom = document.createElement("span");
  262. dom.className = R.klass.emoji.custom +' ' +R.klass.emoji.emoji;
  263. dom.style.backgroundImage = "url('" +emojisrc +"')";
  264. return dom;
  265. }
  266. }
  267. return emoji; // Emoji not found, fallback to std emoji
  268. }
  269. return emoji; //loop detected, return first emoji
  270. }
  271. function makeEmojiDom(emojiCode) {
  272. var emoji = tryGetCustomEmoji(emojiCode);
  273. if (typeof emoji === "string" && "makeEmoji" in window)
  274. emoji = window['makeEmoji'](emoji);
  275. return typeof emoji === "string" ? null : emoji;
  276. }
  277. /**
  278. * replace all :emoji: codes with corresponding image
  279. * @param {string} inputString
  280. * @return {string}
  281. **/
  282. function formatEmojis(inputString) {
  283. return inputString.replace(/:(\w+):/g, function(returnFailed, emoji) {
  284. var emojiDom = makeEmojiDom(emoji);
  285. if (emojiDom) {
  286. var domParent = document.createElement("span");
  287. domParent.className = R.klass.emoji.small;
  288. domParent.appendChild(emojiDom);
  289. return domParent.outerHTML;
  290. }
  291. return returnFailed;
  292. });
  293. }
  294. /**
  295. * @param {string} fullText
  296. * @return {string}
  297. **/
  298. function formatSlackText(fullText) {
  299. var msgContents = fullText.split(/\r?\n/g);
  300. for (var msgContentIndex=0, nbMsgContents = msgContents.length; msgContentIndex < nbMsgContents; msgContentIndex++) {
  301. var msgContent = msgContents[msgContentIndex]
  302. ,_msgContent = ""
  303. ,currentMods = {}
  304. ,quote = false
  305. ,i =0
  306. msgContent = msgContent.replace(new RegExp('<([@#]?)([^>]*)>', 'g'),
  307. function(matched, type, entity) {
  308. var sub = entity.split('|');
  309. if (type === '@') {
  310. if (!sub[1]) {
  311. var user = SLACK.context.getMember(sub[0]);
  312. sub[1] = user ? ('@' +user.name) : locale.unknownMember;
  313. } else if ('@' !== sub[1][0]) {
  314. sub[1] = '@' +sub[1];
  315. }
  316. sub[0] = '#' +sub[0];
  317. sub[2] = R.klass.msg.link +' ' +R.klass.msg.linkuser;
  318. } else if (type === '#') {
  319. if (!sub[1]) {
  320. var chan = SLACK.context.getChannel(sub[0]);
  321. sub[1] = chan ? ('#' +chan.name) : locale.unknownChannel;
  322. } else if ('#' !== sub[1][0]) {
  323. sub[1] = '#' +sub[1];
  324. }
  325. sub[0] = '#' +sub[0];
  326. sub[2] = R.klass.msg.link +' ' +R.klass.msg.linkchan;
  327. } else if (sub[0].indexOf("://") !== -1) {
  328. if (!sub[1])
  329. sub[1] = sub[0];
  330. sub[2] = R.klass.msg.link;
  331. } else {
  332. return matched;
  333. }
  334. return '<a href="' +sub[0] +'" class="' +sub[2] +'"' +(!type ? ' target="_blank"' : '') +'>' +sub[1] +'</a>';
  335. });
  336. msgContent = formatEmojis(msgContent);
  337. var msgLength = msgContent.length;
  338. var checkEnd = function(str, pos, c) {
  339. while (str[pos]) {
  340. if (str[pos] != ' ' && str[pos] != c && str[pos +1] == c) {
  341. return true;
  342. }
  343. pos++;
  344. }
  345. return false;
  346. } ,appendMod = function(mods) {
  347. if (!Object.keys(currentMods).length)
  348. return "";
  349. return '<span class="' +Object.keys(mods).join(' ') +'">';
  350. };
  351. // Skip trailing
  352. while (i < msgLength && (msgContent[i] === ' ' || msgContent[i] === '\t'))
  353. i++;
  354. if (msgContent.substr(i, 4) === '&gt;') {
  355. quote = true;
  356. i += 4;
  357. }
  358. for (; i < msgLength; i++) {
  359. var c = msgContent[i];
  360. if (c === '<') {
  361. do {
  362. _msgContent += msgContent[i++];
  363. } while (msgContent[i -1] !== '>');
  364. i--;
  365. continue;
  366. }
  367. if (!(currentMods[R.klass.msg.style.bold]) && c === '*' && msgContent[i +1] && checkEnd(msgContent, i, c)) {
  368. if (Object.keys(currentMods).length)
  369. _msgContent += '</span>';
  370. currentMods[R.klass.msg.style.bold] = true;
  371. _msgContent += appendMod(currentMods);
  372. } else if (!(currentMods[R.klass.msg.style.strike]) && c === '~' && msgContent[i +1] && checkEnd(msgContent, i, c)) {
  373. if (Object.keys(currentMods).length)
  374. _msgContent += '</span>';
  375. currentMods[R.klass.msg.style.strike] = true;
  376. _msgContent += appendMod(currentMods);
  377. } else if (!(currentMods[R.klass.msg.style.code]) && c === '`' && msgContent[i +1] && checkEnd(msgContent, i, c)) {
  378. if (Object.keys(currentMods).length)
  379. _msgContent += '</span>';
  380. currentMods[R.klass.msg.style.code] = true;
  381. _msgContent += appendMod(currentMods);
  382. } else if (!(currentMods[R.klass.msg.style.italic]) && c === '_' && msgContent[i +1] && checkEnd(msgContent, i, c)) {
  383. if (Object.keys(currentMods).length)
  384. _msgContent += '</span>';
  385. currentMods[R.klass.msg.style.italic] = true;
  386. _msgContent += appendMod(currentMods);
  387. } else {
  388. var finalFound = false;
  389. _msgContent += c;
  390. do {
  391. if ((currentMods[R.klass.msg.style.bold]) && c !== '*' && msgContent[i +1] === '*') {
  392. delete currentMods[R.klass.msg.style.bold];
  393. finalFound = true;
  394. } else if ((currentMods[R.klass.msg.style.strike]) && c !== '~' && msgContent[i +1] === '~') {
  395. delete currentMods[R.klass.msg.style.strike];
  396. finalFound = true;
  397. } else if ((currentMods[R.klass.msg.style.code]) && c !== '`' && msgContent[i +1] === '`') {
  398. delete currentMods[R.klass.msg.style.code];
  399. finalFound = true;
  400. } else if ((currentMods[R.klass.msg.style.italic]) && c !== '_' && msgContent[i +1] === '_') {
  401. delete currentMods[R.klass.msg.style.italic];
  402. finalFound = true;
  403. } else {
  404. break;
  405. }
  406. c = msgContent[++i];
  407. } while (i < msgLength);
  408. if (finalFound)
  409. _msgContent += '</span>' +appendMod(currentMods);
  410. }
  411. }
  412. if (currentMods) {
  413. // Should not append
  414. _msgContent += '</span>';
  415. }
  416. if (quote)
  417. msgContents[msgContentIndex] = '<span class="' +R.klass.msg.style.quote +'">' +_msgContent +'</span>';
  418. else
  419. msgContents[msgContentIndex] = _msgContent;
  420. }
  421. return msgContents.join('<br/>');
  422. }
  423. /**
  424. * @param {string} channelId
  425. * @param {SlackMessage} msg
  426. * @param {*} attachment
  427. * @return {Element|null}
  428. **/
  429. function createAttachmentDom(channelId, msg, attachment) {
  430. var rootDom = document.createElement("li")
  431. ,attachmentBlock = document.createElement("div")
  432. ,pretext = document.createElement("div")
  433. ,titleBlock = document.createElement("a")
  434. ,authorBlock = document.createElement("div")
  435. ,authorImg = document.createElement("img")
  436. ,authorName = document.createElement("a")
  437. ,textBlock = document.createElement("div")
  438. ,textDom = document.createElement("div")
  439. ,thumbImgDom = document.createElement("img")
  440. ,imgDom = document.createElement("img")
  441. ,footerBlock = document.createElement("div")
  442. ,footerIcon = document.createElement("img")
  443. ,footerText = document.createElement("span")
  444. ,footerTs = document.createElement("span")
  445. ;
  446. rootDom.className = R.klass.msg.attachment.container;
  447. //Color
  448. var color = "#e3e4e6";
  449. if (attachment["color"]) {
  450. if (attachment["color"][0] === '#')
  451. color = attachment["color"][0];
  452. else if (attachment["color"] === "good")
  453. color = "#2fa44f";
  454. else if (attachment["color"] === "warning")
  455. color = "#de9e31";
  456. else if (attachment["color"] === "danger")
  457. color = "#d50200";
  458. }
  459. attachmentBlock.style.borderColor = color;
  460. //Pretext
  461. pretext.className = R.klass.msg.attachment.pretext;
  462. if (attachment["pretext"]) {
  463. pretext.innerHTML = formatSlackText(attachment["pretext"]);
  464. } else {
  465. pretext.classList.add(R.klass.hidden);
  466. }
  467. //Title
  468. titleBlock.target = "_blank";
  469. if (attachment["title"]) {
  470. titleBlock.innerHTML = formatSlackText(attachment["title"]);
  471. if (attachment["title_link"]) {
  472. titleBlock.href = attachment["title_link"];
  473. }
  474. titleBlock.className = R.klass.msg.attachment.title;
  475. } else {
  476. titleBlock.className = R.klass.hidden + " " +R.klass.msg.attachment.title;
  477. }
  478. //Author
  479. authorName.target = "_blank";
  480. authorBlock.className = R.klass.msg.author;
  481. if (attachment["author_name"]) {
  482. authorName.innerHTML = formatSlackText(attachment["author_name"]);
  483. authorName.href = attachment["author_link"] || "";
  484. authorName.className = R.klass.msg.authorname;
  485. authorImg.className = R.klass.msg.authorAvatar;
  486. if (attachment["author_icon"])
  487. authorImg.src = attachment["author_icon"];
  488. else
  489. authorImg.classList.add(R.klass.hidden);
  490. } else {
  491. authorBlock.classList.add(R.klass.hidden);
  492. }
  493. //Text
  494. textDom.innerHTML = formatSlackText(attachment["text"] || "");
  495. textDom.klassName = R.klass.msg.attachment.text;
  496. // Img (small one)
  497. thumbImgDom.className = R.klass.msg.attachment.thumbImg;
  498. if (attachment["thumb_url"])
  499. thumbImgDom.src = attachment["thumb_url"];
  500. else
  501. thumbImgDom.classList.add(R.klass.hidden);
  502. //Img (the big one)
  503. imgDom.className = R.klass.msg.attachment.img;
  504. if (attachment["image_url"])
  505. imgDom.src = attachment["image_url"];
  506. else
  507. imgDom.classList.add(R.klass.hidden);
  508. //Footer
  509. footerBlock.className = R.klass.msg.attachment.footer;
  510. footerText.className = R.klass.msg.attachment.footerText;
  511. footerIcon.className = R.klass.msg.attachment.footerIcon;
  512. if (attachment["footer"]) {
  513. footerText.innerHTML = formatSlackText(attachment["footer"]);
  514. if (attachment["footer_icon"])
  515. footerIcon.src = attachment["footer_icon"];
  516. else
  517. footerIcon.classList.add(R.klass.hidden);
  518. } else {
  519. footerIcon.classList.add(R.klass.hidden);
  520. footerText.classList.add(R.klass.hidden);
  521. }
  522. //Ts
  523. footerTs.className = R.klass.msg.ts;
  524. if (attachment["ts"])
  525. footerTs.innerHTML = formatDate(attachment["ts"]);
  526. else
  527. footerTs.classList.add(R.klass.hidden);
  528. // TODO Field [ {title, value, short } ]
  529. // TODO actions (button stuff)
  530. authorBlock.appendChild(authorImg);
  531. authorBlock.appendChild(authorName);
  532. textBlock.appendChild(textDom);
  533. textBlock.appendChild(thumbImgDom);
  534. footerBlock.appendChild(footerIcon);
  535. footerBlock.appendChild(footerText);
  536. footerBlock.appendChild(footerTs);
  537. attachmentBlock.appendChild(titleBlock);
  538. attachmentBlock.appendChild(authorBlock);
  539. attachmentBlock.appendChild(textBlock);
  540. attachmentBlock.appendChild(imgDom);
  541. attachmentBlock.appendChild(footerBlock);
  542. rootDom.appendChild(pretext);
  543. rootDom.appendChild(attachmentBlock);
  544. return rootDom;
  545. }
  546. /**
  547. * @param {string} channelId
  548. * @param {SlackMessage} msg
  549. * @param {boolean=} skipAttachment
  550. * @return {Element}
  551. **/
  552. function doCreateMeMessageDom(channelId, msg, skipAttachment) {
  553. var dom = doCreateMessageDom(channelId, msg, skipAttachment);
  554. dom.classList.add(R.klass.msg.meMessage);
  555. return dom;
  556. }
  557. /**
  558. * @param {string} channelId
  559. * @param {SlackMessage} msg
  560. * @param {boolean=} skipAttachment
  561. * @return {Element}
  562. **/
  563. function createMessageDom(channelId, msg, skipAttachment) {
  564. if (msg.subtype === "me_message") {
  565. return doCreateMeMessageDom(channelId, msg, skipAttachment);
  566. }
  567. return doCreateMessageDom(channelId, msg, skipAttachment);
  568. }
  569. /**
  570. * @param {number} unreadhi
  571. * @param {number} unread
  572. **/
  573. function setFavicon(unreadhi, unread) {
  574. if (!unreadhi && !unread)
  575. document.getElementById(R.id.favicon).href = "favicon_ok.png";
  576. else
  577. document.getElementById(R.id.favicon).href = "favicon.png?h="+unreadhi+"&m="+unread;
  578. }
  579. function setNetErrorFavicon() {
  580. document.getElementById(R.id.favicon).href = "favicon_err.png";
  581. }
  582. function updateTitle() {
  583. var hasUnread = 0
  584. ,hasHl = 0
  585. ,title = "";
  586. if (NEXT_RETRY) {
  587. title = '!' +locale.netErrorShort +' - ';
  588. setNetErrorFavicon();
  589. } else {
  590. for (var i in UNREAD_CHANS) {
  591. if (UNREAD_CHANS.hasOwnProperty(i)) {
  592. hasUnread += UNREAD_CHANS[i].unread;
  593. hasHl += UNREAD_CHANS[i].hl;
  594. }
  595. }
  596. if (hasHl)
  597. title = "(!" +hasHl +") - ";
  598. else if (hasUnread)
  599. title = "(" +hasUnread +") - ";
  600. setFavicon(hasHl, hasUnread);
  601. }
  602. title += SLACK.context.team.name;
  603. document.title = title;
  604. }
  605. function spawnNotification() {
  606. if (!("Notification" in window))
  607. {}
  608. else if (Notification.permission === "granted") {
  609. var now = Date.now();
  610. if (lastNotificationSpawn + NOTIFICATION_COOLDOWN < now) {
  611. var n = new Notification(locale.newMessage);
  612. lastNotificationSpawn = now;
  613. setTimeout(function() {
  614. n.close();
  615. }, NOTIFICATION_DELAY);
  616. }
  617. }
  618. else if (Notification.permission !== "denied")
  619. Notification.requestPermission();
  620. }
  621. function onRoomUpdated() {
  622. var chatFrag = document.createDocumentFragment()
  623. ,currentRoomId = SELECTED_ROOM.id;
  624. document.getElementById(R.id.currentRoom.content).textContent = "";
  625. if (SLACK.history[currentRoomId])
  626. SLACK.history[currentRoomId].messages.forEach(function(msg) {
  627. if (msg.type === "message") {
  628. var dom = createMessageDom(currentRoomId, msg);
  629. chatFrag.appendChild(dom);
  630. }
  631. });
  632. var content = document.getElementById(R.id.currentRoom.content);
  633. content.appendChild(chatFrag);
  634. //TODO scroll lock
  635. content.scrollTop = content.scrollHeight -content.clientHeight;
  636. }
  637. function chatClickDelegate(e) {
  638. var target = e.target
  639. ,getMessageId = function(e, target) {
  640. target = target || e.target;
  641. while (target !== e.currentTarget && target) {
  642. if (target.classList.contains(R.klass.msg.item)) {
  643. return target.id;
  644. }
  645. target = target.parentElement;
  646. }
  647. };
  648. while (target !== e.currentTarget && target) {
  649. if (target.classList.contains(R.klass.msg.hover.container)) {
  650. return;
  651. } else if (target.classList.contains(R.klass.msg.hover.reply)) {
  652. var messageId = getMessageId(e, target);
  653. if (messageId) {
  654. messageId = parseFloat(messageId.split("_")[1]);
  655. var history = SLACK.history[SELECTED_ROOM.id].messages;
  656. for (var i =0, histLen =history.length; i < histLen && history[i].ts <= messageId; i++) {
  657. if (history[i].ts === messageId) {
  658. if (REPLYING_TO !== history[i]) {
  659. REPLYING_TO = history[i];
  660. onReplyingToUpdated();
  661. }
  662. return;
  663. }
  664. }
  665. }
  666. return;
  667. }
  668. target = target.parentElement;
  669. }
  670. }
  671. function focusInput() {
  672. document.getElementById(R.id.message.input).focus();
  673. }
  674. function setRoomFromHashBang() {
  675. var hashId = document.location.hash.substr(1)
  676. ,room = SLACK.context.getChannel(hashId)
  677. ,user = SLACK.context.getMember(hashId);
  678. if (room && room !== SELECTED_ROOM)
  679. selectRoom(room);
  680. else if (user && user.ims)
  681. selectRoom(user.ims);
  682. }
  683. document.addEventListener('DOMContentLoaded', function() {
  684. initLang();
  685. document.getElementById(R.id.currentRoom.content).addEventListener("click", chatClickDelegate);
  686. window.addEventListener("hashchange", function(e) {
  687. if (document.location.hash && document.location.hash[0] === '#') {
  688. setRoomFromHashBang();
  689. }
  690. });
  691. document.getElementById(R.id.message.file.cancel).addEventListener("click", function(e) {
  692. e.preventDefault();
  693. document.getElementById(R.id.message.file.error).classList.add(R.klass.hidden);
  694. document.getElementById(R.id.message.file.formContainer).classList.add(R.klass.hidden);
  695. document.getElementById(R.id.message.file.fileInput).value = "";
  696. return false;
  697. });
  698. document.getElementById(R.id.message.file.form).addEventListener("submit", function(e) {
  699. e.preventDefault();
  700. var fileInput = document.getElementById(R.id.message.file.fileInput)
  701. ,filename = fileInput.value;
  702. if (filename) {
  703. filename = filename.substr(filename.lastIndexOf('\\') +1);
  704. uploadFile(SELECTED_ROOM, filename, fileInput.files[0], function(errorMsg) {
  705. var error = document.getElementById(R.id.message.file.error);
  706. if (errorMsg) {
  707. error.textContent = errorMsg;
  708. error.classList.remove(R.klass.hidden);
  709. } else {
  710. error.classList.add(R.klass.hidden);
  711. document.getElementById(R.id.message.file.fileInput).value = "";
  712. document.getElementById(R.id.message.file.formContainer).classList.add(R.klass.hidden);
  713. }
  714. });
  715. }
  716. return false;
  717. });
  718. document.getElementById(R.id.message.file.bt).addEventListener("click", function(e) {
  719. e.preventDefault();
  720. if (SELECTED_ROOM) {
  721. document.getElementById(R.id.message.file.formContainer).classList.remove(R.klass.hidden);
  722. }
  723. return false;
  724. });
  725. document.getElementById(R.id.message.form).addEventListener("submit", function(e) {
  726. e.preventDefault();
  727. var input =document.getElementById(R.id.message.input);
  728. if (SELECTED_ROOM && input.value) {
  729. sendMsg(SELECTED_ROOM, input.value, REPLYING_TO);
  730. input.value = "";
  731. if (REPLYING_TO) {
  732. REPLYING_TO = null;
  733. onReplyingToUpdated();
  734. }
  735. }
  736. focusInput();
  737. return false;
  738. });
  739. window.addEventListener('blur', function() {
  740. window.hasFocus = false;
  741. });
  742. window.addEventListener('focus', function() {
  743. window.hasFocus = true;
  744. lastNotificationSpawn = 0;
  745. if (SELECTED_ROOM)
  746. markRoomAsRead(SELECTED_ROOM);
  747. focusInput();
  748. });
  749. window.hasFocus = true;
  750. startPolling();
  751. });