Browse Source

Optimize rootScope

Removed inefficient logs
master
morethanwords 4 years ago
parent
commit
322eed41c5
  1. 2
      src/components/audio.ts
  2. 2
      src/components/avatar.ts
  3. 2
      src/components/chat/audio.ts
  4. 158
      src/components/chat/bubbles.ts
  5. 4
      src/components/chat/input.ts
  6. 18
      src/components/chat/markupTooltip.ts
  7. 4
      src/components/chat/pinnedMessage.ts
  8. 2
      src/components/chat/replies.ts
  9. 10
      src/components/chat/topbar.ts
  10. 4
      src/components/emoticonsDropdown/tabs/stickers.ts
  11. 4
      src/components/poll.ts
  12. 4
      src/components/sidebarLeft/index.ts
  13. 6
      src/components/sidebarLeft/tabs/chatFolders.ts
  14. 6
      src/components/sidebarRight/tabs/sharedMedia.ts
  15. 45
      src/helpers/fastSmoothScroll.ts
  16. 9
      src/hooks/useHeavyAnimationCheck.ts
  17. 2
      src/lib/appManagers/appChatsManager.ts
  18. 30
      src/lib/appManagers/appDialogsManager.ts
  19. 2
      src/lib/appManagers/appDownloadManager.ts
  20. 6
      src/lib/appManagers/appImManager.ts
  21. 60
      src/lib/appManagers/appMessagesManager.ts
  22. 2
      src/lib/appManagers/appPollsManager.ts
  23. 2
      src/lib/appManagers/appStickersManager.ts
  24. 2
      src/lib/appManagers/appUsersManager.ts
  25. 2
      src/lib/appManagers/appWebPagesManager.ts
  26. 27
      src/lib/rootScope.ts
  27. 2
      src/lib/storages/filters.ts

2
src/components/audio.ts

