| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197 |
- 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){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.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;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<
- 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}this.staticV=Math.max(this.staticV,
- t);if(data["self"]){this.self=this.users[idPrefix+data["self"]["id"]]||null;if(this.self&&data["self"]["prefs"]){if(!this.self.prefs)this.self.prefs=new SelfPreferences;this.self.prefs.update(data["self"]["prefs"],t)}else this.staticV=0}};
- 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};
- ChatContext.prototype.toStatic=function(t){var channels=[],users=[];var res={"team":this.team.toStatic(t),"self":{"id":this.self.id,"prefs":this.self.prefs.toStatic(t)},"emojis":this.emojis.version>t?this.emojis.data:undefined};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.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};
- (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=-1;this.users={};this.topic;this.topicTs;this.topicCreator;this.purpose;this.purposeTs;this.purposeCreator;this.version=0;this.isPrivate}Room.prototype.setLastMsg=function(lastMsg,t){if(this.lastMsg<lastMsg){this.lastMsg=lastMsg;this.version=t;return true}return false};
- 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};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["latest"])this.lastMsg=parseFloat(chanData["latest"]["ts"]);if(chanData["is_starred"]!==undefined)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]=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)};
- function PrivateMessageRoom(id,user){Room.call(this,id);this.user=user;this.name=this.user.name;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}};
- (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=false;this.pinned=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.pinned=false;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.is_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,evts,now){this.id=typeof room==="string"?room:room.id;this.messages=[];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;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}while(this.messages.length>this.keepMessages)this.messages.shift();return ts||0};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};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};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.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};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.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,"profile":{"email":this.email,"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["real_name"]!==undefined)this.realName=userData["real_name"];else if(userData["profile"]&&userData["profile"]["real_name"]!==undefined)this.realName=userData["profile"]["real_name"];if(userData["presence"]!==undefined)this.presence=userData["presence"]!==
- "away";if(userData["isPresent"]!==undefined)this.presence=userData["isPresent"];if(userData["isBot"])this.isBot=userData["isBot"];if(userData["profile"]){this.email=userData["profile"]["email"];this.firstName=userData["profile"]["first_name"];this.lastName=userData["profile"]["last_name"]}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};
- (function(){if(typeof module!=="undefined")module.exports.Chatter=Chatter})();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.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){};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;i<nbContexts;i++)if(id===this.contexts[i].getId())return this.contexts[i];return null};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};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};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};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};
- MultiChatManager.prototype.poll=function(knownVersion,callback){this.contexts.forEach(function(ctx){ctx.onRequest()});setTimeout(function(){var liveFeed,staticFeed,allTyping,v=0,updated=false,now=Date.now();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=Math.max(v,res["v"]||0);updated=true}}});if(updated)callback({"live":liveFeed,"static":staticFeed,"typing":allTyping,"v":Math.max(v,knownVersion)});else callback({"v":knownVersion})}.bind(this),2E3)};(function(){if(typeof module!=="undefined")module.exports.MultiChatManager=MultiChatManager})();var lang={},locale;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 i in locale.dom)document.getElementById(i).textContent=locale.dom[i]};lang["fr"]={unknownMember:"Utilisateur inconnu",unknownChannel:"Channel inconnu",newMessage:"Nouveau message",netErrorShort:"Reseau",onlyVisible:"(visible seulement par vous)",starred:"Favoris",channels:"Discutions",privateMessageRoom:"Discutions priv\u00e9es",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,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()},dom:{"fileUploadCancel":"Annuler","neterror":"Impossible de se connecter au chat !"}};lang["fr"].edited=function(ts){return"(edité "+lang["fr"].formatDate(ts)+")"};lang["en"]={unknownMember:"Unknown member",unknownChannel:"Unknown channel",newMessage:"New message",netErrorShort:"Network",onlyVisible:"(only visible to you)",starred:"Starred",channels:"Channels",privateMessageRoom:"Direct messages",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()},dom:{"fileUploadCancel":"Cancel","neterror":"Cannot connect to chat !"}};lang["en"].edited=function(ts){return"(edited "+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<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-
- 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||
- _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||
- 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)===">")return">";if(text[i]===">")return text[i]}if("`"===
- text[i]&&!prevIsAlphadec)return text[i];if("\n"===text[i])return text[i];if(["*","~","-","_"].indexOf(text[i])!==-1&&(nextIsAlphadec||["*","~","-","_","<","&"].indexOf(text[i+1])!==-1)&&(prevIsAlphadec||["*","~","-","_","<","&"].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=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"||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,"<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");innerHTML=this.innerHTML()}else{var link;
- if(this._parent.isLink&&(link=opts.linkFilter(this.text))){tagName="a";params=' href="'+link.link+'"';if(link.isExternal)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+"</"+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
- 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);
- 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}
- 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}();
- window["_formatText"]=function(str,opts){return formatText(str,{highlights:opts?opts["highlights"]:undefined})};if(typeof module!=="undefined")module.exports.formatText=formatText;function ConfirmDialog(title,content){this.title=title;this.content=content;this.dom=this.createDom();this.domOverlay=this.createDomOverlay();this.confirmHandlers=[];this.dissmissHandler=[]}
- 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;
- 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)});
- 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};
- 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};
- 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};
- 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:"slackCtx",chatList:"chatList",currentRoom:{title:"currentRoomTitle",content:"chatWindow"},typing:"whoistyping",message:{form:"msgForm",slashComplete:"slashList",input:"msgInput",replyTo:"replyToContainer",file:{bt:"attachFile",formContainer:"fileUploadContainer",fileInput:"fileUploadInput",form:"fileUploadForm",error:"fileUploadError",cancel:"fileUploadCancel"},emoji:"emojiButton"},favicon:"linkFavicon"},klass:{selected:"selected",hidden:"hidden",button:"button",
- buttonContainer:"button-container",noRoomSelected:"no-room-selected",noNetwork:"no-network",unread:"unread",unreadHi:"unreadHi",replyingTo:"replyingTo",presenceAway:"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:"slack-command-item",header:"slack-command-header",name:"slack-command-name",usage:"slack-command-usage",desc:"slack-command-desc"},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:"slack-context-room",typeChannel:"slack-channel",typePrivate:"slack-group",typeDirect:"slack-ims",typing:"slack-context-typing"},msg:{item:"slackmsg-item",notice:"slackmsg-notice",firstUnread:"slackmsg-first-unread",content:"slackmsg-content",
- meMessage:"slackmsg-me_message",ts:"slackmsg-ts",author:"slackmsg-author",authorname:"slackmsg-author-name",authorAvatar:"slackmsg-author-img",authorMessages:"slackmsg-author-messages",msg:"slackmsg-msg",editedStatus:"edited",edited:"slackmsg-edited",authorGroup:"slackmsg-authorGroup",sameTs:"slackmsg-same-ts",hover:{container:"slackmsg-hover",reply:"slackmsg-hover-reply",reaction:"slackmsg-hover-reaction",edit:"slackmsg-hover-edit",remove:"slackmsg-hover-remove"},replyTo:{close:"replyto-close"},
- link:"slackmsg-link",linkuser:"slackmsg-link-user",linkchan:"slackmsg-link-chan",attachment:{container:"slackmsg-attachment",list:"slackmsg-attachments",hasThumb:"has-thumb",pretext:"slackmsg-attachment-pretext",block:"slackmsg-attachment-block",title:"slackmsg-attachment-title",content:"slackmsg-attachment-content",text:"slackmsg-attachment-text",thumbImg:"slackmsg-attachment-thumb",img:"slackmsg-attachment-img",actions:"slackmsg-attachment-actions",actionItem:"slackmsg-attachment-actions-item",
- field:{container:"slackmsg-attachment-fields",item:"field",title:"field-title",text:"field-text",longField:"field-long"},footer:"slackmsg-attachment-footer",footerText:"slackmsg-attachment-footer-text",footerIcon:"slackmsg-attachment-footer-icon"},reactions:{container:"slackmsg-reactions",item:"slackmsg-reaction-item"},style:{bold:"slackmsg-style-bold",code:"slackmsg-style-code",longCode:"slackmsg-style-longcode",italic:"slackmsg-style-italic",strike:"slackmsg-style-strike",quote:"slackmsg-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"}}};var NOTIFICATION_COOLDOWN=30*1E3,NOTIFICATION_DELAY=5*1E3,MSG_GROUPS=[],lastNotificationSpawn=0;
- function onContextUpdated(){var chanListFram=document.createDocumentFragment(),sortedChans=DATA.context.getChannelIds(function(chan){return!chan.archived&&chan.isMember!==false}),starred=[],channels=[],privs=[],priv=[];sortedChans.sort(function(a,b){if(a[0]!==b[0])return a[0]-b[0];return DATA.context.getChannel(a).name.localeCompare(DATA.context.getChannel(b).name)});sortedChans.forEach(function(chanId){var chan=DATA.context.getChannel(chanId);if(chan instanceof PrivateMessageRoom){if(!chan.user.deleted){var chanListItem=
- createImsListItem(chan);if(chanListItem)if(chan.starred)starred.push(chanListItem);else priv.push(chanListItem)}}else{var chanListItem=createChanListItem(chan);if(chanListItem)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)});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);setRoomFromHashBang();updateTitle();if(SELECTED_CONTEXT)createContextBackground(SELECTED_CONTEXT.getChatContext().team.id,
- SELECTED_CONTEXT.getChatContext().users,function(imgData){document.getElementById(R.id.context).style.backgroundImage="url("+imgData+")"})}
- 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 dom=document.getElementById("room_"+chanId);if(typing[chanId])dom.classList.add(R.klass.chatList.typing);else dom.classList.remove(R.klass.chatList.typing)}for(var userId in ctx.users){var ims=ctx.users[userId].privateRoom;if(ims&&!ims.archived){var dom=document.getElementById("room_"+ims.id);if(dom)if(typing[ims.id])dom.classList.add(R.klass.chatList.typing);
- else dom.classList.remove(R.klass.chatList.typing)}}});updateTypingChat()}
- 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)}}
- function onNetworkStateUpdated(isNetworkWorking){isNetworkWorking?document.body.classList.remove(R.klass.noNetwork):document.body.classList.add(R.klass.noNetwork);updateTitle()}
- function onRoomSelected(){var name=SELECTED_ROOM.name||(SELECTED_ROOM.user?SELECTED_ROOM.user.name:undefined);if(!name){var members=[];SELECTED_ROOM.users.forEach(function(i){members.push(i.name)});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);markRoomAsRead(SELECTED_ROOM);if(REPLYING_TO){REPLYING_TO=
- null;onReplyingToUpdated()}if(EDITING){EDITING=null;onReplyingToUpdated()}updateTypingChat()}
- 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);
- document.getElementById(R.id.message.replyTo).textContent="";focusInput()}}
- 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;
- 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)};
- 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}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 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"}
- function updateTitle(){var hasHl=HIGHLIGHTED_CHANS.length,title="";if(NEXT_RETRY){title="!"+locale.netErrorShort+" - ";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(DATA.context.team)title+=DATA.context.team.name;document.title=title}
- 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()}
- function onRoomUpdated(){var chatFrag=document.createDocumentFragment(),currentRoomId=SELECTED_ROOM.id,prevMsg=null,firstTsCombo=0,prevMsgDom=null,currentMsgGroupDom;MSG_GROUPS=[];if(DATA.history[currentRoomId])DATA.history[currentRoomId].messages.forEach(function(msg){if(!msg.removed){var dom=msg.getDom(),newGroupDom=false;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);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;if(window.hasFocus)markRoomAsRead(SELECTED_ROOM)}
- 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;if(target.parentElement&&target.classList.contains(R.klass.msg.attachment.actionItem)){var messageId=getMessageId(e,target),attachmentIndex=target.dataset["attachmentIndex"],
- actionIndex=target.dataset["actionIndex"];if(messageId&&attachmentIndex!==undefined&&actionIndex!==undefined){messageId=messageId.substr(messageId.lastIndexOf("_")+1);var 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)){var messageId=getMessageId(e,target);if(messageId){messageId=messageId.substr(messageId.lastIndexOf("_")+1);var msg=DATA.history[SELECTED_ROOM.id].getMessageById(messageId);if(msg&&target.classList.contains(R.klass.msg.hover.reply)){if(EDITING){EDITING=null;onEditingUpdated()}if(REPLYING_TO!==msg){REPLYING_TO=msg;onReplyingToUpdated()}}else if(msg&&target.classList.contains(R.klass.msg.hover.reaction))EMOJI_BAR.spawn(document.body,
- SELECTED_CONTEXT.getChatContext(),function(emoji){if(emoji)addReaction(SELECTED_ROOM.id,msg.id,emoji)});else if(msg&&target.classList.contains(R.klass.msg.hover.edit)){if(REPLYING_TO){REPLYING_TO=null;onReplyingToUpdated()}if(EDITING!==msg){EDITING=msg;onEditingUpdated()}}else if(msg&&target.classList.contains(R.klass.msg.hover.remove)){if(REPLYING_TO){REPLYING_TO=null;onReplyingToUpdated()}if(EDITING){EDITING=null;onEditingUpdated()}removeMsg(SELECTED_ROOM,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 focusInput(){document.getElementById(R.id.message.input).focus()}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.ims)selectRoom(user.ims)}}
- function updateAuthorAvatarImsOffset(){var chatDom=document.getElementById(R.id.currentRoom.content),chatTop=chatDom.getBoundingClientRect().top;MSG_GROUPS.forEach(function(group){var imgDom=group.authorImg,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"})}
- document.addEventListener("DOMContentLoaded",function(){initLang();initHljs();document.getElementById(R.id.currentRoom.content).addEventListener("click",chatClickDelegate);window.addEventListener("hashchange",function(e){if(document.location.hash&&document.location.hash[0]==="#")setRoomFromHashBang()});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.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.form).addEventListener("submit",
- function(e){e.preventDefault();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();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);var lastKeyDown=0;document.getElementById(R.id.message.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}var commands=[],input=this.value;if(this.value[0]===
- "/"){var endCmd=input.indexOf(" "),inputFinished=endCmd!==-1;endCmd=endCmd===-1?input.length:endCmd;var inputCmd=input.substr(0,endCmd);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)});var slashDom=document.getElementById(R.id.message.slashComplete),slashFrag=document.createDocumentFragment(),prevService;slashDom.textContent="";for(var i=0,nbCmd=commands.length;i<nbCmd;i++){var command=commands[i];if(prevService!==command.category){prevService=command.category;slashFrag.appendChild(createSlashAutocompleteHeader(command.category))}slashFrag.appendChild(createSlashAutocompleteDom(command))}slashDom.appendChild(slashFrag)}});window.hasFocus=true;(function(){var emojiButton=
- document.getElementById(R.id.message.emoji);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")';emojiDom=window["makeEmoji"]("paperclip");if(emojiDom)document.getElementById(R.id.message.file.bt).innerHTML="<span class='"+R.klass.emoji.small+"'>"+emojiDom.outerHTML+"</span>";else document.getElementById(R.id.message.file.bt).style.backgroundImage=
- 'url("public/paperclip.svg")';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()})})}else emojiButton.classList.add(R.klass.hidden)})();startPolling()});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){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=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){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;link.textContent=ims.user.name;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);if(HIGHLIGHTED_CHANS.indexOf(ims)>=
- 0)dom.classList.add(R.klass.unreadHi)}return dom}
- 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.name)}userNames.sort();userList.textContent=userNames.join(", ");emojiContainer.appendChild(emojiDom);emojiContainer.className=
- 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}
- function doCreateMessageDom(msg,skipAttachment){var channelId=msg.channelId;var dom=document.createElement("div"),msgBlock=document.createElement("div"),hover=document.createElement("ul"),hoverReply=document.createElement("li");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=
- R.klass.msg.ts;dom.textDom.className=R.klass.msg.msg;dom.authorName.className=R.klass.msg.authorname;hover.className=R.klass.msg.hover.container;hoverReply.className=R.klass.msg.hover.reply;hover.appendChild(hoverReply);if("makeEmoji"in window){var hoverReaction=document.createElement("li"),domReply=window["makeEmoji"]("arrow_heading_down"),domReaction=window["makeEmoji"]("smile"),domEdit=window["makeEmoji"]("pencil2"),domRemove=window["makeEmoji"]("x");hoverReaction.className=R.klass.msg.hover.reaction;
- if(domReaction){hoverReaction.classList.add(R.klass.emoji.small);hoverReaction.appendChild(domReaction)}else hoverReaction.style.backgroundImage='url("smile.svg")';if(domReply){hoverReply.classList.add(R.klass.emoji.small);hoverReply.appendChild(domReply)}else hoverReply.style.backgroundImage='url("repl.svg")';hover.appendChild(hoverReaction);if(DATA.context.isMe(msg.userId)){var hoverEdit=document.createElement("li");hoverEdit.className=R.klass.msg.hover.edit;if(domEdit)hoverEdit.classList.add(R.klass.emoji.small);
- else hoverEdit.style.backgroundImage='url("edit.svg")';hoverEdit.appendChild(domEdit);hover.appendChild(hoverEdit);var hoverRemove=document.createElement("li");hoverRemove.className=R.klass.msg.hover.remove;if(domRemove)hoverRemove.classList.add(R.klass.emoji.small);else hoverRemove.style.backgroundImage='url("remove.svg")';hoverRemove.appendChild(domRemove);hover.appendChild(hoverRemove)}}else{hoverReply.style.backgroundImage='url("repl.svg")';if(DATA.context.isMe(msg.userId)){var hoverEdit=document.createElement("li");
- hoverEdit.className=R.klass.msg.hover.edit;hoverEdit.style.backgroundImage='url("edit.svg")';hover.appendChild(hoverEdit);var hoverRemove=document.createElement("li");hoverRemove.className=R.klass.msg.hover.remove;hoverRemove.style.backgroundImage='url("remove.svg")';hover.appendChild(hoverRemove)}}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;dom.attachments.className=R.klass.msg.attachment.list;dom.reactions.className=R.klass.msg.reactions.container;dom.appendChild(msgBlock);dom.appendChild(hover);return dom}
- function createMessageGroupDom(user,userName){var dom=document.createElement("div"),authorBlock=document.createElement("div"),authorName=document.createElement("span");dom.authorImg=document.createElement("img");dom.authorImg.className=R.klass.msg.authorAvatar;authorName.className=R.klass.msg.authorname;if(user){authorName.textContent=user.name;dom.authorImg.src=user.getSmallIcon()}else{authorName.textContent=userName||"?";dom.authorImg.src=""}authorBlock.appendChild(dom.authorImg);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}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"}
- 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"),
- 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=
- 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"];
- 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=
- msg.formatText(attachment["text"]||"");textDom.className=R.klass.msg.attachment.text;if(textContent&&textContent!="")textDom.innerHTML=textContent;else textDom.classList.add(R.klass.hidden);imgDom.className=R.klass.msg.attachment.img;if(attachment["image_url"])imgDom.src=attachment["image_url"];else imgDom.classList.add(R.klass.hidden);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=document.createElement("span");footerTs.className=R.klass.msg.ts;footerTs.innerHTML=locale.formatDate(attachment["ts"]);footerBlock.appendChild(footerTs)}textBlock.appendChild(thumbImgDom);
- textBlock.appendChild(textDom);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;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=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}
- 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);
- 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}
- function makeUserIsTypingDom(user){var dom=document.createElement("li"),userName=document.createElement("span");userName.textContent=user.name;dom.appendChild(createTypingDisplay());dom.appendChild(userName);return dom}function createSlashAutocompleteHeader(servicename){var lh=document.createElement("lh");lh.textContent=servicename;lh.className=R.klass.commands.header;return lh}
- function createSlashAutocompleteDom(cmd){var li=document.createElement("li"),name=document.createElement("span"),usage=document.createElement("span"),desc=document.createElement("span");name.textContent=cmd.name;usage.textContent=cmd.usage;desc.textContent=cmd.desc;li.appendChild(name);li.appendChild(usage);li.appendChild(desc);li.className=R.klass.commands.item;name.className=R.klass.commands.name;usage.className=R.klass.commands.usage;desc.className=R.klass.commands.desc;return li};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
- 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");
- 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,
- favoriteEmojis){var names=[],index=0;for(var i in emojiObj){var obj={name:i,pos:index,count:0};if(emojiObj[i].names)emojiObj[i].names.forEach(function(name){obj.count+=favoriteEmojis[name]||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},search=function(queryString){var emojiCount=0,toRemove=[],sortedEmojiNames;queryString=queryString===undefined?searchBar.value:queryString;if(isSupported()){var foundEmojis=window["searchEmojis"](queryString);
- sortedEmojiNames=sortEmojis(foundEmojis,context.self.prefs.favoriteEmojis);for(var i in emojiCache.unicode)if(emojiCache.unicode[i].visible){emojiCache.unicode[i].visible=false;unicodeEmojis.removeChild(emojiCache.unicode[i].dom)}for(var 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++}}for(var i in emojiCache.custom)if(emojiCache.custom[i].visible){emojiCache.custom[i].visible=
- false;customEmojis.removeChild(emojiCache.custom[i].dom)}sortedEmojiNames=sortEmojis(context.emojis.data,context.self.prefs.favoriteEmojis);for(var i=0,nbEmojis=sortedEmojiNames.length;i<nbEmojis;i++){var emojiName=sortedEmojiNames[i].name;if((queryString===""||emojiName.substr(0,queryString.length)===queryString)&&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},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=function(emojiName){if(doClose()&&emojiSelectedHandler)emojiSelectedHandler(emojiName)};overlay.addEventListener("click",function(e){var bounds=dom.getBoundingClientRect();if(e.screenY<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;
- emojiDetail.className=R.klass.emojibar.detail.container;emojiDetailImg.className=R.klass.emojibar.detail.img;emojiDetailName.className=R.klass.emojibar.detail.name;unicodeEmojis.className=customEmojis.className=R.klass.emojibar.list;searchBar.className=R.klass.emojibar.search;emojiDetail.appendChild(emojiDetailImg);emojiDetail.appendChild(emojiDetailName);emojisDom.appendChild(makeHeader(window["emojiProviderHeader"]));emojisDom.appendChild(unicodeEmojis);emojisDom.appendChild(makeHeader("emojicustom.png"));
- emojisDom.appendChild(customEmojis);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}}();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.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();if(data["v"])this.lastServerVersion=data["v"];if(data["static"])for(var i in data["static"]){var ctx=this.context.getById(i);if(!ctx){ctx=new SimpleChatSystem;this.context.push(ctx)}ctx.getChatContext().updateStatic(data["static"][i],now)}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(var 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 ctx=this.context.getChannelContext(roomId).getChatContext(),chan=ctx.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(ctx,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()};setInterval(function(){var updated=false,now=Date.now();DATA.context.foreachContext(function(ctx){if(ctx.getChatContext().cleanTyping(now))updated=true});if(updated)onTypingUpdated()},1E3);
- 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}
- 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;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();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()}}}
- function markRoomAsRead(room){var highlightIndex=HIGHLIGHTED_CHANS.indexOf(room);if(room.lastMsg>room.lastRead){sendReadMArker(room,room.lastMsg);room.lastRead=room.lastMsg}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)}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={};var 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)};var 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};var drawBackground=
- 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)};var filterImage=function(img){var pixelSum=0;for(var 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(var i=0;i<img.width*img.height*4;i+=4)img.data[i]=
- img.data[i+1]=img.data[i+2]=255-img.data[i];return img};var loadImgFromUrl=function(src,cb){var xhr=new XMLHttpRequest;xhr.responseType="blob";xhr.onreadystatechange=function(){if(xhr.readyState===4)if(xhr.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(xhr.response)}else cb(null)};xhr.open("GET",src,true);xhr.send(null)};var 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)};var renderAvatars=function(background,
- imgs){imgs.sort(function(a,b){return Math.random()-.5});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(function(a,b){if(!a.img)return 1;if(!b.img)return-1;return Math.random()-.5});imgIndex=0}}};var 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]=[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;function initHljs(){var xhr=new XMLHttpRequest;xhr.timeout=1E3*60*1;xhr.onreadystatechange=function(e){if(xhr.readyState===4){var script=document.createElement("script");script.innerHTML=xhr.response;script.language="text/javascript";document.head.innerHTML+='<link href="hljs-androidstudio.css" rel="stylesheet"/>';document.body.appendChild(script)}};xhr.open("GET","highlight.pack.js",true);xhr.send(null)}
- function fetchHistory(room,cb){var xhr=new XMLHttpRequest;xhr.open("GET","api/hist?room="+room.id,true);xhr.send(null)}
- function poll(callback){var xhr=new XMLHttpRequest;xhr.timeout=1E3*60*1;xhr.onreadystatechange=function(e){if(xhr.readyState===4){if(xhr.status===0){if(NEXT_RETRY){NEXT_RETRY=0;onNetworkStateUpdated(true)}poll(callback);return}var resp=null,success=Math.floor(xhr.status/100)===2;if(success){if(NEXT_RETRY){NEXT_RETRY=0;onNetworkStateUpdated(true)}resp=xhr.response;try{resp=JSON.parse(resp)}catch(e){resp=null}}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)}};xhr.open("GET","api?v="+DATA.lastServerVersion,true);xhr.send(null)}function outOfSync(){DATA.lastServerVersion=0}function sendTyping(room){var xhr=new XMLHttpRequest,url="api/typing?room="+room.id;xhr.open("POST",url,true);xhr.send(null)}function onPollResponse(success,response){if(success){if(response)DATA.update(response);startPolling()}else setTimeout(startPolling,NEXT_RETRY*1E3)}function startPolling(){poll(onPollResponse)}
- 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();createContextBackground(SELECTED_CONTEXT.getChatContext().team.id,SELECTED_CONTEXT.getChatContext().users,function(imgData){document.getElementById(R.id.context).style.backgroundImage="url("+imgData+")"});if(SELECTED_ROOM.lastMsg!==
- 0&&!DATA.history[SELECTED_ROOM.id])fetchHistory(SELECTED_ROOM,function(success){})}function unselectRoom(){document.getElementById("room_"+SELECTED_ROOM.id).classList.remove(R.klass.selected)}
- function uploadFile(chan,filename,file,callback){var fileReader=new FileReader,formData=new FormData,xhr=new XMLHttpRequest;formData.append("file",file);formData.append("filename",filename);xhr.onreadystatechange=function(){if(xhr.readyState===4)if(xhr.status===204)callback(null);else callback(xhr.statusText)};xhr.open("POST","api/file?room="+chan.id);xhr.send(formData)}
- function sendCommand(payload,serviceId,callback){var xhr=new XMLHttpRequest;if(callback)xhr.onreadystatechange=function(){if(xhr.readyState===4)if(xhr.status===204)callback(null);else callback(xhr.statusText)};xhr.open("POST","api/attachmentAction?serviceId="+serviceId);xhr.send(JSON.stringify(payload))}
- 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){var xhr=new XMLHttpRequest,url="api/cmd?room="+chan.id+"&cmd="+encodeURIComponent(cmd.name.substr(1))+"&args="+encodeURIComponent(args);xhr.open("POST",url,true);xhr.send(null)}
- function sendMsg(chan,msg,replyTo){var xhr=new XMLHttpRequest;var url="api/msg?room="+chan.id+"&text="+encodeURIComponent(msg);if(replyTo){var sender=DATA.context.getUser(replyTo.userId),footer="Message";if(chan.isPrivate)footer="Private message";else footer=chan.name;var attachment={"fallback":replyTo.text,"author_name":"<@"+sender.id+"|"+sender.name+">","text":replyTo.text,"footer":footer,"ts":replyTo.ts};url+="&attachments="+encodeURIComponent(JSON.stringify([attachment]))}xhr.open("POST",url,
- true);xhr.send(null)}
- 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,cmdObject=ctx?ctx.getChatContext().commands.data[cmd]:null;if(cmdObject){doCommand(SELECTED_ROOM,cmdObject,args.trim());return true}return false}sendMsg(SELECTED_ROOM,input,REPLYING_TO);return true}
- function editMsg(chan,text,msg){var xhr=new XMLHttpRequest;var url="api/msg?room="+chan.id+"&ts="+msg.id+"&text="+encodeURIComponent(text);xhr.open("PUT",url,true);xhr.send(null)}function removeMsg(chan,msg){var xhr=new XMLHttpRequest;var url="api/msg?room="+chan.id+"&ts="+msg.id;xhr.open("DELETE",url,true);xhr.send(null)}function sendReadMArker(chan,ts){var xhr=new XMLHttpRequest;var url="api/markread?room="+chan.id+"&ts="+ts;xhr.open("POST",url,true);xhr.send(null)}
- function addReaction(channelId,msgId,reaction){var xhr=new XMLHttpRequest;var url="api/reaction?room="+channelId+"&msg="+msgId+"&reaction="+encodeURIComponent(reaction);xhr.open("POST",url,true);xhr.send(null)}function removeReaction(channelId,msgId,reaction){var xhr=new XMLHttpRequest;var url="api/reaction?room="+channelId+"&msg="+msgId+"&reaction="+encodeURIComponent(reaction);xhr.open("DELETE",url,true);xhr.send(null)};function UiRoomHistory(room,keepMessages,evts,now){RoomHistory.call(this,room,keepMessages,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)};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(){};
- 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=
- str.substr(0,sep);text=str.substr(sep+1)}if(link[0]==="@"){var newLink=msgContext.context.getId()+"|"+link.substr(1),user=DATA.context.getUser(newLink);if(user){isInternal=true;link=newLink;text="@"+user.name}else return null}else if(link[0]==="#"){var newLink=msgContext.context.getId()+"|"+link.substr(1),chan=DATA.context.getChannel(newLink);if(chan){isInternal=true;link=newLink;text="#"+chan.name}else return null}else 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},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)},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.name:_this.username||"?"};return{invalidate:function(_this){_this.uiNeedRefresh=true;return _this},removeDom:function(_this){if(_this.dom&&_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);if(_this.edited){_this.dom.edited.innerHTML=locale.edited(_this.edited);_this.dom.classList.add(R.klass.msg.editedStatus)}return _this},duplicateDom:function(_this){return _this.dom.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);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)};UiMeMessage.prototype.createDom=function(){this.dom=doCreateMessageDom(this,false);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()};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)};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,false);return this};
- UiMessage.prototype.duplicateDom=function(){return AbstractUiMessage.duplicateDom(this)};UiMessage.prototype.updateDom=function(){AbstractUiMessage.updateDom(this);return this};UiMessage.prototype.update=function(ev,ts){Message.prototype.update.call(this,ev,ts);this.invalidate()};
- 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)};
- 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)};
- UiNoticeMessage.prototype.createDom=function(){this.dom=doCreateMessageDom(this,false);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};
- 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};
|