ui.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. var
  2. /** @type {SlackMessage|null} */
  3. REPLYING_TO = null
  4. ;
  5. /**
  6. * @param {SlackChan|SlackGroup} chan
  7. * @return {Element}
  8. **/
  9. function createChanListItem(chan) {
  10. var dom = document.createElement("li");
  11. dom.id = chan.id;
  12. if (chan.id[0] === 'D')
  13. dom.className = R.klass.chatList.entry + " " +R.klass.chatList.typeDirect;
  14. else if (chan.id[0] === 'G')
  15. dom.className = R.klass.chatList.entry + " " +R.klass.chatList.typeGroup;
  16. else if (chan.id[0] === 'C')
  17. dom.className = R.klass.chatList.entry + " " +R.klass.chatList.typeChannel;
  18. dom.textContent = chan.name;
  19. return dom;
  20. }
  21. /**
  22. * @param {SlackIms} ims
  23. * @return {Element}
  24. **/
  25. function createImsListItem(ims) {
  26. var dom = document.createElement("li");
  27. dom.id = ims.id;
  28. dom.className = R.klass.chatList.entry;
  29. dom.textContent = ims.user.name;
  30. return dom;
  31. }
  32. function onContextUpdated() {
  33. var chanListFram = document.createDocumentFragment();
  34. var sortedChans = SLACK.context.self ? Object.keys(SLACK.context.self.channels) : [];
  35. sortedChans.sort(function(a, b) {
  36. if (a[0] !== b[0]) {
  37. return a[0] - b[0];
  38. }
  39. return (SLACK.context.channels[a] || SLACK.context.groups[a]).name.localeCompare((SLACK.context.channels[b] || SLACK.context.groups[b]).name);
  40. });
  41. sortedChans.forEach(function(chanId) {
  42. var chan = SLACK.context.channels[chanId] || SLACK.context.groups[chanId]
  43. ,chanListItem = createChanListItem(chan);
  44. if (chanListItem) {
  45. chanListFram.appendChild(chanListItem);
  46. }
  47. });
  48. var sortedUsers = SLACK.context.users ? Object.keys(SLACK.context.users) : [];
  49. sortedUsers.sort(function(a, b) {
  50. return SLACK.context.users[a].name.localeCompare(SLACK.context.users[b].name);
  51. });
  52. sortedUsers.forEach(function(userId) {
  53. var ims = SLACK.context.users[userId].ims
  54. ,imsListItem = createImsListItem(ims);
  55. if (imsListItem) {
  56. chanListFram.appendChild(imsListItem);
  57. }
  58. });
  59. document.getElementById(R.id.chanList).textContent = "";
  60. document.getElementById(R.id.chanList).appendChild(chanListFram);
  61. }
  62. function onNetworkStateUpdated(isNetworkWorking) {
  63. isNetworkWorking ? document.body.classList.remove(R.klass.noNetwork) : document.body.classList.add(R.klass.noNetwork);
  64. }
  65. function onRoomSelected() {
  66. var name = SELECTED_ROOM.name || (SELECTED_ROOM.user ? SELECTED_ROOM.user.name : undefined);
  67. if (!name) {
  68. var members = [];
  69. for (var i in SELECTED_ROOM.members) {
  70. members.push(SELECTED_ROOM.members[i].name);
  71. }
  72. name = members.join(", ");
  73. }
  74. var roomLi = document.getElementById(SELECTED_ROOM.id);
  75. document.getElementById(R.id.currentRoom.title).textContent = name;
  76. onRoomUpdated();
  77. focusInput();
  78. document.getElementById(R.id.message.file.formContainer).classList.add(R.klass.hidden);
  79. markRoomAsRead(SELECTED_ROOM);
  80. if (REPLYING_TO) {
  81. REPLYING_TO = null;
  82. onReplyingToUpdated();
  83. }
  84. }
  85. function onReplyingToUpdated() {
  86. if (REPLYING_TO) {
  87. document.body.classList.add(R.klass.replyingTo);
  88. var domParent = document.getElementById(R.id.message.replyTo)
  89. ,closeLink = document.createElement("a");
  90. closeLink.addEventListener("click", function() {
  91. REPLYING_TO = null;
  92. onReplyingToUpdated();
  93. });
  94. closeLink.className = R.klass.msg.replyTo.close;
  95. closeLink.textContent = 'x';
  96. domParent.textContent = "";
  97. domParent.appendChild(closeLink);
  98. domParent.appendChild(createMessageDom("reply_" +SELECTED_ROOM.id, REPLYING_TO, true));
  99. } else {
  100. document.body.classList.remove(R.klass.replyingTo);
  101. }
  102. }
  103. /**
  104. * @param {string} channelId
  105. * @param {SlackMessage} msg
  106. * @param {boolean=} skipAttachment
  107. * @return {Element}
  108. **/
  109. function doCreateMessageDom(channelId, msg, skipAttachment) {
  110. var dom = document.createElement("div")
  111. ,ts = document.createElement("div")
  112. ,text = document.createElement("div")
  113. ,author = document.createElement("div")
  114. ,authorImg = document.createElement("img")
  115. ,authorName = document.createElement("span")
  116. ,hover = document.createElement("ul")
  117. ,hoverReply = document.createElement("li")
  118. ,attachments = document.createElement("ul")
  119. ,sender = msg.raw["user"] ?
  120. SLACK.context.users[msg.raw["user"]] :
  121. SLACK.context.bots[msg.raw["bot_id"]];
  122. dom.id = channelId +"_" +msg.ts;
  123. dom.className = R.klass.msg.item;
  124. ts.className = R.klass.msg.ts;
  125. text.className = R.klass.msg.msg;
  126. author.className = R.klass.msg.author;
  127. authorImg.className = R.klass.msg.authorAvatar;
  128. authorName.className = R.klass.msg.authorname;
  129. hover.className = R.klass.msg.hover.container;
  130. hoverReply.className = R.klass.msg.hover.reply;
  131. ts.textContent = (new Date(msg.ts * 1000)).toLocaleTimeString();
  132. text.innerHTML = formatSlackText(msg.raw["text"] || "");
  133. authorName.textContent = sender ? sender.name : (msg.raw["username"] || "?");
  134. if (!sender && !msg.raw["username"])
  135. text.textContent = msg.raw["subtype"] || JSON.stringify(msg.raw);
  136. authorImg.src = sender ? sender.icons.image_48 : "";
  137. author.appendChild(authorImg);
  138. author.appendChild(authorName);
  139. hover.appendChild(hoverReply);
  140. dom.appendChild(author);
  141. dom.appendChild(text);
  142. dom.appendChild(ts);
  143. dom.appendChild(attachments);
  144. if (skipAttachment !== true && msg.raw["attachments"]) {
  145. msg.raw["attachments"].forEach(function(attachment) {
  146. var domAttachment = createAttachmentDom(channelId, msg, attachment);
  147. if (domAttachment)
  148. attachments.appendChild(domAttachment);
  149. });
  150. }
  151. dom.appendChild(hover);
  152. return dom;
  153. }
  154. /**
  155. * @param {string} fullText
  156. * @return {string}
  157. **/
  158. function formatSlackText(fullText) {
  159. var msgContents = fullText.split(/\r?\n/g);
  160. for (var msgContentIndex=0, nbMsgContents = msgContents.length; msgContentIndex < nbMsgContents; msgContentIndex++) {
  161. var msgContent = msgContents[msgContentIndex]
  162. ,_msgContent = ""
  163. ,currentMods = {}
  164. ,quote = false
  165. ,i =0
  166. ,msgLength = msgContent.length;
  167. var checkEnd = function(str, pos, c) {
  168. while (str[pos]) {
  169. if (str[pos] != ' ' && str[pos] != c && str[pos +1] == c) {
  170. return true;
  171. }
  172. pos++;
  173. }
  174. return false;
  175. } ,appendMod = function(mods) {
  176. if (!Object.keys(currentMods).length)
  177. return "";
  178. return '<span class="' +Object.keys(mods).join(' ') +'">';
  179. };
  180. // Skip trailing
  181. while (i < msgLength && (msgContent[i] === ' ' || msgContent[i] === '\t'))
  182. i++;
  183. if (msgContent.substr(i, 4) === '&gt;') {
  184. quote = true;
  185. i += 4;
  186. }
  187. for (; i < msgLength; i++) {
  188. var c = msgContent[i];
  189. if (!(currentMods[R.klass.msg.style.bold]) && c === '*' && msgContent[i +1] && checkEnd(msgContent, i, c)) {
  190. if (Object.keys(currentMods).length)
  191. _msgContent += '</span>';
  192. currentMods[R.klass.msg.style.bold] = true;
  193. _msgContent += appendMod(currentMods);
  194. } else if (!(currentMods[R.klass.msg.style.strike]) && c === '~' && msgContent[i +1] && checkEnd(msgContent, i, c)) {
  195. if (Object.keys(currentMods).length)
  196. _msgContent += '</span>';
  197. currentMods[R.klass.msg.style.strike] = true;
  198. _msgContent += appendMod(currentMods);
  199. } else if (!(currentMods[R.klass.msg.style.code]) && c === '`' && msgContent[i +1] && checkEnd(msgContent, i, c)) {
  200. if (Object.keys(currentMods).length)
  201. _msgContent += '</span>';
  202. currentMods[R.klass.msg.style.code] = true;
  203. _msgContent += appendMod(currentMods);
  204. } else if (!(currentMods[R.klass.msg.style.italic]) && c === '_' && msgContent[i +1] && checkEnd(msgContent, i, c)) {
  205. if (Object.keys(currentMods).length)
  206. _msgContent += '</span>';
  207. currentMods[R.klass.msg.style.italic] = true;
  208. _msgContent += appendMod(currentMods);
  209. } else {
  210. var finalFound = false;
  211. _msgContent += c;
  212. do {
  213. if ((currentMods[R.klass.msg.style.bold]) && c !== '*' && msgContent[i +1] === '*') {
  214. delete currentMods[R.klass.msg.style.bold];
  215. finalFound = true;
  216. } else if ((currentMods[R.klass.msg.style.strike]) && c !== '~' && msgContent[i +1] === '~') {
  217. delete currentMods[R.klass.msg.style.strike];
  218. finalFound = true;
  219. } else if ((currentMods[R.klass.msg.style.code]) && c !== '`' && msgContent[i +1] === '`') {
  220. delete currentMods[R.klass.msg.style.code];
  221. finalFound = true;
  222. } else if ((currentMods[R.klass.msg.style.italic]) && c !== '_' && msgContent[i +1] === '_') {
  223. delete currentMods[R.klass.msg.style.italic];
  224. finalFound = true;
  225. } else {
  226. break;
  227. }
  228. c = msgContent[++i];
  229. } while (i < msgLength);
  230. if (finalFound)
  231. _msgContent += '</span>' +appendMod(currentMods);
  232. }
  233. }
  234. if (currentMods) {
  235. // Should not append
  236. _msgContent += '</span>';
  237. }
  238. _msgContent = _msgContent.replace(new RegExp('<([@#]?)([^>]*)>', 'g'),
  239. function(matched, type, entity) {
  240. var sub = entity.split('|');
  241. if (type === '@') {
  242. if (!sub[1]) {
  243. var user = SLACK.context.getMember(sub[0]);
  244. sub[1] = user ? ('@' +user.name) : "Unknown member"; // TODO locale
  245. } else if ('@' !== sub[1][0]) {
  246. sub[1] = '@' +sub[1];
  247. }
  248. sub[0] = '#' +sub[0];
  249. sub[2] = R.klass.msg.link +' ' +R.klass.msg.linkuser;
  250. } else if (type === '#') {
  251. if (!sub[1]) {
  252. var chan = SLACK.context.getChannel(sub[0]);
  253. sub[1] = chan ? ('#' +chan.name) : "Unknown channel"; // TODO locale
  254. } else if ('#' !== sub[1][0]) {
  255. sub[1] = '#' +sub[1];
  256. }
  257. sub[0] = '#' +sub[0];
  258. sub[2] = R.klass.msg.link +' ' +R.klass.msg.linkchan;
  259. } else if (sub[0].indexOf("://") !== -1) {
  260. if (!sub[1])
  261. sub[1] = sub[0];
  262. sub[2] = R.klass.msg.link;
  263. } else {
  264. return matched;
  265. }
  266. return '<a href="' +sub[0] +'" class="' +sub[2] +'"' +(!type ? ' target="_blank"' : '') +'>' +sub[1] +'</a>';
  267. });
  268. if (quote)
  269. msgContents[msgContentIndex] = '<span class="' +R.klass.msg.style.quote +'">' +_msgContent +'</span>';
  270. else
  271. msgContents[msgContentIndex] = _msgContent;
  272. }
  273. return msgContents.join('<br/>');
  274. }
  275. /**
  276. * @param {string} channelId
  277. * @param {SlackMessage} msg
  278. * @param {*} attachment
  279. * @return {Element|null}
  280. **/
  281. function createAttachmentDom(channelId, msg, attachment) {
  282. var rootDom = document.createElement("li")
  283. ,attachmentBlock = document.createElement("div")
  284. ,pretext = document.createElement("div")
  285. ,titleBlock = document.createElement("a")
  286. ,authorBlock = document.createElement("div")
  287. ,authorImg = document.createElement("img")
  288. ,authorName = document.createElement("a")
  289. ,textBlock = document.createElement("div")
  290. ,imgDom = document.createElement("img")
  291. ,footerBlock = document.createElement("div")
  292. ,footerIcon = document.createElement("img")
  293. ,footerText = document.createElement("span")
  294. ,footerTs = document.createElement("span")
  295. ;
  296. //Color
  297. var color = "#e3e4e6";
  298. if (attachment["color"]) {
  299. if (attachment["color"][0] === '#')
  300. color = attachment["color"][0];
  301. else if (attachment["color"] === "good")
  302. color = "#2fa44f";
  303. else if (attachment["color"] === "warning")
  304. color = "#de9e31";
  305. else if (attachment["color"] === "danger")
  306. color = "#d50200";
  307. }
  308. //Pretext
  309. if (attachment["pretext"]) {
  310. pretext.innerHTML = formatSlackText(attachment["pretext"]);
  311. }
  312. //Title
  313. if (attachment["title"]) {
  314. titleBlock.innerHTML = formatSlackText(attachment["title"]);
  315. if (attachment["title_link"]) {
  316. titleBlock.href = attachment["title_link"];
  317. }
  318. } else {
  319. titleBlock.className = R.klass.hidden;
  320. }
  321. //Author
  322. authorName.target = "_blank";
  323. if (attachment["author_name"]) {
  324. authorName.innerHTML = formatSlackText(attachment["author_name"]);
  325. authorName.href = attachment["author_link"];
  326. if (attachment["author_icon"])
  327. authorImg.src = attachment["author_icon"];
  328. else
  329. authorImg.className = R.klass.hidden;
  330. } else {
  331. authorBlock.className = R.klass.hidden;
  332. }
  333. //Text
  334. textBlock.innerHTML = formatSlackText(attachment["text"] || "");
  335. //Img (the big one)
  336. if (attachment["image_url"]) {
  337. imgDom.src = attachment["image_url"];
  338. } else {
  339. imgDom.className = R.klass.hidden;
  340. }
  341. //Footer
  342. if (attachment["footer"]) {
  343. footerText.innerHTML = formatSlackText(attachment["footer"]);
  344. if (attachment["footer_icon"])
  345. footerIcon.src = attachment["footer_icon"];
  346. else
  347. footerIcon.className = R.klass.hidden;
  348. } else {
  349. footerText.className = R.klass.hidden;
  350. footerIcon.className = R.klass.hidden;
  351. }
  352. if (attachment["ts"])
  353. footerTs.textContent = new Date(parseFloat(attachment["ts"])).toString();
  354. else
  355. footerTs.className = R.klass.hidden;
  356. console.log(attachment);
  357. // thumb_url (str)
  358. // Field [ {title, value, short } ]
  359. // actions (button stuff)
  360. attachmentBlock.style.borderColor = color;
  361. authorBlock.appendChild(authorImg);
  362. authorBlock.appendChild(authorName);
  363. footerBlock.appendChild(footerIcon);
  364. footerBlock.appendChild(footerText);
  365. footerBlock.appendChild(footerTs);
  366. attachmentBlock.appendChild(titleBlock);
  367. attachmentBlock.appendChild(authorBlock);
  368. attachmentBlock.appendChild(textBlock);
  369. attachmentBlock.appendChild(imgDom);
  370. attachmentBlock.appendChild(footerBlock);
  371. rootDom.appendChild(pretext);
  372. rootDom.appendChild(attachmentBlock);
  373. console.log(attachment);
  374. return rootDom;
  375. }
  376. /**
  377. * @param {string} channelId
  378. * @param {SlackMessage} msg
  379. * @param {boolean=} skipAttachment
  380. * @return {Element}
  381. **/
  382. function doCreateMeMessageDom(channelId, msg, skipAttachment) {
  383. var dom = doCreateMessageDom(channelId, msg, skipAttachment);
  384. dom.classList.add(R.klass.msg.meMessage);
  385. return dom;
  386. }
  387. /**
  388. * @param {string} channelId
  389. * @param {SlackMessage} msg
  390. * @param {boolean=} skipAttachment
  391. * @return {Element}
  392. **/
  393. function createMessageDom(channelId, msg, skipAttachment) {
  394. if (msg.subtype === "me_message") {
  395. return doCreateMeMessageDom(channelId, msg, skipAttachment);
  396. }
  397. return doCreateMessageDom(channelId, msg, skipAttachment);
  398. }
  399. function updateTitle() {
  400. var hasUnread = 0
  401. ,hasHl = 0
  402. ,title;
  403. for (var i in UNREAD_CHANS) {
  404. if (UNREAD_CHANS.hasOwnProperty(i)) {
  405. hasUnread += UNREAD_CHANS[i].unread;
  406. hasHl += UNREAD_CHANS[i].hl;
  407. }
  408. }
  409. if (hasHl) {
  410. title = "(!" +hasHl;
  411. }
  412. if (hasUnread) {
  413. title = (title ? (title+" - ") : "(") +hasUnread;
  414. }
  415. if (title)
  416. title += ") " +SLACK.context.team.name;
  417. else
  418. title = SLACK.context.team.name;
  419. document.title = title;
  420. }
  421. function onRoomUpdated() {
  422. var chatFrag = document.createDocumentFragment()
  423. ,currentRoomId = SELECTED_ROOM.id;
  424. document.getElementById(R.id.currentRoom.content).textContent = "";
  425. if (SLACK.history[currentRoomId])
  426. SLACK.history[currentRoomId].messages.forEach(function(msg) {
  427. if (msg.type === "message") {
  428. var dom = createMessageDom(currentRoomId, msg);
  429. chatFrag.appendChild(dom);
  430. }
  431. });
  432. var content = document.getElementById(R.id.currentRoom.content);
  433. content.appendChild(chatFrag);
  434. //TODO scroll lock
  435. content.scrollTop = content.scrollHeight -content.clientHeight;
  436. }
  437. function onChanClick(e) {
  438. while (e.target !== e.currentTarget && e.target) {
  439. if (e.target.classList.contains(R.klass.chatList.entry)) {
  440. var room = (SLACK.context.channels[e.target.id] ||
  441. SLACK.context.ims[e.target.id] ||
  442. SLACK.context.groups[e.target.id]);
  443. if (room && room !== SELECTED_ROOM) {
  444. selectRoom(room);
  445. }
  446. return;
  447. }
  448. e.target = e.target.parentElement;
  449. }
  450. }
  451. function chatClickDelegate(e) {
  452. var target = e.target
  453. ,getMessageId = function(e, target) {
  454. target = target || e.target;
  455. while (target !== e.currentTarget && target) {
  456. if (target.classList.contains(R.klass.msg.item)) {
  457. return target.id;
  458. }
  459. target = target.parentElement;
  460. }
  461. };
  462. while (target !== e.currentTarget && target) {
  463. if (target.classList.contains(R.klass.msg.hover.container)) {
  464. return;
  465. } else if (target.classList.contains(R.klass.msg.hover.reply)) {
  466. var messageId = getMessageId(e, target);
  467. if (messageId) {
  468. messageId = parseFloat(messageId.split("_")[1]);
  469. var history = SLACK.history[SELECTED_ROOM.id].messages;
  470. for (var i =0, histLen =history.length; i < histLen && history[i].ts <= messageId; i++) {
  471. if (history[i].ts === messageId) {
  472. if (REPLYING_TO !== history[i]) {
  473. REPLYING_TO = history[i];
  474. onReplyingToUpdated();
  475. }
  476. return;
  477. }
  478. }
  479. }
  480. return;
  481. }
  482. target = target.parentElement;
  483. }
  484. }
  485. function focusInput() {
  486. document.getElementById(R.id.message.input).focus();
  487. }
  488. document.addEventListener('DOMContentLoaded', function() {
  489. document.getElementById(R.id.chatList).addEventListener("click", onChanClick);
  490. document.getElementById(R.id.currentRoom.content).addEventListener("click", chatClickDelegate);
  491. document.getElementById(R.id.message.file.cancel).addEventListener("click", function(e) {
  492. e.preventDefault();
  493. document.getElementById(R.id.message.file.error).classList.add(R.klass.hidden);
  494. document.getElementById(R.id.message.file.formContainer).classList.add(R.klass.hidden);
  495. document.getElementById(R.id.message.file.fileInput).value = "";
  496. return false;
  497. });
  498. document.getElementById(R.id.message.file.form).addEventListener("submit", function(e) {
  499. e.preventDefault();
  500. var fileInput = document.getElementById(R.id.message.file.fileInput)
  501. ,filename = fileInput.value;
  502. if (filename) {
  503. filename = filename.substr(filename.lastIndexOf('\\') +1);
  504. uploadFile(SELECTED_ROOM, filename, fileInput.files[0], function(errorMsg) {
  505. var error = document.getElementById(R.id.message.file.error);
  506. if (errorMsg) {
  507. error.textContent = errorMsg;
  508. error.classList.remove(R.klass.hidden);
  509. } else {
  510. error.classList.add(R.klass.hidden);
  511. document.getElementById(R.id.message.file.fileInput).value = "";
  512. document.getElementById(R.id.message.file.formContainer).classList.add(R.klass.hidden);
  513. }
  514. });
  515. }
  516. return false;
  517. });
  518. document.getElementById(R.id.message.file.bt).addEventListener("click", function(e) {
  519. e.preventDefault();
  520. if (SELECTED_ROOM) {
  521. document.getElementById(R.id.message.file.formContainer).classList.remove(R.klass.hidden);
  522. }
  523. return false;
  524. });
  525. document.getElementById(R.id.message.form).addEventListener("submit", function(e) {
  526. e.preventDefault();
  527. var input =document.getElementById(R.id.message.input);
  528. if (SELECTED_ROOM && input.value) {
  529. sendMsg(SELECTED_ROOM, input.value, REPLYING_TO);
  530. input.value = "";
  531. if (REPLYING_TO) {
  532. REPLYING_TO = null;
  533. onReplyingToUpdated();
  534. }
  535. }
  536. focusInput();
  537. return false;
  538. });
  539. window.addEventListener('blur', function() {
  540. window.hasFocus = false;
  541. });
  542. window.addEventListener('focus', function() {
  543. window.hasFocus = true;
  544. if (SELECTED_ROOM)
  545. markRoomAsRead(SELECTED_ROOM);
  546. focusInput();
  547. });
  548. window.hasFocus = true;
  549. startPolling();
  550. });