@ -17,7 +17,7 @@ import { SearchSuperContext } from "./appSearchSuper.";
import { formatDateAccordingToToday } from "../helpers/date"; import { formatDateAccordingToToday } from "../helpers/date";
rootScope.on('messages_media_read', e => { rootScope.on('messages_media_read', e => {
const {mids, peerId} = e.detail; const {mids, peerId} = e;
mids.forEach(mid => { mids.forEach(mid => {
(Array.from(document.querySelectorAll('audio-element[message-id="' + mid + '"][peer-id="' + peerId + '"]')) as AudioElement[]).forEach(elem => { (Array.from(document.querySelectorAll('audio-element[message-id="' + mid + '"][peer-id="' + peerId + '"]')) as AudioElement[]).forEach(elem => {

2
src/components/avatar.ts

@ -7,7 +7,7 @@ import { Photo } from "../layer";
import type { LazyLoadQueueIntersector } from "./lazyLoadQueue"; import type { LazyLoadQueueIntersector } from "./lazyLoadQueue";
rootScope.on('avatar_update', (e) => { rootScope.on('avatar_update', (e) => {
let peerId = e.detail; let peerId = e;
appProfileManager.removeFromAvatarsCache(peerId); appProfileManager.removeFromAvatarsCache(peerId);
(Array.from(document.querySelectorAll('avatar-element[peer="' + peerId + '"]')) as AvatarElement[]).forEach(elem => { (Array.from(document.querySelectorAll('avatar-element[peer="' + peerId + '"]')) as AvatarElement[]).forEach(elem => {

2
src/components/chat/audio.ts

@ -35,7 +35,7 @@ export default class ChatAudio extends PinnedContainer {
this.wrapper.prepend(this.toggleEl); this.wrapper.prepend(this.toggleEl);
this.topbar.listenerSetter.add(rootScope, 'audio_play', (e) => { this.topbar.listenerSetter.add(rootScope, 'audio_play', (e) => {
const {doc, mid, peerId} = e.detail; const {doc, mid, peerId} = e;
let title: string, subtitle: string; let title: string, subtitle: string;
const message = appMessagesManager.getMessageByPeer(peerId, mid); const message = appMessagesManager.getMessageByPeer(peerId, mid);

158
src/components/chat/bubbles.ts

@ -139,7 +139,7 @@ export default class ChatBubbles {
// will call when sent for update pos // will call when sent for update pos
this.listenerSetter.add(rootScope, 'history_update', (e) => { this.listenerSetter.add(rootScope, 'history_update', (e) => {
const {storage, peerId, mid} = e.detail; const {storage, peerId, mid} = e;
if(mid && peerId == this.peerId && this.chat.getMessagesStorage() === storage) { if(mid && peerId == this.peerId && this.chat.getMessagesStorage() === storage) {
const bubble = this.bubbles[mid]; const bubble = this.bubbles[mid];
@ -162,7 +162,7 @@ export default class ChatBubbles {
}); });
this.listenerSetter.add(rootScope, 'dialog_flush', (e) => { this.listenerSetter.add(rootScope, 'dialog_flush', (e) => {
let peerId: number = e.detail.peerId; let peerId: number = e.peerId;
if(this.peerId == peerId) { if(this.peerId == peerId) {
this.deleteMessagesByIds(Object.keys(this.bubbles).map(m => +m)); this.deleteMessagesByIds(Object.keys(this.bubbles).map(m => +m));
} }
@ -170,14 +170,14 @@ export default class ChatBubbles {
// Calls when message successfully sent and we have an id // Calls when message successfully sent and we have an id
this.listenerSetter.add(rootScope, 'message_sent', (e) => { this.listenerSetter.add(rootScope, 'message_sent', (e) => {
const {storage, tempId, tempMessage, mid} = e.detail; const {storage, tempId, tempMessage, mid} = e;
// ! can't use peerId to validate here, because id can be the same in 'scheduled' and 'chat' types // ! can't use peerId to validate here, because id can be the same in 'scheduled' and 'chat' types
if(this.chat.getMessagesStorage() !== storage) { if(this.chat.getMessagesStorage() !== storage) {
return; return;
} }
this.log('message_sent', e.detail); //this.log('message_sent', e);
const mounted = this.getMountedBubble(tempId, tempMessage) || this.getMountedBubble(mid); const mounted = this.getMountedBubble(tempId, tempMessage) || this.getMountedBubble(mid);
if(mounted) { if(mounted) {
@ -226,7 +226,9 @@ export default class ChatBubbles {
this.bubbleGroups.removeBubble(bubble, tempId); */ this.bubbleGroups.removeBubble(bubble, tempId); */
if(message.media?.webpage && !bubble.querySelector('.web')) { if(message.media?.webpage && !bubble.querySelector('.web')) {
this.renderMessage(message, true, false, bubble, false); getHeavyAnimationPromise().then(() => {
this.renderMessage(message, true, false, bubble, false);
});
/* const mounted = this.getMountedBubble(mid); /* const mounted = this.getMountedBubble(mid);
if(!mounted) return; if(!mounted) return;
this.renderMessage(mounted.message, true, false, mounted.bubble, false); */ this.renderMessage(mounted.message, true, false, mounted.bubble, false); */
@ -234,7 +236,7 @@ export default class ChatBubbles {
//delete this.bubbles[tempId]; //delete this.bubbles[tempId];
} else { } else {
this.log.warn('message_sent there is no bubble', e.detail); this.log.warn('message_sent there is no bubble', e);
} }
if(this.bubbles[tempId]) { if(this.bubbles[tempId]) {
@ -242,8 +244,13 @@ export default class ChatBubbles {
this.bubbles[mid] = bubble; this.bubbles[mid] = bubble;
delete this.bubbles[tempId]; delete this.bubbles[tempId];
bubble.classList.remove('is-sending'); //getHeavyAnimationPromise().then(() => {
bubble.classList.add(this.peerId === rootScope.myId && this.chat.type !== 'scheduled' ? 'is-read' : 'is-sent'); fastRaf(() => {
bubble.classList.remove('is-sending');
bubble.classList.add(this.peerId === rootScope.myId && this.chat.type !== 'scheduled' ? 'is-read' : 'is-sent');
});
//});
bubble.dataset.mid = '' + mid; bubble.dataset.mid = '' + mid;
this.bubbleGroups.removeBubble(bubble, tempId); this.bubbleGroups.removeBubble(bubble, tempId);
@ -258,7 +265,7 @@ export default class ChatBubbles {
if(this.chat.type === 'scheduled') { if(this.chat.type === 'scheduled') {
const timestamp = Date.now() / 1000 | 0; const timestamp = Date.now() / 1000 | 0;
const maxTimestamp = tempMessage.date - 10; const maxTimestamp = tempMessage.date - 10;
this.log('scheduled timing:', timestamp, maxTimestamp); //this.log('scheduled timing:', timestamp, maxTimestamp);
if(timestamp >= maxTimestamp) { if(timestamp >= maxTimestamp) {
this.deleteMessagesByIds([mid]); this.deleteMessagesByIds([mid]);
} }
@ -266,36 +273,41 @@ export default class ChatBubbles {
}); });
this.listenerSetter.add(rootScope, 'message_edit', (e) => { this.listenerSetter.add(rootScope, 'message_edit', (e) => {
const {storage, peerId, mid} = e.detail; fastRaf(() => {
const {storage, peerId, mid} = e;
if(peerId != this.peerId || storage !== this.chat.getMessagesStorage()) return; if(peerId != this.peerId || storage !== this.chat.getMessagesStorage()) return;
const mounted = this.getMountedBubble(mid); const mounted = this.getMountedBubble(mid);
if(!mounted) return; if(!mounted) return;
const updatePosition = this.chat.type === 'scheduled'; const updatePosition = this.chat.type === 'scheduled';
this.renderMessage(mounted.message, true, false, mounted.bubble, updatePosition); this.renderMessage(mounted.message, true, false, mounted.bubble, updatePosition);
if(updatePosition) { if(updatePosition) {
(this.messagesQueuePromise || Promise.resolve()).then(() => { (this.messagesQueuePromise || Promise.resolve()).then(() => {
this.deleteEmptyDateGroups(); this.deleteEmptyDateGroups();
}); });
} }
});
}); });
this.listenerSetter.add(rootScope, 'album_edit', (e) => { this.listenerSetter.add(rootScope, 'album_edit', (e) => {
const {peerId, groupId, deletedMids} = e.detail; fastRaf(() => {
const {peerId, groupId, deletedMids} = e;
if(peerId != this.peerId) return; if(peerId != this.peerId) return;
const mids = this.appMessagesManager.getMidsByAlbum(groupId); const mids = this.appMessagesManager.getMidsByAlbum(groupId);
const renderedId = mids.concat(deletedMids).find(mid => this.bubbles[mid]); const renderedId = mids.concat(deletedMids).find(mid => this.bubbles[mid]);
if(!renderedId) return; if(!renderedId) return;
const renderMaxId = getObjectKeysAndSort(this.appMessagesManager.groupedMessagesStorage[groupId], 'asc').pop(); const renderMaxId = getObjectKeysAndSort(this.appMessagesManager.groupedMessagesStorage[groupId], 'asc').pop();
this.renderMessage(this.chat.getMessage(renderMaxId), true, false, this.bubbles[renderedId], false);
this.renderMessage(this.chat.getMessage(renderMaxId), true, false, this.bubbles[renderedId], false);
});
}); });
this.listenerSetter.add(rootScope, 'messages_downloaded', (e) => { this.listenerSetter.add(rootScope, 'messages_downloaded', (e) => {
const {peerId, mids} = e.detail; const {peerId, mids} = e;
const middleware = this.getMiddleware(); const middleware = this.getMiddleware();
getHeavyAnimationPromise().then(() => { getHeavyAnimationPromise().then(() => {
@ -330,7 +342,7 @@ export default class ChatBubbles {
}); });
this.listenerSetter.add(rootScope, 'dialog_drop', (e) => { this.listenerSetter.add(rootScope, 'dialog_drop', (e) => {
if(e.detail.peerId == this.peerId) { if(e.peerId == this.peerId) {
this.chat.appImManager.setPeer(0); this.chat.appImManager.setPeer(0);
} }
}); });
@ -368,7 +380,7 @@ export default class ChatBubbles {
public constructPeerHelpers() { public constructPeerHelpers() {
// will call when message is sent (only 1) // will call when message is sent (only 1)
this.listenerSetter.add(rootScope, 'history_append', (e) => { this.listenerSetter.add(rootScope, 'history_append', (e) => {
let details = e.detail; let details = e;
if(!this.scrolledAllDown) { if(!this.scrolledAllDown) {
this.chat.setPeer(this.peerId, 0); this.chat.setPeer(this.peerId, 0);
@ -378,7 +390,7 @@ export default class ChatBubbles {
}); });
this.listenerSetter.add(rootScope, 'history_multiappend', (e) => { this.listenerSetter.add(rootScope, 'history_multiappend', (e) => {
const msgIdsByPeer = e.detail; const msgIdsByPeer = e;
if(!(this.peerId in msgIdsByPeer)) return; if(!(this.peerId in msgIdsByPeer)) return;
const msgIds = msgIdsByPeer[this.peerId]; const msgIds = msgIdsByPeer[this.peerId];
@ -386,7 +398,7 @@ export default class ChatBubbles {
}); });
this.listenerSetter.add(rootScope, 'history_delete', (e) => { this.listenerSetter.add(rootScope, 'history_delete', (e) => {
const {peerId, msgs} = e.detail; const {peerId, msgs} = e;
const mids = Object.keys(msgs).map(s => +s); const mids = Object.keys(msgs).map(s => +s);
@ -396,7 +408,7 @@ export default class ChatBubbles {
}); });
this.listenerSetter.add(rootScope, 'dialog_unread', (e) => { this.listenerSetter.add(rootScope, 'dialog_unread', (e) => {
const info = e.detail; const info = e;
if(info.peerId === this.peerId) { if(info.peerId === this.peerId) {
this.chat.input.setUnreadCount(); this.chat.input.setUnreadCount();
@ -405,7 +417,7 @@ export default class ChatBubbles {
}); });
this.listenerSetter.add(rootScope, 'dialogs_multiupdate', (e) => { this.listenerSetter.add(rootScope, 'dialogs_multiupdate', (e) => {
const dialogs = e.detail; const dialogs = e;
if(dialogs[this.peerId]) { if(dialogs[this.peerId]) {
this.chat.input.setUnreadCount(); this.chat.input.setUnreadCount();
@ -413,7 +425,7 @@ export default class ChatBubbles {
}); });
this.listenerSetter.add(rootScope, 'dialog_notify_settings', (e) => { this.listenerSetter.add(rootScope, 'dialog_notify_settings', (e) => {
const peerId = e.detail; const peerId = e;
if(this.peerId === peerId) { if(this.peerId === peerId) {
this.chat.input.setUnreadCount(); this.chat.input.setUnreadCount();
@ -449,7 +461,9 @@ export default class ChatBubbles {
} }
} }
this.log('will readHistory by ids:', max, length); if(DEBUG) {
this.log('will readHistory by ids:', max, length);
}
/* if(this.peerId < 0) { /* if(this.peerId < 0) {
max = appMessagesIDsManager.getMessageIdInfo(max)[0]; max = appMessagesIDsManager.getMessageIdInfo(max)[0];
@ -466,7 +480,7 @@ export default class ChatBubbles {
public constructPinnedHelpers() { public constructPinnedHelpers() {
this.listenerSetter.add(rootScope, 'peer_pinned_messages', (e) => { this.listenerSetter.add(rootScope, 'peer_pinned_messages', (e) => {
const {peerId, mids, pinned} = e.detail; const {peerId, mids, pinned} = e;
if(peerId !== this.peerId) return; if(peerId !== this.peerId) return;
if(mids) { if(mids) {
@ -483,7 +497,7 @@ export default class ChatBubbles {
}; };
this.listenerSetter.add(rootScope, 'scheduled_new', (e) => { this.listenerSetter.add(rootScope, 'scheduled_new', (e) => {
const {peerId, mid} = e.detail; const {peerId, mid} = e;
if(peerId !== this.peerId) return; if(peerId !== this.peerId) return;
this.renderNewMessagesByIds([mid]); this.renderNewMessagesByIds([mid]);
@ -491,7 +505,7 @@ export default class ChatBubbles {
}); });
this.listenerSetter.add(rootScope, 'scheduled_delete', (e) => { this.listenerSetter.add(rootScope, 'scheduled_delete', (e) => {
const {peerId, mids} = e.detail; const {peerId, mids} = e;
if(peerId !== this.peerId) return; if(peerId !== this.peerId) return;
this.deleteMessagesByIds(mids); this.deleteMessagesByIds(mids);
@ -641,7 +655,9 @@ export default class ChatBubbles {
let idx = targets.findIndex(t => t.mid == messageId); let idx = targets.findIndex(t => t.mid == messageId);
this.log('open mediaViewer single with ids:', ids, idx, targets); if(DEBUG) {
this.log('open mediaViewer single with ids:', ids, idx, targets);
}
if(!targets[idx]) { if(!targets[idx]) {
this.log('no target for media viewer!', target); this.log('no target for media viewer!', target);
@ -826,7 +842,10 @@ export default class ChatBubbles {
if(!history.length) return; if(!history.length) return;
if(top && !this.scrolledAll) { if(top && !this.scrolledAll) {
this.log('Will load more (up) history by id:', history[0], 'maxId:', history[history.length - 1], history); if(DEBUG) {
this.log('Will load more (up) history by id:', history[0], 'maxId:', history[history.length - 1], history);
}
/* if(history.length == 75) { /* if(history.length == 75) {
this.log('load more', this.scrollable.scrollHeight, this.scrollable.scrollTop, this.scrollable); this.log('load more', this.scrollable.scrollHeight, this.scrollable.scrollTop, this.scrollable);
return; return;
@ -841,7 +860,10 @@ export default class ChatBubbles {
// if scroll down after search // if scroll down after search
if(!top && history.indexOf(historyStorage.maxId) === -1/* && this.chat.type == 'chat' */) { if(!top && history.indexOf(historyStorage.maxId) === -1/* && this.chat.type == 'chat' */) {
this.log('Will load more (down) history by maxId:', history[history.length - 1], history); if(DEBUG) {
this.log('Will load more (down) history by maxId:', history[history.length - 1], history);
}
/* false && */this.getHistory(history[history.length - 1], false, true, undefined, justLoad); /* false && */this.getHistory(history[history.length - 1], false, true, undefined, justLoad);
} }
} }
@ -979,7 +1001,7 @@ export default class ChatBubbles {
public renderNewMessagesByIds(mids: number[], scrolledDown = this.scrolledDown) { public renderNewMessagesByIds(mids: number[], scrolledDown = this.scrolledDown) {
if(!this.scrolledAllDown) { // seems search active or sliced if(!this.scrolledAllDown) { // seems search active or sliced
this.log('renderNewMessagesByIds: seems search is active, skipping render:', mids); //this.log('renderNewMessagesByIds: seems search is active, skipping render:', mids);
return; return;
} }
@ -1011,7 +1033,11 @@ export default class ChatBubbles {
public scrollToNewLastBubble() { public scrollToNewLastBubble() {
const bubble = this.chatInner.lastElementChild.lastElementChild as HTMLElement; const bubble = this.chatInner.lastElementChild.lastElementChild as HTMLElement;
this.log('scrollToNewLastBubble: will scroll into view:', bubble);
/* if(DEBUG) {
this.log('scrollToNewLastBubble: will scroll into view:', bubble);
} */
if(bubble) { if(bubble) {
this.scrollingToNewBubble = bubble; this.scrollingToNewBubble = bubble;
this.scrollable.scrollIntoViewNew(bubble, 'end').then(() => { this.scrollable.scrollIntoViewNew(bubble, 'end').then(() => {
@ -1489,7 +1515,7 @@ export default class ChatBubbles {
} }
// * 1 for date, 1 for date sentinel // * 1 for date, 1 for date sentinel
let index = 2 + i; let index = this.stickyIntersector ? 2 + i : 1 + i;
/* if(bubble.parentElement) { // * if already mounted /* if(bubble.parentElement) { // * if already mounted
const currentIndex = whichChild(bubble); const currentIndex = whichChild(bubble);
if(index > currentIndex) { if(index > currentIndex) {
@ -1500,7 +1526,7 @@ export default class ChatBubbles {
positionElementByIndex(bubble, dateMessage.container, index); positionElementByIndex(bubble, dateMessage.container, index);
} else { } else {
if(reverse) { if(reverse) {
dateMessage.container.insertBefore(bubble, dateMessage.container.children[1].nextSibling); dateMessage.container.insertBefore(bubble, dateMessage.container.children[this.stickyIntersector ? 1 : 0].nextSibling);
} else { } else {
dateMessage.container.append(bubble); dateMessage.container.append(bubble);
} }
@ -1517,7 +1543,10 @@ export default class ChatBubbles {
// reverse means top // reverse means top
public renderMessage(message: any, reverse = false, multipleRender = false, bubble: HTMLDivElement = null, updatePosition = true) { public renderMessage(message: any, reverse = false, multipleRender = false, bubble: HTMLDivElement = null, updatePosition = true) {
this.log.debug('message to render:', message); /* if(DEBUG) {
this.log.debug('message to render:', message);
} */
//return; //return;
const albumMustBeRenderedFull = this.chat.type !== 'pinned'; const albumMustBeRenderedFull = this.chat.type !== 'pinned';
if(message.deleted) return; if(message.deleted) return;
@ -2088,11 +2117,11 @@ export default class ChatBubbles {
} }
default: default:
bubble.classList.remove('is-message-empty'); bubble.classList.remove('is-message-empty');
messageDiv.innerHTML = 'unrecognized media type: ' + message.media._; messageDiv.innerHTML = 'unrecognized media type: ' + message.media._;
messageDiv.append(timeSpan); messageDiv.append(timeSpan);
this.log.warn('unrecognized media type:', message.media._, message); this.log.warn('unrecognized media type:', message.media._, message);
break; break;
} }
if(!processingWebPage) { if(!processingWebPage) {
@ -2296,7 +2325,7 @@ export default class ChatBubbles {
return new Promise<boolean>((resolve, reject) => { return new Promise<boolean>((resolve, reject) => {
//await new Promise((resolve) => setTimeout(resolve, 1e3)); //await new Promise((resolve) => setTimeout(resolve, 1e3));
this.log('performHistoryResult: will render some messages:', history.length, this.isHeavyAnimationInProgress); //this.log('performHistoryResult: will render some messages:', history.length, this.isHeavyAnimationInProgress);
const method = (reverse ? history.shift : history.pop).bind(history); const method = (reverse ? history.shift : history.pop).bind(history);
@ -2349,14 +2378,19 @@ export default class ChatBubbles {
//const newScrollTop = reverse ? scrollHeight - previousScrollHeightMinusTop : previousScrollHeightMinusTop; //const newScrollTop = reverse ? scrollHeight - previousScrollHeightMinusTop : previousScrollHeightMinusTop;
const newScrollTop = reverse ? this.scrollable.scrollHeight - previousScrollHeightMinusTop : previousScrollHeightMinusTop; const newScrollTop = reverse ? this.scrollable.scrollHeight - previousScrollHeightMinusTop : previousScrollHeightMinusTop;
this.log('performHistoryResult: will set up scrollTop:', newScrollTop, this.isHeavyAnimationInProgress); /* if(DEBUG) {
this.log('performHistoryResult: will set up scrollTop:', newScrollTop, this.isHeavyAnimationInProgress);
} */
// touchSupport for safari iOS // touchSupport for safari iOS
isTouchSupported && isApple && (this.scrollable.container.style.overflow = 'hidden'); isTouchSupported && isApple && (this.scrollable.container.style.overflow = 'hidden');
this.scrollable.scrollTop = newScrollTop; this.scrollable.scrollTop = newScrollTop;
//this.scrollable.scrollTop = this.scrollable.scrollHeight; //this.scrollable.scrollTop = this.scrollable.scrollHeight;
isTouchSupported && isApple && (this.scrollable.container.style.overflow = ''); isTouchSupported && isApple && (this.scrollable.container.style.overflow = '');
this.log('performHistoryResult: have set up scrollTop:', newScrollTop, this.scrollable.scrollTop, this.isHeavyAnimationInProgress); /* if(DEBUG) {
this.log('performHistoryResult: have set up scrollTop:', newScrollTop, this.scrollable.scrollTop, this.isHeavyAnimationInProgress);
} */
} }
resolve(true); resolve(true);
@ -2490,7 +2524,7 @@ export default class ChatBubbles {
const processResult = (historyResult: typeof result) => { const processResult = (historyResult: typeof result) => {
if(this.chat.type === 'discussion' && 'offsetIdOffset' in historyResult) { if(this.chat.type === 'discussion' && 'offsetIdOffset' in historyResult) {
const isTopEnd = historyResult.offsetIdOffset >= (historyResult.count - loadCount); const isTopEnd = historyResult.offsetIdOffset >= (historyResult.count - loadCount);
this.log('discussion got history', loadCount, backLimit, historyResult, isTopEnd); //this.log('discussion got history', loadCount, backLimit, historyResult, isTopEnd);
// * inject discussion start // * inject discussion start
if(isTopEnd) { if(isTopEnd) {
@ -2504,7 +2538,7 @@ export default class ChatBubbles {
const processPromise = (result: Promise<HistoryResult>) => { const processPromise = (result: Promise<HistoryResult>) => {
const promise = result.then((result) => { const promise = result.then((result) => {
this.log('getHistory not cached result by maxId:', maxId, reverse, isBackLimit, result, peerId, justLoad); //this.log('getHistory not cached result by maxId:', maxId, reverse, isBackLimit, result, peerId, justLoad);
if(justLoad) { if(justLoad) {
this.scrollable.onScroll(); // нужно делать из-за ранней прогрузки this.scrollable.onScroll(); // нужно делать из-за ранней прогрузки
@ -2541,7 +2575,7 @@ export default class ChatBubbles {
return null; return null;
} else { } else {
cached = true; cached = true;
this.log('getHistory cached result by maxId:', maxId, reverse, isBackLimit, result, peerId, justLoad); //this.log('getHistory cached result by maxId:', maxId, reverse, isBackLimit, result, peerId, justLoad);
processResult(result); processResult(result);
promise = getHeavyAnimationPromise().then(() => { promise = getHeavyAnimationPromise().then(() => {
return this.performHistoryResult((result as HistoryResult).history || [], reverse, isBackLimit, !isFirstMessageRender && additionMsgId); return this.performHistoryResult((result as HistoryResult).history || [], reverse, isBackLimit, !isFirstMessageRender && additionMsgId);
@ -2616,7 +2650,7 @@ export default class ChatBubbles {
//let removeCount = loadCount / 2; //let removeCount = loadCount / 2;
const safeCount = realLoadCount * 2; // cause i've been runningrunningrunning all day const safeCount = realLoadCount * 2; // cause i've been runningrunningrunning all day
this.log('getHistory: slice loadedTimes:', reverse, pageCount, this.loadedTopTimes, this.loadedBottomTimes, ids?.length, safeCount); //this.log('getHistory: slice loadedTimes:', reverse, pageCount, this.loadedTopTimes, this.loadedBottomTimes, ids?.length, safeCount);
if(ids && ids.length > safeCount) { if(ids && ids.length > safeCount) {
if(reverse) { if(reverse) {
//ids = ids.slice(-removeCount); //ids = ids.slice(-removeCount);
@ -2624,7 +2658,7 @@ export default class ChatBubbles {
ids = ids.slice(safeCount); ids = ids.slice(safeCount);
this.scrolledAllDown = false; this.scrolledAllDown = false;
this.log('getHistory: slice bottom messages:', ids.length, loadCount); //this.log('getHistory: slice bottom messages:', ids.length, loadCount);
//this.getHistoryBottomPromise = undefined; // !WARNING, это нужно для обратной загрузки истории, если запрос словил флуд //this.getHistoryBottomPromise = undefined; // !WARNING, это нужно для обратной загрузки истории, если запрос словил флуд
} else { } else {
//ids = ids.slice(0, removeCount); //ids = ids.slice(0, removeCount);
@ -2632,11 +2666,11 @@ export default class ChatBubbles {
ids = ids.slice(0, ids.length - safeCount); ids = ids.slice(0, ids.length - safeCount);
this.scrolledAll = false; this.scrolledAll = false;
this.log('getHistory: slice up messages:', ids.length, loadCount); //this.log('getHistory: slice up messages:', ids.length, loadCount);
//this.getHistoryTopPromise = undefined; // !WARNING, это нужно для обратной загрузки истории, если запрос словил флуд //this.getHistoryTopPromise = undefined; // !WARNING, это нужно для обратной загрузки истории, если запрос словил флуд
} }
this.log('getHistory: will slice ids:', ids, reverse); //this.log('getHistory: will slice ids:', ids, reverse);
this.deleteMessagesByIds(ids, false); this.deleteMessagesByIds(ids, false);
} }

4
src/components/chat/input.ts

@ -175,7 +175,7 @@ export default class ChatInput {
}, {listenerSetter: this.listenerSetter}); }, {listenerSetter: this.listenerSetter});
this.listenerSetter.add(rootScope, 'scheduled_new', (e) => { this.listenerSetter.add(rootScope, 'scheduled_new', (e) => {
const peerId = e.detail.peerId; const peerId = e.peerId;
if(this.chat.peerId !== peerId) { if(this.chat.peerId !== peerId) {
return; return;
@ -185,7 +185,7 @@ export default class ChatInput {
}); });
this.listenerSetter.add(rootScope, 'scheduled_delete', (e) => { this.listenerSetter.add(rootScope, 'scheduled_delete', (e) => {
const peerId = e.detail.peerId; const peerId = e.peerId;
if(this.chat.peerId !== peerId) { if(this.chat.peerId !== peerId) {
return; return;

18
src/components/chat/markupTooltip.ts

@ -254,14 +254,26 @@ export default class MarkupTooltip {
this.container.style.transform = `translate3d(${left}px, ${top}px, 0)`; this.container.style.transform = `translate3d(${left}px, ${top}px, 0)`;
} }
public isSelectionEmpty(selection = window.getSelection()) {
if(!selection || !selection.rangeCount) {
return true;
}
const selectionRange = selection.getRangeAt(0);
if(!selectionRange.toString() || !selectionRange.START_TO_END) {
return true;
}
return false;
}
public show() { public show() {
if(this.init) { if(this.init) {
this.init(); this.init();
this.init = null; this.init = null;
} }
const selection = document.getSelection(); if(this.isSelectionEmpty()) {
if(!selection.toString().trim().length) {
this.hide(); this.hide();
return; return;
} }
@ -359,7 +371,7 @@ export default class MarkupTooltip {
} }
const selection = document.getSelection(); const selection = document.getSelection();
if(!selection.toString().trim().length) { if(this.isSelectionEmpty(selection)) {
this.hide(); this.hide();
return; return;
} }

4
src/components/chat/pinnedMessage.ts

@ -280,7 +280,7 @@ export default class ChatPinnedMessage {
}, {listenerSetter: this.listenerSetter}); }, {listenerSetter: this.listenerSetter});
this.listenerSetter.add(rootScope, 'peer_pinned_messages', (e) => { this.listenerSetter.add(rootScope, 'peer_pinned_messages', (e) => {
const peerId = e.detail.peerId; const peerId = e.peerId;
if(peerId == this.topbar.peerId) { if(peerId == this.topbar.peerId) {
//this.wasPinnedIndex = 0; //this.wasPinnedIndex = 0;
@ -302,7 +302,7 @@ export default class ChatPinnedMessage {
}); });
this.listenerSetter.add(rootScope, 'peer_pinned_hidden', (e) => { this.listenerSetter.add(rootScope, 'peer_pinned_hidden', (e) => {
const {peerId, maxId} = e.detail; const {peerId, maxId} = e;
if(peerId == this.topbar.peerId) { if(peerId == this.topbar.peerId) {
this.pinnedMessageContainer.toggle(this.hidden = true); this.pinnedMessageContainer.toggle(this.hidden = true);

2
src/components/chat/replies.ts

@ -8,7 +8,7 @@ import { ripple } from "../ripple";
const TAG_NAME = 'replies-element'; const TAG_NAME = 'replies-element';
rootScope.on('replies_updated', (e) => { rootScope.on('replies_updated', (e) => {
const message = e.detail; const message = e;
(Array.from(document.querySelectorAll(TAG_NAME + `[data-post-key="${message.peerId}_${message.mid}"]`)) as RepliesElement[]).forEach(element => { (Array.from(document.querySelectorAll(TAG_NAME + `[data-post-key="${message.peerId}_${message.mid}"]`)) as RepliesElement[]).forEach(element => {
element.message = message; element.message = message;
element.render(); element.render();

10
src/components/chat/topbar.ts

@ -246,7 +246,7 @@ export default class ChatTopbar {
}, {listenerSetter: this.listenerSetter}); }, {listenerSetter: this.listenerSetter});
this.listenerSetter.add(rootScope, 'chat_update', (e) => { this.listenerSetter.add(rootScope, 'chat_update', (e) => {
const peerId: number = e.detail; const peerId: number = e;
if(this.peerId == -peerId) { if(this.peerId == -peerId) {
const chat = this.appChatsManager.getChat(peerId) as Channel/* | Chat */; const chat = this.appChatsManager.getChat(peerId) as Channel/* | Chat */;
@ -256,7 +256,7 @@ export default class ChatTopbar {
}); });
this.listenerSetter.add(rootScope, 'dialog_notify_settings', (e) => { this.listenerSetter.add(rootScope, 'dialog_notify_settings', (e) => {
const peerId = e.detail; const peerId = e;
if(peerId == this.peerId) { if(peerId == this.peerId) {
this.setMutedState(); this.setMutedState();
@ -264,7 +264,7 @@ export default class ChatTopbar {
}); });
this.listenerSetter.add(rootScope, 'peer_typings', (e) => { this.listenerSetter.add(rootScope, 'peer_typings', (e) => {
const {peerId} = e.detail; const {peerId} = e;
if(this.peerId == peerId) { if(this.peerId == peerId) {
this.setPeerStatus(); this.setPeerStatus();
@ -272,7 +272,7 @@ export default class ChatTopbar {
}); });
this.listenerSetter.add(rootScope, 'user_update', (e) => { this.listenerSetter.add(rootScope, 'user_update', (e) => {
const userId = e.detail; const userId = e;
if(this.peerId == userId) { if(this.peerId == userId) {
this.setPeerStatus(); this.setPeerStatus();
@ -305,7 +305,7 @@ export default class ChatTopbar {
public constructPinnedHelpers() { public constructPinnedHelpers() {
this.listenerSetter.add(rootScope, 'peer_pinned_messages', (e) => { this.listenerSetter.add(rootScope, 'peer_pinned_messages', (e) => {
const {peerId, mids, pinned} = e.detail; const {peerId, mids, pinned} = e;
if(peerId !== this.peerId) return; if(peerId !== this.peerId) return;

4
src/components/emoticonsDropdown/tabs/stickers.ts

@ -268,7 +268,7 @@ export default class StickersTab implements EmoticonsTab {
}); */ }); */
rootScope.on('stickers_installed', (e) => { rootScope.on('stickers_installed', (e) => {
const set: StickerSet.stickerSet = e.detail; const set: StickerSet.stickerSet = e;
if(!this.stickerSets[set.id] && this.mounted) { if(!this.stickerSets[set.id] && this.mounted) {
this.renderStickerSet(set, true); this.renderStickerSet(set, true);
@ -276,7 +276,7 @@ export default class StickersTab implements EmoticonsTab {
}); });
rootScope.on('stickers_deleted', (e) => { rootScope.on('stickers_deleted', (e) => {
const set: StickerSet.stickerSet = e.detail; const set: StickerSet.stickerSet = e;
if(this.stickerSets[set.id] && this.mounted) { if(this.stickerSets[set.id] && this.mounted) {
const elements = this.stickerSets[set.id]; const elements = this.stickerSets[set.id];

4
src/components/poll.ts

@ -66,7 +66,7 @@ export const roundPercents = (percents: number[]) => {
/* const connectedPolls: {id: string, element: PollElement}[] = []; /* const connectedPolls: {id: string, element: PollElement}[] = [];
rootScope.on('poll_update', (e) => { rootScope.on('poll_update', (e) => {
const {poll, results} = e.detail as {poll: Poll, results: PollResults}; const {poll, results} = e as {poll: Poll, results: PollResults};
//console.log('poll_update', poll, results); //console.log('poll_update', poll, results);
for(const connected of connectedPolls) { for(const connected of connectedPolls) {
@ -79,7 +79,7 @@ rootScope.on('poll_update', (e) => {
}); */ }); */
rootScope.on('poll_update', (e) => { rootScope.on('poll_update', (e) => {
const {poll, results} = e.detail as {poll: Poll, results: PollResults}; const {poll, results} = e as {poll: Poll, results: PollResults};
const pollElement = document.querySelector(`poll-element[poll-id="${poll.id}"]`) as PollElement; const pollElement = document.querySelector(`poll-element[poll-id="${poll.id}"]`) as PollElement;
//console.log('poll_update', poll, results); //console.log('poll_update', poll, results);

4
src/components/sidebarLeft/index.ts

@ -160,8 +160,8 @@ export class AppSidebarLeft extends SidebarSlider {
}); });
rootScope.on('dialogs_archived_unread', (e) => { rootScope.on('dialogs_archived_unread', (e) => {
this.archivedCount.innerText = '' + formatNumber(e.detail.count, 1); this.archivedCount.innerText = '' + formatNumber(e.count, 1);
this.archivedCount.classList.toggle('hide', !e.detail.count); this.archivedCount.classList.toggle('hide', !e.count);
}); });
appUsersManager.getTopPeers(); appUsersManager.getTopPeers();

6
src/components/sidebarLeft/tabs/chatFolders.ts

@ -160,7 +160,7 @@ export default class AppChatFoldersTab extends SliderSuperTab {
}); });
this.rootScope.on('filter_update', (e) => { this.rootScope.on('filter_update', (e) => {
const filter = e.detail; const filter = e;
if(this.filtersRendered.hasOwnProperty(filter.id)) { if(this.filtersRendered.hasOwnProperty(filter.id)) {
this.renderFolder(filter, null, this.filtersRendered[filter.id]); this.renderFolder(filter, null, this.filtersRendered[filter.id]);
} else { } else {
@ -171,7 +171,7 @@ export default class AppChatFoldersTab extends SliderSuperTab {
}); });
this.rootScope.on('filter_delete', (e) => { this.rootScope.on('filter_delete', (e) => {
const filter = e.detail; const filter = e;
if(this.filtersRendered.hasOwnProperty(filter.id)) { if(this.filtersRendered.hasOwnProperty(filter.id)) {
/* for(const suggested of this.suggestedFilters) { /* for(const suggested of this.suggestedFilters) {
if(deepEqual(suggested.filter, filter)) { if(deepEqual(suggested.filter, filter)) {
@ -186,7 +186,7 @@ export default class AppChatFoldersTab extends SliderSuperTab {
}); });
this.rootScope.on('filter_order', (e) => { this.rootScope.on('filter_order', (e) => {
const order = e.detail; const order = e;
order.forEach((filterId, idx) => { order.forEach((filterId, idx) => {
const div = this.filtersRendered[filterId]; const div = this.filtersRendered[filterId];
positionElementByIndex(div, div.parentElement, idx + 1); // ! + 1 due to header positionElementByIndex(div, div.parentElement, idx + 1); // ! + 1 due to header

6
src/components/sidebarRight/tabs/sharedMedia.ts

@ -84,7 +84,7 @@ export default class AppSharedMediaTab implements SliderTab {
}); });
rootScope.on('dialog_notify_settings', (e) => { rootScope.on('dialog_notify_settings', (e) => {
if(this.peerId == e.detail) { if(this.peerId == e) {
const muted = appMessagesManager.isPeerMuted(this.peerId); const muted = appMessagesManager.isPeerMuted(this.peerId);
this.profileElements.notificationsCheckbox.checked = !muted; this.profileElements.notificationsCheckbox.checked = !muted;
this.profileElements.notificationsStatus.innerText = muted ? 'Disabled' : 'Enabled'; this.profileElements.notificationsStatus.innerText = muted ? 'Disabled' : 'Enabled';
@ -92,7 +92,7 @@ export default class AppSharedMediaTab implements SliderTab {
}); });
rootScope.on('peer_typings', (e) => { rootScope.on('peer_typings', (e) => {
const {peerId} = e.detail; const {peerId} = e;
if(this.peerId == peerId) { if(this.peerId == peerId) {
this.setPeerStatus(); this.setPeerStatus();
@ -100,7 +100,7 @@ export default class AppSharedMediaTab implements SliderTab {
}); });
rootScope.on('user_update', (e) => { rootScope.on('user_update', (e) => {
const userId = e.detail; const userId = e;
if(this.peerId == userId) { if(this.peerId == userId) {
this.setPeerStatus(); this.setPeerStatus();

45
src/helpers/fastSmoothScroll.ts

@ -4,6 +4,7 @@ import { dispatchHeavyAnimationEvent } from '../hooks/useHeavyAnimationCheck';
import { fastRaf } from './schedulers'; import { fastRaf } from './schedulers';
import { animateSingle, cancelAnimationByKey } from './animation'; import { animateSingle, cancelAnimationByKey } from './animation';
import rootScope from '../lib/rootScope'; import rootScope from '../lib/rootScope';
import { isInDOM } from './dom';
const MAX_DISTANCE = 1500; const MAX_DISTANCE = 1500;
const MIN_JS_DURATION = 250; const MIN_JS_DURATION = 250;
@ -42,7 +43,7 @@ export default function fastSmoothScroll(
return Promise.resolve(); */ return Promise.resolve(); */
} }
if(axis === 'y') { if(axis === 'y' && isInDOM(element)) {
const elementRect = element.getBoundingClientRect(); const elementRect = element.getBoundingClientRect();
const containerRect = container.getBoundingClientRect(); const containerRect = container.getBoundingClientRect();
@ -58,6 +59,21 @@ export default function fastSmoothScroll(
} else if(forceDirection === FocusDirection.Down) { // * not tested yet } else if(forceDirection === FocusDirection.Down) { // * not tested yet
container.scrollTop = Math.max(0, offsetTop + container.scrollTop - maxDistance); container.scrollTop = Math.max(0, offsetTop + container.scrollTop - maxDistance);
} }
/* const { offsetTop } = element;
if(forceDirection === undefined) {
const offset = offsetTop - container.scrollTop;
if(offset < -maxDistance) {
container.scrollTop += (offset + maxDistance);
} else if(offset > maxDistance) {
container.scrollTop += (offset - maxDistance);
}
} else if(forceDirection === FocusDirection.Up) {
container.scrollTop = offsetTop + maxDistance;
} else if(forceDirection === FocusDirection.Down) {
container.scrollTop = Math.max(0, offsetTop - maxDistance);
} */
} }
const promise = new Promise((resolve) => { const promise = new Promise((resolve) => {
@ -73,6 +89,11 @@ export default function fastSmoothScroll(
function scrollWithJs( function scrollWithJs(
container: HTMLElement, element: HTMLElement, position: ScrollLogicalPosition, margin = 0, forceDuration?: number, axis: 'x' | 'y' = 'y' container: HTMLElement, element: HTMLElement, position: ScrollLogicalPosition, margin = 0, forceDuration?: number, axis: 'x' | 'y' = 'y'
) { ) {
if(!isInDOM(element)) {
cancelAnimationByKey(container);
return Promise.resolve();
}
const rectStartKey = axis === 'y' ? 'top' : 'left'; const rectStartKey = axis === 'y' ? 'top' : 'left';
const rectEndKey = axis === 'y' ? 'bottom' : 'right'; const rectEndKey = axis === 'y' ? 'bottom' : 'right';
const sizeKey = axis === 'y' ? 'height' : 'width'; const sizeKey = axis === 'y' ? 'height' : 'width';
@ -90,6 +111,12 @@ function scrollWithJs(
const scrollPosition = container[scrollPositionKey]; const scrollPosition = container[scrollPositionKey];
const scrollSize = container[scrollSizeKey]; const scrollSize = container[scrollSizeKey];
/* const elementPosition = element.offsetTop;
const elementSize = element.offsetHeight;
const scrollPosition = container[scrollPositionKey];
const scrollSize = container[scrollSizeKey];
const containerSize = container.offsetHeight; */
let path!: number; let path!: number;
@ -98,7 +125,6 @@ function scrollWithJs(
path = elementPosition - margin; path = elementPosition - margin;
break; break;
case 'end': case 'end':
//path = (elementTop + elementHeight + margin) - containerHeight;
path = elementRect[rectEndKey] + (elementSize - elementRect[sizeKey]) - containerRect[rectEndKey]; path = elementRect[rectEndKey] + (elementSize - elementRect[sizeKey]) - containerRect[rectEndKey];
break; break;
// 'nearest' is not supported yet // 'nearest' is not supported yet
@ -109,6 +135,21 @@ function scrollWithJs(
: elementPosition - margin; : elementPosition - margin;
break; break;
} }
/* switch (position) {
case 'start':
path = (elementPosition - margin) - scrollPosition;
break;
case 'end':
path = (elementPosition + elementSize + margin) - (scrollPosition + containerSize);
break;
// 'nearest' is not supported yet
case 'nearest':
case 'center':
path = elementSize < containerSize
? (elementPosition + elementSize / 2) - (scrollPosition + containerSize / 2)
: (elementPosition - margin) - scrollPosition;
break;
} */
// console.log('scrollWithJs: will scroll path:', path, element); // console.log('scrollWithJs: will scroll path:', path, element);

9
src/hooks/useHeavyAnimationCheck.ts

@ -5,6 +5,7 @@ import { AnyToVoidFunction } from '../types';
import ListenerSetter from '../helpers/listenerSetter'; import ListenerSetter from '../helpers/listenerSetter';
import { CancellablePromise, deferredPromise } from '../helpers/cancellablePromise'; import { CancellablePromise, deferredPromise } from '../helpers/cancellablePromise';
import { pause } from '../helpers/schedulers'; import { pause } from '../helpers/schedulers';
import rootScope from '../lib/rootScope';
const ANIMATION_START_EVENT = 'event-heavy-animation-start'; const ANIMATION_START_EVENT = 'event-heavy-animation-start';
const ANIMATION_END_EVENT = 'event-heavy-animation-end'; const ANIMATION_END_EVENT = 'event-heavy-animation-end';
@ -16,7 +17,7 @@ let promisesInQueue = 0;
export const dispatchHeavyAnimationEvent = (promise: Promise<any>, timeout?: number) => { export const dispatchHeavyAnimationEvent = (promise: Promise<any>, timeout?: number) => {
if(!isAnimating) { if(!isAnimating) {
heavyAnimationPromise = deferredPromise<void>(); heavyAnimationPromise = deferredPromise<void>();
document.dispatchEvent(new Event(ANIMATION_START_EVENT)); rootScope.broadcast(ANIMATION_START_EVENT);
isAnimating = true; isAnimating = true;
console.log('dispatchHeavyAnimationEvent: start'); console.log('dispatchHeavyAnimationEvent: start');
} }
@ -36,7 +37,7 @@ export const dispatchHeavyAnimationEvent = (promise: Promise<any>, timeout?: num
if(!promisesInQueue) { if(!promisesInQueue) {
isAnimating = false; isAnimating = false;
promisesInQueue = 0; promisesInQueue = 0;
document.dispatchEvent(new Event(ANIMATION_END_EVENT)); rootScope.broadcast(ANIMATION_END_EVENT);
heavyAnimationPromise.resolve(); heavyAnimationPromise.resolve();
console.log('dispatchHeavyAnimationEvent: end'); console.log('dispatchHeavyAnimationEvent: end');
@ -58,8 +59,8 @@ export default (
handleAnimationStart(); handleAnimationStart();
} }
const add = listenerSetter ? listenerSetter.add.bind(listenerSetter, document) : document.addEventListener.bind(document); const add = listenerSetter ? listenerSetter.add.bind(listenerSetter, rootScope) : rootScope.addEventListener.bind(rootScope);
const remove = listenerSetter ? listenerSetter.removeManual.bind(listenerSetter, document) : document.removeEventListener.bind(document); const remove = listenerSetter ? listenerSetter.removeManual.bind(listenerSetter, rootScope) : rootScope.removeEventListener.bind(rootScope);
add(ANIMATION_START_EVENT, handleAnimationStart); add(ANIMATION_START_EVENT, handleAnimationStart);
add(ANIMATION_END_EVENT, handleAnimationEnd); add(ANIMATION_END_EVENT, handleAnimationEnd);

2
src/lib/appManagers/appChatsManager.ts

@ -80,7 +80,7 @@ export class AppChatsManager {
constructor() { constructor() {
rootScope.on('apiUpdate', (e) => { rootScope.on('apiUpdate', (e) => {
// console.log('on apiUpdate', update) // console.log('on apiUpdate', update)
const update = e.detail; const update = e;
switch(update._) { switch(update._) {
case 'updateChannel': case 'updateChannel':
const channelId = update.channel_id; const channelId = update.channel_id;

30
src/lib/appManagers/appDialogsManager.ts

@ -67,14 +67,14 @@ class ConnectionStatusComponent {
chatsContainer.prepend(this.statusContainer); chatsContainer.prepend(this.statusContainer);
rootScope.on('connection_status_change', (e) => { rootScope.on('connection_status_change', (e) => {
const status = e.detail; const status = e;
console.log(status); console.log(status);
setConnectionStatus(); setConnectionStatus();
}); });
rootScope.on('state_synchronizing', (e) => { rootScope.on('state_synchronizing', (e) => {
const channelId = e.detail; const channelId = e;
if(!channelId) { if(!channelId) {
this.updating = true; this.updating = true;
this.log('updating', this.updating); this.log('updating', this.updating);
@ -83,7 +83,7 @@ class ConnectionStatusComponent {
}); });
rootScope.on('state_synchronized', (e) => { rootScope.on('state_synchronized', (e) => {
const channelId = e.detail; const channelId = e;
this.log('state_synchronized', channelId); this.log('state_synchronized', channelId);
if(!channelId) { if(!channelId) {
this.updating = false; this.updating = false;
@ -259,7 +259,7 @@ export class AppDialogsManager {
} }
rootScope.on('user_update', (e) => { rootScope.on('user_update', (e) => {
const userId = e.detail; const userId = e;
const user = appUsersManager.getUser(userId); const user = appUsersManager.getUser(userId);
const dialog = appMessagesManager.getDialogByPeerId(user.id)[0]; const dialog = appMessagesManager.getDialogByPeerId(user.id)[0];
//console.log('updating user:', user, dialog); //console.log('updating user:', user, dialog);
@ -275,7 +275,7 @@ export class AppDialogsManager {
}); });
/* rootScope.$on('dialog_top', (e) => { /* rootScope.$on('dialog_top', (e) => {
const dialog = e.detail; const dialog = e;
this.setLastMessage(dialog); this.setLastMessage(dialog);
this.setDialogPosition(dialog); this.setDialogPosition(dialog);
@ -284,7 +284,7 @@ export class AppDialogsManager {
}); */ }); */
rootScope.on('dialog_flush', (e) => { rootScope.on('dialog_flush', (e) => {
const peerId: number = e.detail.peerId; const peerId: number = e.peerId;
const dialog = appMessagesManager.getDialogByPeerId(peerId)[0]; const dialog = appMessagesManager.getDialogByPeerId(peerId)[0];
if(dialog) { if(dialog) {
this.setLastMessage(dialog); this.setLastMessage(dialog);
@ -294,7 +294,7 @@ export class AppDialogsManager {
}); });
rootScope.on('dialogs_multiupdate', (e) => { rootScope.on('dialogs_multiupdate', (e) => {
const dialogs = e.detail; const dialogs = e;
for(const id in dialogs) { for(const id in dialogs) {
const dialog = dialogs[id]; const dialog = dialogs[id];
@ -306,7 +306,7 @@ export class AppDialogsManager {
}); });
rootScope.on('dialog_drop', (e) => { rootScope.on('dialog_drop', (e) => {
const {peerId, dialog} = e.detail; const {peerId, dialog} = e;
const dom = this.getDialogDom(peerId); const dom = this.getDialogDom(peerId);
if(dom) { if(dom) {
@ -318,7 +318,7 @@ export class AppDialogsManager {
}); });
rootScope.on('dialog_unread', (e) => { rootScope.on('dialog_unread', (e) => {
const info = e.detail; const info = e;
const dialog = appMessagesManager.getDialogByPeerId(info.peerId)[0]; const dialog = appMessagesManager.getDialogByPeerId(info.peerId)[0];
if(dialog) { if(dialog) {
@ -329,14 +329,14 @@ export class AppDialogsManager {
}); });
rootScope.on('dialog_notify_settings', e => { rootScope.on('dialog_notify_settings', e => {
const dialog = appMessagesManager.getDialogByPeerId(e.detail)[0]; const dialog = appMessagesManager.getDialogByPeerId(e)[0];
if(dialog) { if(dialog) {
this.setUnreadMessages(dialog); // возможно это не нужно, но нужно менять is-muted this.setUnreadMessages(dialog); // возможно это не нужно, но нужно менять is-muted
} }
}); });
rootScope.on('peer_changed', (e) => { rootScope.on('peer_changed', (e) => {
const peerId = e.detail; const peerId = e;
//const perf = performance.now(); //const perf = performance.now();
for(const element of this.lastActiveElements) { for(const element of this.lastActiveElements) {
@ -355,7 +355,7 @@ export class AppDialogsManager {
}); });
rootScope.on('filter_update', (e) => { rootScope.on('filter_update', (e) => {
const filter: DialogFilter = e.detail; const filter: DialogFilter = e;
if(!this.filtersRendered[filter.id]) { if(!this.filtersRendered[filter.id]) {
this.addFilter(filter); this.addFilter(filter);
return; return;
@ -375,7 +375,7 @@ export class AppDialogsManager {
}); });
rootScope.on('filter_delete', (e) => { rootScope.on('filter_delete', (e) => {
const filter: DialogFilter = e.detail; const filter: DialogFilter = e;
const elements = this.filtersRendered[filter.id]; const elements = this.filtersRendered[filter.id];
if(!elements) return; if(!elements) return;
@ -395,7 +395,7 @@ export class AppDialogsManager {
}); });
rootScope.on('filter_order', (e) => { rootScope.on('filter_order', (e) => {
const order = e.detail; const order = e;
const containerToAppend = this.folders.menu.firstElementChild as HTMLUListElement; const containerToAppend = this.folders.menu.firstElementChild as HTMLUListElement;
order.forEach((filterId) => { order.forEach((filterId) => {
@ -413,7 +413,7 @@ export class AppDialogsManager {
}); });
rootScope.on('peer_typings', (e) => { rootScope.on('peer_typings', (e) => {
const {peerId, typings} = e.detail; const {peerId, typings} = e;
const dialog = appMessagesManager.getDialogByPeerId(peerId)[0]; const dialog = appMessagesManager.getDialogByPeerId(peerId)[0];
if(!dialog) return; if(!dialog) return;

2
src/lib/appManagers/appDownloadManager.ts

@ -32,7 +32,7 @@ export class AppDownloadManager {
constructor() { constructor() {
rootScope.on('download_progress', (e) => { rootScope.on('download_progress', (e) => {
const details = e.detail as {done: number, fileName: string, total: number, offset: number}; const details = e as {done: number, fileName: string, total: number, offset: number};
this.progress[details.fileName] = details; this.progress[details.fileName] = details;
const callbacks = this.progressCallbacks[details.fileName]; const callbacks = this.progressCallbacks[details.fileName];

6
src/lib/appManagers/appImManager.ts

@ -258,7 +258,7 @@ export class AppImManager {
document.body.addEventListener('keydown', onKeyDown); document.body.addEventListener('keydown', onKeyDown);
rootScope.addEventListener('history_multiappend', (e) => { rootScope.addEventListener('history_multiappend', (e) => {
const msgIdsByPeer = e.detail; const msgIdsByPeer = e;
for(const peerId in msgIdsByPeer) { for(const peerId in msgIdsByPeer) {
appSidebarRight.sharedMediaTab.renderNewMessages(+peerId, msgIdsByPeer[peerId]); appSidebarRight.sharedMediaTab.renderNewMessages(+peerId, msgIdsByPeer[peerId]);
@ -266,7 +266,7 @@ export class AppImManager {
}); });
rootScope.addEventListener('history_delete', (e) => { rootScope.addEventListener('history_delete', (e) => {
const {peerId, msgs} = e.detail; const {peerId, msgs} = e;
const mids = Object.keys(msgs).map(s => +s); const mids = Object.keys(msgs).map(s => +s);
appSidebarRight.sharedMediaTab.deleteDeletedMessages(peerId, mids); appSidebarRight.sharedMediaTab.deleteDeletedMessages(peerId, mids);
@ -274,7 +274,7 @@ export class AppImManager {
// Calls when message successfully sent and we have an id // Calls when message successfully sent and we have an id
rootScope.addEventListener('message_sent', (e) => { rootScope.addEventListener('message_sent', (e) => {
const {storage, tempId, mid} = e.detail; const {storage, tempId, mid} = e;
const message = appMessagesManager.getMessageFromStorage(storage, mid); const message = appMessagesManager.getMessageFromStorage(storage, mid);
appSidebarRight.sharedMediaTab.renderNewMessages(message.peerId, [mid]); appSidebarRight.sharedMediaTab.renderNewMessages(message.peerId, [mid]);
}); });

60
src/lib/appManagers/appMessagesManager.ts

@ -13,7 +13,7 @@ import { logger, LogLevels } from "../logger";
import type { ApiFileManager } from '../mtproto/apiFileManager'; import type { ApiFileManager } from '../mtproto/apiFileManager';
//import apiManager from '../mtproto/apiManager'; //import apiManager from '../mtproto/apiManager';
import apiManager from '../mtproto/mtprotoworker'; import apiManager from '../mtproto/mtprotoworker';
import { MOUNT_CLASS_TO } from "../mtproto/mtproto_config"; import { MOUNT_CLASS_TO, DEBUG } from "../mtproto/mtproto_config";
import referenceDatabase, { ReferenceContext } from "../mtproto/referenceDatabase"; import referenceDatabase, { ReferenceContext } from "../mtproto/referenceDatabase";
import serverTimeManager from "../mtproto/serverTimeManager"; import serverTimeManager from "../mtproto/serverTimeManager";
import { RichTextProcessor } from "../richtextprocessor"; import { RichTextProcessor } from "../richtextprocessor";
@ -178,11 +178,11 @@ export class AppMessagesManager {
this.filtersStorage = new FiltersStorage(appPeersManager, appUsersManager, /* apiManager, */ rootScope); this.filtersStorage = new FiltersStorage(appPeersManager, appUsersManager, /* apiManager, */ rootScope);
rootScope.on('apiUpdate', (e) => { rootScope.on('apiUpdate', (e) => {
this.handleUpdate(e.detail); this.handleUpdate(e);
}); });
rootScope.on('webpage_updated', (e) => { rootScope.on('webpage_updated', (e) => {
const eventData = e.detail; const eventData = e;
eventData.msgs.forEach((mid) => { eventData.msgs.forEach((mid) => {
const message = this.getMessageById(mid) as Message.message; const message = this.getMessageById(mid) as Message.message;
if(!message) return; if(!message) return;
@ -202,7 +202,7 @@ export class AppMessagesManager {
}); });
/* rootScope.$on('draft_updated', (e) => { /* rootScope.$on('draft_updated', (e) => {
let eventData = e.detail;; let eventData = e;;
var peerId = eventData.peerId; var peerId = eventData.peerId;
var draft = eventData.draft; var draft = eventData.draft;
@ -396,7 +396,7 @@ export class AppMessagesManager {
if(message.pFlags.is_outgoing) { if(message.pFlags.is_outgoing) {
return this.invokeAfterMessageIsSent(mid, 'edit', (message) => { return this.invokeAfterMessageIsSent(mid, 'edit', (message) => {
this.log('invoke editMessage callback', message); //this.log('invoke editMessage callback', message);
return this.editMessage(message, text, options); return this.editMessage(message, text, options);
}); });
} }
@ -799,7 +799,7 @@ export class AppMessagesManager {
appDocsManager.saveDoc(document); appDocsManager.saveDoc(document);
} }
this.log('AMM: sendFile', attachType, apiFileName, file.type, options); this.log('sendFile', attachType, apiFileName, file.type, options);
const preloader = new ProgressivePreloader(null, true, false, 'prepend'); const preloader = new ProgressivePreloader(null, true, false, 'prepend');
@ -883,7 +883,9 @@ export class AppMessagesManager {
} }
uploadPromise && uploadPromise.then(async(inputFile) => { uploadPromise && uploadPromise.then(async(inputFile) => {
this.log('appMessagesManager: sendFile uploaded:', inputFile); /* if(DEBUG) {
this.log('appMessagesManager: sendFile uploaded:', inputFile);
} */
delete message.media.preloader; delete message.media.preloader;
@ -922,7 +924,10 @@ export class AppMessagesManager {
}); });
uploadPromise.addNotifyListener((progress: {done: number, total: number}) => { uploadPromise.addNotifyListener((progress: {done: number, total: number}) => {
this.log('upload progress', progress); /* if(DEBUG) {
this.log('upload progress', progress);
} */
const percents = Math.max(1, Math.floor(100 * progress.done / progress.total)); const percents = Math.max(1, Math.floor(100 * progress.done / progress.total));
this.setTyping(peerId, {_: actionName, progress: percents | 0}); this.setTyping(peerId, {_: actionName, progress: percents | 0});
}); });
@ -1021,7 +1026,7 @@ export class AppMessagesManager {
caption = RichTextProcessor.parseMarkdown(caption, entities); caption = RichTextProcessor.parseMarkdown(caption, entities);
} }
this.log('AMM: sendAlbum', files, options); this.log('sendAlbum', files, options);
const messages = files.map((file, idx) => { const messages = files.map((file, idx) => {
const details = options.sendFileDetails[idx]; const details = options.sendFileDetails[idx];
@ -1445,7 +1450,9 @@ export class AppMessagesManager {
public cancelPendingMessage(randomId: string) { public cancelPendingMessage(randomId: string) {
const pendingData = this.pendingByRandomId[randomId]; const pendingData = this.pendingByRandomId[randomId];
this.log('cancelPendingMessage', randomId, pendingData); /* if(DEBUG) {
this.log('cancelPendingMessage', randomId, pendingData);
} */
if(pendingData) { if(pendingData) {
const {peerId, tempId, storage} = pendingData; const {peerId, tempId, storage} = pendingData;
@ -1797,7 +1804,7 @@ export class AppMessagesManager {
[].concat(peerId).forEach(peerId => { [].concat(peerId).forEach(peerId => {
if(!this.reloadConversationsPeers.includes(peerId)) { if(!this.reloadConversationsPeers.includes(peerId)) {
this.reloadConversationsPeers.push(peerId); this.reloadConversationsPeers.push(peerId);
this.log('will reloadConversation', peerId); //this.log('will reloadConversation', peerId);
} }
}); });
@ -1917,7 +1924,7 @@ export class AppMessagesManager {
pm_oneside: oneSide, pm_oneside: oneSide,
id: this.getLocalMessageId(mid) id: this.getLocalMessageId(mid)
}).then(updates => { }).then(updates => {
this.log('pinned updates:', updates); //this.log('pinned updates:', updates);
apiUpdatesManager.processUpdateMessage(updates); apiUpdatesManager.processUpdateMessage(updates);
}); });
} }
@ -2509,7 +2516,7 @@ export class AppMessagesManager {
}; };
}) })
}).then(updates => { }).then(updates => {
this.log('editPeerFolders updates:', updates); //this.log('editPeerFolders updates:', updates);
apiUpdatesManager.processUpdateMessage(updates); // WARNING! возможно тут нужно добавлять channelId, и вызывать апдейт для каждого канала отдельно apiUpdatesManager.processUpdateMessage(updates); // WARNING! возможно тут нужно добавлять channelId, и вызывать апдейт для каждого канала отдельно
}); });
} }
@ -3145,7 +3152,9 @@ export class AppMessagesManager {
storage.count = searchResult.count; storage.count = searchResult.count;
} }
this.log('getSearch result:', inputFilter, searchResult); if(DEBUG) {
this.log('getSearch result:', inputFilter, searchResult);
}
const foundCount: number = searchResult.count || (foundMsgs.length + searchResult.messages.length); const foundCount: number = searchResult.count || (foundMsgs.length + searchResult.messages.length);
@ -3456,7 +3465,10 @@ export class AppMessagesManager {
} }
public handleUpdate(update: Update) { public handleUpdate(update: Update) {
this.log.debug('handleUpdate', update._, update); /* if(DEBUG) {
this.log.debug('handleUpdate', update._, update);
} */
switch(update._) { switch(update._) {
case 'updateMessageID': { case 'updateMessageID': {
const randomId = update.random_id; const randomId = update.random_id;
@ -3562,7 +3574,7 @@ export class AppMessagesManager {
} }
case 'updateDialogUnreadMark': { case 'updateDialogUnreadMark': {
this.log('updateDialogUnreadMark', update); //this.log('updateDialogUnreadMark', update);
const peerId = appPeersManager.getPeerId((update.peer as DialogPeer.dialogPeer).peer); const peerId = appPeersManager.getPeerId((update.peer as DialogPeer.dialogPeer).peer);
const foundDialog = this.getDialogByPeerId(peerId); const foundDialog = this.getDialogByPeerId(peerId);
@ -3585,7 +3597,7 @@ export class AppMessagesManager {
} }
case 'updateFolderPeers': { // only 0 and 1 folders case 'updateFolderPeers': { // only 0 and 1 folders
this.log('updateFolderPeers', update); //this.log('updateFolderPeers', update);
const peers = update.folder_peers; const peers = update.folder_peers;
this.scheduleHandleNewDialogs(); this.scheduleHandleNewDialogs();
@ -3616,7 +3628,7 @@ export class AppMessagesManager {
case 'updateDialogPinned': { case 'updateDialogPinned': {
const folderId = update.folder_id ?? 0; const folderId = update.folder_id ?? 0;
this.log('updateDialogPinned', update); //this.log('updateDialogPinned', update);
const peerId = appPeersManager.getPeerId((update.peer as DialogPeer.dialogPeer).peer); const peerId = appPeersManager.getPeerId((update.peer as DialogPeer.dialogPeer).peer);
const foundDialog = this.getDialogByPeerId(peerId); const foundDialog = this.getDialogByPeerId(peerId);
@ -3688,7 +3700,7 @@ export class AppMessagesManager {
} }
}; };
this.log('updatePinnedDialogs', update); //this.log('updatePinnedDialogs', update);
const newPinned: {[peerId: number]: true} = {}; const newPinned: {[peerId: number]: true} = {};
if(!update.order) { if(!update.order) {
apiManager.invokeApi('messages.getPinnedDialogs', { apiManager.invokeApi('messages.getPinnedDialogs', {
@ -4009,7 +4021,7 @@ export class AppMessagesManager {
} }
case 'updateServiceNotification': { case 'updateServiceNotification': {
this.log('updateServiceNotification', update); //this.log('updateServiceNotification', update);
const fromId = 777000; const fromId = 777000;
const peerId = fromId; const peerId = fromId;
const messageId = this.generateTempMessageId(peerId); const messageId = this.generateTempMessageId(peerId);
@ -4309,11 +4321,11 @@ export class AppMessagesManager {
public finalizePendingMessageCallbacks(storage: MessagesStorage, tempId: number, mid: number) { public finalizePendingMessageCallbacks(storage: MessagesStorage, tempId: number, mid: number) {
const message = this.getMessageFromStorage(storage, mid); const message = this.getMessageFromStorage(storage, mid);
const callbacks = this.tempFinalizeCallbacks[tempId]; const callbacks = this.tempFinalizeCallbacks[tempId];
this.log.warn(callbacks, tempId); //this.log.warn(callbacks, tempId);
if(callbacks !== undefined) { if(callbacks !== undefined) {
for(const name in callbacks) { for(const name in callbacks) {
const {deferred, callback} = callbacks[name]; const {deferred, callback} = callbacks[name];
this.log(`finalizePendingMessageCallbacks: will invoke ${name} callback`); //this.log(`finalizePendingMessageCallbacks: will invoke ${name} callback`);
callback(message).then(deferred.resolve, deferred.reject); callback(message).then(deferred.resolve, deferred.reject);
} }
@ -4589,7 +4601,9 @@ export class AppMessagesManager {
}) as any; }) as any;
return promise.then((historyResult) => { return promise.then((historyResult) => {
this.log('requestHistory result:', peerId, historyResult, maxId, limit, offset); if(DEBUG) {
this.log('requestHistory result:', peerId, historyResult, maxId, limit, offset);
}
appUsersManager.saveApiUsers(historyResult.users); appUsersManager.saveApiUsers(historyResult.users);
appChatsManager.saveApiChats(historyResult.chats); appChatsManager.saveApiChats(historyResult.chats);

2
src/lib/appManagers/appPollsManager.ts

@ -78,7 +78,7 @@ export class AppPollsManager {
constructor() { constructor() {
rootScope.on('apiUpdate', (e) => { rootScope.on('apiUpdate', (e) => {
const update = e.detail; const update = e;
this.handleUpdate(update); this.handleUpdate(update);
}); });

2
src/lib/appManagers/appStickersManager.ts

@ -35,7 +35,7 @@ export class AppStickersManager {
}); });
rootScope.on('apiUpdate', (e) => { rootScope.on('apiUpdate', (e) => {
const update = e.detail; const update = e;
switch(update._) { switch(update._) {
case 'updateNewStickerSet': { case 'updateNewStickerSet': {

2
src/lib/appManagers/appUsersManager.ts

@ -36,7 +36,7 @@ export class AppUsersManager {
rootScope.on('state_synchronized', this.updateUsersStatuses); rootScope.on('state_synchronized', this.updateUsersStatuses);
rootScope.on('apiUpdate', (e) => { rootScope.on('apiUpdate', (e) => {
const update = e.detail as Update; const update = e as Update;
//console.log('on apiUpdate', update); //console.log('on apiUpdate', update);
switch(update._) { switch(update._) {
case 'updateUserStatus': case 'updateUserStatus':

2
src/lib/appManagers/appWebPagesManager.ts

@ -16,7 +16,7 @@ export class AppWebPagesManager {
constructor() { constructor() {
rootScope.on('apiUpdate', (e) => { rootScope.on('apiUpdate', (e) => {
const update = e.detail; const update = e;
switch(update._) { switch(update._) {
case 'updateWebPage': case 'updateWebPage':

27
src/lib/rootScope.ts

@ -7,6 +7,7 @@ import type { ConnectionStatusChange } from "../types";
import type { UserTyping } from "./appManagers/appChatsManager"; import type { UserTyping } from "./appManagers/appChatsManager";
import { DEBUG, MOUNT_CLASS_TO, UserAuth } from "./mtproto/mtproto_config"; import { DEBUG, MOUNT_CLASS_TO, UserAuth } from "./mtproto/mtproto_config";
import { State } from "./appManagers/appStateManager"; import { State } from "./appManagers/appStateManager";
import EventListenerBase from "../helpers/eventListenerBase";
type BroadcastEvents = { type BroadcastEvents = {
'user_update': number, 'user_update': number,
@ -76,9 +77,12 @@ type BroadcastEvents = {
'connection_status_change': ConnectionStatusChange, 'connection_status_change': ConnectionStatusChange,
'settings_updated': {key: string, value: any}, 'settings_updated': {key: string, value: any},
//'draft_updated': any, //'draft_updated': any,
'event-heavy-animation-start': void,
'event-heavy-animation-end': void
}; };
class RootScope { class RootScope extends EventListenerBase<any> {
public overlayIsActive: boolean = false; public overlayIsActive: boolean = false;
public myId = 0; public myId = 0;
public idle = { public idle = {
@ -88,13 +92,15 @@ class RootScope {
public settings: State['settings']; public settings: State['settings'];
constructor() { constructor() {
super();
this.on('user_auth', (e) => { this.on('user_auth', (e) => {
this.myId = e.detail; this.myId = e;
}); });
this.on('connection_status_change', (e) => { this.on('connection_status_change', (e) => {
const status = e.detail; const status = e;
this.connectionStatus[e.detail.name] = status; this.connectionStatus[e.name] = status;
}); });
} }
@ -105,20 +111,17 @@ class RootScope {
} }
} */ } */
const myCustomEvent = new CustomEvent(name, {detail}); this.setListenerResult(name, detail);
document.dispatchEvent(myCustomEvent);
}; };
public on = <T extends keyof BroadcastEvents>(name: T, callback: (e: Omit<CustomEvent, 'detail'> & {detail: BroadcastEvents[T]}) => any) => { public on = <T extends keyof BroadcastEvents>(name: T, callback: (e: BroadcastEvents[T]) => any) => {
// @ts-ignore this.addListener(name, callback);
document.addEventListener(name, callback);
}; };
public addEventListener = this.on; public addEventListener = this.on;
public off = <T extends keyof BroadcastEvents>(name: T, callback: (e: Omit<CustomEvent, 'detail'> & {detail: BroadcastEvents[T]}) => any) => { public off = <T extends keyof BroadcastEvents>(name: T, callback: (e: BroadcastEvents[T]) => any) => {
// @ts-ignore this.removeListener(name, callback);
document.removeEventListener(name, callback);
}; };
public removeEventListener = this.off; public removeEventListener = this.off;

2
src/lib/storages/filters.ts

@ -24,7 +24,7 @@ export default class FiltersStorage {
constructor(private appPeersManager: AppPeersManager, private appUsersManager: AppUsersManager, /* private apiManager: ApiManagerProxy, */ private rootScope: typeof _rootScope) { constructor(private appPeersManager: AppPeersManager, private appUsersManager: AppUsersManager, /* private apiManager: ApiManagerProxy, */ private rootScope: typeof _rootScope) {
rootScope.on('apiUpdate', (e) => { rootScope.on('apiUpdate', (e) => {
this.handleUpdate(e.detail); this.handleUpdate(e);
}); });
} }

Loading…
Cancel
Save