tweb/public/17.37db4aa399340711ccb2.chunk.js
Eduard Kuzmenko 14597933ba Build
2021-06-14 16:53:09 +03:00

2 lines
517 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([[17],{122: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}])},33:function(e,t,s){"use strict";s.d(t,"b",(function(){return c})),s.d(t,"a",(function(){return d}));var i=s(19),n=s(23),a=s(37),o=s(38),r=s(12);class l{constructor(e,t="",s=document.createElement("div")){this.el=e,this.container=s,this.onScrollMeasure=0,this.isHeavyAnimationInProgress=!1,this.needCheckAfterAnimation=!1,this.container.classList.add("scrollable"),this.log=Object(n.b)("SCROLL"+(t?"-"+t:""),n.a.Error),e&&(Array.from(e.children).forEach(e=>this.container.append(e)),e.append(this.container))}setListeners(){window.addEventListener("resize",this.onScroll,{passive:!0}),this.container.addEventListener("scroll",this.onScroll,{passive:!0,capture:!0}),Object(o.a)(()=>{this.isHeavyAnimationInProgress=!0,this.onScrollMeasure&&(this.needCheckAfterAnimation=!0,window.cancelAnimationFrame(this.onScrollMeasure))},()=>{this.isHeavyAnimationInProgress=!1,this.needCheckAfterAnimation&&(this.onScroll(),this.needCheckAfterAnimation=!1)})}append(e){this.container.append(e)}scrollIntoViewNew(e,t,s,i,n,o,r){return Object(a.b)(this.container,e,t,s,i,n,o,r)}}class c extends l{constructor(e,t="",s=300,i){super(e,t),this.onScrollOffset=s,this.onAdditionalScroll=null,this.onScrolledTop=null,this.onScrolledBottom=null,this.lastScrollTop=0,this.lastScrollDirection=0,this.loadedAll={top:!0,bottom:!1},this.onScroll=()=>{if(this.isHeavyAnimationInProgress)return this.onScrollMeasure&&window.cancelAnimationFrame(this.onScrollMeasure),void(this.needCheckAfterAnimation=!0);(this.onScrolledTop||this.onScrolledBottom||this.splitUp||this.onAdditionalScroll)&&(this.onScrollMeasure&&window.cancelAnimationFrame(this.onScrollMeasure),this.onScrollMeasure=window.requestAnimationFrame(()=>{this.onScrollMeasure=0;const e=this.container.scrollTop;this.lastScrollDirection=this.lastScrollTop===e?0:this.lastScrollTop<e?1:-1,this.lastScrollTop=e,this.onAdditionalScroll&&0!==this.lastScrollDirection&&this.onAdditionalScroll(),this.checkForTriggers&&this.checkForTriggers()}))},this.checkForTriggers=()=>{if(!this.onScrolledTop&&!this.onScrolledBottom)return;if(this.isHeavyAnimationInProgress)return void this.onScroll();const e=this.container.scrollHeight;if(!e)return;const t=e-this.container.clientHeight,s=this.lastScrollTop;this.onScrolledTop&&s<=this.onScrollOffset&&this.lastScrollDirection<=0&&this.onScrolledTop(),this.onScrolledBottom&&t-s<=this.onScrollOffset&&this.lastScrollDirection>=0&&this.onScrolledBottom()},this.container.classList.add("scrollable-y"),this.setListeners()}setVirtualContainer(e){this.splitUp=e,this.log("setVirtualContainer:",e,this)}prepend(...e){(this.splitUp||this.padding||this.container).prepend(...e)}append(...e){(this.splitUp||this.padding||this.container).append(...e)}getDistanceToEnd(){return this.scrollHeight-Math.round(this.scrollTop+this.container.offsetHeight)}get isScrolledDown(){return this.getDistanceToEnd()<=1}set scrollTop(e){this.container.scrollTop=e}get scrollTop(){return this.container.scrollTop}get scrollHeight(){return this.container.scrollHeight}}class d extends l{constructor(e,t="",s=300,n=15,a=document.createElement("div")){if(super(e,t,a),this.onScrollOffset=s,this.splitCount=n,this.container=a,this.container.classList.add("scrollable-x"),!i.isTouchSupported){const e=e=>{!e.deltaX&&this.container.scrollWidth>this.container.clientWidth&&(this.container.scrollLeft+=e.deltaY/4,Object(r.a)(e))};this.container.addEventListener("wheel",e,{passive:!1})}}}},43:function(e,t,s){"use strict";s.d(t,"a",(function(){return r}));var i=s(18),n=s(20),a=s(24),o=s(9);class r{constructor(e={}){const t=this.label=document.createElement("label");t.classList.add("checkbox-field"),e.restriction&&t.classList.add("checkbox-field-restriction"),e.round&&t.classList.add("checkbox-field-round"),e.disabled&&this.toggleDisability(!0);const s=this.input=document.createElement("input");let r;if(s.type="checkbox",e.name&&(s.id="input-"+e.name),e.checked&&(s.checked=!0),e.stateKey&&i.default.getState().then(t=>{const a=Object(n.d)(t,e.stateKey);let o;o=e.stateValues?1===e.stateValues.indexOf(a):a,this.setValueSilently(o),s.addEventListener("change",()=>{let t;t=e.stateValues?e.stateValues[s.checked?1:0]:s.checked,i.default.setByKey(e.stateKey,t)})}),e.text?(r=this.span=document.createElement("span"),r.classList.add("checkbox-caption"),Object(o._i18n)(r,e.text,e.textArgs)):t.classList.add("checkbox-without-caption"),t.append(s),e.toggle){t.classList.add("checkbox-field-toggle");const e=document.createElement("div");e.classList.add("checkbox-toggle"),t.append(e)}else{const e=document.createElement("div");e.classList.add("checkbox-box");const s=document.createElementNS("http://www.w3.org/2000/svg","svg");s.classList.add("checkbox-box-check"),s.setAttributeNS(null,"viewBox","0 0 24 24");const i=document.createElementNS("http://www.w3.org/2000/svg","use");i.setAttributeNS(null,"href","#check"),i.setAttributeNS(null,"x","-1"),s.append(i);const n=document.createElement("div");n.classList.add("checkbox-box-background");const a=document.createElement("div");a.classList.add("checkbox-box-border"),e.append(a,n,s),t.append(e)}r&&t.append(r),e.withRipple?(t.classList.add("checkbox-ripple","hover-effect"),Object(a.ripple)(t,void 0,void 0,!0)):e.withHover&&t.classList.add("hover-effect")}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}toggleDisability(e){return this.label.classList.toggle("checkbox-disabled",e),()=>this.toggleDisability(!e)}}},44:function(e,t,s){"use strict";function i(e,t){return t?e.forEach(e=>e.setAttribute("disabled","true")):e.forEach(e=>e.removeAttribute("disabled")),()=>i(e,!t)}s.d(t,"a",(function(){return i}))},47:function(e,t,s){"use strict";function i(e,t){return e.closest(t)}s.d(t,"a",(function(){return i}))},84:function(e,t,s){"use strict";s.r(t),s.d(t,"AppDialogsManager",(function(){return Ia})),s.d(t,"generateVerifiedIcon",(function(){return Ca}));var i=s(29),n=s(53),a=s(11),o=s(27),r=s(22),l=s(19),c=s(0),d=s(54),h=s(42),u=s(46),p=s(18),m=s(26),g=s(33),b=s(25),f=s(9);class v{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=Ta.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(f.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&&Ta.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 y{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 g.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){this.peerId=e,this.threadId=t,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}=Ta.addDialogNew({dialog:s,container:this.scrollable,drawStatus:!1,avatarSize:54,meAsSaved:!1});t.peerId!==s&&(n.listEl.dataset.peerId=""+t.peerId),Ta.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(b.a)(n.nameEl,Object(f.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 w=s(28);class L{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 w.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 S=s(69),M=s(36),E=s(34);class I{constructor(){this.listeners=new Set}add(e,t,s,i){const n={element:e,event:t,callback:s,options:i};return this.addManual(n),n}addManual(e){e.element.addEventListener(e.event,e.callback,e.options),this.listeners.add(e)}remove(e){e.element.removeEventListener(e.event,e.callback,e.options),this.listeners.delete(e)}removeManual(e,t,s,i){let n;for(const a of this.listeners)if(a.element===e&&a.event===t&&a.callback===s&&a.options===i){n=a;break}n&&this.remove(n)}removeAll(){this.listeners.forEach(e=>{this.remove(e)})}}var C=s(17);var k=(e,t={})=>Object(C.a)("btn-icon",Object.assign({icon:e},t)),T=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 P{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("sidebar-slider-item"),this.header=document.createElement("div"),this.header.classList.add("sidebar-header"),this.closeBtn=k("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 g.b(this.content,void 0,void 0,!0),this.container.append(this.header,this.content),this.slider.addTab(this),this.listenerSetter=new I}close(){return this.slider.closeTab(this)}open(...e){return T(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(f.i18n)(e))}}class x extends P{constructor(e){super(e),this.eventListener=new E.a}onCloseAfterTimeout(){return this.eventListener.dispatchEvent("destroy"),this.eventListener.cleanup(),super.onCloseAfterTimeout()}}var A=s(20),F=s(13);class O{constructor(e){this.historyTabIds=[],this.canHideFirst=!1,this.onCloseBtnClick=()=>{M.a.findItemByType(this.navigationType)?M.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 P?n.container:n:this.canHideFirst?-1:0,t),!0},Object(A.g)(this,e),this.tabs||(this.tabs=new Map),this.tabsContainer=this.sidebarEl.querySelector(".sidebar-slider"),this._selectTab=Object(S.a)(this.tabsContainer,"navigation",250),this.canHideFirst||this._selectTab(0),Array.from(this.sidebarEl.querySelectorAll(".sidebar-close-button")).forEach(e=>{Object(F.b)(e,this.onCloseBtnClick)})}selectTab(e){if(this.historyTabIds[this.historyTabIds.length-1]===e)return!1;const t=e instanceof P?e:this.tabs.get(e);return t&&(t.onOpen&&t.onOpen(),t.onOpenAfterTimeout&&setTimeout(()=>{t.onOpenAfterTimeout()},250)),M.a.pushItem({type:this.navigationType,onPop:e=>(this.closeTab(void 0,e,!0),!0)}),this.historyTabIds.push(e),this._selectTab(e instanceof P?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||M.a.removeByType(this.navigationType,!0);const i=e instanceof P?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 D=s(41),j=s(86);class _{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 j.a).open(this.canvas,e)})}clear(){this.canvas.getContext("2d").clearRect(0,0,this.canvas.width,this.canvas.height)}}var B=(e={})=>Object(C.a)("btn-circle btn-corner z-depth-1"+(e.className?" "+e.className:""),e);class R extends P{constructor(){super(...arguments),this.searchGroup=new v(!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 _(e=>{this.uploadAvatar=e});const e=document.createElement("div");e.classList.add("input-wrapper"),this.groupNameInputField=new w.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=B({icon:"arrow_next"}),this.nextBtn.addEventListener("click",()=>{const e=this.groupNameInputField.value;this.nextBtn.disabled=!0,D.a.createChat(e,this.userIds).then(e=>{this.uploadAvatar&&this.uploadAvatar().then(t=>{D.a.editPhoto(e,t)}),ui.removeTabFromHistory(this),ui.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}=Ta.addDialogNew({dialog:e,container:this.searchGroup.list,drawStatus:!1,rippleEnabled:!1,avatarSize:48});t.lastMessageSpan.append(m.a.getUserStatusString(e))}),this.searchGroup.nameEl.textContent="",this.searchGroup.nameEl.append(Object(f.i18n)("Members",[this.userIds.length])),this.searchGroup.setActive()}),t}}var H=s(31),N=s(66),U=s(35),z=s(51),W=s(23),q=s(16),V=s(68),G=s(71),K=s(21),Q=s(24),$=s(114),Y=s(87),X=s(30),J=s(109),Z=s(10),ee=s(49);const te=new class{constructor(){this.media={},this.waitingMediaForLoad={},this.onPause=e=>{a.default.dispatchEvent("audio_pause")},this.onEnded=e=>{if(this.onPause(e),this.nextMid){const e=this.media[this.currentPeerId][this.nextMid];this.resolveWaitingForLoadMedia(this.currentPeerId,this.nextMid),setTimeout(()=>{e.play()},0)}},this.container=document.createElement("div"),this.container.style.cssText="display: none;",document.body.append(this.container)}addMedia(e,t,s,i=!0){var n,r;const l=null!==(n=this.media[e])&&void 0!==n?n:this.media[e]={};if(l[s])return l[s];const h=document.createElement("round"===t.type?"video":"audio");"round"===t.type&&h.setAttribute("playsinline","true"),h.dataset.mid=""+s,h.dataset.type=t.type,h.volume=1,this.container.append(h),h.addEventListener("playing",()=>{this.currentPeerId=e,this.playingMedia!==h&&(this.playingMedia&&!this.playingMedia.paused&&this.playingMedia.pause(),this.playingMedia=h,this.loadSiblingsMedia(e,t.type,s)),setTimeout(()=>{a.default.dispatchEvent("audio_play",{peerId:e,doc:t,mid:s})},0)}),h.addEventListener("pause",this.onPause),h.addEventListener("ended",this.onEnded);const u=i=>{this.nextMid===s&&this.loadSiblingsMedia(e,t.type,s).then(()=>{this.nextMid&&l[this.nextMid]&&l[this.nextMid].play()})};h.addEventListener("error",u);const p=Object(o.a)();if(i)p.resolve();else{(null!==(r=this.waitingMediaForLoad[e])&&void 0!==r?r:this.waitingMediaForLoad[e]={})[s]=p}return p.then(()=>{(t.supportsStreaming?Promise.resolve():d.a.downloadDoc(t)).then(()=>{"audio"===t.type&&t.supportsStreaming&&c.isSafari&&this.handleSafariStreamable(h);const e=ee.a.getCacheContext(t);h.src=e.url})},u),l[s]=h}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){var s;const i=null!==(s=this.waitingMediaForLoad[e])&&void 0!==s?s:this.waitingMediaForLoad[e]={},n=i[t];n&&(n.resolve(),delete i[t])}isSafariBuffering(e){return!!e.safariBuffering}setSafariBuffering(e,t){e.safariBuffering=t}loadSiblingsMedia(e,t,s){const n=this.playingMedia;return this.prevMid=this.nextMid=0,i.a.getSearch({peerId:e,query:"",inputFilter:{_:"audio"===t?"inputMessagesFilterMusic":"inputMessagesFilterRoundVoice"},maxId:s,limit:3,backLimit:2}).then(t=>{if(this.playingMedia===n){for(const{mid:e}of t.history)if(e>s)this.nextMid=e;else if(e<s){this.prevMid=e;break}[this.prevMid,this.nextMid].filter(Boolean).forEach(t=>{const s=i.a.getMessageByPeer(e,t);this.addMedia(e,s.media.document,t,!1)})}})}toggle(){this.playingMedia&&(this.playingMedia.paused?this.playingMedia.play():this.playingMedia.pause())}pause(){this.playingMedia&&!this.playingMedia.paused&&this.playingMedia.pause()}willBePlayed(e){this.willBePlayedMedia=e}};Z.a.appMediaPlaybackController=te;var se=te,ie=s(83);function ne(e,t,s,i){const n=e=>{s({x:e.pageX,y:e.pageY})},a=t=>{document.removeEventListener("mousemove",n),e.addEventListener("mousedown",o,{once:!0}),i&&i({x:t.pageX,y:t.pageY})},o=s=>{0===s.button?(t({x:s.pageX,y:s.pageY}),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})},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})},c=e=>{t({x:e.touches[0].clientX,y:e.touches[0].clientY,isTouch:!0}),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 ae{constructor(e,t,s,i){this.step=e,this.value=t,this.min=s,this.max=i,this.mousedown=!1,this.events={},this.onMouseMove=e=>{this.scrub(e)},this.onMouseDown=e=>{var t;this.rect=this.container.getBoundingClientRect(),this.mousedown=!0,this.scrub(e),(null===(t=this.events)||void 0===t?void 0:t.onMouseDown)&&this.events.onMouseDown(e)},this.onMouseUp=e=>{var t;this.mousedown=!1,(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)},this.container=document.createElement("div"),this.container.classList.add("progress-line"),this.filled=document.createElement("div"),this.filled.classList.add("progress-line__filled");const n=this.seek=document.createElement("input");n.classList.add("progress-line__seek"),n.type="range",n.step=""+e,n.min=""+this.min,n.max=""+this.max,n.value=""+t,t&&this.setProgress(t);const a=""+this.step,o=a.indexOf(".");this.decimals=-1===o?0:a.length-o-1,this.container.append(this.filled,n)}setHandlers(e){this.events=e}setListeners(){this.seek.addEventListener("input",this.onInput),this._removeListeners=ne(this.container,this.onMouseDown,this.onMouseMove,this.onMouseUp)}setProgress(e){this.setFilled(e),this.seek.value=""+e}setFilled(e){let t=(e-this.min)/(this.max-this.min);t=Object(u.a)(t,0,1),this.filled.style.width=100*t+"%"}scrub(e){var t;const s=Object(u.a)(e.x-this.rect.left,0,this.rect.width);let i=this.min+s/this.rect.width*(this.max-this.min);return i-this.min<(this.max-this.min)/2&&(i-=this.step/10),i=+i.toFixed(this.decimals),i=Object(u.a)(i,this.min,this.max),this.setProgress(i),(null===(t=this.events)||void 0===t?void 0:t.onScrub)&&this.events.onScrub(i),i}removeListeners(){this._removeListeners&&(this._removeListeners(),this._removeListeners=null),this.seek.removeEventListener("input",this.onInput),this.events={}}}var oe=s(85),re=s(12);class le extends ae{constructor(e,t=!1){super(1e3/60/1e3,0,0,1),this.media=e,this.streamable=t,this.stopAndScrubTimeout=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.onProgress=e=>{this.setLoadProgress()},t&&(this.filledLoad=document.createElement("div"),this.filledLoad.classList.add("progress-line__filled","progress-line__loaded"),this.container.prepend(this.filledLoad)),(!e.paused||e.currentTime>0)&&this.onPlay(),this.setSeekMax(),this.setListeners(),this.setHandlers({onMouseDown:()=>{this.stopAndScrubTimeout&&clearTimeout(this.stopAndScrubTimeout),this.stopAndScrubTimeout=window.setTimeout(()=>{!this.media.paused&&this.media.pause(),this.stopAndScrubTimeout=0},150)},onMouseUp:()=>{this.stopAndScrubTimeout&&(clearTimeout(this.stopAndScrubTimeout),this.stopAndScrubTimeout=0),this.media.paused&&this.media.play()}})}scrub(e){const t=super.scrub(e);return this.media.currentTime=t,t}setLoadProgress(){if(se.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(se.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.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.streamable&&this.media.removeEventListener("progress",this.onProgress),this.stopAndScrubTimeout&&clearTimeout(this.stopAndScrubTimeout),this.progressRAF&&window.cancelAnimationFrame(this.progressRAF)}}let ce=1,de=!ce;class he{constructor(e,t=!1,s=!1,i){var n;if(this.video=e,this.onFullScreen=()=>{null!==document.webkitFullscreenElement||this.wrapper.classList.remove("ckin__fullscreen")},this.wrapper=document.createElement("div"),this.wrapper.classList.add("ckin__player"),e.parentNode.insertBefore(this.wrapper,e),this.wrapper.appendChild(e),this.skin=null!==(n=e.dataset.ckin)&&void 0!==n?n:"default",this.stylePlayer(i),"default"===this.skin){let t=this.wrapper.querySelector(".default__controls.ckin__controls");this.progress=new le(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 a;if(t.insertAdjacentHTML("beforeend",n),"default"===i){const e=t.querySelectorAll(".toggle"),i=t.querySelector(".fullscreen"),n=t.querySelector("#time-elapsed");a=t.querySelector("#time-duration"),a.innerHTML=String(0|s.duration).toHHMMSS();const o=document.createElement("div");o.classList.add("player-volume"),o.innerHTML='\n <svg class="player-volume__icon" focusable="false" viewBox="0 0 24 24" aria-hidden="true"></svg>\n ';const r=o.firstElementChild;r.addEventListener("click",e=>{Object(re.a)(e),s.muted=!s.muted});const c=new ae(.01,1,0,1);c.setListeners(),c.setHandlers({onScrub:e=>{const t=Math.max(Math.min(e,1),0);s.muted=!1,s.volume=t}}),o.append(c.container);const d=()=>{const e=s.volume;let t;t=!e||s.muted?"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{r.innerHTML=`<path d="${t}"></path>`}catch(e){}c.mousedown||c.setProgress(s.muted?0:e)};s.addEventListener("volumechange",()=>{de=s.muted,ce=s.volume,d()}),s.volume=ce,s.muted=de,d();if(t.querySelector(".left-controls").insertBefore(o,n.parentElement),Array.from(e).forEach(e=>e.addEventListener("click",()=>{this.togglePlay()})),s.addEventListener("click",()=>{l.isTouchSupported||this.togglePlay()}),l.isTouchSupported){let e=0;const s=()=>{e=window.setTimeout(()=>{e=0,t.classList.remove("show-controls")},3e3)};t.addEventListener("click",()=>{e?clearTimeout(e):t.classList.add("show-controls"),s()}),t.addEventListener("touchstart",()=>{t.classList.add("show-controls"),clearTimeout(e)}),t.addEventListener("touchend",()=>{t.classList.contains("is-playing")&&s()})}s.addEventListener("dblclick",()=>{if(!l.isTouchSupported)return this.toggleFullScreen(i)}),i.addEventListener("click",e=>this.toggleFullScreen(i)),"webkitfullscreenchange mozfullscreenchange fullscreenchange MSFullscreenChange".split(" ").forEach(e=>{t.addEventListener(e,this.onFullScreen,!1)}),s.addEventListener("timeupdate",()=>{n.innerHTML=String(0|s.currentTime).toHHMMSS()})}s.addEventListener("play",()=>{this.wrapper.classList.add("is-playing")}),s.addEventListener("pause",()=>{this.wrapper.classList.remove("is-playing")}),s.duration||e?a.innerHTML=String(Math.round(s.duration||e)).toHHMMSS():Object(oe.d)(s).then(()=>{a.innerHTML=String(Math.round(s.duration)).toHHMMSS()})}togglePlay(e){return e?(this.video.pause(),void this.wrapper.classList.remove("is-playing")):!1===e?(this.video.play(),void this.wrapper.classList.add("is-playing")):void 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="${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="${e}__button fullscreen tgico-fullscreen" title="Full Screen"></button>\n </div>\n </div>\n </div>`}static isFullScreen(){return!!(document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement||document.msFullscreenElement)}toggleFullScreen(e){const t=this.wrapper;if(c.isAppleMobile){const e=this.video;return e.webkitEnterFullscreen(),void e.enterFullscreen()}he.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"))}}s(107);function ue(e){e.classList.add("is-voice");const t=e.message,s=t.media.document||t.media.webpage.document,n=t.fromId===a.default.myId&&t.peerId!==a.default.myId;let o=t&&t.pFlags.media_unread;o&&e.classList.add("is-unread"),t.pFlags.out&&e.classList.add("is-out");const l=r.b.isMobile?16:23,c=document.createElementNS("http://www.w3.org/2000/svg","svg");c.classList.add("audio-waveform"),c.setAttributeNS(null,"width","150"),c.setAttributeNS(null,"height",""+l),c.setAttributeNS(null,"viewBox","0 0 150 "+l);const d=document.createElement("div");d.classList.add("audio-time"),e.append(c,d);let h=s.attributes.find(e=>"documentAttributeAudio"===e._).waveform||new Uint8Array([]);h=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}(h.slice(0,63));const u=Math.max(...h),p=h.length?h.length:100,m=Math.min(37,p);let g=0;const b=l-4;let f="";for(let e=0,t=0,s=0;e<p;++e){const i=h[e]||0;if(s+m>=p){s=s+m-p,s<(m+1)/2&&g<i&&(g=i);const e=Math.max((g*b+(u+1)/2)/(u+1),4);f+=`\n <rect x="${t}" y="${l-e}" width="2" height="${e}" rx="1" ry="1"></rect>\n `,t+=4,g=s<(m+1)/2?0:i}else g<i&&(g=i),s+=m}c.insertAdjacentHTML("beforeend",f);const v=Array.from(c.children);let y=e.querySelector(".audio-waveform");return()=>{let t=0,s=0,a=e.audio;(!a.paused||a.currentTime>0&&a.currentTime!==a.duration)&&(s=Math.round(a.currentTime/a.duration*m),v.slice(0,s+1).forEach(e=>e.classList.add("active")));let r=()=>{clearInterval(t),t=window.setInterval(()=>{s>c.childElementCount||isNaN(a.duration)||a.paused?clearInterval(t):(s=Math.round(a.currentTime/a.duration*m),v.slice(0,s+1).forEach(e=>e.classList.add("active")))},20)};a.paused||r(),e.addAudioListener("playing",()=>{o&&!n&&e.classList.contains("is-unread")&&(e.classList.remove("is-unread"),i.a.readMessages(e.message.peerId,[e.message.mid]),o=!1),r()}),e.addAudioListener("pause",()=>{clearInterval(t)}),e.addAudioListener("ended",()=>{clearInterval(t),v.forEach(e=>e.classList.remove("active"))});let l=!1,d=!1;function h(e){let t;if(e instanceof MouseEvent)t=e.offsetX;else{const s=e.target.getBoundingClientRect();t=e.targetTouches[0].pageX-s.left}const i=t/150*a.duration;s=Math.round(i/a.duration*m),v.slice(0,s+1).forEach(e=>e.classList.add("active"));for(let e=s+1;e<v.length;++e)v[e].classList.remove("active");a.currentTime=i}return y.addEventListener("mouseleave",e=>{l&&(a.play(),l=!1),d=!1}),y.addEventListener("mousemove",e=>{d=!0,l&&h(e)}),y.addEventListener("mousedown",e=>{e.preventDefault(),a.paused||a.pause(),h(e),l=!0}),y.addEventListener("mouseup",e=>{d&&l&&(a.play(),l=!1)}),Object(F.b)(y,e=>{Object(re.a)(e),a.paused||h(e)}),()=>{clearInterval(t),y.remove(),y=null,a=null}}}a.default.addEventListener("messages_media_read",e=>{const{mids:t,peerId:s}=e;t.forEach(e=>{Array.from(document.querySelectorAll('audio-element[message-id="'+e+'"][peer-id="'+s+'"]')).forEach(e=>{e.classList.remove("is-unread")})})});class pe extends HTMLElement{constructor(){super(),this.withTime=!1,this.voiceAsMusic=!1,this.showSender=!1,this.attachedHandlers={}}render(){var e;this.classList.add("audio");const t=this.message.media.document||this.message.media.webpage.document,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='<div class="audio-toggle audio-ico"> \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>';const l=document.createElement("div");l.classList.add("audio-download"),o&&this.append(l);const h=n?ue(this):function(e){const t=e.withTime,s=e.message,n=s.media.document||s.media.webpage.document,a=e.showSender?i.a.getSenderToPeerText(s):"";let o,r="voice"===n.type?a:n.audioTitle||n.file_name;"voice"===n.type?o="":(o=n.audioPerformer?q.a.wrapPlainText(n.audioPerformer):"",t?o+=(o?" • ":"")+zt(n.date):o||(o="Unknown Artist"),e.showSender?o+=" • "+a:o=" • "+o);let l="";e.showSender&&(l=`<div class="sent-time">${Object(H.c)(new Date(1e3*s.date))}</div>`);const c=`\n <div class="audio-details">\n <div class="audio-title"><middle-ellipsis-element data-font-weight="${e.dataset.fontWeight}">${r}</middle-ellipsis-element>${l}</div>\n <div class="audio-subtitle"><div class="audio-time"></div>${o||"<div></div>"}</div>\n </div>`;return e.insertAdjacentHTML("beforeend",c),()=>{const t=e.querySelector(".audio-subtitle");let s=!1,i=new le(e.audio,n.supportsStreaming);e.addAudioListener("ended",()=>{e.classList.remove("audio-show-progress"),t.lastChild.replaceWith(o),s=!1});const a=()=>{s||(e.classList.add("audio-show-progress"),s=!0,i&&t.lastChild.replaceWith(i.container))};return e.addAudioListener("playing",a),(!e.audio.paused||e.audio.currentTime>0)&&a(),()=>{i.removeListeners(),i.container.remove(),i=null}}}(this),u=this.querySelector(".audio-time");u.innerHTML=r;const p=this.onLoad=(e=!0)=>{this.onLoad=void 0;const t=this.audio=se.addMedia(this.message.peerId,this.message.media.document||this.message.media.webpage.document,this.message.mid,e);this.onTypeDisconnect=h();const s=this.querySelector(".audio-toggle"),i=()=>String(0|t.currentTime).toHHMMSS()+(n?" / "+r:""),a=()=>{u.innerText=i(),s.classList.toggle("playing",!t.paused)};(!t.paused||t.currentTime>0&&t.currentTime!==t.duration)&&a(),Object(F.b)(s,e=>{Object(re.a)(e),t.paused?t.play().catch(()=>{}):t.pause()}),this.addAudioListener("ended",()=>{s.classList.remove("playing")}),this.addAudioListener("timeupdate",()=>{se.isSafariBuffering(t)||(u.innerText=i())}),this.addAudioListener("pause",()=>{s.classList.remove("playing")}),this.addAudioListener("playing",a)};if(a)o&&this.preloader.attach(l,!1);else{let i=this.preloader;const n=()=>d.a.downloadDoc(t);if(s){i||(i=new ie.a({cancelable:!0}));const e=()=>{const e=n();return i.attach(l,!1,e),l.parentElement||this.append(l),e.then(()=>{Object(F.c)(this,t),p(),l.classList.add("downloaded"),setTimeout(()=>{l.remove()},200)}),{download:e}};i.construct(),i.setManual(),i.attach(l),i.setDownloadFunction(e);const t=e=>{i.onClick(e)};Object(F.b)(this,t),this.noAutoDownload||t()}else{t.supportsStreaming&&p(!1);const s=e=>{if(this.audio||p(!1),!this.audio.src){if(se.resolveWaitingForLoadMedia(this.message.peerId,this.message.mid),se.willBePlayed(this.audio),!i)if(t.supportsStreaming)i=new ie.a({cancelable:!1}),i.attach(l,!1);else{i=new ie.a({cancelable:!0});const e=()=>{const e=n();return i.attach(l,!1,e),{download:e}};i.setDownloadFunction(e),e()}c.isSafari&&(this.audio.autoplay=!0,this.audio.play().catch(()=>{})),this.append(l),new Promise(e=>{this.audio.readyState>=2?e():this.addAudioListener("canplay",e)}).then(()=>{l.classList.add("downloaded"),setTimeout(()=>{l.remove()},200),se.willBePlayedMedia===this.audio&&(this.audio.play(),se.willBePlayedMedia=null)})}};(null===(e=this.audio)||void 0===e?void 0:e.src)||Object(F.b)(this,s,{once:!0,capture:!0,passive:!1})}}}addAudioListener(e,t){this.attachedHandlers[e]||(this.attachedHandlers[e]=[]),this.attachedHandlers[e].push(t),this.audio.addEventListener(e,t)}disconnectedCallback(){if(!this.isConnected){this.onTypeDisconnect&&(this.onTypeDisconnect(),this.onTypeDisconnect=null);for(let e in this.attachedHandlers){for(let t of this.attachedHandlers[e])this.audio.removeEventListener(e,t);delete this.attachedHandlers[e]}this.preloader=null}}}customElements.define("audio-element",pe);var me=s(70);class ge{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 be(e){var t;let{title:s,titleEl:n,subtitle:a,subtitleEl:o,mediaEl:r,message:l}=e;void 0!==s&&("string"==typeof s&&(s=Object(N.f)(s,140),s=q.a.wrapEmojiText(s)),Object(b.a)(n,s));let c=l&&l.media,d=!1;if(c&&r){if(o.textContent="",o.append(i.a.wrapMessageForReply(l)),c.webpage&&(c=c.webpage),c.photo||c.document&&-1!==["video","sticker","gif"].indexOf(c.document.type)){const e=32;if("sticker"===(null===(t=c.document)||void 0===t?void 0:t.type))r.style.backgroundImage&&(r.style.backgroundImage=""),d=!0,Vt({doc:c.document,div:r,lazyLoadQueue:da.chat.bubbles.lazyLoadQueue,group:ra,width:e,height:e});else{r.firstElementChild&&(r.innerHTML="");const t=c.photo||c.document,s=z.a.choosePhotoSize(t,e,e),i=ee.a.getCacheContext(t,s.type);if(!i.downloaded){const e=t.sizes||t.thumbs;e&&e[0].bytes&&(d=!0,Object(me.a)(r,z.a.getPreviewURLFromThumb(t,e[0])))}"photoSizeEmpty"!==s._&&(d=!0,z.a.preloadPhoto(t,s).then(()=>{Object(me.a)(r,i.url)}))}}}else"string"==typeof a&&(a=Object(N.f)(a,140),a=q.a.wrapEmojiText(a)),Object(b.a)(o,a);return d}class fe extends ge{constructor(e){super(e,(e,t="",s)=>{this.mediaEl||(this.mediaEl=document.createElement("div"),this.mediaEl.classList.add(this.className+"-media"));const i=be({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}}var ve=s(63);const ye=0,we=1,Le=2,Se=4,Me=8;class Ee{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=Ee.countRatios(e),this.proportions=Ee.countProportions(this.ratios),this.averageRatio=Object(ve.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 Ie(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:Me|we|Le},{geometry:{x:0,y:t+this.spacing,width:e,height:t},sides:Me|Se|Le}]}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:we|Me|Se},{geometry:{x:e+this.spacing,y:0,width:e,height:t},sides:we|Le|Se}]}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:we|Me|Se},{geometry:{x:s+this.spacing,y:0,width:t,height:i},sides:we|Le|Se}]}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:we|Me|Se},{geometry:{x:n+this.spacing,y:0,width:i,height:s},sides:we|Le},{geometry:{x:n+this.spacing,y:s+this.spacing,width:i,height:t},sides:Se|Le}]}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:Me|we|Le},{geometry:{x:0,y:t+this.spacing,width:s,height:i},sides:Se|Me},{geometry:{x:s+this.spacing,y:t+this.spacing,width:n,height:i},sides:Se|Le}]}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:Me|we|Le},{geometry:{x:0,y:t+this.spacing,width:i,height:o},sides:Se|Me},{geometry:{x:i+this.spacing,y:t+this.spacing,width:a,height:o},sides:Se},{geometry:{x:i+this.spacing+a+this.spacing,y:t+this.spacing,width:n,height:o},sides:Le|Se}]}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:we|Me|Se},{geometry:{x:t+this.spacing,y:0,width:o,height:i},sides:we|Le},{geometry:{x:t+this.spacing,y:i+this.spacing,width:o,height:n},sides:Le},{geometry:{x:t+this.spacing,y:i+n+2*this.spacing,width:o,height:a},sides:Se|Le}]}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 Ie{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=Ie.cropRatios(e,t),this.count=e.length}static cropRatios(e,t){return e.map(e=>t>1.1?Object(u.a)(e,1,2.75):Object(u.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(ve.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(ve.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=ye|(0===t?we:ye)|(t===l-1?Se:ye)|(0===o?Me:ye)|(o===s-1?Le:ye),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 Ce=s(98),ke=s(56),Te=s(43),Pe=s(79);class xe{constructor(e){this.isChanged=()=>!!this.uploadAvatar||!!this.inputFields.find(e=>e.isValid()),this.handleChange=()=>{this.nextBtn.classList.toggle("is-visible",this.isChanged())},Object(A.g)(this,e),this.nextBtn=B({icon:"check"}),this.avatarElem=document.createElement("avatar-element"),this.avatarElem.classList.add("avatar-placeholder","avatar-120"),this.avatarElem.setAttribute("peer",""+this.peerId),e.doNotEditAvatar||(this.avatarEdit=new _(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)})}}class Ae{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?this.subtitle.innerHTML=e.subtitle:e.subtitleLangKey&&this.subtitle.append(Object(f.i18n)(e.subtitleLangKey)),this.container.append(this.subtitle);let t=!1;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(b.a)(this.subtitle,Object(f.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(f.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"),Object(Q.ripple)(this.container,void 0,void 0,!0))}}const Fe=(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 Oe(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 De=s(55);class je{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&&(p.default.getState().then(t=>{s.checked=Object(A.d)(t,e.stateKey)===e.value}),s.addEventListener("change",()=>{p.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(f._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 _e=document.createElement("div");function Be(e){_e.innerHTML=e,document.body.append(_e),_e.dataset.timeout&&clearTimeout(+_e.dataset.timeout),_e.dataset.timeout=""+setTimeout(()=>{_e.remove(),delete _e.dataset.timeout},3e3)}_e.classList.add("toast");var Re=s(14),He=s(15);class Ne extends w.b{constructor(e){super(e),this.checkUsernameDebounced=Object(Re.a)(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(w.a.Neutral,this.options.label),void(this.options.onChange&&this.options.onChange());q.b.isUsernameValid(e)?this.setState(w.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=He.a.invokeApi("channels.checkUsername",{channel:D.a.getChannelInput(-this.options.peerId),username:e}):this.checkUsernamePromise=He.a.invokeApi("account.checkUsername",{username:e}),this.checkUsernamePromise.then(t=>{this.getValue()===e&&(t?this.setState(w.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()&&q.b.isUsernameValid(t)&&this.checkUsername(t)}))}}var Ue=s(50);class ze extends Ue.b{constructor(e,t={}){if(super("popup-peer"+(e?" "+e:""),Object(Ue.a)(t.buttons),Object.assign({overlayClosable:!0},t)),this.className=e,t.peerId){let e=new wa;e.setAttribute("dialog","1"),e.setAttribute("peer",""+t.peerId),e.classList.add("avatar-32"),this.header.prepend(e)}t.descriptionLangKey?this.title.append(Object(f.i18n)(t.titleLangKey,t.titleLangArgs)):this.title.innerText=t.title||"";let s=document.createElement("p");s.classList.add("popup-description"),t.descriptionLangKey?s.append(Object(f.i18n)(t.descriptionLangKey,t.descriptionLangArgs)):s.innerHTML=t.description;const i=document.createDocumentFragment();i.append(s),t.checkboxes&&(this.container.classList.add("have-checkbox"),t.checkboxes.forEach(e=>{e.withRipple=!0;const t=new Te.a(e);e.checkboxField=t,i.append(t.label)}),t.buttons.forEach(e=>{if(e.callback){const s=e.callback;e.callback=()=>{const e={};t.checkboxes.forEach(t=>{e[t.text]=t.checkboxField.checked}),s(e)}}})),this.container.insertBefore(i,this.header.nextElementSibling)}}var We=s(44);class qe extends x{init(){this.container.classList.add("edit-peer-container","group-type-container");const e=D.a.isBroadcast(this.chatId);this.setTitle(e?"ChannelType":"GroupType");const t=new ci({name:e?"ChannelType":"GroupType"}),s=Object(De.b)(),i=new Ae({radioField:new je({langKey:e?"ChannelPrivate":"MegaPrivate",name:s,value:"private"}),subtitleLangKey:e?"ChannelPrivateInfo":"MegaPrivateInfo"}),a=new Ae({radioField:new je({langKey:e?"ChannelPublic":"MegaPublic",name:s,value:"public"}),subtitleLangKey:e?"ChannelPublicInfo":"MegaPublicInfo"}),o=Fe([i,a],e=>{const t=[l,h];"public"===e&&t.reverse(),t[0].container.classList.remove("hide"),t[1].container.classList.add("hide"),p()}),r=D.a.getChat(this.chatId);t.content.append(o);const l=new ci({}),c=new Ae({title:this.chatFull.exported_invite.link,subtitleLangKey:e?"ChannelPrivateLinkHelp":"MegaPrivateLinkHelp",clickable:()=>{Oe(this.chatFull.exported_invite.link),Be(f.default.format("LinkCopied",!0))}}),d=Object(C.a)("btn-primary btn-transparent danger",{icon:"delete",text:"RevokeLink"});Object(F.b)(d,()=>{new ze("revoke-link",{buttons:[{langKey:"RevokeButton",callback:()=>{const e=Object(We.a)([d],!0);n.default.getChatInviteLink(this.chatId,!0).then(t=>{e(),c.title.innerHTML=t})}}],titleLangKey:"RevokeLink",descriptionLangKey:"RevokeAlert"}).show()},{listenerSetter:this.listenerSetter}),l.content.append(c.container,d);const h=new ci({caption:e?"Channel.UsernameAboutChannel":"Channel.UsernameAboutGroup",noDelimiter:!0}),u=document.createElement("div");u.classList.add("input-wrapper");const p=()=>{const e=i.radioField.checked&&"t.me/"!==g||m.isValid()&&m.input.classList.contains("valid");b.classList.toggle("is-visible",e)},m=new Ne({label:"SetUrlPlaceholder",name:"group-public-link",plainText:!0,listenerSetter:this.listenerSetter,availableText:"Link.Available",invalidText:"Link.Invalid",takenText:"Link.Taken",onChange:p,peerId:-this.chatId,head:"t.me/"}),g="t.me/"+(r.username||"");u.append(m.container),h.content.append(u);const b=B({icon:"check",className:"is-visible"});this.content.append(b),Object(F.b)(b,()=>{Object(K.g)(b);const e=a.radioField.checked?m.getValue():"";D.a.migrateChat(this.chatId).then(t=>D.a.updateUsername(t,e)).then(()=>{this.close()})},{listenerSetter:this.listenerSetter}),("t.me/"!==g?a:i).radioField.checked=!0,m.setOriginalValue(g),this.scrollable.append(t.container,l.container,h.container)}}var Ve=s(47);class Ge{constructor(e){this.loading=!1,this.loaded=!1,Object(A.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 Ke=s(37);var Qe=s(1),$e=s(48),Ye=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 Xe,Je=!1;class Ze{constructor(e){this.container=document.createElement("div"),this.list=Ta.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.checkForTriggers=()=>{this.scrollable.checkForTriggers()},Object(A.g)(this,e),this.container.classList.add("selector");let t=!1;const s=(this.renderResultsFunc||this.renderResults).bind(this);if(this.renderResultsFunc=e=>(t&&(this.scrollable.splitUp.replaceWith(this.list),this.scrollable.setVirtualContainer(this.list),t=!1),e=e.filter(e=>{const t=!this.renderedPeerIds.has(e);return t&&this.renderedPeerIds.add(e),t}),s(e)),this.input=document.createElement("input"),this.input.classList.add("selector-search-input"),this.placeholder?Object(f._i18n)(this.input,this.placeholder,void 0,"placeholder"):Object(f._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 g.b(e);let t=document.createElement("hr");this.selectedContainer.addEventListener("click",e=>{if(this.freezed)return;let t=e.target;if(t=Object(Qe.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 g.b(this.chatsContainer),this.scrollable.setVirtualContainer(this.list),this.chatsContainer.addEventListener("click",e=>{const t=(s=e.target,i="data-peer-id",s.closest(`[${i}]`));var s,i;if(Object(re.a)(e),!t)return;if(this.freezed)return;let n=t.dataset.peerId;if(n=+n||n,!this.multiSelect)return void this.add(n);this.selected.has(n)?this.remove(n):this.add(n);const a=t.querySelector("input");a.checked=!a.checked}),this.input.addEventListener("input",()=>{const e=this.input.value;if(this.query!==e){this.peerType.includes("contacts")&&(this.cachedContacts=null),this.folderId=0,this.offsetIndex=0;for(let e in this.tempIds)++this.tempIds[e];this.list=Ta.createChatList(),this.promise=null,this.loadedWhat={},this.query=e,this.renderedPeerIds.clear(),t=!0,this.getMoreResults()}}),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&&!m.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 Ye(this,void 0,void 0,(function*(){if(this.promise)return this.promise;if(this.loadedWhat.dialogs&&this.loadedWhat.archived)return;const e=z.a.windowH/72*1.25|0,t=this.getTempId("dialogs");this.promise=i.a.getConversations(this.query,this.offsetIndex,e,this.folderId);const s=yield this.promise;if(this.promise=null,this.tempIds.dialogs!==t)return;let n=s.dialogs;if(n.length){const e=n[n.length-1].index||0;n=n.slice(),n.findAndSplice(e=>e.peerId===a.default.myId),this.chatRightsAction&&(n=n.filter(e=>e.peerId>0&&("send_messages"!==this.chatRightsAction||m.a.canSendToUser(e.peerId))||D.a.hasRights(-e.peerId,this.chatRightsAction))),this.renderSaved(),this.offsetIndex=e,this.renderResultsFunc(n.map(e=>e.peerId))}else{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()}}))}getMoreContacts(){return Ye(this,void 0,void 0,(function*(){if(this.promise)return this.promise;if(!this.loadedWhat.contacts){if(!this.cachedContacts){const e=this.getTempId("contacts");if(this.promise=m.a.getContacts(this.query),this.cachedContacts=(yield this.promise).slice(),this.tempIds.contacts!==e)return;this.cachedContacts.findAndSplice(e=>e===a.default.myId),this.promise=null}if(this.cachedContacts.length){const e=z.a.windowH/72*1.25|0,t=this.cachedContacts.splice(0,e);this.renderResultsFunc(t)}return this.cachedContacts.length||(this.loadedWhat.contacts=!0,this.peerType.includes("dialogs"))?void 0:this.getMoreDialogs()}}))}getMoreChannelParticipants(){return Ye(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=>D.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 Je||!this.peerType.includes("dialogs")&&!this.peerType.includes("contacts")||(Xe||(Xe=i.a.getConversationsAll().then(()=>{Je=!0}).finally(()=>{Xe=null})),e.push(Xe)),!this.peerType.includes("dialogs")&&!this.loadedWhat.contacts||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=>m.a.isNonContactUser(e))),e.forEach(e=>{const{dom:t}=Ta.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 Te.a;s&&(i.input.checked=!0),t.containerEl.prepend(i.label)}let s;s=e<0?D.a.getChatMembersString(-e):e===a.default.myId?Object(f.i18n)("Presence.YourChat"):m.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);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 $e.a({peerId:e,onlyFirstName:!0,dialog:!0}).element),n.setAttribute("peer",""+e)),t&&("string"==typeof t?i.innerHTML=t:(Object(b.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,Ke.a.Static)})}}var et=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 extends Ue.b{constructor(e){super("popup-forward",null,{closable:!0,overlayClosable:!0,body:!0}),e.onClose&&(this.onClose=e.onClose),this.selector=new Ze({appendTo:this.body,onChange:()=>et(this,void 0,void 0,(function*(){const t=this.selector.getSelected()[0];if(this.selector=null,e.onSelect){const s=e.onSelect(t);s instanceof Promise&&(yield s)}this.hide()})),peerType:e.peerTypes,onFirstRender:()=>{this.show(),this.selector.checkForTriggers(),l.isTouchSupported||this.selector.input.focus()},chatRightsAction:e.chatRightsAction,multiSelect:!1,rippleEnabled:!1,avatarSize:46,peerId:e.peerId,placeholder:e.placeholder}),this.title.append(this.selector.input)}}class st extends x{init(){let e;this.container.classList.add("edit-peer-container","user-permissions-container"),this.setTitle("UserRestrictions");{const t=new ci({name:"UserRestrictionsCanDo"}),s=document.createElement("div");s.classList.add("chatlist-container"),t.content.insertBefore(s,t.title);const i=Ta.createChatList();s.append(i);const{dom:n}=Ta.addDialogNew({dialog:this.userId,container:i,drawStatus:!1,rippleEnabled:!0,avatarSize:48});n.lastMessageSpan.append(m.a.getUserStatusString(this.userId));const a=new nt({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(A.b)(this.participant.banned_rights.pFlags,e.pFlags)||D.a.editBanned(this.chatId,this.participant,e)},this.eventListener.addEventListener("destroy",e),this.scrollable.append(t.container)}{const t=new ci({});if("channelParticipantBanned"===this.participant._){const s=Object(C.a)("btn-primary btn-transparent danger",{icon:"delete",text:"GroupPermission.Delete"});Object(F.b)(s,()=>{const t=Object(We.a)([s],!0);D.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(C.a)("btn-primary btn-transparent danger",{icon:"deleteuser",text:"UserRestrictionsBlock"});Object(F.b)(s,()=>{Object(We.a)([s],!0);D.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 it=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 nt{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=D.a.getChat(e.chatId).default_banned_rights,s=e.participant?D.a.combineParticipantBannedRights(e.chatId,e.participant.banned_rights):t;for(const i of this.v){const n=i.flags[0];i.checkboxField=new Te.a({text:i.text,checked:D.a.hasRights(e.chatId,n,s),restriction:!0,withRipple:!0}),e.participant&&t.pFlags[n]&&(i.checkboxField.input.disabled=!0,Object(F.b)(i.checkboxField.label,e=>{Be(f.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 at extends x{init(){return it(this,void 0,void 0,(function*(){let e;this.container.classList.add("edit-peer-container","group-permissions-container"),this.setTitle("ChannelPermissions");{const t=new ci({name:"ChannelPermissionsHeader"});e=new nt({chatId:this.chatId,listenerSetter:this.listenerSetter,appendTo:t.content}),this.eventListener.addEventListener("destroy",()=>{D.a.editChatDefaultBannedRights(this.chatId,e.takeOut())}),this.scrollable.append(t.container)}{const t=new ci({name:"PrivacyExceptions"}),s=new Ae({titleLangKey:"ChannelAddException",subtitleLangKey:"Loading",icon:"adduser",clickable:()=>{new tt({peerTypes:["channelParticipants"],onSelect:e=>{setTimeout(()=>{i(e)},0)},placeholder:"ExceptionModal.Search.Placeholder",peerId:-this.chatId})}}),i=e=>it(this,void 0,void 0,(function*(){let t;try{t=yield n.default.getChannelParticipant(this.chatId,e)}catch(e){return void Be("User is no longer participant")}const s=new st(this.slider);s.participant=t,s.chatId=this.chatId,s.userId=e,s.open()}));t.content.append(s.container);const o=t.generateContentElement();o.classList.add("chatlist-container");const r=Ta.createChatList();o.append(r),Object(F.b)(r,e=>{const t=Object(Ve.a)(e.target,"LI");if(!t)return;const s=+t.dataset.peerId;i(s)},{listenerSetter:this.listenerSetter});const l=(t,s)=>{const i=s.banned_rights,n=D.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(f.join)(a.map(e=>Object(f.i18n)(e)),!1))),o.classList.toggle("hide",!a.length)},c=(e,t)=>{const{dom:s}=Ta.addDialogNew({dialog:U.a.getPeerId(e.peer),container:r,drawStatus:!1,rippleEnabled:!0,avatarSize:48,append:t});l(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=r.querySelector(`[data-peer-id="${e.user_id}"]`);n?(a?l(a,e.new_participant):c(e.new_participant,!1),"channelParticipantBanned"!==(null===(s=e.prev_participant)||void 0===s?void 0:s._)&&++h):(a&&a.remove(),"channelParticipantBanned"===(null===(i=e.prev_participant)||void 0===i?void 0:i._)&&--h),d()});const d=()=>{Object(b.a)(s.subtitle,Object(f.i18n)(h?"Permissions.ExceptionsCount":"Permissions.NoExceptions",[h]))};let h=0;const u=50,p=new Ge({scrollable:this.scrollable,getPromise:()=>n.default.getChannelParticipants(this.chatId,{_:"channelParticipantsBanned",q:""},u,r.childElementCount).then(e=>{for(const t of e.participants)c(t,!0);return h=e.count,d(),e.participants.length<u||e.count===r.childElementCount})});this.scrollable.append(t.container),yield p.load()}}))}onOpenAfterTimeout(){this.scrollable.onScroll()}}class ot{constructor(e,t=U.a.getDialogType(e),s){const n=new $e.a({peerId:e,onlyFirstName:!0}).element,a=t=>{let n=D.a.leave(-e);h&&t[h[0].text]&&(n=n.then(()=>i.a.flushHistory(e))),s&&s(n)},o=t=>{let n;if(e>0)n=i.a.flushHistory(e,!1,h?t[h[0].text]:void 0);else{if(!t[h[0].text])return a(t);n=D.a.delete(-e)}s&&s(n)};let r,l,c,d,h;switch(t){case"channel":r="LeaveChannelMenu",l="ChannelLeaveAlertWithName",c=[n],d=[{langKey:"LeaveChannel",isDanger:!0,callback:a}];break;case"chat":r="DeleteChatUser",l="AreYouSureDeleteThisChatWithUser",c=[n],h=[{text:"DeleteMessagesOptionAlso",textArgs:[new $e.a({peerId:e,onlyFirstName:!0}).element]}],d=[{langKey:"DeleteChatUser",isDanger:!0,callback:o}];break;case"saved":r="DeleteChatUser",l="AreYouSureDeleteThisChatSavedMessages",d=[{langKey:"DeleteChatUser",isDanger:!0,callback:o}];break;case"megagroup":case"group":D.a.hasRights(-e,"delete_chat")?(r="DeleteMegaMenu",l="AreYouSureDeleteAndExit",d=[{langKey:"DeleteMegaMenu",isDanger:!0,callback:o}],h=[{text:"DeleteChat.DeleteGroupForAll"}]):(r="LeaveMegaMenu",l="AreYouSureDeleteAndExitName",c=[n],d=[{langKey:"DeleteChatUser",isDanger:!0,callback:a}])}new ze("popup-delete-chat",{peerId:e,titleLangKey:r,descriptionLangKey:l,descriptionLangArgs:c,buttons:d,checkboxes:h}).show()}}var rt=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 lt extends P{_init(){return rt(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=D.a.getChat(this.chatId),s=D.a.isBroadcast(this.chatId),i=D.a.isChannel(this.chatId);{const i=new ci({noDelimiter:!0}),n=[],o=document.createElement("div");if(o.classList.add("input-wrapper"),this.chatNameInputField=new w.b({label:s?"Channel.ChannelNameHolder":"CreateGroup.NameHolder",name:"chat-name",maxLength:255}),this.descriptionInputField=new w.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),D.a.hasRights(this.chatId,"change_type")){const n=new Ae({titleLangKey:s?"ChannelType":"GroupType",clickable:()=>{const t=new qe(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(f.i18n)(e))};a(),i.content.append(n.container)}if(D.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 Ae({titleLangKey:"ChannelPermissions",clickable:()=>{const e=new at(this.slider);e.chatId=this.chatId,e.open()},icon:"permissions"}),n=()=>{s.subtitle.innerHTML=e.reduce((e,s)=>e+ +D.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()})}this.scrollable.append(i.container),Object(F.b)(this.editPeer.nextBtn,()=>{this.editPeer.nextBtn.disabled=!0;let e=[];const t=this.chatId;this.chatNameInputField.isValid()&&e.push(D.a.editTitle(t,this.chatNameInputField.value)),this.descriptionInputField.isValid()&&e.push(D.a.editAbout(t,this.descriptionInputField.value)),this.editPeer.uploadAvatar&&e.push(this.editPeer.uploadAvatar().then(e=>D.a.editPhoto(t,e))),Promise.race(e).finally(()=>{this.editPeer.nextBtn.removeAttribute("disabled"),this.close()})},{listenerSetter:this.listenerSetter})}if(D.a.hasRights(this.chatId,"delete_chat")){const e=new ci({}),t=Object(C.a)("btn-primary btn-transparent danger",{icon:"delete",text:s?"PeerInfo.DeleteChannel":"DeleteMega"});Object(F.b)(t,()=>{s?new ze("popup-delete-channel",{peerId:-this.chatId,titleLangKey:"ChannelDeleteMenu",descriptionLangKey:"AreYouSureDeleteAndExitChannel",buttons:Object(Ue.a)([{langKey:"ChannelDeleteMenu",callback:()=>{Object(We.a)([t],!0)},isDanger:!0},{langKey:"DeleteChannelForAll",callback:()=>{const e=Object(We.a)([t],!0);D.a.deleteChannel(this.chatId).then(()=>{this.close()},()=>{e()})},isDanger:!0}])}).show():new ot(-this.chatId,void 0,e=>{const s=Object(We.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()}}class ct extends P{init(){this.container.classList.add("edit-peer-container","edit-contact-container"),this.setTitle("Edit");{const e=new ci({noDelimiter:!0}),t=[],s=document.createElement("div");s.classList.add("input-wrapper"),this.nameInputField=new w.b({label:"EditProfile.FirstNameLabel",name:"contact-name",maxLength:70}),this.lastNameInputField=new w.b({label:"Login.Register.LastName.Placeholder",name:"contact-lastname",maxLength:70});const n=m.a.getUser(this.peerId);this.nameInputField.setOriginalValue(n.first_name),this.lastNameInputField.setOriginalValue(n.last_name),s.append(this.nameInputField.container,this.lastNameInputField.container),t.push(this.nameInputField,this.lastNameInputField),this.editPeer=new xe({peerId:this.peerId,inputFields:t,listenerSetter:this.listenerSetter,doNotEditAvatar:!0}),this.content.append(this.editPeer.nextBtn);const o=document.createElement("div");o.classList.add("avatar-edit"),o.append(this.editPeer.avatarElem);const r=new Te.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=U.a.getPeerId(e.peer.peer);if(this.peerId===t){const t=!Pe.a.isMuted(e.notify_settings);t!==r.checked&&(r.checked=t)}});const l=new Ae({checkboxField:r}),c=!Pe.a.isPeerLocalMuted(this.peerId,!1);r.checked=c;const d=document.createElement("div");d.classList.add("profile-name"),d.append(new $e.a({peerId:this.peerId}).element);const h=document.createElement("div");h.classList.add("profile-subtitle"),h.append(Object(f.i18n)("EditContact.OriginalName")),e.content.append(o,d,h,s,l.container),this.scrollable.append(e.container),Object(F.b)(this.editPeer.nextBtn,()=>{this.editPeer.nextBtn.disabled=!0,m.a.addContact(this.peerId,this.nameInputField.value,this.lastNameInputField.value,m.a.getUser(this.peerId).phone).finally(()=>{this.editPeer.nextBtn.removeAttribute("disabled"),this.close()})},{listenerSetter:this.listenerSetter})}{const e=new ci({}),t=Object(C.a)("btn-primary btn-transparent danger",{icon:"delete",text:"PeerInfo.DeleteContact"});Object(F.b)(t,()=>{new ze("popup-delete-contact",{peerId:this.peerId,titleLangKey:"DeleteContact",descriptionLangKey:"AreYouSureDeleteContact",buttons:Object(Ue.a)([{langKey:"Delete",callback:()=>{const e=Object(We.a)([t],!0);m.a.deleteContacts([this.peerId]).then(()=>{this.close()},()=>{e()})},isDanger:!0}])}).show()},{listenerSetter:this.listenerSetter}),e.content.append(t),this.scrollable.append(e.container)}}}const dt=e=>e.touches?e.touches[0]:e,ht=window;class ut{constructor(e){this.hadMove=!1,this.xDown=null,this.yDown=null,this.reset=e=>{l.isTouchSupported?ht.removeEventListener("touchmove",this.handleMove,{capture:!0}):(ht.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=dt(e);if(this.verifyTouchTarget&&!this.verifyTouchTarget(e))return this.reset();this.xDown=t.clientX,this.yDown=t.clientY,l.isTouchSupported?ht.addEventListener("touchmove",this.handleMove,{passive:!1,capture:!0}):ht.addEventListener("mousemove",this.handleMove,!1)},this.handleMove=e=>{if(null===this.xDown||null===this.yDown)return this.reset();Object(re.a)(e);const t=dt(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,l.isTouchSupported||(this.element.style.cursor="grabbing"),this.onFirstSwipe&&this.onFirstSwipe()}this.onSwipe(n,a)&&this.reset()},Object(A.g)(this,e),l.isTouchSupported?(this.element.addEventListener("touchstart",this.handleStart,!1),ht.addEventListener("touchend",this.reset)):(this.element.addEventListener("mousedown",this.handleStart,!1),ht.addEventListener("mouseup",this.reset))}}class pt extends P{init(){this.nextBtn=B({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){this.nextBtn.classList.remove("tgico-arrow_next"),this.nextBtn.disabled=!0,Object(K.f)(this.nextBtn),this.selector.freezed=!0,e.then(()=>{this.close()})}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 Ze({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 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())}))};let gt=(e,t)=>{t.title.innerHTML=e,t.container.style.display=""};const bt=!c.isFirefox;class ft{constructor(e){this.previous=[],this.next=[],this.tempId=0,this.loadCount=50,this.reverse=!1,this.loadedAllUp=!1,this.loadedAllDown=!1,Object(A.g)(this,e)}get index(){return void 0!==this.count?this.previous.length:-1}go(e){let t,s;if(e>0){if(t=this.next.splice(0,e),s=t.pop(),!s)return;this.previous.push(this.current,...t)}else{if(t=this.previous.splice(this.previous.length+e,-e),s=t.shift(),!s)return;this.next.unshift(...t,this.current)}this.current=s,this.onJump(s,e>0)}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).then(t=>{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):ve.c.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))})},()=>{}).then(()=>{e?this.loadPromiseDown=null:this.loadPromiseUp=null});return e?this.loadPromiseDown=s:this.loadPromiseUp=s,s}}class vt{constructor(e){this.scrollable=e,this.processItem=e=>{const t=document.createElement("div");let s;t.classList.add(vt.BASE_CLASS+"-avatar"),e&&(s="string"==typeof e?z.a.getPhoto(e):e.action.photo);const i=new Image;if(i.classList.add(vt.BASE_CLASS+"-avatar-image"),i.draggable=!1,s){const e=z.a.choosePhotoSize(s,420,420,!1);z.a.preloadPhoto(s,e).then(()=>{const n=ee.a.getCacheContext(s,e.type);Object(me.a)(i,n.url,()=>{t.append(i)})})}else{const e=U.a.getPeerPhoto(this.peerId);n.default.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(vt.BASE_CLASS+"-container"),this.avatars=document.createElement("div"),this.avatars.classList.add(vt.BASE_CLASS+"-avatars"),this.gradient=document.createElement("div"),this.gradient.classList.add(vt.BASE_CLASS+"-gradient"),this.info=document.createElement("div"),this.info.classList.add(vt.BASE_CLASS+"-info"),this.tabs=document.createElement("div"),this.tabs.classList.add(vt.BASE_CLASS+"-tabs"),this.container.append(this.avatars,this.gradient,this.info,this.tabs);const t=()=>0===this.scrollable.scrollTop||(this.scrollable.scrollIntoViewNew(this.scrollable.container.firstElementChild,"start"),!1);let s=!1,i=!1;Object(F.b)(this.container,e=>mt(this,void 0,void 0,(function*(){if(i)return void Object(re.a)(e);if(s)return void(s=!1);if(!t())return;const n=this.container.getBoundingClientRect(),a=(e.touches?e.touches[0]: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,fa(a,e,()=>e===this.peerId,this.listLoader.current,s,n),i=!1}else{const e=a>n.right-n.width/2;this.listLoader.go(e?1:-1)}})));const a=()=>{s=!0,document.body.addEventListener(l.isTouchSupported?"touchend":"click",e=>{s=!1},{once:!0})};let o=0,r=0,c=0,d=0;new ut({element:this.avatars,onSwipe:(e,t)=>{c=e;let s=r+e*-vt.SCALE;return s>0?s=0:s<d&&(s=d),this.avatars.style.transform=vt.TRANSLATE_TEMPLATE.replace("{x}",s+"px"),!1},verifyTouchTarget:e=>t()?!this.tabs.classList.contains("hide")&&!i:(a(),Object(re.a)(e),!1),onFirstSwipe:()=>{const e=this.avatars.getBoundingClientRect();o=e.width,d=-o*(this.tabs.childElementCount-1),r=e.left-this.container.getBoundingClientRect().left,this.avatars.style.transform=vt.TRANSLATE_TEMPLATE.replace("{x}",r+"px"),this.avatars.classList.add("no-transition"),this.avatars.offsetLeft},onReset:()=>{const e=Math.ceil(Math.abs(c)/(o/vt.SCALE))*(c>=0?1:-1);a(),this.avatars.classList.remove("no-transition"),Object(Re.c)(()=>{this.listLoader.go(e)})}})}setPeer(e){this.peerId=e;const t=U.a.getPeerPhoto(e);if(!t)return;const s=this.listLoader=new ft({loadCount:50,loadMore:(t,a)=>{if(e>0)return z.a.getUserPhotos(e,t||s.current,50).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:50,backLimit:0})),Promise.all(t).then(e=>{const t=e.pop();if(!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*vt.SCALE*s;this.avatars.style.transform=vt.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(vt.BASE_CLASS+"-tab"),this.tabs.append(e),1===this.tabs.childElementCount&&e.classList.add("active"),this.tabs.classList.toggle("hide",this.tabs.childElementCount<=1)}}vt.BASE_CLASS="profile-avatars",vt.SCALE=bt?2:1,vt.TRANSLATE_TEMPLATE=bt?`translate3d({x}, 0, -1px) scale(${vt.SCALE})`:"translate({x}, 0)";class yt{constructor(e){this.scrollable=e,this.peerId=0,this.setPeerStatus=(e=!1)=>{if(!this.peerId)return;const t=this.peerId;da.setPeerStatus(this.peerId,this.subtitle,e,!0,()=>t===this.peerId)},bt||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 ci({noDelimiter:!0}),this.avatar=new wa,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 Ae({title:" ",subtitleLangKey:"UserBio",icon:"info",clickable:e=>{"A"!==e.target.tagName&&n.default.getProfileByPeerId(this.peerId).then(e=>{Oe(e.about),Be(f.default.format("BioCopied",!0))})}}),this.bio.title.classList.add("pre-wrap"),this.username=new Ae({title:" ",subtitleLangKey:"Username",icon:"username",clickable:()=>{Oe("@"+U.a.getPeer(this.peerId).username),Be(f.default.format("UsernameCopied",!0))}}),this.phone=new Ae({title:" ",subtitleLangKey:"Phone",icon:"phone",clickable:()=>{Oe("+"+m.a.getUser(this.peerId).phone),Be(f.default.format("PhoneCopied",!0))}}),this.notifications=new Ae({checkboxField:new Te.a({toggle:!0}),titleLangKey:"Notifications",icon:"unmute"}),this.section.content.append(this.phone.container,this.username.container,this.bio.container,this.notifications.container);const e=document.createElement("div");e.classList.add("gradient-delimiter"),this.element.append(this.section.container,e),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=Pe.a.isPeerLocalMuted(this.peerId,!1);this.notifications.checkboxField.checked=!e}}),a.default.addEventListener("peer_typings",e=>{const{peerId:t}=e;this.peerId===t&&this.setPeerStatus()}),a.default.addEventListener("peer_bio_edit",e=>{e===this.peerId&&this.setBio(!0)}),a.default.addEventListener("user_update",e=>{const t=e;this.peerId===t&&this.setPeerStatus()}),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(U.a.getPeerPhoto(this.peerId)){const e=this.avatars;return this.avatars=new vt(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(bt&&this.scrollable.container.classList.add("parallax"))}}bt&&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(){if(!this.cleaned)return;this.cleaned=!1;const e=this.peerId;if(this.cleanupHTML(),this.setAvatar(),e!==a.default.myId){U.a.getPeerUsername(e)&&gt(U.a.getPeerUsername(e),this.username);const t=Pe.a.isPeerLocalMuted(e,!1);this.notifications.checkboxField.checked=!t}else window.requestAnimationFrame(()=>{this.notifications.container.style.display="none"});if(e>0){let t=m.a.getUser(e);t.phone&&e!==a.default.myId&&gt(m.a.formatUserPhone(t.phone),this.phone)}this.setBio(),Object(b.a)(this.name,new $e.a({peerId:e,dialog:!0}).element),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&&gt(e.rAbout,this.bio),!0)):n.default.getChatFull(-t,e).then(e=>this.peerId===t&&this.threadId===s&&(e.about&&gt(q.a.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 wt extends P{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(C.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(f.i18n)("Profile")),this.editBtn=k("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(f.i18n)("PeerInfo.SharedMedia")),n.append(o),s.append(i,n),this.header.append(s),this.profile=new yt(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(S.a)(s,"slide-fade",400,null,!1);r(0),Object(F.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||St.onCloseBtnClick()}),Object(F.b)(this.editBtn,e=>{let t;t=this.peerId<0?new lt(St):new ct(St),t&&(t instanceof lt?t.chatId=-this.peerId:t.peerId=this.peerId,t.open())}),this.searchSuper=new is({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:"inputMessagesFilterVoice",name:"SharedVoiceTab2",type:"voice"}],scrollable:this.scrollable,onChangeTab:e=>{let t="members"===e.type&&a.default.settings.animationsEnabled?250:0;setTimeout(()=>{l.classList.toggle("is-hidden","members"!==e.type)},t)}}),this.profile.element.append(this.searchSuper.container);const l=B({icon:"addmember_filled"});this.content.append(l),l.addEventListener("click",()=>{const e=-this.peerId,t=D.a.isChannel(e),s=(t,s)=>{let i,n;t.length>1?(i="PeerInfo.Confirm.AddMembers1",n=[t.length]):(i="PeerInfo.Confirm.AddMember",n=[new $e.a({peerId:t[0],onlyFirstName:!0}).element]),new ze("popup-add-members",{peerId:-e,titleLangKey:"GroupAddMembers",descriptionLangKey:i,descriptionLangArgs:n,buttons:[{langKey:"Add",callback:()=>{s()}}]}).show()};if(t){const t=new pt(this.slider);t.open({peerId:this.peerId,type:"channel",skippable:!1,takeOut:i=>(s(i,()=>{t.attachToPromise(D.a.inviteToChannel(e,i))}),!1),title:"GroupAddMembers",placeholder:"SendMessageTo"})}else new tt({peerTypes:["contacts"],placeholder:"Search",onSelect:t=>{setTimeout(()=>{s([t],()=>{D.a.addChatUser(e,t)})},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){this.historiesStorage[e][n]&&this.historiesStorage[e][n].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));break}}}}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;if(!this.historiesStorage[e][i])continue;const n=this.historiesStorage[e][i],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&&t.remove(),this.searchSuper.usedFromHistory[i]>=a+1&&this.searchSuper.usedFromHistory[i]--}break}}this.scrollable.onScroll()}}cleanupHTML(){this.profile.cleanupHTML(),this.editBtn.style.display="none",this.searchSuper.cleanupHTML(!0),this.container.classList.toggle("can-add-members",this.searchSuper.canViewMembers()&&D.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(){if(this.peerChanged)if(this.peerChanged=!1,this.cleanupHTML(),this.profile.fillProfileElements(),this.peerId>0)this.peerId!==a.default.myId&&m.a.isContact(this.peerId)&&(this.editBtn.style.display="");else{const e=D.a.getChat(-this.peerId);("chat"===e._||e.admin_rights)&&(this.editBtn.style.display="")}}loadSidebarMedia(e,t=!1){this.searchSuper.load(e,t)}onOpenAfterTimeout(){this.scrollable.onScroll()}}Z.a&&(Z.a.AppSharedMediaTab=wt);const Lt=new class extends O{constructor(){super({sidebarEl:document.getElementById("column-right"),canHideFirst:!0,navigationType:"right"}),r.b.addEventListener("changeScreen",(e,t)=>{t===r.a.medium&&e!==r.a.mobile&&this.toggleSidebar(!1)}),this.sharedMediaTab=new wt(this)}onCloseTab(e,t,s){this.historyTabIds.length||this.toggleSidebar(!1,t),super.onCloseTab(e,t,s)}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();const n=da.selectTab(s?1:2,t);return document.body.classList.toggle("is-right-column-shown",e),n}};Z.a.appSidebarRight=Lt;var St=Lt;class Mt extends P{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=Ce.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);Ct(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=q.a.wrapEmojiText(r.text);const d=document.createElement("div");d.innerText=Math.round(n[i])+"%",l.append(c,d);const h=Ta.createChatList();h.classList.add("poll-results-voters"),Ta.setListClickListener(h,()=>{St.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,Ce.a.getVotes(e,r.option,u,p).then(e=>{e.votes.forEach(e=>{const{dom:t}=Ta.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(f.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(Q.ripple)(v);const y=document.createElement("div");y.classList.add("tgico-down"),v.append(y,Object(f.i18n)("PollResults.LoadMore",[Math.min(20,g)])),a.append(v)}),this.resultsDiv.append(i,a),St.toggleSidebar(!0).then(()=>{}),t}}var Et=s(78);let It=0;const Ct=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",()=>{Tt&&kt(Tt,Pt,xt)});const kt=(e,t,s)=>{e.classList.remove("active"),clearTimeout(s),setTimeout(()=>{t(),e.remove(),Tt===e&&Pt===t&&xt===s&&(Tt=Pt=null,xt=0)},200)};let Tt,Pt,xt;class At extends HTMLElement{constructor(){super(),this.maxOffset=-46.5,this.isClosed=!1,this.isQuiz=!1,this.isRetracted=!1,this.isPublic=!1,this.isMultiple=!1,this.chosenIndexes=[],this.chosingIndexes=[],this.sentVote=!1}render(){It||(It=document.getElementById("poll-line").getTotalLength());const e=this.message.media.poll.id,{poll:t,results:s}=Ce.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");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">${q.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 ${r.b.active.regular.width} 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(f.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-ke.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(()=>{Ce.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(f.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(re.a)(e),St.isTabExists(Mt)||new Mt(St).open(this.message)}),Object(Q.ripple)(this.viewResults),this.isMultiple&&(this.sendVoteBtn=document.createElement("div"),this.sendVoteBtn.classList.add("poll-footer-button","poll-send-vote"),this.sendVoteBtn.append(Object(f.i18n)("Chat.Poll.SubmitVote")),Object(Q.ripple)(this.sendVoteBtn),t.chosenIndexes.length||this.votersCountDiv.classList.add("hide"),Object(F.b)(this.sendVoteBtn,e=>{Object(re.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)),t.chosenIndexes.length||this.isClosed?this.performResults(s,t.chosenIndexes,!1):this.isClosed||(this.setVotersCount(s),Object(F.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(F.b)(t,s=>{Object(re.a)(s),t.classList.add("active"),((e,t,s)=>{Tt&&kt(Tt,Pt,xt);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=q.a.wrapRichText(e,{entities:t}),da.chat.bubbles.bubblesContainer.append(i),i.offsetLeft,i.classList.add("active"),Tt=i,Pt=s,xt=window.setTimeout(()=>{kt(i,s,xt)},l.isTouchSupported?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(Qe.a)(e.target,"poll-answer");if(!t)return;Object(re.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=Ce.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(b.a)(this.typeDiv,Object(f.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(F.b)(this,this.clickHandler):Object(F.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(Et.a)(this,"",!this.isRetracted,340),Object(Re.c)(()=>{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" dialog="0" peer="${e}" ${0===s?"":`style="transform: translateX(-${3*s}px);"`}></avatar-element>`}),this.avatarsDiv.innerHTML=t}this.isMultiple&&(this.sendVoteBtn.classList.toggle("hide",!!this.chosenIndexes.length),this.chosenIndexes.length?this.isPublic?(this.viewResults.classList.toggle("hide",!e.total_voters||!this.chosenIndexes.length),this.votersCountDiv.classList.toggle("hide",!!this.chosenIndexes.length)):this.votersCountDiv.classList.toggle("hide",!this.chosenIndexes.length):(this.votersCountDiv.classList.add("hide"),this.viewResults.classList.add("hide")))}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(Re.c)(e):e()}let n;e=e.slice(),Ct(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(b.a)(this.votersCountDiv,Object(f.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]*100+"%, 485.9",s.style.strokeDashoffset=""+t*this.maxOffset)}}customElements.define("poll-element",At);var Ft=s(73),Ot=s(52),Dt=s(61),jt=s(81),_t=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 Bt=new class{constructor(){this.storage=new Dt.a(jt.a,"stickerSets"),this.getStickerSetPromises={},this.getStickersByEmoticonsPromises={},this.getStickerSet({id:"emoji",access_hash:""}),a.default.addMultipleEventsListeners({updateNewStickerSet:e=>{this.saveStickerSet(e.stickerset,e.stickerset.set.id),a.default.dispatchEvent("stickers_installed",e.stickerset.set)}})}saveStickers(e){Object(ve.c)(e,(t,s)=>{(t=d.a.saveDoc(t))?e[s]=t:e.splice(s,1)})}getStickerSet(e,t={}){return _t(this,void 0,void 0,(function*(){return this.getStickerSetPromises[e.id]?this.getStickerSetPromises[e.id]:this.getStickerSetPromises[e.id]=new Promise(s=>_t(this,void 0,void 0,(function*(){var i;if(!t.overwrite){const t=yield this.storage.get(e.id);if(t&&(null===(i=t.documents)||void 0===i?void 0:i.length)&&Date.now()-t.refreshTime<36e5)return this.saveStickers(t.documents),s(t),void delete this.getStickerSetPromises[e.id]}try{const t=yield He.a.invokeApi("messages.getStickerSet",{stickerset:this.getStickerSetInput(e)});this.saveStickerSet(t,e.id),s(t)}catch(e){s(null)}delete this.getStickerSetPromises[e.id]})))}))}getRecentStickers(){return _t(this,void 0,void 0,(function*(){const e=yield He.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?d.a.getDoc(s.documents[0]):void 0}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"}:{_:"inputStickerSetID",id:e.id,access_hash:e.access_hash}}getFeaturedStickers(){return _t(this,void 0,void 0,(function*(){const e=yield He.a.invokeApiHashable("messages.getFeaturedStickers");return e.sets.forEach(e=>{this.saveStickerSet({set:e.set,documents:[],packs:[]},e.set.id)}),e.sets}))}toggleStickerSet(e){return _t(this,void 0,void 0,(function*(){if(e.installed_date){if(yield He.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 He.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 _t(this,void 0,void 0,(function*(){const s=t?1:0,i=yield He.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 He.a.invokeApiHashable("messages.getAllStickers")}preloadStickerSets(){return this.getAllStickers().then(e=>Promise.all(e.sets.map(e=>this.getStickerSet(e))))}getStickersByEmoticon(e){return this.getStickersByEmoticonsPromises[e]?this.getStickersByEmoticonsPromises[e]:this.getStickersByEmoticonsPromises[e]=Promise.all([He.a.invokeApiHashable("messages.getStickers",{emoticon:e}),this.preloadStickerSets(),this.getRecentStickers()]).then(([t,s,i])=>{const n=t.stickers.map(e=>d.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=d.a.getDoc(e);(t.animated?a:o).push(t)}};r(i.packs);for(const e of s)r(e.packs);return[...new Set(a.concat(o,n))]})}};Z.a.appStickersManager=Bt;var Rt=Bt,Ht=s(39),Nt=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())}))};function Ut({doc:e,container:t,message:s,boxWidth:i,boxHeight:n,withTail:r,isOut:l,middleware:u,lazyLoadQueue:p,noInfo:m,group:g,onlyPreview:b,withoutPreloader:f,loadPromises:v,noPlayButton:y,noAutoDownload:w,size:L}){var S,M;const E=!(i&&n),I=("video"!==e.type||e.size<=52428800&&!E)&&("gif"===e.type?a.default.settings.autoPlay.gifs:a.default.settings.autoPlay.videos);let C,k;if(!m){C=document.createElement("span"),C.classList.add("video-time"),t.append(C);let s=!1;"gif"!==e.type?(C.innerText=(e.duration+"").toHHMMSS(!1),y||"round"===e.type||(I?C.classList.add("tgico","can-autoplay"):s=!0)):(C.innerText="GIF",I||y||(s=!0,w=void 0)),s&&(k=document.createElement("span"),k.classList.add("video-play","tgico-largeplay","btn-circle","position-center"),t.append(k))}let T={};if("image/gif"===e.mime_type){const a=qt({photo:e,message:s,container:t,boxWidth:i,boxHeight:n,withTail:r,isOut:l,lazyLoadQueue:p,middleware:u,withoutPreloader:f,loadPromises:v,noAutoDownload:w,size:L});return T.thumb=a,T.loadPromise=a.loadPromises.full,T}const P=document.createElement("video");if(P.classList.add("media-video"),P.setAttribute("playsinline","true"),P.muted=!0,"round"===e.type){const i=se.addMedia(s.peerId,e,s.mid,!w),n=document.createElement("div");n.classList.add("media-round","z-depth-1"),n.innerHTML='<svg class="progress-ring" width="200px" height="200px">\n <circle class="progress-ring__circle" stroke="white" stroke-opacity="0.3" stroke-width="3.5" cx="100" cy="100" r="93" fill="transparent" transform="rotate(-90, 100, 100)"/>\n </svg>';const a=n.querySelector(".progress-ring__circle"),o=a.r.baseVal.value,r=2*Math.PI*o;a.style.strokeDasharray=r+" "+r,a.style.strokeDashoffset=""+r,C.classList.add("tgico");const l=document.createElement("canvas");l.width=l.height=e.w,n.prepend(l,C),n.append(P),t.append(n);const c=l.getContext("2d"),d=()=>{(da.chat.setPeerPromise||Promise.resolve()).finally(()=>{Object(Ht.a)(i)||(i.removeEventListener("play",p),i.removeEventListener("timeupdate",u),i.removeEventListener("pause",m))})},h=()=>{c.drawImage(i,0,0);const e=r-i.currentTime/i.duration*r;return a.style.strokeDashoffset=""+e,!i.paused},u=()=>{i.duration&&(Object(Ht.a)(i)?C.innerText=(i.duration-i.currentTime+"").toHHMMSS(!1):d())},p=()=>{P.classList.add("hide"),n.classList.remove("is-paused"),Object(Ft.a)(h,l)},m=()=>{Object(Ht.a)(i)?n.classList.add("is-paused"):d()};i.addEventListener("play",p),i.addEventListener("timeupdate",u),i.addEventListener("pause",m),Object(F.b)(l,e=>{Object(re.a)(e),i.paused?i.play():i.pause()}),i.paused?i.duration&&i.currentTime!==i.duration?(h(),u(),P.classList.add("hide")):m():p()}else P.autoplay=!0;let x;if(s){if(x=qt({photo:e,message:s,container:t,boxWidth:i,boxHeight:n,withTail:r,isOut:l,lazyLoadQueue:p,middleware:u,withoutPreloader:!0,loadPromises:v,noAutoDownload:w,size:L}),T.thumb=x,!I&&"gif"!==e.type||b)return T.loadPromise=x.loadPromises.full,T;if(r){const e=(x.images.thumb||x.images.full).parentElement;P.width=+e.getAttributeNS(null,"width"),P.height=+e.getAttributeNS(null,"height"),e.append(P)}}else{const t=d.a.getThumb(e,!1);t&&t.promise.then(()=>{P.poster=t.cacheContext.url})}!P.parentElement&&t&&((null==x?void 0:x.aspecter)||t).append(P);const A=ee.a.getCacheContext(e);let O;(null===(S=null==s?void 0:s.media)||void 0===S?void 0:S.preloader)?(O=s.media.preloader,O.attach(t,!1),w=void 0):A.downloaded||e.supportsStreaming?e.supportsStreaming&&(O=new ie.a({cancelable:!1,attachMethod:"prepend"})):O=new ie.a({attachMethod:"prepend"});let D=w&&(null===(M=null==x?void 0:x.preloader)||void 0===M?void 0:M.loadFunc);const j=()=>{O&&w&&!f&&(O.construct(),O.setManual());let i=Promise.resolve();if(O)if(A.downloaded||e.supportsStreaming)e.supportsStreaming&&(w?i=Promise.reject():A.downloaded||(O.attach(t,!1,null),P.addEventListener(c.isSafari?"timeupdate":"canplay",()=>{O.detach()},{once:!0})));else{const s=i=d.a.downloadDoc(e,null==p?void 0:p.queueId,w);O.attach(t,!1,s)}!w&&D&&(D(),D=null),w=void 0;const n=Object(o.a)();return i.then(()=>{!u||u()?("round"===e.type&&se.resolveWaitingForLoadMedia(s.peerId,s.mid),Object(oe.d)(P).then(()=>{g&&h.a.addAnimation(P,g),n.resolve()}),"video"===e.type&&P.addEventListener("timeupdate",()=>{C.innerText=(P.duration-P.currentTime+"").toHHMMSS(!1)}),P.addEventListener("error",e=>{n.resolve()}),P.muted=!0,P.loop=!0,P.autoplay=!0,Object(me.a)(P,A.url)):n.resolve()},()=>{}),{download:i,render:n}};return O&&O.setDownloadFunction(j),"gif"!==e.type||I?T.loadPromise=p?(p.push({div:t,load:()=>j().render}),Promise.resolve()):j().render:Object(F.b)(t,e=>{Object(re.a)(e),k.remove(),j()},{capture:!0,once:!0}),T}const zt=(e,t=!1,s=!0)=>{const i=new Date(1e3*e);let n=H.g[i.getMonth()];t&&(n=n.slice(0,3));let a=n+" "+i.getDate();return s&&(a+=", "+i.getFullYear()),a+" at "+i.getHours()+":"+("0"+i.getMinutes()).slice(-2)};function Wt({message:e,withTime:t,fontWeight:s,voiceAsMusic:n,showSender:a,searchContext:o,loadPromises:r,noAutoDownload:l}){var c,h;s||(s=500);const p=e.media.document||e.media.webpage.document,m=e.pFlags.is_outgoing&&(null===(c=e.media)||void 0===c?void 0:c.preloader);if("audio"===p.type||"voice"===p.type){const i=new pe;return i.setAttribute("message-id",""+e.mid),i.setAttribute("peer-id",""+e.peerId),i.withTime=t,i.message=e,i.noAutoDownload=l,n&&(i.voiceAsMusic=n),o&&(i.searchContext=o),a&&(i.showSender=a),m&&(i.preloader=e.media.preloader),i.dataset.fontWeight=""+s,i.render(),i}let g=p.file_name?p.file_name.split("."):"",b="";b=g.length>1&&Array.isArray(g)?g.pop().toLowerCase():"file";let f=document.createElement("div");f.classList.add("document","ext-"+b),f.dataset.docId=p.id;const v=document.createElement("div");v.classList.add("document-ico");const y=ee.a.getCacheContext(p);if((null===(h=p.thumbs)||void 0===h?void 0:h.length)||e.pFlags.is_outgoing&&y.url&&"photo"===p.type){f.classList.add("document-with-thumb");let t=[];if(e.pFlags.is_outgoing)v.innerHTML=`<img src="${y.url}">`,t.push(v.firstElementChild);else{const e=qt({photo:p,message:null,container:v,boxWidth:54,boxHeight:54,loadPromises:r,withoutPreloader:!0});v.style.width=v.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 v.innerText=b;let w=p.file_name||"Unknown.file",L=Object(u.b)(p.size);t&&(L+=" · "+zt(p.date)),a&&(L+=" · "+i.a.getSenderToPeerText(e));let S="";if(a&&(S=`<div class="sent-time">${Object(H.c)(new Date(1e3*e.date))}</div>`),f.innerHTML=`\n ${y.downloaded&&!m?"":'<div class="document-download"></div>'}\n <div class="document-name"><middle-ellipsis-element data-font-weight="${s}">${w}</middle-ellipsis-element>${S}</div>\n <div class="document-size">${L}</div>\n `,f.prepend(v),!m&&e.pFlags.is_outgoing)return f;let M,E=null;const I=()=>{if(M){M.classList.add("downloaded");const e=M;setTimeout(()=>{e.remove()},200),M=null}E&&(E=null)},C=()=>{const e=d.a.getDoc(f.dataset.docId);let t;return"pdf"===e.type?(t=d.a.downloadDoc(e,da.chat.bubbles?da.chat.bubbles.lazyLoadQueue.queueId:0),t.then(()=>{const t=ee.a.getCacheContext(e);window.open(t.url)})):t=d.a.saveDocFile(e,da.chat.bubbles?da.chat.bubbles.lazyLoadQueue.queueId:0),M&&(t.then(I),E.attach(M,!0,t)),{download:t}};return y.downloaded&&!m||(M=f.querySelector(".document-download"),E=e.media.preloader,E?(E.attach(M),e.media.promise.then(I)):(E=new ie.a,E.construct(),E.setManual(),E.attach(M),E.setDownloadFunction(C))),Object(F.b)(f,e=>{E?E.onClick(e):C()}),f}function qt({photo:e,message:t,container:s,boxWidth:i,boxHeight:n,withTail:o,isOut:l,lazyLoadQueue:c,middleware:h,size:u,withoutPreloader:p,loadPromises:m,noAutoDownload:g,noBlur:b,noThumb:f,noFadeIn:v}){var y;if(!e.sizes&&!e.thumbs)return i&&n&&!u&&"document"===e._&&z.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};u||(void 0===i&&(i=r.b.active.regular.width),void 0===n&&(n=r.b.active.regular.height)),s.classList.add("media-container");let w,L,S,M=s,E=!0,I=Promise.resolve();if(L=new Image,i&&n&&!u){const a=z.a.setAttachmentSize(e,s,i,n,void 0,t);if(u=a.photoSize,E=a.isFit,S=ee.a.getCacheContext(e,u.type),!E){M=document.createElement("div"),M.classList.add("media-container-aspecter"),M.style.width=a.size.width+"px",M.style.height=a.size.height+"px";const i=z.a.getStrippedThumbIfNeeded(e,S,!b,!0);if(i){I=i.loadPromise;const e=i.image;e.classList.add("media-photo"),s.append(e)}else{qt({container:s,message:t,photo:e,boxWidth:0,boxHeight:0,size:u,lazyLoadQueue:c,isOut:l,loadPromises:m,middleware:h,withoutPreloader:p,withTail:o,noAutoDownload:g,noBlur:b,noThumb:!0}).images.full.classList.add("media-photo","thumbnail")}s.classList.add("media-container-fitted"),s.append(M)}}else u||(u=z.a.choosePhotoSize(e,i,n,!0)),S=ee.a.getCacheContext(e,null==u?void 0:u.type);if(!f){const t=z.a.getStrippedThumbIfNeeded(e,S,!b);t&&(I=Promise.all([I,t.loadPromise]),w=t.image,w.classList.add("media-photo"),M.append(w))}L.classList.add("media-photo");const C=(w||!S.downloaded)&&a.default.settings.animationsEnabled&&!v;let k;C&&L.classList.add("fade-in"),(null===(y=null==t?void 0:t.media)||void 0===y?void 0:y.preloader)?(k=t.media.preloader,k.attach(s),g=void 0):k=new ie.a({attachMethod:"prepend"});const T=()=>h&&!h()?Promise.resolve():new Promise(e=>{Object(me.a)(L,S.url,()=>{Ot.a.mutateElement(s,()=>{M.append(L),Object(Re.c)(()=>{e()}),C&&L.addEventListener("animationend",()=>{Ot.a.mutate(()=>{L.classList.remove("fade-in"),w&&w.remove()})},{once:!0})})})});let P;const x=()=>{g&&!p&&(k.construct(),k.setManual());const t=(()=>{const t="document"===e._&&"image/gif"===e.mime_type?d.a.downloadDoc(e,null==c?void 0:c.queueId):z.a.preloadPhoto(e,u,null==c?void 0:c.queueId,g);return g=void 0,t})();!S.downloaded&&!p&&u.w>=150&&u.h>=150&&k.attach(s,!1,t);const i=t.then(T);return i.catch(()=>{}),{download:t,render:i}};return k.setDownloadFunction(x),S.downloaded?I=P=x().render:c?c.push({div:s,load:()=>x().download}):P=x().render,m&&I&&m.push(I),{loadPromises:{thumb:I,full:P||Promise.resolve()},images:{thumb:w,full:L},preloader:k,aspecter:M}}function Vt({doc:e,div:t,middleware:s,lazyLoadQueue:i,group:n,play:r,onlyThumb:l,emoji:c,width:h,height:u,withThumb:p,loop:m,loadPromises:g,needFadeIn:b}){var f;const v=e.sticker;if(h||(h=c?void 0:200),u||(u=c?void 0:200),2!==v||X.b.loaded||X.b.loadLottieWorkers(),!v)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 y=ee.a.getCacheContext(e),w=c?Object($.b)(c):-1,L=y.downloaded&&!b;let S=Object(o.a)(),M=!1;if(((null===(f=e.thumbs)||void 0===f?void 0:f.length)||e.stickerCachedThumbs)&&!t.firstElementChild&&(!L||2===v||l)){let n,a=e.stickerCachedThumbs&&e.stickerCachedThumbs[w]||e.thumbs[0];const o=()=>{t.childElementCount||(n.classList.add("media-sticker","thumbnail"),Ot.a.mutateElement(t,()=>{t.append(n),S.resolve()}))};if("url"in a)n=new Image,Object(me.a)(n,a.url,o),M=!0;else if("bytes"in a){if("photoPathSize"===a._)if(a.bytes.length){const s=z.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._&&w<=0&&(n=new Image,J.a.isWebpSupported()||e.pFlags.stickerThumbConverted||y.url?(Object(me.a)(n,z.a.getPreviewURLFromThumb(e,a,!0),o),M=!0):J.a.convert(e.id,a.bytes).then(i=>{a.bytes=i,e.pFlags.stickerThumbConverted=!0,s&&!s()||t.childElementCount||Object(me.a)(n,z.a.getPreviewURLFromThumb(e,a,!0),o)}).catch(()=>{}))}else if(2===v&&(p||l)&&w<=0){n=new Image;const r=()=>{if(t.childElementCount||s&&!s())return;const i=()=>{t.childElementCount||s&&!s()||Object(me.a)(n,y.url,o)};return y.url?(i(),Promise.resolve()):d.a.getThumbURL(e,a).promise.then(i)};if(i&&l)return i.push({div:t,load:r}),Promise.resolve();r(),a.url&&(M=!0)}}if(g&&M&&g.push(S),l)return Promise.resolve();const E=()=>Nt(this,void 0,void 0,(function*(){if(!s||s())if(2===v)yield d.a.downloadDoc(e,null==i?void 0:i.queueId).then(Y.b).then(i=>Nt(this,void 0,void 0,(function*(){if(s&&!s())return;let o=yield X.b.loadAnimationWorker({container:t,loop:m&&!c,autoplay:r,animationData:i,width:h,height:u},n,w);o.addEventListener("firstFrame",()=>{const s=t.firstElementChild;b=(b||!s||"svg"===s.tagName)&&a.default.settings.animationsEnabled;const i=()=>{s&&s!==o.canvas&&s.remove()};b?Ot.a.mutate(()=>{o.canvas.classList.add("fade-in"),s&&s.classList.add("fade-out"),o.canvas.addEventListener("animationend",()=>{Ot.a.mutate(()=>{o.canvas.classList.remove("fade-in"),i()})},{once:!0})}):s&&Ot.a.mutate(i),d.a.saveLottiePreview(e,o.canvas,w)},!0),c&&Object(F.b)(t,e=>{Object(re.a)(e);let s=X.b.getAnimation(t);s.paused&&(s.autoplay=!0,s.restart())})})));else if(1===v){const n=new Image,o=t.firstElementChild!==n&&t.firstElementChild;return b=(b||!L||o)&&a.default.settings.animationsEnabled,n.classList.add("media-sticker"),b&&n.classList.add("fade-in"),new Promise((a,r)=>{const l=()=>{if(s&&!s())return a();Object(me.a)(n,y.url,()=>{Ot.a.mutateElement(t,()=>{t.append(n),o&&o.classList.add("fade-out"),a(),b&&n.addEventListener("animationend",()=>{n.classList.remove("fade-in"),o&&o.remove()},{once:!0})})})};y.url?l():d.a.downloadDoc(e,null==i?void 0:i.queueId).then(l,a)})}})),I=!i||L&&2!==v?E():(i.push({div:t,load:E}),Promise.resolve());return L&&1===v&&(S=I,g&&g.push(S)),I}function Gt(e,t,s){const i=new fe("reply");return i.fill(e,t,s),i.container}function Kt(e){const t=new Ee(e.items,e.maxWidth,e.minWidth,e.spacing,e.maxHeight).layout(),s=t.find(e=>e.sides&Le),i=s.geometry.width+s.geometry.x,n=t.find(e=>e.sides&Se),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&Me&&s&we&&(l.style.borderTopLeftRadius="inherit"),s&Me&&s&Se&&(l.style.borderBottomLeftRadius="inherit"),s&Le&&s&we&&(l.style.borderTopRightRadius="inherit"),s&Le&&s&Se&&(l.style.borderBottomRightRadius="inherit"),e.forMedia){const e=document.createElement("div");e.classList.add("album-item-media"),l.append(e)}})}function Qt({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._?z.a.choosePhotoSize(s,480,480):{w:s.w,h:s.h};h.push({size:i,media:s,message:t})}Kt({container:t,items:h.map(e=>({w:e.size.w,h:e.size.h})),maxWidth:r.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._?qt({photo:r,message:l,container:u,boxWidth:0,boxHeight:0,isOut:o,lazyLoadQueue:a,middleware:s,size:n,loadPromises:c,noAutoDownload:d}):Ut({doc:l.media.document,container:u,message:l,boxWidth:0,boxHeight:0,withTail:!1,isOut:o,lazyLoadQueue:a,middleware:s,loadPromises:c,noAutoDownload:d})})}var $t=s(38);const Yt=()=>{let e={cleaned:!1};return{clean:()=>{e.cleaned=!0,e={cleaned:!1}},get:()=>{const t=e;return()=>!t.cleaned}}};var Xt=s(40);function Jt(e,t,s,i){return void 0===i&&(i=e.parentElement===t?Object(Xt.a)(e):-1),i!==s&&(-1!==i&&i<s&&(s+=1),t.childElementCount>s?t.insertBefore(e,t.children[s]):t.append(e),!0)}var Zt=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 es{constructor(){let e;this.list=Ta.createChatList(),this.users=new Map,this.sorted=[];const t=()=>{e=window.setTimeout(()=>{this.updateList().then(e=>{e&&t()})},es.SORT_INTERVAL)};t()}updateList(){return Zt(this,void 0,void 0,(function*(){return!!Object(Ht.a)(this.list)&&(yield Object($t.c)(),!!Object(Ht.a)(this.list)&&(this.users.forEach(e=>{this.update(e.peerId,!0)}),this.sorted.forEach((e,t)=>{Jt(e.dom.listEl,this.list,t)}),!0))}))}add(e){if(this.users.has(e))return;const{dom:t}=Ta.addDialogNew({dialog:e,container:!1,drawStatus:!1,avatarSize:48,autonomous:!0,meAsSaved:!1,rippleEnabled:!1,lazyLoadQueue:this.lazyLoadQueue}),s={peerId:e,status:m.a.getUserStatusForSort(e),dom:t};this.users.set(e,s),this.update(e)}update(e,t=!1){const s=this.users.get(e);s.status=m.a.getUserStatusForSort(e);const i=m.a.getUserStatusString(e);Object(b.a)(s.dom.lastMessageSpan,i);const n=Object(ve.d)(this.sorted,s,"status");t||Jt(s.dom.listEl,this.list,n)}}es.SORT_INTERVAL=3e4;var ts=s(105),ss=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 is{constructor(e){this.tabs={},this.prevTabId=-1,this.lazyLoadQueue=new G.d,this.middleware=Yt(),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(W.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(A.g)(this,e),this.container=document.createElement("div"),this.container.classList.add("search-super");const t=this.navScrollableContainer=document.createElement("div");t.classList.add("search-super-tabs-scrollable","menu-horizontal-scrollable","sticky");const s=new g.a(t),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(f.i18n)(e.name)),s.append(i),t.append(s),Object(Q.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");for(const e of this.mediaTabs){const t=document.createElement("div");t.classList.add("search-super-container-"+e.type);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 v(!1,"messages",!0),this.scrollable.onScrolledBottom=()=>{this.mediaTab.contentTab&&this.mediaTab.contentTab.childElementCount&&this.load(!0)},this.selectTab=Object(V.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),this.tabs.inputMessagesFilterPhotoVideo.addEventListener("click",e=>{const t=Object(Qe.a)(e.target,"grid-item"),s=+t.dataset.mid;if(!s)return void this.log.warn("no messageId by click on target:",t);const n=+t.dataset.peerId,a=Array.from(this.tabs.inputMessagesFilterPhotoVideo.querySelectorAll(".grid-item")).map(e=>({element:e,mid:+e.dataset.mid,peerId:+e.dataset.peerId})),o=a.findIndex(e=>e.mid===s&&e.peerId===n),r=i.a.getMessageByPeer(n,s);(new pa).setSearchContext(this.copySearchContext(this.mediaTab.inputFilter)).openMedia(r,t,0,!1,a.slice(0,o),a.slice(o+1))}),this.mediaTab=this.mediaTabs[0],Object($t.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)}return s}performSearchResult(e,t,s=!0){var n;return ss(this,void 0,void 0,(function*(){const a=[],o=t.contentTab,r=[],l=this.middleware.get();let c,d=t.inputFilter;switch(yield Object($t.c)(),"inputMessagesFilterPhotoVideo"===d&&this.searchContext.query.trim()?(d="inputMessagesFilterEmpty",c=this.searchGroupMedia,o.append(c.container)):"inputMessagesFilterEmpty"===d&&(c=this.searchGroups.messages),d){case"inputMessagesFilterEmpty":for(const t of e){const{dialog:e,dom:s}=Ta.addDialogNew({dialog:t.peerId,container:c.list,drawStatus:!1,avatarSize:54});Ta.setLastMessage(e,t,s,this.searchContext.query)}c.list.childElementCount&&c.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=z.a.choosePhotoSize(e,200,200);i="photo"!==e._?Ut({doc:e,message:t,container:s,boxWidth:0,boxHeight:0,lazyLoadQueue:this.lazyLoadQueue,middleware:l,onlyPreview:!0,withoutPreloader:!0,noPlayButton:!0,size:n}).thumb:qt({photo:e,message:t,container:s,boxWidth:0,boxHeight:0,lazyLoadQueue:this.lazyLoadQueue,middleware:l,withoutPreloader:!0,noBlur:!0,size:n}),[i.images.thumb,i.images.full].filter(Boolean).forEach(e=>{e.classList.add("grid-item-media")}),r.push(i.loadPromises.thumb),a.push({element:s,message:t})}break;case"inputMessagesFilterVoice":case"inputMessagesFilterMusic":case"inputMessagesFilterDocument":for(const t of e){const e=this.showSender||"voice"===t.media.document.type,s=Wt({message:t,withTime:!e,fontWeight:400,voiceAsMusic:!0,showSender:e,searchContext:this.copySearchContext(d)});["audio","voice"].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=q.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=q.b.wrapRichText(Object(N.f)(t.message,150,180)))}let s=document.createElement("div"),o=document.createElement("div");if(o.classList.add("preview"),e.photo){qt({container:o,message:null,photo:e.photo,boxWidth:0,boxHeight:0,withoutPreloader:!0,lazyLoadQueue:this.lazyLoadQueue,middleware:l,size:z.a.choosePhotoSize(e.photo,60,60,!1),loadPromises:r,noBlur:!0})}else o.classList.add("empty"),o.innerHTML=q.b.getAbbreviation(e.title||e.display_url||e.description||e.url,!0);let c=e.rTitle||"",d=e.rDescription||"",h=q.b.wrapRichText(e.url||"");c||(c=q.b.wrapPlainText(e.display_url.split("/",1)[0]));let u=this.showSender?`<div class="subtitle sender">${i.a.getSenderToPeerText(t)}</div>`:"",p="";this.showSender&&(p=`<div class="sent-time">${Object(H.c)(new Date(1e3*t.date))}</div>`),s.append(o),s.insertAdjacentHTML("beforeend",`\n <div class="title">${c}${p}</div>\n <div class="subtitle">${d}</div>\n <div class="url">${h}</div>\n ${u}\n `),s.innerText.trim().length&&a.push({element:s,message:t})}}if(this.loadMutex&&r.push(this.loadMutex),!r.length||(yield Promise.all(r),l())){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,d);s.classList.add("search-super-item"),s.dataset.mid=""+i.mid,s.dataset.peerId=""+i.peerId,n.items[e](s)})}this.afterPerforming("inputMessagesFilterEmpty"===d?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 n=(t,i,n=!1)=>{t.forEach(t=>{if(e.has(t))return;e.add(t);const o=U.a.getPeer(t),{dom:r}=Ta.addDialogNew({dialog:t,container:i.list,drawStatus:!1,avatarSize:48,autonomous:i.autonomous});if(n&&(o.participants_count||o.participants)){const e=new RegExp(`(${Object(N.e)(s)}|${Object(N.e)(Object(ts.a)(s))})`,"gi");r.titleSpan.innerHTML=r.titleSpan.innerHTML.replace(e,"<i>$1</i>"),r.lastMessageSpan.append(D.a.getChatMembersString(-t))}else if(t===a.default.myId)r.lastMessageSpan.append(Object(f.i18n)("Presence.YourChat"));else{let e=U.a.getPeerUsername(t);if(e)e="@"+e;else{const s=m.a.getUser(t);s&&s.phone&&(e="+"+Object(K.c)(s.phone).formatted)}r.lastMessageSpan.innerHTML="<i>"+e+"</i>"}}),i.toggle()},o=e=>{if(t())return e};return Promise.all([m.a.getContacts(s,!0).then(o).then(e=>{e&&n(e,this.searchGroups.contacts,!0)}),m.a.searchContacts(s,20).then(o).then(e=>{if(e&&(n(e.my_results,this.searchGroups.contacts,!0),n(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).then(o).then(e=>{e&&n(e.dialogs.map(e=>e.peerId),this.searchGroups.contacts,!0)})])}if(this.searchContext.peerId||this.searchContext.minDate)return Promise.resolve();{const e=(e=!0)=>p.default.getState().then(s=>{t()&&(this.searchGroups.recent.list.innerHTML="",s.recentSearch.slice(0,20).forEach(e=>{let{dialog:t,dom:s}=Ta.addDialogNew({dialog:e,container:this.searchGroups.recent.list,drawStatus:!1,meAsSaved:!0,avatarSize:48,autonomous:!0});s.lastMessageSpan.append(e>0?m.a.getUserStatusString(e):D.a.getChatMembersString(e))}),s.recentSearch.length?e&&this.searchGroups.recent.setActive():this.searchGroups.recent.clear())});return Promise.all([m.a.getTopPeers().then(e=>{t()&&(e.length&&e.forEach(e=>{Ta.addDialogNew({dialog:e,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=>ss(this,void 0,void 0,(function*(){this.loadMutex&&(yield this.loadMutex,!s())||(this.membersList||(this.membersList=new es,this.membersList.lazyLoadQueue=this.lazyLoadQueue,this.membersList.list.addEventListener("click",e=>{const t=Object(Ve.a)(e.target,"LI");if(!t)return;const s=+t.dataset.peerId;let i=Promise.resolve();r.b.isMobile&&(i=St.toggleSidebar(!1)),i.then(()=>{da.setInnerPeer(s)})}),e.contentTab.append(this.membersList.list),this.afterPerforming(1,e.contentTab)),t.forEach(e=>{const t=D.a.getParticipantPeerId(e);if(t<0)return;m.a.getUser(t).pFlags.deleted||this.membersList.add(t)}))}));if(D.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({peerId:this.searchContext.peerId,query:this.searchContext.query,inputFilter:{_:r},maxId:d,limit:s,nextRate:null!==(o=this.nextRates[r])&&void 0!==o?o:this.nextRates[r]=0,threadId:this.searchContext.threadId,folderId:this.searchContext.folderId,minDate:this.searchContext.minDate,maxDate:this.searchContext.maxDate}).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&&(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 ss(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*(z.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=H.g[i.getMonth()]+" "+i.getFullYear(),s=document.createElement("div");s.className="search-super-month";const o=document.createElement("div");o.classList.add("search-super-month-name"),o.innerText=e,s.append(o);const r=document.createElement("div");r.classList.add("search-super-month-items"),s.append(o,r);const l=Object(A.e)(a,"desc");let c=0;for(;c<l.length;++c){if(n>l[c])break}a[n]={container:s,items:r},Jt(s,this.tabs[t],c)}return a[n]}canViewMembers(){return this.searchContext.peerId<0&&!D.a.isBroadcast(-this.searchContext.peerId)&&D.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.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(K.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(A.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()}}const ns=e=>{if(e.element)return e.element;const{icon:t,text:s,onClick:i}=e,n=document.createElement("div");n.className="btn-menu-item tgico-"+t,Object(Q.ripple)(n);const a=Object(f.i18n)(s);return a.classList.add("btn-menu-item-text"),n.append(a),e.checkboxField&&(n.append(e.checkboxField.label),Object(F.b)(n,()=>{e.checkboxField.checked=!e.checkboxField.checked},e.options)),Object(F.b)(n,"click"!==F.a?e=>{Object(re.a)(e),i(e),Object(K.b)()}:i,e.options),e.element=n};var as=(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(ns);return s.append(...i),s};const os=(e,t,s)=>{((null==s?void 0:s.listenerSetter)?s.listenerSetter.add.bind(s.listenerSetter,e):e.addEventListener.bind(e))(F.a,s=>{if(!e.classList.contains("btn-menu-toggle"))return!1;const i=e.querySelector(".btn-menu");Object(re.a)(s),e.classList.contains("menu-open")?Object(K.b)():(t&&t(s),Object(K.d)(i))})};var rs,ls=(e={},t,s,i)=>{e.asDiv=!0;const n=k("more btn-menu-toggle",e),a=as(s,e.listenerSetter);return a.classList.add(t),os(n,i,e),n.append(a),n},cs=s(62);!function(e){e[e.Everybody=2]="Everybody",e[e.Contacts=1]="Contacts",e[e.Nobody=0]="Nobody"}(rs||(rs={}));const ds=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 He.a.invokeApi("account.setPrivacy",{key:{_:e},rules:t}).then(s=>(m.a.saveApiUsers(s.users),D.a.saveApiChats(s.chats),cs.a.processUpdateMessage({_:"updateShort",update:{_:"updatePrivacy",key:{_:Object(N.b)(e)},rules:t.map(e=>{const t={};return Object.assign(t,e),t._=Object(N.b)(t._),t})}}),s.rules))}getPrivacy(e){const t=Object(N.b)(e),s=this.privacy[t];return s?Promise.resolve(s):this.privacy[t]=He.a.invokeApi("account.getPrivacy",{key:{_:e}}).then(e=>(m.a.saveApiUsers(e.users),D.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}}};Z.a.appPrivacyManager=ds;var hs=ds;class us{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(f._i18n)(s,t):s.innerHTML="",s.classList.toggle("hide",!t),this.exceptions&&(this.exceptions.get("allow").row.container.classList.toggle("hide",this.type===rs.Everybody),this.exceptions.get("disallow").row.container.classList.toggle("hide",this.type===rs.Nobody)),this.options.onRadioChange&&this.options.onRadioChange(e)},e.captions&&e.captions.reverse(),this.radioSection=new ci({name:e.title,caption:!0}),this.radioRows=new Map;let t=[{type:rs.Everybody,langKey:"PrivacySettingsController.Everbody"},{type:rs.Contacts,langKey:"PrivacySettingsController.MyContacts"},{type:rs.Nobody,langKey:"PrivacySettingsController.Nobody"}];e.skipTypes&&(t=t.filter(t=>!e.skipTypes.includes(t.type)));const s=Object(De.b)();t.forEach(({type:e,langKey:t})=>{const i=new Ae({radioField:new je({langKey:t,name:s,value:""+e})});this.radioRows.set(e,i)});const i=Fe([...this.radioRows.values()],this.onRadioChange);if(this.radioSection.content.append(i),e.appendTo&&e.appendTo.append(this.radioSection.container),!e.noExceptions){const t=di(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 Ae(s),s.row.container.addEventListener("click",()=>{n.then(()=>{const t=this.peerIds[s.key];new pt(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=hs.getPrivacy(e.inputKey).then(t=>{const s=hs.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 rs.Everybody:t.push({_:"inputPrivacyValueAllowAll"});break;case rs.Contacts:t.push({_:"inputPrivacyValueAllowContacts"});break;case rs.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=>m.a.getUserInput(e))})}}),hs.setPrivacy(e.inputKey,t)},!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(f.join)([e.users.length?Object(f.i18n)("Users",[e.users.length]):null,e.chats.length?Object(f.i18n)("Chats",[e.chats.length]):null].filter(Boolean),!1):[Object(f.i18n)("PrivacySettingsController.AddUsers")]}}class ps extends x{init(){this.container.classList.add("privacy-tab","privacy-phone-number"),this.setTitle("PrivacyPhone");const e=new us({tab:this,title:"PrivacyPhoneTitle",inputKey:"inputPrivacyKeyPhoneNumber",captions:["PrivacyPhoneInfo","PrivacyPhoneInfo",""],exceptionTexts:["PrivacySettingsController.NeverShare","PrivacySettingsController.AlwaysShare"],appendTo:this.scrollable,onRadioChange:e=>{t.setRadio(rs.Everybody),t.radioSection.container.classList.toggle("hide",e!==rs.Nobody)}}),t=new us({tab:this,title:"PrivacyPhoneTitle2",inputKey:"inputPrivacyKeyAddedByPhone",captions:["PrivacyPhoneInfo3","PrivacyPhoneInfo3",""],noExceptions:!0,skipTypes:[rs.Nobody]});this.scrollable.container.insertBefore(t.radioSection.container,e.radioSection.container.nextSibling)}}var ms=s(59);class gs extends P{init(){this.container.classList.add("two-step-verification","two-step-verification-set"),this.setTitle("TwoStepVerificationPasswordSet");const e=new ci({caption:"TwoStepVerificationPasswordSetInfo",noDelimiter:!0}),t=Rt.getAnimatedEmojiSticker("🥳"),s=document.createElement("div");t?Vt({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(C.a)("btn-primary btn-color-primary",{text:"TwoStepVerificationPasswordReturnSettings"});Object(F.b)(a,e=>{this.close()}),this.slider.sliceTabsUntilTab(ni,this),n.append(a),i.append(n),this.scrollable.container.append(e.container)}}var bs=s(101);function fs(e){return!c.isMobileSafari||!e}class vs extends P{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 ci({caption:!0,noDelimiter:!0});Object(f._i18n)(e.caption,"TwoStepAuth.ConfirmEmailCodeDesc",[this.email]);const t=Rt.getAnimatedEmojiSticker("📬"),s=document.createElement("div");t?Vt({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 bs.a({name:"recovery-email-code",label:"TwoStepAuth.RecoveryCode",length:this.length,onFill:e=>{c(!0),ms.a.confirmPasswordEmail(""+e).then(e=>{l()}).catch(e=>{switch(e.type){case"CODE_INVALID":a.input.classList.add("error"),Object(b.a)(a.label,Object(f.i18n)("TwoStepAuth.RecoveryCodeInvalid"));break;case"EMAIL_HASH_EXPIRED":a.input.classList.add("error"),Object(b.a)(a.label,Object(f.i18n)("TwoStepAuth.RecoveryCodeExpired"));break;default:console.error("confirm error",e)}c(!1)})}}),o=Object(C.a)("btn-primary btn-primary-transparent primary",{text:"TwoStepAuth.EmailCodeChangeEmail"}),r=Object(C.a)("btn-primary btn-secondary btn-primary-transparent primary",{text:"ResendCode"}),l=()=>{new gs(this.slider).open()},c=e=>{Object(We.a)([a.input,o,r],e)};Object(F.b)(o,e=>{c(!0),ms.a.cancelPasswordEmail().then(e=>{this.slider.sliceTabsUntilTab(ys,this),this.close()},()=>{c(!1)})}),Object(F.b)(r,e=>{c(!0);const t=Object(K.f)(r);ms.a.resendPasswordEmail().then(e=>{t.remove(),c(!1)})}),n.append(a.container,o,r),i.append(n),this.scrollable.container.append(e.container)}onOpenAfterTimeout(){fs(this.isFirst)&&this.codeInputField.input.focus()}}class ys extends P{constructor(){super(...arguments),this.isFirst=!1}init(){this.container.classList.add("two-step-verification","two-step-verification-email"),this.setTitle("RecoveryEmailTitle");const e=new ci({caption:!0,noDelimiter:!0}),t=Rt.getAnimatedEmojiSticker("💌"),s=document.createElement("div");t?Vt({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 w.b({name:"recovery-email",label:"RecoveryEmail",plainText:!0});a.input.addEventListener("keypress",e=>{if("Enter"===e.key)return Object(re.a)(e),c()}),a.input.addEventListener("input",e=>{a.input.classList.remove("error")});const o=Object(C.a)("btn-primary btn-color-primary",{text:"Continue"}),r=Object(C.a)("btn-primary btn-secondary btn-primary-transparent primary",{text:"YourEmailSkip"}),l=()=>{new gs(this.slider).open()},c=()=>{const e=a.value.trim(),t=q.b.matchEmail(e);if(!t||t[0].length!==e.length)return void a.input.classList.add("error");d(!0);const s=Object(K.f)(o);ms.a.updateSettings({hint:this.hint,currentPassword:this.plainPassword,newPassword:this.newPassword,email:e}).then(e=>{l()},t=>{if(t.type.includes("EMAIL_UNCONFIRMED")){const s=+t.type.match(/^EMAIL_UNCONFIRMED_(\d+)/)[1],i=new vs(this.slider);i.state=this.state,i.email=e,i.length=s,i.open()}else console.log("password set error",t);d(!1),s.remove()})};Object(F.b)(o,c);const d=e=>{e?(o.setAttribute("disabled","true"),r.setAttribute("disabled","true")):(o.removeAttribute("disabled"),r.removeAttribute("disabled"))};Object(F.b)(r,e=>{new ze("popup-skip-email",{buttons:[{langKey:"Cancel",isCancel:!0},{langKey:"YourEmailSkip",callback:()=>{d(!0),Object(K.f)(r),ms.a.updateSettings({hint:this.hint,currentPassword:this.plainPassword,newPassword:this.newPassword,email:""}).then(()=>{l()},e=>{d(!1)})},isDanger:!0}],titleLangKey:"YourEmailSkipWarning",descriptionLangKey:"YourEmailSkipWarningText"}).show()}),n.append(a.container,o,r),i.append(n),this.scrollable.container.append(e.container)}onOpenAfterTimeout(){fs(this.isFirst)&&this.inputField.input.focus()}}var ws=s(80),Ls=s(74),Ss=s(100);class Ms extends P{init(){this.container.classList.add("two-step-verification","two-step-verification-hint"),this.setTitle("TwoStepAuth.SetupHintTitle");const e=new ci({noDelimiter:!0}),t=Rt.getAnimatedEmojiSticker("💡"),s=document.createElement("div");t?Vt({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 w.b({name:"hint",label:"TwoStepAuth.SetupHintPlaceholder"});n.input.addEventListener("keypress",e=>{if("Enter"===e.key)return Object(re.a)(e),n.value?l():c()});const a=(e,t)=>{e&&Object(re.a)(e);const s=t?n.value:void 0;if(s&&this.newPassword===s)return void Be(f.default.format("PasswordAsHintError",!0));const i=new ys(this.slider);i.state=this.state,i.plainPassword=this.plainPassword,i.newPassword=this.newPassword,i.hint=s,i.open()},o=Object(C.a)("btn-primary btn-color-primary",{text:"Continue"}),r=Object(C.a)("btn-primary btn-secondary btn-primary-transparent primary",{text:"YourEmailSkip"}),l=e=>a(e,!0),c=e=>a(e,!1);Object(F.b)(o,l),Object(F.b)(r,c),i.append(n.container,o,r),e.content.append(i),this.scrollable.container.append(e.container)}onOpenAfterTimeout(){this.inputField.input.focus()}}class Es extends P{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 ci({noDelimiter:!0}),t=document.createElement("div");t.classList.add("input-wrapper");const s=this.passwordInputField=new Ls.a({name:"re-enter-password",label:"PleaseReEnterPassword"}),i=new Ss.a(s,157),n=Object(C.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(w.a.Neutral),"Enter"===e.key)return o()});const a=()=>this.newPassword===s.value||(s.setError(),!1),o=e=>{if(e&&Object(re.a)(e),!a())return;const t=new Ms(this.slider);t.state=this.state,t.plainPassword=this.plainPassword,t.newPassword=this.newPassword,t.open()};return Object(F.b)(n,o),i.load()}onOpenAfterTimeout(){this.passwordInputField.input.focus()}}class Is extends P{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 ci({noDelimiter:!0}),s=document.createElement("div");s.classList.add("input-wrapper");const i=this.passwordInputField=new Ls.a({name:"enter-password",label:e?"PleaseEnterFirstPassword":this.state.hint?void 0:"LoginPassword",labelText:!e&&this.state.hint?q.b.wrapEmojiText(this.state.hint):void 0}),n=new ws.a(i,157),a=Object(C.a)("btn-primary btn-color-primary"),o=new f.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 l()});const r=()=>!!i.value.length||(i.input.classList.add("error"),!1);let l;if(e)l=e=>{if(e&&Object(re.a)(e),!r())return;const t=new Es(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)),ms.a.getState().then(e=>{this.state=e,this.state.hint?i.label.innerHTML=q.b.wrapEmojiText(this.state.hint):Object(b.a)(i.label,Object(f.i18n)("LoginPassword"))}));l=s=>{if(!r())return void Object(re.a)(s);a.setAttribute("disabled","true"),o.key="PleaseWait",o.update();const l=Object(K.f)(a),c=i.value;ms.a.check(i.value,this.state).then(t=>{if(console.log(t),"auth.authorization"===t._){clearInterval(e),n&&n.remove();const t=new Cs(this.slider);t.state=this.state,t.plainPassword=c,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(F.b)(a,l),n.load()}onOpenAfterTimeout(){fs(this.isFirst)&&this.passwordInputField.input.focus()}}class Cs extends P{init(){this.container.classList.add("two-step-verification","two-step-verification-main"),this.setTitle("TwoStepVerificationTitle");const e=new ci({caption:!0,noDelimiter:!0}),t=Rt.getAnimatedEmojiSticker("🔐"),s=document.createElement("div");t?Vt({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(f._i18n)(e.caption,"TwoStepAuth.GenericHelp");const t=Object(C.a)("btn-primary btn-transparent",{icon:"edit",text:"TwoStepAuth.ChangePassword"}),s=Object(C.a)("btn-primary btn-transparent",{icon:"passwordoff",text:"TwoStepAuth.RemovePassword"}),n=Object(C.a)("btn-primary btn-transparent",{icon:"email",text:this.state.pFlags.has_recovery?"TwoStepAuth.ChangeEmail":"TwoStepAuth.SetupEmail"});Object(F.b)(t,()=>{const e=new Is(this.slider);e.state=this.state,e.plainPassword=this.plainPassword,e.open()}),Object(F.b)(s,()=>{new ze("popup-disable-password",{buttons:[{langKey:"Disable",callback:()=>{ms.a.updateSettings({currentPassword:this.plainPassword}).then(()=>{this.slider.sliceTabsUntilTab(ni,this),this.close()})},isDanger:!0}],titleLangKey:"TurnPasswordOffQuestionTitle",descriptionLangKey:"TurnPasswordOffQuestion"}).show()}),Object(F.b)(n,()=>{const e=new ys(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(f._i18n)(e.caption,"TwoStepAuth.SetPasswordHelp");const t=document.createElement("div");t.classList.add("input-wrapper");const s=Object(C.a)("btn-primary btn-color-primary",{text:"TwoStepVerificationSetPassword"});t.append(s),i.append(t),Object(F.b)(s,e=>{const t=new Is(this.slider);t.state=this.state,t.open()})}this.scrollable.container.append(e.container)}}class ks extends x{init(){this.container.classList.add("privacy-tab","privacy-last-seen"),this.setTitle("PrivacyLastSeen");const e="PrivacySettingsController.LastSeenDescription";new us({tab:this,title:"LastSeenTitle",inputKey:"inputPrivacyKeyStatusTimestamp",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverShare","PrivacySettingsController.AlwaysShare"],appendTo:this.scrollable})}}class Ts extends x{init(){this.container.classList.add("privacy-tab","privacy-profile-photo"),this.setTitle("PrivacyProfilePhoto");const e="PrivacySettingsController.ProfilePhoto.CustomHelp";new us({tab:this,title:"PrivacyProfilePhotoTitle",inputKey:"inputPrivacyKeyProfilePhoto",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverShare","PrivacySettingsController.AlwaysShare"],appendTo:this.scrollable,skipTypes:[rs.Nobody]})}}class Ps extends x{init(){this.container.classList.add("privacy-tab","privacy-forward-messages"),this.setTitle("PrivacySettings.Forwards");const e="PrivacySettingsController.Forwards.CustomHelp";new us({tab:this,title:"PrivacyForwardsTitle",inputKey:"inputPrivacyKeyForwards",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable})}}class xs extends x{init(){this.container.classList.add("privacy-tab","privacy-add-to-groups"),this.setTitle("PrivacySettings.Groups");const e="PrivacySettingsController.GroupDescription";new us({tab:this,title:"WhoCanAddMe",inputKey:"inputPrivacyKeyChatInvite",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable})}}class As extends x{init(){this.container.classList.add("privacy-tab","privacy-calls"),this.setTitle("PrivacySettings.VoiceCalls");const e="PrivacySettingsController.PhoneCallDescription";new us({tab:this,title:"WhoCanCallMe",inputKey:"inputPrivacyKeyPhoneCall",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable});{const e="PrivacySettingsController.P2p.Desc";new us({tab:this,title:"PrivacyP2PHeader",inputKey:"inputPrivacyKeyPhoneP2P",captions:[e,e,e],exceptionTexts:["PrivacySettingsController.NeverAllow","PrivacySettingsController.AlwaysAllow"],appendTo:this.scrollable})}}}class Fs extends P{init(){this.container.classList.add("active-sessions-container"),this.setTitle("SessionsTitle");const e=e=>{const t=new Ae({title:[e.app_name,e.app_version].join(" "),subtitle:[e.ip,e.country].join(" - "),clickable:!0,titleRight:e.pFlags.current?void 0:Object(H.c)(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 ci({name:"CurrentSession"}),a=t.findAndSplice(e=>e.pFlags.current),o=e(a);if(n.content.append(o.container),t.length){const e=Object(C.a)("btn-primary btn-transparent danger",{icon:"stop",text:"TerminateAllSessions"});Object(F.b)(e,t=>{new ze("revoke-session",{buttons:[{langKey:"Terminate",isDanger:!0,callback:()=>{const t=Object(We.a)([e],!0);He.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 ci({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&&Be(f.default.format("RecentSessions.Error.FreshReset",!0))};let n;const a=()=>{const e=n.dataset.hash;new ze("revoke-session",{buttons:[{langKey:"Terminate",isDanger:!0,callback:()=>{He.a.invokeApi("account.resetAuthorization",{hash:e}).then(e=>{e&&(n.remove(),this.privacyTab.updateActiveSessions())},i)}}],titleLangKey:"AreYouSureSessionTitle",descriptionLangKey:"TerminateSessionText"}).show()},o=this.menuElement=as([{icon:"stop",text:"Terminate",onClick:a}]);o.id="active-sessions-contextmenu",o.classList.add("contextmenu"),document.getElementById("page-chats").append(o),Object(K.a)(this.scrollable.container,e=>{n=Object(Qe.a)(e.target,"row"),n&&"0"!==n.dataset.hash&&(e instanceof MouseEvent&&e.preventDefault(),e instanceof MouseEvent&&(e.cancelBubble=!0),Object(K.e)(e,o),Object(K.d)(o))}),Object(F.b)(this.scrollable.container,e=>{n=Object(Qe.a)(e.target,"row"),n&&"0"!==n.dataset.hash&&a()})}onCloseAfterTimeout(){return this.menuElement&&this.menuElement.remove(),super.onCloseAfterTimeout()}}class Os extends P{init(){this.container.classList.add("blocked-users-container"),this.setTitle("BlockedUsers");{const e=new ci({caption:"BlockedUsersInfo"});this.scrollable.append(e.container)}const e=B({icon:"add",className:"is-visible"});this.content.append(e),Object(F.b)(e,e=>{new tt({peerTypes:["contacts"],placeholder:"BlockModal.Search.Placeholder",onSelect:e=>{m.a.toggleBlock(e,!0)}})},{listenerSetter:this.listenerSetter});const t=Ta.createChatList();this.scrollable.container.classList.add("chatlist-container"),this.scrollable.append(t);const s=(e,s)=>{const{dom:i}=Ta.addDialogNew({dialog:e,container:t,drawStatus:!1,rippleEnabled:!0,avatarSize:48,append:s}),n=m.a.getUser(e);n.pFlags.bot?i.lastMessageSpan.append("@"+n.username):n.phone?i.lastMessageSpan.innerHTML=m.a.formatUserPhone(n.phone):i.lastMessageSpan.append(n.username?"@"+n.username:m.a.getUserStatusString(e))};for(const e of this.peerIds)s(e,!0);let i;const n=this.menuElement=as([{icon:"lockoff",text:"Unblock",onClick:()=>{const e=+i.dataset.peerId;m.a.toggleBlock(e,!1)},options:{listenerSetter:this.listenerSetter}}]);n.id="blocked-users-contextmenu",n.classList.add("contextmenu"),document.getElementById("page-chats").append(n),Object(K.a)(this.scrollable.container,e=>{i=Object(Ve.a)(e.target,"LI"),i&&(e instanceof MouseEvent&&e.preventDefault(),e instanceof MouseEvent&&(e.cancelBubble=!0),Object(K.e)(e,n),Object(K.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,m.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()}}class Ds extends P{init(){this.container.classList.add("privacy-container"),this.setTitle("PrivacySettings");{const e=new ci({noDelimiter:!0});let t;const s=new Ae({icon:"deleteuser",titleLangKey:"BlockedUsers",subtitleLangKey:"Loading",clickable:()=>{const e=new Os(this.slider);e.peerIds=t,e.open()}});let i;s.freezed=!0;const n=new Ae({icon:"lock",titleLangKey:"TwoStepVerification",subtitleLangKey:"Loading",clickable:e=>{let t;i.pFlags.has_password?t=new Is(this.slider):i.email_unconfirmed_pattern?(t=new vs(this.slider),t.email=i.email_unconfirmed_pattern,t.length=6,t.isFirst=!0,ms.a.resendPasswordEmail()):t=new Cs(this.slider),t.state=i,t.open()}});n.freezed=!0;const o=this.activeSessionsRow=new Ae({icon:"activesessions",titleLangKey:"SessionsTitle",subtitleLangKey:"Loading",clickable:()=>{const e=new Fs(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(b.a)(s.subtitle,Object(f.i18n)("PrivacySettingsController.UserCount",[e])):Object(b.a)(s.subtitle,Object(f.i18n)("BlockedEmpty",[e]))};this.listenerSetter.add(a.default,"peer_block",()=>{l()});const l=()=>{m.a.getBlocked().then(e=>{s.freezed=!1,r(e.count),t=e.peerIds})};l(),ms.a.getState().then(e=>{i=e,Object(b.a)(n.subtitle,Object(f.i18n)(e.pFlags.has_password?"PrivacyAndSecurity.Item.On":"PrivacyAndSecurity.Item.Off")),n.freezed=!1}),this.updateActiveSessions()}{const e=new ci({name:"PrivacyTitle"});e.content.classList.add("privacy-navigation-container");const t={},s=t.inputPrivacyKeyPhoneNumber=new Ae({titleLangKey:"PrivacyPhoneTitle",subtitleLangKey:"Loading",clickable:()=>{new ps(this.slider).open()}}),i=t.inputPrivacyKeyStatusTimestamp=new Ae({titleLangKey:"LastSeenTitle",subtitleLangKey:"Loading",clickable:()=>{new ks(this.slider).open()}}),n=t.inputPrivacyKeyProfilePhoto=new Ae({titleLangKey:"PrivacyProfilePhotoTitle",subtitleLangKey:"Loading",clickable:()=>{new Ts(this.slider).open()}}),o=t.inputPrivacyKeyPhoneCall=new Ae({titleLangKey:"WhoCanCallMe",subtitleLangKey:"Loading",clickable:()=>{new As(this.slider).open()}}),r=t.inputPrivacyKeyForwards=new Ae({titleLangKey:"PrivacyForwardsTitle",subtitleLangKey:"Loading",clickable:()=>{new Ps(this.slider).open()}}),l=t.inputPrivacyKeyChatInvite=new Ae({titleLangKey:"WhoCanAddMe",subtitleLangKey:"Loading",clickable:()=>{new xs(this.slider).open()}}),c=e=>{const s=t[e];s&&hs.getPrivacy(e).then(e=>{const t=hs.getPrivacyRulesDetails(e),i=t.type===rs.Everybody?"PrivacySettingsController.Everbody":t.type===rs.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(f.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(N.c)(e.key._))})}}updateActiveSessions(){He.a.invokeApi("account.getAuthorizations").then(e=>{this.activeSessionsRow.freezed=!1,this.authorizations=e.authorizations,Object(f._i18n)(this.activeSessionsRow.subtitle,"Privacy.Devices",[this.authorizations.length])})}}var js=s(110);function _s(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 Bs(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 Rs(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 Hs(e){return"#"+e.map(e=>("0"+e.toString(16)).slice(-2)).join("")}function Ns(e){return Hs(function(e){const t=e.slice(5,-1).split(", "),s=+t.pop(),i=t.map(e=>e.endsWith("%")?+e.slice(0,-1):+e);return Bs(i[0],i[1],i[2],s)}(e))}function Us(e){let{h:t,s:s,l:i}=_s(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)`}class zs{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(zs.BASE_CLASS);const e=`\n <svg class="${zs.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="${zs.BASE_CLASS+"-dragger"} ${zs.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="${zs.BASE_CLASS+"-sliders"}">\n <svg class="${zs.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="${zs.BASE_CLASS+"-dragger"} ${zs.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 w.b({plainText:!0,label:"Appearance.Color.Hex"}),this.rgbInputField=new w.b({plainText:!0,label:"Appearance.Color.RGB"});const t=document.createElement("div");t.className=zs.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?w.a.Neutral:w.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?w.a.Neutral:w.a.Error),e&&this.setColor(_s(+e[1],+e[2],+e[3]),!0,!1)}),this.attachBoxListeners(),this.attachHueListeners()}attachBoxListeners(){ne(this.elements.box,()=>{this.onGrabStart(),this.boxRect=this.elements.box.getBoundingClientRect()},e=>{this.saturationHandler(e.x,e.y)},()=>{this.onGrabEnd()})}attachHueListeners(){ne(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=Rs(e);return _s(t[0],t[1],t[2],t[3])}(e);else{const t=e.match(/[.?\d]+/g);e=_s(+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=Bs(this.hue,this.saturation,this.lightness,this.alpha),t=Hs(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(w.a.Neutral)),t&&(this.rgbInputField.setValueSilently(s.rgbaArray.slice(0,-1).join(", ")),this.rgbInputField.setState(w.a.Neutral)),this.onChange&&this.onChange(s)}hueHandler(e,t=!0){const s=Object(u.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(u.a)(e-this.boxRect.left,0,i)/i*100,o=Object(u.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(u.a)(a,0,100),c=100-l/2,d=100-Object(u.a)(o,0,100),h=Object(u.a)(d/100*c,0,100);this.saturation=l,this.lightness=h,s&&this.updatePicker()}}zs.BASE_CLASS="color-picker";class Ws extends P{constructor(){super(...arguments),this._applyColor=(e,t=!0)=>{if(t)this.colorPicker.setColor(e);else{const t=Rs(e),s=this.theme.background,i=Us(t);s.color=e.toLowerCase(),s.type="color",s.highlightningColor=i,p.default.pushToState("settings",a.default.settings),da.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 ci({});this.colorPicker=new zs,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(F.b)(t,e=>{const t=Object(Qe.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(Re.e)(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 qs=0;class Vs extends P{constructor(){super(...arguments),this.tempId=0,this.clicked=new Set,this.onUploadClick=()=>{Object(oe.e)("image/x-png,image/png,image/jpeg").then(e=>{const t="wallpaper-upload-"+ ++qs,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=d.a.saveDoc(i);const n=ee.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 r=ee.a.upload(e,e.name),l=Object(o.a)();l.addNotifyListener=r.addNotifyListener,l.cancel=r.cancel,r.then(t=>{He.a.invokeApi("account.uploadWallPaper",{file:t,mime_type:e.type,settings:{_:"wallPaperSettings"}}).then(e=>{const t=e.document,s=ee.a.getCacheContext(t);Object.assign(s,n),a=e,a.document=d.a.saveDoc(a.document),h.dataset.docId=a.document.id,h.dataset.slug=a.slug,this.setBackgroundDocument(a.slug,a.document).then(l.resolve,l.reject)},l.reject)},l.reject),l.then(()=>{this.clicked.delete(a.document.id)},e=>{h.remove()});const c=new ie.a({isUpload:!0,cancelable:!0,tryAgainOnFail:!1}),h=this.addWallPaper(a,!1);this.clicked.add(a.document.id),c.attach(h,!1,l)})},this.onResetClick=()=>{const e=p.STATE_INIT.settings.themes.find(e=>e.name===this.theme.name);e&&(++this.tempId,this.theme.background=Object(A.a)(e.background),p.default.pushToState("settings",a.default.settings),da.applyCurrentTheme(void 0,void 0,!0),this.blurCheckboxField.setValueSilently(this.theme.background.blur))},this.onGridClick=e=>{const t=Object(Qe.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 ie.a({cancelable:!0,tryAgainOnFail:!1}),a=d.a.getDoc(s),o=()=>{const e=this.setBackgroundDocument(i,a);ee.a.getCacheContext(a).url&&!this.theme.background.blur||n.attach(t,!0,e)};n.construct(),Object(F.b)(t,e=>{n.preloader.parentElement?(n.onClick(e),n.detach()):o()},{listenerSetter:this.listenerSetter}),o()},this.saveToCache=(e,t)=>{fetch(t).then(t=>{ee.a.cacheStorage.save("backgrounds/"+e,t)})},this.setBackgroundDocument=(e,t)=>{let s=++this.tempId;const i=()=>s===this.tempId,n=d.a.downloadDoc(t,da.chat.bubbles?da.chat.bubbles.lazyLoadQueue.queueId:0),r=Object(o.a)();return r.addNotifyListener=n.addNotifyListener,r.cancel=n.cancel,n.then(()=>{if(!i())return void r.resolve();const s=this.theme.background,n=t=>{(e=>{const t=document.createElement("img");return new Promise(s=>{Object(me.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 r.resolve();const o=Us(Array.from(n));s.slug=e,s.type="image",s.highlightningColor=o,p.default.pushToState("settings",a.default.settings),this.saveToCache(e,t),da.applyCurrentTheme(e,t).then(r.resolve)})},o=ee.a.getCacheContext(t);s.blur?setTimeout(()=>{Object(js.a)(o.url,12,4).then(e=>{i()?n(e):r.resolve()})},200):n(o.url)}),r},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=di(this.scrollable),s=Object(C.a)("btn-primary btn-transparent",{icon:"cameraadd",text:"ChatBackground.UploadWallpaper"}),i=Object(C.a)("btn-primary btn-transparent",{icon:"colorize",text:"SetColor"}),n=Object(C.a)("btn-primary btn-transparent",{icon:"favourites",text:"Appearance.Reset"});Object(F.b)(s,this.onUploadClick,{listenerSetter:this.listenerSetter}),Object(F.b)(i,()=>{new Ws(this.slider).open()},{listenerSetter:this.listenerSetter}),Object(F.b)(n,this.onResetClick,{listenerSetter:this.listenerSetter});const o=this.blurCheckboxField=new Te.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,p.default.pushToState("settings",a.default.settings);const t=e.querySelector(".active");t&&setTimeout(()=>{this.setBackgroundDocument(t.dataset.slug,d.a.getDoc(t.dataset.docId))},100)}),t.append(s,i,n,o.label)}a.default.addEventListener("background_change",this.setActive),He.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(F.b)(e,this.onGridClick,{listenerSetter:this.listenerSetter}),this.scrollable.append(e)}addWallPaper(e,t=!0){if(e.pFlags.pattern||0===e.document.mime_type.indexOf("application/"))return;e.document=d.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=qt({photo:e.document,message:null,container:i,withoutPreloader:!0,size:z.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(()=>{Ot.a.mutate(()=>{s.append(i)})}),this.grid[t?"append":"prepend"](s),s}}class Gs{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(f._i18n)(r,e);const l=document.createElement("div");l.classList.add(a+"-value"),l.innerHTML=""+s,o.append(r,l),this.range=new ae(t,s,i,n),this.range.setListeners(),this.range.setHandlers({onScrub:e=>{this.onChange&&this.onChange(e),l.innerText=""+e}}),this.container.append(o,this.range.container)}}class Ks extends P{init(){this.container.classList.add("general-settings-container"),this.setTitle("General");const e=di.bind(null,this.scrollable);{const t=e("Settings"),s=new Gs("TextSize",1,a.default.settings.messagesTextSize,12,20);s.onChange=e=>{p.default.setByKey("settings.messagesTextSize",e)};const i=Object(C.a)("btn-primary btn-transparent",{icon:"image",text:"ChatBackground"});Object(F.b)(i,()=>{new Vs(this.slider).open()});const n=new Te.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 Ae({radioField:new je({langKey:"General.SendShortcut.Enter",name:"send-shortcut",value:"enter",stateKey:"settings.sendShortcut"}),subtitleLangKey:"General.SendShortcut.NewLine.ShiftEnter"}),n=new Ae({radioField:new je({name:"send-shortcut",value:"ctrlEnter",stateKey:"settings.sendShortcut"}),subtitleLangKey:"General.SendShortcut.NewLine.Enter"});Object(f._i18n)(n.radioField.main,"General.SendShortcut.CtrlEnter",[c.isApple?"⌘":"Ctrl"]),s.append(i.container,n.container),t.append(s)}{const t=e("AutoDownloadMedia"),s=new Te.a({text:"AutodownloadContacts",name:"contacts",stateKey:"settings.autoDownload.contacts",withRipple:!0}),i=new Te.a({text:"AutodownloadPrivateChats",name:"private",stateKey:"settings.autoDownload.private",withRipple:!0}),n=new Te.a({text:"AutodownloadGroupChats",name:"groups",stateKey:"settings.autoDownload.groups",withRipple:!0}),a=new Te.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 Te.a({text:"AutoplayGIF",name:"gifs",stateKey:"settings.autoPlay.gifs",withRipple:!0}),i=new Te.a({text:"AutoplayVideo",name:"videos",stateKey:"settings.autoPlay.videos",withRipple:!0});t.append(s.label,i.label)}{const t=e("Emoji"),s=new Te.a({text:"GeneralSettings.EmojiPrediction",name:"suggest-emoji",stateKey:"settings.emoji.suggest",withRipple:!0}),i=new Te.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 Te.a({text:"Stickers.SuggestStickers",name:"suggest",stateKey:"settings.stickers.suggest",withRipple:!0}),i=new Te.a({text:"InstalledStickers.LoopAnimated",name:"loop",stateKey:"settings.stickers.loop",withRipple:!0});t.append(s.label,i.label)}}onOpen(){this.init&&(this.init(),this.init=null)}}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 $s extends P{init(){return Qs(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 w.b({label:"EditProfile.FirstNameLabel",name:"first-name",maxLength:70}),this.lastNameInputField=new w.b({label:"Login.Register.LastName.Placeholder",name:"last-name",maxLength:64}),this.bioInputField=new w.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(f.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:m.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(f.i18n_)({element:t,key:"EditAccount.Username"});const s=document.createElement("div");s.classList.add("input-wrapper"),this.usernameInputField=new Ne({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(f.i18n)("EditProfile.Username.Help")),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(f.i18n)("UsernameHelpLink",[a])),i.append(n),e.push(this.usernameInputField),this.scrollable.append(t,s,i)}Object(F.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(m.a.updateUsername(this.usernameInputField.value)),Promise.race(e).finally(()=>{this.editPeer.nextBtn.removeAttribute("disabled")})},{listenerSetter:this.listenerSetter});const t=m.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 Ys=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 Xs extends P{constructor(){super(...arguments),this.renderResults=e=>Ys(this,void 0,void 0,(function*(){yield m.a.getContacts(),e.forEach(e=>{const{dom:t}=Ta.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=q.b.wrapEmojiText(s.title),i.push(e)}});Object(f.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=k("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 Te.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 ci({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(C.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 ci({name:"FilterChats"});t.append(s.container,a.container);const o=("included"===this.type?e.include_peers:e.exclude_peers).slice();this.selector=new Ze({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 Be(f.default.format("excluded"===this.type?"ChatList.Filter.Exclude.LimitReached":"ChatList.Filter.Include.LimitReached",!0))}const n=l(e,i[e]?Object(f.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(A.a)(this.originalFilter),this.type=t,this.editFolderTab=s,super.open()}}class Js extends P{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(f.i18n)("FilterIncludeExcludeInfo")),this.stickerContainer=document.createElement("div"),this.stickerContainer.classList.add("sticker-container"),this.confirmBtn=k("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=ls({},"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 w.b({label:"FilterNameInputLabel",maxLength:12}),t.append(this.nameInputField.container);const s=(e,t,s,i)=>{const n=new ci({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(C.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 Xs(this.slider).open(this.filter,"included",this)}),a.querySelector(".btn").addEventListener("click",()=>{new Xs(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?Be("Sorry, you can't create more folders."):console.error("updateDialogFilter error:",e)}).finally(()=>{this.confirmBtn.removeAttribute("disabled")})):Be("Please choose at least one chat for this folder.")}),this.nameInputField.input.addEventListener("input",()=>{this.filter.title=this.nameInputField.value,this.editCheckForChange()}),this.loadAnimationPromise=X.b.loadAnimationFromURL({container:this.stickerContainer,loop:!1,autoplay:!1,width:86,height:86},"assets/img/Folders_2.tgs").then(e=>(this.animation=e,X.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=q.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=Ta.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}=Ta.addDialogNew({dialog:e,container:i,drawStatus:!1,rippleEnabled:!1,meAsSaved:!0,avatarSize:32});t.lastMessageSpan.parentElement.remove()}n.length?o.lastElementChild.replaceWith(Object(f.i18n)("FilterShowMoreChats",[n.length])):o&&o.remove()};let o;if(s.generateContentElement().append(i),n.length){const e=s.generateContentElement();o=Object(C.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(f.i18n)("FilterShowMoreChats",[n.length])),e.append(o)}a(4)})}editCheckForChange(){if("edit"===this.type){const e=!Object(A.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(A.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 Zs=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 ei extends P{constructor(){super(...arguments),this.filtersRendered={}}renderFolder(e,t,s){let n,a,o="",r=[];if("dialogFilterSuggested"===e._)n=e.filter,o=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&&r.push(Object(f.i18n)(t))}if(!r.length){const e=i.a.dialogsStorage.getFolder(n.id);let t=0,s=0,a=0;for(const i of e)U.a.isAnyGroup(i.peerId)?a++:U.a.isBroadcast(i.peerId)?s++:t++;t&&r.push(Object(f.i18n)("Chats",[t])),s&&r.push(Object(f.i18n)("Channels",[s])),a&&r.push(Object(f.i18n)("Groups",[a]))}}if(s)s.subtitle.textContent="",Object(f.join)(r).forEach(e=>{s.subtitle.append(e)});else if(s=new Ae({title:q.a.wrapEmojiText(n.title),subtitle:o,clickable:!0}),r.length&&Object(f.join)(r).forEach(e=>{s.subtitle.append(e)}),"dialogFilter"===e._){const e=n.id;this.filtersRendered.hasOwnProperty(n.id)||Object(F.b)(s.container,()=>{new Js(this.slider).open(i.a.filtersStorage.filters[e])},{listenerSetter:this.listenerSetter}),this.filtersRendered[n.id]=s}return a=s.container,n.hasOwnProperty("orderIndex")?Jt(a,a.parentElement||t,n.orderIndex):t&&t.append(a),a}init(){return Zs(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(f.i18n_)({element:e,key:"ChatList.Filter.Header"}),this.createFolderBtn=Object(C.a)("btn-primary btn-color-primary btn-control tgico",{text:"ChatList.Filter.NewTitle",icon:"add"}),this.foldersSection=new ci({name:"Filters"}),this.foldersSection.container.style.display="none",this.suggestedSection=new ci({name:"FilterRecommended"}),this.suggestedSection.container.style.display="none",this.scrollable.append(this.stickerContainer,e,this.createFolderBtn,this.foldersSection.container,this.suggestedSection.container),Object(F.b)(this.createFolderBtn,()=>{Object.keys(this.filtersRendered).length>=10?Be("Sorry, you can't create more folders."):new Js(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;Jt(s,s.parentElement,t+1)})}),this.getSuggestedFilters(),this.loadAnimationPromise=X.b.loadAnimationFromURL({container:this.stickerContainer,loop:!1,autoplay:!1,width:86,height:86},"assets/img/Folders_1.tgs").then(e=>(this.animation=e,X.b.waitForFirstFrame(e)))}))}onOpenAfterTimeout(){this.loadAnimationPromise.then(()=>{this.animation.autoplay=!0,this.animation.play()})}getSuggestedFilters(){He.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(C.a)("btn-primary btn-color-primary",{text:"Add"});t.append(s),this.suggestedSection.content.append(t),Object(F.b)(s,n=>{Object(re.a)(n),Object.keys(this.filtersRendered).length>=10?Be("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 ti extends x{init(){this.container.classList.add("notifications-container"),this.setTitle("Telegram.NotificationSettingsViewController");const e=e=>{const t=new ci({name:e.name}),s=new Ae({checkboxField:new Te.a({text:e.typeText,checked:!0}),subtitleLangKey:"Loading"}),i=new Ae({checkboxField:new Te.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=Pe.a.getNotifySettings(n);(o instanceof Promise?o:Promise.resolve(o)).then(t=>{const o=()=>{const e=Pe.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===Pe.a.isMuted(t)&&a===t.show_previews)return;const o=Object(A.a)(t);o._="inputPeerNotifySettings",o.mute_until=e?2147483647:0,o.show_previews=a,Pe.a.updateNotifySettings(n,o)},!0),this.listenerSetter.add(a.default,"notify_settings",s=>{const i=Object(N.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 ci({name:"NotificationsOther"}),t=new Ae({checkboxField:new Te.a({text:"ContactJoined",checked:!0}),subtitleLangKey:"Loading"}),s=new Ae({checkboxField:new Te.a({text:"Notifications.Sound",checked:!0,stateKey:"settings.notifications.sound"}),subtitleLangKey:"Loading"});p.default.getState().then(e=>{s.checkboxField.checked=e.settings.notifications.sound}),e.content.append(t.container,s.container),this.scrollable.append(e.container),Pe.a.getContactSignUpNotification().then(e=>{t.checkboxField.checked=e,this.eventListener.addEventListener("destroy",()=>{const s=t.checkboxField.checked;e!==s&&Pe.a.setContactSignUpNotification(!s)},!0)})}}}var si=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 ii extends P{init(){return si(this,void 0,void 0,(function*(){this.container.classList.add("language-container"),this.setTitle("Telegram.LanguageViewController");const e=new ci({}),t=new Map,s=He.a.invokeApiCacheable("langpack.getLanguages",{lang_pack:"macos"}).then(s=>{const i=Object(De.b)();s.forEach(e=>{const s=new Ae({radioField:new je({text:e.name,name:i,value:e.lang_code}),subtitle:e.native_name});t.set(e.lang_code,s)});const n=Fe([...t.values()],e=>{f.default.getLangPack(e)});f.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 ni extends P{constructor(){super(...arguments),this.buttons={}}init(){this.container.classList.add("settings-container"),this.setTitle("Settings");const e=ls({},"bottom-left",[{icon:"logout",text:"EditAccount.Logout",onClick:()=>{He.a.logOut()}}]);this.header.append(e),this.avatarElem=new wa,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(C.a)(s,{icon:"edit",text:"EditAccount.Title"})),t.append(this.buttons.folders=Object(C.a)(s,{icon:"folder",text:"AccountSettings.Filters"})),t.append(this.buttons.general=Object(C.a)(s,{icon:"settings",text:"Telegram.GeneralSettingsViewController"})),t.append(this.buttons.notifications=Object(C.a)(s,{icon:"unmute",text:"AccountSettings.Notifications"})),t.append(this.buttons.privacy=Object(C.a)(s,{icon:"lock",text:"AccountSettings.PrivacyAndSecurity"})),t.append(this.buttons.language=Object(C.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 $s(this.slider).open()}),this.buttons.folders.addEventListener("click",()=>{new ei(this.slider).open()}),this.buttons.general.addEventListener("click",()=>{new Ks(this.slider).open()}),this.buttons.notifications.addEventListener("click",()=>{new ti(this.slider).open()}),this.buttons.privacy.addEventListener("click",()=>{new Ds(this.slider).open()}),this.buttons.language.addEventListener("click",()=>{new ii(this.slider).open()}),X.b.loadLottieWorkers(),this.fillElements()}fillElements(){let e=m.a.getSelf();this.avatarElem.setAttribute("peer",""+e.id),this.nameDiv.append(new $e.a({peerId:e.id}).element),this.phoneDiv.innerHTML=e.phone?m.a.formatUserPhone(e.phone):""}}class ai extends P{constructor(){super(...arguments),this.uploadAvatar=null}init(){this.container.classList.add("new-channel-container"),this.setTitle("NewChannel"),this.avatarEdit=new _(e=>{this.uploadAvatar=e});const e=document.createElement("div");e.classList.add("input-wrapper"),this.channelNameInputField=new w.b({label:"Channel.ChannelNameHolder",maxLength:128}),this.channelDescriptionInputField=new w.b({label:"Channel.DescriptionPlaceholder",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(f._i18n)(s,"Channel.DescriptionHolderDescrpiton"),this.nextBtn=B({icon:"arrow_next"}),this.nextBtn.addEventListener("click",()=>{const e=this.channelNameInputField.value,t=this.channelDescriptionInputField.value;this.nextBtn.disabled=!0,D.a.createChannel(e,t).then(e=>{this.uploadAvatar&&this.uploadAvatar().then(t=>{D.a.editPhoto(e,t)}),ui.removeTabFromHistory(this),new pt(this.slider).open({peerId:e,type:"channel",skippable:!0,title:"GroupAddMembers",placeholder:"SendMessageTo",takeOut:t=>D.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()}}class oi extends P{constructor(){super(...arguments),this.alive=!0}init(){this.container.id="contacts-container",this.list=Ta.createChatList(),this.list.id="contacts",this.list.classList.add("contacts-container"),Ta.setListClickListener(this.list,()=>{this.container.querySelector(".sidebar-close-button").click()},void 0,!0),this.inputSearch=new L("Search",e=>{this.list.innerHTML="",this.openContacts(e)}),this.title.replaceWith(this.inputSearch.container),this.scrollable.append(this.list)}onClose(){this.alive=!1}onOpenAfterTimeout(){!c.isMobile&&fs(!0)&&this.inputSearch.input.focus()}openContacts(e){if(this.init&&(this.init(),this.init=null),this.promise)return this.promise;this.scrollable.onScrolledBottom=null,this.promise=m.a.getContacts(e).then(t=>{if(this.promise=null,!this.alive)return;const s=[...t];e||s.findAndSplice(e=>e===a.default.myId);let i=s.map(e=>{let t=m.a.getUser(e);return{user:t,status:m.a.getUserStatusForSort(t.status)}}).sort((e,t)=>t.status-e.status),n=()=>{let e=z.a.windowH/72*1.25|0;i.splice(0,e).forEach(({user:e})=>{let{dialog:t,dom:s}=Ta.addDialogNew({dialog:e.id,container:this.list,drawStatus:!1,avatarSize:48,autonomous:!0}),i=m.a.getUserStatusString(e.id);s.lastMessageSpan.append(i)}),i.length||(n=void 0)};n(),this.scrollable.onScrolledBottom=()=>{n?n():this.scrollable.onScrolledBottom=null}})}open(){return this.openContacts(),super.open()}}class ri extends P{init(){if(this.container.id="chats-archived-container",this.setTitle("ArchivedChats"),!Ta.chatLists[ri.filterId]){const e=Ta.createChatList();Ta.generateScrollable(e,ri.filterId),Ta.setListClickListener(e,null,!0)}const e=Ta.scrollables[ri.filterId];this.scrollable.container.replaceWith(e.container),this.scrollable=e}onOpen(){this.init&&(this.init(),this.init=null),this.wasFilterId=Ta.filterId,Ta.filterId=ri.filterId,Ta.onTabChange()}onOpenAfterTimeout(){Ta.chatLists[this.wasFilterId].innerHTML=""}onClose(){Ta.filterId=this.wasFilterId,Ta.onTabChange()}onCloseAfterTimeout(){return Ta.chatLists[ri.filterId].innerHTML="",super.onCloseAfterTimeout()}}ri.filterId=1;var li=s(3);class ci{constructor(e){if(this.container=document.createElement("div"),this.container.classList.add("sidebar-left-section"),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(f.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(f.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 di=(e,t,s)=>{const i=new ci({name:t,caption:s});return e.append(i.container),i.content},hi=new class extends O{constructor(){super({sidebarEl:document.getElementById("column-left"),navigationType:"left"}),this.searchGroups={},this.inputSearch=new L("Search");const e=this.sidebarEl.querySelector(".item-main .sidebar-header");e.append(this.inputSearch.container);const t=()=>{new oi(this).open()};this.backBtn=this.sidebarEl.querySelector(".sidebar-back-button");const s={icon:"archive",text:"ArchivedChats",onClick:()=>{new ri(this).open()},verify:()=>!!i.a.dialogsStorage.getFolder(1).length},n=new Te.a({toggle:!0,checked:"night"===a.default.getTheme().name});n.input.addEventListener("change",()=>{a.default.settings.theme=n.input.checked?"night":"day",p.default.pushToState("settings",a.default.settings),da.applyCurrentTheme()}),a.default.addEventListener("theme_change",()=>{n.setValueSilently("night"===a.default.getTheme().name)});const o=[{icon:"saved",text:"SavedMessages",onClick:()=>{setTimeout(()=>{da.setPeer(da.myId)},0)}},s,{icon:"user",text:"Contacts",onClick:t},{icon:"settings",text:"Settings",onClick:()=>{new ni(this).open()}},{icon:"darkmode",text:"DarkMode",onClick:()=>{},checkboxField:n},{icon:"animations",text:"Animations",onClick:()=>{},checkboxField:new Te.a({toggle:!0,checked:!0,stateKey:"settings.animationsEnabled"})},{icon:"help",text:"TelegramFeatures",onClick:()=>{da.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:()=>{location.href="https://web.telegram.org/z/"},verify:()=>li.a.isMainDomain},{icon:"char w",text:"ChatList.Menu.SwitchTo.Webogram",onClick:()=>{location.href="https://web.telegram.org/"},verify:()=>li.a.isMainDomain}];this.toolsBtn=ls({},"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"),l=document.createElement("div");l.classList.add("btn-menu-footer");const c=document.createElement("span");c.classList.add("btn-menu-footer-text"),c.innerHTML="Telegram Web"+li.a.suffix+" alpha "+li.a.version,l.append(c),r.classList.add("has-footer"),r.append(l),this.newBtnMenu=ls({},"top-left",[{icon:"newchannel",text:"NewChannel",onClick:()=>{new ai(this).open()}},{icon:"newgroup",text:"NewGroup",onClick:()=>{new pt(this).open({peerId:0,type:"chat",skippable:!1,takeOut:e=>{new R(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(u.c)(e.count,1),this.archivedCount.classList.toggle("hide",!e.count)}),m.a.getTopPeers(),p.default.getState().then(e=>{const t=e.recentSearch||[];for(let e=0,s=t.length;e<s;++e)p.default.requestPeer(t[e],"recentSearch")})}initSearch(){const e=this.sidebarEl.querySelector("#search-container"),t=new g.b(e),s=()=>{this.backBtn.click()};this.searchGroups={contacts:new v("Search.Chats","contacts",void 0,void 0,void 0,void 0,s),globalContacts:new v("Search.Global","contacts",void 0,void 0,void 0,void 0,s),messages:new v("Search.Messages","messages"),people:new v(!1,"contacts",!0,"search-group-people",!0,!1,s),recent:new v("Recent","contacts",!0,"search-group-recent",!0,!0,s)};const n=this.searchSuper=new is({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:"inputMessagesFilterVoice",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 d=()=>{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")},h=document.createElement("div");h.classList.add("search-helper"),h.addEventListener("click",e=>{const t=Object(Qe.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",()=>{f(t)}),this.inputSearch.container.append(t),this.inputSearch.onChange(this.inputSearch.value=""),a.push(t),d()}),n.nav.parentElement.append(h);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 $e.a({peerId:e,onlyFirstName:!0}).element),i.setAttribute("peer",""+e)):i.classList.add("tgico-calendarfilter"),t&&("string"==typeof t?s.innerHTML=t:(Object(b.a)(s,t),s.append(t))),s.insertAdjacentElement("afterbegin",i),s},f=e=>{0===e.dataset.key.indexOf("date_")?r=l=0:o=0,e.remove(),a.findAndSplice(t=>t===e),setTimeout(()=>{d(),this.inputSearch.onChange(this.inputSearch.value)},0)};this.inputSearch.onClear=()=>{a.forEach(e=>{f(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),h.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)),m.a.getContacts(e,!0)]).then(e=>{if(!t())return;new Set(e[0].concat(e[1])).forEach(e=>{h.append(u(e))}),n.nav.classList.toggle("hide",!!h.innerHTML)})}if(!r&&e.trim()){const t=[];Object(H.b)(e,t),t.forEach(e=>{h.append(u("date_"+e.minDate+"_"+e.maxDate,e.title))}),n.nav.classList.toggle("hide",!!h.innerHTML)}},n.tabs.inputMessagesFilterEmpty.addEventListener("mousedown",e=>{const t=Object(Ve.a)(e.target,"LI");if(!t)return;const s=Object(Qe.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");p.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),p.default.pushToState("recentSearch",t);for(const e of t)p.default.requestPeer(e,"recentSearch")}})},{capture:!0});let y=document.createElement("div");y.classList.add("search-group-scrollable"),y.append(this.searchGroups.people.list),this.searchGroups.people.container.append(y);new g.a(y);let w,L=!0;const E=Object(S.a)(e.parentElement,"zoom-fade",150,e=>{w&&clearTimeout(w),0!==e||L||(n.selectTab(0,!1),this.inputSearch.onClearClick(),w=window.setTimeout(()=>{w=0,this.newBtnMenu.classList.remove("is-hidden")},150)),L=!1});E(0);const I=()=>{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),c.isMobileSafari||M.a.findItemByType("global-search")||M.a.pushItem({onPop:()=>{s()},type:"global-search"}),E(1)};this.inputSearch.input.addEventListener("focus",I),I(),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),M.a.removeByType("global-search"),E(0)});const C=document.createElement("button");C.classList.add("btn-icon","tgico-close"),this.searchGroups.recent.nameEl.append(C),C.addEventListener("click",()=>{this.searchGroups.recent.clear(),p.default.pushToState("recentSearch",[])})}};Z.a.appSidebarLeft=hi;var ui=hi;class pi{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.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 mi extends Ue.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"),this.prevBtn.addEventListener("click",this.onPrevClick),this.nextBtn=document.createElement("button"),this.nextBtn.classList.add("btn-icon","tgico-down","date-picker-next"),this.nextBtn.addEventListener("click",this.onNextClick),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"),this.monthsContainer.addEventListener("click",this.onDateClick),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;t.input.addEventListener("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 w.b({plainText:!0}),this.minutesInputField=new w.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),this.btnConfirm.addEventListener("click",()=>{this.onPick&&(this.selectedDate.setHours(+this.hoursInputField.value||0,+this.minutesInputField.value||0,0,0),this.onPick(this.selectedDate.getTime()/1e3|0)),this.hide()},{once:!0}),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 f.default.IntlDateElement({date:n,options:i}).element)}t.push(new f.default.IntlDateElement({date:n,options:i}).element),this.btnConfirm.firstChild.replaceWith(Object(f.i18n)(e,t))}}setTitle(){this.title.textContent="",this.title.append(new f.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&&r.b.isMobile?"short":"long"};this.monthTitle.textContent="",this.monthTitle.append(new f.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 f.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 l=Math.ceil(this.month.childElementCount/7);this.container.dataset.lines=""+l,this.monthsContainer.append(this.month)}}var gi=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 bi extends tt{constructor(e,t,s,i){super({peerTypes:["dialogs","contacts"],onSelect:i=>gi(this,void 0,void 0,(function*(){if(s){const e=s();e instanceof Promise&&(yield e)}da.setInnerPeer(i),da.chat.input.initMessagesForward(e,t.slice())})),onClose:i,placeholder:"ShareModal.Search.ForwardPlaceholder",chatRightsAction:"send_messages"})}}class fi extends Ue.b{constructor(e){super("popup-stickers",null,{closable:!0,overlayClosable:!0,body:!0}),this.stickerSetInput=e,this.onFooterClick=()=>{const e=Object(We.a)([this.stickersFooter],!0);Rt.toggleStickerSet(this.set).then(()=>{this.hide()}).catch(()=>{e()})},this.onStickersClick=e=>{const t=Object(Qe.a)(e.target,"sticker-set-sticker");if(!t)return;const s=t.dataset.docId;da.chat.input.sendMessageWithDocument(s)?this.hide():console.warn("got no doc by id:",s)},this.h6=document.createElement("h6"),this.h6.append(Object(f.i18n)("Loading")),this.header.append(this.h6),this.onClose=()=>{h.a.setOnlyOnePlayableGroup(""),this.stickersFooter.removeEventListener("click",this.onFooterClick),this.stickersDiv.removeEventListener("click",this.onStickersClick)};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(K.f)(this.stickersDiv,!0),this.stickersFooter=document.createElement("div"),this.stickersFooter.classList.add("sticker-set-footer"),t.append(this.stickersDiv);const s=Object(C.a)("btn-primary btn-primary-transparent disable-hover",{noRipple:!0,text:"Loading"});this.stickersFooter.append(s),this.body.append(t);new g.b(this.body);this.body.append(this.stickersFooter),this.loadStickerSet()}loadStickerSet(){return Rt.getStickerSet(this.stickerSetInput).then(e=>{let t;this.set=e.set,h.a.setOnlyOnePlayableGroup("STICKERS-POPUP"),this.h6.innerHTML=q.a.wrapEmojiText(e.set.title),this.stickersFooter.classList.toggle("add",!e.set.installed_date),e.set.installed_date?(t=Object(C.a)("btn-primary btn-primary-transparent danger",{noRipple:!0}),t.append(Object(f.i18n)("RemoveStickersCount",[Object(f.i18n)("Stickers",[e.set.count])]))):(t=Object(C.a)("btn-primary btn-color-primary",{noRipple:!0}),t.append(Object(f.i18n)("AddStickersCount",[Object(f.i18n)("Stickers",[e.set.count])]))),this.stickersFooter.textContent="",this.stickersFooter.append(t),t.addEventListener("click",this.onFooterClick),e.documents.length&&this.stickersDiv.addEventListener("click",this.onStickersClick);const s=new G.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=r.b.active.esgSticker.width;Vt({doc:t,div:e,lazyLoadQueue:s,group:"STICKERS-POPUP",play:!0,loop:!0,width:i,height:i}),this.stickersDiv.append(e)}})}}class vi{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 yi 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 wa,i.setAttribute("dialog","0"),i.classList.add("avatar-30"),i.lazyLoadQueue=this.lazyLoadQueue,this.loadPromises&&(i.loadPromises=this.loadPromises)),i.setAttribute("peer",""+U.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?e.replies+" "+(e.replies>1?"Comments":"Comment"):"Leave a Comment":"View in chat",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(Q.ripple)(t),this.append(n,e,t)}n.innerHTML=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(u.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 wi,Li;customElements.define("replies-element",yi),(Li=wi||(wi={})).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 e=t.post_author||(null===(a=t.fwd_from)||void 0===a?void 0:a.post_author);if(s.classList.add("channel-post"),l=Object(u.c)(t.views,1)+' <i class="tgico-channelviews time-icon"></i> '+(e?q.b.wrapEmojiText(e)+", ":"")+l,!(null===(o=t.fwd_from)||void 0===o?void 0:o.saved_from_msg_id)){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(H.f)(r)+(t.edit_date?"\nEdited: "+Object(H.f)(new Date(1e3*t.edit_date)):"")+(t.fwd_from?"\nOriginal: "+Object(H.f)(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},Li.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 yi;return r.message=s,r.type=o?"footer":"beside",r.loadPromises=n,r.lazyLoadQueue=a,r.init(),t.prepend(r),o},Li.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(f.i18n)("Loading")):r=new $e.a({peerId:l.fromId||l.fwdFromId,dialog:!1,onlyFirstName:!1,plainText:!1}).element;const c=Gt(r,l.message||"",l);a?a.replaceWith(c):s.append(c),t.classList.add("is-reply")};var Si=s(94),Mi=s(96);function Ei(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)}Z.a.getElementByPoint=Ei;var Ii=s(117);function Ci(e){e.style.display="none",e.offsetLeft,e.style.display=""}function ki(e,t){e.setAttribute("dir","auto"),e.innerHTML=t}const Ti=[];let Pi=void 0,xi=0;class Ai{constructor(e,t,s,i,n,o,r){let c;this.chat=e,this.appMessagesManager=t,this.appStickersManager=s,this.appUsersManager=i,this.appInlineBotsManager=n,this.appPhotosManager=o,this.appPeersManager=r,this.peerId=0,this.unreadOut=new Set,this.needUpdate=[],this.bubbles={},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=Yt(),this.replyFollowHistory=[],this.isHeavyAnimationInProgress=!1,this.isFirstLoad=!0,this.passEntities={},this.onBubblesClick=e=>{var t,s;let i=e.target,n=null;try{n=Object(Qe.a)(i,"bubble")}catch(e){}if(!n)return;if(n.classList.contains("is-date")&&Object(Qe.a)(i,"bubble-content")){if(n.classList.contains("is-sticky")&&!this.chatInner.classList.contains("is-scrolling"))return;for(const e in this.dateMessages){if(this.dateMessages[e].div===n){new mi(new Date(+e),this.onDatePick).show();break}}return}if(this.chat.selection.isSelecting&&e.isTrusted){if(n.classList.contains("service")&&void 0===n.dataset.mid)return;return Object(re.a)(e),l.isTouchSupported&&this.chat.selection.selectedText?void(this.chat.selection.selectedText=void 0):void this.chat.selection.toggleByBubble(Object(Qe.a)(i,"grouped-item")||n)}const a=Object(Qe.a)(i,"contact");if(a)return void this.chat.appImManager.setInnerPeer(+a.dataset.peerId);if(Object(Qe.a)(i,"replies")){const e=+n.dataset.mid;if(this.peerId===Si.a){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;this.appMessagesManager.wrapSingleMessage(s,i).then(()=>{this.appMessagesManager.generateThreadServiceStartMessage(this.appMessagesManager.getMessageByPeer(s,i)),this.chat.appImManager.setInnerPeer(s,t.fwd_from.saved_from_msg_id,"discussion",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 o=Object(Qe.a)(i,"peer-title")||Object(Qe.a)(i,"name")||Object(Ve.a)(i,"AVATAR-ELEMENT");if(o){i=o||i;const e=+(i.dataset.peerId||i.getAttribute("peer")),t=i.dataset.savedFrom;if(t){const e=t.split("_"),s=+e[0],i=+e[1];this.chat.appImManager.setInnerPeer(s,i)}else e?this.chat.appImManager.setInnerPeer(e):Be(f.default.format("HidAccount",!0));return}const r="SPAN"===i.tagName;if(n.classList.contains("sticker")&&i.parentElement.classList.contains("attachment")){const e=+n.dataset.mid,s=null===(t=this.chat.getMessage(e).media)||void 0===t?void 0:t.document;(null==s?void 0:s.stickerSetInput)&&new fi(s.stickerSetInput).show()}else{if("IMG"===i.tagName&&!i.classList.contains("emoji")&&!i.classList.contains("document-thumb")||i.classList.contains("album-item")||r||"VIDEO"===i.tagName&&!n.classList.contains("round")){let t=+(null===(s=Object(Qe.a)(i,"album-item"))||void 0===s?void 0:s.dataset.mid)||+n.dataset.mid,a=this.chat.getMessage(t);if(!a)return void this.log.warn("no message by messageId:",t);let o=[],r=Object.keys(this.bubbles).map(e=>+e).filter(e=>{let t=this.chat.getMessage(e);return t.media&&(t.media.photo||t.media.document&&("video"===t.media.document.type||"gif"===t.media.document.type)||t.media.webpage&&(t.media.webpage.document||t.media.webpage.photo))}).sort((e,t)=>e-t);r.forEach(e=>{let 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=!!this.bubbles[e].querySelector(".media-container-aspecter");let i=this.bubbles[e].querySelectorAll(t);const n=new Set;Array.from(i).forEach(t=>{if(s&&!Object(Qe.a)(t,"media-container-aspecter"))return;let i=Object(Qe.a)(t,"album-item");const a=i||t.parentElement;n.has(a)||(n.add(a),o.push({element:t,mid:+(null==i?void 0:i.dataset.mid)||e,peerId:this.peerId}))})}),o.sort((e,t)=>e.mid-t.mid);let l=o.findIndex(e=>e.mid===t);return Z.b&&this.log("open mediaViewer single with ids:",r,l,o),o[l]?((new pa).setSearchContext({threadId:this.chat.threadId,peerId:this.peerId,inputFilter:"inputMessagesFilterPhotoVideo"}).openMedia(a,o[l].element,0,!0,o.slice(0,l),o.slice(l+1)),void Object(re.a)(e)):void this.log("no target for media viewer!",i)}if(-1===["IMG","DIV","SPAN"].indexOf(i.tagName)&&(i=Object(Ve.a)(i,"DIV")),-1!==["DIV","SPAN"].indexOf(i.tagName)){if(i.classList.contains("goto-original")){const e=n.dataset.savedFrom.split("_"),t=+e[0],s=+e[1];return void this.chat.appImManager.setInnerPeer(t,s)}if(i.classList.contains("forward")){const e=+n.dataset.mid;return void new bi(this.peerId,[e])}let t=!1;try{t=!!Object(Qe.a)(e.target,"reply")}catch(e){}if(t&&n.classList.contains("is-reply")){const e=+n.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,i=t.reply_to.reply_to_msg_id;this.chat.appImManager.setInnerPeer(s,i,this.chat.type,this.chat.threadId)}}}},this.onScroll=()=>{this.isHeavyAnimationInProgress&&this.scrolledDown||(l.isTouchSupported||(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 I,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 pi(this.chat),this.preloader=new ie.a({cancelable:!1}),this.lazyLoadQueue=new G.d,this.lazyLoadQueue.queueId=++xi,this.listenerSetter.add(a.default,"history_update",e=>{const{storage:t,peerId:s,mid:i}=e;if(i&&s===this.peerId&&this.chat.getMessagesStorage()===t){const e=this.bubbles[i];if(!e)return;const t=this.chat.getMessage(i);if(+e.dataset.timestamp>=t.date+ke.a.serverTimeOffset-1)return;this.setBubblePosition(e,t,!1),this.scrollingToNewBubble&&this.scrollToBubbleEnd()}}),this.listenerSetter.add(a.default,"dialog_flush",e=>{let t=e.peerId;this.peerId===t&&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(Wt({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[message-id="${r}"], .document[data-doc-id="${r}"]`);t&&(t instanceof pe?(t.setAttribute("doc-id",e.media.document.id),t.setAttribute("message-id",""+c),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($t.c)().then(()=>{this.renderMessage(e,!0,!1,a,!1),this.scrollToBubbleIfLast(a)})}else this.log.warn("message_sent there is no bubble",e);if(this.bubbles[r]){const e=this.bubbles[r];this.bubbles[c]=e,delete this.bubbles[r],Object(Re.c)(()=>{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",e=>{Object(Re.c)(()=>{const{storage:t,peerId:s,mid:i}=e;if(s!==this.peerId||t!==this.chat.getMessagesStorage())return;const n=this.getMountedBubble(i);if(!n)return;const a="scheduled"===this.chat.type;this.renderMessage(n.message,!0,!1,n.bubble,a),this.scrollToBubbleIfLast(n.bubble),a&&(this.messagesQueuePromise||Promise.resolve()).then(()=>{this.deleteEmptyDateGroups()})})}),this.listenerSetter.add(a.default,"album_edit",e=>{const{peerId:t,groupId:s,deletedMids:i}=e;if(t!==this.peerId)return;const n=this.appMessagesManager.getMidsByAlbum(s).concat(i).find(e=>this.bubbles[e]);if(!n)return;const a=Object(A.e)(this.appMessagesManager.groupedMessagesStorage[s],"asc").pop();this.renderMessage(this.chat.getMessage(a),!0,!1,this.bubbles[n],!1)}),this.listenerSetter.add(a.default,"messages_downloaded",e=>{const{peerId:t,mids:s}=e,i=this.getMiddleware();Object($t.c)().then(()=>{i()&&s.forEach(e=>{Object(ve.c)(this.needUpdate,(s,i)=>{if(s.replyMid===e&&s.replyToPeerId===t){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,wi.setReply({chat:this.chat,bubble:n,message:a})}})})})}),this.listenerSetter.add(this.bubblesContainer,"click",this.onBubblesClick),Z.b&&this.listenerSetter.add(this.bubblesContainer,"dblclick",e=>{const t=Object(Qe.a)(e.target,"grouped-item")||Object(Qe.a)(e.target,"bubble");if(t){const e=+t.dataset.mid;this.log("debug message:",this.chat.getMessage(e)),this.highlightBubble(t)}}),this.listenerSetter.add(this.bubblesContainer,"dblclick",e=>{if(this.chat.selection.isSelecting||!this.appMessagesManager.canWriteToPeer(this.peerId,this.chat.threadId))return;const t=e.target.classList.contains("bubble")?e.target:null;if(t){const e=+t.dataset.mid;this.chat.input.initMessageReply(e)}}),this.stickyIntersector=new vi(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($t.a)(()=>{this.isHeavyAnimationInProgress=!0,this.lazyLoadQueue.lock(),c=this.getMiddleware()},()=>{this.isHeavyAnimationInProgress=!1,c&&c()&&(this.lazyLoadQueue.unlock(),this.lazyLoadQueue.refresh()),c=null},this.listenerSetter)}constructPeerHelpers(){if(this.listenerSetter.add(a.default,"history_append",e=>{const{peerId:t,storage:s,mid:i}=e;t===this.peerId&&s===this.chat.getMessagesStorage()&&(this.scrollable.loadedAll.bottom?this.renderNewMessagesByIds([i],!0):this.chat.setMessageId())}),this.listenerSetter.add(a.default,"history_multiappend",e=>{const t=e;if(!(this.peerId in t))return;const s=Array.from(t[this.peerId]).slice().sort((e,t)=>t-e);this.renderNewMessagesByIds(s)}),this.listenerSetter.add(a.default,"history_delete",e=>{const{peerId:t,msgs:s}=e,i=Object.keys(s).map(e=>+e);t===this.peerId&&this.deleteMessagesByIds(i)}),this.listenerSetter.add(a.default,"dialog_unread",e=>{e.peerId===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=>{const t=e;if(this.peerId===-t){this.chatInner.classList.contains("has-rights")!==this.appMessagesManager.canWriteToPeer(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(A.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.renderMessage(s,void 0,!1,t)}}),e?this.scrollable.scrollTop=99999:this.performHistoryResult([],!0,!1,void 0)}}),this.unreadedObserver=new IntersectionObserver(e=>{e.forEach(e=>{if(e.isIntersecting){const t=e.target,s=this.unreaded.get(t);this.onUnreadedInViewport(t,s)}})}),"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)}}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))}return this.unreaded.forEach((e,s)=>{e<=t&&this.onUnreadedInViewport(s,e)}),this.unreadedSeen.clear(),Z.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(Object.keys(this.appMessagesManager.getScheduledMessagesStorage(this.peerId)).length)};this.listenerSetter.add(a.default,"scheduled_new",t=>{const{peerId:s,mid:i}=t;s===this.peerId&&(this.renderNewMessagesByIds([i]),e())}),this.listenerSetter.add(a.default,"scheduled_delete",t=>{const{peerId:s,mids:i}=t;s===this.peerId&&(this.deleteMessagesByIds(i),e())})}onGoDownClick(){if(this.replyFollowHistory.length){Object(ve.c)(this.replyFollowHistory,(e,t)=>{const s=this.bubbles[e];let i=!0;if(s){const e=s.getBoundingClientRect();i=this.appPhotosManager.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=Ei(this.scrollable.container,e,"center");return t&&(t=Object(Qe.a)(t,"bubble")),t}getGroupedBubble(e){const t=this.appMessagesManager.groupedMessagesStorage[e];for(const e in t)if(this.bubbles[e]){const s=Math.max(...Object.keys(t).map(e=>+e));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(A.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)Z.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.scrollable.loadedAll.bottom=!0);Z.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 g.b(null,"IM",300),this.scrollable.loadedAll.top=!1,this.scrollable.loadedAll.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),l.isTouchSupported&&(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"),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.firstUnreadBubble===t&&(this.firstUnreadBubble=null),this.bubbleGroups.removeBubble(t),this.unreadedObserver&&(this.unreadedObserver.unobserve(t),this.unreaded.delete(t)),t.remove()}),t&&this.chat.selection.isSelecting&&this.chat.selection.deleteSelectedMids(e),h.a.checkAnimations(!1,ra),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]);const s=this.performHistoryResult(e,!1,!0);t&&s.then(()=>{this.scrollToBubbleEnd()})}scrollToBubble(e,t,s,i){const n=Object(Qe.a)(e,"bubble");if("center"===t&&Object(Xt.a)(n)===(this.stickyIntersector?2:1)){const s=n.parentElement;0===Object(Xt.a)(s)&&(e=s,t="start")}return this.scrollable.scrollIntoViewNew(e,t,4,void 0,s,i)}scrollToBubbleEnd(e=this.chatInner.lastElementChild.lastElementChild){e&&(this.scrollingToNewBubble=e,this.scrollToBubble(e,"end").then(()=>{this.scrollingToNewBubble=null}))}scrollToBubbleIfLast(e){e.parentElement.lastElementChild===e&&e.parentElement.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(!(i in this.dateMessages)){let e;const t=new Date;if(t.setHours(0,0,0,0),t.getTime()===s.getTime())e=Object(f.i18n)("scheduled"===this.chat.type?"Chat.Date.ScheduledForToday":"Date.Today");else{const i={day:"numeric",month:"long"};s.getFullYear()!==t.getFullYear()&&(i.year="numeric"),e=new f.default.IntlDateElement({date:s,options:i}).element,"scheduled"===this.chat.type&&(e=Object(f.i18n)("Chat.Date.ScheduledFor",[e]))}const n=document.createElement("div");n.className="bubble service is-date";const a=document.createElement("div");a.classList.add("bubble-content");const o=document.createElement("div");o.classList.add("service-msg"),o.append(e),a.append(o),n.append(a);const r=document.createElement("div");r.className="bubbles-date-group";const l=Object(A.e)(this.dateMessages,"asc");let c=0;for(;c<l.length;++c){if(i<l[c])break}this.dateMessages[i]={div:n,container:r,firstTimestamp:s.getTime()},r.append(n),Jt(r,this.chatInner,c),this.stickyIntersector&&this.stickyIntersector.observeStickyHeaderChanges(r)}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.stickyIntersector&&this.stickyIntersector.disconnect(),delete this.lazyLoadQueue,this.unreadedObserver&&delete this.unreadedObserver,this.stickyIntersector&&delete this.stickyIntersector}cleanup(e=!1){this.scrollable.loadedAll.top=!1,this.scrollable.loadedAll.bottom=!1,Object(Ft.b)(this.scrollable.container),Object($t.d)(),void 0!==Pi&&(Pi=void 0),this.bubbles={},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.loadedTopTimes=this.loadedBottomTimes=0,this.middleware.clean()}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=++xi,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)};Z.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 u=this.chatInner;let p;this.cleanup(),this.chatInner=document.createElement("div"),i?(this.chatInner.className=u.className,this.chatInner.classList.remove("disable-hover","is-scrolling")):this.chatInner.classList.add("bubbles-inner"),this.lazyLoadQueue.lock(),p=o?{promise:Object($t.c)().then(()=>this.performHistoryResult(o.mids,!0,!1,void 0)),cached:!0}:this.getHistory(t,!0,l,c);const{promise:m,cached:g}=p;g||i||(this.scrollable.container.textContent="",this.chat.finishPeerChange(a,l,t),this.preloader.attach(this.bubblesContainer)),h.a.lockGroup(ra);const f=m.then(()=>{if(g?i||this.chat.finishPeerChange(a,l,t):this.preloader.detach(),Object(b.a)(this.scrollable.container,this.chatInner),h.a.unlockGroup(ra),h.a.checkAnimations(!1,ra),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:Ke.a.Static),s||this.highlightBubble(o))}else this.scrollable.scrollTop=99999;this.onScroll(),this.chat.dispatchEvent("setPeer",t,!l);const s=this.appMessagesManager.isFetchIntervalNeeded(e);if(o||s){const t=this.getMiddleware();Promise.all([f,Object($t.c)()]).then(()=>{if(t()&&(this.scrollable.checkForTriggers(),s)){const s=()=>{this.fetchNewPromise=new Promise(i=>{t()&&this.appMessagesManager.isFetchIntervalNeeded(e)?this.appMessagesManager.getNewHistory(e,this.chat.threadId).then(e=>{if(!t())return void i();const n=e.history.slice.isEnd(Mi.a.Bottom);this.scrollable.loadedAll.bottom&&this.scrollable.loadedAll.bottom!==n&&(this.scrollable.loadedAll.bottom=n,this.onScroll()),setTimeout(s,3e4),i()}):i()}).finally(()=>{this.fetchNewPromise=void 0})};i?setTimeout(s,3e4):s()}})}else t&&!this.bubbles[n]&&t!==n||(this.scrollable.loadedAll.bottom=!0);if(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:g,promise:f}}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.canWriteToPeer(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())return Promise.reject("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){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;Jt(e,i.container,r)}else s?i.container.insertBefore(e,i.container.children[this.stickyIntersector?1:0].nextSibling):i.container.append(e);this.bubbleGroups.addBubble(e,t,s)}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 l="pinned"!==this.chat.type;if(e.deleted)return;if(e.grouped_id&&l){const t=this.appMessagesManager.groupedMessagesStorage[e.grouped_id],s=Math.max(...Object.keys(t).map(e=>+e));if(e.mid<s)return}const d=this.peerId,h=e.fromId===a.default.myId||e.pFlags.out&&this.appPeersManager.isMegagroup(this.peerId),u=document.createElement("div");let p,m;if(u.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(" "),m=i.lastElementChild,p=m.firstElementChild,p.innerHTML="",p.style.cssText="",m.innerHTML="",m.appendChild(p);const a=m.style.transitionDelay;m.style.cssText="",m.style.transitionDelay=a,i===this.firstUnreadBubble&&i.classList.add("is-first-unread");const o=+i.dataset.mid;+e.mid===o||delete this.bubbles[o]}else if(m=document.createElement("div"),m.classList.add("bubble-content-wrapper"),p=document.createElement("div"),p.classList.add("bubble-content"),(i=document.createElement("div")).classList.add("bubble"),m.appendChild(p),i.appendChild(m),!h&&!e.pFlags.out&&this.unreadedObserver){(e.pFlags.unread||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.timestamp=e.date;const g=[];if("messageService"===e._){let s=e.action._;if(Ti.includes(s)||f.langPack.hasOwnProperty(s)&&!f.langPack[s])return i;i.className="bubble service",p.innerHTML="";const a=document.createElement("div");return a.classList.add("service-msg"),a.append(this.appMessagesManager.wrapMessageActionTextNew(e)),p.append(a),n&&(this.renderMessagesQueue(e,i,t,g),e.pFlags.is_single&&i.classList.add("is-group-last")),i}let b,v,y=e.media;if((null==y?void 0:y.document)&&!["video","gif"].includes(y.document.type));else if(e.grouped_id&&l){const t=this.appMessagesManager.getAlbumText(e.grouped_id);b=t.message,v=t.totalEntities}else"sticker"!==(null===(o=null==y?void 0:y.document)||void 0===o?void 0:o.type)&&(b=e.message,v=e.totalEntities);let w=q.b.wrapRichText(b,{entities:v,passEntities:this.passEntities}),L=!0,S=!0;if(v&&!y){let e=v.filter(e=>"messageEntityEmoji"===e._),t=b.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(b);if(1===e.length&&!y&&t)y={_:"messageMediaDocument",document:t};else{let t=document.createElement("div");t.classList.add("attachment"),t.innerHTML=w,i.classList.add("emoji-"+e.length+"x"),p.append(t)}i.classList.add("is-message-empty","emoji-big"),L=!1,S=!1}i.classList.add("can-have-big-emoji")}}S&&ki(u,w);const M=wi.setTime(this.chat,e,i,p,u);if(p.prepend(u),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(e=>{const t=e.buttons;if(!t||!t.length)return;const i=document.createElement("div");i.classList.add("reply-markup-row"),t.forEach(e=>{const t=q.b.wrapRichText(e.text,{noLinks:!0,noLinebreaks:!0});let s;switch(e._){case"keyboardButtonUrl":{const t=q.b.wrapRichText(" ",{entities:[{_:"messageEntityTextUrl",length:1,offset:0,url:e.url}]});s=Object(Ii.a)(t).firstElementChild,s.classList.add("is-link","tgico");break}default:s=document.createElement("button")}s.classList.add("reply-markup-button","rp"),s.innerHTML=t,Object(Q.ripple)(s),i.append(s)}),s.append(i)}),Object(F.b)(s,s=>{let i=s.target;if(i.classList.contains("reply-markup-button")||(i=Object(Qe.a)(i,"reply-markup-button")),!i||i.classList.contains("is-link"))return;Object(re.a)(s);const n=Object(Xt.a)(i),a=t[Object(Xt.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)}),L=!1,i.classList.add("with-reply-markup"),m.append(s)}const E=e.pFlags.is_outgoing;if(h){(e.pFlags.unread||E)&&this.unreadOut.add(e.mid);let t="";t=E?"is-sending":e.pFlags.unread?"is-sent":"is-read",i.classList.add(t)}const I=this.appMessagesManager.getMessageWithReplies(e),C=!!I;C&&i.classList.add("with-replies");const k=h&&(!e.fwd_from||this.peerId!==a.default.myId);let T=p;if(y){let t=document.createElement("div");t.classList.add("attachment"),b||i.classList.add("is-message-empty");let s=!1;switch(y._){case"messageMediaPhoto":{const s=y.photo;b||(L=!1),i.classList.add("hide-name","photo");const n=this.appMessagesManager.groupedMessagesStorage[e.grouped_id];if(e.grouped_id&&1!==Object.keys(n).length&&l){i.classList.add("is-album","is-grouped"),Qt({groupId:e.grouped_id,attachmentDiv:t,middleware:this.getMiddleware(),isOut:h,lazyLoadQueue:this.lazyLoadQueue,chat:this.chat,loadPromises:g,noAutoDownload:this.chat.noAutoDownloadMedia});break}const a=!c.isAndroid&&L&&!C&&!1;a&&i.classList.add("with-media-tail"),qt({photo:s,message:e,container:t,withTail:a,isOut:k,lazyLoadQueue:this.lazyLoadQueue,middleware:this.getMiddleware(),loadPromises:g,noAutoDownload:this.chat.noAutoDownloadMedia});break}case"messageMediaWebPage":{s=!0;let t=y.webpage;if("webPageEmpty"===t._)break;i.classList.add("webpage");let n=document.createElement("div");n.classList.add("web");let a,o,l=document.createElement("div");l.classList.add("quote"),(t.photo||t.document)&&(a=document.createElement("div"),a.classList.add("preview-resizer"),o=document.createElement("div"),o.classList.add("preview"),a.append(o));let c=null;if(t.document)if(c=t.document,"gif"===c.type||"video"===c.type)i.classList.add("video"),Ut({doc:c,container:o,message:e,boxWidth:r.b.active.webpage.width,boxHeight:r.b.active.webpage.height,lazyLoadQueue:this.lazyLoadQueue,middleware:this.getMiddleware(),isOut:k,group:ra,loadPromises:g,noAutoDownload:this.chat.noAutoDownloadMedia});else{const t=Wt({message:e,noAutoDownload:this.chat.noAutoDownloadMedia});o.append(t),o.classList.add("preview-with-document")}a&&l.append(a);let d=document.createElement("div");if(d.classList.add("quote-text"),t.site_name){let e=document.createElement("a");e.classList.add("webpage-name"),e.setAttribute("target","_blank"),e.href=t.url||"#",ki(e,q.b.wrapEmojiText(t.site_name)),d.append(e)}if(t.rTitle){let e=document.createElement("div");e.classList.add("title"),ki(e,t.rTitle),d.append(e)}if(t.rDescription){let e=document.createElement("div");e.classList.add("text"),ki(e,t.rDescription),d.append(e)}if(l.append(d),t.photo&&!c){i.classList.add("photo");const s=t.photo.sizes[t.photo.sizes.length-1];let n=!1;s.w===s.h&&d.childElementCount?(i.classList.add("is-square-photo"),n=!0,this.appPhotosManager.setAttachmentSize(t.photo,o,80,80,!1)):s.h>s.w&&i.classList.add("is-vertical-photo"),qt({photo:t.photo,message:e,container:o,boxWidth:n?0:r.b.active.webpage.width,boxHeight:n?0:r.b.active.webpage.height,isOut:k,lazyLoadQueue:this.lazyLoadQueue,middleware:this.getMiddleware(),loadPromises:g,withoutPreloader:n,noAutoDownload:this.chat.noAutoDownloadMedia})}n.append(l),u.insertBefore(n,u.lastElementChild);break}case"messageMediaDocument":{let n=y.document;if(n.sticker){i.classList.add("sticker"),L=!1,n.animated&&i.classList.add("sticker-animated");const e=r.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),p.style.height=t.style.height,p.style.width=t.style.width,Vt({doc:n,div:t,middleware:this.getMiddleware(),lazyLoadQueue:this.lazyLoadQueue,group:ra,play:!0,loop:!0,emoji:i.classList.contains("emoji-big")?b:void 0,withThumb:!0,loadPromises:g});break}if("video"===n.type||"gif"===n.type||"round"===n.type){"round"!==n.type&&b||(L=!1),i.classList.add("hide-name","round"===n.type?"round":"video");const s=this.appMessagesManager.groupedMessagesStorage[e.grouped_id];if(e.grouped_id&&1!==Object.keys(s).length&&l)i.classList.add("is-album","is-grouped"),Qt({groupId:e.grouped_id,attachmentDiv:t,middleware:this.getMiddleware(),isOut:h,lazyLoadQueue:this.lazyLoadQueue,chat:this.chat,loadPromises:g,noAutoDownload:this.chat.noAutoDownloadMedia});else{const s=!c.isAndroid&&!c.isApple&&"round"!==n.type&&L&&!C&&!1;s&&i.classList.add("with-media-tail"),Ut({doc:n,container:t,message:e,boxWidth:r.b.active.regular.width,boxHeight:r.b.active.regular.height,withTail:s,isOut:k,lazyLoadQueue:this.lazyLoadQueue,middleware:this.getMiddleware(),group:ra,loadPromises:g,noAutoDownload:this.chat.noAutoDownloadMedia})}break}{const t=function({albumMustBeRenderedFull:e,message:t,bubble:s,messageDiv:i,chat:n,loadPromises:a,noAutoDownload:o}){let r;const l=e?n.getMidsByMid(t.mid):[t.mid];return l.forEach((e,t)=>{const s=n.getMessage(e),c=Wt({message:s,loadPromises:a,noAutoDownload:o}),d=document.createElement("div");d.classList.add("document-container"),d.dataset.mid=""+e;const h=document.createElement("div");if(h.classList.add("document-wrapper"),s.message){const e=document.createElement("div");e.classList.add("document-message");const t=q.b.wrapRichText(s.message,{entities:s.totalEntities});e.innerHTML=t,h.append(e)}if(l.length>1){const e=document.createElement("div");e.classList.add("document-selection"),d.append(e),d.classList.add("grouped-item"),0===t&&(r=h)}h.append(c),d.append(h),i.append(d)}),l.length>1&&s.classList.add("is-multiple-documents","is-grouped"),r}({albumMustBeRenderedFull:l,message:e,bubble:i,messageDiv:u,chat:this.chat,loadPromises:g,noAutoDownload:this.chat.noAutoDownloadMedia});t&&(T=t);const a=u.lastElementChild.querySelector(".document-message, .document-size, .audio");a&&a.append(M.cloneNode(!0)),i.classList.remove("is-message-empty"),u.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=""+y.user_id,u.classList.add("contact-message"),s=!0;const n=[];e.media.first_name&&n.push(q.b.wrapEmojiText(e.media.first_name)),e.media.last_name&&n.push(q.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(K.c)(e.media.phone_number).formatted:"Unknown phone number"}</div>\n </div>`;const a=new wa;a.setAttribute("peer",""+e.media.user_id),a.classList.add("contact-avatar","avatar-54"),t.prepend(a),i.classList.remove("is-message-empty"),u.classList.add("contact-message"),u.append(t);break}case"messageMediaPoll":{i.classList.remove("is-message-empty");const t=function(e){const t=new At;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);u.prepend(t),u.classList.add("poll-message");break}default:i.classList.remove("is-message-empty"),u.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>',u.append(M),this.log.warn("unrecognized media type:",e.media._,e)}s||p.append(t)}this.chat.selection.isSelecting&&this.chat.selection.toggleBubbleCheckbox(i,!0);let P="";const x=d<0&&(d!==e.fromId||h)&&e.fromId!==a.default.myId;if(x||e.fwd_from||e.reply_to_mid){let t;const s=e.from_id&&"peerChannel"===e.from_id._&&e.fromId===e.fwdFromId;if(e.fwd_from&&!e.fwd_from.from_id&&!e.fwd_from.channel_id?(t=document.createElement("span"),t.innerHTML=q.b.wrapEmojiText(e.fwd_from.from_name),t.classList.add("peer-title"),i.classList.add("hidden-profile")):t=new $e.a({peerId:e.fwdFromId||e.fromId}).element,e.fwdFromId||e.fwd_from){if(this.peerId===a.default.myId||s||i.classList.add("forwarded"),e.savedFrom&&(P=e.savedFrom),!i.classList.contains("sticker")){let i=document.createElement("div");i.classList.add("name"),i.dataset.peerId=e.fwdFromId,this.peerId===a.default.myId||this.peerId===Si.a||s?(i.style.color=this.appPeersManager.getPeerColorById(e.fwdFromId,!1),i.append(t)):(i.append(Object(f.i18n)("ForwardedFrom",[t])),P&&(i.dataset.savedFrom=P)),T.append(i)}}else if(!i.classList.contains("sticker")&&x){let s=document.createElement("div");s.classList.add("name"),s.append(t),h||(s.style.color=this.appPeersManager.getPeerColorById(e.fromId,!1)),s.dataset.peerId=e.fromId,T.append(s)}else i.classList.add("hide-name");e.reply_to_mid&&e.reply_to_mid!==this.chat.threadId&&wi.setReply({chat:this.chat,bubble:i,bubbleContainer:p,message:e});if(this.chat.isAnyGroup()&&!k){let t=new wa;t.classList.add("user-avatar","avatar-40"),t.loadPromises=g,!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===Si.a)||s?e.fwdFromId:e.fromId)||0)),m.append(t)}}else i.classList.add("hide-name");"pinned"===this.chat.type&&(P=`${this.chat.peerId}_${e.mid}`);if(I&&I.mid===this.chat.threadId&&i.classList.add("is-thread-starter","is-group-last"),P&&("pinned"===this.chat.type||e.fwd_from.saved_from_msg_id)&&this.peerId!==Si.a){const e=document.createElement("div");e.classList.add("bubble-beside-button","goto-original","tgico-arrow_next"),p.append(e),i.dataset.savedFrom=P,i.classList.add("with-beside-button")}if(i.classList.add(k?"is-out":"is-in"),n&&this.renderMessagesQueue(e,i,t,g),C){wi.renderReplies({bubble:i,bubbleContainer:p,message:I,messageDiv:u,loadPromises:g,lazyLoadQueue:this.lazyLoadQueue})&&(L=!0)}return L&&(i.classList.add("can-have-tail"),p.append(Fi())),i}performHistoryResult(e,t,s,i){e=e.slice(),i&&e.unshift(i);const n=this.appMessagesManager.getHistoryStorage(this.peerId,this.chat.threadId),a=n.history.first,o=n.history.last;return!a.isEnd(Mi.a.Bottom)||a.length&&!e.includes(a[0])||(this.scrollable.loadedAll.bottom=!0),!o.isEnd(Mi.a.Top)||o.length&&!e.includes(o[o.length-1])||(this.scrollable.loadedAll.top=!0),new Promise((s,i)=>{const n=(t?e.shift:e.pop).bind(e);let a;for(this.messagesQueueOnRender=()=>{const{scrollTop:e,scrollHeight:s}=this.scrollable;a=t?s-e:e,this.messagesQueueOnRender=void 0},this.needReflowScroll&&(Ci(this.scrollable.container),this.needReflowScroll=!1);e.length;){let e=this.chat.getMessage(n());this.renderMessage(e,t,!0)}(this.messagesQueuePromise||Promise.resolve()).then(()=>{if(void 0!==a){const e=t?this.scrollable.scrollHeight-a:a;this.scrollable.scrollTop=e,c.isSafari&&Ci(this.scrollable.container)}s(!0)},i)}).then(()=>!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=>(this.scrollable.loadedAll.top=!0,this.scrollable.loadedAll.bottom=!0,{history:e.slice().reverse()})):void 0}getHistory(e=0,t=!1,s=!1,i=0,n=!1){const r=this.peerId,l=Math.min(30,this.appPhotosManager.windowH/38|0),d=Object.keys(this.bubbles).length>0?Math.max(40,l):l;let h=d;if(void 0!==Pi){if(!Pi)return{cached:!1,promise:Promise.resolve(!0)};Object.keys(this.bubbles).length>0&&--Pi}let u,p=0;if(s&&(p=h,t||(h=0)),i&&!s)if("pinned"===this.chat.type)u=[i];else{const t=this.appMessagesManager.getHistoryStorage(r,this.chat.threadId).history.slice;if(t.length<h&&!t.isEnd(Mi.a.Both)){u=t.slice();for(let e=u.length-1;e>=0;--e){if(!this.chat.getMessage(u[e]).grouped_id)break;u.splice(e,1)}e=u[u.length-1]||e}}let m,g=this.requestHistory(e,h,p);const b=(null==u?void 0:u.length)&&g instanceof Promise,f=this.isFirstLoad&&p&&g instanceof Promise||b;b&&(m=g,g={history:u}),this.isFirstLoad=!1;const v=e=>{if("discussion"===this.chat.type&&"offsetIdOffset"in e&&e.history.isEnd(Mi.a.Top)){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()),this.scrollable.loadedAll.top=!0}},y=e=>(v(e),Object($t.c)().then(()=>this.performHistoryResult(e.history||[],t,s,!b&&i))),w=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):y(e),e=>{throw this.log.error("getHistory error:",e),e});return s};let L,S;if(g instanceof Promise)S=!1,L=w(g);else{if(n)return null;S=!0,L=y(g)}const M=b?w(m):L;if(f&&a.default.settings.animationsEnabled){let s=b?2:1;this.messagesQueueOnRenderAdditional=()=>{if(this.log("ship went past rocks of magnets"),--s)return;if(this.messagesQueueOnRenderAdditional=void 0,!Object.keys(this.bubbles).length)return;let n,a=Object(A.e)(this.bubbles,"desc");b&&u.length&&(a=a.filter(e=>!u.includes(e))),n=p?e||Math.max(...a):i||Math.max(...a);const r=a.slice(a.findIndex(e=>n>e)),l=b?[]:[n],d=b?[]:a.slice(0,a.findIndex(e=>n>=e)).reverse();Z.b&&this.log("getHistory: targeting mid:",n,e,i,r.map(e=>this.appMessagesManager.getServerMessageId(e)),d.map(e=>this.appMessagesManager.getServerMessageId(e)));const h=[];this.chatInner.classList.add("zoom-fading");const m=b?10:40,g=b?0:1,f=(e,t=0)=>{const s=Object(o.a)();let i=0;return e.forEach((n,a)=>{if(!this.bubbles[n])return void this.log.warn("animateAsLadder: no bubble by mid:",n);const o=this.bubbles[n].lastElementChild;if(i=(a+t||.1)*m,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)}h.push(o)}),e.length||s.resolve(),{lastMsDelay:i,animationPromise:s}},v=f(r,g),y=f(l),w=f(d,g),L=[v.animationPromise,y.animationPromise,w.animationPromise],S=[v.lastMsDelay,y.lastMsDelay,w.lastMsDelay];let M;Object(Re.c)(()=>{h.forEach(e=>{e.classList.remove("zoom-fade")})}),(r.length||l.length||d.length)&&(M=Promise.all(L),Object($t.b)(M,Math.max(...S)+200).then(()=>{Object(Re.c)(()=>{h.forEach(e=>{e.style.transitionDelay=""}),this.chatInner.classList.remove("zoom-fading")}),c.isSafari||(this.needReflowScroll=!0)})),(M||Promise.resolve()).then(()=>{setTimeout(()=>{this.loadMoreHistory(t,!0)},0)})}}else this.messagesQueueOnRenderAdditional=void 0;return t?this.getHistoryTopPromise=M:this.getHistoryBottomPromise=M,M.then(()=>{t?this.getHistoryTopPromise=void 0:this.getHistoryBottomPromise=void 0}),n?null:(!f&&L.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(A.e)(this.bubbles));const s=2*d;e&&e.length>s&&(t?(e=e.slice(s),this.scrollable.loadedAll.bottom=!1):(e=e.slice(0,e.length-s),this.scrollable.loadedAll.top=!1),this.deleteMessagesByIds(e,!1))}),L.then(()=>{"chat"===this.chat.type&&setTimeout(()=>{t?this.loadMoreHistory(!0,!0):this.loadMoreHistory(!1,!0)},0)}),{cached:S,promise:L})}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])}}}function Fi(){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 Oi{constructor(e,t,s,n){const o=new $e.a({peerId:e,onlyFirstName:!0}).element;t=t.slice();const r=a=>{n&&n(),"scheduled"===s?i.a.deleteScheduledMessages(e,t):i.a.deleteMessages(e,t,a)};let l,c,d,h,u;if(1===t.length?l="DeleteSingleMessagesTitle":(l="DeleteMessagesTitle",c=[Object(f.i18n)("messages",[t.length])]),d=1===t.length?"AreYouSureDeleteSingleMessage":"AreYouSureDeleteFewMessages",u=[{langKey:"Delete",isDanger:!0,callback:()=>r()}],e===a.default.myId||"scheduled"===s);else if(e>0)u.push({langKey:"DeleteMessagesOptionAlso",langArgs:[o],isDanger:!0,callback:()=>r(!0)});else{const s=D.a.getChat(-e),n=D.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?u.push({langKey:"DeleteForAll",isDanger:!0,callback:()=>r(!0)}):(u.push({langKey:"DeleteMessagesOption",isDanger:!0,callback:()=>r(!0)}),d="DeleteMessagesTextGroup",h=[Object(f.i18n)("messages",[s.length])]))}else u[0].callback=()=>r(!0)}Object(Ue.a)(u);new ze("popup-delete-chat",{peerId:e,titleLangKey:l,titleLangArgs:c,descriptionLangKey:d,descriptionLangArgs:h,buttons:u}).show()}}class Di{constructor(e,t,s,n){let o,r,l=[];const c=U.a.canPinMessage(e),d=(a,o)=>{setTimeout(()=>{let r;r=s&&!t?c?i.a.unpinAllMessages(e):i.a.hidePinnedMessages(e):i.a.updatePinnedMessage(e,t,s,o,a),n&&r.then(n)},300)};if(s){let e="UnpinMessage";t?(o="UnpinMessageAlertTitle",r="Chat.Confirm.Unpin"):c?(o="Popup.Unpin.AllTitle",r="Chat.UnpinAllMessagesConfirmation"):(o="Popup.Unpin.HideTitle",r="Popup.Unpin.HideDescription",e="Popup.Unpin.Hide"),l.push({langKey:e,isDanger:!0,callback:()=>d()})}else{o="PinMessageAlertTitle";const t="PinMessage";e<0?(l.push({langKey:t,callback:()=>d()}),D.a.isBroadcast(-e)?r="PinMessageAlertChannel":(r="PinMessageAlert",l.push({langKey:"PinNotify",callback:()=>d(void 0,!0)}))):(r="PinMessageAlertChat",e===a.default.myId?l.push({langKey:t,callback:()=>d()}):(l.push({langKey:t,callback:()=>d(!0)}),l.push({langKey:"PinAlsoFor",langArgs:[new $e.a({peerId:e,onlyFirstName:!0}).element],callback:()=>d()})))}Object(Ue.a)(l);new ze("popup-delete-chat",{peerId:e,titleLangKey:o,descriptionLangKey:r,buttons:l}).show()}}class ji{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({text:"SEND",callback:()=>{s&&s(),i.a.sendScheduledMessages(e,t)}}),o.push({text:"CANCEL",isCancel:!0});new ze("popup-delete-chat",{peerId:e,title:n,description:a,buttons:o}).show()}}function _i(){window.getSelection?window.getSelection().empty?window.getSelection().empty():window.getSelection().removeAllRanges&&window.getSelection().removeAllRanges():document.selection&&document.selection.empty()}function Bi(e=window.getSelection()){if(!e||!e.rangeCount)return!0;const t=e.getRangeAt(0);return!t.toString()||!t.START_TO_END}class Ri{constructor(e,t,s,i,n,a){this.attachTo=e,this.chat=t,this.appMessagesManager=s,this.appChatsManager=i,this.appPeersManager=n,this.appPollsManager=a,this.onSendScheduledClick=()=>{this.chat.selection.isSelecting?this.chat.selection.selectionSendNowBtn.click():new ji(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(Bi()){Oe((this.chat.selection.isSelecting?[...this.chat.selection.selectedMids].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=()=>{Oe(this.target.href)},this.onCopyLinkClick=()=>{const e=this.appPeersManager.getPeerUsername(this.peerId),t=this.appMessagesManager.getServerMessageId(this.mid);let s,i="https://t.me/";e?(i+=e+"/"+t,s="LinkCopied"):(i+="c/"+Math.abs(this.peerId)+"/"+t,s="LinkCopiedPrivateInfo"),Be(f.default.format(s,!0)),Oe(i)},this.onPinClick=()=>{new Di(this.peerId,this.mid)},this.onUnpinClick=()=>{new Di(this.peerId,this.mid,!0)},this.onRetractVote=()=>{this.appPollsManager.sendVote(this.message,[])},this.onStopPoll=()=>{this.appPollsManager.stopPoll(this.message)},this.onForwardClick=()=>{this.chat.selection.isSelecting?this.chat.selection.selectionForwardBtn.click():new bi(this.peerId,this.isTargetAGroupedItem?[this.mid]:this.chat.getMidsByMid(this.mid))},this.onSelectClick=()=>{this.chat.selection.toggleByBubble(Object(Qe.a)(this.target,"grouped-item")||Object(Qe.a)(this.target,"bubble"))},this.onClearSelectionClick=()=>{this.chat.selection.cancelSelection()},this.onDeleteClick=()=>{this.chat.selection.isSelecting?this.chat.selection.selectionDeleteBtn.click():new Oi(this.peerId,this.isTargetAGroupedItem?[this.mid]:this.chat.getMidsByMid(this.mid),this.chat.type)};const o=e=>{let s,i;this.init&&(this.init(),this.init=null);try{i=Object(Qe.a)(e.target,"bubble-content-wrapper"),s=i?i.parentElement:Object(Qe.a)(e.target,"bubble")}catch(e){}if(!s)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(t.selection.isSelecting&&!i){const e=this.chat.getMidsByMid(n);if(e.length>1){const s=t.selection.selectedMids.has(n)?n:e.find(e=>t.selection.selectedMids.has(e));s&&(n=s)}}this.isSelectable=this.chat.selection.canSelectBubble(s),this.peerId=this.chat.peerId,this.target=e.target,this.isTextSelected=!Bi(),this.isAnchorTarget="A"===this.target.tagName&&"_blank"===this.target.target;const a=Object(Qe.a)(this.target,"grouped-item");this.isTargetAGroupedItem=!!a,this.mid=a?+a.dataset.mid:n,this.message=this.chat.getMessage(this.mid),this.buttons.forEach(e=>{let s;s=!(t.selection.isSelecting&&!e.withSelection)&&(i||l.isTouchSupported?e.verify():e.notDirect&&e.verify()&&e.notDirect()),e.element.classList.toggle("hide",!s)});const o=s.classList.contains("is-in")?"left":"right";Object(K.e)(e.touches?e.touches[0]:e,this.element,o),Object(K.d)(this.element,()=>{this.peerId=this.mid=0,this.target=null})};l.isTouchSupported?(Object(F.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(re.a)(e),o(e.changedTouches?e.changedTouches[0]:e))},{listenerSetter:this.chat.bubbles.listenerSetter}),Object(K.a)(e,s=>{if(t.selection.isSelecting)return;document.body.classList.add("no-select"),e.addEventListener("touchend",e=>{Object(re.a)(e),document.body.classList.remove("no-select")},{once:!0,capture:!0}),_i();const i=Object(Qe.a)(s.target,"grouped-item")||Object(Qe.a)(s.target,"bubble");i&&t.selection.toggleByBubble(i)},this.chat.bubbles.listenerSetter)):Object(K.a)(e,o,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.chat.selection.selectedMids.has(this.mid)&&!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.canWriteToPeer(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},{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:()=>this.chat.selection.selectedMids.has(this.mid)&&!![...this.chat.selection.selectedMids].find(e=>!!this.chat.getMessage(e).message),notDirect:()=>!0,withSelection:!0},{icon:"copy",text:"CopyLink",onClick:this.onCopyAnchorLinkClick,verify:()=>this.isAnchorTarget,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:()=>{d.a.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;return t&&t.type&&!["gif","photo","video","sticker"].includes(t.type)}},{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.chat.selection.selectedMids.has(this.mid)&&!this.chat.selection.selectionForwardBtn.hasAttribute("disabled"),notDirect:()=>!0,withSelection:!0},{icon:"select",text:"Message.Context.Select",onClick:this.onSelectClick,verify:()=>!this.message.action&&!this.chat.selection.selectedMids.has(this.mid)&&this.isSelectable,notDirect:()=>!0,withSelection:!0},{icon:"select",text:"Message.Context.Selection.Clear",onClick:this.onClearSelectionClick,verify:()=>this.chat.selection.selectedMids.has(this.mid),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.chat.selection.selectedMids.has(this.mid)&&!this.chat.selection.selectionDeleteBtn.hasAttribute("disabled"),notDirect:()=>!0,withSelection:!0}],this.element=as(this.buttons,this.chat.bubbles.listenerSetter),this.element.id="bubble-contextmenu",this.element.classList.add("contextmenu"),this.chat.container.append(this.element)}}var Hi=s(122),Ni=s.n(Hi),Ui=s(115),zi=s(120),Wi=s(89),qi=s(65);const Vi={keywords:{},version:0,langCode:li.a.langPackCode};class Gi{constructor(){this.keywordLangPacks={},this.indexedLangPacks={},this.getKeywordsPromises={}}getEmojiKeywords(e=li.a.langPackCode){const t=this.getKeywordsPromises[e];if(t)return t;const s="emojiKeywords_"+e;return this.getKeywordsPromises[e]=qi.a.get(s).then(t=>(Object(zi.a)(t)||(t={}),Object(A.k)(Vi,t),t.langCode=e,this.keywordLangPacks[e]=t,He.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 qi.a.set({[s]:t}),t},()=>t)))}getBothEmojiKeywords(){const e=[this.getEmojiKeywords()];return f.default.lastRequestedLangCode!==li.a.langPackCode&&e.push(this.getEmojiKeywords(f.default.lastRequestedLangCode)),this.recent||e.push(this.getRecentEmojis()),Promise.all(e)}indexEmojis(){this.index||(this.index=new Wi.a(!1,!1));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(Gi.POPULAR_EMOJI).slice(0,36);return t=Array.from(new Set(t)),t}getRecentEmojis(){return this.getRecentEmojisPromise?this.getRecentEmojisPromise:this.getRecentEmojisPromise=p.default.getState().then(e=>this.recent=Array.isArray(e.recentEmoji)?e.recentEmoji:[])}pushRecentEmoji(e){this.getRecentEmojis().then(t=>{t.findAndSplice(t=>t===e),t.unshift(e),t.length>36&&(t.length=36),p.default.pushToState("recentEmoji",t)})}}Gi.POPULAR_EMOJI=["😂","😘","❤️","😍","😊","😁","👍","☺️","😔","😄","😭","💋","😒","😳","😜","🙈","😉","😃","😢","😝","😱","😡","😏","😞","😅","😚","🙊","😌","😀","😋","😆","👌","😐","😕"];const Ki=new Gi;Z.a&&(Z.a.appEmojiManager=Ki);var Qi=Ki,$i=s(103);const Yi=new Set;function Xi(e,t,s=!1,i=!1){const n=document.createElement("span");let o;if(n.classList.add("super-emoji"),i&&!q.a.emojiSupported?o=q.a.wrapSingleEmoji(e):(e=q.a.fixEmoji(e),o=q.a.wrapEmojiText(e)),n.innerHTML=o,n.children.length>1){const e=n.firstElementChild;n.innerHTML="",n.append(e)}if(n.firstElementChild&&!q.a.emojiSupported){const e=n.firstElementChild;e.setAttribute("loading","lazy");const t=e.src;if(!Yi.has(t)){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(Re.c)(()=>{a.default.settings.animationsEnabled&&(e.style.opacity="",s.style.opacity=""),n.classList.remove("empty"),Yi.add(t)})},{once:!0}),n.append(s)}}s?t.prepend(n):t.appendChild(n)}function Ji(e){return 3===e.nodeType?e.nodeValue:("SPAN"===e.tagName&&!e.classList.contains("emoji")&&e.firstElementChild&&(e=e.firstElementChild),e.getAttribute("alt")||e.innerText)}class Zi{constructor(){this.onContentClick=e=>{Object(re.a)(e);let t=e.target;if("SPAN"!==t.tagName||t.classList.contains("emoji")){if("DIV"===t.tagName)return}else{if(t=Object(Qe.a)(t,"super-emoji"),!t)return;t=t.firstChild}const s=l.isTouchSupported?void 0:fn.getSavedRange();let i;s&&(i=document.getSelection(),i.removeAllRanges(),i.addRange(s));const n=q.a.emojiSupported?3===t.nodeType?t.nodeValue:t.innerHTML:t.outerHTML;document.activeElement&&("INPUT"===document.activeElement.tagName||document.activeElement.hasAttribute("contenteditable"))||s?document.execCommand("insertHTML",!0,n):da.chat.input.messageInput.innerHTML+=n;const a=Ji(t);Array.from(this.recentItemsDiv.children).forEach((e,t)=>{const s=Ji(e);a===s&&e.remove()}),Xi(a,this.recentItemsDiv,!0),Qi.pushRecentEmoji(a),this.recentItemsDiv.parentElement.classList.remove("hide");const o=new Event("input",{bubbles:!0,cancelable:!0});da.chat.input.messageInput.dispatchEvent(o)}}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 $i.a.Emoji){const i=""+$i.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(f.i18n)(s));const a=document.createElement("div");a.classList.add("super-emojis"),i.append(n,a),e.forEach(e=>{Xi(e.split("-").reduce((e,t)=>e+String.fromCodePoint(parseInt(t,16)),""),a,!1)}),t[s]=i});const i=this.content.previousElementSibling,n=this.scroll=new g.b(this.content,"EMOJI"),a=Object(K.f)(this.content,!0);Promise.all([Object(Re.d)(200),Qi.getRecentEmojis()]).then(([s,i])=>{a.remove(),this.recentItemsDiv=t["Emoji.Recent"].querySelector(".super-emojis");for(const e of i)Xi(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.stickyIntersector=gn.menuOnClick(i,n),this.init=null}onClose(){}}var en=s(67),tn=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 sn{constructor(e,t,s){this.element=e,this.group=t,this.scrollable=s,this.scrollPromise=Promise.resolve(),this.processVisibleDiv=e=>{if(e.querySelector("video"))return;this.lazyLoadQueue.push({div:e,load:()=>{const t=e.dataset.docId,s=d.a.getDoc(t);return this.scrollPromise.then(()=>{const t=Ut({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();h.a.getAnimations(t).forEach(e=>{h.a.checkAnimation(e,!0,!0)})},0),this.lazyLoadQueue.intersector.isVisible(e)||this.processInvisibleDiv(e)}),t})}})},this.processInvisibleDiv=e=>tn(this,void 0,void 0,(function*(){return this.scrollPromise.then(()=>tn(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 new Promise(e=>{window.requestAnimationFrame(()=>window.requestAnimationFrame(e))})),!this.lazyLoadQueue.intersector.isVisible(e)&&t){t.remove(),t.src="",t.load();h.a.getAnimations(t).forEach(e=>{h.a.checkAnimation(e,!0,!0)})}})))})),this.lazyLoadQueue=new G.c(void 0,(e,t)=>{t?this.processVisibleDiv(e):this.processInvisibleDiv(e)});let i=0;s.container.addEventListener("scroll",()=>{i?clearTimeout(i):this.scrollPromise=Object(o.a)(),i=window.setTimeout(()=>{i=0,this.scrollPromise.resolve()},150)})}add(e){var t;let s=e.w,i=e.h;i<100&&(s*=100/i,i=100);const n=Math.min(300,400,s),a=Object(en.a)(s,i,n,100),o=document.createElement("div");o.classList.add("gif","fade-in-transition"),o.style.width=a.width+"px",o.style.opacity="0",o.dataset.docId=e.id,this.element.append(o),this.lazyLoadQueue.observe(o);const r=d.a.getThumb(e,!1);let l;!!r&&(l=new Image,r.cacheContext.url||r.promise.then(()=>{l.src=r.cacheContext.url}));const c=()=>{l&&(o.append(l),o.style.opacity="")};(null===(t=null==r?void 0:r.cacheContext)||void 0===t?void 0:t.url)?Object(me.a)(l,r.cacheContext.url,c):c()}}class nn{init(){this.content=document.getElementById("content-gifs");const e=this.content.firstElementChild;e.addEventListener("click",gn.onMediaClick);const t=new g.b(this.content,"GIFS"),s=new sn(e,mn,t),i=Object(K.f)(this.content,!0);He.a.invokeApi("messages.getSavedGifs",{hash:0}).then(e=>{"messages.savedGifs"===e._&&e.gifs.forEach((t,i)=>{e.gifs[i]=t=d.a.saveDoc(t),s.add(t)}),i.remove()}),fn.addLazyLoadQueueRepeat(s.lazyLoadQueue,s.processInvisibleDiv),this.init=null}onClose(){}}var an=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 on{constructor(e,t){this.regularLazyLoadQueue=e,this.group=t,this.animatedDivs=new Set,this.checkAnimationContainer=(e,t)=>{h.a.getAnimations(e).forEach(e=>{t?h.a.checkAnimation(e,!1):h.a.checkAnimation(e,!0,!0)})},this.processVisibleDiv=e=>{const t=e.dataset.docId,s=d.a.getDoc(t),i=r.b.active.esgSticker.width,n=Vt({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=d.a.getDoc(t);this.checkAnimationContainer(e,!1),e.innerHTML="",this.renderSticker(s,e)},this.lazyLoadQueue=new G.b(void 0,(e,t)=>{t||this.processInvisibleDiv(e)})}renderSticker(e,t,s){return t||((t=document.createElement("div")).classList.add("grid-item","super-sticker"),2===e.sticker&&(this.animatedDivs.add(t),this.lazyLoadQueue.observe({div:t,load:this.processVisibleDiv}))),Vt({doc:e,div:t,lazyLoadQueue:this.regularLazyLoadQueue,group:this.group,onlyThumb:2===e.sticker,loadPromises:s}),t}}class rn{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){var s;return an(this,void 0,void 0,(function*(){const i=document.createElement("div");i.classList.add("sticker-category");const n=document.createElement("button");n.classList.add("btn-icon","menu-horizontal-div-item"),this.stickerSets[e.id]={stickers:i,tab:n},t?this.menu.insertBefore(n,this.menu.firstElementChild.nextSibling):this.menu.append(n);const a=Rt.getStickerSet(e);this.categoryPush(i,q.a.wrapEmojiText(e.title),a.then(e=>e.documents),t);const o=yield a;(null===(s=o.set.thumbs)||void 0===s?void 0:s.length)?gn.lazyLoadQueue.push({div:n,load:()=>{const e=Rt.getStickerSetThumbDownloadOptions(o.set),t=ee.a.download(e);if(o.set.pFlags.animated)return t.then(Y.b).then(e=>{X.b.loadAnimationWorker({container:n,loop:!0,autoplay:!1,animationData:e,width:32,height:32,needUpscale:!0},mn)});{const e=new Image;return t.then(t=>{Object(me.a)(e,URL.createObjectURL(t),()=>{n.append(e)})})}}}):"documentEmpty"!==o.documents[0]._&&Vt({doc:o.documents[0],div:n,group:mn,lazyLoadQueue:gn.lazyLoadQueue})}))}init(){this.content=document.getElementById("content-stickers"),this.recentDiv=document.createElement("div"),this.recentDiv.classList.add("sticker-category");let e=this.content.previousElementSibling;this.menu=e.firstElementChild;let t=new g.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",gn.onMediaClick),this.scroll=new g.b(this.content,"STICKERS"),this.scroll.setVirtualContainer(this.stickersDiv),this.stickyIntersector=gn.menuOnClick(this.menu,this.scroll,t);const s=Object(K.f)(this.content,!0);Promise.all([Rt.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(f.i18n)("Stickers.Recent"))}),Rt.getAllStickers().then(e=>{s.remove();for(let t of e.sets)this.renderStickerSet(t)})]).finally(()=>{this.mounted=!0}),this.superStickerRenderer=new on(gn.lazyLoadQueue,mn),fn.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 ln=new class{constructor(){this.inlineResults={}}getInlineResults(e,t,s="",i="",n){return He.a.invokeApi("messages.getInlineBotResults",{bot:m.a.getUserInput(t),peer:U.a.getInputPeerById(e),query:s,geo_point:n&&{_:"inputGeoPoint",lat:n.lat,long:n.long}||void 0,offset:i},{stopTime:-1,noErrorBox:!0}).then(e=>{const t=e.query_id;return e.results.forEach(e=>{const s=t+"_"+e.id;"botInlineMediaResult"===e._&&(e.document&&(e.document=d.a.saveDoc(e.document)),e.photo&&(e.photo=z.a.savePhoto(e.photo))),this.inlineResults[s]=e}),e})}callbackButtonClick(e,t,s){return He.a.invokeApi("messages.getBotCallbackAnswer",{peer:U.a.getInputPeerById(e),msg_id:i.a.getServerMessageId(t),data:s.data},{timeout:1,stopTime:-1,noErrorBox:!0}).then(e=>{"string"==typeof e.message&&e.message.length&&Be(q.a.wrapRichText(e.message,{noLinks:!0,noLinebreaks:!0}))})}},cn=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 dn extends P{constructor(){super(...arguments),this.nextOffset="",this.loadedAll=!1,this.onGifsClick=e=>{const t=Object(Qe.a)(e.target,"gif");if(!t)return;const s=t.dataset.docId;da.chat.input.sendMessageWithDocument(s)?r.b.isMobile&&St.onCloseBtnClick():console.warn("got no doc by id:",s)}}init(){this.container.id="search-gifs-container",this.inputSearch=new L("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(F.b)(this.gifsDiv,this.onGifsClick,{listenerSetter:this.listenerSetter}),this.scrollable.append(this.gifsDiv),this.masonry=new sn(this.gifsDiv,"GIFS-SEARCH",this.scrollable)}onClose(){this.scrollable.onScrolledBottom=()=>{}}onCloseAfterTimeout(){return this.reset(),this.gifsDiv.innerHTML="",h.a.checkAnimations(void 0,"GIFS-SEARCH"),this.inputSearch.remove(),super.onCloseAfterTimeout()}reset(){this.searchPromise=null,this.nextOffset="",this.loadedAll=!1,this.masonry.lazyLoadQueue.clear()}open(){const e=super.open();return St.toggleSidebar(!0).then(()=>{this.search("",!0),this.scrollable.onScrolledBottom=()=>{this.search(this.inputSearch.value,!1)}}),e}search(e,t=!0){return cn(this,void 0,void 0,(function*(){if(!this.searchPromise&&!this.loadedAll){this.gifBotPeerId||(this.gifBotPeerId=(yield m.a.resolveUsername("gif")).id);try{this.searchPromise=ln.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 hn extends P{init(){this.container.id="stickers-container",this.container.classList.add("chatlist-container"),this.lazyLoadQueue=new G.d,this.inputSearch=new L("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(F.b)(this.setsDiv,e=>{const t=Object(Qe.a)(e.target,"sticker-set-sticker");if(t){const e=t.dataset.docId;return void da.chat.input.sendMessageWithDocument(e)}const s=Object(Qe.a)(e.target,"sticker-set");if(!s)return;const i=s.dataset.stickerSet,n=s.dataset.access_hash,a=Object(Qe.a)(e.target,"sticker-set-button");a?(e.preventDefault(),e.cancelBubble=!0,a.setAttribute("disabled","true"),Rt.getStickerSet({id:i,access_hash:n}).then(e=>{Rt.toggleStickerSet(e.set).then(t=>{t&&(a.textContent="",a.append(Object(f.i18n)(e.set.installed_date?"Stickers.SearchAdded":"Stickers.SearchAdd")),a.classList.toggle("gray",!!e.set.installed_date))}).finally(()=>{a.removeAttribute("disabled")})})):Rt.getStickerSet({id:i,access_hash:n}).then(e=>{new fi(e.set).show()})},{listenerSetter:this.listenerSetter})}onCloseAfterTimeout(){return this.setsDiv.innerHTML="",h.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">${q.a.wrapEmojiText(e.title)}</div>\n `;const n=document.createElement("div");n.classList.add("sticker-set-count"),n.append(Object(f.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(f.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)}Rt.getStickerSet(e).then(e=>{for(let t=0;t<r;++t){const s=o.children[t],i=e.documents[t];"documentEmpty"!==i._&&Vt({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 St.toggleSidebar(!0).then(()=>{this.renderFeatured()}),e}renderFeatured(){return Rt.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(ve.c)(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()}),h.a.checkAnimations(void 0,"STICKERS-SEARCH"),t}search(e){return e?Rt.searchStickerSets(e,!1).then(t=>{this.inputSearch.value===e&&(t=this.filterRendered(e,t)).forEach(e=>{this.renderSet(e.set)})}):this.renderFeatured()}}var un=s(2),pn=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 mn="emoticons-dropdown";class gn{constructor(){this.tabId=-1,this.events={onClose:[],onCloseAfter:[],onOpen:[],onOpenAfter:[]},this.forceClose=!1,this.onMouseOut=e=>{if(clearTimeout(this.displayTimeout),!this.element.classList.contains("active"))return;const t=e.toElement;t&&Object(Qe.a)(t,"emoji-dropdown")||(this.displayTimeout=window.setTimeout(()=>{this.toggle(!1)},200))},this.onSelectTabClick=e=>{this.tabId!==e&&(h.a.checkAnimations(!0,mn),this.tabId=e,this.searchButton.classList.toggle("hide",0===this.tabId),this.deleteBtn.classList.toggle("hide",0!==this.tabId))},this.checkRights=()=>{const e=da.chat.peerId,t=this.tabsEl.children,s=Array.from(t),i=e>0||D.a.hasRights(e,"send_stickers");s[2].toggleAttribute("disabled",!i);const n=e>0||D.a.hasRights(e,"send_gifs");s[3].toggleAttribute("disabled",!n);const a=this.tabsEl.querySelector(".active");!a||1===Object(Xt.a)(a)||i&&n||this.selectTab(0,!1)},this.toggle=e=>pn(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(l.isTouchSupported&&t&&Object(un.a)()&&(yield Object(Re.d)(100)),this.element.parentElement!==da.chat.input.chatInput&&da.chat.input.chatInput.append(this.element),this.element.style.display&&void 0===e||e){this.events.onOpen.forEach(e=>e());const e=document.getSelection();e.rangeCount&&document.activeElement===da.chat.input.messageInput?this.savedRange=e.getRangeAt(0):this.savedRange=void 0,gn.lazyLoadQueue.lock(),h.a.lockIntersectionGroup(mn),this.element.style.display="",this.element.offsetLeft,this.element.classList.add("active"),clearTimeout(this.displayTimeout),this.displayTimeout=window.setTimeout(()=>{h.a.unlockIntersectionGroup(mn),gn.lazyLoadQueue.unlock(),gn.lazyLoadQueue.refresh(),this.forceClose=!1,this.container.classList.remove("disable-hover"),this.events.onOpenAfter.forEach(e=>e())},l.isTouchSupported?0:200)}else this.events.onClose.forEach(e=>e()),gn.lazyLoadQueue.lock(),h.a.lockIntersectionGroup(mn),h.a.checkAnimations(!0,mn),this.element.classList.remove("active"),clearTimeout(this.displayTimeout),this.displayTimeout=window.setTimeout(()=>{this.element.style.display="none",h.a.unlockIntersectionGroup(mn),gn.lazyLoadQueue.unlock(),gn.lazyLoadQueue.refresh(),this.forceClose=!1,this.container.classList.remove("disable-hover"),this.events.onCloseAfter.forEach(e=>e()),this.savedRange=void 0},l.isTouchSupported?0:200)})),this.element=document.getElementById("emoji-dropdown")}attachButtonListener(e,t){let s=!0;l.isTouchSupported?Object(F.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(){this.emojiTab=new Zi,this.stickersTab=new rn,this.gifsTab=new nn,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(V.a)(this.tabsEl,this.container,this.onSelectTabClick,()=>{const e=this.tabs[this.tabId];e.init&&e.init(),e.onCloseAfterTimeout&&e.onCloseAfterTimeout(),h.a.checkAnimations(!1,mn)}),this.searchButton=this.element.querySelector(".emoji-tabs-search"),this.searchButton.addEventListener("click",()=>{1===this.tabId?St.isTabExists(hn)||new hn(St).open():St.isTabExists(dn)||new dn(St).open()}),this.deleteBtn=this.element.querySelector(".emoji-tabs-delete"),this.deleteBtn.addEventListener("click",e=>{var t;const s=da.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});da.chat.input.messageInput.dispatchEvent(i),Object(re.a)(e)}),this.tabsEl.children[1].click(),this.tabs[0].init&&this.tabs[0].init(),a.default.addEventListener("peer_changed",this.checkRights),this.checkRights(),l.isTouchSupported||(this.element.onmouseout=this.onMouseOut,this.element.onmouseover=e=>{this.forceClose||clearTimeout(this.displayTimeout)})}addLazyLoadQueueRepeat(e,t){this.events.onClose.push(()=>{e.lock()}),this.events.onCloseAfter.push(()=>{const s=e.intersector.getVisible();for(const e of s)t(e);e.intersector.clearVisible()}),this.events.onOpenAfter.push(()=>{e.unlockAndRefresh()})}getSavedRange(){return this.savedRange}}gn.lazyLoadQueue=new G.d,gn.menuOnClick=(e,t,s)=>{let i=0,n=-1;const a=t=>t!==i&&(e.children[i].classList.remove("active"),e.children[t].classList.add("active"),i=t,!0),o=new vi(t.container,(i,o)=>{if(Math.abs(n-t.container.scrollTop)<=1)return;n=-1;const r=Object(Xt.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(Qe.a)(s,"menu-horizontal-div-item"),!s)return;const i=Object(Xt.a)(s);if(!a(i))return;const o=(t.splitUp||t.container).children[i].offsetTop+1;t.container.scrollTop=n=o}),o},gn.onMediaClick=(e,t=!1)=>{let s=e.target;if(s=Object(Ve.a)(s,"DIV"),!s)return;const i=s.dataset.docId;i&&(da.chat.input.sendMessageWithDocument(i,void 0,t)?bn.container&&(bn.forceClose=!0,bn.container.classList.add("disable-hover"),bn.toggle(!1)):console.warn("got no doc by id:",i))};const bn=new gn;Z.a.emoticonsDropdown=bn;var fn=bn;class vn{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=as(this.sendMenuButtons,e.listenerSetter),this.sendMenu.classList.add("menu-send",e.openSide),Object(K.a)(e.onContextElement,t=>{e.onOpen&&!e.onOpen()||(this.sendMenuButtons.forEach(e=>{e.element.classList.toggle("hide",!e.verify())}),Object(re.a)(t),Object(K.d)(this.sendMenu))},e.listenerSetter)}setPeerId(e){this.type=e===a.default.myId?"reminder":"schedule"}}var yn=s(91),wn=s(104);class Ln extends Ue.b{constructor(e){if(super("popup-create-poll popup-new-media",null,{closable:!0,withConfirm:"NewPoll.Create",body:!0}),this.chat=e,this.tempId=0,this.onSubmitClick=()=>{this.send()},this.onInput=e=>{const t=e.target,s=Object(Ve.a)(t,"LABEL"),i=Object(wn.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(Ve.a)(t,"LABEL"),i=Object(Xt.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);f.default.weakMap.get(e.label.firstElementChild).update()}),this.handleChange()},Object(f._i18n)(this.title,"NewPoll"),this.questionInputField=new w.b({placeholder:"AskAQuestion",label:"AskAQuestion",name:"question",maxLength:255}),this.questionInputField.input.addEventListener("input",()=>{this.handleChange()}),this.optionInputFields=[],"scheduled"!==this.chat.type){const e=new vn({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(f._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(f._i18n)(n,"Settings"),this.chat.appPeersManager.isBroadcast(this.chat.peerId)||(this.anonymousCheckboxField=new Te.a({text:"NewPoll.Anonymous",name:"anonymous"}),this.anonymousCheckboxField.input.checked=!0,i.append(this.anonymousCheckboxField.label)),this.multipleCheckboxField=new Te.a({text:"NewPoll.MultipleChoice",name:"multiple"}),this.quizCheckboxField=new Te.a({text:"NewPoll.Quiz",name:"quiz"}),this.multipleCheckboxField.input.addEventListener("change",()=>{const e=this.multipleCheckboxField.input.checked;this.quizCheckboxField.input.toggleAttribute("disabled",e)}),this.quizCheckboxField.input.addEventListener("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(f._i18n)(o,"AccDescrQuizExplanation");const r=document.createElement("hr"),l=document.createElement("div");l.classList.add("poll-create-questions"),this.quizSolutionField=new w.b({placeholder:"NewPoll.Explanation.Placeholder",label:"NewPoll.Explanation.Placeholder",name:"solution",maxLength:200}),this.questionInputField.input.addEventListener("input",()=>{this.handleChange()});const c=document.createElement("div");c.classList.add("subtitle"),Object(f._i18n)(c,"AddAnExplanationInfo"),l.append(this.quizSolutionField.container,c),a.push(r,o,l),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),this.btnConfirm.addEventListener("click",this.onSubmitClick),this.scrollable=new g.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(yn.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(yn.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(yn.a)(this.quizSolutionField.input);if("scheduled"===this.chat.type&&!e)return void this.chat.input.scheduleSending(()=>{this.send(!0)});this.btnClose.click(),this.btnConfirm.removeEventListener("click",this.onSubmitClick);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 w.b({placeholder:"NewPoll.OptionsAddOption",label:"NewPoll.OptionLabel",labelOptions:[t],name:"question-"+e,maxLength:100});s.input.addEventListener("input",this.onInput);const i=new je({text:"",name:"question"});i.main.append(s.container),s.input.addEventListener("click",re.a),i.label.classList.add("hidden-widget"),i.input.disabled=!0,this.quizCheckboxField.input.checked||i.label.classList.remove("radio-field"),i.input.addEventListener("change",()=>{if(i.input.checked){const e=Object(Xt.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),n.addEventListener("click",this.onDeleteClick,{once:!0}),this.questions.append(i.label),this.scrollable.scrollIntoViewNew(this.questions.lastElementChild,"center"),this.optionInputFields.push(s)}}function Sn(e){if("Enter"===e.key&&!c.isMobile&&!e.isComposing){if("enter"===a.default.settings.sendShortcut){if(e.shiftKey||e.ctrlKey||e.metaKey)return;return!0}{const t=c.isApple?e.metaKey:e.ctrlKey;if(e.shiftKey||(c.isApple?e.ctrlKey:e.metaKey))return;if(t)return!0}}return!1}function Mn(e){if(!l.isTouchSupported)if(e.focus(),void 0!==window.getSelection&&void 0!==document.createRange){var t=document.createRange();t.selectNodeContents(e),t.collapse(!1);var s=window.getSelection();s.removeAllRanges(),s.addRange(t)}else if(void 0!==document.body.createTextRange){var i=document.body.createTextRange();i.moveToElementText(e),i.collapse(!1),i.select()}}class En extends Ue.b{constructor(e,t,s){if(super("popup-send-photo popup-new-media",null,{closable:!0,withConfirm:"Modal.Send"}),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(),Mn(this.input)}Sn(e)&&this.btnConfirm.click()},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(oe.d)(t).then(()=>{i.width=t.videoWidth,i.height=t.videoHeight,i.duration=Math.floor(t.duration),n.append(t),Object(oe.b)(t).then(e=>{i.thumbBlob=e,i.thumbURL=URL.createObjectURL(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||"",size:e.size,type:t?"photo":"doc"},r=ee.a.getCacheContext(o);r.url=i.objectURL,r.downloaded=e.size;const l=Wt({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,this.btnConfirm.addEventListener("click",()=>this.send()),"scheduled"!==this.chat.type){const e=new vn({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.mediaContainer=document.createElement("div"),this.mediaContainer.classList.add("popup-photo");const i=new g.b(null);i.container.append(this.mediaContainer),this.inputField=new w.b({placeholder:"PreviewSender.CaptionPlaceholder",label:"Caption",name:"photo-caption",maxLength:1024,showLengthOn:80}),this.input=this.inputField.input,this.inputField.value=this.wasInputValue=this.chat.input.messageInputField.value,this.chat.input.messageInputField.value="",this.container.append(i.container),t.length>1&&(this.groupCheckboxField=new Te.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.groupCheckboxField.input.addEventListener("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>1024)return void Be(f.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,a=n.sendSilent,o=n.scheduleDate;if(s.sendFileDetails.length>1&&s.group)for(let e=0;e<s.sendFileDetails.length;){let l=s.sendFileDetails[e].file.type.split("/")[0];for(var r=0;r<10&&e<s.sendFileDetails.length;++e,++r){if(l!==s.sendFileDetails[e].file.type.split("/")[0])break}const c=Object.assign({},s);c.sendFileDetails=s.sendFileDetails.slice(e-r,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:a,scheduleDate:o,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:a,scheduleDate:o,clearDraft:!0}),t="");s.sendFileDetails.map(e=>{const r=this.chat.appMessagesManager.sendFile(i,e.file,Object.assign({isMedia:s.isMedia,caption:t,replyToMsgId:n.replyToMsgId,threadId:this.chat.threadId,silent:a,scheduleDate:o,clearDraft:!0},e));return t="",r});n.replyToMsgId=this.chat.threadId}n.onMessageSent()}attachFiles(e){const t=this.container,s=this.willAttach;e=e.filter(e=>"media"!==s.type||["image/","video/"].find(t=>0===e.type.indexOf(t))),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(f.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)),Kt({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(en.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")||(document.body.addEventListener("keydown",this.onKeyDown),this.onClose=()=>{this.wasInputValue&&(this.chat.input.messageInputField.value=this.wasInputValue),document.body.removeEventListener("keydown",this.onKeyDown)},this.show())})}}var In=s(75);function Cn({list:e,type:t,onSelect:s,once:i,waitForKey:n}){const a=new Set(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"]);let o;const r=()=>o||e.querySelector(".active")||e.firstElementChild,l=(e,s)=>{if(o===e)return;let i=!1;o&&(i=!0,o.classList.remove("active")),o=e,o.classList.add("active"),i&&u&&s&&Object(Ke.b)(u,o,"center",void 0,void 0,void 0,100,"x"===t?"x":"y")},c=(t,s)=>{let i;return i=s?t.nextElementSibling||e.firstElementChild:t.previousElementSibling||e.lastElementChild,i};let d;d="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):c(t,"ArrowRight"===s):(e,t)=>c(e,"ArrowRight"===t||"ArrowDown"===t);let h=t=>{if(a.has(t.key)){if(Object(re.a)(t),e.childElementCount>1){let e=r();e=d(e,t.key),l(e,!0)}}else"Enter"===t.key&&(Object(re.a)(t),g(r()))};const u=Object(Qe.a)(e,"scrollable");e.classList.add("navigable-list");const p=t=>{const s=Object(In.a)(t.target,e);s&&l(s,!1)},m=t=>{Object(re.a)(t);const s=Object(In.a)(t.target,e);s&&(l(s,!1),g(r()))},g=e=>{const t=s(e);(void 0!==t?!t:i)&&b()},b=()=>{document.removeEventListener("keydown",h,{capture:!0}),e.removeEventListener("mousemove",p),Object(F.c)(e,m)},f=()=>{n||l(e.firstElementChild,!1)};if(n){const e=h;h=t=>{t.key===n&&(Object(re.a)(t),document.removeEventListener("keydown",h,{capture:!0}),h=e,document.addEventListener("keydown",h,{capture:!0,passive:!1}),n=void 0,f())}}else f();return document.addEventListener("keydown",h,{capture:!0,passive:!1}),e.addEventListener("mousemove",p,{passive:!0}),Object(F.b)(e,m),{detach:b,resetTarget:f}}class kn extends E.a{constructor(e){super(!1),this.hidden=!0,this.onVisible=()=>{const e=this.list,{detach:t,resetTarget:s}=Cn({list:e,type:this.listType,onSelect:this.onSelect,once:!0,waitForKey:this.waitForKey});let i;this.resetTarget=s,c.isMobile||(i={type:"autocomplete-helper",onPop:()=>this.toggle(!0),noBlurOnPop:!0},M.a.pushItem(i)),this.addEventListener("hidden",()=>{this.resetTarget=void 0,e.innerHTML="",t(),i&&M.a.removeItem(i)},!0)},Object(A.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?t||this.controller.hideOtherHelpers():(this.controller.hideOtherHelpers(this),this.dispatchEvent("visible")),Object(Et.a)(this.container,"is-visible",!e,a.default.settings.animationsEnabled?200:0,()=>{this.hidden&&this.dispatchEvent("hidden")})):!e&&this.resetTarget&&this.resetTarget())}}class Tn extends kn{constructor(e,t){super({appendTo:e,controller:t,listType:"xy",onSelect:e=>{gn.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&&(r.b.removeEventListener("changeScreen",this.onChangeScreen),this.onChangeScreen=void 0)})}checkEmoticon(e){const t=this.controller.getMiddleware();this.lazyLoadQueue&&this.lazyLoadQueue.clear(),Rt.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).then(t,t)}):Promise.resolve(),i.then(()=>{this.list.replaceWith(s),this.list=s,this.onChangeScreen||(this.onChangeScreen=()=>{const e=this.list.childElementCount*r.b.active.esgSticker.width+(this.list.childElementCount-1);this.list.style.width=e+"px"},r.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 g.b(this.container),this.lazyLoadQueue=new G.d,this.superStickerRenderer=new on(this.lazyLoadQueue,ra)}}const Pn=()=>{const e=new Date;return e.setHours(0,0,0,0),e};class xn extends mi{constructor(e,t){super(e,t,{noButtons:!0,noTitle:!0,closable:!0,withConfirm:!0,minDate:Pn(),maxDate:(()=>{const e=new Date;return e.setFullYear(e.getFullYear()+1),e.setDate(e.getDate()-1),e})(),withTime:!0,showOverflowMonths:!0}),this.element.classList.add("popup-schedule"),this.header.append(this.controlsDiv),this.title.replaceWith(this.monthTitle),this.body.append(this.btnConfirm)}}var An=s(92);function Fn(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(An.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&&q.b.combineSameEntities(r),{value:l,entities:r,caretPos:c}}class On extends kn{constructor(e,t,s,i){super({appendTo:e,controller:t,listType:"x",onSelect:e=>{s.onEmojiSelected(Ji(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 g.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=>{Xi(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 Dn extends kn{constructor(e,t,s,i){super({appendTo:e,controller:t,listType:"y",onSelect:i}),this.className=s,this.container.classList.add(Dn.BASE_CLASS,s)}init(){this.list=document.createElement("div"),this.list.classList.add(Dn.BASE_CLASS+"-list"),this.container.append(this.list),this.scrollable=new g.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=Dn.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=Dn.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 wa;i.classList.add("avatar-30"),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=q.b.wrapEmojiText(e.name):n.append(new $e.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=q.b.wrapEmojiText(e.description),s.append(i)}return s}}Dn.BASE_CLASS="autocomplete-peer-helper",Dn.BASE_CLASS_LIST_ELEMENT=Dn.BASE_CLASS+"-list-element";class jn extends Dn{constructor(e,t,s,i,n){super(e,t,"commands-helper",e=>{const t=e.querySelector(`.${Dn.BASE_CLASS_LIST_ELEMENT}-name`).innerHTML;s.messageInput.innerHTML=t,s.sendMessage()}),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 Wi.a(!1,!1),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 _n{constructor(){this.helpers=new Set,this.middleware=Yt()}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 Bn extends Dn{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();return!(t>0||e.length!==i.length)&&(this.appProfileManager.getMentions(-t,i,s).then(e=>{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)}}class Rn{constructor(e,t,s,i,n,a,o,r,c,d,h){this.chat=e,this.appMessagesManager=t,this.appDocsManager=s,this.appChatsManager=i,this.appPeersManager=n,this.appWebPagesManager=a,this.appImManager=o,this.appDraftsManager=r,this.serverTimeManager=c,this.appNotificationsManager=d,this.appEmojiManager=h,this.lastUrl="",this.lastTimeType=0,this.replyElements={},this.willSendWebPage=null,this.forwardingMids=[],this.forwardingFromPeerId=0,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(re.a)(e),this.recordCanceled=!0,this.recorder.stop(),Ui.a.setKeepAlive(!1)},this.onEmoticonsOpen=()=>{const e=l.isTouchSupported?"flip-icon":"active";this.btnToggleEmoticons.classList.toggle(e,!0)},this.onEmoticonsClose=()=>{const e=l.isTouchSupported?"flip-icon":"active";this.btnToggleEmoticons.classList.toggle(e,!1)},this.scheduleSending=(e=this.sendMessage.bind(this,!0),t=new Date)=>{new xn(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)}).show()},this.prepareDocumentExecute=()=>(this.executedHistory.push(this.messageInput.innerHTML),()=>this.canUndoFromHTML=this.messageInput.innerHTML),this.undoRedo=(e,t,s)=>{Object(re.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.showLinkEditor(),Object(re.a)(e);break}this.applyMarkdown(t[s]),Object(re.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}=Fn(this.messageInputField.input),n=q.b.parseMarkdown(t,s,!0),a=q.b.mergeEntities(s,q.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;this.lastUrl!==s&&(this.lastUrl=s,this.willSendWebPage=null,He.a.invokeApi("messages.getWebPage",{url:s,hash:0}).then(e=>{if("webPage"===(e=this.appWebPagesManager.saveWebPage(e))._){if(this.lastUrl!==s)return;this.setTopInfo("webpage",()=>{},e.site_name||e.title||"Webpage",e.description||e.url||""),delete this.noWebPage,this.willSendWebPage=e}}));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.hide();this.editMsgId||this.saveDraftDebounced(),this.checkAutocomplete(t,i,a),this.updateSendBtn()},this.onEmojiSelected=(e,t)=>{t&&this.insertAtCaret(e,q.b.getEmojiEntityFromEmoji(e))},this.onBtnSendClick=e=>{if(Object(re.a)(e),!this.recorder||this.recording||!this.isInputEmpty()||this.forwardingMids.length||this.editMsgId)this.recording?Date.now()-this.recordStartTime<500?this.onCancelRecordClick():this.recorder.stop():this.sendMessage();else{if(this.chat.peerId<0&&!this.appChatsManager.hasRights(this.chat.peerId,"send_media"))return void Be("Posting media content isn't allowed in this group.");this.chatInput.classList.add("is-locked"),Object(un.a)(),this.recorder.start().then(()=>{this.recordCanceled=!1,this.chatInput.classList.add("is-recording"),this.recording=!0,this.updateSendBtn(),Ui.a.setKeepAlive(!0),this.recordStartTime=Date.now();const e=this.recorder.sourceNode,t=e.context.createAnalyser();e.connect(t),t.fftSize=32;const s=new Uint8Array(t.frequencyBinCount),i=255*s.length;let n=()=>{if(!this.recording)return;t.getByteFrequencyData(s);let e=0;s.forEach(t=>{e+=t});let a=Math.min(1,e/i+.36);this.recordRippleEl.style.transform=`scale(${a})`;let o=Date.now()-this.recordStartTime,r=o%1e3,l=(""+o/1e3).toHHMMSS()+","+("00"+Math.round(r/10)).slice(-2);this.recordTimeEl.innerText=l,window.requestAnimationFrame(n)};n()}).catch(e=>{switch(e.name){case"NotAllowedError":Be("Please allow access to your microphone");break;case"NotReadableError":Be(e.message);break;default:console.error("Recorder start error:",e,e.name,e.message),Be(e.message)}this.chatInput.classList.remove("is-recording","is-locked")})}},this.onHelperCancel=e=>{if(e&&Object(re.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(re.a)(e),Object(Qe.a)(e.target,"reply-wrapper"))if("forward"===this.helperType){if(this.helperWaitingForward)return;this.helperWaitingForward=!0;const e=this.forwardingFromPeerId,t=this.forwardingMids.slice(),s=this.helperFunc;this.clearHelper();let i=!1;new bi(e,t,()=>{i=!0},()=>{this.helperWaitingForward=!1,i||s()})}else"reply"===this.helperType?this.chat.setMessageId(this.replyToMsgId):"edit"===this.helperType&&this.chat.setMessageId(this.editMsgId)},this.listenerSetter=new I}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=Fi();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=B({icon:"arrow_down",className:"bubbles-go-down hide"}),this.inputContainer.append(this.goDownBtn),Object(F.b)(this.goDownBtn,e=>{Object(re.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=k("close reply-cancel");const e=new ge("reply");this.replyElements.titleEl=e.title,this.replyElements.subtitleEl=e.subtitle,this.replyElements.container.append(this.replyElements.cancelBtn,e.container),this.newMessageWrapper=document.createElement("div"),this.newMessageWrapper.classList.add("new-message-wrapper"),this.btnToggleEmoticons=k("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.btnScheduled=k("scheduled",{noRipple:!0}),this.btnScheduled.classList.add("btn-scheduled","hide"),Object(F.b)(this.btnScheduled,e=>{this.appImManager.openScheduled(this.chat.peerId)},{listenerSetter:this.listenerSetter}),this.listenerSetter.add(a.default,"scheduled_new",e=>{const t=e.peerId;this.chat.peerId===t&&this.btnScheduled.classList.remove("hide")}),this.listenerSetter.add(a.default,"scheduled_delete",e=>{const t=e.peerId;this.chat.peerId===t&&this.appMessagesManager.getScheduledMessages(this.chat.peerId).then(e=>{this.btnScheduled.classList.toggle("hide",!e.length)})})),this.attachMenuButtons=[{icon:"image",text:"Chat.Input.Attach.PhotoOrVideo",onClick:()=>{this.fileInput.value="",this.fileInput.setAttribute("accept","image/*, video/*"),this.willAttachType="media",this.fileInput.click()},verify:e=>e>0||this.appChatsManager.hasRights(e,"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=>e>0||this.appChatsManager.hasRights(e,"send_media")},{icon:"poll",text:"Poll",onClick:()=>{new Ln(this.chat).show()},verify:e=>e<0&&this.appChatsManager.hasRights(e,"send_polls")}],this.attachMenu=ls({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.attachMenu,this.recordTimeEl,this.fileInput].filter(Boolean)),this.rowsWrapper.append(this.replyElements.container),this.autocompleteHelperController=new _n,this.stickersHelper=new Tn(this.rowsWrapper,this.autocompleteHelperController),this.emojiHelper=new On(this.rowsWrapper,this.autocompleteHelperController,this,this.appEmojiManager),this.commandsHelper=new jn(this.rowsWrapper,this.autocompleteHelperController,this,this.chat.appProfileManager,this.chat.appUsersManager),this.mentionsHelper=new Bn(this.rowsWrapper,this.autocompleteHelperController,this,this.chat.appProfileManager,this.chat.appUsersManager),this.rowsWrapper.append(this.newMessageWrapper),this.btnCancelRecord=k("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=k("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 vn({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),fn.attachButtonListener(this.btnToggleEmoticons,this.listenerSetter),fn.events.onOpen.push(this.onEmoticonsOpen),fn.events.onClose.push(this.onEmoticonsClose),this.attachMessageInputField(),this.listenerSetter.add(a.default,"settings_updated",()=>{(this.stickersHelper||this.emojiHelper)&&(this.previousQuery=void 0,this.checkAutocomplete()),this.messageInputField&&this.messageInputField.onFakeInput()}),this.listenerSetter.add(a.default,"draft_updated",e=>{const{peerId:t,threadId:s,draft:i}=e;this.chat.threadId===s&&this.chat.peerId===t&&this.setDraft(i)}),this.listenerSetter.add(a.default,"peer_changing",e=>{this.chat===e&&this.saveDraft()});try{this.recorder=new Ni.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 En(this.chat,Array.from(t).slice(),this.willAttachType),this.fileInput.value="")},!1),Object(F.b)(this.btnSend,this.onBtnSendClick,{listenerSetter:this.listenerSetter,touchMouseDown:!0}),this.recorder&&(Object(F.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.recordCanceled)return;const t=(Date.now()-this.recordStartTime)/1e3|0,s=new Blob([e],{type:"audio/ogg"});Ui.a.decode(e,!0).then(e=>{Ui.a.setKeepAlive(!1);let i=this.chat.peerId;this.appMessagesManager.sendFile(i,s,{isVoiceMessage:!0,isMedia:!0,duration:t,waveform:e.waveform,objectURL:e.url,replyToMsgId:this.replyToMsgId,threadId:this.chat.threadId,clearDraft:!0}),this.onMessageSent(!1,!0)})}),Object(F.b)(this.replyElements.cancelBtn,this.onHelperCancel,{listenerSetter:this.listenerSetter}),Object(F.b)(this.replyElements.container,this.onHelperClick,{listenerSetter:this.listenerSetter}),this.saveDraftDebounced=Object(Re.a)(()=>this.saveDraft(),2500,!1,!0)}constructPinnedHelpers(){const e=document.createElement("div");e.classList.add("pinned-container"),this.pinnedControlBtn=Object(C.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 Di(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")}setUnreadCount(){const e=this.appMessagesManager.getDialogOnly(this.chat.peerId),t=null==e?void 0:e.unread_count;this.goDownUnreadBadge.innerText=""+(t||""),this.goDownUnreadBadge.classList.toggle("badge-gray",this.appNotificationsManager.isPeerLocalMuted(this.chat.peerId,!0))}saveDraft(){if(!this.chat.peerId||this.editMsgId||"scheduled"===this.chat.type)return;const{value:e,entities:t}=Object(yn.a)(this.messageInputField.input);let s;(e.length||this.replyToMsgId)&&(s={_:"draftMessage",date:Object(H.h)(!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(){fn.events.onOpen.findAndSplice(e=>e===this.onEmoticonsOpen),fn.events.onClose.findAndSplice(e=>e===this.onEmoticonsClose),this.listenerSetter.removeAll()}cleanup(e=!0){this.chat.peerId||(this.chatInput.style.display="none",this.goDownBtn.classList.add("hide")),_i(),this.lastTimeType=0,this.messageInput&&(this.clearInput(),e&&this.clearHelper())}setDraft(e,t=!0){return!(!Object(wn.a)(this.messageInput)||"scheduled"===this.chat.type)&&(!(!e&&!(e=this.appDraftsManager.getDraft(this.chat.peerId,this.chat.threadId)))&&(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.sendMenu&&this.sendMenu.setPeerId(e),this.messageInput?this.updateMessageInput():this.pinnedControlBtn&&(this.appPeersManager.canPinMessage(this.chat.peerId)?(this.pinnedControlBtn.append(Object(f.i18n)("Chat.Input.UnpinAll")),this.fakePinnedControlBtn.append(Object(f.i18n)("Chat.Input.UnpinAll"))):(this.pinnedControlBtn.append(Object(f.i18n)("Chat.Pinned.DontShow")),this.fakePinnedControlBtn.append(Object(f.i18n)("Chat.Pinned.DontShow"))))}updateMessageInput(){const e=this.appMessagesManager.canWriteToPeer(this.chat.peerId,this.chat.threadId);this.chatInput.classList.add("no-transition"),this.chatInput.classList.toggle("is-hidden",!e),this.chatInput.offsetLeft,this.chatInput.classList.remove("no-transition");const t=this.attachMenuButtons.filter(e=>{const t=e.verify(this.chat.peerId);return e.element.classList.toggle("hide",!t),t});e?(this.messageInput.setAttribute("contenteditable","true"),this.setDraft(void 0,!1),this.messageInput.innerHTML||this.messageInputField.onFakeInput()):this.messageInput.removeAttribute("contenteditable"),this.attachMenu.toggleAttribute("disabled",!t.length),this.updateSendBtn()}attachMessageInputField(){const e=this.messageInputField;this.messageInputField=new w.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.attachMessageInputListeners(),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(Sn(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 Mn(this.messageInput)}),l.isTouchSupported&&Object(F.b)(this.messageInput,e=>{this.appImManager.selectTab(1),fn.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=An.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){const{value:s,caretPos:i,entities:n}=Fn(this.messageInput),a=i>=0?i:s.length,o=s.substr(0,a),r=s.substr(a),l=o.match(Rn.AUTO_COMPLETE_REG_EXP),c=l.index+(l[0].length-l[2].length),d=o.slice(0,c)+e+r,h=q.b.parseEntities(s);q.b.mergeEntities(n,h);const u=t?Math.max(t.length,e.length):e.length,p=[];t&&(p.push(t),t.offset=c),p.push({_:"messageEntityCaret",length:0,offset:c+u});const m=u-l[2].length;n.forEach(e=>{e.offset>=c&&(e.offset+=m)}),q.b.mergeEntities(n,p),this.messageInputField.setValueSilently(q.b.wrapDraftText(d,{entities:n}),!0);const g=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,g),g.remove(),this.onMessageInput()}checkAutocomplete(e,t,s){if(void 0===e){const i=Fn(this.messageInputField.input,!0);e=i.value,t=i.caretPos,s=i.entities}if(-1===t&&(t=e.length),void 0===s){const t=q.b.parseMarkdown(e,s,!0);s=q.b.mergeEntities(s,q.b.parseEntities(t))}const i=(e=e.substr(0,t)).match(Rn.AUTO_COMPLETE_REG_EXP);if(!i)return this.previousQuery=void 0,void this.autocompleteHelperController.hideOtherHelpers();if(this.previousQuery===i[0])return;let n;this.previousQuery=i[0];const o=s[0],r=i[2],l=r[0];if(this.stickersHelper&&a.default.settings.stickers.suggest&&(this.chat.peerId>0||this.appChatsManager.hasRights(this.chat.peerId,"send_stickers"))&&"messageEntityEmoji"===(null==o?void 0:o._)&&o.length===e.length&&!o.offset)n=this.stickersHelper,this.stickersHelper.checkEmoticon(e);else if("@"===l){const e=this.chat.threadId?this.appMessagesManager.getServerMessageId(this.chat.threadId):void 0;this.mentionsHelper.checkQuery(r,this.chat.peerId,e)&&(n=this.mentionsHelper)}else i[1]||"/"!==l?a.default.settings.emoji.suggest&&(e.match(/^\s*:(.+):\s*$/)||(n=this.emojiHelper,this.emojiHelper.checkQuery(r,l))):this.commandsHelper.checkQuery(r,this.chat.peerId)&&(n=this.commandsHelper);this.autocompleteHelperController.hideOtherHelpers(n)}clearInput(e=!0){this.messageInputField.value="",l.isTouchSupported||(this.canRedoFromHTML="",this.undoHistory.length=0,this.executedHistory.length=0,this.canUndoFromHTML="");let t=!1;e&&(t=this.setDraft(void 0,!1))}isInputEmpty(){return Object(wn.a)(this.messageInput)}updateSendBtn(){let e;const t=this.isInputEmpty();e=this.editMsgId?"edit":!this.recorder||this.recording||!t||this.forwardingMids.length?"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)}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,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(yn.a)(this.messageInputField.input);if(this.editMsgId?this.appMessagesManager.editMessage(this.chat.getMessage(this.editMsgId),t,{entities:s,noWebPage:this.noWebPage}):this.appMessagesManager.sendText(this.chat.peerId,t,{entities:s,replyToMsgId:this.replyToMsgId,threadId:this.chat.threadId,noWebPage:this.noWebPage,webPage:this.willSendWebPage,scheduleDate:this.scheduleDate,silent:this.sendSilent,clearDraft:!0}),this.forwardingMids.length){const e=this.forwardingMids.slice(),t=this.forwardingFromPeerId,s=this.chat.peerId,i=this.sendSilent,n=this.scheduleDate;setTimeout(()=>{this.appMessagesManager.forwardMessages(s,t,e,{silent:i,scheduleDate:n})},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";if(!(this.chat.peerId<0)||this.appChatsManager.hasRights(this.chat.peerId,n))return"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=fn.stickersTab)||void 0===i||i.pushRecentSticker(e)),!0):(this.scheduleSending(()=>this.sendMessageWithDocument(e,!0)),!1);Be("Posting media content isn't allowed in this group.")}initMessageEditing(e){const t=this.chat.getMessage(e);let s=q.b.wrapDraftText(t.message,{entities:t.totalEntities});const i=()=>{const n=this.appMessagesManager.wrapMessageForReply(t,void 0,[t.mid]);this.setTopInfo("edit",i,"Editing",void 0,s,t);const a=this.replyElements.container.querySelector(".reply-subtitle");a.textContent="",a.append(n),this.editMsgId=e,s=void 0};i()}initMessagesForward(e,t){const s=()=>{const i=new Set(t.map(t=>{const s=this.appMessagesManager.getMessageByPeer(e,t);return s.fwd_from&&s.fwd_from.from_name&&!s.fromId&&!s.fwdFromId?s.fwd_from.from_name:s.fromId})),n=i.size>1,a=[...i].map(e=>"number"==typeof e?this.appPeersManager.getPeerTitle(e,!0,n):n?e.split(" ")[0]:e),o=a.length<3?a.join(" and "):a[0]+" and "+(a.length-1)+" others",r=this.appMessagesManager.getMessageByPeer(e,t[0]);let l=!0;if(r.grouped_id){const e=this.appMessagesManager.getMidsByMessage(r);(e.length!==t.length||e.find(e=>!t.includes(e)))&&(l=!1)}const c=this.appMessagesManager.wrapMessageForReply(r,void 0,t);if(l||1===t.length){this.setTopInfo("forward",s,o);const e=this.replyElements.container.querySelector(".reply-subtitle");e.textContent="",e.append(c)}else this.setTopInfo("forward",s,o,t.length+" "+(t.length>1?"forwarded messages":"forwarded message"));this.forwardingMids=t.slice(),this.forwardingFromPeerId=e};s()}initMessageReply(e){const t=this.chat.getMessage(e),s=()=>{this.setTopInfo("reply",s,this.appPeersManager.getPeerTitle(t.fromId,!0),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.forwardingMids.length=0,this.forwardingFromPeerId=0,this.editMsgId=void 0,this.helperType=this.helperFunc=void 0,this.chat.container.classList.contains("is-helper-active")&&(M.a.removeByType("input-helper"),this.chat.container.classList.remove("is-helper-active"))}setInputValue(e,t=!0,s=!0){t&&this.clearInput(),this.messageInputField.value=e||"",window.requestAnimationFrame(()=>{s&&Mn(this.messageInput),this.messageInput.scrollTop=this.messageInput.scrollHeight})}setTopInfo(e,t,s="",i="",n,a){"webpage"!==e&&(this.clearHelper(e),this.helperType=e,this.helperFunc=t),"DIV"===this.replyElements.container.lastElementChild.tagName&&(this.replyElements.container.lastElementChild.remove(),this.replyElements.container.append(Gt(s,i,a))),this.chat.container.classList.add("is-helper-active"),c.isMobile||M.a.pushItem({type:"input-helper",onPop:()=>{this.onHelperCancel()}}),void 0!==n&&this.setInputValue(n),setTimeout(()=>{this.updateSendBtn()},0)}}Rn.AUTO_COMPLETE_REG_EXP=/(\s|^)((?::|.)(?!.*[:@]).*|(?:[@\/]\S*))$/;class Hn{constructor(e,t,s,i){this.chat=e,this.bubbles=t,this.input=s,this.appMessagesManager=i,this.selectedMids=new Set,this.isSelecting=!1,this.cancelSelection=()=>{for(const e of this.selectedMids){const t=this.bubbles.getMountedBubble(e);t&&this.toggleByBubble(t.bubble)}this.selectedMids.clear(),this.toggleSelection(),_i()},this.toggleByBubble=e=>{if(!this.canSelectBubble(e))return;const t=+e.dataset.mid;if(e.classList.contains("is-grouped")){if(!this.isGroupedBubbleSelected(e)){this.chat.getMidsByMid(t).forEach(e=>this.selectedMids.delete(e))}return void this.bubbles.getBubbleGroupedItems(e).forEach(this.toggleByBubble)}const s=this.selectedMids.has(t);if(s)this.selectedMids.delete(t);else{if(100-this.selectedMids.size-1<0)return void Be(f.default.format("Chat.Selection.LimitToast",!0));this.selectedMids.add(t)}if(e.classList.contains("grouped-item")){const s=Object(Qe.a)(e,"bubble"),i=this.isGroupedBubbleSelected(s),n=this.isGroupedMidsSelected(t);(n||i)&&this.updateBubbleSelection(s,n)}this.updateBubbleSelection(e,!s)};const n=t.bubblesContainer;this.listenerSetter=t.listenerSetter,l.isTouchSupported?this.listenerSetter.add(n,"touchend",e=>{this.isSelecting&&(this.selectedText=window.getSelection?window.getSelection().toString():document.selection?document.selection.createRange().text:"")}):this.listenerSetter.add(n,"mousedown",e=>{const t=Object(Qe.a)(e.target,"bubble");if(0!==e.button||!this.selectedMids.size&&!e.target.classList.contains("bubble")&&!e.target.classList.contains("document-selection")&&t)return;const s=new Set;let i,a=!1;const o=e=>{a||(_i(),a=!0);const t=Object(Qe.a)(e.target,"grouped-item")||Object(Qe.a)(e.target,"bubble");if(!t)return;const c=+t.dataset.mid;if(c){if(e.target!==t&&!e.target.classList.contains("document-selection")&&void 0===i&&!this.selectedMids.size)return this.listenerSetter.removeManual(n,"mousemove",o),void this.listenerSetter.removeManual(document,"mouseup",r,l);if(!s.has(c)){const e=this.selectedMids.has(c);void 0===i&&(i=!e),s.add(c),(i&&!e||!i&&e)&&(this.selectedMids.size?this.toggleByBubble(t):2===s.size&&[...s].forEach(e=>{const t=this.bubbles.getMountedBubble(e);t&&this.toggleByBubble(t.bubble)}))}}},r=e=>{s.size&&window.addEventListener("click",e=>{Object(re.a)(e)},{capture:!0,once:!0,passive:!1}),this.listenerSetter.removeManual(n,"mousemove",o),_i()},l={once:!0};this.listenerSetter.add(n,"mousemove",o),this.listenerSetter.add(document,"mouseup",r,l)})}toggleBubbleCheckbox(e,t){if(!this.canSelectBubble(e))return;const s=!!this.getCheckboxInputFromBubble(e),i=e.classList.contains("is-grouped");if(t){if(s)return;const t=new Te.a({name:e.dataset.mid,round:!0});if(t.label.classList.add("bubble-select-checkbox"),this.isSelecting){const s=+e.dataset.mid;!this.selectedMids.has(s)||i&&!this.isGroupedMidsSelected(s)||(t.input.checked=!0,e.classList.add("is-selected"))}e.classList.contains("document-container")?e.querySelector(".document, audio-element").append(t.label):e.prepend(t.label)}else s&&this.getCheckboxInputFromBubble(e).parentElement.remove();i&&this.bubbles.getBubbleGroupedItems(e).forEach(e=>this.toggleBubbleCheckbox(e,t))}getCheckboxInputFromBubble(e){return e.classList.contains("document-container")?e.querySelector("label input"):"LABEL"===e.firstElementChild.tagName&&e.firstElementChild.firstElementChild}updateContainer(e=!1){if(!this.selectedMids.size&&!e)return;this.selectionCountEl.textContent="",this.selectionCountEl.append(Object(f.i18n)("Chat.Selection.MessagesCount",[this.selectedMids.size]));let t=!this.selectedMids.size,s=!this.selectedMids.size,i=!this.selectedMids.size;for(const e of this.selectedMids.values()){const i=this.appMessagesManager.getMessageByPeer(this.bubbles.peerId,e);if(t||i.action&&(t=!0),!s){this.appMessagesManager.canDeleteMessage(this.chat.getMessage(e))||(s=!0)}if(t&&s)break}this.selectionSendNowBtn&&this.selectionSendNowBtn.toggleAttribute("disabled",i),this.selectionForwardBtn&&this.selectionForwardBtn.toggleAttribute("disabled",t),this.selectionDeleteBtn.toggleAttribute("disabled",s)}toggleSelection(e=!0,t=!1){const s=this.isSelecting;if(this.isSelecting=this.selectedMids.size>0||t,s===this.isSelecting)return;const i=this.bubbles.bubblesContainer;l.isTouchSupported||(i.classList.toggle("no-select",this.isSelecting),s&&_i()),Object(un.a)();let n="",a="";const o=!!this.selectedMids.size||t;if(o){const e=this.input.rowsWrapper.parentElement,t=e.querySelector(".fake-selection-wrapper"),s=e.querySelector(".fake-rows-wrapper"),i=t.getBoundingClientRect(),o=s.getBoundingClientRect(),r=o.width,l=i.width;if(r!==l){const e=l/r,t=(r-l)/2;if(n=`translateX(${i.left-o.left-t}px) scaleX(${e})`,e<1){const t=12;a=t+t*(1-e)+"px"}}}if(Object(Et.a)(this.input.rowsWrapper,"is-centering",o,200),this.input.rowsWrapper.style.transform=n,this.input.rowsWrapper.style.borderRadius=a,Object(Et.a)(i,"is-selecting",o,200,()=>{this.isSelecting||(this.selectionInputWrapper.remove(),this.selectionInputWrapper=this.selectionContainer=this.selectionSendNowBtn=this.selectionForwardBtn=this.selectionDeleteBtn=null,this.selectedText=void 0),window.requestAnimationFrame(()=>{this.bubbles.onScroll()})}),c.isMobileSafari||(o?M.a.pushItem({type:"multiselect",onPop:()=>{this.cancelSelection()}}):M.a.removeByType("multiselect")),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=k("close",{noRipple:!0});this.listenerSetter.add(e,"click",this.cancelSelection,{once:!0}),this.selectionCountEl=document.createElement("div"),this.selectionCountEl.classList.add("selection-container-count"),"scheduled"===this.chat.type?(this.selectionSendNowBtn=Object(C.a)("btn-primary btn-transparent btn-short text-bold selection-container-send",{icon:"send2"}),this.selectionSendNowBtn.append(Object(f.i18n)("MessageScheduleSend")),this.listenerSetter.add(this.selectionSendNowBtn,"click",()=>{new ji(this.bubbles.peerId,[...this.selectedMids],()=>{this.cancelSelection()})})):(this.selectionForwardBtn=Object(C.a)("btn-primary btn-transparent text-bold selection-container-forward",{icon:"forward"}),this.selectionForwardBtn.append(Object(f.i18n)("Forward")),this.listenerSetter.add(this.selectionForwardBtn,"click",()=>{new bi(this.bubbles.peerId,[...this.selectedMids],()=>{this.cancelSelection()})})),this.selectionDeleteBtn=Object(C.a)("btn-primary btn-transparent danger text-bold selection-container-delete",{icon:"delete"}),this.selectionDeleteBtn.append(Object(f.i18n)("Delete")),this.listenerSetter.add(this.selectionDeleteBtn,"click",()=>{new Oi(this.bubbles.peerId,[...this.selectedMids],this.chat.type,()=>{this.cancelSelection()})}),this.selectionContainer.append(...[e,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=""}if(e)for(const e in this.bubbles.bubbles){const t=this.bubbles.bubbles[e];this.toggleBubbleCheckbox(t,this.isSelecting)}t&&this.updateContainer(t)}cleanup(){this.selectedMids.clear(),this.toggleSelection(!1)}updateBubbleSelection(e,t){this.toggleBubbleCheckbox(e,!0);this.getCheckboxInputFromBubble(e).checked=t,this.toggleSelection(),this.updateContainer(),Object(Et.a)(e,"is-selected",t,200)}isGroupedBubbleSelected(e){const t=this.getCheckboxInputFromBubble(e);return null==t?void 0:t.checked}isGroupedMidsSelected(e){const t=this.chat.getMidsByMid(e),s=t.filter(e=>this.selectedMids.has(e));return t.length===s.length}deleteSelectedMids(e){e.forEach(e=>{this.selectedMids.delete(e)}),this.updateContainer(),this.toggleSelection()}canSelectBubble(e){return!e.classList.contains("service")&&!e.classList.contains("is-sending")}}const Nn=["is-pinned-message-shown","is-pinned-audio-shown"];class Un{constructor(e,t,s,i,n,a){this.topbar=e,this.chat=t,this.listenerSetter=s,this.className=i,this.divAndCaption=n,n.container.classList.add("pinned-container","hide"),n.title.classList.add("pinned-container-title"),n.subtitle.classList.add("pinned-container-subtitle"),n.content.classList.add("pinned-container-content"),this.close=document.createElement("button"),this.close.classList.add("pinned-container-close",`pinned-${i}-close`,"btn-icon","tgico-close"),this.wrapper=document.createElement("div"),this.wrapper.classList.add("pinned-container-wrapper"),this.wrapper.append(...Array.from(n.container.children)),Object(Q.ripple)(this.wrapper),n.container.append(this.close,this.wrapper),Object(F.b)(this.close,e=>{Object(re.a)(e),((a?a():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;this.divAndCaption.container.classList.toggle("is-floating",r.b.isMobile),this.topbar.container.classList.toggle("is-pinned-floating",r.b.isMobile);const s=this.chat.bubbles.scrollable,i=r.b.isMobile?s.scrollTop:void 0;this.divAndCaption.container.classList.toggle("hide",e);const n=`is-pinned-${this.className}-shown`;this.topbar.container.classList.toggle(n,!e);const a=Nn.filter(e=>this.topbar.container.classList.contains(e)),o=e?0:1;void 0!==i&&a.length<=o&&(s.scrollTop=i+52*(e?-1:1)),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 zn extends Un{constructor(e,t,s){super(e,t,e.listenerSetter,"audio",new ge("pinned-audio",(e,t)=>{Object(b.a)(this.divAndCaption.title,e),Object(b.a)(this.divAndCaption.subtitle,t)}),()=>{this.toggleEl.classList.contains("flip-icon")&&se.toggle()}),this.topbar=e,this.chat=t,this.appMessagesManager=s,this.divAndCaption.border.remove(),this.toggleEl=document.createElement("button"),this.toggleEl.classList.add("pinned-audio-ico","tgico","btn-icon"),Object(F.b)(this.toggleEl,e=>{Object(re.a)(e),se.toggle()},{listenerSetter:this.topbar.listenerSetter}),this.wrapper.prepend(this.toggleEl),this.topbar.listenerSetter.add(a.default,"audio_play",e=>{const{doc:t,mid:i,peerId:n}=e;let a,o;const r=s.getMessageByPeer(n,i);"voice"===t.type||"round"===t.type?(a=new $e.a({peerId:r.fromId,onlyFirstName:!0}).element,o=zt(r.date,!1,!1)):(a=t.audioTitle||t.file_name,o=t.audioPerformer?q.a.wrapPlainText(t.audioPerformer):"Unknown Artist"),this.fill(a,o,r),this.toggleEl.classList.add("flip-icon"),this.toggle(!1)}),this.topbar.listenerSetter.add(a.default,"audio_pause",()=>{this.toggleEl.classList.remove("flip-icon")})}}class Wn{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(3===s)i=this.drawRect(0,0,2,t,1)+this.drawRect(0,11,2,t+1,1)+this.drawRect(0,23,2,t,1);else for(let e=0;e<s;e++)i+=this.drawRect(0,(t+2)*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=32;return 1===e?s=32:2===e?s=15:3===e?s=9:(4===e||e>3)&&(s=7),s},this.getMarkHeight=(e,t)=>{let s=32;return 1===e?s=32:2===e?s=15:3===e?s=1===t?10:9:(4===e||e>3)&&(s=7),s},this.getMarkTranslateY=(e,t,s)=>1===s?0:2===s?0===e?0:t+2:3===s?0===e?0:1===e?11:23:(t+2)*e,this.getTrackTranslateY=(e,t,s,i)=>t<=4||e<=1?0:e>=t-2?i-32:(s+4)/2+(e-2)*(s+2),this.getTrackHeight=(e,t)=>e<=3?32:t*e+2*(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),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 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())}))};class Vn{constructor(){this.rows={},this.container=document.createElement("div"),this.container.className=Vn.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=Vn.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)},Vn.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)}}Vn.DURATION=200,Vn.BASE_CLASS="animated-super";class Gn{constructor(e=!1){this.reverse=e,this.decimals=[],this.previousNumber=0,this.container=document.createElement("div"),this.container.className=Gn.BASE_CLASS}getDecimal(e){if(this.decimals[e])return this.decimals[e];const t=document.createElement("div");t.className=Gn.BASE_CLASS+"-decimal";const s=document.createElement("div");s.className=Gn.BASE_CLASS+"-decimal-placeholder";const i=new Vn;return i.container.className=Gn.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()})},Vn.DURATION))}hideLeft(e){const t=(""+e).length;this.decimals.slice(t).forEach(t=>{const s=+t.placeholder.innerText||0;t.animatedSuper.getRow(Gn.EMPTY_INDEX,!0);t.animatedSuper.animate(Gn.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:Gn.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}}Gn.EMPTY_INDEX=-1,Gn.BASE_CLASS="animated-counter";class Kn{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 I,this.pinnedMessageContainer=new Un(e,t,this.listenerSetter,"message",new fe("pinned-message"),()=>qn(this,void 0,void 0,(function*(){return i.canPinMessage(this.topbar.peerId)?new Di(this.topbar.peerId,this.pinnedMid,!0):new Di(this.topbar.peerId,0,!0),!1}))),this.pinnedMessageBorder=new Wn,this.pinnedMessageContainer.divAndCaption.border.replaceWith(this.pinnedMessageBorder.render(1,0)),this.animatedSubtitle=new Vn,this.pinnedMessageContainer.divAndCaption.subtitle.append(this.animatedSubtitle.container),this.animatedMedia=new Vn,this.animatedMedia.container.classList.add("pinned-message-media-container"),this.pinnedMessageContainer.divAndCaption.content.prepend(this.animatedMedia.container),this.animatedCounter=new Gn(!0),this.pinnedMessageContainer.divAndCaption.title.append(Object(f.i18n)("PinnedMessage")," ",this.animatedCounter.container),this.btnOpen=k("pinlist pinned-container-close pinned-message-pinlist",{noRipple:!0}),this.pinnedMessageContainer.divAndCaption.container.prepend(this.btnOpen),Object(F.b)(this.btnOpen,e=>{Object(re.a)(e),this.topbar.openPinned(!0)},{listenerSetter:this.listenerSetter}),this.listenerSetter.add(a.default,"peer_pinned_messages",e=>{e.peerId===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",e=>{const{peerId:t,maxId:s}=e;t===this.topbar.peerId&&this.pinnedMessageContainer.toggle(this.hidden=!0)}),this.setPinnedMessage=Object(Re.a)(()=>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>Kn.LOAD_COUNT&&(!this.loadedBottom&&e<=Kn.LOAD_OFFSET||!this.loadedTop&&this.count-1-e<=Kn.LOAD_OFFSET)}getCurrentIndex(e,t=!0){return qn(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:Kn.LOAD_COUNT,backLimit:Kn.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 I,function(e,t,s,i){if(l.isTouchSupported){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 qn(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($t.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 qn(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(){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=be({title:void 0,titleEl:null,subtitle:s.message,subtitleEl:a,message:s,mediaEl:o});this.pinnedMessageContainer.divAndCaption.container.classList.toggle("is-media",r),this.animatedSubtitle.animate(t,this.wasPinnedIndex),r?(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)}}Kn.LOAD_COUNT=50,Kn.LOAD_OFFSET=5;class Qn{constructor(e,t,s,i,n,a){this.chat=e,this.appSidebarRight=t,this.appMessagesManager=s,this.appPeersManager=i,this.appChatsManager=n,this.appNotificationsManager=a,this.menuButtons=[],this.onResize=()=>{this.setUtilsWidth(!0)},this.onChangeScreen=(e,t)=>{this.container.classList.toggle("is-pinned-floating",r.b.isMobile),this.chatAudio&&this.chatAudio.divAndCaption.container.classList.toggle("is-floating",t===r.a.mobile),this.pinnedMessage&&this.pinnedMessage.pinnedMessageContainer.divAndCaption.container.classList.toggle("is-floating",t===r.a.mobile),this.setUtilsWidth(!0)},this.setUtilsWidth=(e=!1)=>{this.setUtilsRAF&&window.cancelAnimationFrame(this.setUtilsRAF),c.isSafari&&e&&this.chatUtils.classList.add("hide"),this.setUtilsRAF=window.requestAnimationFrame(()=>{c.isSafari&&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.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 I}construct(){this.container=document.createElement("div"),this.container.classList.add("sidebar-header","topbar"),this.btnBack=k("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 zn(this,this.chat,this.appMessagesManager),this.menuButtons.length&&(this.btnMore=ls({listenerSetter:this.listenerSetter},"bottom-left",this.menuButtons,e=>{Object(re.a)(e),this.menuButtons.forEach(e=>{e.element.classList.toggle("hide",!e.verify())}),this.menuButtons[this.menuButtons.length-1].element.lastChild.replaceWith(Object(f.i18n)(this.appPeersManager.getDeleteButtonText(this.peerId)))})),this.chatUtils.append(...[this.chatAudio?this.chatAudio.divAndCaption.container:null,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.listenerSetter.add(window,"resize",this.onResize),r.b.addEventListener("changeScreen",this.onChangeScreen),Object(F.b)(this.container,e=>{const t=Object(Qe.a)(e.target,"pinned-container");if(Object(un.a)(),t){Object(re.a)(e);const s=+t.dataset.mid,i=+t.dataset.peerId;t.classList.contains("pinned-message")?this.pinnedMessage.followPinnedMessage(s):this.chat.appImManager.setInnerPeer(i,s)}else r.b.activeScreen===r.a.medium&&document.body.classList.contains("is-left-column-shown")?n():Object(Ve.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(re.a)(e),r.b.activeScreen===r.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);M.a.back(e?"im":"chat")}};Object(F.b)(this.btnBack,n,{listenerSetter:this.listenerSetter})}constructUtils(){this.menuButtons=[{icon:"search",text:"Search",onClick:()=>{this.chat.initSearch()},verify:()=>r.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:"select",text:"Chat.Menu.SelectMessages",onClick:()=>{this.chat.selection.toggleSelection(!0,!0)},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:"delete danger",text:"Delete",onClick:()=>{new ot(this.peerId)},verify:()=>"chat"===this.chat.type&&!!this.appMessagesManager.getDialogOnly(this.peerId)}],this.btnSearch=k("search"),Object(F.b)(this.btnSearch,e=>{Object(re.a)(e),this.chat.initSearch()},{listenerSetter:this.listenerSetter})}constructPeerHelpers(){return this.avatarElement=new wa,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 Kn(this,this.chat,this.appMessagesManager,this.appPeersManager),this.btnJoin=Object(C.a)("btn-primary btn-color-primary chat-join hide"),this.btnJoin.append(Object(f.i18n)("Chat.Subscribe")),this.btnPinned=k("pinlist"),this.btnMute=k("mute"),Object(F.b)(this.btnPinned,e=>{Object(re.a)(e),Object(un.a)(),this.openPinned(!0)},{listenerSetter:this.listenerSetter}),Object(F.b)(this.btnMute,e=>{Object(re.a)(e),Object(un.a)(),this.appMessagesManager.mutePeer(this.peerId)},{listenerSetter:this.listenerSetter}),Object(F.b)(this.btnJoin,e=>{Object(re.a)(e),Object(un.a)(),this.btnJoin.setAttribute("disabled","true"),this.appChatsManager.joinChannel(-this.peerId).finally(()=>{this.btnJoin.removeAttribute("disabled")})},{listenerSetter:this.listenerSetter}),this.listenerSetter.add(a.default,"chat_update",e=>{var t,s;const i=e;if(this.peerId===-i){const e=this.appChatsManager.getChat(i);this.btnJoin.classList.toggle("hide",!(null===(s=null===(t=e)||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",e=>{const{peerId:t}=e;this.peerId===t&&this.setPeerStatus()}),this.listenerSetter.add(a.default,"user_update",e=>{const t=e;this.peerId===t&&this.setPeerStatus()}),this.pinnedMessage&&this.chat.addEventListener("setPeer",(e,t)=>{const s=this.chat.bubbles.getMiddleware();p.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 Kn(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(),r.b.removeEventListener("changeScreen",this.onChangeScreen),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&&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(this.wasPeerId){const e=new Kn(this,this.chat,this.appMessagesManager,this.appPeersManager);this.pinnedMessage.pinnedMessageContainer.divAndCaption.container.replaceWith(e.pinnedMessageContainer.divAndCaption.container),this.pinnedMessage.destroy(),this.pinnedMessage=e}p.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());window.requestAnimationFrame(()=>{this.setTitle(),this.setPeerStatus(!0),this.setMutedState()})}setTitle(e){let t;"pinned"===this.chat.type?(t=void 0===e?Object(f.i18n)("Loading"):Object(f.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?(t=this.peerId===a.default.myId?Object(f.i18n)("Reminders"):Object(f.i18n)("ScheduledMessages"),void 0===e&&this.appMessagesManager.getScheduledMessages(this.peerId).then(e=>{this.setTitle(e.length)})):"discussion"===this.chat.type?(t=void 0===e?Object(f.i18n)("Loading"):Object(f.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&&(t=new $e.a({peerId:this.peerId,dialog:!0}).element),this.title.textContent="",this.title.append(t)}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 $n extends P{constructor(){super(...arguments),this.peerId=0,this.threadId=0}onOpenAfterTimeout(){this.appSearch.beginSearch(this.peerId,this.threadId)}init(){this.container.id="search-private-container",this.container.classList.add("chatlist-container"),this.inputSearch=new L("Search"),this.title.replaceWith(this.inputSearch.container),this.btnPickDate=k("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 y(e,this.inputSearch,{messages:new v("Chat.Search.PrivateSearch","messages")})}open(e,t,s,i){const n=super.open();return this.init&&(this.init(),this.init=null),i&&(this.inputSearch.inputField.value=i),0!==this.peerId?(this.appSearch.beginSearch(this.peerId,this.threadId),n):(this.peerId=e,this.threadId=t,this.onDatePick=s,this.btnPickDate.classList.toggle("hide",!this.onDatePick),this.onDatePick&&Object(F.b)(this.btnPickDate,()=>{new mi(new Date,this.onDatePick).show()}),St.toggleSidebar(!0),n)}}class Yn{constructor(e,t,s){this.topbar=e,this.chat=t,this.query=s,this.foundCount=0,this.selectedIndex=0,this.onDateClick=e=>{Object(re.a)(e),new mi(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(Xt.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(b.a)(this.foundCountEl,Object(f.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(Ve.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(re.a)(e),this.selectResult(this.searchGroup.list.children[this.selectedIndex+1])},this.onDownClick=e=>{Object(re.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(Q.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 L("Search"),this.results=document.createElement("div"),this.results.classList.add("chat-search-results","chatlist-container"),this.searchGroup=new v(!1,"messages",void 0,"",!1),this.searchGroup.list.addEventListener("click",this.onResultsClick),this.appSearch=new y(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(f.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(Q.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 Xn extends E.a{constructor(e,t,s,i,n,a,o,r,l,c,d,h,u,p,m,g,b,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=f,this.wasAlreadyUsed=!1,this.initPeerId=0,this.peerId=0,this.type="chat",this.container=document.createElement("div"),this.container.classList.add("chat"),this.backgroundEl=document.createElement("div"),this.backgroundEl.classList.add("chat-background"),this.log=Object(W.b)("CHAT",W.a.Log|W.a.Warn|W.a.Debug|W.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(Re.c)(()=>{Object(Re.c)(()=>{Object(Et.a)(s,"is-visible",!0,200,e?()=>{e.remove()}:null)})}),t()):t()};e?Object(me.a)(s,e,i):i()})}setType(e){this.type=e,"scheduled"===this.type&&(this.getMessagesStorage=()=>this.appMessagesManager.getScheduledMessagesStorage(this.peerId))}init(e){this.initPeerId=e,this.topbar=new Qn(this,St,this.appMessagesManager,this.appPeersManager,this.appChatsManager,this.appNotificationsManager),this.bubbles=new Ai(this,this.appMessagesManager,this.appStickersManager,this.appUsersManager,this.appInlineBotsManager,this.appPhotosManager,this.appPeersManager),this.input=new Rn(this,this.appMessagesManager,this.appDocsManager,this.appChatsManager,this.appPeersManager,this.appWebPagesManager,this.appImManager,this.appDraftsManager,this.serverTimeManager,this.appNotificationsManager,this.appEmojiManager),this.selection=new Hn(this,this.bubbles,this.input,this.appMessagesManager),this.contextMenu=new Ri(this.bubbles.bubblesContainer,this,this.appMessagesManager,this.appChatsManager,this.appPeersManager,this.appPollsManager),"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){this.init&&(this.init(e),this.init=null);const s=this.peerId===e;if(s){if(this.setPeerPromise)return}else a.default.dispatchEvent("peer_changing",this),this.peerId=e;if(!e)return St.toggleSidebar(!1),this.cleanup(!0),this.topbar.setPeer(e),this.bubbles.setPeer(e),void a.default.dispatchEvent("peer_changed",e);if(!s){const t=St.getTab($n);t&&t.close(),St.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||(St.sharedMediaTab.setLoadMutex(this.setPeerPromise),St.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(),St.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===Si.a||this.appPeersManager.isAnyGroup(this.peerId)}initSearch(e){if(this.peerId)if(r.b.isMobile)new Yn(this.topbar,this,e);else{let t=St.getTab($n);t||(t=new $n(St)),t.open(this.peerId,this.threadId,this.bubbles.onDatePick,e)}}}var Jn=s(116);class Zn{constructor(e){this.appImManager=e,this.buttons={},this.addedListener=!1,this.waitingForMouseUp=!1,this.mouseUpCounter=0,this.onMouseUpSingle=e=>{if(this.waitingForMouseUp=!1,l.isTouchSupported){if(Object(re.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=k(t,{noRipple:!0});e.append(this.buttons[t]=s),"link"!==t?s.addEventListener("mousedown",e=>{Object(re.a)(e),this.appImManager.chat.input.applyMarkdown(t),this.cancelClosening()}):Object(F.b)(s,e=>{Object(re.a)(e),this.showLinkEditor(),this.cancelClosening()})}),this.linkBackButton=k("left",{noRipple:!0}),this.linkInput=document.createElement("input"),Object(f._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||!!q.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(re.a)(e),this.container.classList.remove("is-link"),this.resetSelection(),this.setTooltipPosition(),this.cancelClosening()}),this.linkApplyButton=k("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(re.a)(e),this.resetSelection();let t=this.linkInput.value;t&&!q.b.matchUrlProtocol(t)&&(t="https://"+t),this.appImManager.chat.input.applyMarkdown("link",t),setTimeout(()=>{this.hide()},0)}isLinkValid(){return!this.linkInput.value.length||!!q.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,M.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 An.b){const i=An.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(u.a)(e.left,l,c)}else{const e=i.left+(i.width-o.width)/2;d=Object(u.a)(e,l,c)}this.container.style.transform=`translate3d(${d}px, ${r}px, 0)`}show(){if(this.init&&(this.init(),this.init=null),Bi())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"),c.isMobile||M.a.pushItem({type:"markup",onPop:()=>{this.hide()}})}setMouseUpEvent(){this.waitingForMouseUp||(this.waitingForMouseUp=!0,document.addEventListener("mouseup",this.onMouseUpSingle,{once:!0}))}cancelClosening(){l.isTouchSupported&&!c.isApple&&(document.removeEventListener("mouseup",this.onMouseUpSingle),document.addEventListener("mouseup",e=>{Object(re.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(Bi(t))this.hide();else if(l.isTouchSupported)if(c.isApple)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 ea(e,t,s,i,n,a,o){return[e,",",t," ",s," ",i,",",n," ",a,",",o].join("")}function ta(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"+ea(a,a,0,0,1,e+s,t+a)),l.push("V"+(t+i-o)),o>0&&l.push("A"+ea(o,o,0,0,1,e+s-o,t+i)),l.push("H"+(e+r)),r>0&&l.push("A"+ea(r,r,0,0,1,e+0,t+i-r)),l.push("V"+(t+n)),n>0&&l.push("A"+ea(n,n,0,0,1,e+n,t+0)),l.push("Z"),l.join(" ")}Z.a.generatePathData=ta;class sa{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(f.i18n)(t.header));const n=document.createElement("div");n.classList.add("drop-subtitle"),n.append(Object(f.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=ta(5,5,e.width-10,e.height-10,10,10,10,10);this.path.setAttributeNS(null,"d",t)}}var ia=s(106);function na(e){e.forEach(e=>e.classList.add("no-transition")),Object(Re.b)().then(()=>{e.forEach(e=>e.classList.remove("no-transition"))})}var aa=s(113),oa=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 ra="chat",la=l.isTouchSupported?"touchstart":"mousemove";const ca=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);switch(this.log("hashchange",e,t[0],s),t[0]){case"#/im":{const e=s.p;let t=void 0!==s.post?i.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=Object(Re.a)(()=>{const e=this.chat.topbar;e.pinnedMessage&&e.pinnedMessage.setCorrectIndex(0),He.a.setQueueId(this.chat.bubbles.lazyLoadQueue.queueId)},a.default.settings.animationsEnabled?250:0,!1,!0),X.b.setLoop(a.default.settings.stickers.loop),h.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(re.a)(e)}Object(oe.c)(e).then(e=>{if(e.length){"media"===t&&e.find(e=>!["image","video"].includes(e.type.split("/")[0]))&&(t="document");const s=this.chat.input;s.willAttachType=t||(0===e[0].type.indexOf("image/")?"media":"document"),new En(this.chat,e,s.willAttachType)}})}},cs.a.attach(),this.log=Object(W.b)("IM",W.a.Log|W.a.Warn|W.a.Debug|W.a.Error),this.selectTab(0),window.addEventListener("blur",()=>{h.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),h.a.checkAnimations(!1),a.default.dispatchEvent("idle",a.default.idle.isIDLE)},{once:!0})}),window.addEventListener(la,()=>{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),M.a.onHashChange=this.onHashChange,this.setSettings(),a.default.addEventListener("settings_updated",this.setSettings),Object($t.a)(()=>{h.a.setOnlyOnePlayableGroup("lock"),h.a.checkAnimations(!0)},()=>{h.a.setOnlyOnePlayableGroup(""),h.a.checkAnimations(!1)}),this.applyCurrentTheme(),r.b.addEventListener("changeScreen",(e,t)=>{document.body.classList.contains("is-left-column-shown")&&document.body.classList.contains("is-right-column-shown")&&St.toggleSidebar(!1)}),a.default.addEventListener("history_focus",e=>{const{peerId:t,mid:s}=e;this.setInnerPeer(t,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 Ue.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(f.i18n)("Deactivated.Title"));const i=document.createElement("div");i.classList.add("subtitle"),i.append(Object(f.i18n)("Deactivated.Subtitle")),t.append(s,i),document.body.classList.add("deactivated"),e.onClose=()=>{document.body.classList.add("deactivated-backwards"),aa.a.reset(),aa.a.checkInstance(!1),setTimeout(()=>{document.body.classList.remove("deactivated","deactivated-backwards")},333)},e.show()}),qi.a.get("chatPositions").then(e=>{qi.a.setToCache("chatPositions",e||{})}),window.showMaskedAlert=(e,t)=>{Object(re.a)(null);const s=e.href,i=e.cloneNode(!0);return i.className="anchor-url",i.innerText=s,i.removeAttribute("onclick"),new ze("popup-masked-url",{titleLangKey:"OpenUrlTitle",descriptionLangKey:"OpenUrlAlert2",descriptionLangArgs:[i],buttons:[{langKey:"Open",callback:()=>{i.click()}}]}).show(),!1},window.execBotCommand=(e,t)=>{Object(re.a)(null);const s=e.href,n=this.parseUriParams(s);if(!n)return;const{command:a,bot:o}=n;return i.a.sendText(this.chat.peerId,"/"+a+(o?"@"+o:"")),!1},window.searchByHashtag=(e,t)=>{Object(re.a)(null);const s=e.href,i=this.parseUriParams(s);if(!i)return;const{hashtag:n}=i;return this.chat.initSearch("#"+n+" "),!1}}get myId(){return a.default.myId}get chat(){return this.chats[this.chats.length-1]}parseUriParams(e,t=e.split("?")){if(!t[1])return;const s={};return t[1].split("&").forEach(e=>{s[e.split("=")[0]]=decodeURIComponent(e.split("=")[1])}),s}openUsername(e,t){return m.a.resolveUsername(e).then(e=>{const s="user"===e._?e.id:-e.id;return this.setInnerPeer(s,t)})}setCurrentBackground(e=!1){const t=a.default.getTheme();if("image"===t.background.type||"default"===t.background.type&&t.background.slug){const s=p.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(A.a)(s.background),this.setBackground("",!0)))}return this.setBackground("",e)}getBackground(e){return this.backgroundPromises[e]?this.backgroundPromises[e]:this.backgroundPromises[e]=ee.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.scrollable.scrollTop,s=e.peerId+(e.threadId?"_"+e.threadId:""),i=qi.a.getFromCache("chatPositions");if(e.bubbles.scrollable.getDistanceToEnd()<=16&&e.bubbles.scrollable.loadedAll.bottom||!Object.keys(e.bubbles.bubbles).length)delete i[s],this.log("deleted chat position");else{const n={mids:Object(A.e)(e.bubbles.bubbles,"desc"),top:t};i[s]=n,this.log("saved chat position:",n)}qi.a.set({chatPositions:i},!0)}getChatSavedPosition(e){if(!["chat","discussion"].includes(e.type)||!e.peerId)return;const t=e.peerId+(e.threadId?"_"+e.threadId:""),s=qi.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");let s="#ffffff";e&&(s=function(e){return Ns(e).slice(0,-2)}(e)),void 0===this.themeColorElem&&(this.themeColorElem=document.head.querySelector('[name="theme-color"]')||null),this.themeColorElem&&this.themeColorElem.setAttribute("content",s)}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&&na([e,this.prevTab].filter(Boolean)),this.prevTab){this.prevTab.classList.remove("active"),this.chatsSelectTabDebounced(),a.default.settings.animationsEnabled&&!1!==t&&Object($t.b)(Object(Re.d)(400),400);const s=Object(Xt.a)(this.prevTab);Object(Xt.a)(e)>s&&M.a.pushItem({type:"chat",onPop:e=>{this.setPeer(0,void 0,e),Object(un.a)()}})}e.classList.add("active"),this.prevTab=e}}init(){document.addEventListener("paste",this.onDocumentPaste,!0);const e=new Set(["PageUp","PageDown","Meta","Control"]);document.body.addEventListener("keydown",t=>{if(a.default.overlayIsActive||e.has(t.key))return;const s=t.target,n=this.chat;if("KeyC"!==t.code||!t.ctrlKey&&!t.metaKey||"INPUT"===s.tagName){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(Mi.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(re.a)(t))}}}else if("ArrowDown"===t.code)return;!n.input.messageInput||t.target===n.input.messageInput||"INPUT"===s.tagName||s.hasAttribute("contenteditable")||l.isTouchSupported||r.b.isMobile&&1!==this.tabId||this.chat.selection.isSelecting||this.chat.input.recording||(n.input.messageInput.focus(),Mn(n.input.messageInput))}}),a.default.addEventListener("history_multiappend",e=>{const t=e;for(const e in t)St.sharedMediaTab.renderNewMessages(+e,Array.from(t[e]))}),a.default.addEventListener("history_delete",e=>{const{peerId:t,msgs:s}=e,i=Object.keys(s).map(e=>+e);St.sharedMediaTab.deleteDeletedMessages(t,i)}),a.default.addEventListener("message_sent",e=>{const{storage:t,tempId:s,mid:n}=e,a=i.a.getMessageFromStorage(t,n);St.sharedMediaTab.renderNewMessages(a.peerId,[n])}),l.isTouchSupported||this.attachDragAndDropListeners(),this.markupTooltip=new Zn(this),this.markupTooltip.handleSelection()}attachDragAndDropListeners(){const e=[];let t=!1;const s=(a,o)=>oa(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(oe.c)(a,!0),i=l&&!t.length,o=t.filter(e=>["image","video"].includes(e.split("/")[0])).length,r=t.length-o;this.log("drag files",t),(t.length||i)&&e.push(new sa(n,{icon:"dragfiles",header:"Chat.DropTitle",subtitle:"Chat.DropAsFilesDesc",onDrop:e=>{s(e,!1),ca.log("drop",e),ca.onDocumentPaste(e,"document")}})),(o&&!r||i)&&e.push(new sa(n,{icon:"dragmedia",header:"Chat.DropTitle",subtitle:"Chat.DropQuickDesc",onDrop:e=>{s(e,!1),ca.log("drop",e),ca.onDocumentPaste(e,"media")}})),this.chat.container.append(n)}Object(Et.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(re.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.overlayIsActive||t<0&&!D.a.hasRights(t,"send_media"))}selectTab(e,t){!1===t&&na([ui.sidebarEl,this.columnEl,St.sidebarEl]),document.body.classList.toggle("is-left-column-shown",0===e);const s=this.tabId;this.log("selectTab",e,s);let i=Object(Re.b)();if(-1!==s&&s!==e&&a.default.settings.animationsEnabled&&!1!==t){const e=100+(r.b.isMobile?250:200);i=Object(Re.d)(e),Object($t.b)(i,e),this.columnEl.classList.add("disable-hover"),i.finally(()=>{this.columnEl.classList.remove("disable-hover")})}return this.tabId=e,Object(un.a)(),r.b.isMobile&&2===s&&e<2&&document.body.classList.remove("is-right-column-shown"),-1!==s&&e>s&&(e<2||!M.a.findItemByType("im"))&&M.a.pushItem({type:"im",onPop:e=>{this.setPeer(0,void 0,e)}}),a.default.dispatchEvent("im_tab_change",e),i}updateStatus(){return this.myId?(m.a.setUserStatus(this.myId,this.offline),He.a.invokeApiSingle("account.updateStatus",{offline:this.offline})):Promise.resolve()}createNewChat(){const e=new Xn(this,D.a,d.a,ln,i.a,U.a,z.a,n.default,Rt,m.a,Jn.a,Ce.a,He.a,ia.a,ke.a,qi.a,Pe.a,Qi);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)M.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=St.getTab($n);e&&e.close();St.sharedMediaTab.setPeer(this.chat.peerId,this.chat.threadId)&&(St.sharedMediaTab.loadSidebarMedia(!0),St.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(r.b.activeScreen===r.a.medium)return void this.selectTab(+!this.tabId,s)}if(e===i.peerId&&r.b.activeScreen<=r.a.medium&&document.body.classList.contains("is-left-column-shown"))return this.selectTab(1,s),!1;if(e||r.b.activeScreen!==r.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.init||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(!m.a.isBot(e)){const s=D.a.getPeerTypings(e);if(!s||!s.length)return;const i=s[0],n={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"}},a=e>0?n.private:s.length>1?n.multi:n.chat;let o=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&&(o={_:"sendMessageTypingAction"})}const r=a[o._];if(!r)return;t||(t=document.createElement("span")).classList.add("online","peer-typing-container");let l,c=t.firstElementChild;c?c.dataset.action!==o._&&c.replaceWith(this.getTypingElement(o)):(c=this.getTypingElement(o),t.prepend(c)),e<0&&(l=[new $e.a({peerId:i.userId,onlyFirstName:!0}).element,s.length-1]);const d=Object(f.i18n)(r,l);return d.classList.add("peer-typing-description"),t.childElementCount>1?t.lastElementChild.replaceWith(d):t.append(d),t}}getPeerStatus(e){var t;return oa(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=D.a.getChatMembersString(-e),s}{const i=m.a.getUser(e);if(a.default.myId===e)return"";if(i){if(s=m.a.getUserStatusString(i.id),!m.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(b.a)(t,e||(i?"":""))})}};Z.a&&(Z.a.appImManager=ca);var da=ca;var ha=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 ua{constructor(e){this.author={},this.content={},this.buttons={},this.tempId=0,this.preloader=null,this.preloaderStreamable=null,this.lastTarget=null,this.prevTargets=[],this.nextTargets=[],this.isFirstOpen=!0,this.loadMediaPromiseUp=null,this.loadMediaPromiseDown=null,this.loadedAllMediaUp=!1,this.loadedAllMediaDown=!1,this.reverse=!1,this.needLoadMore=!0,this.pageEl=document.getElementById("page-chats"),this.onClick=e=>{if(this.setMoverAnimationPromise)return;const t=e.target;if("A"===t.tagName)return;if(Object(re.a)(e),l.isTouchSupported)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));let s=null;["media-viewer-mover","media-viewer-buttons","media-viewer-author","media-viewer-caption"].find(e=>{try{if(s=Object(Qe.a)(t,e),s)return!0}catch(e){return!1}}),s&&"IMG"!==t.tagName&&"image"!==t.tagName||this.buttons.close.click()},this.onKeyDown=e=>{"ArrowRight"===e.key?this.buttons.next.click():"ArrowLeft"===e.key&&this.buttons.prev.click()},this.log=Object(W.b)("AMV"),this.preloader=new ie.a,this.preloaderStreamable=new ie.a({cancelable:!1,streamable:!0}),this.preloader.construct(),this.preloaderStreamable.construct(),this.lazyLoadQueue=new G.a,this.wholeDiv=document.createElement("div"),this.wholeDiv.classList.add("media-viewer-whole"),this.overlaysDiv=document.createElement("div"),this.overlaysDiv.classList.add("overlays");const t=document.createElement("div");t.classList.add("media-viewer"),this.author.container=document.createElement("div"),this.author.container.classList.add("media-viewer-author","no-select"),this.author.avatarEl=new wa,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"),this.author.container.append(this.author.avatarEl,this.author.nameEl,this.author.date);const s=document.createElement("div");s.classList.add("media-viewer-buttons"),e.concat(["download","close"]).forEach(e=>{const t=k(e,{noRipple:"close"===e||void 0});this.buttons[e]=t,s.append(t)}),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),t.append(this.author.container,s,this.content.main),this.overlaysDiv.append(t),this.buttons["mobile-close"]=k("close",{onlyMobile:!0}),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.wholeDiv.append(this.overlaysDiv,this.buttons["mobile-close"],this.buttons.prev,this.buttons.next),this.setNewMover()}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))}),this.buttons.prev.addEventListener("click",e=>{if(Object(re.a)(e),this.setMoverPromise)return;const t=this.prevTargets.pop();t?this.onPrevClick(t):this.buttons.prev.style.display="none"}),this.buttons.next.addEventListener("click",e=>{if(Object(re.a)(e),this.setMoverPromise)return;let t=this.nextTargets.shift();t?this.onNextClick(t):this.buttons.next.style.display="none"}),this.wholeDiv.addEventListener("click",this.onClick),l.isTouchSupported){new ut({element:this.wholeDiv,onSwipe:(e,t)=>{if(he.isFullScreen())return;if(Math.abs(e)/z.a.windowW>.2||e>125)return e<0?this.buttons.prev.click():this.buttons.next.click(),!0;return(Math.abs(t)/z.a.windowH>.2||t>125)&&(this.buttons.close.click(),!0)},verifyTouchTarget:e=>"INPUT"!==e.target.tagName&&!Object(Qe.a)(e.target,"media-viewer-caption")})}}setBtnMenuToggle(e){const t=ls({onlyMobile:!0},"bottom-left",e);this.wholeDiv.append(t)}close(e){if(e&&Object(re.a)(e),this.setMoverAnimationPromise)return;M.a.removeByType("media"),this.lazyLoadQueue.clear();const t=this.setMoverToTarget(this.lastTarget,!0).then(({onAnimationEnd:e})=>e);return this.lastTarget=null,this.prevTargets=[],this.nextTargets=[],this.loadedAllMediaUp=this.loadedAllMediaDown=!1,this.loadMediaPromiseUp=this.loadMediaPromiseDown=null,this.setMoverPromise=null,this.tempId=-1,window.removeEventListener("keydown",this.onKeyDown),t.finally(()=>{this.wholeDiv.remove(),a.default.overlayIsActive=!1,h.a.checkAnimations(!1)}),t}setMoverToTarget(e,t=!1,s=0){return ha(this,void 0,void 0,(function*(){const i=this.content.mover;t||(i.innerHTML=""),this.removeCenterFromMover(i);const n=0!==s,r=a.default.settings.animationsEnabled?n?350:200:0;let l,c;e&&(e instanceof wa||e.classList.contains("grid-item")?(l=e,c=e.getBoundingClientRect()):e instanceof SVGImageElement||e.parentElement instanceof SVGForeignObjectElement?(l=Object(Qe.a)(e,"attachment"),c=l.getBoundingClientRect()):e.classList.contains("profile-avatars-avatar")&&(l=Object(Qe.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(Qe.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(n?(u=1===s?z.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,f=c.height/h.height;n||(g+=`scale3d(${b},${f},1) `);let v=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}(v);let w;v=y.map(e=>parseInt(e)/b+"px").join(" "),n||(i.style.borderRadius=v),i.style.transform=g,d&&(i.style.opacity="0");const L=e.classList.contains("is-out"),S=this.setMoverAnimationPromise=Object(o.a)(),M={onAnimationEnd:S};if(this.setMoverAnimationPromise.then(()=>{this.setMoverAnimationPromise=null}),t)return e instanceof SVGSVGElement&&(w=i.querySelector("path"),w&&this.sizeTailPath(w,h,b,r,!1,L,v)),e.classList.contains("media-viewer-media")&&i.classList.add("hiding"),setTimeout(()=>{this.wholeDiv.classList.remove("active")},0),setTimeout(()=>{i.style.borderRadius=v,i.firstElementChild&&(i.firstElementChild.style.borderRadius=v)},r/2),setTimeout(()=>{i.innerHTML="",i.classList.remove("moving","active","hiding"),i.style.cssText="display: none;",S.resolve()},r),M;{let t,s;if("DIV"===e.tagName||"AVATAR-ELEMENT"===e.tagName)e.firstElementChild&&(t=new Image,s=e.firstElementChild.src,i.append(t));else if(e instanceof HTMLImageElement)t=new Image,s=e.src;else if(e instanceof HTMLVideoElement){(t=document.createElement("video")).src=null==e?void 0: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/f})`),l.setAttributeNS(null,"transform",t),w=r.firstElementChild.lastElementChild;const s=v.split(" ").map(e=>parseInt(e));e=L?ta(0,0,n-9/b,a,...s):ta(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=v,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 new Promise((e,i)=>{t.addEventListener("load",e),s&&(t.src=s)}))),i.style.display="",window.requestAnimationFrame(()=>{i.classList.add(n?"moving":"active")})}return i.classList.toggle("opening",!t),yield new Promise(e=>window.requestAnimationFrame(()=>window.requestAnimationFrame(e))),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"),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,v),M}))}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?ta(0,0,l-9/s*o,c,...u):ta(9/s*o,0,l,c,...u),e.setAttributeNS(null,"d",p),t<i&&window.requestAnimationFrame(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=z.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"),this.content.mover){this.content.mover.parentElement.append(e)}else this.wholeDiv.append(e);return this.content.mover=e}updateMediaSource(e,t,s){const i=e.tagName.toLowerCase()===s?e:e.querySelector(s);i&&Object(me.a)(i,t)}setAuthorInfo(e,t){const s=new Date,i=new Date(1e3*t),n=s.getTime()/1e3,a=i.getHours()+":"+("0"+i.getMinutes()).slice(-2);let o;o=n-t<H.a&&s.getDate()===i.getDate()?"Today":n-t<2*H.a&&s.getDate()-1===i.getDate()?"Yesterday":s.getFullYear()!==i.getFullYear()?H.g[i.getMonth()].slice(0,3)+" "+i.getDate()+", "+i.getFullYear():H.g[i.getMonth()].slice(0,3)+" "+i.getDate(),this.author.date.innerText=o+" at "+a,Object(b.a)(this.author.nameEl,new $e.a({peerId:e,dialog:!1,onlyFirstName:!1,plainText:!1}).element);let r=this.author.avatarEl;this.author.avatarEl=this.author.avatarEl.cloneNode(),this.author.avatarEl.setAttribute("peer",""+e),r.parentElement.replaceChild(this.author.avatarEl,r)}_openMedia(e,t,s,i,n,o=!1,l=[],u=[],p=!0){return ha(this,void 0,void 0,(function*(){if(this.setMoverPromise)return this.setMoverPromise;this.setAuthorInfo(s,t);const m="video"===e.type||"gif"===e.type;this.isFirstOpen&&(this.prevTargets=l,this.nextTargets=u,this.reverse=o,this.needLoadMore=p,this.isFirstOpen=!1),this.buttons.prev.classList.toggle("hide",!this.prevTargets.length),this.buttons.next.classList.toggle("hide",!this.nextTargets.length);const g=this.content.media,b=!n||n===g;b&&(n=g),this.lastTarget=n;const f=++this.tempId;this.needLoadMore&&(this.nextTargets.length<20&&this.loadMoreMedia(!this.reverse),this.prevTargets.length<20&&this.loadMoreMedia(this.reverse)),g.firstElementChild&&(g.innerHTML="");if(0!==i)this.moveTheMover(this.content.mover,1===i),this.setNewMover();else{window.addEventListener("keydown",this.onKeyDown);const e=this.pageEl.querySelector("#main-columns");this.pageEl.insertBefore(this.wholeDiv,e),this.wholeDiv.offsetLeft,this.wholeDiv.classList.add("active"),a.default.overlayIsActive=!0,h.a.checkAnimations(!0),c.isMobileSafari||M.a.pushItem({type:"media",onPop:e=>{if(this.setMoverAnimationPromise)return!1;this.close()}})}const v=this.content.mover,y=r.b.isMobile?this.pageEl.scrollWidth:this.pageEl.scrollWidth-16,w=z.a.windowH-100;let L=Promise.resolve();const S=z.a.setAttachmentSize(e,g,y,w,!r.b.isMobile).photoSize;if(b){const t=ee.a.getCacheContext(e,S.type);let s;if(t.downloaded)s=new Image,s.src=t.url;else{const i=z.a.getStrippedThumbIfNeeded(e,t,!0);i&&(L=i.loadPromise,s=i.image)}s&&(s.classList.add("thumbnail"),g.append(s))}const E=e.supportsStreaming?this.preloaderStreamable:this.preloader;let I;if(m){const t=document.createElement("video"),s=()=>this.setMoverToTarget(n,!1,i).then(({onAnimationEnd:s})=>{const i=v.firstElementChild&&v.firstElementChild.classList.contains("media-viewer-aspecter")?v.firstElementChild:v,a=v.querySelector("video");a&&a.remove(),t.setAttribute("playsinline","true"),t.addEventListener("timeupdate",()=>{this.tempId!==f&&t.pause()}),c.isSafari&&(t.autoplay=!0),"gif"===e.type&&(t.muted=!0,t.autoplay=!0,t.loop=!0),t.parentElement||i.append(t);const o=new Promise(e=>{t.addEventListener("canplay",e,{once:!0})}),r=()=>{"gif"!==e.type&&(t.dataset.ckin="default",t.dataset.overlay="1",se.pause(),se.willBePlayedMedia=null,Promise.all([o,s]).then(()=>{if(this.tempId!==f)return;new he(t,!0,e.supportsStreaming)}))};if(e.supportsStreaming){s.then(()=>{t.readyState<t.HAVE_FUTURE_DATA&&E.attach(v,!0)});const e=()=>{t.addEventListener("canplay",()=>{E.detach(),t.parentElement.classList.remove("is-buffering")},{once:!0})};t.addEventListener("waiting",s=>{const i=t.networkState===t.NETWORK_LOADING,n=t.readyState<t.HAVE_FUTURE_DATA;i&&n&&(e(),E.attach(v,!0),t.parentElement.classList.add("is-buffering"))}),e()}this.lazyLoadQueue.unshift({load:()=>{const a=ee.a.getCacheContext(e),o=e.supportsStreaming?Promise.resolve():d.a.downloadDoc(e);return e.supportsStreaming||s.then(()=>{a.url||E.attach(v,!0,o)}),o.then(()=>ha(this,void 0,void 0,(function*(){if(this.tempId!==f)return void this.log.warn("media viewer changed video");const e=a.url;n instanceof SVGSVGElement?(i.firstElementChild.lastElementChild.append(t),this.updateMediaSource(v,e,"video")):Object(me.a)(t,e),r()}))),o}})});I=L.then(s)}else{const t=()=>this.setMoverToTarget(n,!1,i).then(({onAnimationEnd:t})=>{this.lazyLoadQueue.unshift({load:()=>{const s=ee.a.getCacheContext(e,S.type),i=z.a.preloadPhoto(e.id,S);return t.then(()=>{s.url||this.preloader.attachPromise(i)}),Promise.all([t,i]).then(()=>{var e;if(this.tempId!==f)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(v,t,"img"),r.b.isMobile){const e=v.querySelectorAll("img");e&&e.length&&e.forEach(e=>{e.classList.remove("thumbnail")})}}else{const s=v.firstElementChild&&v.firstElementChild.classList.contains("media-viewer-aspecter")?v.firstElementChild:v,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(me.a)(e,t,()=>{this.updateMediaSource(n,t,"img"),i&&window.requestAnimationFrame(()=>{i.remove()}),s.append(e)})}}}).catch(e=>{this.log.error(e),this.preloader.attach(v),this.preloader.setManual()}),i}})});I=L.then(t)}return this.setMoverPromise=I.catch(()=>{this.setMoverAnimationPromise=null}).finally(()=>{this.setMoverPromise=null})}))}}class pa extends ua{constructor(){super(["forward"]),this.currentMessageId=0,this.currentPeerId=0,this.onPrevClick=e=>{this.nextTargets.unshift({element:this.lastTarget,mid:this.currentMessageId,peerId:this.currentPeerId}),this.openMedia(i.a.getMessageByPeer(e.peerId,e.mid),e.element,-1)},this.onNextClick=e=>{this.prevTargets.push({element:this.lastTarget,mid:this.currentMessageId,peerId:this.currentPeerId}),this.openMedia(i.a.getMessageByPeer(e.peerId,e.mid),e.element,1)},this.onForwardClick=()=>{this.currentMessageId&&new bi(this.currentPeerId,[this.currentMessageId],()=>this.close())},this.onAuthorClick=e=>{if(this.currentMessageId&&this.currentMessageId!==Number.MAX_SAFE_INTEGER){const t=this.currentMessageId,s=this.currentPeerId,n=this.searchContext.threadId;this.close(e).then(()=>{if(r.b.isMobile){const e=St.getTab(wt);e&&e.close()}const e=i.a.getMessageByPeer(s,t);da.setInnerPeer(e.peerId,t,n?"discussion":void 0,n)})}},this.onDownloadClick=()=>{const e=i.a.getMessageByPeer(this.currentPeerId,this.currentMessageId);if(e.media.photo)z.a.savePhotoFile(e.media.photo,da.chat.bubbles.lazyLoadQueue.queueId);else{let t=null;t=e.media.webpage?e.media.webpage.document:e.media.document,t&&d.a.saveDocFile(t,da.chat.bubbles.lazyLoadQueue.queueId)}},this.loadMoreMedia=(e=!0)=>{if(e&&this.loadedAllMediaDown)return Promise.resolve();if(!e&&this.loadedAllMediaUp)return Promise.resolve();if(e&&this.loadMediaPromiseDown)return this.loadMediaPromiseDown;if(!e&&this.loadMediaPromiseUp)return this.loadMediaPromiseUp;const t=e?0:50;let s,n=this.currentMessageId;s=e?this.reverse?this.prevTargets[0]:this.nextTargets[this.nextTargets.length-1]:this.reverse?this.nextTargets[this.nextTargets.length-1]:this.prevTargets[0],s&&(n=s.mid),e||(n=i.a.incrementMessageId(n,1));const a=i.a.getSearch({peerId:this.searchContext.peerId,query:this.searchContext.query,inputFilter:{_:this.searchContext.inputFilter},maxId:n,limit:t?0:50,backLimit:t,threadId:this.searchContext.threadId,folderId:this.searchContext.folderId,nextRate:this.searchContext.nextRate,minDate:this.searchContext.minDate,maxDate:this.searchContext.maxDate}).then(t=>{Z.b&&this.log("loaded more media by maxId:",n,t,e,this.reverse),t.next_rate&&(this.searchContext.nextRate=t.next_rate),t.history.length<50&&(e?this.loadedAllMediaDown=!0:this.loadedAllMediaUp=!0);(e?t.history.forEach.bind(t.history):ve.c.bind(null,t.history))(t=>{const{mid:s,peerId:i}=t;if(!this.getMediaFromMessage(t))return;const n={element:null,mid:s,peerId:i};e?this.reverse?this.prevTargets.unshift(n):this.nextTargets.push(n):this.reverse?this.nextTargets.push(n):this.prevTargets.unshift(n)}),this.buttons.prev.classList.toggle("hide",!this.prevTargets.length),this.buttons.next.classList.toggle("hide",!this.nextTargets.length)},()=>{}).then(()=>{e?this.loadMediaPromiseDown=null:this.loadMediaPromiseUp=null});return e?this.loadMediaPromiseDown=a:this.loadMediaPromiseUp=a,a},this.content.caption=document.createElement("div"),this.content.caption.classList.add("media-viewer-caption"),new g.b(this.content.caption),this.wholeDiv.append(this.content.caption),this.setBtnMenuToggle([{icon:"forward",text:"Forward",onClick:this.onForwardClick},{icon:"download",text:"MediaViewer.Context.Download",onClick:this.onDownloadClick}]),this.setListeners()}setListeners(){super.setListeners(),this.buttons.forward.addEventListener("click",this.onForwardClick),this.author.container.addEventListener("click",this.onAuthorClick)}getMediaFromMessage(e){return e.action?e.action.photo:e.media.photo||e.media.document||e.media.webpage&&(e.media.webpage.document||e.media.webpage.photo)}setCaption(e){const t=e.message;this.content.caption.classList.toggle("hide",!t),this.content.caption.firstElementChild.innerHTML=t?q.a.wrapRichText(t,{entities:e.totalEntities}):""}setSearchContext(e){return this.searchContext=e,void 0!==this.searchContext.folderId&&(this.loadedAllMediaUp=!0,void 0===this.searchContext.nextRate&&(this.loadedAllMediaDown=!0)),this}openMedia(e,t,s=0,i=!1,n=[],a=[],o=!0){const r=Object.create(null,{_openMedia:{get:()=>super._openMedia}});return ha(this,void 0,void 0,(function*(){if(this.setMoverPromise)return this.setMoverPromise;const l=e.mid,c=e.fromId,d=this.getMediaFromMessage(e);this.currentMessageId=l,this.currentPeerId=e.peerId;const h=r._openMedia.call(this,d,e.date,c,s,t,i,n,a,o);return this.setCaption(e),h}))}}class ma extends ua{constructor(e){super([]),this.onPrevClick=e=>{this.nextTargets.unshift({element:this.lastTarget,photoId:this.currentPhotoId}),this.openMedia(e.photoId,e.element,-1)},this.onNextClick=e=>{this.prevTargets.push({element:this.lastTarget,photoId:this.currentPhotoId}),this.openMedia(e.photoId,e.element,1)},this.onDownloadClick=()=>{z.a.savePhotoFile(z.a.getPhoto(this.currentPhotoId),da.chat.bubbles.lazyLoadQueue.queueId)},this.loadMoreMedia=(e=!0)=>{if(this.peerId<0)return Promise.resolve();if(this.loadedAllMediaDown)return Promise.resolve();if(this.loadMediaPromiseDown)return this.loadMediaPromiseDown;const t=this.peerId,s=this.nextTargets.length?this.nextTargets[this.nextTargets.length-1].photoId:this.currentPhotoId,i=z.a.getUserPhotos(t,s,50).then(e=>{this.peerId===t?(e.photos.length<50&&(this.loadedAllMediaDown=!0),e.photos.forEach(e=>{this.currentPhotoId!==e&&this.nextTargets.push({element:null,photoId:e})}),this.buttons.prev.classList.toggle("hide",!this.prevTargets.length),this.buttons.next.classList.toggle("hide",!this.nextTargets.length)):this.log.warn("peer changed")},()=>{}).then(()=>{this.loadMediaPromiseDown=null});return this.loadMediaPromiseDown=i},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 ha(this,void 0,void 0,(function*(){if(this.setMoverPromise)return this.setMoverPromise;const o=z.a.getPhoto(e);return this.currentPhotoId=o.id,a._openMedia.call(this,o,o.date,this.peerId,s,t,!1,i,n)}))}}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())}))};const ba=e=>{n.default.removeFromAvatarsCache(e),Array.from(document.querySelectorAll('avatar-element[peer="'+e+'"]')).forEach(e=>{e.update()})};function fa(e,t,s,a,o,r){return ga(this,void 0,void 0,(function*(){let l=yield n.default.getFullPhoto(t);if(!s()||!l)return;const c=()=>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!==l.id&&(e||(a=i.a.generateFakeAvatarMessage(t,l)));const s=e=>e.map(e=>({element:e.element,mid:e.item.mid,peerId:e.item.peerId}));return void(new pa).setSearchContext({peerId:t,inputFilter:n}).openMedia(a,c(),void 0,void 0,o?s(o):void 0,r?s(r):void 0)}}if(l){"string"==typeof a&&(l=z.a.getPhoto(a));const e=e=>e.map(e=>({element:e.element,photoId:e.item}));new ma(t).openMedia(l.id,c(),void 0,o?e(o):void 0,r?e(r):void 0)}}))}a.default.addEventListener("avatar_update",ba),a.default.addEventListener("peer_title_edit",ba);const va=new Map,ya=new Set;class wa 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(F.b)(this,t=>ga(this,void 0,void 0,(function*(){if(Object(re.a)(t),e)return;const s=this.peerId;e=!0,yield fa(this,this.peerId,()=>this.peerId===s),e=!1})))}}disconnectedCallback(){const e=va.get(this.peerId);e&&e.has(this)&&(e.delete(this),e.size||va.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=U.a.getPeerMigratedTo(+s)||+s;const e=+t;if(e){const t=va.get(e);t&&(t.delete(this),t.size||va.delete(e))}this.update()}else"peer-title"===e?this.peerTitle=s:"dialog"===e&&(this.isDialog="1"===s)}r(e=!1){const t=n.default.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(!ya.has(this.peerId)){if(this.addedToQueue)return;this.addedToQueue=!0;let e=va.get(this.peerId);return e||(e=new Set,va.set(this.peerId,e)),e.add(this),this.r(!0),void this.lazyLoadQueue.push({div:this,load:()=>(ya.add(this.peerId),this.update())})}this.addedToQueue&&this.lazyLoadQueue.unobserve(this)}ya.add(this.peerId);const e=this.r(),t=e?e.loadPromise:Promise.resolve();this.addedToQueue&&t.finally(()=>{this.addedToQueue=!1});const s=va.get(this.peerId);if(s){s.delete(this);const e=Array.from(s);va.delete(this.peerId);for(let t=0,s=e.length;t<s;++t)e[t].update()}return t}}customElements.define("avatar-element",wa);class La{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)},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 ot(this.selectedId)},this.onContextMenu=e=>{this.init&&(this.init(),this.init=null);let t=null;try{t=Object(Ve.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=Ta.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(f.i18n)(U.a.getDeleteButtonText(this.selectedId))),t.classList.add("menu-open"),Object(K.e)(e,this.element),Object(K.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.filters[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.filters[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&&!Pe.a.isPeerLocalMuted(this.dialog.peerId)},{icon:"unmute",text:"ChatList.Context.Unmute",onClick:this.onUnmuteClick,verify:()=>this.selectedId!==a.default.myId&&Pe.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=as(this.buttons),this.element.id="dialogs-contextmenu",this.element.classList.add("contextmenu"),document.getElementById("page-chats").append(this.element)}}var Sa=s(57);class Ma{constructor(e){this.currentLangPackKey="",this.connecting=!1,this.updating=!1,this.setConnectionStatus=()=>{Sa.a.get("dc").then(e=>{e||(e=li.a.baseDcId),this.setFirstConnectionTimeout&&(clearTimeout(this.setFirstConnectionTimeout),this.setFirstConnectionTimeout=0);const t=a.default.connectionStatus["NET-"+e],s=t&&t.online;this.connecting&&s&&cs.a.forceGetDifference(),this.connecting=!s,this.connectingTimeout=t&&t.timeout,Z.b&&this.log("connecting",this.connecting),this.setState()})},this.setStatusText=e=>{this.currentLangPackKey!==e&&(this.currentLangPackKey=e,Object(b.a)(this.statusEl,Object(f.i18n)(e)),this.statusPreloader.attach(this.statusEl))},this.setState=()=>{const e=Ma.CHANGE_STATE_DELAY;this.connecting?this.setStatusText("ConnectionStatus.Waiting"):this.updating&&this.setStatusText("Updating"),Z.b&&this.log("setState",this.connecting||this.updating),window.requestAnimationFrame(()=>{this.setStateTimeout&&clearTimeout(this.setStateTimeout);this.setStateTimeout=window.setTimeout(()=>{Object(Et.a)(this.statusContainer,"is-shown",this.connecting||this.updating,200),this.setStateTimeout=0,Z.b&&this.log("setState: isShown:",this.connecting||this.updating)},e)})},this.log=Object(W.b)("CS"),this.statusContainer=document.createElement("div"),this.statusContainer.classList.add("connection-status"),this.statusEl=Object(C.a)("btn-primary bg-warning connection-status-button",{noRipple:!0}),this.statusPreloader=new ie.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,Z.b&&this.log("updating",this.updating),this.setState())}),a.default.addEventListener("state_synchronized",e=>{const t=e;Z.b&&this.log("state_synchronized",t),t||(this.updating=!1,Z.b&&this.log("updating",this.updating),this.setState())}),this.setFirstConnectionTimeout=window.setTimeout(this.setConnectionStatus,Ma.CHANGE_STATE_DELAY+1e3)}}Ma.CHANGE_STATE_DELAY=1e3;var Ea=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 Ia{constructor(){this.doms={},this.chatsContainer=document.getElementById("chatlist-container"),this.scroll=null,this.log=Object(W.b)("DIALOGS",W.a.Log|W.a.Error|W.a.Warn|W.a.Debug),this.contextMenu=new La,this.chatLists={},this.scrollables={},this.folders={menu:document.getElementById("folders-tabs"),menuScrollContainer:null,container:document.getElementById("folders-container")},this.filtersRendered={},this.lastActiveElements=new Set,this.onTabChange=()=>{this.doms={},this.scroll=this.scrollables[this.filterId],this.scroll.loadedAll.top=!0,this.scroll.loadedAll.bottom=!1,this.loadDialogsPromise=void 0,this.chatList=this.chatLists[this.filterId],this.loadDialogs()},this.onListLengthChange=()=>{if(this.filterId<2)return;const e=this.chatList.parentElement.querySelector(".empty-folder");if(this.scroll.loadedAll.bottom&&!this.chatList.childElementCount){if(e)return;const t="empty-folder",s=document.createElement("div");s.classList.add(t),s.append(function({emoji:e,width:t,height:s}){const i=document.createElement("div"),n=Rt.getAnimatedEmojiSticker(e);return n?Vt({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 n=document.createElement("div");n.classList.add(t+"-header"),Object(f._i18n)(n,"FilterNoChatsToDisplay");const a=document.createElement("div");a.classList.add(t+"-subtitle"),Object(f._i18n)(a,"FilterNoChatsToDisplayInfo");const o=Object(C.a)("btn-primary btn-color-primary btn-control tgico",{text:"FilterHeaderEdit",icon:"settings"});Object(F.b)(o,()=>{new Js(ui).open(i.a.filtersStorage.filters[this.filterId])}),s.append(n,a,o),this.chatList.parentElement.append(s)}else e&&e.remove()},this.onChatsRegularScroll=()=>{this.sliceTimeout&&clearTimeout(this.sliceTimeout),this.sliceTimeout=window.setTimeout(()=>{if(this.sliceTimeout=void 0,!this.chatList.childElementCount)return;const e=this.scroll.scrollTop,t=this.chatList.firstElementChild,s=this.scroll.container.getBoundingClientRect(),i=t.getBoundingClientRect(),n=Array.from(this.scroll.splitUp.children);let a=this.scroll.splitUp.offsetTop;a&&e<a&&(a-=e);const o=s.y+a,r=s.y,l=Object(Ve.a)(document.elementFromPoint(Math.ceil(i.x),Math.ceil(o+1)),t.tagName),d=Object(Ve.a)(document.elementFromPoint(Math.ceil(i.x),Math.floor(r+s.height-1)),t.tagName);if(!l||!d)return;const h=l.getBoundingClientRect().y-o,u=[],p=n.indexOf(l),m=n.indexOf(d),g=c.isSafari?[]:n.slice(0,Math.max(0,p-10)),b=n.slice(m+10);g.length&&(this.scroll.loadedAll.top=!1),b.length&&(this.scroll.loadedAll.bottom=!1),u.push(...g),u.push(...b),u.forEach(e=>{const t=+e.dataset.peerId;this.deleteDialog(t)}),this.scroll.scrollTop=l.offsetTop-h},200)},this.onChatsScrollTop=()=>{this.onChatsScroll("top")},this.onChatsScroll=(e="bottom")=>{this.scroll.loadedAll[e]||this.loadDialogsPromise||(this.log("onChatsScroll",e),this.loadDialogs(e))},this.chatsPreloader=Object(K.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),this.filterId=0,this.addFilter({id:this.filterId,title:"",titleEl:Object(f.i18n)("ChatList.Filter.AllChats"),orderIndex:0}),this.chatList=this.chatLists[this.filterId],this.scroll=this.scrollables[this.filterId],a.default.addEventListener("user_update",e=>{var t;const s=this.getDialogDom(e);if(s&&!m.a.isBot(e)&&e!==a.default.myId){const i="userStatusOnline"===(null===(t=m.a.getUser(e).status)||void 0===t?void 0:t._);s.avatarEl.classList.toggle("is-online",i)}}),a.default.addEventListener("dialog_flush",e=>{const t=e.peerId,s=i.a.getDialogOnly(t);s&&(this.setLastMessage(s),this.validateForFilter(),this.setFiltersUnreadCount())}),a.default.addEventListener("dialogs_multiupdate",e=>{const t=e;for(const e in t){const s=t[e];this.updateDialog(s)}this.validateForFilter(),this.setFiltersUnreadCount()}),a.default.addEventListener("dialog_drop",e=>{const{peerId:t}=e;this.deleteDialog(t),this.setFiltersUnreadCount()}),a.default.addEventListener("dialog_unread",e=>{const t=e,s=i.a.getDialogOnly(t.peerId);s&&(this.setUnreadMessages(s),this.validateForFilter(),this.setFiltersUnreadCount())}),a.default.addEventListener("dialog_notify_settings",e=>{this.setUnreadMessages(e)}),a.default.addEventListener("dialog_draft",e=>{const t=i.a.getDialogOnly(e.peerId);t&&this.updateDialog(t)}),a.default.addEventListener("peer_changed",e=>{const t=e;for(const e of this.lastActiveElements)+e.dataset.peerId!==t&&(e.classList.remove("active"),this.lastActiveElements.delete(e));Array.from(document.querySelectorAll(`[data-autonomous="0"] li[data-peer-id="${t}"]`)).forEach(e=>{e.classList.add("active"),this.lastActiveElements.add(e)})}),a.default.addEventListener("filter_update",e=>{const t=e;if(!this.filtersRendered[t.id])return void this.addFilter(t);if(t.id===this.filterId){const e=i.a.dialogsStorage.getFolder(t.id);this.validateForFilter();for(let t=0,s=e.length;t<s;++t){const s=e[t];this.updateDialog(s)}this.setFiltersUnreadCount()}this.filtersRendered[t.id].title.innerHTML=q.a.wrapEmojiText(t.title)}),a.default.addEventListener("filter_delete",e=>{const t=e,s=this.filtersRendered[t.id];s&&(this.folders.menu.firstElementChild.click(),s.container.remove(),s.menu.remove(),delete this.chatLists[t.id],delete this.scrollables[t.id],delete this.filtersRendered[t.id],Object.keys(this.filtersRendered).length<=1&&this.folders.menuScrollContainer.classList.add("hide"))}),a.default.addEventListener("filter_order",e=>{const t=e,s=this.folders.menu;t.forEach(e=>{const t=i.a.filtersStorage.filters[e],n=this.filtersRendered[e];Jt(n.menu,s,t.orderIndex),Jt(n.container,this.folders.container,t.orderIndex)})}),a.default.addEventListener("peer_typings",e=>{const{peerId:t,typings:s}=e,n=i.a.getDialogOnly(t);n&&(s.length?this.setTyping(n):this.unsetTyping(n))});const t=new g.a(this.folders.menuScrollContainer);e.prepend(this.folders.menuScrollContainer);Object(V.a)(this.folders.menu,this.folders.container,(e,t)=>{e=+t.dataset.filterId||0,this.filterId!==e&&(this.chatLists[e].innerHTML="",this.filterId=e,this.onTabChange())},()=>{for(const e in this.chatLists)+e!==this.filterId&&(this.chatLists[e].innerHTML="")},void 0,t);this.folders.menu.firstElementChild.click(),i.a.construct(),p.default.getState().then(e=>Ea(this,void 0,void 0,(function*(){Pe.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)),p.default.storagesResults.dialogs.length&&(ia.a.getAllDrafts(),ia.a.addMissedDialogs()),this.loadDialogs()}))).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&&(cs.a.updatesState.syncLoading||Promise.resolve()).then(()=>{i.a.refreshConversations()})})})}),new Ma(this.chatsContainer),this.chatsContainer.append(e),setTimeout(()=>{X.b.loadLottieWorkers()},200)}getOffset(e){if(!this.scroll.loadedAll[e]){const t="top"===e?this.chatList.firstElementChild:this.chatList.lastElementChild;if(t){const e=+t.dataset.peerId,s=i.a.getDialogByPeerId(e);return{index:s[0].index,pos:s[1]}}}return{index:0,pos:-1}}isDialogMustBeInViewport(e){const t=this.getOffset("top"),s=this.getOffset("bottom");if(!t.index&&!s.index)return!0;const i=e.index;return(!t.index||i<=t.index)&&(!s.index||i>=s.index)}deleteDialog(e){const t=this.getDialogDom(e);return!!t&&(t.listEl.remove(),delete this.doms[e],this.onListLengthChange(),!0)}updateDialog(e){if(e)if(this.isDialogMustBeInViewport(e)){if(!this.doms.hasOwnProperty(e.peerId)){const t=this.addDialogNew({dialog:e});if(!t)return;{const s=i.a.getDialogByPeerId(e.peerId)[1];Jt(t.dom.listEl,this.chatList,s),this.onListLengthChange()}}this.getDialogDom(e.peerId)&&(this.setLastMessage(e),this.reorderDialogs())}else this.deleteDialog(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=Pe.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)}validateForFilter(){const e=i.a.dialogsStorage.getFolder(this.filterId);for(const t in this.doms){const s=+t;-1===e.findIndex(e=>e.peerId===s)&&this.deleteDialog(s)}}generateScrollable(e,t){const s=new g.b(null,"CL",500);return s.container.addEventListener("scroll",this.onChatsRegularScroll),s.container.dataset.filterId=""+t,s.container.append(e),s.onScrolledTop=this.onChatsScrollTop,s.onScrolledBottom=this.onChatsScroll,s.setVirtualContainer(e),this.chatLists[t]=e,this.scrollables[t]=s,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=q.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(Q.ripple)(t);Jt(t,this.folders.menu,e.orderIndex);const o=this.createChatList(),r=this.generateScrollable(o,e.id),l=r.container;Jt(r.container,this.folders.container,e.orderIndex),this.setListClickListener(o,null,!0),this.filtersRendered[e.id]={menu:t,container:l,unread:n,title:i},!this.showFiltersPromise&&Object.keys(this.filtersRendered).length>1&&(this.showFiltersPromise=new Promise(e=>{window.setTimeout(()=>{this.showFiltersPromise=void 0,this.folders.menuScrollContainer.classList.remove("hide"),this.setFiltersUnreadCount(),e()},0)}))}loadDialogs(e="bottom"){if(this.loadDialogsPromise)return this.loadDialogsPromise;const t=new Promise((t,s)=>Ea(this,void 0,void 0,(function*(){if(!this.chatList.childElementCount){this.chatList.parentElement.append(this.chatsPreloader)}const s=this.filterId;let n=30;const a=i.a.dialogsStorage.getFolder(s);let o=0;if("top"===e){const e=this.chatList.firstElementChild;if(e){const t=+e.dataset.peerId,s=a.findIndex(e=>e.peerId===t),i=Math.max(0,s-n);n=s-i,o=a[i].index+1}}else{const e=this.chatList.lastElementChild;if(e){const t=+e.dataset.peerId,s=a.find(e=>e.peerId===t);o=s.index}}try{const t=(this.filterId>1?m.a.getContacts():Promise.resolve()).then(()=>i.a.getConversations("",o,n,s)),a=yield t;if(this.filterId!==s)return;if("bottom"===e)a.isEnd&&(this.scroll.loadedAll[e]=!0);else{const t=i.a.dialogsStorage.getFolder(s);(!a.dialogs.length||t.length&&t[0].index<o)&&(this.scroll.loadedAll[e]=!0)}if(a.dialogs.length){("top"===e?a.dialogs.slice().reverse():a.dialogs).forEach(t=>{this.addDialogNew({dialog:t,append:"bottom"===e})})}this.onListLengthChange(),this.log.debug("getDialogs "+n+" dialogs by offset:",o,a,this.chatList.childElementCount),setTimeout(()=>{this.scroll.onScroll()},0)}catch(e){this.log.error(e)}this.chatsPreloader.remove(),t()})));return this.loadDialogsPromise=t.finally(()=>{this.loadDialogsPromise=void 0})}setListClickListener(e,t,s=!1,n=!1,a=!1){let o;const r=(a?da.setInnerPeer:da.setPeer).bind(da);e.dataset.autonomous=""+ +n,e.addEventListener("mousedown",e=>{if(0!==e.button)return;this.log("dialogs click list");const s=e.target,i=Object(Ve.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}),Z.b&&e.addEventListener("dblclick",e=>{const t=Object(Ve.a)(e.target,"LI");if(t){const e=+t.dataset.peerId;this.log("debug dialog:",i.a.getDialogByPeerId(e))}}),s&&Object(K.a)(e,this.contextMenu.onContextMenu)}createChatList(){const e=document.createElement("ul");return e.classList.add("chatlist"),e}reorderDialogs(){this.reorderDialogsTimeout&&window.cancelAnimationFrame(this.reorderDialogsTimeout),this.reorderDialogsTimeout=window.requestAnimationFrame(()=>{this.reorderDialogsTimeout=0;const e=Math.max(0,this.getOffset("top").pos),t=i.a.dialogsStorage.getFolder(this.filterId),s=Array.from(this.chatList.children).map(e=>+e.dataset.peerId);t.forEach((t,i)=>{const n=this.getDialogDom(t.peerId);if(!n)return;const a=i-e;if(a>s.length)return void this.deleteDialog(t.peerId);const o=s[a];o!==t.peerId&&Jt(n.listEl,this.chatList,a)&&this.log.debug("setDialogPosition:",t,n,o,a)})})}setLastMessage(e,t,s,n){if(!s&&!(s=this.getDialogDom(e.peerId)))return;let o;if(t||(e.draft&&"draftMessage"===e.draft._&&(o=e.draft),t=i.a.getMessageByPeer(e.peerId,e.top_message)),"messageEmpty"===t._)return s.lastMessageSpan.innerHTML="",s.lastTimeSpan.innerHTML="",void delete s.listEl.dataset.mid;let r=e.peer,l=e.peerId;if(s.lastMessageSpan.textContent="",n&&t.message?s.lastMessageSpan.append(i.a.wrapMessageForReply(t,void 0,void 0,!1,n)):o?s.lastMessageSpan.append(i.a.wrapMessageForReply(o)):t.deleted||s.lastMessageSpan.append(i.a.wrapMessageForReply(t)),o){const e=document.createElement("b");e.classList.add("danger"),e.append(Object(f.i18n)("Draft")),e.append(": "),s.lastMessageSpan.prepend(e)}else if("peerUser"!==r._&&l!==t.fromId&&!t.action){const e=U.a.getPeer(t.fromId);if(e&&e.id){const i=document.createElement("b");e.id===a.default.myId?i.append(Object(f.i18n)("FromYou")):i.append(new $e.a({peerId:t.fromId,onlyFirstName:!0}).element),i.append(": "),s.lastMessageSpan.prepend(i)}}if(!t.deleted||o){const e=o?Math.max(o.date,t.date||0):t.date;s.lastTimeSpan.textContent="",s.lastTimeSpan.append(Object(H.d)(new Date(1e3*e)))}else s.lastTimeSpan.textContent="";this.doms[l]===s?this.setUnreadMessages(e):s.listEl.dataset.mid=t.mid}setUnreadMessages(e){const t=this.getDialogDom(e.peerId);if(1===e.folder_id&&this.accumulateArchivedUnread(),!t)return;const s=Pe.a.isPeerLocalMuted(e.peerId,!0);s!==t.listEl.classList.contains("is-muted")&&Object(Et.a)(t.listEl,"is-muted",s,200);const n=e.draft&&"draftMessage"===e.draft._?e.draft:i.a.getMessageByPeer(e.peerId,e.top_message);if("messageEmpty"!==n._&&!n.deleted&&n.pFlags.out&&n.peerId!==a.default.myId){n.pFlags&&n.pFlags.unread?(t.statusSpan.classList.remove("tgico-checks"),t.statusSpan.classList.add("tgico-check")):(t.statusSpan.classList.remove("tgico-check"),t.statusSpan.classList.add("tgico-checks"))}else t.statusSpan.classList.remove("tgico-check","tgico-checks");t.unreadMessagesSpan.innerText="";const o=i.a.filtersStorage.filters[this.filterId];let r;r=o?-1!==o.pinned_peers.findIndex(t=>t===e.peerId):!!e.pFlags.pinned,r?t.unreadMessagesSpan.classList.add("tgico-chatspinned","tgico"):t.unreadMessagesSpan.classList.remove("tgico-chatspinned","tgico"),e.unread_count||e.pFlags.unread_mark?(t.unreadMessagesSpan.innerText=""+(e.unread_count||" "),t.unreadMessagesSpan.classList.add("unread")):t.unreadMessagesSpan.classList.remove("unread")}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){return this.doms[e]}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)}addDialog(e,t,s=!0,n=!0,o=!1,r=!0,l=!0,c=54,d=!!t,h){var u,p;let g;if("number"==typeof e){let t=i.a.getDialogOnly(e);t||(t={peerId:e,peer:U.a.getOutputPeer(e),pFlags:{}}),g=t}else g=e;const b=g.peerId;if(void 0===t){if(this.doms[b])return;const e=i.a.filtersStorage.filters[this.filterId];if(e&&!i.a.filtersStorage.testDialogForFilter(g,e)||!e&&this.filterId!==g.folder_id)return}const f=new wa;if(f.lazyLoadQueue=h,f.setAttribute("dialog",r?"1":"0"),f.setAttribute("peer",""+b),f.classList.add("dialog-avatar","avatar-"+c),s&&b!==a.default.myId&&g.peer){switch(g.peer._){case"peerUser":const e=m.a.getUser(b);e.status&&"userStatusOnline"===e.status._&&f.classList.add("is-online")}}const v=document.createElement("div");v.classList.add("user-caption");const y=document.createElement("span");y.classList.add("user-title");const w=new $e.a({peerId:b,dialog:r,onlyFirstName:o,plainText:!1});y.append(w.element);const L=U.a.getPeer(b);y.classList.add("tgico"),(null===(u=null==L?void 0:L.pFlags)||void 0===u?void 0:u.verified)&&(y.classList.add("is-verified"),y.append(Ca()));const S=document.createElement("span");S.classList.add("user-last-message"),S.setAttribute("dir","auto");const M=document.createElement("li");n&&Object(Q.ripple)(M),M.append(f,v),M.dataset.peerId=""+b;const E=document.createElement("span");E.classList.add("message-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 T=document.createElement("span");T.classList.add("dialog-title-details"),T.append(E,I),k.append(y,T);const P=document.createElement("p");P.classList.add("dialog-subtitle"),P.append(S,C),v.append(k,P);const x={avatarEl:f,captionDiv:v,titleSpan:w.element,titleSpanContainer:y,statusSpan:E,lastTimeSpan:I,unreadMessagesSpan:C,lastMessageSpan:S,containerEl:M,listEl:M},A=l?"append":"prepend";if(void 0===t){this.scroll[A](M),this.doms[g.peerId]=x;Pe.a.isPeerLocalMuted(g.peerId,!0)&&M.classList.add("is-muted"),this.setLastMessage(g)}else t&&t[A](M);return d||(null===(p=da.chat)||void 0===p?void 0:p.peerId)!==b||(M.classList.add("active"),this.lastActiveElements.add(M)),{dom:x,dialog:g}}setTyping(e){const t=this.getDialogDom(e.peerId);if(!t)return;let s=t.lastMessageSpan.querySelector(".peer-typing-container");s?da.getPeerTyping(e.peerId,s):(s=da.getPeerTyping(e.peerId),Object(b.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))}}function Ca(){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}const ka=new Ia;Z.a.appDialogsManager=ka;var Ta=t.default=ka}}]);
//# sourceMappingURL=17.37db4aa399340711ccb2.chunk.js.map