1
0

ui.js 30 KB

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