ui.js 26 KB

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