ui.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  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. MSG_GROUPS = [],
  15. /** @type {number} */
  16. lastNotificationSpawn = 0;
  17. function onContextUpdated() {
  18. var chanListFram = document.createDocumentFragment(),
  19. sortedChans = DATA.context.getChannelIds(function(chan) {
  20. return !chan.archived && chan.isMember !== false;
  21. }),
  22. starred = [],
  23. channels = [],
  24. privs = [],
  25. priv = [],
  26. chanNames = {};
  27. sortedChans.sort(function(a, b) {
  28. if (a[0] !== b[0]) {
  29. return a[0] - b[0];
  30. }
  31. var aChanCtx = DATA.context.getChannelContext(a).getChatContext(),
  32. bChanCtx = DATA.context.getChannelContext(b).getChatContext(),
  33. aChan = aChanCtx.channels[a],
  34. bChan = bChanCtx.channels[b];
  35. if (aChan.name === bChan.name) {
  36. chanNames[aChan.id] = locale.chanName(aChanCtx.team.name, aChan.name);
  37. chanNames[bChan.id] = locale.chanName(bChanCtx.team.name, bChan.name);
  38. return aChanCtx.team.name.localeCompare(bChanCtx.team.name);
  39. }
  40. return aChan.name.localeCompare(bChan.name);
  41. });
  42. sortedChans.forEach(function(chanId) {
  43. var chan = DATA.context.getChannel(chanId),
  44. chanListItem;
  45. if (chan instanceof PrivateMessageRoom) {
  46. if (!chan.user.deleted) {
  47. if ((chanListItem = createImsListItem(chan, chanNames[chan.id]))) {
  48. if (chan.starred)
  49. starred.push(chanListItem);
  50. else
  51. priv.push(chanListItem);
  52. }
  53. }
  54. //FIXME else remove
  55. } else {
  56. if ((chanListItem = createChanListItem(chan, chanNames[chan.id]))) {
  57. if (chan.starred)
  58. starred.push(chanListItem);
  59. else if (chan.isPrivate)
  60. privs.push(chanListItem);
  61. else
  62. channels.push(chanListItem);
  63. }
  64. }
  65. });
  66. if (starred.length)
  67. chanListFram.appendChild(createChanListHeader(locale.starred));
  68. starred.forEach(function(dom) {
  69. chanListFram.appendChild(dom);
  70. });
  71. if (channels.length)
  72. chanListFram.appendChild(createChanListHeader(locale.channels));
  73. channels.forEach(function(dom) {
  74. chanListFram.appendChild(dom);
  75. });
  76. privs.forEach(function(dom) {
  77. chanListFram.appendChild(dom);
  78. });
  79. if (priv.length)
  80. chanListFram.appendChild(createChanListHeader(locale.privateMessageRoom));
  81. priv.forEach(function(dom) {
  82. chanListFram.appendChild(dom);
  83. });
  84. document.getElementById(R.id.chanList).textContent = "";
  85. document.getElementById(R.id.chanList).appendChild(chanListFram);
  86. setRoomFromHashBang();
  87. updateTitle();
  88. if (SELECTED_CONTEXT) {
  89. createContextBackground(SELECTED_CONTEXT.getChatContext().team.id, SELECTED_CONTEXT.getChatContext().users, function(imgData) {
  90. document.getElementById(R.id.context).style.backgroundImage = 'url(' +imgData +')';
  91. });
  92. }
  93. }
  94. function onTypingUpdated() {
  95. DATA.context.foreachContext(function(ctx) {
  96. var typing = ctx.typing;
  97. for (var chanId in ctx.self.channels) {
  98. if (!ctx.self.channels[chanId].archived) {
  99. var chanDom = document.getElementById("room_" +chanId);
  100. if (typing[chanId])
  101. chanDom.classList.add(R.klass.chatList.typing);
  102. else
  103. chanDom.classList.remove(R.klass.chatList.typing);
  104. }
  105. }
  106. for (var userId in ctx.users) {
  107. var ims = ctx.users[userId].privateRoom;
  108. if (ims && !ims.archived) {
  109. var userDom = document.getElementById("room_" +ims.id);
  110. if (userDom) {
  111. if (typing[ims.id])
  112. userDom.classList.add(R.klass.chatList.typing);
  113. else
  114. userDom.classList.remove(R.klass.chatList.typing);
  115. }
  116. }
  117. }
  118. });
  119. updateTypingChat();
  120. }
  121. function updateTypingChat() {
  122. var typing;
  123. document.getElementById(R.id.typing).textContent = "";
  124. if (SELECTED_CONTEXT && SELECTED_ROOM && (typing = SELECTED_CONTEXT.getChatContext().typing[SELECTED_ROOM.id])) {
  125. var areTyping = document.createDocumentFragment(),
  126. isOutOfSync = false;
  127. for (var i in typing) {
  128. var member = DATA.context.getUser(i);
  129. if (member)
  130. areTyping.appendChild(makeUserIsTypingDom(member));
  131. else
  132. isOutOfSync = true;
  133. }
  134. if (isOutOfSync)
  135. outOfSync();
  136. document.getElementById(R.id.typing).appendChild(areTyping);
  137. }
  138. }
  139. function onNetworkStateUpdated(isNetworkWorking) {
  140. if (isNetworkWorking)
  141. document.body.classList.remove(R.klass.noNetwork);
  142. else
  143. document.body.classList.add(R.klass.noNetwork);
  144. updateTitle();
  145. }
  146. function onRoomSelected() {
  147. var name = SELECTED_ROOM.name || (SELECTED_ROOM.user ? SELECTED_ROOM.user.name : undefined);
  148. if (!name) {
  149. /** @type {Array.<string>} */
  150. var members = [];
  151. SELECTED_ROOM.users.forEach(function(i) {
  152. members.push(i.name);
  153. });
  154. name = members.join(", ");
  155. }
  156. var roomLi = document.getElementById("room_" +SELECTED_ROOM.id);
  157. document.getElementById(R.id.currentRoom.title).textContent = name;
  158. onRoomUpdated();
  159. focusInput();
  160. document.getElementById(R.id.message.file.formContainer).classList.add(R.klass.hidden);
  161. markRoomAsRead(SELECTED_ROOM);
  162. if (REPLYING_TO) {
  163. REPLYING_TO = null;
  164. onReplyingToUpdated();
  165. }
  166. if (EDITING) {
  167. EDITING = null;
  168. onReplyingToUpdated();
  169. }
  170. updateTypingChat();
  171. }
  172. function onReplyingToUpdated() {
  173. if (REPLYING_TO) {
  174. document.body.classList.add(R.klass.replyingTo);
  175. var domParent = document.getElementById(R.id.message.replyTo),
  176. closeLink = document.createElement("a");
  177. closeLink.addEventListener("click", function() {
  178. REPLYING_TO = null;
  179. onReplyingToUpdated();
  180. });
  181. closeLink.className = R.klass.msg.replyTo.close;
  182. closeLink.textContent = 'x';
  183. domParent.textContent = "";
  184. domParent.appendChild(closeLink);
  185. domParent.appendChild(REPLYING_TO.duplicateDom());
  186. focusInput();
  187. } else {
  188. document.body.classList.remove(R.klass.replyingTo);
  189. document.getElementById(R.id.message.replyTo).textContent = "";
  190. focusInput();
  191. }
  192. }
  193. function onEditingUpdated() {
  194. if (EDITING) {
  195. document.body.classList.add(R.klass.replyingTo);
  196. var domParent = document.getElementById(R.id.message.replyTo),
  197. closeLink = document.createElement("a");
  198. closeLink.addEventListener("click", function() {
  199. EDITING = null;
  200. onEditingUpdated();
  201. });
  202. closeLink.className = R.klass.msg.replyTo.close;
  203. closeLink.textContent = 'x';
  204. domParent.textContent = "";
  205. domParent.appendChild(closeLink);
  206. domParent.appendChild(EDITING.duplicateDom());
  207. document.getElementById(R.id.message.input).value = EDITING.text;
  208. focusInput();
  209. } else {
  210. document.body.classList.remove(R.klass.replyingTo);
  211. document.getElementById(R.id.message.replyTo).textContent = "";
  212. focusInput();
  213. }
  214. }
  215. /**
  216. * @param {string} chanId
  217. * @param {string} msgId
  218. * @param {string} reaction
  219. **/
  220. window['toggleReaction'] = function(chanId, msgId, reaction) {
  221. var hist = DATA.history[chanId],
  222. msg,
  223. ctx;
  224. if ((hist = DATA.history[chanId]) && (msg = hist.getMessageById(msgId)) && (ctx = DATA.context.getChannelContext(chanId))) {
  225. if (msg.hasReactionForUser(reaction, ctx.getChatContext().self.id)) {
  226. removeReaction(chanId, msgId, reaction);
  227. } else {
  228. addReaction(chanId, msgId, reaction);
  229. }
  230. }
  231. };
  232. /**
  233. * Try to resolve emoji from customized context
  234. * @param {string} emoji
  235. * @return {Element|string}
  236. **/
  237. function tryGetCustomEmoji(emoji) {
  238. var loop = {};
  239. if (SELECTED_CONTEXT) {
  240. var ctx = SELECTED_CONTEXT.getChatContext();
  241. while (!loop[emoji]) {
  242. var emojisrc= ctx.emojis.data[emoji];
  243. if (emojisrc) {
  244. if (emojisrc.substr(0, 6) == "alias:") {
  245. loop[emoji] = true;
  246. emoji = emojisrc.substr(6);
  247. } else {
  248. var dom = document.createElement("span");
  249. dom.className = R.klass.emoji.custom +' ' +R.klass.emoji.emoji;
  250. dom.style.backgroundImage = "url('" +emojisrc +"')";
  251. return dom;
  252. }
  253. }
  254. return emoji; // Emoji not found, fallback to std emoji
  255. }
  256. }
  257. return emoji; //loop detected, return first emoji
  258. }
  259. function makeEmojiDom(emojiCode) {
  260. var emoji = tryGetCustomEmoji(emojiCode);
  261. if (typeof emoji === "string" && "makeEmoji" in window)
  262. emoji = window['makeEmoji'](emoji);
  263. return typeof emoji === "string" ? null : emoji;
  264. }
  265. /**
  266. * @param {number} unreadhi
  267. * @param {number} unread
  268. **/
  269. function setFavicon(unreadhi, unread) {
  270. if (!unreadhi && !unread)
  271. document.getElementById(R.id.favicon).href = "favicon_ok.png";
  272. else
  273. document.getElementById(R.id.favicon).href = "favicon.png?h="+unreadhi+"&m="+unread;
  274. }
  275. function setNetErrorFavicon() {
  276. document.getElementById(R.id.favicon).href = "favicon_err.png";
  277. }
  278. function updateTitle() {
  279. var hasHl = HIGHLIGHTED_CHANS.length,
  280. title = "";
  281. if (NEXT_RETRY) {
  282. title = '!' +locale.netErrorShort +' - ';
  283. setNetErrorFavicon();
  284. } else if (hasHl) {
  285. title = "(!" +hasHl +") - ";
  286. setFavicon(hasHl, hasHl);
  287. } else {
  288. var hasUnread = 0;
  289. DATA.context.foreachChannels(function(i) {
  290. if (i.lastMsg > i.lastRead)
  291. hasUnread++;
  292. });
  293. if (hasUnread)
  294. title = "(" +hasUnread +") - ";
  295. setFavicon(0, hasUnread);
  296. }
  297. if (DATA.context.team)
  298. title += DATA.context.team.name;
  299. document.title = title;
  300. }
  301. function spawnNotification() {
  302. if (!("Notification" in window))
  303. {}
  304. else if (Notification.permission === "granted") {
  305. var now = Date.now();
  306. if (lastNotificationSpawn + NOTIFICATION_COOLDOWN < now) {
  307. var n = new Notification(locale.newMessage);
  308. lastNotificationSpawn = now;
  309. setTimeout(function() {
  310. n.close();
  311. }, NOTIFICATION_DELAY);
  312. }
  313. }
  314. else if (Notification.permission !== "denied")
  315. Notification.requestPermission();
  316. }
  317. function onRoomUpdated() {
  318. var chatFrag = document.createDocumentFragment(),
  319. currentRoomId = SELECTED_ROOM.id,
  320. prevMsg = null,
  321. firstTsCombo = 0,
  322. prevMsgDom = null,
  323. currentMsgGroupDom;
  324. MSG_GROUPS = [];
  325. if (DATA.history[currentRoomId])
  326. DATA.history[currentRoomId].messages.forEach(function(msg) {
  327. if (!msg.removed) {
  328. var dom = msg.getDom(),
  329. newGroupDom = false;
  330. if (prevMsg && prevMsg.userId === msg.userId && msg.userId) {
  331. if (Math.abs(firstTsCombo -msg.ts) < 30 && !(msg instanceof MeMessage))
  332. prevMsgDom.classList.add(R.klass.msg.sameTs);
  333. else
  334. firstTsCombo = msg.ts;
  335. } else {
  336. firstTsCombo = msg.ts;
  337. newGroupDom = true;
  338. }
  339. if ((!prevMsg || prevMsg.ts <= SELECTED_ROOM.lastRead) && msg.ts > SELECTED_ROOM.lastRead)
  340. dom.classList.add(R.klass.msg.firstUnread);
  341. else
  342. dom.classList.remove(R.klass.msg.firstUnread);
  343. if (msg instanceof MeMessage) {
  344. prevMsg = null;
  345. prevMsgDom = null;
  346. firstTsCombo = 0;
  347. newGroupDom = true;
  348. chatFrag.appendChild(dom);
  349. currentMsgGroupDom = null;
  350. } else {
  351. if (newGroupDom || !currentMsgGroupDom) {
  352. currentMsgGroupDom = createMessageGroupDom(DATA.context.getUser(msg.userId), msg.username);
  353. MSG_GROUPS.push(currentMsgGroupDom);
  354. chatFrag.appendChild(currentMsgGroupDom);
  355. }
  356. prevMsg = msg;
  357. prevMsgDom = dom;
  358. currentMsgGroupDom.content.appendChild(dom);
  359. }
  360. } else {
  361. msg.removeDom();
  362. }
  363. });
  364. var content = document.getElementById(R.id.currentRoom.content);
  365. //TODO lazy add dom if needed
  366. content.textContent = "";
  367. content.appendChild(chatFrag);
  368. //TODO scroll lock
  369. content.scrollTop = content.scrollHeight -content.clientHeight;
  370. updateAuthorAvatarImsOffset();
  371. if (window.hasFocus)
  372. markRoomAsRead(SELECTED_ROOM);
  373. }
  374. function onMsgClicked(target, msg) {
  375. if (target.classList.contains(R.klass.msg.hover.reply)) {
  376. if (EDITING) {
  377. EDITING = null;
  378. onEditingUpdated();
  379. }
  380. if (REPLYING_TO !== msg) {
  381. REPLYING_TO = msg;
  382. onReplyingToUpdated();
  383. }
  384. } else if (target.classList.contains(R.klass.msg.hover.reaction)) {
  385. var currentRoomId = SELECTED_ROOM.id,
  386. currentMsgId = msg.id;
  387. EMOJI_BAR.spawn(document.body, SELECTED_CONTEXT, function(emoji) {
  388. if (emoji)
  389. addReaction(currentRoomId, currentMsgId, emoji);
  390. });
  391. } else if (target.classList.contains(R.klass.msg.hover.edit)) {
  392. if (REPLYING_TO) {
  393. REPLYING_TO = null;
  394. onReplyingToUpdated();
  395. }
  396. if (EDITING !== msg) {
  397. EDITING = msg;
  398. onEditingUpdated();
  399. }
  400. } else if (target.classList.contains(R.klass.msg.hover.remove)) {
  401. //TODO prompt confirm
  402. if (REPLYING_TO) {
  403. REPLYING_TO = null;
  404. onReplyingToUpdated();
  405. }
  406. if (EDITING) {
  407. EDITING = null;
  408. onEditingUpdated();
  409. }
  410. removeMsg(SELECTED_ROOM, msg);
  411. }
  412. }
  413. function chatClickDelegate(e) {
  414. var target = e.target,
  415. getMessageId = function(e, target) {
  416. target = target || e.target;
  417. while (target !== e.currentTarget && target) {
  418. if (target.id && target.classList.contains(R.klass.msg.item)) {
  419. return target.id;
  420. }
  421. target = target.parentElement;
  422. }
  423. };
  424. while (target !== e.currentTarget && target) {
  425. if (target.classList.contains(R.klass.msg.hover.container)) {
  426. return;
  427. }
  428. var messageId,
  429. msg;
  430. if (target.parentElement && target.classList.contains(R.klass.msg.attachment.actionItem)) {
  431. var attachmentIndex = target.dataset["attachmentIndex"],
  432. actionIndex = target.dataset["actionIndex"];
  433. messageId = getMessageId(e, target);
  434. if (messageId && attachmentIndex !== undefined && actionIndex !== undefined) {
  435. messageId = messageId.substr(messageId.lastIndexOf("_") +1);
  436. msg = DATA.history[SELECTED_ROOM.id].getMessageById(messageId);
  437. if (msg && msg.attachments[attachmentIndex] && msg.attachments[attachmentIndex].actions && msg.attachments[attachmentIndex].actions[actionIndex]) {
  438. confirmAction(SELECTED_ROOM.id, msg, msg.attachments[attachmentIndex], msg.attachments[attachmentIndex].actions[actionIndex]);
  439. }
  440. return;
  441. }
  442. }
  443. if (target.parentElement && target.parentElement.classList.contains(R.klass.msg.hover.container)) {
  444. if ((messageId = getMessageId(e, target))) {
  445. messageId = messageId.substr(messageId.lastIndexOf("_") +1);
  446. msg = DATA.history[SELECTED_ROOM.id].getMessageById(messageId);
  447. if (msg)
  448. onMsgClicked(target, msg);
  449. }
  450. return;
  451. }
  452. target = target.parentElement;
  453. }
  454. }
  455. function confirmAction(roomId, msg, attachmentObject, actionObject) {
  456. var confirmed = function() {
  457. var payload = getActionPayload(roomId, msg, attachmentObject, actionObject);
  458. sendCommand(payload, msg.userId);
  459. };
  460. if (actionObject["confirm"]) {
  461. (new ConfirmDialog(actionObject["confirm"]["title"], actionObject["confirm"]["text"]))
  462. .setButtonText(actionObject["confirm"]["ok_text"], actionObject["confirm"]["dismiss_text"])
  463. .onConfirm(confirmed)
  464. .spawn();
  465. } else {
  466. confirmed();
  467. }
  468. }
  469. function focusInput() {
  470. document.getElementById(R.id.message.input).focus();
  471. }
  472. function setRoomFromHashBang() {
  473. var hashId = document.location.hash.substr(1),
  474. room = DATA.context.getChannel(hashId);
  475. if (room && room !== SELECTED_ROOM)
  476. selectRoom(room);
  477. else {
  478. var user = DATA.context.getUser(hashId);
  479. if (user && user.ims)
  480. selectRoom(user.ims);
  481. }
  482. }
  483. function updateAuthorAvatarImsOffset() {
  484. var chatDom = document.getElementById(R.id.currentRoom.content),
  485. chatTop = chatDom.getBoundingClientRect().top;
  486. MSG_GROUPS.forEach(function(group) {
  487. var imgDom = group.authorImgWrapper,
  488. imgSize = imgDom.clientHeight,
  489. domRect = group.getBoundingClientRect(),
  490. _top = 0;
  491. imgDom.style.top = Math.max(0, Math.min(chatTop -domRect.top, domRect.height -imgSize -(imgSize /2))) +"px";
  492. imgDom.dataset["debugval"] = chatTop -domRect.top;
  493. imgDom.dataset["debugmax"] = domRect.height -imgSize -(imgSize /2);
  494. });
  495. }
  496. document.addEventListener('DOMContentLoaded', function() {
  497. initLang();
  498. // FIXME load config
  499. initHljs();
  500. document.getElementById(R.id.currentRoom.content).addEventListener("click", chatClickDelegate);
  501. window.addEventListener("hashchange", function(e) {
  502. if (document.location.hash && document.location.hash[0] === '#') {
  503. setRoomFromHashBang();
  504. }
  505. });
  506. document.getElementById(R.id.message.file.cancel).addEventListener("click", function(e) {
  507. e.preventDefault();
  508. document.getElementById(R.id.message.file.error).classList.add(R.klass.hidden);
  509. document.getElementById(R.id.message.file.formContainer).classList.add(R.klass.hidden);
  510. document.getElementById(R.id.message.file.fileInput).value = "";
  511. return false;
  512. });
  513. document.getElementById(R.id.message.file.form).addEventListener("submit", function(e) {
  514. e.preventDefault();
  515. var fileInput = document.getElementById(R.id.message.file.fileInput),
  516. filename = fileInput.value;
  517. if (filename) {
  518. filename = filename.substr(filename.lastIndexOf('\\') +1);
  519. uploadFile(SELECTED_ROOM, filename, fileInput.files[0], function(errorMsg) {
  520. var error = document.getElementById(R.id.message.file.error);
  521. if (errorMsg) {
  522. error.textContent = errorMsg;
  523. error.classList.remove(R.klass.hidden);
  524. } else {
  525. error.classList.add(R.klass.hidden);
  526. document.getElementById(R.id.message.file.fileInput).value = "";
  527. document.getElementById(R.id.message.file.formContainer).classList.add(R.klass.hidden);
  528. }
  529. });
  530. }
  531. return false;
  532. });
  533. document.getElementById(R.id.message.file.bt).addEventListener("click", function(e) {
  534. e.preventDefault();
  535. if (SELECTED_ROOM) {
  536. document.getElementById(R.id.message.file.formContainer).classList.remove(R.klass.hidden);
  537. }
  538. return false;
  539. });
  540. document.getElementById(R.id.message.form).addEventListener("submit", function(e) {
  541. e.preventDefault();
  542. var input =document.getElementById(R.id.message.input);
  543. if (SELECTED_ROOM && input.value) {
  544. if (onTextEntered(input.value)) {
  545. input.value = "";
  546. if (REPLYING_TO) {
  547. REPLYING_TO = null;
  548. onReplyingToUpdated();
  549. }
  550. if (EDITING) {
  551. EDITING = null;
  552. onReplyingToUpdated();
  553. }
  554. document.getElementById(R.id.message.slashComplete).textContent = '';
  555. }
  556. }
  557. focusInput();
  558. return false;
  559. });
  560. window.addEventListener('blur', function() {
  561. window.hasFocus = false;
  562. });
  563. window.addEventListener('focus', function() {
  564. window.hasFocus = true;
  565. lastNotificationSpawn = 0;
  566. if (SELECTED_ROOM)
  567. markRoomAsRead(SELECTED_ROOM);
  568. focusInput();
  569. });
  570. document.getElementById(R.id.currentRoom.content).addEventListener('scroll', updateAuthorAvatarImsOffset);
  571. var lastKeyDown = 0;
  572. document.getElementById(R.id.message.input).addEventListener('input', function() {
  573. if (SELECTED_ROOM) {
  574. var now = Date.now();
  575. if (lastKeyDown + 3000 < now && (SELECTED_CONTEXT.getChatContext().self.presence || (SELECTED_ROOM instanceof PrivateMessageRoom))) {
  576. sendTyping(SELECTED_ROOM);
  577. lastKeyDown = now;
  578. }
  579. var /** @type {Array<Command|{names: Array<string>!, desc: string!, usage: string!, category: string!, exec: Function!}>} */
  580. commands = [],
  581. input = this.value;
  582. if (this.value[0] === '/') {
  583. var endCmd = input.indexOf(' '),
  584. inputFinished = endCmd !== -1;
  585. endCmd = endCmd === -1 ? input.length : endCmd;
  586. var inputCmd = input.substr(0, endCmd);
  587. if (inputFinished) {
  588. var currentClientCmd = CLIENT_COMMANDS.getCommand(inputCmd);
  589. if (currentClientCmd)
  590. commands.push(currentClientCmd);
  591. } else {
  592. commands = CLIENT_COMMANDS.getCommandsStartingWith(inputCmd);
  593. }
  594. var availableCommands = (SELECTED_CONTEXT ? SELECTED_CONTEXT.getChatContext().commands.data : {});
  595. for (var currentCmdId in availableCommands) {
  596. var currentCmd = availableCommands[currentCmdId];
  597. if ((!inputFinished && currentCmd.name.substr(0, endCmd) === inputCmd) ||
  598. (inputFinished && currentCmd.name === inputCmd))
  599. commands.push(currentCmd);
  600. }
  601. }
  602. commands.sort(function(a, b) {
  603. return a.category.localeCompare(b.category) || a.name.localeCompare(b.name);
  604. });
  605. var slashDom = document.getElementById(R.id.message.slashComplete),
  606. slashFrag = document.createDocumentFragment(),
  607. prevService;
  608. slashDom.textContent = '';
  609. for (var i =0, nbCmd = commands.length; i < nbCmd; i++) {
  610. var command = commands[i];
  611. if (prevService !== command.category) {
  612. prevService = command.category;
  613. slashFrag.appendChild(createSlashAutocompleteHeader(command.category));
  614. }
  615. slashFrag.appendChild(createSlashAutocompleteDom(command));
  616. }
  617. slashDom.appendChild(slashFrag);
  618. }
  619. });
  620. window.hasFocus = true;
  621. //Emoji closure
  622. (function() {
  623. var emojiButton = document.getElementById(R.id.message.emoji);
  624. if ('makeEmoji' in window) {
  625. var emojiDom = window['makeEmoji']('smile');
  626. if (emojiDom) {
  627. emojiButton.innerHTML = "<span class='" +R.klass.emoji.small +"'>" +emojiDom.outerHTML +"</span>";
  628. } else {
  629. emojiButton.style.backgroundImage = 'url("smile.svg")';
  630. }
  631. emojiDom = window['makeEmoji']('paperclip');
  632. if (emojiDom) {
  633. document.getElementById(R.id.message.file.bt).innerHTML = "<span class='" +R.klass.emoji.small +"'>" +emojiDom.outerHTML +"</span>";
  634. } else {
  635. document.getElementById(R.id.message.file.bt).style.backgroundImage = 'url("public/paperclip.svg")';
  636. }
  637. emojiButton.addEventListener("click", function() {
  638. if (SELECTED_CONTEXT)
  639. EMOJI_BAR.spawn(document.body, SELECTED_CONTEXT.getChatContext(), function(e) {
  640. if (e) document.getElementById(R.id.message.input).value += ":"+e+":";
  641. focusInput();
  642. });
  643. });
  644. } else {
  645. emojiButton.classList.add(R.klass.hidden);
  646. }
  647. })();
  648. startPolling();
  649. });