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."; @@ -17,7 +17,7 @@ import { SearchSuperContext } from "./appSearchSuper.";
import { formatDateAccordingToToday } from "../helpers/date";
rootScope.on('messages_media_read', e => {
const {mids, peerId} = e.detail;
const {mids, peerId} = e;
mids.forEach(mid => {
(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"; @@ -7,7 +7,7 @@ import { Photo } from "../layer";
import type { LazyLoadQueueIntersector } from "./lazyLoadQueue";
rootScope.on('avatar_update', (e) => {
let peerId = e.detail;
let peerId = e;
appProfileManager.removeFromAvatarsCache(peerId);
(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 { @@ -35,7 +35,7 @@ export default class ChatAudio extends PinnedContainer {
this.wrapper.prepend(this.toggleEl);
this.topbar.listenerSetter.add(rootScope, 'audio_play', (e) => {
const {doc, mid, peerId} = e.detail;
const {doc, mid, peerId} = e;
let title: string, subtitle: string;
const message = appMessagesManager.getMessageByPeer(peerId, mid);

158
src/components/chat/bubbles.ts

@ -139,7 +139,7 @@ export default class ChatBubbles { @@ -139,7 +139,7 @@ export default class ChatBubbles {
// will call when sent for update pos
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) {
const bubble = this.bubbles[mid];
@ -162,7 +162,7 @@ export default class ChatBubbles { @@ -162,7 +162,7 @@ export default class ChatBubbles {
});
this.listenerSetter.add(rootScope, 'dialog_flush', (e) => {
let peerId: number = e.detail.peerId;
let peerId: number = e.peerId;
if(this.peerId == peerId) {
this.deleteMessagesByIds(Object.keys(this.bubbles).map(m => +m));
}
@ -170,14 +170,14 @@ export default class ChatBubbles { @@ -170,14 +170,14 @@ export default class ChatBubbles {
// Calls when message successfully sent and we have an id
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
if(this.chat.getMessagesStorage() !== storage) {
return;
}
this.log('message_sent', e.detail);
//this.log('message_sent', e);
const mounted = this.getMountedBubble(tempId, tempMessage) || this.getMountedBubble(mid);
if(mounted) {
@ -226,7 +226,9 @@ export default class ChatBubbles { @@ -226,7 +226,9 @@ export default class ChatBubbles {
this.bubbleGroups.removeBubble(bubble, tempId); */
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);
if(!mounted) return;
this.renderMessage(mounted.message, true, false, mounted.bubble, false); */
@ -234,7 +236,7 @@ export default class ChatBubbles { @@ -234,7 +236,7 @@ export default class ChatBubbles {
//delete this.bubbles[tempId];
} 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]) {
@ -242,8 +244,13 @@ export default class ChatBubbles { @@ -242,8 +244,13 @@ export default class ChatBubbles {
this.bubbles[mid] = bubble;
delete this.bubbles[tempId];
bubble.classList.remove('is-sending');
bubble.classList.add(this.peerId === rootScope.myId && this.chat.type !== 'scheduled' ? 'is-read' : 'is-sent');
//getHeavyAnimationPromise().then(() => {
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;
this.bubbleGroups.removeBubble(bubble, tempId);
@ -258,7 +265,7 @@ export default class ChatBubbles { @@ -258,7 +265,7 @@ export default class ChatBubbles {
if(this.chat.type === 'scheduled') {
const timestamp = Date.now() / 1000 | 0;
const maxTimestamp = tempMessage.date - 10;
this.log('scheduled timing:', timestamp, maxTimestamp);
//this.log('scheduled timing:', timestamp, maxTimestamp);
if(timestamp >= maxTimestamp) {
this.deleteMessagesByIds([mid]);
}
@ -266,36 +273,41 @@ export default class ChatBubbles { @@ -266,36 +273,41 @@ export default class ChatBubbles {
});
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;
const mounted = this.getMountedBubble(mid);
if(!mounted) return;
if(peerId != this.peerId || storage !== this.chat.getMessagesStorage()) return;
const mounted = this.getMountedBubble(mid);
if(!mounted) return;
const updatePosition = this.chat.type === 'scheduled';
this.renderMessage(mounted.message, true, false, mounted.bubble, updatePosition);
const updatePosition = this.chat.type === 'scheduled';
this.renderMessage(mounted.message, true, false, mounted.bubble, updatePosition);
if(updatePosition) {
(this.messagesQueuePromise || Promise.resolve()).then(() => {
this.deleteEmptyDateGroups();
});
}
if(updatePosition) {
(this.messagesQueuePromise || Promise.resolve()).then(() => {
this.deleteEmptyDateGroups();
});
}
});
});
this.listenerSetter.add(rootScope, 'album_edit', (e) => {
const {peerId, groupId, deletedMids} = e.detail;
fastRaf(() => {
const {peerId, groupId, deletedMids} = e;
if(peerId != this.peerId) return;
const mids = this.appMessagesManager.getMidsByAlbum(groupId);
const renderedId = mids.concat(deletedMids).find(mid => this.bubbles[mid]);
if(!renderedId) return;
if(peerId != this.peerId) return;
const mids = this.appMessagesManager.getMidsByAlbum(groupId);
const renderedId = mids.concat(deletedMids).find(mid => this.bubbles[mid]);
if(!renderedId) return;
const renderMaxId = getObjectKeysAndSort(this.appMessagesManager.groupedMessagesStorage[groupId], 'asc').pop();
this.renderMessage(this.chat.getMessage(renderMaxId), true, false, this.bubbles[renderedId], false);
const renderMaxId = getObjectKeysAndSort(this.appMessagesManager.groupedMessagesStorage[groupId], 'asc').pop();
this.renderMessage(this.chat.getMessage(renderMaxId), true, false, this.bubbles[renderedId], false);
});
});
this.listenerSetter.add(rootScope, 'messages_downloaded', (e) => {
const {peerId, mids} = e.detail;
const {peerId, mids} = e;
const middleware = this.getMiddleware();
getHeavyAnimationPromise().then(() => {
@ -330,7 +342,7 @@ export default class ChatBubbles { @@ -330,7 +342,7 @@ export default class ChatBubbles {
});
this.listenerSetter.add(rootScope, 'dialog_drop', (e) => {
if(e.detail.peerId == this.peerId) {
if(e.peerId == this.peerId) {
this.chat.appImManager.setPeer(0);
}
});
@ -368,7 +380,7 @@ export default class ChatBubbles { @@ -368,7 +380,7 @@ export default class ChatBubbles {
public constructPeerHelpers() {
// will call when message is sent (only 1)
this.listenerSetter.add(rootScope, 'history_append', (e) => {
let details = e.detail;
let details = e;
if(!this.scrolledAllDown) {
this.chat.setPeer(this.peerId, 0);
@ -378,7 +390,7 @@ export default class ChatBubbles { @@ -378,7 +390,7 @@ export default class ChatBubbles {
});
this.listenerSetter.add(rootScope, 'history_multiappend', (e) => {
const msgIdsByPeer = e.detail;
const msgIdsByPeer = e;
if(!(this.peerId in msgIdsByPeer)) return;
const msgIds = msgIdsByPeer[this.peerId];
@ -386,7 +398,7 @@ export default class ChatBubbles { @@ -386,7 +398,7 @@ export default class ChatBubbles {
});
this.listenerSetter.add(rootScope, 'history_delete', (e) => {
const {peerId, msgs} = e.detail;
const {peerId, msgs} = e;
const mids = Object.keys(msgs).map(s => +s);
@ -396,7 +408,7 @@ export default class ChatBubbles { @@ -396,7 +408,7 @@ export default class ChatBubbles {
});
this.listenerSetter.add(rootScope, 'dialog_unread', (e) => {
const info = e.detail;
const info = e;
if(info.peerId === this.peerId) {
this.chat.input.setUnreadCount();
@ -405,7 +417,7 @@ export default class ChatBubbles { @@ -405,7 +417,7 @@ export default class ChatBubbles {
});
this.listenerSetter.add(rootScope, 'dialogs_multiupdate', (e) => {
const dialogs = e.detail;
const dialogs = e;
if(dialogs[this.peerId]) {
this.chat.input.setUnreadCount();
@ -413,7 +425,7 @@ export default class ChatBubbles { @@ -413,7 +425,7 @@ export default class ChatBubbles {
});
this.listenerSetter.add(rootScope, 'dialog_notify_settings', (e) => {
const peerId = e.detail;
const peerId = e;
if(this.peerId === peerId) {
this.chat.input.setUnreadCount();
@ -449,7 +461,9 @@ export default class ChatBubbles { @@ -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) {
max = appMessagesIDsManager.getMessageIdInfo(max)[0];
@ -466,7 +480,7 @@ export default class ChatBubbles { @@ -466,7 +480,7 @@ export default class ChatBubbles {
public constructPinnedHelpers() {
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(mids) {
@ -483,7 +497,7 @@ export default class ChatBubbles { @@ -483,7 +497,7 @@ export default class ChatBubbles {
};
this.listenerSetter.add(rootScope, 'scheduled_new', (e) => {
const {peerId, mid} = e.detail;
const {peerId, mid} = e;
if(peerId !== this.peerId) return;
this.renderNewMessagesByIds([mid]);
@ -491,7 +505,7 @@ export default class ChatBubbles { @@ -491,7 +505,7 @@ export default class ChatBubbles {
});
this.listenerSetter.add(rootScope, 'scheduled_delete', (e) => {
const {peerId, mids} = e.detail;
const {peerId, mids} = e;
if(peerId !== this.peerId) return;
this.deleteMessagesByIds(mids);
@ -641,7 +655,9 @@ export default class ChatBubbles { @@ -641,7 +655,9 @@ export default class ChatBubbles {
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]) {
this.log('no target for media viewer!', target);
@ -826,7 +842,10 @@ export default class ChatBubbles { @@ -826,7 +842,10 @@ export default class ChatBubbles {
if(!history.length) return;
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) {
this.log('load more', this.scrollable.scrollHeight, this.scrollable.scrollTop, this.scrollable);
return;
@ -841,7 +860,10 @@ export default class ChatBubbles { @@ -841,7 +860,10 @@ export default class ChatBubbles {
// if scroll down after search
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);
}
}
@ -979,7 +1001,7 @@ export default class ChatBubbles { @@ -979,7 +1001,7 @@ export default class ChatBubbles {
public renderNewMessagesByIds(mids: number[], scrolledDown = this.scrolledDown) {
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;
}
@ -1011,7 +1033,11 @@ export default class ChatBubbles { @@ -1011,7 +1033,11 @@ export default class ChatBubbles {
public scrollToNewLastBubble() {
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) {
this.scrollingToNewBubble = bubble;
this.scrollable.scrollIntoViewNew(bubble, 'end').then(() => {
@ -1489,7 +1515,7 @@ export default class ChatBubbles { @@ -1489,7 +1515,7 @@ export default class ChatBubbles {
}
// * 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
const currentIndex = whichChild(bubble);
if(index > currentIndex) {
@ -1500,7 +1526,7 @@ export default class ChatBubbles { @@ -1500,7 +1526,7 @@ export default class ChatBubbles {
positionElementByIndex(bubble, dateMessage.container, index);
} else {
if(reverse) {
dateMessage.container.insertBefore(bubble, dateMessage.container.children[1].nextSibling);
dateMessage.container.insertBefore(bubble, dateMessage.container.children[this.stickyIntersector ? 1 : 0].nextSibling);
} else {
dateMessage.container.append(bubble);
}
@ -1517,7 +1543,10 @@ export default class ChatBubbles { @@ -1517,7 +1543,10 @@ export default class ChatBubbles {
// reverse means top
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;
const albumMustBeRenderedFull = this.chat.type !== 'pinned';
if(message.deleted) return;
@ -2088,11 +2117,11 @@ export default class ChatBubbles { @@ -2088,11 +2117,11 @@ export default class ChatBubbles {
}
default:
bubble.classList.remove('is-message-empty');
messageDiv.innerHTML = 'unrecognized media type: ' + message.media._;
messageDiv.append(timeSpan);
this.log.warn('unrecognized media type:', message.media._, message);
break;
bubble.classList.remove('is-message-empty');
messageDiv.innerHTML = 'unrecognized media type: ' + message.media._;
messageDiv.append(timeSpan);
this.log.warn('unrecognized media type:', message.media._, message);
break;
}
if(!processingWebPage) {
@ -2296,7 +2325,7 @@ export default class ChatBubbles { @@ -2296,7 +2325,7 @@ export default class ChatBubbles {
return new Promise<boolean>((resolve, reject) => {
//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);
@ -2349,14 +2378,19 @@ export default class ChatBubbles { @@ -2349,14 +2378,19 @@ export default class ChatBubbles {
//const newScrollTop = reverse ? 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
isTouchSupported && isApple && (this.scrollable.container.style.overflow = 'hidden');
this.scrollable.scrollTop = newScrollTop;
//this.scrollable.scrollTop = this.scrollable.scrollHeight;
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);
@ -2490,7 +2524,7 @@ export default class ChatBubbles { @@ -2490,7 +2524,7 @@ export default class ChatBubbles {
const processResult = (historyResult: typeof result) => {
if(this.chat.type === 'discussion' && 'offsetIdOffset' in historyResult) {
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
if(isTopEnd) {
@ -2504,7 +2538,7 @@ export default class ChatBubbles { @@ -2504,7 +2538,7 @@ export default class ChatBubbles {
const processPromise = (result: Promise<HistoryResult>) => {
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) {
this.scrollable.onScroll(); // нужно делать из-за ранней прогрузки
@ -2541,7 +2575,7 @@ export default class ChatBubbles { @@ -2541,7 +2575,7 @@ export default class ChatBubbles {
return null;
} else {
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);
promise = getHeavyAnimationPromise().then(() => {
return this.performHistoryResult((result as HistoryResult).history || [], reverse, isBackLimit, !isFirstMessageRender && additionMsgId);
@ -2616,7 +2650,7 @@ export default class ChatBubbles { @@ -2616,7 +2650,7 @@ export default class ChatBubbles {
//let removeCount = loadCount / 2;
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(reverse) {
//ids = ids.slice(-removeCount);
@ -2624,7 +2658,7 @@ export default class ChatBubbles { @@ -2624,7 +2658,7 @@ export default class ChatBubbles {
ids = ids.slice(safeCount);
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, это нужно для обратной загрузки истории, если запрос словил флуд
} else {
//ids = ids.slice(0, removeCount);
@ -2632,11 +2666,11 @@ export default class ChatBubbles { @@ -2632,11 +2666,11 @@ export default class ChatBubbles {
ids = ids.slice(0, ids.length - safeCount);
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.log('getHistory: will slice ids:', ids, reverse);
//this.log('getHistory: will slice ids:', ids, reverse);
this.deleteMessagesByIds(ids, false);
}

4
src/components/chat/input.ts

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

18
src/components/chat/markupTooltip.ts

@ -254,14 +254,26 @@ export default class MarkupTooltip { @@ -254,14 +254,26 @@ export default class MarkupTooltip {
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() {
if(this.init) {
this.init();
this.init = null;
}
const selection = document.getSelection();
if(!selection.toString().trim().length) {
if(this.isSelectionEmpty()) {
this.hide();
return;
}
@ -359,7 +371,7 @@ export default class MarkupTooltip { @@ -359,7 +371,7 @@ export default class MarkupTooltip {
}
const selection = document.getSelection();
if(!selection.toString().trim().length) {
if(this.isSelectionEmpty(selection)) {
this.hide();
return;
}

4
src/components/chat/pinnedMessage.ts

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

2
src/components/chat/replies.ts

@ -8,7 +8,7 @@ import { ripple } from "../ripple"; @@ -8,7 +8,7 @@ import { ripple } from "../ripple";
const TAG_NAME = 'replies-element';
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 => {
element.message = message;
element.render();

10
src/components/chat/topbar.ts

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

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

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

4
src/components/poll.ts

@ -66,7 +66,7 @@ export const roundPercents = (percents: number[]) => { @@ -66,7 +66,7 @@ export const roundPercents = (percents: number[]) => {
/* const connectedPolls: {id: string, element: PollElement}[] = [];
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);
for(const connected of connectedPolls) {
@ -79,7 +79,7 @@ rootScope.on('poll_update', (e) => { @@ -79,7 +79,7 @@ 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;
//console.log('poll_update', poll, results);

4
src/components/sidebarLeft/index.ts

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

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

@ -160,7 +160,7 @@ export default class AppChatFoldersTab extends SliderSuperTab { @@ -160,7 +160,7 @@ export default class AppChatFoldersTab extends SliderSuperTab {
});
this.rootScope.on('filter_update', (e) => {
const filter = e.detail;
const filter = e;
if(this.filtersRendered.hasOwnProperty(filter.id)) {
this.renderFolder(filter, null, this.filtersRendered[filter.id]);
} else {
@ -171,7 +171,7 @@ export default class AppChatFoldersTab extends SliderSuperTab { @@ -171,7 +171,7 @@ export default class AppChatFoldersTab extends SliderSuperTab {
});
this.rootScope.on('filter_delete', (e) => {
const filter = e.detail;
const filter = e;
if(this.filtersRendered.hasOwnProperty(filter.id)) {
/* for(const suggested of this.suggestedFilters) {
if(deepEqual(suggested.filter, filter)) {
@ -186,7 +186,7 @@ export default class AppChatFoldersTab extends SliderSuperTab { @@ -186,7 +186,7 @@ export default class AppChatFoldersTab extends SliderSuperTab {
});
this.rootScope.on('filter_order', (e) => {
const order = e.detail;
const order = e;
order.forEach((filterId, idx) => {
const div = this.filtersRendered[filterId];
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 { @@ -84,7 +84,7 @@ export default class AppSharedMediaTab implements SliderTab {
});
rootScope.on('dialog_notify_settings', (e) => {
if(this.peerId == e.detail) {
if(this.peerId == e) {
const muted = appMessagesManager.isPeerMuted(this.peerId);
this.profileElements.notificationsCheckbox.checked = !muted;
this.profileElements.notificationsStatus.innerText = muted ? 'Disabled' : 'Enabled';
@ -92,7 +92,7 @@ export default class AppSharedMediaTab implements SliderTab { @@ -92,7 +92,7 @@ export default class AppSharedMediaTab implements SliderTab {
});
rootScope.on('peer_typings', (e) => {
const {peerId} = e.detail;
const {peerId} = e;
if(this.peerId == peerId) {
this.setPeerStatus();
@ -100,7 +100,7 @@ export default class AppSharedMediaTab implements SliderTab { @@ -100,7 +100,7 @@ export default class AppSharedMediaTab implements SliderTab {
});
rootScope.on('user_update', (e) => {
const userId = e.detail;
const userId = e;
if(this.peerId == userId) {
this.setPeerStatus();

45
src/helpers/fastSmoothScroll.ts

@ -4,6 +4,7 @@ import { dispatchHeavyAnimationEvent } from '../hooks/useHeavyAnimationCheck'; @@ -4,6 +4,7 @@ import { dispatchHeavyAnimationEvent } from '../hooks/useHeavyAnimationCheck';
import { fastRaf } from './schedulers';
import { animateSingle, cancelAnimationByKey } from './animation';
import rootScope from '../lib/rootScope';
import { isInDOM } from './dom';
const MAX_DISTANCE = 1500;
const MIN_JS_DURATION = 250;
@ -42,7 +43,7 @@ export default function fastSmoothScroll( @@ -42,7 +43,7 @@ export default function fastSmoothScroll(
return Promise.resolve(); */
}
if(axis === 'y') {
if(axis === 'y' && isInDOM(element)) {
const elementRect = element.getBoundingClientRect();
const containerRect = container.getBoundingClientRect();
@ -58,6 +59,21 @@ export default function fastSmoothScroll( @@ -58,6 +59,21 @@ export default function fastSmoothScroll(
} else if(forceDirection === FocusDirection.Down) { // * not tested yet
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) => {
@ -73,6 +89,11 @@ export default function fastSmoothScroll( @@ -73,6 +89,11 @@ export default function fastSmoothScroll(
function scrollWithJs(
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 rectEndKey = axis === 'y' ? 'bottom' : 'right';
const sizeKey = axis === 'y' ? 'height' : 'width';
@ -90,6 +111,12 @@ function scrollWithJs( @@ -90,6 +111,12 @@ function scrollWithJs(
const scrollPosition = container[scrollPositionKey];
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;
@ -98,7 +125,6 @@ function scrollWithJs( @@ -98,7 +125,6 @@ function scrollWithJs(
path = elementPosition - margin;
break;
case 'end':
//path = (elementTop + elementHeight + margin) - containerHeight;
path = elementRect[rectEndKey] + (elementSize - elementRect[sizeKey]) - containerRect[rectEndKey];
break;
// 'nearest' is not supported yet
@ -109,6 +135,21 @@ function scrollWithJs( @@ -109,6 +135,21 @@ function scrollWithJs(
: elementPosition - margin;
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);

9
src/hooks/useHeavyAnimationCheck.ts

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

2
src/lib/appManagers/appChatsManager.ts

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

30
src/lib/appManagers/appDialogsManager.ts

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

2
src/lib/appManagers/appDownloadManager.ts

@ -32,7 +32,7 @@ export class AppDownloadManager { @@ -32,7 +32,7 @@ export class AppDownloadManager {
constructor() {
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;
const callbacks = this.progressCallbacks[details.fileName];

6
src/lib/appManagers/appImManager.ts

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

60
src/lib/appManagers/appMessagesManager.ts

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

2
src/lib/appManagers/appPollsManager.ts

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

2
src/lib/appManagers/appStickersManager.ts

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

2
src/lib/appManagers/appUsersManager.ts

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

2
src/lib/appManagers/appWebPagesManager.ts

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

27
src/lib/rootScope.ts

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

2
src/lib/storages/filters.ts

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

Loading…
Cancel
Save