ui.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  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. } else {
  55. if ((chanListItem = createChanListItem(chan, chanNames[chan.id]))) {
  56. if (chan.starred)
  57. starred.push(chanListItem);
  58. else if (chan.isPrivate)
  59. privs.push(chanListItem);
  60. else
  61. channels.push(chanListItem);
  62. }
  63. }
  64. });
  65. if (starred.length)
  66. chanListFram.appendChild(createChanListHeader(locale.starred));
  67. starred.forEach(function(dom) {
  68. chanListFram.appendChild(dom);
  69. });
  70. if (channels.length)
  71. chanListFram.appendChild(createChanListHeader(locale.channels));
  72. channels.forEach(function(dom) {
  73. chanListFram.appendChild(dom);
  74. });
  75. privs.forEach(function(dom) {
  76. chanListFram.appendChild(dom);
  77. });
  78. if (priv.length)
  79. chanListFram.appendChild(createChanListHeader(locale.privateMessageRoom));
  80. priv.forEach(function(dom) {
  81. chanListFram.appendChild(dom);
  82. });
  83. document.getElementById(R.id.chanList).textContent = "";
  84. document.getElementById(R.id.chanList).appendChild(chanListFram);
  85. filterChanList.apply(document.getElementById(R.id.chanFilter));
  86. if (setRoomFromHashBang()) {
  87. createContextBackground(SELECTED_CONTEXT.getChatContext().team.id, SELECTED_CONTEXT.getChatContext().users, function(imgData) {
  88. document.getElementById(R.id.context).style.backgroundImage = 'url(' +imgData +')';
  89. });
  90. } else if (isNative()) {
  91. var roomId = __native.getPreviousChannel();
  92. if (roomId)
  93. document.location.hash = roomId;
  94. }
  95. }
  96. function onTypingUpdated() {
  97. DATA.context.foreachContext(function(ctx) {
  98. var typing = ctx.typing;
  99. for (var chanId in ctx.self.channels) {
  100. if (!ctx.self.channels[chanId].archived) {
  101. var chanDom = document.getElementById("room_" +chanId);
  102. if (typing[chanId])
  103. chanDom.classList.add(R.klass.chatList.typing);
  104. else
  105. chanDom.classList.remove(R.klass.chatList.typing);
  106. }
  107. }
  108. for (var userId in ctx.users) {
  109. var ims = ctx.users[userId].privateRoom;
  110. if (ims && !ims.archived) {
  111. var userDom = document.getElementById("room_" +ims.id);
  112. if (userDom) {
  113. if (typing[ims.id])
  114. userDom.classList.add(R.klass.chatList.typing);
  115. else
  116. userDom.classList.remove(R.klass.chatList.typing);
  117. }
  118. }
  119. }
  120. });
  121. updateTypingChat();
  122. }
  123. function updateTypingChat() {
  124. var typing;
  125. document.getElementById(R.id.typing).textContent = "";
  126. if (SELECTED_CONTEXT && SELECTED_ROOM && (typing = SELECTED_CONTEXT.getChatContext().typing[SELECTED_ROOM.id])) {
  127. var areTyping = document.createDocumentFragment(),
  128. isOutOfSync = false;
  129. for (var i in typing) {
  130. var member = DATA.context.getUser(i);
  131. if (member)
  132. areTyping.appendChild(makeUserIsTypingDom(member));
  133. else
  134. isOutOfSync = true;
  135. }
  136. if (isOutOfSync)
  137. outOfSync();
  138. document.getElementById(R.id.typing).appendChild(areTyping);
  139. }
  140. }
  141. function onNetworkStateUpdated(isNetworkWorking) {
  142. if (isNetworkWorking)
  143. document.body.classList.remove(R.klass.noNetwork);
  144. else
  145. document.body.classList.add(R.klass.noNetwork);
  146. updateTitle();
  147. }
  148. function onRoomSelected() {
  149. var name = SELECTED_ROOM.name || (SELECTED_ROOM.user ? SELECTED_ROOM.user.getName() : undefined);
  150. if (!name) {
  151. console.error("No name provided for ", SELECTED_ROOM);
  152. /** @type {Array.<string>} */
  153. var members = [];
  154. for (var userId in SELECTED_ROOM.users)
  155. members.push(SELECTED_ROOM.users[userId].getName());
  156. name = members.join(", ");
  157. }
  158. var roomLi = document.getElementById("room_" +SELECTED_ROOM.id);
  159. document.getElementById(R.id.currentRoom.title).textContent = name;
  160. document.getElementById(R.id.currentRoom.content).textContent = '';
  161. MSG_GROUPS = [];
  162. onRoomUpdated();
  163. focusInput();
  164. document.getElementById(R.id.message.file.formContainer).classList.add(R.klass.hidden);
  165. markRoomAsRead(SELECTED_ROOM);
  166. if (REPLYING_TO) {
  167. REPLYING_TO = null;
  168. onReplyingToUpdated();
  169. }
  170. if (EDITING) {
  171. EDITING = null;
  172. onReplyingToUpdated();
  173. }
  174. updateTypingChat();
  175. }
  176. function onReplyingToUpdated() {
  177. if (REPLYING_TO) {
  178. document.body.classList.add(R.klass.replyingTo);
  179. var domParent = document.getElementById(R.id.message.replyTo),
  180. closeLink = document.createElement("a");
  181. closeLink.addEventListener("click", function() {
  182. REPLYING_TO = null;
  183. onReplyingToUpdated();
  184. });
  185. closeLink.className = R.klass.msg.replyTo.close;
  186. closeLink.textContent = 'x';
  187. domParent.textContent = "";
  188. domParent.appendChild(closeLink);
  189. domParent.appendChild(REPLYING_TO.duplicateDom());
  190. focusInput();
  191. } else {
  192. document.body.classList.remove(R.klass.replyingTo);
  193. document.getElementById(R.id.message.replyTo).textContent = "";
  194. focusInput();
  195. }
  196. }
  197. function onEditingUpdated() {
  198. if (EDITING) {
  199. document.body.classList.add(R.klass.replyingTo);
  200. var domParent = document.getElementById(R.id.message.replyTo),
  201. closeLink = document.createElement("a");
  202. closeLink.addEventListener("click", function() {
  203. EDITING = null;
  204. onEditingUpdated();
  205. });
  206. closeLink.className = R.klass.msg.replyTo.close;
  207. closeLink.textContent = 'x';
  208. domParent.textContent = "";
  209. domParent.appendChild(closeLink);
  210. domParent.appendChild(EDITING.duplicateDom());
  211. document.getElementById(R.id.message.input).value = EDITING.text;
  212. focusInput();
  213. } else {
  214. document.body.classList.remove(R.klass.replyingTo);
  215. document.getElementById(R.id.message.replyTo).textContent = "";
  216. focusInput();
  217. }
  218. }
  219. /**
  220. * @param {string} chanId
  221. * @param {string} msgId
  222. * @param {string} reaction
  223. **/
  224. window['toggleReaction'] = function(chanId, msgId, reaction) {
  225. var hist = DATA.history[chanId],
  226. msg,
  227. ctx;
  228. if ((hist = DATA.history[chanId]) && (msg = hist.getMessageById(msgId)) && (ctx = DATA.context.getChannelContext(chanId))) {
  229. if (msg.hasReactionForUser(reaction, ctx.getChatContext().self.id)) {
  230. removeReaction(chanId, msgId, reaction);
  231. } else {
  232. addReaction(chanId, msgId, reaction);
  233. }
  234. }
  235. };
  236. /**
  237. * @param {number} unreadhi
  238. * @param {number} unread
  239. **/
  240. function setFavicon(unreadhi, unread) {
  241. if (!unreadhi && !unread)
  242. document.getElementById(R.id.favicon).href = "favicon_ok.png";
  243. else
  244. document.getElementById(R.id.favicon).href = "favicon.png?h="+unreadhi+"&m="+unread;
  245. }
  246. function setNetErrorFavicon() {
  247. document.getElementById(R.id.favicon).href = "favicon_err.png";
  248. }
  249. function updateTitle() {
  250. var hasHl = HIGHLIGHTED_CHANS.length,
  251. title = "";
  252. if (NEXT_RETRY) {
  253. title = '!' +locale.netErrorShort +' - Mimouchat';
  254. setNetErrorFavicon();
  255. } else if (hasHl) {
  256. title = "(!" +hasHl +")";
  257. setFavicon(hasHl, hasHl);
  258. } else {
  259. var hasUnread = 0;
  260. DATA.context.foreachChannels(function(i) {
  261. if (i.lastMsg > i.lastRead)
  262. hasUnread++;
  263. });
  264. if (hasUnread)
  265. title = "(" +hasUnread +")";
  266. setFavicon(0, hasUnread);
  267. }
  268. if (!title.length && SELECTED_ROOM)
  269. title = SELECTED_ROOM.name;
  270. title = title.length ? title : "Mimouchat";
  271. document.title = title;
  272. setNativeTitle(title);
  273. }
  274. function spawnNotification() {
  275. if (!("Notification" in window))
  276. {}
  277. else if (Notification.permission === "granted") {
  278. var now = Date.now();
  279. if (lastNotificationSpawn + NOTIFICATION_COOLDOWN < now) {
  280. var n = new Notification(locale.newMessage);
  281. lastNotificationSpawn = now;
  282. setTimeout(function() {
  283. n.close();
  284. }, NOTIFICATION_DELAY);
  285. }
  286. }
  287. else if (Notification.permission !== "denied")
  288. Notification.requestPermission();
  289. }
  290. function isSameGroup(group, msg) {
  291. return group &&
  292. isSameDay(msg.ts, group.ts) &&
  293. !(msg instanceof MeMessage) &&
  294. !group.meMessage &&
  295. msg.userId === group.userId;
  296. }
  297. function onRoomUpdated() {
  298. var chatFrag = document.getElementById(R.id.currentRoom.content),
  299. prevMsg = null,
  300. firstTsCombo = 0,
  301. currentGroup = 0,
  302. currentMsgInGroup = 0;
  303. if (SELECTED_ROOM.starred)
  304. document.getElementById(R.id.mainSection).classList.add(R.klass.starred);
  305. else
  306. document.getElementById(R.id.mainSection).classList.remove(R.klass.starred);
  307. DATA.history[SELECTED_ROOM.id] && DATA.history[SELECTED_ROOM.id].messages.forEach(function(msg) {
  308. var groupDomCreated = false;
  309. if (MSG_GROUPS[currentGroup]) {
  310. if (currentMsgInGroup >= MSG_GROUPS[currentGroup].messages.length) {
  311. if (!msg.removed) {
  312. if (isSameGroup(MSG_GROUPS[currentGroup], msg)) {
  313. // New message belonging in this group
  314. var dom = msg.getDom();
  315. if (Math.abs(firstTsCombo -msg.ts) < 30 && prevMsg)
  316. prevMsg.getDom().classList.add(R.klass.msg.sameTs);
  317. firstTsCombo = msg.ts;
  318. if ((!prevMsg || prevMsg.ts <= SELECTED_ROOM.lastRead) && msg.ts > SELECTED_ROOM.lastRead)
  319. dom.classList.add(R.klass.msg.firstUnread);
  320. else
  321. dom.classList.remove(R.klass.msg.firstUnread);
  322. MSG_GROUPS[currentGroup].content.appendChild(dom);
  323. MSG_GROUPS[currentGroup].messages.push(msg.id);
  324. ++currentMsgInGroup;
  325. prevMsg = msg;
  326. return;
  327. }
  328. if (msg.ts < MSG_GROUPS[currentGroup].ts) {
  329. while (currentGroup > 0 && msg.ts < MSG_GROUPS[currentGroup].ts) {
  330. // New message in previous group, move group cursor before the group to be inserted
  331. --currentGroup;
  332. }
  333. while (MSG_GROUPS[currentGroup]) {
  334. MSG_GROUPS[currentGroup].remove();
  335. MSG_GROUPS.splice(currentGroup, 1);
  336. }
  337. } else {
  338. // New message in next group
  339. while (MSG_GROUPS[currentGroup].content.children[currentMsgInGroup])
  340. MSG_GROUPS[currentGroup].content.children[currentMsgInGroup].remove();
  341. MSG_GROUPS[currentGroup].messages.splice(currentMsgInGroup);
  342. if (!MSG_GROUPS[currentGroup].messages.length) {
  343. MSG_GROUPS[currentGroup].remove();
  344. MSG_GROUPS[currentGroup] = null;
  345. } else {
  346. currentGroup++;
  347. }
  348. }
  349. currentMsgInGroup = 0;
  350. firstTsCombo = msg.ts;
  351. }
  352. // else message got removed
  353. }
  354. if (isSameGroup(MSG_GROUPS[currentGroup], msg)) {
  355. if (MSG_GROUPS[currentGroup].messages[currentMsgInGroup] === msg.id) {
  356. // same message
  357. var dom = MSG_GROUPS[currentGroup].content.children[currentMsgInGroup];
  358. if (msg.removed) {
  359. // Check removed
  360. dom.remove();
  361. MSG_GROUPS[currentGroup].messages.splice(currentMsgInGroup, 1);
  362. } else if (msg.uiNeedRefresh) {
  363. // Check invalidated
  364. var newDom = msg.getDom();
  365. MSG_GROUPS[currentGroup].content.replaceChild(dom, newDom);
  366. dom = newDom;
  367. }
  368. if ((!prevMsg || prevMsg.ts <= SELECTED_ROOM.lastRead) && msg.ts > SELECTED_ROOM.lastRead)
  369. dom.classList.add(R.klass.msg.firstUnread);
  370. else
  371. dom.classList.remove(R.klass.msg.firstUnread);
  372. currentMsgInGroup++;
  373. prevMsg = msg;
  374. } else if (!msg.removed) {
  375. // Another message, insert it before
  376. var dom = msg.getDom();
  377. MSG_GROUPS[currentGroup].content.insertBefore(dom, MSG_GROUPS[currentGroup].content.children[currentMsgInGroup]);
  378. MSG_GROUPS[currentGroup].messages.splice(currentMsgInGroup, 0, msg.id);
  379. if ((!prevMsg || prevMsg.ts <= SELECTED_ROOM.lastRead) && msg.ts > SELECTED_ROOM.lastRead)
  380. dom.classList.add(R.klass.msg.firstUnread);
  381. else
  382. dom.classList.remove(R.klass.msg.firstUnread);
  383. // Check invalidated
  384. currentMsgInGroup++;
  385. prevMsg = msg;
  386. }
  387. return;
  388. }
  389. }
  390. if (msg.removed)
  391. return;
  392. if (MSG_GROUPS[currentGroup] && !isSameGroup(MSG_GROUPS[currentGroup], msg)) { // Next group is not the good one, insert a new group
  393. MSG_GROUPS.splice(currentGroup, 0, null);
  394. }
  395. if (!MSG_GROUPS[currentGroup]) {
  396. MSG_GROUPS[currentGroup] = createMessageGroupDom(DATA.context.getUser(msg.userId), msg.username, msg instanceof MeMessage, msg.ts);
  397. groupDomCreated = true;
  398. }
  399. /** @type {Element} */
  400. var dom = msg.getDom();
  401. firstTsCombo = msg.ts;
  402. if ((!prevMsg || prevMsg.ts <= SELECTED_ROOM.lastRead) && msg.ts > SELECTED_ROOM.lastRead) {
  403. dom.classList.add(R.klass.msg.firstUnread);
  404. dom.insertBefore(UNREAD_INDICATOR_DOM, dom.firstChild);
  405. } else {
  406. dom.classList.remove(R.klass.msg.firstUnread);
  407. }
  408. MSG_GROUPS[currentGroup].content.appendChild(dom);
  409. MSG_GROUPS[currentGroup].messages.push(msg.id);
  410. prevMsg = msg;
  411. if (groupDomCreated) {
  412. if (MSG_GROUPS[currentGroup +1])
  413. chatFrag.insertBefore(MSG_GROUPS[currentGroup], MSG_GROUPS[currentGroup +1]);
  414. else
  415. chatFrag.appendChild(MSG_GROUPS[currentGroup]);
  416. currentMsgInGroup = 1;
  417. }
  418. return;
  419. });
  420. if (MSG_GROUPS[currentGroup]) {
  421. while (MSG_GROUPS[currentGroup].content.children[currentMsgInGroup])
  422. MSG_GROUPS[currentGroup].content.children[currentMsgInGroup].remove();
  423. MSG_GROUPS[currentGroup].messages.splice(currentMsgInGroup);
  424. if (!MSG_GROUPS[currentGroup].messages.length)
  425. --currentGroup;
  426. for (var i = currentGroup +1;MSG_GROUPS[i]; i++) {
  427. MSG_GROUPS[i].remove();
  428. }
  429. }
  430. for (var i =0, len =MSG_GROUPS.length; i < len; ++i) {
  431. if (MSG_GROUPS[i -1] && isSameDay(MSG_GROUPS[i -1].ts, MSG_GROUPS[i].ts)) {
  432. MSG_GROUPS[i].classList.remove(R.klass.msg.firstOfDay);
  433. } else {
  434. MSG_GROUPS[i].classList.add(R.klass.msg.firstOfDay);
  435. MSG_GROUPS[i].dataset["date"] = MSG_GROUPS[i].dataset["date"] || locale.formatDay(MSG_GROUPS[i].ts);
  436. }
  437. }
  438. currentGroup = MSG_GROUPS.length;
  439. PENDING_MESSAGES.forEach(function(msg) {
  440. if (msg.channel === SELECTED_ROOM.id) {
  441. if (!MSG_GROUPS[currentGroup]) {
  442. MSG_GROUPS[currentGroup] = createMessageGroupDom(SELECTED_CONTEXT.self, SELECTED_CONTEXT.self.getName(), msg instanceof MeMessage, msg.ts);
  443. chatFrag.appendChild(MSG_GROUPS[currentGroup]);
  444. }
  445. MSG_GROUPS[currentGroup].classList.add("pending");
  446. MSG_GROUPS[currentGroup].content.appendChild(msg.dom);
  447. MSG_GROUPS[currentGroup].messages.push(msg.id);
  448. }
  449. });
  450. //TODO scroll lock
  451. var content = document.getElementById(R.id.currentRoom.content);
  452. content.scrollTop = content.scrollHeight -content.clientHeight;
  453. updateTitle();
  454. if (window.hasFocus)
  455. markRoomAsRead(SELECTED_ROOM);
  456. }
  457. function onMsgClicked(target, msg) {
  458. if (target.classList.contains(R.klass.msg.hover.reply)) {
  459. if (EDITING) {
  460. EDITING = null;
  461. onEditingUpdated();
  462. }
  463. if (REPLYING_TO !== msg) {
  464. REPLYING_TO = msg;
  465. onReplyingToUpdated();
  466. }
  467. } else if (target.classList.contains(R.klass.msg.hover.reaction)) {
  468. var currentRoomId = SELECTED_ROOM.id,
  469. currentMsgId = msg.id;
  470. EMOJI_BAR.spawn(document.body, SELECTED_CONTEXT, function(emoji) {
  471. if (emoji)
  472. addReaction(currentRoomId, currentMsgId, emoji);
  473. });
  474. } else if (target.classList.contains(R.klass.msg.hover.edit)) {
  475. if (REPLYING_TO) {
  476. REPLYING_TO = null;
  477. onReplyingToUpdated();
  478. }
  479. if (EDITING !== msg) {
  480. EDITING = msg;
  481. onEditingUpdated();
  482. }
  483. } else if (target.classList.contains(R.klass.msg.hover.star)) {
  484. if (msg.starred)
  485. unstarMsg(SELECTED_ROOM, msg);
  486. else
  487. starMsg(SELECTED_ROOM, msg);
  488. } else if (target.classList.contains(R.klass.msg.hover.pin)) {
  489. if (msg.pinned)
  490. unpinMsg(SELECTED_ROOM, msg);
  491. else
  492. pinMsg(SELECTED_ROOM, msg);
  493. } else if (target.classList.contains(R.klass.msg.hover.remove)) {
  494. //TODO prompt confirm
  495. if (REPLYING_TO) {
  496. REPLYING_TO = null;
  497. onReplyingToUpdated();
  498. }
  499. if (EDITING) {
  500. EDITING = null;
  501. onEditingUpdated();
  502. }
  503. removeMsg(SELECTED_ROOM, msg);
  504. }
  505. }
  506. /**
  507. * @param {Room} channel
  508. * @param {string} input
  509. * @param {boolean} isMeMessage
  510. **/
  511. function displayTmpMessage(channel, input, isMeMessage) {
  512. var obj = {
  513. channel: channel.id,
  514. text: input.trim(),
  515. isMe: isMeMessage,
  516. dom: createTmpMsgDom(input, isMeMessage),
  517. ts: Date.now(),
  518. id: "pending" +channel.id +Date.now()
  519. };
  520. PENDING_MESSAGES.push(obj);
  521. if (channel === SELECTED_ROOM)
  522. onRoomUpdated();
  523. return obj;
  524. }
  525. function chatClickDelegate(e) {
  526. var target = e.target,
  527. getMessageId = function(e, target) {
  528. target = target || e.target;
  529. while (target !== e.currentTarget && target) {
  530. if (target.id && target.classList.contains(R.klass.msg.item)) {
  531. return target.id;
  532. }
  533. target = target.parentElement;
  534. }
  535. };
  536. while (target !== e.currentTarget && target) {
  537. if (target.classList.contains(R.klass.msg.hover.container)) {
  538. return;
  539. }
  540. var messageId,
  541. msg;
  542. if (target.parentElement && target.classList.contains(R.klass.msg.attachment.actionItem)) {
  543. var attachmentIndex = target.dataset["attachmentIndex"],
  544. actionIndex = target.dataset["actionIndex"];
  545. messageId = getMessageId(e, target);
  546. if (messageId && attachmentIndex !== undefined && actionIndex !== undefined) {
  547. messageId = messageId.substr(messageId.lastIndexOf("_") +1);
  548. msg = DATA.history[SELECTED_ROOM.id].getMessageById(messageId);
  549. if (msg && msg.attachments[attachmentIndex] && msg.attachments[attachmentIndex].actions && msg.attachments[attachmentIndex].actions[actionIndex]) {
  550. confirmAction(SELECTED_ROOM.id, msg, msg.attachments[attachmentIndex], msg.attachments[attachmentIndex].actions[actionIndex]);
  551. }
  552. return;
  553. }
  554. }
  555. if (target.parentElement && target.parentElement.classList.contains(R.klass.msg.hover.container)) {
  556. if ((messageId = getMessageId(e, target))) {
  557. messageId = messageId.substr(messageId.lastIndexOf("_") +1);
  558. msg = DATA.history[SELECTED_ROOM.id].getMessageById(messageId);
  559. if (msg)
  560. onMsgClicked(target, msg);
  561. }
  562. return;
  563. }
  564. target = target.parentElement;
  565. }
  566. }
  567. function confirmAction(roomId, msg, attachmentObject, actionObject) {
  568. var confirmed = function() {
  569. var payload = getActionPayload(roomId, msg, attachmentObject, actionObject);
  570. sendCommand(payload, msg.userId);
  571. };
  572. if (actionObject["confirm"]) {
  573. (new ConfirmDialog(actionObject["confirm"]["title"], actionObject["confirm"]["text"]))
  574. .setButtonText(actionObject["confirm"]["ok_text"], actionObject["confirm"]["dismiss_text"])
  575. .onConfirm(confirmed)
  576. .spawn();
  577. } else {
  578. confirmed();
  579. }
  580. }
  581. function updateAuthorAvatarImsOffset() {
  582. if (CONFIG.isDisplayAvatars() && CONFIG.isScrollAvatars()) {
  583. var chatDom = document.getElementById(R.id.currentRoom.content),
  584. chatTop = chatDom.getBoundingClientRect().top;
  585. MSG_GROUPS.forEach(function(group) {
  586. var imgDom = group.authorImgWrapper,
  587. imgSize = imgDom.clientHeight,
  588. domRect = group.getBoundingClientRect(),
  589. _top = 0;
  590. imgDom.style.top = Math.max(0, Math.min(chatTop -domRect.top, domRect.height -imgSize -(imgSize /2))) +"px";
  591. });
  592. }
  593. }
  594. function onEmojiReady() {
  595. var emojiButton = document.getElementById(R.id.message.emoji);
  596. invalidateAllMessages();
  597. EMOJI_BAR.reset();
  598. if ('makeEmoji' in window) {
  599. emojiButton.style.backgroundImage = 'url("smile.svg")';
  600. emojiButton.classList.remove(R.klass.hidden);
  601. } else {
  602. emojiButton.classList.add(R.klass.hidden);
  603. }
  604. }
  605. function _toggleMenu() {
  606. var menu = document.getElementById(R.id.context);
  607. if (menu.classList.contains(R.klass.opened))
  608. menu.classList.remove(R.klass.opened);
  609. else
  610. menu.classList.add(R.klass.opened);
  611. }
  612. document.addEventListener('DOMContentLoaded', function() {
  613. initLang();
  614. // FIXME load config
  615. initHljs();
  616. initMsgInput();
  617. var chanSearch = document.getElementById(R.id.chanFilter);
  618. chanSearch.addEventListener("input", filterChanList);
  619. chanSearch.addEventListener("blur", filterChanList);
  620. document.getElementById(R.id.currentRoom.content).addEventListener("click", chatClickDelegate);
  621. window.addEventListener("hashchange", function(e) {
  622. if (document.location.hash && document.location.hash[0] === '#') {
  623. setRoomFromHashBang();
  624. }
  625. });
  626. document.addEventListener("mouseover", function(e) {
  627. var t = e.target;
  628. if (roomInfo.isParentOf(t)) {
  629. roomInfo.cancelHide();
  630. return;
  631. }
  632. while (t && t !== this) {
  633. if (t.nodeName === 'A') {
  634. var href = t.href,
  635. sepPosition = href.indexOf('#');
  636. if (sepPosition >= 0) {
  637. href = href.substr(sepPosition +1);
  638. var channelCtx = DATA.context.getChannelContext(href);
  639. if (channelCtx) {
  640. roomInfo.populate(channelCtx, channelCtx.getChatContext().channels[href]).show(t);
  641. return;
  642. }
  643. channelCtx = DATA.context.getUserContext(href);
  644. if (channelCtx) {
  645. var room = channelCtx.getChatContext().users[href].privateRoom;
  646. if (room) {
  647. roomInfo.populate(channelCtx, room).show(t);
  648. return;
  649. }
  650. }
  651. }
  652. }
  653. t = t.parentElement;
  654. }
  655. roomInfo.hideDelayed();
  656. });
  657. document.getElementById(R.id.contextButton).addEventListener("click", _toggleMenu);
  658. document.getElementById(R.id.currentRoom.starButton).addEventListener("click", function(e) {
  659. e.preventDefault();
  660. if (SELECTED_ROOM) {
  661. if (SELECTED_ROOM.starred) {
  662. unstarChannel(SELECTED_ROOM);
  663. } else {
  664. starChannel(SELECTED_ROOM);
  665. }
  666. }
  667. return false;
  668. });
  669. document.getElementById(R.id.message.file.cancel).addEventListener("click", function(e) {
  670. e.preventDefault();
  671. document.getElementById(R.id.message.file.error).classList.add(R.klass.hidden);
  672. document.getElementById(R.id.message.file.formContainer).classList.add(R.klass.hidden);
  673. document.getElementById(R.id.message.file.fileInput).value = "";
  674. return false;
  675. });
  676. document.getElementById(R.id.settings.logout).addEventListener("click", logout);
  677. document.getElementById(R.id.settings.menuButton).addEventListener("click", function(e) {
  678. e.preventDefault();
  679. Settings.display().setClosable(true);
  680. });
  681. document.getElementById(R.id.message.file.form).addEventListener("submit", function(e) {
  682. e.preventDefault();
  683. var fileInput = document.getElementById(R.id.message.file.fileInput),
  684. filename = fileInput.value;
  685. if (filename) {
  686. filename = filename.substr(filename.lastIndexOf('\\') +1);
  687. uploadFile(SELECTED_ROOM, filename, fileInput.files[0], function(errorMsg) {
  688. var error = document.getElementById(R.id.message.file.error);
  689. if (errorMsg) {
  690. error.textContent = errorMsg;
  691. error.classList.remove(R.klass.hidden);
  692. } else {
  693. error.classList.add(R.klass.hidden);
  694. document.getElementById(R.id.message.file.fileInput).value = "";
  695. document.getElementById(R.id.message.file.formContainer).classList.add(R.klass.hidden);
  696. }
  697. });
  698. }
  699. return false;
  700. });
  701. document.getElementById(R.id.message.file.bt).addEventListener("click", function(e) {
  702. e.preventDefault();
  703. if (SELECTED_ROOM) {
  704. document.getElementById(R.id.message.file.formContainer).classList.remove(R.klass.hidden);
  705. }
  706. return false;
  707. });
  708. document.getElementById(R.id.message.submitButton).addEventListener("click", function(e) {
  709. e.preventDefault();
  710. onMsgFormSubmit();
  711. return false;
  712. });
  713. document.getElementById(R.id.message.form).addEventListener("submit", function(e) {
  714. e.preventDefault();
  715. onMsgFormSubmit();
  716. return false;
  717. });
  718. window.addEventListener('blur', function() {
  719. window.hasFocus = false;
  720. });
  721. window.addEventListener('focus', function() {
  722. window.hasFocus = true;
  723. lastNotificationSpawn = 0;
  724. if (SELECTED_ROOM)
  725. markRoomAsRead(SELECTED_ROOM);
  726. focusInput();
  727. });
  728. window.hasFocus = true;
  729. var emojiButton = document.getElementById(R.id.message.emoji);
  730. emojiButton.addEventListener("click", function() {
  731. if (SELECTED_CONTEXT)
  732. EMOJI_BAR.spawn(document.body, SELECTED_CONTEXT.getChatContext(), function(e) {
  733. if (e) document.getElementById(R.id.message.input).value += ":"+e+":";
  734. focusInput();
  735. });
  736. });
  737. if (isNative()) {
  738. __native.readSmsPermission(CALLBACK.makeCallback(function() {
  739. var response = JSON.parse(__native.getStatic());
  740. if (response) {
  741. DATA.update(response);
  742. }
  743. }));
  744. document.body.classList.add(R.klass.native);
  745. }
  746. if (!IS_LOCAL)
  747. startPolling();
  748. });
  749. function onMsgFormSubmit() {
  750. var input = document.getElementById(R.id.message.input);
  751. if (SELECTED_ROOM && input.value) {
  752. if (onTextEntered(input.value)) {
  753. input.value = "";
  754. if (REPLYING_TO) {
  755. REPLYING_TO = null;
  756. onReplyingToUpdated();
  757. }
  758. if (EDITING) {
  759. EDITING = null;
  760. onReplyingToUpdated();
  761. }
  762. document.getElementById(R.id.message.slashComplete).textContent = '';
  763. updateInputRowCount(input);
  764. }
  765. }
  766. focusInput();
  767. }