mimouchat.min.js 125 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. function ChatInfo(id){this.id=id;this.name;this.version=0}ChatInfo.prototype.toStatic=function(t){return t>=this.version?undefined:{"id":this.id,"name":this.name}};ChatInfo.prototype.update=function(data,t){if(data["name"]!==undefined)this.name=data["name"];this.version=Math.max(this.version,t)};function Command(data){this.desc=data["desc"];this.name=data["name"];this.type=data["type"];this.usage=data["usage"];this.category=data["category"]}
  2. Command.prototype.toStatic=function(t){return{"desc":this.desc,"name":this.name,"type":this.type,"usage":this.usage,"category":this.category}};function SelfPreferences(){this.favoriteEmojis={};this.highlights=[];this.version=0}
  3. SelfPreferences.prototype.update=function(prefs,t){if(prefs["emoji_use"])this.favoriteEmojis=JSON.parse(prefs["emoji_use"]);if(prefs["highlight_words"])this.highlights=(prefs["highlight_words"]||"").split(",").filter(function(i){return i.trim()!==""});else if(prefs["highlights"])this.highlights=prefs["highlights"];this.version=Math.max(this.version,t)};SelfPreferences.prototype.toStatic=function(t){return this.version<=t?undefined:{"emoji_use":JSON.stringify(this.favoriteEmojis),"highlights":this.highlights}};
  4. function ChatContext(){this.team=null;this.channels={};this.users={};this.self=null;this.emojis={version:0,data:{}};this.commands={version:0,data:{}};this.typing={};this.capacities={};this.staticV=0;this.liveV=0}ChatContext.prototype.userFactory=function(userData){return new Chatter(userData["id"])};ChatContext.prototype.roomFactory=function(roomData){return roomData["pv"]?new PrivateMessageRoom(roomData["id"],this.users[roomData["user"]]):new Room(roomData["id"])};
  5. ChatContext.prototype.teamFactory=function(id){return new ChatInfo(id)};ChatContext.prototype.commandFactory=function(data){return new Command(data)};
  6. ChatContext.prototype.updateStatic=function(data,t,idPrefix){idPrefix=idPrefix||"";if(data["team"]){if(!this.team)this.team=this.teamFactory(data["team"]["id"]);this.team.update(data["team"],t)}if(data["users"])for(var i=0,nbUsers=data["users"].length;i<nbUsers;i++){var userObj=this.users[idPrefix+data["users"][i]["id"]];if(!userObj)userObj=this.users[idPrefix+data["users"][i]["id"]]=this.userFactory(data["users"][i]);userObj.update(data["users"][i],t)}if(data["channels"])for(var i=0,nbChan=data["channels"].length;i<
  7. nbChan;i++){var chanObj=this.channels[idPrefix+data["channels"][i]["id"]];if(!chanObj)chanObj=this.channels[idPrefix+data["channels"][i]["id"]]=this.roomFactory(data["channels"][i]);chanObj.update(data["channels"][i],this,t,idPrefix)}if(data["emojis"]){this.emojis.data=data["emojis"];this.emojis.version=t}if(data["commands"]!==undefined){this.commands.data={};for(var i in data["commands"])this.commands.data[i]=this.commandFactory(data["commands"][i]);this.commands.version=t}if(data["self"]){this.self=
  8. this.users[idPrefix+data["self"]["id"]]||null;if(!this.self.prefs)this.self.prefs=new SelfPreferences;if(data["self"]["prefs"])this.self.prefs.update(data["self"]["prefs"],t)}if(data["capacities"]){this.capacities={};data["capacities"].forEach(function(i){this.capacities[i]=true},this)}this.staticV=Math.max(this.staticV,t)};
  9. ChatContext.prototype.updateTyping=function(typing,now){var updated=false;if(this.typing)for(var i in this.typing)if(!typing[i]){delete this.typing[i];updated=true}if(typing)for(var i in typing)if(this.channels[i]){if(!this.typing[i])this.typing[i]={};for(var j in typing[i]){if(!this.typing[i][j])updated=true;this.typing[i][j]=now}}return updated};
  10. ChatContext.prototype.toStatic=function(t){var channels=[],users=[];var res={"team":this.team.toStatic(t),"self":{"id":this.self.id,"prefs":this.self.prefs?this.self.prefs.toStatic(t):undefined},"emojis":this.emojis.version>t?this.emojis.data:undefined};if(this.staticV>t)res["capacities"]=Object.keys(this.capacities);if(this.commands.version>t){res["commands"]={};for(var i in this.commands.data)res["commands"][i]=this.commands.data[i].toStatic(t)}for(var chanId in this.channels){var chan=this.channels[chanId].toStatic(t);
  11. if(chan)channels.push(chan)}if(channels.length)res["channels"]=channels;for(var userId in this.users){var user=this.users[userId].toStatic(t);if(user)users.push(user)}if(users.length)res["users"]=users;return res};
  12. ChatContext.prototype.getWhoIsTyping=function(now){var res;for(var typingChan in this.typing){var tChan=null;for(var typingUser in this.typing[typingChan])if(this.typing[typingChan][typingUser]>=now){if(!tChan)tChan={};tChan[typingUser]=1}else delete this.typing[typingChan][typingUser];if(tChan){if(!res)res={};res[typingChan]=tChan}else delete this.typing[typingChan]}return res};
  13. ChatContext.prototype.getChannelsWithName=function(name){var chans=[];for(var i in this.channels)if(this.channels[i].name===name)chans.push(this.channels[i]);return chans};
  14. ChatContext.prototype.cleanTyping=function(now){var updated=false;for(var typingChan in this.typing){var chanEmpty=true;for(var typingUser in this.typing[typingChan])if(this.typing[typingChan][typingUser]+3E3<now){delete this.typing[typingChan][typingUser];updated=true}else chanEmpty=false;if(chanEmpty){delete this.typing[typingChan];updated=true}}return updated};
  15. (function(){if(typeof module!=="undefined"){module.exports.ChatContext=ChatContext;module.exports.ChatInfo=ChatInfo;module.exports.Command=Command}})();function Room(id){this.id=id;this.name;this.created;this.creator;this.archived;this.isMember;this.starred=false;this.lastRead=0;this.lastMsg;this.users={};this.topic;this.topicTs;this.topicCreator;this.purpose;this.purposeTs;this.purposeCreator;this.version=0;this.isPrivate;this.pins}Room.prototype.setLastMsg=function(lastMsg,t){if(this.lastMsg<lastMsg){this.lastMsg=lastMsg;this.version=t;return true}return false};
  16. Room.prototype.toStatic=function(t){if(t>=this.version)return null;var res={"id":this.id,"name":this.name,"created":this.created,"creator":this.creator?this.creator.id:undefined,"is_archived":this.archived,"is_member":this.isMember,"last_read":this.lastRead,"last_msg":this.lastMsg,"is_private":this.isPrivate,"is_starred":this.starred||undefined,"pins":this.exposePins()};if(this.isMember){res["members"]=this.users?Object.keys(this.users):[];res["topic"]={"value":this.topic,"creator":this.topicCreator?
  17. this.topicCreator.id:null,"last_set":this.topicTs};res["purpose"]={"value":this.purpose,"creator":this.purposeCreator?this.purposeCreator.id:null,"last_set":this.purposeTs}}return res};
  18. Room.prototype.update=function(chanData,ctx,t,idPrefix){idPrefix=idPrefix||"";if(chanData["name"]!==undefined)this.name=chanData["name"];if(chanData["created"]!==undefined)this.created=chanData["created"];if(chanData["creator"]!==undefined)this.creator=ctx.users[chanData["creator"]];if(chanData["is_archived"]!==undefined)this.archived=chanData["is_archived"];if(chanData["is_member"]!==undefined)this.isMember=chanData["is_member"];if(chanData["last_read"]!==undefined)this.lastRead=Math.max(parseFloat(chanData["last_read"]),
  19. this.lastRead);if(chanData["last_msg"]!==undefined)this.lastMsg=parseFloat(chanData["last_msg"]);if(chanData["is_private"]!==undefined)this.isPrivate=chanData["is_private"];if(chanData["pins"]!==undefined)this.pins=chanData["pins"];this.starred=!!chanData["is_starred"];if(chanData["members"]){this.users={};if(chanData["members"])for(var i=0,nbMembers=chanData["members"].length;i<nbMembers;i++){var member=ctx.users[idPrefix+chanData["members"][i]];this.users[member.id]=member;member.channels[this.id]=
  20. this}}if(chanData["topic"]){this.topic=chanData["topic"]["value"];this.topicCreator=ctx.users[idPrefix+chanData["topic"]["creator"]];this.topicTs=chanData["topic"]["last_set"]}if(chanData["purpose"]){this.purpose=chanData["purpose"]["value"];this.purposeCreator=ctx.users[idPrefix+chanData["purpose"]["creator"]];this.purposeTs=chanData["purpose"]["last_set"]}this.version=Math.max(this.version,t)};
  21. Room.prototype.exposePins=function(){if(this.pins){var msgs=[];this.pins.forEach(function(msg){msgs.push(msg.toStatic())});return msgs}};Room.prototype.matchString=function(str,Utils){return{name:Utils.getClosestDistanceString(str,this.name),members:Utils.getClosestDistanceString(str,Object.values(this.users),function(m){return m?m.getName():null}),topic:Utils.getClosestDistanceString(str,this.topic),purpose:Utils.getClosestDistanceString(str,this.purpose)}};
  22. function PrivateMessageRoom(id,user){Room.call(this,id);this.user=user;this.name=user.getName();this.isPrivate=true;user.privateRoom=this}PrivateMessageRoom.prototype=Object.create(Room.prototype);PrivateMessageRoom.prototype.constructor=PrivateMessageRoom;PrivateMessageRoom.prototype.toStatic=function(t){return t>=this.version?null:{"id":this.id,"created":this.created,"user":this.user.id,"last_read":this.lastRead,"last_msg":this.lastMsg,"pv":true,"is_starred":this.starred||undefined,"pins":this.exposePins()}};
  23. (function(){if(typeof module!=="undefined"){module.exports.Room=Room;module.exports.PrivateMessageRoom=PrivateMessageRoom}})();function Message(e,ts){this.userId=e["user"];this.username=e["username"];this.id=e["id"]||e["ts"];this.ts=parseFloat(e["ts"]);this.text="";this.attachments=[];this.starred=e["is_starred"]||false;this.edited=false;this.removed=false;this.reactions={};this.version=ts;this.update(e,ts)}function MeMessage(e,ts){Message.call(this,e,ts)}function NoticeMessage(e,ts){Message.call(this,e,ts)}
  24. Message.prototype.update=function(e,ts){if(e){this.text=e["text"]||"";if(e["attachments"])this.attachments=e["attachments"];this.starred=!!e["is_starred"];this.edited=e["edited"]===undefined?false:e["edited"];this.removed=!!e["removed"];if(e["reactions"]){var reactions={};e["reactions"].forEach(function(r){reactions[r["name"]]=[];r["users"].forEach(function(userId){reactions[r["name"]].push(userId)})});this.reactions=reactions}}else this.removed=true;this.version=ts};
  25. Message.prototype.toStatic=function(){var reactions=[];for(var reaction in this.reactions)reactions.push({"name":reaction,"users":this.reactions[reaction]});return{"id":this.id,"user":this.userId,"username":this.username,"ts":this.ts,"text":this.text,"attachments":this.attachments.length?this.attachments:undefined,"is_starred":this.starred||undefined,"edited":this.edited===false?undefined:this.edited,"removed":this.removed||undefined,"reactions":reactions,"isMeMessage":this instanceof MeMessage||
  26. undefined,"isNotice":this instanceof NoticeMessage||undefined}};Message.prototype.addReaction=function(reaction,userId,ts){if(!this.reactions[reaction])this.reactions[reaction]=[];if(this.reactions[reaction].indexOf(userId)===-1){this.reactions[reaction].push(userId);this.version=ts;return true}return false};
  27. Message.prototype.removeReaction=function(reaction,userId,ts){var updated=false;if(this.reactions[reaction])if(this.reactions[reaction].length===1&&this.reactions[reaction][0]===userId){delete this.reactions[reaction];updated=true}else this.reactions[reaction]=this.reactions[reaction].filter(function(i){if(i!==userId)return true;updated=true;return false});if(updated)this.version=ts;return updated};
  28. Message.prototype.hasReactionForUser=function(reaction,userId){if(this.reactions[reaction])return this.reactions[reaction].indexOf(userId)!==-1;return false};function RoomHistory(room,keepMessages,maxAge,evts,now){this.id=typeof room==="string"?room:room.id;this.messages=[];this.maxAge=maxAge;this.v=0;this.keepMessages=keepMessages;if(evts)this.pushAll(evts,now)}
  29. RoomHistory.prototype.pushAll=function(evts,t){var result=0;evts.forEach(function(e){result=Math.max(this.push(e,t),result)}.bind(this));this.resort();return result};RoomHistory.prototype.messageFactory=function(ev,ts){if(ev["isMeMessage"]===true)return new MeMessage(ev,ts);if(ev["isNotice"]===true)return new NoticeMessage(ev,ts);return new Message(ev,ts)};
  30. RoomHistory.prototype.push=function(e,t){var exists=false,ts;for(var i=0,nbMsg=this.messages.length;i<nbMsg;i++){var msgObj=this.messages[i];if(msgObj.id===e["id"]){ts=msgObj.update(e,t);exists=true;break}}if(!exists){var msgObj=this.messageFactory(e,t);this.messages.push(msgObj);ts=msgObj.ts}this.cleanOld(t);return ts||0};
  31. RoomHistory.prototype.cleanOld=function(t){while(this.messages.length>this.keepMessages)this.messages.shift();if(this.maxAge)for(var i=0;i<this.messages.length;i++)if(this.messages[i].version<t-this.maxAge)this.messages.splice(i--,1)};RoomHistory.prototype.lastMessage=function(){return this.messages[this.messages.length-1]};RoomHistory.prototype.addReaction=function(reaction,userId,msgId,ts){var msg=this.getMessageById(msgId);if(msg)msg.addReaction(reaction,userId,ts);return msg};
  32. RoomHistory.prototype.removeReaction=function(reaction,userId,msgId,ts){var msg=this.getMessageById(msgId);if(msg)msg.removeReaction(reaction,userId,ts);return msg};RoomHistory.prototype.getMessage=function(ts){for(var i=0,nbMessages=this.messages.length;i<nbMessages&&ts>=this.messages[i].ts;i++)if(this.messages[i].ts===ts)return this.messages[i];return null};
  33. RoomHistory.prototype.getMessageById=function(id){for(var i=0,nbMessages=this.messages.length;i<nbMessages;i++)if(this.messages[i].id==id)return this.messages[i];return null};RoomHistory.prototype.last=function(){return this.messages[this.messages.length-1]};RoomHistory.prototype.toStatic=function(knownVersion){var result=[];for(var i=this.messages.length-1;i>=0;i--)if(this.messages[i].version>knownVersion)result.push(this.messages[i].toStatic());return result};
  34. RoomHistory.prototype.resort=function(){this.messages.sort(function(a,b){return a.ts-b.ts})};MeMessage.prototype=Object.create(Message.prototype);MeMessage.prototype.constructor=MeMessage;NoticeMessage.prototype=Object.create(Message.prototype);NoticeMessage.prototype.constructor=NoticeMessage;(function(){if(typeof module!=="undefined")module.exports={Message:Message,MeMessage:MeMessage,NoticeMessage:NoticeMessage,RoomHistory:RoomHistory}})();function Chatter(id){this.id=id;this.name;this.deleted;this.status;this.realName;this.goal;this.phone;this.presence;this.email;this.firstName;this.lastName;this.channels={};this.prefs=null;this.isBot;this.privateRoom=null;this.version=0}
  35. Chatter.prototype.toStatic=function(t){return t>=this.version?null:{"id":this.id,"name":this.name,"deleted":this.deleted,"status":this.status,"real_name":this.realName,"isPresent":this.presence,"isBot":this.isBot,"email":this.email,"phone":this.phone,"goal":this.goal,"first_name":this.firstName,"last_name":this.lastName}};
  36. Chatter.prototype.update=function(userData,t){if(userData["name"]!==undefined)this.name=userData["name"];if(userData["deleted"]!==undefined)this.deleted=userData["deleted"];if(userData["status"]!==undefined)this.status=userData["status"];if(userData["goal"]!==undefined)this.goal=userData["goal"];if(userData["phone"]!==undefined)this.phone=userData["phone"];if(userData["email"]!==undefined)this.email=userData["email"];if(userData["first_name"]!==undefined)this.firstName=userData["first_name"];if(userData["last_name"]!==
  37. undefined)this.lastName=userData["last_name"];if(userData["real_name"]!==undefined)this.realName=userData["real_name"];if(userData["isPresent"]!==undefined)this.presence=userData["isPresent"];if(userData["isBot"])this.isBot=userData["isBot"];this.version=Math.max(this.version,t)};Chatter.prototype.getSmallIcon=function(){return"api/avatar?user="+this.id};Chatter.prototype.getLargeIcon=function(){return"api/avatar?size=l&user="+this.id};
  38. Chatter.prototype.getName=function(){return this.name||this.realName||this.firstName||this.lastName};(function(){if(typeof module!=="undefined")module.exports.Chatter=Chatter})();var POLL_TIMEOUT=55E3;function ChatSystem(){}ChatSystem.prototype.onRequest=function(){};ChatSystem.prototype.getId=function(){};ChatSystem.prototype.getChatContext=function(){};ChatSystem.prototype.sendMeMsg=function(chan,text){};ChatSystem.prototype.sendMsg=function(chan,text,attachments){};ChatSystem.prototype.starMsg=function(chan,msgId){};ChatSystem.prototype.unstarMsg=function(chan,msgId){};ChatSystem.prototype.removeMsg=function(chan,ts){};ChatSystem.prototype.editMsg=function(chan,ts,newText){};
  39. ChatSystem.prototype.addReaction=function(chan,ts,reaction){};ChatSystem.prototype.removeReaction=function(chan,ts,reaction){};ChatSystem.prototype.openUploadFileStream=function(chan,contentType,callback){};ChatSystem.prototype.fetchHistory=function(chan,cb){};ChatSystem.prototype.sendTyping=function(chan){};ChatSystem.prototype.markRead=function(chan,ts){};ChatSystem.prototype.sendCommand=function(chan,cmd,args){};ChatSystem.prototype.poll=function(knownVersion,nowTs){};
  40. function MultiChatManager(){this.contexts=[]}MultiChatManager.prototype.push=function(chatSystem){this.contexts.push(chatSystem)};MultiChatManager.prototype.getById=function(id){for(var i=0,nbContexts=this.contexts.length;i<nbContexts;i++)if(id===this.contexts[i].getId())return this.contexts[i];return null};
  41. MultiChatManager.prototype.foreachChannels=function(cb){for(var i=0,nbCtx=this.contexts.length;i<nbCtx;i++){var ctx=this.contexts[i].getChatContext();for(var chanId in ctx.channels)if(cb(ctx.channels[chanId],chanId)===true)return}};MultiChatManager.prototype.foreachContext=function(cb){for(var i=0,nbCtx=this.contexts.length;i<nbCtx;i++)if(cb(this.contexts[i].getChatContext())===true)return};
  42. MultiChatManager.prototype.getChannelContext=function(chanId){for(var i=0,nbCtx=this.contexts.length;i<nbCtx;i++){var ctx=this.contexts[i].getChatContext();if(ctx.channels[chanId])return this.contexts[i]}return null};MultiChatManager.prototype.getUserContext=function(userId){for(var i=0,nbCtx=this.contexts.length;i<nbCtx;i++){var ctx=this.contexts[i].getChatContext();if(ctx.users[userId])return this.contexts[i]}return null};
  43. MultiChatManager.prototype.getChannel=function(chanId){for(var i=0,nbCtx=this.contexts.length;i<nbCtx;i++){var chan=this.contexts[i].getChatContext().channels[chanId];if(chan)return chan}return null};MultiChatManager.prototype.getChannelIds=function(filter){var ids=[];for(var i=0,nbCtx=this.contexts.length;i<nbCtx;i++){var channels=this.contexts[i].getChatContext().channels;for(var chanId in channels)if(!filter||filter(channels[chanId],this.contexts[i],chanId))ids.push(chanId)}return ids};
  44. MultiChatManager.prototype.getUser=function(userId){for(var i=0,nbCtx=this.contexts.length;i<nbCtx;i++){var user=this.contexts[i].getChatContext().users[userId];if(user)return user}return null};MultiChatManager.prototype.isMe=function(userId){for(var i=0,nbCtx=this.contexts.length;i<nbCtx;i++)if(this.contexts[i].getChatContext().self.id===userId)return true;return false};
  45. MultiChatManager.prototype.pollPeriodical=function(knownVersion){var liveFeed,staticFeed,allTyping,v=0,now=Date.now(),updated=false;this.contexts.forEach(function(ctx){var id=ctx.getId();if(id){var res=ctx.poll(knownVersion,now);if(res){if(res["static"]){if(!staticFeed)staticFeed={};staticFeed[id]=res["static"]}if(res["live"])if(!liveFeed)liveFeed={};for(var i in res["live"])liveFeed[i]=res["live"][i];if(res["typing"]){if(!allTyping)allTyping={};for(var i in res["typing"])allTyping[i]=res["typing"][i]}v=
  46. Math.max(v,res["v"]||0);updated=true}}});if(updated)return{"live":liveFeed,"static":staticFeed,"typing":allTyping,"v":Math.max(v,knownVersion)}};MultiChatManager.prototype.startPolling=function(knownVersion,reqT,callback){var _this=this;var res=_this.pollPeriodical(knownVersion),now=Date.now();if(res)callback(res);else if(now-reqT>POLL_TIMEOUT)callback({"v":knownVersion});else setTimeout(function(){_this.startPolling(knownVersion,reqT,callback)},2E3)};
  47. MultiChatManager.prototype.poll=function(knownVersion,reqT,callback,checkConfigUpdate){this.contexts.forEach(function(ctx){ctx.onRequest()});var _this=this;if(checkConfigUpdate)checkConfigUpdate(knownVersion,function(config){if(config){var exposedConfig=[],v=0;config.forEach(function(conf){exposedConfig.push(conf.expose());v=Math.max(v,conf.modified)});var res=_this.pollPeriodical(knownVersion);if(res){res["config"]=exposedConfig;callback(res)}else callback({"config":exposedConfig,"v":v})}else setTimeout(function(){_this.startPolling(knownVersion,
  48. reqT,callback)},1E3)});else setTimeout(function(){_this.startPolling(knownVersion,reqT,callback)},1E3)};(function(){if(typeof module!=="undefined")module.exports.MultiChatManager=MultiChatManager})();var Utils=function(){var stringDist=function(b,a){if(!a||b===undefined||b===null)return 0;if(!b.length)return 1;var pos=a.indexOf(b);if(pos===-1)return 0;return b.length/a.length},getClosestDistanceString=function(strToMatch,str,getString){if(Array.isArray(str)){var maxScore=0;for(var i=0,nbItems=str.length;i<nbItems;i++){var currentScore=getClosestDistanceString(strToMatch,str[i],getString);if(currentScore===1)return 1;maxScore=Math.max(currentScore,maxScore)}return maxScore}else return stringDist(strToMatch,
  49. getString?getString(str):str)};return{getClosestDistanceString:getClosestDistanceString}}();(function(){if(typeof module!=="undefined")module.exports.Utils=Utils})();var lang={},locale,onLangInitialized=[];function initLang(lg){if(!lg){for(var i=0,nbLang=navigator.languages.length;i<nbLang;i++)if(lang.hasOwnProperty(navigator.languages[i])){lg=navigator.languages[i];break}if(!lg)lg="en"}locale=lang[lg];console.log("Loading language pack: "+lg);if(locale.dom)for(var domId in locale.dom){var dom=document.getElementById(domId);if(dom)dom.textContent=locale.dom[domId]}onLangInitialized.forEach(function(fnc){fnc()})};lang["fr"]={unknownMember:"Utilisateur inconnu",unknownChannel:"Channel inconnu",newMessage:"Nouveau message",message:"Message",netErrorShort:"Reseau",onlyVisible:"(visible seulement par vous)",starred:"Favoris",channels:"Discutions",members:"Membres",privateMessageRoom:"Discutions priv\u00e9es",shareYourLocation:"Partage sa position GPS",ok:"Ok",dissmiss:"Annuler",formatDate:function(ts){if(typeof ts!=="string")ts=parseFloat(ts);var today=new Date,yesterday=new Date,dateObj=new Date(ts);today.setHours(0,
  50. 0,0,0);yesterday.setTime(today.getTime());yesterday.setDate(yesterday.getDate()-1);if(dateObj.getTime()>today.getTime())return dateObj.toLocaleTimeString();if(dateObj.getTime()>yesterday.getTime())return"hier, "+dateObj.toLocaleTimeString();return dateObj.toLocaleString()},chanName:function(serviceName,chanName){return serviceName+"/"+chanName},dom:{"fileUploadCancel":"Annuler","neterror":"Impossible de se connecter au chat !","ctxMenuSettings":"Configuration","settingTitle":"Configuration","setting-menu-services":"Services",
  51. "settings-services-title":"Services","setting-menu-display":"Affichage","settings-display-title":"Affichage","setting-menu-privacy":"Vie priv\u00e9e","settings-privacy-title":"Vie priv\u00e9e","settingCommit":"Appliquer","settings-serviceAddButton":"Ajouter un service","settings-serviceListEmpty":"Vous n'avez pas encore ajout\u00e9 de service. Ajouter un service pour continuer.","settings-serviceAddConfirm":"Suivant"}};
  52. lang["fr"].pinCount=function(count){if(count===0)return"Pas de message \u00e9pingl\u00e9";return count+(count===1?" message \u00e9pingl\u00e9":" messages \u00e9pingl\u00e9s")};lang["fr"].userCount=function(count){if(count===0)return"Pas de chatteur";return count+(count===1?" chatteur":" chatteurs")};lang["fr"].edited=function(ts){return"(edit&eacute; "+lang["fr"].formatDate(ts)+")"};lang["fr"].topicDetail=function(creator,ts){return"par "+creator.getName()+" le "+lang["fr"].formatDate(ts)};lang["en"]={unknownMember:"Unknown member",unknownChannel:"Unknown channel",newMessage:"New message",message:"Message",netErrorShort:"Network",onlyVisible:"(only visible to you)",starred:"Starred",channels:"Channels",members:"Members",privateMessageRoom:"Direct messages",shareYourLocation:"Share your GPS location",ok:"Ok",dissmiss:"Cancel",formatDate:function(ts){if(typeof ts!=="string")ts=parseFloat(ts);var today=new Date,yesterday=new Date,dateObj=new Date(ts);today.setHours(0,0,0,0);yesterday.setTime(today.getTime());
  53. yesterday.setDate(yesterday.getDate()-1);if(dateObj.getTime()>today.getTime())return dateObj.toLocaleTimeString();if(dateObj.getTime()>yesterday.getTime())return"yesterday, "+dateObj.toLocaleTimeString();return dateObj.toLocaleString()},chanName:function(serviceName,chanName){return serviceName+"/"+chanName},dom:{"fileUploadCancel":"Cancel","neterror":"Cannot connect to chat !","ctxMenuSettings":"Settings","settingTitle":"Settings","setting-menu-services":"Services","settings-services-title":"Services",
  54. "setting-menu-display":"Display","settings-display-title":"Display","setting-menu-privacy":"Privacy","settings-privacy-title":"Privacy","settingCommit":"Apply","settings-serviceAddButton":"Add a service","settings-serviceListEmpty":"You don't have any service yet. Please add a service to continue.","settings-serviceAddConfirm":"Next"}};lang["en"].pinCount=function(count){if(count===0)return"No pinned messages";return count+(count===1?" pinned message":" pinned messages")};
  55. lang["en"].userCount=function(count){if(count===0)return"No users in this room";return count+(count===1?" user":" users")};lang["en"].edited=function(ts){return"(edited "+lang["en"].formatDate(ts)+")"};lang["en"].topicDetail=function(creator,ts){return"by "+creator.getName()+" on "+lang["en"].formatDate(ts)};var formatText=function(){var text;var root;var opts={highlights:[],emojiFormatFunction:identity,textFilter:identity,linkFilter:linkidentity};function MsgTextLeaf(_parent){this.text="";this._parent=_parent}function MsgBranch(_parent,triggerIndex,trigger){this.triggerIndex=triggerIndex;this.lastNode=null;this.subNodes=[];this.trigger=trigger||"";this.isLink=this.trigger==="<";this.isBold=this.trigger==="*";this.isItalic=this.trigger==="_";this.isStrike=this.trigger==="~"||this.trigger==="-";this.isQuote=
  56. this.trigger===">"||this.trigger==="&gt;";this.isEmoji=this.trigger===":";this.isCode=this.trigger==="`";this.isCodeBlock=this.trigger==="```";this.isEol=this.trigger==="\n";this.isHighlight=trigger!==undefined&&opts.highlights.indexOf(trigger)!==-1;this._parent=_parent;this.prevTwin=null;this.terminated=this.isEol||this.isHighlight?triggerIndex+trigger.length-1:false;if(this.isHighlight){this.lastNode=new MsgTextLeaf(this);this.subNodes.push(this.lastNode);this.lastNode.text=trigger}}MsgBranch.prototype.checkIsBold=
  57. function(){return this.isBold&&!!this.terminated||this._parent instanceof MsgBranch&&this._parent.checkIsBold()};MsgBranch.prototype.checkIsItalic=function(){return this.isItalic&&!!this.terminated||this._parent instanceof MsgBranch&&this._parent.checkIsItalic()};MsgBranch.prototype.checkIsStrike=function(){return this.isStrike&&!!this.terminated||this._parent instanceof MsgBranch&&this._parent.checkIsStrike()};MsgBranch.prototype.checkIsQuote=function(){return this.isQuote&&!!this.terminated||this._parent instanceof
  58. MsgBranch&&this._parent.checkIsQuote()};MsgBranch.prototype.checkIsEmoji=function(){return this.isEmoji&&!!this.terminated||this._parent instanceof MsgBranch&&this._parent.checkIsEmoji()};MsgBranch.prototype.checkIsHighlight=function(){return this.isHighlight&&!!this.terminated||this._parent instanceof MsgBranch&&this._parent.checkIsHighlight()};MsgBranch.prototype.checkIsCode=function(){return this.isCode&&!!this.terminated||this._parent instanceof MsgBranch&&this._parent.checkIsCode()};MsgBranch.prototype.checkIsCodeBlock=
  59. function(){return this.isCodeBlock&&!!this.terminated||this._parent instanceof MsgBranch&&this._parent.checkIsCodeBlock()};MsgBranch.prototype.containsUnterminatedBranch=function(){for(var i=0,nbBranches=this.subNodes.length;i<nbBranches;i++)if(this.subNodes[i]instanceof MsgBranch&&(!this.subNodes[i].terminated||this.subNodes[i].containsUnterminatedBranch()))return true;return false};MsgBranch.prototype.finishWith=function(i){if(this.trigger==="<"&&text[i]===">")return true;var prevIsAlphadec=isAlphadec(text[i-
  60. 1]);if(!this.isQuote&&text.substr(i,this.trigger.length)===this.trigger){if(!prevIsAlphadec&&(this.isBold||this.isItalic||this.isStrike))return false;if(this.lastNode&&this.containsUnterminatedBranch())return this.lastNode.makeNewBranchFromThis();else if(this.hasContent())return true}if(text[i]==="\n"&&this.isQuote)return true;return false};MsgBranch.prototype.hasContent=function(){var _this=this;while(_this){for(var i=0,nbNodes=_this.subNodes.length;i<nbNodes;i++)if(_this.subNodes[i]instanceof MsgBranch||
  61. _this.subNodes[i].text.length)return true;_this=_this.prevTwin}return false};MsgBranch.prototype.makeNewBranchFromThis=function(){var other=new MsgBranch(this._parent,this.triggerIndex,this.trigger);other.prevTwin=this;if(this.lastNode&&this.lastNode instanceof MsgBranch){other.lastNode=this.lastNode.makeNewBranchFromThis();other.subNodes=[other.lastNode]}return other};MsgBranch.prototype.isAcceptable=function(i){if(this.isEmoji&&(text[i]===" "||text[i]==="\t"))return false;if((this.isEmoji||this.isLink||
  62. this.isBold||this.isItalic||this.isStrike||this.isCode)&&text[i]==="\n")return false;return true};MsgBranch.prototype.isNewToken=function(i){if(this.isCode||this.isEmoji||this.isCodeBlock||this.isLink)return null;if(!this.lastNode||this.lastNode.terminated||this.lastNode instanceof MsgTextLeaf){var prevIsAlphadec=isAlphadec(text[i-1]),nextIsAlphadec=isAlphadec(text[i+1]);if(text.substr(i,3)==="```")return"```";if(isBeginingOfLine()){if(text.substr(i,4)==="&gt;")return"&gt;";if(text[i]===">")return text[i]}if("`"===
  63. text[i]&&!prevIsAlphadec)return text[i];if("\n"===text[i])return text[i];if(["*","~","-","_"].indexOf(text[i])!==-1&&(nextIsAlphadec||text[i+1]===undefined||["*","~","-","_","<","&"].indexOf(text[i+1])!==-1)&&(!prevIsAlphadec||text[i-1]===undefined||["*","~","-","_","<","&"].indexOf(text[i-1])!==-1))return text[i];if([":"].indexOf(text[i])!==-1&&nextIsAlphadec)return text[i];if(["<"].indexOf(text[i])!==-1)return text[i];for(var highlightIndex=0,nbHighlight=opts.highlights.length;highlightIndex<nbHighlight;highlightIndex++){var highlight=
  64. opts.highlights[highlightIndex];if(text.substr(i,highlight.length)===highlight)return highlight}}return null};MsgTextLeaf.prototype.isBeginingOfLine=function(){if(this.text.trim()!=="")return false;return undefined};MsgBranch.prototype.isBeginingOfLine=function(){for(var i=this.subNodes.length-1;i>=0;i--){var isNewLine=this.subNodes[i].isBeginingOfLine();if(isNewLine!==undefined)return isNewLine}if(this.isEol||this.isQuote)return true;return undefined};function isAlphadec(c){return c>="A"&&c<="Z"||
  65. c>="a"&&c<="z"||c>="0"&&c<="9"||"\u00e0\u00e8\u00ec\u00f2\u00f9\u00c0\u00c8\u00cc\u00d2\u00d9\u00e1\u00e9\u00ed\u00f3\u00fa\u00fd\u00c1\u00c9\u00cd\u00d3\u00da\u00dd\u00e2\u00ea\u00ee\u00f4\u00fb\u00c2\u00ca\u00ce\u00d4\u00db\u00e3\u00f1\u00f5\u00c3\u00d1\u00d5\u00e4\u00eb\u00ef\u00f6\u00fc\u00ff\u00c4\u00cb\u00cf\u00d6\u00dc\u0178\u00e7\u00c7\u00df\u00d8\u00f8\u00c5\u00e5\u00c6\u00e6\u0153+".indexOf(c)!==-1}function isBeginingOfLine(){var isNewLine=root.isBeginingOfLine();return isNewLine===undefined?
  66. true:isNewLine}MsgTextLeaf.prototype.addChar=function(i){this.text+=text[i];return 1};MsgBranch.prototype.addChar=function(i){var isFinished=this.lastNode&&!this.lastNode.terminated&&this.lastNode.finishWith?this.lastNode.finishWith(i):null;if(isFinished){var lastTriggerLen=this.lastNode.trigger.length;this.lastNode.terminate(i);if(isFinished instanceof MsgBranch){this.lastNode=isFinished;this.subNodes.push(isFinished)}return lastTriggerLen}else if(!this.lastNode||this.lastNode.terminated||this.lastNode instanceof
  67. MsgTextLeaf||this.lastNode.isAcceptable(i)){var isNewToken=this.isNewToken(i);if(isNewToken){this.lastNode=new MsgBranch(this,i,isNewToken);this.subNodes.push(this.lastNode);return this.lastNode.trigger.length}else{if(!this.lastNode||this.lastNode.terminated){this.lastNode=new MsgTextLeaf(this);this.subNodes.push(this.lastNode)}return this.lastNode.addChar(i)}}else{var revertTo=this.lastNode.triggerIndex+1;root.cancelTerminate(this.lastNode.triggerIndex);this.lastNode=new MsgTextLeaf(this);this.lastNode.addChar(revertTo-
  68. 1);this.subNodes.pop();this.subNodes.push(this.lastNode);return revertTo-i}};MsgBranch.prototype.terminate=function(terminateAtIndex){var _this=this;while(_this){_this.terminated=terminateAtIndex;_this=_this.prevTwin}};MsgBranch.prototype.cancelTerminate=function(unTerminatedIndex){if(this.terminated&&this.terminated>=unTerminatedIndex)this.terminated=false;this.subNodes.forEach(function(node){if(node instanceof MsgBranch)node.cancelTerminate(unTerminatedIndex)})};MsgTextLeaf.prototype.innerHTML=
  69. function(){if(this._parent.checkIsEmoji()){var _parent=this._parent;while(_parent&&!_parent.isEmoji)_parent=_parent._parent;if(_parent){var fallback=_parent.trigger+this.text+_parent.trigger;var formatted=opts.emojiFormatFunction(fallback);return formatted?formatted:fallback}var _formatted=opts.emojiFormatFunction(this.text);return _formatted?_formatted:this.text}if(this._parent.checkIsCodeBlock()){if(typeof hljs!=="undefined")try{var lang=this.text.match(/^\w+/);hljs.configure({"useBR":true,"tabReplace":"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"});
  70. if(lang&&hljs.getLanguage(lang[0]))return hljs.fixMarkup(hljs.highlight(lang[0],this.text.substr(lang[0].length)).value);return hljs.fixMarkup(hljs.highlightAuto(this.text).value)}catch(e){console.error(e)}return this.text.replace(/\n/g,"<br/>")}return opts.textFilter(this.text)};MsgTextLeaf.prototype.outerHTML=function(){var tagName="span",classList=[],innerHTML,params="";if(this._parent.checkIsCodeBlock()){tagName="pre";classList.push("codeblock");innerHTML=this.innerHTML()}else if(this._parent.checkIsCode()){classList.push("code");
  71. innerHTML=this.innerHTML()}else{var link;if(this._parent.isLink&&(link=opts.linkFilter(this.text))){tagName="a";params=' href="'+link.link+'"';if(!link.isInternal)params+=' target="_blank"';innerHTML=opts.textFilter(link.text)}else innerHTML=this.innerHTML();if(this._parent.checkIsBold())classList.push("bold");if(this._parent.checkIsItalic())classList.push("italic");if(this._parent.checkIsStrike())classList.push("strike");if(this._parent.checkIsEmoji())classList.push("emoji");if(this._parent.checkIsHighlight())classList.push("highlight")}return"<"+
  72. tagName+params+(classList.length?' class="'+classList.join(" ")+'"':"")+">"+innerHTML+"</"+tagName+">"};MsgBranch.prototype.outerHTML=function(){var html="";if(this.isQuote)html+='<span class="quote">';if(this.isEol)html+="<br/>";this.subNodes.forEach(function(node){html+=node.outerHTML()});if(this.isQuote)html+="</span>";return html};function getFirstUnterminated(_root){_root=_root||root;for(var i=0,nbBranches=_root.subNodes.length;i<nbBranches;i++){var branch=_root.subNodes[i];if(branch instanceof
  73. MsgBranch)if(!branch.terminated)return branch;else{var unTerminatedChild=getFirstUnterminated(branch);if(unTerminatedChild)return unTerminatedChild}}return null}function revertTree(branch,next){if(branch._parent instanceof MsgBranch){branch._parent.subNodes.splice(branch._parent.subNodes.indexOf(branch)+(next?1:0));branch._parent.lastNode=branch._parent.subNodes[branch._parent.subNodes.length-1];revertTree(branch._parent,true)}}MsgBranch.prototype.implicitClose=function(i){if(this.isQuote&&!this.terminated)this.terminate(i);
  74. this.subNodes.forEach(function(node){if(node instanceof MsgBranch)node.implicitClose(i)})};function eof(){root.implicitClose(text.length);var unterminated=getFirstUnterminated();if(unterminated){revertTree(unterminated,false);root.cancelTerminate(unterminated.triggerIndex);var textNode=new MsgTextLeaf(unterminated._parent);textNode.addChar(unterminated.triggerIndex);unterminated._parent.subNodes.push(textNode);unterminated._parent.lastNode=textNode;return unterminated.triggerIndex+1}else;}function identity(a){return a}
  75. function linkidentity(str){return{link:str,text:str,isInternal:false}}function _parse(_text,_opts){if(!_opts)_opts={};opts.highlights=_opts.highlights||[];opts.emojiFormatFunction=_opts.emojiFormatFunction||identity;opts.textFilter=_opts.textFilter||identity;opts.linkFilter=_opts.linkFilter||linkidentity;text=_text;root=new MsgBranch(this,0);var i=0,textLen=text.length;do{while(i<textLen)i+=root.addChar(i);i=eof()}while(i!==undefined);return root.outerHTML()}return _parse}();
  76. if(typeof module!=="undefined")module.exports.formatText=formatText;var HttpRequestMethod={GET:"GET",POST:"POST",PUT:"PUT",DELETE:"DELETE"};var HttpRequestResponseType={ARRAYBUFFER:"arraybuffer",BLOB:"blob",DOCUMENT:"document",JSON:"json",TEXT:"text"};
  77. function HttpRequest(urlOrMethod,url){this.xhr=new XMLHttpRequest;this.url=url||urlOrMethod;this.method=url?urlOrMethod:HttpRequestMethod.GET;this._callback;this._callbackError;this._callbackSuccess;this.xhr.onreadystatechange=function(e){if(this.xhr.readyState===4){if(Math.floor(this.xhr.status/100)===2)HttpRequest.fireCallbacks(this._callbackSuccess,this.xhr.status,this.xhr.statusText,this.xhr.response);else HttpRequest.fireCallbacks(this._callbackError,this.xhr.status,this.xhr.statusText,this.xhr.response);
  78. HttpRequest.fireCallbacks(this._callback,this.xhr.status,this.xhr.statusText,this.xhr.response)}}.bind(this)}HttpRequest.fireCallbacks=function(callbacks,statusCode,statusText,response){if(callbacks)callbacks.forEach(function(cb){cb(statusCode,statusText,response)})};HttpRequest.prototype.callback=function(cb,ctx){if(!this._callback)this._callback=[];cb.bind(ctx||this);this._callback.push(cb);return this};
  79. HttpRequest.prototype.callbackSuccess=function(cb,ctx){if(!this._callbackSuccess)this._callbackSuccess=[];cb.bind(ctx||this);this._callbackSuccess.push(cb);return this};HttpRequest.prototype.callbackError=function(cb,ctx){if(!this._callbackError)this._callbackError=[];cb.bind(ctx||this);this._callbackError.push(cb);return this};HttpRequest.prototype.setTimeout=function(timeo){this.xhr.timeout=timeo;return this};
  80. HttpRequest.prototype.setResponseType=function(respType){this.xhr.responseType=respType;return this};HttpRequest.prototype.send=function(payload){this.xhr.open(this.method,this.url,true);this.xhr.send(payload);return this};function ConfirmDialog(title,content){this.title=title;this.content=content;this.dom=this.createDom();this.domOverlay=this.createDomOverlay();this.confirmHandlers=[];this.dissmissHandler=[]}
  81. ConfirmDialog.prototype.createDom=function(){var dom=document.createElement("div"),domTitle=document.createElement("header"),titleLabel=document.createElement("span"),closeButton=document.createElement("span"),domBody=document.createElement("div"),domButtons=document.createElement("footer");var _this=this;dom.confirmButton=document.createElement("span");dom.dissmissButton=document.createElement("span");titleLabel.textContent=this.title;if(typeof this.content=="string")domBody.innerHTML=this.content;
  82. else domBody.appendChild(this.content);domTitle.className=R.klass.dialog.title;titleLabel.className=R.klass.dialog.titleLabel;closeButton.className=R.klass.dialog.closeButton;closeButton.textContent="x";domTitle.appendChild(titleLabel);domTitle.appendChild(closeButton);dom.appendChild(domTitle);domBody.className=R.klass.dialog.body;dom.appendChild(domBody);dom.dissmissButton.className=R.klass.button;dom.dissmissButton.textContent=locale.dissmiss;dom.dissmissButton.addEventListener("click",function(){_this.buttonClicked(false)});
  83. closeButton.addEventListener("click",function(){_this.buttonClicked(false)});dom.confirmButton.addEventListener("click",function(){_this.buttonClicked(true)});domButtons.appendChild(dom.dissmissButton);dom.confirmButton.className=R.klass.button;dom.confirmButton.textContent=locale.ok;domButtons.appendChild(dom.confirmButton);domButtons.className=R.klass.buttonContainer+" "+R.klass.dialog.buttonBar;dom.appendChild(domButtons);dom.className=R.klass.dialog.container;return dom};
  84. ConfirmDialog.prototype.buttonClicked=function(confirmed){(confirmed?this.confirmHandlers:this.dissmissHandler).forEach(function(handler){handler()});this.close()};ConfirmDialog.prototype.createDomOverlay=function(){var dom=document.createElement("div");dom.className=R.klass.dialog.overlay;dom.addEventListener("click",function(){this.buttonClicked(false)}.bind(this));return dom};
  85. ConfirmDialog.prototype.setButtonText=function(confirmText,dissmissText){this.dom.confirmButton.textContent=confirmText;this.dom.dissmissButton.textContent=dissmissText;return this};ConfirmDialog.prototype.spawn=function(domParent){domParent=domParent||document.body;domParent.appendChild(this.domOverlay);domParent.appendChild(this.dom);return this};ConfirmDialog.prototype.close=function(){this.dom.remove();this.domOverlay.remove();return this};
  86. ConfirmDialog.prototype.onConfirm=function(handler){this.confirmHandlers.push(handler);return this};ConfirmDialog.prototype.onDissmiss=function(handler){this.dissmissHandler.push(handler);return this};var R={id:{chanList:"chanList",context:"chatCtx",chatList:"chatList",roomInfoPopin:"ctxRoomInfo",mainSection:"chatSystemContainer",currentRoom:{title:"currentRoomTitle",starButton:"currentRoomStar",content:"chatWindow"},typing:"whoistyping",chanFilter:"chanSearch",message:{form:"msgForm",submitButton:"msgFormSubmit",slashComplete:"slashList",input:"msgInput",replyTo:"replyToContainer",file:{bt:"attachFile",formContainer:"fileUploadContainer",fileInput:"fileUploadInput",form:"fileUploadForm",error:"fileUploadError",
  87. cancel:"fileUploadCancel"},emoji:"emojiButton"},settings:{menuButton:"ctxMenuSettings",closeButton:"settingDiscardClose",wrapper:"settings",commitBt:"settingCommit",menu:{list:"settingMenuItems"},services:{addButton:"settings-serviceAddButton",addSection:"settings-serviceAddSection",serviceProviderList:"settings-serviceAddServiceList",serviceAddConfirm:"settings-serviceAddConfirm"},display:{emojiProvider:"settings-displayEmojiProvider"}},favicon:"linkFavicon"},klass:{selected:"selected",hidden:"hidden",
  88. button:"button",buttonContainer:"button-container",noRoomSelected:"no-room-selected",noNetwork:"no-network",presenceIndicator:"presence-indicator",starred:"starred",unread:"unread",unreadHi:"unreadHi",replyingTo:"replyingTo",presenceAway:"presence-away",typing:{container:"typing-container",dot1:"typing-dot1",dot2:"typing-dot2",dot3:"typing-dot3"},emoji:{emoji:"emoji",small:"emoji-small",medium:"emoji-medium",custom:"emoji-custom"},commands:{item:"chat-command-item",header:"chat-command-header",name:"chat-command-name",
  89. usage:"chat-command-usage",desc:"chat-command-desc",userIcon:"chat-command-userIcon"},emojibar:{container:"emojibar",emojis:"emojibar-emojis",close:"emojibar-close",header:"emojibar-header",list:"emojibar-list",item:"emojibar-list-item",search:"emojibar-search",overlay:"emojibar-overlay",detail:{container:"emojibar-detail",img:"emojibar-detail-img",name:"emojibar-detail-name"}},chatList:{entry:"chat-context-room",typeChannel:"chat-channel",typePrivate:"chat-group",typeDirect:"chat-ims",typing:"chat-context-typing",
  90. roomInfo:{container:"chat-context-roominfo",title:"roominfo-title",presence:"roominfo-presence",topic:"roominfo-topic",topicCreator:"roominfo-topic-creator",purpose:"roominfo-purpose",purposeCreator:"roominfo-purpose-creator",userCount:"roominfo-usercount",userList:"roominfo-userlist",pinCount:"roominfo-pincount",pinList:"roominfo-pinlist",pinItem:"roominfo-pinlist-item",unpin:"roominfo-unpin",author:"roominfo-author",phone:"roominfo-phone",type:{channel:"roominfo-channel",user:"roominfo-user"}}},
  91. msg:{item:"chatmsg-item",notice:"chatmsg-notice",firstUnread:"chatmsg-first-unread",content:"chatmsg-content",meMessage:"chatmsg-me_message",ts:"chatmsg-ts",author:"chatmsg-author",authorname:"chatmsg-author-name",authorAvatar:"chatmsg-author-img",authorAvatarWrapper:"chatmsg-author-img-wrapper",authorMessages:"chatmsg-author-messages",msg:"chatmsg-msg",editedStatus:"edited",edited:"chatmsg-edited",authorGroup:"chatmsg-authorGroup",sameTs:"chatmsg-same-ts",hover:{container:"chatmsg-hover",reply:"chatmsg-hover-reply",
  92. reaction:"chatmsg-hover-reaction",edit:"chatmsg-hover-edit",star:"chatmsg-hover-star",pin:"chatmsg-hover-pin",remove:"chatmsg-hover-remove"},replyTo:{close:"replyto-close"},link:"chatmsg-link",linkuser:"chatmsg-link-user",linkchan:"chatmsg-link-chan",attachment:{container:"chatmsg-attachment",list:"chatmsg-attachments",hasThumb:"has-thumb",pretext:"chatmsg-attachment-pretext",block:"chatmsg-attachment-block",title:"chatmsg-attachment-title",content:"chatmsg-attachment-content",text:"chatmsg-attachment-text",
  93. thumbImg:"chatmsg-attachment-thumb",img:"chatmsg-attachment-img",actions:"chatmsg-attachment-actions",actionItem:"chatmsg-attachment-actions-item",field:{container:"chatmsg-attachment-fields",item:"field",title:"field-title",text:"field-text",longField:"field-long"},footer:"chatmsg-attachment-footer",footerText:"chatmsg-attachment-footer-text",footerIcon:"chatmsg-attachment-footer-icon"},reactions:{container:"chatmsg-reactions",item:"chatmsg-reaction-item"},style:{bold:"chatmsg-style-bold",code:"chatmsg-style-code",
  94. longCode:"chatmsg-style-longcode",italic:"chatmsg-style-italic",strike:"chatmsg-style-strike",quote:"chatmsg-style-quote"}},dialog:{container:"dialog",overlay:"dialog-overlay",title:"dialog-title",titleLabel:"dialog-title-label",closeButton:"dialog-title-close",body:"dialog-body",buttonBar:"dialog-footer"},map:{container:"OSM-wrapper",canvas:"OSM-canvas",buttonContainer:"OSM-controls",buttonM:"OSM-controls-zoomMin",buttonP:"OSM-controls-zoomPlus"}}};function createSlashAutocompleteHeader(servicename){var lh=document.createElement("lh");lh.textContent=servicename;lh.className=R.klass.commands.header;return lh}
  95. function createSlashAutocompleteDom(cmd,imgSpan){var li=document.createElement("li"),name=document.createElement("span");name.className=R.klass.commands.name;if(typeof cmd==="string"){if(imgSpan)li.appendChild(imgSpan);name.textContent=cmd;li.appendChild(name)}else{var usage=document.createElement("span"),desc=document.createElement("span");name.textContent=cmd.name;usage.textContent=cmd.usage;desc.textContent=cmd.desc;usage.className=R.klass.commands.usage;desc.className=R.klass.commands.desc;li.appendChild(name);
  96. li.appendChild(usage);li.appendChild(desc)}li.dataset.input=name.textContent;li.className=R.klass.commands.item;return li}
  97. function autoComplete(inputDom){var now=Date.now(),slashDom=document.getElementById(R.id.message.slashComplete);if(slashDom.dataset.cursor)delete slashDom.dataset.cursor;var commands=[],input=inputDom.value;if(inputDom.selectionStart===inputDom.selectionEnd&&inputDom.selectionStart){var start=inputDom.selectionStart,end=inputDom.selectionEnd;for(;start&&input[start-1]!==" ";start--);for(var valueLen=input.length;end<valueLen&&input[end]!==" ";end++);if(start!==end&&end-start-1>0){if(input[start]===
  98. "#"){var channels=SELECTED_CONTEXT.getChatContext().channels,inputStr=input.substr(start+1,end-start-1);for(var i in channels)if(channels[i].name.length>=inputStr.length&&channels[i].name.substr(0,inputStr.length)===inputStr)commands.push(channels[i])}else if(input[start]==="@"){var users=SELECTED_ROOM instanceof PrivateMessageRoom?SELECTED_CONTEXT.getChatContext().users:SELECTED_ROOM.users,inputStr=input.substr(start+1,end-start-1);for(var i in users){var userName=users[i].getName();if(userName.length>=
  99. inputStr.length&&userName.substr(0,inputStr.length)===inputStr)commands.push(users[i])}}else if(input[start]===":"&&window["searchEmojis"]){var inputCmd=input.substr(start+1,end-start-1),emojiList=window["searchEmojis"](inputCmd);for(var emojiCode in emojiList){var domEmoji=window["makeEmoji"](emojiCode,false),domParent=document.createElement("span");domParent.appendChild(domEmoji);domParent.className=R.klass.emoji.small;commands.push({name:":"+emojiCode+":",emojiSpan:domParent,provider:CURRENT_EMOJI_PROVIDER.name})}for(var i in SELECTED_CONTEXT.getChatContext().emojis.data)if(i.length>=
  100. inputCmd.length&&i.substr(0,inputCmd.length)===inputCmd){var emojiSpan=document.createElement("span");emojiSpan.className=R.klass.emoji.small;emojiSpan.appendChild(makeEmojiDom(i));commands.push({name:":"+i+":",emojiSpan:emojiSpan,provider:"custom"})}}if(commands.length)slashDom.dataset.cursor=JSON.stringify([start,end])}}if(!commands.length&&input[0]==="/"){var endCmd=input.indexOf(" "),inputFinished=endCmd!==-1;endCmd=endCmd===-1?input.length:endCmd;var inputCmd=input.substr(0,endCmd);if(inputFinished){var currentClientCmd=
  101. CLIENT_COMMANDS.getCommand(inputCmd);if(currentClientCmd)commands.push(currentClientCmd)}else{commands=CLIENT_COMMANDS.getCommandsStartingWith(inputCmd);slashDom.dataset.cursor=JSON.stringify([0,inputDom.selectionEnd])}var availableCommands=SELECTED_CONTEXT?SELECTED_CONTEXT.getChatContext().commands.data:{};for(var currentCmdId in availableCommands){var currentCmd=availableCommands[currentCmdId];if(!inputFinished&&currentCmd.name.substr(0,endCmd)===inputCmd||inputFinished&&currentCmd.name===inputCmd)commands.push(currentCmd)}commands.sort(function(a,
  102. b){return a.category.localeCompare(b.category)||a.name.localeCompare(b.name)})}slashDom.textContent="";if(commands.length){var slashFrag=document.createDocumentFragment(),prevService;for(var i=0,nbCmd=commands.length;i<nbCmd;i++){var command=commands[i];if(command instanceof Chatter){if(!prevService){prevService=true;slashFrag.appendChild(createSlashAutocompleteHeader(locale.members))}var span=document.createElement("span");span.className=R.klass.commands.userIcon;span.style.backgroundImage='url("'+
  103. command.getSmallIcon()+'")';slashFrag.appendChild(createSlashAutocompleteDom("@"+command.getName(),span))}else if(command instanceof Room){if(!prevService){prevService=true;slashFrag.appendChild(createSlashAutocompleteHeader(locale.channels))}slashFrag.appendChild(createSlashAutocompleteDom("#"+command.name))}else if(command.emojiSpan){if(prevService!==command.provider){prevService=command.provider;slashFrag.appendChild(createSlashAutocompleteHeader(command.provider))}slashFrag.appendChild(createSlashAutocompleteDom(command.name,
  104. command.emojiSpan))}else{if(prevService!==command.category){prevService=command.category;slashFrag.appendChild(createSlashAutocompleteHeader(command.category))}slashFrag.appendChild(createSlashAutocompleteDom(command))}}slashDom.appendChild(slashFrag)}}
  105. function onTextEntered(input,skipCommand){var success=true;if(EDITING){editMsg(SELECTED_ROOM,input,EDITING);return true}if(input[0]==="/"&&skipCommand!==true){var endCmd=input.indexOf(" "),cmd=input.substr(0,endCmd===-1?undefined:endCmd),args=endCmd===-1?"":input.substr(endCmd),ctx=SELECTED_CONTEXT,cliCmdObject=CLIENT_COMMANDS.getCommand(cmd);if(cliCmdObject){cliCmdObject.exec(ctx,SELECTED_ROOM,args.trim());return true}else if(ctx){var cmdObject=ctx.getChatContext().commands.data[cmd];if(cmdObject){doCommand(SELECTED_ROOM,
  106. cmdObject,args.trim());return true}}return false}sendMsg(SELECTED_ROOM,input,REPLYING_TO);return true}function focusInput(){document.getElementById(R.id.message.input).focus()}
  107. function initMsgInput(){var lastKeyDown=0,input=document.getElementById(R.id.message.input);function updateInputRowCount(input){var nbRows=1;for(var i=0,nbChars=input.value.length;i<nbChars;i++)if(input.value[i]==="\n")nbRows++;input.rows=Math.min(5,nbRows)}input.addEventListener("input",function(){if(SELECTED_ROOM){var now=Date.now();if(lastKeyDown+3E3<now&&(SELECTED_CONTEXT.getChatContext().self.presence||SELECTED_ROOM instanceof PrivateMessageRoom)){sendTyping(SELECTED_ROOM);lastKeyDown=now}autoComplete(this);
  108. updateInputRowCount(this)}});input.addEventListener("keydown",function(e){var TAB_KEY=9,ENTER_KEY=13;if(e.keyCode===TAB_KEY){e.preventDefault();return false}else if(e.keyCode===ENTER_KEY){e.preventDefault();if(e.shiftKey||e.altKey||e.ctrlKey){this.value+="\n";updateInputRowCount(this)}else onMsgFormSubmit();return false}});document.getElementById(R.id.message.slashComplete).addEventListener("click",function(e){if(SELECTED_ROOM){var target=e.target;var cursor=this.dataset.cursor;if(cursor){cursor=
  109. JSON.parse(cursor);while(target&&target!==this){if(target.dataset.input){var inputElement=document.getElementById(R.id.message.input),toAdd=target.dataset.input;if(inputElement.value.length<=cursor[1])toAdd+=" ";inputElement.value=inputElement.value.substr(0,cursor[0])+toAdd+inputElement.value.substr(cursor[1]);inputElement.selectionStart=inputElement.selectionEnd=cursor[0]+toAdd.length;autoComplete(inputElement);inputElement.focus();break}target=target.parentElement}}}})};var NOTIFICATION_COOLDOWN=30*1E3,NOTIFICATION_DELAY=5*1E3,MSG_GROUPS=[],lastNotificationSpawn=0;
  110. function onContextUpdated(){var chanListFram=document.createDocumentFragment(),sortedChans=DATA.context.getChannelIds(function(chan){return!chan.archived&&chan.isMember!==false}),starred=[],channels=[],privs=[],priv=[],chanNames={};sortedChans.sort(function(a,b){if(a[0]!==b[0])return a[0]-b[0];var aChanCtx=DATA.context.getChannelContext(a).getChatContext(),bChanCtx=DATA.context.getChannelContext(b).getChatContext(),aChan=aChanCtx.channels[a],bChan=bChanCtx.channels[b];if(aChan.name===bChan.name){chanNames[aChan.id]=
  111. locale.chanName(aChanCtx.team.name,aChan.name);chanNames[bChan.id]=locale.chanName(bChanCtx.team.name,bChan.name);return aChanCtx.team.name.localeCompare(bChanCtx.team.name)}return aChan.name.localeCompare(bChan.name)});sortedChans.forEach(function(chanId){var chan=DATA.context.getChannel(chanId),chanListItem;if(chan instanceof PrivateMessageRoom){if(!chan.user.deleted)if(chanListItem=createImsListItem(chan,chanNames[chan.id]))if(chan.starred)starred.push(chanListItem);else priv.push(chanListItem)}else if(chanListItem=
  112. createChanListItem(chan,chanNames[chan.id]))if(chan.starred)starred.push(chanListItem);else if(chan.isPrivate)privs.push(chanListItem);else channels.push(chanListItem)});if(starred.length)chanListFram.appendChild(createChanListHeader(locale.starred));starred.forEach(function(dom){chanListFram.appendChild(dom)});if(channels.length)chanListFram.appendChild(createChanListHeader(locale.channels));channels.forEach(function(dom){chanListFram.appendChild(dom)});privs.forEach(function(dom){chanListFram.appendChild(dom)});
  113. if(priv.length)chanListFram.appendChild(createChanListHeader(locale.privateMessageRoom));priv.forEach(function(dom){chanListFram.appendChild(dom)});document.getElementById(R.id.chanList).textContent="";document.getElementById(R.id.chanList).appendChild(chanListFram);filterChanList.apply(document.getElementById(R.id.chanFilter));setRoomFromHashBang();updateTitle();if(SELECTED_CONTEXT)createContextBackground(SELECTED_CONTEXT.getChatContext().team.id,SELECTED_CONTEXT.getChatContext().users,function(imgData){document.getElementById(R.id.context).style.backgroundImage=
  114. "url("+imgData+")"})}
  115. function onTypingUpdated(){DATA.context.foreachContext(function(ctx){var typing=ctx.typing;for(var chanId in ctx.self.channels)if(!ctx.self.channels[chanId].archived){var chanDom=document.getElementById("room_"+chanId);if(typing[chanId])chanDom.classList.add(R.klass.chatList.typing);else chanDom.classList.remove(R.klass.chatList.typing)}for(var userId in ctx.users){var ims=ctx.users[userId].privateRoom;if(ims&&!ims.archived){var userDom=document.getElementById("room_"+ims.id);if(userDom)if(typing[ims.id])userDom.classList.add(R.klass.chatList.typing);
  116. else userDom.classList.remove(R.klass.chatList.typing)}}});updateTypingChat()}
  117. function updateTypingChat(){var typing;document.getElementById(R.id.typing).textContent="";if(SELECTED_CONTEXT&&SELECTED_ROOM&&(typing=SELECTED_CONTEXT.getChatContext().typing[SELECTED_ROOM.id])){var areTyping=document.createDocumentFragment(),isOutOfSync=false;for(var i in typing){var member=DATA.context.getUser(i);if(member)areTyping.appendChild(makeUserIsTypingDom(member));else isOutOfSync=true}if(isOutOfSync)outOfSync();document.getElementById(R.id.typing).appendChild(areTyping)}}
  118. function onNetworkStateUpdated(isNetworkWorking){if(isNetworkWorking)document.body.classList.remove(R.klass.noNetwork);else document.body.classList.add(R.klass.noNetwork);updateTitle()}
  119. function onRoomSelected(){var name=SELECTED_ROOM.name||(SELECTED_ROOM.user?SELECTED_ROOM.user.getName():undefined);if(!name){console.error("No name provided for ",SELECTED_ROOM);var members=[];for(var userId in SELECTED_ROOM.users)members.push(SELECTED_ROOM.users[userId].getName());name=members.join(", ")}var roomLi=document.getElementById("room_"+SELECTED_ROOM.id);document.getElementById(R.id.currentRoom.title).textContent=name;onRoomUpdated();focusInput();document.getElementById(R.id.message.file.formContainer).classList.add(R.klass.hidden);
  120. markRoomAsRead(SELECTED_ROOM);if(REPLYING_TO){REPLYING_TO=null;onReplyingToUpdated()}if(EDITING){EDITING=null;onReplyingToUpdated()}updateTitle();updateTypingChat()}
  121. function onReplyingToUpdated(){if(REPLYING_TO){document.body.classList.add(R.klass.replyingTo);var domParent=document.getElementById(R.id.message.replyTo),closeLink=document.createElement("a");closeLink.addEventListener("click",function(){REPLYING_TO=null;onReplyingToUpdated()});closeLink.className=R.klass.msg.replyTo.close;closeLink.textContent="x";domParent.textContent="";domParent.appendChild(closeLink);domParent.appendChild(REPLYING_TO.duplicateDom());focusInput()}else{document.body.classList.remove(R.klass.replyingTo);
  122. document.getElementById(R.id.message.replyTo).textContent="";focusInput()}}
  123. function onEditingUpdated(){if(EDITING){document.body.classList.add(R.klass.replyingTo);var domParent=document.getElementById(R.id.message.replyTo),closeLink=document.createElement("a");closeLink.addEventListener("click",function(){EDITING=null;onEditingUpdated()});closeLink.className=R.klass.msg.replyTo.close;closeLink.textContent="x";domParent.textContent="";domParent.appendChild(closeLink);domParent.appendChild(EDITING.duplicateDom());document.getElementById(R.id.message.input).value=EDITING.text;
  124. focusInput()}else{document.body.classList.remove(R.klass.replyingTo);document.getElementById(R.id.message.replyTo).textContent="";focusInput()}}window["toggleReaction"]=function(chanId,msgId,reaction){var hist=DATA.history[chanId],msg,ctx;if((hist=DATA.history[chanId])&&(msg=hist.getMessageById(msgId))&&(ctx=DATA.context.getChannelContext(chanId)))if(msg.hasReactionForUser(reaction,ctx.getChatContext().self.id))removeReaction(chanId,msgId,reaction);else addReaction(chanId,msgId,reaction)};
  125. function setFavicon(unreadhi,unread){if(!unreadhi&&!unread)document.getElementById(R.id.favicon).href="favicon_ok.png";else document.getElementById(R.id.favicon).href="favicon.png?h="+unreadhi+"&m="+unread}function setNetErrorFavicon(){document.getElementById(R.id.favicon).href="favicon_err.png"}
  126. function updateTitle(){var hasHl=HIGHLIGHTED_CHANS.length,title="";if(NEXT_RETRY){title="!"+locale.netErrorShort+" - Mimouchat";setNetErrorFavicon()}else if(hasHl){title="(!"+hasHl+")";setFavicon(hasHl,hasHl)}else{var hasUnread=0;DATA.context.foreachChannels(function(i){if(i.lastMsg>i.lastRead)hasUnread++});if(hasUnread)title="("+hasUnread+")";setFavicon(0,hasUnread)}if(!title.length&&SELECTED_ROOM)title=SELECTED_ROOM.name;document.title=title.length?title:"Mimouchat"}
  127. function spawnNotification(){if(!("Notification"in window));else if(Notification.permission==="granted"){var now=Date.now();if(lastNotificationSpawn+NOTIFICATION_COOLDOWN<now){var n=new Notification(locale.newMessage);lastNotificationSpawn=now;setTimeout(function(){n.close()},NOTIFICATION_DELAY)}}else if(Notification.permission!=="denied")Notification.requestPermission()}
  128. function onRoomUpdated(){var chatFrag=document.createDocumentFragment(),currentRoomId=SELECTED_ROOM.id,prevMsg=null,firstTsCombo=0,prevMsgDom=null,currentMsgGroupDom;if(SELECTED_ROOM.starred)document.getElementById(R.id.mainSection).classList.add(R.klass.starred);else document.getElementById(R.id.mainSection).classList.remove(R.klass.starred);MSG_GROUPS=[];if(DATA.history[currentRoomId])DATA.history[currentRoomId].messages.forEach(function(msg){if(!msg.removed){var dom=msg.getDom(),newGroupDom=false;
  129. if(prevMsg&&prevMsg.userId===msg.userId&&msg.userId)if(Math.abs(firstTsCombo-msg.ts)<30&&!(msg instanceof MeMessage))prevMsgDom.classList.add(R.klass.msg.sameTs);else firstTsCombo=msg.ts;else{firstTsCombo=msg.ts;newGroupDom=true}if((!prevMsg||prevMsg.ts<=SELECTED_ROOM.lastRead)&&msg.ts>SELECTED_ROOM.lastRead)dom.classList.add(R.klass.msg.firstUnread);else dom.classList.remove(R.klass.msg.firstUnread);if(msg instanceof MeMessage){prevMsg=null;prevMsgDom=null;firstTsCombo=0;newGroupDom=true;chatFrag.appendChild(dom);
  130. currentMsgGroupDom=null}else{if(newGroupDom||!currentMsgGroupDom){currentMsgGroupDom=createMessageGroupDom(DATA.context.getUser(msg.userId),msg.username);MSG_GROUPS.push(currentMsgGroupDom);chatFrag.appendChild(currentMsgGroupDom)}prevMsg=msg;prevMsgDom=dom;currentMsgGroupDom.content.appendChild(dom)}}else msg.removeDom()});var content=document.getElementById(R.id.currentRoom.content);content.textContent="";content.appendChild(chatFrag);content.scrollTop=content.scrollHeight-content.clientHeight;
  131. updateAuthorAvatarImsOffset();if(window.hasFocus)markRoomAsRead(SELECTED_ROOM)}
  132. function onMsgClicked(target,msg){if(target.classList.contains(R.klass.msg.hover.reply)){if(EDITING){EDITING=null;onEditingUpdated()}if(REPLYING_TO!==msg){REPLYING_TO=msg;onReplyingToUpdated()}}else if(target.classList.contains(R.klass.msg.hover.reaction)){var currentRoomId=SELECTED_ROOM.id,currentMsgId=msg.id;EMOJI_BAR.spawn(document.body,SELECTED_CONTEXT,function(emoji){if(emoji)addReaction(currentRoomId,currentMsgId,emoji)})}else if(target.classList.contains(R.klass.msg.hover.edit)){if(REPLYING_TO){REPLYING_TO=
  133. null;onReplyingToUpdated()}if(EDITING!==msg){EDITING=msg;onEditingUpdated()}}else if(target.classList.contains(R.klass.msg.hover.star))if(msg.starred)unstarMsg(SELECTED_ROOM,msg);else starMsg(SELECTED_ROOM,msg);else if(target.classList.contains(R.klass.msg.hover.pin))if(msg.pinned)unpinMsg(SELECTED_ROOM,msg);else pinMsg(SELECTED_ROOM,msg);else if(target.classList.contains(R.klass.msg.hover.remove)){if(REPLYING_TO){REPLYING_TO=null;onReplyingToUpdated()}if(EDITING){EDITING=null;onEditingUpdated()}removeMsg(SELECTED_ROOM,
  134. msg)}}
  135. function chatClickDelegate(e){var target=e.target,getMessageId=function(e,target){target=target||e.target;while(target!==e.currentTarget&&target){if(target.id&&target.classList.contains(R.klass.msg.item))return target.id;target=target.parentElement}};while(target!==e.currentTarget&&target){if(target.classList.contains(R.klass.msg.hover.container))return;var messageId,msg;if(target.parentElement&&target.classList.contains(R.klass.msg.attachment.actionItem)){var attachmentIndex=target.dataset["attachmentIndex"],actionIndex=
  136. target.dataset["actionIndex"];messageId=getMessageId(e,target);if(messageId&&attachmentIndex!==undefined&&actionIndex!==undefined){messageId=messageId.substr(messageId.lastIndexOf("_")+1);msg=DATA.history[SELECTED_ROOM.id].getMessageById(messageId);if(msg&&msg.attachments[attachmentIndex]&&msg.attachments[attachmentIndex].actions&&msg.attachments[attachmentIndex].actions[actionIndex])confirmAction(SELECTED_ROOM.id,msg,msg.attachments[attachmentIndex],msg.attachments[attachmentIndex].actions[actionIndex]);
  137. return}}if(target.parentElement&&target.parentElement.classList.contains(R.klass.msg.hover.container)){if(messageId=getMessageId(e,target)){messageId=messageId.substr(messageId.lastIndexOf("_")+1);msg=DATA.history[SELECTED_ROOM.id].getMessageById(messageId);if(msg)onMsgClicked(target,msg)}return}target=target.parentElement}}
  138. function confirmAction(roomId,msg,attachmentObject,actionObject){var confirmed=function(){var payload=getActionPayload(roomId,msg,attachmentObject,actionObject);sendCommand(payload,msg.userId)};if(actionObject["confirm"])(new ConfirmDialog(actionObject["confirm"]["title"],actionObject["confirm"]["text"])).setButtonText(actionObject["confirm"]["ok_text"],actionObject["confirm"]["dismiss_text"]).onConfirm(confirmed).spawn();else confirmed()}
  139. function updateAuthorAvatarImsOffset(){var chatDom=document.getElementById(R.id.currentRoom.content),chatTop=chatDom.getBoundingClientRect().top;MSG_GROUPS.forEach(function(group){var imgDom=group.authorImgWrapper,imgSize=imgDom.clientHeight,domRect=group.getBoundingClientRect(),_top=0;imgDom.style.top=Math.max(0,Math.min(chatTop-domRect.top,domRect.height-imgSize-imgSize/2))+"px"})}
  140. function onEmojiReady(){var emojiButton=document.getElementById(R.id.message.emoji);invalidateAllMessages();EMOJI_BAR.reset();if("makeEmoji"in window){var emojiDom=window["makeEmoji"]("smile");if(emojiDom)emojiButton.innerHTML="<span class='"+R.klass.emoji.small+"'>"+emojiDom.outerHTML+"</span>";else emojiButton.style.backgroundImage='url("smile.svg")'}else emojiButton.classList.add(R.klass.hidden)}
  141. document.addEventListener("DOMContentLoaded",function(){initLang();initHljs();initMsgInput();var chanSearch=document.getElementById(R.id.chanFilter);chanSearch.addEventListener("input",filterChanList);chanSearch.addEventListener("blur",filterChanList);document.getElementById(R.id.currentRoom.content).addEventListener("click",chatClickDelegate);window.addEventListener("hashchange",function(e){if(document.location.hash&&document.location.hash[0]==="#")setRoomFromHashBang()});document.addEventListener("mouseover",
  142. function(e){var t=e.target;if(roomInfo.isParentOf(t)){roomInfo.cancelHide();return}while(t&&t!==this){if(t.nodeName==="A"){var href=t.href,sepPosition=href.indexOf("#");if(sepPosition>=0){href=href.substr(sepPosition+1);var channelCtx=DATA.context.getChannelContext(href);if(channelCtx){roomInfo.populate(channelCtx,channelCtx.getChatContext().channels[href]).show(t);return}channelCtx=DATA.context.getUserContext(href);if(channelCtx){var room=channelCtx.getChatContext().users[href].privateRoom;if(room){roomInfo.populate(channelCtx,
  143. room).show(t);return}}}}t=t.parentElement}roomInfo.hideDelayed()});document.getElementById(R.id.currentRoom.starButton).addEventListener("click",function(e){e.preventDefault();if(SELECTED_ROOM)if(SELECTED_ROOM.starred)unstarChannel(SELECTED_ROOM);else starChannel(SELECTED_ROOM);return false});document.getElementById(R.id.message.file.cancel).addEventListener("click",function(e){e.preventDefault();document.getElementById(R.id.message.file.error).classList.add(R.klass.hidden);document.getElementById(R.id.message.file.formContainer).classList.add(R.klass.hidden);
  144. document.getElementById(R.id.message.file.fileInput).value="";return false});document.getElementById(R.id.settings.menuButton).addEventListener("click",function(e){e.preventDefault();Settings.display().setClosable(true)});document.getElementById(R.id.message.file.form).addEventListener("submit",function(e){e.preventDefault();var fileInput=document.getElementById(R.id.message.file.fileInput),filename=fileInput.value;if(filename){filename=filename.substr(filename.lastIndexOf("\\")+1);uploadFile(SELECTED_ROOM,
  145. filename,fileInput.files[0],function(errorMsg){var error=document.getElementById(R.id.message.file.error);if(errorMsg){error.textContent=errorMsg;error.classList.remove(R.klass.hidden)}else{error.classList.add(R.klass.hidden);document.getElementById(R.id.message.file.fileInput).value="";document.getElementById(R.id.message.file.formContainer).classList.add(R.klass.hidden)}})}return false});document.getElementById(R.id.message.file.bt).addEventListener("click",function(e){e.preventDefault();if(SELECTED_ROOM)document.getElementById(R.id.message.file.formContainer).classList.remove(R.klass.hidden);
  146. return false});document.getElementById(R.id.message.submitButton).addEventListener("click",function(e){e.preventDefault();onMsgFormSubmit();return false});document.getElementById(R.id.message.form).addEventListener("submit",function(e){e.preventDefault();onMsgFormSubmit();return false});window.addEventListener("blur",function(){window.hasFocus=false});window.addEventListener("focus",function(){window.hasFocus=true;lastNotificationSpawn=0;if(SELECTED_ROOM)markRoomAsRead(SELECTED_ROOM);focusInput()});
  147. document.getElementById(R.id.currentRoom.content).addEventListener("scroll",updateAuthorAvatarImsOffset);window.hasFocus=true;var emojiButton=document.getElementById(R.id.message.emoji);emojiButton.addEventListener("click",function(){if(SELECTED_CONTEXT)EMOJI_BAR.spawn(document.body,SELECTED_CONTEXT.getChatContext(),function(e){if(e)document.getElementById(R.id.message.input).value+=":"+e+":";focusInput()})});startPolling()});
  148. function onMsgFormSubmit(){var input=document.getElementById(R.id.message.input);if(SELECTED_ROOM&&input.value)if(onTextEntered(input.value)){input.value="";if(REPLYING_TO){REPLYING_TO=null;onReplyingToUpdated()}if(EDITING){EDITING=null;onReplyingToUpdated()}document.getElementById(R.id.message.slashComplete).textContent=""}focusInput()};var Settings=function(){var displayed=false,currentPage=null,pages={services:"services",display:"display",privacy:"privacy"},spawn=function(){document.getElementById(R.id.settings.wrapper).classList.remove(R.klass.hidden);var emojiFrag=document.createDocumentFragment(),emojiList=document.getElementById(R.id.settings.display.emojiProvider);for(var i in EmojiProvider){var opt=document.createElement("option");opt.value=i;opt.textContent=EmojiProvider[i].name;if(EmojiProvider[i]===CURRENT_EMOJI_PROVIDER)opt.selected=
  149. true;emojiFrag.appendChild(opt)}emojiList.textContent="";emojiList.appendChild(emojiFrag);displayed=true},setVisiblePage=function(page){if(currentPage){document.getElementById(R.id.settings.wrapper).classList.remove("display-"+currentPage);document.getElementById("setting-menu-"+currentPage).classList.remove(R.klass.selected);document.getElementById(R.id.settings.services.addSection).classList.add(R.klass.hidden)}document.getElementById(R.id.settings.wrapper).classList.add("display-"+page);document.getElementById("setting-menu-"+
  150. page).classList.add(R.klass.selected);currentPage=page},close=function(){document.getElementById(R.id.settings.wrapper).classList.add(R.klass.hidden);displayed=false};document.getElementById(R.id.settings.menu.list).addEventListener("click",function(e){for(var target=e.target;e.currentTarget!==target&&target;target=target.parentNode)if(target.dataset&&target.dataset["target"])for(var i in pages)if(pages[i]===target.dataset["target"]){setVisiblePage(pages[i]);return}});document.getElementById(R.id.settings.closeButton).addEventListener("click",
  151. close);document.getElementById(R.id.settings.services.addButton).addEventListener("click",function(e){e.preventDefault();document.getElementById(R.id.settings.services.addSection).classList.remove(R.klass.hidden);return false});document.getElementById(R.id.settings.services.serviceAddConfirm).addEventListener("click",function(e){e.preventDefault();document.location.href=document.getElementById(R.id.settings.services.serviceProviderList).value;return false});document.getElementById(R.id.settings.commitBt).addEventListener("click",
  152. function(){loadEmojiProvider(document.getElementById(R.id.settings.display.emojiProvider).value);close()});return{display:function(page){if(!displayed)spawn();setVisiblePage(page||pages.services);return this},setClosable:function(closable){return this},pages:pages}}();function makeOSMTiles(geo){if(geo["latitude"]!==undefined&&geo["longitude"]!==undefined&&geo["latitude"]>=-90&&geo["latitude"]<=90&&geo["longitude"]>=-180&&geo["longitude"]<=180){var tileServer="https://c.tile.openstreetmap.org",currentVersion=0,getTile=function(zoom,x,y,result){return new Promise(function(resolve,reject){var img=new Image;img.addEventListener("load",function(){result.img=img;resolve(result)});img.addEventListener("error",function(){console.warn("Error loading tile ",{"zoom":zoom,
  153. "x":x,"y":y});reject(img)});img.crossOrigin="anonymous";img.src=tileServer+"/"+zoom+"/"+x+"/"+y+".png"})},canvas=document.createElement("canvas"),mapCanvas=document.createElement("canvas");var imgSize=300,tileSize=imgSize/3;canvas.height=canvas.width=mapCanvas.height=mapCanvas.width=imgSize;var ctx=canvas.getContext("2d"),mapCtx=mapCanvas.getContext("2d");var drawPlot=function(centerX,centerY,radius){centerX=tileSize*centerX+tileSize;centerY=tileSize*centerY+tileSize;ctx.putImageData(mapCtx.getImageData(0,
  154. 0,imgSize,imgSize),0,0);if(radius!==undefined){ctx.beginPath();ctx.arc(centerX,centerY,Math.max(radius,10),0,2*Math.PI,false);ctx.lineWidth=2;ctx.fillStyle="rgba(244, 146, 66, 0.4)";ctx.strokeStyle="rgba(244, 146, 66, 0.8)";ctx.stroke();ctx.fill()}if(radius===undefined||radius>25){ctx.strokeStyle="rgba(244, 146, 66, 1)";ctx.beginPath();ctx.moveTo(centerX-5,centerY-5);ctx.lineTo(centerX+5,centerY+5);ctx.stroke();ctx.moveTo(centerX+5,centerY-5);ctx.lineTo(centerX-5,centerY+5);ctx.stroke()}},distanceLatlonlon=
  155. function(lat,lon0,lon1){lat=lat*Math.PI/180;lon0=lon0*Math.PI/180;lon1=lon1*Math.PI/180;return Math.abs(6371E3*Math.acos(Math.pow(Math.sin(lat),2)+Math.pow(Math.cos(lat),2)*Math.cos(lon1-lon0)))},drawTiles=function(zoom,lat,lon,acc){mapCtx.fillStyle="#808080";mapCtx.fillRect(0,0,imgSize,imgSize);ctx.fillStyle="#808080";ctx.fillRect(0,0,imgSize,imgSize);var nbTiles=Math.pow(2,zoom),px=(lon+180)/360*nbTiles,py=(1-Math.log(Math.tan(lat*Math.PI/180)+1/Math.cos(lat*Math.PI/180))/Math.PI)/2*nbTiles,absoluteX=
  156. Math.floor(px),absoluteY=Math.floor(py),accRadiusPx=acc?acc*100/distanceLatlonlon(180/Math.PI*Math.atan(.5*(Math.exp(Math.PI-2*Math.PI*absoluteY/nbTiles)-Math.exp(-(Math.PI-2*Math.PI*absoluteY/nbTiles)))),absoluteX/nbTiles*360-180,(absoluteX+1)/nbTiles*360-180):0,v=currentVersion;for(var i=0;i<3;i++)for(var j=0;j<3;j++)getTile(zoom,absoluteX+i-1,absoluteY+j-1,{i:i,j:j,v:v}).then(function(img){if(img.v===currentVersion){mapCtx.drawImage(img.img,tileSize*img.i,tileSize*img.j,tileSize,tileSize);drawPlot(px-
  157. absoluteX,py-absoluteY,accRadiusPx)}})},currentZoom,setZoom=function(val){var newZoom=Math.max(4,Math.min(19,val));if(currentZoom!==newZoom){currentVersion++;currentZoom=newZoom;drawTiles(currentZoom,Number(geo["latitude"]),Number(geo["longitude"]),Number(geo["accuracy"]))}};setZoom(12);var canvasWrapper=document.createElement("div"),buttonContainer=document.createElement("div"),zoomP=document.createElement("button"),zoomM=document.createElement("button");canvasWrapper.className=R.klass.map.container;
  158. canvas.className=R.klass.map.canvas;buttonContainer.className=R.klass.map.buttonContainer;zoomM.className=R.klass.map.buttonM;zoomP.className=R.klass.map.buttonP;zoomM.addEventListener("click",function(){setZoom(currentZoom-1)});zoomP.addEventListener("click",function(){setZoom(currentZoom+1)});buttonContainer.appendChild(zoomM);buttonContainer.appendChild(zoomP);canvasWrapper.appendChild(canvas);canvasWrapper.appendChild(buttonContainer);return canvasWrapper}};function createTypingDisplay(){var dom=document.createElement("span"),dot1=document.createElement("span"),dot2=document.createElement("span"),dot3=document.createElement("span");dom.className=R.klass.typing.container;dot1.className=R.klass.typing.dot1;dot2.className=R.klass.typing.dot2;dot3.className=R.klass.typing.dot3;dot1.textContent=dot2.textContent=dot3.textContent=".";dom.appendChild(dot1);dom.appendChild(dot2);dom.appendChild(dot3);return dom}
  159. function createChanListItem(chan,alternateChanName){var dom=document.createElement("li"),link=document.createElement("a");dom.id="room_"+chan.id;link.href="#"+chan.id;if(chan.isPrivate){dom.className=R.klass.chatList.entry+" "+R.klass.chatList.typePrivate;dom.dataset["count"]=Object.keys(chan.users||{}).length}else dom.className=R.klass.chatList.entry+" "+R.klass.chatList.typeChannel;if(SELECTED_ROOM===chan)dom.classList.add(R.klass.selected);link.textContent=alternateChanName||chan.name;dom.appendChild(createTypingDisplay());
  160. dom.appendChild(link);if(chan.lastMsg>chan.lastRead){dom.classList.add(R.klass.unread);if(HIGHLIGHTED_CHANS.indexOf(chan)>=0)dom.classList.add(R.klass.unreadHi)}return dom}var createChanListHeader=function(){var cache={};return function(title){var dom=cache[title];if(!dom){dom=cache[title]=document.createElement("header");dom.textContent=title}return dom}}();
  161. function createImsListItem(ims,alternateChanName){var dom=document.createElement("li"),link=document.createElement("a");dom.id="room_"+ims.id;link.href="#"+ims.id;dom.className=R.klass.chatList.entry+" "+R.klass.chatList.typeDirect+" "+R.klass.presenceIndicator;link.textContent=alternateChanName||ims.user.getName();dom.appendChild(createTypingDisplay());dom.appendChild(link);if(!ims.user.presence)dom.classList.add(R.klass.presenceAway);if(SELECTED_ROOM===ims)dom.classList.add(R.klass.selected);if(ims.lastMsg>
  162. ims.lastRead){dom.classList.add(R.klass.unread);dom.classList.add(R.klass.unreadHi)}return dom}
  163. function tryGetCustomEmoji(emoji){var loop={};if(SELECTED_CONTEXT){var ctx=SELECTED_CONTEXT.getChatContext();while(!loop[emoji]){var emojisrc=ctx.emojis.data[emoji];if(emojisrc)if(emojisrc.substr(0,6)=="alias:"){loop[emoji]=true;emoji=emojisrc.substr(6)}else{var dom=document.createElement("span");dom.className=R.klass.emoji.custom+" "+R.klass.emoji.emoji;dom.style.backgroundImage="url('"+emojisrc+"')";return dom}else return emoji}}return emoji}
  164. function makeEmojiDom(emojiCode){var emoji=tryGetCustomEmoji(emojiCode);if(typeof emoji==="string"&&"makeEmoji"in window)emoji=window["makeEmoji"](emoji);return typeof emoji==="string"?null:emoji}
  165. function createReactionDom(chanId,msgId,reaction,users){var emojiDom=makeEmojiDom(reaction);if(emojiDom){var dom=document.createElement("li"),a=document.createElement("a"),emojiContainer=document.createElement("span"),userList=document.createElement("span"),userNames=[];for(var i=0,nbUser=users.length;i<nbUser;i++){var user=DATA.context.getUser(users[i]);if(user)userNames.push(user.getName())}userNames.sort();userList.textContent=userNames.join(", ");emojiContainer.appendChild(emojiDom);emojiContainer.className=
  166. R.klass.emoji.small;a.href="javascript:toggleReaction('"+chanId+"', '"+msgId+"', '"+reaction+"')";a.appendChild(emojiContainer);a.appendChild(userList);dom.className=R.klass.msg.reactions.item;dom.appendChild(a);return dom}else console.warn("Reaction id not found: "+reaction);return null}
  167. function addHoverButtons(hover,msg){var capacities=msg.context.getChatContext().capacities,isMe=DATA.context.isMe(msg.userId);if(capacities["replyToMsg"]){var hoverReply=document.createElement("li");hoverReply.className=R.klass.msg.hover.reply;hoverReply.style.backgroundImage='url("repl.svg")';hover.appendChild(hoverReply)}if(capacities["reactMsg"]){var hoverReaction=document.createElement("li");hoverReaction.className=R.klass.msg.hover.reaction;hoverReaction.style.backgroundImage='url("smile.svg")';
  168. hover.appendChild(hoverReaction)}if(isMe&&capacities["editMsg"]||capacities["editOtherMsg"]){var hoverEdit=document.createElement("li");hoverEdit.className=R.klass.msg.hover.edit;hoverEdit.style.backgroundImage='url("edit.svg")';hover.appendChild(hoverEdit)}if(capacities["starMsg"]){hover.hoverStar=document.createElement("li");hover.hoverStar.className=R.klass.msg.hover.star;hover.appendChild(hover.hoverStar)}if(capacities["pinMsg"]){var hoverPin=document.createElement("li");hoverPin.className=R.klass.msg.hover.pin;
  169. hover.appendChild(hoverPin);hoverPin.style.backgroundImage='url("pin.svg")'}if(isMe&&capacities["removeMsg"]||capacities["moderate"]){var hoverRemove=document.createElement("li");hoverRemove.className=R.klass.msg.hover.remove;hoverRemove.style.backgroundImage='url("remove.svg")';hover.appendChild(hoverRemove)}}
  170. function doCreateMessageDom(msg){var channelId=msg.channelId;var dom=document.createElement("div"),msgBlock=document.createElement("div"),hoverReaction=document.createElement("li");dom.hover=document.createElement("ul");dom.attachments=document.createElement("ul");dom.reactions=document.createElement("ul");dom.ts=document.createElement("div");dom.textDom=document.createElement("div");dom.authorName=document.createElement("span");dom.id=channelId+"_"+msg.id;dom.className=R.klass.msg.item;dom.ts.className=
  171. R.klass.msg.ts;dom.textDom.className=R.klass.msg.msg;dom.authorName.className=R.klass.msg.authorname;addHoverButtons(dom.hover,msg);dom.hover.className=R.klass.msg.hover.container;msgBlock.appendChild(dom.authorName);msgBlock.appendChild(dom.textDom);msgBlock.appendChild(dom.ts);msgBlock.appendChild(dom.attachments);dom.edited=document.createElement("div");dom.edited.className=R.klass.msg.edited;msgBlock.appendChild(dom.edited);msgBlock.appendChild(dom.reactions);msgBlock.className=R.klass.msg.content;
  172. dom.attachments.className=R.klass.msg.attachment.list;dom.reactions.className=R.klass.msg.reactions.container;dom.appendChild(msgBlock);dom.appendChild(dom.hover);return dom}
  173. function createMessageGroupDom(user,userName){var dom=document.createElement("div"),authorBlock=document.createElement("div"),authorName=document.createElement("a"),authorImg=document.createElement("img");dom.authorImgWrapper=document.createElement("span");dom.authorImgWrapper.className=R.klass.msg.authorAvatarWrapper;authorImg.className=R.klass.msg.authorAvatar;authorName.className=R.klass.msg.authorname;authorName.href="#"+user.id;if(user){authorName.textContent=user.getName();authorImg.src=user.getSmallIcon()}else{authorName.textContent=
  174. userName||"?";authorImg.src=""}dom.authorImgWrapper.appendChild(authorImg);authorBlock.appendChild(dom.authorImgWrapper);authorBlock.appendChild(authorName);authorBlock.className=R.klass.msg.author;dom.className=R.klass.msg.authorGroup;dom.appendChild(authorBlock);dom.content=document.createElement("div");dom.content.className=R.klass.msg.authorMessages;dom.appendChild(dom.content);return dom}
  175. function getColor(colorText){var colorMap={"good":"#2fa44f","warning":"#de9e31","danger":"#d50200"};if(colorText)if(colorText[0]==="#")return colorText;else if(colorMap[colorText])return colorMap[colorText];return"#e3e4e6"}
  176. function createAttachmentDom(channelId,msg,attachment,attachmentIndex){var rootDom=document.createElement("li"),attachmentBlock=document.createElement("div"),pretext=document.createElement("div"),titleBlock=document.createElement("a"),authorBlock=document.createElement("div"),authorImg=document.createElement("img"),authorName=document.createElement("a"),textBlock=document.createElement("div"),textDom=document.createElement("div"),thumbImgDom=document.createElement("div"),imgDom=document.createElement("img"),
  177. footerBlock=document.createElement("div");rootDom.className=R.klass.msg.attachment.container;attachmentBlock.style.borderColor=getColor(attachment["color"]||"");attachmentBlock.className=R.klass.msg.attachment.block;pretext.className=R.klass.msg.attachment.pretext;if(attachment["pretext"])pretext.innerHTML=msg.formatText(attachment["pretext"]);else pretext.classList.add(R.klass.hidden);titleBlock.target="_blank";if(attachment["title"]){titleBlock.innerHTML=msg.formatText(attachment["title"]);if(attachment["title_link"])titleBlock.href=
  178. attachment["title_link"];titleBlock.className=R.klass.msg.attachment.title}else titleBlock.className=R.klass.hidden+" "+R.klass.msg.attachment.title;authorName.target="_blank";authorBlock.className=R.klass.msg.author;if(attachment["author_name"]){authorName.innerHTML=msg.formatText(attachment["author_name"]);authorName.href=attachment["author_link"]||"";authorName.className=R.klass.msg.authorname;authorImg.className=R.klass.msg.authorAvatar;if(attachment["author_icon"]){authorImg.src=attachment["author_icon"];
  179. authorBlock.appendChild(authorImg)}authorBlock.appendChild(authorName)}thumbImgDom.className=R.klass.msg.attachment.thumbImg;if(attachment["thumb_url"]){var img=document.createElement("img");img.src=attachment["thumb_url"];thumbImgDom.appendChild(img);attachmentBlock.classList.add(R.klass.msg.attachment.hasThumb);if(attachment["video_html"])thumbImgDom.dataset["video"]=attachment["video_html"]}else thumbImgDom.classList.add(R.klass.hidden);textBlock.className=R.klass.msg.attachment.content;var textContent=
  180. msg.formatText(attachment["text"]||"");textDom.className=R.klass.msg.attachment.text;if(textContent&&textContent!="")textDom.innerHTML=textContent;else textDom.classList.add(R.klass.hidden);textBlock.appendChild(thumbImgDom);textBlock.appendChild(textDom);if(attachment["geo"]){var geoTileDom=makeOSMTiles(attachment["geo"]);if(geoTileDom)textBlock.appendChild(geoTileDom)}imgDom.className=R.klass.msg.attachment.img;if(attachment["image_url"])imgDom.src=attachment["image_url"];else imgDom.classList.add(R.klass.hidden);
  181. footerBlock.className=R.klass.msg.attachment.footer;if(attachment["footer"]){var footerText=document.createElement("span");footerText.className=R.klass.msg.attachment.footerText;footerText.innerHTML=msg.formatText(attachment["footer"]);if(attachment["footer_icon"]){var footerIcon=document.createElement("img");footerIcon.src=attachment["footer_icon"];footerIcon.className=R.klass.msg.attachment.footerIcon;footerBlock.appendChild(footerIcon)}footerBlock.appendChild(footerText)}if(attachment["ts"]){var footerTs=
  182. document.createElement("span");footerTs.className=R.klass.msg.ts;footerTs.innerHTML=locale.formatDate(attachment["ts"]);footerBlock.appendChild(footerTs)}attachmentBlock.appendChild(titleBlock);attachmentBlock.appendChild(authorBlock);attachmentBlock.appendChild(textBlock);attachmentBlock.appendChild(imgDom);if(attachment["fields"]&&attachment["fields"].length){var fieldsContainer=document.createElement("ul");attachmentBlock.appendChild(fieldsContainer);fieldsContainer.className=R.klass.msg.attachment.field.container;
  183. attachment["fields"].forEach(function(fieldData){var fieldDom=createFieldDom(msg,fieldData["title"]||"",fieldData["value"]||"",!!fieldData["short"]);if(fieldDom)fieldsContainer.appendChild(fieldDom)})}if(attachment["actions"]&&attachment["actions"].length){var buttons;buttons=document.createElement("ul");buttons.className=R.klass.msg.attachment.actions+" "+R.klass.buttonContainer;attachmentBlock.appendChild(buttons);for(var i=0,nbAttachments=attachment["actions"].length;i<nbAttachments;i++){var action=
  184. attachment["actions"][i];if(action){var button=createActionButtonDom(attachmentIndex,i,action);if(button)buttons.appendChild(button)}}}attachmentBlock.appendChild(footerBlock);rootDom.appendChild(pretext);rootDom.appendChild(attachmentBlock);return rootDom}
  185. function createFieldDom(msg,title,text,isShort){var fieldDom=document.createElement("li"),titleDom=document.createElement("div"),textDom=document.createElement("div");fieldDom.className=R.klass.msg.attachment.field.item;if(!isShort)fieldDom.classList.add(R.klass.msg.attachment.field.longField);titleDom.className=R.klass.msg.attachment.field.title;titleDom.textContent=title;textDom.className=R.klass.msg.attachment.field.text;textDom.innerHTML=msg.formatText(text);fieldDom.appendChild(titleDom);fieldDom.appendChild(textDom);
  186. return fieldDom}function createActionButtonDom(attachmentIndex,actionIndex,action){var li=document.createElement("li"),color=getColor(action["style"]);li.textContent=action["text"];if(color!==getColor())li.style.color=color;li.style.borderColor=color;li.dataset["attachmentIndex"]=attachmentIndex;li.dataset["actionIndex"]=actionIndex;li.className=R.klass.msg.attachment.actionItem+" "+R.klass.button;return li}
  187. function makeUserIsTypingDom(user){var dom=document.createElement("li"),userName=document.createElement("span");userName.textContent=user.getName();dom.appendChild(createTypingDisplay());dom.appendChild(userName);return dom};var EMOJI_BAR=function(){var dom=document.createElement("div"),overlay=document.createElement("div"),emojisDom=document.createElement("div"),unicodeEmojis=document.createElement("ul"),customEmojis=document.createElement("ul"),searchBar=document.createElement("input"),emojiCache={unicode:{},custom:{}},emojiDetail=document.createElement("div"),emojiDetailImg=document.createElement("span"),emojiDetailName=document.createElement("span"),emojiSelectedHandler,context,isSupported=function(){return"searchEmojis"in
  188. window},makeHeader=function(imgSrc){var img=document.createElement("img"),dom=document.createElement("div");img.src=imgSrc;dom.appendChild(img);dom.className=R.klass.emojibar.header;return dom},wrapEmojiLi=function(emojiName,emojiDom){var dom=document.createElement("li");dom.appendChild(emojiDom);dom.className=R.klass.emojibar.item;dom.id="emojibar-"+emojiName;return{visible:false,dom:dom}},makeUnicodeEmojiLi=function(emojiName,emoji){var domEmoji=window["makeEmoji"](emoji),domParent=document.createElement("span");
  189. domParent.appendChild(domEmoji);domParent.className=R.klass.emoji.medium;return wrapEmojiLi(emojiName,domParent)},makeCustomEmoji=function(emojiName,emojiSrc){var domEmoji=document.createElement("span"),domParent=document.createElement("span");domEmoji.className=R.klass.emoji.emoji+" "+R.klass.emoji.custom;domEmoji.style.backgroundImage='url("'+emojiSrc+'")';domParent.appendChild(domEmoji);domParent.className=R.klass.emoji.medium;return wrapEmojiLi(emojiName,domParent)},sortEmojis=function(emojiObj,
  190. favoriteEmojis){var names=[],index=0;for(var i in emojiObj){var obj={name:i,pos:index,count:0};if(emojiObj[i].names)for(var nameI=0,nbNames=emojiObj[i].names.length;nameI<nbNames;nameI++)obj.count+=favoriteEmojis[emojiObj[i].names[nameI]]||0;names.push(obj)}names=names.sort(function(a,b){var diff=b.count-a.count;if(diff)return diff;return a.pos-b.pos});return names},searchFromService=function(queryString){var emojiCount=0,foundEmojis=window["searchEmojis"](queryString),sortedEmojiNames=sortEmojis(foundEmojis,
  191. context?context.self.prefs.favoriteEmojis:[]),i,nbEmojis;for(i in emojiCache.unicode)if(emojiCache.unicode[i].visible){emojiCache.unicode[i].visible=false;unicodeEmojis.removeChild(emojiCache.unicode[i].dom)}for(i=0,nbEmojis=sortedEmojiNames.length;i<nbEmojis;i++){var emojiName=sortedEmojiNames[i].name,e=emojiCache.unicode[emojiName];if(!e)e=emojiCache.unicode[emojiName]=makeUnicodeEmojiLi(emojiName,foundEmojis[emojiName]);if(!e.visible){e.visible=true;unicodeEmojis.appendChild(e.dom)}emojiCount++}return emojiCount},
  192. searchFromCustom=function(queryString){var i,nbEmojis,emojiCount=0;for(i in emojiCache.custom)if(emojiCache.custom[i].visible){emojiCache.custom[i].visible=false;customEmojis.removeChild(emojiCache.custom[i].dom)}if(!context)return 0;var sortedEmojiNames=sortEmojis(context.emojis.data,context?context.self.prefs.favoriteEmojis:[]);for(i=0,nbEmojis=sortedEmojiNames.length;i<nbEmojis;i++){var emojiName=sortedEmojiNames[i].name;if((queryString===""||emojiName.substr(0,queryString.length)===queryString)&&
  193. context.emojis.data[emojiName].substr(0,6)!=="alias:"){var e=emojiCache.custom[emojiName];if(!e)e=emojiCache.custom[emojiName]=makeCustomEmoji(emojiName,context.emojis.data[emojiName]);if(!e.visible){e.visible=true;customEmojis.appendChild(e.dom)}emojiCount++}}return emojiCount},search=function(queryString){var emojiCount=0;queryString=queryString===undefined?searchBar.value:queryString;if(isSupported())emojiCount+=searchFromService(queryString);emojiCount+=searchFromCustom(queryString);return emojiCount},
  194. spawn=function(domParent,ctx,handler){if(isSupported()){context=ctx;emojiSelectedHandler=handler;domParent.appendChild(overlay);domParent.appendChild(dom);searchBar.value="";search();searchBar.focus();return true}return false},doClose=function(){if(dom.parentElement){dom.parentElement.removeChild(overlay);dom.parentElement.removeChild(dom);return true}return false},close=function(){var closed=doClose();if(!closed)return false;if(emojiSelectedHandler)emojiSelectedHandler(null);return true},onEmojiSelected=
  195. function(emojiName){if(doClose()&&emojiSelectedHandler)emojiSelectedHandler(emojiName)},reset=function(){emojiCache.unicode={};emojisDom.textContent="";if(window["emojiProviderHeader"]){emojisDom.appendChild(makeHeader(window["emojiProviderHeader"]));unicodeEmojis.textContent="";emojisDom.appendChild(unicodeEmojis)}emojisDom.appendChild(makeHeader("emojicustom.png"));emojisDom.appendChild(customEmojis)};overlay.addEventListener("click",function(e){var bounds=dom.getBoundingClientRect();if(e.screenY<
  196. bounds.top||e.screenY>bounds.bottom||e.screenX<bounds.left||e.screenX>bounds.right)close()});overlay.className=R.klass.emojibar.overlay;dom.className=R.klass.emojibar.container;emojisDom.className=R.klass.emojibar.emojis;unicodeEmojis.className=customEmojis.className=R.klass.emojibar.list;searchBar.className=R.klass.emojibar.search;emojiDetail.className=R.klass.emojibar.detail.container;emojiDetailImg.className=R.klass.emojibar.detail.img;emojiDetailName.className=R.klass.emojibar.detail.name;emojiDetail.appendChild(emojiDetailImg);
  197. emojiDetail.appendChild(emojiDetailName);reset();dom.appendChild(emojisDom);dom.appendChild(emojiDetail);dom.appendChild(searchBar);searchBar.addEventListener("keyup",function(){search()});var makeDelegate=function(e,cb){var target=e.target;while(target!==dom&&target&&target.nodeName!=="LI")target=target.parentElement;if(target&&target.nodeName==="LI"&&target.id&&target.id.substr(0,"emojibar-".length)==="emojibar-"){var emojiId=target.id.substr("emojibar-".length);return cb(emojiId)}cb(null)};dom.addEventListener("mousemove",
  198. function(e){makeDelegate(e,function(emoji){var emojiCached=emoji?emojiCache.unicode[emoji]||emojiCache.custom[emoji]:null;if(emojiCached){emojiDetailImg.innerHTML=emojiCached.dom.outerHTML;emojiDetailName.textContent=":"+emoji+":"}else{emojiDetailImg.textContent="";emojiDetailName.textContent=""}})});dom.addEventListener("click",function(e){makeDelegate(e,function(emoji){if(emoji)onEmojiSelected(emoji)})});return{isSupported:isSupported,spawn:spawn,search:search,close:close,reset:function(){reset();
  199. search()}}}();var DATA,HIGHLIGHTED_CHANS=[];function SimpleChatSystem(){ChatContext.call(this)}SimpleChatSystem.prototype=Object.create(ChatContext.prototype);SimpleChatSystem.prototype.constructor=SimpleChatSystem;SimpleChatSystem.prototype.getId=function(){return this.team?this.team.id:null};SimpleChatSystem.prototype.getChatContext=function(){return this};SimpleChatSystem.prototype.onRequest=function(){console.error("unimplemented")};SimpleChatSystem.prototype.sendMeMsg=function(chan,text){console.error("unimplemented")};
  200. SimpleChatSystem.prototype.sendMsg=function(chan,text,attachments){console.error("unimplemented")};SimpleChatSystem.prototype.removeMsg=function(chan,ts){console.error("unimplemented")};SimpleChatSystem.prototype.starMsg=function(chan,msgId){console.error("unimplemented")};SimpleChatSystem.prototype.unstarMsg=function(chan,msgId){console.error("unimplemented")};SimpleChatSystem.prototype.pinMsg=function(chan,msgId){console.error("unimplemented")};
  201. SimpleChatSystem.prototype.unpinMsg=function(chan,msgId){console.error("unimplemented")};SimpleChatSystem.prototype.editMsg=function(chan,ts,newText){console.error("unimplemented")};SimpleChatSystem.prototype.addReaction=function(chan,ts,reaction){console.error("unimplemented")};SimpleChatSystem.prototype.removeReaction=function(chan,ts,reaction){console.error("unimplemented")};SimpleChatSystem.prototype.openUploadFileStream=function(chan,contentType,callback){console.error("unimplemented")};
  202. SimpleChatSystem.prototype.fetchHistory=function(chan){console.error("unimplemented")};SimpleChatSystem.prototype.sendTyping=function(chan){console.error("unimplemented")};SimpleChatSystem.prototype.markRead=function(chan,ts){console.error("unimplemented")};SimpleChatSystem.prototype.sendCommand=function(chan,cmd,args){console.error("unimplemented")};SimpleChatSystem.prototype.poll=function(knownVersion,now){console.error("unimplemented");return null};
  203. function SlackWrapper(){this.lastServerVersion=0;this.context=new MultiChatManager;this.history={}}
  204. SlackWrapper.prototype.update=function(data){var now=Date.now(),i;if(data["v"])this.lastServerVersion=data["v"];if(data["static"])for(i in data["static"]){var ctx=this.context.getById(i);if(!ctx){ctx=new SimpleChatSystem;this.context.push(ctx)}var pins={};if(data["static"][i]["channels"])data["static"][i]["channels"].forEach(function(chanInfo){if(chanInfo["pins"]){pins[chanInfo["id"]]=chanInfo["pins"];chanInfo["pins"]=undefined}});ctx.getChatContext().updateStatic(data["static"][i],now);for(var chanId in pins){var msgs=
  205. [],histo=this.history[chanId];if(!histo)histo=this.history[chanId]=new UiRoomHistory(chanId,250,null,now);pins[chanId].forEach(function(msg){msgs.push(histo.messageFactory(msg,now))});ctx.getChatContext().channels[chanId].pins=msgs}}this.context.foreachChannels(function(chan){if(chan.lastMsg===chan.lastRead){var pos=HIGHLIGHTED_CHANS.indexOf(chan);if(pos!==-1)HIGHLIGHTED_CHANS.splice(pos,1)}});if(data["live"]){for(i in data["live"]){var history=this.history[i];if(!history)history=this.history[i]=
  206. new UiRoomHistory(i,250,data["live"][i],now);else history.pushAll(data["live"][i],now)}for(var roomId in data["live"]){var liveCtx=this.context.getChannelContext(roomId).getChatContext(),chan=liveCtx.channels[roomId];if(chan){if(this.history[roomId].messages.length)chan.lastMsg=Math.max(chan.lastMsg,this.history[roomId].lastMessage().ts);if(!chan.archived){onMsgReceived(liveCtx,chan,data["live"][roomId]);if(SELECTED_ROOM&&data["live"][SELECTED_ROOM.id])onRoomUpdated()}}else outOfSync()}}if(data["static"])onContextUpdated();
  207. var typingUpdated=false;if(data["typing"])this.context.contexts.forEach(function(ctx){var chatCtx=ctx.getChatContext();typingUpdated|=chatCtx.updateTyping(data["typing"],now)},this);if(data["static"]||typingUpdated)onTypingUpdated();if(data["config"]){CONFIG=new Config(data["config"]);onConfigUpdated()}if(SELECTED_CONTEXT&&SELECTED_ROOM&&data["static"]&&data["static"][SELECTED_CONTEXT.team.id]&&data["static"][SELECTED_CONTEXT.team.id]["channels"]&&data["static"][SELECTED_CONTEXT.team.id]["channels"]){var arr=
  208. data["static"][SELECTED_CONTEXT.team.id]["channels"];i=0;for(var nbChan=arr.length;i<nbChan;i++)if(arr[i].id===SELECTED_ROOM.id){onRoomUpdated();break}}};setInterval(function(){var updated=false,now=Date.now();DATA.context.foreachContext(function(ctx){if(ctx.getChatContext().cleanTyping(now))updated=true});if(updated)onTypingUpdated()},1E3);
  209. function isHighlighted(ctx,text){var highlights=ctx.self.prefs.highlights;for(var i=0,nbHighlights=highlights.length;i<nbHighlights;i++)if(text.indexOf(highlights[i])!==-1)return true;return false}
  210. function onMsgReceived(ctx,chan,msg){if(chan!==SELECTED_ROOM||!window.hasFocus){var selfReg=new RegExp("<@"+ctx.self.id),highligted=false,areNew=false,newHighlited=false;msg.forEach(function(i){if(parseFloat(i["ts"])<=chan.lastRead)return;if(i["userId"]===ctx.self.id){areNew=true;if(chan instanceof PrivateMessageRoom||i["text"]&&(i["text"].match(selfReg)||isHighlighted(ctx,i["text"]))){if(HIGHLIGHTED_CHANS.indexOf(chan)===-1){newHighlited=true;HIGHLIGHTED_CHANS.push(chan)}highligted=true}}});if(areNew){updateTitle();
  211. var dom=document.getElementById("room_"+chan.id);if(dom){dom.classList.add(R.klass.unread);if(highligted)dom.classList.add(R.klass.unreadHi)}if(newHighlited&&!window.hasFocus)spawnNotification()}}}
  212. function markRoomAsRead(room){var highlightIndex=HIGHLIGHTED_CHANS.indexOf(room);if(room.lastMsg>room.lastRead){var history=DATA.history[room.id];if(history){var lastMsg=history.last();if(lastMsg){sendReadMarker(room,lastMsg.id,lastMsg.ts);room.lastRead=lastMsg.ts}}}if(highlightIndex>=0){HIGHLIGHTED_CHANS.splice(highlightIndex,1);updateTitle()}var roomLi=document.getElementById("room_"+room.id);roomLi.classList.remove(R.klass.unread);roomLi.classList.remove(R.klass.unreadHi)}
  213. function invalidateAllMessages(){for(var i in DATA.history)DATA.history[i].invalidateAllMessages();if(SELECTED_ROOM)onRoomUpdated()}DATA=new SlackWrapper;var createContextBackground=function(){var canvas=document.createElement("canvas"),ctx=canvas.getContext("2d"),WIDTH=canvas.width=250,HEIGHT=canvas.height=290,MARGIN=20,NB_ITEM=3,ITEM_SIZE=(WIDTH-2*MARGIN)/NB_ITEM,ITEM_SPACING=.1*ITEM_SIZE,ITEM_INNER_SIZE=Math.floor(ITEM_SIZE-ITEM_SPACING*2),AVATAR_SIZE=ITEM_INNER_SIZE*.5,RESULT={},drawItem=function(background,avatar,x0,y0){var y0Index=Math.floor(y0),y1Index=Math.floor(y0+ITEM_SIZE),topColor=[background.data[y0Index*WIDTH*4+0],background.data[y0Index*
  214. WIDTH*4+1],background.data[y0Index*WIDTH*4+2]],botColor=[background.data[y1Index*WIDTH*4+0],background.data[y1Index*WIDTH*4+1],background.data[y1Index*WIDTH*4+2]],targetPcent=1.1,targetColor=(topColor[0]*targetPcent<<16|topColor[1]*targetPcent<<8|topColor[2]*targetPcent).toString(16);ctx.fillStyle="#"+targetColor;ctx.beginPath();ctx.moveTo(x0+ITEM_SIZE/2,y0+ITEM_SPACING);ctx.lineTo(x0-ITEM_SPACING+ITEM_SIZE,y0+ITEM_SIZE/2);ctx.lineTo(x0+ITEM_SIZE/2,y0-ITEM_SPACING+ITEM_SIZE);ctx.lineTo(x0+ITEM_SPACING,
  215. y0+ITEM_SIZE/2);ctx.closePath();ctx.fill();ctx.putImageData(blend(ctx.getImageData(x0+ITEM_SPACING,y0+ITEM_SPACING,ITEM_INNER_SIZE,ITEM_INNER_SIZE),avatar),x0+ITEM_SPACING,y0+ITEM_SPACING)},blend=function(img,img2){var margin=(img.height-img2.height)/2;for(var i=0;i<img2.height;i++)for(var j=0;j<img2.width;j++){var img2Grey=img2.data[(i*img2.width+j)*4]/255,iImg=((i+margin)*img.width+j+margin)*4;img.data[iImg]*=img2Grey;img.data[iImg+1]*=img2Grey;img.data[iImg+2]*=img2Grey}return img},drawBackground=
  216. function(){var grd=ctx.createLinearGradient(0,0,0,HEIGHT);grd.addColorStop(0,"#4D394B");grd.addColorStop(1,"#201820");ctx.fillStyle=grd;ctx.fillRect(0,0,WIDTH,HEIGHT);return ctx.getImageData(0,0,WIDTH,HEIGHT)},filterImage=function(img){var pixelSum=0,i;for(i=0;i<img.width*img.height*4;i+=4){img.data[i]=img.data[i+1]=img.data[i+2]=(img.data[i]+img.data[i+1]+img.data[i+2])/3;img.data[i+3]=50;pixelSum+=img.data[i]}if(pixelSum/(img.height*img.width)<50)for(i=0;i<img.width*img.height*4;i+=4)img.data[i]=
  217. img.data[i+1]=img.data[i+2]=255-img.data[i];return img},loadImgFromUrl=function(src,cb){(new HttpRequest(src)).callbackSuccess(function(code,head,response){if(response){var img=new Image;img.onload=function(){var imgCanvas=document.createElement("canvas");imgCanvas.height=imgCanvas.width=AVATAR_SIZE;var imgCtx=imgCanvas.getContext("2d");imgCtx.drawImage(img,0,0,AVATAR_SIZE,AVATAR_SIZE);cb(filterImage(imgCtx.getImageData(0,0,AVATAR_SIZE,AVATAR_SIZE)))};img.onerror=function(){cb(null)};img.src=window.URL.createObjectURL(response)}else cb(null)}).callbackError(function(){cb(null)}).setResponseType(HttpRequestResponseType.BLOB).send()},
  218. loadImages=function(userImgs,doneImgLoading){for(var i=0,nbImgs=userImgs.length;i<nbImgs;i++)if(userImgs[i].img===undefined){loadImgFromUrl(userImgs[i].src,function(img){userImgs[i].img=img;loadImages(userImgs,doneImgLoading)});return}var imgs=[];userImgs.forEach(function(i){if(i.img)imgs.push(i.img)});doneImgLoading(imgs)},compareImgs=function(a,b){if(!a.img)return 1;if(!b.img)return-1;return Math.random()-.5},renderAvatars=function(background,imgs){imgs.sort(function(a,b){return Math.random()-.5});
  219. for(var imgIndex=0,i=MARGIN;i<WIDTH-MARGIN*2;i+=ITEM_SIZE)for(var j=0;j+ITEM_SIZE<=HEIGHT;j+=ITEM_SIZE){drawItem(background,imgs[imgIndex],i,j);imgIndex++;if(imgIndex===imgs.length){imgs.sort(compareImgs);imgIndex=0}}},callbacks={},isLoading={};return function(ctxId,users,cb){if(RESULT[ctxId])cb(RESULT[ctxId]);else if(isLoading[ctxId])if(!callbacks[ctxId])callbacks[ctxId]=[cb];else callbacks[ctxId].push(cb);else{var background=drawBackground(),userImgs=[];isLoading[ctxId]=true;if(!callbacks[ctxId])callbacks[ctxId]=
  220. [cb];else callbacks[ctxId].push(cb);for(var userId in users)if(!users[userId].deleted&&!users[userId].isBot)userImgs.push({src:users[userId].getSmallIcon()});loadImages(userImgs,function(imgs){renderAvatars(background,imgs);RESULT[ctxId]=canvas.toDataURL();callbacks[ctxId].forEach(function(i){i(RESULT[ctxId])})})}}}();var NEXT_RETRY=0,SELECTED_ROOM=null,SELECTED_CONTEXT=null,REPLYING_TO=null,EDITING=null,KEEP_MESSAGES=100;
  221. function initHljs(){(new HttpRequest("highlight.pack.js")).callbackSuccess(function(code,head,resp){var script=document.createElement("script"),link=document.createElement("link");script.innerHTML=resp;script.language="text/javascript";link.href="hljs-androidstudio.css";link.rel="stylesheet";document.head.appendChild(link);document.body.appendChild(script)}).callbackError(function(){console.error("Failure loading hljs required files")}).setTimeout(1E3*60*1).send()}
  222. function fetchHistory(room,cb){(new HttpRequest("api/hist?room="+room.id)).setResponseType(HttpRequestResponseType.JSON).callbackSuccess(function(code,status,resp){if(resp){var history=DATA.history[room.id],updated;if(!history){history=DATA.history[room.id]=new UiRoomHistory(room,KEEP_MESSAGES,resp,Date.now());updated=true}else updated=!!history.pushAll(resp,Date.now());if(updated){onMsgReceived(DATA.context.getChannelContext(room.id).getChatContext(),room,resp);if(room===SELECTED_ROOM)onRoomUpdated()}}},
  223. this).callback(function(){}).send()}function onConfigUpdated(){if(isObjectEmpty(CONFIG.services))Settings.setClosable(false).display(Settings.pages.services);loadEmojiProvider(CONFIG.getEmojiProvider())}
  224. function poll(callback){(new HttpRequest("api?v="+DATA.lastServerVersion)).callback(function(statusCode,statusText,resp){if(statusCode===0){if(NEXT_RETRY){NEXT_RETRY=0;onNetworkStateUpdated(true)}poll(callback);return}var success=Math.floor(statusCode/100)===2;if(success){if(NEXT_RETRY){NEXT_RETRY=0;onNetworkStateUpdated(true)}}else if(NEXT_RETRY){NEXT_RETRY+=Math.floor((NEXT_RETRY||5)/2);NEXT_RETRY=Math.min(60,NEXT_RETRY)}else{NEXT_RETRY=5;onNetworkStateUpdated(false)}callback(success,resp)}).setResponseType(HttpRequestResponseType.JSON).setTimeout(1E3*
  225. 60*1).send()}function outOfSync(){DATA.lastServerVersion=0}function sendTyping(room){(new HttpRequest(HttpRequestMethod.POST,"api/typing?room="+room.id)).send()}function onPollResponse(success,response){if(success){if(response)DATA.update(response);startPolling()}else setTimeout(startPolling,NEXT_RETRY*1E3)}function startPolling(){poll(onPollResponse)}
  226. function selectRoom(room){if(SELECTED_ROOM)unselectRoom();document.getElementById("room_"+room.id).classList.add(R.klass.selected);document.body.classList.remove(R.klass.noRoomSelected);SELECTED_ROOM=room;SELECTED_CONTEXT=DATA.context.getChannelContext(room.id);onRoomSelected();roomInfo.hide();createContextBackground(SELECTED_CONTEXT.getChatContext().team.id,SELECTED_CONTEXT.getChatContext().users,function(imgData){document.getElementById(R.id.context).style.backgroundImage="url("+imgData+")"});if(!DATA.history[SELECTED_ROOM.id]||
  227. DATA.history[SELECTED_ROOM.id].messages.length<KEEP_MESSAGES)fetchHistory(SELECTED_ROOM,function(success){});document.getElementById(R.id.mainSection).classList.remove(R.klass.noRoomSelected)}function setRoomFromHashBang(){var hashId=document.location.hash.substr(1),room=DATA.context.getChannel(hashId);if(room&&room!==SELECTED_ROOM)selectRoom(room);else{var user=DATA.context.getUser(hashId);if(user&&user.privateRoom)selectRoom(user.privateRoom)}}
  228. function starChannel(room){(new HttpRequest(HttpRequestMethod.POST,"api/starChannel?room="+room.id)).send()}function unstarChannel(room){(new HttpRequest(HttpRequestMethod.POST,"api/unstarChannel?room="+room.id)).send()}function unselectRoom(){document.getElementById("room_"+SELECTED_ROOM.id).classList.remove(R.klass.selected);document.getElementById(R.id.mainSection).classList.add(R.klass.noRoomSelected)}
  229. function uploadFile(chan,filename,file,callback){var fileReader=new FileReader,formData=new FormData;formData.append("file",file);formData.append("filename",filename);(new HttpRequest(HttpRequestMethod.POST,"api/file?room="+chan.id)).callbackSuccess(function(){callback(null)}).callbackError(function(sCode,sText,resp){callback(sText)}).send(formData)}
  230. function sendCommand(payload,serviceId,callback){var xhr=new HttpRequest(HttpRequestMethod.POST,"api/attachmentAction?serviceId="+serviceId);if(callback)xhr.callbackSuccess(function(){callback(null)}).callbackError(function(code,head,resp){callback(head)});xhr.send(JSON.stringify(payload))}
  231. function getActionPayload(channelId,msg,attachment,action){var payload={"actions":[action],"attachment_id":attachment["id"],"callback_id":attachment["callback_id"],"channel_id":channelId,"is_ephemeral":msg instanceof NoticeMessage,"message_ts":msg["id"]};return payload}function doCommand(chan,cmd,args){(new HttpRequest(HttpRequestMethod.POST,"api/cmd?room="+chan.id+"&cmd="+encodeURIComponent(cmd.name.substr(1))+"&args="+encodeURIComponent(args))).send()}
  232. function sendMsg(chan,msg,replyTo){var url="api/msg?room="+chan.id+"&text="+encodeURIComponent(msg);if(replyTo){var sender=DATA.context.getUser(replyTo.userId),footer=chan.isPrivate?locale.message:chan.name;var attachment={"fallback":replyTo.text,"author_name":sender.getName(),"text":replyTo.text,"footer":footer,"ts":replyTo.ts};url+="&attachments="+encodeURIComponent(JSON.stringify([attachment]))}(new HttpRequest(HttpRequestMethod.POST,url)).send()}
  233. function editMsg(chan,text,msg){(new HttpRequest(HttpRequestMethod.PUT,"api/msg?room="+chan.id+"&ts="+msg.id+"&text="+encodeURIComponent(text))).send()}function removeMsg(chan,msg){(new HttpRequest(HttpRequestMethod.DELETE,"api/msg?room="+chan.id+"&ts="+msg.id)).send()}function pinMsg(chan,msg){(new HttpRequest(HttpRequestMethod.POST,"api/pinMsg?room="+chan.id+"&msgId="+msg.id)).send()}
  234. function starMsg(chan,msg){(new HttpRequest(HttpRequestMethod.POST,"api/starMsg?room="+chan.id+"&msgId="+msg.id)).send()}function unpinMsg(chan,msg){(new HttpRequest(HttpRequestMethod.DELETE,"api/pinMsg?room="+chan.id+"&msgId="+msg.id)).send()}function unstarMsg(chan,msg){(new HttpRequest(HttpRequestMethod.DELETE,"api/starMsg?room="+chan.id+"&msgId="+msg.id)).send()}
  235. function sendReadMarker(chan,id,ts){(new HttpRequest(HttpRequestMethod.POST,"api/markread?room="+chan.id+"&id="+id+"&ts="+ts)).send()}function addReaction(channelId,msgId,reaction){(new HttpRequest(HttpRequestMethod.POST,"api/reaction?room="+channelId+"&msg="+msgId+"&reaction="+encodeURIComponent(reaction))).send()}
  236. function removeReaction(channelId,msgId,reaction){(new HttpRequest(HttpRequestMethod.DELETE,"api/reaction?room="+channelId+"&msg="+msgId+"&reaction="+encodeURIComponent(reaction))).send()}
  237. function filterChanList(){var chans={},matchingChans=[],val=this.value;DATA.context.foreachChannels(function(chan){chans[chan.id]=chan.matchString(val,Utils)});for(var chanId in chans){var chanDom=document.getElementById("room_"+chanId);if(chanDom)if(chans[chanId].name+chans[chanId].members+chans[chanId].topic+chans[chanId].purpose){chanDom.classList.remove(R.klass.hidden);matchingChans.push(chanId)}else chanDom.classList.add(R.klass.hidden)}};var EmojiProvider={"emojione_v2_3":{js:"emojione_v2.3.sprites.js",css:"emojione_v2.3.sprites.css",name:"Emojione v2.3"},"emojione_v3":{js:"emojione_v3.sprites.js",css:"emojione_v3.sprites.css",name:"Emojione v3"}};var DEFAULT_EMOJI_PROVIDER=EmojiProvider["emojione_v2_3"],CURRENT_EMOJI_PROVIDER;
  238. function setEmojiProvider(provider){if(CURRENT_EMOJI_PROVIDER!==provider){console.log("Loading emoji pack "+provider.name);(new HttpRequest(provider.js)).callbackSuccess(function(code,head,resp){var script=document.createElement("script"),link=document.createElement("link");script.innerHTML=resp;script.language="text/javascript";link.href=provider.css;link.rel="stylesheet";document.head.appendChild(link);document.body.appendChild(script);onEmojiReady()}).setTimeout(1E3*60*1).send();CURRENT_EMOJI_PROVIDER=
  239. provider}}function loadEmojiProvider(providerId){setEmojiProvider(providerId&&EmojiProvider[providerId]?EmojiProvider[providerId]:DEFAULT_EMOJI_PROVIDER)}function isValidEmojiProvider(providerId){return!!EmojiProvider[providerId]};var roomInfo=function(){var dom=document.createElement("div"),domHeader=document.createElement("header"),headerContent=document.createElement("h3"),section=document.createElement("div"),topicDom=document.createElement("div"),topicContent=document.createElement("span"),topicDetails=document.createElement("span"),phone=document.createElement("div"),purposeDom=document.createElement("div"),purposeContent=document.createElement("span"),purposeDetails=document.createElement("span"),pinCount=document.createElement("div"),
  240. pinList=document.createElement("ul"),userCount=document.createElement("div"),userList=document.createElement("ul"),currentChatCtx,currentChan;dom.className=R.klass.chatList.roomInfo.container;domHeader.className=R.klass.chatList.roomInfo.title;topicDom.className=R.klass.chatList.roomInfo.topic;purposeDom.className=R.klass.chatList.roomInfo.purpose;phone.className=R.klass.chatList.roomInfo.phone;pinCount.className=R.klass.chatList.roomInfo.pinCount;pinList.className=R.klass.chatList.roomInfo.pinList;
  241. userCount.className=R.klass.chatList.roomInfo.userCount;userList.className=R.klass.chatList.roomInfo.userList;purposeDetails.className=topicDetails.className=R.klass.chatList.roomInfo.author;domHeader.appendChild(headerContent);dom.appendChild(domHeader);dom.appendChild(section);topicDom.appendChild(topicContent);topicDom.appendChild(topicDetails);purposeDom.appendChild(purposeContent);purposeDom.appendChild(purposeDetails);section.appendChild(topicDom);section.appendChild(phone);section.appendChild(purposeDom);
  242. section.appendChild(pinCount);section.appendChild(pinList);section.appendChild(userCount);section.appendChild(userList);var removePin=function(){if(currentChan.pins)for(var i=0,nbPins=currentChan.pins.length;i<nbPins;i++)if(currentChan.pins[i].id===this.dataset["msgId"]){unpinMsg(currentChan,currentChan.pins[i]);break}};var updateCommon=function(){headerContent.textContent=currentChan.name;if(currentChan.pins){pinCount.textContent=locale.pinCount(currentChan.pins.length);pinCount.classList.remove(R.klass.hidden);
  243. pinList.classList.remove(R.klass.hidden);var pinFrag=document.createDocumentFragment();currentChan.pins.forEach(function(uiMsg){var li=document.createElement("li"),unpinButton=document.createElement("a");unpinButton.href="javascript:void(0)";unpinButton.dataset["msgId"]=uiMsg.id;unpinButton.addEventListener("click",removePin);unpinButton.className=R.klass.button+" "+R.klass.chatList.roomInfo.unpin;li.className=R.klass.chatList.roomInfo.pinItem;li.appendChild(uiMsg.duplicateDom());li.appendChild(unpinButton);
  244. pinFrag.appendChild(li)});pinList.textContent="";pinList.appendChild(pinFrag)}else{pinCount.classList.add(R.klass.hidden);pinList.classList.add(R.klass.hidden)}},updateForChannel=function(){var ctx=currentChatCtx.getChatContext();if(ctx.capacities["topic"]){topicDom.classList.remove(R.klass.hidden);topicContent.textContent=currentChan.topic||"";topicDetails.textContent=currentChan.topicCreator?locale.topicDetail(currentChan.topicCreator,currentChan.topicTs):""}else topicDom.classList.add(R.klass.hidden);
  245. if(ctx.capacities["purpose"]){purposeDom.classList.remove(R.klass.hidden);purposeContent.textContent=currentChan.purpose||"";purposeDetails.textContent=currentChan.purposeCreator?locale.topicDetail(currentChan.purposeCreator,currentChan.purposeTs):""}else purposeDom.classList.add(R.klass.hidden);domHeader.style.backgroundImage="";headerContent.classList.remove(R.klass.presenceIndicator);userCount.textContent=locale.userCount(currentChan.users?Object.keys(currentChan.users).length:0);var memberIds=
  246. [];if(currentChan.users)for(var id in currentChan.users)memberIds.push(currentChan.users[id]);memberIds.sort(function(a,b){if(a.presence&&!b.presence)return-1;if(b.presence&&!a.presence)return 1;return a.getName().localeCompare(b.getName())});var userFrag=document.createDocumentFragment();memberIds.forEach(function(user){var li=document.createElement("li"),link=document.createElement("a");link.href="#"+user.id;link.textContent=user.getName();li.appendChild(link);li.classList.add(R.klass.presenceIndicator);
  247. if(!user.presence)li.classList.add(R.klass.presenceAway);userFrag.appendChild(li)});userList.textContent="";userList.appendChild(userFrag);dom.classList.add(R.klass.chatList.roomInfo.type.channel);dom.classList.remove(R.klass.chatList.roomInfo.type.user)},updateForDm=function(){domHeader.style.backgroundImage="url("+currentChan.user.getLargeIcon()+")";topicContent.textContent=(currentChan.user.realName||(currentChan.user.firstName||"")+" "+currentChan.user.lastName).trim();headerContent.classList.add(R.klass.presenceIndicator);
  248. if(currentChan.user.presence)headerContent.classList.remove(R.klass.presenceAway);else headerContent.classList.add(R.klass.presenceAway);topicDom.classList.remove(R.klass.hidden);phone.classList.remove(R.klass.hidden);phone.textContent=currentChan.user.phone||"";purposeContent.textContent=currentChan.user.goal||"";purposeDom.classList.remove(R.klass.hidden);dom.classList.remove(R.klass.chatList.roomInfo.type.channel);dom.classList.add(R.klass.chatList.roomInfo.type.user)},_update=function(){updateCommon();
  249. if(currentChan instanceof PrivateMessageRoom)updateForDm();else updateForChannel()};var hideTimeo=null;return{populate:function(channelContext,channel){this.cancelHide();currentChatCtx=channelContext;currentChan=channel;_update();return this},update:function(){this.cancelHide();_update();return this},show:function(domParent){this.cancelHide();domParent.appendChild(dom);dom.classList.remove(R.klass.hidden);return this},hide:function(){this.cancelHide();dom.classList.add(R.klass.hidden);return this},
  250. cancelHide:function(){if(hideTimeo)clearTimeout(hideTimeo);hideTimeo=null;return this},hideDelayed:function(){if(!hideTimeo)hideTimeo=setTimeout(function(){dom.classList.add(R.klass.hidden);hideTimeo=null},300);return this},isParentOf:function(_dom){while(_dom){if(_dom===dom)return true;_dom=_dom.parentNode}return false}}}();function UiRoomHistory(room,keepMessages,evts,now){RoomHistory.call(this,room,keepMessages,0,evts,now)}UiRoomHistory.prototype=Object.create(RoomHistory.prototype);UiRoomHistory.prototype.constructor=UiRoomHistory;UiRoomHistory.prototype.messageFactory=function(ev,ts){if(ev["isMeMessage"]===true)return new UiMeMessage(this.id,ev,ts);if(ev["isNotice"]===true)return new UiNoticeMessage(this.id,ev,ts);return new UiMessage(this.id,ev,ts)};UiRoomHistory.prototype.invalidateAllMessages=function(){this.messages.forEach(function(m){m.invalidate()})};
  251. function IUiMessage(){}IUiMessage.prototype.getDom=function(){};IUiMessage.prototype.removeDom=function(){};IUiMessage.prototype.invalidate=function(){};IUiMessage.prototype.createDom=function(){};IUiMessage.prototype.updateDom=function(){};IUiMessage.prototype.duplicateDom=function(){};
  252. var AbstractUiMessage=function(){var updateReactions=function(_this,channelId){var reactionFrag=document.createDocumentFragment();if(_this.reactions)for(var reaction in _this.reactions){var reac=createReactionDom(channelId,_this.id,reaction,_this.reactions[reaction]);if(reac)reactionFrag.appendChild(reac)}_this.dom.reactions.textContent="";_this.dom.reactions.appendChild(reactionFrag)},_linkFilter=function(msgContext,str){var sep=str.indexOf("|"),link,text,isInternal=false;if(sep===-1)link=str;else{link=
  253. str.substr(0,sep);text=str.substr(sep+1)}var newLink;if(link[0]==="@"){newLink=msgContext.context.getId()+"|"+link.substr(1);var user=DATA.context.getUser(newLink);if(user){isInternal=true;link="#"+user.privateRoom.id;text="@"+user.getName()}else return null}else if(link[0]==="#"){newLink=msgContext.context.getId()+"|"+link.substr(1);var chan=DATA.context.getChannel(newLink);if(chan){isInternal=true;link="#"+newLink;text="#"+chan.name}else return null}else{if(!link.match(/^(https?|mailto):\/\//i))return null;
  254. isInternal=false}return{link:link,text:text||link,isInternal:isInternal}},_formatText=function(_this,text){return formatText(text,{highlights:_this.context.self.prefs.highlights,emojiFormatFunction:function(emoji){if(emoji[0]===":"&&emoji[emoji.length-1]===":")emoji=emoji.substr(1,emoji.length-2);var emojiDom=makeEmojiDom(emoji);if(emojiDom){var domParent=document.createElement("span");domParent.className=R.klass.emoji.small;domParent.appendChild(emojiDom);return domParent.outerHTML}return null},
  255. linkFilter:function(link){return _linkFilter(_this,link)}})},updateAttachments=function(_this,channelId){var attachmentFrag=document.createDocumentFragment();for(var i=0,nbAttachments=_this.attachments.length;i<nbAttachments;i++){var attachment=_this.attachments[i];if(attachment){var domAttachment=createAttachmentDom(channelId,_this,attachment,i);if(domAttachment)attachmentFrag.appendChild(domAttachment)}}_this.dom.attachments.textContent="";_this.dom.attachments.appendChild(attachmentFrag)},updateHover=
  256. function(_this,channelId){if(_this.dom.hover.hoverStar)_this.dom.hover.hoverStar.style.backgroundImage=_this.starred?'url("star_full.png")':'url("star_empty.png")'},updateCommon=function(_this,sender){_this.dom.ts.innerHTML=locale.formatDate(_this.ts);_this.dom.textDom.innerHTML=_formatText(_this,_this.text);_this.dom.authorName.textContent=sender?sender.getName():_this.username||"?"};return{invalidate:function(_this){_this.uiNeedRefresh=true;return _this},removeDom:function(_this){if(_this.dom&&
  257. _this.dom.parentElement){_this.dom.remove();delete _this.dom}return _this},getDom:function(_this){if(!_this.dom)_this.createDom().updateDom();else if(_this.uiNeedRefresh){_this.uiNeedRefresh=false;_this.updateDom()}return _this.dom},updateDom:function(_this){var sender=DATA.context.getUser(_this.userId);updateCommon(_this,sender);updateAttachments(_this,_this.channelId);updateReactions(_this,_this.channelId);updateHover(_this,_this.channelId);if(_this.edited){_this.dom.edited.innerHTML=locale.edited(_this.edited);
  258. _this.dom.classList.add(R.klass.msg.editedStatus)}return _this},duplicateDom:function(_this){return _this.getDom().cloneNode(true)},formatText:function(_this,text){return _formatText(_this,text)}}}();function UiMeMessage(channelId,ev,ts){MeMessage.call(this,ev,ts);this.context=DATA.context.getChannelContext(channelId).getChatContext();this.channelId=channelId;this.dom=AbstractUiMessage.dom;this.uiNeedRefresh=AbstractUiMessage.uiNeedRefresh}UiMeMessage.prototype=Object.create(MeMessage.prototype);
  259. UiMeMessage.prototype.constructor=UiMeMessage;UiMeMessage.prototype.invalidate=function(){return AbstractUiMessage.invalidate(this)};UiMeMessage.prototype.formatText=function(text){return AbstractUiMessage.formatText(this,text)};UiMeMessage.prototype.removeDom=function(){return AbstractUiMessage.removeDom(this)};UiMeMessage.prototype.getDom=function(){return AbstractUiMessage.getDom(this)};
  260. UiMeMessage.prototype.createDom=function(){this.dom=doCreateMessageDom(this);this.dom.classList.add(R.klass.msg.meMessage);return this};UiMeMessage.prototype.duplicateDom=function(){return AbstractUiMessage.duplicateDom(this)};UiMeMessage.prototype.updateDom=function(){AbstractUiMessage.updateDom(this);return this};UiMeMessage.prototype.update=function(ev,ts){MeMessage.prototype.update.call(this,ev,ts);this.invalidate()};
  261. function UiMessage(channelId,ev,ts){Message.call(this,ev,ts);this.context=DATA.context.getChannelContext(channelId).getChatContext();this.channelId=channelId;this.dom=AbstractUiMessage.dom;this.uiNeedRefresh=AbstractUiMessage.uiNeedRefresh}UiMessage.prototype=Object.create(Message.prototype);UiMessage.prototype.constructor=UiMessage;UiMessage.prototype.invalidate=function(){return AbstractUiMessage.invalidate(this)};
  262. UiMessage.prototype.formatText=function(text){return AbstractUiMessage.formatText(this,text)};UiMessage.prototype.removeDom=function(){return AbstractUiMessage.removeDom(this)};UiMessage.prototype.getDom=function(){return AbstractUiMessage.getDom(this)};UiMessage.prototype.createDom=function(){this.dom=doCreateMessageDom(this);return this};UiMessage.prototype.duplicateDom=function(){return AbstractUiMessage.duplicateDom(this)};
  263. UiMessage.prototype.updateDom=function(){AbstractUiMessage.updateDom(this);return this};
  264. UiMessage.prototype.update=function(ev,ts){Message.prototype.update.call(this,ev,ts);this.invalidate();var match=this.text.match(/^<?https:\/\/www\.openstreetmap\.org\/\?mlat=(-?[0-9\.]+)(&amp;|&)mlon=(-?[0-9\.]+)(&amp;|&)macc=([0-9\.]+)[^\s]*/);if(match){var lat=match[1],lon=match[3],acc=match[5];this.text=this.text.substr(0,match.index)+this.text.substr(match.index+match[0].length).trim();this.attachments.unshift({"color":"#008000","text":match[0],"footer":"Open Street Map","footer_icon":"https://www.openstreetmap.org/assets/favicon-32x32-36d06d8a01933075bc7093c9631cffd02d49b03b659f767340f256bb6839d990.png",
  265. "geo":{"latitude":match[1],"longitude":match[3],"accuracy":match[5]}})}};function UiNoticeMessage(channelId,ev,ts){NoticeMessage.call(this,ev,ts);this.context=DATA.context.getChannelContext(channelId).getChatContext();this.channelId=channelId;this.dom;this.domWrapper=null;this.uiNeedRefresh=true}UiNoticeMessage.prototype=Object.create(NoticeMessage.prototype);UiNoticeMessage.prototype.constructor=UiNoticeMessage;UiNoticeMessage.prototype.invalidate=function(){return AbstractUiMessage.invalidate(this)};
  266. UiNoticeMessage.prototype.formatText=function(text){return AbstractUiMessage.formatText(this,text)};UiNoticeMessage.prototype.removeDom=function(){if(this.domWrapper&&this.domWrapper.parentElement){this.domWrapper.remove();delete this.domWrapper}if(this.dom)delete this.dom;return this};UiNoticeMessage.prototype.getDom=function(){AbstractUiMessage.getDom(this);return this.domWrapper};UiNoticeMessage.prototype.duplicateDom=function(){return this.domWrapper.cloneNode(true)};
  267. UiNoticeMessage.prototype.createDom=function(){this.dom=doCreateMessageDom(this);this.domWrapper=document.createElement("span");this.dom.classList.add(R.klass.msg.notice);this.domWrapper.className=R.klass.msg.notice;this.domWrapper.textContent=locale.onlyVisible;this.domWrapper.appendChild(this.dom);return this};UiNoticeMessage.prototype.updateDom=function(){AbstractUiMessage.updateDom(this);return this};
  268. UiNoticeMessage.prototype.update=function(ev,ts){NoticeMessage.prototype.update.call(this,ev,ts);this.invalidate()};function isObjectEmpty(o){for(var i in o)if(o.hasOwnProperty(i))return false;return true};var CONFIG;function Config(configData){this.deviceId=null;this.services={};for(var i=0,nbConfig=configData.length;i<nbConfig;i++)if(configData[i]["service"]===null&&configData[i]["device"]===null)this.mergeConfig(JSON.parse(configData[i]["config"]))}Config.prototype.mergeConfig=function(configData){if(configData["services"])for(var i in configData["services"])this.services[i]=configData["services"][i]};
  269. Config.prototype.getEmojiProvider=function(){for(var i in this.services){var emojiProvider=this.services[i]["emojiProvider"];if(emojiProvider&&isValidEmojiProvider(emojiProvider))return emojiProvider}};var CLIENT_COMMANDS=function(){var commands=[];return{getCommand:function(name){for(var i=0,nbCmd=commands.length;i<nbCmd;i++)if(commands[i].names.indexOf(name)!==-1)return commands[i];return null},getCommandsStartingWith:function(cmdPrefix){var result=[];commands.forEach(function(cmd){for(var i=0,nbNames=cmd.names.length;i<nbNames;i++)if(cmd.names[i].substr(0,cmdPrefix.length)===cmdPrefix){result.push(cmd);break}});return result},registerCommand:function(cmdObj){cmdObj.category="client";cmdObj.exec=
  270. cmdObj.exec.bind(cmdObj);commands.push(cmdObj)}}}();function getLocation(){return new Promise(function(resolve,reject){if("geolocation"in window.navigator)navigator.geolocation.getCurrentPosition(function(coords){if(coords)resolve(coords);else reject("denied")});else reject("geolocation not available")})}
  271. onLangInitialized.push(function(){CLIENT_COMMANDS.registerCommand({name:"/sherlock",names:["/sherlock","/sharelock"],usage:"",description:locale.shareYourLocation,exec:function(context,room,args){getLocation().then(function(coords){var lat=coords["coords"]["latitude"],lon=coords["coords"]["longitude"],acc=coords["coords"]["accuracy"];sendMsg(room,"https://www.openstreetmap.org/?mlat="+lat+"&mlon="+lon+"&macc="+acc+"#map=17/"+lat+"/"+lon)}).catch(function(err){console.error("Error: ",err)})}})});