tweb/public/15.1a3e11966cccf1381885.chu...

2 lines
615 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

(this.webpackJsonp=this.webpackJsonp||[]).push([[15],{104:function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var i=s(49);class n{constructor(e,t){this.inputField=e,this.size=t,this.max=45,this.needFrame=0,this.container=document.createElement("div"),this.container.classList.add("media-sticker-wrapper");const s=e.input;s.addEventListener("blur",()=>{this.playAnimation(0)}),s.addEventListener("input",t=>{this.playAnimation(e.value.length)})}playAnimation(e){if(!this.animation)return;let t;(e=Math.min(e,30))?(t=Math.round(Math.min(this.max,e)*(165/this.max)+11.33),this.idleAnimation&&(this.idleAnimation.stop(!0),this.idleAnimation.canvas.style.display="none"),this.animation.canvas.style.display=""):t=0;const s=this.needFrame>t?-1:1;this.animation.setDirection(s),0!==this.needFrame&&0===t&&this.animation.setSpeed(7),this.needFrame=t,this.animation.play()}load(){return this.loadPromise?this.loadPromise:this.loadPromise=Promise.all([i.b.loadAnimationFromURL({container:this.container,loop:!0,autoplay:!0,width:this.size,height:this.size},"assets/img/TwoFactorSetupMonkeyIdle.tgs").then(e=>(this.idleAnimation=e,this.inputField.value.length||e.play(),i.b.waitForFirstFrame(e))),i.b.loadAnimationFromURL({container:this.container,loop:!1,autoplay:!1,width:this.size,height:this.size},"assets/img/TwoFactorSetupMonkeyTracking.tgs").then(e=>(this.animation=e,this.inputField.value.length||(this.animation.canvas.style.display="none"),this.animation.addEventListener("enterFrame",e=>{(1===this.animation.direction&&e>=this.needFrame||-1===this.animation.direction&&e<=this.needFrame)&&(this.animation.setSpeed(1),this.animation.pause()),0===e&&0===this.needFrame&&this.idleAnimation&&(this.idleAnimation.canvas.style.display="",this.idleAnimation.play(),this.animation.canvas.style.display="none")}),i.b.waitForFirstFrame(e)))])}remove(){this.animation&&this.animation.remove(),this.idleAnimation&&this.idleAnimation.remove()}}},105:function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var i=s(38);class n extends i.b{constructor(e){super(Object.assign({plainText:!0},e));const t=this.input;t.type="tel",t.setAttribute("required",""),t.autocomplete="off";let s=0;this.input.addEventListener("input",t=>{this.input.classList.remove("error"),this.setLabel();const i=this.value.replace(/\D/g,"").slice(0,e.length);this.setValueSilently(i);const n=this.value.length;if(n===e.length)e.onFill(this.value);else if(n===s)return;s=n})}}},138:function(e,t,s){"use strict";s.r(t),s.d(t,"AppDialogsManager",(function(){return Fo}));var i=s(39),n=s(67),a=s(15),o=s(41),r=s(46),l=s(28),c=s(4),d=s(110),h=s(0);var u=!!document.createElement("video").canPlayType("video/quicktime")||h.IS_SAFARI||h.IS_APPLE_MOBILE,p=s(113);const m=new Set(["image/jpeg","image/png","image/gif","image/bmp","video/mp4","video/webm"]);u&&m.add("video/quicktime"),p.a&&m.add("image/webp");var g=m;function b(e,t){e.setAttribute("dir","auto"),e.innerHTML=t}var v=s(37),f=s(97),y=s(56);function w(e){Object(y.d)(e.history,(t,s,i)=>{t.action.photo||(i.splice(s,1),void 0!==e.count&&--e.count)})}var L=s(32);class S{constructor(e){this.previous=[],this.next=[],this.reverse=!1,this.loadCount=50,this.loadWhenLeft=20,this.loadedAllUp=!1,this.loadedAllDown=!1,Object(L.g)(this,e)}setTargets(e,t,s){this.previous=e,this.next=t,this.reverse=s}get index(){return void 0!==this.count?this.previous.length:-1}reset(e=!1){this.current=void 0,this.previous=[],this.next=[],this.loadedAllUp=this.loadedAllDown=e,this.loadPromiseUp=this.loadPromiseDown=null}go(e,t=!0){let s,i;if(e>0){if(s=this.next.splice(0,e),i=s.pop(),!i)return;this.previous.push(this.current,...s)}else{if(s=this.previous.splice(this.previous.length+e,-e),i=s.shift(),!i)return;this.next.unshift(...s,this.current)}return this.next.length<this.loadWhenLeft&&this.load(!this.reverse),this.previous.length<this.loadWhenLeft&&this.load(this.reverse),this.current=i,t&&this.onJump&&this.onJump(i,e>0),this.current}load(e){if(e&&this.loadedAllDown)return Promise.resolve();if(!e&&this.loadedAllUp)return Promise.resolve();if(e&&this.loadPromiseDown)return this.loadPromiseDown;if(!e&&this.loadPromiseUp)return this.loadPromiseUp;let t;t=e?this.reverse?this.previous[0]:this.next[this.next.length-1]:this.reverse?this.next[this.next.length-1]:this.previous[0];const s=this.loadMore(t,e,this.loadCount).then(t=>{if(e&&this.loadPromiseDown!==s||!e&&this.loadPromiseUp!==s)return;t.items.length<this.loadCount&&(e?this.loadedAllDown=!0:this.loadedAllUp=!0),void 0===this.count&&(this.count=t.count||t.items.length);(e?t.items.forEach.bind(t.items):y.d.bind(null,t.items))(t=>{const s=this.processItem?this.processItem(t):t;s&&(e?this.reverse?this.previous.unshift(s):this.next.push(s):this.reverse?this.next.push(s):this.previous.unshift(s))}),this.onLoadedMore&&this.onLoadedMore()},()=>{}).then(()=>{e?this.loadPromiseDown=null:this.loadPromiseUp=null});return e?this.loadPromiseDown=s:this.loadPromiseUp=s,s}}class E extends S{constructor(e={}){super(Object.assign(Object.assign({},e),{loadMore:(e,t,s)=>{var n;const a=t?0:s;let o=null===(n=this.current)||void 0===n?void 0:n.mid;return e&&(o=e.mid),t||(o=f.a.incrementMessageId(o,1)),i.a.getSearch(Object.assign(Object.assign({},this.searchContext),{peerId:this.searchContext.peerId||(null==e?void 0:e.peerId),maxId:o,limit:a?0:s,backLimit:a})).then(e=>("inputMessagesFilterChatPhotos"===this.searchContext.inputFilter._&&w(e),e.next_rate&&(this.searchContext.nextRate=e.next_rate),{count:e.count,items:e.history}))},processItem:t=>{if(this.filterMids([t.mid]).length)return e.processItem(t)}})),this.onHistoryDelete=({peerId:e,msgs:t})=>{const s=s=>s.peerId===e&&t.has(s.mid),i=(e,t,i)=>{s(e)&&i.splice(t,1)};Object(y.d)(this.previous,i),Object(y.d)(this.next,i),this.current&&s(this.current)&&this.onEmptied&&this.onEmptied()},this.onHistoryMultiappend=e=>{if(void 0!==this.searchContext.folderId)return;if(!this.loadedAllUp||this.loadPromiseUp)return;const t=e[this.searchContext.peerId];if(!t)return;const s=Array.from(t).sort((e,t)=>e-t),i=this.filterMids(s).map(e=>this.processItem(e)).filter(Boolean);i.length&&this.next.push(...i)},this.onMessageSent=({message:e})=>{this.onHistoryMultiappend({[e.peerId]:new Set([e.mid])})},a.default.addEventListener("history_delete",this.onHistoryDelete),a.default.addEventListener("history_multiappend",this.onHistoryMultiappend),a.default.addEventListener("message_sent",this.onMessageSent)}filterMids(e){const t=this.searchContext.isScheduled?i.a.getScheduledMessagesStorage(this.searchContext.peerId):i.a.getMessagesStorage(this.searchContext.peerId);return i.a.filterMessagesByInputFilter(this.searchContext.inputFilter._,e,t,e.length)}setSearchContext(e){this.searchContext=e,void 0!==this.searchContext.folderId&&(this.loadedAllUp=!0,void 0===this.searchContext.nextRate&&(this.loadedAllDown=!0)),"inputMessagesFilterChatPhotos"===this.searchContext.inputFilter._&&(this.loadedAllUp=!0),this.searchContext.useSearch||(this.loadedAllDown=this.loadedAllUp=!0)}reset(){super.reset(),this.searchContext=void 0}cleanup(){this.reset(),a.default.removeEventListener("history_delete",this.onHistoryDelete),a.default.removeEventListener("history_multiappend",this.onHistoryMultiappend),a.default.removeEventListener("message_sent",this.onMessageSent),this.onEmptied=void 0}}var M=s(61),I=s(68),C=s(63),k=s(16),T=s(36),P=s(45),x=s(34),A=s(14);class O{constructor(e,t,s=!0,i,n=!0,a=!0,o){this.name=e,this.type=t,this.clearable=s,this.autonomous=a,this.onFound=o,this.list=Do.createChatList(),this.container=document.createElement("div"),i&&(this.container.className=i),e&&(this.nameEl=document.createElement("div"),this.nameEl.classList.add("search-group__name"),"string"==typeof e&&this.nameEl.append(Object(A.i18n)(e)),this.container.append(this.nameEl)),this.container.classList.add("search-group","search-group-"+t),this.container.append(this.list),this.container.style.display="none",n&&Do.setListClickListener(this.list,o,void 0,a)}clear(){this.container.style.display="none",this.clearable&&(this.list.innerHTML="")}setActive(){this.container.style.display=""}toggle(){this.list.childElementCount?this.setActive():this.clear()}}class _{constructor(e,t,s,i){this.container=e,this.searchInput=t,this.searchGroups=s,this.onSearch=i,this.minMsgId=0,this.loadedCount=-1,this.foundCount=-1,this.searchPromise=null,this.searchTimeout=0,this.query="",this.listsContainer=null,this.peerId=0,this.threadId=0,this.scrollable=new P.b(this.container),this.listsContainer=this.scrollable.container;for(let e in this.searchGroups)this.listsContainer.append(this.searchGroups[e].container);this.searchGroups.messages&&this.scrollable.setVirtualContainer(this.searchGroups.messages.list),this.searchInput.onChange=e=>{this.query=e,this.reset(!1),this.searchMore()},this.scrollable.onScrolledBottom=()=>{this.query.trim()&&(this.searchTimeout||(this.searchTimeout=window.setTimeout(()=>{this.searchMore(),this.searchTimeout=0},0)))}}reset(e=!0){e&&(this.searchInput.value="",this.query="",this.peerId=0,this.threadId=0),this.minMsgId=0,this.loadedCount=-1,this.foundCount=-1;for(let e in this.searchGroups)this.searchGroups[e].clear();this.searchPromise=null}beginSearch(e=0,t=0,s=""){this.peerId=e,this.threadId=t,this.query!==s&&(this.searchInput.inputField.value=s),this.searchInput.input.focus()}searchMore(){if(this.searchPromise)return this.searchPromise;const e=this.query;if(!e.trim())return void(this.onSearch&&this.onSearch(0));if(-1!==this.foundCount&&this.loadedCount>=this.foundCount)return Promise.resolve();const t=this.minMsgId||0;return this.searchPromise=i.a.getSearch({peerId:this.peerId,query:e,inputFilter:{_:"inputMessagesFilterEmpty"},maxId:t,limit:20,threadId:this.threadId}).then(t=>{if(this.searchPromise=null,this.searchInput.value!==e)return;const{count:s,history:i}=t;i.length&&i[0].mid===this.minMsgId&&i.shift();const n=this.searchGroups.messages;i.forEach(t=>{const s=this.peerId?t.fromId:t.peerId,{dialog:i,dom:n}=Do.addDialogNew({dialog:s,container:this.scrollable,drawStatus:!1,avatarSize:54,meAsSaved:!1});t.peerId!==s&&(n.listEl.dataset.peerId=""+t.peerId),Do.setLastMessage(i,t,n,e)}),n.toggle(),this.minMsgId=i.length&&i[i.length-1].mid,-1===this.loadedCount&&(this.loadedCount=0),this.loadedCount+=i.length,-1===this.foundCount&&(this.foundCount=s,n.nameEl&&Object(x.a)(n.nameEl,Object(A.i18n)(s?"Chat.Search.MessagesFound":"Chat.Search.NoMessagesFound",[s])),this.onSearch&&this.onSearch(this.foundCount))}).catch(e=>{console.error("search error",e),this.searchPromise=null})}}var F=s(38);class j{constructor(e,t){this.prevValue="",this.timeout=0,this.onInput=()=>{if(!this.onChange)return;let e=this.value;e!==this.prevValue&&(this.prevValue=e,clearTimeout(this.timeout),this.timeout=window.setTimeout(()=>{this.onChange(e)},200))},this.onClearClick=()=>{this.value="",this.onChange&&this.onChange(""),this.onClear&&this.onClear()},this.inputField=new F.b({placeholder:e,plainText:!0}),this.container=this.inputField.container,this.container.classList.remove("input-field"),this.container.classList.add("input-search"),this.onChange=t,this.input=this.inputField.input,this.input.classList.add("input-search-input");const s=document.createElement("i");s.classList.add("tgico","tgico-search"),this.clearBtn=document.createElement("i"),this.clearBtn.classList.add("tgico","btn-icon","tgico-close"),this.input.addEventListener("input",this.onInput),this.clearBtn.addEventListener("click",this.onClearClick),this.container.append(s,this.clearBtn)}get value(){return this.inputField.value}set value(e){this.prevValue=e,clearTimeout(this.timeout),this.inputField.value=e}remove(){clearTimeout(this.timeout),this.input.removeEventListener("input",this.onInput),this.clearBtn.removeEventListener("click",this.onClearClick)}}var D=s(116),B=s(44),R=s(52),H=s(84),U=s(31);var N=(e,t={})=>Object(U.a)("btn-icon",Object.assign({icon:e||void 0},t)),z=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class V{constructor(e,t){this._constructor(e,t)}_constructor(e,t=!0){this.slider=e,this.destroyable=t,this.container=document.createElement("div"),this.container.classList.add("tabs-tab","sidebar-slider-item"),this.header=document.createElement("div"),this.header.classList.add("sidebar-header"),this.closeBtn=N("left sidebar-close-button",{noRipple:!0}),this.title=document.createElement("div"),this.title.classList.add("sidebar-header__title"),this.header.append(this.closeBtn,this.title),this.content=document.createElement("div"),this.content.classList.add("sidebar-content"),this.scrollable=new P.b(this.content,void 0,void 0,!0),this.container.append(this.header,this.content),this.slider.addTab(this),this.listenerSetter=new H.a}close(){return this.slider.closeTab(this)}open(...e){return z(this,void 0,void 0,(function*(){if(this.init)try{const e=this.init();this.init=null,e instanceof Promise&&(yield e)}catch(e){console.error("open tab error",e)}return this.slider.selectTab(this)}))}init(){}onCloseAfterTimeout(){this.destroyable&&(this.slider.tabs.delete(this),this.container.remove()),this.listenerSetter&&this.listenerSetter.removeAll()}setTitle(e){this.title.innerHTML="",this.title.append(Object(A.i18n)(e))}}class W extends V{constructor(e){super(e),this.eventListener=new R.a}onCloseAfterTimeout(){return this.eventListener.dispatchEvent("destroy"),this.eventListener.cleanup(),super.onCloseAfterTimeout()}}class K{constructor(e){this.historyTabIds=[],this.canHideFirst=!1,this.onCloseBtnClick=()=>{B.a.findItemByType(this.navigationType)?B.a.back(this.navigationType):this.historyTabIds.length&&this.closeTab(this.historyTabIds[this.historyTabIds.length-1])},this.closeTab=(e,t,s)=>{if(void 0!==e&&this.historyTabIds[this.historyTabIds.length-1]!==e)return!1;const i=this.historyTabIds.pop();this.onCloseTab(i,t,s);const n=this.historyTabIds[this.historyTabIds.length-1];return this._selectTab(void 0!==n?n instanceof V?n.container:n:this.canHideFirst?-1:0,t),!0},Object(L.g)(this,e),this.tabs||(this.tabs=new Map),this.tabsContainer=this.sidebarEl.querySelector(".sidebar-slider"),this._selectTab=Object(D.a)(this.tabsContainer,"navigation",250),this.canHideFirst||this._selectTab(0),Array.from(this.sidebarEl.querySelectorAll(".sidebar-close-button")).forEach(e=>{Object(l.b)(e,this.onCloseBtnClick)})}selectTab(e){if(this.historyTabIds[this.historyTabIds.length-1]===e)return!1;const t=e instanceof V?e:this.tabs.get(e);return t&&(t.onOpen&&t.onOpen(),t.onOpenAfterTimeout&&setTimeout(()=>{t.onOpenAfterTimeout()},250)),B.a.pushItem({type:this.navigationType,onPop:e=>(this.closeTab(void 0,e,!0),!0)}),this.historyTabIds.push(e),this._selectTab(e instanceof V?e.container:e),!0}removeTabFromHistory(e){this.historyTabIds.findAndSplice(t=>t===e),this.onCloseTab(e,void 0)}sliceTabsUntilTab(e,t){for(let s=this.historyTabIds.length-1;s>=0;--s){const i=this.historyTabIds[s];if(i!==t){if(i instanceof e)break;this.removeTabFromHistory(i)}}}getTab(e){return this.historyTabIds.find(t=>t instanceof e)}isTabExists(e){return!!this.getTab(e)}onCloseTab(e,t,s){s||B.a.removeByType(this.navigationType,!0);const i=e instanceof V?e:this.tabs.get(e);i&&(i.onClose&&i.onClose(),i.onCloseAfterTimeout&&setTimeout(()=>{i.onCloseAfterTimeout()},250))}addTab(e){e.container.parentElement||(this.tabsContainer.append(e.container),e.closeBtn&&e.closeBtn.addEventListener("click",this.onCloseBtnClick))}}var G=s(43),q=s(131);class Q{constructor(e){this.container=document.createElement("div"),this.container.classList.add("avatar-edit"),this.canvas=document.createElement("canvas"),this.canvas.classList.add("avatar-edit-canvas"),this.icon=document.createElement("span"),this.icon.classList.add("tgico","tgico-cameraadd"),this.container.append(this.canvas,this.icon),this.container.addEventListener("click",()=>{(new q.a).open(this.canvas,e)})}clear(){this.canvas.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height)}}var $=(e={})=>Object(U.a)("btn-circle btn-corner z-depth-1"+(e.className?" "+e.className:""),e);class Y extends V{constructor(){super(...arguments),this.searchGroup=new O(!0,"contacts",!0,"new-group-members disable-hover",!1),this.uploadAvatar=null}init(){this.container.classList.add("new-group-container"),this.setTitle("NewGroup"),this.avatarEdit=new Q(e=>{this.uploadAvatar=e});const e=document.createElement("div");e.classList.add("input-wrapper"),this.groupNameInputField=new F.b({label:"CreateGroup.NameHolder",maxLength:128}),e.append(this.groupNameInputField.container),this.groupNameInputField.input.addEventListener("input",()=>{const e=this.groupNameInputField.value;this.nextBtn.classList.toggle("is-visible",!!e.length&&!this.groupNameInputField.input.classList.contains("error"))}),this.nextBtn=$({icon:"arrow_next"}),this.nextBtn.addEventListener("click",()=>{const e=this.groupNameInputField.value;this.nextBtn.disabled=!0,G.a.createChat(e,this.userIds).then(e=>{this.uploadAvatar&&this.uploadAvatar().then(t=>{G.a.editPhoto(e,t)}),ln.removeTabFromHistory(this),ln.selectTab(0)})});const t=document.createElement("div");t.classList.add("chatlist-container"),t.append(this.searchGroup.container),this.content.append(this.nextBtn),this.scrollable.append(this.avatarEdit.container,e,t)}onCloseAfterTimeout(){this.searchGroup.clear(),this.avatarEdit.clear(),this.uploadAvatar=null,this.groupNameInputField.value="",this.nextBtn.disabled=!1}open(e){const t=super.open();return t.then(()=>{this.userIds=e,this.userIds.forEach(e=>{let{dom:t}=Do.addDialogNew({dialog:e,container:this.searchGroup.list,drawStatus:!1,rippleEnabled:!1,avatarSize:48});t.lastMessageSpan.append(T.a.getUserStatusString(e))}),this.searchGroup.nameEl.textContent="",this.searchGroup.nameEl.append(Object(A.i18n)("Members",[this.userIds.length])),this.searchGroup.setActive()}),t}}var X=s(73),J=s(40),Z=s(29),ee=s(115),te=s(70),se=s(33),ie=s(17),ne=s(94),ae=s(87),oe=s(42),re=s(51),le=s(49),ce=s(139),de=s(27),he=s(65),ue=s(47),pe=s(1),me=s(99),ge=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};const be=(()=>{try{return h.IS_SAFARI&&+navigator.userAgent.match(/ Version\/(\d+)/)[1]<14}catch(e){return!1}})();const ve=new class{constructor(){if(this.media=new Map,this.scheduled=new Map,this.mediaDetails=new Map,this.waitingMediaForLoad=new Map,this.waitingScheduledMediaForLoad=new Map,this.waitingDocumentsForLoad={},this._volume=1,this._muted=!1,this._playbackRate=1,this.seekBackward=e=>{const t=this.playingMedia;t&&(t.currentTime=Math.max(0,t.currentTime-(e.seekOffset||10)))},this.seekForward=e=>{const t=this.playingMedia;t&&(t.currentTime=Math.min(t.duration,t.currentTime+(e.seekOffset||10)))},this.seekTo=e=>{const t=this.playingMedia;t&&(t.currentTime=e.seekTime)},this.onMediaDocumentLoad=e=>{const t=this.mediaDetails.get(e),s=M.a.getDoc(t.docId);"audio"===s.type&&s.supportsStreaming&&be&&this.handleSafariStreamable(e);const i=he.a.getCacheContext(s);e.src=i.url;const n=this.waitingDocumentsForLoad[s.id];n&&(n.delete(e),n.size||delete this.waitingDocumentsForLoad[s.id])},this.onPlay=e=>{const t=e.target,s=this.mediaDetails.get(t),{peerId:n,mid:o}=s,r=this.getMessageByMedia(t);if(this.playingMedia!==t){this.stop();const e=e=>e.mid===o&&e.peerId===n;if(!this.listLoader.current||!e(this.listLoader.current)){let t,s=this.listLoader.previous.findIndex(e);-1!==s?t=-(this.listLoader.previous.length-s):(s=this.listLoader.next.findIndex(e),-1!==s&&(t=s+1)),-1!==s?t&&this.listLoader.go(t,!1):this.setTargets({peerId:n,mid:o})}this.setMedia(t,r)}setTimeout(()=>{a.default.dispatchEvent("media_play",{doc:i.a.getMediaFromMessage(r),message:r,media:t})},0)},this.onPause=e=>{a.default.dispatchEvent("media_pause")},this.onEnded=e=>{e.isTrusted&&(this.onPause(e),this.next()||(this.stop(),a.default.dispatchEvent("media_stop")))},this.play=()=>this.toggle(!0),this.pause=()=>this.toggle(!1),this.stop=()=>{const e=this.playingMedia;if(!e)return!1;e.paused||e.pause(),e.currentTime=0,Object(ue.a)(e,"ended");const t=this.mediaDetails.get(e);if(null==t?void 0:t.clean){e.src="";const s=t.peerId,i=t.isScheduled?this.scheduled:this.media,n=i.get(s);n&&(n.delete(t.mid),n.size||i.delete(s)),e.remove(),this.mediaDetails.delete(e)}return this.playingMedia=void 0,!0},this.playItem=e=>{const{peerId:t,mid:s}=e,i=this.searchContext.isScheduled;this.getMedia(t,s,i).play(),setTimeout(()=>{this.resolveWaitingForLoadMedia(t,s,i)},0)},this.next=()=>!this.lockedSwitchers&&this.listLoader.go(1),this.previous=()=>{const e=this.playingMedia;return e&&e.currentTime>5?(e.currentTime=0,void this.toggle(!0)):!this.lockedSwitchers&&this.listLoader.go(-1)},this.container=document.createElement("div"),this.container.style.cssText="display: none;",document.body.append(this.container),navigator.mediaSession){const e={play:this.play,pause:this.pause,stop:this.stop,seekbackward:this.seekBackward,seekforward:this.seekForward,seekto:this.seekTo,previoustrack:this.previous,nexttrack:this.next};for(const t in e)try{navigator.mediaSession.setActionHandler(t,e[t])}catch(e){console.warn("MediaSession action is not supported:",t)}}a.default.addEventListener("document_downloaded",e=>{const t=this.waitingDocumentsForLoad[e.id];if(t)for(const e of t)this.onMediaDocumentLoad(e)});const e={};["volume","muted","playbackRate"].forEach(t=>{const s="_"+t;e[t]={get:()=>this[s],set:e=>{this[s]!==e&&(this[s]=e,this.playingMedia&&(this.playingMedia[t]=e),this.dispatchPlaybackParams())}}}),Object.defineProperties(this,e)}dispatchPlaybackParams(){const{volume:e,muted:t,playbackRate:s}=this;a.default.dispatchEvent("media_playback_params",{volume:e,muted:t,playbackRate:s})}addMedia(e,t,s){const{peerId:n,mid:o}=e,r=!!e.pFlags.is_scheduled?this.scheduled:this.media;let l=r.get(e.peerId);l||r.set(e.peerId,l=new Map);let c=l.get(o);if(c)return c;const d=i.a.getMediaFromMessage(e);l.set(o,c=document.createElement("round"===d.type||"video"===d.type?"video":"audio")),"round"===d.type&&c.setAttribute("playsinline","true");const h={peerId:n,mid:o,docId:d.id,clean:s,isScheduled:e.pFlags.is_scheduled};this.mediaDetails.set(c,h),c.volume=1,this.container.append(c),c.addEventListener("play",this.onPlay),c.addEventListener("pause",this.onPause),c.addEventListener("ended",this.onEnded),"audio"!==d.type&&(null==e?void 0:e.pFlags.media_unread)&&e.fromId!==a.default.myId&&c.addEventListener("timeupdate",()=>{i.a.readMessages(n,[o])},{once:!0});const u=Object(oe.a)();if(t)u.resolve();else{const t=e.pFlags.is_scheduled?this.waitingScheduledMediaForLoad:this.waitingMediaForLoad;let s=t.get(n);s||t.set(n,s=new Map),s.set(o,u)}return u.then(()=>{const e=he.a.getCacheContext(d);if(d.supportsStreaming||e.url)this.onMediaDocumentLoad(c);else{let e=this.waitingDocumentsForLoad[d.id];e||(e=this.waitingDocumentsForLoad[d.id]=new Set),e.add(c),M.a.downloadDoc(d)}}),c}getMedia(e,t,s){const i=(s?this.scheduled:this.media).get(e);return null==i?void 0:i.get(t)}handleSafariStreamable(e){e.addEventListener("play",()=>{const t=e.currentTime;e.addEventListener("progress",()=>{e.currentTime=e.duration-1,e.addEventListener("progress",()=>{e.currentTime=t,e.paused||e.play()},{once:!0})},{once:!0})})}resolveWaitingForLoadMedia(e,t,s){const i=s?this.waitingScheduledMediaForLoad:this.waitingMediaForLoad,n=i.get(e);if(!n)return;const a=n.get(t);a&&(a.resolve(),n.delete(t),n.size||i.delete(e))}isSafariBuffering(e){return!!e.safariBuffering}setSafariBuffering(e,t){e.safariBuffering=t}setNewMediadata(e,t=this.playingMedia){var s;return ge(this,void 0,void 0,(function*(){yield Object(me.d)(t,void 0,!1);const i=e.media.document,n=[],a="voice"===i.type||"round"===i.type;let l="",c="";if(null===(s=i.thumbs)||void 0===s?void 0:s.length){const s=i.thumbs[i.thumbs.length-1];if(!s.bytes){const a=he.a.getCacheContext(i,s.type);if(a.url)n.push({src:a.url,sizes:`${s.w}x${s.h}`,type:"image/jpeg"});else{r.a.preloadPhoto(i,s).then(()=>{this.playingMedia===t&&a.url&&this.setNewMediadata(e)})}}}else if(a){const s=e.fromId||e.peerId,a=o.a.getPeerPhoto(s);if(a){const i=d.a.loadAvatar(s,a,"photo_small");if(i.cached){const e=yield i.loadPromise;n.push({src:e,sizes:"160x160",type:"image/jpeg"})}else i.loadPromise.then(s=>{this.playingMedia===t&&s&&this.setNewMediadata(e)})}l=o.a.getPeerTitle(s,!0,!1),c=A.default.format("voice"===i.type?"AttachAudio":"AttachRound",!0)}if(!a){const e=i.attributes.find(e=>"documentAttributeAudio"===e._);l=e&&e.title||i.file_name,c=e&&e.performer}n.length||(h.IS_APPLE?pe.IS_TOUCH_SUPPORTED?n.push({src:"assets/img/apple-touch-icon-precomposed.png",sizes:"180x180",type:"image/png"}):n.push({src:"assets/img/apple-touch-icon.png",sizes:"180x180",type:"image/png"}):[72,96,144,192,256,384,512].forEach(e=>{const t=`${e}x${e}`;n.push({src:`assets/img/android-chrome-${t}.png`,sizes:t,type:"image/png"})}));const u=new MediaMetadata({title:l,artist:c,artwork:n});navigator.mediaSession.metadata=u}))}getMessageByMedia(e){const t=this.mediaDetails.get(e),{peerId:s,mid:n}=t;return t.isScheduled?i.a.getScheduledMessageByPeer(s,n):i.a.getMessageByPeer(s,n)}toggle(e){return!!this.playingMedia&&(void 0===e&&(e=this.playingMedia.paused),this.playingMedia.paused===e&&(e?this.playingMedia.play():this.playingMedia.pause(),!0))}willBePlayed(e){this.willBePlayedMedia=e}setSearchContext(e){return!Object(L.b)(this.searchContext,e)&&(this.searchContext=Object(L.a)(e),!0)}getSearchContext(){return this.searchContext}setTargets(e,t,s){this.listLoader?this.listLoader.reset():this.listLoader=new E({loadCount:10,loadWhenLeft:5,processItem:e=>(this.addMedia(e,!1),{peerId:e.peerId,mid:e.mid}),onJump:(e,t)=>{this.playItem(e)},onEmptied:()=>{a.default.dispatchEvent("media_stop"),this.stop()}});const i=void 0===this.searchContext.folderId;t?this.listLoader.setTargets(t,s,i):this.listLoader.reverse=i,this.listLoader.setSearchContext(this.searchContext),this.listLoader.current=e,this.listLoader.load(!0),this.listLoader.load(!1)}setMedia(e,t){this.playingMedia=e,this.playingMedia.volume=this.volume,this.playingMedia.muted=this.muted,this.playingMedia.playbackRate=this.playbackRate,"mediaSession"in navigator&&this.setNewMediadata(t)}setSingleMedia(e,t){const s=this.playingMedia,i=this.pause();return this.willBePlayed(void 0),e?this.setMedia(e,t):this.playingMedia=void 0,this.toggleSwitchers(!1),()=>{this.toggleSwitchers(!0),s&&(this.mediaDetails.get(s)?this.setMedia(s,this.getMessageByMedia(s)):this.next()||this.previous()),e&&this.playingMedia===e&&this.stop(),i&&this.play()}}toggleSwitchers(e){this.lockedSwitchers=!e}};de.a.appMediaPlaybackController=ve;var fe=ve,ye=s(98);function we(e,t,s,i){const n=e=>{s({x:e.pageX,y:e.pageY,event:e})},a=t=>{document.removeEventListener("mousemove",n),e.addEventListener("mousedown",o,{once:!0}),i&&i({x:t.pageX,y:t.pageY,event:t})},o=s=>{0===s.button?(t({x:s.pageX,y:s.pageY,event:s}),n(s),document.addEventListener("mousemove",n),document.addEventListener("mouseup",a,{once:!0})):e.addEventListener("mousedown",o,{once:!0})};e.addEventListener("mousedown",o,{once:!0});const r=e=>{e.preventDefault(),s({x:e.touches[0].clientX,y:e.touches[0].clientY,isTouch:!0,event:e})},l=t=>{document.removeEventListener("touchmove",r),e.addEventListener("touchstart",c,{passive:!1,once:!0}),i&&i({x:t.touches[0].clientX,y:t.touches[0].clientY,isTouch:!0,event:t})},c=e=>{t({x:e.touches[0].clientX,y:e.touches[0].clientY,isTouch:!0,event:e}),r(e),document.addEventListener("touchmove",r,{passive:!1}),document.addEventListener("touchend",l,{passive:!1,once:!0})};return e.addEventListener("touchstart",c,{passive:!1,once:!0}),()=>{e.removeEventListener("mousedown",o),document.removeEventListener("mousemove",n),document.removeEventListener("mouseup",a),e.removeEventListener("touchstart",c),document.removeEventListener("touchmove",r),document.removeEventListener("touchend",l)}}class Le{constructor(e,t=0){this.mousedown=!1,this.events={},this.withTransition=!1,this.useTransform=!1,this.vertical=!1,this.onMouseMove=e=>{this.scrub(e)},this.onMouseDown=e=>{var t;this.rect=this.container.getBoundingClientRect(),this.mousedown=!0,this.scrub(e),this.container.classList.add("is-focused"),(null===(t=this.events)||void 0===t?void 0:t.onMouseDown)&&this.events.onMouseDown(e)},this.onMouseUp=e=>{var t;this.mousedown=!1,this.container.classList.remove("is-focused"),(null===(t=this.events)||void 0===t?void 0:t.onMouseUp)&&this.events.onMouseUp(e)},this.onInput=()=>{var e;const t=+this.seek.value;this.setFilled(t),(null===(e=this.events)||void 0===e?void 0:e.onScrub)&&this.events.onScrub(t)},Object(L.g)(this,e),this.container=document.createElement("div"),this.container.classList.add("progress-line"),this.useTransform?this.container.classList.add("use-transform"):this.withTransition&&this.container.classList.add("with-transition"),this.filled=document.createElement("div"),this.filled.classList.add("progress-line__filled");const s=this.seek=document.createElement("input");s.classList.add("progress-line__seek"),s.type="range",s.step=""+this.step,s.min=""+this.min,s.max=""+this.max,s.value=""+t,t&&this.setProgress(t);const i=""+this.step,n=i.indexOf(".");this.decimals=-1===n?0:i.length-n-1,this.container.append(this.filled,s)}get value(){return+this.seek.value}setHandlers(e){this.events=e}setListeners(){this.seek.addEventListener("input",this.onInput),this._removeListeners=we(this.container,this.onMouseDown,this.onMouseMove,this.onMouseUp)}setProgress(e){this.seek.value=""+e,this.setFilled(+this.seek.value)}addProgress(e){this.seek.value=""+(+this.seek.value+e),this.setFilled(+this.seek.value)}setFilled(e){let t=(e-this.min)/(this.max-this.min);t=Object(C.a)(t,0,1),this.useTransform?this.filled.style.transform=`scaleX(${t})`:this.filled.style.width=100*t+"%"}scrub(e){var t;const s=this.vertical?this.rect.height:this.rect.width,i=Object(C.a)(this.vertical?-(e.y-this.rect.bottom):e.x-this.rect.left,0,s);let n=this.min+i/s*(this.max-this.min);return n-this.min<(this.max-this.min)/2&&(n-=this.step/10),n=+n.toFixed(this.decimals),n=Object(C.a)(n,this.min,this.max),this.setProgress(n),(null===(t=this.events)||void 0===t?void 0:t.onScrub)&&this.events.onScrub(n),n}removeListeners(){this._removeListeners&&(this._removeListeners(),this._removeListeners=null),this.seek.removeEventListener("input",this.onInput),this.events={}}}const Se=e=>{if(e.element)return e.element;const{icon:t,text:s,onClick:i}=e,n=document.createElement("div");n.className="btn-menu-item"+(t?" tgico-"+t:""),Object(ie.ripple)(n);const a=s?Object(A.i18n)(s):document.createElement("span");e.regularText&&(a.innerHTML=e.regularText),a.classList.add("btn-menu-item-text"),n.append(a),e.checkboxField&&(n.append(e.checkboxField.label),Object(l.b)(n,()=>{e.checkboxField.checked=!e.checkboxField.checked},e.options));const o=!!e.checkboxField||!!e.keepOpen;return Object(l.b)(n,"click"!==l.a||o?e=>{Object(c.a)(e),i(e),o||Object(se.c)()}:i,e.options),e.element=n};var Ee=(e,t)=>{const s=document.createElement("div");s.classList.add("btn-menu"),t&&e.forEach(e=>{e.options?e.options.listenerSetter=t:e.options={listenerSetter:t}});const i=e.map(Se);return s.append(...i),s};const Me=(e,t,s)=>{((null==s?void 0:s.listenerSetter)?s.listenerSetter.add(e):e.addEventListener.bind(e))(l.a,s=>{if(!e.classList.contains("btn-menu-toggle"))return!1;const i=e.querySelector(".btn-menu");Object(c.a)(s),e.classList.contains("menu-open")?Object(se.c)():(t&&t(s),Object(se.d)(i))})};var Ie=(e={},t,s,i)=>{e.asDiv=!0;const n=N("more btn-menu-toggle",e),a=Ee(s,e.listenerSetter);return a.classList.add(t),Me(n,i,e),n.append(a),n},Ce=s(5);class ke extends Le{constructor(e,t,s,i){super({step:1e3/60/1e3,min:0,max:1,withTransition:s,useTransform:i},0),this.progressRAF=0,this.onLoadedData=()=>{this.max=this.media.duration,this.seek.setAttribute("max",""+this.max)},this.onEnded=()=>{this.setProgress()},this.onPlay=()=>{let e=()=>{this.setProgress(),this.progressRAF=this.media.paused?0:window.requestAnimationFrame(e)};this.progressRAF&&window.cancelAnimationFrame(this.progressRAF),this.streamable&&this.setLoadProgress(),this.progressRAF=window.requestAnimationFrame(e)},this.onTimeUpdate=()=>{this.media.paused&&(this.setProgress(),this.streamable&&this.setLoadProgress())},this.onProgress=e=>{this.setLoadProgress()},e&&this.setMedia(e,t)}setMedia(e,t=!1){this.media&&this.removeListeners(),t&&!this.filledLoad?(this.filledLoad=document.createElement("div"),this.filledLoad.classList.add("progress-line__filled","progress-line__loaded"),this.container.prepend(this.filledLoad)):this.filledLoad&&this.filledLoad.classList.toggle("hide",!t),this.media=e,this.streamable=t,(!e.paused||e.currentTime>0)&&this.onPlay();let s=!1;this.setSeekMax(),this.setListeners(),this.setHandlers({onMouseDown:()=>{s=!this.media.paused,s&&this.media.pause()},onMouseUp:e=>{s&&this.media.play()}})}scrub(e){const t=super.scrub(e);return this.media.currentTime=t,t}setLoadProgress(){if(fe.isSafariBuffering(this.media))return;const e=this.media.buffered,t=e.length,s=this.media.currentTime;let i=0,n=0;for(let a=0;a<t;++a){const t=e.start(a);s>=t&&t>=i&&(i=t,n=e.end(a))}const a=this.media.duration?n/this.media.duration:0;this.filledLoad.style.width=100*a+"%"}setSeekMax(){this.max=this.media.duration||0,this.max>0?this.onLoadedData():this.media.addEventListener("loadeddata",this.onLoadedData)}setProgress(){if(fe.isSafariBuffering(this.media))return;const e=this.media.currentTime;super.setProgress(e)}setListeners(){super.setListeners(),this.media.addEventListener("ended",this.onEnded),this.media.addEventListener("play",this.onPlay),this.media.addEventListener("timeupdate",this.onTimeUpdate),this.streamable&&this.media.addEventListener("progress",this.onProgress)}removeListeners(){super.removeListeners(),this.media.removeEventListener("loadeddata",this.onLoadedData),this.media.removeEventListener("ended",this.onEnded),this.media.removeEventListener("play",this.onPlay),this.media.removeEventListener("timeupdate",this.onTimeUpdate),this.streamable&&this.media.removeEventListener("progress",this.onProgress),this.progressRAF&&(window.cancelAnimationFrame(this.progressRAF),this.progressRAF=0)}}class Te extends Le{constructor(e,t=!1){super({step:.01,min:0,max:1,vertical:t},1),this.listenerSetter=e,this.vertical=t,this.onMuteClick=e=>{e&&Object(c.a)(e),fe.muted=!fe.muted},this.setVolume=()=>{const{volume:e,muted:t}=fe;let s;s=!e||t?"M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51C20.63 14.91 21 13.5 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06c1.38-.31 2.63-.95 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z":e>.5?"M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z":e>0&&e<.25?"M7 9v6h4l5 5V4l-5 5H7z":"M18.5 12c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM5 9v6h4l5 5V4L9 9H5z";try{this.volumeSvg.innerHTML=`<path d="${s}"></path>`}catch(e){}this.mousedown||this.setProgress(t?0:e)},this.setListeners(),this.setHandlers({onScrub:e=>{const t=Math.max(Math.min(e,1),0);fe.muted=!1,fe.volume=t}}),this.btn=document.createElement("div"),this.btn.classList.add("player-volume"),this.btn.innerHTML='\n <svg class="player-volume__icon" focusable="false" viewBox="0 0 24 24" aria-hidden="true"></svg>\n ',this.btn.classList.add("btn-icon"),this.volumeSvg=this.btn.firstElementChild,this.btn.append(this.container),Object(l.b)(this.volumeSvg,this.onMuteClick,{listenerSetter:this.listenerSetter}),this.listenerSetter.add(a.default)("media_playback_params",this.setVolume),this.setVolume()}}class Pe extends R.a{constructor(e,t=!1,s=!1,i){if(super(!1),this.video=e,this.showControlsTimeout=0,this.hideControls=()=>{clearTimeout(this.showControlsTimeout),this.showControlsTimeout=0;const e=this.wrapper.classList.contains("show-controls");if(!1!==this.controlsLocked){if(this.video.paused||!e||this.controlsLocked)return}else if(!e)return;this.dispatchEvent("toggleControls",!1),this.wrapper.classList.remove("show-controls")},this.showControls=(e=!0)=>{this.showControlsTimeout?(clearTimeout(this.showControlsTimeout),this.showControlsTimeout=0):this.wrapper.classList.contains("show-controls")||!1===this.controlsLocked||(this.dispatchEvent("toggleControls",!0),this.wrapper.classList.add("show-controls")),e&&!this.controlsLocked&&(this.showControlsTimeout=window.setTimeout(this.hideControls,3e3))},this.toggleControls=e=>{const t=this.wrapper.classList.contains("show-controls");if(void 0===e)t?this.hideControls():this.showControls();else{if(e===t)return;!1===e?this.hideControls():this.showControls()}},this.onFullScreen=()=>{null!==document.webkitFullscreenElement||this.wrapper.classList.remove("ckin__fullscreen")},this.wrapper=document.createElement("div"),this.wrapper.classList.add("ckin__player"),this.listenerSetter=new H.a,e.parentNode.insertBefore(this.wrapper,e),this.wrapper.appendChild(e),this.skin="default",this.stylePlayer(i),"default"===this.skin){const t=this.wrapper.querySelector(".default__controls.ckin__controls");this.progress=new ke(e,s),t.prepend(this.progress.container)}if(t){e.play().catch(t=>{"NotAllowedError"===t.name&&(e.muted=!0,e.autoplay=!0,e.play())}).finally(()=>{this.wrapper.classList.toggle("is-playing",!this.video.paused)})}}stylePlayer(e){const{wrapper:t,video:s,skin:i}=this;t.classList.add(i);const n=this.buildControls();let o;if(t.insertAdjacentHTML("beforeend",n),"default"===i){const e=t.querySelectorAll(".toggle"),i=t.querySelector(".fullscreen"),n=t.querySelector("#time-elapsed");o=t.querySelector("#time-duration"),o.innerHTML=String(0|s.duration).toHHMMSS();const r=new Te(this.listenerSetter);t.querySelector(".left-controls").insertBefore(r.btn,n.parentElement),Array.from(e).forEach(e=>{this.listenerSetter.add(e)("click",()=>{this.togglePlay()})}),this.listenerSetter.add(s)("click",()=>{pe.IS_TOUCH_SUPPORTED||this.togglePlay()}),pe.IS_TOUCH_SUPPORTED?this.listenerSetter.add(t)("click",()=>{this.toggleControls()}):(this.listenerSetter.add(this.wrapper)("mousemove",()=>{this.showControls()}),this.listenerSetter.add(this.wrapper)("mouseenter",()=>{this.showControls(!1)}),this.listenerSetter.add(this.wrapper)("mouseleave",e=>{Object(Ce.a)(e.relatedTarget,"media-viewer-caption")?this.showControls(!1):this.hideControls()}),this.listenerSetter.add(document)("keydown",e=>{if(a.default.overlaysActive>1)return;let t=!0;return"KeyF"===e.code?this.toggleFullScreen(i):"KeyM"===e.code?fe.muted=!fe.muted:"Space"===e.code?this.togglePlay():e.altKey&&"Equal"===e.code?fe.playbackRate+=.25:e.altKey&&"Minus"===e.code?fe.playbackRate-=.25:t=!1,t?(Object(c.a)(e),!1):void 0})),this.listenerSetter.add(s)("dblclick",()=>{pe.IS_TOUCH_SUPPORTED||this.toggleFullScreen(i)}),this.listenerSetter.add(i)("click",e=>{this.toggleFullScreen(i)}),"webkitfullscreenchange mozfullscreenchange fullscreenchange MSFullscreenChange".split(" ").forEach(e=>{this.listenerSetter.add(t)(e,this.onFullScreen,!1)}),this.listenerSetter.add(s)("timeupdate",()=>{n.innerHTML=String(0|s.currentTime).toHHMMSS()}),this.listenerSetter.add(s)("play",()=>{this.wrapper.classList.add("played")},{once:!0}),this.listenerSetter.add(s)("pause",()=>{this.showControls(!1)})}this.listenerSetter.add(s)("play",()=>{this.wrapper.classList.add("is-playing")}),this.listenerSetter.add(s)("pause",()=>{this.wrapper.classList.remove("is-playing")}),s.duration||e?o.innerHTML=String(Math.round(s.duration||e)).toHHMMSS():Object(me.d)(s).then(()=>{o.innerHTML=String(Math.round(s.duration)).toHHMMSS()})}lockControls(e){this.controlsLocked=e,this.wrapper.classList.toggle("disable-hover",!1===e),this.toggleControls(e)}togglePlay(){this.video[this.video.paused?"play":"pause"]()}buildControls(){const e=this.skin;if("default"===e)return`\n <button class="${e}__button--big toggle tgico" title="Toggle Play"></button>\n <div class="${e}__gradient-bottom ckin__controls"></div>\n <div class="${e}__controls ckin__controls">\n <div class="bottom-controls">\n <div class="left-controls">\n <button class="btn-icon ${e}__button toggle tgico" title="Toggle Video"></button>\n <div class="time">\n <time id="time-elapsed">0:00</time>\n <span> / </span>\n <time id="time-duration">0:00</time>\n </div>\n </div>\n <div class="right-controls">\n <button class="btn-icon ${e}__button btn-menu-toggle settings tgico-settings hide" title="Playback Rate"></button>\n <button class="btn-icon ${e}__button fullscreen tgico-fullscreen" title="Full Screen"></button>\n </div>\n </div>\n </div>`}setBtnMenuToggle(){const e=[.25,.5,1,1.25,1.5,2].map(e=>({regularText:1===e?"Normal":""+e,onClick:()=>this.video.playbackRate=e})),t=Ee(e),s=this.wrapper.querySelector(".settings");t.classList.add("top-left"),Me(s),s.append(t)}static isFullScreen(){return!!(document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement||document.msFullscreenElement)}toggleFullScreen(e){const t=this.wrapper;if(h.IS_APPLE_MOBILE){const e=this.video;return e.webkitEnterFullscreen(),void e.enterFullscreen()}Pe.isFullScreen()?(t.classList.remove("ckin__fullscreen"),document.cancelFullScreen?document.cancelFullScreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitCancelFullScreen?document.webkitCancelFullScreen():document.msExitFullscreen&&document.msExitFullscreen(),e.classList.remove("tgico-smallscreen"),e.classList.add("tgico-fullscreen"),e.setAttribute("title","Full Screen")):(t.classList.add("ckin__fullscreen"),t.requestFullscreen?t.requestFullscreen():t.mozRequestFullScreen?t.mozRequestFullScreen():t.webkitRequestFullscreen?t.webkitRequestFullscreen():t.msRequestFullscreen&&t.msRequestFullscreen(),e.classList.remove("tgico-fullscreen"),e.classList.add("tgico-smallscreen"),e.setAttribute("title","Exit Full Screen"))}removeListeners(){super.cleanup(),this.listenerSetter.removeAll(),this.progress.removeListeners()}}var xe=s(108),Ae=s(100),Oe=s(107),_e=s(35);function Fe(e){return function(e,t){let s,i=!1;return(...n)=>{s=n,i||(i=!0,e(()=>{i=!1,t(...s)}))}}(_e.b,e)}function je(e){e.classList.add("is-voice");const t=e.message,s=i.a.getMediaFromMessage(t);t.pFlags.out&&e.classList.add("is-out");const n=v.b.isMobile?16:23,a=document.createElementNS("http://www.w3.org/2000/svg","svg");a.classList.add("audio-waveform"),a.setAttributeNS(null,"width","150"),a.setAttributeNS(null,"height",""+n),a.setAttributeNS(null,"viewBox","0 0 150 "+n);const o=document.createElement("div");o.classList.add("audio-time"),e.append(a,o);let r=s.attributes.find(e=>"documentAttributeAudio"===e._).waveform||new Uint8Array([]);r=function(e){e instanceof Uint8Array||(e=new Uint8Array(e));const t=8*e.length/5|0;if(!t)return new Uint8Array([]);let s;try{const i=new DataView(e.buffer);s=new Uint8Array(t);for(let e=0;e<t;e++){const t=5*e/8|0,n=5*e%8,a=i.getUint16(t,!0);s[e]=a>>n&31}}catch(e){s=new Uint8Array([])}return s}(r.slice(0,63));const d=Math.max(...r),h=r.length?r.length:100,u=Math.min(37,h);let p=0;const m=n-4;let g="";for(let e=0,t=0,s=0;e<h;++e){const i=r[e]||0;if(s+u>=h){s=s+u-h,s<(u+1)/2&&p<i&&(p=i);const e=Math.max((p*m+(d+1)/2)/(d+1),4);g+=`\n <rect x="${t}" y="${n-e}" width="2" height="${e}" rx="1" ry="1"></rect>\n `,t+=4,p=s<(u+1)/2?0:i}else p<i&&(p=i),s+=u}a.insertAdjacentHTML("beforeend",g);const b=Array.from(a.children);let f=e.querySelector(".audio-waveform");return()=>{let t=e.audio;const s=()=>{const e=t.currentTime===t.duration?0:Math.ceil(t.currentTime/t.duration*u);b.forEach((t,s)=>t.classList.toggle("active",s<e))};(!t.paused||t.currentTime>0&&t.currentTime!==t.duration)&&s();const i=Fe(s);return e.addAudioListener("timeupdate",i),e.addAudioListener("ended",i),e.readyPromise.then(()=>{let e=!1,s=!1;function i(e){let s;if(e instanceof MouseEvent)s=e.offsetX;else{const t=e.target.getBoundingClientRect();s=e.targetTouches[0].pageX-t.left}const i=s/150*t.duration;t.currentTime=i}f.addEventListener("mouseleave",i=>{e&&(t.play(),e=!1),s=!1}),f.addEventListener("mousemove",t=>{s=!0,e&&i(t)}),f.addEventListener("mousedown",s=>{s.preventDefault(),0===s.button&&(t.paused||t.pause(),i(s),e=!0)}),f.addEventListener("mouseup",i=>{s&&e&&(t.play(),e=!1)}),Object(l.b)(f,e=>{Object(c.a)(e),t.paused||i(e)})},Ae.a),()=>{f.remove(),f=null,t=null}}}function De(e=!0){const t=new ye.a({cancelable:!0,tryAgainOnFail:e});return t.construct(),e||(t.circle.setAttributeNS(null,"r","23"),t.totalLength=143.58203125),t}a.default.addEventListener("messages_media_read",({mids:e,peerId:t})=>{e.forEach(e=>{const s=`[data-mid="${e}"][data-peer-id="${t}"]`;Array.from(document.querySelectorAll(`audio-element.is-unread${s}, .media-round.is-unread${s}`)).forEach(e=>{e.classList.remove("is-unread")})})});const Be=(e,t)=>{let s,i;const n=Object(Ce.a)(e,e.classList.contains("search-super-item")?"tabs-tab":"bubbles-inner");if(n){const t=':not([data-is-outgoing="1"])',a=".audio:not(.is-voice)"+t;let o;o=e.matches(a)?a:`.audio.is-voice${t}, .media-round${t}`;const r=Array.from(n.querySelectorAll(o)),l=r.indexOf(e),c=r.map(e=>({peerId:+e.dataset.peerId,mid:+e.dataset.mid}));s=c.slice(0,l),i=c.slice(l+1)}return[s,i]};class Re extends HTMLElement{constructor(){super(...arguments),this.withTime=!1,this.voiceAsMusic=!1,this.showSender=!1,this.listenerSetter=new H.a}render(){var e;this.classList.add("audio"),this.dataset.mid=""+this.message.mid,this.dataset.peerId=""+this.message.peerId;const t=i.a.getMediaFromMessage(this.message),s="voice"===t.type,n=!this.voiceAsMusic&&s,a=this.message.pFlags.is_outgoing,o=a&&this.preloader,r=String(0|t.duration).toHHMMSS();this.innerHTML='\n <div class="audio-toggle audio-ico">\n <div class="audio-play-icon">\n <div class="part one" x="0" y="0" fill="#fff"></div>\n <div class="part two" x="0" y="0" fill="#fff"></div>\n </div>\n </div>';const d=this.firstElementChild,u=document.createElement("div");u.classList.add("audio-download");"audio"!==t.type&&this.message&&this.message.pFlags.media_unread&&this.classList.add("is-unread"),o&&(this.classList.add("is-outgoing"),this.append(u));const p=n?je(this):function(e){const t=e.withTime,s=e.message,n=i.a.getMediaFromMessage(s),a="voice"===n.type||"round"===n.type,o=document.createElement("div");if(o.classList.add("audio-description"),!a){const a=[];n.audioPerformer&&a.push(Object(Oe.a)(n.audioPerformer)),t?a.push(Object(re.c)(s.date)):a.length||a.push(Object(C.b)(n.size)),e.showSender&&a.push(i.a.wrapSenderToPeer(s)),o.append(...Object(A.joinElementsWith)(a," • "))}e.insertAdjacentHTML("beforeend",'\n <div class="audio-details">\n <div class="audio-title"></div>\n <div class="audio-subtitle"><div class="audio-time"></div></div>\n </div>');const r=e.querySelector(".audio-title"),l=new xe.a;l.dataset.fontWeight=e.dataset.fontWeight,a?l.append(i.a.wrapSenderToPeer(s)):l.innerHTML=n.audioTitle||n.fileName,r.append(l),e.showSender&&r.append(i.a.wrapSentTime(s));const c=e.querySelector(".audio-subtitle");return c.append(o),()=>{let t=!1,s=new ke(e.audio,n.supportsStreaming);e.addAudioListener("ended",()=>{e.classList.remove("audio-show-progress"),c.lastChild.replaceWith(o),t=!1});const i=()=>{t||(e.classList.add("audio-show-progress"),t=!0,s&&c.lastChild.replaceWith(s.container))};return e.addAudioListener("play",i),(!e.audio.paused||e.audio.currentTime>0)&&i(),()=>{s.removeListeners(),s.container.remove(),s=null}}}(this),m=this.querySelector(".audio-time");m.innerHTML=r;const g=this.onLoad=e=>{this.onLoad=void 0;const t=this.audio=fe.addMedia(this.message,e),s=this.readyPromise=Object(oe.a)();this.audio.readyState>=this.audio.HAVE_CURRENT_DATA?s.resolve():this.addAudioListener("canplay",()=>s.resolve(),{once:!0}),this.onTypeDisconnect=p();const i=()=>String(0|t.currentTime).toHHMMSS()+(n?" / "+r:""),a=()=>{m.innerText=i(),d.classList.toggle("playing",!t.paused)};(!t.paused||t.currentTime>0&&t.currentTime!==t.duration)&&a();const o=(e,s=t.paused)=>{if(e&&Object(c.a)(e),s){if(fe.setSearchContext(this.searchContext)){const[e,t]=Be(this,this.searchContext.useSearch);fe.setTargets({peerId:this.message.peerId,mid:this.message.mid},e,t)}t.play().catch(()=>{})}else t.pause()};return Object(l.b)(d,e=>o(e),{listenerSetter:this.listenerSetter}),this.addAudioListener("ended",()=>{d.classList.remove("playing"),m.innerText=r}),this.addAudioListener("timeupdate",()=>{!t.currentTime&&t.paused||fe.isSafariBuffering(t)||(m.innerText=i())}),this.addAudioListener("pause",()=>{d.classList.remove("playing")}),this.addAudioListener("play",a),o};if(a)o&&(this.dataset.isOutgoing="1",this.preloader.attach(u,!1));else{let s=this.preloader;if(g("audio"!==t.type&&!this.noAutoDownload),t.thumbs){const e=[],s=ys({photo:t,message:null,container:d,boxWidth:48,boxHeight:48,loadPromises:this.loadPromises,withoutPreloader:!0,lazyLoadQueue:this.lazyLoadQueue});d.style.width=d.style.height="",s.images.thumb&&e.push(s.images.thumb),s.images.full&&e.push(s.images.full),this.classList.add("audio-with-thumb"),e.forEach(e=>e.classList.add("audio-thumb"))}const i=e=>{if(this.audio.src)return;fe.resolveWaitingForLoadMedia(this.message.peerId,this.message.mid,this.message.pFlags.is_scheduled);const i=()=>{e&&(fe.willBePlayed(this.audio),h.IS_SAFARI&&!this.audio.autoplay&&(this.audio.autoplay=!0))};if(i(),!s)if(t.supportsStreaming){let e;this.classList.add("corner-download");const t=()=>{const t=De(!1),s=Object(oe.a)();s.notifyAll({done:75,total:100}),s.catch(()=>{this.audio.pause(),fe.willBePlayed(void 0)}),s.cancel=()=>{s.cancel=Ae.a;const e=new Error;e.type="CANCELED",s.reject(e)},t.attach(u,!1,s),e=this.addAudioListener("pause",()=>{s.cancel()},{once:!0}),i()},s=this.addAudioListener("play",t);this.readyPromise.then(()=>{this.listenerSetter.remove(s),this.listenerSetter.remove(e)})}else{s=De(),e||(this.readyPromise=Object(oe.a)());const n=()=>{i();const n=M.a.downloadDoc(t);return e||n.then(()=>{this.readyPromise.resolve()}),s.attach(u,!1,n),{download:n}};s.setDownloadFunction(n),n()}this.append(u),this.classList.add("downloading"),this.readyPromise.then(()=>{this.classList.remove("downloading"),u.classList.add("downloaded"),setTimeout(()=>{u.remove()},200),fe.willBePlayedMedia===this.audio&&(this.audio.play(),fe.willBePlayed(void 0))})};(null===(e=this.audio)||void 0===e?void 0:e.src)||("audio"===t.type||this.noAutoDownload?Object(l.b)(d,()=>{i(!0)},{once:!0,capture:!0,passive:!1,listenerSetter:this.listenerSetter}):i(!1))}}get addAudioListener(){return this.listenerSetter.add(this.audio)}disconnectedCallback(){this.isConnected||(this.onTypeDisconnect&&(this.onTypeDisconnect(),this.onTypeDisconnect=null),this.readyPromise&&this.readyPromise.reject(),this.listenerSetter.removeAll(),this.listenerSetter=null,this.preloader=null)}}customElements.define("audio-element",Re);class He{constructor(e,t){this.className=e,this.fill=t,this.container=document.createElement("div"),this.container.className=e,this.border=document.createElement("div"),this.border.classList.add(e+"-border"),this.content=document.createElement("div"),this.content.classList.add(e+"-content"),this.title=document.createElement("div"),this.title.classList.add(e+"-title"),this.title.setAttribute("dir","auto"),this.subtitle=document.createElement("div"),this.subtitle.classList.add(e+"-subtitle"),this.subtitle.setAttribute("dir","auto"),this.content.append(this.title,this.subtitle),this.container.append(this.border,this.content)}}function Ue(e){var t;let{title:s,titleEl:n,subtitle:a,subtitleEl:o,mediaEl:l,message:c,loadPromises:d}=e;void 0!==s&&("string"==typeof s&&(s=Object(X.f)(s,140),s=Z.a.wrapEmojiText(s)),Object(x.a)(n,s)),d||(d=[]);let h=c&&c.media,u=!1,p=!1;const m=l?Array.from(l.children).slice():[];let g;if(h&&l){if(o.textContent="",o.append(i.a.wrapMessageForReply(c)),h.webpage&&(h=h.webpage),h.photo||h.document&&-1!==["video","sticker","gif","round","photo"].indexOf(h.document.type)){g=mo.chat.bubbles.getMiddleware();const e=mo.chat.bubbles.lazyLoadQueue;if("sticker"===(null===(t=h.document)||void 0===t?void 0:t.type))u=!0,Ls({doc:h.document,div:l,lazyLoadQueue:e,group:ho,width:32,height:32,middleware:g,loadPromises:d});else{const t=h.photo||h.document;p="round"===t.type;try{ys({photo:t,container:l,boxWidth:32,boxHeight:32,size:r.a.choosePhotoSize(t,32,32),middleware:g,lazyLoadQueue:e,noBlur:!0,withoutPreloader:!0,loadPromises:d}),u=!0}catch(e){}}}}else c?(o.textContent="",o.append(i.a.wrapMessageForReply(c,c.message&&Object(X.f)(c.message,140)))):("string"==typeof a&&(a=Object(X.f)(a,140),a=Z.a.wrapEmojiText(a)),Object(x.a)(o,a||""));return Promise.all(d).then(()=>{g&&!g()||(m.forEach(e=>e.remove()),l&&l.classList.toggle("is-round",p))}),u}class Ne extends He{constructor(e){super(e,(e,t="",s)=>{this.mediaEl||(this.mediaEl=document.createElement("div"),this.mediaEl.classList.add(this.className+"-media"));const i=Ue({title:e,titleEl:this.title,subtitle:t,subtitleEl:this.subtitle,mediaEl:this.mediaEl,message:s});this.container.classList.toggle("is-media",i),i?this.content.prepend(this.mediaEl):this.mediaEl.remove()}),this.className=e}}const ze=0,Ve=1,We=2,Ke=4,Ge=8;class qe{constructor(e,t,s,i,n=t){this.sizes=e,this.maxWidth=t,this.minWidth=s,this.spacing=i,this.maxHeight=n,this.count=e.length,this.ratios=qe.countRatios(e),this.proportions=qe.countProportions(this.ratios),this.averageRatio=Object(y.a)(this.ratios,1)/this.count,this.maxSizeRatio=t/this.maxHeight}layout(){return this.count?this.count>=5||this.ratios.find(e=>e>2)?new Qe(this.ratios,this.averageRatio,this.maxWidth,this.minWidth,this.spacing).layout():2===this.count?this.layoutTwo():3===this.count?this.layoutThree():this.layoutFour():[]}layoutTwo(){return"ww"===this.proportions&&this.averageRatio>1.4*this.maxSizeRatio&&this.ratios[1]-this.ratios[0]<.2?this.layoutTwoTopBottom():"ww"===this.proportions||"qq"===this.proportions?this.layoutTwoLeftRightEqual():this.layoutTwoLeftRight()}layoutThree(){return"n"===this.proportions[0]?this.layoutThreeLeftAndOther():this.layoutThreeTopAndOther()}layoutFour(){return"w"===this.proportions[0]?this.layoutFourTopAndOther():this.layoutFourLeftAndOther()}layoutTwoTopBottom(){const e=this.maxWidth,t=Math.round(Math.min(e/this.ratios[0],Math.min(e/this.ratios[1],(this.maxHeight-this.spacing)/2)));return[{geometry:{x:0,y:0,width:e,height:t},sides:Ge|Ve|We},{geometry:{x:0,y:t+this.spacing,width:e,height:t},sides:Ge|Ke|We}]}layoutTwoLeftRightEqual(){const e=(this.maxWidth-this.spacing)/2,t=Math.round(Math.min(e/this.ratios[0],Math.min(e/this.ratios[1],1*this.maxHeight)));return[{geometry:{x:0,y:0,width:e,height:t},sides:Ve|Ge|Ke},{geometry:{x:e+this.spacing,y:0,width:e,height:t},sides:Ve|We|Ke}]}layoutTwoLeftRight(){const e=Math.round(1.5*this.minWidth),t=Math.min(Math.round(Math.max(.4*(this.maxWidth-this.spacing),(this.maxWidth-this.spacing)/this.ratios[0]/(1/this.ratios[0]+1/this.ratios[1]))),this.maxWidth-this.spacing-e),s=this.maxWidth-t-this.spacing,i=Math.min(this.maxHeight,Math.round(Math.min(s/this.ratios[0],t/this.ratios[1])));return[{geometry:{x:0,y:0,width:s,height:i},sides:Ve|Ge|Ke},{geometry:{x:s+this.spacing,y:0,width:t,height:i},sides:Ve|We|Ke}]}layoutThreeLeftAndOther(){const e=this.maxHeight,t=Math.round(Math.min((this.maxHeight-this.spacing)/2,this.ratios[1]*(this.maxWidth-this.spacing)/(this.ratios[2]+this.ratios[1]))),s=e-t-this.spacing,i=Math.max(this.minWidth,Math.round(Math.min((this.maxWidth-this.spacing)/2,Math.min(t*this.ratios[2],s*this.ratios[1])))),n=Math.min(Math.round(e*this.ratios[0]),this.maxWidth-this.spacing-i);return[{geometry:{x:0,y:0,width:n,height:e},sides:Ve|Ge|Ke},{geometry:{x:n+this.spacing,y:0,width:i,height:s},sides:Ve|We},{geometry:{x:n+this.spacing,y:s+this.spacing,width:i,height:t},sides:Ke|We}]}layoutThreeTopAndOther(){const e=this.maxWidth,t=Math.round(Math.min(e/this.ratios[0],.66*(this.maxHeight-this.spacing))),s=(this.maxWidth-this.spacing)/2,i=Math.min(this.maxHeight-t-this.spacing,Math.round(Math.min(s/this.ratios[1],s/this.ratios[2]))),n=e-s-this.spacing;return[{geometry:{x:0,y:0,width:e,height:t},sides:Ge|Ve|We},{geometry:{x:0,y:t+this.spacing,width:s,height:i},sides:Ke|Ge},{geometry:{x:s+this.spacing,y:t+this.spacing,width:n,height:i},sides:Ke|We}]}layoutFourTopAndOther(){const e=this.maxWidth,t=Math.round(Math.min(e/this.ratios[0],.66*(this.maxHeight-this.spacing))),s=Math.round((this.maxWidth-2*this.spacing)/(this.ratios[1]+this.ratios[2]+this.ratios[3])),i=Math.max(this.minWidth,Math.round(Math.min(.4*(this.maxWidth-2*this.spacing),s*this.ratios[1]))),n=Math.round(Math.max(Math.max(1*this.minWidth,.33*(this.maxWidth-2*this.spacing)),s*this.ratios[3])),a=e-i-n-2*this.spacing,o=Math.min(this.maxHeight-t-this.spacing,s);return[{geometry:{x:0,y:0,width:e,height:t},sides:Ge|Ve|We},{geometry:{x:0,y:t+this.spacing,width:i,height:o},sides:Ke|Ge},{geometry:{x:i+this.spacing,y:t+this.spacing,width:a,height:o},sides:Ke},{geometry:{x:i+this.spacing+a+this.spacing,y:t+this.spacing,width:n,height:o},sides:We|Ke}]}layoutFourLeftAndOther(){const e=this.maxHeight,t=Math.round(Math.min(e*this.ratios[0],.6*(this.maxWidth-this.spacing))),s=Math.round((this.maxHeight-2*this.spacing)/(1/this.ratios[1]+1/this.ratios[2]+1/this.ratios[3])),i=Math.round(s/this.ratios[1]),n=Math.round(s/this.ratios[2]),a=e-i-n-2*this.spacing,o=Math.max(this.minWidth,Math.min(this.maxWidth-t-this.spacing,s));return[{geometry:{x:0,y:0,width:t,height:e},sides:Ve|Ge|Ke},{geometry:{x:t+this.spacing,y:0,width:o,height:i},sides:Ve|We},{geometry:{x:t+this.spacing,y:i+this.spacing,width:o,height:n},sides:We},{geometry:{x:t+this.spacing,y:i+n+2*this.spacing,width:o,height:a},sides:Ke|We}]}static countRatios(e){return e.map(e=>e.w/e.h)}static countProportions(e){return e.map(e=>e>1.2?"w":e<.8?"n":"q").join("")}}class Qe{constructor(e,t,s,i,n,a=4*s/3){this.averageRatio=t,this.maxWidth=s,this.minWidth=i,this.spacing=n,this.maxHeight=a,this.ratios=Qe.cropRatios(e,t),this.count=e.length}static cropRatios(e,t){return e.map(e=>t>1.1?Object(C.a)(e,1,2.75):Object(C.a)(e,.6667,1))}layout(){let e=new Array(this.count),t=[];const s=(e,t)=>{const s=this.ratios.slice(e,e+t),i=Object(y.a)(s,0);return(this.maxWidth-(t-1)*this.spacing)/i},i=e=>{let i=[],n=0;for(let t of e)i.push(s(n,t)),n+=t;t.push({lineCounts:e,heights:i})};for(let e=1;e!==this.count;++e){const t=this.count-e;e>3||t>3||i([e,t])}for(let e=1;e!==this.count-1;++e)for(let t=1;t!==this.count-e;++t){const s=this.count-e-t;e>3||t>(this.averageRatio<.85?4:3)||s>3||i([e,t,s])}for(let e=1;e!==this.count-1;++e)for(let t=1;t!==this.count-e;++t)for(let s=1;s!==this.count-e-t;++s){const n=this.count-e-t-s;e>3||t>3||s>3||n>3||i([e,t,s,n])}let n=null,a=0;for(const e of t){const{heights:t,lineCounts:s}=e,i=s.length,o=Object(y.a)(t,0)+this.spacing*(i-1),r=Math.min(...t),l=(Math.max(...t),r<this.minWidth?1.5:1),c=(()=>{for(let e=1;e!==i;++e)if(s[e-1]>s[e])return 1.5;return 1})(),d=Math.abs(o-this.maxHeight)*l*c;(!n||d<a)&&(n=e,a=d)}const o=n.lineCounts,r=n.heights,l=o.length;let c=0,d=0;for(let t=0;t!==l;++t){const s=o[t],i=r[t],n=Math.round(i);let a=0;for(let o=0;o!==s;++o){const r=ze|(0===t?Ve:ze)|(t===l-1?Ke:ze)|(0===o?Ge:ze)|(o===s-1?We:ze),h=this.ratios[c],u=o===s-1?this.maxWidth-a:Math.round(h*i);e[c]={geometry:{x:a,y:d,width:u,height:n},sides:r},a+=u+this.spacing,++c}d+=n+this.spacing}return e}}var $e=s(122),Ye=s(60);class Xe{constructor(e){this._disabled=!1,this.avatarSize=120,this.isChanged=()=>{if(this.uploadAvatar)return!0;let e=0,t=0,s=0;return this.inputFields.forEach(i=>{i.isValid()&&(++e,i.required&&++s),i.required&&++t}),t===s&&e>0},this.handleChange=()=>{this.nextBtn.classList.toggle("is-visible",this.isChanged())},Object(L.g)(this,e),this.nextBtn?this.nextBtn.classList.contains("btn-corner")||(this.handleChange=()=>{this.nextBtn.toggleAttribute("disabled",!this.isChanged()||this.disabled)}):this.nextBtn=$({icon:"check"}),e.withoutAvatar||(this.avatarElem=document.createElement("avatar-element"),this.avatarElem.classList.add("avatar-placeholder","avatar-"+this.avatarSize),this.avatarElem.setAttribute("peer",""+this.peerId),e.doNotEditAvatar||(this.avatarEdit=new Q(e=>{this.uploadAvatar=e,this.handleChange(),this.avatarElem.remove()}),this.avatarEdit.container.append(this.avatarElem))),this.inputFields.forEach(e=>{this.listenerSetter.add(e.input)("input",this.handleChange)}),this.handleChange()}get disabled(){return this._disabled}set disabled(e){this._disabled=e,this.inputFields.forEach(t=>t.input.toggleAttribute("disabled",e)),this.handleChange()}lockWithPromise(e,t=!1){this.disabled=!0,e.then(()=>{t&&(this.disabled=!1)},()=>{this.disabled=!1})}}class Je{constructor(e={}){this.freezed=!1,this.container=document.createElement(e.radioField||e.checkboxField?"label":"div"),this.container.classList.add("row"),this.subtitle=document.createElement("div"),this.subtitle.classList.add("row-subtitle"),this.subtitle.setAttribute("dir","auto"),e.subtitle?"string"==typeof e.subtitle?b(this.subtitle,e.subtitle):this.subtitle.append(e.subtitle):e.subtitleLangKey&&this.subtitle.append(Object(A.i18n)(e.subtitleLangKey,e.subtitleLangArgs)),this.container.append(this.subtitle);let t=!!e.havePadding;if(e.radioField||e.checkboxField){if(t=!0,e.radioField&&(this.radioField=e.radioField,this.container.append(this.radioField.label)),e.checkboxField){this.checkboxField=e.checkboxField;const t=e.checkboxField.label.classList.contains("checkbox-field-toggle");t?(this.container.classList.add("row-with-toggle"),e.titleRight=this.checkboxField.label):this.container.append(this.checkboxField.label),e.noCheckboxSubtitle||t||this.checkboxField.input.addEventListener("change",()=>{Object(x.a)(this.subtitle,Object(A.i18n)(this.checkboxField.input.checked?"Checkbox.Enabled":"Checkbox.Disabled"))})}(e.radioField||e.checkboxField).label.classList.add("disable-hover")}if(e.title||e.titleLangKey){let t;if(e.titleRight?(t=document.createElement("div"),t.classList.add("row-title-row"),this.container.append(t)):t=this.container,this.title=document.createElement("div"),this.title.classList.add("row-title"),this.title.setAttribute("dir","auto"),e.title?this.title.innerHTML=e.title:this.title.append(Object(A.i18n)(e.titleLangKey)),t.append(this.title),e.titleRight){const s=document.createElement("div");s.classList.add("row-title","row-title-right"),"string"==typeof e.titleRight?s.innerHTML=e.titleRight:s.append(e.titleRight),t.append(s)}}e.icon&&(t=!0,this.title.classList.add("tgico","tgico-"+e.icon),this.container.classList.add("row-with-icon")),t&&this.container.classList.add("row-with-padding"),e.navigationTab&&(e.clickable=()=>e.navigationTab.open()),(e.clickable||e.radioField||e.checkboxField)&&("function"==typeof e.clickable&&this.container.addEventListener("click",t=>{this.freezed||e.clickable(t)}),this.container.classList.add("row-clickable","hover-effect"),e.noRipple||Object(ie.ripple)(this.container,void 0,void 0,!0))}}const Ze=(e,t)=>function(e,t){const s=document.createElement("form");return e.forEach(e=>{const{container:i,input:n}=e;s.append(i),n.addEventListener("change",()=>{n.checked&&t(n.value)})}),s}(e.map(e=>({container:e.container,input:e.radioField.input})),t);function et(e){navigator.clipboard?navigator.clipboard.writeText(e):function(e){var t=document.createElement("textarea");t.value=e,t.style.top="0",t.style.left="0",t.style.position="fixed",document.body.appendChild(t),t.focus(),t.select();try{document.execCommand("copy")}catch(e){}document.body.removeChild(t)}(e)}var tt=s(62);class st{constructor(e){const t=this.label=document.createElement("label");t.classList.add("radio-field");const s=this.input=document.createElement("input");s.type="radio",s.name="input-radio-"+e.name,e.value&&(s.value=e.value,e.stateKey&&(k.default.getState().then(t=>{s.checked=Object(L.d)(t,e.stateKey)===e.value}),s.addEventListener("change",()=>{k.default.setByKey(e.stateKey,e.value)})));const i=this.main=document.createElement("div");i.classList.add("radio-field-main"),e.text?i.innerHTML=e.text:e.langKey&&Object(A._i18n)(i,e.langKey),t.append(s,i)}get checked(){return this.input.checked}set checked(e){this.setValueSilently(e);const t=new Event("change",{bubbles:!0,cancelable:!0});this.input.dispatchEvent(t)}setValueSilently(e){this.input.checked=e}}const it=document.createElement("div");function nt(e){Object(x.a)(it,e),document.body.append(it),it.dataset.timeout&&clearTimeout(+it.dataset.timeout),it.dataset.timeout=""+setTimeout(()=>{it.remove(),delete it.dataset.timeout},3e3)}function at(e){nt(Object(A.i18n)(e.langPackKey))}function ot(e,t,s=!0,i=!0){let n,a,o,r,l=!1;return(...c)=>(a||(a=new Promise((e,t)=>(o=e,r=t))),n?(clearTimeout(n),l=!0,r(),a=new Promise((e,t)=>(o=e,r=t))):s&&(o(e(...c)),l=!1),n=setTimeout(()=>{!i||s&&!l||o(e(...c)),n=a=o=r=void 0,l=!1},t),a.catch(()=>{}),a)}it.classList.add("toast");var rt=s(30);class lt extends F.b{constructor(e){super(e),this.checkUsernameDebounced=ot(this.checkUsername.bind(this),150,!1,!0),e.listenerSetter.add(this.input)("input",()=>{const e=this.getValue();if(e===this.originalValue||!e.length)return this.setState(F.a.Neutral,this.options.label),void(this.options.onChange&&this.options.onChange());Z.b.isUsernameValid(e)?this.setState(F.a.Neutral):this.setError(this.options.invalidText),this.input.classList.contains("error")?this.options.onChange&&this.options.onChange():this.checkUsernameDebounced(e)})}getValue(){let e=this.value;return this.options.head&&(e=e.slice(this.options.head.length),this.setValueSilently(this.options.head+e)),e}checkUsername(e){this.checkUsernamePromise||(this.options.peerId?this.checkUsernamePromise=rt.a.invokeApi("channels.checkUsername",{channel:G.a.getChannelInput(-this.options.peerId),username:e}):this.checkUsernamePromise=rt.a.invokeApi("account.checkUsername",{username:e}),this.checkUsernamePromise.then(t=>{this.getValue()===e&&(t?this.setState(F.a.Valid,this.options.availableText):this.setError(this.options.takenText))},t=>{if(this.getValue()===e)switch(t.type){case"USERNAME_INVALID":this.setError(this.options.invalidText)}}).then(()=>{this.checkUsernamePromise=void 0,this.options.onChange&&this.options.onChange();const t=this.getValue();t!==e&&this.isValid()&&Z.b.isUsernameValid(t)&&this.checkUsername(t)}))}}var ct=s(66),dt=s(50);class ht extends ct.b{constructor(e,t={}){if(super("popup-peer"+(e?" "+e:""),t.buttons&&Object(ct.a)(t.buttons),Object.assign({overlayClosable:!0},t)),this.className=e,t.peerId){let e=new ko;e.setAttribute("dialog","1"),e.setAttribute("peer",""+t.peerId),e.classList.add("avatar-32"),this.header.prepend(e)}t.noTitle||(t.titleLangKey||!t.title?this.title.append(Object(A.i18n)(t.titleLangKey||"AppName",t.titleLangArgs)):this.title.innerText=t.title||"");const s=document.createDocumentFragment();if(t.descriptionLangKey||t.description){const e=document.createElement("p");e.classList.add("popup-description"),t.descriptionLangKey?e.append(Object(A.i18n)(t.descriptionLangKey,t.descriptionLangArgs)):t.description&&(e.innerHTML=t.description),s.append(e)}t.checkboxes&&(this.container.classList.add("have-checkbox"),t.checkboxes.forEach(e=>{e.withRipple=!1;const t=new dt.a(e);e.checkboxField=t,s.append(t.label)}),t.buttons.forEach(e=>{if(e.callback){const s=e.callback;e.callback=()=>{const e=new Set;t.checkboxes.forEach(t=>{t.checkboxField.checked&&e.add(t.text)}),s(e)}}})),this.container.insertBefore(s,this.header.nextElementSibling)}}var ut=s(54);class pt extends W{init(){this.container.classList.add("edit-peer-container","group-type-container");const e=G.a.isBroadcast(this.chatId);this.setTitle(e?"ChannelType":"GroupType");const t=new nn({name:e?"ChannelType":"GroupType"}),s=Object(tt.b)(),i=new Je({radioField:new st({langKey:e?"ChannelPrivate":"MegaPrivate",name:s,value:"private"}),subtitleLangKey:e?"ChannelPrivateInfo":"MegaPrivateInfo"}),a=new Je({radioField:new st({langKey:e?"ChannelPublic":"MegaPublic",name:s,value:"public"}),subtitleLangKey:e?"ChannelPublicInfo":"MegaPublicInfo"}),o=Ze([i,a],e=>{const t=[c,u];"public"===e&&t.reverse(),t[0].container.classList.remove("hide"),t[1].container.classList.add("hide"),m()}),r=G.a.getChat(this.chatId);t.content.append(o);const c=new nn({}),d=new Je({title:this.chatFull.exported_invite.link,subtitleLangKey:e?"ChannelPrivateLinkHelp":"MegaPrivateLinkHelp",clickable:()=>{et(this.chatFull.exported_invite.link),nt(A.default.format("LinkCopied",!0))}}),h=Object(U.a)("btn-primary btn-transparent danger",{icon:"delete",text:"RevokeLink"});Object(l.b)(h,()=>{new ht("revoke-link",{buttons:[{langKey:"RevokeButton",callback:()=>{const e=Object(ut.a)([h],!0);n.default.getChatInviteLink(this.chatId,!0).then(t=>{e(),d.title.innerHTML=t})}}],titleLangKey:"RevokeLink",descriptionLangKey:"RevokeAlert"}).show()},{listenerSetter:this.listenerSetter}),c.content.append(d.container,h);const u=new nn({caption:e?"Channel.UsernameAboutChannel":"Channel.UsernameAboutGroup",noDelimiter:!0}),p=document.createElement("div");p.classList.add("input-wrapper");const m=()=>{const e=i.radioField.checked&&"t.me/"!==b||g.isValid()&&g.input.classList.contains("valid");v.classList.toggle("is-visible",e)},g=new lt({label:"SetUrlPlaceholder",name:"group-public-link",plainText:!0,listenerSetter:this.listenerSetter,availableText:"Link.Available",invalidText:"Link.Invalid",takenText:"Link.Taken",onChange:m,peerId:-this.chatId,head:"t.me/"}),b="t.me/"+(r.username||"");p.append(g.container),u.content.append(p);const v=$({icon:"check",className:"is-visible"});this.content.append(v),Object(l.b)(v,()=>{Object(se.g)(v);const e=a.radioField.checked?g.getValue():"";G.a.migrateChat(this.chatId).then(t=>G.a.updateUsername(t,e)).then(()=>{this.close()})},{listenerSetter:this.listenerSetter}),("t.me/"!==b?a:i).radioField.checked=!0,g.setOriginalValue(b),this.scrollable.append(t.container,c.container,u.container)}}var mt=s(59);class gt{constructor(e){this.loading=!1,this.loaded=!1,Object(L.g)(this,e),e.scrollable.onScrolledBottom=()=>{this.load()}}load(){return this.loaded?Promise.resolve():this.loading?this.promise:(this.loading=!0,void(this.promise=this.getPromise().then(e=>{this.loading=!1,this.promise=void 0,e?(this.loaded=!0,this.scrollable.onScrolledBottom=null):this.scrollable.checkForTriggers()},()=>{this.promise=void 0,this.loading=!1})))}}var bt=s(80),vt=s(81),ft=s(48),yt=s(92),wt=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};let Lt,St=!1;class Et{constructor(e){this.container=document.createElement("div"),this.list=Do.createChatList(),this.chatsContainer=document.createElement("div"),this.selected=new Set,this.freezed=!1,this.folderId=0,this.offsetIndex=0,this.query="",this.loadedWhat={},this.renderedPeerIds=new Set,this.peerType=["dialogs"],this.multiSelect=!0,this.rippleEnabled=!0,this.avatarSize=48,this.tempIds={},this.peerId=0,this.selfPresence="Presence.YourChat",this.needSwitchList=!1,this.onInput=()=>{const e=this.input.value;if(this.query!==e){this.peerType.includes("contacts")&&(this.cachedContacts=null),this.peerType.includes("dialogs")&&(this.folderId=0,this.offsetIndex=0);for(let e in this.tempIds)++this.tempIds[e];this.list=Do.createChatList(),this.promise=null,this.loadedWhat={},this.query=e,this.renderedPeerIds.clear(),this.needSwitchList=!0,this.getMoreResults()}},this.checkForTriggers=()=>{this.scrollable.checkForTriggers()},Object(L.g)(this,e),this.container.classList.add("selector");const t=(this.renderResultsFunc||this.renderResults).bind(this);if(this.renderResultsFunc=e=>(this.needSwitchList&&(this.scrollable.splitUp.replaceWith(this.list),this.scrollable.setVirtualContainer(this.list),this.needSwitchList=!1),e=e.filter(e=>{const t=!this.renderedPeerIds.has(e);return t&&this.renderedPeerIds.add(e),t}),t(e)),this.input=document.createElement("input"),this.input.classList.add("selector-search-input"),this.placeholder?Object(A._i18n)(this.input,this.placeholder,void 0,"placeholder"):Object(A._i18n)(this.input,"SendMessageTo",void 0,"placeholder"),this.input.type="text",this.multiSelect){let e=document.createElement("div");e.classList.add("selector-search-container"),this.selectedContainer=document.createElement("div"),this.selectedContainer.classList.add("selector-search"),this.selectedContainer.append(this.input),e.append(this.selectedContainer),this.selectedScrollable=new P.b(e);let t=document.createElement("hr");this.selectedContainer.addEventListener("click",e=>{if(this.freezed)return;let t=e.target;if(t=Object(Ce.a)(t,"selector-user"),!t)return;const s=t.dataset.key,i=this.chatsContainer.querySelector('[data-peer-id="'+s+'"]');i?i.click():this.remove(+s||s)}),this.container.append(e,t)}this.chatsContainer.classList.add("chatlist-container"),this.chatsContainer.append(this.list),this.scrollable=new P.b(this.chatsContainer),this.scrollable.setVirtualContainer(this.list),this.chatsContainer.addEventListener("click",e=>{const t=Object(vt.a)(e.target,"data-peer-id");if(Object(c.a)(e),!t)return;if(this.freezed)return;let s=t.dataset.peerId;if(s=+s||s,!this.multiSelect)return void this.add(s);this.selected.has(s)?this.remove(s):this.add(s);const i=t.querySelector("input");i.checked=!i.checked});const s=ot(this.onInput,200,!1,!0);this.input.addEventListener("input",s),this.scrollable.onScrolledBottom=()=>{this.getMoreResults()},this.container.append(this.chatsContainer),this.appendTo.append(this.container),setTimeout(()=>{let t=this.getMoreResults();e.onFirstRender&&t.then(()=>{e.onFirstRender()})},0)}renderSaved(){this.offsetIndex||0!==this.folderId||!this.peerType.includes("dialogs")||this.query&&!T.a.testSelfSearch(this.query)||this.renderResultsFunc([a.default.myId])}getTempId(e){return void 0===this.tempIds[e]&&(this.tempIds[e]=0),++this.tempIds[e]}getMoreDialogs(){return wt(this,void 0,void 0,(function*(){if(this.promise)return this.promise;if(this.loadedWhat.dialogs&&this.loadedWhat.archived)return;const e=yt.a.windowH/72*1.25|0,t=this.getTempId("dialogs"),s=i.a.getConversations(this.query,this.offsetIndex,e,this.folderId,!0).promise;this.promise=s;const n=yield s;if(this.tempIds.dialogs!==t)return;this.promise=null;let o=n.dialogs;if(o.length){const e=o[o.length-1].index||0;o=o.slice(),o.findAndSplice(e=>e.peerId===a.default.myId),this.chatRightsAction&&(o=o.filter(e=>this.filterByRights(e.peerId))),this.renderSaved(),this.offsetIndex=e,this.renderResultsFunc(o.map(e=>e.peerId))}if(n.isEnd){if(!this.loadedWhat.dialogs)return this.renderSaved(),this.loadedWhat.dialogs=!0,this.offsetIndex=0,this.folderId=1,this.getMoreDialogs();if(this.loadedWhat.archived=!0,!this.loadedWhat.contacts&&this.peerType.includes("contacts"))return this.getMoreContacts()}}))}filterByRights(e){return e>0&&("send_messages"!==this.chatRightsAction||T.a.canSendToUser(e))||G.a.hasRights(-e,this.chatRightsAction)}getMoreContacts(){return wt(this,void 0,void 0,(function*(){if(this.promise)return this.promise;if(!this.loadedWhat.contacts){if(!this.cachedContacts){const e=this.getTempId("contacts"),t=Promise.all([T.a.getContacts(this.query),this.query?T.a.searchContacts(this.query):void 0]);this.promise=t;const[s,i]=yield t;if(this.tempIds.contacts!==e)return;if(i){let e=i.my_results.concat(i.results);this.chatRightsAction&&(e=e.filter(e=>this.filterByRights(e))),this.peerType.includes("dialogs")||(e=e.filter(e=>e>0)),this.cachedContacts=Object(y.b)(s.concat(e))}else this.cachedContacts=s.slice();this.cachedContacts.findAndSplice(e=>e===a.default.myId),this.promise=null}if(this.cachedContacts.length){const e=yt.a.windowH/72*1.25|0,t=this.cachedContacts.splice(0,e);this.renderResultsFunc(t)}this.cachedContacts.length||(this.loadedWhat.contacts=!0)}}))}getMoreChannelParticipants(){return wt(this,void 0,void 0,(function*(){if(this.promise)return this.promise;if(this.loadedWhat.channelParticipants)return;const e=this.getTempId("channelParticipants"),t=n.default.getChannelParticipants(-this.peerId,{_:"channelParticipantsSearch",q:this.query},50,this.list.childElementCount),s=yield t;if(this.tempIds.channelParticipants!==e)return;const i=s.participants.map(e=>G.a.getParticipantPeerId(e));i.findAndSplice(e=>e===a.default.myId),this.renderResultsFunc(i),(this.list.childElementCount>=s.count||s.participants.length<50)&&(this.loadedWhat.channelParticipants=!0)}))}getMoreResults(){const e=(()=>{const e=[];return!St&&this.peerType.includes("dialogs")&&(Lt||(Lt=i.a.getConversationsAll().then(()=>{St=!0}).finally(()=>{Lt=null})),e.push(Lt)),!this.peerType.includes("dialogs")||this.loadedWhat.archived||(e.push(this.getMoreDialogs()),this.loadedWhat.archived)?(this.peerType.includes("contacts")&&!this.loadedWhat.contacts&&e.push(this.getMoreContacts()),this.peerType.includes("channelParticipants")&&!this.loadedWhat.channelParticipants&&e.push(this.getMoreChannelParticipants()),e):e})(),t=Promise.all(e);return e.length&&t.then(this.checkForTriggers),t}renderResults(e){!this.peerType.includes("dialogs")&&this.loadedWhat.contacts&&(e=e.filter(e=>T.a.isNonContactUser(e))),e.forEach(e=>{const{dom:t}=Do.addDialogNew({dialog:e,container:this.scrollable,drawStatus:!1,rippleEnabled:this.rippleEnabled,avatarSize:this.avatarSize});if(this.multiSelect){const s=this.selected.has(e),i=new dt.a;s&&(i.input.checked=!0),t.containerEl.prepend(i.label)}let s;s=e<0?n.default.getChatMembersString(-e):e===a.default.myId?Object(A.i18n)(this.selfPresence):T.a.getUserStatusString(e),t.lastMessageSpan.append(s)})}add(e,t,s=!0){if(this.selected.add(e),!this.multiSelect)return void this.onChange(this.selected.size);this.query.trim()&&(this.input.value="",this.onInput());const i=document.createElement("div");i.classList.add("selector-user","scale-in");const n=document.createElement("avatar-element");return n.classList.add("selector-user-avatar","tgico"),n.setAttribute("dialog","1"),n.classList.add("avatar-32"),i.dataset.key=""+e,"number"==typeof e&&(void 0===t&&(t=new ft.a({peerId:e,dialog:!0}).element),n.setAttribute("peer",""+e)),t&&("string"==typeof t?i.innerHTML=t:(Object(x.a)(i,t),i.append(t))),i.insertAdjacentElement("afterbegin",n),this.selectedContainer.insertBefore(i,this.input),this.onChange&&this.onChange(this.selected.size),s&&this.selectedScrollable.scrollIntoViewNew(this.input,"center"),i}remove(e){if(!this.multiSelect)return;const t=this.selectedContainer.querySelector(`[data-key="${e}"]`);t.classList.remove("scale-in"),t.offsetWidth,t.classList.add("scale-out");const s=()=>{this.selected.delete(e),t.remove(),this.onChange&&this.onChange(this.selected.size)};a.default.settings.animationsEnabled?t.addEventListener("animationend",s,{once:!0}):s()}getSelected(){return[...this.selected]}addInitial(e){e.forEach(e=>{this.add(e,void 0,!1)}),window.requestAnimationFrame(()=>{this.selectedScrollable.scrollIntoViewNew(this.input,"center",void 0,void 0,bt.a.Static)})}}var Mt=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class It extends ct.b{constructor(e){super("popup-forward",null,{closable:!0,overlayClosable:!0,body:!0}),e.onClose&&(this.onClose=e.onClose),this.selector=new Et({appendTo:this.body,onChange:()=>Mt(this,void 0,void 0,(function*(){const t=this.selector.getSelected(),s=t[t.length-1];if(e.onSelect){const t=e.onSelect(s);if(t instanceof Promise)try{yield t}catch(e){return}}this.selector=null,this.hide()})),peerType:e.peerTypes,onFirstRender:()=>{this.show(),this.selector.checkForTriggers(),pe.IS_TOUCH_SUPPORTED||this.selector.input.focus()},chatRightsAction:e.chatRightsAction,multiSelect:!1,rippleEnabled:!1,avatarSize:46,peerId:e.peerId,placeholder:e.placeholder,selfPresence:e.selfPresence}),this.title.append(this.selector.input)}}class Ct extends W{init(){let e;this.container.classList.add("edit-peer-container","user-permissions-container"),this.setTitle("UserRestrictions");{const t=new nn({name:"UserRestrictionsCanDo"}),s=document.createElement("div");s.classList.add("chatlist-container"),t.content.insertBefore(s,t.title);const i=Do.createChatList({new:!0});s.append(i);const{dom:n}=Do.addDialogNew({dialog:this.userId,container:i,drawStatus:!1,rippleEnabled:!0,avatarSize:48});n.lastMessageSpan.append(T.a.getUserStatusString(this.userId));const a=new Tt({chatId:this.chatId,listenerSetter:this.listenerSetter,appendTo:t.content,participant:"channelParticipantBanned"===this.participant._?this.participant:void 0});e=()=>{const e=a.takeOut();"channelParticipantBanned"===this.participant._&&Object(L.b)(this.participant.banned_rights.pFlags,e.pFlags)||G.a.editBanned(this.chatId,this.participant,e)},this.eventListener.addEventListener("destroy",e,{once:!0}),this.scrollable.append(t.container)}{const t=new nn({});if("channelParticipantBanned"===this.participant._){const s=Object(U.a)("btn-primary btn-transparent danger",{icon:"delete",text:"GroupPermission.Delete"});Object(l.b)(s,()=>{const t=Object(ut.a)([s],!0);G.a.clearChannelParticipantBannedRights(this.chatId,this.participant).then(()=>{this.eventListener.removeEventListener("destroy",e),this.close()},()=>{t()})},{listenerSetter:this.listenerSetter}),t.content.append(s)}const s=Object(U.a)("btn-primary btn-transparent danger",{icon:"deleteuser",text:"UserRestrictionsBlock"});Object(l.b)(s,()=>{Object(ut.a)([s],!0);G.a.kickFromChannel(this.chatId,this.participant).then(()=>{this.eventListener.removeEventListener("destroy",e),this.close()})},{listenerSetter:this.listenerSetter}),t.content.append(s),this.scrollable.append(t.container)}}}var kt=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class Tt{constructor(e){this.v=[{flags:["send_messages"],text:"UserRestrictionsSend",exceptionText:"UserRestrictionsNoSend"},{flags:["send_media"],text:"UserRestrictionsSendMedia",exceptionText:"UserRestrictionsNoSendMedia"},{flags:["send_stickers","send_gifs"],text:"UserRestrictionsSendStickers",exceptionText:"UserRestrictionsNoSendStickers"},{flags:["send_polls"],text:"UserRestrictionsSendPolls",exceptionText:"UserRestrictionsNoSendPolls"},{flags:["embed_links"],text:"UserRestrictionsEmbedLinks",exceptionText:"UserRestrictionsNoEmbedLinks"},{flags:["invite_users"],text:"UserRestrictionsInviteUsers",exceptionText:"UserRestrictionsNoInviteUsers"},{flags:["pin_messages"],text:"UserRestrictionsPinMessages",exceptionText:"UserRestrictionsNoPinMessages"},{flags:["change_info"],text:"UserRestrictionsChangeInfo",exceptionText:"UserRestrictionsNoChangeInfo"}],this.toggleWith={send_messages:["send_media","send_stickers","send_polls","embed_links"]};const t=G.a.getChat(e.chatId).default_banned_rights,s=e.participant?G.a.combineParticipantBannedRights(e.chatId,e.participant.banned_rights):t;for(const i of this.v){const n=i.flags[0];i.checkboxField=new dt.a({text:i.text,checked:G.a.hasRights(e.chatId,n,s),restriction:!0,withRipple:!0}),e.participant&&t.pFlags[n]&&(i.checkboxField.input.disabled=!0,Object(l.b)(i.checkboxField.label,e=>{nt(A.default.format("UserRestrictionsDisabled",!0))},{listenerSetter:e.listenerSetter})),this.toggleWith[n]&&e.listenerSetter.add(i.checkboxField.input)("change",()=>{if(!i.checkboxField.checked){this.v.filter(e=>this.toggleWith[n].includes(e.flags[0])).forEach(e=>{e.checkboxField.checked=!1})}}),e.appendTo.append(i.checkboxField.label)}}takeOut(){const e={_:"chatBannedRights",until_date:2147483647,pFlags:{}};for(const t of this.v){!t.checkboxField.checked&&t.flags.forEach(t=>{e.pFlags[t]=!0})}return e}}class Pt extends W{init(){return kt(this,void 0,void 0,(function*(){let e;this.container.classList.add("edit-peer-container","group-permissions-container"),this.setTitle("ChannelPermissions");{const t=new nn({name:"ChannelPermissionsHeader"});e=new Tt({chatId:this.chatId,listenerSetter:this.listenerSetter,appendTo:t.content}),this.eventListener.addEventListener("destroy",()=>{G.a.editChatDefaultBannedRights(this.chatId,e.takeOut())},{once:!0}),this.scrollable.append(t.container)}{const t=new nn({name:"PrivacyExceptions"}),s=new Je({titleLangKey:"ChannelAddException",subtitleLangKey:"Loading",icon:"adduser",clickable:()=>{new It({peerTypes:["channelParticipants"],onSelect:e=>{setTimeout(()=>{i(e)},0)},placeholder:"ExceptionModal.Search.Placeholder",peerId:-this.chatId})}}),i=e=>kt(this,void 0,void 0,(function*(){let t;try{t=yield n.default.getChannelParticipant(this.chatId,e)}catch(e){return void nt("User is no longer participant")}const s=new Ct(this.slider);s.participant=t,s.chatId=this.chatId,s.userId=e,s.open()}));t.content.append(s.container);const r=t.generateContentElement();r.classList.add("chatlist-container");const c=Do.createChatList({new:!0});r.append(c),Object(l.b)(c,e=>{const t=Object(mt.a)(e.target,"LI");if(!t)return;const s=+t.dataset.peerId;i(s)},{listenerSetter:this.listenerSetter});const d=(t,s)=>{const i=s.banned_rights,n=G.a.getChat(this.chatId).default_banned_rights,a=[];e.v.forEach(e=>{const t=e.flags[0];i.pFlags[t]&&!n.pFlags[t]&&a.push(e.exceptionText)});const o=t.querySelector(".user-last-message");a.length&&(o.innerHTML="",o.append(...Object(A.join)(a.map(e=>Object(A.i18n)(e)),!1))),o.classList.toggle("hide",!a.length)},h=(e,t)=>{const{dom:s}=Do.addDialogNew({dialog:o.a.getPeerId(e.peer),container:c,drawStatus:!1,rippleEnabled:!0,avatarSize:48,append:t});d(s.listEl,e)};this.listenerSetter.add(a.default)("updateChannelParticipant",e=>{var t,s,i;const n="channelParticipantBanned"===(null===(t=e.new_participant)||void 0===t?void 0:t._)&&!e.new_participant.banned_rights.pFlags.view_messages,a=c.querySelector(`[data-peer-id="${e.user_id}"]`);n?(a?d(a,e.new_participant):h(e.new_participant,!1),"channelParticipantBanned"!==(null===(s=e.prev_participant)||void 0===s?void 0:s._)&&++m):(a&&a.remove(),"channelParticipantBanned"===(null===(i=e.prev_participant)||void 0===i?void 0:i._)&&--m),u()});const u=()=>{Object(x.a)(s.subtitle,Object(A.i18n)(m?"Permissions.ExceptionsCount":"Permissions.NoExceptions",[m]))};let p,m=0;const g=()=>(p=new gt({scrollable:this.scrollable,getPromise:()=>n.default.getChannelParticipants(this.chatId,{_:"channelParticipantsBanned",q:""},50,c.childElementCount).then(e=>{for(const t of e.participants)h(t,!0);return m=e.count,u(),e.participants.length<50||e.count===c.childElementCount})}),p.load());this.scrollable.append(t.container),G.a.isChannel(this.chatId)?yield g():(u(),this.listenerSetter.add(a.default)("dialog_migrate",({migrateFrom:e,migrateTo:t})=>{this.chatId===e&&(this.chatId=t,g())}))}}))}onOpenAfterTimeout(){this.scrollable.onScroll()}}class xt{constructor(e,t=o.a.getDialogType(e),s){const n=new ft.a({peerId:e}).element,a=(t,n=u&&!!t.size)=>{let a=G.a.leave(-e);n&&(a=a.finally(()=>i.a.flushHistory(e))),s&&s(a)},r=t=>{let n;if(e>0)n=i.a.flushHistory(e,!1,u?!!t.size:void 0);else{if(!t.size)return a(t);n=G.a.delete(-e)}s&&s(n)};let l,c,d,h,u;switch(t){case"channel":G.a.hasRights(-e,"delete_chat")?(G.a.deleteChannel,l="ChannelDeleteMenu",c="AreYouSureDeleteAndExitChannel",h=[{langKey:"ChannelDeleteMenu",isDanger:!0,callback:r}],u=[{text:"DeleteChannelForAll"}]):(l="LeaveChannelMenu",c="ChannelLeaveAlertWithName",d=[n],h=[{langKey:"LeaveChannel",isDanger:!0,callback:a}]);break;case"chat":l="DeleteChatUser",c="AreYouSureDeleteThisChatWithUser",d=[n],h=[{langKey:"DeleteChatUser",isDanger:!0,callback:r}],u=[{text:"DeleteMessagesOptionAlso",textArgs:[new ft.a({peerId:e}).element]}];break;case"saved":l="DeleteChatUser",c="AreYouSureDeleteThisChatSavedMessages",h=[{langKey:"DeleteChatUser",isDanger:!0,callback:r}];break;case"megagroup":case"group":G.a.hasRights(-e,"delete_chat")?(l="DeleteMegaMenu",c="AreYouSureDeleteAndExit",h=[{langKey:"DeleteMegaMenu",isDanger:!0,callback:r}],u=[{text:"DeleteChat.DeleteGroupForAll"}]):(l="LeaveMegaMenu",c="AreYouSureDeleteAndExitName",d=[n],h=[{langKey:"DeleteChatUser",isDanger:!0,callback:e=>a(e,!0)}])}new ht("popup-delete-chat",{peerId:e,titleLangKey:l,descriptionLangKey:c,descriptionLangArgs:d,buttons:h,checkboxes:u}).show()}}var At=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class Ot extends V{_init(){return At(this,void 0,void 0,(function*(){this.listenerSetter.removeAll(),this.scrollable.container.innerHTML="",this.container.classList.add("edit-peer-container","edit-group-container"),this.setTitle("Edit");const e=yield n.default.getChatFull(this.chatId,!0),t=G.a.getChat(this.chatId),s=G.a.isBroadcast(this.chatId),i=G.a.isChannel(this.chatId),o=[],r=e=>{o.push(e)};this.listenerSetter.add(a.default)("chat_update",e=>{this.chatId===e&&o.forEach(e=>e())});{const i=new nn({noDelimiter:!0}),n=[],o=document.createElement("div");if(o.classList.add("input-wrapper"),this.chatNameInputField=new F.b({label:s?"EnterChannelName":"CreateGroup.NameHolder",name:"chat-name",maxLength:255,required:!0}),this.descriptionInputField=new F.b({label:"DescriptionPlaceholder",name:"chat-description",maxLength:255}),this.chatNameInputField.setOriginalValue(t.title),this.descriptionInputField.setOriginalValue(e.about),o.append(this.chatNameInputField.container,this.descriptionInputField.container),n.push(this.chatNameInputField,this.descriptionInputField),this.editPeer=new Xe({peerId:-this.chatId,inputFields:n,listenerSetter:this.listenerSetter}),this.content.append(this.editPeer.nextBtn),i.content.append(this.editPeer.avatarEdit.container,o),G.a.hasRights(this.chatId,"change_type")){const n=new Je({titleLangKey:s?"ChannelType":"GroupType",clickable:()=>{const t=new pt(this.slider);t.chatId=this.chatId,t.chatFull=e,t.open(),this.listenerSetter.add(t.eventListener)("destroy",a)},icon:"lock"}),a=()=>{let e;n.subtitle.textContent="",e=s?t.username?"TypePublic":"TypePrivate":t.username?"TypePublicGroup":"TypePrivateGroup",n.subtitle.append(Object(A.i18n)(e))};a(),i.content.append(n.container)}if(G.a.hasRights(this.chatId,"change_permissions")&&!s){const e=["send_messages","send_media","send_stickers","send_polls","embed_links","invite_users","pin_messages","change_info"],s=new Je({titleLangKey:"ChannelPermissions",clickable:()=>{const e=new Pt(this.slider);e.chatId=this.chatId,e.open()},icon:"permissions"}),n=()=>{s.subtitle.innerHTML=e.reduce((e,s)=>e+ +G.a.hasRights(this.chatId,s,t.default_banned_rights),0)+"/"+e.length};n(),i.content.append(s.container),this.listenerSetter.add(a.default)("chat_update",e=>{this.chatId===e&&n()})}if(this.scrollable.append(i.container),Object(l.b)(this.editPeer.nextBtn,()=>{this.editPeer.nextBtn.disabled=!0;let e=[];const t=this.chatId;this.chatNameInputField.isValid()&&e.push(G.a.editTitle(t,this.chatNameInputField.value)),this.descriptionInputField.isValid()&&e.push(G.a.editAbout(t,this.descriptionInputField.value)),this.editPeer.uploadAvatar&&e.push(this.editPeer.uploadAvatar().then(e=>G.a.editPhoto(t,e))),Promise.race(e).finally(()=>{this.editPeer.nextBtn.removeAttribute("disabled"),this.close()})},{listenerSetter:this.listenerSetter}),s&&G.a.hasRights(this.chatId,"change_info")){const e=new dt.a({text:"PeerInfo.SignMessages",checked:!!t.pFlags.signatures,withRipple:!0});this.listenerSetter.add(e.input)("change",()=>{const t=e.toggleDisability(!0);G.a.toggleSignatures(this.chatId,e.checked).then(()=>{t()})}),r(()=>{e.setValueSilently(!!t.pFlags.signatures)}),i.content.append(e.label)}}if(!s){const t=new nn({});if(!s&&G.a.hasRights(this.chatId,"change_permissions")){const s=new dt.a({text:"ChatHistory",withRipple:!0});this.listenerSetter.add(s.input)("change",()=>{const e=s.toggleDisability(!0);G.a.togglePreHistoryHidden(this.chatId,!s.checked).then(()=>{e()})});const n=()=>{s.setValueSilently(i&&!e.pFlags.hidden_prehistory)};n(),r(n),t.content.append(s.label)}this.scrollable.append(t.container)}if(G.a.hasRights(this.chatId,"delete_chat")){const e=new nn({}),t=Object(U.a)("btn-primary btn-transparent danger",{icon:"delete",text:s?"PeerInfo.DeleteChannel":"DeleteAndExitButton"});Object(l.b)(t,()=>{new xt(-this.chatId,void 0,e=>{const s=Object(ut.a)([t],!0);e.then(()=>{this.close()},()=>{s()})})},{listenerSetter:this.listenerSetter}),e.content.append(t),this.scrollable.append(e.container)}i||this.listenerSetter.add(a.default)("dialog_migrate",({migrateFrom:e,migrateTo:t})=>{-this.chatId===e&&(this.chatId=-t,this._init())})}))}init(){return this._init()}}var _t=s(91);class Ft extends V{init(){this.container.classList.add("edit-peer-container","edit-contact-container");const e=!T.a.isContact(this.peerId);this.setTitle(e?"AddContactTitle":"Edit");{const t=new nn({noDelimiter:!0}),s=[],n=document.createElement("div");if(n.classList.add("input-wrapper"),this.nameInputField=new F.b({label:"FirstName",name:"contact-name",maxLength:70,required:!0}),this.lastNameInputField=new F.b({label:"LastName",name:"contact-lastname",maxLength:70}),this.peerId){const t=T.a.getUser(this.peerId);e?(this.nameInputField.setDraftValue(t.first_name),this.lastNameInputField.setDraftValue(t.last_name)):(this.nameInputField.setOriginalValue(t.first_name),this.lastNameInputField.setOriginalValue(t.last_name))}if(n.append(this.nameInputField.container,this.lastNameInputField.container),s.push(this.nameInputField,this.lastNameInputField),this.editPeer=new Xe({peerId:this.peerId,inputFields:s,listenerSetter:this.listenerSetter,doNotEditAvatar:!0}),this.content.append(this.editPeer.nextBtn),this.peerId){const s=document.createElement("div");s.classList.add("avatar-edit"),s.append(this.editPeer.avatarElem);const r=new dt.a({text:"Notifications"});r.input.addEventListener("change",e=>{e.isTrusted&&i.a.mutePeer(this.peerId)}),this.listenerSetter.add(a.default)("notify_settings",e=>{if("notifyPeer"!==e.peer._)return;const t=o.a.getPeerId(e.peer.peer);if(this.peerId===t){const t=!_t.a.isMuted(e.notify_settings);t!==r.checked&&(r.checked=t)}});const l=document.createElement("div");l.classList.add("profile-name"),l.append(new ft.a({peerId:this.peerId}).element);const c=document.createElement("div");if(c.classList.add("profile-subtitle"),c.append(Object(A.i18n)("EditContact.OriginalName")),t.content.append(s,l,c,n),e){const e=T.a.getUser(this.peerId),s=new Je({icon:"phone",titleLangKey:e.phone?void 0:"MobileHidden",title:e.phone?T.a.formatUserPhone(e.phone):void 0,subtitleLangKey:e.phone?"Phone":"MobileHiddenExceptionInfo",subtitleLangArgs:e.phone?void 0:[new ft.a({peerId:this.peerId}).element]});t.content.append(s.container)}else{const e=new Je({checkboxField:r}),s=!_t.a.isPeerLocalMuted(this.peerId,!1);r.checked=s,t.content.append(e.container)}}else t.content.append(n);this.scrollable.append(t.container),Object(l.b)(this.editPeer.nextBtn,()=>{this.editPeer.nextBtn.disabled=!0,T.a.addContact(this.peerId,this.nameInputField.value,this.lastNameInputField.value,T.a.getUser(this.peerId).phone).finally(()=>{this.editPeer.nextBtn.removeAttribute("disabled"),this.close()})},{listenerSetter:this.listenerSetter})}if(!e){const e=new nn({}),t=Object(U.a)("btn-primary btn-transparent danger",{icon:"delete",text:"PeerInfo.DeleteContact"});Object(l.b)(t,()=>{new ht("popup-delete-contact",{peerId:this.peerId,titleLangKey:"DeleteContact",descriptionLangKey:"AreYouSureDeleteContact",buttons:Object(ct.a)([{langKey:"Delete",callback:()=>{const e=Object(ut.a)([t],!0);T.a.deleteContacts([this.peerId]).then(()=>{this.close()},()=>{e()})},isDanger:!0}])}).show()},{listenerSetter:this.listenerSetter}),e.content.append(t),this.scrollable.append(e.container)}}}class jt extends V{init(){this.nextBtn=$({icon:"arrow_next"}),this.content.append(this.nextBtn),this.scrollable.container.remove(),this.nextBtn.addEventListener("click",()=>{const e=this.selector.getSelected();if(this.skippable)this.takeOut(e),this.close();else{const t=this.takeOut(e);t instanceof Promise?this.attachToPromise(t):void 0===t&&this.close()}})}attachToPromise(e){const t=Object(se.g)(this.nextBtn,"arrow_next");e.then(()=>{this.close()},()=>{t()})}open(e){const t=super.open();return this.setTitle(e.title),this.peerType=e.type,this.takeOut=e.takeOut,this.skippable=e.skippable,this.selector=new Et({appendTo:this.content,onChange:this.skippable?null:e=>{this.nextBtn.classList.toggle("is-visible",!!e)},peerType:["contacts"],placeholder:e.placeholder}),e.selectedPeerIds&&this.selector.addInitial(e.selectedPeerIds),this.nextBtn.classList.add("tgico-arrow_next"),this.nextBtn.innerHTML="",this.nextBtn.disabled=!1,this.nextBtn.classList.toggle("is-visible",this.skippable),t}}var Dt=!h.IS_FIREFOX&&!1;function Bt(){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttributeNS(null,"viewBox","0 0 24 24"),e.setAttributeNS(null,"width","24"),e.setAttributeNS(null,"height","24"),e.classList.add("verified-icon");const t=document.createElementNS("http://www.w3.org/2000/svg","use");t.setAttributeNS(null,"href","#verified-background"),t.classList.add("verified-background");const s=document.createElementNS("http://www.w3.org/2000/svg","use");return s.setAttributeNS(null,"href","#verified-check"),s.classList.add("verified-check"),e.append(t,s),e}var Rt=s(86);const Ht=e=>e.touches?e.touches[0]:e,Ut=window;let Nt=!1;a.default.addEventListener("context_menu_toggle",e=>{Nt=e});class zt{constructor(e){this.cursor="grabbing",this.cancelEvent=!0,this.hadMove=!1,this.xDown=null,this.yDown=null,this.reset=e=>{pe.IS_TOUCH_SUPPORTED?Ut.removeEventListener("touchmove",this.handleMove,{capture:!0}):(Ut.removeEventListener("mousemove",this.handleMove),this.element.style.cursor=""),this.onReset&&this.hadMove&&this.onReset(),this.xDown=this.yDown=null,this.hadMove=!1},this.handleStart=e=>{const t=Ht(e);if(this.verifyTouchTarget&&!this.verifyTouchTarget(e))return this.reset();this.xDown=t.clientX,this.yDown=t.clientY,pe.IS_TOUCH_SUPPORTED?Ut.addEventListener("touchmove",this.handleMove,{passive:!1,capture:!0}):Ut.addEventListener("mousemove",this.handleMove,!1)},this.handleMove=e=>{if(null===this.xDown||null===this.yDown||Nt)return void this.reset();this.cancelEvent&&Object(c.a)(e);const t=Ht(e),s=t.clientX,i=t.clientY,n=this.xDown-s,a=this.yDown-i;if(!this.hadMove){if(!n&&!a)return;this.hadMove=!0,pe.IS_TOUCH_SUPPORTED||this.element.style.setProperty("cursor",this.cursor,"important"),this.onFirstSwipe&&this.onFirstSwipe()}const o=this.onSwipe(n,a,e);void 0!==o&&o&&this.reset()},Object(L.g)(this,e),this.setListeners()}setListeners(){pe.IS_TOUCH_SUPPORTED?(this.element.addEventListener("touchstart",this.handleStart,!1),Ut.addEventListener("touchend",this.reset)):(this.element.addEventListener("mousedown",this.handleStart,!1),Ut.addEventListener("mouseup",this.reset))}removeListeners(){pe.IS_TOUCH_SUPPORTED?(this.element.removeEventListener("touchstart",this.handleStart,!1),Ut.removeEventListener("touchend",this.reset)):(this.element.removeEventListener("mousedown",this.handleStart,!1),Ut.removeEventListener("mouseup",this.reset))}}var Vt=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class Wt{constructor(e){this.scrollable=e,this.processItem=e=>{const t=document.createElement("div");let s;t.classList.add(Wt.BASE_CLASS+"-avatar"),e&&(s="string"==typeof e?r.a.getPhoto(e):e.action.photo);const i=new Image;if(i.classList.add(Wt.BASE_CLASS+"-avatar-image"),i.draggable=!1,s){const e=r.a.choosePhotoSize(s,420,420,!1);r.a.preloadPhoto(s,e).then(()=>{const n=he.a.getCacheContext(s,e.type);Object(Rt.a)(i,n.url,()=>{t.append(i)})})}else{const e=o.a.getPeerPhoto(this.peerId);d.a.putAvatar(t,this.peerId,e,"photo_big",i)}return this.avatars.append(t),this.addTab(),e},this.container=document.createElement("div"),this.container.classList.add(Wt.BASE_CLASS+"-container"),this.avatars=document.createElement("div"),this.avatars.classList.add(Wt.BASE_CLASS+"-avatars"),this.gradient=document.createElement("div"),this.gradient.classList.add(Wt.BASE_CLASS+"-gradient"),this.info=document.createElement("div"),this.info.classList.add(Wt.BASE_CLASS+"-info"),this.tabs=document.createElement("div"),this.tabs.classList.add(Wt.BASE_CLASS+"-tabs"),this.arrowPrevious=document.createElement("div"),this.arrowPrevious.classList.add(Wt.BASE_CLASS+"-arrow"),this.arrowNext=document.createElement("div"),this.arrowNext.classList.add(Wt.BASE_CLASS+"-arrow",Wt.BASE_CLASS+"-arrow-next"),this.container.append(this.avatars,this.gradient,this.info,this.tabs,this.arrowPrevious,this.arrowNext);const t=()=>0===this.scrollable.scrollTop||(this.scrollable.scrollIntoViewNew(this.scrollable.container.firstElementChild,"start"),!1);let s=!1,i=!1;Object(l.b)(this.container,e=>Vt(this,void 0,void 0,(function*(){if(i)return void Object(c.a)(e);if(s)return void(s=!1);if(!t())return;const n=this.container.getBoundingClientRect(),a=e.pageX,o=a-n.left;if(!this.listLoader.previous.length&&!this.listLoader.next.length||o>n.width*(1/3)&&o<n.width-n.width*(1/3)){const e=this.peerId,t=[];this.listLoader.previous.concat(this.listLoader.current,this.listLoader.next).forEach((e,s)=>{t.push({element:this.avatars.children[s],item:e})});const s=t.slice(0,this.listLoader.previous.length),n=t.slice(this.listLoader.previous.length+1),a=this.avatars.children[this.listLoader.previous.length];i=!0,Mo(a,e,()=>e===this.peerId,this.listLoader.current,s,n),i=!1}else{const e=a>n.right-n.width/2;let t;this.avatars.classList.add("no-transition"),this.avatars.offsetLeft,t=0!==this.listLoader.index||e?this.listLoader.index===this.listLoader.count-1&&e?-(this.listLoader.count-1):e?1:-1:this.listLoader.count-1,this.listLoader.go(t),Object(_e.b)(()=>{this.avatars.classList.remove("no-transition")})}})));const n=()=>{s=!0,document.body.addEventListener(pe.IS_TOUCH_SUPPORTED?"touchend":"click",e=>{s=!1},{once:!0})};let a=0,h=0,u=0,p=0;new zt({element:this.avatars,onSwipe:(e,t)=>{u=e;let s=h+e*-Wt.SCALE;return s>0?s=0:s<p&&(s=p),this.avatars.style.transform=Wt.TRANSLATE_TEMPLATE.replace("{x}",s+"px"),!1},verifyTouchTarget:e=>t()?!this.container.classList.contains("is-single")&&!i:(n(),Object(c.a)(e),!1),onFirstSwipe:()=>{const e=this.avatars.getBoundingClientRect();a=e.width,p=-a*(this.tabs.childElementCount-1),h=e.left-this.container.getBoundingClientRect().left,this.avatars.style.transform=Wt.TRANSLATE_TEMPLATE.replace("{x}",h+"px"),this.container.classList.add("is-swiping"),this.avatars.classList.add("no-transition"),this.avatars.offsetLeft},onReset:()=>{const e=Math.ceil(Math.abs(u)/(a/Wt.SCALE))*(u>=0?1:-1);n(),this.avatars.classList.remove("no-transition"),Object(_e.b)(()=>{this.listLoader.go(e),this.container.classList.remove("is-swiping")})}})}setPeer(e){this.peerId=e;const t=o.a.getPeerPhoto(e);if(!t)return;const s=this.listLoader=new S({loadCount:50,loadMore:(t,a,o)=>{if(!a)return Promise.resolve({count:void 0,items:[]});if(e>0){const i=t||s.current;return r.a.getUserPhotos(e,i,o).then(e=>({count:e.count,items:e.photos}))}{const t=[];return s.current||t.push(n.default.getChatFull(-e)),t.push(i.a.getSearch({peerId:e,maxId:Number.MAX_SAFE_INTEGER,inputFilter:{_:"inputMessagesFilterChatPhotos"},limit:o,backLimit:0})),Promise.all(t).then(e=>{const t=e.pop();if(w(t),!s.current){const n=e[0],a=t.history.findAndSplice(e=>e.action.photo.id===n.chat_photo.id);s.current=a||i.a.generateFakeAvatarMessage(this.peerId,n.chat_photo)}return{count:t.count,items:t.history}})}},processItem:this.processItem,onJump:(e,t)=>{const s=this.listLoader.index,i=100*Wt.SCALE*s;this.avatars.style.transform=Wt.TRANSLATE_TEMPLATE.replace("{x}",`-${i}%`);const n=this.tabs.querySelector(".active");n&&n.classList.remove("active");this.tabs.children[s].classList.add("active")}});"userProfilePhoto"===t._&&(s.current=t.photo_id),this.processItem(s.current),s.load(!0)}addTab(){const e=document.createElement("div");e.classList.add(Wt.BASE_CLASS+"-tab"),this.tabs.append(e),1===this.tabs.childElementCount&&e.classList.add("active"),this.container.classList.toggle("is-single",this.tabs.childElementCount<=1)}}Wt.BASE_CLASS="profile-avatars",Wt.SCALE=Dt?2:1,Wt.TRANSLATE_TEMPLATE=Dt?`translate3d({x}, 0, -1px) scale(${Wt.SCALE})`:"translate({x}, 0)";let Kt=(e,t)=>{t.title.innerHTML=e,t.container.style.display=""};class Gt{constructor(e){this.scrollable=e,this.peerId=0,this.setPeerStatus=(e=!1)=>{if(!this.peerId)return;const t=this.peerId;mo.setPeerStatus(this.peerId,this.subtitle,e,!0,()=>t===this.peerId)},Dt||this.scrollable.container.classList.add("no-parallax")}init(){this.init=null,this.element=document.createElement("div"),this.element.classList.add("profile-content"),this.section=new nn({noDelimiter:!0}),this.avatar=new ko,this.avatar.classList.add("profile-avatar","avatar-120"),this.avatar.setAttribute("dialog","1"),this.avatar.setAttribute("clickable",""),this.name=document.createElement("div"),this.name.classList.add("profile-name"),this.subtitle=document.createElement("div"),this.subtitle.classList.add("profile-subtitle"),this.bio=new Je({title:" ",subtitleLangKey:"UserBio",icon:"info",clickable:e=>{"A"!==e.target.tagName&&n.default.getProfileByPeerId(this.peerId).then(e=>{et(e.about),nt(A.default.format("BioCopied",!0))})}}),this.bio.title.classList.add("pre-wrap"),this.username=new Je({title:" ",subtitleLangKey:"Username",icon:"username",clickable:()=>{et("@"+o.a.getPeer(this.peerId).username),nt(A.default.format("UsernameCopied",!0))}}),this.phone=new Je({title:" ",subtitleLangKey:"Phone",icon:"phone",clickable:()=>{et("+"+T.a.getUser(this.peerId).phone),nt(A.default.format("PhoneCopied",!0))}}),this.notifications=new Je({checkboxField:new dt.a({toggle:!0}),titleLangKey:"Notifications",icon:"unmute"}),this.section.content.append(this.phone.container,this.username.container,this.bio.container,this.notifications.container),this.element.append(this.section.container,on()),this.notifications.checkboxField.input.addEventListener("change",e=>{e.isTrusted&&i.a.mutePeer(this.peerId)}),a.default.addEventListener("dialog_notify_settings",e=>{if(this.peerId===e.peerId){const e=_t.a.isPeerLocalMuted(this.peerId,!1);this.notifications.checkboxField.checked=!e}}),a.default.addEventListener("peer_typings",({peerId:e})=>{this.peerId===e&&this.setPeerStatus()}),a.default.addEventListener("peer_bio_edit",e=>{e===this.peerId&&this.setBio(!0)}),a.default.addEventListener("user_update",e=>{this.peerId===e&&this.setPeerStatus()}),a.default.addEventListener("contacts_update",e=>{if(this.peerId===e){const t=T.a.getUser(e);t.pFlags.self||(t.phone?Kt(T.a.formatUserPhone(t.phone),this.phone):this.phone.container.style.display="none")}}),this.setPeerStatusInterval=window.setInterval(this.setPeerStatus,6e4)}cleanupHTML(){this.bio.container.style.display="none",this.phone.container.style.display="none",this.username.container.style.display="none",this.notifications.container.style.display="",this.notifications.checkboxField.checked=!0,this.setBioTimeout&&(window.clearTimeout(this.setBioTimeout),this.setBioTimeout=0)}setAvatar(){if(this.peerId!==a.default.myId){if(o.a.getPeerPhoto(this.peerId)){const e=this.avatars;return this.avatars=new Wt(this.scrollable),this.avatars.setPeer(this.peerId),this.avatars.info.append(this.name,this.subtitle),this.avatar.remove(),e?e.container.replaceWith(this.avatars.container):this.element.prepend(this.avatars.container),void(Dt&&this.scrollable.container.classList.add("parallax"))}}Dt&&this.scrollable.container.classList.remove("parallax"),this.avatars&&(this.avatars.container.remove(),this.avatars=void 0),this.avatar.setAttribute("peer",""+this.peerId),this.section.content.prepend(this.avatar,this.name,this.subtitle)}fillProfileElements(){var e;if(!this.cleaned)return;this.cleaned=!1;const t=this.peerId;if(this.cleanupHTML(),this.setAvatar(),t!==a.default.myId){o.a.getPeerUsername(t)&&Kt(o.a.getPeerUsername(t),this.username);const e=_t.a.isPeerLocalMuted(t,!1);this.notifications.checkboxField.checked=!e}else Object(_e.b)(()=>{this.notifications.container.style.display="none"});if(t>0){let e=T.a.getUser(t);e.phone&&t!==a.default.myId&&Kt(T.a.formatUserPhone(e.phone),this.phone)}this.setBio(),Object(x.a)(this.name,new ft.a({peerId:t,dialog:!0}).element);const s=o.a.getPeer(t);(null===(e=null==s?void 0:s.pFlags)||void 0===e?void 0:e.verified)&&this.name.append(Bt()),this.setPeerStatus(!0)}setBio(e){this.setBioTimeout&&(window.clearTimeout(this.setBioTimeout),this.setBioTimeout=0);const t=this.peerId,s=this.threadId;if(!t)return;let i;i=t>0?n.default.getProfile(t,e).then(e=>this.peerId===t&&this.threadId===s&&(e.rAbout&&t!==a.default.myId&&Kt(e.rAbout,this.bio),!0)):n.default.getChatFull(-t,e).then(e=>this.peerId===t&&this.threadId===s&&(e.about&&Kt(Z.b.wrapRichText(e.about),this.bio),!0)),i.then(e=>{e&&(this.setBioTimeout=window.setTimeout(()=>this.setBio(!0),6e4))})}setPeer(e,t=0){this.peerId===e&&this.threadId===e||(this.init&&this.init(),this.peerId=e,this.threadId=t,this.cleaned=!0)}}class qt extends V{constructor(e){super(e,!1),this.peerId=0,this.threadId=0,this.historiesStorage={}}init(){this.container.classList.add("shared-media-container","profile-container");const e=Object(U.a)("btn-icon sidebar-close-button",{noRipple:!0});this.closeBtn.replaceWith(e),this.closeBtn=e;const t=document.createElement("div");t.classList.add("animated-close-icon"),e.append(t);const s=document.createElement("div");s.className="transition slide-fade";const i=document.createElement("div");i.classList.add("transition-item"),this.title.append(Object(A.i18n)("Profile")),this.editBtn=N("edit"),i.append(this.title,this.editBtn);const n=document.createElement("div");n.classList.add("transition-item");const o=this.title.cloneNode();o.append(Object(A.i18n)("PeerInfo.SharedMedia")),n.append(o),s.append(i,n),this.header.append(s),this.profile=new Gt(this.scrollable),this.profile.init(),this.scrollable.append(this.profile.element);this.scrollable.onAdditionalScroll=()=>{const e=this.searchSuper.nav.getBoundingClientRect();if(!e.width)return;const s=e.top-1<=56;t.classList.toggle("state-back",s),this.searchSuper.container.classList.toggle("is-full-viewport",s),r(+s),s||this.searchSuper.cleanScrollPositions()};const r=Object(D.a)(s,"slide-fade",400,null,!1);r(0),Object(l.b)(this.closeBtn,e=>{this.closeBtn.firstElementChild.classList.contains("state-back")?(this.scrollable.scrollIntoViewNew(this.scrollable.container.firstElementChild,"start"),r(0),t.classList.remove("state-back")):this.scrollable.isHeavyAnimationInProgress||this.slider.onCloseBtnClick()}),Object(l.b)(this.editBtn,e=>{let t;t=this.peerId<0?new Ot(this.slider):new Ft(this.slider),t&&(t instanceof Ot?t.chatId=-this.peerId:t.peerId=this.peerId,t.open())}),a.default.addEventListener("contacts_update",e=>{this.peerId===e&&this.toggleEditBtn()}),a.default.addEventListener("chat_update",e=>{this.peerId===-e&&this.toggleEditBtn()}),a.default.addEventListener("history_multiappend",e=>{for(const t in e)this.renderNewMessages(+t,Array.from(e[t]))}),a.default.addEventListener("history_delete",({peerId:e,msgs:t})=>{this.deleteDeletedMessages(e,Array.from(t))}),a.default.addEventListener("message_sent",({message:e})=>{this.renderNewMessages(e.peerId,[e.mid])}),this.searchSuper=new $s({mediaTabs:[{inputFilter:"inputMessagesFilterEmpty",name:"PeerMedia.Members",type:"members"},{inputFilter:"inputMessagesFilterPhotoVideo",name:"SharedMediaTab2",type:"media"},{inputFilter:"inputMessagesFilterDocument",name:"SharedFilesTab2",type:"files"},{inputFilter:"inputMessagesFilterUrl",name:"SharedLinksTab2",type:"links"},{inputFilter:"inputMessagesFilterMusic",name:"SharedMusicTab2",type:"music"},{inputFilter:"inputMessagesFilterRoundVoice",name:"SharedVoiceTab2",type:"voice"}],scrollable:this.scrollable,onChangeTab:e=>{let t="members"===e.type&&a.default.settings.animationsEnabled?250:0;setTimeout(()=>{c.classList.toggle("is-hidden","members"!==e.type)},t)}}),this.profile.element.append(this.searchSuper.container);const c=$({icon:"addmember_filled"});this.content.append(c),c.addEventListener("click",()=>{const e=-this.peerId,t=G.a.isChannel(e),s=(s,i)=>{let n,a,o,r,l;if(s.length>1)n="AddMembersAlertTitle",a=[Object(A.i18n)("Members",[s.length])],o="AddMembersAlertCountText",r=s.map(e=>{const t=document.createElement("b");return t.append(new ft.a({peerId:e}).element),t}),t||(l=[{text:"AddMembersForwardMessages",checked:!0}]);else{n="AddOneMemberAlertTitle",o="AddMembersAlertNamesText";const e=document.createElement("b");e.append(new ft.a({peerId:s[0]}).element),r=[e],t||(l=[{text:"AddOneMemberForwardMessages",textArgs:[new ft.a({peerId:s[0]}).element],checked:!0}])}r.push(new ft.a({peerId:-e}).element),new ht("popup-add-members",{peerId:-e,titleLangKey:n,descriptionLangKey:o,descriptionLangArgs:r,buttons:[{langKey:"Add",callback:i}],checkboxes:l}).show()},i=e=>{"USER_PRIVACY_RESTRICTED"===e.type&&at({langPackKey:"InviteToGroupError"})};if(t){const t=new jt(this.slider);t.open({peerId:this.peerId,type:"channel",skippable:!1,takeOut:n=>(s(n,()=>{const s=G.a.inviteToChannel(e,n);s.catch(i),t.attachToPromise(s)}),!1),title:"GroupAddMembers",placeholder:"SendMessageTo"})}else new It({peerTypes:["contacts"],placeholder:"Search",onSelect:t=>{setTimeout(()=>{s([t],s=>{G.a.addChatUser(e,t,s.size?void 0:0).catch(i)})},0)}})})}renderNewMessages(e,t){if(!this.init&&this.historiesStorage[e]){t=t.slice().reverse();for(const s of this.searchSuper.mediaTabs){const n=s.inputFilter,a=this.searchSuper.filterMessagesByType(t.map(t=>i.a.getMessageByPeer(e,t)),n);if(a.length){const t=this.historiesStorage[e][n];t&&t.unshift(...a.map(e=>({mid:e.mid,peerId:e.peerId}))),this.peerId===e&&-1!==this.searchSuper.usedFromHistory[n]&&(this.searchSuper.usedFromHistory[n]+=a.length,this.searchSuper.performSearchResult(a,s,!1))}}}}deleteDeletedMessages(e,t){if(!this.init&&this.historiesStorage[e]){for(const s of t)for(const t of this.searchSuper.mediaTabs){const i=t.inputFilter,n=this.historiesStorage[e][i];if(!n)continue;const a=n.findIndex(e=>e.mid===s);if(-1!==a){if(n.splice(a,1),this.peerId===e){const t=this.searchSuper.tabs[i].querySelector(`div[data-mid="${s}"][data-peer-id="${e}"]`);t&&(this.searchSuper.selection.isSelecting&&this.searchSuper.selection.toggleByElement(t),t.remove()),this.searchSuper.usedFromHistory[i]>=a+1&&this.searchSuper.usedFromHistory[i]--}break}}this.scrollable.onScroll()}}cleanupHTML(){this.profile.cleanupHTML(),this.editBtn.classList.add("hide"),this.searchSuper.cleanupHTML(!0),this.container.classList.toggle("can-add-members",this.searchSuper.canViewMembers()&&G.a.hasRights(-this.peerId,"invite_users"))}setLoadMutex(e){this.searchSuper.loadMutex=e}setPeer(e,t=0){var s;return(this.peerId!==e||this.threadId!==t)&&(this.peerId=e,this.threadId=t,this.peerChanged=!0,this.init&&(this.init(),this.init=null),this.searchSuper.setQuery({peerId:e,historyStorage:null!==(s=this.historiesStorage[e])&&void 0!==s?s:this.historiesStorage[e]={}}),this.profile.setPeer(e,t),!0)}fillProfileElements(){this.peerChanged&&(this.peerChanged=!1,this.cleanupHTML(),this.profile.fillProfileElements(),this.toggleEditBtn())}toggleEditBtn(){let e;e=this.peerId>0?this.peerId!==a.default.myId&&T.a.isContact(this.peerId):G.a.hasRights(-this.peerId,"change_info"),this.editBtn.classList.toggle("hide",!e)}loadSidebarMedia(e,t=!1){this.searchSuper.load(e,t)}onOpenAfterTimeout(){this.scrollable.onScroll()}}const Qt=new class extends K{constructor(){super({sidebarEl:document.getElementById("column-right"),canHideFirst:!0,navigationType:"right"}),this.isColumnProportionSet=!1,v.b.addEventListener("changeScreen",(e,t)=>{t===v.a.medium&&e!==v.a.mobile&&this.toggleSidebar(!1)}),v.b.addEventListener("resize",()=>{this.setColumnProportion()}),this.sharedMediaTab=new qt(this)}onCloseTab(e,t,s){this.historyTabIds.length||this.toggleSidebar(!1,t),super.onCloseTab(e,t,s)}setColumnProportion(){const e=this.sidebarEl.scrollWidth/this.sidebarEl.previousElementSibling.scrollWidth;document.documentElement.style.setProperty("--right-column-proportion",""+e)}toggleSidebar(e,t){const s=document.body.classList.contains("is-right-column-shown");let i;if(void 0!==e?e?s||(i=!0):s&&(i=!0):i=!0,!i)return Promise.resolve();s||this.historyTabIds.length||this.sharedMediaTab.open(),this.isColumnProportionSet||(this.setColumnProportion(),this.isColumnProportionSet=!0);const n=mo.selectTab(s?1:2,t);return document.body.classList.toggle("is-right-column-shown",e),n}};de.a.appSidebarRight=Qt;var $t=Qt;class Yt extends V{init(){this.container.id="poll-results-container",this.container.classList.add("chatlist-container"),this.resultsDiv=document.createElement("div"),this.resultsDiv.classList.add("poll-results"),this.scrollable.append(this.resultsDiv)}open(e){const t=super.open(),s=$e.a.getPoll(e.media.poll.id);this.setTitle(s.poll.pFlags.quiz?"PollResults.Title.Quiz":"PollResults.Title.Poll");const i=document.createElement("h3");i.innerHTML=s.poll.rQuestion;const n=s.results.results.map(e=>e.voters/s.results.total_voters*100);Zt(n);const a=document.createDocumentFragment();return s.results.results.forEach((t,i)=>{if(!t.voters)return;const o=document.createElement("hr"),r=s.poll.answers[i],l=document.createElement("div");l.classList.add("poll-results-answer");const c=document.createElement("div");c.innerHTML=Z.a.wrapEmojiText(r.text);const d=document.createElement("div");d.innerText=Math.round(n[i])+"%",l.append(c,d);const h=Do.createChatList();h.classList.add("poll-results-voters"),Do.setListClickListener(h,()=>{$t.onCloseBtnClick()},void 0,!0),h.style.minHeight=50*Math.min(t.voters,4)+"px",a.append(o,l,h);let u,p=4,m=!1,g=t.voters-4;const b=()=>{m||(m=!0,$e.a.getVotes(e,r.option,u,p).then(e=>{e.votes.forEach(e=>{const{dom:t}=Do.addDialogNew({dialog:e.user_id,container:h,drawStatus:!1,rippleEnabled:!1,meAsSaved:!1,avatarSize:32});t.lastMessageSpan.parentElement.remove()}),u&&(g-=e.votes.length,v.lastElementChild.replaceWith(Object(A.i18n)("PollResults.LoadMore",[Math.min(20,g)]))),u=e.next_offset,p=20,g&&e.votes.length||v.remove()}).finally(()=>{m=!1}))};if(b(),g<=0)return;const v=document.createElement("div");v.classList.add("poll-results-more","show-more","rp-overflow"),v.addEventListener("click",b),Object(ie.ripple)(v);const f=document.createElement("div");f.classList.add("tgico-down"),v.append(f,Object(A.i18n)("PollResults.LoadMore",[Math.min(20,g)])),a.append(v)}),this.resultsDiv.append(i,a),$t.toggleSidebar(!0).then(()=>{}),t}}var Xt=s(85);let Jt=0;const Zt=e=>{const t=e.reduce((e,t)=>e+Math.round(t),0);if(t>100){const s=t-100,i=e.length;for(let t=0;t<s;++t){let t=-1,s=1;for(let n=0;n<i;++n){let i=e[n]%1;i>=.5&&i<s&&(s=i,t=n)}if(-1===t)return;e[t]-=s}}else if(t<100){const s=100-t,i=e.length;for(let t=0;t<s;++t){let t=-1,s=0;for(let n=0;n<i;++n){let i=e[n]%1;i<.5&&i>s&&(s=i,t=n)}if(-1===t)return;e[t]+=1-s}}};a.default.addEventListener("poll_update",e=>{const{poll:t,results:s}=e;Array.from(document.querySelectorAll(`poll-element[poll-id="${t.id}"]`)).forEach(e=>{e.isClosed=!!t.pFlags.closed,e.performResults(s,t.chosenIndexes)})}),a.default.addEventListener("peer_changed",()=>{ts&&es(ts,ss,is)}),v.b.addEventListener("resize",()=>{ns.setMaxLength(),ns.resizePolls()}),v.b.addEventListener("changeScreen",()=>{ns.setMaxLength()});const es=(e,t,s)=>{e.classList.remove("active"),clearTimeout(s),setTimeout(()=>{t(),e.remove(),ts===e&&ss===t&&is===s&&(ts=ss=null,is=0)},200)};let ts,ss,is;class ns extends HTMLElement{constructor(){super(),this.isClosed=!1,this.isQuiz=!1,this.isRetracted=!1,this.isPublic=!1,this.isMultiple=!1,this.chosenIndexes=[],this.chosingIndexes=[],this.sentVote=!1}static setMaxLength(){const e=yt.a.windowW<=360?yt.a.windowW-120:v.b.active.poll.width;this.MAX_LENGTH=e+9+this.MAX_OFFSET+-13.7}static resizePolls(){if(!this.MAX_LENGTH)return;Array.from(document.querySelectorAll("poll-element.is-voted")).forEach(e=>{e.svgLines.forEach((t,s)=>{e.setLineProgress(s,1)})})}render(){Jt||(Jt=document.getElementById("poll-line").getTotalLength(),ns.setMaxLength());const e=this.message.media.poll.id,{poll:t,results:s}=$e.a.getPoll(e);let i;this.message.pFlags.is_scheduled&&this.classList.add("disable-hover"),t.pFlags&&(this.isPublic=!!t.pFlags.public_voters,this.isQuiz=!!t.pFlags.quiz,this.isClosed=!!t.pFlags.closed,this.isMultiple=!!t.pFlags.multiple_choice,this.isClosed?(i="Chat.Poll.Type.Closed",this.classList.add("is-closed")):i=this.isQuiz?this.isPublic?"Chat.Poll.Type.Quiz":"Chat.Poll.Type.AnonymousQuiz":this.isPublic?"Chat.Poll.Type.Public":"Chat.Poll.Type.Anonymous"),this.classList.toggle("is-multiple",this.isMultiple);const n=this.isMultiple?'<span class="poll-answer-selected tgico-check"></span>':"",a=t.answers.map((e,t)=>`\n <div class="poll-answer" data-index="${t}">\n <div class="circle-hover">\n <div class="animation-ring"></div>\n <svg class="progress-ring">\n <circle class="progress-ring__circle" cx="13" cy="13" r="9"></circle>\n </svg>\n ${n}\n </div>\n <div class="poll-answer-percents"></div>\n <div class="poll-answer-text">${Z.a.wrapEmojiText(e.text)}</div>\n <svg version="1.1" class="poll-line" style="display: none;" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 485.9 35" xml:space="preserve">\n <use href="#poll-line"></use>\n </svg>\n <span class="poll-answer-selected tgico"></span>\n </div>\n `).join("");if(this.innerHTML=`\n <div class="poll-title">${t.rQuestion}</div>\n <div class="poll-desc">\n <div class="poll-type"></div>\n <div class="poll-avatars"></div>\n </div>\n ${a}`,this.descDiv=this.firstElementChild.nextElementSibling,this.typeDiv=this.descDiv.firstElementChild,this.avatarsDiv=this.descDiv.lastElementChild,i&&this.typeDiv.append(Object(A.i18n)(i)),this.isQuiz&&(this.classList.add("is-quiz"),t.close_period&&t.close_date)){const e=document.createElement("div");e.classList.add("poll-time"),this.descDiv.append(e);const s=document.createElementNS("http://www.w3.org/2000/svg","svg");s.classList.add("poll-quiz-timer"),this.quizTimer=s;const i=2,n=7,a=2*Math.PI*n,o=document.createElementNS("http://www.w3.org/2000/svg","circle");o.classList.add("poll-quiz-timer-circle"),o.setAttributeNS(null,"cx","16"),o.setAttributeNS(null,"cy","16"),o.setAttributeNS(null,"r",""+n),o.setAttributeNS(null,"stroke-width",""+i),s.append(o),this.descDiv.append(s);const r=1e3*t.close_period,l=1e3*(t.close_date-Ye.a.serverTimeOffset);this.quizInterval=window.setInterval(()=>{const t=Date.now(),s=(l-t)/r,i=(l-t)/1e3+1|0;e.innerHTML=String(i).toHHMMSS(),i<=5&&(e.style.color="#ee545c",o.style.stroke="#ee545c"),o.style.strokeDashoffset=a+s*a,o.style.strokeDasharray=`${a} ${a}`,t>=l&&(clearInterval(this.quizInterval),e.innerHTML="",o.style.strokeDashoffset=a,this.quizInterval=0,setTimeout(()=>{$e.a.getResults(this.message)},3e3))},1e3)}this.answerDivs=Array.from(this.querySelectorAll(".poll-answer")),this.svgLines=Array.from(this.querySelectorAll(".poll-line")),this.numberDivs=Array.from(this.querySelectorAll(".poll-answer-percents"));const o=document.createElement("div");o.classList.add("poll-footer"),this.viewResults=document.createElement("div"),this.viewResults.className="poll-footer-button poll-view-results hide",this.viewResults.append(Object(A.i18n)("Chat.Poll.ViewResults")),this.votersCountDiv=document.createElement("div"),this.votersCountDiv.className="poll-votes-count",o.append(this.viewResults,this.votersCountDiv),this.append(o),this.viewResults.addEventListener("click",e=>{Object(c.a)(e),$t.isTabExists(Yt)||new Yt($t).open(this.message)}),Object(ie.ripple)(this.viewResults),this.isMultiple&&(this.sendVoteBtn=document.createElement("div"),this.sendVoteBtn.classList.add("poll-footer-button","poll-send-vote"),this.sendVoteBtn.append(Object(A.i18n)("Chat.Poll.SubmitVote")),Object(ie.ripple)(this.sendVoteBtn),t.chosenIndexes.length||this.votersCountDiv.classList.add("hide"),Object(l.b)(this.sendVoteBtn,e=>{Object(c.a)(e),this.chosingIndexes.length&&this.sendVotes(this.chosingIndexes).then(()=>{this.chosingIndexes.length=0,this.answerDivs.forEach(e=>{e.classList.remove("is-chosing")})})}),o.append(this.sendVoteBtn));const r=!(t.chosenIndexes.length||this.isClosed);r&&!this.isPublic||this.performResults(s,t.chosenIndexes,!1),r&&(this.setVotersCount(s),Object(l.b)(this,this.clickHandler))}initQuizHint(e){if(e.solution&&e.solution_entities){const t=document.createElement("div");if(t.classList.add("tgico-tip","poll-hint"),this.descDiv.append(t),Object(l.b)(t,s=>{Object(c.a)(s),t.classList.add("active"),((e,t,s)=>{ts&&es(ts,ss,is);const i=document.createElement("div");i.classList.add("quiz-hint");const n=document.createElement("div");n.classList.add("container","tgico");const a=document.createElement("div");a.classList.add("text"),n.append(a),i.append(n),a.innerHTML=Z.a.wrapRichText(e,{entities:t}),mo.chat.bubbles.bubblesContainer.append(i),i.offsetLeft,i.classList.add("active"),ts=i,ss=s,is=window.setTimeout(()=>{es(i,s,is)},pe.IS_TOUCH_SUPPORTED?5e3:7e3)})(e.solution,e.solution_entities,()=>{t.classList.remove("active")})}),this.sentVote){const s=e.results.find(e=>e.pFlags.correct);s&&!s.pFlags.chosen&&t.click()}}}clickHandler(e){const t=Object(Ce.a)(e.target,"poll-answer");if(!t)return;Object(c.a)(e);const s=+t.dataset.index;if(this.isMultiple){t.classList.toggle("is-chosing");const e=this.chosingIndexes.indexOf(s);-1!==e?this.chosingIndexes.splice(e,1):this.chosingIndexes.push(s)}else this.sendVotes([s])}sendVotes(e){if(this.sendVotePromise)return this.sendVotePromise;const t=this.answerDivs.filter((t,s)=>e.includes(s));return t.forEach(e=>{e.classList.add("is-voting")}),this.classList.add("disable-hover"),this.sentVote=!0,this.sendVotePromise=$e.a.sendVote(this.message,e).then(()=>{t.forEach(e=>{e.classList.remove("is-voting")}),this.classList.remove("disable-hover")}).catch(()=>{this.sentVote=!1}).finally(()=>{this.sendVotePromise=null})}performResults(e,t,s=!0){var i,n;if(a.default.settings.animationsEnabled||(s=!1),this.isQuiz&&((null===(i=e.results)||void 0===i?void 0:i.length)||this.isClosed)){this.answerDivs.forEach((t,s)=>{t.classList.toggle("is-correct",!!e.results[s].pFlags.correct)}),this.initQuizHint&&(this.initQuizHint(e),this.initQuizHint=null),this.quizInterval&&(clearInterval(this.quizInterval),this.quizInterval=0),(null===(n=this.quizTimer)||void 0===n?void 0:n.parentElement)&&this.quizTimer.remove();const t=this.descDiv.querySelector(".poll-time");t&&t.remove()}if(this.isClosed&&(this.classList.add("is-closed"),Object(x.a)(this.typeDiv,Object(A.i18n)("Chat.Poll.Type.Closed"))),(this.chosenIndexes.length!==t.length||this.isClosed)&&(this.isRetracted=this.chosenIndexes.length&&!t.length,this.chosenIndexes=t.slice(),this.isRetracted?Object(l.b)(this,this.clickHandler):Object(l.c)(this,this.clickHandler)),this.chosenIndexes.length||this.isRetracted||this.isClosed){const t=e.results.map(t=>e.total_voters?t.voters/e.total_voters*100:0);this.classList.toggle("no-transition",!s),s&&Object(Xt.a)(this,"",!this.isRetracted,340),Object(_e.b)(()=>{this.setResults(this.isRetracted?this.percents:t,this.chosenIndexes,s),this.percents=t,this.isRetracted=!1})}if(this.setVotersCount(e),this.isPublic){this.isMultiple||(this.viewResults.classList.toggle("hide",!e.total_voters||!this.chosenIndexes.length),this.votersCountDiv.classList.toggle("hide",!!this.chosenIndexes.length));let t="";e.recent_voters.forEach((e,s)=>{t+=`<avatar-element class="avatar-16 poll-avatar" dialog="0" peer="${e}" ${0===s?"":`style="transform: translateX(-${3*s}px);"`}></avatar-element>`}),this.avatarsDiv.innerHTML=t}if(this.isMultiple){const t=!!this.chosenIndexes.length,s=this.isClosed||t,i=!this.isPublic||!e.total_voters||!t&&!this.isClosed;this.sendVoteBtn.classList.toggle("hide",s),this.viewResults.classList.toggle("hide",i),this.votersCountDiv.classList.toggle("hide",!s||!i)}}setResults(e,t,s){this.svgLines.forEach(e=>e.style.display=""),this.answerDivs.forEach((e,s)=>{e.classList.toggle("is-chosen",t.includes(s))});const i=Math.max(...e);if(this.maxPercents=e.map(e=>e/i),this.isRetracted)this.svgLines.forEach((e,t)=>{this.setLineProgress(t,-1)});else{const e=()=>{this.svgLines.forEach((e,t)=>{this.setLineProgress(t,1)})};s?Object(_e.b)(e):e()}let n;e=e.slice(),Zt(e);const a=t=>{e.forEach((e,s)=>{const i=n(e,t);this.numberDivs[s].innerText=i+"%"})};if(this.isRetracted)if(n=(e,t)=>Math.round(e/10*t),s)for(let e=9,t=0;e>=0;--e,++t)setTimeout(()=>{a(e)},34*t);else a(0);else if(n=(e,t)=>Math.round(e/10*(t+1)),s)for(let e=0;e<10;++e)setTimeout(()=>{a(e)},34*e);else a(9);if(this.isRetracted){s&&this.classList.add("is-retracting"),this.classList.remove("is-voted");const e=()=>{this.svgLines.forEach(e=>e.style.display="none")};s?setTimeout(()=>{this.classList.remove("is-retracting"),e()},340):e()}else this.classList.add("is-voted")}setVotersCount(e){const t=e.total_voters||0;let s,i=[t];s=this.isClosed?this.isQuiz?t?"Chat.Quiz.TotalVotes":"Chat.Quiz.TotalVotesResultEmpty":t?"Chat.Poll.TotalVotes1":"Chat.Poll.TotalVotesResultEmpty":this.isQuiz?t?"Chat.Quiz.TotalVotes":"Chat.Quiz.TotalVotesEmpty":t?"Chat.Poll.TotalVotes1":"Chat.Poll.TotalVotesEmpty",Object(x.a)(this.votersCountDiv,Object(A.i18n)(s,i))}setLineProgress(e,t){const s=this.svgLines[e];-1===t?(s.style.strokeDasharray="",s.style.strokeDashoffset=""):(s.style.strokeDasharray=t*this.maxPercents[e]*ns.MAX_LENGTH+", 485.9",s.style.strokeDashoffset=""+t*ns.MAX_OFFSET)}}ns.MAX_OFFSET=-46.5,ns.MAX_LENGTH=0,customElements.define("poll-element",ns);var as=s(127),os=s(53),rs=s(93),ls=s(112),cs=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};const ds=new class{constructor(){this.storage=new rs.a(ls.a,"stickerSets"),this.getStickerSetPromises={},this.getStickersByEmoticonsPromises={},this.getAnimatedEmojiStickerSet(),a.default.addMultipleEventsListeners({updateNewStickerSet:e=>{this.saveStickerSet(e.stickerset,e.stickerset.set.id),a.default.dispatchEvent("stickers_installed",e.stickerset.set)}}),this.getGreetingStickersTimeout=window.setTimeout(()=>{this.getGreetingStickersTimeout=void 0,this.getGreetingSticker(!0)},5e3)}getGreetingSticker(e=!1){return this.getGreetingStickersTimeout&&(clearTimeout(this.getGreetingStickersTimeout),this.getGreetingStickersTimeout=void 0),this.getGreetingStickersPromise||(this.getGreetingStickersPromise=this.getStickersByEmoticon("👋⭐️",!1).then(e=>{if(!e.length)throw"NO_STICKERS";this.greetingStickers=e.slice(),this.greetingStickers.sort((e,t)=>Math.random()-Math.random())})),this.getGreetingStickersPromise.then(()=>{let t;return e||(t=this.greetingStickers.shift(),this.greetingStickers.push(t)),M.a.downloadDoc(this.greetingStickers[0]),t})}saveStickers(e){Object(y.d)(e,(t,s)=>{(t=M.a.saveDoc(t))?e[s]=t:e.splice(s,1)})}getStickerSet(e,t={}){return cs(this,void 0,void 0,(function*(){const s=e.id;return this.getStickerSetPromises[s]?this.getStickerSetPromises[s]:this.getStickerSetPromises[s]=new Promise(i=>cs(this,void 0,void 0,(function*(){var n;if(!t.overwrite){const e=yield this.storage.get(s);if(e&&(null===(n=e.documents)||void 0===n?void 0:n.length)&&(Date.now()-e.refreshTime<36e5||t.useCache))return this.saveStickers(e.documents),i(e),void delete this.getStickerSetPromises[s]}try{const n=yield rt.a.invokeApi("messages.getStickerSet",{stickerset:this.getStickerSetInput(e)}),a=t.saveById?s:n.set.id;this.saveStickerSet(n,a),i(n)}catch(e){i(null)}delete this.getStickerSetPromises[s]})))}))}getAnimatedEmojiStickerSet(){return this.getStickerSet({id:"emoji"},{saveById:!0})}getRecentStickers(){return cs(this,void 0,void 0,(function*(){const e=yield rt.a.invokeApiHashable("messages.getRecentStickers");return this.saveStickers(e.stickers),e}))}getAnimatedEmojiSticker(e){const t=this.storage.getFromCache("emoji");if(!t||!t.documents)return;e=e.replace(/\ufe0f/g,"").replace(/🏻|🏼|🏽|🏾|🏿/g,"");const s=t.packs.find(t=>t.emoticon===e);return s?M.a.getDoc(s.documents[0]):void 0}preloadAnimatedEmojiSticker(e){return this.getAnimatedEmojiStickerSet().then(()=>{const t=this.getAnimatedEmojiSticker(e);if(t)return M.a.downloadDoc(t)})}saveStickerSet(e,t){const s={_:"messages.stickerSet",set:e.set,packs:e.packs,documents:e.documents};let i=this.storage.getFromCache(t);i?Object.assign(i,s):i=this.storage.setToCache(t,s),this.saveStickers(e.documents);const n=i.set.installed_date||"emoji"===t;i.refreshTime=Date.now(),this.storage.set({[t]:i},!n)}getStickerSetThumbDownloadOptions(e){var t;const s=e.thumbs.find(e=>"photoSize"===e._),i=e.thumb_dc_id,n=null===(t=e.pFlags)||void 0===t?void 0:t.animated;return{dcId:i,location:{_:"inputStickerSetThumb",stickerset:this.getStickerSetInput(e),thumb_version:e.thumb_version},size:s.size,mimeType:n?"application/x-tgsticker":"image/webp"}}getStickerSetInput(e){return"emoji"===e.id?{_:"inputStickerSetAnimatedEmoji"}:e.access_hash?{_:"inputStickerSetID",id:e.id,access_hash:e.access_hash}:{_:"inputStickerSetShortName",short_name:e.id}}getFeaturedStickers(){return cs(this,void 0,void 0,(function*(){const e=yield rt.a.invokeApiHashable("messages.getFeaturedStickers");return e.sets.forEach(e=>{this.saveStickerSet({set:e.set,documents:[],packs:[]},e.set.id)}),e.sets}))}toggleStickerSet(e){return cs(this,void 0,void 0,(function*(){if(e.installed_date){if(yield rt.a.invokeApi("messages.uninstallStickerSet",{stickerset:this.getStickerSetInput(e)}))return delete e.installed_date,a.default.dispatchEvent("stickers_deleted",e),this.storage.delete(e.id,!0),!0}else{if(yield rt.a.invokeApi("messages.installStickerSet",{stickerset:this.getStickerSetInput(e),archived:!1}))return e.installed_date=Date.now()/1e3|0,a.default.dispatchEvent("stickers_installed",e),!0}return!1}))}searchStickerSets(e,t=!0){return cs(this,void 0,void 0,(function*(){const s=t?1:0,i=yield rt.a.invokeApiHashable("messages.searchStickerSets",{flags:s,exclude_featured:t||void 0,q:e});i.sets.forEach(e=>{this.saveStickerSet({set:e.set,documents:[],packs:[]},e.set.id)});const n=[],a=this.storage.getCache();for(let t in a){const{set:s}=a[t];s.title.toLowerCase().includes(e.toLowerCase())&&!i.sets.find(e=>e.set.id===s.id)&&n.push({_:"stickerSetCovered",set:s,cover:null})}return i.sets.concat(n)}))}getAllStickers(){return rt.a.invokeApiHashable("messages.getAllStickers")}preloadStickerSets(){return this.getAllStickers().then(e=>Promise.all(e.sets.map(e=>this.getStickerSet(e,{useCache:!0}))))}getStickersByEmoticon(e,t=!0){return this.getStickersByEmoticonsPromises[e]?this.getStickersByEmoticonsPromises[e]:this.getStickersByEmoticonsPromises[e]=Promise.all([rt.a.invokeApiHashable("messages.getStickers",{emoticon:e}),t?this.preloadStickerSets():[],t?this.getRecentStickers().then(e=>e.packs):[]]).then(([t,s,i])=>{const n=t.stickers.map(e=>M.a.saveDoc(e)),a=[],o=[],r=t=>{for(const s of t)if(s.emoticon.includes(e))for(const e of s.documents){const t=M.a.getDoc(e);(t.animated?a:o).push(t)}};r(i);for(const e of s)r(e.packs);return[...new Set(a.concat(o,n))]})}};de.a.appStickersManager=ds;var hs=ds,us=s(55),ps=s(118),ms=s(123),gs=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};let bs=0;function vs({doc:e,container:t,message:s,boxWidth:i,boxHeight:n,withTail:o,isOut:r,middleware:d,lazyLoadQueue:u,noInfo:p,group:m,onlyPreview:g,withoutPreloader:b,loadPromises:f,noPlayButton:y,noAutoDownload:w,size:L,searchContext:S}){var E,C;const k=!(i&&n),T=("video"!==e.type||e.size<=52428800&&!k)&&("gif"===e.type?a.default.settings.autoPlay.gifs:a.default.settings.autoPlay.videos);let P,x;if(!p){P=document.createElement("span"),P.classList.add("video-time"),t.append(P);let s=!1;"gif"!==e.type?(P.innerText=(e.duration+"").toHHMMSS(!1),y||"round"===e.type||(T&&!w?P.classList.add("tgico","can-autoplay"):s=!0)):(P.innerText="GIF",T||y||(s=!0,w=void 0)),s&&(x=document.createElement("span"),x.classList.add("video-play","tgico-largeplay","btn-circle","position-center"),t.append(x))}let A={};if("image/gif"===e.mime_type){const a=ys({photo:e,message:s,container:t,boxWidth:i,boxHeight:n,withTail:o,isOut:r,lazyLoadQueue:u,middleware:d,withoutPreloader:b,loadPromises:f,noAutoDownload:w,size:L});return A.thumb=a,A.loadPromise=a.loadPromises.full,A}const O=document.createElement("video");if(O.classList.add("media-video"),O.setAttribute("playsinline","true"),O.muted=!0,"round"===e.type){const i=document.createElement("div");i.classList.add("media-round","z-depth-1"),i.dataset.mid=""+s.mid,i.dataset.peerId=""+s.peerId,i.message=s;const n=v.b.active.round,a=n.width/2,o=3.5,r=a-2*o;i.innerHTML=`<svg class="progress-ring" width="${n.width}" height="${n.width}" style="transform: rotate(-90deg);">\n <circle class="progress-ring__circle" stroke="white" stroke-opacity="0.3" stroke-width="${o}" cx="${a}" cy="${a}" r="${r}" fill="transparent"/>\n </svg>`;const d=i.firstElementChild.firstElementChild;bs||(bs=2*Math.PI*r),d.style.strokeDasharray=bs+" "+bs,d.style.strokeDashoffset=""+bs,P.classList.add("tgico");s.pFlags.media_unread&&i.classList.add("is-unread");const h=document.createElement("canvas");h.width=h.height=e.w,i.prepend(h,P),i.append(O),t.append(i);const u=h.getContext("2d"),p=()=>{const e=i.message,t=fe.addMedia(e,!w),s=()=>{(mo.chat.setPeerPromise||Promise.resolve()).finally(()=>{Object(us.a)(t)||(t.removeEventListener("play",r),t.removeEventListener("timeupdate",o),t.removeEventListener("pause",p),t.removeEventListener("ended",m))})},n=()=>{u.drawImage(t,0,0);const e=bs-t.currentTime/t.duration*bs;return d.style.strokeDashoffset=""+e,!t.paused},a=()=>{t.duration&&(Object(us.a)(t)?(t.paused&&n(),P.innerText=(t.duration-t.currentTime+"").toHHMMSS(!1)):s())},o=Fe(a),r=()=>{O.classList.add("hide"),i.classList.remove("is-paused"),Object(as.a)(n,h),D&&D.preloader&&D.preloader.classList.contains("manual")&&D.onClick()},p=()=>{Object(us.a)(t)?i.classList.add("is-paused"):s()},m=()=>{O.classList.remove("hide"),i.classList.add("is-paused"),O.currentTime=0,P.innerText=(""+t.duration).toHHMMSS(!1),t.currentTime&&(t.currentTime=0)};t.addEventListener("play",r),t.addEventListener("timeupdate",o),t.addEventListener("pause",p),t.addEventListener("ended",m),Object(l.b)(h,s=>{if(Object(c.a)(s),D&&!D.detached&&D.onClick(),t.paused){if(fe.setSearchContext(S)){const[t,s]=Be(i,S.useSearch);fe.setTargets({peerId:e.peerId,mid:e.mid},t,s)}t.play()}else t.pause()}),t.paused?t.duration&&t.currentTime!==t.duration&&t.currentTime>0?(n(),a(),O.classList.add("hide")):p():r()};s.pFlags.is_outgoing?(i.onLoad=p,i.dataset.isOutgoing="1"):p()}else O.autoplay=!0;let _;if(s){if(_=ys({photo:e,message:s,container:t,boxWidth:i,boxHeight:n,withTail:o,isOut:r,lazyLoadQueue:u,middleware:d,withoutPreloader:!0,loadPromises:f,noAutoDownload:w,size:L}),A.thumb=_,!T&&"gif"!==e.type||g)return A.loadPromise=_.loadPromises.full,A;if(o){const e=(_.images.thumb||_.images.full).parentElement;O.width=+e.getAttributeNS(null,"width"),O.height=+e.getAttributeNS(null,"height"),e.append(O)}}else{const t=M.a.getThumb(e,!1);t&&t.promise.then(()=>{O.poster=t.cacheContext.url})}!O.parentElement&&t&&((null==_?void 0:_.aspecter)||t).append(O);const F=he.a.getCacheContext(e),j=!!(null===(E=null==s?void 0:s.media)||void 0===E?void 0:E.preloader);let D;j?(D=s.media.preloader,D.attach(t,!1),w=void 0):F.downloaded||e.supportsStreaming?e.supportsStreaming&&(D=new ye.a({cancelable:!1,attachMethod:"prepend"})):D=new ye.a({attachMethod:"prepend"});const B=Object(oe.a)();O.addEventListener("error",e=>{4!==O.error.code&&console.error("Error "+O.error.code+"; details: "+O.error.message),D&&!j&&D.detach(),B.isFulfilled||B.resolve()},{once:!0}),Object(me.d)(O).then(()=>{m&&I.a.addAnimation(O,m),D&&!j&&D.detach(),B.resolve()}),"video"===e.type&&O.addEventListener("timeupdate",()=>{P.innerText=(O.duration-O.currentTime+"").toHHMMSS(!1)}),O.muted=!0,O.loop=!0,O.autoplay=!0;let R=w&&(null===(C=null==_?void 0:_.preloader)||void 0===C?void 0:C.loadFunc);const H=()=>{D&&w&&!b&&(D.construct(),D.setManual());let i=Promise.resolve();if(D&&!j)if(F.downloaded||e.supportsStreaming)e.supportsStreaming&&(w?i=Promise.reject():F.downloaded||(D.attach(t,!1,null),O.addEventListener(h.IS_SAFARI?"timeupdate":"canplay",()=>{D.detach()},{once:!0})));else{const s=i=M.a.downloadDoc(e,null==u?void 0:u.queueId,w);D.attach(t,!1,s)}return!w&&R&&(R(),R=null),w=void 0,i.then(()=>{!d||d()?("round"===e.type&&fe.resolveWaitingForLoadMedia(s.peerId,s.mid,s.pFlags.is_scheduled),Object(Rt.a)(O,F.url)):B.resolve()},()=>{}),{download:i,render:B}};return D&&!j&&D.setDownloadFunction(H),"gif"!==e.type||T?A.loadPromise=u?(u.push({div:t,load:()=>H().render}),Promise.resolve()):H().render:Object(l.b)(t,e=>{Object(c.a)(e),x.remove(),H()},{capture:!0,once:!0}),A}function fs({message:e,withTime:t,fontWeight:s,voiceAsMusic:n,showSender:o,searchContext:r,loadPromises:c,noAutoDownload:d,lazyLoadQueue:h}){var u,p;s||(s=500);const m=e.media.document||e.media.webpage.document,b=e.pFlags.is_outgoing&&(null===(u=e.media)||void 0===u?void 0:u.preloader);if("audio"===m.type||"voice"===m.type||"round"===m.type){const i=new Re;return i.withTime=t,i.message=e,i.noAutoDownload=d,i.lazyLoadQueue=h,i.loadPromises=c,n&&(i.voiceAsMusic=n),r&&(i.searchContext=r),o&&(i.showSender=o),b&&(i.preloader=e.media.preloader),i.dataset.fontWeight=""+s,i.render(),i}let v=m.file_name?m.file_name.split("."):"",f="";f=v.length>1&&Array.isArray(v)?Object(ps.a)(v.pop().split(" ",1)[0].toLowerCase()):"file";let y=document.createElement("div");y.classList.add("document","ext-"+f),y.dataset.docId=m.id;const w=document.createElement("div");w.classList.add("document-ico");const L=he.a.getCacheContext(m);if(((null===(p=m.thumbs)||void 0===p?void 0:p.length)||e.pFlags.is_outgoing&&L.url&&"photo"===m.type)&&"image/gif"!==m.mime_type){y.classList.add("document-with-thumb");let t=[];if(e.pFlags.is_outgoing)w.innerHTML=`<img src="${L.url}">`,t.push(w.firstElementChild);else{const e=ys({photo:m,message:null,container:w,boxWidth:54,boxHeight:54,loadPromises:c,withoutPreloader:!0,lazyLoadQueue:h});w.style.width=w.style.height="",e.images.thumb&&t.push(e.images.thumb),e.images.full&&t.push(e.images.full)}t.forEach(e=>e.classList.add("document-thumb"))}else w.innerText=f;let S=m.fileName||"Unknown.file";document.createElement("div").classList.add("document-description");const E=[Object(C.b)(m.size)];t&&E.push(Object(re.c)(e.date)),o&&E.push(i.a.wrapSenderToPeer(e)),y.innerHTML=`\n ${L.downloaded&&!b?"":'<div class="document-download"></div>'}\n <div class="document-name"></div>\n <div class="document-size"></div>\n `;const I=y.querySelector(".document-name"),k=new xe.a;k.dataset.fontWeight=""+s,k.innerHTML=S,I.append(k),o&&I.append(i.a.wrapSentTime(e));if(y.querySelector(".document-size").append(...Object(A.joinElementsWith)(E," · ")),y.prepend(w),!b&&e.pFlags.is_outgoing)return y;let T,P=null;const x=()=>{if(T){T.classList.add("downloaded");const e=T;setTimeout(()=>{e.remove()},200),T=null}P&&(P=null)},O=e=>{var t;const s=!e||e.isTrusted,i=M.a.getDoc(y.dataset.docId);let n;const o=mo.chat.bubbles?mo.chat.bubbles.lazyLoadQueue.queueId:void 0;return s?"pdf"===i.type?(n=M.a.downloadDoc(i,o),n.then(()=>{setTimeout(()=>{const e=he.a.getCacheContext(i).url;window.open(e)},a.default.settings.animationsEnabled?250:0)})):n=g.has(i.mime_type)&&(null===(t=i.thumbs)||void 0===t?void 0:t.length)?M.a.downloadDoc(i,o):M.a.saveDocFile(i,o):n=M.a.downloadDoc(i,o),T&&(n.then(x),P.attach(T,!0,n)),{download:n}};return M.a.downloading.has(m.id)?(T=y.querySelector(".document-download"),P=new ye.a,P.attach(T,!1,M.a.downloading.get(m.id))):L.downloaded&&!b||(T=y.querySelector(".document-download"),P=e.media.preloader,P?(P.attach(T),e.media.promise.then(x)):(P=new ye.a,P.construct(),P.setManual(),P.attach(T),P.setDownloadFunction(O))),Object(l.b)(y,e=>{P?P.onClick(e):O(e)}),y}function ys({photo:e,message:t,container:s,boxWidth:i,boxHeight:n,withTail:o,isOut:l,lazyLoadQueue:c,middleware:d,size:h,withoutPreloader:u,loadPromises:p,noAutoDownload:m,noBlur:g,noThumb:b,noFadeIn:f,blurAfter:y}){var w;if(!e.sizes&&!e.thumbs)return i&&n&&!h&&"document"===e._&&r.a.setAttachmentSize(e,s,i,n,void 0,t),{loadPromises:{thumb:Promise.resolve(),full:Promise.resolve()},images:{thumb:null,full:null},preloader:null,aspecter:null};h||(void 0===i&&(i=v.b.active.regular.width),void 0===n&&(n=v.b.active.regular.height)),s.classList.add("media-container");let L,S,E,I=s,C=!0,k=Promise.resolve();if(S=new Image,i&&n&&!h){const a=r.a.setAttachmentSize(e,s,i,n,void 0,t);if(h=a.photoSize,C=a.isFit,E=he.a.getCacheContext(e,h.type),!C){I=document.createElement("div"),I.classList.add("media-container-aspecter"),I.style.width=a.size.width+"px",I.style.height=a.size.height+"px";const i=r.a.getStrippedThumbIfNeeded(e,E,!g,!0);if(i){k=i.loadPromise;const e=i.image;e.classList.add("media-photo"),s.append(e)}else{ys({container:s,message:t,photo:e,boxWidth:0,boxHeight:0,size:h,lazyLoadQueue:c,isOut:l,loadPromises:p,middleware:d,withoutPreloader:u,withTail:o,noAutoDownload:m,noBlur:g,noThumb:!0,blurAfter:!0}).images.full.classList.add("media-photo","thumbnail")}s.classList.add("media-container-fitted"),s.append(I)}}else h||(h=r.a.choosePhotoSize(e,i,n,!0)),E=he.a.getCacheContext(e,null==h?void 0:h.type);if(!b){const t=r.a.getStrippedThumbIfNeeded(e,E,!g);t&&(k=Promise.all([k,t.loadPromise]),L=t.image,L.classList.add("media-photo"),I.append(L))}S.classList.add("media-photo");const T=(L||!E.downloaded)&&a.default.settings.animationsEnabled&&!f;let P;(null===(w=null==t?void 0:t.media)||void 0===w?void 0:w.preloader)&&!u?(P=t.media.preloader,P.attach(s),m=void 0):E.downloaded||(P=new ye.a({attachMethod:"prepend"}));const x=e=>ws(s,S,e,T,I,L),A=()=>d&&!d()?Promise.resolve():y?Object(ms.a)(E.url,12).then(e=>x(e)):x(E.url);let O;const _=h.w>=150&&h.h>=150||m,F=()=>{m&&!u&&P&&(P.construct(),P.setManual());const t="document"===e._&&"image/gif"===e.mime_type?M.a.downloadDoc(e,null==c?void 0:c.queueId):r.a.preloadPhoto(e,h,null==c?void 0:c.queueId,m);P&&!E.downloaded&&!u&&_&&P.attach(s,!1,t),m=void 0;const i=t.then(A);return i.catch(()=>{}),{download:t,render:i}};return P&&P.setDownloadFunction(F),E.downloaded?k=O=F().render:c?c.push({div:s,load:()=>F().download}):O=F().render,p&&k&&p.push(k),{loadPromises:{thumb:k,full:O||Promise.resolve()},images:{thumb:L,full:S},preloader:P,aspecter:I}}function ws(e,t,s,i,n=e,a){return i&&t.classList.add("fade-in"),new Promise(o=>{Object(Rt.a)(t,s,()=>{os.a.mutateElement(e,()=>{n.append(t),Object(_e.b)(()=>{o()}),i&&t.addEventListener("animationend",()=>{os.a.mutate(()=>{t.classList.remove("fade-in"),a&&a.remove()})},{once:!0})})})})}function Ls({doc:e,div:t,middleware:s,lazyLoadQueue:i,group:n,play:o,onlyThumb:d,emoji:h,width:u,height:m,withThumb:g,loop:b,loadPromises:v,needFadeIn:f}){var y;const w=e.sticker;if(u||(u=h?void 0:200),m||(m=h?void 0:200),2!==w||le.b.loaded||le.b.loadLottieWorkers(),!w)throw console.error("wrong doc for wrapSticker!",e),new Error("wrong doc for wrapSticker!");t.dataset.docId=e.id,t.classList.add("media-sticker-wrapper");const L=he.a.getCacheContext(e),S=h?Object(ne.d)(h):-1,E=L.downloaded&&!f;let I=Object(oe.a)(),C=!1;if(((null===(y=e.thumbs)||void 0===y?void 0:y.length)||e.stickerCachedThumbs)&&!t.firstElementChild&&(!E||2===w||d)){let n,a=e.stickerCachedThumbs&&e.stickerCachedThumbs[S]||e.thumbs[0];const o=()=>{t.childElementCount||(n.classList.add("media-sticker","thumbnail"),os.a.mutateElement(t,()=>{t.append(n),I.resolve()}))};if("url"in a)n=new Image,Object(Rt.a)(n,a.url,o),C=!0;else if("bytes"in a){if("photoPathSize"===a._)if(a.bytes.length){const s=r.a.getPathFromPhotoPathSize(a);t.innerHTML=`<svg class="rlottie-vector media-sticker thumbnail" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 ${e.w||512} ${e.h||512}" xml:space="preserve">\n <path d="${s}"/>\n </svg>`}else a=e.thumbs.find(e=>{var t;return null===(t=e.bytes)||void 0===t?void 0:t.length})||a;a&&"photoPathSize"!==a._&&S<=0&&(n=new Image,p.a||e.pFlags.stickerThumbConverted||L.url?(Object(Rt.a)(n,r.a.getPreviewURLFromThumb(e,a,!0),o),C=!0):ce.a.convert(e.id,a.bytes).then(i=>{a.bytes=i,e.pFlags.stickerThumbConverted=!0,s&&!s()||t.childElementCount||Object(Rt.a)(n,r.a.getPreviewURLFromThumb(e,a,!0),o)}).catch(()=>{}))}else if(2===w&&(g||d)&&S<=0){n=new Image;const r=()=>{if(t.childElementCount||s&&!s())return;const i=()=>{t.childElementCount||s&&!s()||Object(Rt.a)(n,L.url,o)};return L.url?(i(),Promise.resolve()):M.a.getThumbURL(e,a).promise.then(i)};if(i&&d)return i.push({div:t,load:r}),Promise.resolve();r(),a.url&&(C=!0)}}if(v&&C&&v.push(I),d)return Promise.resolve();const k=()=>gs(this,void 0,void 0,(function*(){if(!s||s())if(2===w)yield M.a.downloadDoc(e,null==i?void 0:i.queueId).then(ae.c).then(i=>gs(this,void 0,void 0,(function*(){if(s&&!s())return;let r=yield le.b.loadAnimationWorker({container:t,loop:b&&!h,autoplay:o,animationData:i,width:u,height:m},n,S);r.addEventListener("firstFrame",()=>{const s=t.firstElementChild;f=(f||!s||"svg"===s.tagName)&&a.default.settings.animationsEnabled;const i=()=>{s&&s!==r.canvas&&s.remove()};f?os.a.mutate(()=>{r.canvas.classList.add("fade-in"),s&&s.classList.add("fade-out"),r.canvas.addEventListener("animationend",()=>{os.a.mutate(()=>{r.canvas.classList.remove("fade-in"),i()})},{once:!0})}):s&&os.a.mutate(i),M.a.saveLottiePreview(e,r.canvas,S)},{once:!0}),h&&Object(l.b)(t,e=>{Object(c.a)(e);let s=le.b.getAnimation(t);s.paused&&(s.autoplay=!0,s.restart())})})));else if(1===w){const n=new Image,o=t.firstElementChild!==n&&t.firstElementChild;return f=(f||!E||o)&&a.default.settings.animationsEnabled,n.classList.add("media-sticker"),f&&n.classList.add("fade-in"),new Promise((a,r)=>{const l=()=>{if(s&&!s())return a();Object(Rt.a)(n,L.url,()=>{os.a.mutateElement(t,()=>{t.append(n),o&&o.classList.add("fade-out"),a(),f&&n.addEventListener("animationend",()=>{n.classList.remove("fade-in"),o&&o.remove()},{once:!0})})})};L.url?l():M.a.downloadDoc(e,null==i?void 0:i.queueId).then(l,a)})}})),T=!i||E&&2!==w?k():(i.push({div:t,load:k}),Promise.resolve());return E&&1===w&&(I=T,v&&v.push(I)),T}function Ss({set:e,lazyLoadQueue:t,container:s,group:i,autoplay:n,width:a,height:o}){var r;return gs(this,void 0,void 0,(function*(){if(null===(r=e.thumbs)||void 0===r?void 0:r.length)return s.classList.add("media-sticker-wrapper"),void t.push({div:s,load:()=>{const t=hs.getStickerSetThumbDownloadOptions(e),r=he.a.download(t);if(e.pFlags.animated)return r.then(ae.c).then(e=>{le.b.loadAnimationWorker({container:s,loop:!0,autoplay:n,animationData:e,width:a,height:o,needUpscale:!0},i)});{const e=new Image;return e.classList.add("media-sticker"),r.then(t=>{Object(Rt.a)(e,URL.createObjectURL(t),()=>{s.append(e)})})}}});const l=hs.getStickerSet(e),c=yield l;"documentEmpty"!==c.documents[0]._&&Ls({doc:c.documents[0],div:s,group:i,lazyLoadQueue:t})}))}function Es(e,t,s){const i=new Ne("reply");return i.fill(e,t,s),i.container}function Ms(e){const t=new qe(e.items,e.maxWidth,e.minWidth,e.spacing,e.maxHeight).layout(),s=t.find(e=>e.sides&We),i=s.geometry.width+s.geometry.x,n=t.find(e=>e.sides&Ke),a=n.geometry.height+n.geometry.y,o=e.container;o.style.width=i+"px",o.style.height=a+"px";const r=o.children;t.forEach(({geometry:t,sides:s},n)=>{let l;if(l=r[n],l||(l=document.createElement("div"),o.append(l)),l.classList.add("album-item","grouped-item"),l.style.width=t.width/i*100+"%",l.style.height=t.height/a*100+"%",l.style.top=t.y/a*100+"%",l.style.left=t.x/i*100+"%",s&Ge&&s&Ve&&(l.style.borderTopLeftRadius="inherit"),s&Ge&&s&Ke&&(l.style.borderBottomLeftRadius="inherit"),s&We&&s&Ve&&(l.style.borderTopRightRadius="inherit"),s&We&&s&Ke&&(l.style.borderBottomRightRadius="inherit"),e.forMedia){const e=document.createElement("div");e.classList.add("album-item-media"),l.append(e)}})}function Is({groupId:e,attachmentDiv:t,middleware:s,uploading:n,lazyLoadQueue:a,isOut:o,chat:l,loadPromises:c,noAutoDownload:d}){const h=[],u=i.a.getMidsByAlbum(e);for(const e of u){const t=l.getMessage(e),s=t.media.photo||t.media.document,i="photo"===s._?r.a.choosePhotoSize(s,480,480):{w:s.w,h:s.h};h.push({size:i,media:s,message:t})}Ms({container:t,items:h.map(e=>({w:e.size.w,h:e.size.h})),maxWidth:v.b.active.album.width,minWidth:100,spacing:2,forMedia:!0}),h.forEach((e,i)=>{const{size:n,media:r,message:l}=e,h=t.children[i];h.dataset.mid=""+l.mid;const u=h.firstElementChild;"photo"===r._?ys({photo:r,message:l,container:u,boxWidth:0,boxHeight:0,isOut:o,lazyLoadQueue:a,middleware:s,size:n,loadPromises:c,noAutoDownload:d}):vs({doc:l.media.document,container:u,message:l,boxWidth:0,boxHeight:0,withTail:!1,isOut:o,lazyLoadQueue:a,middleware:s,loadPromises:c,noAutoDownload:d})})}v.b.addEventListener("changeScreen",(e,t)=>{if(t===v.a.mobile||e===v.a.mobile){const e=Array.from(document.querySelectorAll(".media-round .progress-ring")),t=v.b.active.round.width,s=t/2,i=s-7;bs=2*Math.PI*i,e.forEach(e=>{e.setAttributeNS(null,"width",""+t),e.setAttributeNS(null,"height",""+t);const n=e.firstElementChild;n.setAttributeNS(null,"cx",""+s),n.setAttributeNS(null,"cy",""+s),n.setAttributeNS(null,"r",""+i),n.style.strokeDasharray=bs+" "+bs,n.style.strokeDashoffset=""+bs})}}),a.default.addEventListener("download_start",e=>{Array.from(document.querySelectorAll(`.document[data-doc-id="${e}"]`)).forEach(e=>{e.querySelector(".preloader-container.manual")&&Object(l.d)(e)})});var Cs=s(77),ks=s(102),Ts=s(78);function Ps(e,t,s,i){return void 0===i&&(i=e.parentElement===t?Object(Ts.a)(e):-1),i!==s&&(-1!==i&&i<s&&(s+=1),s?t.childElementCount>s?t.insertBefore(e,t.children[s]):t.append(e):t.prepend(e),!0)}class xs{constructor(e){this.updateElementWith=e=>e(),this.updateListWith=e=>e(!0),this.middleware=Object(ks.a)(),Object(L.g)(this,e),this.elements=new Map,this.sorted=[]}clear(){this.middleware.clean(),this.elements.clear(),this.sorted.length=0}_updateList(){this.elements.forEach(e=>{this.update(e.id,!0)}),this.onSort&&this.sorted.forEach((e,t)=>{this.onSort(e,t)})}updateList(e){const t=this.middleware.get();this.updateListWith(s=>{if(!t()||void 0!==s&&!s)return e(!1);this._updateList(),e(!0)})}has(e){return this.elements.has(e)}get(e){return this.elements.get(e)}getAll(){return this.elements}add(e,t=!1,s,i=t){let n=this.get(e);if(n)return n;const a={id:e,index:0};return n=this.onElementCreate(a,t),this.elements.set(e,n),this.update(e,i,n,s),n}delete(e,t){const s=this.elements.get(e);if(!s)return!1;this.elements.delete(e);const i=this.sorted.indexOf(s);if(-1!==i&&this.sorted.splice(i,1),this.onDelete)if(t)this.onDelete(s);else{const e=this.middleware.get();this.updateElementWith(()=>{e()&&this.onDelete(s)})}return!0}update(e,t=!1,s=this.get(e),i){if(!s)return;s.index=this.getIndex(e),this.onUpdate&&this.onUpdate(s);const n=Object(y.e)(this.sorted,s,"index");if(!t&&this.onSort){const e=this.middleware.get();(i||this.updateElementWith)(()=>{e()&&this.onSort(s,n)})}}}var As=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class Os extends xs{constructor(e={}){let t;super({getIndex:e=>T.a.getUserStatusForSort(e),onDelete:e=>e.dom.listEl.remove(),onUpdate:e=>{const t=T.a.getUserStatusString(e.id);Object(x.a)(e.dom.lastMessageSpan,t)},onSort:(e,t)=>Ps(e.dom.listEl,this.list,t),onElementCreate:e=>{const{dom:t}=Do.addDialogNew({dialog:e.id,container:!1,drawStatus:!1,avatarSize:this.avatarSize,autonomous:!0,meAsSaved:!1,rippleEnabled:this.rippleEnabled,lazyLoadQueue:this.lazyLoadQueue});return e.dom=t,e},updateElementWith:_e.b,updateListWith:e=>As(this,void 0,void 0,(function*(){return Object(us.a)(this.list)?(yield Object(Cs.c)(),Object(us.a)(this.list)?void e(!0):e(!1)):e(!1)}))}),this.avatarSize=48,this.rippleEnabled=!0,Object(L.g)(this,e),this.list=Do.createChatList({new:e.new});const s=()=>{t=window.setTimeout(()=>{this.updateList(e=>{e&&s()})},Os.SORT_INTERVAL)};s()}}function _s(e,t){return new zt({element:e,onSwipe:(e,s,i)=>{if(Math.abs(s)>20)return!0;if(Math.abs(e)>Math.abs(s))Object(c.a)(i);else if(Math.abs(s)>Math.abs(e))return!0;return Math.abs(e)>50?(t(e>0),Object(se.b)(),!0):void 0},cancelEvent:!1})}Os.SORT_INTERVAL=3e4;var Fs=s(89),js=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class Ds extends It{constructor(e,t,s,i=!1){super({peerTypes:["dialogs","contacts"],onSelect:i?t:s=>js(this,void 0,void 0,(function*(){if(t){const e=t(s);e instanceof Promise&&(yield e)}mo.setInnerPeer(s),mo.chat.input.initMessagesForward(e)})),onClose:s,placeholder:"ShareModal.Search.ForwardPlaceholder",chatRightsAction:"send_messages",selfPresence:"ChatYourSelf"})}}class Bs{constructor(e,t,s,n){const r=new ft.a({peerId:e}).element;t=t.slice();const l=(a,o)=>{n&&n(),"scheduled"===s?i.a.deleteScheduledMessages(e,t):i.a.deleteMessages(e,t,!!a.size||o)};let c,d,h,u,p,m=[];if(1===t.length?c="DeleteSingleMessagesTitle":(c="DeleteMessagesTitle",d=[Object(A.i18n)("messages",[t.length])]),h=o.a.isMegagroup(e)?1===t.length?"AreYouSureDeleteSingleMessageMega":"AreYouSureDeleteFewMessagesMega":1===t.length?"AreYouSureDeleteSingleMessage":"AreYouSureDeleteFewMessages",p=[{langKey:"Delete",isDanger:!0,callback:l}],e===a.default.myId||"scheduled"===s);else if(e>0)m.push({text:"DeleteMessagesOptionAlso",textArgs:[r]});else{const s=G.a.getChat(-e),n=G.a.hasRights(-e,"delete_messages");if("chat"===s._){const s=n?t.slice():t.filter(t=>i.a.getMessageByPeer(e,t).fromId===a.default.myId);s.length&&(s.length===t.length?m.push({text:"DeleteForAll"}):(m.push({text:"DeleteMessagesOption"}),h="DeleteMessagesTextGroup",u=[Object(A.i18n)("messages",[s.length])]))}else p[0].callback=e=>l(e,!0)}Object(ct.a)(p);new ht("popup-delete-chat",{peerId:e,titleLangKey:c,titleLangArgs:d,descriptionLangKey:h,descriptionLangArgs:u,buttons:p,checkboxes:m}).show()}}var Rs=s(130);class Hs{constructor(e,t,s){let n,a,o=[];n=`Send Message${t.length>1?"s":""} Now`,a=t.length>1?"Send "+t.length+" messages now?":"Send message now?";o.push({langKey:"Send",callback:()=>{s&&s(),i.a.sendScheduledMessages(e,t)}});new ht("popup-delete-chat",{peerId:e,title:n,description:a,buttons:o}).show()}}var Us=s(6);function Ns(){window.getSelection?window.getSelection().empty?window.getSelection().empty():window.getSelection().removeAllRanges&&window.getSelection().removeAllRanges():document.selection&&document.selection.empty()}var zs=s(103);const Vs=e=>[...e.values()].reduce((e,t)=>e+t.size,0);class Ws{constructor(e){if(this.selectedMids=new Map,this.isSelecting=!1,this.cancelSelection=()=>{this.onCancelSelection&&this.onCancelSelection(),this.selectedMids.clear(),this.toggleSelection(),Ns()},Object(L.g)(this,e),this.navigationType="multiselect-"+Object(tt.b)(),pe.IS_TOUCH_SUPPORTED)return this.listenerSetter.add(this.listenElement)("touchend",()=>{this.isSelecting&&(this.selectedText=window.getSelection?window.getSelection().toString():document.selection?document.selection.createRange().text:"")}),void Object(se.a)(this.listenElement,e=>{if(this.isSelecting||this.verifyTouchLongPress&&!this.verifyTouchLongPress())return;document.body.classList.add("no-select"),this.listenElement.addEventListener("touchend",e=>{Object(c.a)(e),document.body.classList.remove("no-select")},{once:!0,capture:!0}),Ns();const t=this.getElementFromTarget(e.target);t&&this.toggleByElement(t)},this.listenerSetter);const t=(e,t)=>{if(e===t)return[];const s=e.getBoundingClientRect(),i=t.getBoundingClientRect(),n=(s.top-i.top||s.left-i.left)<0,a=Object(Ce.a)(e,this.lookupBetweenParentClassName);if(!a)return[];const o=Array.from(a.querySelectorAll(this.lookupBetweenElementsQuery));let r=o.indexOf(e),l=o.indexOf(t);n||([l,r]=[r,l]);return o.slice(r+1,l)};this.listenerSetter.add(this.listenElement)("mousedown",e=>{const s=Object(Ce.a)(e.target,this.targetLookupClassName);if(0!==e.button)return;if(this.verifyTarget&&!this.verifyTarget(e,s))return;const i=new Map;let n,a=s;const o=(e,s=!0)=>{const r=+e.dataset.mid,l=+e.dataset.peerId;if(!r||!l)return;Object(us.a)(a)||(a=e);let c=i.get(l);if(c||i.set(l,c=new Set),!c.has(r)){const d=this.isMidSelected(l,r);if(void 0===n&&(n=!d),c.add(r),n&&!d||!n&&d){const n=Vs(i);if(this.toggleByElement&&s){n<2&&Object(zs.a)(e,a)&&(a=e);const s=t(a,e);s.length&&s.forEach(e=>{o(e,!1)})}if(this.selectedMids.size)this.toggleByElement&&this.toggleByElement(e);else if(2===n&&this.toggleByMid)for(const[e,t]of i)for(const s of t)this.toggleByMid(e,s)}}};let r=!1;const d=e=>{r||(Ns(),r=!0);const t=this.getElementFromTarget(e.target);if(t)return this.verifyMouseMoveTarget&&!this.verifyMouseMoveTarget(e,t,n)?(this.listenerSetter.removeManual(this.listenElement,"mousemove",d),void this.listenerSetter.removeManual(document,"mouseup",h,u)):void o(t)},h=e=>{i.size&&Object(l.b)(window,c.a,{capture:!0,once:!0,passive:!1}),this.listenerSetter.removeManual(this.listenElement,"mousemove",d),Ns()},u={once:!0};this.listenerSetter.add(this.listenElement)("mousemove",d),this.listenerSetter.add(document)("mouseup",h,u)})}isElementShouldBeSelected(e){return this.isMidSelected(+e.dataset.peerId,+e.dataset.mid)}appendCheckbox(e,t){e.prepend(t.label)}toggleElementCheckbox(e,t){const s=!!this.getCheckboxInputFromElement(e);if(t){if(s)return!1;const t=new dt.a({name:e.dataset.mid,round:!0});this.isSelecting&&this.isElementShouldBeSelected(e)&&(t.input.checked=!0,e.classList.add("is-selected")),this.appendCheckbox(e,t)}else s&&this.getCheckboxInputFromElement(e).parentElement.remove();return!0}getCheckboxInputFromElement(e){var t;return"LABEL"===(null===(t=e.firstElementChild)||void 0===t?void 0:t.tagName)&&e.firstElementChild.firstElementChild}updateContainer(e=!1){const t=this.selectedMids.size;if(!t&&!e)return;let s=!t,i=!t,n=!t;for(const[e,t]of this.selectedMids){const n=this.isScheduled?this.appMessagesManager.getScheduledMessagesStorage(e):this.appMessagesManager.getMessagesStorage(e);for(const e of t){const t=this.appMessagesManager.getMessageFromStorage(n,e);if(s||t.action&&(s=!0),!i){this.appMessagesManager.canDeleteMessage(t)||(i=!0)}if(s&&i)break}if(s&&i)break}this.onUpdateContainer&&this.onUpdateContainer(s,i,n)}toggleSelection(e=!0,t=!1){const s=this.isSelecting,i=this.selectedMids.size;if(this.isSelecting=!!i||t,s===this.isSelecting)return!1;pe.IS_TOUCH_SUPPORTED||(this.listenElement.classList.toggle("no-select",this.isSelecting),s&&Ns()),Object(Us.a)();const n=!!i||t;return this.onToggleSelection&&this.onToggleSelection(n),h.IS_MOBILE_SAFARI||(n?B.a.pushItem({type:this.navigationType,onPop:()=>{this.cancelSelection()}}):B.a.removeByType(this.navigationType)),t&&this.updateContainer(t),!0}cleanup(){this.selectedMids.clear(),this.toggleSelection(!1)}updateElementSelection(e,t){this.toggleElementCheckbox(e,!0);this.getCheckboxInputFromElement(e).checked=t,this.toggleSelection(),this.updateContainer(),Object(Xt.a)(e,"is-selected",t,200)}isMidSelected(e,t){const s=this.selectedMids.get(e);return null==s?void 0:s.has(t)}length(){return Vs(this.selectedMids)}toggleMid(e,t,s){let i=this.selectedMids.get(e);if(s||void 0===s&&(null==i?void 0:i.has(t)))i&&(i.delete(t),i.size||this.selectedMids.delete(e));else{if(a.default.config.forwarded_count_max-this.length()-1<0)return nt(A.default.format("Chat.Selection.LimitToast",!0)),!1;i||(i=new Set,this.selectedMids.set(e,i)),i.add(t)}return!0}deleteSelectedMids(e,t){const s=this.selectedMids.get(e);s&&(t.forEach(e=>{s.delete(e)}),s.size||this.selectedMids.delete(e),this.updateContainer(),this.toggleSelection())}}class Ks extends Ws{constructor(e,t){super({appMessagesManager:t,listenElement:e.container,listenerSetter:new H.a,verifyTarget:(e,t)=>!!t&&this.isSelecting,getElementFromTarget:e=>Object(Ce.a)(e,"search-super-item"),targetLookupClassName:"search-super-item",lookupBetweenParentClassName:"tabs-tab",lookupBetweenElementsQuery:".search-super-item"}),this.searchSuper=e,this.toggleByElement=e=>{const t=+e.dataset.mid,s=+e.dataset.peerId;this.toggleMid(s,t)&&this.updateElementSelection(e,this.isMidSelected(s,t))},this.toggleByMid=(e,t)=>{const s=this.searchSuper.mediaTab.contentTab.querySelector(`.search-super-item[data-peer-id="${e}"][data-mid="${t}"]`);this.toggleByElement(s)},this.onUpdateContainer=(e,t,s)=>{const i=this.length();Object(x.a)(this.selectionCountEl,Object(A.i18n)("messages",[i])),this.selectionGotoBtn.classList.toggle("hide",1!==i),this.selectionForwardBtn.classList.toggle("hide",e),this.selectionDeleteBtn&&this.selectionDeleteBtn.classList.toggle("hide",t)},this.onToggleSelection=e=>{if(Object(Xt.a)(this.searchSuper.navScrollableContainer,"is-selecting",e,200,()=>{this.isSelecting||(this.selectionContainer.remove(),this.selectionContainer=this.selectionForwardBtn=this.selectionDeleteBtn=null,this.selectedText=void 0)}),Object(Xt.a)(this.searchSuper.container,"is-selecting",e,200),this.isSelecting&&!this.selectionContainer){const e="search-super-selection";this.selectionContainer=document.createElement("div"),this.selectionContainer.classList.add(e+"-container");const t=N(`close ${e}-cancel`,{noRipple:!0});this.listenerSetter.add(t)("click",this.cancelSelection,{once:!0}),this.selectionCountEl=document.createElement("div"),this.selectionCountEl.classList.add(e+"-count"),this.selectionGotoBtn=N(`message ${e}-goto`);const s={listenerSetter:this.listenerSetter};Object(l.b)(this.selectionGotoBtn,()=>{const e=[...this.selectedMids.keys()][0],t=[...this.selectedMids.get(e)][0];this.cancelSelection(),a.default.dispatchEvent("history_focus",{peerId:e,mid:t})},s),this.selectionForwardBtn=N(`forward ${e}-forward`),Object(l.b)(this.selectionForwardBtn,()=>{const e={};for(const[t,s]of this.selectedMids)e[t]=Array.from(s);new Ds(e,()=>{this.cancelSelection()})},s),this.isPrivate&&(this.selectionDeleteBtn=N(`delete danger ${e}-delete`),Object(l.b)(this.selectionDeleteBtn,()=>{const e=[...this.selectedMids.keys()][0];new Bs(e,[...this.selectedMids.get(e)],"chat",()=>{this.cancelSelection()})},s)),this.selectionContainer.append(...[t,this.selectionCountEl,this.selectionGotoBtn,this.selectionForwardBtn,this.selectionDeleteBtn].filter(Boolean));const i=this.selectionContainer;i.style.opacity="0",this.searchSuper.navScrollableContainer.append(i),i.offsetLeft,i.style.opacity=""}},this.isPrivate=!e.showSender}toggleSelection(e=!0,t=!1){const s=super.toggleSelection(e,t);if(s&&e){Array.from(this.searchSuper.tabsContainer.querySelectorAll(".search-super-item")).forEach(e=>{this.toggleElementCheckbox(e,this.isSelecting)})}return s}}class Gs extends Ws{constructor(e,t,s,i){super({appMessagesManager:i,listenElement:t.bubblesContainer,listenerSetter:t.listenerSetter,getElementFromTarget:e=>Object(Ce.a)(e,"grouped-item")||Object(Ce.a)(e,"bubble"),verifyTarget:(e,t)=>!(!this.selectedMids.size&&!e.target.classList.contains("bubble")&&!e.target.classList.contains("document-selection")&&t),verifyMouseMoveTarget:(e,t,s)=>!(e.target!==t&&!e.target.classList.contains("document-selection")&&void 0===s&&!this.selectedMids.size),verifyTouchLongPress:()=>!this.chat.input.recording,targetLookupClassName:"bubble",lookupBetweenParentClassName:"bubbles-inner",lookupBetweenElementsQuery:".bubble:not(.is-multiple-documents), .grouped-item",isScheduled:"scheduled"===e.type}),this.chat=e,this.bubbles=t,this.input=s,this.toggleByElement=e=>{if(!this.canSelectBubble(e))return;const t=+e.dataset.mid;if(e.classList.contains("is-grouped")){if(!this.isGroupedBubbleSelected(e)){const e=this.selectedMids.get(this.bubbles.peerId);if(e){this.chat.getMidsByMid(t).forEach(t=>e.delete(t))}}return void this.bubbles.getBubbleGroupedItems(e).forEach(this.toggleByElement)}if(!this.toggleMid(this.bubbles.peerId,t))return;if(e.classList.contains("grouped-item")){const s=Object(Ce.a)(e,"bubble"),i=this.isGroupedBubbleSelected(s),n=this.isGroupedMidsSelected(t);(n||i)&&this.updateElementSelection(s,n)}this.updateElementSelection(e,this.isMidSelected(this.bubbles.peerId,t))},this.toggleByMid=(e,t)=>{const s=this.bubbles.getMountedBubble(t);s&&this.toggleByElement(s.bubble)},this.onToggleSelection=e=>{let t="",s="";if(e){const e=this.input.rowsWrapper.parentElement,i=e.querySelector(".fake-selection-wrapper"),n=e.querySelector(".fake-rows-wrapper"),a=i.getBoundingClientRect(),o=n.getBoundingClientRect(),r=o.width,l=a.width;if(r!==l){const e=l/r,i=(r-l)/2;if(t=`translateX(${a.left-o.left-i}px) scaleX(${e})`,e<1){const t=12;s=t+t*(1-e)+"px"}}}if(Object(Xt.a)(this.input.rowsWrapper,"is-centering",e,200),this.input.rowsWrapper.style.transform=t,this.input.rowsWrapper.style.borderRadius=s,Object(Xt.a)(this.listenElement,"is-selecting",e,200,()=>{this.isSelecting||(this.selectionInputWrapper.remove(),this.selectionInputWrapper=this.selectionContainer=this.selectionSendNowBtn=this.selectionForwardBtn=this.selectionDeleteBtn=null,this.selectedText=void 0),Object(_e.b)(()=>{this.bubbles.onScroll()})}),this.isSelecting&&!this.selectionContainer){this.selectionInputWrapper=document.createElement("div"),this.selectionInputWrapper.classList.add("chat-input-wrapper","selection-wrapper"),this.selectionContainer=document.createElement("div"),this.selectionContainer.classList.add("selection-container");const e={listenerSetter:this.listenerSetter},t=N("close",{noRipple:!0});Object(l.b)(t,this.cancelSelection,{once:!0,listenerSetter:this.listenerSetter}),this.selectionCountEl=document.createElement("div"),this.selectionCountEl.classList.add("selection-container-count"),"scheduled"===this.chat.type?(this.selectionSendNowBtn=Object(U.a)("btn-primary btn-transparent btn-short text-bold selection-container-send",{icon:"send2"}),this.selectionSendNowBtn.append(Object(A.i18n)("MessageScheduleSend")),Object(l.b)(this.selectionSendNowBtn,()=>{new Hs(this.bubbles.peerId,[...this.selectedMids.get(this.bubbles.peerId)],()=>{this.cancelSelection()})},e)):(this.selectionForwardBtn=Object(U.a)("btn-primary btn-transparent text-bold selection-container-forward",{icon:"forward"}),this.selectionForwardBtn.append(Object(A.i18n)("Forward")),Object(l.b)(this.selectionForwardBtn,()=>{const e={};for(const[t,s]of this.selectedMids)e[t]=Array.from(s);new Ds(e,()=>{this.cancelSelection()})},e)),this.selectionDeleteBtn=Object(U.a)("btn-primary btn-transparent danger text-bold selection-container-delete",{icon:"delete"}),this.selectionDeleteBtn.append(Object(A.i18n)("Delete")),Object(l.b)(this.selectionDeleteBtn,()=>{new Bs(this.bubbles.peerId,[...this.selectedMids.get(this.bubbles.peerId)],this.chat.type,()=>{this.cancelSelection()})},e),this.selectionContainer.append(...[t,this.selectionCountEl,this.selectionSendNowBtn,this.selectionForwardBtn,this.selectionDeleteBtn].filter(Boolean)),this.selectionInputWrapper.style.opacity="0",this.selectionInputWrapper.append(this.selectionContainer),this.input.rowsWrapper.parentElement.append(this.selectionInputWrapper),this.selectionInputWrapper.offsetLeft,this.selectionInputWrapper.style.opacity=""}},this.onUpdateContainer=(e,t,s)=>{Object(x.a)(this.selectionCountEl,Object(A.i18n)("messages",[this.length()])),this.selectionSendNowBtn&&this.selectionSendNowBtn.toggleAttribute("disabled",s),this.selectionForwardBtn&&this.selectionForwardBtn.toggleAttribute("disabled",e),this.selectionDeleteBtn.toggleAttribute("disabled",t)},this.onCancelSelection=()=>{for(const[e,t]of this.selectedMids)for(const e of t){const t=this.bubbles.getMountedBubble(e);t&&this.toggleByElement(t.bubble)}}}appendCheckbox(e,t){t.label.classList.add("bubble-select-checkbox"),e.classList.contains("document-container")?e.querySelector(".document, audio-element").append(t.label):super.appendCheckbox(e,t)}toggleSelection(e=!0,t=!1){const s=super.toggleSelection(e,t);if(s&&e)for(const e in this.bubbles.bubbles){const t=this.bubbles.bubbles[e];this.toggleElementCheckbox(t,this.isSelecting)}return s}toggleElementCheckbox(e,t){if(!this.canSelectBubble(e))return;const s=super.toggleElementCheckbox(e,t);if(s){e.classList.contains("is-grouped")&&this.bubbles.getBubbleGroupedItems(e).forEach(e=>this.toggleElementCheckbox(e,t))}return s}isElementShouldBeSelected(e){const t=e.classList.contains("is-grouped");return super.isElementShouldBeSelected(e)&&(!t||this.isGroupedMidsSelected(+e.dataset.mid))}isGroupedBubbleSelected(e){const t=this.getCheckboxInputFromElement(e);return null==t?void 0:t.checked}isGroupedMidsSelected(e){const t=this.chat.getMidsByMid(e),s=t.filter(e=>this.isMidSelected(this.bubbles.peerId,e));return t.length===s.length}getCheckboxInputFromElement(e){return e.classList.contains("document-container")?e.querySelector("label input"):super.getCheckboxInputFromElement(e)}canSelectBubble(e){return!e.classList.contains("service")&&!e.classList.contains("is-sending")&&!e.classList.contains("bubble-first")}}var qs=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class Qs{constructor(e,t){this.attachTo=e,this.searchSuper=t,this.onGotoClick=()=>{a.default.dispatchEvent("history_focus",{peerId:this.peerId,mid:this.mid,threadId:this.searchSuper.searchContext.threadId})},this.onForwardClick=()=>{this.searchSuper.selection.isSelecting?Object(l.d)(this.searchSuper.selection.selectionForwardBtn):new Ds({[this.peerId]:[this.mid]})},this.onSelectClick=()=>{this.searchSuper.selection.toggleByElement(this.target)},this.onClearSelectionClick=()=>{this.searchSuper.selection.cancelSelection()},this.onDeleteClick=()=>{this.searchSuper.selection.isSelecting?Object(l.d)(this.searchSuper.selection.selectionDeleteBtn):new Bs(this.peerId,[this.mid],"chat")};const s=e=>{let s;this.init&&(this.init(),this.init=null);try{s=Object(Ce.a)(e.target,"search-super-item")}catch(e){}if(s){if(e instanceof MouseEvent&&e.preventDefault(),this.element.classList.contains("active"))return!1;e instanceof MouseEvent&&(e.cancelBubble=!0),this.target=s,this.peerId=+s.dataset.peerId,this.mid=+s.dataset.mid,this.isSelected=t.selection.isMidSelected(this.peerId,this.mid),this.buttons.forEach(e=>{let t;t=!(this.isSelected&&!e.withSelection)&&(!e.verify||e.verify()),e.element.classList.toggle("hide",!t)}),s.classList.add("menu-open"),Object(se.e)(e,this.element),Object(se.d)(this.element,()=>{s.classList.remove("menu-open")})}};pe.IS_TOUCH_SUPPORTED||Object(se.a)(e,s)}init(){this.buttons=[{icon:"forward",text:"Forward",onClick:this.onForwardClick},{icon:"forward",text:"Message.Context.Selection.Forward",onClick:this.onForwardClick,verify:()=>this.isSelected&&!this.searchSuper.selection.selectionForwardBtn.classList.contains("hide"),withSelection:!0},{icon:"message",text:"Message.Context.Goto",onClick:this.onGotoClick,withSelection:!0},{icon:"select",text:"Message.Context.Select",onClick:this.onSelectClick},{icon:"select",text:"Message.Context.Selection.Clear",onClick:this.onClearSelectionClick,verify:()=>this.isSelected,withSelection:!0},{icon:"delete danger",text:"Delete",onClick:this.onDeleteClick,verify:()=>i.a.canDeleteMessage(i.a.getMessageByPeer(this.peerId,this.mid))},{icon:"delete danger",text:"Message.Context.Selection.Delete",onClick:this.onDeleteClick,verify:()=>this.isSelected&&!this.searchSuper.selection.selectionDeleteBtn.classList.contains("hide"),withSelection:!0}],this.element=Ee(this.buttons),this.element.classList.add("search-contextmenu","contextmenu"),document.getElementById("page-chats").append(this.element)}}class $s{constructor(e){this.tabs={},this.prevTabId=-1,this.lazyLoadQueue=new te.d,this.middleware=Object(ks.a)(),this.historyStorage={},this.usedFromHistory={},this.urlsToRevoke=[],this.loadMutex=Promise.resolve(),this.nextRates={},this.loadPromises={},this.loaded={},this.loadedChats=!1,this.firstLoad=!0,this.log=Object(J.b)("SEARCH-SUPER"),this.monthContainers={},this.mediaTabsMap=new Map,this.asChatList=!1,this.groupByMonth=!0,this.hideEmptyTabs=!0,this.showSender=!1,this.onTransitionStart=()=>{this.container.classList.add("sliding")},this.onTransitionEnd=()=>{this.container.classList.remove("sliding")},Object(L.g)(this,e),this.container=document.createElement("div"),this.container.classList.add("search-super"),this.searchContextMenu=new Qs(this.container,this),this.selection=new Ks(this,i.a);const t=this.navScrollableContainer=document.createElement("div");t.classList.add("search-super-tabs-scrollable","menu-horizontal-scrollable","sticky");const s=this.navScrollable=new P.a(t);s.container.classList.add("search-super-nav-scrollable");const n=this.nav=document.createElement("nav");n.classList.add("search-super-tabs","menu-horizontal-div"),this.tabsMenu=n,s.container.append(n);for(const e of this.mediaTabs){const t=document.createElement("div");t.classList.add("menu-horizontal-div-item");const s=document.createElement("span"),i=document.createElement("i");s.append(Object(A.i18n)(e.name)),s.append(i),t.append(s),Object(ie.ripple)(t),this.tabsMenu.append(t),this.mediaTabsMap.set(e.type,e),e.menuTab=t}this.tabsContainer=document.createElement("div"),this.tabsContainer.classList.add("search-super-tabs-container","tabs-container"),pe.IS_TOUCH_SUPPORTED&&_s(this.tabsContainer,e=>{const t=this.selectTab.prevId();this.selectTab(e?t+1:t-1)});for(const e of this.mediaTabs){const t=document.createElement("div");t.classList.add("search-super-container-"+e.type,"tabs-tab");const s=document.createElement("div");s.classList.add("search-super-content-"+e.type),t.append(s),this.tabsContainer.append(t),this.tabs[e.inputFilter]=s,e.contentTab=s}this.container.append(t,this.tabsContainer),this.searchGroupMedia=new O(!1,"messages",!0),this.scrollable.onScrolledBottom=()=>{this.mediaTab.contentTab&&this.mediaTab.contentTab.childElementCount&&this.load(!0)},this.selectTab=Object(ee.a)(this.tabsMenu,this.tabsContainer,(e,t,s)=>{if(this.prevTabId===e&&!this.skipScroll)return void this.scrollable.scrollIntoViewNew(this.container,"start");const i=this.mediaTabs[e];this.onChangeTab&&this.onChangeTab(i);const n=this.mediaTab;if(this.mediaTab=i,-1!==this.prevTabId&&s&&this.onTransitionStart(),this.skipScroll)this.skipScroll=!1;else{const e=this.container.offsetTop;let t=this.scrollable.scrollTop;if(t<e&&(this.scrollable.scrollIntoViewNew(this.container,"start"),t=e),n.scroll={scrollTop:t,scrollHeight:this.scrollable.scrollHeight},void 0===i.scroll){const e=this.container.getBoundingClientRect(),s=this.container.parentElement.getBoundingClientRect(),n=e.y-s.y;t>n&&(i.scroll={scrollTop:n,scrollHeight:0})}if(i.scroll){const e=n.scroll.scrollTop-i.scroll.scrollTop;e&&(i.contentTab.style.transform=`translateY(${e}px)`)}}-1===this.prevTabId||i.contentTab.childElementCount||this.load(!0),this.prevTabId=e},()=>{this.scrollable.onScroll(),void 0!==this.mediaTab.scroll&&(this.mediaTab.contentTab.style.transform="",this.scrollable.scrollTop=this.mediaTab.scroll.scrollTop),this.onTransitionEnd()},void 0,s),Object(l.b)(this.tabsContainer,e=>{this.selection.isSelecting&&(Object(c.a)(e),this.selection.toggleByElement(Object(Ce.a)(e.target,"search-super-item")))},{capture:!0,passive:!1});const a=(e,t,s,n)=>{const a=Object(Ce.a)(n.target,e);if(!a)return;const o=+a.dataset.mid;if(!o)return void this.log.warn("no messageId by click on target:",a);const r=+a.dataset.peerId,l=Array.from(this.tabs[s].querySelectorAll("."+t)).map(t=>{const s=Object(Ce.a)(t,e);return{element:t,mid:+s.dataset.mid,peerId:+s.dataset.peerId}}),c=l.findIndex(e=>e.mid===o&&e.peerId===r),d=i.a.getMessageByPeer(r,o);(new fo).setSearchContext(this.copySearchContext(s)).openMedia(d,l[c].element,0,!1,l.slice(0,c),l.slice(c+1))};Object(l.b)(this.tabs.inputMessagesFilterPhotoVideo,a.bind(null,"grid-item","grid-item","inputMessagesFilterPhotoVideo")),Object(l.b)(this.tabs.inputMessagesFilterDocument,a.bind(null,"document-with-thumb","media-container","inputMessagesFilterDocument")),this.mediaTab=this.mediaTabs[0],Object(Cs.a)(()=>{this.lazyLoadQueue.lock()},()=>{this.lazyLoadQueue.unlockAndRefresh()})}filterMessagesByType(e,t){if("inputMessagesFilterEmpty"===t)return e;"inputMessagesFilterUrl"!==t&&(e=e.filter(e=>!!e.media));let s=[];switch(t){case"inputMessagesFilterPhotoVideo":for(let t of e){let e=t.media.photo||t.media.document||t.media.webpage&&t.media.webpage.document;e&&("document"===e._&&"video"!==e.type||s.push(t))}break;case"inputMessagesFilterDocument":for(let t of e)t.media.document&&!["voice","audio","gif","sticker","round"].includes(t.media.document.type)&&s.push(t);break;case"inputMessagesFilterUrl":for(let t of e)s.push(t);break;case"inputMessagesFilterMusic":for(let t of e)t.media.document&&"audio"===t.media.document.type&&s.push(t);break;case"inputMessagesFilterVoice":for(let t of e)t.media.document&&"voice"===t.media.document.type&&s.push(t);break;case"inputMessagesFilterRoundVoice":for(let t of e)t.media.document&&["voice","round"].includes(t.media.document.type)&&s.push(t)}return s}performSearchResult(e,t,s=!0){var n;return qs(this,void 0,void 0,(function*(){const a=[],o=t.contentTab,l=[],c=this.middleware.get();let d,h=t.inputFilter;switch(yield Object(Cs.c)(),"inputMessagesFilterPhotoVideo"===h&&this.searchContext.query.trim()?(h="inputMessagesFilterEmpty",d=this.searchGroupMedia,o.append(d.container)):"inputMessagesFilterEmpty"===h&&(d=this.searchGroups.messages),h){case"inputMessagesFilterEmpty":for(const t of e){const{dialog:e,dom:s}=Do.addDialogNew({dialog:t.peerId,container:d.list,drawStatus:!1,avatarSize:54});Do.setLastMessage(e,t,s,this.searchContext.query)}d.list.childElementCount&&d.setActive();break;case"inputMessagesFilterPhotoVideo":for(const t of e){const e=t.media.photo||t.media.document||t.media.webpage&&t.media.webpage.document,s=document.createElement("div");let i;s.classList.add("grid-item");const n=r.a.choosePhotoSize(e,200,200);i="photo"!==e._?vs({doc:e,message:t,container:s,boxWidth:0,boxHeight:0,lazyLoadQueue:this.lazyLoadQueue,middleware:c,onlyPreview:!0,withoutPreloader:!0,noPlayButton:!0,size:n}).thumb:ys({photo:e,message:t,container:s,boxWidth:0,boxHeight:0,lazyLoadQueue:this.lazyLoadQueue,middleware:c,withoutPreloader:!0,noBlur:!0,size:n}),[i.images.thumb,i.images.full].filter(Boolean).forEach(e=>{e.classList.add("grid-item-media")}),l.push(i.loadPromises.thumb),a.push({element:s,message:t})}break;case"inputMessagesFilterVoice":case"inputMessagesFilterRoundVoice":case"inputMessagesFilterMusic":case"inputMessagesFilterDocument":for(const t of e){const e=this.showSender||["voice","round"].includes(t.media.document.type),s=fs({message:t,withTime:!e,fontWeight:400,voiceAsMusic:!0,showSender:e,searchContext:this.copySearchContext(h),lazyLoadQueue:this.lazyLoadQueue,noAutoDownload:!0});["audio","voice","round"].includes(t.media.document.type)&&s.classList.add("audio-48"),a.push({element:s,message:t})}break;case"inputMessagesFilterUrl":for(let t of e){let e;if((null===(n=t.media)||void 0===n?void 0:n.webpage)&&"webPageEmpty"!==t.media.webpage._)e=t.media.webpage;else{const s=t.totalEntities?t.totalEntities.find(e=>"messageEntityUrl"===e._||"messageEntityTextUrl"===e._):null;let i,n,a;if(s)a=t.message.slice(s.offset,s.offset+s.length);else{const e=Z.b.matchUrl(t.message);if(!e)continue;i=e[0]}i="messageEntityTextUrl"===(null==s?void 0:s._)?s.url:i||a,n=i;const o=t.message===i;i.match(/^(ftp|http|https):\/\//)||(n="https://"+i,i=i.includes("@")?i:"https://"+i),n=new URL(n).hostname,e={url:i,display_url:n},o||(e.description=t.message,e.rDescription=Z.b.wrapRichText(Object(X.f)(t.message,150,180)))}document.createElement("div");let s=document.createElement("div");if(s.classList.add("preview","row-media"),e.photo){ys({container:s,message:null,photo:e.photo,boxWidth:0,boxHeight:0,withoutPreloader:!0,lazyLoadQueue:this.lazyLoadQueue,middleware:c,size:r.a.choosePhotoSize(e.photo,60,60,!1),loadPromises:l,noBlur:!0})}else s.classList.add("empty"),s.innerHTML=Z.b.getAbbreviation(e.title||e.display_url||e.description||e.url,!0);let o=e.rTitle||"",d=e.rDescription||"";const h=Object(Rs.a)(d),u=Object(Rs.a)(Z.b.wrapRichText(e.url||"")).firstElementChild;u instanceof HTMLAnchorElement&&(u.innerText=decodeURIComponent(u.href)),h.firstChild&&h.append("\n"),h.append(u),this.showSender&&h.append("\n",i.a.wrapSenderToPeer(t)),o||(o=Z.b.wrapPlainText(e.display_url.split("/",1)[0]));const p=new Je({title:o,titleRight:i.a.wrapSentTime(t),subtitle:h,havePadding:!0,clickable:!0,noRipple:!0});p.container.append(s),p.container.innerText.trim().length&&a.push({element:p.container,message:t})}}if(this.loadMutex&&l.push(this.loadMutex),!l.length||(yield Promise.all(l),c())){if(a.length){const e=s?"append":"prepend";a.forEach(t=>{const{element:s,message:i}=t,n=this.getMonthContainerByTimestamp(this.groupByMonth?i.date:0,h);s.classList.add("search-super-item"),s.dataset.mid=""+i.mid,s.dataset.peerId=""+i.peerId,n.items[e](s),this.selection.isSelecting&&this.selection.toggleElementCheckbox(s,!0)})}this.afterPerforming("inputMessagesFilterEmpty"===h?1:e.length,o)}}))}afterPerforming(e,t){if(t){const s=t.parentElement;if(Array.from(s.children).slice(1).forEach(e=>{e.remove()}),!e&&!t.childElementCount){const e=document.createElement("div");e.innerText="Nothing interesting here yet...",e.classList.add("position-center","text-center","content-empty","no-select"),s.append(e)}}}loadChats(){const e=new Set,t=this.middleware.get();for(let e in this.searchGroups){const t=this.searchGroups[e];this.tabs.inputMessagesFilterEmpty.append(t.container),t.clear()}const s=this.searchContext.query;if(s){const r=(t,i,r=!1)=>{t.forEach(t=>{if(e.has(t))return;e.add(t);const l=o.a.getPeer(t),{dom:c}=Do.addDialogNew({dialog:t,container:i.list,drawStatus:!1,avatarSize:48,autonomous:i.autonomous});if(r&&(l.participants_count||l.participants)){const e=new RegExp(`(${Object(X.e)(s)}|${Object(X.e)(Object(ps.b)(s))})`,"gi");c.titleSpan.innerHTML=c.titleSpan.innerHTML.replace(e,"<i>$1</i>"),c.lastMessageSpan.append(n.default.getChatMembersString(-t))}else if(t===a.default.myId)c.lastMessageSpan.append(Object(A.i18n)("Presence.YourChat"));else{let e=o.a.getPeerUsername(t);if(e)e="@"+e;else{const s=T.a.getUser(t);s&&s.phone&&(e="+"+Object(Fs.a)(s.phone).formatted)}c.lastMessageSpan.innerHTML="<i>"+e+"</i>"}}),i.toggle()},l=e=>{if(t())return e};return Promise.all([T.a.getContacts(s,!0).then(l).then(e=>{e&&r(e,this.searchGroups.contacts,!0)}),T.a.searchContacts(s,20).then(l).then(e=>{if(e&&(r(e.my_results,this.searchGroups.contacts,!0),r(e.results,this.searchGroups.globalContacts),this.searchGroups.globalContacts.nameEl.lastElementChild&&this.searchGroups.globalContacts.nameEl.lastElementChild.remove(),this.searchGroups.globalContacts.container.classList.add("is-short"),this.searchGroups.globalContacts.list.childElementCount>3)){const e=document.createElement("div");e.classList.add("search-group__show-more"),e.innerText="Show more",this.searchGroups.globalContacts.nameEl.append(e),e.addEventListener("click",()=>{const t=this.searchGroups.globalContacts.container.classList.toggle("is-short");e.innerText=t?"Show more":"Show less"})}}),i.a.getConversations(s,0,20,0).promise.then(l).then(e=>{e&&r(e.dialogs.map(e=>e.peerId),this.searchGroups.contacts,!0)})])}if(this.searchContext.peerId||this.searchContext.minDate)return Promise.resolve();{const e=(e=!0)=>k.default.getState().then(s=>{t()&&(this.searchGroups.recent.list.innerHTML="",s.recentSearch.slice(0,20).forEach(e=>{let{dialog:t,dom:s}=Do.addDialogNew({dialog:e,container:this.searchGroups.recent.list,drawStatus:!1,meAsSaved:!0,avatarSize:48,autonomous:!0});s.lastMessageSpan.append(e>0?T.a.getUserStatusString(e):n.default.getChatMembersString(-e))}),s.recentSearch.length?e&&this.searchGroups.recent.setActive():this.searchGroups.recent.clear())});return Promise.all([T.a.getTopPeers("correspondents").then(e=>{if(!t())return;const s=e.findIndex(e=>e.id===a.default.myId);-1!==s&&(e=e.slice()).splice(s,1),e.length&&e.forEach(e=>{Do.addDialogNew({dialog:e.id,container:this.searchGroups.people.list,drawStatus:!1,onlyFirstName:!0,avatarSize:54,autonomous:!1})}),this.searchGroups.people.setActive()}),e()])}}loadMembers(e){const t=-this.searchContext.peerId,s=this.middleware.get();let i;const a=t=>qs(this,void 0,void 0,(function*(){this.loadMutex&&(yield this.loadMutex,!s())||(this.membersList||(this.membersList=new Os({lazyLoadQueue:this.lazyLoadQueue,rippleEnabled:!1}),this.membersList.list.addEventListener("click",e=>{const t=Object(mt.a)(e.target,"LI");if(!t)return;const s=+t.dataset.peerId;let i=Promise.resolve();v.b.isMobile&&(i=$t.toggleSidebar(!1)),i.then(()=>{mo.setInnerPeer(s)})}),e.contentTab.append(this.membersList.list),this.afterPerforming(1,e.contentTab)),t.forEach(e=>{const t=G.a.getParticipantPeerId(e);if(t<0)return;T.a.getUser(t).pFlags.deleted||this.membersList.add(t)}))}));if(G.a.isChannel(t)){const o=this.membersList?200:50;i=n.default.getChannelParticipants(t,void 0,o,this.nextRates[e.inputFilter]).then(t=>{if(!s())return;let i=e.contentTab.firstElementChild;return this.nextRates[e.inputFilter]=(i?i.childElementCount:0)+t.participants.length,t.participants.length<o&&(this.loaded[e.inputFilter]=!0),a(t.participants)})}else i=n.default.getChatFull(t).then(t=>{if(!s())return;this.loaded[e.inputFilter]=!0;const i=t.participants;return"chatParticipantsForbidden"!==i._?a(i.participants):void 0});return this.loadPromises[e.inputFilter]=i.finally(()=>{s()&&(this.loadPromises[e.inputFilter]=null)})}loadType(e,t,s,n){var a,o;const r=e.inputFilter;if(this.loadPromises[r])return this.loadPromises[r];if("members"===e.type)return this.loadMembers(e);const l=null!==(a=this.historyStorage[r])&&void 0!==a?a:this.historyStorage[r]=[];if(!("inputMessagesFilterEmpty"!==r||l.length||(this.loadedChats||(this.loadChats(),this.loadedChats=!0),this.searchContext.query.trim()||this.searchContext.peerId||this.searchContext.minDate)))return this.loaded[r]=!0,Promise.resolve();const c="load ["+r+"]: ";if(l.length&&this.usedFromHistory[r]<l.length&&!t){let t=[],n=Math.max(0,this.usedFromHistory[r]),a=0;do{let e=l.slice(n,n+s);n+=e.length,a+=e.length,t.push(...this.filterMessagesByType(e.map(e=>i.a.getMessageByPeer(e.peerId,e.mid)),r))}while(a<s&&n<l.length);return this.usedFromHistory[r]=n,this.performSearchResult(t,e).finally(()=>{setTimeout(()=>{this.scrollable.checkForTriggers()},0)})}let d=l.length?l[l.length-1].mid:0;return this.loadPromises[r]=i.a.getSearch(Object.assign(Object.assign({},this.searchContext),{inputFilter:{_:r},maxId:d,limit:s,nextRate:null!==(o=this.nextRates[r])&&void 0!==o?o:this.nextRates[r]=0})).then(i=>{if(l.push(...i.history.map(e=>({mid:e.mid,peerId:e.peerId}))),this.log(c+"search house of glass",r,i),n())return(i.history.length<s||void 0!==this.searchContext.folderId&&!i.next_rate||i.history.length===i.count)&&(this.loaded[r]=!0),this.nextRates[r]=i.next_rate,t?Promise.resolve():(this.usedFromHistory[r]=l.length,this.loaded[r]||(this.loadPromises[r]||Promise.resolve()).then(()=>{setTimeout(()=>{if(n()&&this.mediaTab===e){const e=this.load(!0,!0);e&&e.then(()=>{n()&&setTimeout(()=>{this.scrollable.checkForTriggers()},0)})}},0)}),this.performSearchResult(this.filterMessagesByType(i.history,r),e))}).catch(e=>{this.log.error("load error:",e)}).finally(()=>{this.loadPromises[r]=null})}load(e=!1,t=!1){return qs(this,void 0,void 0,(function*(){const s=this.searchContext.peerId;this.log("load",e,s,this.loadPromises);const n=this.middleware.get();if(this.firstLoad){if(this.hideEmptyTabs){const e=this.mediaTabs.filter(e=>"inputMessagesFilterEmpty"!==e.inputFilter),t=e.map(e=>({_:e.inputFilter})),a=yield i.a.getSearchCounters(s,t);if(!n())return;if(this.loadMutex&&(yield this.loadMutex,!n()))return;let o,r=0;e.forEach(e=>{const t=a.find(t=>t.filter._===e.inputFilter);e.menuTab.classList.toggle("hide",!t.count),e.menuTab.classList.remove("active"),t.count&&void 0===o&&(o=e),t.count&&++r});const l=this.mediaTabsMap.get("members"),c=this.canViewMembers();l.menuTab.classList.toggle("hide",!c),c&&(o=l),this.container.classList.toggle("hide",!o),this.container.parentElement.classList.toggle("search-empty",!o),o&&(this.skipScroll=!0,this.selectTab(this.mediaTabs.indexOf(o),!1),o.menuTab.classList.add("active"),this.navScrollableContainer.classList.toggle("hide",r<=1))}this.firstLoad=!1}let a=e?[this.mediaTab]:this.mediaTabs.filter(e=>e!==this.mediaTab);if(a=a.filter(e=>{const t=e.inputFilter;return!this.loaded[t]||this.historyStorage[t]&&this.usedFromHistory[t]<this.historyStorage[t].length}),s>0&&a.findAndSplice(e=>"members"===e.type),!a.length)return;const o=t?50:Math.round(3*(yt.a.windowH/130|0)*1.25),r=a.map(e=>this.loadType(e,t,o,n));return Promise.all(r).catch(e=>{this.log.error("Load error all promises:",e)})}))}getMonthContainerByTimestamp(e,t){var s;const i=new Date(1e3*e);i.setHours(0,0,0),i.setDate(1);const n=i.getTime(),a=null!==(s=this.monthContainers[t])&&void 0!==s?s:this.monthContainers[t]={};if(!(n in a)){const e=document.createElement("div");e.className="search-super-month";const s=document.createElement("div");s.classList.add("search-super-month-name");const o={month:"long"};i.getFullYear()!==(new Date).getFullYear()&&(o.year="numeric");const r=new A.default.IntlDateElement({date:i,options:o}).element;s.append(r),e.append(s);const l=document.createElement("div");l.classList.add("search-super-month-items"),e.append(s,l);const c=Object(L.e)(a,"desc");let d=0;for(;d<c.length;++d){if(n>c[d])break}a[n]={container:e,items:l},Ps(e,this.tabs[t],d)}return a[n]}canViewMembers(){return this.searchContext.peerId<0&&!G.a.isBroadcast(-this.searchContext.peerId)&&G.a.hasRights(-this.searchContext.peerId,"view_participants")}cleanup(){this.loadPromises={},this.loaded={},this.loadedChats=!1,this.nextRates={},this.firstLoad=!0,this.lazyLoadQueue.clear(),this.mediaTabs.forEach(e=>{this.usedFromHistory[e.inputFilter]=-1}),this.selection.isSelecting&&this.selection.cancelSelection(),this.middleware.clean(),this.cleanScrollPositions(),this.membersList=void 0}cleanScrollPositions(){this.mediaTabs.forEach(e=>{e.scroll=void 0})}cleanupHTML(e=!1){this.urlsToRevoke.length&&(this.urlsToRevoke.forEach(e=>{URL.revokeObjectURL(e)}),this.urlsToRevoke.length=0),this.mediaTabs.forEach(e=>{if(e.contentTab.innerHTML="",this.hideEmptyTabs&&(this.container.classList.add("hide"),this.container.parentElement.classList.add("search-empty")),"chats"!==e.type&&!this.historyStorage[e.inputFilter]){const t=e.contentTab.parentElement;t.querySelector(".preloader")||Object(se.f)(t,!0);const s=t.querySelector(".content-empty");s&&s.remove()}}),this.monthContainers={},this.searchGroupMedia.clear(),this.scrollable.scrollTop=0}copySearchContext(e){const t=Object(L.a)(this.searchContext);return t.inputFilter={_:e},t.nextRate=this.nextRates[e],t}setQuery({peerId:e,query:t,threadId:s,historyStorage:i,folderId:n,minDate:a,maxDate:o}){this.searchContext={peerId:e||0,query:t||"",inputFilter:{_:this.mediaTab.inputFilter},threadId:s,folderId:n,minDate:a,maxDate:o},this.historyStorage=null!=i?i:{},this.cleanup()}}var Ys,Xs=s(69);!function(e){e[e.Everybody=2]="Everybody",e[e.Contacts=1]="Contacts",e[e.Nobody=0]="Nobody"}(Ys||(Ys={}));const Js=new class{constructor(){this.privacy={},a.default.addMultipleEventsListeners({updatePrivacy:e=>{const t=e.key._;this.privacy[t]=e.rules,a.default.dispatchEvent("privacy_update",e)}})}setPrivacy(e,t){return rt.a.invokeApi("account.setPrivacy",{key:{_:e},rules:t}).then(s=>(T.a.saveApiUsers(s.users),G.a.saveApiChats(s.chats),Xs.a.processLocalUpdate({_:"updatePrivacy",key:{_:Object(X.b)(e)},rules:t.map(e=>{const t={};return Object.assign(t,e),t._=Object(X.b)(t._),t})}),s.rules))}getPrivacy(e){const t=Object(X.b)(e),s=this.privacy[t];return s?Promise.resolve(s):this.privacy[t]=rt.a.invokeApi("account.getPrivacy",{key:{_:e}}).then(e=>(T.a.saveApiUsers(e.users),G.a.saveApiChats(e.chats),this.privacy[t]=e.rules))}getPrivacyRulesDetails(e){const t=[];let s={users:[],chats:[]},i={users:[],chats:[]};return e.forEach(e=>{switch(e._){case"privacyValueAllowAll":t.push(2);break;case"privacyValueDisallowAll":t.push(0);break;case"privacyValueAllowContacts":t.push(1);break;case"privacyValueAllowChatParticipants":s.chats.push(...e.chats);break;case"privacyValueAllowUsers":s.users.push(...e.users);break;case"privacyValueDisallowChatParticipants":i.chats.push(...e.chats);break;case"privacyValueDisallowUsers":i.users.push(...e.users)}}),{type:t[0],disallowPeers:i,allowPeers:s}}};de.a.appPrivacyManager=Js;var Zs=Js;class ei{constructor(e){this.options=e,this.onRadioChange=e=>{e=+e,this.type=e;const t=this.options.captions[this.type],s=this.radioSection.caption;t?Object(A._i18n)(s,t):s.innerHTML="",s.classList.toggle("hide",!t),this.exceptions&&(this.exceptions.get("allow").row.container.classList.toggle("hide",this.type===Ys.Everybody),this.exceptions.get("disallow").row.container.classList.toggle("hide",this.type===Ys.Nobody)),this.options.onRadioChange&&this.options.onRadioChange(e)},e.captions&&e.captions.reverse(),this.radioSection=new nn({name:e.title,caption:!0}),this.radioRows=new Map;let t=[{type:Ys.Everybody,langKey:"PrivacySettingsController.Everbody"},{type:Ys.Contacts,langKey:"PrivacySettingsController.MyContacts"},{type:Ys.Nobody,langKey:"PrivacySettingsController.Nobody"}];e.skipTypes&&(t=t.filter(t=>!e.skipTypes.includes(t.type)));const s=Object(tt.b)();t.forEach(({type:e,langKey:t})=>{const i=new Je({radioField:new st({langKey:t,name:s,value:""+e})});this.radioRows.set(e,i)});const i=Ze([...this.radioRows.values()],this.onRadioChange);if(this.radioSection.content.append(i),e.appendTo&&e.appendTo.append(this.radioSection.container),!e.noExceptions){const t=an(e.appendTo,"PrivacyExceptions","PrivacySettingsController.PeerInfo");this.exceptions=new Map([["disallow",{titleLangKey:e.exceptionTexts[0],key:"disallow",row:null,icon:"deleteuser",subtitleLangKey:"PrivacySettingsController.AddUsers",clickable:!0}],["allow",{titleLangKey:e.exceptionTexts[1],key:"allow",row:null,icon:"adduser",subtitleLangKey:"PrivacySettingsController.AddUsers",clickable:!0}]]),this.exceptions.forEach(s=>{s.row=new Je(s),s.row.container.addEventListener("click",()=>{n.then(()=>{const t=this.peerIds[s.key];new jt(e.tab.slider).open({type:"privacy",skippable:!0,title:s.titleLangKey,placeholder:"PrivacyModal.Search.Placeholder",takeOut:e=>{t.length=0,t.push(...e),s.row.subtitle.innerHTML="",s.row.subtitle.append(...this.generateStr(this.splitPeersByType(e)))},selectedPeerIds:t})})}),t.append(s.row.container)})}const n=Zs.getPrivacy(e.inputKey).then(t=>{const s=Zs.getPrivacyRulesDetails(t);this.setRadio(s.type),this.exceptions&&(this.peerIds={},["allow","disallow"].forEach(e=>{const t=[],i="allow"===e?s.allowPeers:s.disallowPeers;t.push(...i.users),t.push(...i.chats.map(e=>-e)),this.peerIds[e]=t;const n=this.exceptions.get(e).row.subtitle;n.innerHTML="",n.append(...this.generateStr(i))})),e.tab.eventListener.addEventListener("destroy",()=>{const t=[];switch(this.type){case Ys.Everybody:t.push({_:"inputPrivacyValueAllowAll"});break;case Ys.Contacts:t.push({_:"inputPrivacyValueAllowContacts"});break;case Ys.Nobody:t.push({_:"inputPrivacyValueDisallowAll"})}this.exceptions&&[["allow","inputPrivacyValueAllowChatParticipants","inputPrivacyValueAllowUsers"],["disallow","inputPrivacyValueDisallowChatParticipants","inputPrivacyValueDisallowUsers"]].forEach(([e,s,i],n)=>{if(this.exceptions.get(e).row.container.classList.contains("hide"))return;const a=this.peerIds[e];if(a){const e=this.splitPeersByType(a);e.chats.length&&t.push({_:s,chats:e.chats.map(e=>-e)}),e.users.length&&t.push({_:i,users:e.users.map(e=>T.a.getUserInput(e))})}}),Zs.setPrivacy(e.inputKey,t)},{once:!0})})}setRadio(e){const t=this.radioRows.get(e);this.onRadioChange(e),t.radioField.input.checked=!0}splitPeersByType(e){const t={users:[],chats:[]};return e.forEach(e=>{t[e<0?"chats":"users"].push(e<0?-e:e)}),t}generateStr(e){return e.users.length||e.chats.length?Object(A.join)([e.users.length?Object(A.i18n)("Users",[e.users.length]):null,e.chats.length?Object(A.i18n)("Chats",[e.chats.length]):null].filter(Boolean),!1):[Object(A.i18n)("PrivacySettingsController.AddUsers")]}}class ti extends W{init(){this.container.classList.add("privacy-tab","privacy-phone-number"),this.setTitle("PrivacyPhone");const e=new ei({tab:this,title:"PrivacyPhoneTitle",inputKey:"inputPrivacyKeyPhoneNumber",captions:["PrivacyPhoneInfo","PrivacyPhoneInfo",""],exceptionTexts:["PrivacySettingsController.NeverShare","PrivacySettingsController.AlwaysShare"],appendTo:this.scrollable,onRadioChange:e=>{t.setRadio(Ys.Everybody),t.radioSection.container.classList.toggle("hide",e!==Ys.Nobody)}}),t=new ei({tab:this,title:"PrivacyPhoneTitle2",inputKey:"inputPrivacyKeyAddedByPhone",captions:["PrivacyPhoneInfo3","PrivacyPhoneInfo3",""],noExceptions:!0,skipTypes:[Ys.Nobody]});this.scrollable.container.insertBefore(t.radioSection.container,e.radioSection.container.nextSibling)}}var si=s(74);class ii extends V{init(){this.container.classList.add("two-step-verification","two-step-verification-set"),this.setTitle("TwoStepVerificationPasswordSet");const e=new nn({caption:"TwoStepVerificationPasswordSetInfo",noDelimiter:!0}),t=hs.getAnimatedEmojiSticker("🥳"),s=document.createElement("div");t?Ls({doc:t,div:s,loop:!0,play:!0,width:160,height:160}).then(()=>{}):s.classList.add("media-sticker-wrapper"),e.content.append(s);const i=e.generateContentElement(),n=document.createElement("div");n.classList.add("input-wrapper");const a=Object(U.a)("btn-primary btn-color-primary",{text:"TwoStepVerificationPasswordReturnSettings"});Object(l.b)(a,e=>{this.close()}),this.slider.sliceTabsUntilTab($i,this),n.append(a),i.append(n),this.scrollable.container.append(e.container)}}var ni=s(105);function ai(e){return!h.IS_MOBILE_SAFARI||!e}class oi extends V{constructor(){super(...arguments),this.isFirst=!1}init(){this.container.classList.add("two-step-verification","two-step-verification-email-confirmation"),this.setTitle("TwoStepAuth.RecoveryTitle");const e=new nn({caption:!0,noDelimiter:!0});Object(A._i18n)(e.caption,"TwoStepAuth.ConfirmEmailCodeDesc",[this.email]);const t=hs.getAnimatedEmojiSticker("📬"),s=document.createElement("div");t?Ls({doc:t,div:s,loop:!1,play:!0,width:160,height:160,emoji:"📬"}).then(()=>{}):s.classList.add("media-sticker-wrapper"),e.content.append(s);const i=e.generateContentElement(),n=document.createElement("div");n.classList.add("input-wrapper");const a=this.codeInputField=new ni.a({name:"recovery-email-code",label:"TwoStepAuth.RecoveryCode",length:this.length,onFill:e=>{d(!0),si.a.confirmPasswordEmail(""+e).then(e=>{c()}).catch(e=>{switch(e.type){case"CODE_INVALID":a.input.classList.add("error"),Object(x.a)(a.label,Object(A.i18n)("TwoStepAuth.RecoveryCodeInvalid"));break;case"EMAIL_HASH_EXPIRED":a.input.classList.add("error"),Object(x.a)(a.label,Object(A.i18n)("TwoStepAuth.RecoveryCodeExpired"));break;default:console.error("confirm error",e)}d(!1)})}}),o=Object(U.a)("btn-primary btn-primary-transparent primary",{text:"TwoStepAuth.EmailCodeChangeEmail"}),r=Object(U.a)("btn-primary btn-secondary btn-primary-transparent primary",{text:"ResendCode"}),c=()=>{new ii(this.slider).open()},d=e=>{Object(ut.a)([a.input,o,r],e)};Object(l.b)(o,e=>{d(!0),si.a.cancelPasswordEmail().then(e=>{this.slider.sliceTabsUntilTab(ri,this),this.close()},()=>{d(!1)})}),Object(l.b)(r,e=>{d(!0);const t=Object(se.f)(r);si.a.resendPasswordEmail().then(e=>{t.remove(),d(!1)})}),n.append(a.container,o,r),i.append(n),this.scrollable.container.append(e.container)}onOpenAfterTimeout(){ai(this.isFirst)&&this.codeInputField.input.focus()}}class ri extends V{constructor(){super(...arguments),this.isFirst=!1}init(){this.container.classList.add("two-step-verification","two-step-verification-email"),this.setTitle("RecoveryEmailTitle");const e=new nn({caption:!0,noDelimiter:!0}),t=hs.getAnimatedEmojiSticker("💌"),s=document.createElement("div");t?Ls({doc:t,div:s,loop:!1,play:!0,width:160,height:160,emoji:"💌"}).then(()=>{}):s.classList.add("media-sticker-wrapper"),e.content.append(s);const i=e.generateContentElement(),n=document.createElement("div");n.classList.add("input-wrapper");const a=this.inputField=new F.b({name:"recovery-email",label:"RecoveryEmail",plainText:!0});a.input.addEventListener("keypress",e=>{if("Enter"===e.key)return Object(c.a)(e),h()}),a.input.addEventListener("input",e=>{a.input.classList.remove("error")});const o=Object(U.a)("btn-primary btn-color-primary",{text:"Continue"}),r=Object(U.a)("btn-primary btn-secondary btn-primary-transparent primary",{text:"YourEmailSkip"}),d=()=>{new ii(this.slider).open()},h=()=>{const e=a.value.trim(),t=Z.b.matchEmail(e);if(!t||t[0].length!==e.length)return void a.input.classList.add("error");u(!0);const s=Object(se.f)(o);si.a.updateSettings({hint:this.hint,currentPassword:this.plainPassword,newPassword:this.newPassword,email:e}).then(e=>{d()},t=>{if(t.type.includes("EMAIL_UNCONFIRMED")){const s=+t.type.match(/^EMAIL_UNCONFIRMED_(\d+)/)[1],i=new oi(this.slider);i.state=this.state,i.email=e,i.length=s,i.open()}else console.log("password set error",t);u(!1),s.remove()})};Object(l.b)(o,h);const u=e=>{e?(o.setAttribute("disabled","true"),r.setAttribute("disabled","true")):(o.removeAttribute("disabled"),r.removeAttribute("disabled"))};Object(l.b)(r,e=>{new ht("popup-skip-email",{buttons:[{langKey:"Cancel",isCancel:!0},{langKey:"YourEmailSkip",callback:()=>{u(!0),Object(se.f)(r),si.a.updateSettings({hint:this.hint,currentPassword:this.plainPassword,newPassword:this.newPassword,email:""}).then(()=>{d()},e=>{u(!1)})},isDanger:!0}],titleLangKey:"YourEmailSkipWarning",descriptionLangKey:"YourEmailSkipWarningText"}).show()}),n.append(a.container,o,r),i.append(n),this.scrollable.container.append(e.container)}onOpenAfterTimeout(){ai(this.isFirst)&&this.inputField.input.focus()}}var li=s(96),ci=s(90),di=s(104);class hi extends V{init(){this.container.classList.add("two-step-verification","two-step-verification-hint"),this.setTitle("TwoStepAuth.SetupHintTitle");const e=new nn({noDelimiter:!0}),t=hs.getAnimatedEmojiSticker("💡"),s=document.createElement("div");t?Ls({doc:t,div:s,loop:!1,play:!0,width:160,height:160,emoji:"💡"}).then(()=>{}):s.classList.add("media-sticker-wrapper"),e.content.append(s);const i=document.createElement("div");i.classList.add("input-wrapper");const n=this.inputField=new F.b({name:"hint",label:"TwoStepAuth.SetupHintPlaceholder"});n.input.addEventListener("keypress",e=>{if("Enter"===e.key)return Object(c.a)(e),n.value?d():h()});const a=(e,t)=>{e&&Object(c.a)(e);const s=t?n.value:void 0;if(s&&this.newPassword===s)return void nt(A.default.format("PasswordAsHintError",!0));const i=new ri(this.slider);i.state=this.state,i.plainPassword=this.plainPassword,i.newPassword=this.newPassword,i.hint=s,i.open()},o=Object(U.a)("btn-primary btn-color-primary",{text:"Continue"}),r=Object(U.a)("btn-primary btn-secondary btn-primary-transparent primary",{text:"YourEmailSkip"}),d=e=>a(e,!0),h=e=>a(e,!1);Object(l.b)(o,d),Object(l.b)(r,h),i.append(n.container,o,r),e.content.append(i),this.scrollable.container.append(e.container)}onOpenAfterTimeout(){this.inputField.input.focus()}}class ui extends V{init(){this.container.classList.add("two-step-verification","two-step-verification-enter-password","two-step-verification-re-enter-password"),this.setTitle("PleaseReEnterPassword");const e=new nn({noDelimiter:!0}),t=document.createElement("div");t.classList.add("input-wrapper");const s=this.passwordInputField=new ci.a({name:"re-enter-password",label:"PleaseReEnterPassword"}),i=new di.a(s,157),n=Object(U.a)("btn-primary btn-color-primary",{text:"Continue"});t.append(s.container,n),e.content.append(i.container,t),this.scrollable.container.append(e.container),s.input.addEventListener("keypress",e=>{if(s.input.classList.contains("error")&&s.setState(F.a.Neutral),"Enter"===e.key)return o()});const a=()=>this.newPassword===s.value||(s.setError(),!1),o=e=>{if(e&&Object(c.a)(e),!a())return;const t=new hi(this.slider);t.state=this.state,t.plainPassword=this.plainPassword,t.newPassword=this.newPassword,t.open()};return Object(l.b)(n,o),i.load()}onOpenAfterTimeout(){this.passwordInputField.input.focus()}}class pi extends V{constructor(){super(...arguments),this.isFirst=!0}init(){const e=!this.state.pFlags.has_password||this.plainPassword;this.container.classList.add("two-step-verification","two-step-verification-enter-password"),this.setTitle(e?"PleaseEnterFirstPassword":"PleaseEnterCurrentPassword");const t=new nn({noDelimiter:!0}),s=document.createElement("div");s.classList.add("input-wrapper");const i=this.passwordInputField=new ci.a({name:"enter-password",label:e?"PleaseEnterFirstPassword":this.state.hint?void 0:"LoginPassword",labelText:!e&&this.state.hint?Z.b.wrapEmojiText(this.state.hint):void 0}),n=new li.a(i,157),a=Object(U.a)("btn-primary btn-color-primary"),o=new A.default.IntlElement({key:"Continue"});a.append(o.element),s.append(i.container,a),t.content.append(n.container,s),this.scrollable.container.append(t.container),i.input.addEventListener("keypress",e=>{if(i.input.classList.contains("error")&&(i.input.classList.remove("error"),o.key="Continue",o.update()),"Enter"===e.key)return d()});const r=()=>!!i.value.length||(i.input.classList.add("error"),!1);let d;if(e)d=e=>{if(e&&Object(c.a)(e),!r())return;const t=new ui(this.slider);t.state=this.state,t.newPassword=i.value,t.plainPassword=this.plainPassword,t.open()};else{let e,t=()=>(e||(e=window.setInterval(t,1e4)),si.a.getState().then(e=>{this.state=e,this.state.hint?i.label.innerHTML=Z.b.wrapEmojiText(this.state.hint):Object(x.a)(i.label,Object(A.i18n)("LoginPassword"))}));d=s=>{if(!r())return void Object(c.a)(s);a.setAttribute("disabled","true"),o.key="PleaseWait",o.update();const l=Object(se.f)(a),d=i.value;si.a.check(i.value,this.state).then(t=>{if(console.log(t),"auth.authorization"===t._){clearInterval(e),n&&n.remove();const t=new mi(this.slider);t.state=this.state,t.plainPassword=d,t.open(),this.slider.removeTabFromHistory(this)}},e=>{a.removeAttribute("disabled"),i.input.classList.add("error"),e.type,o.key="TwoStepAuth.InvalidPassword",o.update(),l.remove(),i.select(),t()})},t()}return Object(l.b)(a,d),n.load()}onOpenAfterTimeout(){ai(this.isFirst)&&this.passwordInputField.input.focus()}}class mi extends V{init(){this.container.classList.add("two-step-verification","two-step-verification-main"),this.setTitle("TwoStepVerificationTitle");const e=new nn({caption:!0,noDelimiter:!0}),t=hs.getAnimatedEmojiSticker("🔐"),s=document.createElement("div");t?Ls({doc:t,div:s,loop:!1,play:!0,width:168,height:168,emoji:"🔐"}).then(()=>{}):s.classList.add("media-sticker-wrapper"),e.content.append(s);const i=e.generateContentElement();if(this.state.pFlags.has_password){Object(A._i18n)(e.caption,"TwoStepAuth.GenericHelp");const t=Object(U.a)("btn-primary btn-transparent",{icon:"edit",text:"TwoStepAuth.ChangePassword"}),s=Object(U.a)("btn-primary btn-transparent",{icon:"passwordoff",text:"TwoStepAuth.RemovePassword"}),n=Object(U.a)("btn-primary btn-transparent",{icon:"email",text:this.state.pFlags.has_recovery?"TwoStepAuth.ChangeEmail":"TwoStepAuth.SetupEmail"});Object(l.b)(t,()=>{const e=new pi(this.slider);e.state=this.state,e.plainPassword=this.plainPassword,e.open()}),Object(l.b)(s,()=>{new ht("popup-disable-password",{buttons:[{langKey:"Disable",callback:()=>{si.a.updateSettings({currentPassword:this.plainPassword}).then(()=>{this.slider.sliceTabsUntilTab($i,this),this.close()})},isDanger:!0}],titleLangKey:"TurnPasswordOffQuestionTitle",descriptionLangKey:"TurnPasswordOffQuestion"}).show()}),Object(l.b)(n,()=>{const e=new ri(this.slider);e.state=this.state,e.hint=this.state.hint,e.plainPassword=this.plainPassword,e.newPassword=this.plainPassword,e.isFirst=!0,e.open()}),i.append(t,s,n)}else{Object(A._i18n)(e.caption,"TwoStepAuth.SetPasswordHelp");const t=document.createElement("div");t.classList.add("input-wrapper");const s=Object(U.a)("btn-primary btn-color-primary",{text:"TwoStepVerificationSetPassword"});t.append(s),i.append(t),Object(l.b)(s,e=>{const t=new pi(this.slider);t.state=this.state,t.open()})}this.scrollable.container.append(e.container)}}class gi extends W{init(){this.container.classList.add("privacy-tab","privacy-last-seen"),this.setTitle("PrivacyLastSeen");const e="PrivacySettingsController.LastSeenDescription";new ei({tab:this,title:"LastSeenTitle",inputKey:"inputPrivacyKeyStatusTimestamp",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverShare","PrivacySettingsController.AlwaysShare"],appendTo:this.scrollable})}}class bi extends W{init(){this.container.classList.add("privacy-tab","privacy-profile-photo"),this.setTitle("PrivacyProfilePhoto");const e="PrivacySettingsController.ProfilePhoto.CustomHelp";new ei({tab:this,title:"PrivacyProfilePhotoTitle",inputKey:"inputPrivacyKeyProfilePhoto",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverShare","PrivacySettingsController.AlwaysShare"],appendTo:this.scrollable,skipTypes:[Ys.Nobody]})}}class vi extends W{init(){this.container.classList.add("privacy-tab","privacy-forward-messages"),this.setTitle("PrivacySettings.Forwards");const e="PrivacySettingsController.Forwards.CustomHelp";new ei({tab:this,title:"PrivacyForwardsTitle",inputKey:"inputPrivacyKeyForwards",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable})}}class fi extends W{init(){this.container.classList.add("privacy-tab","privacy-add-to-groups"),this.setTitle("PrivacySettings.Groups");const e="PrivacySettingsController.GroupDescription";new ei({tab:this,title:"WhoCanAddMe",inputKey:"inputPrivacyKeyChatInvite",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable,skipTypes:[Ys.Nobody]})}}class yi extends W{init(){this.container.classList.add("privacy-tab","privacy-calls"),this.setTitle("PrivacySettings.VoiceCalls");const e="PrivacySettingsController.PhoneCallDescription";new ei({tab:this,title:"WhoCanCallMe",inputKey:"inputPrivacyKeyPhoneCall",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable});{const e="PrivacySettingsController.P2p.Desc";new ei({tab:this,title:"PrivacyP2PHeader",inputKey:"inputPrivacyKeyPhoneP2P",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable})}}}class wi extends V{init(){this.container.classList.add("active-sessions-container"),this.setTitle("SessionsTitle");const e=e=>{const t=new Je({title:[e.app_name,e.app_version].join(" "),subtitle:[e.ip,e.country].join(" - "),clickable:!0,titleRight:e.pFlags.current?void 0:Object(re.b)(new Date(1e3*Math.max(e.date_active,e.date_created)))});t.container.dataset.hash=e.hash;const s=document.createElement("div");return s.classList.add("row-midtitle"),s.innerHTML=[e.device_model,e.system_version||e.platform].filter(Boolean).join(", "),t.subtitle.parentElement.insertBefore(s,t.subtitle),t},t=this.authorizations.slice();{const n=new nn({name:"CurrentSession"}),a=t.findAndSplice(e=>e.pFlags.current),o=e(a);if(n.content.append(o.container),t.length){const e=Object(U.a)("btn-primary btn-transparent danger",{icon:"stop",text:"TerminateAllSessions"});Object(l.b)(e,t=>{new ht("revoke-session",{buttons:[{langKey:"Terminate",isDanger:!0,callback:()=>{const t=Object(ut.a)([e],!0);rt.a.invokeApi("auth.resetAuthorizations").then(t=>{e.remove(),s.container.remove(),this.privacyTab.updateActiveSessions()},i).finally(()=>{t()})}}],titleLangKey:"AreYouSureSessionsTitle",descriptionLangKey:"AreYouSureSessions"}).show()}),n.content.append(e)}this.scrollable.append(n.container)}if(!t.length)return;const s=new nn({name:"OtherSessions"});t.forEach(t=>{s.content.append(e(t).container)}),this.scrollable.append(s.container);const i=e=>{"FRESH_RESET_AUTHORISATION_FORBIDDEN"===e.type&&nt(A.default.format("RecentSessions.Error.FreshReset",!0))};let n;const a=()=>{const e=n.dataset.hash;new ht("revoke-session",{buttons:[{langKey:"Terminate",isDanger:!0,callback:()=>{rt.a.invokeApi("account.resetAuthorization",{hash:e}).then(e=>{e&&(n.remove(),this.privacyTab.updateActiveSessions())},i)}}],titleLangKey:"AreYouSureSessionTitle",descriptionLangKey:"TerminateSessionText"}).show()},o=this.menuElement=Ee([{icon:"stop",text:"Terminate",onClick:a}]);o.id="active-sessions-contextmenu",o.classList.add("contextmenu"),document.getElementById("page-chats").append(o),Object(se.a)(this.scrollable.container,e=>{n=Object(Ce.a)(e.target,"row"),n&&"0"!==n.dataset.hash&&(e instanceof MouseEvent&&e.preventDefault(),e instanceof MouseEvent&&(e.cancelBubble=!0),Object(se.e)(e,o),Object(se.d)(o))}),Object(l.b)(this.scrollable.container,e=>{n=Object(Ce.a)(e.target,"row"),n&&"0"!==n.dataset.hash&&a()})}onCloseAfterTimeout(){return this.menuElement&&this.menuElement.remove(),super.onCloseAfterTimeout()}}class Li extends V{init(){this.container.classList.add("blocked-users-container"),this.setTitle("BlockedUsers");{const e=new nn({caption:"BlockedUsersInfo"});this.scrollable.append(e.container)}const e=$({icon:"add",className:"is-visible"});this.content.append(e),Object(l.b)(e,e=>{new It({peerTypes:["contacts"],placeholder:"BlockModal.Search.Placeholder",onSelect:e=>{T.a.toggleBlock(e,!0)}})},{listenerSetter:this.listenerSetter});const t=Do.createChatList();this.scrollable.container.classList.add("chatlist-container"),this.scrollable.append(t);const s=(e,s)=>{const{dom:i}=Do.addDialogNew({dialog:e,container:t,drawStatus:!1,rippleEnabled:!0,avatarSize:48,append:s}),n=T.a.getUser(e);n.pFlags.bot?i.lastMessageSpan.append("@"+n.username):n.phone?i.lastMessageSpan.innerHTML=T.a.formatUserPhone(n.phone):i.lastMessageSpan.append(n.username?"@"+n.username:T.a.getUserStatusString(e))};for(const e of this.peerIds)s(e,!0);let i;const n=this.menuElement=Ee([{icon:"lockoff",text:"Unblock",onClick:()=>{const e=+i.dataset.peerId;T.a.toggleBlock(e,!1)},options:{listenerSetter:this.listenerSetter}}]);n.id="blocked-users-contextmenu",n.classList.add("contextmenu"),document.getElementById("page-chats").append(n),Object(se.a)(this.scrollable.container,e=>{i=Object(mt.a)(e.target,"LI"),i&&(e instanceof MouseEvent&&e.preventDefault(),e instanceof MouseEvent&&(e.cancelBubble=!0),Object(se.e)(e,n),Object(se.d)(n))},this.listenerSetter),this.listenerSetter.add(a.default)("peer_block",e=>{const{peerId:i,blocked:n}=e,a=t.querySelector(`[data-peer-id="${i}"]`);n?a||s(i,!1):a&&a.remove()});let o=!1;this.scrollable.onScrolledBottom=()=>{o||(o=!0,T.a.getBlocked(t.childElementCount,50).then(e=>{for(const t of e.peerIds)s(t,!0);(e.peerIds.length<50||t.childElementCount===e.count)&&(this.scrollable.onScrolledBottom=null),this.scrollable.checkForTriggers()}).finally(()=>{o=!1}))}}onOpenAfterTimeout(){this.scrollable.onScroll()}onCloseAfterTimeout(){return this.menuElement&&this.menuElement.remove(),super.onCloseAfterTimeout()}}var Si=s(109);class Ei extends W{init(){this.container.classList.add("dont-u-dare-block-me"),this.setTitle("PrivacySettings");{const e=new nn({noDelimiter:!0});let t;const s=new Je({icon:"deleteuser",titleLangKey:"BlockedUsers",subtitleLangKey:"Loading",clickable:()=>{const e=new Li(this.slider);e.peerIds=t,e.open()}});let i;s.freezed=!0;const n=new Je({icon:"lock",titleLangKey:"TwoStepVerification",subtitleLangKey:"Loading",clickable:e=>{let t;i.pFlags.has_password?t=new pi(this.slider):i.email_unconfirmed_pattern?(t=new oi(this.slider),t.email=i.email_unconfirmed_pattern,t.length=6,t.isFirst=!0,si.a.resendPasswordEmail()):t=new mi(this.slider),t.state=i,t.open()}});n.freezed=!0;const o=this.activeSessionsRow=new Je({icon:"activesessions",titleLangKey:"SessionsTitle",subtitleLangKey:"Loading",clickable:()=>{const e=new wi(this.slider);e.privacyTab=this,e.authorizations=this.authorizations,e.open()}});o.freezed=!0,e.content.append(s.container,n.container,o.container),this.scrollable.append(e.container);const r=e=>{e?Object(x.a)(s.subtitle,Object(A.i18n)("PrivacySettingsController.UserCount",[e])):Object(x.a)(s.subtitle,Object(A.i18n)("BlockedEmpty",[e]))};this.listenerSetter.add(a.default)("peer_block",()=>{l()});const l=()=>{T.a.getBlocked().then(e=>{s.freezed=!1,r(e.count),t=e.peerIds})};l(),si.a.getState().then(e=>{i=e,Object(x.a)(n.subtitle,Object(A.i18n)(e.pFlags.has_password?"PrivacyAndSecurity.Item.On":"PrivacyAndSecurity.Item.Off")),n.freezed=!1}),this.updateActiveSessions()}{const e=new nn({name:"PrivacyTitle"});e.content.classList.add("privacy-navigation-container");const t={},s=t.inputPrivacyKeyPhoneNumber=new Je({titleLangKey:"PrivacyPhoneTitle",subtitleLangKey:"Loading",clickable:()=>{new ti(this.slider).open()}}),i=t.inputPrivacyKeyStatusTimestamp=new Je({titleLangKey:"LastSeenTitle",subtitleLangKey:"Loading",clickable:()=>{new gi(this.slider).open()}}),n=t.inputPrivacyKeyProfilePhoto=new Je({titleLangKey:"PrivacyProfilePhotoTitle",subtitleLangKey:"Loading",clickable:()=>{new bi(this.slider).open()}}),o=t.inputPrivacyKeyPhoneCall=new Je({titleLangKey:"WhoCanCallMe",subtitleLangKey:"Loading",clickable:()=>{new yi(this.slider).open()}}),r=t.inputPrivacyKeyForwards=new Je({titleLangKey:"PrivacyForwardsTitle",subtitleLangKey:"Loading",clickable:()=>{new vi(this.slider).open()}}),l=t.inputPrivacyKeyChatInvite=new Je({titleLangKey:"WhoCanAddMe",subtitleLangKey:"Loading",clickable:()=>{new fi(this.slider).open()}}),c=e=>{const s=t[e];s&&Zs.getPrivacy(e).then(e=>{const t=Zs.getPrivacyRulesDetails(e),i=t.type===Ys.Everybody?"PrivacySettingsController.Everbody":t.type===Ys.Contacts?"PrivacySettingsController.MyContacts":"PrivacySettingsController.Nobody",n=t.disallowPeers.users.length+t.disallowPeers.chats.length,a=t.allowPeers.users.length+t.allowPeers.chats.length;s.subtitle.innerHTML="";const o=Object(A.i18n)(i);s.subtitle.append(o),(n||a)&&s.subtitle.append(` (${[-n,a?"+"+a:0].filter(Boolean).join(", ")})`)})};e.content.append(s.container,i.container,n.container,o.container,r.container,l.container),this.scrollable.append(e.container);for(const e in t)c(e);a.default.addEventListener("privacy_update",e=>{c(Object(X.c)(e.key._))})}const e=[];{const t=new nn({name:"Privacy.SensitiveContent"});t.container.classList.add("hide"),e.push(rt.a.invokeApi("account.getContentSettings").then(e=>{if(!e.pFlags.sensitive_can_change)return;const s=e.pFlags.sensitive_enabled,i=new Je({checkboxField:new dt.a({text:"PrivacyAndSecurity.SensitiveText",checked:s}),subtitleLangKey:"PrivacyAndSecurity.SensitiveDesc",noCheckboxSubtitle:!0});t.content.append(i.container),t.container.classList.remove("hide"),this.eventListener.addEventListener("destroy",()=>{const e=i.checkboxField.checked;e!==s&&rt.a.invokeApi("account.setContentSettings",{sensitive_enabled:e})},{once:!0})})),this.scrollable.append(t.container)}{const e=new nn({name:"FilterChats"}),t=()=>{new ht("popup-delete-drafts",{buttons:[{langKey:"Delete",callback:()=>{const e=Object(ut.a)([s],!0);Si.a.clearAllDrafts().then(()=>{e()})},isDanger:!0}],titleLangKey:"AreYouSureClearDraftsTitle",descriptionLangKey:"AreYouSureClearDrafts"}).show()},s=Object(U.a)("btn-primary btn-transparent",{icon:"delete",text:"PrivacyDeleteCloudDrafts"});this.listenerSetter.add(s)("click",t),e.content.append(s),this.scrollable.append(e.container)}return Promise.all(e)}updateActiveSessions(){rt.a.invokeApi("account.getAuthorizations").then(e=>{this.activeSessionsRow.freezed=!1,this.authorizations=e.authorizations,Object(A._i18n)(this.activeSessionsRow.subtitle,"Privacy.Devices",[this.authorizations.length])})}}function Mi(e,t,s,i=1){e/=255,t/=255,s/=255;const n=Math.max(e,t,s),a=Math.min(e,t,s);let o,r,l=(n+a)/2;if(n===a)o=r=0;else{let i=n-a;switch(r=l>.5?i/(2-n-a):i/(n+a),n){case e:o=(t-s)/i+(t<s?6:0);break;case t:o=(s-e)/i+2;break;case s:o=(e-t)/i+4}o/=6}return{h:360*o,s:100*r,l:100*l,a:i}}function Ii(e,t,s,i){let n,a,o;if(e/=360,s/=100,0===(t/=100))n=a=o=s;else{const i=function(e,t,s){return s<0&&(s+=1),s>1&&(s-=1),s<1/6?e+6*(t-e)*s:s<.5?t:s<2/3?e+(t-e)*(2/3-s)*6:e},r=s<.5?s*(1+t):s+t-s*t,l=2*s-r;n=i(l,r,e+1/3),a=i(l,r,e),o=i(l,r,e-1/3)}return[Math.round(255*n),Math.round(255*a),Math.round(255*o),Math.round(255*i)]}function Ci(e){const t=[];if(4===e.length)for(let s=1;s<e.length;++s)t.push(parseInt(e[s]+e[s],16));else if(5===e.length){for(let s=1;s<e.length-1;++s)t.push(parseInt(e[s]+e[s],16));t.push(parseInt(e[e.length-1],16))}else for(let s=1;s<e.length;s+=2)t.push(parseInt(e.slice(s,s+2),16));return t}function ki(e){return"#"+e.map(e=>("0"+e.toString(16)).slice(-2)).join("")}function Ti(e){return ki(function(e){const t=e.slice(5,-1).split(", "),s=+t.pop(),i=t.map(e=>e.endsWith("%")?+e.slice(0,-1):+e);return Ii(i[0],i[1],i[2],s)}(e))}function Pi(e){let{h:t,s:s,l:i}=Mi(e[0],e[1],e[2]);s>0&&(s=Math.min(100,s+5+.1*(100-s))),i=Math.max(0,.65*i);return`hsla(${t}, ${s}%, ${i}%, .4)`}var xi=s(124);class Ai{constructor(){this.hue=0,this.saturation=100,this.lightness=50,this.alpha=1,this.elements={},this.onGrabStart=()=>{document.documentElement.style.cursor=this.elements.boxDragger.style.cursor="grabbing"},this.onGrabEnd=()=>{document.documentElement.style.cursor=this.elements.boxDragger.style.cursor=""},this.container=document.createElement("div"),this.container.classList.add(Ai.BASE_CLASS);const e=`\n <svg class="${Ai.BASE_CLASS+"-box"}" viewBox="0 0 380 198">\n <defs>\n <linearGradient id="color-picker-saturation" x1="0%" y1="0%" x2="100%" y2="0%">\n <stop offset="0%" stop-color="#fff"></stop>\n <stop offset="100%" stop-color="hsl(0,100%,50%)"></stop>\n </linearGradient>\n <linearGradient id="color-picker-brightness" x1="0%" y1="0%" x2="0%" y2="100%">\n <stop offset="0%" stop-color="rgba(0,0,0,0)"></stop>\n <stop offset="100%" stop-color="#000"></stop>\n </linearGradient>\n <pattern id="color-picker-pattern" width="100%" height="100%">\n <rect x="0" y="0" width="100%" height="100%" fill="url(#color-picker-saturation)"></rect>\n <rect x="0" y="0" width="100%" height="100%" fill="url(#color-picker-brightness)"></rect>\n </pattern>\n </defs>\n <rect rx="10" ry="10" x="0" y="0" width="380" height="198" fill="url(#color-picker-pattern)"></rect>\n <svg class="${Ai.BASE_CLASS+"-dragger"} ${Ai.BASE_CLASS+"-box-dragger"}" x="0" y="0">\n <circle r="11" fill="inherit" stroke="#fff" stroke-width="2"></circle>\n </svg>\n </svg>\n <div class="${Ai.BASE_CLASS+"-sliders"}">\n <svg class="${Ai.BASE_CLASS+"-color-slider"}" viewBox="0 0 380 24">\n <defs>\n <linearGradient id="hue" x1="100%" y1="0%" x2="0%" y2="0%">\n <stop offset="0%" stop-color="#f00"></stop>\n <stop offset="16.666%" stop-color="#f0f"></stop>\n <stop offset="33.333%" stop-color="#00f"></stop>\n <stop offset="50%" stop-color="#0ff"></stop>\n <stop offset="66.666%" stop-color="#0f0"></stop>\n <stop offset="83.333%" stop-color="#ff0"></stop>\n <stop offset="100%" stop-color="#f00"></stop>\n </linearGradient>\n </defs>\n <rect rx="4" ry="4" x="0" y="9" width="380" height="8" fill="url(#hue)"></rect>\n <svg class="${Ai.BASE_CLASS+"-dragger"} ${Ai.BASE_CLASS+"-color-slider-dragger"}" x="0" y="13">\n <circle r="11" fill="inherit" stroke="#fff" stroke-width="2"></circle>\n </svg>\n </svg>\n </div>\n `;this.container.innerHTML=e,this.elements.box=this.container.firstElementChild,this.elements.boxDragger=this.elements.box.lastElementChild,this.elements.saturation=this.elements.box.firstElementChild.firstElementChild,this.elements.sliders=this.elements.box.nextElementSibling,this.elements.hue=this.elements.sliders.firstElementChild,this.elements.hueDragger=this.elements.hue.lastElementChild,this.hexInputField=new F.b({plainText:!0,label:"Appearance.Color.Hex"}),this.rgbInputField=new F.b({plainText:!0,label:"Appearance.Color.RGB"});const t=document.createElement("div");t.className=Ai.BASE_CLASS+"-inputs",t.append(this.hexInputField.container,this.rgbInputField.container),this.container.append(t),this.hexInputField.input.addEventListener("input",()=>{let e=this.hexInputField.value.replace(/#/g,"").slice(0,6);const t=e.match(/([a-fA-F\d]+)/),s=t&&t[0].length===e.length&&[6].includes(e.length);this.hexInputField.setState(s?F.a.Neutral:F.a.Error),e="#"+e,this.hexInputField.setValueSilently(e),s&&this.setColor(e,!1,!0)});const s=/^(?:rgb)?\(?([01]?\d\d?|2[0-4]\d|25[0-5])(?:\W+)([01]?\d\d?|2[0-4]\d|25[0-5])\W+(?:([01]?\d\d?|2[0-4]\d|25[0-5])\)?)$/;this.rgbInputField.input.addEventListener("input",()=>{const e=this.rgbInputField.value.match(s);this.rgbInputField.setState(e?F.a.Neutral:F.a.Error),e&&this.setColor(Mi(+e[1],+e[2],+e[3]),!0,!1)}),this.attachBoxListeners(),this.attachHueListeners()}attachBoxListeners(){we(this.elements.box,()=>{this.onGrabStart(),this.boxRect=this.elements.box.getBoundingClientRect()},e=>{this.saturationHandler(e.x,e.y)},()=>{this.onGrabEnd()})}attachHueListeners(){we(this.elements.hue,()=>{this.onGrabStart(),this.hueRect=this.elements.hue.getBoundingClientRect()},e=>{this.hueHandler(e.x)},()=>{this.onGrabEnd()})}setColor(e,t=!0,s=!0){if(void 0===e)e={h:0,s:100,l:50,a:1};else if("string"==typeof e)if("#"===e[0])e=function(e){const t=Ci(e);return Mi(t[0],t[1],t[2],t[3])}(e);else{const t=e.match(/[.?\d]+/g);e=Mi(+t[0],+t[1],+t[2],void 0===t[3]?1:+t[3])}this.boxRect=this.elements.box.getBoundingClientRect();const i=this.boxRect.width/100*e.s,n=100-e.l/(100-e.s/2)*100,a=this.boxRect.height/100*n;this.saturationHandler(this.boxRect.left+i,this.boxRect.top+a,!1),this.hueRect=this.elements.hue.getBoundingClientRect();const o=e.h/360,r=this.hueRect.left+this.hueRect.width*o;this.hueHandler(r,!1),this.hue=e.h,this.saturation=e.s,this.lightness=e.l,this.alpha=e.a,this.updatePicker(t,s)}getCurrentColor(){const e=Ii(this.hue,this.saturation,this.lightness,this.alpha),t=ki(e),s=t.slice(0,-2);return{hsl:`hsl(${this.hue}, ${this.saturation}%, ${this.lightness}%)`,rgb:`rgb(${e[0]}, ${e[1]}, ${e[2]})`,hex:s,hsla:`hsla(${this.hue}, ${this.saturation}%, ${this.lightness}%, ${this.alpha})`,rgba:`rgba(${e[0]}, ${e[1]}, ${e[2]}, ${e[3]})`,hexa:t,rgbaArray:e}}updatePicker(e=!0,t=!0){const s=this.getCurrentColor();this.elements.boxDragger.setAttributeNS(null,"fill",s.hex),e&&(this.hexInputField.setValueSilently(s.hex),this.hexInputField.setState(F.a.Neutral)),t&&(this.rgbInputField.setValueSilently(s.rgbaArray.slice(0,-1).join(", ")),this.rgbInputField.setState(F.a.Neutral)),this.onChange&&this.onChange(s)}hueHandler(e,t=!0){const s=Object(C.a)(e-this.hueRect.left,0,this.hueRect.width)/this.hueRect.width;this.hue=Math.round(360*s);const i=`hsla(${this.hue}, 100%, 50%, ${this.alpha})`;this.elements.hueDragger.setAttributeNS(null,"x",100*s+"%"),this.elements.hueDragger.setAttributeNS(null,"fill",i),this.elements.saturation.lastElementChild.setAttributeNS(null,"stop-color",i),t&&this.updatePicker()}saturationHandler(e,t,s=!0){const i=this.boxRect.width,n=this.boxRect.height,a=Object(C.a)(e-this.boxRect.left,0,i)/i*100,o=Object(C.a)(t-this.boxRect.top,0,n)/n*100,r=this.elements.boxDragger;r.setAttributeNS(null,"x",a+"%"),r.setAttributeNS(null,"y",o+"%");const l=Object(C.a)(a,0,100),c=100-l/2,d=100-Object(C.a)(o,0,100),h=Object(C.a)(d/100*c,0,100);this.saturation=l,this.lightness=h,s&&this.updatePicker()}}Ai.BASE_CLASS="color-picker";class Oi extends V{constructor(){super(...arguments),this._applyColor=(e,t=!0)=>{if(t)this.colorPicker.setColor(e);else{const t=Ci(e),s=this.theme.background,i=Pi(t);s.color=e.toLowerCase(),s.type="color",s.highlightningColor=i,k.default.pushToState("settings",a.default.settings),mo.applyCurrentTheme(void 0,void 0,!0),this.setActive()}},this.onColorChange=e=>{this.applyColor(e.hex,!1)}}init(){this.container.classList.add("background-container","background-color-container"),this.setTitle("SetColor"),this.theme=a.default.getTheme();const e=new nn({});this.colorPicker=new Ai,e.content.append(this.colorPicker.container),this.scrollable.append(e.container);const t=this.grid=document.createElement("div");t.classList.add("grid");["#E6EBEE","#B2CEE1","#008DD0","#C6E7CB","#C4E1A6","#60B16E","#CCD0AF","#A6A997","#7A7072","#FDD7AF","#FDB76E","#DD8851"].forEach(e=>{const s=document.createElement("div");s.classList.add("grid-item"),s.dataset.color=e.toLowerCase();const i=document.createElement("div");i.classList.add("grid-item-media"),i.style.backgroundColor=e,s.append(i),t.append(s)}),Object(l.b)(t,e=>{const t=Object(Ce.a)(e.target,"grid-item");if(!t||t.classList.contains("active"))return;const s=t.dataset.color;s&&this.applyColor(s)},{listenerSetter:this.listenerSetter}),this.scrollable.append(t),this.applyColor=Object(xi.a)(this._applyColor,16,!0)}setActive(){const e=this.grid.querySelector(".active"),t=this.theme.background,s="color"===t.type?this.grid.querySelector(`.grid-item[data-color="${t.color}"]`):null;e!==s&&(e&&e.classList.remove("active"),s&&s.classList.add("active"))}onOpen(){setTimeout(()=>{const e=this.theme.background;"color"===e.type&&(this.colorPicker.onChange=this.onColorChange),this.colorPicker.setColor(e.color||"#cccccc"),"color"!==e.type&&(this.colorPicker.onChange=this.onColorChange)},0)}onCloseAfterTimeout(){return this.colorPicker.onChange=void 0,this.colorPicker=void 0,super.onCloseAfterTimeout()}}let _i=0;class Fi extends V{constructor(){super(...arguments),this.tempId=0,this.clicked=new Set,this.onUploadClick=()=>{Object(me.e)("image/x-png,image/png,image/jpeg").then(e=>{const t="wallpaper-upload-"+ ++_i,s={_:"photoSize",h:0,w:0,location:{},size:e.size,type:"full"};let i={_:"document",access_hash:"",attributes:[],dc_id:0,file_reference:[],id:t,mime_type:e.type,size:e.size,date:Date.now()/1e3,pFlags:{},thumbs:[s],file_name:e.name};i=M.a.saveDoc(i);const n=he.a.getCacheContext(i);n.downloaded=e.size,n.url=URL.createObjectURL(e);let a={_:"wallPaper",access_hash:"",document:i,id:t,slug:t,pFlags:{}};const o=he.a.upload(e,e.name),r=Object(oe.a)();r.addNotifyListener=o.addNotifyListener,r.cancel=o.cancel,o.then(t=>{rt.a.invokeApi("account.uploadWallPaper",{file:t,mime_type:e.type,settings:{_:"wallPaperSettings"}}).then(e=>{const t=e.document,s=he.a.getCacheContext(t);Object.assign(s,n),a=e,a.document=M.a.saveDoc(a.document),c.dataset.docId=a.document.id,c.dataset.slug=a.slug,this.setBackgroundDocument(a.slug,a.document).then(r.resolve,r.reject)},r.reject)},r.reject),r.then(()=>{this.clicked.delete(a.document.id)},e=>{c.remove()});const l=new ye.a({isUpload:!0,cancelable:!0,tryAgainOnFail:!1}),c=this.addWallPaper(a,!1);this.clicked.add(a.document.id),l.attach(c,!1,r)})},this.onResetClick=()=>{const e=k.STATE_INIT.settings.themes.find(e=>e.name===this.theme.name);e&&(++this.tempId,this.theme.background=Object(L.a)(e.background),k.default.pushToState("settings",a.default.settings),mo.applyCurrentTheme(void 0,void 0,!0),this.blurCheckboxField.setValueSilently(this.theme.background.blur))},this.onGridClick=e=>{const t=Object(Ce.a)(e.target,"grid-item");if(!t)return;const{docId:s,slug:i}=t.dataset;if(this.clicked.has(s))return;this.clicked.add(s);const n=new ye.a({cancelable:!0,tryAgainOnFail:!1}),a=M.a.getDoc(s),o=()=>{const e=this.setBackgroundDocument(i,a);he.a.getCacheContext(a).url&&!this.theme.background.blur||n.attach(t,!0,e)};n.construct(),Object(l.b)(t,e=>{n.preloader.parentElement?(n.onClick(e),n.detach()):o()},{listenerSetter:this.listenerSetter}),o()},this.saveToCache=(e,t)=>{fetch(t).then(t=>{he.a.cacheStorage.save("backgrounds/"+e,t)})},this.setBackgroundDocument=(e,t)=>{let s=++this.tempId;const i=()=>s===this.tempId,n=M.a.downloadDoc(t,mo.chat.bubbles?mo.chat.bubbles.lazyLoadQueue.queueId:0),o=Object(oe.a)();return o.addNotifyListener=n.addNotifyListener,o.cancel=n.cancel,n.then(()=>{if(!i())return void o.resolve();const s=this.theme.background,n=t=>{(e=>{const t=document.createElement("img");return new Promise(s=>{Object(Rt.a)(t,e,()=>{const e=document.createElement("canvas"),i=t.naturalWidth/t.naturalHeight;1===i?(e.width=50,e.height=e.width/i):i>1?(e.height=50,e.width=e.height/i):e.width=e.height=50;const n=e.getContext("2d");n.drawImage(t,0,0,t.naturalWidth,t.naturalHeight,0,0,e.width,e.height);const a=new Array(4).fill(0),o=n.getImageData(0,0,e.width,e.height).data;for(let e=0;e<o.length;e+=4)a[0]+=o[e],a[1]+=o[e+1],a[2]+=o[e+2],a[3]+=o[e+3];const r=o.length/4,l=new Uint8ClampedArray(4);l[0]=a[0]/r,l[1]=a[1]/r,l[2]=a[2]/r,l[3]=a[3]/r,s(l)})})})(t).then(n=>{if(!i())return void o.resolve();const r=Pi(Array.from(n));s.slug=e,s.type="image",s.highlightningColor=r,k.default.pushToState("settings",a.default.settings),this.saveToCache(e,t),mo.applyCurrentTheme(e,t).then(o.resolve)})},r=he.a.getCacheContext(t);s.blur?setTimeout(()=>{Object(ms.a)(r.url,12,4).then(e=>{i()?n(e):o.resolve()})},200):n(r.url)}),o},this.setActive=()=>{const e=this.grid.querySelector(".active"),t=this.theme.background,s="image"===t.type?this.grid.querySelector(`.grid-item[data-slug="${t.slug}"]`):null;e!==s&&(e&&e.classList.remove("active"),s&&s.classList.add("active"))}}init(){this.container.classList.add("background-container","background-image-container"),this.setTitle("ChatBackground"),this.theme=a.default.getTheme();{const t=an(this.scrollable),s=Object(U.a)("btn-primary btn-transparent",{icon:"cameraadd",text:"ChatBackground.UploadWallpaper"}),i=Object(U.a)("btn-primary btn-transparent",{icon:"colorize",text:"SetColor"}),n=Object(U.a)("btn-primary btn-transparent",{icon:"favourites",text:"Appearance.Reset"});Object(l.b)(s,this.onUploadClick,{listenerSetter:this.listenerSetter}),Object(l.b)(i,()=>{new Oi(this.slider).open()},{listenerSetter:this.listenerSetter}),Object(l.b)(n,this.onResetClick,{listenerSetter:this.listenerSetter});const o=this.blurCheckboxField=new dt.a({text:"ChatBackground.Blur",name:"blur",checked:this.theme.background.blur,withRipple:!0});this.listenerSetter.add(o.input)("change",()=>{this.theme.background.blur=o.input.checked,k.default.pushToState("settings",a.default.settings);const t=e.querySelector(".active");t&&setTimeout(()=>{this.setBackgroundDocument(t.dataset.slug,M.a.getDoc(t.dataset.docId))},100)}),t.append(s,i,n,o.label)}a.default.addEventListener("background_change",this.setActive),rt.a.invokeApiHashable("account.getWallPapers").then(e=>{e.wallpapers.forEach(e=>{this.addWallPaper(e)})});const e=this.grid=document.createElement("div");e.classList.add("grid"),Object(l.b)(e,this.onGridClick,{listenerSetter:this.listenerSetter}),this.scrollable.append(e)}addWallPaper(e,t=!0){if(e.pFlags.pattern||!e.document||0===e.document.mime_type.indexOf("application/"))return;e.document=M.a.saveDoc(e.document);const s=document.createElement("div");s.classList.add("grid-item");const i=document.createElement("div");i.classList.add("grid-item-media");const n=ys({photo:e.document,message:null,container:i,withoutPreloader:!0,size:r.a.choosePhotoSize(e.document,200,200)});return s.dataset.docId=e.document.id,s.dataset.slug=e.slug,"image"===this.theme.background.type&&this.theme.background.slug===e.slug&&s.classList.add("active"),(n.loadPromises.thumb||n.loadPromises.full).then(()=>{os.a.mutate(()=>{s.append(i)})}),this.grid[t?"append":"prepend"](s),s}}var ji=s(101);class Di extends ct.b{constructor(e){super("popup-stickers",null,{closable:!0,overlayClosable:!0,body:!0}),this.stickerSetInput=e,this.onStickersClick=e=>{const t=Object(Ce.a)(e.target,"sticker-set-sticker");if(!t)return;const s=t.dataset.docId;mo.chat.input.sendMessageWithDocument(s)?this.hide():console.warn("got no doc by id:",s)},this.h6=document.createElement("h6"),this.h6.append(Object(A.i18n)("Loading")),this.header.append(this.h6),this.onClose=()=>{I.a.setOnlyOnePlayableGroup("")};const t=document.createElement("div");t.classList.add("sticker-set"),this.stickersDiv=document.createElement("div"),this.stickersDiv.classList.add("sticker-set-stickers","is-loading"),Object(l.b)(this.stickersDiv,this.onStickersClick,{listenerSetter:this.listenerSetter}),Object(se.f)(this.stickersDiv,!0),this.stickersFooter=document.createElement("div"),this.stickersFooter.classList.add("sticker-set-footer"),t.append(this.stickersDiv);const s=Object(U.a)("btn-primary btn-primary-transparent disable-hover",{noRipple:!0,text:"Loading"});this.stickersFooter.append(s),this.body.append(t);new P.b(this.body);this.body.append(this.stickersFooter),this.loadStickerSet()}loadStickerSet(){return hs.getStickerSet(this.stickerSetInput).then(e=>{let t;this.set=e.set,I.a.setOnlyOnePlayableGroup("STICKERS-POPUP"),this.h6.innerHTML=Z.a.wrapEmojiText(e.set.title),this.stickersFooter.classList.toggle("add",!e.set.installed_date),e.set.installed_date?(t=Object(U.a)("btn-primary btn-primary-transparent danger",{noRipple:!0}),t.append(Object(A.i18n)("RemoveStickersCount",[Object(A.i18n)("Stickers",[e.set.count])]))):(t=Object(U.a)("btn-primary btn-color-primary",{noRipple:!0}),t.append(Object(A.i18n)("AddStickersCount",[Object(A.i18n)("Stickers",[e.set.count])]))),this.stickersFooter.textContent="",this.stickersFooter.append(t),Object(l.b)(t,()=>{const e=Object(ut.a)([t],!0);hs.toggleStickerSet(this.set).then(()=>{this.hide()}).catch(()=>{e()})});const s=new te.d;this.stickersDiv.classList.remove("is-loading"),this.stickersDiv.innerHTML="";for(let t of e.documents){if("documentEmpty"===t._)continue;const e=document.createElement("div");e.classList.add("sticker-set-sticker");const i=v.b.active.esgSticker.width;Ls({doc:t,div:e,lazyLoadQueue:s,group:"STICKERS-POPUP",play:!0,loop:!0,width:i,height:i}),this.stickersDiv.append(e)}})}}class Bi{constructor(e,t,s,i,n){const a="range-setting-selector";this.container=document.createElement("div"),this.container.classList.add(a);const o=document.createElement("div");o.classList.add(a+"-details");const r=document.createElement("div");r.classList.add(a+"-name"),Object(A._i18n)(r,e);const l=document.createElement("div");l.classList.add(a+"-value"),l.innerHTML=""+s,o.append(r,l),this.range=new Le({step:t,min:i,max:n},s),this.range.setListeners(),this.range.setHandlers({onScrub:e=>{this.onChange&&this.onChange(e),l.innerText=""+e}}),this.container.append(o,this.range.container)}}class Ri extends V{init(){this.container.classList.add("general-settings-container"),this.setTitle("General");const e=an.bind(null,this.scrollable);{const t=e("Settings"),s=new Bi("TextSize",1,a.default.settings.messagesTextSize,12,20);s.onChange=e=>{k.default.setByKey("settings.messagesTextSize",e)};const i=Object(U.a)("btn-primary btn-transparent",{icon:"image",text:"ChatBackground"});Object(l.b)(i,()=>{new Fi(this.slider).open()});const n=new dt.a({text:"EnableAnimations",name:"animations",stateKey:"settings.animationsEnabled",withRipple:!0});t.append(s.container,i,n.label)}{const t=e("General.Keyboard"),s=document.createElement("form"),i=new Je({radioField:new st({langKey:"General.SendShortcut.Enter",name:"send-shortcut",value:"enter",stateKey:"settings.sendShortcut"}),subtitleLangKey:"General.SendShortcut.NewLine.ShiftEnter"}),n=new Je({radioField:new st({name:"send-shortcut",value:"ctrlEnter",stateKey:"settings.sendShortcut"}),subtitleLangKey:"General.SendShortcut.NewLine.Enter"});Object(A._i18n)(n.radioField.main,"General.SendShortcut.CtrlEnter",[h.IS_APPLE?"⌘":"Ctrl"]),s.append(i.container,n.container),t.append(s)}{const t=e("AutoDownloadMedia"),s=new dt.a({text:"AutodownloadContacts",name:"contacts",stateKey:"settings.autoDownload.contacts",withRipple:!0}),i=new dt.a({text:"AutodownloadPrivateChats",name:"private",stateKey:"settings.autoDownload.private",withRipple:!0}),n=new dt.a({text:"AutodownloadGroupChats",name:"groups",stateKey:"settings.autoDownload.groups",withRipple:!0}),a=new dt.a({text:"AutodownloadChannels",name:"channels",stateKey:"settings.autoDownload.channels",withRipple:!0});t.append(s.label,i.label,n.label,a.label)}{const t=e("General.AutoplayMedia"),s=new dt.a({text:"AutoplayGIF",name:"gifs",stateKey:"settings.autoPlay.gifs",withRipple:!0}),i=new dt.a({text:"AutoplayVideo",name:"videos",stateKey:"settings.autoPlay.videos",withRipple:!0});t.append(s.label,i.label)}{const t=e("Emoji"),s=new dt.a({text:"GeneralSettings.EmojiPrediction",name:"suggest-emoji",stateKey:"settings.emoji.suggest",withRipple:!0}),i=new dt.a({text:"GeneralSettings.BigEmoji",name:"emoji-big",stateKey:"settings.emoji.big",withRipple:!0});t.append(s.label,i.label)}{const t=e("Telegram.InstalledStickerPacksController"),s=new dt.a({text:"Stickers.SuggestStickers",name:"suggest",stateKey:"settings.stickers.suggest",withRipple:!0}),i=new dt.a({text:"InstalledStickers.LoopAnimated",name:"loop",stateKey:"settings.stickers.loop",withRipple:!0}),n={},o=new te.d,r=(e,s="append")=>{const i=new Je({title:Z.b.wrapEmojiText(e.title),subtitleLangKey:"Stickers",subtitleLangArgs:[e.count],havePadding:!0,clickable:()=>{new Di({id:e.id,access_hash:e.access_hash}).show()}});n[e.id]=i;const a=document.createElement("div");a.classList.add("row-media"),Ss({set:e,container:a,group:"GENERAL-SETTINGS",lazyLoadQueue:o,width:48,height:48,autoplay:!0}),i.container.append(a),t[s](i.container)};hs.getAllStickers().then(e=>{Object(ji.a)(e);for(const t of e.sets)r(t)}),this.listenerSetter.add(a.default)("stickers_installed",e=>{const t=e;n[t.id]||r(t,"prepend")}),this.listenerSetter.add(a.default)("stickers_deleted",e=>{const t=e;n[t.id]&&(n[t.id].container.remove(),delete n[t.id])}),t.append(s.label,i.label)}}onOpen(){this.init&&(this.init(),this.init=null)}}var Hi=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class Ui extends V{init(){return Hi(this,void 0,void 0,(function*(){this.container.classList.add("edit-profile-container"),this.setTitle("EditAccount.Title");const e=[];{const t=document.createElement("div");t.classList.add("input-wrapper"),this.firstNameInputField=new F.b({label:"EditProfile.FirstNameLabel",name:"first-name",maxLength:70}),this.lastNameInputField=new F.b({label:"Login.Register.LastName.Placeholder",name:"last-name",maxLength:64}),this.bioInputField=new F.b({label:"EditProfile.BioLabel",name:"bio",maxLength:70}),t.append(this.firstNameInputField.container,this.lastNameInputField.container,this.bioInputField.container);const s=document.createElement("div");s.classList.add("caption"),Object(A.i18n_)({element:s,key:"Bio.Description"}),e.push(this.firstNameInputField,this.lastNameInputField,this.bioInputField),this.scrollable.append(t,s)}this.scrollable.append(document.createElement("hr")),this.editPeer=new Xe({peerId:T.a.getSelf().id,inputFields:e,listenerSetter:this.listenerSetter}),this.content.append(this.editPeer.nextBtn),this.scrollable.prepend(this.editPeer.avatarEdit.container);{const t=document.createElement("div");t.classList.add("sidebar-left-h2"),Object(A.i18n_)({element:t,key:"EditAccount.Username"});const s=document.createElement("div");s.classList.add("input-wrapper"),this.usernameInputField=new lt({peerId:0,label:"EditProfile.Username.Label",name:"username",plainText:!0,listenerSetter:this.listenerSetter,onChange:()=>{this.editPeer.handleChange(),this.setProfileUrl()},availableText:"EditProfile.Username.Available",takenText:"EditProfile.Username.Taken",invalidText:"EditProfile.Username.Invalid"}),s.append(this.usernameInputField.container);const i=document.createElement("div");i.classList.add("caption"),i.append(Object(A.i18n)("UsernameSettings.ChangeDescription")),i.append(document.createElement("br"),document.createElement("br"));const n=this.profileUrlContainer=document.createElement("div");n.classList.add("profile-url-container");const a=this.profileUrlAnchor=document.createElement("a");a.classList.add("profile-url"),a.href="#",a.target="_blank",n.append(Object(A.i18n)("UsernameHelpLink",[a])),i.append(n),e.push(this.usernameInputField),this.scrollable.append(t,s,i)}Object(l.b)(this.editPeer.nextBtn,()=>{this.editPeer.nextBtn.disabled=!0;let e=[];e.push(n.default.updateProfile(this.firstNameInputField.value,this.lastNameInputField.value,this.bioInputField.value).then(()=>{this.close()},e=>{console.error("updateProfile error:",e)})),this.editPeer.uploadAvatar&&e.push(this.editPeer.uploadAvatar().then(e=>n.default.uploadProfilePhoto(e))),this.usernameInputField.isValid()&&!this.usernameInputField.input.classList.contains("error")&&e.push(T.a.updateUsername(this.usernameInputField.value)),Promise.race(e).finally(()=>{this.editPeer.nextBtn.removeAttribute("disabled")})},{listenerSetter:this.listenerSetter});const t=T.a.getSelf(),s=yield n.default.getProfile(t.id,!0);this.firstNameInputField.setOriginalValue(t.first_name,!0),this.lastNameInputField.setOriginalValue(t.last_name,!0),this.bioInputField.setOriginalValue(s.about,!0),this.usernameInputField.setOriginalValue(t.username,!0),this.setProfileUrl(),this.editPeer.handleChange()}))}setProfileUrl(){if(this.usernameInputField.input.classList.contains("error")||!this.usernameInputField.value.length)this.profileUrlContainer.style.display="none";else{this.profileUrlContainer.style.display="";let e="https://t.me/"+this.usernameInputField.value;this.profileUrlAnchor.innerText=e,this.profileUrlAnchor.href=e}}}var Ni=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class zi extends V{constructor(){super(...arguments),this.renderResults=e=>Ni(this,void 0,void 0,(function*(){yield T.a.getContacts(),e.forEach(e=>{const{dom:t}=Do.addDialogNew({dialog:e,container:this.selector.scrollable,drawStatus:!1,rippleEnabled:!0,avatarSize:46}),s=this.selector.selected.has(e);t.containerEl.append(this.checkbox(s));const i=[];this.dialogsByFilters.forEach((t,s)=>{if(t.has(e)){const e=document.createElement("span");e.innerHTML=Z.b.wrapEmojiText(s.title),i.push(e)}});Object(A.join)(i,!1).forEach(e=>{t.lastMessageSpan.append(e)})})})),this.onSelectChange=e=>{"included"===this.type&&(this.confirmBtn.style.display=e?"":"none")}}init(){return this.content.remove(),this.container.classList.add("included-chatlist-container"),this.confirmBtn=N("check btn-confirm blue",{noRipple:!0}),this.confirmBtn.style.display="none",this.header.append(this.confirmBtn),this.confirmBtn.addEventListener("click",()=>{const e=this.selector.getSelected();if("included"===this.type)for(const e in this.filter.pFlags)0!==e.indexOf("exclude_")&&delete this.filter.pFlags[e];else for(const e in this.filter.pFlags)0===e.indexOf("exclude_")&&delete this.filter.pFlags[e];const t=[];for(const s of e)"number"==typeof s?t.push(s):this.filter.pFlags[s]=!0;"included"===this.type?this.filter.pinned_peers=this.filter.pinned_peers.filter(e=>t.includes(e)):this.filter.pinned_peers=this.filter.pinned_peers.filter(e=>!t.includes(e));const s="included"===this.type?"exclude_peers":"include_peers";this.filter[s]=this.filter[s].filter(e=>!t.includes(e)),this.filter["included"===this.type?"include_peers":"exclude_peers"]=t,this.editFolderTab.setFilter(this.filter,!1),this.close()}),this.dialogsByFilters=new Map,i.a.filtersStorage.getDialogFilters().then(e=>{for(const t of e)this.dialogsByFilters.set(t,new Set(i.a.dialogsStorage.getFolder(t.id).map(e=>e.peerId)))})}checkbox(e){const t=new dt.a({round:!0});return e&&(t.input.checked=e),t.label}onOpen(){this.init&&(this.init(),this.init=null),this.confirmBtn.style.display="excluded"===this.type?"":"none",this.setTitle("included"===this.type?"FilterAlwaysShow":"FilterNeverShow");const e=this.filter,t=document.createDocumentFragment(),s=new nn({noDelimiter:!0,name:"FilterChatTypes"});let i;s.container.classList.add("folder-categories"),i="excluded"===this.type?{exclude_muted:{ico:"mute",text:"ChatList.Filter.MutedChats"},exclude_archived:{ico:"archive",text:"ChatList.Filter.Archive"},exclude_read:{ico:"readchats",text:"ChatList.Filter.ReadChats"}}:{contacts:{ico:"newprivate",text:"ChatList.Filter.Contacts"},non_contacts:{ico:"noncontacts",text:"ChatList.Filter.NonContacts"},groups:{ico:"group",text:"ChatList.Filter.Groups"},broadcasts:{ico:"newchannel",text:"ChatList.Filter.Channels"},bots:{ico:"bots",text:"ChatList.Filter.Bots"}};const n=document.createDocumentFragment();for(const e in i){const t=Object(U.a)("btn-primary btn-transparent folder-category-button",{icon:i[e].ico,text:i[e].text});t.dataset.peerId=e,t.append(this.checkbox()),n.append(t)}s.content.append(n);const a=new nn({name:"FilterChats"});t.append(s.container,a.container);const o=("included"===this.type?e.include_peers:e.exclude_peers).slice();this.selector=new Et({appendTo:this.container,onChange:this.onSelectChange,peerType:["dialogs"],renderResultsFunc:this.renderResults,placeholder:"Search"}),this.selector.selected=new Set(o);let r=!1;const l=this.selector.add.bind(this.selector);this.selector.add=(e,t,s)=>{if(this.selector.selected.size>=100&&r&&!i[e]){const t=this.selector.list.querySelector(`[data-peer-id="${e}"] [type="checkbox"]`);t&&setTimeout(()=>{t.checked=!1},0);return void nt(A.default.format("excluded"===this.type?"ChatList.Filter.Exclude.LimitReached":"ChatList.Filter.Include.LimitReached",!0))}const n=l(e,i[e]?Object(A.i18n)(i[e].text):void 0,s);return i[e]&&n.querySelector("avatar-element").classList.add("tgico-"+i[e].ico),n};const c=this.selector.list.parentElement;a.content.append(this.selector.list),c.append(t),this.selector.addInitial(o),r=!0;for(const t in e.pFlags)i.hasOwnProperty(t)&&e.pFlags[t]&&s.content.querySelector(`[data-peer-id="${t}"]`).click()}onCloseAfterTimeout(){return this.selector&&(this.selector.container.remove(),this.selector=null),super.onCloseAfterTimeout()}open(e,t,s){return this.originalFilter=e,this.filter=Object(L.a)(this.originalFilter),this.type=t,this.editFolderTab=s,super.open()}}class Vi extends V{constructor(){super(...arguments),this.flags={}}init(){this.container.classList.add("edit-folder-container"),this.caption=document.createElement("div"),this.caption.classList.add("caption"),this.caption.append(Object(A.i18n)("FilterIncludeExcludeInfo")),this.stickerContainer=document.createElement("div"),this.stickerContainer.classList.add("sticker-container"),this.confirmBtn=N("check btn-confirm hide blue");const e={icon:"delete danger",text:"FilterMenuDelete",onClick:()=>{e.element.setAttribute("disabled","true"),i.a.filtersStorage.updateDialogFilter(this.filter,!0).then(e=>{e&&this.close()}).finally(()=>{e.element.removeAttribute("disabled")})}};this.menuBtn=Ie({},"bottom-left",[e]),this.menuBtn.classList.add("hide"),this.header.append(this.confirmBtn,this.menuBtn);const t=document.createElement("div");t.classList.add("input-wrapper"),this.nameInputField=new F.b({label:"FilterNameInputLabel",maxLength:12}),t.append(this.nameInputField.container);const s=(e,t,s,i)=>{const n=new nn({name:t,noDelimiter:!0});n.container.classList.add("folder-list",e);const a=n.generateContentElement();return a.classList.add("folder-categories"),s.forEach(e=>{const t=Object(U.a)("folder-category-button btn btn-primary btn-transparent",{icon:e.icon,text:e.text,noRipple:!e.withRipple||void 0});e.name&&(i[e.name]=t),a.append(t)}),n};this.include_peers=s("folder-list-included","FilterInclude",[{icon:"add primary",text:"ChatList.Filter.Include.AddChat",withRipple:!0},{text:"ChatList.Filter.Contacts",icon:"newprivate",name:"contacts"},{text:"ChatList.Filter.NonContacts",icon:"noncontacts",name:"non_contacts"},{text:"ChatList.Filter.Groups",icon:"group",name:"groups"},{text:"ChatList.Filter.Channels",icon:"channel",name:"broadcasts"},{text:"ChatList.Filter.Bots",icon:"bots",name:"bots"}],this.flags),this.exclude_peers=s("folder-list-excluded","FilterExclude",[{icon:"minus primary",text:"ChatList.Filter.Exclude.AddChat",withRipple:!0},{text:"ChatList.Filter.MutedChats",icon:"mute",name:"exclude_muted"},{text:"ChatList.Filter.Archive",icon:"archive",name:"exclude_archived"},{text:"ChatList.Filter.ReadChats",icon:"readchats",name:"exclude_read"}],this.flags),this.scrollable.append(this.stickerContainer,this.caption,t,this.include_peers.container,this.exclude_peers.container);const n=this.include_peers.container.querySelector(".folder-categories"),a=this.exclude_peers.container.querySelector(".folder-categories");return n.querySelector(".btn").addEventListener("click",()=>{new zi(this.slider).open(this.filter,"included",this)}),a.querySelector(".btn").addEventListener("click",()=>{new zi(this.slider).open(this.filter,"excluded",this)}),this.confirmBtn.addEventListener("click",()=>{if(this.nameInputField.input.classList.contains("error"))return;if(!this.nameInputField.value.trim())return void this.nameInputField.input.classList.add("error");let e,t=Array.from(n.children).slice(1).reduce((e,t)=>e+ +!t.style.display,0);t+=this.filter.include_peers.length,t?(this.confirmBtn.setAttribute("disabled","true"),e=this.filter.id?i.a.filtersStorage.updateDialogFilter(this.filter):i.a.filtersStorage.createDialogFilter(this.filter),e.then(e=>{e&&this.close()}).catch(e=>{"DIALOG_FILTERS_TOO_MUCH"===e.type?nt("Sorry, you can't create more folders."):console.error("updateDialogFilter error:",e)}).finally(()=>{this.confirmBtn.removeAttribute("disabled")})):nt("Please choose at least one chat for this folder.")}),this.nameInputField.input.addEventListener("input",()=>{this.filter.title=this.nameInputField.value,this.editCheckForChange()}),this.loadAnimationPromise=le.b.loadAnimationFromURL({container:this.stickerContainer,loop:!1,autoplay:!1,width:86,height:86},"assets/img/Folders_2.tgs").then(e=>(this.animation=e,le.b.waitForFirstFrame(e)))}onOpenAfterTimeout(){this.loadAnimationPromise.then(()=>{this.animation.autoplay=!0,this.animation.play()})}onCreateOpen(){this.caption.style.display="",this.setTitle("FilterNew"),this.menuBtn.classList.add("hide"),this.confirmBtn.classList.remove("hide"),this.nameInputField.value="";for(const e in this.flags)this.flags[e].style.display="none"}onEditOpen(){this.caption.style.display="none",this.setTitle("create"===this.type?"FilterNew":"FilterHeaderEdit"),"edit"===this.type&&(this.menuBtn.classList.remove("hide"),this.confirmBtn.classList.add("hide"));const e=this.filter;this.nameInputField.value=Z.b.wrapDraftText(e.title);for(const t in this.flags)this.flags[t].style.display=e.pFlags[t]?"":"none";["include_peers","exclude_peers"].forEach(t=>{const s=this[t],i=Do.createChatList(),n=e[t].slice(),a=e=>{for(let t=0,s=Math.min(n.length,e);t<s;++t){const e=n.shift(),{dom:t}=Do.addDialogNew({dialog:e,container:i,drawStatus:!1,rippleEnabled:!1,meAsSaved:!0,avatarSize:32});t.lastMessageSpan.parentElement.remove()}n.length?o.lastElementChild.replaceWith(Object(A.i18n)("FilterShowMoreChats",[n.length])):o&&o.remove()};let o;if(s.generateContentElement().append(i),n.length){const e=s.generateContentElement();o=Object(U.a)("folder-category-button btn btn-primary btn-transparent",{icon:"down"}),o.classList.add("load-more","rp-overflow"),o.addEventListener("click",()=>a(20)),o.append(Object(A.i18n)("FilterShowMoreChats",[n.length])),e.append(o)}a(4)})}editCheckForChange(){if("edit"===this.type){const e=!Object(L.b)(this.originalFilter,this.filter);this.confirmBtn.classList.toggle("hide",!e),this.menuBtn.classList.toggle("hide",e)}}setFilter(e,t){Array.from(this.container.querySelectorAll("ul, .load-more")).forEach(e=>e.remove()),t?(this.originalFilter=e,this.filter=Object(L.a)(e)):(this.filter=e,this.onEditOpen(),this.editCheckForChange())}open(e){const t=super.open();return void 0===e?(this.setFilter({_:"dialogFilter",id:0,title:"",pFlags:{},pinned_peers:[],include_peers:[],exclude_peers:[]},!0),this.type="create",this.onCreateOpen()):(this.setFilter(e,!0),this.type="edit",this.onEditOpen()),t}}var Wi=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class Ki extends V{constructor(){super(...arguments),this.filtersRendered={}}renderFolder(e,t,s){let n,a,r="",c=[];if("dialogFilterSuggested"===e._)n=e.filter,r=e.description;else{if(n=e,1===Object.keys(n.pFlags).length){const e=n.pFlags;let t;e.contacts?t="FilterAllContacts":e.non_contacts?t="FilterAllNonContacts":e.groups?t="FilterAllGroups":e.broadcasts?t="FilterAllChannels":e.bots&&(t="FilterAllBots"),t&&c.push(Object(A.i18n)(t))}if(!c.length){const e=i.a.dialogsStorage.getFolder(n.id);let t=0,s=0,a=0;for(const i of e)o.a.isAnyGroup(i.peerId)?a++:o.a.isBroadcast(i.peerId)?s++:t++;t&&c.push(Object(A.i18n)("Chats",[t])),s&&c.push(Object(A.i18n)("Channels",[s])),a&&c.push(Object(A.i18n)("Groups",[a]))}}if(s)s.subtitle.textContent="",Object(A.join)(c).forEach(e=>{s.subtitle.append(e)});else if(s=new Je({title:Z.a.wrapEmojiText(n.title),subtitle:r,clickable:!0}),c.length&&Object(A.join)(c).forEach(e=>{s.subtitle.append(e)}),"dialogFilter"===e._){const e=n.id;this.filtersRendered.hasOwnProperty(n.id)||Object(l.b)(s.container,()=>{new Vi(this.slider).open(i.a.filtersStorage.getFilter(e))},{listenerSetter:this.listenerSetter}),this.filtersRendered[n.id]=s}return a=s.container,n.hasOwnProperty("orderIndex")?Ps(a,a.parentElement||t,n.orderIndex):t&&t.append(a),a}init(){return Wi(this,void 0,void 0,(function*(){this.container.classList.add("chat-folders-container"),this.setTitle("ChatList.Filter.List.Title"),this.scrollable.container.classList.add("chat-folders"),this.stickerContainer=document.createElement("div"),this.stickerContainer.classList.add("sticker-container");const e=document.createElement("div");e.classList.add("caption"),Object(A.i18n_)({element:e,key:"ChatList.Filter.Header"}),this.createFolderBtn=Object(U.a)("btn-primary btn-color-primary btn-control tgico",{text:"ChatList.Filter.NewTitle",icon:"add"}),this.foldersSection=new nn({name:"Filters"}),this.foldersSection.container.style.display="none",this.suggestedSection=new nn({name:"FilterRecommended"}),this.suggestedSection.container.style.display="none",this.scrollable.append(this.stickerContainer,e,this.createFolderBtn,this.foldersSection.container,this.suggestedSection.container),Object(l.b)(this.createFolderBtn,()=>{Object.keys(this.filtersRendered).length>=10?nt("Sorry, you can't create more folders."):new Vi(this.slider).open()},{listenerSetter:this.listenerSetter});const t=()=>{this.foldersSection.container.style.display=Object.keys(this.filtersRendered).length?"":"none"};return i.a.filtersStorage.getDialogFilters().then(e=>{for(const t of e)this.renderFolder(t,this.foldersSection.content);t()}),this.listenerSetter.add(a.default)("filter_update",e=>{const s=e;this.filtersRendered.hasOwnProperty(s.id)?this.renderFolder(s,null,this.filtersRendered[s.id]):this.renderFolder(s,this.foldersSection.content),t(),this.getSuggestedFilters()}),this.listenerSetter.add(a.default)("filter_delete",e=>{const s=e;this.filtersRendered.hasOwnProperty(s.id)&&(this.getSuggestedFilters(),this.filtersRendered[s.id].container.remove(),delete this.filtersRendered[s.id]),t()}),this.listenerSetter.add(a.default)("filter_order",e=>{e.forEach((e,t)=>{const s=this.filtersRendered[e].container;Ps(s,s.parentElement,t+1)})}),this.loadAnimationPromise=le.b.loadAnimationFromURL({container:this.stickerContainer,loop:!1,autoplay:!1,width:86,height:86},"assets/img/Folders_1.tgs").then(e=>(this.animation=e,le.b.waitForFirstFrame(e))),this.getSuggestedFilters(),this.loadAnimationPromise}))}onOpenAfterTimeout(){this.loadAnimationPromise.then(()=>{this.animation.autoplay=!0,this.animation.play()})}getSuggestedFilters(){return rt.a.invokeApi("messages.getSuggestedDialogFilters").then(e=>{this.suggestedSection.container.style.display=e.length?"":"none",Array.from(this.suggestedSection.content.children).slice(1).forEach(e=>e.remove()),e.forEach(e=>{const t=this.renderFolder(e),s=Object(U.a)("btn-primary btn-color-primary",{text:"Add"});t.append(s),this.suggestedSection.content.append(t),Object(l.b)(s,n=>{Object(c.a)(n),Object.keys(this.filtersRendered).length>=10?nt("Sorry, you can't create more folders."):(s.setAttribute("disabled","true"),i.a.filtersStorage.createDialogFilter(e.filter).then(e=>{e&&t.remove()}).finally(()=>{s.removeAttribute("disabled")}))},{listenerSetter:this.listenerSetter})})})}}class Gi extends W{init(){this.container.classList.add("notifications-container"),this.setTitle("Telegram.NotificationSettingsViewController");const e=e=>{const t=new nn({name:e.name}),s=new Je({checkboxField:new dt.a({text:e.typeText,checked:!0}),subtitleLangKey:"Loading"}),i=new Je({checkboxField:new dt.a({text:"Notifications.MessagePreview",checked:!0}),subtitleLangKey:"Loading"});t.content.append(s.container,i.container),this.scrollable.append(t.container);const n={_:e.inputKey},o=_t.a.getNotifySettings(n);(o instanceof Promise?o:Promise.resolve(o)).then(t=>{const o=()=>{const e=_t.a.isMuted(t);return s.checkboxField.checked=!e,i.checkboxField.checked=t.show_previews,e};o(),this.eventListener.addEventListener("destroy",()=>{const e=!s.checkboxField.checked,a=i.checkboxField.checked;if(e===_t.a.isMuted(t)&&a===t.show_previews)return;const o=Object(L.a)(t);o._="inputPeerNotifySettings",o.mute_until=e?2147483647:0,o.show_previews=a,_t.a.updateNotifySettings(n,o)},{once:!0}),this.listenerSetter.add(a.default)("notify_settings",s=>{const i=Object(X.c)(s.peer._);e.inputKey===i&&(t=s.notify_settings,o())})})};e({name:"NotificationsPrivateChats",typeText:"NotificationsForPrivateChats",inputKey:"inputNotifyUsers"}),e({name:"NotificationsGroups",typeText:"NotificationsForGroups",inputKey:"inputNotifyChats"}),e({name:"NotificationsChannels",typeText:"NotificationsForChannels",inputKey:"inputNotifyBroadcasts"});{const e=new nn({name:"NotificationsOther"}),t=new Je({checkboxField:new dt.a({text:"ContactJoined",checked:!0}),subtitleLangKey:"Loading"}),s=new Je({checkboxField:new dt.a({text:"Notifications.Sound",checked:!0,stateKey:"settings.notifications.sound"}),subtitleLangKey:"Loading"});k.default.getState().then(e=>{s.checkboxField.checked=e.settings.notifications.sound}),e.content.append(t.container,s.container),this.scrollable.append(e.container),_t.a.getContactSignUpNotification().then(e=>{t.checkboxField.checked=e,this.eventListener.addEventListener("destroy",()=>{const s=t.checkboxField.checked;e!==s&&_t.a.setContactSignUpNotification(!s)},{once:!0})})}}}var qi=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class Qi extends V{init(){return qi(this,void 0,void 0,(function*(){this.container.classList.add("language-container"),this.setTitle("Telegram.LanguageViewController");const e=new nn({}),t=new Map,s=rt.a.invokeApiCacheable("langpack.getLanguages",{lang_pack:"macos"}).then(s=>{const i=Object(tt.b)();s.forEach(e=>{const s=new Je({radioField:new st({text:e.name,name:i,value:e.lang_code}),subtitle:e.native_name});t.set(e.lang_code,s)});const n=Ze([...t.values()],e=>{A.default.getLangPack(e)});A.default.getCacheLangPack().then(e=>{const s=t.get(e.lang_code);s?s.radioField.setValueSilently(!0):console.error("no row",s,e)}),e.content.append(n)});return this.scrollable.append(e.container),s}))}}class $i extends V{constructor(){super(...arguments),this.buttons={}}init(){this.container.classList.add("settings-container"),this.setTitle("Settings");const e=Ie({},"bottom-left",[{icon:"logout",text:"EditAccount.Logout",onClick:()=>{rt.a.logOut()}}]);this.header.append(e),this.avatarElem=new ko,this.avatarElem.setAttribute("clickable",""),this.avatarElem.classList.add("profile-avatar","avatar-120"),this.nameDiv=document.createElement("div"),this.nameDiv.classList.add("profile-name"),this.phoneDiv=document.createElement("div"),this.phoneDiv.classList.add("profile-subtitle");const t=document.createElement("div");t.classList.add("profile-buttons");const s="profile-button btn-primary btn-transparent";t.append(this.buttons.edit=Object(U.a)(s,{icon:"edit",text:"EditAccount.Title"})),t.append(this.buttons.folders=Object(U.a)(s,{icon:"folder",text:"AccountSettings.Filters"})),t.append(this.buttons.general=Object(U.a)(s,{icon:"settings",text:"Telegram.GeneralSettingsViewController"})),t.append(this.buttons.notifications=Object(U.a)(s,{icon:"unmute",text:"AccountSettings.Notifications"})),t.append(this.buttons.privacy=Object(U.a)(s,{icon:"lock",text:"AccountSettings.PrivacyAndSecurity"})),t.append(this.buttons.language=Object(U.a)(s,{icon:"language",text:"AccountSettings.Language"})),this.scrollable.append(this.avatarElem,this.nameDiv,this.phoneDiv,t),this.scrollable.container.classList.add("profile-content-wrapper"),this.buttons.edit.addEventListener("click",()=>{new Ui(this.slider).open()}),this.buttons.folders.addEventListener("click",()=>{new Ki(this.slider).open()}),this.buttons.general.addEventListener("click",()=>{new Ri(this.slider).open()}),this.buttons.notifications.addEventListener("click",()=>{new Gi(this.slider).open()}),this.buttons.privacy.addEventListener("click",()=>{new Ei(this.slider).open()}),this.buttons.language.addEventListener("click",()=>{new Qi(this.slider).open()}),le.b.loadLottieWorkers(),this.fillElements()}fillElements(){let e=T.a.getSelf();this.avatarElem.setAttribute("peer",""+e.id),this.nameDiv.append(new ft.a({peerId:e.id}).element),this.phoneDiv.innerHTML=e.phone?T.a.formatUserPhone(e.phone):""}}class Yi extends V{constructor(){super(...arguments),this.uploadAvatar=null}init(){this.container.classList.add("new-channel-container"),this.setTitle("NewChannel"),this.avatarEdit=new Q(e=>{this.uploadAvatar=e});const e=document.createElement("div");e.classList.add("input-wrapper"),this.channelNameInputField=new F.b({label:"EnterChannelName",maxLength:128}),this.channelDescriptionInputField=new F.b({label:"DescriptionOptionalPlaceholder",maxLength:255}),e.append(this.channelNameInputField.container,this.channelDescriptionInputField.container);const t=()=>{this.nextBtn.classList.toggle("is-visible",!!this.channelNameInputField.value.length&&!this.channelNameInputField.input.classList.contains("error")&&!this.channelDescriptionInputField.input.classList.contains("error"))};this.channelNameInputField.input.addEventListener("input",t),this.channelDescriptionInputField.input.addEventListener("input",t);const s=document.createElement("div");s.classList.add("caption"),Object(A._i18n)(s,"Channel.DescriptionHolderDescrpiton"),this.nextBtn=$({icon:"arrow_next"}),this.nextBtn.addEventListener("click",()=>{const e=this.channelNameInputField.value,t=this.channelDescriptionInputField.value;this.nextBtn.disabled=!0,G.a.createChannel(e,t).then(e=>{this.uploadAvatar&&this.uploadAvatar().then(t=>{G.a.editPhoto(e,t)}),ln.removeTabFromHistory(this),new jt(this.slider).open({peerId:e,type:"channel",skippable:!0,title:"GroupAddMembers",placeholder:"SendMessageTo",takeOut:t=>G.a.inviteToChannel(Math.abs(e),t)})})}),this.content.append(this.nextBtn),this.scrollable.append(this.avatarEdit.container,e,s)}onCloseAfterTimeout(){return this.avatarEdit.clear(),this.uploadAvatar=null,this.channelNameInputField.value="",this.channelDescriptionInputField.value="",this.nextBtn.disabled=!1,super.onCloseAfterTimeout()}}var Xi=s(117);class Ji extends ct.b{constructor(){super("popup-create-contact popup-send-photo popup-new-media",null,{closable:!0,withConfirm:"Add"}),Object(A._i18n)(this.title,"AddContactTitle"),Object(l.b)(this.btnConfirm,()=>{const e=T.a.importContact(s.value,i.value,n.value);e.then(()=>{this.hide()},e=>{"NO_USER"===e.type&&(at({langPackKey:"Contacts.PhoneNumber.NotRegistred"}),c.disabled=!1)}),c.lockWithPromise(e)},{listenerSetter:this.listenerSetter});const e=[],t=document.createElement("div");t.classList.add("name-fields");const s=new F.b({label:"FirstName",name:"create-contact-name",maxLength:70,required:!0}),i=new F.b({label:"LastName",name:"create-contact-lastname",maxLength:70}),n=new Xi.a({required:!0});e.push(s,i,n);const a=()=>{const e=s.value+" "+i.value;c.avatarElem.setAttribute("peer-title",e),c.avatarElem.update()};this.listenerSetter.add(s.input)("input",a),this.listenerSetter.add(i.input)("input",a);const o=T.a.getSelf(),r=Object(Fs.a)(o.phone);r&&(n.validate=()=>!!n.value.match(/\d/),n.value="+"+r.code.country_code);const c=new Xe({inputFields:e,listenerSetter:this.listenerSetter,doNotEditAvatar:!0,nextBtn:this.btnConfirm,avatarSize:100});t.append(s.container,i.container,c.avatarElem),this.container.append(t,n.container),this.show()}}class Zi extends V{init(){this.container.id="contacts-container";const e=$({icon:"add",className:"is-visible"});this.content.append(e),Object(l.b)(e,()=>{new Ji},{listenerSetter:this.listenerSetter}),this.inputSearch=new j("Search",e=>{this.openContacts(e)}),this.listenerSetter.add(a.default)("contacts_update",e=>{T.a.isContact(e)?this.sortedUserList.add(e):this.sortedUserList.delete(e)}),this.title.replaceWith(this.inputSearch.container),this.middleware=Object(ks.a)()}createList(){const e=new Os,t=e.list;return t.id="contacts",t.classList.add("contacts-container"),Do.setListClickListener(t,()=>{this.close()},void 0,!0),e}onClose(){this.middleware.clean()}onOpenAfterTimeout(){!h.IS_MOBILE&&ai(!0)&&this.inputSearch.input.focus()}openContacts(e){this.init&&(this.init(),this.init=null),this.middleware.clean();const t=this.middleware.get();this.scrollable.onScrolledBottom=null,this.scrollable.container.textContent="",T.a.getContacts(e,void 0,"online").then(e=>{if(!t())return;const s=this.sortedUserList=this.createList();let i=()=>{const t=yt.a.windowH/72*1.25|0;e.splice(0,t).forEach(e=>{s.add(e)}),e.length||(i=void 0,this.scrollable.onScrolledBottom=null)};i(),this.scrollable.onScrolledBottom=()=>{i?i():this.scrollable.onScrolledBottom=null},Object(x.a)(this.scrollable.container,s.list)})}open(){return this.openContacts(),super.open()}}class en extends V{init(){if(this.container.id="chats-archived-container",this.setTitle("ArchivedChats"),!Do.sortedLists[en.filterId]){const e=Do.createChatList();Do.generateScrollable(e,en.filterId).container.append(e),Do.setListClickListener(e,null,!0)}const e=Do.scrollables[en.filterId];this.scrollable.container.replaceWith(e.container),this.scrollable=e}onOpen(){this.init&&(this.init(),this.init=null),this.wasFilterId=Do.filterId,Do.setFilterId(en.filterId),Do.onTabChange()}onOpenAfterTimeout(){Do.sortedLists[this.wasFilterId].clear()}onClose(){Do.setFilterId(this.wasFilterId),Do.onTabChange()}onCloseAfterTimeout(){return Do.sortedLists[en.filterId].clear(),super.onCloseAfterTimeout()}}en.filterId=1;var tn=s(7),sn=s(57);class nn{constructor(e){if(this.container=document.createElement("div"),this.container.classList.add("sidebar-left-section"),e.fakeGradientDelimiter)this.container.append(on()),this.container.classList.add("with-fake-delimiter");else if(e.noDelimiter)this.container.classList.add("no-delimiter");else{const e=document.createElement("hr");this.container.append(e)}this.content=this.generateContentElement(),e.name&&(this.title=document.createElement("div"),this.title.classList.add("sidebar-left-h2","sidebar-left-section-name"),Object(A.i18n_)({element:this.title,key:e.name}),this.content.append(this.title)),e.caption&&(this.caption=this.generateContentElement(),this.caption.classList.add("sidebar-left-section-caption"),!0!==e.caption&&Object(A.i18n_)({element:this.caption,key:e.caption}))}generateContentElement(){const e=document.createElement("div");return e.classList.add("sidebar-left-section-content"),this.container.append(e),e}}const an=(e,t,s)=>{const i=new nn({name:t,caption:s});return e.append(i.container),i.content},on=()=>{const e=document.createElement("div");return e.classList.add("gradient-delimiter"),e},rn=new class extends K{constructor(){super({sidebarEl:document.getElementById("column-left"),navigationType:"left"}),this.searchGroups={},this.inputSearch=new j("Search");const e=this.sidebarEl.querySelector(".item-main .sidebar-header");e.append(this.inputSearch.container);const t=()=>{new Zi(this).open()};this.backBtn=this.sidebarEl.querySelector(".sidebar-back-button");const s={icon:"archive",text:"ArchivedChats",onClick:()=>{new en(this).open()},verify:()=>!!i.a.dialogsStorage.getFolder(1).length},n=new dt.a({toggle:!0,checked:"night"===a.default.getTheme().name});n.input.addEventListener("change",()=>{a.default.settings.theme=n.input.checked?"night":"day",k.default.pushToState("settings",a.default.settings),mo.applyCurrentTheme()}),a.default.addEventListener("theme_change",()=>{n.setValueSilently("night"===a.default.getTheme().name)});const o=[{icon:"saved",text:"SavedMessages",onClick:()=>{setTimeout(()=>{mo.setPeer(mo.myId)},0)}},s,{icon:"user",text:"Contacts",onClick:t},{icon:"settings",text:"Settings",onClick:()=>{new $i(this).open()}},{icon:"darkmode",text:"DarkMode",onClick:()=>{},checkboxField:n},{icon:"animations",text:"Animations",onClick:()=>{},checkboxField:new dt.a({toggle:!0,checked:!0,stateKey:"settings.animationsEnabled"})},{icon:"help",text:"TelegramFeatures",onClick:()=>{mo.openUsername("TelegramTips")}},{icon:"bug",text:"ReportBug",onClick:()=>{const e=document.createElement("a");e.target="_blank",e.href="https://bugs.telegram.org/?tag_ids=40&sort=time",document.body.append(e),e.click(),setTimeout(()=>{e.remove()},0)}},{icon:"char z",text:"ChatList.Menu.SwitchTo.Z",onClick:()=>{sn.a.set({kz_version:"Z"}).then(()=>{location.href="https://web.telegram.org/z/"})},verify:()=>tn.a.isMainDomain},{icon:"char w",text:"ChatList.Menu.SwitchTo.Webogram",onClick:()=>{location.href="https://web.telegram.org/?legacy=1"},verify:()=>tn.a.isMainDomain}];this.toolsBtn=Ie({},"bottom-right",o,e=>{o.forEach(e=>{e.verify&&e.element.classList.toggle("hide",!e.verify())})}),this.toolsBtn.classList.remove("tgico-more"),this.toolsBtn.classList.add("sidebar-tools-button","is-visible"),this.backBtn.parentElement.insertBefore(this.toolsBtn,this.backBtn);const r=this.toolsBtn.querySelector(".btn-menu"),c=document.createElement("a");c.href="https://github.com/morethanwords/tweb/blob/master/CHANGELOG.md",c.target="_blank",c.rel="noopener noreferrer",c.classList.add("btn-menu-footer"),c.addEventListener(l.a,e=>{e.stopPropagation(),Object(se.c)()});const d=document.createElement("span");d.classList.add("btn-menu-footer-text"),d.innerHTML="Telegram Web"+tn.a.suffix+" alpha "+tn.a.versionFull,c.append(d),r.classList.add("has-footer"),r.append(c),this.newBtnMenu=Ie({},"top-left",[{icon:"newchannel",text:"NewChannel",onClick:()=>{new Yi(this).open()}},{icon:"newgroup",text:"NewGroup",onClick:()=>{new jt(this).open({peerId:0,type:"chat",skippable:!1,takeOut:e=>{new Y(this).open(e)},title:"GroupAddMembers",placeholder:"SendMessageTo"})}},{icon:"newprivate",text:"NewPrivateChat",onClick:t}]),this.newBtnMenu.className="btn-circle rp btn-corner z-depth-1 btn-menu-toggle animated-button-icon",this.newBtnMenu.insertAdjacentHTML("afterbegin",'\n <span class="tgico tgico-newchat_filled"></span>\n <span class="tgico tgico-close"></span>\n '),this.newBtnMenu.id="new-menu",e.nextElementSibling.append(this.newBtnMenu),this.inputSearch.input.addEventListener("focus",()=>this.initSearch(),{once:!0}),this.archivedCount=document.createElement("span"),this.archivedCount.className="archived-count badge badge-24 badge-gray",s.element.append(this.archivedCount),a.default.addEventListener("dialogs_archived_unread",e=>{this.archivedCount.innerText=""+Object(C.c)(e.count,1),this.archivedCount.classList.toggle("hide",!e.count)}),T.a.getTopPeers("correspondents"),k.default.getState().then(e=>{const t=e.recentSearch||[];for(let e=0,s=t.length;e<s;++e)k.default.requestPeer(t[e],"recentSearch")})}initSearch(){const e=this.sidebarEl.querySelector("#search-container"),t=new P.b(e),s=()=>{this.backBtn.click()};this.searchGroups={contacts:new O("Search.Chats","contacts",void 0,void 0,void 0,void 0,s),globalContacts:new O("Search.Global","contacts",void 0,void 0,void 0,void 0,s),messages:new O("Search.Messages","messages"),people:new O(!1,"contacts",!0,"search-group-people",!0,!1,s),recent:new O("Recent","contacts",!0,"search-group-recent",!0,!0,s)};const n=this.searchSuper=new $s({mediaTabs:[{inputFilter:"inputMessagesFilterEmpty",name:"FilterChats",type:"chats"},{inputFilter:"inputMessagesFilterPhotoVideo",name:"SharedMediaTab2",type:"media"},{inputFilter:"inputMessagesFilterUrl",name:"SharedLinksTab2",type:"links"},{inputFilter:"inputMessagesFilterDocument",name:"SharedFilesTab2",type:"files"},{inputFilter:"inputMessagesFilterMusic",name:"SharedMusicTab2",type:"music"},{inputFilter:"inputMessagesFilterRoundVoice",name:"SharedVoiceTab2",type:"voice"}],scrollable:t,searchGroups:this.searchGroups,asChatList:!0,hideEmptyTabs:!1,showSender:!0});e.prepend(n.nav.parentElement.parentElement),t.container.append(n.container);n.setQuery({peerId:0,folderId:0}),n.selectTab(0),n.load(!0);let a=[],o=0,r=0,l=0;const c=()=>{this.inputSearch.container.classList.toggle("is-picked-twice",2===a.length),this.inputSearch.container.classList.toggle("is-picked",!!a.length),a.length?this.inputSearch.input.style.setProperty("--paddingLeft",a[a.length-1].getBoundingClientRect().right-this.inputSearch.input.getBoundingClientRect().left+"px"):this.inputSearch.input.style.removeProperty("--paddingLeft")},d=document.createElement("div");d.classList.add("search-helper"),d.addEventListener("click",e=>{const t=Object(Ce.a)(e.target,"selector-user");if(!t)return;const s=t.dataset.key;if(0===s.indexOf("date_")){const[e,t,i]=s.split("_");r=+t,l=+i}else o=+s;t.addEventListener("click",()=>{p(t)}),this.inputSearch.container.append(t),this.inputSearch.onChange(this.inputSearch.value=""),a.push(t),c()}),n.nav.parentElement.append(d);const u=(e,t)=>{const s=document.createElement("div");s.classList.add("selector-user");const i=document.createElement("avatar-element");return i.classList.add("selector-user-avatar","tgico"),i.setAttribute("dialog","1"),i.classList.add("avatar-30"),s.dataset.key=""+e,"number"==typeof e?(void 0===t&&(t=new ft.a({peerId:e}).element),i.setAttribute("peer",""+e)):i.classList.add("tgico-calendarfilter"),t&&("string"==typeof t?s.innerHTML=t:(Object(x.a)(s,t),s.append(t))),s.insertAdjacentElement("afterbegin",i),s},p=e=>{0===e.dataset.key.indexOf("date_")?r=l=0:o=0,e.remove(),a.findAndSplice(t=>t===e),setTimeout(()=>{c(),this.inputSearch.onChange(this.inputSearch.value)},0)};this.inputSearch.onClear=()=>{a.forEach(e=>{p(e)})},this.inputSearch.onChange=e=>{if(n.cleanupHTML(),n.setQuery({peerId:o,folderId:o?void 0:0,query:e,minDate:r,maxDate:l}),n.load(!0),d.innerHTML="",n.nav.classList.remove("hide"),!o&&e.trim()){const t=n.middleware.get();Promise.all([i.a.getConversationsAll(e).then(e=>e.map(e=>e.peerId)),T.a.getContacts(e,!0)]).then(e=>{if(!t())return;new Set(e[0].concat(e[1])).forEach(e=>{d.append(u(e))}),n.nav.classList.toggle("hide",!!d.innerHTML)})}if(!r&&e.trim()){const t=[];Object(re.a)(e,t),t.forEach(e=>{d.append(u("date_"+e.minDate+"_"+e.maxDate,e.title))}),n.nav.classList.toggle("hide",!!d.innerHTML)}},n.tabs.inputMessagesFilterEmpty.addEventListener("mousedown",e=>{const t=Object(mt.a)(e.target,"LI");if(!t)return;const s=Object(Ce.a)(t,"search-group");if(!s||s.classList.contains("search-group-recent")||s.classList.contains("search-group-people"))return;const i=+t.getAttribute("data-peer-id");k.default.getState().then(e=>{const t=e.recentSearch||[];if(t[0]!==i){t.findAndSplice(e=>e===i),t.unshift(i),t.length>20&&(t.length=20),k.default.pushToState("recentSearch",t);for(const e of t)k.default.requestPeer(e,"recentSearch")}})},{capture:!0});let m=document.createElement("div");m.classList.add("search-group-scrollable"),m.append(this.searchGroups.people.list),this.searchGroups.people.container.append(m);new P.a(m);let g,b=!0;const v=Object(D.a)(e.parentElement,"zoom-fade",150,e=>{g&&clearTimeout(g),0!==e||b||(n.selectTab(0,!1),this.inputSearch.onClearClick(),g=window.setTimeout(()=>{g=0,this.newBtnMenu.classList.remove("is-hidden")},150)),b=!1});v(0);const f=()=>{this.toolsBtn.classList.remove("is-visible"),this.backBtn.classList.add("is-visible"),this.newBtnMenu.classList.add("is-hidden"),this.toolsBtn.parentElement.firstElementChild.classList.toggle("state-back",!0),h.IS_MOBILE_SAFARI||B.a.findItemByType("global-search")||B.a.pushItem({onPop:()=>{s()},type:"global-search"}),v(1)};this.inputSearch.input.addEventListener("focus",f),f(),this.backBtn.addEventListener("click",e=>{this.toolsBtn.classList.add("is-visible"),this.backBtn.classList.remove("is-visible"),this.toolsBtn.parentElement.firstElementChild.classList.toggle("state-back",!1),B.a.removeByType("global-search"),v(0)});const y=document.createElement("button");y.classList.add("btn-icon","tgico-close"),this.searchGroups.recent.nameEl.append(y),y.addEventListener("click",()=>{this.searchGroups.recent.clear(),k.default.pushToState("recentSearch",[])})}};de.a.appSidebarLeft=rn;var ln=rn;class cn{constructor(e){this.chat=e,this.bubbles=[],this.detailsMap=new Map,this.groups=[],this.newGroupDiff=121}removeBubble(e){const t=this.detailsMap.get(e);t&&(t.group.length&&(t.group.findAndSplice(t=>t.bubble===e),t.group.length?this.updateGroup(t.group):this.groups.findAndSplice(e=>e===t.group)),this.detailsMap.delete(e))}addBubble(e,t,s){const i=t.date,n=t.mid;let o,r=t.viaBotId||t.fromId;r===a.default.myId&&t.peerId===a.default.myId&&t.fwdFromId===r&&(r=-r),this.removeBubble(e);const l={bubble:e,mid:n,timestamp:i};if(this.bubbles.length){let e,t=-1;for(let e=0;e<this.bubbles.length;++e){const s=this.bubbles[e],a=Math.abs(s.timestamp-i);if(s.fromId===r&&a<=this.newGroupDiff){if(t=e,"scheduled"===this.chat.type)break}else t=-1;if("scheduled"!==this.chat.type&&n>s.mid)break}if(-1!==t&&(e=this.bubbles[t]),e){o=e.group;let t=0,s=0;for(;t<o.length;++t){const e=o[t].timestamp,a=o[t].mid;if(i<e)break;if(i===e&&(s=a),s&&n<s)break}o.splice(t,0,l)}else this.groups.push(o=[l])}else this.groups.push(o=[l]);const c={timestamp:i,fromId:r,mid:t.mid,group:o};let d=0;for(;d<this.bubbles.length&&!(this.bubbles[d].mid<n);++d);this.bubbles.splice(d,0,{timestamp:i,fromId:r,mid:t.mid,group:o}),this.updateGroup(o),this.detailsMap.set(e,c)}updateGroup(e){if(!e.length)return;const t=e[0].bubble;if(1===e.length)return void t.classList.add("is-group-first","is-group-last");t.classList.remove("is-group-last"),t.classList.add("is-group-first");const s=e.length-1;for(let t=1;t<s;++t){e[t].bubble.classList.remove("is-group-last","is-group-first")}const i=e[e.length-1].bubble;i.classList.remove("is-group-first"),i.classList.add("is-group-last")}updateGroupByMessageId(e){const t=this.bubbles.find(t=>t.mid===e);t&&this.updateGroup(t.group)}cleanup(){this.bubbles=[],this.groups=[],this.detailsMap.clear()}}class dn extends ct.b{constructor(e,t,s={}){if(super("popup-date-picker",s.noButtons?[]:[{langKey:"JumpToDate",callback:()=>{this.onPick&&this.onPick(this.selectedDate.getTime()/1e3|0)}},{langKey:"Cancel",isCancel:!0}],Object.assign({body:!0,overlayClosable:!0},s)),this.onPick=t,this.options=s,this.onPrevClick=e=>{this.selectedMonth.setMonth(this.selectedMonth.getMonth()-1),this.setMonth(),this.selectedMonth.getTime()===this.minMonth.getTime()&&this.prevBtn.setAttribute("disabled","true"),this.nextBtn.removeAttribute("disabled")},this.onNextClick=e=>{this.selectedMonth.setMonth(this.selectedMonth.getMonth()+1),this.setMonth(),this.selectedMonth.getTime()===this.maxMonth.getTime()&&this.nextBtn.setAttribute("disabled","true"),this.prevBtn.removeAttribute("disabled")},this.onDateClick=e=>{const t=e.target;if(!t.dataset.timestamp)return;if(this.selectedEl){if(this.selectedEl===t)return;this.selectedEl.classList.remove("active")}this.selectedEl=t,t.classList.add("active");const s=+t.dataset.timestamp;this.selectedDate=new Date(s),this.setTitle(),this.setTimeTitle()},this.minDate=s.minDate||new Date("2013-08-01T00:00:00"),e<this.minDate&&e.setFullYear(this.minDate.getFullYear(),this.minDate.getMonth(),this.minDate.getDate()),this.controlsDiv=document.createElement("div"),this.controlsDiv.classList.add("date-picker-controls"),this.prevBtn=document.createElement("button"),this.prevBtn.classList.add("btn-icon","tgico-down","date-picker-prev"),Object(l.b)(this.prevBtn,this.onPrevClick,{listenerSetter:this.listenerSetter}),this.nextBtn=document.createElement("button"),this.nextBtn.classList.add("btn-icon","tgico-down","date-picker-next"),Object(l.b)(this.nextBtn,this.onNextClick,{listenerSetter:this.listenerSetter}),this.monthTitle=document.createElement("div"),this.monthTitle.classList.add("date-picker-month-title"),this.controlsDiv.append(this.prevBtn,this.monthTitle,this.nextBtn),this.monthsContainer=document.createElement("div"),this.monthsContainer.classList.add("date-picker-months"),Object(l.b)(this.monthsContainer,this.onDateClick,{listenerSetter:this.listenerSetter}),this.body.append(this.controlsDiv,this.monthsContainer),s.withTime){this.timeDiv=document.createElement("div"),this.timeDiv.classList.add("date-picker-time");const t=document.createElement("div");t.classList.add("date-picker-time-delimiter"),t.append(":");const s=(e,t,s,i)=>{const n=""+e;this.listenerSetter.add(t.input)("input",a=>{let o=t.value.replace(/\D/g,"");o.length>2?o=o.slice(0,2):(1===o.length&&+o[0]>+n[0]||2===o.length&&+o>e)&&(2===o.length&&i&&i(+o[1]),o="0"+o[0]),t.setValueSilently(o),s(o.length)})};this.hoursInputField=new F.b({plainText:!0}),this.minutesInputField=new F.b({plainText:!0}),s(23,this.hoursInputField,e=>{2===e&&this.minutesInputField.input.focus(),this.setTimeTitle()},e=>{this.minutesInputField.value=(e+this.minutesInputField.value).slice(0,2)}),s(59,this.minutesInputField,e=>{e||this.hoursInputField.input.focus(),this.setTimeTitle()}),this.selectedDate=e,e.setMinutes(e.getMinutes()+10),this.hoursInputField.setValueSilently(("0"+e.getHours()).slice(-2)),this.minutesInputField.setValueSilently(("0"+e.getMinutes()).slice(-2)),e.setHours(0,0,0,0),this.timeDiv.append(this.hoursInputField.container,t,this.minutesInputField.container),Object(l.b)(this.btnConfirm,()=>{this.onPick&&(this.selectedDate.setHours(+this.hoursInputField.value||0,+this.minutesInputField.value||0,0,0),this.onPick(this.selectedDate.getTime()/1e3|0)),this.hide()},{listenerSetter:this.listenerSetter}),this.body.append(this.timeDiv),this.prevBtn.classList.add("primary"),this.nextBtn.classList.add("primary")}const i=document.createElement("div");i.classList.add("popup-centerer"),i.append(this.container),this.element.append(i),e.setHours(0,0,0,0),this.selectedDate=e,this.maxDate=s.maxDate||new Date,this.maxDate.setHours(0,0,0,0),this.selectedMonth=new Date(this.selectedDate),this.selectedMonth.setDate(1),this.maxMonth=new Date(this.maxDate),this.maxMonth.setDate(1),this.minMonth=new Date(this.minDate),this.minMonth.setHours(0,0,0,0),this.minMonth.setDate(1),this.selectedMonth.getTime()===this.minMonth.getTime()&&this.prevBtn.setAttribute("disabled","true"),this.selectedMonth.getTime()===this.maxMonth.getTime()&&this.nextBtn.setAttribute("disabled","true"),s.noTitle&&(this.setTitle=()=>{}),this.setTimeTitle(),this.setTitle(),this.setMonth()}setTimeTitle(){if(this.btnConfirm&&this.selectedDate){let e,t=[];const s=new Date;s.setHours(0,0,0,0);const i={minute:"2-digit",hour:"2-digit"},n=new Date(this.selectedDate.getTime());if(n.setHours(+this.hoursInputField.value,+this.minutesInputField.value),this.selectedDate.getTime()===s.getTime())e="Schedule.SendToday";else{e="Schedule.SendDate";const i={month:"short",day:"numeric"};n.getFullYear()!==s.getFullYear()&&(i.year="numeric"),t.push(new A.default.IntlDateElement({date:n,options:i}).element)}t.push(new A.default.IntlDateElement({date:n,options:i}).element),this.btnConfirm.firstChild.replaceWith(Object(A.i18n)(e,t))}}setTitle(){this.title.textContent="",this.title.append(new A.default.IntlDateElement({date:this.selectedDate,options:{day:"numeric",month:"long",weekday:"short"}}).element)}renderElement(e,t=""){const s=document.createElement("button");return s.classList.add("btn-icon","date-picker-month-date"),e&&s.setAttribute("disabled","true"),t&&s.append(t),s}setMonth(){const e=new Date(this.selectedMonth),t={year:"numeric",month:this.timeDiv&&v.b.isMobile?"short":"long"};this.monthTitle.textContent="",this.monthTitle.append(new A.default.IntlDateElement({date:e,options:t}).element),this.month&&this.month.remove(),this.month=document.createElement("div"),this.month.classList.add("date-picker-month");const s=new Date,i=s.getDay();1!==i&&s.setHours(-24*(i-1));for(let e=0;e<7;++e){const e=this.renderElement(!0,new A.default.IntlDateElement({date:s,options:{weekday:"narrow"}}).element);e.classList.remove("date-picker-month-date"),e.classList.add("date-picker-month-day"),this.month.append(e),s.setDate(s.getDate()+1)}let n=e.getDay()-1;-1===n&&(n=6);const a=new Date(e.getTime());a.setDate(a.getDate()-n-1);for(let e=0;e<n;++e)this.options.showOverflowMonths?(a.setDate(a.getDate()+1),this.month.append(this.renderElement(!0,""+a.getDate()))):this.month.append(this.renderElement(!0));do{const t=e.getDate(),s=this.renderElement(e>this.maxDate||e<this.minDate,""+t);s.dataset.timestamp=""+e.getTime(),e.getTime()===this.selectedDate.getTime()&&(this.selectedEl=s,s.classList.add("active")),this.month.append(s),e.setDate(t+1)}while(1!==e.getDate());const o=this.month.childElementCount%7;if(this.options.showOverflowMonths&&o)for(let t=o;t<7;++t)this.month.append(this.renderElement(!0,""+e.getDate())),e.setDate(e.getDate()+1);const r=Math.ceil(this.month.childElementCount/7);this.container.dataset.lines=""+r,this.monthsContainer.append(this.month)}}class hn{constructor(e,t){this.container=e,this.handler=t,this.observeHeaders(),this.observeElements()}observeHeaders(){this.headersObserver=new IntersectionObserver(e=>{for(const t of e){const e=t.boundingClientRect,s=t.target.parentElement,i=t.rootBounds;e.bottom<i.top&&this.handler(!0,s),e.bottom>=i.top&&e.bottom<i.bottom&&this.handler(!1,s)}},{threshold:0,root:this.container})}observeElements(){this.elementsObserver=new IntersectionObserver(e=>{let t=e.filter(e=>e.boundingClientRect.top<0).sort((e,t)=>e.boundingClientRect.top-t.boundingClientRect.top)[0];if(!t)return;let s=t.isIntersecting?t.target:t.target.nextElementSibling;this.handler(!0,s)},{root:this.container})}addSentinel(e,t){const s=document.createElement("div");return s.classList.add("sticky_sentinel",t),e.appendChild(s)}observeStickyHeaderChanges(e){const t=this.addSentinel(e,"sticky_sentinel--top");this.headersObserver.observe(t),this.elementsObserver.observe(e)}disconnect(){this.headersObserver.disconnect(),this.elementsObserver.disconnect()}unobserve(e,t){this.elementsObserver.unobserve(e),this.headersObserver.unobserve(t)}}a.default.addEventListener("replies_updated",e=>{const t=e;Array.from(document.querySelectorAll(`replies-element[data-post-key="${t.peerId}_${t.mid}"]`)).forEach(e=>{e.message=t,e.render()})});class un extends HTMLElement{constructor(){super(),this.updated=!1}init(){this.render(),this.dataset.postKey=this.message.peerId+"_"+this.message.mid,this.classList.add("replies","replies-"+this.type)}render(){const e=this.message.replies;if("footer"===this.type){let t,s;if(this.firstElementChild&&(t=this.firstElementChild),(null==e?void 0:e.recent_repliers)?(t&&!t.classList.contains("replies-footer-avatars")&&(this.innerHTML="",t=null),t||(t=document.createElement("div"),t.classList.add("replies-footer-avatars")),e.recent_repliers.slice().reverse().forEach((e,s)=>{let i=t.children[s];i||(i=new ko,i.setAttribute("dialog","0"),i.classList.add("avatar-30"),i.lazyLoadQueue=this.lazyLoadQueue,this.loadPromises&&(i.loadPromises=this.loadPromises)),i.setAttribute("peer",""+o.a.getPeerId(e)),i.parentNode||t.append(i)}),Array.from(t.children).slice(e.recent_repliers.length).forEach(e=>e.remove())):(t&&!t.classList.contains("tgico-comments")&&(t.remove(),t=null),t||(t=document.createElement("span"),t.classList.add("tgico-comments"))),t.parentElement||this.append(t),s=e?e.replies?Object(A.i18n)("Comments",[e.replies]):Object(A.i18n)("LeaveAComment"):Object(A.i18n)("ViewInChat"),e){const t=i.a.getHistoryStorage(-e.channel_id);let s=!1;e.replies&&(s=void 0!==e.read_max_id&&void 0!==e.max_id?e.read_max_id<e.max_id:!t.readMaxId||t.readMaxId<(e.max_id||0)),this.classList.toggle("is-unread",s)}let n=this.children[1];if(!n){n=document.createElement("span"),n.classList.add("replies-footer-text");const e=document.createElement("span");e.classList.add("tgico-next");const t=document.createElement("div");Object(ie.ripple)(t),this.append(n,e,t)}Object(x.a)(n,s)}else this.classList.add("bubble-beside-button"),this.innerHTML=`<span class="tgico-commentssticker"></span><span class="replies-beside-text">${(null==e?void 0:e.replies)?Object(C.c)(e.replies,0):""}</span>`;!e||this.updated||this.message.pFlags.is_outgoing||(i.a.subscribeRepliesThread(this.message.peerId,this.message.mid),i.a.updateMessage(this.message.peerId,this.message.mid,"replies_updated"),this.updated=!0),this.loadPromises&&(this.loadPromises=void 0)}}var pn,mn;customElements.define("replies-element",un),(mn=pn||(pn={})).setTime=(e,t,s,i,n)=>{var a,o;const r=new Date(1e3*t.date);let l=("0"+r.getHours()).slice(-2)+":"+("0"+r.getMinutes()).slice(-2);if(t.views){const n=t.post_author||(null===(a=t.fwd_from)||void 0===a?void 0:a.post_author);if(s.classList.add("channel-post"),l='<span class="post-views">'+Object(C.c)(t.views,1)+'</span> <i class="tgico-channelviews time-icon"></i> '+(n?Z.b.wrapEmojiText(n)+", ":"")+l,!(null===(o=t.fwd_from)||void 0===o?void 0:o.saved_from_msg_id)&&"pinned"!==e.type){const e=document.createElement("div");e.classList.add("bubble-beside-button","forward"),e.innerHTML='\n <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24">\n <defs>\n <path d="M13.55 3.24L13.64 3.25L13.73 3.27L13.81 3.29L13.9 3.32L13.98 3.35L14.06 3.39L14.14 3.43L14.22 3.48L14.29 3.53L14.36 3.59L14.43 3.64L22.23 10.85L22.36 10.99L22.48 11.15L22.57 11.31L22.64 11.48L22.69 11.66L22.72 11.85L22.73 12.04L22.71 12.22L22.67 12.41L22.61 12.59L22.53 12.76L22.42 12.93L22.29 13.09L22.23 13.15L14.43 20.36L14.28 20.48L14.12 20.58L13.95 20.66L13.77 20.72L13.58 20.76L13.4 20.77L13.22 20.76L13.03 20.73L12.85 20.68L12.68 20.61L12.52 20.52L12.36 20.4L12.22 20.27L12.16 20.2L12.1 20.13L12.05 20.05L12.01 19.98L11.96 19.9L11.93 19.82L11.89 19.73L11.87 19.65L11.84 19.56L11.83 19.47L11.81 19.39L11.81 19.3L11.8 19.2L11.8 16.42L11 16.49L10.23 16.58L9.51 16.71L8.82 16.88L8.18 17.09L7.57 17.33L7.01 17.6L6.48 17.91L5.99 18.26L5.55 18.64L5.14 19.05L4.77 19.51L4.43 19.99L4.29 20.23L4.21 20.35L4.11 20.47L4 20.57L3.88 20.65L3.75 20.72L3.62 20.78L3.48 20.82L3.33 20.84L3.19 20.84L3.04 20.83L2.9 20.79L2.75 20.74L2.62 20.68L2.53 20.62L2.45 20.56L2.38 20.5L2.31 20.43L2.25 20.36L2.2 20.28L2.15 20.19L2.11 20.11L2.07 20.02L2.04 19.92L2.02 19.83L2.01 19.73L2 19.63L2.04 17.99L2.19 16.46L2.46 15.05L2.85 13.75L3.35 12.58L3.97 11.53L4.7 10.6L5.55 9.8L6.51 9.12L7.59 8.56L8.77 8.13L10.07 7.83L11.48 7.65L11.8 7.63L11.8 4.8L11.91 4.56L12.02 4.35L12.14 4.16L12.25 3.98L12.37 3.82L12.48 3.68L12.61 3.56L12.73 3.46L12.85 3.38L12.98 3.31L13.11 3.27L13.24 3.24L13.37 3.23L13.46 3.23L13.55 3.24Z" id="b13RmHDQtl"></path>\n </defs>\n <use xlink:href="#b13RmHDQtl" opacity="1" fill="#fff" fill-opacity="1"></use>\n </svg>',i.append(e),s.classList.add("with-beside-button")}}t.edit_date&&"scheduled"!==e.type&&!t.pFlags.edit_hide&&(s.classList.add("is-edited"),l='<i class="edited">edited</i> '+l),"pinned"!==e.type&&t.pFlags.pinned&&(s.classList.add("is-pinned"),l='<i class="tgico-pinnedchat time-icon"></i>'+l);const c=Object(re.e)(r)+(t.edit_date?"\nEdited: "+Object(re.e)(new Date(1e3*t.edit_date)):"")+(t.fwd_from?"\nOriginal: "+Object(re.e)(new Date(1e3*t.fwd_from.date)):""),d=document.createElement("span");return d.classList.add("time","tgico"),d.title=c,d.innerHTML=`${l}<div class="inner tgico" title="${c}">${l}</div>`,n.append(d),d},mn.renderReplies=({bubble:e,bubbleContainer:t,message:s,messageDiv:i,loadPromises:n,lazyLoadQueue:a})=>{const o=!e.classList.contains("sticker")&&!e.classList.contains("emoji-big")&&!e.classList.contains("round"),r=new un;return r.message=s,r.type=o?"footer":"beside",r.loadPromises=n,r.lazyLoadQueue=a,r.init(),t.prepend(r),o},mn.setReply=({chat:e,bubble:t,bubbleContainer:s,message:i})=>{const n=!s;n&&(s=t.querySelector(".bubble-content"));const a=n?s.querySelector(".reply"):null;if(!i.reply_to_mid)return a&&a.remove(),void t.classList.remove("is-reply");const o=i.reply_to.reply_to_peer_id?e.appPeersManager.getPeerId(i.reply_to.reply_to_peer_id):e.peerId;let r,l=e.appMessagesManager.getMessageByPeer(o,i.reply_to_mid);"messageEmpty"===l._?(e.appMessagesManager.wrapSingleMessage(o,i.reply_to_mid),e.bubbles.needUpdate.push({replyToPeerId:o,replyMid:i.reply_to_mid,mid:i.mid}),r=Object(A.i18n)("Loading")):r=new ft.a({peerId:l.fromId||l.fwdFromId,dialog:!1,onlyFirstName:!1,plainText:!1}).element;const c=Es(r,void 0,l);a?a.replaceWith(c):s.append(c),t.classList.add("is-reply")};var gn=s(119),bn=s(121);function vn(e,t,s){const i=e.getBoundingClientRect(),n="center"===s?Math.ceil(i.left+(i.right-i.left)/2+1):Math.ceil(i.left+1),a="bottom"===t?Math.floor(i.top+i.height-1):Math.ceil(i.top+1);return document.elementFromPoint(n,a)}function fn(e){e.style.display="none",e.offsetLeft,e.style.display=""}de.a.getElementByPoint=vn;var yn=s(76),wn=s(140),Ln=s(106),Sn=s(75);const En={keywords:{},version:0,langCode:tn.a.langPackCode};class Mn{constructor(){this.keywordLangPacks={},this.indexedLangPacks={},this.getKeywordsPromises={}}getEmojiKeywords(e=tn.a.langPackCode){const t=this.getKeywordsPromises[e];if(t)return t;const s="emojiKeywords_"+e;return this.getKeywordsPromises[e]=Sn.a.get(s).then(t=>(Object(wn.a)(t)||(t={}),Object(L.k)(En,t),t.langCode=e,this.keywordLangPacks[e]=t,rt.a.invokeApi("messages.getEmojiKeywordsDifference",{lang_code:t.langCode,from_version:t.version}).then(e=>{t.version=e.version;const i=t.keywords,n=e.keywords;for(let e=0,t=n.length;e<t;++e){const{keyword:t,emoticons:s}=n[e];i[t]=s}return Sn.a.set({[s]:t}),t},()=>t)))}getBothEmojiKeywords(){const e=[this.getEmojiKeywords()];return A.default.lastRequestedLangCode!==tn.a.langPackCode&&e.push(this.getEmojiKeywords(A.default.lastRequestedLangCode)),this.recent||e.push(this.getRecentEmojis()),Promise.all(e)}indexEmojis(){this.index||(this.index=new Ln.a(void 0,2));for(const e in this.keywordLangPacks){if(this.indexedLangPacks[e])continue;const t=this.keywordLangPacks[e].keywords;for(const e in t){const s=t[e];this.index.indexObject(s,e)}this.indexedLangPacks[e]=!0}}searchEmojis(e){let t;if(this.indexEmojis(),(e=e.toLowerCase().replace(/_/g," ")).trim()){const s=this.index.search(e);t=Array.from(s).reduce((e,t)=>e.concat(t),[])}else t=this.recent.concat(Mn.POPULAR_EMOJI).slice(0,36);return t=Array.from(new Set(t)),t}getRecentEmojis(){return this.getRecentEmojisPromise?this.getRecentEmojisPromise:this.getRecentEmojisPromise=k.default.getState().then(e=>this.recent=Array.isArray(e.recentEmoji)?e.recentEmoji:[])}pushRecentEmoji(e){e=Z.b.fixEmoji(e),this.getRecentEmojis().then(t=>{t.findAndSplice(t=>t===e),t.unshift(e),t.length>36&&(t.length=36),k.default.pushToState("recentEmoji",t),a.default.dispatchEvent("emoji_recent",e)})}}Mn.POPULAR_EMOJI=["😂","😘","❤️","😍","😊","😁","👍","☺️","😔","😄","😭","💋","😒","😳","😜","🙈","😉","😃","😢","😝","😱","😡","😏","😞","😅","😚","🙊","😌","😀","😋","😆","👌","😐","😕"];const In=new Mn;de.a&&(de.a.appEmojiManager=In);var Cn=In,kn=s(126),Tn=s(9);const Pn=new Set;function xn(e,t,s=!1,i=!1){const n=document.createElement("span");let o;if(n.classList.add("super-emoji"),i&&!Tn.a?o=Z.a.wrapSingleEmoji(e):(e=Z.a.fixEmoji(e),o=Z.a.wrapEmojiText(e)),n.innerHTML=o,n.children.length>1){const e=n.firstElementChild;n.innerHTML="",n.append(e)}if(n.firstElementChild&&!Tn.a){const e=n.firstElementChild,t=e.src;if(!Pn.has(t)){e.setAttribute("loading","lazy");const s=document.createElement("span");s.classList.add("emoji-placeholder"),a.default.settings.animationsEnabled&&(e.style.opacity="0",s.style.opacity="1"),e.addEventListener("load",()=>{Object(_e.b)(()=>{a.default.settings.animationsEnabled&&(e.style.opacity="",s.style.opacity=""),n.classList.remove("empty"),Pn.add(t)})},{once:!0}),n.append(s)}}s?t.prepend(n):t.appendChild(n)}function An(e){return Object(Ce.a)(e,"super-emoji")?3===e.nodeType?e.nodeValue:("SPAN"===e.tagName&&!e.classList.contains("emoji")&&e.firstElementChild&&(e=e.firstElementChild),e.getAttribute("alt")||e.innerText):""}class On{constructor(){this.closeScrollTop=0,this.onContentClick=e=>{Object(c.a)(e);const t=An(e.target);if(!t)return;const s=mo.chat.input.messageInput;let i=s.innerHTML;const n=Z.a.wrapEmojiText(t,!0);let a=!1;if(window.getSelection){const e=pe.IS_TOUCH_SUPPORTED?void 0:Jn.getSavedRange();let t=window.getSelection();if(e&&(t.removeAllRanges(),t.addRange(e)),t.getRangeAt&&t.rangeCount){var o=document.createElement("div");o.innerHTML=n;var r=o.firstChild,l=t.getRangeAt(0);l.deleteContents(),l.insertNode(r),l.setStart(r,0),a=!0,setTimeout(()=>{(l=document.createRange()).setStartAfter(r),l.collapse(!0),t.removeAllRanges(),t.addRange(l)},0)}}a&&s.innerHTML!==i||s.insertAdjacentHTML("beforeend",n);const d=new Event("input",{bubbles:!0,cancelable:!0});s.dispatchEvent(d)}}init(){this.content=document.getElementById("content-emoji");const e=["Emoji.SmilesAndPeople","Emoji.AnimalsAndNature","Emoji.FoodAndDrink","Emoji.TravelAndPlaces","Emoji.ActivityAndSport","Emoji.Objects","Emoji.Flags","Skin Tones"],t={},s=new Map([["Emoji.Recent",[]]]);for(const t in kn.a.Emoji){const i=""+kn.a.Emoji[t],n=e[+i[0]-1];if(!n)continue;let a=s.get(n);a||(a=[],s.set(n,a)),a[+i.slice(1)||0]=t}s.delete(e.pop()),s.forEach((e,s)=>{const i=document.createElement("div");i.classList.add("emoji-category");const n=document.createElement("div");n.classList.add("category-title"),n.append(Object(A.i18n)(s));const a=document.createElement("div");a.classList.add("super-emojis"),i.append(n,a),e.forEach(e=>{xn(Object(ne.a)(e),a,!1)}),t[s]=i});const i=this.menu=this.content.previousElementSibling,n=this.scroll=new P.b(this.content,"EMOJI"),o=Object(se.f)(this.content,!0);Promise.all([Object(yn.a)(200),Cn.getRecentEmojis().then(e=>{const t=!!e.length,s=t?0:1;this.menu.children[0].classList.toggle("hide",!t),this.menu.children[s].classList.add("active");const a=Yn.menuOnClick(i,n,void 0,s);return this.stickyIntersector=a.stickyIntersector,this.setMenuActive=a.setActive,e})]).then(([s,i])=>{o.remove(),this.recentItemsDiv=t["Emoji.Recent"].querySelector(".super-emojis");for(const e of i)xn(e,this.recentItemsDiv);this.recentItemsDiv.parentElement.classList.toggle("hide",!this.recentItemsDiv.childElementCount),e.unshift("Emoji.Recent"),e.map(e=>{const s=t[e];return s||console.error("no div by category:",e),n.container.append(s),this.stickyIntersector.observeStickyHeaderChanges(s),s})}),this.content.addEventListener("click",this.onContentClick),this.init=null,a.default.addEventListener("emoji_recent",e=>{const t=Array.from(this.recentItemsDiv.children);for(let s=0,i=t.length;s<i;++s){const i=t[s];if(e===Z.a.fixEmoji(An(i))){if(0===s)return;i.remove()}}xn(e,this.recentItemsDiv,!0),this.recentItemsDiv.parentElement.classList.remove("hide"),this.menu.children[0].classList.remove("hide"),this.closeScrollTop||this.setMenuActive(0)}),Jn.addEventListener("close",()=>{this.closeScrollTop=this.scroll.scrollTop})}onClose(){}}var _n=s(114),Fn=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class jn{constructor(e,t,s,i=!0){this.element=e,this.group=t,this.scrollable=s,this.scrollPromise=Promise.resolve(),this.timeout=0,this.onScroll=()=>{this.timeout?clearTimeout(this.timeout):this.scrollPromise=Object(oe.a)(),this.timeout=window.setTimeout(()=>{this.timeout=0,this.scrollPromise.resolve()},150)},this.processInvisibleDiv=e=>this.scrollPromise.then(()=>Fn(this,void 0,void 0,(function*(){if(this.lazyLoadQueue.intersector.isVisible(e))return;const t=e.querySelector("video"),s=e.querySelector("img");if(s&&(s&&s.classList.remove("hide"),yield Object(_e.a)()),!this.lazyLoadQueue.intersector.isVisible(e)&&t){t.remove(),t.src="",t.load();I.a.getAnimations(t).forEach(e=>{I.a.checkAnimation(e,!0,!0)})}}))),this.lazyLoadQueue=new te.c(void 0,(e,t)=>{t?this.processVisibleDiv(e):this.processInvisibleDiv(e)}),i&&this.attach()}attach(){this.scrollable.container.addEventListener("scroll",this.onScroll)}detach(){this.clear(),this.scrollable.container.removeEventListener("scroll",this.onScroll)}clear(){this.lazyLoadQueue.clear()}processVisibleDiv(e){if(e.querySelector("video"))return;this.lazyLoadQueue.push({div:e,load:()=>{const t=e.dataset.docId,s=M.a.getDoc(t);return this.scrollPromise.then(()=>{const t=vs({doc:s,container:e,lazyLoadQueue:null,group:this.group,noInfo:!0}).loadPromise;return t.finally(()=>{const t=e.querySelector("video");e.style.opacity="";const s=e.querySelector("img");s&&s.classList.add("hide"),t&&!t.parentElement&&setTimeout(()=>{t.src="",t.load();I.a.getAnimations(t).forEach(e=>{I.a.checkAnimation(e,!0,!0)})},0),this.lazyLoadQueue.intersector.isVisible(e)||this.processInvisibleDiv(e)}),t})}})}add(e,t=this.element){var s;let i=e.w,n=e.h;n<100&&(i*=100/n,n=100);const a=Math.min(300,400,i),o=Object(_n.a)(i,n,a,100),r=document.createElement("div");r.classList.add("gif","fade-in-transition"),r.style.width=o.width+"px",r.style.opacity="0",r.dataset.docId=e.id,t.append(r),this.lazyLoadQueue.observe(r);const l=M.a.getThumb(e,!1);let c;!!l&&(c=new Image,c.classList.add("media-poster"),l.cacheContext.url||l.promise.then(()=>{c.src=l.cacheContext.url}));const d=()=>{c&&(r.append(c),r.style.opacity="")};(null===(s=null==l?void 0:l.cacheContext)||void 0===s?void 0:s.url)?Object(Rt.a)(c,l.cacheContext.url,d):d()}}class Dn{init(){this.content=document.getElementById("content-gifs");const e=this.content.firstElementChild;e.addEventListener("click",Yn.onMediaClick);const t=new P.b(this.content,"GIFS"),s=new jn(e,$n,t),i=Object(se.f)(this.content,!0);rt.a.invokeApi("messages.getSavedGifs",{hash:0}).then(e=>{"messages.savedGifs"===e._&&e.gifs.forEach((t,i)=>{e.gifs[i]=t=M.a.saveDoc(t),s.add(t)}),i.remove()}),Jn.addLazyLoadQueueRepeat(s.lazyLoadQueue,s.processInvisibleDiv),this.init=null}onClose(){}}var Bn=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class Rn{constructor(e,t){this.regularLazyLoadQueue=e,this.group=t,this.animatedDivs=new Set,this.checkAnimationContainer=(e,t)=>{I.a.getAnimations(e).forEach(e=>{t?I.a.checkAnimation(e,!1):I.a.checkAnimation(e,!0,!0)})},this.processVisibleDiv=e=>{const t=e.dataset.docId,s=M.a.getDoc(t),i=v.b.active.esgSticker.width,n=Ls({doc:s,div:e,width:i,height:i,lazyLoadQueue:null,group:this.group,onlyThumb:!1,play:!0,loop:!0});return n.then(()=>{this.checkAnimationContainer(e,this.lazyLoadQueue.intersector.isVisible(e))}),n},this.processInvisibleDiv=e=>{const t=e.dataset.docId,s=M.a.getDoc(t);this.checkAnimationContainer(e,!1),e.innerHTML="",this.renderSticker(s,e)},this.lazyLoadQueue=new te.b(void 0,(e,t)=>{t||this.processInvisibleDiv(e)})}clear(){this.lazyLoadQueue.clear()}renderSticker(e,t,s){return t||((t=document.createElement("div")).classList.add("grid-item","super-sticker"),2===e.sticker&&this.observeAnimatedDiv(t)),Ls({doc:e,div:t,lazyLoadQueue:this.regularLazyLoadQueue,group:this.group,onlyThumb:2===e.sticker,loadPromises:s}),t}observeAnimatedDiv(e){this.animatedDivs.add(e),this.lazyLoadQueue.observe({div:e,load:this.processVisibleDiv})}}class Hn{constructor(){this.stickerSets={},this.recentStickers=[],this.mounted=!1,this.queueCategoryPush=[]}categoryPush(e,t="",s,i){const n=document.createElement("div");n.classList.add("category-items","super-stickers");const a=document.createElement("div");return a.classList.add("category-title"),t&&(a.innerHTML=t),e.append(a,n),this.stickyIntersector.observeStickyHeaderChanges(e),this.queueCategoryPush.push({element:e,prepend:i}),s.then(e=>{e.forEach(e=>{n.append(this.superStickerRenderer.renderSticker(e))}),this.queueCategoryPush.length&&(this.queueCategoryPush.forEach(({element:e,prepend:t})=>{t?this.recentDiv.parentElement?(this.stickersDiv.prepend(e),this.stickersDiv.prepend(this.recentDiv)):this.stickersDiv.prepend(e):this.stickersDiv.append(e)}),this.queueCategoryPush.length=0)}),{titleDiv:a}}renderStickerSet(e,t=!1){return Bn(this,void 0,void 0,(function*(){const s=document.createElement("div");s.classList.add("sticker-category"),s.dataset.id=e.id,s.dataset.access_hash=e.access_hash;const i=document.createElement("button");i.classList.add("btn-icon","menu-horizontal-div-item"),this.stickerSets[e.id]={stickers:s,tab:i},t?this.menu.insertBefore(i,this.menu.firstElementChild.nextSibling):this.menu.append(i);const n=hs.getStickerSet(e);this.categoryPush(s,Z.a.wrapEmojiText(e.title),n.then(e=>e.documents),t);yield n;Ss({set:e,container:i,group:$n,lazyLoadQueue:Yn.lazyLoadQueue,width:32,height:32,autoplay:!1})}))}init(){this.content=document.getElementById("content-stickers"),this.recentDiv=document.createElement("div"),this.recentDiv.classList.add("sticker-category","stickers-recent");let e=this.content.previousElementSibling;this.menu=e.firstElementChild;let t=new P.a(e);this.stickersDiv=document.createElement("div"),this.stickersDiv.classList.add("stickers-categories"),this.content.append(this.stickersDiv),a.default.addEventListener("stickers_installed",e=>{const t=e;!this.stickerSets[t.id]&&this.mounted&&this.renderStickerSet(t,!0)}),a.default.addEventListener("stickers_deleted",e=>{const t=e;if(this.stickerSets[t.id]&&this.mounted){const e=this.stickerSets[t.id];e.stickers.remove(),e.tab.remove(),delete this.stickerSets[t.id]}}),this.stickersDiv.addEventListener("click",e=>{const t=e.target;if(Object(Ce.a)(t,"category-title")){const e=Object(vt.a)(t,"data-id");new Di({id:e.dataset.id,access_hash:e.dataset.access_hash}).show()}else Yn.onMediaClick(e)}),this.scroll=new P.b(this.content,"STICKERS"),this.scroll.setVirtualContainer(this.stickersDiv),this.stickyIntersector=Yn.menuOnClick(this.menu,this.scroll,t).stickyIntersector;const s=Object(se.f)(this.content,!0);Promise.all([hs.getRecentStickers().then(e=>{this.recentStickers=e.stickers.slice(0,20),this.stickerSets.recent={stickers:this.recentDiv,tab:this.menu.firstElementChild},s.remove();const{titleDiv:t}=this.categoryPush(this.recentDiv,"",Promise.resolve(this.recentStickers),!0);t.append(Object(A.i18n)("Stickers.Recent"))}),hs.getAllStickers().then(e=>{s.remove();for(let t of e.sets)this.renderStickerSet(t)})]).finally(()=>{this.mounted=!0}),this.superStickerRenderer=new Rn(Yn.lazyLoadQueue,$n),Jn.addLazyLoadQueueRepeat(this.superStickerRenderer.lazyLoadQueue,this.superStickerRenderer.processInvisibleDiv),this.init=null}pushRecentSticker(e){var t;if(!(null===(t=this.recentDiv)||void 0===t?void 0:t.parentElement))return;let s=this.recentDiv.querySelector(`[data-doc-id="${e.id}"]`);s||(s=this.superStickerRenderer.renderSticker(e));const i=this.recentDiv.querySelector(".category-items");i.prepend(s),i.childElementCount>20&&Array.from(i.children).slice(20).forEach(e=>e.remove())}onClose(){}}var Un=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};const Nn=new class{constructor(){this.inlineResults={},this.setHash={}}getGeoInput(e){return"geoPoint"===e._?{_:"inputGeoPoint",lat:e.lat,long:e.long,accuracy_radius:e.accuracy_radius}:{_:"inputGeoPointEmpty"}}getInlineResults(e,t,s="",i="",n){return rt.a.invokeApi("messages.getInlineBotResults",{bot:T.a.getUserInput(t),peer:o.a.getInputPeerById(e),query:s,geo_point:n?this.getGeoInput(n):void 0,offset:i},{stopTime:-1,noErrorBox:!0}).then(e=>{const t=e.query_id;return e.results.forEach(e=>{"botInlineMediaResult"===e._&&(e.document&&(e.document=M.a.saveDoc(e.document)),e.photo&&(e.photo=r.a.savePhoto(e.photo))),this.inlineResults[this.generateQId(t,e.id)]=e}),e})}generateQId(e,t){return e+"_"+t}pushPopularBot(e){T.a.getTopPeers("bots_inline").then(t=>{const s=t.findIndex(e=>e.id);let i;i=-1!==s?t[s]:{id:e,rating:0},++i.rating,Object(y.e)(t,i,"rating"),k.default.setKeyValueToStorage("topPeersCache")})}switchToPM(e,t,s){return this.setHash[t]={peerId:e,time:Date.now()},a.default.dispatchEvent("history_focus",{peerId:t}),i.a.startBot(t,0,s)}checkSwitchReturn(e){return Un(this,void 0,void 0,(function*(){const t=T.a.getUser(e);if(!t||!t.pFlags.bot||!t.bot_inline_placeholder)return;const s=this.setHash[e];return s&&(delete this.setHash[e],Date.now()-s.time<36e5)?s.peerId:void 0}))}switchInlineQuery(e,t,s,i){a.default.dispatchEvent("history_focus",{peerId:e,threadId:t}),Si.a.setDraft(e,t,"@"+T.a.getUser(s).username+" "+i)}callbackButtonClick(e,t,s){return rt.a.invokeApi("messages.getBotCallbackAnswer",{peer:o.a.getInputPeerById(e),msg_id:f.a.getServerMessageId(t),data:s.data},{stopTime:-1,noErrorBox:!0}).then(e=>{"string"==typeof e.message&&e.message.length&&nt(Z.a.wrapRichText(e.message,{noLinks:!0,noLinebreaks:!0}))})}sendInlineResult(e,t,s,n={}){var a;const o=this.inlineResults[s];if(!o)return;this.pushPopularBot(t);const l=s.split("_"),c=l.shift(),d=l.join("_");if(n.viaBotId=t,n.queryId=c,n.resultId=d,o.send_message.reply_markup&&(n.replyMarkup=o.send_message.reply_markup),"botInlineMessageText"===o.send_message._)n.entities=o.send_message.entities,i.a.sendText(e,o.send_message.message,n);else{let t,s="";const l=o.send_message;switch(l._){case"botInlineMessageMediaAuto":if(s=l.message,"botInlineMediaResult"===o._){const{document:e,photo:s}=o;t=e?M.a.getMediaInput(e):r.a.getMediaInput(s)}break;case"botInlineMessageMediaGeo":t={_:"inputMediaGeoPoint",geo_point:this.getGeoInput(l.geo)},n.geoPoint=l.geo;break;case"botInlineMessageMediaVenue":t={_:"inputMediaVenue",geo_point:this.getGeoInput(l.geo),title:l.title,address:l.address,provider:l.provider,venue_id:l.venue_id,venue_type:l.venue_type},n.geoPoint=l.geo;break;case"botInlineMessageMediaContact":t={_:"inputMediaContact",phone_number:l.phone_number,first_name:l.first_name,last_name:l.last_name,vcard:l.vcard}}t||(t={_:"messageMediaPending",type:o.type,file_name:o.title||(null===(a=o.content)||void 0===a?void 0:a.url)||o.url,size:0,progress:{percent:30,total:0}}),i.a.sendOther(e,t,n)}}};de.a&&(de.a.appInlineBotsManager=Nn);var zn=Nn,Vn=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class Wn extends V{constructor(){super(...arguments),this.nextOffset="",this.loadedAll=!1,this.onGifsClick=e=>{const t=Object(Ce.a)(e.target,"gif");if(!t)return;const s=t.dataset.docId;mo.chat.input.sendMessageWithDocument(s)?v.b.isMobile&&$t.onCloseBtnClick():console.warn("got no doc by id:",s)}}init(){this.container.id="search-gifs-container",this.inputSearch=new j("SearchGifsTitle",e=>{this.reset(),this.search(e)}),this.title.replaceWith(this.inputSearch.container),this.gifsDiv=document.createElement("div"),this.gifsDiv.classList.add("gifs-masonry"),Object(l.b)(this.gifsDiv,this.onGifsClick,{listenerSetter:this.listenerSetter}),this.scrollable.append(this.gifsDiv),this.masonry=new jn(this.gifsDiv,"GIFS-SEARCH",this.scrollable)}onClose(){this.scrollable.onScrolledBottom=()=>{}}onCloseAfterTimeout(){return this.reset(),this.gifsDiv.innerHTML="",I.a.checkAnimations(void 0,"GIFS-SEARCH"),this.inputSearch.remove(),super.onCloseAfterTimeout()}reset(){this.searchPromise=null,this.nextOffset="",this.loadedAll=!1,this.masonry.clear()}open(){const e=super.open();return $t.toggleSidebar(!0).then(()=>{this.search("",!0),this.scrollable.onScrolledBottom=()=>{this.search(this.inputSearch.value,!1)}}),e}search(e,t=!0){return Vn(this,void 0,void 0,(function*(){if(!this.searchPromise&&!this.loadedAll){this.gifBotPeerId||(this.gifBotPeerId=(yield T.a.resolveUsername("gif")).id);try{this.searchPromise=zn.getInlineResults(0,this.gifBotPeerId,e,this.nextOffset);const{results:s,next_offset:i}=yield this.searchPromise;if(this.inputSearch.value!==e)return;this.searchPromise=null,this.nextOffset=i,t&&(this.gifsDiv.innerHTML=""),s.length?s.forEach(e=>{"botInlineMediaResult"===e._&&e.document&&this.masonry.add(e.document)}):this.loadedAll=!0,this.scrollable.onScroll()}catch(e){throw this.searchPromise=null,console.error("gifs loading error:",e),e}}}))}}class Kn extends V{init(){this.container.id="stickers-container",this.container.classList.add("chatlist-container"),this.lazyLoadQueue=new te.d,this.inputSearch=new j("StickersTab.SearchPlaceholder",e=>{this.search(e)}),this.title.replaceWith(this.inputSearch.container),this.setsDiv=document.createElement("div"),this.setsDiv.classList.add("sticker-sets"),this.scrollable.append(this.setsDiv),Object(l.b)(this.setsDiv,e=>{const t=Object(Ce.a)(e.target,"sticker-set-sticker");if(t){const e=t.dataset.docId;return void mo.chat.input.sendMessageWithDocument(e)}const s=Object(Ce.a)(e.target,"sticker-set");if(!s)return;const i=s.dataset.stickerSet,n=s.dataset.access_hash,a=Object(Ce.a)(e.target,"sticker-set-button");a?(e.preventDefault(),e.cancelBubble=!0,a.setAttribute("disabled","true"),hs.getStickerSet({id:i,access_hash:n}).then(e=>{hs.toggleStickerSet(e.set).then(t=>{t&&(a.textContent="",a.append(Object(A.i18n)(e.set.installed_date?"Stickers.SearchAdded":"Stickers.SearchAdd")),a.classList.toggle("gray",!!e.set.installed_date))}).finally(()=>{a.removeAttribute("disabled")})})):hs.getStickerSet({id:i,access_hash:n}).then(e=>{new Di(e.set).show()})},{listenerSetter:this.listenerSetter})}onCloseAfterTimeout(){return this.setsDiv.innerHTML="",I.a.checkAnimations(void 0,"STICKERS-SEARCH"),super.onCloseAfterTimeout()}renderSet(e){const t=document.createElement("div");t.classList.add("sticker-set");const s=document.createElement("div");s.classList.add("sticker-set-header");const i=document.createElement("div");i.classList.add("sticker-set-details"),i.innerHTML=`\n <div class="sticker-set-name">${Z.a.wrapEmojiText(e.title)}</div>\n `;const n=document.createElement("div");n.classList.add("sticker-set-count"),n.append(Object(A.i18n)("Stickers",[e.count])),i.append(n);const a=document.createElement("button");a.classList.add("btn-primary","btn-color-primary","sticker-set-button"),a.append(Object(A.i18n)(e.installed_date?"Stickers.SearchAdded":"Stickers.SearchAdd")),e.installed_date&&a.classList.add("gray"),s.append(i,a);const o=document.createElement("div");o.classList.add("sticker-set-stickers");const r=Math.min(5,e.count);for(let e=0;e<r;++e){const e=document.createElement("div");e.classList.add("sticker-set-sticker"),o.append(e)}hs.getStickerSet(e).then(e=>{for(let t=0;t<r;++t){const s=o.children[t],i=e.documents[t];"documentEmpty"!==i._&&Ls({doc:i,div:s,lazyLoadQueue:this.lazyLoadQueue,group:"STICKERS-SEARCH",play:!0,loop:!0,width:68,height:68})}}),t.dataset.stickerSet=e.id,t.dataset.access_hash=e.access_hash,t.dataset.title=e.title,t.append(s,o),this.setsDiv.append(t)}open(){const e=super.open();return $t.toggleSidebar(!0).then(()=>{this.renderFeatured()}),e}renderFeatured(){return hs.getFeaturedStickers().then(e=>{this.inputSearch.value||(e=this.filterRendered("",e)).forEach(e=>{this.renderSet(e.set)})})}filterRendered(e,t){t=t.slice();const s=Array.from(this.setsDiv.children);return Object(y.d)(s,s=>{const i=s.dataset.stickerSet,n=t.findIndex(e=>e.set.id===i);-1!==n?t.splice(n,1):e&&s.dataset.title.toLowerCase().includes(e.toLowerCase())||s.remove()}),I.a.checkAnimations(void 0,"STICKERS-SEARCH"),t}search(e){return e?hs.searchStickerSets(e,!1).then(t=>{this.inputSearch.value===e&&(t=this.filterRendered(e,t)).forEach(e=>{this.renderSet(e.set)})}):this.renderFeatured()}}var Gn=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class qn extends R.a{constructor(e){super(!1),this.forceClose=!1,this.inited=!1,this.onMouseOut=e=>{if(clearTimeout(this.displayTimeout),!this.isActive())return;const t=e.toElement;t&&Object(zs.a)(t,this.element)||(this.displayTimeout=window.setTimeout(()=>{this.toggle(!1)},200))},this.toggle=e=>Gn(this,void 0,void 0,(function*(){const t=!!this.element.style.display&&void 0===e||e;if(this.init){if(!t)return;this.init(),this.init=null}if(t!==this.isActive())if(this.element.style.display&&void 0===e||e){const e=this.dispatchEvent("open");yield Promise.all(e),this.element.style.display="",this.element.offsetLeft,this.element.classList.add("active"),clearTimeout(this.displayTimeout),this.displayTimeout=window.setTimeout(()=>{this.forceClose=!1,this.dispatchEvent("opened")},pe.IS_TOUCH_SUPPORTED?0:200)}else this.dispatchEvent("close"),this.element.classList.remove("active"),clearTimeout(this.displayTimeout),this.displayTimeout=window.setTimeout(()=>{this.element.style.display="none",this.forceClose=!1,this.dispatchEvent("closed")},pe.IS_TOUCH_SUPPORTED?0:200)})),Object(L.g)(this,e)}attachButtonListener(e,t){let s=!0;pe.IS_TOUCH_SUPPORTED?Object(l.b)(e,()=>{s?(s=!1,this.toggle(!0)):this.toggle()},{listenerSetter:t}):t.add(e)("mouseover",i=>{s&&(t.add(e)("mouseout",this.onMouseOut),s=!1),clearTimeout(this.displayTimeout),this.displayTimeout=window.setTimeout(()=>{this.toggle(!0)},200)})}init(){pe.IS_TOUCH_SUPPORTED||(this.element.onmouseout=this.onMouseOut,this.element.onmouseover=e=>{this.forceClose||clearTimeout(this.displayTimeout)})}isActive(){return this.element.classList.contains("active")}}var Qn=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};const $n="emoticons-dropdown";class Yn extends qn{constructor(){super({element:document.getElementById("emoji-dropdown")}),this.tabId=-1,this.onSelectTabClick=e=>{this.tabId!==e&&(I.a.checkAnimations(!0,$n),this.tabId=e,this.searchButton.classList.toggle("hide",0===this.tabId),this.deleteBtn.classList.toggle("hide",0!==this.tabId))},this.checkRights=()=>{const{peerId:e,threadId:t}=mo.chat,s=this.tabsEl.children,n=Array.from(s),a=i.a.canSendToPeer(e,t,"send_stickers");n[2].toggleAttribute("disabled",!a);const o=i.a.canSendToPeer(e,t,"send_gifs");n[3].toggleAttribute("disabled",!o);const r=this.tabsEl.querySelector(".active");!r||1===Object(Ts.a)(r)||a&&o||this.selectTab(0,!1)},this.addEventListener("open",()=>Qn(this,void 0,void 0,(function*(){pe.IS_TOUCH_SUPPORTED&&Object(Us.a)()&&(yield Object(yn.a)(100)),this.element.parentElement!==mo.chat.input.chatInput&&mo.chat.input.chatInput.append(this.element),this.savedRange=this.getGoodRange(),Yn.lazyLoadQueue.lock(),I.a.lockIntersectionGroup($n)}))),this.addEventListener("opened",()=>{I.a.unlockIntersectionGroup($n),Yn.lazyLoadQueue.unlock(),Yn.lazyLoadQueue.refresh(),this.container.classList.remove("disable-hover")}),this.addEventListener("close",()=>{Yn.lazyLoadQueue.lock(),I.a.lockIntersectionGroup($n),I.a.checkAnimations(!0,$n)}),this.addEventListener("closed",()=>{I.a.unlockIntersectionGroup($n),Yn.lazyLoadQueue.unlock(),Yn.lazyLoadQueue.refresh(),this.container.classList.remove("disable-hover"),this.savedRange=void 0})}init(){return this.emojiTab=new On,this.stickersTab=new Hn,this.gifsTab=new Dn,this.tabs={0:this.emojiTab,1:this.stickersTab,2:this.gifsTab},this.container=this.element.querySelector(".emoji-container .tabs-container"),this.tabsEl=this.element.querySelector(".emoji-tabs"),this.selectTab=Object(ee.a)(this.tabsEl,this.container,this.onSelectTabClick,()=>{const e=this.tabs[this.tabId];e.init&&e.init(),e.onCloseAfterTimeout&&e.onCloseAfterTimeout(),I.a.checkAnimations(!1,$n)}),this.searchButton=this.element.querySelector(".emoji-tabs-search"),this.searchButton.addEventListener("click",()=>{1===this.tabId?$t.isTabExists(Kn)||new Kn($t).open():$t.isTabExists(Wn)||new Wn($t).open()}),this.deleteBtn=this.element.querySelector(".emoji-tabs-delete"),this.deleteBtn.addEventListener("click",e=>{var t;const s=mo.chat.input.messageInput;(null===(t=s.lastChild)||void 0===t?void 0:t.tagName)?s.lastElementChild.remove():s.lastChild&&(s.lastChild.textContent.length?s.lastChild.textContent=s.lastChild.textContent.slice(0,-1):s.lastChild.remove());const i=new Event("input",{bubbles:!0,cancelable:!0});mo.chat.input.messageInput.dispatchEvent(i),Object(c.a)(e)}),this.tabsEl.children[1].click(),this.tabs[0].init&&this.tabs[0].init(),a.default.addEventListener("peer_changed",this.checkRights),this.checkRights(),super.init()}addLazyLoadQueueRepeat(e,t){this.addEventListener("close",()=>{e.lock()}),this.addEventListener("closed",()=>{const s=e.intersector.getVisible();for(const e of s)t(e);e.intersector.clearVisible()}),this.addEventListener("opened",()=>{e.unlockAndRefresh()})}getSavedRange(){return this.getGoodRange()||this.savedRange}getGoodRange(){const e=document.getSelection();if(e.rangeCount&&document.activeElement===mo.chat.input.messageInput)return e.getRangeAt(0)}}Yn.lazyLoadQueue=new te.d,Yn.menuOnClick=(e,t,s,i=0)=>{let n=-1;const a=t=>t!==i&&(e.children[i].classList.remove("active"),e.children[t].classList.add("active"),i=t,!0),o=new hn(t.container,(i,o)=>{if(Math.abs(n-t.container.scrollTop)<=1)return;n=-1;const r=Object(Ts.a)(o);!i&&r||(a(r),s&&(r<e.childElementCount-4?s.container.scrollLeft=47*(r-3):s.container.scrollLeft=47*r))});return e.addEventListener("click",e=>{let s=e.target;if(s=Object(Ce.a)(s,"menu-horizontal-div-item"),!s)return;const i=Object(Ts.a)(s);if(!a(i))return;const o=(t.splitUp||t.container).children[i].offsetTop+1;t.container.scrollTop=n=o}),{stickyIntersector:o,setActive:a}},Yn.onMediaClick=(e,t=!1)=>{let s=e.target;if(s=Object(mt.a)(s,"DIV"),!s)return!1;const i=s.dataset.docId;return!!i&&(mo.chat.input.sendMessageWithDocument(i,void 0,t)?(Xn.container&&(Xn.forceClose=!0,Xn.container.classList.add("disable-hover"),Xn.toggle(!1)),!0):(console.warn("got no doc by id:",i),!1))};const Xn=new Yn;de.a.emoticonsDropdown=Xn;var Jn=Xn;var Zn=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};const ea=new Set(["messageActionHistoryClear","messageActionChatCreate"]);let ta=void 0,sa=0;class ia{constructor(e,t,s,i,n,o,r,l,d,u){let p;this.chat=e,this.appMessagesManager=t,this.appStickersManager=s,this.appUsersManager=i,this.appInlineBotsManager=n,this.appPhotosManager=o,this.appPeersManager=r,this.appProfileManager=l,this.appDraftsManager=d,this.appMessagesIdsManager=u,this.peerId=0,this.unreadOut=new Set,this.needUpdate=[],this.bubbles={},this.skippedMids=new Set,this.dateMessages={},this.scrolledDown=!0,this.isScrollingTimeout=0,this.unreaded=new Map,this.unreadedSeen=new Set,this.preloader=null,this.loadedTopTimes=0,this.loadedBottomTimes=0,this.messagesQueuePromise=null,this.messagesQueue=[],this.messagesQueueOnRender=null,this.messagesQueueOnRenderAdditional=null,this.firstUnreadBubble=null,this.middleware=Object(ks.a)(),this.replyFollowHistory=[],this.isHeavyAnimationInProgress=!1,this.isFirstLoad=!0,this.passEntities={},this.viewsMids=new Set,this.onBubblesClick=e=>{var t;let s=e.target,i=null;try{i=Object(Ce.a)(s,"bubble")}catch(e){}if(!i)return;if(i.classList.contains("is-date")&&Object(Ce.a)(s,"bubble-content")){if(i.classList.contains("is-sticky")&&!this.chatInner.classList.contains("is-scrolling"))return;for(const e in this.dateMessages){if(this.dateMessages[e].div===i){new dn(new Date(+e),this.onDatePick).show();break}}return}if(!pe.IS_TOUCH_SUPPORTED&&Object(Ce.a)(s,"time"))return void this.chat.selection.toggleByElement(i);if(this.chat.selection.isSelecting&&e.isTrusted){if(i.classList.contains("service")&&void 0===i.dataset.mid)return;return Object(c.a)(e),pe.IS_TOUCH_SUPPORTED&&this.chat.selection.selectedText?void(this.chat.selection.selectedText=void 0):void this.chat.selection.toggleByElement(Object(Ce.a)(s,"grouped-item")||i)}const n=Object(Ce.a)(s,"contact");if(n)return void this.chat.appImManager.setInnerPeer(+n.dataset.peerId);if(Object(Ce.a)(s,"replies")){const e=+i.dataset.mid;if(this.peerId===gn.b){const t=this.chat.getMessage(e),s=this.appPeersManager.getPeerId(t.reply_to.reply_to_peer_id),i=t.reply_to.reply_to_top_id,n=t.fwd_from.saved_from_msg_id;this.chat.appImManager.openThread(s,n,i)}else{const t=this.appMessagesManager.filterMessages(this.chat.getMessage(e),e=>!!e.replies)[0],s=t.replies;s&&this.appMessagesManager.getDiscussionMessage(this.peerId,t.mid).then(e=>{this.chat.appImManager.setInnerPeer(-s.channel_id,void 0,"discussion",e.mid)})}return}const a=Object(Ce.a)(s,"peer-title")||Object(Ce.a)(s,"name")||Object(mt.a)(s,"AVATAR-ELEMENT");if(a){s=a||s;const t=+(s.dataset.peerId||s.getAttribute("peer")),i=s.dataset.savedFrom;if(a.classList.contains("is-via")){const s="@"+this.appUsersManager.getUser(t).username+" ";this.appDraftsManager.setDraft(this.peerId,this.chat.threadId,s),Object(c.a)(e)}else if(i){const e=i.split("_"),t=+e[0],s=+e[1];this.chat.appImManager.setInnerPeer(t,s)}else t?this.chat.appImManager.setInnerPeer(t):nt(A.default.format("HidAccount",!0));return}const o="SPAN"===s.tagName&&!s.classList.contains("emoji");if(i.classList.contains("sticker")&&s.parentElement.classList.contains("attachment")){const e=+i.dataset.mid,s=null===(t=this.chat.getMessage(e).media)||void 0===t?void 0:t.document;return void((null==s?void 0:s.stickerSetInput)&&new Di(s.stickerSetInput).show())}const r=Object(Ce.a)(s,"document-with-thumb");if("IMG"===s.tagName&&!s.classList.contains("emoji")&&!s.classList.contains("document-thumb")||s.classList.contains("album-item")||o||"VIDEO"===s.tagName&&!i.classList.contains("round")||r&&!r.querySelector(".preloader-container")){const t=+(Object(Ce.a)(s,"album-item")||Object(Ce.a)(s,"document-container")||i).dataset.mid,n=this.chat.getMessage(t);if(!n)return void this.log.warn("no message by messageId:",t);const a=r?e=>fo.isMediaCompatibleForDocumentViewer(e):e=>"photo"===e._||["video","gif"].includes(e.type),o=[],l=Object.keys(this.bubbles).map(e=>+e).filter(e=>{const t=this.chat.getMessage(e),s=this.appMessagesManager.getMediaFromMessage(t);return s&&a(s)}).sort((e,t)=>e-t);l.forEach(e=>{let t;if(r)t=".document-container";else{t=".album-item video, .album-item img, .preview video, .preview img, ",t+=this.bubbles[e].classList.contains("with-media-tail")?".bubble__media-container":".attachment video, .attachment img"}const s=Array.from(this.bubbles[e].querySelectorAll(t)),i=new Set;if(r)s.forEach(e=>{o.push({element:e.querySelector(".document-ico"),mid:+e.dataset.mid,peerId:this.peerId})});else{const t=!!this.bubbles[e].querySelector(".media-container-aspecter");s.forEach(s=>{if(t&&!Object(Ce.a)(s,"media-container-aspecter"))return;let n=Object(Ce.a)(s,"album-item");const a=n||s.parentElement;i.has(a)||(i.add(a),o.push({element:s,mid:n?+n.dataset.mid:e,peerId:this.peerId}))})}}),o.sort((e,t)=>e.mid-t.mid);let d=o.findIndex(e=>e.mid===t);return de.b&&this.log("open mediaViewer single with ids:",l,d,o),o[d]?((new fo).setSearchContext({threadId:this.chat.threadId,peerId:this.peerId,inputFilter:{_:r?"inputMessagesFilterDocument":"inputMessagesFilterPhotoVideo"},useSearch:"scheduled"!==this.chat.type,isScheduled:"scheduled"===this.chat.type}).openMedia(n,o[d].element,0,!0,o.slice(0,d),o.slice(d+1)),void Object(c.a)(e)):void this.log("no target for media viewer!",s)}if(-1===["IMG","DIV","SPAN"].indexOf(s.tagName)&&(s=Object(mt.a)(s,"DIV")),-1!==["DIV","SPAN"].indexOf(s.tagName)){if(s.classList.contains("goto-original")){const e=i.dataset.savedFrom.split("_"),t=+e[0],s=+e[1];return void this.chat.appImManager.setInnerPeer(t,s)}if(s.classList.contains("forward")){const e=+i.dataset.mid,t=this.appMessagesManager.getMessageByPeer(this.peerId,e);return void new Ds({[this.peerId]:this.appMessagesManager.getMidsByMessage(t)})}let t=!1;try{t=!!Object(Ce.a)(e.target,"reply")}catch(e){}if(t&&i.classList.contains("is-reply")){const e=+i.dataset.mid;this.replyFollowHistory.push(e);const t=this.chat.getMessage(e),s=t.reply_to.reply_to_peer_id?this.appPeersManager.getPeerId(t.reply_to.reply_to_peer_id):this.peerId,n=t.reply_to.reply_to_msg_id;this.chat.appImManager.setInnerPeer(s,n,this.chat.type,this.chat.threadId)}}},this.onScroll=()=>{this.isHeavyAnimationInProgress&&this.scrolledDown||(pe.IS_TOUCH_SUPPORTED||(this.isScrollingTimeout?clearTimeout(this.isScrollingTimeout):this.chatInner.classList.contains("is-scrolling")||this.chatInner.classList.add("is-scrolling"),this.isScrollingTimeout=window.setTimeout(()=>{this.chatInner.classList.remove("is-scrolling"),this.isScrollingTimeout=0},1350)),this.scrollable.getDistanceToEnd()<300&&this.scrollable.loadedAll.bottom?(this.bubblesContainer.classList.add("scrolled-down"),this.scrolledDown=!0):this.bubblesContainer.classList.contains("scrolled-down")&&(this.bubblesContainer.classList.remove("scrolled-down"),this.scrolledDown=!1),this.chat.topbar.pinnedMessage&&this.chat.topbar.pinnedMessage.setCorrectIndex(this.scrollable.lastScrollDirection))},this.onDatePick=e=>{const t=this.peerId;this.appMessagesManager.requestHistory(t,0,2,-1,e,this.chat.threadId).then(e=>{var s;(null===(s=null==e?void 0:e.messages)||void 0===s?void 0:s.length)?this.peerId===t&&this.chat.setMessageId(e.messages[0].mid):this.log.error("no history!")})},this.listenerSetter=new H.a,this.bubblesContainer=document.createElement("div"),this.bubblesContainer.classList.add("bubbles","scrolled-down"),this.chatInner=document.createElement("div"),this.chatInner.classList.add("bubbles-inner"),this.setScroll(),this.bubblesContainer.append(this.scrollable.container),this.log=this.chat.log,this.bubbleGroups=new cn(this.chat),this.preloader=new ye.a({cancelable:!1}),this.lazyLoadQueue=new te.d,this.lazyLoadQueue.queueId=++sa,this.listenerSetter.add(a.default)("history_update",({storage:e,peerId:t,mid:s})=>{if(this.chat.getMessagesStorage()===e){const e=this.bubbles[s];if(!e)return;const t=this.chat.getMessage(s);if(+e.dataset.timestamp>=t.date+Ye.a.serverTimeOffset-1)return;this.setBubblePosition(e,t,!1),this.scrollingToBubble&&this.scrollToBubbleEnd()}}),this.listenerSetter.add(a.default)("dialog_flush",({peerId:e})=>{this.peerId===e&&this.deleteMessagesByIds(Object.keys(this.bubbles).map(e=>+e))}),this.listenerSetter.add(a.default)("message_sent",e=>{var t,s,i,n;const{storage:o,tempId:r,tempMessage:l,mid:c}=e;if(this.chat.getMessagesStorage()!==o)return;const d=this.getMountedBubble(r,l)||this.getMountedBubble(c);if(d){const e=this.chat.getMessage(c),a=d.bubble;if(e.replies){const t=a.querySelector("replies-element");t&&(t.message=e,t.init())}if((null===(t=e.media)||void 0===t?void 0:t.document)&&!e.media.document.type){const t=a.querySelector(`.document-container[data-mid="${r}"] .document`);t&&t.replaceWith(fs({message:e}))}if(e.grouped_id){const e=a.querySelector(`.grouped-item[data-mid="${r}"]`)||a;e&&(e.dataset.mid=""+c)}if(null===(s=e.media)||void 0===s?void 0:s.poll){const t=a.querySelector("poll-element");if(t){const s=e.media.poll;t.message=e,t.setAttribute("poll-id",s.id),t.setAttribute("message-id",""+c)}}if(null===(i=e.media)||void 0===i?void 0:i.document){const t=a.querySelector(`audio-element[data-mid="${r}"], .document[data-doc-id="${r}"], .media-round[data-mid="${r}"]`);t&&(t instanceof Re||t.classList.contains("media-round")?(t.dataset.mid=""+e.mid,delete t.dataset.isOutgoing,t.message=e,t.onLoad(!0)):t.dataset.docId=e.media.document.id)}(null===(n=e.media)||void 0===n?void 0:n.webpage)&&!a.querySelector(".web")&&Object(Cs.c)().then(()=>{this.safeRenderMessage(e,!0,!1,a,!1),this.scrollToBubbleIfLast(a)})}else this.log.warn("message_sent there is no bubble",e);const h=this.bubbles;if(h[r]){const e=h[r];h[c]=e,delete h[r],Object(_e.b)(()=>{e.classList.contains("is-sending")&&(e.classList.remove("is-sending"),e.classList.add(this.peerId===a.default.myId&&"scheduled"!==this.chat.type?"is-read":"is-sent"))}),e.dataset.mid=""+c}if(this.unreadOut.has(r)&&(this.unreadOut.delete(r),this.unreadOut.add(c)),"scheduled"===this.chat.type){(Date.now()/1e3|0)>=l.date-10&&this.deleteMessagesByIds([c])}}),this.listenerSetter.add(a.default)("message_edit",({storage:e,peerId:t,mid:s})=>{if(e!==this.chat.getMessagesStorage())return;const i=this.chat.getMessage(s),n=i.grouped_id?this.getGroupedBubble(i.grouped_id):this.getMountedBubble(s);if(!n)return;const a="scheduled"===this.chat.type,o=this.scrolledDown;this.safeRenderMessage(n.message,!0,!1,n.bubble,a),o&&this.scrollToBubbleIfLast(n.bubble),a&&(this.messagesQueuePromise||Promise.resolve()).then(()=>{this.deleteEmptyDateGroups()})}),this.listenerSetter.add(a.default)("album_edit",({peerId:e,groupId:t,deletedMids:s})=>{if(e!==this.peerId)return;const i=this.appMessagesManager.getMidsByAlbum(t).concat(s).find(e=>this.bubbles[e]);if(!i)return;const n=Object(L.e)(this.appMessagesManager.groupedMessagesStorage[t],"asc").pop();this.safeRenderMessage(this.chat.getMessage(n),!0,!1,this.bubbles[i],!1)}),this.listenerSetter.add(a.default)("messages_downloaded",({peerId:e,mids:t})=>{const s=this.getMiddleware();Object(Cs.c)().then(()=>{s()&&t.forEach(t=>{Object(y.d)(this.needUpdate,(s,i)=>{if(s.replyMid===t&&s.replyToPeerId===e){const{mid:e,replyMid:t}=this.needUpdate.splice(i,1)[0],n=this.bubbles[e];if(!n)return;const a=this.chat.getMessage(e);this.appMessagesManager.getMessageByPeer(s.replyToPeerId,t).deleted&&delete a.reply_to_mid,pn.setReply({chat:this.chat,bubble:n,message:a})}})})})}),this.listenerSetter.add(this.bubblesContainer)("click",this.onBubblesClick),de.b&&this.listenerSetter.add(this.bubblesContainer)("dblclick",e=>{const t=Object(Ce.a)(e.target,"grouped-item")||Object(Ce.a)(e.target,"bubble");if(t){const e=+t.dataset.mid;this.log("debug message:",this.chat.getMessage(e)),this.highlightBubble(t)}}),h.IS_MOBILE||this.listenerSetter.add(this.bubblesContainer)("dblclick",e=>{if(this.chat.selection.isSelecting||!this.appMessagesManager.canSendToPeer(this.peerId,this.chat.threadId))return;const t=e.target,s=t.classList.contains("bubble")?t:t.classList.contains("document-selection")?t.parentElement:null;if(s&&!s.classList.contains("bubble-first")){const e=+s.dataset.mid;if(this.chat.getMessage(e).pFlags.is_outgoing)return;this.chat.input.initMessageReply(e)}}),this.stickyIntersector=new hn(this.scrollable.container,(e,t)=>{for(const s in this.dateMessages){const i=this.dateMessages[s];if(i.container===t){i.div.classList.toggle("is-sticky",e);break}}}),Object(Cs.a)(()=>{this.isHeavyAnimationInProgress=!0,this.lazyLoadQueue.lock(),p=this.getMiddleware()},()=>{this.isHeavyAnimationInProgress=!1,p&&p()&&(this.lazyLoadQueue.unlock(),this.lazyLoadQueue.refresh()),p=null},this.listenerSetter)}constructPeerHelpers(){if(this.listenerSetter.add(a.default)("history_append",({storage:e,mid:t})=>{e===this.chat.getMessagesStorage()&&(this.scrollable.loadedAll.bottom?this.renderNewMessagesByIds([t],!0):this.chat.setMessageId())}),this.listenerSetter.add(a.default)("history_multiappend",e=>{if(!(this.peerId in e))return;const t=Array.from(e[this.peerId]).slice().sort((e,t)=>t-e);this.renderNewMessagesByIds(t)}),this.listenerSetter.add(a.default)("history_delete",({peerId:e,msgs:t})=>{e===this.peerId&&this.deleteMessagesByIds(Array.from(t))}),this.listenerSetter.add(a.default)("dialog_unread",({peerId:e})=>{e===this.peerId&&(this.chat.input.setUnreadCount(),this.updateUnreadByDialog())}),this.listenerSetter.add(a.default)("dialogs_multiupdate",e=>{e[this.peerId]&&this.chat.input.setUnreadCount()}),this.listenerSetter.add(a.default)("dialog_notify_settings",e=>{this.peerId===e.peerId&&this.chat.input.setUnreadCount()}),this.listenerSetter.add(a.default)("chat_update",e=>{if(this.peerId===-e){this.chatInner.classList.contains("has-rights")!==this.appMessagesManager.canSendToPeer(this.peerId,this.chat.threadId)&&(this.finishPeerChange(),this.chat.input.updateMessageInput())}}),this.listenerSetter.add(a.default)("settings_updated",e=>{if("settings.emoji.big"===e.key){const e=this.scrollable.isScrolledDown;e||this.setMessagesQueuePromise();Object(L.e)(this.bubbles,"desc").forEach(e=>{const t=this.bubbles[e];if(t.classList.contains("can-have-big-emoji")){const s=this.chat.getMessage(e);this.safeRenderMessage(s,void 0,!1,t)}}),e?this.scrollable.scrollTop=99999:this.performHistoryResult([],!0,!1,void 0)}}),this.listenerSetter.add(a.default)("message_views",({peerId:e,views:t,mid:s})=>{this.peerId===e&&Object(_e.b)(()=>{const e=this.bubbles[s];if(!e)return;const i=Array.from(e.querySelectorAll(".post-views"));if(i.length){const e=Object(C.c)(t,1);let s=!1;i.forEach(t=>{(s||t.innerHTML!==e)&&(s=!0,t.innerHTML=e)})}})}),this.unreadedObserver=new IntersectionObserver(e=>{e.forEach(e=>{if(e.isIntersecting){const t=e.target,s=this.unreaded.get(t);this.onUnreadedInViewport(t,s)}})}),this.viewsObserver=new IntersectionObserver(e=>{e.forEach(e=>{e.isIntersecting&&(this.viewsMids.add(+e.target.dataset.mid),this.viewsObserver.unobserve(e.target),this.sendViewCountersDebounced())})}),this.sendViewCountersDebounced=ot(()=>{const e=[...this.viewsMids];this.viewsMids.clear(),this.appMessagesManager.incrementMessageViews(this.peerId,e)},1e3,!1,!0),"ResizeObserver"in window){let e=this.scrollable.container.offsetHeight,t=!1,s=!1,i=0,n=0,a=0;const o=()=>{const o=this.scrollable.container.offsetHeight,r=this.scrollable.isScrolledDown;o===e||s&&r||(n+=e-o),n&&(this.scrollable.scrollTop+=Math.round(n)),e=o,i=0,a=0,n=0,t=!1,s=!1},r=e=>{a&&window.cancelAnimationFrame(a),a=window.requestAnimationFrame(e?o:()=>{a=window.requestAnimationFrame(o)})};new ResizeObserver(a=>{if(s)return void r(!1);const o=a[0].contentRect.height;if(!e)return void(e=o);const l=e-o;let c=l+n;const d=c%1;if(c-=d,!t&&(t=!0,l<0&&this.scrollable.isScrolledDown))return n=-l,s=!0,void r(!1);if(i+=c,c){const e=this.scrollable.scrollTop+c;this.scrollable.scrollTop=e}r(!1),n=d,e=o}).observe(this.bubblesContainer)}}getRenderedLength(){return Object.keys(this.bubbles).length-this.skippedMids.size}onUnreadedInViewport(e,t){this.unreadedSeen.add(t),this.unreadedObserver.unobserve(e),this.unreaded.delete(e),this.readUnreaded()}readUnreaded(){if(this.readPromise)return;const e=this.getMiddleware();this.readPromise=a.default.idle.focusPromise.then(()=>{if(!e())return;let t=Math.max(...Array.from(this.unreadedSeen));if(this.scrollable.loadedAll.bottom){const e=Math.max(...Object.keys(this.bubbles).map(e=>+e));t>=e&&(t=Math.max(this.appMessagesManager.getHistoryStorage(this.peerId,this.chat.threadId).maxId||0,t))}this.unreaded.forEach((e,s)=>{e<=t&&this.onUnreadedInViewport(s,e)});const s=[];for(const e of this.unreadedSeen){const t=this.chat.getMessage(e);this.appMessagesManager.isMentionUnread(t)&&s.push(e)}return this.appMessagesManager.readMessages(this.peerId,s),this.unreadedSeen.clear(),de.b&&this.log("will readHistory by maxId:",t),this.appMessagesManager.readHistory(this.peerId,t,this.chat.threadId).catch(e=>{this.log.error("readHistory err:",e),this.appMessagesManager.readHistory(this.peerId,t,this.chat.threadId)}).finally(()=>{e()&&(this.readPromise=void 0,this.unreadedSeen.size&&this.readUnreaded())})})}constructPinnedHelpers(){this.listenerSetter.add(a.default)("peer_pinned_messages",e=>{const{peerId:t,mids:s,pinned:i}=e;t===this.peerId&&s&&(i||this.deleteMessagesByIds(s))})}constructScheduledHelpers(){const e=()=>{this.chat.topbar.setTitle(this.appMessagesManager.getScheduledMessagesStorage(this.peerId).size)};this.listenerSetter.add(a.default)("scheduled_new",({peerId:t,mid:s})=>{t===this.peerId&&(this.renderNewMessagesByIds([s]),e())}),this.listenerSetter.add(a.default)("scheduled_delete",({peerId:t,mids:s})=>{t===this.peerId&&(this.deleteMessagesByIds(s),e())})}onGoDownClick(){if(this.replyFollowHistory.length){Object(y.d)(this.replyFollowHistory,(e,t)=>{const s=this.bubbles[e];let i=!0;if(s){const e=s.getBoundingClientRect();i=yt.a.windowH/2>e.top}else{this.chat.getMessage(e).deleted||(i=!1)}i&&this.replyFollowHistory.splice(t,1)}),this.replyFollowHistory.sort((e,t)=>t-e);const e=this.replyFollowHistory.pop();this.chat.setMessageId(e)}else this.chat.setMessageId()}getBubbleByPoint(e){let t=vn(this.scrollable.container,e,"center");return t&&(t=Object(Ce.a)(t,"bubble")),t}getGroupedBubble(e){const t=this.appMessagesManager.groupedMessagesStorage[e];for(const[e]of t)if(this.bubbles[e]){const s=Math.max(...t.keys());return{bubble:this.bubbles[e],mid:+e,message:this.chat.getMessage(s)}}return null}getBubbleGroupedItems(e){return Array.from(e.querySelectorAll(".grouped-item"))}getMountedBubble(e,t=this.chat.getMessage(e)){if(t.grouped_id&&this.appMessagesManager.getMidsByAlbum(t.grouped_id).length>1){const s=this.getGroupedBubble(t.grouped_id);if(s)return s.bubble=s.bubble.querySelector(`.document-container[data-mid="${e}"]`)||s.bubble,s}const s=this.bubbles[e];if(s)return{bubble:s,mid:e,message:t}}findNextMountedBubbleByMsgId(e){return this.bubbles[Object(L.e)(this.bubbles).find(t=>{var s;return!(t<e)&&!!(null===(s=this.bubbles[t])||void 0===s?void 0:s.parentElement)})]}loadMoreHistory(e,t=!1){if(!this.peerId||this.chat.setPeerPromise||this.isHeavyAnimationInProgress||e&&(this.getHistoryTopPromise||this.scrollable.loadedAll.top)||!e&&(this.getHistoryBottomPromise||this.scrollable.loadedAll.bottom))return;const s=Object.keys(this.bubbles).map(e=>+e).sort((e,t)=>e-t);if(s.length)if(e)de.b&&this.log("Will load more (up) history by id:",s[0],"maxId:",s[s.length-1],t),this.getHistory(s[0],!0,void 0,void 0,t);else{const e=this.appMessagesManager.getHistoryStorage(this.peerId,this.chat.threadId);if(-1!==s.indexOf(e.maxId))return void this.setLoaded("bottom",!0);de.b&&this.log("Will load more (down) history by id:",s[s.length-1],t),this.getHistory(s[s.length-1],!1,!0,void 0,t)}}setScroll(){this.scrollable=new P.b(null,"IM",300),this.setLoaded("top",!1),this.setLoaded("bottom",!1),this.scrollable.container.append(this.chatInner),this.scrollable.onAdditionalScroll=this.onScroll,this.scrollable.onScrolledTop=()=>this.loadMoreHistory(!0),this.scrollable.onScrolledBottom=()=>this.loadMoreHistory(!1),pe.IS_TOUCH_SUPPORTED&&(this.scrollable.container.addEventListener("touchmove",()=>{this.isScrollingTimeout?clearTimeout(this.isScrollingTimeout):this.chatInner.classList.contains("is-scrolling")||this.chatInner.classList.add("is-scrolling")},{passive:!0}),this.scrollable.container.addEventListener("touchend",()=>{this.chatInner.classList.contains("is-scrolling")&&(this.isScrollingTimeout&&clearTimeout(this.isScrollingTimeout),this.isScrollingTimeout=window.setTimeout(()=>{this.chatInner.classList.remove("is-scrolling"),this.isScrollingTimeout=0},1350))},{passive:!0}))}updateUnreadByDialog(){const e=this.appMessagesManager.getHistoryStorage(this.peerId,this.chat.threadId),t=this.peerId===a.default.myId?e.readMaxId:e.readOutboxMaxId;for(const e of this.unreadOut)if(e>0&&e<=t){const t=this.bubbles[e];t&&(t.classList.remove("is-sent","is-sending"),t.classList.add("is-read")),this.unreadOut.delete(e)}}deleteMessagesByIds(e,t=!0){e.forEach(e=>{if(!(e in this.bubbles))return;const t=this.bubbles[e];delete this.bubbles[e],this.skippedMids.delete(e),this.firstUnreadBubble===t&&(this.firstUnreadBubble=null),this.bubbleGroups.removeBubble(t),this.unreadedObserver&&(this.unreadedObserver.unobserve(t),this.unreaded.delete(t)),this.viewsObserver&&(this.viewsObserver.unobserve(t),this.viewsMids.delete(e)),t.remove(),this.emptyPlaceholderMid===e&&(this.emptyPlaceholderMid=void 0)}),t&&this.chat.selection.isSelecting&&this.chat.selection.deleteSelectedMids(this.peerId,e),I.a.checkAnimations(!1,ho),this.deleteEmptyDateGroups()}renderNewMessagesByIds(e,t=this.scrolledDown){if(!this.scrollable.loadedAll.bottom)return;this.chat.threadId&&(e=e.filter(e=>{const t=this.chat.getMessage(e).reply_to;return t&&(t.reply_to_top_id||t.reply_to_msg_id)===this.chat.threadId})),e=e.filter(e=>!this.bubbles[e]),t||this.scrollingToBubble&&this.scrollingToBubble===this.getLastBubble()&&(t=!0);const s=this.performHistoryResult(e,!1,!0);t&&s.then(()=>{let t;"scheduled"===this.chat.type&&(t=this.bubbles[Math.max(...e)]),this.scrollToBubbleEnd(t)})}getLastBubble(){const e=this.getLastDateGroup();if(e)return e.lastElementChild}scrollToBubble(e,t,s,i){const n=Object(Ce.a)(e,"bubble");if("center"===t&&Object(Ts.a)(n)===(this.stickyIntersector?2:1)){const s=n.parentElement;0===Object(Ts.a)(s)&&(e=s,t="start")}return this.scrollable.scrollIntoViewNew(e,t,4,void 0,s,i)}scrollToBubbleEnd(e=this.getLastBubble()){if(e){this.scrollingToBubble=e;const t=this.getMiddleware();this.scrollToBubble(e,"end").then(()=>{t()&&(this.scrollingToBubble=void 0)})}}getLastDateGroup(){let e,t=0;for(const s in this.dateMessages){const i=this.dateMessages[s];i.firstTimestamp>t&&(e=i.container,t=i.firstTimestamp)}return e}scrollToBubbleIfLast(e){e.parentElement.lastElementChild===e&&this.getLastDateGroup().parentElement.lastElementChild===e.parentElement&&this.scrollToBubbleEnd(e)}highlightBubble(e){const t="highlightTimeout";e.dataset[t]&&(clearTimeout(+e.dataset[t]),e.classList.remove("is-highlighted"),e.offsetWidth),e.classList.add("is-highlighted"),e.dataset[t]=""+setTimeout(()=>{e.classList.remove("is-highlighted"),delete e.dataset[t]},2e3)}getDateContainerByMessage(e,t){const s=new Date(1e3*e.date);s.setHours(0,0,0);const i=s.getTime();if(!this.dateMessages[i]){let t;const n=new Date;n.setHours(0,0,0,0);const a="scheduled"===this.chat.type;if(n.getTime()===s.getTime())t=Object(A.i18n)(a?"Chat.Date.ScheduledForToday":"Date.Today");else if(a&&2147483646===e.date)t=Object(A.i18n)("MessageScheduledUntilOnline");else{const e={day:"numeric",month:"long"};s.getFullYear()!==n.getFullYear()&&(e.year="numeric"),t=new A.default.IntlDateElement({date:s,options:e}).element,a&&(t=Object(A.i18n)("Chat.Date.ScheduledFor",[t]))}const o=document.createElement("div");o.className="bubble service is-date";const r=document.createElement("div");r.classList.add("bubble-content");const l=document.createElement("div");l.classList.add("service-msg"),l.append(t),r.append(l),o.append(r);const c=document.createElement("div");c.className="bubbles-date-group",c.append(o),this.dateMessages[i]={div:o,container:c,firstTimestamp:s.getTime()};const d=Object(L.e)(this.dateMessages,"asc");let h,u=0,p=d.length;for(;u<d.length;++u){const e=d[u];if(h=this.dateMessages[e].container,i<e)break}u===p&&h&&(h=h.nextElementSibling),h?this.chatInner.insertBefore(c,h):this.chatInner.append(c),this.stickyIntersector&&this.stickyIntersector.observeStickyHeaderChanges(c)}return this.dateMessages[i]}destroy(){this.scrollable.onScrolledTop=this.scrollable.onScrolledBottom=this.scrollable.onAdditionalScroll=null,this.listenerSetter.removeAll(),this.lazyLoadQueue.clear(),this.unreadedObserver&&this.unreadedObserver.disconnect(),this.viewsObserver&&this.viewsObserver.disconnect(),this.stickyIntersector&&this.stickyIntersector.disconnect(),delete this.lazyLoadQueue,this.unreadedObserver&&delete this.unreadedObserver,this.viewsObserver&&delete this.viewsObserver,this.stickyIntersector&&delete this.stickyIntersector}cleanup(e=!1){this.setLoaded("top",!1),this.setLoaded("bottom",!1),Object(as.b)(this.scrollable.container),Object(Cs.d)(),void 0!==ta&&(ta=void 0),this.bubbles={},this.skippedMids.clear(),this.dateMessages={},this.bubbleGroups.cleanup(),this.unreadOut.clear(),this.needUpdate.length=0,this.lazyLoadQueue.clear(),e&&(this.scrollable.container.textContent=""),this.firstUnreadBubble=null,this.attachedUnreadBubble=!1,this.messagesQueue.length=0,this.messagesQueuePromise=null,this.getHistoryTopPromise=this.getHistoryBottomPromise=void 0,this.fetchNewPromise=void 0,this.stickyIntersector&&this.stickyIntersector.disconnect(),this.unreadedObserver&&(this.unreadedObserver.disconnect(),this.unreaded.clear(),this.unreadedSeen.clear(),this.readPromise=void 0),this.viewsObserver&&(this.viewsObserver.disconnect(),this.viewsMids.clear()),this.loadedTopTimes=this.loadedBottomTimes=0,this.middleware.clean(),this.onAnimateLadder=void 0,this.resolveLadderAnimation=void 0,this.emptyPlaceholderMid=void 0,this.scrollingToBubble=void 0}setPeer(e,t){var s;if(!e)return this.cleanup(!0),this.peerId=0,null;const i=this.peerId===e;this.historyStorage=this.appMessagesManager.getHistoryStorage(e,this.chat.threadId);let n="pinned"===this.chat.type?this.appMessagesManager.pinnedMessages[e].maxId:null!==(s=this.historyStorage.maxId)&&void 0!==s?s:0;const a=void 0!==t;let o,r=0;a||(i||(o=this.chat.appImManager.getChatSavedPosition(this.chat)),o||n&&(r=this.appMessagesManager.getReadMaxIdIfUnread(e,this.chat.threadId),t=r&&!i?r:n));const l=t!==n;if(i){const e=this.getMountedBubble(t);if(e)return a?(this.scrollToBubble(e.bubble,"center"),this.highlightBubble(e.bubble),this.chat.dispatchEvent("setPeer",t,!1)):n&&!l&&(this.scrollable.scrollTop=this.scrollable.scrollHeight,this.chat.dispatchEvent("setPeer",t,!0)),null}else this.peerId&&(this.lazyLoadQueue.queueId=++sa,this.chat.apiManager.setQueueId(this.chat.bubbles.lazyLoadQueue.queueId)),this.peerId=e,this.replyFollowHistory.length=0,this.passEntities={messageEntityBotCommand:this.appPeersManager.isAnyGroup(this.peerId)||this.appUsersManager.isBot(this.peerId)};de.b&&this.log("setPeer peerId:",this.peerId,this.historyStorage,t,n);const c=l||"scheduled"===this.chat.type?0:n;let d=0;if(i){let e=this.getBubbleByPoint("bottom");e&&(d=+e.dataset.mid),d<=0&&(d=Math.max(...Object.keys(this.bubbles).map(e=>+e)))}else this.isFirstLoad=!0;const h=this.chatInner;let u;this.cleanup(),this.chatInner=document.createElement("div"),i?(this.chatInner.className=h.className,this.chatInner.classList.remove("disable-hover","is-scrolling")):this.chatInner.classList.add("bubbles-inner"),this.lazyLoadQueue.lock(),u=o?{promise:Object(Cs.c)().then(()=>this.performHistoryResult(o.mids,!0,!1,void 0)),cached:!0}:this.getHistory(t,!0,l,c);const{promise:p,cached:m}=u;m||i||(this.scrollable.container.textContent="",this.chat.finishPeerChange(a,l,t),this.preloader.attach(this.bubblesContainer)),I.a.lockGroup(ho);const g=p.then(()=>{if(m?i||this.chat.finishPeerChange(a,l,t):this.preloader.detach(),this.resolveLadderAnimation&&(this.resolveLadderAnimation(),this.resolveLadderAnimation=void 0),this.scrollable.lastScrollDirection=0,this.scrollable.lastScrollTop=0,Object(x.a)(this.scrollable.container,this.chatInner),I.a.unlockGroup(ho),I.a.checkAnimations(!1,ho),this.lazyLoadQueue.unlock(),o)this.scrollable.scrollTop=o.top;else if(n&&l||a){const e=d>0&&(d<t||t<0),s=r===t&&!a;!e&&i?this.scrollable.scrollTop=99999:e&&(this.scrollable.scrollTop=0);const n=this.getMountedBubble(t);let o=s&&this.firstUnreadBubble||(null==n?void 0:n.bubble);(null==o?void 0:o.parentElement)||(o=this.findNextMountedBubbleByMsgId(t)),o&&(this.scrollToBubble(o,s?"start":"center",i?void 0:bt.a.Static),s||this.highlightBubble(o))}else this.scrollable.scrollTop=99999;this.onScroll();const s=this.getMiddleware(),c=Promise.all([g,Object(Cs.c)()]);c.then(()=>{this.scrollable.checkForTriggers()}),this.chat.dispatchEvent("setPeer",t,!l);const h=this.appMessagesManager.isFetchIntervalNeeded(e);if(o||h?c.then(()=>{if(s()&&(this.scrollable.checkForTriggers(),h)){const t=()=>{this.fetchNewPromise=new Promise(i=>{s()&&this.appMessagesManager.isFetchIntervalNeeded(e)?this.appMessagesManager.getNewHistory(e,this.chat.threadId).then(e=>{if(!s()||!e)return void i();const n=e.history.slice.isEnd(bn.a.Bottom);this.scrollable.loadedAll.bottom&&this.scrollable.loadedAll.bottom!==n&&(this.setLoaded("bottom",n),this.onScroll()),setTimeout(t,3e4),i()}):i()}).finally(()=>{this.fetchNewPromise=void 0})};i?setTimeout(t,3e4):t()}}):t&&!this.bubbles[n]&&t!==n||this.setLoaded("bottom",!0),this.log("scrolledAllDown:",this.scrollable.loadedAll.bottom),this.scrollable.loadedAll.bottom&&n&&!this.unreaded.size&&this.onScrolledAllDown(),"chat"===this.chat.type){const t=this.appMessagesManager.getDialogOnly(e);(null==t?void 0:t.pFlags.unread_mark)&&this.appMessagesManager.markDialogUnread(e,!0)}}).catch(e=>{throw this.log.error("getHistory promise error:",e),this.preloader.detach(),e});return{cached:m,promise:g}}onScrolledAllDown(){if("chat"===this.chat.type||"discussion"===this.chat.type){const e=this.appMessagesManager.getHistoryStorage(this.peerId,this.chat.threadId);this.appMessagesManager.readHistory(this.peerId,e.maxId,this.chat.threadId,!0)}}finishPeerChange(){const e=this.peerId,t=this.appPeersManager.isChannel(e),s=this.appMessagesManager.canSendToPeer(e,this.chat.threadId);this.chatInner.classList.toggle("has-rights",s),this.bubblesContainer.classList.toggle("is-chat-input-hidden",!s),this.chatInner.classList.toggle("is-chat",this.chat.isAnyGroup()),this.chatInner.classList.toggle("is-channel",t)}renderMessagesQueue(e,t,s,i){this.messagesQueue.push({message:e,bubble:t,reverse:s,promises:i}),this.setMessagesQueuePromise()}setMessagesQueuePromise(){!this.messagesQueuePromise&&this.messagesQueue.length&&(this.messagesQueuePromise=new Promise((e,t)=>{setTimeout(()=>{const s=this.messagesQueue.slice();this.messagesQueue.length=0;const i=s.reduce((e,{promises:t})=>e.concat(t),[]);this.log("promises to call",i,s,this.isHeavyAnimationInProgress);const n=this.getMiddleware();Promise.all(i).then(()=>{if(!n())throw"setMessagesQueuePromise: peer changed!";this.messagesQueueOnRender&&this.messagesQueueOnRender(),this.messagesQueueOnRenderAdditional&&this.messagesQueueOnRenderAdditional(),s.forEach(({message:e,bubble:t,reverse:s})=>{this.setBubblePosition(t,e,s)}),e(),this.messagesQueuePromise=null,this.messagesQueue.length&&this.setMessagesQueuePromise(),this.setUnreadDelimiter()}).catch(t)},0)}))}setBubblePosition(e,t,s){if(t.id<0)return void this.chatInner.prepend(e);const i=this.getDateContainerByMessage(t,s);if("scheduled"===this.chat.type||"pinned"===this.chat.type){const s=this.stickyIntersector?2:1;let n=Array.from(i.container.children).slice(s),a=0,o=0;for(;a<n.length;++a){const e=n[a],s=+e.dataset.timestamp;if(t.date<s)break;if(t.date===s&&(o=+e.dataset.mid),o&&t.mid<o)break}let r=s+a;Ps(e,i.container,r)}else s?i.container.insertBefore(e,i.container.children[this.stickyIntersector?1:0].nextSibling):i.container.append(e);"message"===t._?this.bubbleGroups.addBubble(e,t,s):e.classList.add("is-group-first","is-group-last")}getMiddleware(){return this.middleware.get()}renderMessage(e,t=!1,s=!1,i=null,n=!0){var o;if(!i&&this.bubbles[e.mid])return;const r="pinned"!==this.chat.type;if(e.deleted)return;if(e.grouped_id&&r){const t=this.appMessagesManager.groupedMessagesStorage[e.grouped_id],s=Math.max(...t.keys());if(e.mid<s)return}const d=this.peerId,u=e.fromId===a.default.myId||e.pFlags.out&&this.appPeersManager.isMegagroup(this.peerId),p=document.createElement("div");let m,g;if(p.classList.add("message"),i){const t=["is-highlighted","is-group-first","is-group-last"],s=i.className.split(" "),n=["bubble"].concat(t.filter(e=>s.includes(e)));i.className=n.join(" "),g=i.lastElementChild,m=g.firstElementChild,m.innerHTML="",m.style.cssText="",g.innerHTML="",g.appendChild(m);const a=g.style.transitionDelay;g.style.cssText="",g.style.transitionDelay=a,i===this.firstUnreadBubble&&i.classList.add("is-first-unread");const o=+i.dataset.mid;+e.mid===o||(delete this.bubbles[o],this.skippedMids.delete(o))}else if(g=document.createElement("div"),g.classList.add("bubble-content-wrapper"),m=document.createElement("div"),m.classList.add("bubble-content"),(i=document.createElement("div")).classList.add("bubble"),g.appendChild(m),i.appendChild(g),!u&&!e.pFlags.out&&this.unreadedObserver){(e.pFlags.unread||this.appMessagesManager.isMentionUnread(e)||void 0!==this.historyStorage.readMaxId&&this.historyStorage.readMaxId<e.mid)&&(this.unreadedObserver.observe(i),this.unreaded.set(i,e.mid))}this.bubbles[+e.mid]=i,i.dataset.mid=e.mid,i.dataset.peerId=""+e.peerId,i.dataset.timestamp=e.date;const f=[];if("messageService"===e._){Object(ji.a)(e);const s=e.action;if(s){const t=s._;if(ea.has(t)||A.langPack.hasOwnProperty(t)&&!A.langPack[t])return this.skippedMids.add(+e.mid),i}i.className="bubble service",m.innerHTML="";const a=document.createElement("div");return a.classList.add("service-msg"),s&&("messageActionChannelMigrateFrom"===s._?a.append(Object(A.i18n)("ChatMigration.From",[new ft.a({peerId:-s.chat_id}).element])):"messageActionChatMigrateTo"===s._?a.append(Object(A.i18n)("ChatMigration.To",[new ft.a({peerId:-s.channel_id}).element])):a.append(this.appMessagesManager.wrapMessageActionTextNew(e))),m.append(a),n&&(this.renderMessagesQueue(e,i,t,f),e.pFlags.is_single&&i.classList.add("is-group-last")),i}let y,w,L=e.media;if((null==L?void 0:L.document)&&!["video","gif"].includes(L.document.type));else if(e.grouped_id&&r){const t=this.appMessagesManager.getAlbumText(e.grouped_id);y=t.message,w=t.totalEntities}else"sticker"!==(null===(o=null==L?void 0:L.document)||void 0===o?void 0:o.type)&&(y=e.message,w=e.totalEntities);let S=Z.b.wrapRichText(y,{entities:w,passEntities:this.passEntities}),E=!0,M=!1,I=!0;if(w&&!L){let e=w.filter(e=>"messageEntityEmoji"===e._),t=y.length;if(e.reduce((e,t)=>e+t.length,0)===t&&e.length<=3){if(a.default.settings.emoji.big){let t=this.appStickersManager.getAnimatedEmojiSticker(y);if(1===e.length&&!L&&t)L={_:"messageMediaDocument",document:t};else{let t=document.createElement("div");t.classList.add("attachment"),t.innerHTML=S,i.classList.add("emoji-"+e.length+"x"),m.append(t)}i.classList.add("is-message-empty","emoji-big"),M=!0,E=!1,I=!1}i.classList.add("can-have-big-emoji")}}I&&b(p,S);const C=pn.setTime(this.chat,e,i,m,p);if(m.prepend(p),e.views&&!e.pFlags.is_outgoing&&this.viewsObserver&&this.viewsObserver.observe(i),e.reply_markup&&"replyInlineMarkup"===e.reply_markup._&&e.reply_markup.rows&&e.reply_markup.rows.length){const t=e.reply_markup.rows,s=document.createElement("div");s.classList.add("reply-markup"),t.forEach(t=>{const i=t.buttons;if(!i||!i.length)return;const n=document.createElement("div");n.classList.add("reply-markup-row"),i.forEach(t=>{const s=Z.b.wrapRichText(t.text,{noLinks:!0,noLinebreaks:!0});let i;switch(t._){case"keyboardButtonUrl":{const e=Z.b.wrapRichText(" ",{entities:[{_:"messageEntityTextUrl",length:1,offset:0,url:t.url}]});i=Object(Rs.a)(e).firstElementChild,i.classList.add("is-link","tgico");break}case"keyboardButtonSwitchInline":{i=document.createElement("button"),i.classList.add("is-switch-inline");const s=document.createElement("i");s.classList.add("forward-icon"),s.innerHTML='<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24">\n <defs>\n <path d="M13.55 3.24L13.64 3.25L13.73 3.27L13.81 3.29L13.9 3.32L13.98 3.35L14.06 3.39L14.14 3.43L14.22 3.48L14.29 3.53L14.36 3.59L14.43 3.64L22.23 10.85L22.36 10.99L22.48 11.15L22.57 11.31L22.64 11.48L22.69 11.66L22.72 11.85L22.73 12.04L22.71 12.22L22.67 12.41L22.61 12.59L22.53 12.76L22.42 12.93L22.29 13.09L22.23 13.15L14.43 20.36L14.28 20.48L14.12 20.58L13.95 20.66L13.77 20.72L13.58 20.76L13.4 20.77L13.22 20.76L13.03 20.73L12.85 20.68L12.68 20.61L12.52 20.52L12.36 20.4L12.22 20.27L12.16 20.2L12.1 20.13L12.05 20.05L12.01 19.98L11.96 19.9L11.93 19.82L11.89 19.73L11.87 19.65L11.84 19.56L11.83 19.47L11.81 19.39L11.81 19.3L11.8 19.2L11.8 16.42L11 16.49L10.23 16.58L9.51 16.71L8.82 16.88L8.18 17.09L7.57 17.33L7.01 17.6L6.48 17.91L5.99 18.26L5.55 18.64L5.14 19.05L4.77 19.51L4.43 19.99L4.29 20.23L4.21 20.35L4.11 20.47L4 20.57L3.88 20.65L3.75 20.72L3.62 20.78L3.48 20.82L3.33 20.84L3.19 20.84L3.04 20.83L2.9 20.79L2.75 20.74L2.62 20.68L2.53 20.62L2.45 20.56L2.38 20.5L2.31 20.43L2.25 20.36L2.2 20.28L2.15 20.19L2.11 20.11L2.07 20.02L2.04 19.92L2.02 19.83L2.01 19.73L2 19.63L2.04 17.99L2.19 16.46L2.46 15.05L2.85 13.75L3.35 12.58L3.97 11.53L4.7 10.6L5.55 9.8L6.51 9.12L7.59 8.56L8.77 8.13L10.07 7.83L11.48 7.65L11.8 7.63L11.8 4.8L11.91 4.56L12.02 4.35L12.14 4.16L12.25 3.98L12.37 3.82L12.48 3.68L12.61 3.56L12.73 3.46L12.85 3.38L12.98 3.31L13.11 3.27L13.24 3.24L13.37 3.23L13.46 3.23L13.55 3.24Z" id="b13RmHDQtl"></path>\n </defs>\n <use xlink:href="#b13RmHDQtl" opacity="1" fill="#fff" fill-opacity="1"></use>\n </svg>',i.append(s),Object(l.b)(i,s=>{Object(c.a)(s);const i=e.viaBotId||e.fromId;let n;n=t.pFlags.same_peer?Promise.resolve(this.peerId):this.appInlineBotsManager.checkSwitchReturn(i).then(e=>e||new Promise((e,t)=>{new Ds({[this.peerId]:[]},t=>{e(t)},()=>{t()},!0)})),n.then(e=>{const s=this.peerId===e?this.chat.threadId:void 0;this.appInlineBotsManager.switchInlineQuery(e,s,i,t.query)})});break}default:i=document.createElement("button")}i.classList.add("reply-markup-button","rp"),i.insertAdjacentHTML("beforeend",s),Object(ie.ripple)(i),n.append(i)}),s.append(n)}),Object(l.b)(s,s=>{let i=s.target;if(i.classList.contains("reply-markup-button")||(i=Object(Ce.a)(i,"reply-markup-button")),!i||i.classList.contains("is-link")||i.classList.contains("is-switch-inline"))return;Object(c.a)(s);const n=Object(Ts.a)(i),a=t[Object(Ts.a)(i.parentElement)];if(!a.buttons||!a.buttons[n])return void this.log.warn("no such button",a,n,e);const o=a.buttons[n];this.appInlineBotsManager.callbackButtonClick(this.peerId,e.mid,o)}),E=!1,i.classList.add("with-reply-markup"),g.append(s)}const k=e.pFlags.is_outgoing;if(u){(e.pFlags.unread||k)&&this.unreadOut.add(e.mid);let t="";t=k?"is-sending":e.pFlags.unread?"is-sent":"is-read",i.classList.add(t)}const T=this.appMessagesManager.getMessageWithReplies(e),P=!!T&&e.mid>0;P&&i.classList.add("with-replies");const x=u&&(!e.fwd_from||this.peerId!==a.default.myId);let O=m;if(L){let t=document.createElement("div");t.classList.add("attachment"),y||i.classList.add("is-message-empty");let s=!1;switch(L._){case"messageMediaPhoto":{const s=L.photo;y||(E=!1),e.viaBotId||i.classList.add("hide-name"),i.classList.add("photo");const n=this.appMessagesManager.groupedMessagesStorage[e.grouped_id];if(e.grouped_id&&1!==n.size&&r){i.classList.add("is-album","is-grouped"),Is({groupId:e.grouped_id,attachmentDiv:t,middleware:this.getMiddleware(),isOut:u,lazyLoadQueue:this.lazyLoadQueue,chat:this.chat,loadPromises:f,noAutoDownload:this.chat.noAutoDownloadMedia});break}const a=!h.IS_ANDROID&&E&&!P&&!1;a&&i.classList.add("with-media-tail"),ys({photo:s,message:e,container:t,withTail:a,isOut:x,lazyLoadQueue:this.lazyLoadQueue,middleware:this.getMiddleware(),loadPromises:f,noAutoDownload:this.chat.noAutoDownloadMedia});break}case"messageMediaWebPage":{s=!0;let t=L.webpage;if("webPage"!==t._)break;i.classList.add("webpage");let n=document.createElement("div");n.classList.add("web");let a,o,r=document.createElement("div");r.classList.add("quote");const l=t.photo;(l||t.document)&&(a=document.createElement("div"),a.classList.add("preview-resizer"),o=document.createElement("div"),o.classList.add("preview"),a.append(o));const c=t.document;if(c)if("gif"===c.type||"video"===c.type)i.classList.add("video"),vs({doc:c,container:o,message:e,boxWidth:v.b.active.webpage.width,boxHeight:v.b.active.webpage.height,lazyLoadQueue:this.lazyLoadQueue,middleware:this.getMiddleware(),isOut:x,group:ho,loadPromises:f,noAutoDownload:this.chat.noAutoDownloadMedia});else{const t=fs({message:e,noAutoDownload:this.chat.noAutoDownloadMedia,lazyLoadQueue:this.lazyLoadQueue,loadPromises:f});o.append(t),o.classList.add("preview-with-document")}let d,h=document.createElement("div");if(h.classList.add("quote-text"),a&&h.append(a),t.site_name){const e=Z.b.wrapRichText(t.url),s=Object(Rs.a)(e).firstElementChild;s.classList.add("webpage-name"),b(s,Z.b.wrapEmojiText(t.site_name)),h.append(s),d=s}if(t.rTitle){let e=document.createElement("div");e.classList.add("title"),b(e,t.rTitle),h.append(e),d=e}if(t.rDescription){let e=document.createElement("div");e.classList.add("text"),b(e,t.rDescription),h.append(e),d=e}if(r.append(h),l&&!c){i.classList.add("photo");const t=l.sizes[l.sizes.length-1];let s=!1;t.w===t.h&&d?(i.classList.add("is-square-photo"),s=!0,this.appPhotosManager.setAttachmentSize(l,o,48,48,!1)):t.h>t.w&&i.classList.add("is-vertical-photo"),ys({photo:l,message:e,container:o,boxWidth:s?0:v.b.active.webpage.width,boxHeight:s?0:v.b.active.webpage.height,isOut:x,lazyLoadQueue:this.lazyLoadQueue,middleware:this.getMiddleware(),loadPromises:f,withoutPreloader:s,noAutoDownload:this.chat.noAutoDownloadMedia})}n.append(r),p.insertBefore(n,C);break}case"messageMediaDocument":{const n=L.document;if(n.sticker){i.classList.add("sticker"),E=!1,M=!0,n.animated&&i.classList.add("sticker-animated");const e=v.b.active,s=i.classList.contains("emoji-big")?e.emojiSticker:n.animated?e.animatedSticker:e.staticSticker;this.appPhotosManager.setAttachmentSize(n,t,s.width,s.height),m.style.height=t.style.height,m.style.width=t.style.width,Ls({doc:n,div:t,middleware:this.getMiddleware(),lazyLoadQueue:this.lazyLoadQueue,group:ho,play:!0,loop:!0,emoji:i.classList.contains("emoji-big")?y:void 0,withThumb:!0,loadPromises:f})}else if("video"===n.type||"gif"===n.type||"round"===n.type){const s="round"===n.type;s&&(M=!0),!s&&y||(E=!1),e.viaBotId||i.classList.add("hide-name"),i.classList.add(s?"round":"video");const a=this.appMessagesManager.groupedMessagesStorage[e.grouped_id];if(e.grouped_id&&1!==a.size&&r)i.classList.add("is-album","is-grouped"),Is({groupId:e.grouped_id,attachmentDiv:t,middleware:this.getMiddleware(),isOut:u,lazyLoadQueue:this.lazyLoadQueue,chat:this.chat,loadPromises:f,noAutoDownload:this.chat.noAutoDownloadMedia});else{const a=!h.IS_ANDROID&&!h.IS_APPLE&&!s&&E&&!P&&!1;a&&i.classList.add("with-media-tail"),vs({doc:n,container:t,message:e,boxWidth:v.b.active.regular.width,boxHeight:v.b.active.regular.height,withTail:a,isOut:x,lazyLoadQueue:this.lazyLoadQueue,middleware:this.getMiddleware(),group:ho,loadPromises:f,noAutoDownload:this.chat.noAutoDownloadMedia,searchContext:s?{peerId:this.peerId,inputFilter:{_:"inputMessagesFilterRoundVoice"},threadId:this.chat.threadId,useSearch:!e.pFlags.is_scheduled,isScheduled:e.pFlags.is_scheduled}:void 0})}}else{const t=function({albumMustBeRenderedFull:e,message:t,bubble:s,messageDiv:i,chat:n,loadPromises:a,noAutoDownload:o,lazyLoadQueue:r,searchContext:l,useSearch:c}){let d;const h=e?n.getMidsByMid(t.mid):[t.mid];return h.forEach((e,t)=>{const s=n.getMessage(e),c=fs({message:s,loadPromises:a,noAutoDownload:o,lazyLoadQueue:r,searchContext:l}),u=document.createElement("div");u.classList.add("document-container"),u.dataset.mid=""+e,u.dataset.peerId=""+s.peerId;const p=document.createElement("div");if(p.classList.add("document-wrapper"),s.message){const e=document.createElement("div");e.classList.add("document-message");const t=Z.b.wrapRichText(s.message,{entities:s.totalEntities});e.innerHTML=t,p.append(e)}if(h.length>1){const e=document.createElement("div");e.classList.add("document-selection"),u.append(e),u.classList.add("grouped-item"),0===t&&(d=p)}p.append(c),u.append(p),i.append(u)}),h.length>1&&s.classList.add("is-multiple-documents","is-grouped"),d}({albumMustBeRenderedFull:r,message:e,bubble:i,messageDiv:p,chat:this.chat,loadPromises:f,noAutoDownload:this.chat.noAutoDownloadMedia,lazyLoadQueue:this.lazyLoadQueue,searchContext:"voice"===n.type||"audio"===n.type?{peerId:this.peerId,inputFilter:{_:"voice"===n.type?"inputMessagesFilterRoundVoice":"inputMessagesFilterMusic"},threadId:this.chat.threadId,useSearch:!e.pFlags.is_scheduled,isScheduled:e.pFlags.is_scheduled}:void 0});t&&(O=t);const a=p.lastElementChild.querySelector(".document-message, .document-size, .audio");a&&a.append(C.cloneNode(!0)),i.classList.remove("is-message-empty"),p.classList.add((["photo","pdf"].includes(n.type)?"document":n.type||"document")+"-message"),s=!0}break}case"messageMediaContact":{const t=document.createElement("div");t.classList.add("contact"),t.dataset.peerId=""+L.user_id,p.classList.add("contact-message"),s=!0;const n=[];e.media.first_name&&n.push(Z.b.wrapEmojiText(e.media.first_name)),e.media.last_name&&n.push(Z.b.wrapEmojiText(e.media.last_name)),t.innerHTML=`\n <div class="contact-details">\n <div class="contact-name">${n.join(" ")}</div>\n <div class="contact-number">${e.media.phone_number?"+"+Object(Fs.a)(e.media.phone_number).formatted:"Unknown phone number"}</div>\n </div>`;const a=new ko;a.lazyLoadQueue=this.lazyLoadQueue,a.setAttribute("peer",""+e.media.user_id),a.classList.add("contact-avatar","avatar-54"),t.prepend(a),i.classList.remove("is-message-empty"),p.classList.add("contact-message"),p.append(t);break}case"messageMediaPoll":{i.classList.remove("is-message-empty");const t=function(e){const t=new ns;return t.message=e,t.setAttribute("peer-id",""+e.peerId),t.setAttribute("poll-id",e.media.poll.id),t.setAttribute("message-id",""+e.mid),t.render(),t}(e);p.prepend(t),p.classList.add("poll-message");break}default:i.classList.remove("is-message-empty"),p.innerHTML='<i class="media-not-supported">This message is currently not supported on Telegram Web. Try <a href="https://desktop.telegram.org/" target="_blank">desktop.telegram.org</a></i>',p.append(C),this.log.warn("unrecognized media type:",e.media._,e)}s||m.append(t)}M&&i.classList.add("just-media"),this.chat.selection.isSelecting&&this.chat.selection.toggleElementCheckbox(i,!0);let _="";const F=e.fromId!==a.default.myId&&d<0&&!this.appPeersManager.isBroadcast(d)||e.viaBotId;if(F||e.fwd_from||e.reply_to_mid){let t;const s=e.from_id&&"peerChannel"===e.from_id._&&e.fromId===e.fwdFromId;let n=e.fwd_from&&!e.fwd_from.from_id&&!e.fwd_from.channel_id;if(e.viaBotId?(t=document.createElement("span"),t.innerText="@"+this.appUsersManager.getUser(e.viaBotId).username,t.classList.add("peer-title")):n?(t=document.createElement("span"),t.innerHTML=Z.b.wrapEmojiText(e.fwd_from.from_name),t.classList.add("peer-title"),i.classList.add("hidden-profile")):t=new ft.a({peerId:e.viaBotId||e.fwdFromId||e.fromId}).element,e.viaBotId){let s=document.createElement("div");s.classList.add("name","is-via"),s.dataset.peerId=e.viaBotId,s.append(Object(A.i18n)("ViaBot")," ",t),O.append(s)}else if(e.fwdFromId||e.fwd_from){this.peerId===a.default.myId||s||i.classList.add("forwarded"),e.savedFrom&&(_=e.savedFrom);let n=document.createElement("div");if(n.classList.add("name"),n.dataset.peerId=e.fwdFromId,this.peerId!==a.default.myId&&this.peerId!==gn.b&&!s||M){if(M){const e=document.createDocumentFragment();e.append(document.createElement("br")),e.append(t),t=e}n.append(Object(A.i18n)("ForwardedFrom",[t])),_&&(n.dataset.savedFrom=_)}else n.style.color=this.appPeersManager.getPeerColorById(e.fwdFromId,!1),n.append(t);O.append(n)}else if(!M&&F){let s=document.createElement("div");s.classList.add("name"),s.append(t),u||(s.style.color=this.appPeersManager.getPeerColorById(e.fromId,!1)),s.dataset.peerId=e.fromId,O.append(s)}else i.classList.add("hide-name");e.reply_to_mid&&e.reply_to_mid!==this.chat.threadId&&pn.setReply({chat:this.chat,bubble:i,bubbleContainer:m,message:e});if(this.chat.isAnyGroup()&&!x){let t=new ko;t.lazyLoadQueue=this.lazyLoadQueue,t.classList.add("user-avatar","avatar-40"),t.loadPromises=f,!e.fwdFromId&&e.fwd_from&&e.fwd_from.from_name&&t.setAttribute("peer-title",e.fwd_from.from_name),t.setAttribute("peer",""+((e.fwd_from&&(this.peerId===a.default.myId||this.peerId===gn.b)||s?e.fwdFromId:e.fromId)||0)),g.append(t)}}else i.classList.add("hide-name");"pinned"===this.chat.type&&(_=`${this.chat.peerId}_${e.mid}`);if(T&&T.mid===this.chat.threadId&&i.classList.add("is-thread-starter","is-group-last"),_&&("pinned"===this.chat.type||e.fwd_from.saved_from_msg_id)&&this.peerId!==gn.b){const e=document.createElement("div");e.classList.add("bubble-beside-button","goto-original","tgico-arrow_next"),m.append(e),i.dataset.savedFrom=_,i.classList.add("with-beside-button")}if(i.classList.add(x?"is-out":"is-in"),n&&this.renderMessagesQueue(e,i,t,f),P){pn.renderReplies({bubble:i,bubbleContainer:m,message:T,messageDiv:p,loadPromises:f,lazyLoadQueue:this.lazyLoadQueue})&&(E=!0)}return E&&(i.classList.add("can-have-tail"),m.append(na())),i}safeRenderMessage(e,t,s,i,n){try{return this.renderMessage(e,t,s,i,n)}catch(e){this.log.error("renderMessage error:",e)}}performHistoryResult(e,t,s,i){return Zn(this,void 0,void 0,(function*(){let s;e=e.slice(),i&&e.unshift(i),this.messagesQueueOnRender=()=>{const{scrollTop:e,scrollHeight:i}=this.scrollable;s=t?i-e:e,this.messagesQueueOnRender=void 0},this.needReflowScroll&&(fn(this.scrollable.container),this.needReflowScroll=!1);const n=e=>{const s=this.chat.getMessage(e);s.id>0?this.safeRenderMessage(s,t,!0):this.processLocalMessageRender(s)},a=e.length;if(t)for(let t=0;t<a;++t)n(e[t]);else for(let t=a-1;t>=0;--t)n(e[t]);if("scheduled"!==this.chat.type){const t=this.appMessagesManager.getHistoryStorage(this.peerId,this.chat.threadId),s=t.history.first,i=t.history.last;!s.isEnd(bn.a.Bottom)||s.length&&!e.includes(s[0])||this.setLoaded("bottom",!0,!1),!i.isEnd(bn.a.Top)||i.length&&!e.includes(i[i.length-1])||this.setLoaded("top",!0,!1)}else this.setLoaded("top",!0),this.setLoaded("bottom",!0);if(yield this.messagesQueuePromise,this.scrollable.loadedAll.top&&this.messagesQueueOnRenderAdditional&&(this.messagesQueueOnRenderAdditional(),this.messagesQueueOnRenderAdditional&&this.messagesQueueOnRenderAdditional()),void 0!==s){const e=t?this.scrollable.scrollHeight-s:s;this.scrollable.scrollTop=e,h.IS_SAFARI&&fn(this.scrollable.container)}return!0}))}requestHistory(e,t,s){if("chat"===this.chat.type||"discussion"===this.chat.type)return this.appMessagesManager.getHistory(this.peerId,e,t,s,this.chat.threadId);if("pinned"===this.chat.type){return this.appMessagesManager.getSearch({peerId:this.peerId,inputFilter:{_:"inputMessagesFilterPinned"},maxId:e,limit:t,backLimit:s}).then(e=>({history:e.history.map(e=>e.mid)}))}return"scheduled"===this.chat.type?this.appMessagesManager.getScheduledMessages(this.peerId).then(e=>({history:e.slice().reverse()})):void 0}animateAsLadder(e,t,s,i,n){return Zn(this,void 0,void 0,(function*(){if(this.chat.setPeerPromise&&!this.resolveLadderAnimation)return void(this.resolveLadderAnimation=this.animateAsLadder.bind(this,e,t,s,i,n));if(!Object.keys(this.bubbles).length)return;let a,o=Object(L.e)(this.bubbles,"desc");s&&t.length&&(o=o.filter(e=>!t.includes(e))),a=i?n||Math.max(...o):e||Math.max(...o);const r=o.slice(o.findIndex(e=>a>e)),l=s?[]:[a],c=s?[]:o.slice(0,o.findIndex(e=>a>=e)).reverse();de.b&&this.log("getHistory: targeting mid:",a,n,e,r.map(e=>this.appMessagesIdsManager.getServerMessageId(e)),c.map(e=>this.appMessagesIdsManager.getServerMessageId(e)));const d=[];this.chatInner.classList.add("zoom-fading");const u=s?10:40,p=s?0:1,m=(e,t=0)=>{const s=Object(oe.a)();let i=0;return e.forEach((n,a)=>{if(!this.bubbles[n]||this.skippedMids.has(n))return void this.log.warn("animateAsLadder: no bubble by mid:",n);const o=this.bubbles[n].lastElementChild;if(i=(a+t||.1)*u,o.classList.add("zoom-fade"),o.style.transitionDelay=i+"ms",a===e.length-1){const e=t=>{t.target===o&&(s.resolve(),o.removeEventListener("transitionend",e))};o.addEventListener("transitionend",e)}d.push(o)}),e.length||s.resolve(),{lastMsDelay:i,animationPromise:s}},g=m(r,p),b=m(l),v=m(c,p),f=[g.animationPromise,b.animationPromise,v.animationPromise],y=[g.lastMsDelay,b.lastMsDelay,v.lastMsDelay];let w;return this.onAnimateLadder&&(yield this.onAnimateLadder()),Object(_e.b)(()=>{d.forEach(e=>{e.classList.remove("zoom-fade")})}),(r.length||l.length||c.length)&&(w=Promise.all(f),Object(Cs.b)(w,Math.max(...y)+200).then(()=>{Object(_e.b)(()=>{d.forEach(e=>{e.style.transitionDelay=""}),this.chatInner.classList.remove("zoom-fading")}),h.IS_SAFARI||(this.needReflowScroll=!0)})),w}))}renderEmptyPlaceholder(e,t,s,i){const n="empty-bubble-placeholder";let a,o;if(t.classList.add(n,n+"-"+e),"group"===e?a=Object(A.i18n)("GroupEmptyTitle1"):"saved"===e?a=Object(A.i18n)("ChatYourSelfTitle"):"noMessages"===e||"greeting"===e?a=Object(A.i18n)("NoMessages"):"noScheduledMessages"===e&&(a=Object(A.i18n)("NoScheduledMessages")),a.classList.add("center",n+"-title"),i.push(a),"group"===e)i.push(Object(A.i18n)("GroupEmptyTitle2")),o=[Object(A.i18n)("GroupDescription1"),Object(A.i18n)("GroupDescription2"),Object(A.i18n)("GroupDescription3"),Object(A.i18n)("GroupDescription4")];else if("saved"===e)o=[Object(A.i18n)("ChatYourSelfDescription1"),Object(A.i18n)("ChatYourSelfDescription2"),Object(A.i18n)("ChatYourSelfDescription3"),Object(A.i18n)("ChatYourSelfDescription4")];else if("greeting"===e){const e=Object(A.i18n)("NoMessagesGreetingsDescription");e.classList.add("center",n+"-subtitle"),this.messagesQueue.findAndSplice(e=>e.bubble===t);const a=document.createElement("div");a.classList.add(n+"-sticker");const o=this.getMiddleware(),r=this.appStickersManager.getGreetingSticker().then(e=>{if(!o())return;const t=[];return Ls({doc:e,div:a,middleware:o,lazyLoadQueue:this.lazyLoadQueue,group:ho,play:!0,loop:!0,withThumb:!0,loadPromises:t}),Object(l.b)(a,e=>{Object(c.a)(e),Yn.onMediaClick({target:e.target})}),Promise.all(t)});this.renderMessagesQueue(s,t,!1,[r]),i.push(e,a)}o&&(i.push(...o.map(e=>{const t=document.createElement("span");return t.classList.add(n+"-list-item"),t.append(e),t})),"group"===e?o.forEach(e=>{const t=document.createElement("span");t.classList.add("tgico-check"),e.prepend(t)}):"saved"===e&&o.forEach(e=>{const t=document.createElement("span");t.classList.add(n+"-list-bullet"),t.innerText="•",e.prepend(t)})),i.length>1&&t.classList.add("has-description"),i.forEach(e=>e.classList.add(n+"-line"))}processLocalMessageRender(e){const t=this.safeRenderMessage(e,void 0,void 0,void 0,!1);t.classList.add("bubble-first","is-group-last","is-group-first"),t.classList.remove("can-have-tail","is-in");const s=t.querySelector(".message, .service-msg"),i=[],n=this.appPeersManager.isBot(this.peerId);if(n&&"message"===e._){const e=document.createElement("b");e.append(Object(A.i18n)("BotInfoTitle")),i.push(e,"\n\n")}else this.appPeersManager.isAnyGroup(this.peerId)&&this.appPeersManager.getPeer(this.peerId).pFlags.creator?this.renderEmptyPlaceholder("group",t,e,i):a.default.myId===this.peerId?this.renderEmptyPlaceholder("saved",t,e,i):this.peerId>0&&!n&&this.appMessagesManager.canSendToPeer(this.peerId)&&"chat"===this.chat.type?this.renderEmptyPlaceholder("greeting",t,e,i):"scheduled"===this.chat.type?this.renderEmptyPlaceholder("noScheduledMessages",t,e,i):this.renderEmptyPlaceholder("noMessages",t,e,i);s.prepend(...i),this.messagesQueueOnRenderAdditional?this.onAnimateLadder=()=>{if(this.chatInner.prepend(t),this.onAnimateLadder=void 0,!this.messagesQueuePromise)return Object(_e.d)()}:this.chatInner.prepend(t),this.emptyPlaceholderMid=e.mid}generateLocalFirstMessage(e,t){const s=this.appMessagesIdsManager.generateMessageId("scheduled"===this.chat.type?-1:0),i={_:e?"messageService":"message",date:0,id:-(this.peerId+s),peer_id:this.appPeersManager.getOutputPeer(this.peerId),pFlags:{}};return e||(i.message=""),Object(ji.a)(i),t&&t(i),this.appMessagesManager.saveMessages([i]),i}setLoaded(e,t,s=!0){if(this.scrollable.loadedAll[e]!==t){if(this.scrollable.loadedAll[e]=t,"top"===e&&t&&this.appUsersManager.isBot(this.peerId)){this.log("inject bot description");const e=this.getMiddleware();return this.appProfileManager.getProfile(this.peerId).then(t=>{var s;if(!e())return;if(!(null===(s=t.bot_info)||void 0===s?void 0:s.description))return void this.checkIfEmptyPlaceholderNeeded();const i=this.generateLocalFirstMessage(!1,e=>{e.message=t.bot_info.description});this.processLocalMessageRender(i)})}this.checkIfEmptyPlaceholderNeeded()}}checkIfEmptyPlaceholderNeeded(){if(this.scrollable.loadedAll.top&&this.scrollable.loadedAll.bottom&&void 0===this.emptyPlaceholderMid&&(!this.appMessagesManager.getHistoryStorage(this.peerId).count||Object.keys(this.bubbles).length&&!this.getRenderedLength()||"scheduled"===this.chat.type&&!Object.keys(this.bubbles).length)){this.log("inject empty peer placeholder");const e=this.generateLocalFirstMessage(!0);return this.processLocalMessageRender(e),!0}return!1}getHistory(e=0,t=!1,s=!1,i=0,n=!1){const o=this.peerId,r=Math.min(30,yt.a.windowH/38|0),l=Object.keys(this.bubbles).length>0?Math.max(40,r):r;let c=l;if(void 0!==ta){if(!ta)return{cached:!1,promise:Promise.resolve(!0)};Object.keys(this.bubbles).length>0&&--ta}let d,h=0;if(s&&(h=c,t||(c=0)),i&&!s)if("pinned"===this.chat.type)d=[i];else{const t=this.appMessagesManager.getHistoryStorage(o,this.chat.threadId).history.slice;if(t.length<c&&!t.isEnd(bn.a.Both)){d=t.slice();for(let e=d.length-1;e>=0;--e){if(!this.chat.getMessage(d[e]).grouped_id)break;d.splice(e,1)}e=d[d.length-1]||e}}let u,p=this.requestHistory(e,c,h);const m=(null==d?void 0:d.length)&&p instanceof Promise,g=this.isFirstLoad&&h&&p instanceof Promise||m;m&&(u=p,p={history:d}),this.isFirstLoad=!1;const b=e=>Zn(this,void 0,void 0,(function*(){if("offsetIdOffset"in e&&e.history.isEnd(bn.a.Top)){if("discussion"===this.chat.type){const t=this.appMessagesManager.threadsServiceMessagesIdsStorage[this.peerId+"_"+this.chat.threadId];t&&e.history.push(t),e.history.push(...this.chat.getMidsByMid(this.chat.threadId).reverse())}yield this.setLoaded("top",!0)}})),v=e=>Object(Cs.c)().then(()=>b(e)).then(()=>this.performHistoryResult(e.history||[],t,s,!m&&i)),f=e=>{const s=e.then(e=>(t?this.getHistoryTopPromise!==s:this.getHistoryBottomPromise!==s)?(this.log.warn("getHistory: peer changed"),Promise.reject()):n?(this.scrollable.onScroll(),!0):v(e),e=>{throw this.log.error("getHistory error:",e),e});return s};let y,w;if(p instanceof Promise)w=!1,y=f(p);else{if(n)return null;w=!0,y=v(p)}const S=m?f(u):y;if(g&&a.default.settings.animationsEnabled){let s=m?2:1;this.messagesQueueOnRenderAdditional=()=>{if(this.log("ship went past rocks of magnets"),--s)return;this.messagesQueueOnRenderAdditional=void 0;(this.animateAsLadder(i,d,m,h,e)||Promise.resolve()).then(()=>{setTimeout(()=>{this.loadMoreHistory(t,!0)},0)})}}else this.messagesQueueOnRenderAdditional=void 0;return t?this.getHistoryTopPromise=S:this.getHistoryBottomPromise=S,S.then(()=>{t?this.getHistoryTopPromise=void 0:this.getHistoryBottomPromise=void 0}),n?null:(!g&&y.then(()=>{let e;t?(this.loadedTopTimes++,this.loadedBottomTimes=Math.max(0,--this.loadedBottomTimes)):(this.loadedBottomTimes++,this.loadedTopTimes=Math.max(0,--this.loadedTopTimes)),(t&&this.loadedTopTimes>2||!t&&this.loadedBottomTimes>2)&&(e=Object(L.e)(this.bubbles));const s=2*l;e&&e.length>s&&(t?(e=e.slice(s),this.setLoaded("bottom",!1)):(e=e.slice(0,e.length-s),this.setLoaded("top",!1)),this.deleteMessagesByIds(e,!1))}),y.then(()=>{"chat"===this.chat.type&&setTimeout(()=>{t?this.loadMoreHistory(!0,!0):this.loadMoreHistory(!1,!0)},0)}),{cached:w,promise:y})}setUnreadDelimiter(){if("chat"!==this.chat.type&&"discussion"!==this.chat.type)return;if(this.attachedUnreadBubble)return;const e=this.appMessagesManager.getHistoryStorage(this.peerId,this.chat.threadId);let t=this.appMessagesManager.getReadMaxIdIfUnread(this.peerId,this.chat.threadId);if(t&&(t=Object.keys(this.bubbles).filter(e=>!this.bubbles[e].classList.contains("is-out")).map(e=>+e).sort((e,t)=>e-t).find(e=>e>t),t&&this.bubbles[t])){let s=this.bubbles[t];this.firstUnreadBubble&&this.firstUnreadBubble!==s&&(this.firstUnreadBubble.classList.remove("is-first-unread"),this.firstUnreadBubble=null),t!==e.maxId&&s.classList.add("is-first-unread"),this.firstUnreadBubble=s,this.attachedUnreadBubble=!0}}deleteEmptyDateGroups(){const e=+!!this.stickyIntersector+1;for(const t in this.dateMessages){const s=this.dateMessages[t];s.container.childElementCount===e&&(s.container.remove(),this.stickyIntersector&&this.stickyIntersector.unobserve(s.container,s.div),delete this.dateMessages[t])}this.checkIfEmptyPlaceholderNeeded()}}function na(){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttributeNS(null,"viewBox","0 0 11 20"),e.setAttributeNS(null,"width","11"),e.setAttributeNS(null,"height","20"),e.classList.add("bubble-tail");const t=document.createElementNS("http://www.w3.org/2000/svg","use");return t.setAttributeNS(null,"href","#message-tail-filled"),e.append(t),e}class aa{constructor(e,t,s,n){var r;let l,c,d,h=[],u=[];const p=o.a.canPinMessage(e),m=(a,o,r)=>{setTimeout(()=>{let a;a=s&&!t?p?i.a.unpinAllMessages(e):i.a.hidePinnedMessages(e):i.a.updatePinnedMessage(e,t,s,r,o),n&&a.then(n)},300)};if(s){let s="UnpinMessage";t?(l="UnpinMessageAlertTitle",c="Chat.Confirm.Unpin"):p?(l="Popup.Unpin.AllTitle",c="Chat.UnpinAllMessagesConfirmation",d=[""+((null===(r=i.a.pinnedMessages[e])||void 0===r?void 0:r.count)||1)]):(l="Popup.Unpin.HideTitle",c="Popup.Unpin.HideDescription",s="Popup.Unpin.Hide"),h.push({langKey:s,isDanger:!0,callback:m})}else{l="PinMessageAlertTitle";const t="PinMessage";e<0?(h.push({langKey:t,callback:e=>m(0,!1,!e.size)}),G.a.isBroadcast(-e)?c="PinMessageAlertChannel":(c="PinMessageAlert",u.push({text:"PinNotify",checked:!0}))):(c="PinMessageAlertChat",e===a.default.myId?h.push({langKey:t,callback:m}):(h.push({langKey:t,callback:e=>m(0,!e.size)}),u.push({text:"PinAlsoFor",textArgs:[new ft.a({peerId:e}).element],checked:!0})))}Object(ct.a)(h);new ht("popup-delete-chat",{peerId:e,titleLangKey:l,descriptionLangKey:c,descriptionLangArgs:d,buttons:h,checkboxes:u}).show()}}function oa(e=window.getSelection()){if(!e||!e.rangeCount)return!0;const t=e.getRangeAt(0);return!t.toString()||!t.START_TO_END}class ra extends ht{constructor(e,t,s,n){super("popup-report-messages-confirm",{noTitle:!0,descriptionLangKey:"ReportInfo",buttons:[{langKey:"ReportChat",callback:()=>{o.isValid()&&(n&&n(),i.a.reportMessages(e,t,s,o.value).then(e=>{e&&at({langPackKey:"ReportSentInfo"})}))}}],body:!0});const a=document.createElement("div");Ls({doc:hs.getAnimatedEmojiSticker(ra.STICKER_EMOJI),div:a,emoji:ra.STICKER_EMOJI,width:100,height:100,loop:!1,play:!0}).finally(()=>{this.show()}),this.header.append(a);const o=new F.b({label:"ReportHint",maxLength:512,placeholder:"ReportChatDescription"});this.body.append(o.container)}}ra.STICKER_EMOJI="👮‍♀️";class la extends ht{constructor(e,t,s){super("popup-report-messages",{titleLangKey:"ChatTitle.ReportMessages",buttons:[],body:!0}),t=t.slice();const i=[["ReportChatSpam","inputReportReasonSpam"],["ReportChatViolence","inputReportReasonViolence"],["ReportChatChild","inputReportReasonChildAbuse"],["ReportChatPornography","inputReportReasonPornography"],["ReportChatOther","inputReportReasonOther"]];i.forEach(e=>{const t=Object(U.a)("btn-primary btn-transparent",{text:e[0]});this.body.append(t)});const n=hs.preloadAnimatedEmojiSticker(ra.STICKER_EMOJI);Object(l.b)(this.body,a=>{const o=Object(Ce.a)(a.target,"btn-primary"),r=i[Object(Ts.a)(o)][1];n.then(()=>{this.hide(),new ra(e,t,r,s)})},{listenerSetter:this.listenerSetter}),this.body.style.margin="0 -1rem",this.buttons.style.marginTop=".5rem",this.show()}}class ca{constructor(e,t,s,i,n,a,o){this.attachTo=e,this.chat=t,this.appMessagesManager=s,this.appPeersManager=i,this.appPollsManager=n,this.appDocsManager=a,this.appMessagesIdsManager=o,this.onSendScheduledClick=()=>{this.chat.selection.isSelecting?Object(l.d)(this.chat.selection.selectionSendNowBtn):new Hs(this.peerId,this.chat.getMidsByMid(this.mid))},this.onReplyClick=()=>{this.chat.input.initMessageReply(this.mid)},this.onEditClick=()=>{this.chat.input.initMessageEditing(this.mid)},this.onCopyClick=()=>{if(oa()){et((this.chat.selection.isSelecting?[...this.chat.selection.selectedMids.get(this.peerId)].sort((e,t)=>e-t):[this.mid]).reduce((e,t)=>{const s=this.chat.getMessage(t);return e+((null==s?void 0:s.message)?s.message+"\n":"")},"").trim())}else document.execCommand("copy")},this.onCopyAnchorLinkClick=()=>{et(this.target.href)},this.onCopyLinkClick=()=>{let e;"discussion"===this.chat.type&&(e=this.appMessagesManager.getMessageByPeer(this.peerId,this.chat.threadId));const t=this.appPeersManager.getPeerUsername(e?e.fromId:this.peerId),s=this.appMessagesIdsManager.getServerMessageId(this.mid);let i,n="https://t.me/";t?(n+=t+"/"+(e?this.appMessagesIdsManager.getServerMessageId(e.fwd_from.channel_post):s),e&&(n+="?comment="+s),i="LinkCopied"):(n+="c/"+Math.abs(this.peerId)+"/"+s,e&&(n+="?thread="+this.appMessagesIdsManager.getServerMessageId(e.mid)),i="LinkCopiedPrivateInfo"),nt(A.default.format(i,!0)),et(n)},this.onPinClick=()=>{new aa(this.peerId,this.mid)},this.onUnpinClick=()=>{new aa(this.peerId,this.mid,!0)},this.onRetractVote=()=>{this.appPollsManager.sendVote(this.message,[])},this.onStopPoll=()=>{this.appPollsManager.stopPoll(this.message)},this.onForwardClick=()=>{if(this.chat.selection.isSelecting)Object(l.d)(this.chat.selection.selectionForwardBtn);else{const e=this.isTargetAGroupedItem?[this.mid]:this.chat.getMidsByMid(this.mid);new Ds({[this.peerId]:e})}},this.onSelectClick=()=>{this.chat.selection.toggleByElement(Object(Ce.a)(this.target,"grouped-item")||Object(Ce.a)(this.target,"bubble"))},this.onClearSelectionClick=()=>{this.chat.selection.cancelSelection()},this.onDeleteClick=()=>{this.chat.selection.isSelecting?Object(l.d)(this.chat.selection.selectionDeleteBtn):new Bs(this.peerId,this.isTargetAGroupedItem?[this.mid]:this.chat.getMidsByMid(this.mid),this.chat.type)};const r=e=>{let s,i;this.init&&(this.init(),this.init=null);try{i=Object(Ce.a)(e.target,"bubble-content-wrapper"),s=i?i.parentElement:Object(Ce.a)(e.target,"bubble")}catch(e){}if(!s||s.classList.contains("bubble-first"))return;if((e instanceof MouseEvent||e.hasOwnProperty("preventDefault"))&&e.preventDefault(),this.element.classList.contains("active"))return!1;(e instanceof MouseEvent||e.hasOwnProperty("cancelBubble"))&&(e.cancelBubble=!0);let n=+s.dataset.mid;if(!n)return;if(this.isSelectable=this.chat.selection.canSelectBubble(s),this.peerId=this.chat.peerId,this.target=e.target,this.isTextSelected=!oa(),this.isAnchorTarget="A"===this.target.tagName&&("_blank"===this.target.target||this.target.classList.contains("anchor-url")),this.isUsernameTarget="A"===this.target.tagName&&this.target.classList.contains("mention"),t.selection.isSelecting&&!i){const e=this.chat.getMidsByMid(n);if(e.length>1){const t=this.chat.selection.isMidSelected(this.peerId,n)?n:e.find(e=>this.chat.selection.isMidSelected(this.peerId,e));t&&(n=t)}}const a=Object(Ce.a)(this.target,"grouped-item");this.isTargetAGroupedItem=!!a,this.mid=a?+a.dataset.mid:n,this.isSelected=this.chat.selection.isMidSelected(this.peerId,this.mid),this.message=this.chat.getMessage(this.mid),this.buttons.forEach(e=>{let s;t.selection.isSelecting&&!e.withSelection?s=!1:(i||pe.IS_TOUCH_SUPPORTED,s=e.verify()),e.element.classList.toggle("hide",!s)});const o=s.classList.contains("is-in")?"left":"right";Object(se.e)(e.touches?e.touches[0]:e,this.element,o),Object(se.d)(this.element,()=>{this.peerId=this.mid=0,this.target=null})};pe.IS_TOUCH_SUPPORTED?Object(l.b)(e,e=>{if(t.selection.isSelecting)return;const s=e.target.className;if(!s||!s.includes)return;t.log("touchend",e);["bubble","bubble-content-wrapper","bubble-content","message","time","inner"].find(e=>s.match(new RegExp(e+"($|\\s)")))&&(Object(c.a)(e),r(e))},{listenerSetter:this.chat.bubbles.listenerSetter}):Object(se.a)(e,r,this.chat.bubbles.listenerSetter)}init(){this.buttons=[{icon:"send2",text:"MessageScheduleSend",onClick:this.onSendScheduledClick,verify:()=>"scheduled"===this.chat.type&&!this.message.pFlags.is_outgoing},{icon:"send2",text:"Message.Context.Selection.SendNow",onClick:this.onSendScheduledClick,verify:()=>"scheduled"===this.chat.type&&this.isSelected&&!this.chat.selection.selectionSendNowBtn.hasAttribute("disabled"),notDirect:()=>!0,withSelection:!0},{icon:"schedule",text:"MessageScheduleEditTime",onClick:()=>{this.chat.input.scheduleSending(()=>{this.appMessagesManager.editMessage(this.message,this.message.message,{scheduleDate:this.chat.input.scheduleDate,entities:this.message.entities}),this.chat.input.onMessageSent(!1,!1)},new Date(1e3*this.message.date))},verify:()=>"scheduled"===this.chat.type},{icon:"reply",text:"Reply",onClick:this.onReplyClick,verify:()=>this.appMessagesManager.canSendToPeer(this.peerId,this.chat.threadId)&&!this.message.pFlags.is_outgoing&&!!this.chat.input.messageInput&&"scheduled"!==this.chat.type},{icon:"edit",text:"Edit",onClick:this.onEditClick,verify:()=>this.appMessagesManager.canEditMessage(this.message,"text")&&!!this.chat.input.messageInput},{icon:"copy",text:"Copy",onClick:this.onCopyClick,verify:()=>!(!this.message.message||this.isTextSelected||this.isAnchorTarget&&this.message.message===this.target.innerText)},{icon:"copy",text:"Chat.CopySelectedText",onClick:this.onCopyClick,verify:()=>!!this.message.message&&this.isTextSelected},{icon:"copy",text:"Message.Context.Selection.Copy",onClick:this.onCopyClick,verify:()=>{if(!this.isSelected)return!1;for(const[e,t]of this.chat.selection.selectedMids)for(const s of t)if(this.appMessagesManager.getMessageByPeer(e,s).message)return!0;return!1},notDirect:()=>!0,withSelection:!0},{icon:"copy",text:"CopyLink",onClick:this.onCopyAnchorLinkClick,verify:()=>this.isAnchorTarget,withSelection:!0},{icon:"copy",text:"Text.Context.Copy.Username",onClick:()=>{et(this.target.innerHTML)},verify:()=>this.isUsernameTarget,withSelection:!0},{icon:"copy",text:"Text.Context.Copy.Hashtag",onClick:()=>{et(this.target.innerHTML)},verify:()=>this.target.classList.contains("anchor-hashtag"),withSelection:!0},{icon:"link",text:"MessageContext.CopyMessageLink1",onClick:this.onCopyLinkClick,verify:()=>this.appPeersManager.isChannel(this.peerId)&&!this.message.pFlags.is_outgoing},{icon:"pin",text:"Message.Context.Pin",onClick:this.onPinClick,verify:()=>!this.message.pFlags.is_outgoing&&"messageService"!==this.message._&&!this.message.pFlags.pinned&&this.appPeersManager.canPinMessage(this.peerId)&&"scheduled"!==this.chat.type},{icon:"unpin",text:"Message.Context.Unpin",onClick:this.onUnpinClick,verify:()=>this.message.pFlags.pinned&&this.appPeersManager.canPinMessage(this.peerId)},{icon:"download",text:"MediaViewer.Context.Download",onClick:()=>{this.appDocsManager.saveDocFile(this.message.media.document)},verify:()=>{var e;if(this.message.pFlags.is_outgoing)return!1;const t=null===(e=this.message.media)||void 0===e?void 0:e.document;if(!t)return!1;let s=!!pe.IS_TOUCH_SUPPORTED;const i=!t.type||!["gif","video","sticker"].includes(t.type);return i&&(s=s||!!Object(Ce.a)(this.target,"document")||!!Object(Ce.a)(this.target,"audio")),i&&s}},{icon:"checkretract",text:"Chat.Poll.Unvote",onClick:this.onRetractVote,verify:()=>{var e;const t=null===(e=this.message.media)||void 0===e?void 0:e.poll;return t&&t.chosenIndexes.length&&!t.pFlags.closed&&!t.pFlags.quiz}},{icon:"stop",text:"Chat.Poll.Stop",onClick:this.onStopPoll,verify:()=>{var e;const t=null===(e=this.message.media)||void 0===e?void 0:e.poll;return this.appMessagesManager.canEditMessage(this.message,"poll")&&t&&!t.pFlags.closed&&!this.message.pFlags.is_outgoing}},{icon:"forward",text:"Forward",onClick:this.onForwardClick,verify:()=>"scheduled"!==this.chat.type&&!this.message.pFlags.is_outgoing&&"messageService"!==this.message._},{icon:"forward",text:"Message.Context.Selection.Forward",onClick:this.onForwardClick,verify:()=>this.chat.selection.selectionForwardBtn&&this.isSelected&&!this.chat.selection.selectionForwardBtn.hasAttribute("disabled"),notDirect:()=>!0,withSelection:!0},{icon:"flag",text:"ReportChat",onClick:()=>{new la(this.peerId,[this.mid])},verify:()=>!this.message.pFlags.out&&"message"===this.message._&&!this.message.pFlags.is_outgoing&&this.appPeersManager.isChannel(this.peerId),notDirect:()=>!0,withSelection:!0},{icon:"select",text:"Message.Context.Select",onClick:this.onSelectClick,verify:()=>!this.message.action&&!this.isSelected&&this.isSelectable,notDirect:()=>!0,withSelection:!0},{icon:"select",text:"Message.Context.Selection.Clear",onClick:this.onClearSelectionClick,verify:()=>this.isSelected,notDirect:()=>!0,withSelection:!0},{icon:"delete danger",text:"Delete",onClick:this.onDeleteClick,verify:()=>this.appMessagesManager.canDeleteMessage(this.message)},{icon:"delete danger",text:"Message.Context.Selection.Delete",onClick:this.onDeleteClick,verify:()=>this.isSelected&&!this.chat.selection.selectionDeleteBtn.hasAttribute("disabled"),notDirect:()=>!0,withSelection:!0}],this.element=Ee(this.buttons,this.chat.bubbles.listenerSetter),this.element.id="bubble-contextmenu",this.element.classList.add("contextmenu"),this.chat.container.append(this.element)}}var da=s(143),ha=s.n(da),ua=s(136);class pa{constructor(e){this.sendMenuButtons=[{icon:"mute",text:"Chat.Send.WithoutSound",onClick:e.onSilentClick,verify:()=>"schedule"===this.type},{icon:"schedule",text:"Chat.Send.ScheduledMessage",onClick:e.onScheduleClick,verify:()=>"schedule"===this.type},{icon:"schedule",text:"Chat.Send.SetReminder",onClick:e.onScheduleClick,verify:()=>"reminder"===this.type}],this.sendMenu=Ee(this.sendMenuButtons,e.listenerSetter),this.sendMenu.classList.add("menu-send",e.openSide),Object(se.a)(e.onContextElement,t=>{e.onOpen&&!e.onOpen()||(this.sendMenuButtons.forEach(e=>{e.element.classList.toggle("hide",!e.verify())}),Object(c.a)(t),Object(se.d)(this.sendMenu))},e.listenerSetter)}setPeerId(e){this.type=e===a.default.myId?"reminder":"schedule"}}var ma=s(64),ga=s(82);class ba extends ct.b{constructor(e){if(super("popup-create-poll popup-new-media",null,{closable:!0,withConfirm:"Create",body:!0}),this.chat=e,this.tempId=0,this.onSubmitClick=()=>{this.send()},this.onInput=e=>{const t=e.target,s=Object(mt.a)(t,"LABEL"),i=Object(ga.a)(t);i||(t.parentElement.classList.add("is-filled"),s.classList.remove("hidden-widget"),s.firstElementChild.removeAttribute("disabled"));!s.nextElementSibling&&!i&&this.questions.childElementCount<10&&this.appendMoreField(),this.handleChange()},this.onDeleteClick=e=>{const t=e.target,s=Object(mt.a)(t,"LABEL"),i=Object(Ts.a)(s);this.correctAnswers&&this.correctAnswers[0][0]===i&&(this.correctAnswers=void 0),s.remove(),this.optionInputFields.splice(i,1),this.optionInputFields.forEach((e,t)=>{e.options.labelOptions.length=0,e.options.labelOptions.push(t+1);A.default.weakMap.get(e.label.firstElementChild).update()}),this.handleChange()},Object(A._i18n)(this.title,"NewPoll"),this.questionInputField=new F.b({placeholder:"AskAQuestion",label:"AskAQuestion",name:"question",maxLength:255}),this.listenerSetter.add(this.questionInputField.input)("input",()=>{this.handleChange()}),this.optionInputFields=[],"scheduled"!==this.chat.type){const e=new pa({onSilentClick:()=>{this.chat.input.sendSilent=!0,this.send()},onScheduleClick:()=>{this.chat.input.scheduleSending(()=>{this.send()})},openSide:"bottom-left",onContextElement:this.btnConfirm});e.setPeerId(this.chat.peerId),this.header.append(e.sendMenu)}this.header.append(this.questionInputField.container);const t=document.createElement("hr"),s=document.createElement("div");s.classList.add("caption"),Object(A._i18n)(s,"PollOptions"),this.questions=document.createElement("form"),this.questions.classList.add("poll-create-questions");const i=document.createElement("div");i.classList.add("poll-create-settings");const n=document.createElement("div");n.classList.add("caption"),Object(A._i18n)(n,"Settings"),this.chat.appPeersManager.isBroadcast(this.chat.peerId)||(this.anonymousCheckboxField=new dt.a({text:"NewPoll.Anonymous",name:"anonymous"}),this.anonymousCheckboxField.input.checked=!0,i.append(this.anonymousCheckboxField.label)),this.multipleCheckboxField=new dt.a({text:"NewPoll.MultipleChoice",name:"multiple"}),this.quizCheckboxField=new dt.a({text:"NewPoll.Quiz",name:"quiz"}),this.listenerSetter.add(this.multipleCheckboxField.input)("change",()=>{const e=this.multipleCheckboxField.input.checked;this.quizCheckboxField.input.toggleAttribute("disabled",e)}),this.listenerSetter.add(this.quizCheckboxField.input)("change",()=>{const e=this.quizCheckboxField.input.checked;Array.from(this.questions.children).map(t=>{t.classList.toggle("radio-field",e)}),e||(this.correctAnswers=void 0,this.quizSolutionField.setValueSilently("")),a.forEach(t=>t.classList.toggle("hide",!e)),this.multipleCheckboxField.input.toggleAttribute("disabled",e),this.handleChange()}),i.append(this.multipleCheckboxField.label,this.quizCheckboxField.label);const a=[],o=document.createElement("div");o.classList.add("caption"),Object(A._i18n)(o,"AccDescrQuizExplanation");const r=document.createElement("hr"),c=document.createElement("div");c.classList.add("poll-create-questions"),this.quizSolutionField=new F.b({placeholder:"NewPoll.Explanation.Placeholder",label:"NewPoll.Explanation.Placeholder",name:"solution",maxLength:200}),this.listenerSetter.add(this.questionInputField.input)("input",()=>{this.handleChange()});const d=document.createElement("div");d.classList.add("subtitle"),Object(A._i18n)(d,"AddAnExplanationInfo"),c.append(this.quizSolutionField.container,d),a.push(r,o,c),a.forEach(e=>e.classList.add("hide")),this.body.parentElement.insertBefore(t,this.body),this.body.append(s,this.questions,document.createElement("hr"),n,i,...a),Object(l.b)(this.btnConfirm,this.onSubmitClick,{listenerSetter:this.listenerSetter}),this.scrollable=new P.b(this.body),this.appendMoreField(),this.onEscape=()=>!this.getFilledAnswers().length,this.handleChange()}getFilledAnswers(){return Array.from(this.questions.children).map((e,t)=>{const s=e.querySelector(".input-field-input");return s instanceof HTMLInputElement?s.value:Object(ma.a)(s,!1).value}).filter(e=>!!e.trim())}validate(){var e;const t=this.questionInputField.value;if(!t)return!1;if(t.length>255)return!1;if(this.quizCheckboxField.input.checked&&!(null===(e=this.correctAnswers)||void 0===e?void 0:e.length))return!1;const s=this.getFilledAnswers();if(s.length<2)return!1;if(s.find(e=>e.length>100))return!1;const{value:i}=Object(ma.a)(this.quizSolutionField.input,!1);return!(i.length>200)}handleChange(){const e=this.validate();this.btnConfirm.toggleAttribute("disabled",!e)}send(e=!1){const t=this.questionInputField.value,s=this.getFilledAnswers(),{value:i,entities:n}=Object(ma.a)(this.quizSolutionField.input);if("scheduled"===this.chat.type&&!e)return void this.chat.input.scheduleSending(()=>{this.send(!0)});this.hide();const a={};this.anonymousCheckboxField&&!this.anonymousCheckboxField.input.checked&&(a.public_voters=!0),this.multipleCheckboxField.input.checked&&(a.multiple_choice=!0),this.quizCheckboxField.input.checked&&(a.quiz=!0);const o={_:"poll",pFlags:a,question:t,answers:s.map((e,t)=>({_:"pollAnswer",text:e,option:new Uint8Array([t])})),id:void 0},r=this.chat.appPollsManager.getInputMediaPoll(o,this.correctAnswers,i,n);this.chat.appMessagesManager.sendOther(this.chat.peerId,r,{threadId:this.chat.threadId,replyToMsgId:this.chat.input.replyToMsgId,scheduleDate:this.chat.input.scheduleDate,silent:this.chat.input.sendSilent}),"reply"===this.chat.input.helperType&&this.chat.input.clearHelper(),this.chat.input.onMessageSent(!1,!1)}appendMoreField(){const e=this.tempId++,t=this.questions.childElementCount+1,s=new F.b({placeholder:"NewPoll.OptionsAddOption",label:"NewPoll.OptionLabel",labelOptions:[t],name:"question-"+e,maxLength:100});this.listenerSetter.add(s.input)("input",this.onInput);const i=new st({text:"",name:"question"});i.main.append(s.container),Object(l.b)(s.input,c.a,{listenerSetter:this.listenerSetter}),i.label.classList.add("hidden-widget"),i.input.disabled=!0,this.quizCheckboxField.input.checked||i.label.classList.remove("radio-field"),this.listenerSetter.add(i.input)("change",()=>{if(i.input.checked){const e=Object(Ts.a)(i.label);this.correctAnswers=[new Uint8Array([e])],this.handleChange()}});const n=document.createElement("span");n.classList.add("btn-icon","tgico-close"),s.container.append(n),Object(l.b)(n,this.onDeleteClick,{listenerSetter:this.listenerSetter,once:!0}),this.questions.append(i.label),this.scrollable.scrollIntoViewNew(this.questions.lastElementChild,"center"),this.optionInputFields.push(s)}}var va=s(95);class fa extends ct.b{constructor(e,t,s){if(super("popup-send-photo popup-new-media",null,{closable:!0,withConfirm:"Modal.Send",confirmShortcutIsSendShortcut:!0}),this.chat=e,this.wasInputValue="",this.willAttach={sendFileDetails:[],group:!1},this.onKeyDown=e=>{const t=e.target;if(t!==this.input){if("INPUT"===t.tagName||t.hasAttribute("contenteditable"))return;this.input.focus(),Object(va.a)(this.input)}},this.attachFile=e=>{const t=this.willAttach;return new Promise(s=>{const i={};i.file=e;const n=document.createElement("div");switch(t.type){case"media":{const t=0===e.type.indexOf("video/");if(n.classList.add("popup-item-media"),t){const t=document.createElement("video"),a=document.createElement("source");a.src=i.objectURL=URL.createObjectURL(e),t.autoplay=!0,t.controls=!1,t.muted=!0,t.setAttribute("playsinline","true"),t.addEventListener("timeupdate",()=>{t.pause()},{once:!0}),Object(me.d)(t).then(()=>{i.width=t.videoWidth,i.height=t.videoHeight,i.duration=Math.floor(t.duration);const e=t.webkitAudioDecodedByteCount;void 0!==e&&(i.noSound=!e),n.append(t),Object(me.b)(t).then(e=>{i.thumb=Object.assign({url:URL.createObjectURL(e.blob)},e),s(n)})}),t.append(a)}else{const t=new Image;t.src=i.objectURL=URL.createObjectURL(e),t.onload=()=>{i.width=t.naturalWidth,i.height=t.naturalHeight,n.append(t),s(n)}}break}case"document":{const t=-1!==e.type.indexOf("image/"),a=-1!==e.type.indexOf("audio/");(t||a)&&(i.objectURL=URL.createObjectURL(e));const o={_:"document",file:e,file_name:e.name||"",fileName:e.name?Z.b.wrapEmojiText(e.name):"",size:e.size,type:t?"photo":"doc"},r=he.a.getCacheContext(o);r.url=i.objectURL,r.downloaded=e.size;const l=fs({message:{_:"message",pFlags:{is_outgoing:!0},mid:0,peerId:0,media:{_:"messageMediaDocument",document:o}}}),c=()=>{n.append(l),s(n)};if(t){const e=new Image;e.src=i.objectURL,e.onload=()=>{i.width=e.naturalWidth,i.height=e.naturalHeight,c()},e.onerror=c}else c();break}}t.sendFileDetails.push(i)})},this.willAttach.type=s,Object(l.b)(this.btnConfirm,()=>this.send(),{listenerSetter:this.listenerSetter}),"scheduled"!==this.chat.type){const e=new pa({onSilentClick:()=>{this.chat.input.sendSilent=!0,this.send()},onScheduleClick:()=>{this.chat.input.scheduleSending(()=>{this.send()})},openSide:"bottom-left",onContextElement:this.btnConfirm,listenerSetter:this.listenerSetter});e.setPeerId(this.chat.peerId),this.header.append(e.sendMenu)}this.mediaContainer=document.createElement("div"),this.mediaContainer.classList.add("popup-photo");const i=new P.b(null);i.container.append(this.mediaContainer),this.inputField=new F.b({placeholder:"PreviewSender.CaptionPlaceholder",label:"Caption",name:"photo-caption",maxLength:a.default.config.caption_length_max,showLengthOn:80}),this.input=this.inputField.input,this.inputField.value=this.wasInputValue=this.chat.input.messageInputField.input.innerHTML,this.chat.input.messageInputField.value="",this.container.append(i.container),t.length>1&&(this.groupCheckboxField=new dt.a({text:"PreviewSender.GroupItems",name:"group-items"}),this.container.append(this.groupCheckboxField.label,this.inputField.container),this.groupCheckboxField.input.checked=!0,this.willAttach.group=!0,this.listenerSetter.add(this.groupCheckboxField.input)("change",()=>{const e=this.groupCheckboxField.input.checked;this.willAttach.group=e,this.willAttach.sendFileDetails.length=0,this.attachFiles(t)})),this.container.append(this.inputField.container),this.attachFiles(t)}send(e=!1){if("scheduled"===this.chat.type&&!e)return void this.chat.input.scheduleSending(()=>{this.send(!0)});let t=this.inputField.value;if(t.length>a.default.config.caption_length_max)return void nt(A.default.format("Error.PreviewSender.CaptionTooLong",!0));this.hide();const s=this.willAttach;s.isMedia="media"===s.type||void 0;const i=this.chat.peerId,n=this.chat.input,o=n.sendSilent,r=n.scheduleDate;if(s.sendFileDetails.length>1&&s.group)for(let e=0;e<s.sendFileDetails.length;){let a=s.sendFileDetails[e].file.type.split("/")[0];for(var l=0;l<10&&e<s.sendFileDetails.length;++e,++l){if(a!==s.sendFileDetails[e].file.type.split("/")[0])break}const c=Object.assign({},s);c.sendFileDetails=s.sendFileDetails.slice(e-l,e),this.chat.appMessagesManager.sendAlbum(i,c.sendFileDetails.map(e=>e.file),Object.assign({caption:t,replyToMsgId:n.replyToMsgId,threadId:this.chat.threadId,isMedia:s.isMedia,silent:o,scheduleDate:r,clearDraft:!0},c)),t=void 0,n.replyToMsgId=this.chat.threadId}else{t&&s.sendFileDetails.length>1&&(this.chat.appMessagesManager.sendText(i,t,{replyToMsgId:n.replyToMsgId,threadId:this.chat.threadId,silent:o,scheduleDate:r,clearDraft:!0}),t="");s.sendFileDetails.map(e=>{const a=this.chat.appMessagesManager.sendFile(i,e.file,Object.assign({isMedia:s.isMedia,caption:t,replyToMsgId:n.replyToMsgId,threadId:this.chat.threadId,silent:o,scheduleDate:r,clearDraft:!0},e));return t="",a});n.replyToMsgId=this.chat.threadId}n.onMessageSent()}attachFiles(e){const t=this.container,s=this.willAttach;e="media"===s.type?e.filter(e=>g.has(e.type)):e.slice(),Promise.all(e.map(this.attachFile)).then(i=>{if(this.container.classList.remove("is-media","is-document","is-album"),this.mediaContainer.innerHTML="",e.length){let i;const n=[];if("document"===s.type)i="PreviewSender.SendFile",n.push(e.length),t.classList.add("is-document");else{t.classList.add("is-media");let a=0,o=0;e.forEach(e=>{0===e.type.indexOf("image/")?++a:0===e.type.indexOf("video/")&&++o});const r=a+o;if(r>1&&s.group){i="PreviewSender.SendAlbum";const e=Math.ceil(r/10);n.push(e)}else a?(i="PreviewSender.SendPhoto",n.push(a)):o&&(i="PreviewSender.SendVideo",n.push(o))}this.title.textContent="",this.title.append(Object(A.i18n)(i,n))}if("media"===s.type)if(s.sendFileDetails.length>1&&s.group){t.classList.add("is-album");for(let e=0;e<i.length;e+=10){const t=document.createElement("div");t.classList.add("popup-album"),t.append(...i.slice(e,e+10)),Ms({container:t,items:s.sendFileDetails.slice(e,e+10).map(e=>({w:e.width,h:e.height})),maxWidth:380,minWidth:100,spacing:4}),this.mediaContainer.append(t)}}else for(let e=0;e<i.length;++e){const t=s.sendFileDetails[e],n=i[e],a=Object(_n.a)(t.width,t.height,380,320);n.style.width=a.width+"px",n.style.height=a.height+"px",this.mediaContainer.append(n)}else this.mediaContainer.append(...i);this.element.classList.contains("active")||(this.listenerSetter.add(document.body)("keydown",this.onKeyDown),this.onClose=()=>{this.wasInputValue&&(this.chat.input.messageInputField.value=this.wasInputValue)},this.show())})}}const ya=["ArrowUp","ArrowDown"],wa=["ArrowLeft","ArrowRight"];function La({list:e,type:t,onSelect:s,once:i,waitForKey:n}){const a=new Set("xy"===t?ya.concat(wa):"x"===t?wa:ya);let o;const r=()=>o||e.querySelector(".active")||e.firstElementChild,d=(e,s)=>{if(o===e)return;let i=!1;o&&(i=!0,o.classList.remove("active")),o=e,o&&(o.classList.add("active"),i&&m&&s&&Object(bt.b)(m,o,"center",void 0,void 0,void 0,100,"x"===t?"x":"y"))},h=(t,s)=>{let i;return i=s?t.nextElementSibling||e.firstElementChild:t.previousElementSibling||e.lastElementChild,i};let u;u="xy"===t?(t,s)=>"ArrowUp"===s||"ArrowDown"===s?((t,s)=>{const i=s?"nextElementSibling":"previousElementSibling",n=s?"firstElementChild":"lastElementChild",a=t.getBoundingClientRect();let o=t[i]||e[n];for(;o!==t;){const t=o.getBoundingClientRect();if(t.x===a.x&&t.y!==a.y)break;o=o[i]||e[n]}return o})(t,"ArrowDown"===s):h(t,"ArrowRight"===s):(e,t)=>h(e,"ArrowRight"===t||"ArrowDown"===t);let p=t=>{if(a.has(t.key)){if(Object(c.a)(t),e.childElementCount>1){let e=r();e=u(e,t.key),d(e,!0)}}else"Enter"===t.key&&(Object(c.a)(t),v(r()))};const m=Object(Ce.a)(e,"scrollable");e.classList.add("navigable-list");const g=t=>{const s=Object(zs.a)(t.target,e);s&&d(s,!1)},b=t=>{Object(c.a)(t);const s=Object(zs.a)(t.target,e);s&&(d(s,!1),v(r()))},v=e=>{const t=s(e);(void 0!==t?!t:i)&&f()},f=()=>{document.removeEventListener("keydown",p,{capture:!0}),e.removeEventListener("mousemove",g),Object(l.c)(e,b)},y=()=>{n||d(e.firstElementChild,!1)};if(n){const e=p;p=t=>{t.key===n&&(Object(c.a)(t),document.removeEventListener("keydown",p,{capture:!0}),p=e,document.addEventListener("keydown",p,{capture:!0,passive:!1}),n=void 0,y())}}else y();return document.addEventListener("keydown",p,{capture:!0,passive:!1}),e.addEventListener("mousemove",g,{passive:!0}),Object(l.b)(e,b),{detach:f,resetTarget:y}}class Sa extends R.a{constructor(e){super(!1),this.hidden=!0,this.onVisible=()=>{this.detach&&this.detach();const e=this.list,{detach:t,resetTarget:s}=La({list:e,type:this.listType,onSelect:this.onSelect,once:!0,waitForKey:this.waitForKey});this.detach=t,this.resetTarget=s,h.IS_MOBILE||this.navigationItem||(this.navigationItem={type:"autocomplete-helper",onPop:()=>{this.navigationItem=void 0,this.toggle(!0)},noBlurOnPop:!0},B.a.pushItem(this.navigationItem)),this.addEventListener("hidden",()=>{this.resetTarget=void 0,this.detach=void 0,e.innerHTML="",t(),this.navigationItem&&(B.a.removeItem(this.navigationItem),this.navigationItem=void 0)},{once:!0})},Object(L.g)(this,e),this.container=document.createElement("div"),this.container.classList.add("autocomplete-helper","z-depth-1"),e.appendTo.append(this.container),this.attachNavigation(),this.controller.addHelper(this)}attachNavigation(){this.addEventListener("visible",this.onVisible)}toggle(e,t=!1){this.init||(void 0===e&&(e=this.container.classList.contains("is-visible")&&!this.container.classList.contains("backwards")),this.hidden!==e?(this.hidden=e,e?(this.navigationItem&&(B.a.removeItem(this.navigationItem),this.navigationItem=void 0),t||this.controller.hideOtherHelpers(),this.detach&&this.detach()):(this.controller.hideOtherHelpers(this),this.dispatchEvent("visible")),Object(Xt.a)(this.container,"is-visible",!e,a.default.settings.animationsEnabled?200:0,()=>{this.hidden&&this.dispatchEvent("hidden")})):e||this.dispatchEvent("visible"))}}class Ea extends Sa{constructor(e,t){super({appendTo:e,controller:t,listType:"xy",onSelect:e=>!Yn.onMediaClick({target:e},!0),waitForKey:"ArrowUp"}),this.container.classList.add("stickers-helper"),this.addEventListener("visible",()=>{setTimeout(()=>{this.scrollable.container.scrollTop=0},0)}),this.addEventListener("hidden",()=>{this.onChangeScreen&&(v.b.removeEventListener("changeScreen",this.onChangeScreen),this.onChangeScreen=void 0)})}checkEmoticon(e){const t=this.controller.getMiddleware();this.lazyLoadQueue&&this.lazyLoadQueue.clear(),hs.getStickersByEmoticon(e).then(e=>{if(!t())return;this.init&&(this.init(),this.init=null);const s=this.list.cloneNode();let i;this.lazyLoadQueue.clear(),i=e.length?new Promise(t=>{const i=[];e.forEach(e=>{s.append(this.superStickerRenderer.renderSticker(e,void 0,i))}),Promise.all(i).finally(t)}):Promise.resolve(),i.then(()=>{this.list.replaceWith(s),this.list=s,this.onChangeScreen||(this.onChangeScreen=()=>{const e=this.list.childElementCount*v.b.active.esgSticker.width+(this.list.childElementCount-1);this.list.style.width=e+"px"},v.b.addEventListener("changeScreen",this.onChangeScreen)),this.onChangeScreen(),this.toggle(!e.length),this.scrollable.scrollTop=0})})}init(){this.list=document.createElement("div"),this.list.classList.add("stickers-helper-stickers","super-stickers"),this.container.append(this.list),this.scrollable=new P.b(this.container),this.lazyLoadQueue=new te.d,this.superStickerRenderer=new Rn(this.lazyLoadQueue,ho)}}const Ma=()=>{const e=new Date;return e.setHours(0,0,0,0),e},Ia=()=>{const e=new Date;return e.setFullYear(e.getFullYear()+1),e.setDate(e.getDate()-1),e};class Ca extends dn{constructor(e,t,s){var i;if(super((i=e).getTime()>Ia().getTime()?new Date:i,t,{noButtons:!0,noTitle:!0,closable:!0,withConfirm:!0,minDate:Ma(),maxDate:Ia(),withTime:!0,showOverflowMonths:!0,confirmShortcutIsSendShortcut:!0}),this.element.classList.add("popup-schedule"),this.header.append(this.controlsDiv),this.title.replaceWith(this.monthTitle),this.body.append(this.btnConfirm),s){const e=Object(U.a)("btn-primary btn-secondary btn-primary-transparent primary",{text:"Schedule.SendWhenOnline"});this.body.append(e),Object(l.b)(e,()=>{t(2147483646),this.hide()})}}}var ka=s(133),Ta=s(79);function Pa(e,t=!0){const s=[],i=[],n=window.getSelection();let a,o;if(n&&n.rangeCount){const e=n.getRangeAt(0);e.startContainer&&e.startContainer==e.endContainer&&e.startOffset==e.endOffset&&(a=e.startContainer,o=e.startOffset)}const r=t?[]:void 0;Object(Ta.a)(e,s,i,a,o,r),i.length&&s.push(i.join(""));let l=s.join("\n");const c=l.indexOf("");return-1!=c&&(l=l.substr(0,c)+l.substr(c+1)),l=l.replace(/\u00A0/g," "),r&&Z.b.combineSameEntities(r),{value:l,entities:r,caretPos:c}}class xa extends Sa{constructor(e,t,s,i){super({appendTo:e,controller:t,listType:"x",onSelect:e=>{s.onEmojiSelected(An(e),!0)}}),this.appEmojiManager=i,this.container.classList.add("emoji-helper")}init(){this.list=document.createElement("div"),this.list.classList.add("emoji-helper-emojis","super-emojis"),this.container.append(this.list),this.scrollable=new P.a(this.container),this.addEventListener("visible",()=>{setTimeout(()=>{this.scrollable.container.scrollLeft=0},0)})}render(e,t){if(this.init){if(!e.length)return;this.init(),this.init=null}(e=e.slice(0,80)).length&&(this.list.innerHTML="",e.forEach(e=>{xn(e,this.list,!1,!0)})),this.waitForKey=t?"ArrowUp":void 0,this.toggle(!e.length)}checkQuery(e,t){const s=this.controller.getMiddleware();this.appEmojiManager.getBothEmojiKeywords().then(()=>{if(!s())return;const i=e.replace(/^:/,""),n=this.appEmojiManager.searchEmojis(i);this.render(n,":"!==t)})}}class Aa extends Sa{constructor(e,t,s,i){super({appendTo:e,controller:t,listType:"y",onSelect:i}),this.className=s,this.container.classList.add(Aa.BASE_CLASS,s)}init(){this.list=document.createElement("div"),this.list.classList.add(Aa.BASE_CLASS+"-list"),this.container.append(this.list),this.scrollable=new P.b(this.container),this.addEventListener("visible",()=>{setTimeout(()=>{this.scrollable.container.scrollTop=0},0)})}render(e){if(this.init){if(!e.length)return;this.init(),this.init=null}e.length&&(this.list.innerHTML="",e.forEach(e=>{const t=Aa.listElement({className:this.className,peerId:e.peerId,name:e.name,description:e.description});this.list.append(t)})),this.toggle(!e.length)}static listElement(e){const t=Aa.BASE_CLASS_LIST_ELEMENT;e.className+="-list-element";const s=document.createElement("div");s.classList.add(t,e.className),s.dataset.peerId=""+e.peerId;const i=new ko;i.classList.add("avatar-30",t+"-avatar",e.className+"-avatar"),i.setAttribute("dialog","0"),i.setAttribute("peer",""+e.peerId);const n=document.createElement("div");if(n.classList.add(t+"-name",e.className+"-name"),e.name?n.innerHTML=Z.b.wrapEmojiText(e.name):n.append(new ft.a({peerId:e.peerId,dialog:!1,onlyFirstName:!1,plainText:!1}).element),s.append(i,n),e.description){const i=document.createElement("div");i.classList.add(t+"-description",e.className+"-description"),i.innerHTML=Z.b.wrapEmojiText(e.description),s.append(i)}return s}}Aa.BASE_CLASS="autocomplete-peer-helper",Aa.BASE_CLASS_LIST_ELEMENT=Aa.BASE_CLASS+"-list-element";class Oa extends Aa{constructor(e,t,s,i,n){super(e,t,"commands-helper",e=>{const t=e.querySelector(`.${Aa.BASE_CLASS_LIST_ELEMENT}-name`).innerHTML;return s.getReadyToSend(()=>{s.messageInput.innerHTML=t,s.sendMessage(!0)})}),this.appProfileManager=i,this.appUsersManager=n}checkQuery(e,t){if(!this.appUsersManager.isBot(t))return!1;const s=this.controller.getMiddleware();return this.appProfileManager.getProfileByPeerId(t).then(t=>{if(!s())return;const i=[].concat(t.bot_info),n=new Ln.a({ignoreCase:!0}),a=new Map;i.forEach(e=>{e.commands.forEach(t=>{const s="/"+t.command;a.set(t.command,{peerId:e.user_id,name:s,description:t.description}),n.indexObject(t.command,s)})});const o=n.search(e),r=Array.from(o).map(e=>a.get(e));this.render(r)}),!0}}class _a{constructor(){this.helpers=new Set,this.middleware=Object(ks.a)()}getMiddleware(){return this.middleware.clean(),this.middleware.get()}addHelper(e){this.helpers.add(e)}hideOtherHelpers(e){this.helpers.forEach(t=>{t!==e&&t.toggle(!0,!0)}),e||this.middleware.clean()}}class Fa extends Aa{constructor(e,t,s,i,n){super(e,t,"mentions-helper",e=>{const t=n.getUser(+e.dataset.peerId);let i,a="";t.username?a="@"+t.username:(a=t.first_name||t.last_name,i={_:"messageEntityMentionName",length:a.length,offset:0,user_id:t.id}),a+=" ",s.insertAtCaret(a,i)}),this.appProfileManager=i,this.appUsersManager=n}checkQuery(e,t,s){const i=e.trim();if(e.length!==i.length)return!1;const n=this.controller.getMiddleware();return this.appProfileManager.getMentions(t?-t:0,i,s).then(e=>{if(!n())return;const t=i.slice(1).toLowerCase();this.render(e.map(e=>{const s=this.appUsersManager.getUser(e);if(!s.username||s.username.toLowerCase()!==t)return{peerId:e,description:s.username?"@"+s.username:void 0}}).filter(Boolean))}),!0}}var ja=s(3);class Da extends qn{constructor(e){super({element:document.createElement("div")}),this.onBodyTouchStart=e=>{const t=e.touches[0].target;Object(zs.a)(t,this.element)||t===this.btnHover||(Object(c.a)(e),this.toggle(!1))},Object(L.g)(this,e),this.element.classList.add(Da.BASE_CLASS),this.element.style.display="none",this.attachButtonListener(this.btnHover,this.listenerSetter),this.listenerSetter.add(a.default)("history_reply_markup",({peerId:e})=>{this.peerId===e&&(this.checkAvailability()&&this.isActive()&&this.render(),Object(Cs.c)().then(()=>{this.checkForceReply()}))})}init(){return this.appendTo.append(this.element),this.listenerSetter.add(this)("open",()=>{this.render(),pe.IS_TOUCH_SUPPORTED&&(this.touchListener=this.listenerSetter.add(document.body)("touchstart",this.onBodyTouchStart,{passive:!1,capture:!0}),this.listenerSetter.add(this)("close",()=>{this.listenerSetter.remove(this.touchListener)},{once:!0}))}),this.listenerSetter.add(this.element)("click",e=>{const t=Object(Ce.a)(e.target,"btn");t&&(this.appMessagesManager.sendText(this.peerId,t.dataset.text),this.toggle(!1))}),super.init()}checkForceReply(){const e=this.getReplyMarkup();"replyKeyboardForceReply"!==e._||e.pFlags.hidden||e.pFlags.used||(e.pFlags.used=!0,this.chatInput.initMessageReply(e.mid))}getReplyMarkup(){var e;return null!==(e=this.appMessagesManager.getHistoryStorage(this.peerId).replyMarkup)&&void 0!==e?e:{_:"replyKeyboardHide"}}render(e=this.getReplyMarkup()){this.element.innerHTML="";for(const t of e.rows){const e=document.createElement("div");e.classList.add(Da.BASE_CLASS+"-row");for(const s of t.buttons){const t=document.createElement("button");t.classList.add(Da.BASE_CLASS+"-button","btn"),t.innerHTML=Z.b.wrapEmojiText(s.text),t.dataset.text=s.text,e.append(t)}this.element.append(e)}}checkAvailability(e=this.getReplyMarkup()){var t;const s="replyKeyboardHide"===e._||!(null===(t=e.rows)||void 0===t?void 0:t.length);return this.btnHover.classList.toggle("hide",s),s&&this.toggle(!1),!s}setPeer(e){this.peerId=e,this.checkAvailability(),this.checkForceReply()}}Da.BASE_CLASS="reply-keyboard";var Ba=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class Ra extends Sa{constructor(e,t,s,i,n){super({appendTo:e,controller:t,listType:"xy",onSelect:e=>{const{peerId:t,botId:s,queryId:i}=this.list.dataset;return this.chat.input.getReadyToSend(()=>{const n=this.appInlineBotsManager.generateQId(i,e.dataset.resultId);this.appInlineBotsManager.sendInlineResult(+t,+s,n,{clearDraft:!0,scheduleDate:this.chat.input.scheduleDate,silent:this.chat.input.sendSilent,replyToMsgId:this.chat.input.replyToMsgId}),this.chat.input.onMessageSent(!0,!0)})}}),this.chat=s,this.appUsersManager=i,this.appInlineBotsManager=n,this._checkQuery=(e,t,s)=>Ba(this,void 0,void 0,(function*(){const i=this.controller.getMiddleware(),n=yield this.appUsersManager.resolveUsername(t);if(!i())throw"PEER_CHANGED";if("user"!==n._)throw"NOT_A_BOT";const a=this.appInlineBotsManager.getInlineResults(e,n.id,s).then(t=>{var s;if(!i())throw"PEER_CHANGED";this.init&&(this.init(),this.init=null);const a=this.list.cloneNode();a.dataset.peerId=""+e,a.dataset.botId=""+n.id,a.dataset.queryId=t.query_id;const o=new jn(null,"INLINE-HELPER",this.scrollable,!1);this.lazyLoadQueue.clear(),this.superStickerRenderer.clear();const r=[],c=!!t.pFlags.gallery;for(const e of t.results){const t=document.createElement("div");t.classList.add("inline-helper-result"),t.dataset.resultId=e.id;const n=c?void 0:document.createElement("div");if(n&&(n.classList.add("inline-helper-result-preview"),t.append(n)),a.append(t),c)t.classList.add("grid-item");else{n.classList.add("empty"),n.innerHTML=Z.b.wrapEmojiText([...e.title.trim()][0]);const s=document.createElement("div");s.classList.add("inline-helper-result-title"),s.innerHTML=Z.b.wrapEmojiText(e.title);const i=document.createElement("div");i.classList.add("inline-helper-result-description"),i.innerHTML=Z.b.wrapRichText(e.description,{noCommands:!0,noLinks:!0}),t.append(s,i);const o=document.createElement("div");o.classList.add("inline-helper-separator"),a.append(o)}if("botInlineResult"===e._){if(e.thumb&&0===e.thumb.mime_type.indexOf("image/")){let s;n?(s=document.createElement("div"),n.append(s)):s=t,s.classList.add("media-container"),c&&s.classList.add("no-border-radius"),this.lazyLoadQueue.push({div:t,load:()=>he.a.download({dcId:4,location:{_:"inputWebFileLocation",access_hash:e.thumb.access_hash,url:e.thumb.url},size:e.thumb.size,mimeType:e.thumb.mime_type}).then(e=>{const t=new Image;t.classList.add("media-photo"),Object(ae.b)(e).then(e=>{ws(s,t,e,!0)})})})}}else{const a=e.document||e.photo;if(["sticker","gif"].includes(null===(s=a)||void 0===s?void 0:s.type)&&c)Object(ji.a)(a),"gif"===a.type?o.add(a,t):"sticker"===a.type&&(t.classList.add("super-sticker"),this.superStickerRenderer.renderSticker(a,t,r),2===a.sticker&&this.superStickerRenderer.observeAnimatedDiv(t));else if(a){const e=c?48:void 0;c&&t.classList.add("no-border-radius"),ys({photo:a,container:c?t:n,boxWidth:e,boxHeight:e,middleware:i,lazyLoadQueue:this.lazyLoadQueue,loadPromises:r})}}}return Promise.all(r).then(()=>{if(!i())return void o.clear();a.classList.toggle("is-gallery",c),a.classList.toggle("super-stickers",c),this.container.classList.toggle("is-gallery",c);const s=this.list.parentElement;if(s.textContent="",t.switch_pm){const i=Object(U.a)("btn-primary btn-secondary btn-primary-transparent primary");i.insertAdjacentHTML("beforeend",Z.b.wrapEmojiText(t.switch_pm.text)),Object(l.b)(i,s=>{this.appInlineBotsManager.switchToPM(e,n.id,t.switch_pm.start_param)}),s.append(i)}s.append(this.list=a),this.gifsMasonry&&this.gifsMasonry.detach(),this.gifsMasonry=o,o.attach(),this.onChangeScreen||(this.onChangeScreen=()=>{if(this.list.classList.contains("is-gallery")){const e=this.list.childElementCount*v.b.active.esgSticker.width+(this.list.childElementCount-1);this.list.style.width=e+"px"}else this.list.style.width=""},v.b.addEventListener("changeScreen",this.onChangeScreen)),this.onChangeScreen(),this.toggle(!t.results.length&&!t.switch_pm),this.scrollable.scrollTop=0})});return{user:n,renderPromise:a}})),this.container.classList.add("inline-helper"),this.addEventListener("visible",()=>{setTimeout(()=>{this.scrollable.container.scrollTop=0},0)}),this.checkQuery=ot(this._checkQuery,200,!0,!0),this.addEventListener("hidden",()=>{this.onChangeScreen&&(v.b.removeEventListener("changeScreen",this.onChangeScreen),this.onChangeScreen=void 0)})}init(){this.list=document.createElement("div"),this.list.classList.add("inline-helper-results"),this.container.append(this.list),this.scrollable=new P.b(this.container),this.lazyLoadQueue=new te.d,this.superStickerRenderer=new Rn(this.lazyLoadQueue,"INLINE-HELPER")}}var Ha=s(2);class Ua{constructor(e,t,s,i,n,a,o,r,d,h,u,p,m,g){this.chat=e,this.appMessagesManager=t,this.appMessagesIdsManager=s,this.appDocsManager=i,this.appChatsManager=n,this.appPeersManager=a,this.appWebPagesManager=o,this.appImManager=r,this.appDraftsManager=d,this.serverTimeManager=h,this.appNotificationsManager=u,this.appEmojiManager=p,this.appUsersManager=m,this.appInlineBotsManager=g,this.lastUrl="",this.lastTimeType=0,this.replyElements={},this.willSendWebPage=null,this.recording=!1,this.recordCanceled=!1,this.recordStartTime=0,this.lockRedo=!1,this.canRedoFromHTML="",this.undoHistory=[],this.executedHistory=[],this.canUndoFromHTML="",this.onCancelRecordClick=e=>{e&&Object(c.a)(e),this.recordCanceled=!0,this.recorder.stop(),ua.a.setKeepAlive(!1)},this.onEmoticonsOpen=()=>{const e=pe.IS_TOUCH_SUPPORTED?"flip-icon":"active";this.btnToggleEmoticons.classList.toggle(e,!0)},this.onEmoticonsClose=()=>{const e=pe.IS_TOUCH_SUPPORTED?"flip-icon":"active";this.btnToggleEmoticons.classList.toggle(e,!1)},this.scheduleSending=(e=this.sendMessage.bind(this,!0),t=new Date)=>{const s=this.chat.peerId>0&&this.appUsersManager.isUserOnlineVisible(this.chat.peerId);new Ca(t,t=>{t<=10+(Date.now()/1e3|0)&&(t=void 0),this.scheduleDate=t,e(),"scheduled"!==this.chat.type&&t&&this.appImManager.openScheduled(this.chat.peerId)},s).show()},this.prepareDocumentExecute=()=>(this.executedHistory.push(this.messageInput.innerHTML),()=>this.canUndoFromHTML=this.messageInput.innerHTML),this.undoRedo=(e,t,s)=>{Object(c.a)(e);let i=this.messageInput.innerHTML;if(i&&i!==s){this.lockRedo=!0;let e=0;do{document.execCommand(t,!1,null);const s=this.messageInput.innerHTML;if(i===s){if(++e>2)break}else e=0;i=s}while(i!==s);this.lockRedo=!1}},this.handleMarkdownShortcut=e=>{const t={B:"bold",I:"italic",U:"underline",S:"strikethrough",M:"monospace",K:"link"};if(document.getSelection().toString().trim().length)for(const s in t){if(e.code==="Key"+s){if("K"===s&&this.appImManager.markupTooltip){this.appImManager.markupTooltip.showLinkEditor(),Object(c.a)(e);break}this.applyMarkdown(t[s]),Object(c.a)(e);break}}if("KeyZ"===e.code){let t=this.messageInput.innerHTML;e.shiftKey?this.undoHistory.length&&(this.executedHistory.push(t),t=this.undoHistory.pop(),this.undoRedo(e,"redo",t),t=this.messageInput.innerHTML,this.canRedoFromHTML=this.undoHistory.length?t:"",this.canUndoFromHTML=t):!this.executedHistory.length||this.canUndoFromHTML&&t!==this.canUndoFromHTML||(this.undoHistory.push(t),t=this.executedHistory.pop(),this.undoRedo(e,"undo",t),this.canUndoFromHTML=this.canRedoFromHTML=this.messageInput.innerHTML)}},this.onMessageInput=e=>{const{value:t,entities:s,caretPos:i}=Pa(this.messageInputField.input),n=Z.b.parseMarkdown(t,s,!0),a=Z.b.mergeEntities(s,Z.b.parseEntities(n));this.canRedoFromHTML&&!this.lockRedo&&this.messageInput.innerHTML!==this.canRedoFromHTML&&(this.canRedoFromHTML="",this.undoHistory.length=0);const o=a.filter(e=>"messageEntityUrl"===e._||"messageEntityTextUrl"===e._);if(o.length)for(const e of o){let s;if("messageEntityTextUrl"===e._)s=e.url;else if(s=t.slice(e.offset,e.offset+e.length),!s.includes("http://")&&!s.includes("https://"))continue;if(this.lastUrl!==s){this.lastUrl=s;const e=this.getWebPagePromise=rt.a.invokeApiHashable("messages.getWebPage",{url:s}).then(t=>{t=this.appWebPagesManager.saveWebPage(t),this.getWebPagePromise===e&&(this.getWebPagePromise=void 0),this.lastUrl===s&&("webPage"===t._?(this.setTopInfo("webpage",()=>{},t.site_name||t.title||"Webpage",t.description||t.url||""),delete this.noWebPage,this.willSendWebPage=t):this.willSendWebPage&&this.onHelperCancel())})}break}else this.lastUrl&&(this.lastUrl="",delete this.noWebPage,this.willSendWebPage=null,this.helperType?this.helperFunc():this.clearHelper());if(t.trim()){const e=Date.now();e-this.lastTimeType>=6e3&&(this.lastTimeType=e,this.appMessagesManager.setTyping(this.chat.peerId,{_:"sendMessageTypingAction"}))}else this.lastTimeType&&this.appMessagesManager.setTyping(this.chat.peerId,{_:"sendMessageCancelAction"}),this.appImManager.markupTooltip&&this.appImManager.markupTooltip.hide();this.editMsgId||this.saveDraftDebounced(),this.checkAutocomplete(t,i,a),this.updateSendBtn()},this.onEmojiSelected=(e,t)=>{t&&this.insertAtCaret(e,Z.b.getEmojiEntityFromEmoji(e))},this.onBtnSendClick=e=>{if(Object(c.a)(e),!this.recorder||this.recording||!this.isInputEmpty()||this.forwarding||this.editMsgId)this.recording?Date.now()-this.recordStartTime<500?this.onCancelRecordClick():this.recorder.stop():this.sendMessage();else{if(this.chat.peerId<0&&!this.appMessagesManager.canSendToPeer(this.chat.peerId,this.chat.threadId,"send_media"))return void nt("Posting media content isn't allowed in this group.");this.chatInput.classList.add("is-locked"),Object(Us.a)(),this.recorder.start().then(()=>{this.releaseMediaPlayback=fe.setSingleMedia(),this.recordCanceled=!1,this.chatInput.classList.add("is-recording"),this.recording=!0,this.updateSendBtn(),ua.a.setKeepAlive(!0);const e=()=>{new ht("popup-cancel-record",{titleLangKey:"DiscardVoiceMessageTitle",descriptionLangKey:"DiscardVoiceMessageDescription",buttons:[{langKey:"DiscardVoiceMessageAction",callback:()=>{Object(l.d)(this.btnCancelRecord)}},{langKey:"Continue",isCancel:!0}]}).show()};this.recordingOverlayListener=this.listenerSetter.add(document.body)("mousedown",t=>{Object(Ce.a)(t.target,"chat-input")||Object(Ce.a)(t.target,"popup-cancel-record")||(Object(c.a)(t),e())},{capture:!0,passive:!1}),B.a.pushItem(this.recordingNavigationItem={type:"voice",onPop:()=>(setTimeout(()=>{e()},0),!1)}),this.recordStartTime=Date.now();const t=this.recorder.sourceNode,s=t.context.createAnalyser();t.connect(s),s.fftSize=32;const i=new Uint8Array(s.frequencyBinCount),n=255*i.length;let a=()=>{if(!this.recording)return;s.getByteFrequencyData(i);let e=0;i.forEach(t=>{e+=t});let t=Math.min(1,e/n+.36);this.recordRippleEl.style.transform=`scale(${t})`;let o=Date.now()-this.recordStartTime,r=o%1e3,l=(""+o/1e3).toHHMMSS()+","+("00"+Math.round(r/10)).slice(-2);this.recordTimeEl.innerText=l,Object(_e.b)(a)};a()}).catch(e=>{switch(e.name){case"NotAllowedError":nt("Please allow access to your microphone");break;case"NotReadableError":nt(e.message);break;default:console.error("Recorder start error:",e,e.name,e.message),nt(e.message)}this.chatInput.classList.remove("is-recording","is-locked")})}},this.onHelperCancel=e=>{if(e&&Object(c.a)(e),this.willSendWebPage){const e=this.lastUrl;let t=!1;if(this.helperType&&(this.helperFunc(),t=!0),this.lastUrl=e,this.noWebPage=!0,this.willSendWebPage=null,t)return}this.clearHelper(),this.updateSendBtn()},this.onHelperClick=e=>{if(Object(c.a)(e),Object(Ce.a)(e.target,"reply-wrapper"))if("forward"===this.helperType){if(this.helperWaitingForward)return;this.helperWaitingForward=!0;const e=this.helperFunc;this.clearHelper(),this.updateSendBtn();let t=!1;new Ds(Object(L.a)(this.forwarding),()=>{t=!0},()=>{this.helperWaitingForward=!1,t||e()})}else"reply"===this.helperType?this.chat.setMessageId(this.replyToMsgId):"edit"===this.helperType&&this.chat.setMessageId(this.editMsgId)},this.listenerSetter=new H.a}construct(){this.chatInput=document.createElement("div"),this.chatInput.classList.add("chat-input"),this.chatInput.style.display="none",this.inputContainer=document.createElement("div"),this.inputContainer.classList.add("chat-input-container"),this.rowsWrapper=document.createElement("div"),this.rowsWrapper.classList.add("rows-wrapper","chat-input-wrapper");const e=na();this.rowsWrapper.append(e);const t=this.fakeRowsWrapper=document.createElement("div");t.classList.add("fake-wrapper","fake-rows-wrapper");const s=document.createElement("div");s.classList.add("fake-wrapper","fake-selection-wrapper"),this.inputContainer.append(this.rowsWrapper,t,s),this.chatInput.append(this.inputContainer),this.goDownBtn=$({icon:"arrow_down",className:"bubbles-corner-button bubbles-go-down hide"}),this.inputContainer.append(this.goDownBtn),Object(l.b)(this.goDownBtn,e=>{Object(c.a)(e),this.chat.bubbles.onGoDownClick()},{listenerSetter:this.listenerSetter})}constructPeerHelpers(){this.replyElements.container=document.createElement("div"),this.replyElements.container.classList.add("reply-wrapper"),this.replyElements.cancelBtn=N("close reply-cancel"),this.replyElements.container.append(this.replyElements.cancelBtn),this.newMessageWrapper=document.createElement("div"),this.newMessageWrapper.classList.add("new-message-wrapper"),this.btnToggleEmoticons=N("none toggle-emoticons",{noRipple:!0}),this.inputMessageContainer=document.createElement("div"),this.inputMessageContainer.classList.add("input-message-container"),"chat"===this.chat.type&&(this.goDownUnreadBadge=document.createElement("span"),this.goDownUnreadBadge.classList.add("badge","badge-24","badge-primary"),this.goDownBtn.append(this.goDownUnreadBadge),this.goMentionBtn=$({icon:"mention",className:"bubbles-corner-button bubbles-go-mention"}),this.goMentionUnreadBadge=document.createElement("span"),this.goMentionUnreadBadge.classList.add("badge","badge-24","badge-primary"),this.goMentionBtn.append(this.goMentionUnreadBadge),this.inputContainer.append(this.goMentionBtn),Object(l.b)(this.goMentionBtn,e=>{Object(c.a)(e),this.appMessagesManager.goToNextMention(this.chat.peerId)},{listenerSetter:this.listenerSetter}),this.btnScheduled=N("scheduled btn-scheduled float hide",{noRipple:!0}),Object(l.b)(this.btnScheduled,e=>{this.appImManager.openScheduled(this.chat.peerId)},{listenerSetter:this.listenerSetter}),this.listenerSetter.add(a.default)("scheduled_new",({peerId:e})=>{this.chat.peerId===e&&this.btnScheduled.classList.remove("hide")}),this.listenerSetter.add(a.default)("scheduled_delete",({peerId:e})=>{this.chat.peerId===e&&this.appMessagesManager.getScheduledMessages(this.chat.peerId).then(e=>{this.btnScheduled.classList.toggle("hide",!e.length)})}),this.btnToggleReplyMarkup=N("botcom toggle-reply-markup float hide",{noRipple:!0}),this.replyKeyboard=new Da({appendTo:this.rowsWrapper,listenerSetter:this.listenerSetter,appMessagesManager:this.appMessagesManager,btnHover:this.btnToggleReplyMarkup,chatInput:this}),this.listenerSetter.add(this.replyKeyboard)("open",()=>this.btnToggleReplyMarkup.classList.add("active")),this.listenerSetter.add(this.replyKeyboard)("close",()=>this.btnToggleReplyMarkup.classList.remove("active"))),this.attachMenuButtons=[{icon:"image",text:"Chat.Input.Attach.PhotoOrVideo",onClick:()=>{this.fileInput.value="";const e=[...g].join(", ");this.fileInput.setAttribute("accept",e),this.willAttachType="media",this.fileInput.click()},verify:(e,t)=>this.appMessagesManager.canSendToPeer(e,t,"send_media")},{icon:"document",text:"Chat.Input.Attach.Document",onClick:()=>{this.fileInput.value="",this.fileInput.removeAttribute("accept"),this.willAttachType="document",this.fileInput.click()},verify:(e,t)=>this.appMessagesManager.canSendToPeer(e,t,"send_media")},{icon:"poll",text:"Poll",onClick:()=>{new ba(this.chat).show()},verify:(e,t)=>e<0&&this.appMessagesManager.canSendToPeer(e,t,"send_polls")}],this.attachMenu=Ie({noRipple:!0,listenerSetter:this.listenerSetter},"top-left",this.attachMenuButtons),this.attachMenu.classList.add("attach-file","tgico-attach"),this.attachMenu.classList.remove("tgico-more"),this.recordTimeEl=document.createElement("div"),this.recordTimeEl.classList.add("record-time"),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=!0,this.fileInput.style.display="none",this.newMessageWrapper.append(...[this.btnToggleEmoticons,this.inputMessageContainer,this.btnScheduled,this.btnToggleReplyMarkup,this.attachMenu,this.recordTimeEl,this.fileInput].filter(Boolean)),this.rowsWrapper.append(this.replyElements.container),this.autocompleteHelperController=new _a,this.stickersHelper=new Ea(this.rowsWrapper,this.autocompleteHelperController),this.emojiHelper=new xa(this.rowsWrapper,this.autocompleteHelperController,this,this.appEmojiManager),this.commandsHelper=new Oa(this.rowsWrapper,this.autocompleteHelperController,this,this.chat.appProfileManager,this.chat.appUsersManager),this.mentionsHelper=new Fa(this.rowsWrapper,this.autocompleteHelperController,this,this.chat.appProfileManager,this.chat.appUsersManager),this.inlineHelper=new Ra(this.rowsWrapper,this.autocompleteHelperController,this.chat,this.appUsersManager,this.appInlineBotsManager),this.rowsWrapper.append(this.newMessageWrapper),this.btnCancelRecord=N("delete danger btn-circle z-depth-1 btn-record-cancel"),this.btnSendContainer=document.createElement("div"),this.btnSendContainer.classList.add("btn-send-container"),this.recordRippleEl=document.createElement("div"),this.recordRippleEl.classList.add("record-ripple"),this.btnSend=N("none btn-circle z-depth-1 btn-send animated-button-icon"),this.btnSend.insertAdjacentHTML("afterbegin",'\n <span class="tgico tgico-send"></span>\n <span class="tgico tgico-schedule"></span>\n <span class="tgico tgico-check"></span>\n <span class="tgico tgico-microphone"></span>\n '),this.btnSendContainer.append(this.recordRippleEl,this.btnSend),"scheduled"!==this.chat.type&&(this.sendMenu=new pa({onSilentClick:()=>{this.sendSilent=!0,this.sendMessage()},onScheduleClick:()=>{this.scheduleSending(void 0)},listenerSetter:this.listenerSetter,openSide:"top-left",onContextElement:this.btnSend,onOpen:()=>!this.isInputEmpty()}),this.btnSendContainer.append(this.sendMenu.sendMenu)),this.inputContainer.append(this.btnCancelRecord,this.btnSendContainer),Jn.attachButtonListener(this.btnToggleEmoticons,this.listenerSetter),this.listenerSetter.add(Jn)("open",this.onEmoticonsOpen),this.listenerSetter.add(Jn)("close",this.onEmoticonsClose),this.attachMessageInputField(),this.listenerSetter.add(a.default)("settings_updated",()=>{(this.stickersHelper||this.emojiHelper)&&(this.previousQuery="",this.checkAutocomplete()),this.messageInputField&&this.messageInputField.onFakeInput()}),this.listenerSetter.add(a.default)("draft_updated",({peerId:e,threadId:t,draft:s,force:i})=>{this.chat.threadId===t&&this.chat.peerId===e&&this.setDraft(s,!0,i)}),this.listenerSetter.add(a.default)("peer_changing",e=>{this.chat===e&&this.saveDraft()}),"scheduled"===this.chat.type?this.listenerSetter.add(a.default)("scheduled_delete",({peerId:e,mids:t})=>{this.chat.peerId===e&&t.includes(this.editMsgId)&&this.onMessageSent()}):this.listenerSetter.add(a.default)("history_delete",({peerId:e,msgs:t})=>{this.chat.peerId===e&&(t.has(this.editMsgId)&&this.onMessageSent(),this.replyToMsgId&&t.has(this.replyToMsgId)&&this.clearHelper("reply"))});try{this.recorder=new ha.a({encoderSampleRate:48e3,monitorGain:0,numberOfChannels:1,recordingGain:1,reuseWorker:!0})}catch(e){console.error("Recorder constructor error:",e)}this.updateSendBtn(),this.listenerSetter.add(this.fileInput)("change",e=>{let t=e.target.files;t.length&&(new fa(this.chat,Array.from(t).slice(),this.willAttachType),this.fileInput.value="")},!1),Object(l.b)(this.btnSend,this.onBtnSendClick,{listenerSetter:this.listenerSetter,touchMouseDown:!0}),this.recorder&&(Object(l.b)(this.btnCancelRecord,this.onCancelRecordClick,{listenerSetter:this.listenerSetter}),this.recorder.onstop=()=>{this.recording=!1,this.chatInput.classList.remove("is-recording","is-locked"),this.updateSendBtn(),this.recordRippleEl.style.transform=""},this.recorder.ondataavailable=e=>{if(this.releaseMediaPlayback&&(this.releaseMediaPlayback(),this.releaseMediaPlayback=void 0),this.recordingOverlayListener&&(this.listenerSetter.remove(this.recordingOverlayListener),this.recordingOverlayListener=void 0),this.recordingNavigationItem&&(B.a.removeItem(this.recordingNavigationItem),this.recordingNavigationItem=void 0),this.recordCanceled)return;const{peerId:t,threadId:s}=this.chat,i=this.replyToMsgId,n=(Date.now()-this.recordStartTime)/1e3|0,a=new Blob([e],{type:"audio/ogg"});ua.a.decode(e,!0).then(e=>{ua.a.setKeepAlive(!1),this.appMessagesManager.sendFile(t,a,{isVoiceMessage:!0,isMedia:!0,duration:n,waveform:e.waveform,objectURL:e.url,replyToMsgId:i,threadId:s,clearDraft:!0}),this.onMessageSent(!1,!0)})}),Object(l.b)(this.replyElements.cancelBtn,this.onHelperCancel,{listenerSetter:this.listenerSetter}),Object(l.b)(this.replyElements.container,this.onHelperClick,{listenerSetter:this.listenerSetter}),this.saveDraftDebounced=ot(()=>this.saveDraft(),2500,!1,!0)}constructPinnedHelpers(){const e=document.createElement("div");e.classList.add("pinned-container"),this.pinnedControlBtn=Object(U.a)("btn-primary btn-transparent text-bold pinned-container-button",{icon:"unpin"}),e.append(this.pinnedControlBtn);const t=e.cloneNode(!0);this.fakePinnedControlBtn=t.firstChild,this.fakeRowsWrapper.append(t),this.listenerSetter.add(this.pinnedControlBtn)("click",()=>{const e=this.chat.peerId;new aa(e,0,!0,()=>{this.chat.appImManager.setPeer(0);const e=this.chat.appImManager.chat;e.topbar.pinnedMessage&&e.topbar.pinnedMessage.pinnedMessageContainer.toggle(!0)})}),this.rowsWrapper.append(e),this.chatInput.classList.add("type-pinned"),this.rowsWrapper.classList.add("is-centered")}getReadyToSend(e){return"scheduled"===this.chat.type?(this.scheduleSending(e),!0):(e(),!1)}setUnreadCount(){const e=this.appMessagesManager.getDialogOnly(this.chat.peerId),t=null==e?void 0:e.unread_count;if(this.goDownUnreadBadge.innerText=""+(t||""),this.goDownUnreadBadge.classList.toggle("badge-gray",this.appNotificationsManager.isPeerLocalMuted(this.chat.peerId,!0)),this.goMentionUnreadBadge&&"chat"===this.chat.type){const t=!!(null==e?void 0:e.unread_mentions_count);this.goMentionUnreadBadge.innerText=t?""+e.unread_mentions_count:"",this.goMentionBtn.classList.toggle("is-visible",t)}}saveDraft(){if(!this.chat.peerId||this.editMsgId||"scheduled"===this.chat.type)return;const{value:e,entities:t}=Object(ma.a)(this.messageInputField.input);let s;(e.length||this.replyToMsgId)&&(s={_:"draftMessage",date:Object(re.f)(!0)+this.serverTimeManager.serverTimeOffset,message:e,entities:t.length?t:void 0,pFlags:{no_webpage:this.noWebPage},reply_to_msg_id:this.replyToMsgId}),this.appDraftsManager.syncDraft(this.chat.peerId,this.chat.threadId,s)}destroy(){this.listenerSetter.removeAll()}cleanup(e=!0){this.chat.peerId||(this.chatInput.style.display="none",this.goDownBtn.classList.add("hide")),Ns(),this.lastTimeType=0,this.messageInput&&(this.clearInput(),e&&this.clearHelper())}setDraft(e,t=!0,s=!1){return!(!s&&!Object(ga.a)(this.messageInput)||"scheduled"===this.chat.type)&&(!(!e&&!(e=this.appDraftsManager.getDraft(this.chat.peerId,this.chat.threadId)))&&((this.messageInputField.value!==e.rMessage||this.replyToMsgId!==e.reply_to_msg_id)&&(this.clearHelper(),this.noWebPage=e.pFlags.no_webpage,e.reply_to_msg_id&&this.initMessageReply(e.reply_to_msg_id),this.setInputValue(e.rMessage,t,t),!0)))}finishPeerChange(){const e=this.chat.peerId;this.chatInput.style.display="";const t=this.appPeersManager.isBroadcast(e);if(this.goDownBtn.classList.toggle("is-broadcast",t),this.goDownBtn.classList.remove("hide"),this.goDownUnreadBadge&&this.setUnreadCount(),"pinned"===this.chat.type&&this.chatInput.classList.toggle("can-pin",this.appPeersManager.canPinMessage(e)),this.btnScheduled){this.btnScheduled.classList.add("hide");const t=this.chat.bubbles.getMiddleware();this.appMessagesManager.getScheduledMessages(e).then(e=>{t()&&this.btnScheduled.classList.toggle("hide",!e.length)})}this.replyKeyboard&&this.replyKeyboard.setPeer(e),this.sendMenu&&this.sendMenu.setPeerId(e),this.messageInput?this.updateMessageInput():this.pinnedControlBtn&&(this.appPeersManager.canPinMessage(this.chat.peerId)?(this.pinnedControlBtn.append(Object(A.i18n)("Chat.Input.UnpinAll")),this.fakePinnedControlBtn.append(Object(A.i18n)("Chat.Input.UnpinAll"))):(this.pinnedControlBtn.append(Object(A.i18n)("Chat.Pinned.DontShow")),this.fakePinnedControlBtn.append(Object(A.i18n)("Chat.Pinned.DontShow"))))}updateMessageInput(){const{peerId:e,threadId:t}=this.chat,s=this.appMessagesManager.canSendToPeer(e,t);this.chatInput.classList.add("no-transition"),this.chatInput.classList.toggle("is-hidden",!s),this.chatInput.offsetLeft,this.chatInput.classList.remove("no-transition");const i=A.default.weakMap.get(this.messageInput);if(i){let s;s=t?"Comment":this.appPeersManager.isBroadcast(e)?"ChannelBroadcast":this.appMessagesManager.isAnonymousSending(e)?"SendAnonymously":"Message",i.key!==s&&(i.key=s,i.update())}const n=this.attachMenuButtons.filter(s=>{const i=s.verify(e,t);return s.element.classList.toggle("hide",!i),i});s?(this.messageInput.setAttribute("contenteditable","true"),this.setDraft(void 0,!1),this.messageInput.innerHTML||this.messageInputField.onFakeInput()):this.messageInput.removeAttribute("contenteditable"),this.attachMenu.toggleAttribute("disabled",!n.length),this.attachMenu.classList.toggle("btn-disabled",!n.length),this.updateSendBtn()}attachMessageInputField(){const e=this.messageInputField;this.messageInputField=new F.b({placeholder:"Message",name:"message",animate:!0}),this.messageInputField.input.classList.replace("input-field-input","input-message-input"),this.messageInputField.inputFake.classList.replace("input-field-input","input-message-input"),this.messageInput=this.messageInputField.input,this.messageInput.classList.add("no-scrollbar"),this.attachMessageInputListeners(),Ha.a&&Object(Ha.b)(this.messageInput),e?(e.input.replaceWith(this.messageInputField.input),e.inputFake.replaceWith(this.messageInputField.inputFake)):this.inputMessageContainer.append(this.messageInputField.input,this.messageInputField.inputFake)}attachMessageInputListeners(){this.listenerSetter.add(this.messageInput)("keydown",e=>{if(Object(ka.a)(e))this.sendMessage();else if(e.ctrlKey||e.metaKey)this.handleMarkdownShortcut(e);else if(("PageUp"===e.key||"PageDown"===e.key)&&!e.shiftKey)if(e.preventDefault(),"PageUp"===e.key){const e=document.createRange(),t=window.getSelection();e.setStart(this.messageInput.childNodes[0]||this.messageInput,0),e.collapse(!0),t.removeAllRanges(),t.addRange(e)}else Object(va.a)(this.messageInput)}),pe.IS_TOUCH_SUPPORTED&&Object(l.b)(this.messageInput,e=>{this.appImManager.selectTab(1),Jn.toggle(!1)},{listenerSetter:this.listenerSetter}),this.listenerSetter.add(this.messageInput)("input",this.onMessageInput),this.listenerSetter.add(this.messageInput)("keyup",()=>{this.checkAutocomplete()}),"chat"!==this.chat.type&&"discussion"!==this.chat.type||this.listenerSetter.add(this.messageInput)("focusin",()=>{this.chat.bubbles.scrollable.loadedAll.bottom&&this.appMessagesManager.readAllHistory(this.chat.peerId,this.chat.threadId)})}applyMarkdown(e,t){const s={bold:"Bold",italic:"Italic",underline:"Underline",strikethrough:"Strikethrough",monospace:()=>document.execCommand("fontName",!1,"monospace"),link:t?()=>document.execCommand("createLink",!1,t):()=>document.execCommand("unlink",!1,null)};if(!s[e])return!1;const i=s[e],n=this.prepareDocumentExecute(),a=[];if(a.push(document.execCommand("styleWithCSS",!1,"true")),"monospace"===e){let t=!1;const s=window.getSelection();if(!s.isCollapsed){const i=s.getRangeAt(0),n=Ta.b[e],a=i.commonAncestorContainer;(a.parentNode.matches(n.match)||a instanceof HTMLElement&&a.matches(n.match))&&(t=!0)}t?a.push(document.execCommand("fontName",!1,"Roboto")):a.push("function"==typeof i?i():document.execCommand(i,!1,null))}else a.push("function"==typeof i?i():document.execCommand(i,!1,null));return a.push(document.execCommand("styleWithCSS",!1,"false")),n(),this.appImManager.markupTooltip&&this.appImManager.markupTooltip.setActiveMarkupButton(),!0}insertAtCaret(e,t,s=!0){const{value:i,caretPos:n,entities:a}=Pa(this.messageInput),o=n>=0?n:i.length,r=i.substr(0,o),l=i.substr(o),c=s?r.match(Ua.AUTO_COMPLETE_REG_EXP):null,d=c?c.index+(c[0].length-c[2].length):r.length,h=r.slice(0,d)+e+l,u=Z.b.parseEntities(i);Z.b.mergeEntities(a,u);const p=t?Math.max(t.length,e.length):e.length,m=[];t&&(m.push(t),t.offset=d),m.push({_:"messageEntityCaret",length:0,offset:d+p});const g=p-(c?c[2].length:r.length);a.forEach(e=>{e.offset>=d&&(e.offset+=g)}),Z.b.mergeEntities(a,m),this.messageInputField.setValueSilently(Z.b.wrapDraftText(h,{entities:a}),!0);const b=this.messageInput.querySelector(".composer-sel");!function(e,t,s){if(e.focus(),!t||t.parentNode!=e||t.nextSibling||s||(e.removeChild(t),t=null),window.getSelection&&document.createRange){const i=document.createRange();t?i.selectNode(t):i.selectNodeContents(e),s||i.collapse(!1);const n=window.getSelection();n.removeAllRanges(),n.addRange(i)}}(this.messageInput,b),b.remove(),this.onMessageInput()}checkAutocomplete(e,t,s){if(void 0===e){const i=Pa(this.messageInputField.input,!0);e=i.value,t=i.caretPos,s=i.entities}if(-1===t&&(t=e.length),void 0===s){const t=Z.b.parseMarkdown(e,s,!0);s=Z.b.mergeEntities(s,Z.b.parseEntities(t))}if(e=e.substr(0,t),this.previousQuery===e)return;this.previousQuery=e;const i=e.match(Ua.AUTO_COMPLETE_REG_EXP);let n;if(i){const t=s[0];let o=i[2];const r=o[0];if(this.stickersHelper&&a.default.settings.stickers.suggest&&this.appMessagesManager.canSendToPeer(this.chat.peerId,this.chat.threadId,"send_stickers")&&"messageEntityEmoji"===(null==t?void 0:t._)&&t.length===e.length&&!t.offset)n=this.stickersHelper,this.stickersHelper.checkEmoticon(e);else if("@"===r){const e=this.chat.threadId?this.appMessagesIdsManager.getServerMessageId(this.chat.threadId):void 0;this.mentionsHelper.checkQuery(o,this.chat.peerId>0?0:this.chat.peerId,e)&&(n=this.mentionsHelper)}else i[1]||"/"!==r?a.default.settings.emoji.suggest&&(o=o.replace(/^\s*/,""),e.match(/^\s*:(.+):\s*$/)||e.match(/:[;!@#$%^&*()-=|]/)||!o||(n=this.emojiHelper,this.emojiHelper.checkQuery(o,r))):this.commandsHelper.checkQuery(o,this.chat.peerId)&&(n=this.commandsHelper)}n=this.checkInlineAutocomplete(e,n),this.autocompleteHelperController.hideOtherHelpers(n)}checkInlineAutocomplete(e,t){let s=!1;if(!t){const i=e.match(/^@([a-zA-Z\\d_]{3,32})\s/);if(i){const n=i[1],a=e.slice(i[0].length);s=i[0].length===e.length,t=this.inlineHelper,this.btnPreloader?Object(Xt.a)(this.btnPreloader,"show",!0,400):(this.btnPreloader=N("none btn-preloader float show disable-hover",{noRipple:!0}),Object(se.f)(this.btnPreloader,!0),this.inputMessageContainer.parentElement.insertBefore(this.btnPreloader,this.inputMessageContainer.nextSibling)),this.inlineHelper.checkQuery(this.chat.peerId,n,a).then(({user:e,renderPromise:t})=>{s&&e.bot_inline_placeholder&&(this.messageInput.dataset.inlinePlaceholder=e.bot_inline_placeholder),t.then(()=>{Object(Xt.a)(this.btnPreloader,"show",!1,400)})}).catch(Ae.a)}}return s||delete this.messageInput.dataset.inlinePlaceholder,t!==this.inlineHelper&&this.btnPreloader&&Object(Xt.a)(this.btnPreloader,"show",!1,400),t}clearInput(e=!0,t=!0,s=""){if(document.activeElement===this.messageInput&&h.IS_MOBILE_SAFARI){const e=document.createElement("input");document.body.append(e),Object(ja.a)(e),this.messageInputField.setValueSilently(s),Object(ja.a)(this.messageInput),e.remove()}else this.messageInputField.setValueSilently(s);pe.IS_TOUCH_SUPPORTED||(this.canRedoFromHTML="",this.undoHistory.length=0,this.executedHistory.length=0,this.canUndoFromHTML="");let i=!1;e&&(i=this.setDraft(void 0,!1)),!i&&t&&this.onMessageInput()}isInputEmpty(){return Object(ga.a)(this.messageInput)}updateSendBtn(){let e;const t=this.isInputEmpty();e=this.editMsgId?"edit":!this.recorder||this.recording||!t||this.forwarding?"scheduled"===this.chat.type?"schedule":"send":"record",["send","record","edit","schedule"].forEach(t=>{this.btnSend.classList.toggle(t,e===t)}),this.btnScheduled&&this.btnScheduled.classList.toggle("show",t),this.btnToggleReplyMarkup&&this.btnToggleReplyMarkup.classList.toggle("show",t)}onMessageSent(e=!0,t){"scheduled"!==this.chat.type&&this.appMessagesManager.readAllHistory(this.chat.peerId,this.chat.threadId,!0),this.scheduleDate=void 0,this.sendSilent=void 0;const s=this.messageInputField.value;Z.b.parseEntities(s).filter(e=>"messageEntityEmoji"===e._).forEach(e=>{const t=Object(ne.a)(e.unicode);this.appEmojiManager.pushRecentEmoji(t)}),e&&(this.lastUrl="",delete this.noWebPage,this.willSendWebPage=null,this.clearInput()),(t||e)&&this.clearHelper(),this.updateSendBtn()}sendMessage(e=!1){if("scheduled"===this.chat.type&&!e&&!this.editMsgId)return void this.scheduleSending();const{value:t,entities:s}=Object(ma.a)(this.messageInputField.input);if(this.editMsgId){const e=this.chat.getMessage(this.editMsgId);if(!t.trim()&&!e.media)return void new Bs(this.chat.peerId,[this.editMsgId],this.chat.type);this.appMessagesManager.editMessage(e,t,{entities:s,noWebPage:this.noWebPage})}else this.appMessagesManager.sendText(this.chat.peerId,t,{entities:s,replyToMsgId:this.replyToMsgId,threadId:this.chat.threadId,noWebPage:this.noWebPage,webPage:this.getWebPagePromise?void 0:this.willSendWebPage,scheduleDate:this.scheduleDate,silent:this.sendSilent,clearDraft:!0});if(this.forwarding){const e=Object(L.a)(this.forwarding),t=this.chat.peerId,s=this.sendSilent,i=this.scheduleDate;setTimeout(()=>{for(const n in e)this.appMessagesManager.forwardMessages(t,+n,e[n],{silent:s,scheduleDate:i})},0)}this.onMessageSent()}sendMessageWithDocument(e,t=!1,s=!1){var i;const n="sticker"===(e=this.appDocsManager.getDoc(e)).type?"send_stickers":"gif"===e.type?"send_gifs":"send_media";return this.chat.peerId<0&&!this.appMessagesManager.canSendToPeer(this.chat.peerId,this.chat.threadId,n)?(nt("Posting media content isn't allowed in this group."),!1):"scheduled"!==this.chat.type||t?!!e&&(this.appMessagesManager.sendFile(this.chat.peerId,e,{isMedia:!0,replyToMsgId:this.replyToMsgId,threadId:this.chat.threadId,silent:this.sendSilent,scheduleDate:this.scheduleDate,clearDraft:s||void 0}),this.onMessageSent(s,!0),"sticker"===e.type&&(null===(i=Jn.stickersTab)||void 0===i||i.pushRecentSticker(e)),!0):(this.scheduleSending(()=>this.sendMessageWithDocument(e,!0,s)),!1)}initMessageEditing(e){const t=this.chat.getMessage(e);let s=Z.b.wrapDraftText(t.message,{entities:t.totalEntities});const i=()=>{const n=this.appMessagesManager.wrapMessageForReply(t,void 0,[t.mid]);this.setTopInfo("edit",i,Object(A.i18n)("AccDescrEditing"),n,s,t),this.editMsgId=e,s=void 0};i()}initMessagesForward(e){const t=()=>{const s=Object.keys(e).map(e=>+e),i=new Set;let n=0;s.forEach(t=>{const s=e[t];s.forEach(e=>{var s;const n=this.appMessagesManager.getMessageByPeer(t,e);!(null===(s=n.fwd_from)||void 0===s?void 0:s.from_name)||n.fromId||n.fwdFromId?i.add(n.fromId):i.add(n.fwd_from.from_name)}),n+=s.length});const a=i.size>2,o=[...i].map(e=>"number"==typeof e?new ft.a({peerId:e,dialog:!1,onlyFirstName:a}).element:a?e.split(" ")[0]:e),r=document.createDocumentFragment();let l,c;if(o.length<3?r.append(...Object(A.join)(o,!1)):r.append(o[0],Object(A.i18n)("AndOther",[o.length-1])),1===s.length){const t=s[0],i=e[t];if(l=this.appMessagesManager.getMessageByPeer(t,i[0]),c=!!l.grouped_id,c){const e=this.appMessagesManager.getMidsByMessage(l);(e.length!==n||e.find(e=>!i.includes(e)))&&(c=!1)}}if(c||1===n){const i=e[s[0]],n=this.appMessagesManager.wrapMessageForReply(l,void 0,i);this.setTopInfo("forward",t,r,n)}else this.setTopInfo("forward",t,r,Object(A.i18n)("ForwardedMessageCount",[n]));this.forwarding=e};t()}initMessageReply(e){let t=this.chat.getMessage(e);const s=()=>{let i;"messageEmpty"===t._?(i=Object(A.i18n)("Loading"),this.chat.appMessagesManager.wrapSingleMessage(this.chat.peerId,e).then(()=>{this.replyToMsgId===e&&(t=this.chat.getMessage(e),"messageEmpty"===t._?this.clearHelper("reply"):s())})):i=new ft.a({peerId:t.fromId,dialog:!1}).element,this.setTopInfo("reply",s,i,t&&t.message,void 0,t),this.replyToMsgId=e};s()}clearHelper(e){"edit"===this.helperType&&"edit"!==e&&this.clearInput(),e&&(this.lastUrl="",delete this.noWebPage,this.willSendWebPage=null),this.replyToMsgId=void 0,this.forwarding=void 0,this.editMsgId=void 0,this.helperType=this.helperFunc=void 0,this.chat.container.classList.contains("is-helper-active")&&(B.a.removeByType("input-helper"),this.chat.container.classList.remove("is-helper-active"))}setInputValue(e,t=!0,s=!0){e||(e=""),t?this.clearInput(!1,!1,e):this.messageInputField.setValueSilently(e),Object(_e.b)(()=>{s&&Object(va.a)(this.messageInput),this.onMessageInput(),this.messageInput.scrollTop=this.messageInput.scrollHeight})}setTopInfo(e,t,s="",i="",n,a){"webpage"!==e&&(this.clearHelper(e),this.helperType=e,this.helperFunc=t);const o=this.replyElements.container;"DIV"===o.lastElementChild.tagName&&o.lastElementChild.remove(),o.append(Es(s,i,a)),this.chat.container.classList.add("is-helper-active"),h.IS_MOBILE||B.a.pushItem({type:"input-helper",onPop:()=>{this.onHelperCancel()}}),void 0!==n&&this.setInputValue(n),setTimeout(()=>{this.updateSendBtn()},0)}}Ua.AUTO_COMPLETE_REG_EXP=/(\s|^)((?:(?:@|^\/)\S*)|(?::|^[^:@\/])(?!.*[:@\/]).*)$/;const Na=["is-pinned-message-shown","is-pinned-audio-shown"];class za{constructor(e){this.floating=!1,Object(L.g)(this,e);const{divAndCaption:t,className:s}=this;t.container.classList.add("pinned-container","hide"),t.title.classList.add("pinned-container-title"),t.subtitle.classList.add("pinned-container-subtitle"),t.content.classList.add("pinned-container-content"),this.btnClose=document.createElement("button"),this.btnClose.classList.add("pinned-container-close",`pinned-${s}-close`,"btn-icon","tgico-close"),this.wrapper=document.createElement("div"),this.wrapper.classList.add("pinned-container-wrapper"),Object(ie.ripple)(this.wrapper),this.wrapperUtils=document.createElement("div"),this.wrapperUtils.classList.add("pinned-container-wrapper-utils"),this.wrapperUtils.append(this.btnClose),this.wrapper.append(...Array.from(t.container.children),this.wrapperUtils),t.container.append(this.wrapper),this.attachOnCloseEvent(this.btnClose)}attachOnCloseEvent(e){Object(l.b)(e,e=>{Object(c.a)(e),((this.onClose?this.onClose():null)||Promise.resolve(!0)).then(e=>{e&&this.toggle(!0)})},{listenerSetter:this.listenerSetter})}toggle(e){const t=this.divAndCaption.container.classList.contains("hide");if(void 0===e)e=!t;else if(e===t)return;const s=this.chat.bubbles.scrollable,i=(this.floating||v.b.isMobile)&&!e,n=i||this.divAndCaption.container.classList.contains("is-floating")?s.scrollTop:void 0;this.divAndCaption.container.classList.toggle("is-floating",i),this.divAndCaption.container.classList.toggle("hide",e),this.topbar.container.classList.toggle("is-pinned-floating",i),this.topbar.container.classList.toggle(`is-pinned-${this.className}-shown`,!e);const a=Na.filter(e=>this.topbar.container.classList.contains(e)),o=e?0:1;void 0!==n&&a.length<=o&&(s.scrollTop=n+52*(e?-1:1)),this.topbar.setFloating(),this.topbar.setUtilsWidth()}fill(e,t,s){this.divAndCaption.container.dataset.peerId=""+s.peerId,this.divAndCaption.container.dataset.mid=""+s.mid,this.divAndCaption.fill(e,t,s),this.topbar.setUtilsWidth()}}class Va extends za{constructor(e,t,s){super({topbar:e,chat:t,listenerSetter:e.listenerSetter,className:"audio",divAndCaption:new He("pinned-audio",(e,t)=>{Object(x.a)(this.divAndCaption.title,e),Object(x.a)(this.divAndCaption.subtitle,t)}),onClose:()=>{fe.stop()},floating:!0}),this.topbar=e,this.chat=t,this.appMessagesManager=s,this.divAndCaption.border.remove();const i=N("pprevious active",{noRipple:!0}),n=N("nnext active",{noRipple:!0});i.innerHTML='<svg class="missing-icon" viewBox="0 0 24 24" preserveAspectRatio="xMidYMid meet"><g><path class="missing-icon-path" d="M6 6h2v12H6zm3.5 6l8.5 6V6z"></path></g></svg>',n.innerHTML='<svg class="missing-icon" viewBox="0 0 24 24" preserveAspectRatio="xMidYMid meet"><g><path class="missing-icon-path" d="M6 18l8.5-6L6 6v12zM16 6v12h2V6h-2z"></path></g></svg>';const o=(e,t)=>{Object(l.b)(e,e=>{Object(c.a)(e),t()},{listenerSetter:this.topbar.listenerSetter})};o(i,()=>{fe.previous()}),o(n,()=>{fe.next()}),this.toggleEl=N("",{noRipple:!0}),this.toggleEl.classList.add("active","pinned-audio-ico","tgico"),o(this.toggleEl,()=>{fe.toggle()}),this.wrapper.prepend(this.wrapper.firstElementChild,i,this.toggleEl,n),this.volumeSelector=new Te(this.listenerSetter,!0);const r=document.createElement("div");r.classList.add("progress-line-container"),r.append(this.volumeSelector.container);const d=document.createElement("div");d.classList.add("pinned-audio-volume-tunnel"),this.volumeSelector.btn.classList.add("pinned-audio-volume","active"),this.volumeSelector.btn.prepend(d),this.volumeSelector.btn.append(r),this.wrapperUtils.prepend(this.volumeSelector.btn);const h=document.createElement("div");h.classList.add("pinned-audio-progress-wrapper"),this.progressLine=new ke(void 0,void 0,!0,!0),this.progressLine.container.classList.add("pinned-audio-progress"),h.append(this.progressLine.container),this.wrapper.insertBefore(h,this.wrapperUtils),this.topbar.listenerSetter.add(a.default)("media_play",({doc:e,message:t,media:s})=>{let i,n;"voice"===e.type||"round"===e.type?(i=new ft.a({peerId:t.fromId}).element,n=Object(re.c)(t.date)):(i=e.audioTitle||e.fileName,n=e.audioPerformer||Object(A.i18n)("AudioUnknownArtist")),this.progressLine.setMedia(s),this.fill(i,n,t),this.toggleEl.classList.add("flip-icon"),this.toggle(!1)}),this.topbar.listenerSetter.add(a.default)("media_pause",()=>{this.toggleEl.classList.remove("flip-icon")}),this.topbar.listenerSetter.add(a.default)("media_stop",()=>{this.toggle(!0)})}}var Wa;!function(e){e[e.ONE=32]="ONE",e[e.TWO=15]="TWO",e[e.THREE=10]="THREE",e[e.FOUR=8]="FOUR",e[e.MORE=8]="MORE"}(Wa||(Wa={}));class Ka{constructor(){this.drawRect=(e,t,s,i,n)=>`M${e},${t+n}a${n},${n},0,0,1,${s},0v${i-2*n}a${n},${n},0,0,1,${-s},0Z`,this.getClipPath=(e,t,s)=>{let i="";if(2===s)i=this.drawRect(0,0,2,t,1)+this.drawRect(0,t+2,2,t,1);else for(let e=0;e<s;++e)i+=this.drawRect(0,(t+1)*e,2,t,1);return this.clipPath||(this.clipPath=document.createElementNS("http://www.w3.org/2000/svg","clipPath"),this.path=document.createElementNS("http://www.w3.org/2000/svg","path"),this.clipPath.append(this.path)),this.clipPath.id=e,this.path.setAttributeNS(null,"d",i),this.clipPath},this.getBarHeight=(e,t)=>{let s;return e<=1?s=Wa.ONE:2===e?s=Wa.TWO:3===e?s=Wa.THREE:4===e?s=Wa.FOUR:e>3&&(s=Wa.MORE),s},this.getMarkHeight=(e,t)=>{let s;return e<=1?s=Wa.ONE:2===e?s=Wa.TWO:3===e?s=Wa.THREE:4===e?s=Wa.FOUR:e>3&&(s=Wa.MORE),s},this.getMarkTranslateY=(e,t,s)=>1===s?0:2===s?e?t+1:0:3===s?e?1===e?t+1:2*t+2+1:0:(t+1)*e,this.getTrackTranslateY=(e,t,s,i)=>t<=4||e<=1?0:e>=t-2?i-Wa.ONE-s:(e-2)*s+1*e,this.getTrackHeight=(e,t)=>e<=3?Wa.ONE:t*e+1*(e-1)}render(e,t){if(this.border||(this.border=document.createElement("div"),this.border.classList.add("pinned-message-border"),this.wrapper=document.createElement("div"),this.border.append(this.wrapper)),1===e)return this.count!==e&&(this.wrapper.className="pinned-message-border-wrapper-1",this.border.classList.remove("pinned-message-border-mask"),this.wrapper.innerHTML=this.wrapper.style.cssText=""),this.border;const s=this.getBarHeight(e,t),i=this.getMarkHeight(e,t),n=this.getTrackHeight(e,s),a="clipPath_"+e,o=this.getClipPath(a,s,e),r=this.getMarkTranslateY(t,s,e),l=this.getTrackTranslateY(t,e,s,n);return this.border.classList.toggle("pinned-message-border-mask",e>4),t<=1?(this.border.classList.add("mask-bottom"),this.border.classList.remove("mask-top")):t>=e-2?(this.border.classList.add("mask-top"),this.border.classList.remove("mask-bottom")):this.border.classList.add("mask-top","mask-bottom"),this.wrapper.className="pinned-message-border-wrapper",this.wrapper.style.cssText=`clip-path: url(#${a}); width: 2px; height: ${n}px; transform: translateY(-${l}px);`,this.svg||(this.svg=document.createElementNS("http://www.w3.org/2000/svg","svg"),this.svg.setAttributeNS(null,"height","0"),this.svg.setAttributeNS(null,"width","0"),this.defs=document.createElementNS("http://www.w3.org/2000/svg","defs"),this.defs.append(o),this.svg.append(this.defs),this.mark=document.createElement("div"),this.mark.classList.add("pinned-message-border-mark")),this.svg.parentElement||this.wrapper.append(this.svg,this.mark),this.mark.style.cssText=`height: ${i}px; transform: translateY(${r}px);`,this.count=e,this.index=t,this.border}}var Ga=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class qa{constructor(){this.rows={},this.container=document.createElement("div"),this.container.className=qa.BASE_CLASS}getRow(e,t=!1){if(this.rows[e])return this.rows[e].element;const s=document.createElement("div"),i=!Object.keys(this.rows).length&&!t;return s.className=qa.BASE_CLASS+"-row"+(i?"":" is-hiding hide"),this.rows[e]={element:s,new:!0},this.container.append(s),s}clearRow(e){this.rows[e]&&(this.rows[e].element.remove(),delete this.rows[e])}clearRows(e){this.clearTimeout&&clearTimeout(this.clearTimeout),this.clearTimeout=window.setTimeout(()=>{for(const t in this.rows)+t!==e&&this.clearRow(+t)},qa.DURATION)}setNewRow(e,t=!1){const s=this.rows[e];s.new&&(t?(s.element.classList.remove("hide"),s.element.offsetLeft):s.element.classList.remove("is-hiding","hide"),delete s.new),this.clearRows(e)}animate(e,t,s=e>t,i=!1){if(e===t)return this.setNewRow(e);const n=this.rows[e],a=this.rows[t];if(!a&&!i)return this.setNewRow(e);const o=["from-top","from-bottom"];s||o.reverse(),n.element.classList.add(o[0]),n.element.classList.remove(o[1]),a&&(a.element.classList.add(o[1]),a.element.classList.remove(o[0])),n.new&&this.setNewRow(e,!0),n.element.classList.toggle("is-hiding",!1),a&&a.element.classList.toggle("is-hiding",!0),this.clearRows(e)}}qa.DURATION=200,qa.BASE_CLASS="animated-super";class Qa{constructor(e=!1){this.reverse=e,this.decimals=[],this.previousNumber=0,this.container=document.createElement("div"),this.container.className=Qa.BASE_CLASS}getDecimal(e){if(this.decimals[e])return this.decimals[e];const t=document.createElement("div");t.className=Qa.BASE_CLASS+"-decimal";const s=document.createElement("div");s.className=Qa.BASE_CLASS+"-decimal-placeholder";const i=new qa;return i.container.className=Qa.BASE_CLASS+"-decimal-wrapper",t.append(s,i.container),this.container.append(t),this.decimals[e]={container:t,placeholder:s,animatedSuper:i}}clear(e){this.clearTimeout&&clearTimeout(this.clearTimeout);const t=(""+e).length;t>=this.decimals.length||(this.clearTimeout=window.setTimeout(()=>{this.decimals.splice(t,this.decimals.length-t).forEach(e=>{e.container.remove()})},qa.DURATION))}hideLeft(e){const t=(""+e).length;this.decimals.slice(t).forEach(t=>{const s=+t.placeholder.innerText||0;t.animatedSuper.getRow(Qa.EMPTY_INDEX,!0);t.animatedSuper.animate(Qa.EMPTY_INDEX,s,this.reverse?e<this.previousNumber:e>this.previousNumber,!0)}),this.clear(e)}setCount(e){const t=Array.from(""+this.previousNumber).map(e=>+e);Array.from(""+e).map(e=>+e).forEach((s,i)=>{var n;const a=this.getDecimal(i),o=a.animatedSuper.getRow(s,!0),r=null!==(n=t[i])&&void 0!==n?n:Qa.EMPTY_INDEX;o.innerText=a.placeholder.innerText=""+s,a.animatedSuper.animate(s,r,this.reverse?e<this.previousNumber:e>this.previousNumber,!0)}),this.hideLeft(e),this.previousNumber=e}}Qa.EMPTY_INDEX=-1,Qa.BASE_CLASS="animated-counter";class $a{constructor(e,t,s,i){this.topbar=e,this.chat=t,this.appMessagesManager=s,this.appPeersManager=i,this.pinnedMaxMid=0,this.pinnedMid=0,this.pinnedIndex=-1,this.wasPinnedIndex=0,this.wasPinnedMediaIndex=0,this.locked=!1,this.waitForScrollBottom=!1,this.count=0,this.mids=[],this.offsetIndex=0,this.loading=!1,this.loadedBottom=!1,this.loadedTop=!1,this.scrollDownListenerSetter=null,this.hidden=!1,this.getCurrentIndexPromise=null,this.isStatic=!1,this.debug=!1,this.listenerSetter=new H.a;const n=new Ne("pinned-message");this.pinnedMessageContainer=new za({topbar:e,chat:t,listenerSetter:this.listenerSetter,className:"message",divAndCaption:n,onClose:()=>Ga(this,void 0,void 0,(function*(){return i.canPinMessage(this.topbar.peerId)?new aa(this.topbar.peerId,this.pinnedMid,!0):new aa(this.topbar.peerId,0,!0),!1}))}),this.pinnedMessageBorder=new Ka,n.border.replaceWith(this.pinnedMessageBorder.render(1,0)),this.animatedSubtitle=new qa,n.subtitle.append(this.animatedSubtitle.container),this.animatedMedia=new qa,this.animatedMedia.container.classList.add("pinned-message-media-container"),n.content.prepend(this.animatedMedia.container),this.animatedCounter=new Qa(!0),n.title.append(Object(A.i18n)("PinnedMessage")," ",this.animatedCounter.container);const o=this.pinnedMessageContainer.btnClose.cloneNode(!0);this.pinnedMessageContainer.attachOnCloseEvent(o),n.container.prepend(o),this.btnOpen=N("pinlist pinned-container-close pinned-message-pinlist",{noRipple:!0}),this.pinnedMessageContainer.wrapperUtils.prepend(this.btnOpen),Object(l.b)(this.btnOpen,e=>{Object(c.a)(e),this.topbar.openPinned(!0)},{listenerSetter:this.listenerSetter}),this.listenerSetter.add(a.default)("peer_pinned_messages",({peerId:e})=>{e===this.topbar.peerId&&(this.hidden&&this.pinnedMessageContainer.toggle(this.hidden=!1),this.loadedTop=this.loadedBottom=!1,this.pinnedIndex=-1,this.pinnedMid=0,this.count=0,this.mids=[],this.offsetIndex=0,this.pinnedMaxMid=0,this.setCorrectIndex(0))}),this.listenerSetter.add(a.default)("peer_pinned_hidden",({peerId:e})=>{e===this.topbar.peerId&&this.pinnedMessageContainer.toggle(this.hidden=!0)}),this.setPinnedMessage=ot(()=>this._setPinnedMessage(),100,!0,!0),this.isStatic="discussion"===this.chat.type}destroy(){this.pinnedMessageContainer.divAndCaption.container.remove(),this.pinnedMessageContainer.toggle(!0),this.listenerSetter.removeAll(),this.unsetScrollDownListener(!1)}setCorrectIndex(e){if(this.isStatic)return;if(this.locked||this.hidden)return;if((this.loadedBottom||this.loadedTop)&&!this.count)return;let t=this.chat.bubbles.getBubbleByPoint("bottom");if(!t)return;const s=t.dataset.mid;t&&void 0!==s&&this.testMid(+s,e)}testMid(e,t){if(this.isStatic)return;if(this.hidden)return;let s=this.mids.findIndex(t=>t<=e);if(-1===s||this.isNeededMore(s)){if(!(this.loadedTop&&e<this.mids[this.mids.length-1]))return void(this.getCurrentIndexPromise||(this.getCurrentIndexPromise=this.getCurrentIndex(e,void 0!==t)));s=this.mids.length-1+this.offsetIndex}else s+=this.offsetIndex;if(this.pinnedIndex!==s){if(this.waitForScrollBottom&&void 0!==t&&(0===this.pinnedIndex||this.pinnedIndex>s))return;this.pinnedIndex=s,this.pinnedMid=this.mids.find(t=>t<=e)||this.mids[this.mids.length-1],this.setPinnedMessage()}}isNeededMore(e){return this.count>$a.LOAD_COUNT&&(!this.loadedBottom&&e<=$a.LOAD_OFFSET||!this.loadedTop&&this.count-1-e<=$a.LOAD_OFFSET)}getCurrentIndex(e,t=!0){return Ga(this,void 0,void 0,(function*(){if(!this.loading){this.loading=!0;try{let s=!1;const i=[this.appMessagesManager.getSearch({peerId:this.topbar.peerId,inputFilter:{_:"inputMessagesFilterPinned"},maxId:e,limit:$a.LOAD_COUNT,backLimit:$a.LOAD_COUNT}).then(e=>(s=!0,e))];if(!this.pinnedMaxMid){const e=this.appMessagesManager.getPinnedMessage(this.topbar.peerId).then(e=>{e.maxId&&(this.pinnedMaxMid=e.maxId,!s&&t&&(this.mids=[this.pinnedMaxMid],this.count=e.count,this.pinnedIndex=0,this.pinnedMid=this.mids[0],this.setPinnedMessage()))});i.push(e)}const n=(yield Promise.all(i))[0];let a=n.history.findIndex(t=>t.mid<=e);-1===a&&(a=n.history.length),this.offsetIndex=n.offset_id_offset?n.offset_id_offset-a:0,this.mids=n.history.map(e=>e.mid).slice(),this.count=n.count,this.count||this.pinnedMessageContainer.toggle(!0),this.loadedTop=this.offsetIndex+this.mids.length===this.count,this.loadedBottom=!this.offsetIndex,this.debug&&this.chat.log("[PM]: getCurrentIndex result:",e,n,a,this.offsetIndex,this.loadedTop,this.loadedBottom)}catch(e){this.chat.log.error("[PM]: getCurrentIndex error",e)}this.loading=!1,this.locked?this.testMid(e):t&&this.setCorrectIndex(0),this.getCurrentIndexPromise=null}}))}setScrollDownListener(){this.waitForScrollBottom=!0,this.scrollDownListenerSetter||(this.scrollDownListenerSetter=new H.a,function(e,t,s,i){if(pe.IS_TOUCH_SUPPORTED){let n;const a={passive:!0};i.add(e)("touchstart",t=>{t.touches.length>1?r():(n=t.touches[0].clientY,i.add(e)("touchmove",o,a),i.add(e)("touchend",r,a))},a);const o=e=>{const i=e.touches[0].clientY,a=i<n;"bottom"===t&&a?s():"top"!==t||a||s(),n=i},r=()=>{i.removeManual(e,"touchmove",o,a),i.removeManual(e,"touchend",r,a)}}else i.add(e)("wheel",e=>{const i=e.deltaY>0;"bottom"===t&&i?s():"top"!==t||i||s()},{passive:!0})}(this.chat.bubbles.scrollable.container,"bottom",()=>{this.unsetScrollDownListener()},this.scrollDownListenerSetter))}unsetScrollDownListener(e=!0){this.waitForScrollBottom=!1,this.scrollDownListenerSetter&&(this.scrollDownListenerSetter.removeAll(),this.scrollDownListenerSetter=null),e&&this.setCorrectIndex(0)}handleFollowingPinnedMessage(){return Ga(this,void 0,void 0,(function*(){this.locked=!0,this.debug&&this.chat.log("[PM]: handleFollowingPinnedMessage");try{this.setScrollDownListener();const e=this.chat.setPeerPromise;e instanceof Promise&&(yield e),yield Object(Cs.c)(),this.getCurrentIndexPromise&&(yield this.getCurrentIndexPromise),this.debug&&this.chat.log("[PM]: handleFollowingPinnedMessage: unlock"),this.locked=!1}catch(e){this.chat.log.error("[PM]: handleFollowingPinnedMessage error:",e),this.locked=!1,this.waitForScrollBottom=!1,this.setCorrectIndex(0)}}))}followPinnedMessage(e){return Ga(this,void 0,void 0,(function*(){const t=this.chat.getMessage(e);t&&!t.deleted&&(this.chat.setMessageId(e),(this.chat.setPeerPromise||Promise.resolve()).then(()=>{this.handleFollowingPinnedMessage(),this.testMid(this.pinnedIndex>=this.count-1?this.pinnedMaxMid:e-1)}))}))}_setPinnedMessage(){return Ga(this,void 0,void 0,(function*(){const e=this.count;if(e){const t=this.pinnedIndex,s=this.chat.getMessage(this.pinnedMid),i=0===t;this.animatedCounter.container.classList.toggle("is-last",i),i||this.animatedCounter.setCount(e-t),this.pinnedMessageContainer.toggle(!1);const n=t>this.wasPinnedIndex;this.debug&&this.chat.log("[PM]: setPinnedMessage: fromTop",n,t,this.wasPinnedIndex);const a=this.animatedSubtitle.getRow(t),o=this.animatedMedia.getRow(t);o.classList.add("pinned-message-media");const r=[],l=Ue({title:void 0,titleEl:null,subtitle:s.message,subtitleEl:a,message:s,mediaEl:o,loadPromises:r});yield Promise.all(r),this.pinnedMessageContainer.divAndCaption.container.classList.toggle("is-media",l),this.animatedSubtitle.animate(t,this.wasPinnedIndex),l?(this.animatedMedia.animate(t,this.wasPinnedMediaIndex),this.wasPinnedMediaIndex=t):this.animatedMedia.clearRows(),this.pinnedMessageBorder.render(e,e-t-1),this.wasPinnedIndex=t,this.pinnedMessageContainer.divAndCaption.container.dataset.mid=""+s.mid}else this.pinnedMessageContainer.toggle(!0),this.wasPinnedIndex=0;this.pinnedMessageContainer.divAndCaption.container.classList.toggle("is-many",this.count>1)}))}}$a.LOAD_COUNT=50,$a.LOAD_OFFSET=5;class Ya{constructor(e,t,s,i,n,a,o,r){this.chat=e,this.appSidebarRight=t,this.appMessagesManager=s,this.appPeersManager=i,this.appChatsManager=n,this.appNotificationsManager=a,this.appProfileManager=o,this.appUsersManager=r,this.menuButtons=[],this.onResize=()=>{this.setUtilsWidth(!0),this.setFloating()},this.onChangeScreen=(e,t)=>{this.container.classList.toggle("is-pinned-floating",v.b.isMobile),this.pinnedMessage&&this.pinnedMessage.pinnedMessageContainer.divAndCaption.container.classList.toggle("is-floating",t===v.a.mobile),this.onResize()},this.setUtilsWidth=(e=!1)=>{this.setUtilsRAF&&window.cancelAnimationFrame(this.setUtilsRAF),h.IS_SAFARI&&e&&this.chatUtils.classList.add("hide"),this.setUtilsRAF=window.requestAnimationFrame(()=>{h.IS_SAFARI&&e&&this.chatUtils.classList.remove("hide");const t=this.chatUtils.getBoundingClientRect().width;this.chat.log("utils width:",t),this.chatInfo.style.setProperty("--utils-width",t+"px"),this.setUtilsRAF=0})},this.setFloating=()=>{const e=[this.chatAudio,this.pinnedMessage&&this.pinnedMessage.pinnedMessageContainer].filter(Boolean).reduce((e,t)=>{const s=t.divAndCaption.container.classList.contains("is-floating");return this.container.classList.toggle(`is-pinned-${t.className}-floating`,s),e+ +s},0);this.container.dataset.floating=""+e},this.setPeerStatus=(e=!1)=>{if(!this.subtitle)return;const t=this.peerId;this.chat.appImManager.setPeerStatus(this.peerId,this.subtitle,e,!1,()=>t===this.peerId)},this.listenerSetter=new H.a}construct(){this.container=document.createElement("div"),this.container.classList.add("sidebar-header","topbar"),this.container.dataset.floating="0",this.btnBack=N("left sidebar-close-button",{noRipple:!0}),this.chatInfo=document.createElement("div"),this.chatInfo.classList.add("chat-info");const e=document.createElement("div");e.classList.add("person");const t=document.createElement("div");t.classList.add("content");const s=document.createElement("div");s.classList.add("top"),this.title=document.createElement("div"),this.title.classList.add("user-title"),s.append(this.title);const i=document.createElement("div");i.classList.add("bottom"),this.subtitle&&i.append(this.subtitle),t.append(s,i),this.avatarElement&&e.append(this.avatarElement),e.append(t),this.chatInfo.append(e),this.chatUtils=document.createElement("div"),this.chatUtils.classList.add("chat-utils"),this.chatAudio=new Va(this,this.chat,this.appMessagesManager),this.menuButtons.length&&(this.btnMore=Ie({listenerSetter:this.listenerSetter},"bottom-left",this.menuButtons,e=>{Object(c.a)(e),this.menuButtons.forEach(e=>{e.element.classList.toggle("hide",!e.verify())}),this.menuButtons[this.menuButtons.length-1].element.lastChild.replaceWith(Object(A.i18n)(this.appPeersManager.getDeleteButtonText(this.peerId)))})),this.chatUtils.append(...[this.pinnedMessage?this.pinnedMessage.pinnedMessageContainer.divAndCaption.container:null,this.btnJoin,this.btnPinned,this.btnMute,this.btnSearch,this.btnMore].filter(Boolean)),this.container.append(this.btnBack,this.chatInfo,this.chatUtils),this.chatAudio&&this.container.append(this.chatAudio.divAndCaption.container,this.chatUtils),this.listenerSetter.add(window)("resize",this.onResize),this.listenerSetter.add(v.b)("changeScreen",this.onChangeScreen),Object(l.b)(this.container,e=>{const t=Object(Ce.a)(e.target,"pinned-container");if(Object(Us.a)(),t){if(Object(c.a)(e),Object(Ce.a)(e.target,"progress-line"))return;const s=+t.dataset.mid,i=+t.dataset.peerId;if(t.classList.contains("pinned-message"))this.pinnedMessage.followPinnedMessage(s);else{const e=fe.getSearchContext();this.chat.appImManager.setInnerPeer(i,s,e.isScheduled?"scheduled":e.threadId?"discussion":void 0,e.threadId)}}else v.b.activeScreen===v.a.medium&&document.body.classList.contains("is-left-column-shown")?n():Object(mt.a)(e.target,"AVATAR-ELEMENT")?this.appSidebarRight.toggleSidebar(!document.body.classList.contains("is-right-column-shown")):this.appSidebarRight.toggleSidebar(!0)},{listenerSetter:this.listenerSetter});const n=e=>{if(e&&Object(c.a)(e),v.b.activeScreen===v.a.medium&&document.body.classList.contains("is-left-column-shown"))this.chat.appImManager.setPeer(this.peerId);else{const e=0===this.chat.appImManager.chats.indexOf(this.chat);B.a.back(e?"im":"chat")}};Object(l.b)(this.btnBack,n,{listenerSetter:this.listenerSetter})}constructUtils(){this.menuButtons=[{icon:"search",text:"Search",onClick:()=>{this.chat.initSearch()},verify:()=>v.b.isMobile},{icon:"mute",text:"ChatList.Context.Mute",onClick:()=>{this.appMessagesManager.mutePeer(this.peerId)},verify:()=>"chat"===this.chat.type&&a.default.myId!==this.peerId&&!this.appNotificationsManager.isPeerLocalMuted(this.peerId,!1)},{icon:"unmute",text:"ChatList.Context.Unmute",onClick:()=>{this.appMessagesManager.mutePeer(this.peerId)},verify:()=>"chat"===this.chat.type&&a.default.myId!==this.peerId&&this.appNotificationsManager.isPeerLocalMuted(this.peerId,!1)},{icon:"comments",text:"ViewDiscussion",onClick:()=>{this.appProfileManager.getChannelFull(-this.peerId).then(e=>{e.linked_chat_id&&this.chat.appImManager.setInnerPeer(-e.linked_chat_id)})},verify:()=>{var e;const t=this.appProfileManager.chatsFull[-this.peerId];return"chat"===this.chat.type&&this.appPeersManager.isBroadcast(this.peerId)&&!!(null===(e=t)||void 0===e?void 0:e.linked_chat_id)}},{icon:"select",text:"Chat.Menu.SelectMessages",onClick:()=>{const e=this.chat.selection;e.toggleSelection(!0,!0),k.default.getState().then(t=>{if(t.chatContextMenuHintWasShown)return;const s=e.toggleByElement.bind(e);e.toggleByElement=t=>{k.default.pushToState("chatContextMenuHintWasShown",!0),nt(Object(A.i18n)("Chat.Menu.Hint")),e.toggleByElement=s,e.toggleByElement(t)}})},verify:()=>!this.chat.selection.isSelecting&&!!Object.keys(this.chat.bubbles.bubbles).length},{icon:"select",text:"Chat.Menu.ClearSelection",onClick:()=>{this.chat.selection.cancelSelection()},verify:()=>this.chat.selection.isSelecting},{icon:"adduser",text:"AddContact",onClick:()=>{if(!this.appSidebarRight.isTabExists(Ft)){const e=new Ft(this.appSidebarRight);e.peerId=this.peerId,e.open(),this.appSidebarRight.toggleSidebar(!0)}},verify:()=>this.peerId>0&&!this.appUsersManager.isContact(this.peerId)},{icon:"forward",text:"ShareContact",onClick:()=>{const e=this.peerId;new It({peerTypes:["dialogs","contacts"],onSelect:t=>new Promise((s,i)=>{new ht("",{titleLangKey:"SendMessageTitle",descriptionLangKey:"SendContactToGroupText",descriptionLangArgs:[new ft.a({peerId:t,dialog:!0}).element],buttons:[{langKey:"Send",callback:()=>{s(),this.appMessagesManager.sendOther(t,this.appUsersManager.getContactMediaInput(e)),this.chat.appImManager.setInnerPeer(t)}},{langKey:"Cancel",callback:()=>{i()},isCancel:!0}],peerId:t,overlayClosable:!0}).show()}),placeholder:"ShareModal.Search.Placeholder",chatRightsAction:"send_messages",selfPresence:"ChatYourSelf"})},verify:()=>a.default.myId!==this.peerId&&this.peerId>0&&this.appUsersManager.isContact(this.peerId)},{icon:"lock",text:"BlockUser",onClick:()=>{new ht("",{peerId:this.peerId,titleLangKey:"BlockUser",descriptionLangKey:"AreYouSureBlockContact2",descriptionLangArgs:[new ft.a({peerId:this.peerId}).element],buttons:[{langKey:"BlockUser",isDanger:!0,callback:()=>{this.appUsersManager.toggleBlock(this.peerId,!0).then(e=>{e&&at({langPackKey:"UserBlocked"})})}}]}).show()},verify:()=>{var e;const t=this.appProfileManager.usersFull[this.peerId];return this.peerId>0&&this.peerId!==a.default.myId&&t&&!(null===(e=t.pFlags)||void 0===e?void 0:e.blocked)}},{icon:"lockoff",text:"Unblock",onClick:()=>{this.appUsersManager.toggleBlock(this.peerId,!1).then(e=>{e&&at({langPackKey:"UserUnblocked"})})},verify:()=>{var e;const t=this.appProfileManager.usersFull[this.peerId];return this.peerId>0&&!!(null===(e=null==t?void 0:t.pFlags)||void 0===e?void 0:e.blocked)}},{icon:"delete danger",text:"Delete",onClick:()=>{new xt(this.peerId)},verify:()=>"chat"===this.chat.type&&!!this.appMessagesManager.getDialogOnly(this.peerId)}],this.btnSearch=N("search"),Object(l.b)(this.btnSearch,e=>{Object(c.a)(e),this.chat.initSearch()},{listenerSetter:this.listenerSetter})}constructPeerHelpers(){return this.avatarElement=new ko,this.avatarElement.setAttribute("dialog","1"),this.avatarElement.classList.add("avatar-42","person-avatar"),this.subtitle=document.createElement("div"),this.subtitle.classList.add("info"),this.pinnedMessage=new $a(this,this.chat,this.appMessagesManager,this.appPeersManager),this.btnJoin=Object(U.a)("btn-primary btn-color-primary chat-join hide"),this.btnPinned=N("pinlist"),this.btnMute=N("mute"),Object(l.b)(this.btnPinned,e=>{Object(c.a)(e),Object(Us.a)(),this.openPinned(!0)},{listenerSetter:this.listenerSetter}),Object(l.b)(this.btnMute,e=>{Object(c.a)(e),Object(Us.a)(),this.appMessagesManager.mutePeer(this.peerId)},{listenerSetter:this.listenerSetter}),Object(l.b)(this.btnJoin,e=>{Object(c.a)(e),Object(Us.a)();const t=this.chat.bubbles.getMiddleware();this.btnJoin.setAttribute("disabled","true");const s=-this.peerId;let i;i=this.appChatsManager.isChannel(s)?this.appChatsManager.joinChannel(s):this.appChatsManager.addChatUser(s,a.default.myId),i.finally(()=>{t()&&this.btnJoin.removeAttribute("disabled")})},{listenerSetter:this.listenerSetter}),this.listenerSetter.add(a.default)("chat_update",e=>{var t,s;if(this.peerId===-e){const i=this.appChatsManager.getChat(e);this.btnJoin.classList.toggle("hide",!(null===(s=null===(t=i)||void 0===t?void 0:t.pFlags)||void 0===s?void 0:s.left)),this.setUtilsWidth()}}),this.listenerSetter.add(a.default)("dialog_notify_settings",e=>{e.peerId===this.peerId&&this.setMutedState()}),this.listenerSetter.add(a.default)("peer_typings",({peerId:e})=>{this.peerId===e&&this.setPeerStatus()}),this.listenerSetter.add(a.default)("user_update",e=>{this.peerId===e&&this.setPeerStatus()}),this.pinnedMessage&&this.chat.addEventListener("setPeer",(e,t)=>{const s=this.chat.bubbles.getMiddleware();k.default.getState().then(i=>{s()&&(this.pinnedMessage.hidden=!!i.hiddenPinnedMessages[this.chat.peerId],t?(this.pinnedMessage.unsetScrollDownListener(),this.pinnedMessage.testMid(e,0)):this.pinnedMessage.locked||(this.pinnedMessage.handleFollowingPinnedMessage(),this.pinnedMessage.testMid(e)))})}),this.setPeerStatusInterval=window.setInterval(this.setPeerStatus,6e4),this}constructPinnedHelpers(){this.listenerSetter.add(a.default)("peer_pinned_messages",e=>{const{peerId:t,mids:s,pinned:i}=e;t===this.peerId&&s&&this.setTitle()})}constructDiscussionHelpers(){this.pinnedMessage=new $a(this,this.chat,this.appMessagesManager,this.appPeersManager)}openPinned(e){this.chat.appImManager.setInnerPeer(this.peerId,e?+this.pinnedMessage.pinnedMessageContainer.divAndCaption.container.dataset.mid:0,"pinned")}destroy(){this.listenerSetter.removeAll(),window.clearInterval(this.setPeerStatusInterval),this.pinnedMessage&&this.pinnedMessage.destroy(),delete this.chatAudio,delete this.pinnedMessage}setPeer(e){this.wasPeerId=this.peerId,this.peerId=e,this.container.style.display=e?"":"none"}finishPeerChange(e,t,s){var i,n;const a=this.peerId;this.avatarElement&&(this.avatarElement.setAttribute("peer",""+a),this.avatarElement.update());const o=this.appPeersManager.isBroadcast(a);this.btnMute&&this.btnMute.classList.toggle("hide",!o),this.btnJoin&&(Object(x.a)(this.btnJoin,Object(A.i18n)(this.appChatsManager.isChannel(-a)?"Chat.Subscribe":"ChannelJoin")),this.btnJoin.classList.toggle("hide",!(null===(n=null===(i=this.appChatsManager.getChat(-a))||void 0===i?void 0:i.pFlags)||void 0===n?void 0:n.left))),this.setUtilsWidth();const r=this.chat.bubbles.getMiddleware();if(this.pinnedMessage)if("chat"===this.chat.type){if(void 0!==this.wasPeerId){const e=new $a(this,this.chat,this.appMessagesManager,this.appPeersManager);this.pinnedMessage.pinnedMessageContainer.divAndCaption.container.replaceWith(e.pinnedMessageContainer.divAndCaption.container),this.pinnedMessage.destroy(),this.pinnedMessage=e}k.default.getState().then(t=>{r()&&(this.pinnedMessage.hidden=!!t.hiddenPinnedMessages[a],e||this.pinnedMessage.setCorrectIndex(0))})}else"discussion"===this.chat.type&&(this.pinnedMessage.pinnedMid=this.chat.threadId,this.pinnedMessage.count=1,this.pinnedMessage.pinnedIndex=0,this.pinnedMessage._setPinnedMessage());Object(_e.b)(()=>{this.setTitle(),this.setPeerStatus(!0),this.setMutedState()})}setTitle(e){var t;let s;if("pinned"===this.chat.type?(s=void 0===e?Object(A.i18n)("Loading"):Object(A.i18n)("PinnedMessagesCount",[e]),void 0===e&&this.appMessagesManager.getSearchCounters(this.peerId,[{_:"inputMessagesFilterPinned"}],!1).then(e=>{const t=e[0].count;if(this.setTitle(t),!t){this.chat.appImManager.setPeer(0);const e=this.chat.appImManager.chat;e.topbar.pinnedMessage&&e.topbar.pinnedMessage.pinnedMessageContainer.toggle(!0)}})):"scheduled"===this.chat.type?(s=this.peerId===a.default.myId?Object(A.i18n)("Reminders"):Object(A.i18n)("ScheduledMessages"),void 0===e&&this.appMessagesManager.getScheduledMessages(this.peerId).then(e=>{this.setTitle(e.length)})):"discussion"===this.chat.type?(s=void 0===e?Object(A.i18n)("Loading"):Object(A.i18n)("Chat.Title.Comments",[e]),void 0===e&&Promise.all([this.appMessagesManager.getHistory(this.peerId,0,1,0,this.chat.threadId),Promise.resolve()]).then(()=>{const e=this.appMessagesManager.getHistoryStorage(this.peerId,this.chat.threadId).count;null===e?setTimeout(()=>{this.setTitle()},30):this.setTitle(e)})):"chat"===this.chat.type&&(s=new ft.a({peerId:this.peerId,dialog:!0}).element),Object(x.a)(this.title,s),"chat"===this.chat.type){const e=this.appPeersManager.getPeer(this.peerId);(null===(t=null==e?void 0:e.pFlags)||void 0===t?void 0:t.verified)&&this.title.append(Bt())}}setMutedState(){if(!this.btnMute)return;const e=this.peerId;let t=this.appNotificationsManager.isPeerLocalMuted(e,!1);this.appPeersManager.isBroadcast(e)?(this.btnMute.classList.remove("tgico-mute","tgico-unmute"),this.btnMute.classList.add(t?"tgico-unmute":"tgico-mute"),this.btnMute.style.display=""):this.btnMute.style.display="none"}}class Xa extends V{constructor(){super(...arguments),this.peerId=0,this.threadId=0,this.query=""}onOpenAfterTimeout(){this.appSearch.beginSearch(this.peerId,this.threadId,this.query)}init(){this.container.id="search-private-container",this.container.classList.add("chatlist-container"),this.inputSearch=new j("Search"),this.title.replaceWith(this.inputSearch.container),this.btnPickDate=N("calendar sidebar-header-right"),this.header.append(this.btnPickDate);const e=document.createElement("div");e.classList.add("chatlist-container"),this.scrollable.container.replaceWith(e),this.appSearch=new _(e,this.inputSearch,{messages:new O("Chat.Search.PrivateSearch","messages")})}open(e,t,s,i){const n=super.open();return this.peerId?this.appSearch.beginSearch(this.peerId,this.threadId,i):(this.query=i,this.peerId=e,this.threadId=t,this.onDatePick=s,this.btnPickDate.classList.toggle("hide",!this.onDatePick),this.onDatePick&&Object(l.b)(this.btnPickDate,()=>{new dn(new Date,this.onDatePick).show()}),i&&this.appSearch.searchInput.inputField.setValueSilently(i),$t.toggleSidebar(!0)),n}}class Ja{constructor(e,t,s){this.topbar=e,this.chat=t,this.query=s,this.foundCount=0,this.selectedIndex=0,this.onDateClick=e=>{Object(c.a)(e),new dn(new Date,this.chat.bubbles.onDatePick).show()},this.selectResult=e=>{if(this.setPeerPromise)return this.setPeerPromise;const t=+e.dataset.peerId,s=+e.dataset.mid||void 0,i=Object(Ts.a)(e);i===this.foundCount-1?this.upBtn.setAttribute("disabled","true"):this.upBtn.removeAttribute("disabled"),i?this.downBtn.removeAttribute("disabled"):this.downBtn.setAttribute("disabled","true"),this.results.classList.remove("active"),this.chat.bubbles.bubblesContainer.classList.remove("search-results-active");const n=this.chat.setPeer(t,s);this.setPeerPromise=(n instanceof Promise?n:Promise.resolve(n)).then(()=>{this.selectedIndex=i,Object(x.a)(this.foundCountEl,Object(A.i18n)("Of",[i+1,this.foundCount]));const e=this.searchGroup.list.childElementCount;this.selectedIndex>=e-6&&this.appSearch.searchMore()}).finally(()=>{this.setPeerPromise=null})},this.onResultsClick=e=>{const t=Object(mt.a)(e.target,"LI");t&&this.selectResult(t)},this.onFooterClick=e=>{this.foundCount&&(this.chat.bubbles.bubblesContainer.classList.toggle("search-results-active"),this.results.classList.toggle("active"))},this.onUpClick=e=>{Object(c.a)(e),this.selectResult(this.searchGroup.list.children[this.selectedIndex+1])},this.onDownClick=e=>{Object(c.a)(e),this.selectResult(this.searchGroup.list.children[this.selectedIndex-1])},this.element=document.createElement("div"),this.element.classList.add("sidebar-header","chat-search","chatlist-container"),this.backBtn=document.createElement("button"),this.backBtn.classList.add("btn-icon","tgico-left","sidebar-close-button"),Object(ie.ripple)(this.backBtn),this.backBtn.addEventListener("click",()=>{this.topbar.container.classList.remove("hide-pinned"),this.element.remove(),this.inputSearch.remove(),this.results.remove(),this.footer.remove(),this.footer.removeEventListener("click",this.onFooterClick),this.dateBtn.removeEventListener("click",this.onDateClick),this.upBtn.removeEventListener("click",this.onUpClick),this.downBtn.removeEventListener("click",this.onDownClick),this.searchGroup.list.removeEventListener("click",this.onResultsClick),this.chat.bubbles.bubblesContainer.classList.remove("search-results-active")},{once:!0}),this.inputSearch=new j("Search"),this.results=document.createElement("div"),this.results.classList.add("chat-search-results","chatlist-container"),this.searchGroup=new O(!1,"messages",void 0,"",!1),this.searchGroup.list.addEventListener("click",this.onResultsClick),this.appSearch=new _(this.results,this.inputSearch,{messages:this.searchGroup},e=>{this.foundCount=e,this.foundCount?this.selectResult(this.searchGroup.list.children[0]):(this.foundCountEl.replaceWith(this.inputSearch.value?Object(A.i18n)("NoResult"):""),this.results.classList.remove("active"),this.chat.bubbles.bubblesContainer.classList.remove("search-results-active"),this.upBtn.setAttribute("disabled","true"),this.downBtn.setAttribute("disabled","true"))}),this.appSearch.beginSearch(this.chat.peerId,this.chat.threadId),this.chat.bubbles.bubblesContainer.append(this.results),this.footer=document.createElement("div"),this.footer.classList.add("chat-search-footer"),this.footer.addEventListener("click",this.onFooterClick),Object(ie.ripple)(this.footer),this.foundCountEl=document.createElement("span"),this.foundCountEl.classList.add("chat-search-count"),this.dateBtn=document.createElement("button"),this.dateBtn.classList.add("btn-icon","tgico-calendar"),this.controls=document.createElement("div"),this.controls.classList.add("chat-search-controls"),this.upBtn=document.createElement("button"),this.upBtn.classList.add("btn-icon","tgico-up"),this.downBtn=document.createElement("button"),this.downBtn.classList.add("btn-icon","tgico-down"),this.upBtn.setAttribute("disabled","true"),this.downBtn.setAttribute("disabled","true"),this.dateBtn.addEventListener("click",this.onDateClick),this.upBtn.addEventListener("click",this.onUpClick),this.downBtn.addEventListener("click",this.onDownClick),this.controls.append(this.upBtn,this.downBtn),this.footer.append(this.foundCountEl,this.dateBtn,this.controls),this.topbar.container.parentElement.insertBefore(this.footer,t.input.chatInput),this.element.append(this.backBtn,this.inputSearch.container),this.topbar.container.classList.add("hide-pinned"),this.topbar.container.parentElement.append(this.element),this.inputSearch.input.focus(),s&&(this.inputSearch.inputField.value=s)}}class Za extends R.a{constructor(e,t,s,i,n,a,o,r,l,c,d,h,u,p,m,g,b,v,f){super(),this.appImManager=e,this.appChatsManager=t,this.appDocsManager=s,this.appInlineBotsManager=i,this.appMessagesManager=n,this.appPeersManager=a,this.appPhotosManager=o,this.appProfileManager=r,this.appStickersManager=l,this.appUsersManager=c,this.appWebPagesManager=d,this.appPollsManager=h,this.apiManager=u,this.appDraftsManager=p,this.serverTimeManager=m,this.storage=g,this.appNotificationsManager=b,this.appEmojiManager=v,this.appMessagesIdsManager=f,this.wasAlreadyUsed=!1,this.peerId=0,this.type="chat",this.inited=!1,this.container=document.createElement("div"),this.container.classList.add("chat","tabs-tab"),this.backgroundEl=document.createElement("div"),this.backgroundEl.classList.add("chat-background"),this.log=Object(J.b)("CHAT",J.a.Log|J.a.Warn|J.a.Debug|J.a.Error),this.container.append(this.backgroundEl),this.appImManager.chatsContainer.append(this.container)}setBackground(e){const t=a.default.getTheme();let s;if("color"===t.background.type&&"grabbing"===document.documentElement.style.cursor){const e=this.backgroundEl.lastElementChild;e&&e.dataset.type===t.background.type&&(s=e)}return s||(s=document.createElement("div"),s.classList.add("chat-background-item"),s.dataset.type=t.background.type),"color"===t.background.type&&(s.style.backgroundColor=t.background.color,s.style.backgroundImage="none"),new Promise(t=>{const i=()=>{const e=this.backgroundEl.lastElementChild;e!==s?(this.backgroundEl.append(s),Object(_e.b)(()=>{Object(_e.b)(()=>{Object(Xt.a)(s,"is-visible",!0,200,e?()=>{e.remove()}:null)})}),t()):t()};e?Object(Rt.a)(s,e,i):i()})}setType(e){this.type=e,"scheduled"===this.type&&(this.getMessagesStorage=()=>this.appMessagesManager.getScheduledMessagesStorage(this.peerId))}init(){this.topbar=new Ya(this,$t,this.appMessagesManager,this.appPeersManager,this.appChatsManager,this.appNotificationsManager,this.appProfileManager,this.appUsersManager),this.bubbles=new ia(this,this.appMessagesManager,this.appStickersManager,this.appUsersManager,this.appInlineBotsManager,this.appPhotosManager,this.appPeersManager,this.appProfileManager,this.appDraftsManager,this.appMessagesIdsManager),this.input=new Ua(this,this.appMessagesManager,this.appMessagesIdsManager,this.appDocsManager,this.appChatsManager,this.appPeersManager,this.appWebPagesManager,this.appImManager,this.appDraftsManager,this.serverTimeManager,this.appNotificationsManager,this.appEmojiManager,this.appUsersManager,this.appInlineBotsManager),this.selection=new Gs(this,this.bubbles,this.input,this.appMessagesManager),this.contextMenu=new ca(this.bubbles.bubblesContainer,this,this.appMessagesManager,this.appPeersManager,this.appPollsManager,this.appDocsManager,this.appMessagesIdsManager),"chat"===this.type?(this.topbar.constructUtils(),this.topbar.constructPeerHelpers()):"pinned"===this.type?this.topbar.constructPinnedHelpers():"discussion"===this.type&&(this.topbar.constructUtils(),this.topbar.constructDiscussionHelpers()),this.topbar.construct(),this.input.construct(),"chat"===this.type?(this.bubbles.constructPeerHelpers(),this.input.constructPeerHelpers()):"pinned"===this.type?(this.bubbles.constructPinnedHelpers(),this.input.constructPinnedHelpers()):"scheduled"===this.type?(this.bubbles.constructScheduledHelpers(),this.input.constructPeerHelpers()):"discussion"===this.type&&(this.bubbles.constructPeerHelpers(),this.input.constructPeerHelpers()),this.container.classList.add("type-"+this.type),this.container.append(this.topbar.container,this.bubbles.bubblesContainer,this.input.chatInput),this.bubbles.listenerSetter.add(a.default)("dialog_migrate",({migrateFrom:e,migrateTo:t})=>{this.peerId===e&&this.setPeer(t)}),this.bubbles.listenerSetter.add(a.default)("dialog_drop",e=>{e.peerId===this.peerId&&this.appImManager.setPeer(0)})}beforeDestroy(){this.bubbles.cleanup()}destroy(){this.topbar.destroy(),this.bubbles.destroy(),this.input.destroy(),delete this.topbar,delete this.bubbles,delete this.input,delete this.selection,delete this.contextMenu,this.container.remove()}cleanup(e=!0){this.input.cleanup(e),this.selection.cleanup()}setPeer(e,t){e?this.inited||(this.init&&(this.init(),this.init=null),this.inited=!0):this.inited=!1;const s=this.peerId===e;if(s){if(this.setPeerPromise)return}else a.default.dispatchEvent("peer_changing",this),this.peerId=e;if(!e)return $t.toggleSidebar(!1),this.cleanup(!0),this.topbar.setPeer(e),this.bubbles.setPeer(e),void a.default.dispatchEvent("peer_changed",e);if(!s){const t=$t.getTab(Xa);t&&t.close(),$t.sharedMediaTab.setPeer(e,this.threadId),this.input.clearHelper(),this.selection.cleanup(),this.setAutoDownloadMedia()}this.peerChanged=s;const i=this.bubbles.setPeer(e,t);if(!i)return;const{promise:n}=i,o=this.setPeerPromise=n.finally(()=>{this.setPeerPromise===o&&(this.setPeerPromise=null)});return s||($t.sharedMediaTab.setLoadMutex(this.setPeerPromise),$t.sharedMediaTab.loadSidebarMedia(!0)),i}setAutoDownloadMedia(){let e;e=this.peerId<0?this.appPeersManager.isBroadcast(this.peerId)?"channels":"groups":this.appUsersManager.isContact(this.peerId)?"contacts":"private",this.noAutoDownloadMedia=!a.default.settings.autoDownload[e]}setMessageId(e){return this.setPeer(this.peerId,e)}finishPeerChange(e,t,s){if(this.peerChanged)return;let i=this.peerId;this.peerChanged=!0,this.cleanup(!1),this.topbar.setPeer(i),this.topbar.finishPeerChange(e,t,s),this.bubbles.finishPeerChange(),this.input.finishPeerChange(),$t.sharedMediaTab.fillProfileElements(),this.log.setPrefix("CHAT-"+i+"-"+this.type),a.default.dispatchEvent("peer_changed",i),this.wasAlreadyUsed=!0}getMessagesStorage(){return this.appMessagesManager.getMessagesStorage(this.peerId)}getMessage(e){return this.appMessagesManager.getMessageFromStorage(this.getMessagesStorage(),e)}getMidsByMid(e){return this.appMessagesManager.getMidsByMessage(this.getMessage(e))}isAnyGroup(){return this.peerId===a.default.myId||this.peerId===gn.b||this.appPeersManager.isAnyGroup(this.peerId)}initSearch(e){if(this.peerId)if(v.b.isMobile)new Ja(this.topbar,this,e);else{let t=$t.getTab(Xa);t||(t=new Xa($t)),t.open(this.peerId,this.threadId,this.bubbles.onDatePick,e)}}}var eo=s(137);class to{constructor(e){this.appImManager=e,this.buttons={},this.addedListener=!1,this.waitingForMouseUp=!1,this.mouseUpCounter=0,this.onMouseUpSingle=e=>{if(this.waitingForMouseUp=!1,pe.IS_TOUCH_SUPPORTED){if(Object(c.a)(e),0!=this.mouseUpCounter++)return void this.hide();this.resetSelection(this.savedRange)}this.show()}}init(){this.container=document.createElement("div"),this.container.classList.add("markup-tooltip","z-depth-1","hide"),this.wrapper=document.createElement("div"),this.wrapper.classList.add("markup-tooltip-wrapper");const e=document.createElement("div"),t=document.createElement("div");e.classList.add("markup-tooltip-tools"),t.classList.add("markup-tooltip-tools");["bold","italic","underline","strikethrough","monospace","link"].forEach(t=>{const s=N(t,{noRipple:!0});e.append(this.buttons[t]=s),"link"!==t?s.addEventListener("mousedown",e=>{Object(c.a)(e),this.appImManager.chat.input.applyMarkdown(t),this.cancelClosening()}):Object(l.b)(s,e=>{Object(c.a)(e),this.showLinkEditor(),this.cancelClosening()})}),this.linkBackButton=N("left",{noRipple:!0}),this.linkInput=document.createElement("input"),Object(A._i18n)(this.linkInput,"MarkupTooltip.LinkPlaceholder",void 0,"placeholder"),this.linkInput.classList.add("input-clear"),this.linkInput.addEventListener("keydown",e=>{const t=!this.linkInput.value.length||!!Z.b.matchUrl(this.linkInput.value);"Enter"===e.code&&(t?this.applyLink(e):(this.linkInput.classList.contains("error")&&(this.linkInput.classList.remove("error"),this.linkInput.offsetLeft),this.linkInput.classList.add("error")))}),this.linkInput.addEventListener("input",e=>{const t=this.isLinkValid();this.linkInput.classList.toggle("is-valid",t),this.linkInput.classList.remove("error")}),this.linkBackButton.addEventListener("mousedown",e=>{Object(c.a)(e),this.container.classList.remove("is-link"),this.resetSelection(),this.setTooltipPosition(),this.cancelClosening()}),this.linkApplyButton=N("check markup-tooltip-link-apply",{noRipple:!0}),this.linkApplyButton.addEventListener("mousedown",e=>{this.applyLink(e)});const s=document.createElement("div");s.classList.add("markup-tooltip-link-apply-container");const i=document.createElement("span"),n=document.createElement("span"),a=document.createElement("span");i.classList.add("markup-tooltip-delimiter"),n.classList.add("markup-tooltip-delimiter"),a.classList.add("markup-tooltip-delimiter"),e.insertBefore(i,this.buttons.link),s.append(a,this.linkApplyButton),t.append(this.linkBackButton,n,this.linkInput,s),this.wrapper.append(e,t),this.container.append(this.wrapper),document.body.append(this.container),window.addEventListener("resize",()=>{this.hide()})}showLinkEditor(){this.container&&this.container.classList.contains("is-visible")||this.show();const e=this.buttons.link;this.container.classList.add("is-link");const t=document.getSelection();if(this.savedRange=t.getRangeAt(0),e.classList.contains("active")){const e=this.savedRange.startContainer.parentElement;this.linkInput.value=e.href}else this.linkInput.value="";this.setTooltipPosition(!0),setTimeout(()=>{this.linkInput.focus()},200),this.linkInput.classList.toggle("is-valid",this.isLinkValid())}applyLink(e){Object(c.a)(e),this.resetSelection();let t=this.linkInput.value;t&&!Z.b.matchUrlProtocol(t)&&(t="https://"+t),this.appImManager.chat.input.applyMarkdown("link",t),setTimeout(()=>{this.hide()},0)}isLinkValid(){return!this.linkInput.value.length||!!Z.b.matchUrl(this.linkInput.value)}resetSelection(e=this.savedRange){const t=window.getSelection();t.removeAllRanges(),t.addRange(e),this.appImManager.chat.input.messageInput.focus()}hide(){this.init||(this.container.classList.remove("is-visible"),document.removeEventListener("mouseup",this.onMouseUpSingle),this.waitingForMouseUp=!1,B.a.removeByType("markup"),this.hideTimeout&&clearTimeout(this.hideTimeout),this.hideTimeout=window.setTimeout(()=>{this.hideTimeout=void 0,this.container.classList.add("hide"),this.container.classList.remove("is-link")},200))}getActiveMarkupButton(){const e=function(){const e=[],t=window.getSelection();for(let s=0;s<t.rangeCount;++s){const i=t.getRangeAt(s);let{startContainer:n,endContainer:a}=i;for(3!==a.nodeType&&(a=a.firstChild);n&&n!==a;)e.push(3===n.nodeType?n:n.firstChild),n=n.nextSibling;e[e.length-1]!==a&&e.push(a)}return e.filter(e=>!!e)}(),t=[...new Set(e.map(e=>e.parentNode))],s=new Set;return t.forEach(e=>{for(const t in Ta.b){const i=Ta.b[t];e.closest(i.match+", [contenteditable]")!==this.appImManager.chat.input.messageInput&&s.add(this.buttons[t])}}),[...s]}setActiveMarkupButton(){const e=this.getActiveMarkupButton();for(const t in this.buttons){const s=this.buttons[t];s.classList.toggle("active",e.includes(s))}}setTooltipPosition(e=!1){const t=document.getSelection().getRangeAt(0),s=document.body.getBoundingClientRect(),i=t.getBoundingClientRect(),n=this.appImManager.chat.input.rowsWrapper.getBoundingClientRect();this.container.style.maxWidth=n.width+"px";const a=i.top+-1*s.top,o=(this.container.classList.contains("is-link")?this.wrapper.lastElementChild:this.wrapper.firstElementChild).getBoundingClientRect(),r=a-o.height-8,l=n.left,c=n.left+n.width-Math.min(n.width,o.width);let d;if(e){const e=this.container.getBoundingClientRect();d=Object(C.a)(e.left,l,c)}else{const e=i.left+(i.width-o.width)/2;d=Object(C.a)(e,l,c)}this.container.style.transform=`translate3d(${d}px, ${r}px, 0)`}show(){if(this.init&&(this.init(),this.init=null),oa())return void this.hide();if(void 0!==this.hideTimeout&&clearTimeout(this.hideTimeout),this.container.classList.contains("is-visible"))return;this.setActiveMarkupButton(),this.container.classList.remove("is-link");const e=this.container.classList.contains("hide");e&&(this.container.classList.remove("hide"),this.container.classList.add("no-transition")),this.setTooltipPosition(),e&&(this.container.offsetLeft,this.container.classList.remove("no-transition")),this.container.classList.add("is-visible"),h.IS_MOBILE||B.a.pushItem({type:"markup",onPop:()=>{this.hide()}})}setMouseUpEvent(){this.waitingForMouseUp||(this.waitingForMouseUp=!0,document.addEventListener("mouseup",this.onMouseUpSingle,{once:!0}))}cancelClosening(){pe.IS_TOUCH_SUPPORTED&&!h.IS_APPLE&&(document.removeEventListener("mouseup",this.onMouseUpSingle),document.addEventListener("mouseup",e=>{Object(c.a)(e),this.mouseUpCounter=1,this.waitingForMouseUp=!1,this.setMouseUpEvent()},{once:!0}))}handleSelection(){this.addedListener||(this.addedListener=!0,document.addEventListener("selectionchange",e=>{if(document.activeElement===this.linkInput)return;if(document.activeElement!==this.appImManager.chat.input.messageInput)return void this.hide();const t=document.getSelection();if(oa(t))this.hide();else if(pe.IS_TOUCH_SUPPORTED)if(h.IS_APPLE)this.show(),this.setTooltipPosition();else{if(2===this.mouseUpCounter)return void(this.mouseUpCounter=0);this.savedRange=t.getRangeAt(0),this.setMouseUpEvent()}else this.setMouseUpEvent()}))}}function so(e,t,s,i,n,a,o){return[e,",",t," ",s," ",i,",",n," ",a,",",o].join("")}function io(e,t,s,i,n,a,o,r){const l=[];return l.push("M"+(e+s/2)+","+t),l.push("H"+(e+s-a)),a>0&&l.push("A"+so(a,a,0,0,1,e+s,t+a)),l.push("V"+(t+i-o)),o>0&&l.push("A"+so(o,o,0,0,1,e+s-o,t+i)),l.push("H"+(e+r)),r>0&&l.push("A"+so(r,r,0,0,1,e+0,t+i-r)),l.push("V"+(t+n)),n>0&&l.push("A"+so(n,n,0,0,1,e+n,t+0)),l.push("Z"),l.join(" ")}de.a.generatePathData=io;class no{constructor(e,t){this.options=t,this.onDragOver=e=>{this.container.classList.add("is-dragover")},this.onDragLeave=e=>{this.container.classList.remove("is-dragover")},this.onDrop=e=>{this.options.onDrop(e)},this.container=document.createElement("div"),this.container.classList.add("drop","z-depth-1"),this.outlineWrapper=document.createElement("div"),this.outlineWrapper.classList.add("drop-outline-wrapper"),this.svg=document.createElementNS("http://www.w3.org/2000/svg","svg"),this.svg.classList.add("drop-outline"),this.path=document.createElementNS("http://www.w3.org/2000/svg","path"),this.path.classList.add("drop-outline-path");const s=document.createElement("div");s.classList.add("drop-icon","tgico-"+t.icon);const i=document.createElement("div");i.classList.add("drop-header"),i.append(Object(A.i18n)(t.header));const n=document.createElement("div");n.classList.add("drop-subtitle"),n.append(Object(A.i18n)(t.subtitle)),this.svg.append(this.path),this.outlineWrapper.append(this.svg),this.container.append(this.outlineWrapper,s,i,n),e.append(this.container),this.container.addEventListener("dragover",this.onDragOver),this.container.addEventListener("dragleave",this.onDragLeave),this.container.addEventListener("drop",this.onDrop)}destroy(){delete this.options,this.container.remove(),this.container.removeEventListener("dragover",this.onDragOver),this.container.removeEventListener("dragleave",this.onDragLeave),this.container.removeEventListener("drop",this.onDrop)}setPath(){const e=this.outlineWrapper.getBoundingClientRect();this.svg.setAttributeNS(null,"preserveAspectRatio","none"),this.svg.setAttributeNS(null,"viewBox",`0 0 ${e.width} ${e.height}`),this.svg.setAttributeNS(null,"width",""+e.width),this.svg.setAttributeNS(null,"height",""+e.height);const t=io(5,5,e.width-10,e.height-10,10,10,10,10);this.path.setAttributeNS(null,"d",t)}}function ao(e){e.forEach(e=>e.classList.add("no-transition")),Object(_e.a)().then(()=>{e.forEach(e=>e.classList.remove("no-transition"))})}var oo,ro=s(132);class lo extends ct.b{constructor(e,t){super("popup-join-chat-invite",Object(ct.a)([{langKey:t.pFlags.broadcast?"JoinByPeekChannelTitle":"JoinByPeekGroupTitle",callback:()=>{rt.a.invokeApi("messages.importChatInvite",{hash:e}).then(e=>{Xs.a.processUpdateMessage(e);const t=-e.chats[0].id;a.default.dispatchEvent("history_focus",{peerId:t})})}}]),{closable:!0,overlayClosable:!0,body:!0}),this.header.remove();const s=new ko;s.setAttribute("dialog","0"),s.classList.add("avatar-100"),"photo"===t.photo._?(t.photo=r.a.savePhoto(t.photo),ys({container:s,message:null,photo:t.photo,boxHeight:100,boxWidth:100,withoutPreloader:!0}),s.style.width=s.style.height=""):d.a.putPhoto(s,-0,!1,t.title);const i=document.createElement("div");i.classList.add("chat-title"),i.innerHTML=Z.b.wrapEmojiText(t.title);const n=t.pFlags.broadcast,o=Object(A.i18n)(n?"Subscribers":"Members",[t.participants_count]);o.classList.add("chat-participants-count"),this.body.append(s,i,o)}}!function(e){e[e.MESSAGE=0]="MESSAGE",e[e.PRIVATE_POST=1]="PRIVATE_POST",e[e.STICKER_SET=2]="STICKER_SET",e[e.JOIN_CHAT=3]="JOIN_CHAT"}(oo||(oo={}));var co=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};const ho="chat",uo=pe.IS_TOUCH_SUPPORTED?"touchstart":"mousemove";const po=new class{constructor(){this.columnEl=document.getElementById("column-center"),this.offline=!1,this.updateStatusInterval=0,this.setPeerPromise=null,this.tabId=-1,this.chats=[],this.backgroundPromises={},this.onHashChange=()=>{const e=location.hash,t=e.split("?"),s=this.parseUriParams(e,t);if(this.log("hashchange",e,t[0],s),s.tgaddr){B.a.replaceState();const{onclick:e}=Z.b.wrapUrl(s.tgaddr);if(e){const t=document.createElement("a");t.href=s.tgaddr,window[e](t)}}else switch(t[0]){case"#/im":{const e=s.p;let t=void 0!==s.post?f.a.generateMessageId(+s.post):void 0;switch(e[0]){case"@":this.openUsername(e,t);break;default:this.setInnerPeer(t?-+e:+e,t)}}}},this.setSettings=()=>{document.documentElement.style.setProperty("--messages-text-size",a.default.settings.messagesTextSize+"px"),document.body.classList.toggle("animation-level-0",!a.default.settings.animationsEnabled),document.body.classList.toggle("animation-level-1",!1),document.body.classList.toggle("animation-level-2",a.default.settings.animationsEnabled),this.chatsSelectTabDebounced=ot(()=>{const e=this.chat.topbar;e.pinnedMessage&&e.pinnedMessage.setCorrectIndex(0),rt.a.setQueueId(this.chat.bubbles.lazyLoadQueue.queueId)},a.default.settings.animationsEnabled?250:0,!1,!0),le.b.setLoop(a.default.settings.stickers.loop),I.a.checkAnimations(!1);for(const e of this.chats)e.setAutoDownloadMedia()},this.onDocumentPaste=(e,t)=>{if(this.canDrag()){if(e instanceof DragEvent){const t=e.dataTransfer.types;(t.contains?t.contains("Files"):t.indexOf("Files")>=0)&&Object(c.a)(e)}Object(me.c)(e).then(e=>{if(e.length){e.find(e=>!g.has(e.type))&&(t="document");const s=this.chat.input;s.willAttachType=t||(g.has(e[0].type)?"media":"document"),new fa(this.chat,e,s.willAttachType)}})}},Xs.a.attach(),_t.a.start(),this.log=Object(J.b)("IM",J.a.Log|J.a.Warn|J.a.Debug|J.a.Error),this.selectTab(0),window.addEventListener("blur",()=>{I.a.checkAnimations(!0),this.offline=a.default.idle.isIDLE=!0,this.updateStatus(),clearInterval(this.updateStatusInterval),a.default.dispatchEvent("idle",a.default.idle.isIDLE),window.addEventListener("focus",()=>{this.offline=a.default.idle.isIDLE=!1,this.updateStatus(),this.updateStatusInterval=window.setInterval(()=>this.updateStatus(),5e4),I.a.checkAnimations(!1),a.default.dispatchEvent("idle",a.default.idle.isIDLE)},{once:!0})}),window.addEventListener(uo,()=>{this.updateStatusInterval=window.setInterval(()=>this.updateStatus(),5e4),this.updateStatus(),this.offline=a.default.idle.isIDLE=!1,a.default.dispatchEvent("idle",a.default.idle.isIDLE)},{once:!0,passive:!0}),this.chatsContainer=document.createElement("div"),this.chatsContainer.classList.add("chats-container","tabs-container"),this.chatsContainer.dataset.animation="navigation",this.columnEl.append(this.chatsContainer),this.createNewChat(),this.chatsSelectTab(this.chat.container),B.a.onHashChange=this.onHashChange,this.setSettings(),a.default.addEventListener("settings_updated",this.setSettings),Object(Cs.a)(()=>{I.a.setOnlyOnePlayableGroup("lock"),I.a.checkAnimations(!0)},()=>{I.a.setOnlyOnePlayableGroup(""),I.a.checkAnimations(!1)}),this.applyCurrentTheme(),v.b.addEventListener("changeScreen",(e,t)=>{document.body.classList.contains("is-left-column-shown")&&document.body.classList.contains("is-right-column-shown")&&$t.toggleSidebar(!1)}),a.default.addEventListener("history_focus",e=>{let{peerId:t,threadId:s,mid:i}=e;s&&(s=f.a.generateMessageId(s)),i&&(i=f.a.generateMessageId(i)),this.setInnerPeer(t,i,s?"discussion":void 0,s)}),a.default.addEventListener("peer_changing",e=>{this.saveChatPosition(e)}),a.default.addEventListener("theme_change",()=>{this.applyCurrentTheme()}),a.default.addEventListener("instance_deactivated",()=>{const e=new ct.b("popup-instance-deactivated",void 0,{overlayClosable:!0}),t=document.createElement("div");t.classList.add("instance-deactivated-container"),e.container.replaceWith(t);const s=document.createElement("div");s.classList.add("header"),s.append(Object(A.i18n)("Deactivated.Title"));const i=document.createElement("div");i.classList.add("subtitle"),i.append(Object(A.i18n)("Deactivated.Subtitle")),t.append(s,i),document.body.classList.add("deactivated"),e.onClose=()=>{document.body.classList.add("deactivated-backwards"),ro.a.activateInstance(),setTimeout(()=>{document.body.classList.remove("deactivated","deactivated-backwards")},333)},e.show()}),Sn.a.get("chatPositions").then(e=>{Sn.a.setToCache("chatPositions",e||{})}),ro.a.activateInstance(),this.addAnchorListener({name:"showMaskedAlert",callback:(e,t)=>{const s=t.href,i=t.cloneNode(!0);i.className="anchor-url",i.innerText=s,i.removeAttribute("onclick"),new ht("popup-masked-url",{titleLangKey:"OpenUrlTitle",descriptionLangKey:"OpenUrlAlert2",descriptionLangArgs:[i],buttons:[{langKey:"Open",callback:()=>{i.click()}}]}).show()}}),this.addAnchorListener({name:"execBotCommand",callback:({uriParams:e})=>{const{command:t,bot:s}=e;i.a.sendText(this.chat.peerId,"/"+t+(s?"@"+s:""))}}),this.addAnchorListener({name:"searchByHashtag",callback:({uriParams:e})=>{const{hashtag:t}=e;t&&this.chat.initSearch("#"+t+" ")}}),this.addAnchorListener({name:"addstickers",callback:({pathnameParams:e})=>{const t={_:oo.STICKER_SET,set:e[1]};this.processInternalLink(t)}}),this.addAnchorListener({name:"joinchat",callback:({pathnameParams:e})=>{const t={_:oo.JOIN_CHAT,invite:e[1]};this.processInternalLink(t)}}),this.addAnchorListener({name:"im",callback:({pathnameParams:e,uriParams:t})=>co(this,void 0,void 0,(function*(){let s;s="c"===e[0]?{_:oo.PRIVATE_POST,channel:e[1],post:e[2],thread:"thread"in t?t.thread:void 0,comment:t.comment}:{_:oo.MESSAGE,domain:e[0],post:e[1],comment:t.comment},this.processInternalLink(s)}))}),this.addAnchorListener({name:"resolve",protocol:"tg",callback:({uriParams:e})=>{let t;"telegrampassport"===e.domain||(t=this.makeLink(oo.MESSAGE,e)),this.processInternalLink(t)}}),this.addAnchorListener({name:"privatepost",protocol:"tg",callback:({uriParams:e})=>{const t=this.makeLink(oo.PRIVATE_POST,e);this.processInternalLink(t)}}),this.addAnchorListener({name:"addstickers",protocol:"tg",callback:({uriParams:e})=>{const t=this.makeLink(oo.STICKER_SET,e);this.processInternalLink(t)}}),this.addAnchorListener({name:"joinchat",protocol:"tg",callback:({uriParams:e})=>{const t=this.makeLink(oo.JOIN_CHAT,e);this.processInternalLink(t)}}),this.onHashChange(),this.attachKeydownListener()}get myId(){return a.default.myId}get chat(){return this.chats[this.chats.length-1]}attachKeydownListener(){const e=new Set(["PageUp","PageDown","Meta","Control"]);document.body.addEventListener("keydown",t=>{if(a.default.isOverlayActive||e.has(t.key))return;const s=t.target,n=this.chat;if("KeyC"!==t.code||!t.ctrlKey&&!t.metaKey||"INPUT"===s.tagName){if(!t.altKey||"ArrowUp"!==t.code&&"ArrowDown"!==t.code){if("ArrowUp"===t.code){if(n.input.editMsgId||!n.input.isInputEmpty())return;{const e=i.a.getHistoryStorage(n.peerId,n.threadId).history.slice;if(e.isEnd(bn.a.Bottom)&&e.length){let s;for(const t of e){const e=n.getMessage(t);if((this.myId===n.peerId?e.fromId===this.myId:e.pFlags.out)&&i.a.canEditMessage(n.getMessage(t),"text")){s=t;break}}s&&(n.input.initMessageEditing(s),Object(c.a)(t))}}}else if("ArrowDown"===t.code)return}else{const e=i.a.dialogsStorage.getFolder(a.default.filterId,!0);let s;if(a.default.peerId){const i=e.findIndex(e=>e.peerId===a.default.peerId);if(-1!==i){s=e["ArrowUp"===t.code?i-1:i+1]}}else"ArrowDown"===t.code&&(s=e[0]);s&&this.setPeer(s.peerId)}!n.input.messageInput||t.target===n.input.messageInput||"INPUT"===s.tagName||s.hasAttribute("contenteditable")||pe.IS_TOUCH_SUPPORTED||v.b.isMobile&&1!==this.tabId||this.chat.selection.isSelecting||this.chat.input.recording||(n.input.messageInput.focus(),Object(va.a)(n.input.messageInput))}})}makeLink(e,t){return Object.assign({_:e},t)}processInternalLink(e){return co(this,void 0,void 0,(function*(){switch(null==e?void 0:e._){case oo.MESSAGE:{const t=e.post?f.a.generateMessageId(+e.post):void 0,s=e.comment?f.a.generateMessageId(+e.comment):void 0;this.openUsername(e.domain,t,void 0,s);break}case oo.PRIVATE_POST:{const t=-+e.channel;if(G.a.getChat(-t).deleted)try{yield G.a.resolveChannel(-t)}catch(e){throw at({langPackKey:"LinkNotFound"}),e}const s=f.a.generateMessageId(+e.post),i=e.thread?f.a.generateMessageId(+e.thread):void 0;i?this.openThread(t,s,i):this.setInnerPeer(t,s);break}case oo.STICKER_SET:new Di({id:e.set}).show();break;case oo.JOIN_CHAT:rt.a.invokeApi("messages.checkChatInvite",{hash:e.invite}).then(t=>{t.chat&&G.a.saveApiChat(t.chat,!0),"chatInviteAlready"!==t._&&"chatInvitePeek"!==t._?new lo(e.invite,t).show():this.setInnerPeer(-t.chat.id)},e=>{"INVITE_HASH_EXPIRED"===e.type&&nt(Object(A.i18n)("InviteExpired"))});break;default:this.log.warn("Not supported internal link:",e)}}))}addAnchorListener(e){window[(e.protocol?e.protocol+"_":"")+e.name]=t=>{Object(c.a)(null);const s=t.href;let i,n;e.noPathnameParams||(i=new URL(t.href).pathname.split("/").slice(1)),e.noUriParams||(n=this.parseUriParams(s));const a=e.callback({pathnameParams:i,uriParams:n},t);return void 0===a&&a}}parseUriParams(e,t=e.split("?")){const s={};return t[1]?(t[1].split("&").forEach(e=>{s[e.split("=")[0]]=decodeURIComponent(e.split("=")[1])}),s):s}openUsername(e,t,s,i){return T.a.resolveUsername(e).then(e=>{const n="user"===e._?e.id:-e.id;return s?this.openThread(n,t,s):i?this.openComment(n,t,i):this.setInnerPeer(n,t)},e=>{"USERNAME_NOT_OCCUPIED"===e.type?at({langPackKey:"NoUsernameFound"}):"USERNAME_INVALID"===e.type&&at({langPackKey:"Alert.UserDoesntExists"})})}openThread(e,t,s){return i.a.wrapSingleMessage(e,s).then(()=>{const n=i.a.getMessageByPeer(e,s);return i.a.generateThreadServiceStartMessage(n),this.setInnerPeer(e,t,"discussion",s)})}openComment(e,t,s){return i.a.getDiscussionMessage(e,t).then(e=>this.openThread(e.peerId,s,e.mid))}setCurrentBackground(e=!1){const t=a.default.getTheme();if("image"===t.background.type||"default"===t.background.type&&t.background.slug){const s=k.AppStateManager.STATE_INIT.settings.themes.find(e=>e.name===t.name);if(!(t.background.blur===s.background.blur&&t.background.slug===s.background.slug))return this.getBackground(t.background.slug).then(t=>this.setBackground(t,e),()=>(t.background=Object(L.a)(s.background),this.setBackground("",!0)))}return this.setBackground("",e)}getBackground(e){return this.backgroundPromises[e]?this.backgroundPromises[e]:this.backgroundPromises[e]=he.a.cacheStorage.getFile("backgrounds/"+e).then(e=>URL.createObjectURL(e))}setBackground(e,t=!0){const s=this.chats.map(t=>t.setBackground(e));return s[s.length-1].then(()=>{t&&a.default.dispatchEvent("background_change")})}saveChatPosition(e){if(!["chat","discussion"].includes(e.type)||!e.peerId)return;const t=e.bubbles,s=t.scrollable.scrollTop,i=e.peerId+(e.threadId?"_"+e.threadId:""),n=Sn.a.getFromCache("chatPositions");if(t.scrollable.getDistanceToEnd()<=16&&t.scrollable.loadedAll.bottom||!Object.keys(t.bubbles).length)delete n[i],this.log("deleted chat position");else{const e={mids:Object(L.e)(t.bubbles,"desc"),top:s};n[i]=e,this.log("saved chat position:",e)}Sn.a.set({chatPositions:n},!0)}getChatSavedPosition(e){if(!["chat","discussion"].includes(e.type)||!e.peerId)return;const t=e.peerId+(e.threadId?"_"+e.threadId:""),s=Sn.a.getFromCache("chatPositions");return s&&s[t]}applyHighlightningColor(){let e;const t=a.default.getTheme();t.background.highlightningColor?(e=t.background.highlightningColor,document.documentElement.style.setProperty("--message-highlightning-color",e)):document.documentElement.style.removeProperty("--message-highlightning-color"),!pe.IS_TOUCH_SUPPORTED&&e&&(a.default.themeColor=function(e){return Ti(e).slice(0,-2)}(e))}applyCurrentTheme(e,t,s){return this.applyHighlightningColor(),a.default.setTheme(),t&&(this.backgroundPromises[e]=Promise.resolve(t)),this.setCurrentBackground(void 0===s?!!e:s)}chatsSelectTab(e,t){if(this.prevTab!==e){if(!1===t&&this.prevTab&&ao([e,this.prevTab].filter(Boolean)),this.prevTab){this.prevTab.classList.remove("active"),this.chatsSelectTabDebounced(),a.default.settings.animationsEnabled&&!1!==t&&Object(Cs.b)(Object(yn.a)(400),400);const s=Object(Ts.a)(this.prevTab);Object(Ts.a)(e)>s&&B.a.pushItem({type:"chat",onPop:e=>{this.setPeer(0,void 0,e),Object(Us.a)()}})}e.classList.add("active"),this.prevTab=e}}init(){document.addEventListener("paste",this.onDocumentPaste,!0),pe.IS_TOUCH_SUPPORTED||this.attachDragAndDropListeners(),this.markupTooltip=new to(this),this.markupTooltip.handleSelection()}attachDragAndDropListeners(){const e=[];let t=!1;const s=(a,o)=>co(this,void 0,void 0,(function*(){if(o===t)return;const r=a.dataTransfer.types,l=r.contains?r.contains("Files"):r.indexOf("Files")>=0;if(l&&this.canDrag()){if(o&&!e.length){const t=yield Object(me.c)(a,!0),i=l&&!t.length,o=t.filter(e=>g.has(e)).length,r=t.length-o;this.log("drag files",t),(t.length||i)&&e.push(new no(n,{icon:"dragfiles",header:"Chat.DropTitle",subtitle:"Chat.DropAsFilesDesc",onDrop:e=>{s(e,!1),po.log("drop",e),po.onDocumentPaste(e,"document")}})),(o&&!r||i)&&e.push(new no(n,{icon:"dragmedia",header:"Chat.DropTitle",subtitle:"Chat.DropQuickDesc",onDrop:e=>{s(e,!1),po.log("drop",e),po.onDocumentPaste(e,"media")}})),this.chat.container.append(n)}Object(Xt.a)(n,"is-visible",o,200,()=>{o||(e.forEach(e=>{e.destroy()}),e.length=0)}),o?e.forEach(e=>{e.setPath()}):i=0,document.body.classList.toggle("is-dragging",o),t=o}else i=0}));let i=0;document.body.addEventListener("dragenter",e=>{i++}),document.body.addEventListener("dragover",e=>{s(e,!0),Object(c.a)(e)}),document.body.addEventListener("dragleave",e=>{i--,0===i&&s(e,!1)});const n=document.createElement("div");n.classList.add("drops-container")}canDrag(){var e;const t=null===(e=this.chat)||void 0===e?void 0:e.peerId;return!(!t||a.default.isOverlayActive||!i.a.canSendToPeer(t,this.chat.threadId,"send_media"))}selectTab(e,t){!1===t&&ao([ln.sidebarEl,this.columnEl,$t.sidebarEl]),document.body.classList.toggle("is-left-column-shown",0===e);const s=this.tabId;this.log("selectTab",e,s);let i=a.default.settings.animationsEnabled?Object(_e.a)():Promise.resolve();if(-1!==s&&s!==e&&a.default.settings.animationsEnabled&&!1!==t){const e=100+(v.b.isMobile?250:200);i=Object(yn.a)(e),Object(Cs.b)(i,e)}return this.tabId=e,Object(Us.a)(),v.b.isMobile&&2===s&&e<2&&document.body.classList.remove("is-right-column-shown"),-1!==s&&e>s&&(e<2||!B.a.findItemByType("im"))&&B.a.pushItem({type:"im",onPop:e=>{this.setPeer(0,void 0,e)}}),a.default.dispatchEvent("im_tab_change",e),i}updateStatus(){return this.myId?(T.a.setUserStatus(this.myId,this.offline),rt.a.invokeApiSingle("account.updateStatus",{offline:this.offline})):Promise.resolve()}createNewChat(){const e=new Za(this,G.a,M.a,zn,i.a,o.a,r.a,n.default,hs,T.a,eo.a,$e.a,rt.a,Si.a,Ye.a,Sn.a,_t.a,Cn,f.a);this.chats.length&&e.backgroundEl.append(this.chat.backgroundEl.lastElementChild.cloneNode(!0)),this.chats.push(e)}spliceChats(e,t=!0,s,i){if(!(e>=this.chats.length)){this.chats.length>1&&t&&a.default.dispatchEvent("peer_changing",this.chat),i||(i=this.chats.splice(e,this.chats.length-e));for(let e=0;e<i.length-1;++e)B.a.removeByType("chat",!0);if(i.length>1&&i.slice(0,-1).forEach(e=>{e.container.remove()}),this.chatsSelectTab(this.chat.container,s),t){a.default.dispatchEvent("peer_changed",this.chat.peerId);const e=$t.getTab(Xa);e&&e.close();$t.sharedMediaTab.setPeer(this.chat.peerId,this.chat.threadId)&&($t.sharedMediaTab.loadSidebarMedia(!0),$t.sharedMediaTab.fillProfileElements())}i.forEach(e=>{e.beforeDestroy()}),setTimeout(()=>{i.forEach(e=>{e.destroy()})},350)}}setPeer(e,t,s){this.init&&(this.init(),this.init=null);const i=this.chat,n=this.chats.indexOf(i);if(e){if(n>0&&i.peerId&&i.peerId!==e){const s=this.chats.splice(1,this.chats.length-1);if(this.chat.peerId===e)return void this.spliceChats(0,!0,!0,s);{const i=this.setPeer(e,t);return this.spliceChats(0,!1,!1,s),i}}}else{if(n>0)return void this.spliceChats(n,void 0,s);if(v.b.activeScreen===v.a.medium)return void this.selectTab(+!this.tabId,s)}if(e===i.peerId&&v.b.activeScreen<=v.a.medium&&document.body.classList.contains("is-left-column-shown"))return this.selectTab(1,s),!1;if(e||v.b.activeScreen!==v.a.mobile){const n=i.setPeer(e,t),a=(null==n?void 0:n.cached)?n.promise:Promise.resolve();e&&a.then(()=>{setTimeout(()=>{setTimeout(()=>{this.chatsSelectTab(this.chat.container)},0),this.selectTab(1,s)},0)})}return e?void 0:(this.selectTab(0,s),!1)}setInnerPeer(e,t,s="chat",i){const n=this.chats.findIndex(t=>t.peerId===e&&t.type===s);if(-1!==n)return this.spliceChats(n+1),this.setPeer(e,t);return this.chat.inited&&this.createNewChat(),s&&(this.chat.setType(s),i&&(this.chat.threadId=i)),this.setPeer(e,t)}openScheduled(e){this.setInnerPeer(e,void 0,"scheduled")}getTypingElement(e){const t=document.createElement("span");switch(t.classList.add("peer-typing"),t.dataset.action=e._,e._){case"sendMessageTypingAction":{const e="peer-typing-text";t.classList.add(e);for(let s=0;s<3;++s){const s=document.createElement("span");s.className=e+"-dot",t.append(s)}break}case"sendMessageUploadAudioAction":case"sendMessageUploadDocumentAction":case"sendMessageUploadRoundAction":case"sendMessageUploadVideoAction":case"sendMessageUploadPhotoAction":{const e="peer-typing-upload";t.classList.add(e);break}case"sendMessageRecordAudioAction":case"sendMessageRecordRoundAction":case"sendMessageRecordVideoAction":{const e="peer-typing-record";t.classList.add(e);break}}return t}getPeerTyping(e,t){if(!T.a.isBot(e)){const s=n.default.getPeerTypings(e);if(!s||!s.length)return;const i=s[0],a={private:{sendMessageTypingAction:"Peer.Activity.User.TypingText",sendMessageUploadAudioAction:"Peer.Activity.User.SendingFile",sendMessageUploadDocumentAction:"Peer.Activity.User.SendingFile",sendMessageUploadPhotoAction:"Peer.Activity.User.SendingPhoto",sendMessageUploadVideoAction:"Peer.Activity.User.SendingVideo",sendMessageUploadRoundAction:"Peer.Activity.User.SendingVideo",sendMessageRecordVideoAction:"Peer.Activity.User.RecordingVideo",sendMessageRecordAudioAction:"Peer.Activity.User.RecordingAudio",sendMessageRecordRoundAction:"Peer.Activity.User.RecordingVideo",sendMessageGamePlayAction:"Peer.Activity.User.PlayingGame"},chat:{sendMessageTypingAction:"Peer.Activity.Chat.TypingText",sendMessageUploadAudioAction:"Peer.Activity.Chat.SendingFile",sendMessageUploadDocumentAction:"Peer.Activity.Chat.SendingFile",sendMessageUploadPhotoAction:"Peer.Activity.Chat.SendingPhoto",sendMessageUploadVideoAction:"Peer.Activity.Chat.SendingVideo",sendMessageUploadRoundAction:"Peer.Activity.Chat.SendingVideo",sendMessageRecordVideoAction:"Peer.Activity.Chat.RecordingVideo",sendMessageRecordAudioAction:"Peer.Activity.Chat.RecordingAudio",sendMessageRecordRoundAction:"Peer.Activity.Chat.RecordingVideo",sendMessageGamePlayAction:"Peer.Activity.Chat.PlayingGame"},multi:{sendMessageTypingAction:"Peer.Activity.Chat.Multi.TypingText1",sendMessageUploadAudioAction:"Peer.Activity.Chat.Multi.SendingFile1",sendMessageUploadDocumentAction:"Peer.Activity.Chat.Multi.SendingFile1",sendMessageUploadPhotoAction:"Peer.Activity.Chat.Multi.SendingPhoto1",sendMessageUploadVideoAction:"Peer.Activity.Chat.Multi.SendingVideo1",sendMessageUploadRoundAction:"Peer.Activity.Chat.Multi.SendingVideo1",sendMessageRecordVideoAction:"Peer.Activity.Chat.Multi.RecordingVideo1",sendMessageRecordAudioAction:"Peer.Activity.Chat.Multi.RecordingAudio1",sendMessageRecordRoundAction:"Peer.Activity.Chat.Multi.RecordingVideo1",sendMessageGamePlayAction:"Peer.Activity.Chat.Multi.PlayingGame1"}},o=e>0?a.private:s.length>1?a.multi:a.chat;let r=i.action;if(s.length>1){const e={};s.forEach(t=>{const s=t.action._;void 0===e[s]&&(e[s]=0),++e[s]}),Object.keys(e).length>1&&(r={_:"sendMessageTypingAction"})}const l=o[r._];if(!l)return;t||(t=document.createElement("span")).classList.add("online","peer-typing-container");let c,d=t.firstElementChild;d?d.dataset.action!==r._&&d.replaceWith(this.getTypingElement(r)):(d=this.getTypingElement(r),t.prepend(d)),e<0&&(c=[new ft.a({peerId:i.userId,onlyFirstName:!0}).element,s.length-1]);const h=Object(A.i18n)(l,c);return h.classList.add("peer-typing-description"),t.childElementCount>1?t.lastElementChild.replaceWith(h):t.append(h),t}}getPeerStatus(e){var t;return co(this,void 0,void 0,(function*(){let s;if(!e)return"";if(e<0){let t=this.getPeerTyping(e);if(t)return t;const i=yield n.default.getChatFull(-e);this.chat.log("chatInfo res:",i);i.participants_count||i.participants&&i.participants.participants&&i.participants.participants.length;return s=n.default.getChatMembersString(-e),s}{const i=T.a.getUser(e);if(a.default.myId===e)return"";if(i){if(s=T.a.getUserStatusString(i.id),!T.a.isBot(e)){let n=this.getPeerTyping(e);if(n||"userStatusOnline"!==(null===(t=i.status)||void 0===t?void 0:t._)||(n=document.createElement("span"),n.classList.add("online"),n.append(s)),n)return n}return s}}}))}setPeerStatus(e,t,s,i,n){s&&(t.innerHTML=i?"":"");const a=t.querySelector(".peer-typing-container");a&&this.getPeerTyping(e,a)||this.getPeerStatus(e).then(e=>{n()&&Object(x.a)(t,e||(i?"":""))})}};de.a&&(de.a.appImManager=po);var mo=po;var go=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class bo extends R.a{constructor(e,t){super(!1),this.listLoader=e,this.author={},this.content={},this.buttons={},this.tempId=0,this.preloader=null,this.preloaderStreamable=null,this.isFirstOpen=!0,this.pageEl=document.getElementById("page-chats"),this.zoomElements={},this.zoomSwipeStartX=0,this.zoomSwipeStartY=0,this.zoomSwipeX=0,this.zoomSwipeY=0,this.setZoomValue=(e=this.zoomElements.rangeSelector.value)=>{1===e&&(this.zoomSwipeX=0,this.zoomSwipeY=0),this.moversContainer.style.transform=`matrix(${e}, 0, 0, ${e}, ${this.zoomSwipeX}, ${this.zoomSwipeY})`,this.zoomElements.btnOut.classList.toggle("inactive",.5===e),this.zoomElements.btnIn.classList.toggle("inactive",4===e),this.toggleZoom(1!==e)},this.onClick=e=>{if(this.setMoverAnimationPromise)return;const t=e.target;if("A"===t.tagName)return;if(Object(c.a)(e),pe.IS_TOUCH_SUPPORTED)return this.highlightSwitchersTimeout?clearTimeout(this.highlightSwitchersTimeout):this.wholeDiv.classList.add("highlight-switchers"),void(this.highlightSwitchersTimeout=window.setTimeout(()=>{this.wholeDiv.classList.remove("highlight-switchers"),this.highlightSwitchersTimeout=0},3e3));const s=this.isZooming();let i=null;const n=["ckin__player","media-viewer-buttons","media-viewer-author","media-viewer-caption","zoom-container"];s&&n.push("media-viewer-movers"),n.find(e=>{try{if(i=Object(Ce.a)(t,e),i)return!0}catch(e){return!1}}),i&&(s||"IMG"!==t.tagName&&"image"!==t.tagName)||this.buttons.close.click()},this.onKeyDown=e=>{if(a.default.overlaysActive>1)return;let t=!0;"ArrowRight"===e.key?this.buttons.next.click():"ArrowLeft"===e.key?this.buttons.prev.click():"-"===e.key||"="===e.key?this.ctrlKeyDown&&this.changeZoom("="===e.key):t=!1,(e.ctrlKey||e.metaKey)&&(this.ctrlKeyDown=!0),t&&Object(c.a)(e)},this.onKeyUp=e=>{a.default.overlaysActive>1||e.ctrlKey||e.metaKey||(this.ctrlKeyDown=!1,this.isZooming()&&this.setZoomValue())},this.onWheel=e=>{if(!(a.default.overlaysActive>1||Object(Ce.a)(e.target,"media-viewer-caption")&&!this.ctrlKeyDown)&&(Object(c.a)(e),this.ctrlKeyDown)){const t=e.deltaY<0;this.changeZoom(!!t)}},this.log=Object(J.b)("AMV"),this.preloader=new ye.a,this.preloaderStreamable=new ye.a({cancelable:!1,streamable:!0}),this.preloader.construct(),this.preloaderStreamable.construct(),this.lazyLoadQueue=new te.a,this.wholeDiv=document.createElement("div"),this.wholeDiv.classList.add("media-viewer-whole"),this.overlaysDiv=document.createElement("div"),this.overlaysDiv.classList.add("overlays");const s=document.createElement("div");s.classList.add("media-viewer");const i=this.topbar=document.createElement("div");i.classList.add("media-viewer-topbar","media-viewer-appear");const n=document.createElement("div");n.classList.add("media-viewer-topbar-left"),this.buttons["mobile-close"]=N("close",{onlyMobile:!0}),this.author.container=document.createElement("div"),this.author.container.classList.add("media-viewer-author","no-select");const o=document.createElement("div");this.author.avatarEl=new ko,this.author.avatarEl.classList.add("media-viewer-userpic","avatar-44"),this.author.nameEl=document.createElement("div"),this.author.nameEl.classList.add("media-viewer-name"),this.author.date=document.createElement("div"),this.author.date.classList.add("media-viewer-date"),o.append(this.author.nameEl,this.author.date),this.author.container.append(this.author.avatarEl,o);const r=document.createElement("div");r.classList.add("media-viewer-buttons"),t.concat(["download","zoom","close"]).forEach(e=>{const t=N(e,{noRipple:!0});this.buttons[e]=t,r.append(t)}),this.buttons.zoom.classList.add("zoom-in"),this.zoomElements.container=document.createElement("div"),this.zoomElements.container.classList.add("zoom-container"),this.zoomElements.btnOut=N("zoomout",{noRipple:!0}),this.zoomElements.btnOut.addEventListener("click",()=>this.changeZoom(!1)),this.zoomElements.btnIn=N("zoomin",{noRipple:!0}),this.zoomElements.btnIn.addEventListener("click",()=>this.changeZoom(!0)),this.zoomElements.rangeSelector=new Le({step:.5,min:.5,max:4,withTransition:!0},1),this.zoomElements.rangeSelector.setListeners(),this.zoomElements.rangeSelector.setHandlers({onScrub:this.setZoomValue,onMouseUp:()=>this.setZoomValue()}),this.zoomElements.container.append(this.zoomElements.btnOut,this.zoomElements.rangeSelector.container,this.zoomElements.btnIn),this.wholeDiv.append(this.zoomElements.container),this.content.main=document.createElement("div"),this.content.main.classList.add("media-viewer-content"),this.content.container=document.createElement("div"),this.content.container.classList.add("media-viewer-container"),this.content.media=document.createElement("div"),this.content.media.classList.add("media-viewer-media"),this.content.container.append(this.content.media),this.content.main.append(this.content.container),s.append(this.content.main),this.overlaysDiv.append(s),n.append(this.buttons["mobile-close"],this.author.container),i.append(n,r),this.buttons.prev=document.createElement("div"),this.buttons.prev.className="media-viewer-switcher media-viewer-switcher-left",this.buttons.prev.innerHTML='<span class="tgico-down media-viewer-prev-button"></span>',this.buttons.next=document.createElement("div"),this.buttons.next.className="media-viewer-switcher media-viewer-switcher-right",this.buttons.next.innerHTML='<span class="tgico-down media-viewer-next-button"></span>',this.moversContainer=document.createElement("div"),this.moversContainer.classList.add("media-viewer-movers"),this.wholeDiv.append(this.overlaysDiv,this.buttons.prev,this.buttons.next,this.topbar,this.moversContainer),this.setNewMover()}get target(){return this.listLoader.current}set target(e){this.listLoader.current=e}setListeners(){if(this.buttons.download.addEventListener("click",this.onDownloadClick),[this.buttons.close,this.buttons["mobile-close"],this.preloaderStreamable.preloader].forEach(e=>{e.addEventListener("click",this.close.bind(this))}),[[-1,this.buttons.prev],[1,this.buttons.next]].forEach(([e,t])=>{t.addEventListener("click",t=>{Object(c.a)(t),this.setMoverPromise||this.listLoader.go(e)})}),this.buttons.zoom.addEventListener("click",()=>{this.isZooming()?this.toggleZoom(!1):this.changeZoom(!0)}),this.wholeDiv.addEventListener("click",this.onClick),this.listLoader.onJump=(e,t)=>{t?this.onNextClick(e):this.onPrevClick(e)},pe.IS_TOUCH_SUPPORTED){new zt({element:this.wholeDiv,onSwipe:(e,t)=>{if(Pe.isFullScreen())return;if(Math.abs(e)/yt.a.windowW>.2||e>125)return e<0?this.buttons.prev.click():this.buttons.next.click(),!0;return(Math.abs(t)/yt.a.windowH>.2||t>125)&&(this.buttons.close.click(),!0)},verifyTouchTarget:e=>"INPUT"!==e.target.tagName&&!Object(Ce.a)(e.target,"media-viewer-caption")})}}toggleZoom(e){const t=this.isZooming();if((this.zoomElements.rangeSelector.mousedown||this.ctrlKeyDown)&&(e=!0),t===e)return;void 0===e&&(e=!t),this.buttons.zoom.classList.toggle("zoom-in",!e),this.zoomElements.container.classList.toggle("is-visible",e);const s=e?this.zoomElements.rangeSelector.value:1;if(this.setZoomValue(s),this.zoomElements.rangeSelector.setProgress(s),this.videoPlayer&&this.videoPlayer.lockControls(!e&&void 0),e){if(this.zoomSwipeHandler)this.zoomSwipeHandler.setListeners();else{let e,t;const s=-1;this.zoomSwipeHandler=new zt({element:this.moversContainer,onFirstSwipe:()=>{e=t=0,this.moversContainer.classList.add("no-transition")},onSwipe:(i,n)=>{[i,n]=[i*s,n*s],this.zoomSwipeX+=i-e,this.zoomSwipeY+=n-t,[e,t]=[i,n],this.setZoomValue()},onReset:()=>{this.moversContainer.classList.remove("no-transition")},cursor:"move"})}this.zoomElements.rangeSelector.setProgress(s)}else e||this.zoomSwipeHandler.removeListeners()}changeZoom(e){this.zoomElements.rangeSelector.addProgress(.5*(e?1:-1)),this.setZoomValue()}isZooming(){return this.zoomElements.container.classList.contains("is-visible")}setBtnMenuToggle(e){const t=Ie({onlyMobile:!0},"bottom-left",e);this.topbar.append(t)}close(e){var t;if(e&&Object(c.a)(e),this.setMoverAnimationPromise)return Promise.reject();B.a.removeByType("media"),this.lazyLoadQueue.clear();const s=this.setMoverToTarget(null===(t=this.target)||void 0===t?void 0:t.element,!0).then(({onAnimationEnd:e})=>e);return this.listLoader.reset(),this.listLoader.cleanup&&this.listLoader.cleanup(),this.setMoverPromise=null,this.tempId=-1,window.appMediaViewer=void 0,this.zoomSwipeHandler&&(this.zoomSwipeHandler.removeListeners(),this.zoomSwipeHandler=void 0),window.removeEventListener("keydown",this.onKeyDown),window.removeEventListener("keyup",this.onKeyUp),window.removeEventListener("wheel",this.onWheel,{capture:!0}),s.finally(()=>{this.wholeDiv.remove(),a.default.isOverlayActive=!1,I.a.checkAnimations(!1)}),s}setMoverToTarget(e,t=!1,s=0){return go(this,void 0,void 0,(function*(){this.dispatchEvent("setMoverBefore");const i=this.content.mover;t||(i.innerHTML="");const n=this.isZooming()&&t?this.zoomElements.rangeSelector.value:1;this.removeCenterFromMover(i);const o=0!==s,r=a.default.settings.animationsEnabled?o?350:200:0;let l,c;e&&(e instanceof ko||e.classList.contains("grid-item")?(l=e,c=e.getBoundingClientRect()):e instanceof SVGImageElement||e.parentElement instanceof SVGForeignObjectElement?(l=Object(Ce.a)(e,"attachment"),c=l.getBoundingClientRect()):e.classList.contains("profile-avatars-avatar")&&(l=Object(Ce.a)(e,"profile-avatars-container"),c=l.getBoundingClientRect(),t&&e.getBoundingClientRect().left!==c.left&&(e=l=c=void 0))),e||(e=this.content.media),c||(l=e.parentElement,c=e.getBoundingClientRect());let d=!1;if(e!==this.content.media&&!e.classList.contains("profile-avatars-avatar")){const s=function(e,t){const s=e.getBoundingClientRect(),i=t.getBoundingClientRect();let{top:n,bottom:a}=i;const o=t.querySelector(".sticky");if(o){n=o.getBoundingClientRect().bottom}if(s.top>=a||s.bottom<=n||s.right<=i.left||s.left>=i.right)return null;const r={top:!1,right:!1,bottom:!1,left:!1,vertical:0,horizontal:0},l="visualViewport"in window?window.visualViewport:window,c=(l.width||l.innerWidth,l.height||l.innerHeight);return{rect:{top:s.top<n&&0!==n?(r.top=!0,++r.vertical,n):s.top,right:0,bottom:s.bottom>a&&a!==c?(r.bottom=!0,++r.vertical,a):s.bottom,left:0},overflow:r}}(l,Object(Ce.a)(l,"scrollable"));!t||s&&2!==s.overflow.vertical&&2!==s.overflow.horizontal?!s||1!==s.overflow.vertical&&1!==s.overflow.horizontal||(d=!0):(l=(e=this.content.media).parentElement,c=e.getBoundingClientRect())}const h=this.content.media.getBoundingClientRect();let u,p,m,g="";if(o?(u=1===s?yt.a.windowW:-h.width,p=h.top):(u=c.left,p=c.top),g+=`translate3d(${u}px,${p}px,0) `,e instanceof HTMLImageElement||e instanceof HTMLVideoElement||"DIV"===e.tagName){if(i.firstElementChild&&i.firstElementChild.classList.contains("media-viewer-aspecter")){m=i.firstElementChild;const e=m.querySelector(".ckin__player");if(e){const t=e.firstElementChild;m.append(t),e.remove()}m.style.cssText||(i.classList.remove("active"),this.setFullAspect(m,h,c),i.offsetLeft,i.classList.add("active"))}else m=document.createElement("div"),m.classList.add("media-viewer-aspecter"),i.prepend(m);m.style.cssText=`width: ${c.width}px; height: ${c.height}px; transform: scale3d(${h.width/c.width}, ${h.height/c.height}, 1);`}i.style.width=h.width+"px",i.style.height=h.height+"px";const b=c.width/h.width,v=c.height/h.height;o||(g+=`scale3d(${b},${v},1) `);let f=window.getComputedStyle(l).getPropertyValue("border-radius");const y=function(e){let t=e.split(" ");if(4!==t.length){t[0]||(t[0]="0px");for(let e=t.length;e<4;++e)t[e]=t[e%2]||t[0]||"0px"}return t}(f);if(f=y.map(e=>parseInt(e)/b+"px").join(" "),o||(i.style.borderRadius=f),t&&1!==n){const e=yt.a.windowW/2-c.width/2,t=yt.a.windowH/2-c.height/2,s=c.left-e,i=c.top-t;this.moversContainer.style.transform=`matrix(${b}, 0, 0, ${v}, ${s}, ${i})`}else i.style.transform=g;let w;d&&(i.style.opacity="0");const L=e.classList.contains("is-out"),S=this.setMoverAnimationPromise=Object(oe.a)(),E={onAnimationEnd:S},M=setTimeout(()=>{S.isFulfilled||S.isRejected||S.resolve()},1e3);if(S.finally(()=>{this.dispatchEvent("setMoverAfter"),this.setMoverAnimationPromise===S&&(this.setMoverAnimationPromise=null),clearTimeout(M)}),t)return e instanceof SVGSVGElement&&(w=i.querySelector("path"),w&&this.sizeTailPath(w,h,b,r,!1,L,f)),e.classList.contains("media-viewer-media")&&i.classList.add("hiding"),this.wholeDiv.classList.add("backwards"),setTimeout(()=>{this.wholeDiv.classList.remove("active")},0),setTimeout(()=>{i.style.borderRadius=f,i.firstElementChild&&(i.firstElementChild.style.borderRadius=f)},r/2),setTimeout(()=>{i.innerHTML="",i.classList.remove("moving","active","hiding"),i.style.cssText="display: none;",S.resolve()},r),i.classList.remove("opening"),E;{let t,s;if(e instanceof HTMLVideoElement){const t=Array.from(e.parentElement.querySelectorAll("img"));t.length&&(e=t.pop())}if("DIV"===e.tagName||"AVATAR-ELEMENT"===e.tagName){const n=Array.from(e.querySelectorAll("img")).pop();n&&(t=new Image,s=n.src,i.append(t))}else if(e instanceof HTMLImageElement)t=new Image,s=e.src;else if(e instanceof HTMLVideoElement)t=document.createElement("video"),t.src=e.src;else if(e instanceof SVGSVGElement){const t=e.dataset.clipId,s=t+"-mv",{width:n,height:a}=h,o=document.createElementNS("http://www.w3.org/2000/svg","svg");o.setAttributeNS(null,"width",""+n),o.setAttributeNS(null,"height",""+a),o.setAttributeNS(null,"viewBox",`0 0 ${n} ${a}`),o.setAttributeNS(null,"preserveAspectRatio","xMidYMid meet"),o.insertAdjacentHTML("beforeend",e.firstElementChild.outerHTML.replace(t,s)),o.insertAdjacentHTML("beforeend",e.lastElementChild.outerHTML.replace(t,s));const r=o.firstElementChild,l=r.firstElementChild.firstElementChild;if(l instanceof SVGUseElement){let e,t=l.getAttributeNS(null,"transform");t=t.replace(/translate\((.+?), (.+?)\) scale\((.+?), (.+?)\)/,(e,t,s,i,o)=>`translate(${t=2!==(t=+t)?n-2/b:2/b}, ${a}) scale(${+i/b}, ${+o/v})`),l.setAttributeNS(null,"transform",t),w=r.firstElementChild.lastElementChild;const s=f.split(" ").map(e=>parseInt(e));e=L?io(0,0,n-9/b,a,...s):io(9/b,0,n-9/b,a,...s),w.setAttributeNS(null,"d",e)}const c=o.lastElementChild;c.setAttributeNS(null,"width",""+h.width),c.setAttributeNS(null,"height",""+h.height),i.prepend(o)}m&&(m.style.borderRadius=f,t&&m.append(t)),t=i.querySelector("video, img"),t instanceof HTMLImageElement&&(t.classList.add("thumbnail"),m||(t.style.width=h.width+"px",t.style.height=h.height+"px"),s&&(yield Object(Rt.b)(t,s))),i.style.display="",Object(_e.b)(()=>{i.classList.add(o?"moving":"active")})}return i.classList.add("opening"),yield Object(_e.a)(),i.style.transform=`translate3d(${h.left}px,${h.top}px,0) scale3d(1,1,1)`,d&&(i.style.opacity=""),m&&this.setFullAspect(m,h,c),setTimeout(()=>{i.style.borderRadius="",i.firstElementChild&&(i.firstElementChild.style.borderRadius="")},0),i.dataset.timeout=""+setTimeout(()=>{i.classList.remove("moving","opening"),m&&(i.querySelector("video"),i.classList.remove("active"),m.style.cssText="",i.offsetLeft),i.classList.add("center","no-transition"),i.classList.add("active"),delete i.dataset.timeout,S.resolve()},r),w&&this.sizeTailPath(w,h,b,r,!0,L,f),E}))}setFullAspect(e,t,s){const i=t.width/t.height;let{width:n,height:a}=s;i>0?n=a*i:a=n*i,e.style.cssText=`width: ${n}px; height: ${a}px; transform: scale3d(${t.width/n}, ${t.height/a}, 1);`}sizeTailPath(e,t,s,i,n,a,o){const r=Date.now(),{width:l,height:c}=t;i/=2;const d=o.split(" ").map(e=>parseInt(e)),h=()=>{const t=Date.now()-r;let o=i?t/i:1;o>1&&(o=1),n&&(o=1-o);const u=d.map(e=>e*o);let p;p=a?io(0,0,l-9/s*o,c,...u):io(9/s*o,0,l,c,...u),e.setAttributeNS(null,"d",p),t<i&&Object(_e.b)(h)};h()}removeCenterFromMover(e){if(e.classList.contains("center")){const t=this.content.media.getBoundingClientRect();e.style.transform=`translate3d(${t.left}px,${t.top}px,0)`,e.classList.remove("center"),e.offsetLeft,e.classList.remove("no-transition")}}moveTheMover(e,t=!0){const s=yt.a.windowW;this.removeCenterFromMover(e),e.classList.add("moving"),e.dataset.timeout&&clearTimeout(+e.dataset.timeout);const i=e.getBoundingClientRect(),n=e.style.transform.replace(/translate3d\((.+?),/,(e,n)=>{const a=t?-i.width:s;return e.replace(n,a+"px")});e.style.transform=n,setTimeout(()=>{e.remove()},350)}setNewMover(){const e=document.createElement("div");if(e.classList.add("media-viewer-mover"),e.style.display="none",this.content.mover){this.content.mover.parentElement.append(e)}else this.moversContainer.append(e);return this.content.mover=e}updateMediaSource(e,t,s){const i=e.tagName.toLowerCase()===s?e:e.querySelector(s);if(i){if(!e.classList.contains("document-ico")&&Object(Ce.a)(e,"attachment")){const t=e.parentElement.parentElement.querySelector(".preloader-container");if(t){if("video"===s)return void(t.classList.contains("manual")&&t.click());t.remove()}}Object(Rt.a)(i,t),i.classList.contains("thumbnail")&&i.parentElement.classList.contains("media-container-aspecter")&&i.classList.remove("thumbnail")}}setAuthorInfo(e,t){Object(x.a)(this.author.date,Object(re.c)(t)),Object(x.a)(this.author.nameEl,new ft.a({peerId:e,dialog:!1,onlyFirstName:!1,plainText:!1}).element);let s=this.author.avatarEl;this.author.avatarEl=this.author.avatarEl.cloneNode(),this.author.avatarEl.setAttribute("peer",""+(e||a.default.myId)),s.parentElement.replaceChild(this.author.avatarEl,s)}_openMedia(e,t,s,i,n,o=!1,l=[],c=[],d){return go(this,void 0,void 0,(function*(){if(this.setMoverPromise)return this.setMoverPromise;this.setAuthorInfo(s,t);const u="document"===e._,p=u&&e.mime_type&&(["video","gif"].includes(e.type)||0===e.mime_type.indexOf("video/"));this.isFirstOpen&&(this.isFirstOpen=!1,this.listLoader.setTargets(l,c,o),window.appMediaViewer=this),this.buttons.prev.classList.toggle("hide",!this.listLoader.previous.length),this.buttons.next.classList.toggle("hide",!this.listLoader.next.length);const m=this.content.media,g=!n||n===m;g&&(n=m),this.target={element:n};const b=++this.tempId;m.firstElementChild&&(m.innerHTML="");if(0!==i)this.moveTheMover(this.content.mover,1===i),this.setNewMover();else{window.addEventListener("keydown",this.onKeyDown),window.addEventListener("keyup",this.onKeyUp),pe.IS_TOUCH_SUPPORTED||window.addEventListener("wheel",this.onWheel,{passive:!1,capture:!0});const e=document.getElementById("main-columns");this.pageEl.insertBefore(this.wholeDiv,e),this.wholeDiv.offsetLeft,this.wholeDiv.classList.add("active"),a.default.isOverlayActive=!0,I.a.checkAnimations(!0),h.IS_MOBILE_SAFARI||B.a.pushItem({type:"media",onPop:e=>{if(this.setMoverAnimationPromise)return!1;this.close()}})}const f=this.content.mover,y=yt.a.windowW;let w=0;const L=yt.a.windowH;L<1e6&&!v.b.isMobile&&(w=120);const S=L-120-w;let E=Promise.resolve();const C=r.a.setAttachmentSize(e,m,y,S,!v.b.isMobile,void 0,!!(u&&e.w&&e.h)).photoSize;if(g){const t=he.a.getCacheContext(e,C.type);let s;if(t.downloaded)s=new Image,s.src=t.url;else{const i=r.a.getStrippedThumbIfNeeded(e,t,!0);i&&(E=i.loadPromise,s=i.image)}s&&(s.classList.add("thumbnail"),m.append(s))}const k=!(!u||!e.supportsStreaming),T=k?this.preloaderStreamable:this.preloader;let P;if(p){const t=d&&"gif"!==e.type,s=document.createElement("video"),a=()=>this.setMoverToTarget(n,!1,i).then(({onAnimationEnd:i})=>{const a=f.firstElementChild&&f.firstElementChild.classList.contains("media-viewer-aspecter")?f.firstElementChild:f,o=f.querySelector("video");o&&o.remove(),s.setAttribute("playsinline","true"),s.addEventListener("timeupdate",()=>{this.tempId!==b&&s.pause()}),s.addEventListener("error",()=>{4!==s.error.code&&this.log.error("Error "+s.error.code+"; details: "+s.error.message),T&&T.detach()},{once:!0}),this.addEventListener("setMoverAfter",()=>{s.src="",s.load()},{once:!0}),h.IS_SAFARI&&(s.autoplay=!0),"gif"===e.type&&(s.muted=!0,s.autoplay=!0,s.loop=!0),a.append(s);const r=new Promise(e=>{s.addEventListener("canplay",e,{once:!0})}),l=()=>{"gif"!==e.type&&(s.dataset.ckin="default",s.dataset.overlay="1",Promise.all([r,i]).then(()=>{if(this.tempId!==b)return;(this.videoPlayer=new Pe(s,!0,k)).addEventListener("toggleControls",e=>{this.wholeDiv.classList.toggle("has-video-controls",e)}),this.addEventListener("setMoverBefore",()=>{this.wholeDiv.classList.remove("has-video-controls"),this.videoPlayer.removeListeners(),this.videoPlayer=void 0},{once:!0}),this.isZooming()&&this.videoPlayer.lockControls(!1)}))};if(k){i.then(()=>{s.readyState<s.HAVE_FUTURE_DATA&&T.attach(f,!0)});const e=()=>{s.addEventListener("canplay",()=>{T.detach(),s.parentElement.classList.remove("is-buffering")},{once:!0})};s.addEventListener("waiting",()=>{const t=s.networkState===s.NETWORK_LOADING,i=s.readyState<s.HAVE_FUTURE_DATA;t&&i&&(e(),T.attach(f,!0),s.parentElement.classList.add("is-buffering"))}),e()}this.lazyLoadQueue.unshift({load:()=>{const o=he.a.getCacheContext(e),r=k?Promise.resolve():M.a.downloadDoc(e);return k||i.then(()=>{o.url||T.attach(f,!0,r)}),Promise.all([r,i]).then(()=>{if(this.tempId!==b)return void this.log.warn("media viewer changed video");if(t){const e=fe.setSingleMedia(s,d);this.addEventListener("setMoverBefore",()=>{e()},{once:!0})}const e=o.url;n instanceof SVGSVGElement?a.firstElementChild.lastElementChild.append(s):Object(Rt.a)(s,e),this.updateMediaSource(n,e,"video"),l()}),r}})});P=E.then(a)}else{const t=()=>this.setMoverToTarget(n,!1,i).then(({onAnimationEnd:t})=>{this.lazyLoadQueue.unshift({load:()=>{const s=he.a.getCacheContext(e,C.type),i=u?M.a.downloadDoc(e):r.a.preloadPhoto(e,C);return t.then(()=>{s.url||this.preloader.attachPromise(i)}),Promise.all([t,i]).then(()=>{var e;if(this.tempId!==b)return void this.log.warn("media viewer changed photo");const t=s.url;if(n instanceof SVGSVGElement){if(this.updateMediaSource(n,t,"img"),this.updateMediaSource(f,t,"img"),v.b.isMobile){const e=f.querySelectorAll("img");e&&e.length&&e.forEach(e=>{e.classList.remove("thumbnail")})}}else{const s=f.firstElementChild&&f.firstElementChild.classList.contains("media-viewer-aspecter")?f.firstElementChild:f,i="IMG"===(null===(e=s.firstElementChild)||void 0===e?void 0:e.tagName)?s.firstElementChild:null;if(!i||i.src!==t){let e=new Image;e.classList.add("thumbnail"),Object(Rt.a)(e,t,()=>{this.updateMediaSource(n,t,"img"),i&&Object(_e.b)(()=>{i.remove()}),s.append(e)})}}}).catch(e=>{this.log.error(e),this.preloader.attach(f),this.preloader.setManual()}),i}})});P=E.then(t)}return this.setMoverPromise=P.catch(()=>{this.setMoverAnimationPromise=null}).finally(()=>{this.setMoverPromise=null})}))}}var vo=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class fo extends bo{constructor(){let e;super(new E({processItem:e=>{const t="inputMessagesFilterDocument"===this.searchContext.inputFilter._,{mid:s,peerId:n}=e,a=i.a.getMediaFromMessage(e);if(a&&(!t||fo.isMediaCompatibleForDocumentViewer(a)))return{element:null,mid:s,peerId:n}}}),["delete","forward"]),this.onPrevClick=e=>{this.openMedia(this.getMessageByPeer(e.peerId,e.mid),e.element,-1)},this.onNextClick=e=>{this.openMedia(this.getMessageByPeer(e.peerId,e.mid),e.element,1)},this.onDeleteClick=()=>{const e=this.target;new Bs(e.peerId,[e.mid],"chat",()=>{this.target={element:this.content.media},this.close()})},this.onForwardClick=()=>{const e=this.target;e.mid&&new Ds({[e.peerId]:[e.mid]},()=>this.close())},this.onAuthorClick=e=>{const{mid:t,peerId:s}=this.target;if(t&&t!==Number.MAX_SAFE_INTEGER){const i=this.searchContext.threadId;this.close(e).then(()=>{if(v.b.isMobile){const e=$t.getTab(qt);e&&e.close()}const e=this.getMessageByPeer(s,t);mo.setInnerPeer(e.peerId,t,i?"discussion":void 0,i)})}},this.onDownloadClick=()=>{const{peerId:e,mid:t}=this.target,s=this.getMessageByPeer(e,t);if(s.media.photo)r.a.savePhotoFile(s.media.photo,mo.chat.bubbles.lazyLoadQueue.queueId);else{let e=null;e=s.media.webpage?s.media.webpage.document:s.media.document,e&&M.a.saveDocFile(e,mo.chat.bubbles.lazyLoadQueue.queueId)}},this.listLoader.onEmptied=()=>{this.close()},this.content.caption=document.createElement("div"),this.content.caption.classList.add("media-viewer-caption");const t=()=>{e&&clearTimeout(e),e=window.setTimeout(()=>{e=void 0,this.content.caption.classList.remove("is-focused")},800)};this.content.caption.addEventListener("touchstart",()=>{v.b.isMobile&&(this.content.caption.classList.add("is-focused"),e&&(clearTimeout(e),e=void 0),document.addEventListener("touchend",t,{once:!0}))});new P.b(this.content.caption).onAdditionalScroll=t,this.wholeDiv.append(this.content.caption),Object(l.b)(this.buttons.delete,this.onDeleteClick);const s=[{icon:"forward",text:"Forward",onClick:this.onForwardClick},{icon:"download",text:"MediaViewer.Context.Download",onClick:this.onDownloadClick},{icon:"delete danger",text:"Delete",onClick:this.onDeleteClick}];this.setBtnMenuToggle(s),this.btnMenuDelete=s[s.length-1].element,this.setListeners()}get searchContext(){return this.listLoader.searchContext}setListeners(){super.setListeners(),this.buttons.forward.addEventListener("click",this.onForwardClick),this.author.container.addEventListener("click",this.onAuthorClick);const e=t=>{if(t.target instanceof HTMLAnchorElement){const s=t.target.getAttribute("onclick");if(!s||s.includes("showMaskedAlert"))return;return Object(c.a)(t),this.close().then(()=>{this.content.caption.removeEventListener("click",e,{capture:!0}),t.target.click()}),!1}};this.content.caption.addEventListener("click",e,{capture:!0})}getMessageByPeer(e,t){return this.searchContext.isScheduled?i.a.getScheduledMessageByPeer(e,t):i.a.getMessageByPeer(e,t)}setCaption(e){const t=e.message;let s="";t&&(s=Z.b.wrapRichText(t,{entities:e.totalEntities})),b(this.content.caption.firstElementChild,s),this.content.caption.classList.toggle("hide",!t)}setSearchContext(e){return this.listLoader.setSearchContext(e),this}openMedia(e,t,s=0,n=!1,a=[],o=[]){const r=Object.create(null,{_openMedia:{get:()=>super._openMedia}});return vo(this,void 0,void 0,(function*(){if(this.setMoverPromise)return this.setMoverPromise;const l=e.mid,c=e.fromId,d=i.a.getMediaFromMessage(e);this.buttons.forward.classList.toggle("hide","messageService"===e._);const h=i.a.canDeleteMessage(e);[this.buttons.delete,this.btnMenuDelete].forEach(e=>{e.classList.toggle("hide",!h)}),this.setCaption(e);const u=r._openMedia.call(this,d,e.date,c,s,t,n,a,o,e);return this.target.mid=l,this.target.peerId=e.peerId,u}))}static isMediaCompatibleForDocumentViewer(e){return"photo"===e._||g.has(e.mime_type)}}class yo extends S{constructor(e){super(Object.assign(Object.assign({},e),{loadMore:(e,t,s)=>{if(this.peerId<0||!t)return Promise.resolve({count:0,items:[]});const i=null==e?void 0:e.photoId;return r.a.getUserPhotos(this.peerId,i,s).then(e=>{const t=e.photos.map(e=>({element:null,photoId:e}));return{count:e.count,items:t}})}})),this.loadedAllUp=!0,this.peerId=e.peerId}}var wo=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class Lo extends bo{constructor(e){super(new yo({peerId:e}),[]),this.onPrevClick=e=>{this.openMedia(e.photoId,e.element,-1)},this.onNextClick=e=>{this.openMedia(e.photoId,e.element,1)},this.onDownloadClick=()=>{r.a.savePhotoFile(r.a.getPhoto(this.target.photoId),mo.chat.bubbles.lazyLoadQueue.queueId)},this.peerId=e,this.setBtnMenuToggle([{icon:"download",text:"MediaViewer.Context.Download",onClick:this.onDownloadClick}]),this.setListeners()}openMedia(e,t,s=0,i,n){const a=Object.create(null,{_openMedia:{get:()=>super._openMedia}});return wo(this,void 0,void 0,(function*(){if(this.setMoverPromise)return this.setMoverPromise;const o=r.a.getPhoto(e),l=a._openMedia.call(this,o,o.date,this.peerId,s,t,!1,i,n);return this.target.photoId=o.id,l}))}}var So=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};const Eo=e=>{d.a.removeFromAvatarsCache(e),Array.from(document.querySelectorAll('avatar-element[peer="'+e+'"]')).forEach(e=>{e.update()})};function Mo(e,t,s,a,o,l){return So(this,void 0,void 0,(function*(){let c=yield n.default.getFullPhoto(t);if(!s()||!c)return;const d=()=>Array.from(e.querySelectorAll("img")).find(e=>!e.classList.contains("emoji"))?e:null;if(t<0){const e=!!a,n="inputMessagesFilterChatPhotos";if(!a&&(a=yield i.a.getSearch({peerId:t,inputFilter:{_:n},maxId:0,limit:1}).then(e=>e.history[0]),!s()))return;if(a){a.action.photo.id!==c.id&&(e||(a=i.a.generateFakeAvatarMessage(t,c)));const s=e=>e.map(e=>({element:e.element,mid:e.item.mid,peerId:e.item.peerId}));return void(new fo).setSearchContext({peerId:t,inputFilter:{_:n}}).openMedia(a,d(),void 0,void 0,o?s(o):void 0,l?s(l):void 0)}}if(c){"string"==typeof a&&(c=r.a.getPhoto(a));const e=e=>e.map(e=>({element:e.element,photoId:e.item}));new Lo(t).openMedia(c.id,d(),void 0,o?e(o):void 0,l?e(l):void 0)}}))}a.default.addEventListener("avatar_update",Eo),a.default.addEventListener("peer_title_edit",e=>{d.a.isAvatarCached(e)||Eo(e)});const Io=new Map,Co=new Set;class ko extends HTMLElement{constructor(){super(...arguments),this.isDialog=!1,this.addedToQueue=!1}connectedCallback(){if(this.isDialog="1"===this.getAttribute("dialog"),""===this.getAttribute("clickable")){this.setAttribute("clickable","set");let e=!1;Object(l.b)(this,t=>So(this,void 0,void 0,(function*(){if(Object(c.a)(t),e)return;const s=this.peerId;e=!0,yield Mo(this,this.peerId,()=>this.peerId===s),e=!1})))}}disconnectedCallback(){const e=Io.get(this.peerId);e&&e.has(this)&&(e.delete(this),e.size||Io.delete(this.peerId)),this.lazyLoadQueue&&this.lazyLoadQueue.unobserve(this)}static get observedAttributes(){return["peer","dialog","peer-title"]}attributeChangedCallback(e,t,s){if("peer"===e){if(this.peerId===+s)return;this.peerId=o.a.getPeerMigratedTo(+s)||+s;const e=+t;if(e){const t=Io.get(e);t&&(t.delete(this),t.size||Io.delete(e))}this.update()}else"peer-title"===e?this.peerTitle=s:"dialog"===e&&(this.isDialog="1"===s)}r(e=!1){const t=d.a.putPhoto(this,this.peerId,this.isDialog,this.peerTitle,e),s=t?t.loadPromise:Promise.resolve();return this.loadPromises&&(t&&t.cached&&this.loadPromises.push(s),s.finally(()=>{this.loadPromises=void 0})),t}update(){if(this.lazyLoadQueue){if(!Co.has(this.peerId)){if(this.addedToQueue)return;this.addedToQueue=!0;let e=Io.get(this.peerId);return e||(e=new Set,Io.set(this.peerId,e)),e.add(this),this.r(!0),void this.lazyLoadQueue.push({div:this,load:()=>(Co.add(this.peerId),this.update())})}this.addedToQueue&&this.lazyLoadQueue.unobserve(this)}Co.add(this.peerId);const e=this.r(),t=e?e.loadPromise:Promise.resolve();this.addedToQueue&&t.finally(()=>{this.addedToQueue=!1});const s=Io.get(this.peerId);if(s){s.delete(this);const e=Array.from(s);Io.delete(this.peerId);for(let t=0,s=e.length;t<s;++t)e[t].update()}return t}}customElements.define("avatar-element",ko);class To{constructor(){this.onArchiveClick=()=>{let e=i.a.getDialogOnly(this.selectedId);e&&i.a.editPeerFolders([e.peerId],+!e.folder_id)},this.onPinClick=()=>{i.a.toggleDialogPin(this.selectedId,this.filterId).catch(e=>{"PINNED_DIALOGS_TOO_MUCH"===e.type&&(this.filterId>=1?at({langPackKey:"PinFolderLimitReached"}):new ht("pinned-dialogs-too-much",{buttons:[{langKey:"OK",isCancel:!0},{langKey:"FiltersSetupPinAlert",callback:()=>{new Ki(ln).open()}}],descriptionLangKey:"PinToTopLimitReached2",descriptionLangArgs:[Object(A.i18n)("Chats",[a.default.config.pinned_dialogs_count_max])]}).show())})},this.onUnmuteClick=()=>{i.a.mutePeer(this.selectedId,!1)},this.onMuteClick=()=>{i.a.mutePeer(this.selectedId,!0)},this.onUnreadClick=()=>{const e=i.a.getDialogOnly(this.selectedId);e&&(e.unread_count?(i.a.readHistory(this.selectedId,e.top_message),i.a.markDialogUnread(this.selectedId,!0)):i.a.markDialogUnread(this.selectedId))},this.onDeleteClick=()=>{new xt(this.selectedId)},this.onContextMenu=e=>{this.init&&(this.init(),this.init=null);let t=null;try{t=Object(mt.a)(e.target,"LI")}catch(e){}if(t){if(e instanceof MouseEvent&&e.preventDefault(),this.element.classList.contains("active"))return!1;e instanceof MouseEvent&&(e.cancelBubble=!0),this.filterId=Do.filterId,this.selectedId=+t.dataset.peerId,this.dialog=i.a.getDialogOnly(this.selectedId),this.buttons.forEach(e=>{const t=e.verify();e.element.classList.toggle("hide",!t)}),this.buttons[this.buttons.length-1].element.lastChild.replaceWith(Object(A.i18n)(o.a.getDeleteButtonText(this.selectedId))),t.classList.add("menu-open"),Object(se.e)(e,this.element),Object(se.d)(this.element,()=>{t.classList.remove("menu-open"),this.selectedId=this.dialog=this.filterId=void 0})}}}init(){this.buttons=[{icon:"unread",text:"MarkAsUnread",onClick:this.onUnreadClick,verify:()=>{var e;return!!(!(null===(e=this.dialog.pFlags)||void 0===e?void 0:e.unread_mark)&&!this.dialog.unread_count)}},{icon:"readchats",text:"MarkAsRead",onClick:this.onUnreadClick,verify:()=>{var e;return!(!(null===(e=this.dialog.pFlags)||void 0===e?void 0:e.unread_mark)&&!this.dialog.unread_count)}},{icon:"pin",text:"ChatList.Context.Pin",onClick:this.onPinClick,verify:()=>{var e;return!(this.filterId>1?i.a.filtersStorage.getFilter(this.filterId).pinned_peers.includes(this.dialog.peerId):!!(null===(e=this.dialog.pFlags)||void 0===e?void 0:e.pinned))}},{icon:"unpin",text:"ChatList.Context.Unpin",onClick:this.onPinClick,verify:()=>{var e;return this.filterId>1?i.a.filtersStorage.getFilter(this.filterId).pinned_peers.includes(this.dialog.peerId):!!(null===(e=this.dialog.pFlags)||void 0===e?void 0:e.pinned)}},{icon:"mute",text:"ChatList.Context.Mute",onClick:this.onMuteClick,verify:()=>this.selectedId!==a.default.myId&&!_t.a.isPeerLocalMuted(this.dialog.peerId)},{icon:"unmute",text:"ChatList.Context.Unmute",onClick:this.onUnmuteClick,verify:()=>this.selectedId!==a.default.myId&&_t.a.isPeerLocalMuted(this.dialog.peerId)},{icon:"archive",text:"Archive",onClick:this.onArchiveClick,verify:()=>0===this.filterId&&this.selectedId!==a.default.myId},{icon:"unarchive",text:"Unarchive",onClick:this.onArchiveClick,verify:()=>1===this.filterId&&this.selectedId!==a.default.myId},{icon:"delete danger",text:"Delete",onClick:this.onDeleteClick,verify:()=>!0}],this.element=Ee(this.buttons),this.element.id="dialogs-contextmenu",this.element.classList.add("contextmenu"),document.getElementById("page-chats").append(this.element)}}var Po,xo;!function(e){e[e.Connected=0]="Connected",e[e.Connecting=1]="Connecting",e[e.Closed=2]="Closed",e[e.TimedOut=3]="TimedOut"}(Po||(Po={}));class Ao{constructor(e){this.hadConnect=!1,this.connecting=!1,this.timedOut=!1,this.updating=!1,this.setConnectionStatus=()=>{sn.a.get("dc").then(e=>{e||(e=tn.a.baseDcId),this.setFirstConnectionTimeout&&(clearTimeout(this.setFirstConnectionTimeout),this.setFirstConnectionTimeout=0);const t=a.default.connectionStatus["NET-"+e],s=t&&t.status===Po.Connected;this.connecting&&s&&Xs.a.forceGetDifference(),s&&!this.hadConnect&&(this.hadConnect=!0),this.timedOut=t&&t.status===Po.TimedOut,this.connecting=!s,this.retryAt=t&&t.retryAt,de.b&&this.log("connecting",this.connecting),this.setState()})},this.setStatusText=(e,t)=>{this.currentLangPackKey!==e&&(this.currentLangPackKey=e,Object(x.a)(this.statusEl,Object(A.i18n)(e,t)),this.statusPreloader.attach(this.statusEl))},this.setState=()=>{const e=Ao.CHANGE_STATE_DELAY;if(this.connecting)if(this.timedOut){const e=this.getA("ConnectionStatus.ForceReconnect",()=>rt.a.forceReconnect());this.setStatusText("ConnectionStatus.TimedOut",[e])}else if(this.hadConnect)if(void 0!==this.retryAt){const e=document.createElement("span"),t=this.retryAt,s=()=>{const s=Date.now();e.innerText=""+Math.round((t-s)/1e3),s>t&&clearInterval(i)},i=setInterval(s,1e3);s();const n=this.getA("ConnectionStatus.Reconnect",()=>rt.a.forceReconnectTimeout());this.setStatusText("ConnectionStatus.ReconnectIn",[e,n])}else this.setStatusText("ConnectionStatus.Reconnecting");else this.setStatusText("ConnectionStatus.Waiting");else this.updating&&this.setStatusText("Updating");de.b&&this.log("setState",this.connecting||this.updating),window.requestAnimationFrame(()=>{this.setStateTimeout&&clearTimeout(this.setStateTimeout);this.setStateTimeout=window.setTimeout(()=>{Object(Xt.a)(this.statusContainer,"is-shown",this.connecting||this.updating,200),this.setStateTimeout=0,de.b&&this.log("setState: isShown:",this.connecting||this.updating)},e)})},this.log=Object(J.b)("CS"),this.statusContainer=document.createElement("div"),this.statusContainer.classList.add("connection-status"),this.statusEl=Object(U.a)("btn-primary bg-warning connection-status-button",{noRipple:!0}),this.statusPreloader=new ye.a({cancelable:!1}),this.statusPreloader.constructContainer({color:"transparent",bold:!0}),this.statusContainer.append(this.statusEl),e.prepend(this.statusContainer),a.default.addEventListener("connection_status_change",e=>{const t=e;console.log(t),this.setConnectionStatus()}),a.default.addEventListener("state_synchronizing",e=>{e||(this.updating=!0,de.b&&this.log("updating",this.updating),this.setState())}),a.default.addEventListener("state_synchronized",e=>{const t=e;de.b&&this.log("state_synchronized",t),t||(this.updating=!1,de.b&&this.log("updating",this.updating),this.setState())}),this.setFirstConnectionTimeout=window.setTimeout(this.setConnectionStatus,Ao.CHANGE_STATE_DELAY+1e3)}getA(e,t){const s=document.createElement("a");return s.classList.add("force-reconnect"),s.append(Object(A.i18n)(e)),s.addEventListener("click",e=>{Object(c.a)(e),t()}),s}}Ao.CHANGE_STATE_DELAY=1e3,function(e){e[e.Error=-1]="Error",e[e.Pending=0]="Pending",e[e.Sent=1]="Sent",e[e.Read=2]="Read"}(xo||(xo={}));var Oo=function(e,t,s,i){return new(s||(s=Promise))((function(n,a){function o(e){try{l(i.next(e))}catch(e){a(e)}}function r(e){try{l(i.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,r)}l((i=i.apply(e,t||[])).next())}))};class _o extends xs{constructor(e,t){super({getIndex:e=>i.a.getDialogOnly(e)[this.indexKey],onDelete:e=>{e.dom.listEl.remove(),jo.onListLengthChange()},onSort:(e,t)=>{const s=e.dom.listEl.parentElement!==this.list;Ps(e.dom.listEl,this.list,t),s&&jo.onListLengthChange()},onElementCreate:(e,t)=>{const s=t?[]:void 0,{dom:i}=jo.addListDialog({dialog:e.id,loadPromises:s,isBatch:t});return e.dom=i,(null==s?void 0:s.length)&&(e.loadPromises=s,Promise.all(s).finally(()=>{delete e.loadPromises})),e},updateElementWith:_e.c}),this.list=e,this.indexKey=t}clear(){this.list.innerHTML="",super.clear()}}class Fo{constructor(){this.chatsContainer=document.getElementById("chatlist-container"),this.scroll=null,this.log=Object(J.b)("DIALOGS",J.a.Log|J.a.Error|J.a.Warn|J.a.Debug),this.contextMenu=new To,this.sortedLists={},this.scrollables={},this.folders={menu:document.getElementById("folders-tabs"),menuScrollContainer:null,container:document.getElementById("folders-container")},this.filtersRendered={},this.lastActiveElements=new Set,this.offsets={top:0,bottom:0},this.onTabChange=()=>{this.scroll=this.scrollables[this.filterId],this.scroll.loadedAll.top=!0,this.scroll.loadedAll.bottom=!1,this.offsets.top=this.offsets.bottom=0,this.loadDialogsPromise=void 0,this.sortedList=this.sortedLists[this.filterId],this.onChatsScroll()},this._onListLengthChange=()=>{if(this.checkIfPlaceholderNeeded(),this.filterId>0)return;const e=this.chatList,t=e.childElementCount,s=e.parentElement.parentElement,i=e.parentElement.nextElementSibling,n=!!i.childElementCount;if(t>=10)return void(n&&(s.classList.remove("with-contacts"),i.innerHTML="",this.loadContacts=void 0,this.processContact=void 0));if(n)return;s.classList.add("with-contacts");const a=new nn({name:"Contacts",noDelimiter:!0,fakeGradientDelimiter:!0});a.container.classList.add("hide"),T.a.getContacts(void 0,void 0,"online").then(e=>{const t=new Os({avatarSize:42,new:!0});this.loadContacts=()=>{const s=yt.a.windowH/60|0;e.splice(0,s).filter(this.verifyUserIdForContacts).forEach(e=>{t.add(e)}),e.length||(this.loadContacts=void 0)},this.loadContacts(),this.processContact=e=>{if(e<0)return;const s=this.verifyUserIdForContacts(e),i=t.has(e);!i&&s?t.add(e):i&&!s&&t.delete(e)};const s=t.list;s.classList.add("chatlist-new"),this.setListClickListener(s),a.content.append(s),a.container.classList.remove("hide")}),i.append(a.container)},this.verifyUserIdForContacts=e=>!i.a.getDialogOnly(e),this.onChatsRegularScroll=()=>{this.sliceTimeout&&clearTimeout(this.sliceTimeout),this.sliceTimeout=window.setTimeout(()=>{this.sliceTimeout=void 0,this.chatList.childElementCount&&!this.processContact&&Object(_e.c)(()=>{const e=performance.now(),t=this.scroll.scrollTop,s=this.chatList.firstElementChild,i=this.scroll.container.getBoundingClientRect(),n=s.getBoundingClientRect(),a=Array.from(this.scroll.splitUp.children);let o=this.scroll.splitUp.offsetTop;o&&t<o&&(o-=t);const r=i.y+o,l=i.y,c=Object(mt.a)(document.elementFromPoint(Math.ceil(n.x),Math.ceil(r+1)),s.tagName),d=Object(mt.a)(document.elementFromPoint(Math.ceil(n.x),Math.floor(l+i.height-1)),s.tagName);if(!c||!d)return;const u=c.getBoundingClientRect().y-r,p=[],m=a.indexOf(c),g=a.indexOf(d),b=h.IS_SAFARI?[]:a.slice(0,Math.max(0,m-10)),v=a.slice(g+10);b.length&&(this.scroll.loadedAll.top=!1),v.length&&(this.scroll.loadedAll.bottom=!1),p.push(...b),p.push(...v),p.forEach(e=>{const t=+e.dataset.peerId;this.deleteDialog(t)}),this.setOffsets(),this.scroll.scrollTop=c.offsetTop-u,this.log("slice time",performance.now()-e)})},200)},this.onChatsScrollTop=()=>{this.onChatsScroll("top")},this.onChatsScroll=(e="bottom")=>{if(!this.scroll.loadedAll[e])return this.loadDialogsPromise?this.loadDialogsPromise:(this.log("onChatsScroll",e),this.loadDialogs(e));this.loadContacts&&this.loadContacts()},this.chatsPreloader=Object(se.f)(null,!0),this.allUnreadCount=this.folders.menu.querySelector(".badge"),this.folders.menuScrollContainer=this.folders.menu.parentElement;const e=document.createElement("div");e.classList.add("connection-status-bottom"),e.append(this.folders.container),pe.IS_TOUCH_SUPPORTED&&_s(this.folders.container,e=>{const t=s.prevId();s(e?t+1:t-1)}),this.setFilterId(0),this.addFilter({id:this.filterId,title:"",titleEl:Object(A.i18n)("ChatList.Filter.AllChats"),orderIndex:0}),this.sortedList=this.sortedLists[this.filterId],this.scroll=this.scrollables[this.filterId],a.default.addEventListener("user_update",e=>{var t;const s=this.getDialogDom(e);if(s&&!T.a.isBot(e)&&e!==a.default.myId){const i="userStatusOnline"===(null===(t=T.a.getUser(e).status)||void 0===t?void 0:t._);s.avatarEl.classList.toggle("is-online",i)}}),a.default.addEventListener("dialog_flush",({peerId:e})=>{const t=i.a.getDialogOnly(e);t&&(this.setLastMessage(t,void 0,void 0,void 0,void 0,void 0,!0),this.validateDialogForFilter(t),this.setFiltersUnreadCount())}),a.default.addEventListener("dialogs_multiupdate",e=>{for(const t in e){const s=e[t];this.updateDialog(s),this.processContact&&this.processContact(+t),this.validateDialogForFilter(s)}this.setFiltersUnreadCount()}),a.default.addEventListener("dialog_drop",({peerId:e})=>{this.deleteDialog(e),this.setFiltersUnreadCount(),this.processContact&&this.processContact(e)}),a.default.addEventListener("dialog_unread",({peerId:e})=>{const t=i.a.getDialogOnly(e);t&&(this.setUnreadMessages(t),this.validateDialogForFilter(t),this.setFiltersUnreadCount())}),a.default.addEventListener("dialog_notify_settings",e=>{this.setUnreadMessages(e)}),a.default.addEventListener("dialog_draft",({dialog:e,drop:t,peerId:s})=>{t?this.sortedList.delete(s):this.updateDialog(e),this.processContact&&this.processContact(s)}),a.default.addEventListener("peer_changed",e=>{for(const t of this.lastActiveElements)+t.dataset.peerId!==e&&(t.classList.remove("active"),this.lastActiveElements.delete(t));Array.from(document.querySelectorAll(`[data-autonomous="0"] li[data-peer-id="${e}"]`)).forEach(e=>{e.classList.add("active"),this.lastActiveElements.add(e)})}),a.default.addEventListener("filter_update",e=>{if(!this.filtersRendered[e.id])return void this.addFilter(e);if(e.id===this.filterId){const t=i.a.dialogsStorage.getFolder(e.id);this.validateListForFilter();for(let e=0,s=t.length;e<s;++e){const s=t[e];this.updateDialog(s)}this.setFiltersUnreadCount()}this.filtersRendered[e.id].title.innerHTML=Z.a.wrapEmojiText(e.title)}),a.default.addEventListener("filter_delete",e=>{const t=this.filtersRendered[e.id];t&&(this.folders.menu.firstElementChild.click(),t.container.remove(),t.menu.remove(),delete this.sortedLists[e.id],delete this.scrollables[e.id],delete this.filtersRendered[e.id],Object.keys(this.filtersRendered).length<=1&&this.folders.menuScrollContainer.classList.add("hide"))}),a.default.addEventListener("filter_order",e=>{const t=this.folders.menu;e.forEach(e=>{const s=i.a.filtersStorage.getFilter(e),n=this.filtersRendered[e];this.sortedLists[e].indexKey=i.a.dialogsStorage.getDialogIndexKey(e),Ps(n.menu,t,s.orderIndex),Ps(n.container,this.folders.container,s.orderIndex)}),this.indexKey=i.a.dialogsStorage.getDialogIndexKey(this.filterId)}),a.default.addEventListener("peer_typings",({peerId:e,typings:t})=>{const s=i.a.getDialogOnly(e);s&&(t.length?this.setTyping(s):this.unsetTyping(s))}),a.default.addEventListener("state_cleared",()=>{k.default.getState().then(e=>{T.a.clear(),G.a.clear();const t=i.a.filtersStorage.filters;for(const e in t)a.default.dispatchEvent("updateDialogFilter",{_:"updateDialogFilter",id:+e});i.a.clear(),this.validateListForFilter(),this.onStateLoaded(e)})});const t=new P.a(this.folders.menuScrollContainer);e.prepend(this.folders.menuScrollContainer);const s=Object(ee.a)(this.folders.menu,this.folders.container,(e,t)=>{e=+t.dataset.filterId||0,this.filterId!==e&&(this.sortedLists[e].clear(),this.setFilterId(e),this.onTabChange())},()=>{for(const e in this.sortedLists)+e!==this.filterId&&this.sortedLists[e].clear()},void 0,t);this.folders.menu.firstElementChild.click(),i.a.construct(),k.default.getState().then(e=>this.onStateLoaded(e)).then(()=>{const e=i.a.dialogsStorage.isDialogsLoaded(0),t=i.a.dialogsStorage.isDialogsLoaded(1),s=e||t,n=e?Promise.resolve():i.a.getConversationsAll("",0),a=t?Promise.resolve():i.a.getConversationsAll("",1);n.finally(()=>{a.then(()=>{this.accumulateArchivedUnread(),s&&(Xs.a.updatesState.syncLoading||Promise.resolve()).then(()=>{i.a.refreshConversations()})})})}),new Ao(this.chatsContainer),this.chatsContainer.append(e),setTimeout(()=>{le.b.loadLottieWorkers()},200),this.onListLengthChange=ot(this._onListLengthChange,100,!1,!0)}get chatList(){return this.sortedList.list}setFilterId(e){this.filterId=e,this.indexKey=i.a.dialogsStorage?i.a.dialogsStorage.getDialogIndexKey(this.filterId):"index",a.default.filterId=e}onStateLoaded(e){return Oo(this,void 0,void 0,(function*(){_t.a.getNotifyPeerTypeSettings();const t=i.a.filtersStorage.getDialogFilters().then(e=>{for(const t of e)this.addFilter(t)});return e.filters&&Object.keys(e.filters).length&&(yield t,this.showFiltersPromise&&(yield this.showFiltersPromise)),k.default.storagesResults.dialogs.length&&Si.a.addMissedDialogs(),this.onChatsScroll()}))}getOffsetIndex(e){return{index:this.scroll.loadedAll[e]?0:this.offsets[e]}}isDialogMustBeInViewport(e){if(void 0!==e.migratedTo||!this.testDialogForFilter(e))return!1;const t=this.getOffsetIndex("top"),s=this.getOffsetIndex("bottom");if(!t.index&&!s.index)return!0;const i=e[this.indexKey];return(!t.index||i<=t.index)&&(!s.index||i>=s.index)}deleteDialog(e){this.sortedList.delete(e)}updateDialog(e){if(!this.isDialogMustBeInViewport(e))return void this.deleteDialog(e.peerId);if(!this.sortedList.has(e.peerId))return void this.sortedList.add(e.peerId);const t=this.getDialogDom(e.peerId);t&&(this.setLastMessage(e,void 0,t,void 0,void 0,void 0,!0),this.sortedList.update(e.peerId))}setFilterUnreadCount(e,t){var s;const n=0===e?this.allUnreadCount:null===(s=this.filtersRendered[e])||void 0===s?void 0:s.unread;if(!n)return;t=t||i.a.dialogsStorage.getFolder(e);let a=0,o=0;t.forEach(t=>{const s=_t.a.isPeerLocalMuted(t.peerId,!0);if(s&&0===e)return;const i=+!!t.unread_count||+t.pFlags.unread_mark||0;s?a+=i:o+=i}),n.classList.toggle("badge-gray",a&&!o);const r=a+o;n.innerText=r?""+r:""}setFiltersUnreadCount(){for(const e in this.filtersRendered)this.setFilterUnreadCount(+e);this.setFilterUnreadCount(0)}validateListForFilter(){const e=i.a.filtersStorage.getFilter(this.filterId);this.sortedList.getAll().forEach(t=>{const s=i.a.getDialogOnly(t.id);this.testDialogForFilter(s,e||null)||this.deleteDialog(t.id)})}validateDialogForFilter(e,t){this.getDialogDom(e.peerId)&&(this.testDialogForFilter(e,t)||this.deleteDialog(e.peerId))}testDialogForFilter(e,t=i.a.filtersStorage.getFilter(this.filterId)){return!(!e||t&&!i.a.filtersStorage.testDialogForFilter(e,t)||!t&&this.filterId!==e.folder_id)}generateScrollable(e,t){const s=new P.b(null,"CL",500);s.container.addEventListener("scroll",this.onChatsRegularScroll),s.container.dataset.filterId=""+t,s.onScrolledTop=this.onChatsScrollTop,s.onScrolledBottom=this.onChatsScroll,s.setVirtualContainer(e);const n=new _o(e,i.a.dialogsStorage?i.a.dialogsStorage.getDialogIndexKey(t):"index");return this.scrollables[t]=s,this.sortedLists[t]=n,s}addFilter(e){if(this.filtersRendered[e.id])return;const t=document.createElement("div");t.classList.add("menu-horizontal-div-item");const s=document.createElement("span"),i=document.createElement("span");i.classList.add("text-super"),e.titleEl?i.append(e.titleEl):i.innerHTML=Z.a.wrapEmojiText(e.title);const n=document.createElement("div");n.classList.add("badge","badge-20","badge-primary");const a=document.createElement("i");s.append(i,n,a),t.append(s),Object(ie.ripple)(t);Ps(t,this.folders.menu,e.orderIndex);const o=this.createChatList(),r=this.generateScrollable(o,e.id);r.container.classList.add("tabs-tab","chatlist-parts");const l=document.createElement("div");l.classList.add("chatlist-top");const c=document.createElement("div");c.classList.add("chatlist-bottom"),l.append(o),r.container.append(l,c);const d=r.container;Ps(r.container,this.folders.container,e.orderIndex),this.setListClickListener(o,null,!0),this.filtersRendered[e.id]={menu:t,container:d,unread:n,title:i},!this.showFiltersPromise&&Object.keys(this.filtersRendered).length>1&&(this.showFiltersPromise=new Promise(e=>{window.setTimeout(()=>{this.showFiltersPromise=void 0,Object.keys(this.filtersRendered).length>1&&(this.folders.menuScrollContainer.classList.remove("hide"),this.setFiltersUnreadCount()),e()},0)}))}loadDialogs(e){if(this.loadDialogsPromise)return this.loadDialogsPromise;const t=new Promise(s=>Oo(this,void 0,void 0,(function*(){const{chatList:n,filterId:a}=this;let o=yt.a.windowH/72*1.25|0,r=0;const{index:l}=this.getOffsetIndex(e);if(l)if("top"===e){const e=i.a.dialogsStorage.getFolder(a,!0),t=e.findIndex(e=>e[this.indexKey]<=l),s=Math.max(0,t-o);o=t-s,r=e[s][this.indexKey]+1}else r=l;try{const s=i.a.getConversations("",r,o,a,!0);if(!s.cached&&!n.childElementCount){n.parentElement.append(this.chatsPreloader)}const l=yield s.promise;if(this.loadDialogsPromise!==t)return;if("bottom"===e?l.isEnd&&(this.scroll.loadedAll[e]=!0):l.isTopEnd&&(this.scroll.loadedAll[e]=!0),l.dialogs.length){const t="top"===e?l.dialogs.slice().reverse():l.dialogs,s=[],i=[],n=e=>{i.push(e)};t.forEach(e=>{const t=this.sortedList.add(e.peerId,!0,n,!1);t.loadPromises&&s.push(...t.loadPromises)}),yield Promise.all(s).finally(),i.forEach(e=>e())}else this.onListLengthChange();const c=l.dialogs["top"===e?0:l.dialogs.length-1];c&&(this.offsets[e]=c[this.indexKey]),this.log.debug("getDialogs "+o+" dialogs by offset:",r,l,n.childElementCount),setTimeout(()=>{this.scroll.onScroll()},0)}catch(e){this.log.error(e)}this.chatsPreloader.parentElement&&this.chatsPreloader.remove(),s()}))).finally(()=>{this.loadDialogsPromise=void 0});return this.loadDialogsPromise=t}generateEmptyPlaceholder(e){const t="empty-placeholder",s=document.createElement("div");s.classList.add(t,t+"-"+e.classNameType);const i=document.createElement("div");i.classList.add(t+"-header"),Object(A._i18n)(i,e.title);const n=document.createElement("div");return n.classList.add(t+"-subtitle"),e.subtitle&&Object(A._i18n)(n,e.subtitle,e.subtitleArgs),s.append(i,n),{container:s,header:i,subtitle:n}}checkIfPlaceholderNeeded(){if(1===this.filterId)return;const e=this.chatList,t=e.parentElement;let s=Array.from(t.children).find(e=>e.matches(".empty-placeholder"));const n=this.scroll.loadedAll.bottom&&!e.childElementCount;if(n&&s)return;if(!n)return void(s&&(t.classList.remove("with-placeholder"),s.remove()));let a;if(this.filterId){a=this.generateEmptyPlaceholder({title:"FilterNoChatsToDisplay",subtitle:"FilterNoChatsToDisplayInfo",classNameType:"folder"}),s=a.container,s.prepend(function({emoji:e,width:t,height:s}){const i=document.createElement("div"),n=hs.getAnimatedEmojiSticker(e);return n?Ls({doc:n,div:i,loop:!1,play:!0,width:t,height:s,emoji:e}).then(()=>{}):i.classList.add("media-sticker-wrapper"),{container:i}}({emoji:"📂",width:128,height:128}).container);const e=Object(U.a)("btn-primary btn-color-primary btn-control tgico",{text:"FilterHeaderEdit",icon:"settings"});Object(l.b)(e,()=>{new Vi(ln).open(i.a.filtersStorage.getFilter(this.filterId))}),s.append(e)}else{a=this.generateEmptyPlaceholder({title:"ChatList.Main.EmptyPlaceholder.Title",classNameType:"dialogs"}),s=a.container;const e=document.createElement("img");e.classList.add("empty-placeholder-dialogs-icon"),Promise.all([T.a.getContacts().then(e=>{let t,s;e.length?(t="ChatList.Main.EmptyPlaceholder.Subtitle",s=[Object(A.i18n)("Contacts.Count",[e.length])]):(t="ChatList.Main.EmptyPlaceholder.SubtitleNoContacts",s=[]);new A.default.IntlElement({key:t,args:s,element:a.subtitle})}),Object(Rt.b)(e,"assets/img/EmptyChats.svg"),Object(_e.d)()]).then(()=>{s.classList.add("visible")}),s.prepend(e)}t.append(s),t.classList.add("with-placeholder")}setOffsets(){const e=this.chatList,t=this.getDialogFromElement(e.firstElementChild),s=this.getDialogFromElement(e.lastElementChild);this.offsets.top=t[this.indexKey],this.offsets.bottom=s[this.indexKey]}getDialogFromElement(e){return i.a.getDialogOnly(+e.dataset.peerId)}setListClickListener(e,t,s=!1,n=!1,a=!1){let o;const r=(a?mo.setInnerPeer:mo.setPeer).bind(mo);e.dataset.autonomous=""+ +n,e.addEventListener("mousedown",e=>{if(0!==e.button)return;this.log("dialogs click list");const s=e.target,i=Object(mt.a)(s,"LI");if(i){if(n){const e=o===i;o&&!e&&o.classList.remove("active"),i&&(i.classList.add("active"),o=i,this.lastActiveElements.add(i))}if(i){t&&t();const e=+i.dataset.peerId,s=+i.dataset.mid||void 0;r(e,s)}else r(0)}},{capture:!0}),de.b&&e.addEventListener("dblclick",e=>{const t=Object(mt.a)(e.target,"LI");if(t){const e=+t.dataset.peerId;this.log("debug dialog:",i.a.getDialogByPeerId(e))}}),s&&Object(se.a)(e,this.contextMenu.onContextMenu)}createChatList(e={}){const t=document.createElement("ul");return t.classList.add("chatlist"),e.new&&t.classList.add("chatlist-new"),t}setLastMessage(e,t,s,n,l,c=!1,d=!1){if(!s&&!(s=this.getDialogDom(e.peerId)))return;let h;if(t||(e.draft&&"draftMessage"===e.draft._&&(h=e.draft),t=i.a.getMessageByPeer(e.peerId,e.top_message)),"messageEmpty"===t._)return s.lastMessageSpan.innerHTML="",s.lastTimeSpan.innerHTML="",delete s.listEl.dataset.mid,void(d&&this.setUnreadMessages(e,s,c));const u=e.peerId;{let e;if(!t.deleted&&!h){const s=i.a.getMediaFromMessage(t);if(s&&("photo"===s._||["video","gif"].includes(s.type))){const i=r.a.choosePhotoSize(s,20,20);if("photoSizeEmpty"!==i._&&(e=document.createElement("div"),e.classList.add("dialog-subtitle-media"),ys({photo:s,message:t,container:e,withoutPreloader:!0,size:i,loadPromises:l}),"video"===s.type)){const t=document.createElement("span");t.classList.add("tgico-play"),e.append(t)}}}const c=!!e&&!!(null==t?void 0:t.message);let d;if(d=n&&t.message?i.a.wrapMessageForReply(t,void 0,void 0,!1,n,c):h?i.a.wrapMessageForReply(h):t.deleted?document.createDocumentFragment():i.a.wrapMessageForReply(t,void 0,void 0,!1,void 0,c),e&&d.prepend(e),Object(x.a)(s.lastMessageSpan,d),h){const e=document.createElement("b");e.classList.add("danger"),e.append(Object(A.i18n)("Draft"),": "),s.lastMessageSpan.prepend(e)}else if(u<0&&u!==t.fromId&&!t.action){const e=o.a.getPeer(t.fromId);if(e&&e.id){const i=document.createElement("b");e.id===a.default.myId?i.append(Object(A.i18n)("FromYou")):i.append(new ft.a({peerId:t.fromId,onlyFirstName:!0}).element),i.append(": "),s.lastMessageSpan.prepend(i)}}}if(!t.deleted||h){const e=h?Math.max(h.date,t.date||0):t.date;Object(x.a)(s.lastTimeSpan,Object(re.b)(new Date(1e3*e)))}else s.lastTimeSpan.textContent="";null!==d&&(d?this.setUnreadMessages(e,s,c):s.listEl.dataset.mid=t.mid)}setUnreadMessages(e,t=this.getDialogDom(e.peerId),s=!1){var n;if(1===e.folder_id&&this.accumulateArchivedUnread(),!t)return;if(!s){const s=_t.a.isPeerLocalMuted(e.peerId,!0);s!==t.listEl.classList.contains("is-muted")&&Object(Xt.a)(t.listEl,"is-muted",s,200)}let o;if("draftMessage"!==(null===(n=e.draft)||void 0===n?void 0:n._)){const t=i.a.getMessageByPeer(e.peerId,e.top_message);!t.deleted&&t.pFlags.out&&t.peerId!==a.default.myId&&(o=t)}!function(e,t,s){let i;if((null==t?void 0:t.pFlags.out)&&(i=t.pFlags.is_outgoing?"sending":t.pFlags.unread?"check":"checks"),!i)return void(e.textContent="");const n="tgico-"+i,a=e.lastElementChild;if(a&&a.classList.contains(n))return;const o=document.createElement("i");o.classList.add("sending-status-icon",n),e.append(o),a&&a.remove()}(t.statusSpan,o);const r=i.a.filtersStorage.getFilter(this.filterId);let l;l=r?-1!==r.pinned_peers.indexOf(e.peerId):!!e.pFlags.pinned;const c=l||!!e.unread_count||e.pFlags.unread_mark,d=Object(us.a)(t.unreadBadge);c&&!d&&t.subtitleEl.append(t.unreadBadge);const h=e.unread_mentions_count>1,u=t.mentionsBadge&&Object(us.a)(t.mentionsBadge);h&&(t.mentionsBadge||(t.mentionsBadge=document.createElement("div"),t.mentionsBadge.className="dialog-subtitle-badge badge badge-24 mention mention-badge",t.mentionsBadge.innerText="@",t.subtitleEl.insertBefore(t.mentionsBadge,t.lastMessageSpan.nextSibling)));const p=s?0:200;if(Object(Xt.a)(t.unreadBadge,"is-visible",c,p,c?void 0:()=>{t.unreadBadge.remove()},d?0:2),t.mentionsBadge&&Object(Xt.a)(t.mentionsBadge,"is-visible",h,p,h?void 0:()=>{t.mentionsBadge.remove(),delete t.mentionsBadge},u?0:2),!c)return;l?t.unreadBadge.classList.add("tgico-chatspinned","tgico"):t.unreadBadge.classList.remove("tgico-chatspinned","tgico");let m=!0,g=!1;e.unread_mentions_count&&1===e.unread_count?(t.unreadBadge.innerText="@",g=!0):e.unread_count||e.pFlags.unread_mark?t.unreadBadge.innerText=""+(e.unread_count||" "):(t.unreadBadge.innerText="",m=!1),t.unreadBadge.classList.toggle("unread",m),t.unreadBadge.classList.toggle("mention",g)}accumulateArchivedUnread(){this.accumulateArchivedTimeout||(this.accumulateArchivedTimeout=window.setTimeout(()=>{this.accumulateArchivedTimeout=0;const e=i.a.dialogsStorage.getFolder(1).reduce((e,t)=>e+t.unread_count,0);a.default.dispatchEvent("dialogs_archived_unread",{count:e})},0))}getDialogDom(e){const t=this.sortedList.get(e);return null==t?void 0:t.dom}getDialog(e){if("number"==typeof e){const t=i.a.getDialogOnly(e);return t||{peerId:e,peer:o.a.getOutputPeer(e),pFlags:{}}}return e}addListDialog(e){const t=this.getDialog(e.dialog);e.autonomous=!1;const s=this.addDialogNew(e);if(s){_t.a.isPeerLocalMuted(t.peerId,!0)&&s.dom.listEl.classList.add("is-muted"),this.setLastMessage(t,void 0,s.dom,void 0,e.loadPromises,e.isBatch,!0)}return s}addDialogNew(e){return this.addDialog(e.dialog,e.container,e.drawStatus,e.rippleEnabled,e.onlyFirstName,e.meAsSaved,e.append,e.avatarSize,e.autonomous,e.lazyLoadQueue,e.loadPromises)}addDialog(e,t,s=!0,i=!0,n=!1,r=!0,l=!0,c=54,d=!!t,h,u){var p,m;const g=this.getDialog(e),b=g.peerId,v=new ko;if(v.loadPromises=u,v.lazyLoadQueue=h,v.setAttribute("dialog",r?"1":"0"),v.setAttribute("peer",""+b),v.classList.add("dialog-avatar","avatar-"+c),s&&b!==a.default.myId&&b>0){const e=T.a.getUser(b);e.status&&"userStatusOnline"===e.status._&&v.classList.add("is-online")}const f=document.createElement("div");f.classList.add("user-caption");const y=document.createElement("span");y.classList.add("user-title");const w=new ft.a({peerId:b,dialog:r,onlyFirstName:n,plainText:!1});y.append(w.element),y.classList.add("tgico");const L=o.a.getPeer(b);(null===(p=null==L?void 0:L.pFlags)||void 0===p?void 0:p.verified)&&y.append(Bt());const S=document.createElement("span");S.classList.add("user-last-message"),S.setAttribute("dir","auto");const E=document.createElement("li");i&&Object(ie.ripple)(E),E.append(v,f),E.dataset.peerId=""+b;const M=document.createElement("span");M.classList.add("message-status","sending-status");const I=document.createElement("span");I.classList.add("message-time");const C=document.createElement("div");C.className="dialog-subtitle-badge badge badge-24";const k=document.createElement("p");k.classList.add("dialog-title");const P=document.createElement("span");P.classList.add("dialog-title-details"),P.append(M,I),k.append(y,P);const x=document.createElement("p");x.classList.add("dialog-subtitle"),x.append(S),f.append(k,x);const A={avatarEl:v,captionDiv:f,titleSpan:w.element,titleSpanContainer:y,statusSpan:M,lastTimeSpan:I,unreadBadge:C,lastMessageSpan:S,containerEl:E,listEl:E,subtitleEl:x};if(t){t[l?"append":"prepend"](E)}return d||(null===(m=mo.chat)||void 0===m?void 0:m.peerId)!==b||(E.classList.add("active"),this.lastActiveElements.add(E)),{dom:A,dialog:g}}setTyping(e){const t=this.getDialogDom(e.peerId);if(!t)return;let s=t.lastMessageSpan.querySelector(".peer-typing-container");s?mo.getPeerTyping(e.peerId,s):(s=mo.getPeerTyping(e.peerId),Object(x.a)(t.lastMessageSpan,s),t.lastMessageSpan.classList.add("user-typing"))}unsetTyping(e){const t=this.getDialogDom(e.peerId);t&&(t.lastMessageSpan.classList.remove("user-typing"),this.setLastMessage(e,null,t,void 0,void 0,void 0,null))}}const jo=new Fo;de.a.appDialogsManager=jo;var Do=t.default=jo},143:function(e,t,s){"undefined"!=typeof self&&self,e.exports=function(e){var t={};function s(i){if(t[i])return t[i].exports;var n=t[i]={i:i,l:!1,exports:{}};return e[i].call(n.exports,n,n.exports,s),n.l=!0,n.exports}return s.m=e,s.c=t,s.d=function(e,t,i){s.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:i})},s.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},s.t=function(e,t){if(1&t&&(e=s(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var i=Object.create(null);if(s.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)s.d(i,n,function(t){return e[t]}.bind(null,n));return i},s.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return s.d(t,"a",t),t},s.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},s.p="",s(s.s=0)}([function(e,t,s){"use strict";(function(t){var s=t.AudioContext||t.webkitAudioContext,i=function(e){if(!i.isRecordingSupported())throw new Error("Recording is not supported in this browser");e||(e={}),this.state="inactive",this.config=Object.assign({bufferLength:4096,encoderApplication:2049,encoderFrameSize:20,encoderPath:"encoderWorker.min.js",encoderSampleRate:48e3,maxFramesPerPage:40,mediaTrackConstraints:!0,monitorGain:0,numberOfChannels:1,recordingGain:1,resampleQuality:3,streamPages:!1,reuseWorker:!1,wavBitDepth:16},e),this.encodedSamplePosition=0};i.isRecordingSupported=function(){return s&&t.navigator&&t.navigator.mediaDevices&&t.navigator.mediaDevices.getUserMedia&&t.WebAssembly},i.prototype.clearStream=function(){this.stream&&(this.stream.getTracks?this.stream.getTracks().forEach((function(e){e.stop()})):this.stream.stop(),delete this.stream),this.audioContext&&this.closeAudioContext&&(this.audioContext.close(),delete this.audioContext)},i.prototype.encodeBuffers=function(e){if("recording"===this.state){for(var t=[],s=0;s<e.numberOfChannels;s++)t[s]=e.getChannelData(s);this.encoder.postMessage({command:"encode",buffers:t})}},i.prototype.initAudioContext=function(e){return e&&e.context?(this.audioContext=e.context,this.closeAudioContext=!1):(this.audioContext=new s,this.closeAudioContext=!0),this.audioContext},i.prototype.initAudioGraph=function(){this.encodeBuffers=function(){delete this.encodeBuffers},this.scriptProcessorNode=this.audioContext.createScriptProcessor(this.config.bufferLength,this.config.numberOfChannels,this.config.numberOfChannels),this.scriptProcessorNode.connect(this.audioContext.destination),this.scriptProcessorNode.onaudioprocess=e=>{this.encodeBuffers(e.inputBuffer)},this.monitorGainNode=this.audioContext.createGain(),this.setMonitorGain(this.config.monitorGain),this.monitorGainNode.connect(this.audioContext.destination),this.recordingGainNode=this.audioContext.createGain(),this.setRecordingGain(this.config.recordingGain),this.recordingGainNode.connect(this.scriptProcessorNode)},i.prototype.initSourceNode=function(e){return e&&e.context?t.Promise.resolve(e):t.navigator.mediaDevices.getUserMedia({audio:this.config.mediaTrackConstraints}).then(e=>(this.stream=e,this.audioContext.createMediaStreamSource(e)))},i.prototype.loadWorker=function(){this.encoder||(this.encoder=new t.Worker(this.config.encoderPath))},i.prototype.initWorker=function(){var e=(this.config.streamPages?this.streamPage:this.storePage).bind(this);return this.recordedPages=[],this.totalLength=0,this.loadWorker(),new Promise((t,s)=>{var i=s=>{switch(s.data.message){case"ready":t();break;case"page":this.encodedSamplePosition=s.data.samplePosition,e(s.data.page);break;case"done":this.encoder.removeEventListener("message",i),this.finish()}};this.encoder.addEventListener("message",i),this.encoder.postMessage(Object.assign({command:"init",originalSampleRate:this.audioContext.sampleRate,wavSampleRate:this.audioContext.sampleRate},this.config))})},i.prototype.pause=function(e){if("recording"===this.state){if(this.state="paused",e&&this.config.streamPages){var t=this.encoder;return new Promise((e,s)=>{var i=s=>{"flushed"===s.data.message&&(t.removeEventListener("message",i),this.onpause(),e())};t.addEventListener("message",i),t.postMessage({command:"flush"})})}return this.onpause(),Promise.resolve()}},i.prototype.resume=function(){"paused"===this.state&&(this.state="recording",this.onresume())},i.prototype.setRecordingGain=function(e){this.config.recordingGain=e,this.recordingGainNode&&this.audioContext&&this.recordingGainNode.gain.setTargetAtTime(e,this.audioContext.currentTime,.01)},i.prototype.setMonitorGain=function(e){this.config.monitorGain=e,this.monitorGainNode&&this.audioContext&&this.monitorGainNode.gain.setTargetAtTime(e,this.audioContext.currentTime,.01)},i.prototype.start=function(e){if("inactive"===this.state)return this.initAudioContext(e),this.initAudioGraph(),this.encodedSamplePosition=0,this.initWorker().then(()=>this.initSourceNode(e)).then(e=>{this.sourceNode=e,this.state="recording",this.onstart(),this.encoder.postMessage({command:"getHeaderPages"}),this.sourceNode.connect(this.monitorGainNode),this.sourceNode.connect(this.recordingGainNode)})},i.prototype.stop=function(){if("inactive"!==this.state){this.state="inactive",this.monitorGainNode.disconnect(),this.scriptProcessorNode.disconnect(),this.recordingGainNode.disconnect(),this.sourceNode.disconnect(),this.clearStream();var e=this.encoder;return new Promise(t=>{var s=i=>{"done"===i.data.message&&(e.removeEventListener("message",s),t())};e.addEventListener("message",s),e.postMessage({command:"done"}),this.config.reuseWorker||e.postMessage({command:"close"})})}return Promise.resolve()},i.prototype.destroyWorker=function(){"inactive"===this.state&&this.encoder&&(this.encoder.postMessage({command:"close"}),delete this.encoder)},i.prototype.storePage=function(e){this.recordedPages.push(e),this.totalLength+=e.length},i.prototype.streamPage=function(e){this.ondataavailable(e)},i.prototype.finish=function(){if(!this.config.streamPages){var e=new Uint8Array(this.totalLength);this.recordedPages.reduce((function(t,s){return e.set(s,t),t+s.length}),0),this.ondataavailable(e)}this.onstop(),this.config.reuseWorker||delete this.encoder},i.prototype.ondataavailable=function(){},i.prototype.onpause=function(){},i.prototype.onresume=function(){},i.prototype.onstart=function(){},i.prototype.onstop=function(){},e.exports=i}).call(this,s(1))},function(e,t){var s;s=function(){return this}();try{s=s||new Function("return this")()}catch(e){"object"==typeof window&&(s=window)}e.exports=s}])},17:function(e,t,s){"use strict";s.r(t),s.d(t,"ripple",(function(){return l}));var i=s(5),n=s(53),a=s(1),o=s(15);let r=0;function l(e,t=(()=>Promise.resolve()),s=null,l=!1){if(e.querySelector(".c-ripple"))return;e.classList.add("rp");let c=document.createElement("div");c.classList.add("c-ripple");let d;e.classList.contains("rp-square")&&c.classList.add("is-square"),e[l?"prepend":"append"](c);const h=(e,i)=>{const o=Date.now(),l=document.createElement("div"),h=r++,u=1e3*+window.getComputedStyle(c).getPropertyValue("--ripple-duration").replace("s","");d=()=>{let e=Date.now()-o;const t=()=>{n.a.mutate(()=>{l.remove()}),s&&s(h)};if(e<u){let s=Math.max(u-e,u/2);setTimeout(()=>l.classList.add("hiding"),Math.max(s-u/2,0)),setTimeout(t,s)}else l.classList.add("hiding"),setTimeout(t,u/2);a.IS_TOUCH_SUPPORTED||window.removeEventListener("contextmenu",d),d=null,p=!1},t&&t(h),window.requestAnimationFrame(()=>{const t=c.getBoundingClientRect();l.classList.add("c-ripple__circle");const s=e-t.left,n=i-t.top,a=Math.sqrt(Math.pow(Math.abs(n-t.height/2)+t.height/2,2)+Math.pow(Math.abs(s-t.width/2)+t.width/2,2)),o=s-a/2,r=n-a/2;l.style.width=l.style.height=a+"px",l.style.left=o+"px",l.style.top=r+"px",c.append(l)})},u=t=>t.target!==e&&(["BUTTON","A"].includes(t.target.tagName)||Object(i.a)(t.target,"c-ripple")!==c);let p=!1;if(a.IS_TOUCH_SUPPORTED){let t=()=>{d&&d()};e.addEventListener("touchstart",s=>{if(!o.default.settings.animationsEnabled)return;if(s.touches.length>1||p||u(s))return;p=!0;let{clientX:i,clientY:n}=s.touches[0];h(i,n),e.addEventListener("touchend",t,{once:!0}),window.addEventListener("touchmove",s=>{s.cancelBubble=!0,s.stopPropagation(),t(),e.removeEventListener("touchend",t)},{once:!0})},{passive:!0})}else e.addEventListener("mousedown",t=>{if(![0,2].includes(t.button))return;if(!o.default.settings.animationsEnabled)return;if("0"===e.dataset.ripple||u(t))return;if(p)return void(p=!1);let{clientX:s,clientY:i}=t;h(s,i),window.addEventListener("mouseup",d,{once:!0,passive:!0}),window.addEventListener("contextmenu",d,{once:!0,passive:!0})},{passive:!0})}},28:function(e,t,s){"use strict";s.d(t,"a",(function(){return a})),s.d(t,"b",(function(){return o})),s.d(t,"c",(function(){return r})),s.d(t,"d",(function(){return l}));var i=s(1),n=s(47);const a=i.IS_TOUCH_SUPPORTED?"mousedown":"click";function o(e,t,s={}){const i=s.listenerSetter?s.listenerSetter.add(e):e.addEventListener.bind(e);s.touchMouseDown=!0,i(a,t,s)}function r(e,t,s){e.removeEventListener(a,t,s)}function l(e){Object(n.a)(e,a)}},31:function(e,t,s){"use strict";var i=s(14),n=s(17);t.a=(e,t={})=>{const s=document.createElement(t.asDiv?"div":"button");return s.className=e+(t.icon?" tgico-"+t.icon:""),t.noRipple||(t.rippleSquare&&s.classList.add("rp-square"),Object(n.ripple)(s)),t.onlyMobile&&s.classList.add("only-handhelds"),t.disabled&&s.setAttribute("disabled","true"),t.text&&s.append(Object(i.i18n)(t.text)),s}},33:function(e,t,s){"use strict";s.d(t,"f",(function(){return h})),s.d(t,"g",(function(){return u})),s.d(t,"c",(function(){return g})),s.d(t,"d",(function(){return y})),s.d(t,"e",(function(){return w})),s.d(t,"b",(function(){return E})),s.d(t,"a",(function(){return M}));var i=s(27),n=s(4),a=s(28),o=s(37),r=s(1),l=s(0),c=s(15),d=s(44);function h(e,t=!1){const s='\n <svg xmlns="http://www.w3.org/2000/svg" class="preloader-circular" viewBox="25 25 50 50">\n <circle class="preloader-path" cx="50" cy="50" r="20" fill="none" stroke-miterlimit="10"/>\n </svg>';if(t){const t=document.createElement("div");return t.classList.add("preloader"),t.innerHTML=s,e&&e.appendChild(t),t}return e.insertAdjacentHTML("beforeend",s),e.lastElementChild}function u(e,t="check"){return e.classList.remove("tgico-"+t),e.disabled=!0,h(e),()=>{e.innerHTML="",e.classList.add("tgico-"+t),e.removeAttribute("disabled")}}i.a.putPreloader=h;let p=e=>{let t=b.getBoundingClientRect(),{clientX:s,clientY:i}=e,n=s>=t.right?s-t.right:t.left-s,a=i>=t.bottom?i-t.bottom:t.top-i;(n>=100||a>=100)&&g()};const m=e=>{g()},g=()=>{b&&(b.classList.remove("active"),b.parentElement.classList.remove("menu-open"),f&&f.remove(),b=null,c.default.dispatchEvent("context_menu_toggle",!1)),v&&(v(),v=null),r.IS_TOUCH_SUPPORTED||(window.removeEventListener("mousemove",p),window.removeEventListener("contextmenu",m)),document.removeEventListener(a.a,m),l.IS_MOBILE_SAFARI||d.a.removeByType("menu")};window.addEventListener("resize",()=>{b&&g()});let b=null,v=null,f=null;function y(e,t){g(),l.IS_MOBILE_SAFARI||d.a.pushItem({type:"menu",onPop:e=>{g()}}),b=e,b.classList.add("active"),b.parentElement.classList.add("menu-open"),f||(f=document.createElement("div"),f.classList.add("btn-menu-overlay"),f.addEventListener(a.a,e=>{Object(n.a)(e),m()})),b.parentElement.insertBefore(f,b),v=t,r.IS_TOUCH_SUPPORTED||(window.addEventListener("mousemove",p),window.addEventListener("contextmenu",m,{once:!0})),document.addEventListener(a.a,m),c.default.dispatchEvent("context_menu_toggle",!0)}function w({pageX:e,pageY:t},s,i){let{scrollWidth:n,scrollHeight:a}=s;const r=document.body.getBoundingClientRect(),l=r.width,c=r.height;i=o.b.isMobile?"right":"left";let d="top";const h={x:{left:e,right:e-n},intermediateX:"right"===i?8:l-n-8,y:{top:t,bottom:t-a},intermediateY:t<c/2?8:c-a-8},u={left:h.x.left+n+8<=l,right:h.x.right>=8},p={top:h.y.top+a+8<=c,bottom:h.y.bottom-8>=8};{let e;e=u[i]?h.x[i]:(i="center",h.intermediateX),s.style.left=e+"px"}{let e;e=p[d]?h.y[d]:(d="center",h.intermediateY),s.style.top=e+"px"}s.className=s.className.replace(/(top|center|bottom)-(left|center|right)/g,""),s.classList.add(("center"===d?d:"bottom")+"-"+("center"===i?i:"left"===i?"right":"left"))}let L=!1,S=0;function E(){S&&clearTimeout(S),S=window.setTimeout(()=>{S=0,L=!1},400),L=!0}function M(e,t,s){const i=s?s.add(e):e.addEventListener.bind(e),a=s?s.removeManual.bind(s,e):e.removeEventListener.bind(e);if(l.IS_APPLE&&r.IS_TOUCH_SUPPORTED){let s;const o={capture:!0},r=()=>{clearTimeout(s),a("touchmove",r,o),a("touchend",r,o),a("touchcancel",r,o)};i("touchstart",a=>{a.touches.length>1?r():(i("touchmove",r,o),i("touchend",r,o),i("touchcancel",r,o),s=window.setTimeout(()=>{L?r():(t(a.touches[0]),r(),b&&e.addEventListener("touchend",n.a,{once:!0}))},400))})}else i("contextmenu",r.IS_TOUCH_SUPPORTED?s=>{t(s),b&&e.addEventListener("touchend",n.a,{once:!0})}:t)}},44:function(e,t,s){"use strict";var i=s(27),n=s(0),a=s(40),o=s(35),r=s(6),l=s(4);const c=new class{constructor(){this.navigations=[],this.id=Date.now(),this.manual=!1,this.log=Object(a.b)("NC"),this.debug=!0,this.currentHash=window.location.hash;let e=!1;if(window.addEventListener("popstate",t=>{if(this.debug&&this.log("popstate",t,e),window.location.hash!==this.currentHash)return this.onHashChange&&this.onHashChange(),void this.replaceState();this.currentHash=window.location.hash;if(t.state!==this.id)return void this.pushState();const s=this.navigations.pop();s?(this.manual=!e,this.handleItem(s)):this.pushState()}),window.addEventListener("keydown",e=>{const t=this.navigations[this.navigations.length-1];t&&("Escape"!==e.key||t.onEscape&&!t.onEscape()||(Object(l.a)(e),this.back(t.type)))},{capture:!0,passive:!1}),n.IS_MOBILE_SAFARI){const t={passive:!0};window.addEventListener("touchstart",s=>{if(s.touches.length>1)return;this.debug&&this.log("touchstart");const i=()=>{window.removeEventListener("touchend",r),window.removeEventListener("touchmove",a)};let n=!1;const a=e=>{this.debug&&this.log("touchmove"),e.touches.length>1?i():n=!0},r=t=>{this.debug&&this.log("touchend"),t.touches.length>1||!n||(e=!0,Object(o.a)().then(()=>{e=!1})),i()};window.addEventListener("touchend",r,t),window.addEventListener("touchmove",a,t)},t)}history.scrollRestoration="manual",this.pushState()}handleItem(e){const t=e.onPop(!!this.manual&&void 0);this.debug&&this.log("popstate, navigation:",e,this.navigations),!1===t?this.pushItem(e):e.noBlurOnPop||Object(r.a)(),this.manual=!1}findItemByType(e){for(let t=this.navigations.length-1;t>=0;--t){const s=this.navigations[t];if(s.type===e)return{item:s,index:t}}}back(e){if(e){const t=this.findItemByType(e);if(t)return this.manual=!0,this.navigations.splice(t.index,1),void this.handleItem(t.item)}history.back()}pushItem(e){this.navigations.push(e),this.debug&&this.log("pushstate",e,this.navigations),e.noHistory||this.pushState()}pushState(){this.manual=!1,history.pushState(this.id,"")}replaceState(){history.replaceState(this.id,"",location.origin+location.pathname)}removeItem(e){this.navigations.findAndSplice(t=>t===e)}removeByType(e,t=!1){for(let s=this.navigations.length-1;s>=0;--s){if(this.navigations[s].type===e&&(this.navigations.splice(s,1),t))break}}};i.a.appNavigationController=c,t.a=c},47:function(e,t,s){"use strict";function i(e,t){const s=new Event(t,{bubbles:!0,cancelable:!0});e.dispatchEvent(s)}s.d(t,"a",(function(){return i}))},53:function(e,t,s){"use strict";var i=s(35),n=s(42),a=s(27),o=s(55);const r=new class{constructor(){this.promises={},this.raf=i.b.bind(null),this.scheduled=!1}do(e,t){let s=this.promises[e];return s||(this.scheduleFlush(),s=this.promises[e]=Object(n.a)()),void 0!==t&&s.then(()=>t()),s}measure(e){return this.do("read",e)}mutate(e){return this.do("write",e)}mutateElement(e,t){const s=Object(o.a)(e)?this.mutate():Promise.resolve();return void 0!==t&&s.then(()=>t()),s}scheduleFlush(){this.scheduled||(this.scheduled=!0,this.raf(()=>{this.promises.read&&this.promises.read.resolve(),this.promises.write&&this.promises.write.resolve(),this.scheduled=!1,this.promises={}}))}};a.a&&(a.a.sequentialDom=r),t.a=r},74:function(e,t,s){"use strict";var i=s(27),n=s(36),a=s(30);const o=new class{getState(){return a.a.invokeApi("account.getPassword").then(e=>e)}updateSettings(e={}){return this.getState().then(t=>{let s,i;const n={password:null,new_settings:{_:"account.passwordInputSettings",hint:e.hint,email:e.email}};s=e.currentPassword?a.a.invokeCrypto("computeSRP",e.currentPassword,t,!1):Promise.resolve({_:"inputCheckPasswordEmpty"});const o=t.new_algo,r=new Uint8Array(o.salt1.length+32);return r.randomize(),r.set(o.salt1,0),o.salt1=r,i=e.newPassword?a.a.invokeCrypto("computeSRP",e.newPassword,t,!0):Promise.resolve(new Uint8Array),Promise.all([s,i]).then(e=>(n.password=e[0],n.new_settings.new_algo=o,n.new_settings.new_password_hash=e[1],a.a.invokeApi("account.updatePasswordSettings",n)))})}check(e,t,s={}){return a.a.invokeCrypto("computeSRP",e,t,!1).then(e=>a.a.invokeApi("auth.checkPassword",{password:e},s).then(e=>("auth.authorization"===e._&&(n.a.saveApiUser(e.user),a.a.setUserAuth(e.user.id)),e)))}confirmPasswordEmail(e){return a.a.invokeApi("account.confirmPasswordEmail",{code:e})}resendPasswordEmail(){return a.a.invokeApi("account.resendPasswordEmail")}cancelPasswordEmail(){return a.a.invokeApi("account.cancelPasswordEmail")}};i.a.passwordManager=o,t.a=o},90:function(e,t,s){"use strict";s.d(t,"a",(function(){return a}));var i=s(4),n=s(38);class a extends n.b{constructor(e={}){super(Object.assign({plainText:!0},e)),this.passwordVisible=!1,this.onVisibilityClick=e=>{Object(i.a)(e),this.passwordVisible=!this.passwordVisible,this.toggleVisible.classList.toggle("eye-hidden",this.passwordVisible),this.input.type=this.passwordVisible?"text":"password",this.onVisibilityClickAdditional&&this.onVisibilityClickAdditional()};const t=this.input;t.type="password",t.setAttribute("required",""),t.autocomplete="off";const s=document.createElement("input");s.classList.add("stealthy"),s.tabIndex=-1,s.type="password",t.parentElement.prepend(s),t.parentElement.insertBefore(s.cloneNode(),t.nextSibling);const n=this.toggleVisible=document.createElement("span");n.classList.add("toggle-visible","tgico"),this.container.classList.add("input-field-password"),this.container.append(n),n.addEventListener("click",this.onVisibilityClick),n.addEventListener("touchend",this.onVisibilityClick)}}},96:function(e,t,s){"use strict";s.d(t,"a",(function(){return n}));var i=s(49);class n{constructor(e,t){this.passwordInputField=e,this.size=t,this.needFrame=0,this.container=document.createElement("div"),this.container.classList.add("media-sticker-wrapper")}load(){return this.loadPromise?this.loadPromise:this.loadPromise=i.b.loadAnimationFromURL({container:this.container,loop:!1,autoplay:!1,width:this.size,height:this.size,noCache:!0},"assets/img/TwoFactorSetupMonkeyPeek.tgs").then(e=>(this.animation=e,this.animation.addEventListener("enterFrame",e=>{(1===this.animation.direction&&e>=this.needFrame||-1===this.animation.direction&&e<=this.needFrame)&&(this.animation.setSpeed(1),this.animation.pause())}),this.passwordInputField.onVisibilityClickAdditional=()=>{this.passwordInputField.passwordVisible?(this.animation.setDirection(1),this.animation.curFrame=0,this.needFrame=16,this.animation.play()):(this.animation.setDirection(-1),this.animation.curFrame=16,this.needFrame=0,this.animation.play())},i.b.waitForFirstFrame(e)))}remove(){this.animation&&this.animation.remove()}}}}]);
//# sourceMappingURL=15.1a3e11966cccf1381885.chunk.js.map