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"]} 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} 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}}; 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"])}; ChatContext.prototype.teamFactory=function(id){return new ChatInfo(id)};ChatContext.prototype.commandFactory=function(data){return new Command(data)}; 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;it?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); 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}; 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}; 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}; 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=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? 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}; 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"]), 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=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()}}; (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)} 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}; 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|| 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}; 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}; 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)} 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)}; RoomHistory.prototype.push=function(e,t){var exists=false,ts;for(var i=0,nbMsg=this.messages.length;ithis.keepMessages)this.messages.shift();if(this.maxAge)for(var i=0;i=this.messages[i].ts;i++)if(this.messages[i].ts===ts)return this.messages[i];return null}; RoomHistory.prototype.getMessageById=function(id){for(var i=0,nbMessages=this.messages.length;i=0;i--)if(this.messages[i].version>knownVersion)result.push(this.messages[i].toStatic());return result}; 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} 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}}; 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"]!== 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}; 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){}; 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){}; 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;iPOLL_TIMEOUT)callback({"v":knownVersion});else setTimeout(function(){_this.startPolling(knownVersion,reqT,callback)},2E3)}; 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, 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;itoday.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", "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"}}; 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é "+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()); 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", "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")}; 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= this.trigger===">"||this.trigger===">";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= 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 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= 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")return true;var prevIsAlphadec=isAlphadec(text[i- 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")return text[i]}if("`"=== 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=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"|| 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? 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 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- 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= 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":"      "}); 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,"
")}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"); 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"<"+ tagName+params+(classList.length?' class="'+classList.join(" ")+'"':"")+">"+innerHTML+""};MsgBranch.prototype.outerHTML=function(){var html="";if(this.isQuote)html+='';if(this.isEol)html+="
";this.subNodes.forEach(function(node){html+=node.outerHTML()});if(this.isQuote)html+="
";return html};function getFirstUnterminated(_root){_root=_root||root;for(var i=0,nbBranches=_root.subNodes.length;i0){if(input[start]=== "#"){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>= 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>= 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= 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&¤tCmd.name.substr(0,endCmd)===inputCmd||inputFinished&¤tCmd.name===inputCmd)commands.push(currentCmd)}commands.sort(function(a, 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;ii.lastRead)hasUnread++});if(hasUnread)title="("+hasUnread+")";setFavicon(0,hasUnread)}if(!title.length&&SELECTED_ROOM)title=SELECTED_ROOM.name;document.title=title.length?title:"Mimouchat"} function spawnNotification(){if(!("Notification"in window));else if(Notification.permission==="granted"){var now=Date.now();if(lastNotificationSpawn+NOTIFICATION_COOLDOWNSELECTED_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); 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; updateAuthorAvatarImsOffset();if(window.hasFocus)markRoomAsRead(SELECTED_ROOM)} 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= 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, msg)}} 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= 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]); 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}} 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()} 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"})} 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=""+emojiDom.outerHTML+"";else emojiButton.style.backgroundImage='url("smile.svg")'}else emojiButton.classList.add(R.klass.hidden)} 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", 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, 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); 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, 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); 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()}); 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()}); 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= 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-"+ 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.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", 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", 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, "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, 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= 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= 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- 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; 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} 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()); 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}}(); 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> ims.lastRead){dom.classList.add(R.klass.unread);dom.classList.add(R.klass.unreadHi)}return dom} 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} function makeEmojiDom(emojiCode){var emoji=tryGetCustomEmoji(emojiCode);if(typeof emoji==="string"&&"makeEmoji"in window)emoji=window["makeEmoji"](emoji);return typeof emoji==="string"?null:emoji} 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;ibounds.bottom||e.screenXbounds.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); 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", 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(); 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")}; 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")}; 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")}; 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}; function SlackWrapper(){this.lastServerVersion=0;this.context=new MultiChatManager;this.history={}} 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= [],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]= 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(); 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= data["static"][SELECTED_CONTEXT.team.id]["channels"];i=0;for(var nbChan=arr.length;iroom.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)} 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* 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, 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