ui.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  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. updateTitle();
  171. updateTypingChat();
  172. }
  173. function onReplyingToUpdated() {
  174. if (REPLYING_TO) {
  175. document.body.classList.add(R.klass.replyingTo);
  176. var domParent = document.getElementById(R.id.message.replyTo),
  177. closeLink = document.createElement("a");
  178. closeLink.addEventListener("click", function() {
  179. REPLYING_TO = null;
  180. onReplyingToUpdated();
  181. });
  182. closeLink.className = R.klass.msg.replyTo.close;
  183. closeLink.textContent = 'x';
  184. domParent.textContent = "";
  185. domParent.appendChild(closeLink);
  186. domParent.appendChild(REPLYING_TO.duplicateDom());
  187. focusInput();
  188. } else {
  189. document.body.classList.remove(R.klass.replyingTo);
  190. document.getElementById(R.id.message.replyTo).textContent = "";
  191. focusInput();
  192. }
  193. }
  194. function onEditingUpdated() {
  195. if (EDITING) {
  196. document.body.classList.add(R.klass.replyingTo);
  197. var domParent = document.getElementById(R.id.message.replyTo),
  198. closeLink = document.createElement("a");
  199. closeLink.addEventListener("click", function() {
  200. EDITING = null;
  201. onEditingUpdated();
  202. });
  203. closeLink.className = R.klass.msg.replyTo.close;
  204. closeLink.textContent = 'x';
  205. domParent.textContent = "";
  206. domParent.appendChild(closeLink);
  207. domParent.appendChild(EDITING.duplicateDom());
  208. document.getElementById(R.id.message.input).value = EDITING.text;
  209. focusInput();
  210. } else {
  211. document.body.classList.remove(R.klass.replyingTo);
  212. document.getElementById(R.id.message.replyTo).textContent = "";
  213. focusInput();
  214. }
  215. }
  216. /**
  217. * @param {string} chanId
  218. * @param {string} msgId
  219. * @param {string} reaction
  220. **/
  221. window['toggleReaction'] = function(chanId, msgId, reaction) {
  222. var hist = DATA.history[chanId],
  223. msg,
  224. ctx;
  225. if ((hist = DATA.history[chanId]) && (msg = hist.getMessageById(msgId)) && (ctx = DATA.context.getChannelContext(chanId))) {
  226. if (msg.hasReactionForUser(reaction, ctx.getChatContext().self.id)) {
  227. removeReaction(chanId, msgId, reaction);
  228. } else {
  229. addReaction(chanId, msgId, reaction);
  230. }
  231. }
  232. };
  233. /**
  234. * Try to resolve emoji from customized context
  235. * @param {string} emoji
  236. * @return {Element|string}
  237. **/
  238. function tryGetCustomEmoji(emoji) {
  239. var loop = {};
  240. if (SELECTED_CONTEXT) {
  241. var ctx = SELECTED_CONTEXT.getChatContext();
  242. while (!loop[emoji]) {
  243. var emojisrc= ctx.emojis.data[emoji];
  244. if (emojisrc) {
  245. if (emojisrc.substr(0, 6) == "alias:") {
  246. loop[emoji] = true;
  247. emoji = emojisrc.substr(6);
  248. } else {
  249. var dom = document.createElement("span");
  250. dom.className = R.klass.emoji.custom +' ' +R.klass.emoji.emoji;
  251. dom.style.backgroundImage = "url('" +emojisrc +"')";
  252. return dom;
  253. }
  254. }
  255. return emoji; // Emoji not found, fallback to std emoji
  256. }
  257. }
  258. return emoji; //loop detected, return first emoji
  259. }
  260. function makeEmojiDom(emojiCode) {
  261. var emoji = tryGetCustomEmoji(emojiCode);
  262. if (typeof emoji === "string" && "makeEmoji" in window)
  263. emoji = window['makeEmoji'](emoji);
  264. return typeof emoji === "string" ? null : emoji;
  265. }
  266. /**
  267. * @param {number} unreadhi
  268. * @param {number} unread
  269. **/
  270. function setFavicon(unreadhi, unread) {
  271. if (!unreadhi && !unread)
  272. document.getElementById(R.id.favicon).href = "favicon_ok.png";
  273. else
  274. document.getElementById(R.id.favicon).href = "favicon.png?h="+unreadhi+"&m="+unread;
  275. }
  276. function setNetErrorFavicon() {
  277. document.getElementById(R.id.favicon).href = "favicon_err.png";
  278. }
  279. function updateTitle() {
  280. var hasHl = HIGHLIGHTED_CHANS.length,
  281. title = "";
  282. if (NEXT_RETRY) {
  283. title = '!' +locale.netErrorShort +' - Mimouchat';
  284. setNetErrorFavicon();
  285. } else if (hasHl) {
  286. title = "(!" +hasHl +")";
  287. setFavicon(hasHl, hasHl);
  288. } else {
  289. var hasUnread = 0;
  290. DATA.context.foreachChannels(function(i) {
  291. if (i.lastMsg > i.lastRead)
  292. hasUnread++;
  293. });
  294. if (hasUnread)
  295. title = "(" +hasUnread +")";
  296. setFavicon(0, hasUnread);
  297. }
  298. if (!title.length && SELECTED_ROOM)
  299. title = SELECTED_ROOM.name;
  300. document.title = title.length ? title : "Mimouchat";
  301. }
  302. function spawnNotification() {
  303. if (!("Notification" in window))
  304. {}
  305. else if (Notification.permission === "granted") {
  306. var now = Date.now();
  307. if (lastNotificationSpawn + NOTIFICATION_COOLDOWN < now) {
  308. var n = new Notification(locale.newMessage);
  309. lastNotificationSpawn = now;
  310. setTimeout(function() {
  311. n.close();
  312. }, NOTIFICATION_DELAY);
  313. }
  314. }
  315. else if (Notification.permission !== "denied")
  316. Notification.requestPermission();
  317. }
  318. function onRoomUpdated() {
  319. var chatFrag = document.createDocumentFragment(),
  320. currentRoomId = SELECTED_ROOM.id,
  321. prevMsg = null,
  322. firstTsCombo = 0,
  323. prevMsgDom = null,
  324. currentMsgGroupDom;
  325. if (SELECTED_ROOM.starred)
  326. document.getElementById(R.id.mainSection).classList.add(R.klass.starred);
  327. else
  328. document.getElementById(R.id.mainSection).classList.remove(R.klass.starred);
  329. MSG_GROUPS = [];
  330. if (DATA.history[currentRoomId])
  331. DATA.history[currentRoomId].messages.forEach(function(msg) {
  332. if (!msg.removed) {
  333. var dom = msg.getDom(),
  334. newGroupDom = false;
  335. if (prevMsg && prevMsg.userId === msg.userId && msg.userId) {
  336. if (Math.abs(firstTsCombo -msg.ts) < 30 && !(msg instanceof MeMessage))
  337. prevMsgDom.classList.add(R.klass.msg.sameTs);
  338. else
  339. firstTsCombo = msg.ts;
  340. } else {
  341. firstTsCombo = msg.ts;
  342. newGroupDom = true;
  343. }
  344. if ((!prevMsg || prevMsg.ts <= SELECTED_ROOM.lastRead) && msg.ts > SELECTED_ROOM.lastRead)
  345. dom.classList.add(R.klass.msg.firstUnread);
  346. else
  347. dom.classList.remove(R.klass.msg.firstUnread);
  348. if (msg instanceof MeMessage) {
  349. prevMsg = null;
  350. prevMsgDom = null;
  351. firstTsCombo = 0;
  352. newGroupDom = true;
  353. chatFrag.appendChild(dom);
  354. currentMsgGroupDom = null;
  355. } else {
  356. if (newGroupDom || !currentMsgGroupDom) {
  357. currentMsgGroupDom = createMessageGroupDom(DATA.context.getUser(msg.userId), msg.username);
  358. MSG_GROUPS.push(currentMsgGroupDom);
  359. chatFrag.appendChild(currentMsgGroupDom);
  360. }
  361. prevMsg = msg;
  362. prevMsgDom = dom;
  363. currentMsgGroupDom.content.appendChild(dom);
  364. }
  365. } else {
  366. msg.removeDom();
  367. }
  368. });
  369. var content = document.getElementById(R.id.currentRoom.content);
  370. //TODO lazy add dom if needed
  371. content.textContent = "";
  372. content.appendChild(chatFrag);
  373. //TODO scroll lock
  374. content.scrollTop = content.scrollHeight -content.clientHeight;
  375. updateAuthorAvatarImsOffset();
  376. if (window.hasFocus)
  377. markRoomAsRead(SELECTED_ROOM);
  378. }
  379. function onMsgClicked(target, msg) {
  380. if (target.classList.contains(R.klass.msg.hover.reply)) {
  381. if (EDITING) {
  382. EDITING = null;
  383. onEditingUpdated();
  384. }
  385. if (REPLYING_TO !== msg) {
  386. REPLYING_TO = msg;
  387. onReplyingToUpdated();
  388. }
  389. } else if (target.classList.contains(R.klass.msg.hover.reaction)) {
  390. var currentRoomId = SELECTED_ROOM.id,
  391. currentMsgId = msg.id;
  392. EMOJI_BAR.spawn(document.body, SELECTED_CONTEXT, function(emoji) {
  393. if (emoji)
  394. addReaction(currentRoomId, currentMsgId, emoji);
  395. });
  396. } else if (target.classList.contains(R.klass.msg.hover.edit)) {
  397. if (REPLYING_TO) {
  398. REPLYING_TO = null;
  399. onReplyingToUpdated();
  400. }
  401. if (EDITING !== msg) {
  402. EDITING = msg;
  403. onEditingUpdated();
  404. }
  405. } else if (target.classList.contains(R.klass.msg.hover.star)) {
  406. //FIXME
  407. } else if (target.classList.contains(R.klass.msg.hover.pin)) {
  408. //FIXME
  409. } else if (target.classList.contains(R.klass.msg.hover.remove)) {
  410. //TODO prompt confirm
  411. if (REPLYING_TO) {
  412. REPLYING_TO = null;
  413. onReplyingToUpdated();
  414. }
  415. if (EDITING) {
  416. EDITING = null;
  417. onEditingUpdated();
  418. }
  419. removeMsg(SELECTED_ROOM, msg);
  420. }
  421. }
  422. function chatClickDelegate(e) {
  423. var target = e.target,
  424. getMessageId = function(e, target) {
  425. target = target || e.target;
  426. while (target !== e.currentTarget && target) {
  427. if (target.id && target.classList.contains(R.klass.msg.item)) {
  428. return target.id;
  429. }
  430. target = target.parentElement;
  431. }
  432. };
  433. while (target !== e.currentTarget && target) {
  434. if (target.classList.contains(R.klass.msg.hover.container)) {
  435. return;
  436. }
  437. var messageId,
  438. msg;
  439. if (target.parentElement && target.classList.contains(R.klass.msg.attachment.actionItem)) {
  440. var attachmentIndex = target.dataset["attachmentIndex"],
  441. actionIndex = target.dataset["actionIndex"];
  442. messageId = getMessageId(e, target);
  443. if (messageId && attachmentIndex !== undefined && actionIndex !== undefined) {
  444. messageId = messageId.substr(messageId.lastIndexOf("_") +1);
  445. msg = DATA.history[SELECTED_ROOM.id].getMessageById(messageId);
  446. if (msg && msg.attachments[attachmentIndex] && msg.attachments[attachmentIndex].actions && msg.attachments[attachmentIndex].actions[actionIndex]) {
  447. confirmAction(SELECTED_ROOM.id, msg, msg.attachments[attachmentIndex], msg.attachments[attachmentIndex].actions[actionIndex]);
  448. }
  449. return;
  450. }
  451. }
  452. if (target.parentElement && target.parentElement.classList.contains(R.klass.msg.hover.container)) {
  453. if ((messageId = getMessageId(e, target))) {
  454. messageId = messageId.substr(messageId.lastIndexOf("_") +1);
  455. msg = DATA.history[SELECTED_ROOM.id].getMessageById(messageId);
  456. if (msg)
  457. onMsgClicked(target, msg);
  458. }
  459. return;
  460. }
  461. target = target.parentElement;
  462. }
  463. }
  464. function confirmAction(roomId, msg, attachmentObject, actionObject) {
  465. var confirmed = function() {
  466. var payload = getActionPayload(roomId, msg, attachmentObject, actionObject);
  467. sendCommand(payload, msg.userId);
  468. };
  469. if (actionObject["confirm"]) {
  470. (new ConfirmDialog(actionObject["confirm"]["title"], actionObject["confirm"]["text"]))
  471. .setButtonText(actionObject["confirm"]["ok_text"], actionObject["confirm"]["dismiss_text"])
  472. .onConfirm(confirmed)
  473. .spawn();
  474. } else {
  475. confirmed();
  476. }
  477. }
  478. function focusInput() {
  479. document.getElementById(R.id.message.input).focus();
  480. }
  481. function setRoomFromHashBang() {
  482. var hashId = document.location.hash.substr(1),
  483. room = DATA.context.getChannel(hashId);
  484. if (room && room !== SELECTED_ROOM)
  485. selectRoom(room);
  486. else {
  487. var user = DATA.context.getUser(hashId);
  488. if (user && user.ims)
  489. selectRoom(user.ims);
  490. }
  491. }
  492. function updateAuthorAvatarImsOffset() {
  493. var chatDom = document.getElementById(R.id.currentRoom.content),
  494. chatTop = chatDom.getBoundingClientRect().top;
  495. MSG_GROUPS.forEach(function(group) {
  496. var imgDom = group.authorImgWrapper,
  497. imgSize = imgDom.clientHeight,
  498. domRect = group.getBoundingClientRect(),
  499. _top = 0;
  500. imgDom.style.top = Math.max(0, Math.min(chatTop -domRect.top, domRect.height -imgSize -(imgSize /2))) +"px";
  501. imgDom.dataset["debugval"] = chatTop -domRect.top;
  502. imgDom.dataset["debugmax"] = domRect.height -imgSize -(imgSize /2);
  503. });
  504. }
  505. document.addEventListener('DOMContentLoaded', function() {
  506. initLang();
  507. // FIXME load config
  508. initHljs();
  509. document.getElementById(R.id.currentRoom.content).addEventListener("click", chatClickDelegate);
  510. window.addEventListener("hashchange", function(e) {
  511. if (document.location.hash && document.location.hash[0] === '#') {
  512. setRoomFromHashBang();
  513. }
  514. });
  515. document.getElementById(R.id.currentRoom.starButton).addEventListener("click", function(e) {
  516. e.preventDefault();
  517. if (SELECTED_ROOM) {
  518. if (SELECTED_ROOM.starred) {
  519. unstarChannel(SELECTED_ROOM);
  520. } else {
  521. starChannel(SELECTED_ROOM);
  522. }
  523. }
  524. return false;
  525. });
  526. document.getElementById(R.id.message.file.cancel).addEventListener("click", function(e) {
  527. e.preventDefault();
  528. document.getElementById(R.id.message.file.error).classList.add(R.klass.hidden);
  529. document.getElementById(R.id.message.file.formContainer).classList.add(R.klass.hidden);
  530. document.getElementById(R.id.message.file.fileInput).value = "";
  531. return false;
  532. });
  533. document.getElementById(R.id.message.file.form).addEventListener("submit", function(e) {
  534. e.preventDefault();
  535. var fileInput = document.getElementById(R.id.message.file.fileInput),
  536. filename = fileInput.value;
  537. if (filename) {
  538. filename = filename.substr(filename.lastIndexOf('\\') +1);
  539. uploadFile(SELECTED_ROOM, filename, fileInput.files[0], function(errorMsg) {
  540. var error = document.getElementById(R.id.message.file.error);
  541. if (errorMsg) {
  542. error.textContent = errorMsg;
  543. error.classList.remove(R.klass.hidden);
  544. } else {
  545. error.classList.add(R.klass.hidden);
  546. document.getElementById(R.id.message.file.fileInput).value = "";
  547. document.getElementById(R.id.message.file.formContainer).classList.add(R.klass.hidden);
  548. }
  549. });
  550. }
  551. return false;
  552. });
  553. document.getElementById(R.id.message.file.bt).addEventListener("click", function(e) {
  554. e.preventDefault();
  555. if (SELECTED_ROOM) {
  556. document.getElementById(R.id.message.file.formContainer).classList.remove(R.klass.hidden);
  557. }
  558. return false;
  559. });
  560. document.getElementById(R.id.message.form).addEventListener("submit", function(e) {
  561. e.preventDefault();
  562. var input =document.getElementById(R.id.message.input);
  563. if (SELECTED_ROOM && input.value) {
  564. if (onTextEntered(input.value)) {
  565. input.value = "";
  566. if (REPLYING_TO) {
  567. REPLYING_TO = null;
  568. onReplyingToUpdated();
  569. }
  570. if (EDITING) {
  571. EDITING = null;
  572. onReplyingToUpdated();
  573. }
  574. document.getElementById(R.id.message.slashComplete).textContent = '';
  575. }
  576. }
  577. focusInput();
  578. return false;
  579. });
  580. window.addEventListener('blur', function() {
  581. window.hasFocus = false;
  582. });
  583. window.addEventListener('focus', function() {
  584. window.hasFocus = true;
  585. lastNotificationSpawn = 0;
  586. if (SELECTED_ROOM)
  587. markRoomAsRead(SELECTED_ROOM);
  588. focusInput();
  589. });
  590. document.getElementById(R.id.currentRoom.content).addEventListener('scroll', updateAuthorAvatarImsOffset);
  591. var lastKeyDown = 0;
  592. document.getElementById(R.id.message.input).addEventListener('input', function() {
  593. if (SELECTED_ROOM) {
  594. var now = Date.now();
  595. if (lastKeyDown + 3000 < now && (SELECTED_CONTEXT.getChatContext().self.presence || (SELECTED_ROOM instanceof PrivateMessageRoom))) {
  596. sendTyping(SELECTED_ROOM);
  597. lastKeyDown = now;
  598. }
  599. var /** @type {Array<Command|{names: Array<string>!, desc: string!, usage: string!, category: string!, exec: Function!}>} */
  600. commands = [],
  601. input = this.value;
  602. if (this.value[0] === '/') {
  603. var endCmd = input.indexOf(' '),
  604. inputFinished = endCmd !== -1;
  605. endCmd = endCmd === -1 ? input.length : endCmd;
  606. var inputCmd = input.substr(0, endCmd);
  607. if (inputFinished) {
  608. var currentClientCmd = CLIENT_COMMANDS.getCommand(inputCmd);
  609. if (currentClientCmd)
  610. commands.push(currentClientCmd);
  611. } else {
  612. commands = CLIENT_COMMANDS.getCommandsStartingWith(inputCmd);
  613. }
  614. var availableCommands = (SELECTED_CONTEXT ? SELECTED_CONTEXT.getChatContext().commands.data : {});
  615. for (var currentCmdId in availableCommands) {
  616. var currentCmd = availableCommands[currentCmdId];
  617. if ((!inputFinished && currentCmd.name.substr(0, endCmd) === inputCmd) ||
  618. (inputFinished && currentCmd.name === inputCmd))
  619. commands.push(currentCmd);
  620. }
  621. }
  622. commands.sort(function(a, b) {
  623. return a.category.localeCompare(b.category) || a.name.localeCompare(b.name);
  624. });
  625. var slashDom = document.getElementById(R.id.message.slashComplete),
  626. slashFrag = document.createDocumentFragment(),
  627. prevService;
  628. slashDom.textContent = '';
  629. for (var i =0, nbCmd = commands.length; i < nbCmd; i++) {
  630. var command = commands[i];
  631. if (prevService !== command.category) {
  632. prevService = command.category;
  633. slashFrag.appendChild(createSlashAutocompleteHeader(command.category));
  634. }
  635. slashFrag.appendChild(createSlashAutocompleteDom(command));
  636. }
  637. slashDom.appendChild(slashFrag);
  638. }
  639. });
  640. window.hasFocus = true;
  641. //Emoji closure
  642. (function() {
  643. var emojiButton = document.getElementById(R.id.message.emoji);
  644. if ('makeEmoji' in window) {
  645. var emojiDom = window['makeEmoji']('smile');
  646. if (emojiDom) {
  647. emojiButton.innerHTML = "<span class='" +R.klass.emoji.small +"'>" +emojiDom.outerHTML +"</span>";
  648. } else {
  649. emojiButton.style.backgroundImage = 'url("smile.svg")';
  650. }
  651. emojiDom = window['makeEmoji']('paperclip');
  652. if (emojiDom) {
  653. document.getElementById(R.id.message.file.bt).innerHTML = "<span class='" +R.klass.emoji.small +"'>" +emojiDom.outerHTML +"</span>";
  654. } else {
  655. document.getElementById(R.id.message.file.bt).style.backgroundImage = 'url("public/paperclip.svg")';
  656. }
  657. emojiButton.addEventListener("click", function() {
  658. if (SELECTED_CONTEXT)
  659. EMOJI_BAR.spawn(document.body, SELECTED_CONTEXT.getChatContext(), function(e) {
  660. if (e) document.getElementById(R.id.message.input).value += ":"+e+":";
  661. focusInput();
  662. });
  663. });
  664. } else {
  665. emojiButton.classList.add(R.klass.hidden);
  666. }
  667. })();
  668. startPolling();
  669. });