Browse Source

Delete rootScope .on alias

master
Eduard Kuzmenko 3 years ago
parent
commit
47df8c69e9
  1. 4
      src/components/animationIntersector.ts
  2. 4
      src/components/appMediaPlaybackController.ts
  3. 2
      src/components/audio.ts
  4. 4
      src/components/avatar.ts
  5. 6
      src/components/chat/chat.ts
  6. 2
      src/components/chat/replies.ts
  7. 6
      src/components/connectionStatus.ts
  8. 2
      src/components/emoticonsDropdown/index.ts
  9. 4
      src/components/emoticonsDropdown/tabs/stickers.ts
  10. 2
      src/components/peerTitle.ts
  11. 4
      src/components/poll.ts
  12. 4
      src/components/sidebarLeft/index.ts
  13. 2
      src/components/sidebarLeft/tabs/background.ts
  14. 2
      src/components/sidebarLeft/tabs/privacyAndSecurity.ts
  15. 8
      src/components/sidebarRight/tabs/sharedMedia.ts
  16. 6
      src/helpers/eventListenerBase.ts
  17. 4
      src/hooks/useHeavyAnimationCheck.ts
  18. 4
      src/index.ts
  19. 13
      src/lib/appManagers/apiUpdatesManager.ts
  20. 18
      src/lib/appManagers/appChatsManager.ts
  21. 26
      src/lib/appManagers/appDialogsManager.ts
  22. 2
      src/lib/appManagers/appDownloadManager.ts
  23. 2
      src/lib/appManagers/appDraftsManager.ts
  24. 24
      src/lib/appManagers/appImManager.ts
  25. 106
      src/lib/appManagers/appMessagesManager.ts
  26. 8
      src/lib/appManagers/appNotificationsManager.ts
  27. 2
      src/lib/appManagers/appPeersManager.ts
  28. 2
      src/lib/appManagers/appPollsManager.ts
  29. 2
      src/lib/appManagers/appPrivacyManager.ts
  30. 18
      src/lib/appManagers/appProfileManager.ts
  31. 4
      src/lib/appManagers/appStateManager.ts
  32. 6
      src/lib/appManagers/appStickersManager.ts
  33. 22
      src/lib/appManagers/appUsersManager.ts
  34. 2
      src/lib/appManagers/appWebPagesManager.ts
  35. 2
      src/lib/langPack.ts
  36. 2
      src/lib/mtproto/apiManager.ts
  37. 6
      src/lib/mtproto/mtprotoworker.ts
  38. 37
      src/lib/rootScope.ts
  39. 6
      src/lib/storages/dialogs.ts
  40. 6
      src/lib/storages/filters.ts
  41. 2
      src/pages/pageIm.ts

4
src/components/animationIntersector.ts

@ -60,14 +60,14 @@ export class AnimationIntersector {
} }
}); });
rootScope.on('audio_play', ({doc}) => { rootScope.addEventListener('audio_play', ({doc}) => {
if(doc.type === 'round') { if(doc.type === 'round') {
this.videosLocked = true; this.videosLocked = true;
this.checkAnimations(); this.checkAnimations();
} }
}); });
rootScope.on('audio_pause', () => { rootScope.addEventListener('audio_pause', () => {
if(this.videosLocked) { if(this.videosLocked) {
this.videosLocked = false; this.videosLocked = false;
this.checkAnimations(); this.checkAnimations();

4
src/components/appMediaPlaybackController.ts

@ -88,7 +88,7 @@ class AppMediaPlaybackController {
// audio_pause не успеет сработать без таймаута // audio_pause не успеет сработать без таймаута
setTimeout(() => { setTimeout(() => {
rootScope.broadcast('audio_play', {peerId, doc, mid}); rootScope.dispatchEvent('audio_play', {peerId, doc, mid});
}, 0); }, 0);
}); });
@ -192,7 +192,7 @@ class AppMediaPlaybackController {
return; return;
} */ } */
rootScope.broadcast('audio_pause'); rootScope.dispatchEvent('audio_pause');
}; };
onEnded = (e?: Event) => { onEnded = (e?: Event) => {

2
src/components/audio.ts

@ -21,7 +21,7 @@ import { formatDateAccordingToToday } from "../helpers/date";
import { cancelEvent } from "../helpers/dom/cancelEvent"; import { cancelEvent } from "../helpers/dom/cancelEvent";
import { attachClickEvent, detachClickEvent } from "../helpers/dom/clickEvent"; import { attachClickEvent, detachClickEvent } from "../helpers/dom/clickEvent";
rootScope.on('messages_media_read', e => { rootScope.addEventListener('messages_media_read', e => {
const {mids, peerId} = e; const {mids, peerId} = e;
mids.forEach(mid => { mids.forEach(mid => {

4
src/components/avatar.ts

@ -23,8 +23,8 @@ const onAvatarUpdate = (peerId: number) => {
}); });
}; };
rootScope.on('avatar_update', onAvatarUpdate); rootScope.addEventListener('avatar_update', onAvatarUpdate);
rootScope.on('peer_title_edit', onAvatarUpdate); rootScope.addEventListener('peer_title_edit', onAvatarUpdate);
export async function openAvatarViewer(target: HTMLElement, peerId: number, middleware: () => boolean, message?: any, prevTargets?: {element: HTMLElement, item: string | Message.messageService}[], nextTargets?: typeof prevTargets) { export async function openAvatarViewer(target: HTMLElement, peerId: number, middleware: () => boolean, message?: any, prevTargets?: {element: HTMLElement, item: string | Message.messageService}[], nextTargets?: typeof prevTargets) {
let photo = await appProfileManager.getFullPhoto(peerId); let photo = await appProfileManager.getFullPhoto(peerId);

6
src/components/chat/chat.ts

@ -253,7 +253,7 @@ export default class Chat extends EventListenerBase<{
const samePeer = this.peerId === peerId; const samePeer = this.peerId === peerId;
if(!samePeer) { if(!samePeer) {
rootScope.broadcast('peer_changing', this); rootScope.dispatchEvent('peer_changing', this);
this.peerId = peerId; this.peerId = peerId;
} else if(this.setPeerPromise) { } else if(this.setPeerPromise) {
return; return;
@ -267,7 +267,7 @@ export default class Chat extends EventListenerBase<{
this.cleanup(true); this.cleanup(true);
this.topbar.setPeer(peerId); this.topbar.setPeer(peerId);
this.bubbles.setPeer(peerId); this.bubbles.setPeer(peerId);
rootScope.broadcast('peer_changed', peerId); rootScope.dispatchEvent('peer_changed', peerId);
return; return;
} }
@ -353,7 +353,7 @@ export default class Chat extends EventListenerBase<{
this.log.setPrefix('CHAT-' + peerId + '-' + this.type); this.log.setPrefix('CHAT-' + peerId + '-' + this.type);
rootScope.broadcast('peer_changed', peerId); rootScope.dispatchEvent('peer_changed', peerId);
this.wasAlreadyUsed = true; this.wasAlreadyUsed = true;
} }

2
src/components/chat/replies.ts

@ -15,7 +15,7 @@ import AvatarElement from "../avatar";
const TAG_NAME = 'replies-element'; const TAG_NAME = 'replies-element';
rootScope.on('replies_updated', (e) => { rootScope.addEventListener('replies_updated', (e) => {
const message = e; 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;

6
src/components/connectionStatus.ts

@ -47,14 +47,14 @@ export default class ConnectionStatusComponent {
chatsContainer.prepend(this.statusContainer); chatsContainer.prepend(this.statusContainer);
rootScope.on('connection_status_change', (e) => { rootScope.addEventListener('connection_status_change', (e) => {
const status = e; const status = e;
console.log(status); console.log(status);
this.setConnectionStatus(); this.setConnectionStatus();
}); });
rootScope.on('state_synchronizing', (e) => { rootScope.addEventListener('state_synchronizing', (e) => {
const channelId = e; const channelId = e;
if(!channelId) { if(!channelId) {
this.updating = true; this.updating = true;
@ -63,7 +63,7 @@ export default class ConnectionStatusComponent {
} }
}); });
rootScope.on('state_synchronized', (e) => { rootScope.addEventListener('state_synchronized', (e) => {
const channelId = e; const channelId = e;
DEBUG && this.log('state_synchronized', channelId); DEBUG && this.log('state_synchronized', channelId);
if(!channelId) { if(!channelId) {

2
src/components/emoticonsDropdown/index.ts

@ -183,7 +183,7 @@ export class EmoticonsDropdown {
this.tabs[0].init(); // onTransitionEnd не вызовется, т.к. это первая открытая вкладка this.tabs[0].init(); // onTransitionEnd не вызовется, т.к. это первая открытая вкладка
} }
rootScope.on('peer_changed', this.checkRights); rootScope.addEventListener('peer_changed', this.checkRights);
this.checkRights(); this.checkRights();
if(!isTouchSupported) { if(!isTouchSupported) {

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

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

2
src/components/peerTitle.ts

@ -22,7 +22,7 @@ const weakMap: WeakMap<HTMLElement, PeerTitle> = new WeakMap();
MOUNT_CLASS_TO.peerTitleWeakMap = weakMap; MOUNT_CLASS_TO.peerTitleWeakMap = weakMap;
rootScope.on('peer_title_edit', (peerId) => { rootScope.addEventListener('peer_title_edit', (peerId) => {
const elements = Array.from(document.querySelectorAll(`.peer-title[data-peer-id="${peerId}"]`)) as HTMLElement[]; const elements = Array.from(document.querySelectorAll(`.peer-title[data-peer-id="${peerId}"]`)) as HTMLElement[];
elements.forEach(element => { elements.forEach(element => {
const peerTitle = weakMap.get(element); const peerTitle = weakMap.get(element);

4
src/components/poll.ts

@ -91,7 +91,7 @@ rootScope.on('poll_update', (e) => {
} }
}); */ }); */
rootScope.on('poll_update', (e) => { rootScope.addEventListener('poll_update', (e) => {
const {poll, results} = e as {poll: Poll, results: PollResults}; const {poll, results} = e as {poll: Poll, results: PollResults};
const pollElements = Array.from(document.querySelectorAll(`poll-element[poll-id="${poll.id}"]`)) as PollElement[]; const pollElements = Array.from(document.querySelectorAll(`poll-element[poll-id="${poll.id}"]`)) as PollElement[];
@ -102,7 +102,7 @@ rootScope.on('poll_update', (e) => {
}); });
}); });
rootScope.on('peer_changed', () => { rootScope.addEventListener('peer_changed', () => {
if(prevQuizHint) { if(prevQuizHint) {
hideQuizHint(prevQuizHint, prevQuizHintOnHide, prevQuizHintTimeout); hideQuizHint(prevQuizHint, prevQuizHintOnHide, prevQuizHintTimeout);
} }

4
src/components/sidebarLeft/index.ts

@ -108,7 +108,7 @@ export class AppSidebarLeft extends SidebarSlider {
appImManager.applyCurrentTheme(); appImManager.applyCurrentTheme();
}); });
rootScope.on('theme_change', () => { rootScope.addEventListener('theme_change', () => {
themeCheckboxField.setValueSilently(rootScope.getTheme().name === 'night'); themeCheckboxField.setValueSilently(rootScope.getTheme().name === 'night');
}); });
@ -238,7 +238,7 @@ export class AppSidebarLeft extends SidebarSlider {
btnArchive.element.append(this.archivedCount); btnArchive.element.append(this.archivedCount);
rootScope.on('dialogs_archived_unread', (e) => { rootScope.addEventListener('dialogs_archived_unread', (e) => {
this.archivedCount.innerText = '' + formatNumber(e.count, 1); this.archivedCount.innerText = '' + formatNumber(e.count, 1);
this.archivedCount.classList.toggle('hide', !e.count); this.archivedCount.classList.toggle('hide', !e.count);
}); });

2
src/components/sidebarLeft/tabs/background.ts

@ -82,7 +82,7 @@ export default class AppBackgroundTab extends SliderSuperTab {
container.append(uploadButton, colorButton, resetButton, blurCheckboxField.label); container.append(uploadButton, colorButton, resetButton, blurCheckboxField.label);
} }
rootScope.on('background_change', this.setActive); rootScope.addEventListener('background_change', this.setActive);
apiManager.invokeApiHashable('account.getWallPapers').then((accountWallpapers) => { apiManager.invokeApiHashable('account.getWallPapers').then((accountWallpapers) => {
const wallpapers = (accountWallpapers as AccountWallPapers.accountWallPapers).wallpapers as WallPaper.wallPaper[]; const wallpapers = (accountWallpapers as AccountWallPapers.accountWallPapers).wallpapers as WallPaper.wallPaper[];

2
src/components/sidebarLeft/tabs/privacyAndSecurity.ts

@ -220,7 +220,7 @@ export default class AppPrivacyAndSecurityTab extends SliderSuperTab {
updatePrivacyRow(key as keyof typeof rowsByKeys); updatePrivacyRow(key as keyof typeof rowsByKeys);
} }
rootScope.on('privacy_update', (update) => { rootScope.addEventListener('privacy_update', (update) => {
updatePrivacyRow(convertKeyToInputKey(update.key._) as any); updatePrivacyRow(convertKeyToInputKey(update.key._) as any);
}); });
} }

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

@ -556,14 +556,14 @@ class PeerProfile {
appMessagesManager.mutePeer(this.peerId); appMessagesManager.mutePeer(this.peerId);
}); });
rootScope.on('dialog_notify_settings', (dialog) => { rootScope.addEventListener('dialog_notify_settings', (dialog) => {
if(this.peerId === dialog.peerId) { if(this.peerId === dialog.peerId) {
const muted = appNotificationsManager.isPeerLocalMuted(this.peerId, false); const muted = appNotificationsManager.isPeerLocalMuted(this.peerId, false);
this.notifications.checkboxField.checked = !muted; this.notifications.checkboxField.checked = !muted;
} }
}); });
rootScope.on('peer_typings', (e) => { rootScope.addEventListener('peer_typings', (e) => {
const {peerId} = e; const {peerId} = e;
if(this.peerId === peerId) { if(this.peerId === peerId) {
@ -571,13 +571,13 @@ class PeerProfile {
} }
}); });
rootScope.on('peer_bio_edit', (peerId) => { rootScope.addEventListener('peer_bio_edit', (peerId) => {
if(peerId === this.peerId) { if(peerId === this.peerId) {
this.setBio(true); this.setBio(true);
} }
}); });
rootScope.on('user_update', (e) => { rootScope.addEventListener('user_update', (e) => {
const userId = e; const userId = e;
if(this.peerId === userId) { if(this.peerId === userId) {

6
src/helpers/eventListenerBase.ts

@ -73,7 +73,7 @@ export default class EventListenerBase<Listeners extends {[name: string]: Functi
this.listenerResults = {}; this.listenerResults = {};
} }
public addEventListener(name: keyof Listeners, callback: Listeners[typeof name], once?: boolean) { public addEventListener<T extends keyof Listeners>(name: T, callback: Listeners[T], once?: boolean) {
if(this.listenerResults.hasOwnProperty(name)) { if(this.listenerResults.hasOwnProperty(name)) {
callback(...this.listenerResults[name]); callback(...this.listenerResults[name]);
@ -94,7 +94,7 @@ export default class EventListenerBase<Listeners extends {[name: string]: Functi
} }
} }
public removeEventListener(name: keyof Listeners, callback: Listeners[typeof name]) { public removeEventListener<T extends keyof Listeners>(name: T, callback: Listeners[T]) {
if(this.listeners[name]) { if(this.listeners[name]) {
this.listeners[name].findAndSplice(l => l.callback === callback); this.listeners[name].findAndSplice(l => l.callback === callback);
} }
@ -102,7 +102,7 @@ export default class EventListenerBase<Listeners extends {[name: string]: Functi
} }
// * must be protected, but who cares // * must be protected, but who cares
public dispatchEvent(name: keyof Listeners, ...args: ArgumentTypes<Listeners[typeof name]>) { public dispatchEvent<T extends keyof Listeners>(name: T, ...args: ArgumentTypes<Listeners[T]>) {
if(this.reuseResults) { if(this.reuseResults) {
this.listenerResults[name] = args; this.listenerResults[name] = args;
} }

4
src/hooks/useHeavyAnimationCheck.ts

@ -27,7 +27,7 @@ const log = console.log.bind(console.log, '[HEAVY-ANIMATION]:');
export function dispatchHeavyAnimationEvent(promise: Promise<any>, timeout?: number) { export function dispatchHeavyAnimationEvent(promise: Promise<any>, timeout?: number) {
if(!isAnimating) { if(!isAnimating) {
heavyAnimationPromise = deferredPromise<void>(); heavyAnimationPromise = deferredPromise<void>();
rootScope.broadcast(ANIMATION_START_EVENT); rootScope.dispatchEvent(ANIMATION_START_EVENT);
isAnimating = true; isAnimating = true;
DEBUG && log('start'); DEBUG && log('start');
} }
@ -64,7 +64,7 @@ function onHeavyAnimationEnd() {
isAnimating = false; isAnimating = false;
promisesInQueue = 0; promisesInQueue = 0;
rootScope.broadcast(ANIMATION_END_EVENT); rootScope.dispatchEvent(ANIMATION_END_EVENT);
heavyAnimationPromise.resolve(); heavyAnimationPromise.resolve();
DEBUG && log('end'); DEBUG && log('end');

4
src/index.ts

@ -128,7 +128,7 @@ console.timeEnd('get storage1'); */
}; };
let tabId: number; let tabId: number;
rootScope.default.on('im_tab_change', (id) => { rootScope.default.addEventListener('im_tab_change', (id) => {
const wasTabId = tabId !== undefined; const wasTabId = tabId !== undefined;
tabId = id; tabId = id;
@ -137,7 +137,7 @@ console.timeEnd('get storage1'); */
} }
}); });
rootScope.default.on('overlay_toggle', () => { rootScope.default.addEventListener('overlay_toggle', () => {
toggleResizeMode(); toggleResizeMode();
}); });

13
src/lib/appManagers/apiUpdatesManager.ts

@ -247,6 +247,7 @@ export class ApiUpdatesManager {
const promise = apiManager.invokeApi('updates.getDifference', { const promise = apiManager.invokeApi('updates.getDifference', {
pts: updatesState.pts, pts: updatesState.pts,
// pts_total_limit: 1200,
date: updatesState.date, date: updatesState.date,
qts: -1 qts: -1
}, { }, {
@ -263,7 +264,7 @@ export class ApiUpdatesManager {
// ! SORRY I'M SORRY I'M SORRY // ! SORRY I'M SORRY I'M SORRY
if(first) { if(first) {
rootScope.broadcast('state_synchronizing'); rootScope.dispatchEvent('state_synchronizing');
} }
if(differenceResult._ !== 'updates.differenceTooLong') { if(differenceResult._ !== 'updates.differenceTooLong') {
@ -303,6 +304,8 @@ export class ApiUpdatesManager {
updatesState.pts = differenceResult.pts; updatesState.pts = differenceResult.pts;
delete updatesState.seq; delete updatesState.seq;
delete updatesState.date; delete updatesState.date;
rootScope.dispatchEvent('state_cleared');
} }
// this.log('apply diff', updatesState.seq, updatesState.pts) // this.log('apply diff', updatesState.seq, updatesState.pts)
@ -395,11 +398,11 @@ export class ApiUpdatesManager {
private justAName(state: UpdatesState, promise: UpdatesState['syncLoading'], channelId?: number) { private justAName(state: UpdatesState, promise: UpdatesState['syncLoading'], channelId?: number) {
state.syncLoading = promise; state.syncLoading = promise;
rootScope.broadcast('state_synchronizing', channelId); rootScope.dispatchEvent('state_synchronizing', channelId);
promise.then(() => { promise.then(() => {
state.syncLoading = null; state.syncLoading = null;
rootScope.broadcast('state_synchronized', channelId); rootScope.dispatchEvent('state_synchronized', channelId);
}, () => { }, () => {
state.syncLoading = null; state.syncLoading = null;
}); });
@ -654,9 +657,9 @@ export class ApiUpdatesManager {
apiManager.setUpdatesProcessor(this.processUpdateMessage); apiManager.setUpdatesProcessor(this.processUpdateMessage);
this.updatesState.syncLoading.then(() => { // this.updatesState.syncLoading.then(() => {
this.setProxy(); this.setProxy();
}); // });
}); });
} }
} }

18
src/lib/appManagers/appChatsManager.ts

@ -61,7 +61,7 @@ export class AppChatsManager {
const chat: Chat.chat = this.chats[chatId]; const chat: Chat.chat = this.chats[chatId];
if(chat) { if(chat) {
chat.default_banned_rights = update.default_banned_rights; chat.default_banned_rights = update.default_banned_rights;
rootScope.broadcast('chat_update', chatId); rootScope.dispatchEvent('chat_update', chatId);
} }
}, },
@ -122,7 +122,7 @@ export class AppChatsManager {
typings.splice(idx, 1); typings.splice(idx, 1);
} }
rootScope.broadcast('peer_typings', {peerId, typings}); rootScope.dispatchEvent('peer_typings', {peerId, typings});
if(!typings.length) { if(!typings.length) {
delete this.typingsInPeer[peerId]; delete this.typingsInPeer[peerId];
@ -166,7 +166,7 @@ export class AppChatsManager {
appUsersManager.forceUserOnline(fromId); appUsersManager.forceUserOnline(fromId);
typing.timeout = window.setTimeout(cancelAction, 6000); typing.timeout = window.setTimeout(cancelAction, 6000);
rootScope.broadcast('peer_typings', {peerId, typings}); rootScope.dispatchEvent('peer_typings', {peerId, typings});
} }
}; };
@ -230,15 +230,15 @@ export class AppChatsManager {
} }
safeReplaceObject(oldChat, chat); safeReplaceObject(oldChat, chat);
rootScope.broadcast('chat_update', chat.id); rootScope.dispatchEvent('chat_update', chat.id);
} }
if(changedPhoto) { if(changedPhoto) {
rootScope.broadcast('avatar_update', -chat.id); rootScope.dispatchEvent('avatar_update', -chat.id);
} }
if(changedTitle) { if(changedTitle) {
rootScope.broadcast('peer_title_edit', -chat.id); rootScope.dispatchEvent('peer_title_edit', -chat.id);
} }
if(appStateManager.isPeerNeeded(-chat.id)) { if(appStateManager.isPeerNeeded(-chat.id)) {
@ -546,7 +546,7 @@ export class AppChatsManager {
apiUpdatesManager.processUpdateMessage(updates); apiUpdatesManager.processUpdateMessage(updates);
const channelId = updates.chats[0].id; const channelId = updates.chats[0].id;
rootScope.broadcast('history_focus', {peerId: -channelId}); rootScope.dispatchEvent('history_focus', {peerId: -channelId});
return channelId; return channelId;
}); });
@ -572,7 +572,7 @@ export class AppChatsManager {
apiUpdatesManager.processUpdateMessage(updates); apiUpdatesManager.processUpdateMessage(updates);
const chatId = (updates as any as Updates.updates).chats[0].id; const chatId = (updates as any as Updates.updates).chats[0].id;
rootScope.broadcast('history_focus', {peerId: -chatId}); rootScope.dispatchEvent('history_focus', {peerId: -chatId});
return chatId; return chatId;
}); });
@ -758,7 +758,7 @@ export class AppChatsManager {
about about
}).then(bool => { }).then(bool => {
//apiUpdatesManager.processUpdateMessage(updates); //apiUpdatesManager.processUpdateMessage(updates);
rootScope.broadcast('peer_bio_edit', -id); rootScope.dispatchEvent('peer_bio_edit', -id);
}); });
} }

26
src/lib/appManagers/appDialogsManager.ts

@ -162,7 +162,7 @@ export class AppDialogsManager {
(window as any).addElement = add; (window as any).addElement = add;
} */ } */
rootScope.on('user_update', (userId) => { rootScope.addEventListener('user_update', (userId) => {
//console.log('updating user:', user, dialog); //console.log('updating user:', user, dialog);
const dom = this.getDialogDom(userId); const dom = this.getDialogDom(userId);
@ -182,7 +182,7 @@ export class AppDialogsManager {
this.setFiltersUnreadCount(); this.setFiltersUnreadCount();
}); */ }); */
rootScope.on('dialog_flush', (e) => { rootScope.addEventListener('dialog_flush', (e) => {
const peerId: number = e.peerId; const peerId: number = e.peerId;
const dialog = appMessagesManager.getDialogOnly(peerId); const dialog = appMessagesManager.getDialogOnly(peerId);
if(dialog) { if(dialog) {
@ -192,7 +192,7 @@ export class AppDialogsManager {
} }
}); });
rootScope.on('dialogs_multiupdate', (e) => { rootScope.addEventListener('dialogs_multiupdate', (e) => {
const dialogs = e; const dialogs = e;
for(const id in dialogs) { for(const id in dialogs) {
@ -204,14 +204,14 @@ export class AppDialogsManager {
this.setFiltersUnreadCount(); this.setFiltersUnreadCount();
}); });
rootScope.on('dialog_drop', (e) => { rootScope.addEventListener('dialog_drop', (e) => {
const {peerId} = e; const {peerId} = e;
this.deleteDialog(peerId); this.deleteDialog(peerId);
this.setFiltersUnreadCount(); this.setFiltersUnreadCount();
}); });
rootScope.on('dialog_unread', (e) => { rootScope.addEventListener('dialog_unread', (e) => {
const info = e; const info = e;
const dialog = appMessagesManager.getDialogOnly(info.peerId); const dialog = appMessagesManager.getDialogOnly(info.peerId);
@ -222,18 +222,18 @@ export class AppDialogsManager {
} }
}); });
rootScope.on('dialog_notify_settings', (dialog) => { rootScope.addEventListener('dialog_notify_settings', (dialog) => {
this.setUnreadMessages(dialog); // возможно это не нужно, но нужно менять is-muted this.setUnreadMessages(dialog); // возможно это не нужно, но нужно менять is-muted
}); });
rootScope.on('dialog_draft', (e) => { rootScope.addEventListener('dialog_draft', (e) => {
const dialog = appMessagesManager.getDialogOnly(e.peerId); const dialog = appMessagesManager.getDialogOnly(e.peerId);
if(dialog) { if(dialog) {
this.updateDialog(dialog); this.updateDialog(dialog);
} }
}); });
rootScope.on('peer_changed', (e) => { rootScope.addEventListener('peer_changed', (e) => {
const peerId = e; const peerId = e;
//const perf = performance.now(); //const perf = performance.now();
@ -252,7 +252,7 @@ export class AppDialogsManager {
//this.log('peer_changed total time:', performance.now() - perf); //this.log('peer_changed total time:', performance.now() - perf);
}); });
rootScope.on('filter_update', (e) => { rootScope.addEventListener('filter_update', (e) => {
const filter: DialogFilter = e; const filter: DialogFilter = e;
if(!this.filtersRendered[filter.id]) { if(!this.filtersRendered[filter.id]) {
this.addFilter(filter); this.addFilter(filter);
@ -272,7 +272,7 @@ export class AppDialogsManager {
elements.title.innerHTML = RichTextProcessor.wrapEmojiText(filter.title); elements.title.innerHTML = RichTextProcessor.wrapEmojiText(filter.title);
}); });
rootScope.on('filter_delete', (e) => { rootScope.addEventListener('filter_delete', (e) => {
const filter: DialogFilter = e; const filter: DialogFilter = e;
const elements = this.filtersRendered[filter.id]; const elements = this.filtersRendered[filter.id];
if(!elements) return; if(!elements) return;
@ -293,7 +293,7 @@ export class AppDialogsManager {
} }
}); });
rootScope.on('filter_order', (e) => { rootScope.addEventListener('filter_order', (e) => {
const order = e; const order = e;
const containerToAppend = this.folders.menu as HTMLElement; const containerToAppend = this.folders.menu as HTMLElement;
@ -311,7 +311,7 @@ export class AppDialogsManager {
} */ } */
}); });
rootScope.on('peer_typings', (e) => { rootScope.addEventListener('peer_typings', (e) => {
const {peerId, typings} = e; const {peerId, typings} = e;
const dialog = appMessagesManager.getDialogOnly(peerId); const dialog = appMessagesManager.getDialogOnly(peerId);
@ -1128,7 +1128,7 @@ export class AppDialogsManager {
this.accumulateArchivedTimeout = 0; this.accumulateArchivedTimeout = 0;
const dialogs = appMessagesManager.dialogsStorage.getFolder(1); const dialogs = appMessagesManager.dialogsStorage.getFolder(1);
const sum = dialogs.reduce((acc, dialog) => acc + dialog.unread_count, 0); const sum = dialogs.reduce((acc, dialog) => acc + dialog.unread_count, 0);
rootScope.broadcast('dialogs_archived_unread', {count: sum}); rootScope.dispatchEvent('dialogs_archived_unread', {count: sum});
}, 0); }, 0);
} }

2
src/lib/appManagers/appDownloadManager.ts

@ -59,7 +59,7 @@ export class AppDownloadManager {
}; };
constructor() { constructor() {
rootScope.on('download_progress', (e) => { rootScope.addEventListener('download_progress', (e) => {
const details = e 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;

2
src/lib/appManagers/appDraftsManager.ts

@ -102,7 +102,7 @@ export class AppDraftsManager {
if(options.notify) { if(options.notify) {
// console.warn(dT(), 'save draft', peerId, apiDraft, options) // console.warn(dT(), 'save draft', peerId, apiDraft, options)
rootScope.broadcast('draft_updated', { rootScope.dispatchEvent('draft_updated', {
peerId, peerId,
threadId, threadId,
draft draft

24
src/lib/appManagers/appImManager.ts

@ -114,7 +114,7 @@ export class AppImManager {
this.offline = rootScope.idle.isIDLE = true; this.offline = rootScope.idle.isIDLE = true;
this.updateStatus(); this.updateStatus();
clearInterval(this.updateStatusInterval); clearInterval(this.updateStatusInterval);
rootScope.broadcast('idle', rootScope.idle.isIDLE); rootScope.dispatchEvent('idle', rootScope.idle.isIDLE);
window.addEventListener('focus', () => { window.addEventListener('focus', () => {
this.offline = rootScope.idle.isIDLE = false; this.offline = rootScope.idle.isIDLE = false;
@ -124,7 +124,7 @@ export class AppImManager {
// в обратном порядке // в обратном порядке
animationIntersector.checkAnimations(false); animationIntersector.checkAnimations(false);
rootScope.broadcast('idle', rootScope.idle.isIDLE); rootScope.dispatchEvent('idle', rootScope.idle.isIDLE);
}, {once: true}); }, {once: true});
}); });
@ -134,7 +134,7 @@ export class AppImManager {
this.updateStatus(); this.updateStatus();
this.offline = rootScope.idle.isIDLE = false; this.offline = rootScope.idle.isIDLE = false;
rootScope.broadcast('idle', rootScope.idle.isIDLE); rootScope.dispatchEvent('idle', rootScope.idle.isIDLE);
}, {once: true, passive: true}); }, {once: true, passive: true});
this.chatsContainer = document.createElement('div'); this.chatsContainer = document.createElement('div');
@ -150,7 +150,7 @@ export class AppImManager {
//window.addEventListener('hashchange', this.onHashChange); //window.addEventListener('hashchange', this.onHashChange);
this.setSettings(); this.setSettings();
rootScope.on('settings_updated', this.setSettings); rootScope.addEventListener('settings_updated', this.setSettings);
useHeavyAnimationCheck(() => { useHeavyAnimationCheck(() => {
animationIntersector.setOnlyOnePlayableGroup('lock'); animationIntersector.setOnlyOnePlayableGroup('lock');
@ -170,20 +170,20 @@ export class AppImManager {
} }
}); });
rootScope.on('history_focus', (e) => { rootScope.addEventListener('history_focus', (e) => {
const {peerId, mid} = e; const {peerId, mid} = e;
this.setInnerPeer(peerId, mid); this.setInnerPeer(peerId, mid);
}); });
rootScope.on('peer_changing', (chat) => { rootScope.addEventListener('peer_changing', (chat) => {
this.saveChatPosition(chat); this.saveChatPosition(chat);
}); });
rootScope.on('theme_change', () => { rootScope.addEventListener('theme_change', () => {
this.applyCurrentTheme(); this.applyCurrentTheme();
}); });
rootScope.on('instance_deactivated', () => { rootScope.addEventListener('instance_deactivated', () => {
const popup = new PopupElement('popup-instance-deactivated', undefined, {overlayClosable: true}); const popup = new PopupElement('popup-instance-deactivated', undefined, {overlayClosable: true});
const c = document.createElement('div'); const c = document.createElement('div');
c.classList.add('instance-deactivated-container'); c.classList.add('instance-deactivated-container');
@ -368,7 +368,7 @@ export class AppImManager {
const promises = this.chats.map(chat => chat.setBackground(url)); const promises = this.chats.map(chat => chat.setBackground(url));
return promises[promises.length - 1].then(() => { return promises[promises.length - 1].then(() => {
if(broadcastEvent) { if(broadcastEvent) {
rootScope.broadcast('background_change'); rootScope.dispatchEvent('background_change');
} }
}); });
} }
@ -789,7 +789,7 @@ export class AppImManager {
} }
} }
rootScope.broadcast('im_tab_change', id); rootScope.dispatchEvent('im_tab_change', id);
//this._selectTab(id, mediaSizes.isMobile); //this._selectTab(id, mediaSizes.isMobile);
//document.body.classList.toggle(RIGHT_COLUMN_ACTIVE_CLASSNAME, id === 2); //document.body.classList.toggle(RIGHT_COLUMN_ACTIVE_CLASSNAME, id === 2);
@ -836,7 +836,7 @@ export class AppImManager {
if(fromIndex >= this.chats.length) return; if(fromIndex >= this.chats.length) return;
if(this.chats.length > 1 && justReturn) { if(this.chats.length > 1 && justReturn) {
rootScope.broadcast('peer_changing', this.chat); rootScope.dispatchEvent('peer_changing', this.chat);
} }
if(!spliced) { if(!spliced) {
@ -858,7 +858,7 @@ export class AppImManager {
this.chatsSelectTab(this.chat.container, animate); this.chatsSelectTab(this.chat.container, animate);
if(justReturn) { if(justReturn) {
rootScope.broadcast('peer_changed', this.chat.peerId); rootScope.dispatchEvent('peer_changed', this.chat.peerId);
const searchTab = appSidebarRight.getTab(AppPrivateSearchTab); const searchTab = appSidebarRight.getTab(AppPrivateSearchTab);
if(searchTab) { if(searchTab) {

106
src/lib/appManagers/appMessagesManager.ts

@ -242,7 +242,7 @@ export class AppMessagesManager {
}); });
// ! Invalidate notify settings, can optimize though // ! Invalidate notify settings, can optimize though
rootScope.on('notify_peer_type_settings', ({key, settings}) => { rootScope.addEventListener('notify_peer_type_settings', ({key, settings}) => {
this.getConversationsAll().then(dialogs => { this.getConversationsAll().then(dialogs => {
let filterFunc: (dialog: Dialog) => boolean; let filterFunc: (dialog: Dialog) => boolean;
if(key === 'notifyUsers') filterFunc = (dialog) => dialog.peerId > 0; if(key === 'notifyUsers') filterFunc = (dialog) => dialog.peerId > 0;
@ -252,12 +252,12 @@ export class AppMessagesManager {
dialogs dialogs
.filter(filterFunc) .filter(filterFunc)
.forEach(dialog => { .forEach(dialog => {
rootScope.broadcast('dialog_notify_settings', dialog); rootScope.dispatchEvent('dialog_notify_settings', dialog);
}); });
}); });
}); });
rootScope.on('webpage_updated', (e) => { rootScope.addEventListener('webpage_updated', (e) => {
const eventData = e; 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;
@ -269,7 +269,7 @@ export class AppMessagesManager {
const peerId = this.getMessagePeer(message); const peerId = this.getMessagePeer(message);
const storage = this.getMessagesStorage(peerId); const storage = this.getMessagesStorage(peerId);
rootScope.broadcast('message_edit', { rootScope.dispatchEvent('message_edit', {
storage, storage,
peerId, peerId,
mid mid
@ -277,7 +277,7 @@ export class AppMessagesManager {
}); });
}); });
rootScope.on('draft_updated', (e) => { rootScope.addEventListener('draft_updated', (e) => {
const {peerId, threadId, draft} = e; const {peerId, threadId, draft} = e;
if(threadId) return; if(threadId) return;
@ -288,7 +288,7 @@ export class AppMessagesManager {
this.dialogsStorage.generateIndexForDialog(dialog); this.dialogsStorage.generateIndexForDialog(dialog);
this.dialogsStorage.pushDialog(dialog); this.dialogsStorage.pushDialog(dialog);
rootScope.broadcast('dialog_draft', { rootScope.dispatchEvent('dialog_draft', {
peerId, peerId,
draft, draft,
index: dialog.index index: dialog.index
@ -454,7 +454,7 @@ export class AppMessagesManager {
} else { } else {
delete message.error; delete message.error;
} }
rootScope.broadcast('messages_pending'); rootScope.dispatchEvent('messages_pending');
}; };
message.send = () => { message.send = () => {
@ -808,7 +808,7 @@ export class AppMessagesManager {
delete message.error; delete message.error;
} }
rootScope.broadcast('messages_pending'); rootScope.dispatchEvent('messages_pending');
}; };
let uploaded = false, let uploaded = false,
@ -1041,7 +1041,7 @@ export class AppMessagesManager {
delete message.error; delete message.error;
} }
rootScope.broadcast('messages_pending'); rootScope.dispatchEvent('messages_pending');
}; };
const inputPeer = appPeersManager.getInputPeerById(peerId); const inputPeer = appPeersManager.getInputPeerById(peerId);
@ -1227,7 +1227,7 @@ export class AppMessagesManager {
delete historyMessage.error delete historyMessage.error
} }
} */ } */
rootScope.broadcast('messages_pending'); rootScope.dispatchEvent('messages_pending');
}; };
message.send = () => { message.send = () => {
@ -1311,7 +1311,7 @@ export class AppMessagesManager {
//if(!options.isGroupedItem) { //if(!options.isGroupedItem) {
this.saveMessages([message], {storage, isScheduled: true, isOutgoing: true}); this.saveMessages([message], {storage, isScheduled: true, isOutgoing: true});
setTimeout(() => { setTimeout(() => {
rootScope.broadcast('scheduled_new', {peerId, mid: messageId}); rootScope.dispatchEvent('scheduled_new', {peerId, mid: messageId});
}, 0); }, 0);
} else { } else {
/* if(options.threadId && this.threadsStorage[peerId]) { /* if(options.threadId && this.threadsStorage[peerId]) {
@ -1332,7 +1332,7 @@ export class AppMessagesManager {
this.saveMessages([message], {storage, isOutgoing: true}); this.saveMessages([message], {storage, isOutgoing: true});
setTimeout(() => { setTimeout(() => {
this.setDialogTopMessage(message); this.setDialogTopMessage(message);
rootScope.broadcast('history_append', {storage, peerId, mid: messageId}); rootScope.dispatchEvent('history_append', {storage, peerId, mid: messageId});
}, 0); }, 0);
} }
@ -1583,7 +1583,7 @@ export class AppMessagesManager {
outDialogs.forEach(dialog => { outDialogs.forEach(dialog => {
obj[dialog.peerId] = dialog; obj[dialog.peerId] = dialog;
}); });
rootScope.broadcast('dialogs_multiupdate', obj); rootScope.dispatchEvent('dialogs_multiupdate', obj);
return outDialogs; return outDialogs;
} }
@ -1716,10 +1716,10 @@ export class AppMessagesManager {
if(Object.keys(noIdsDialogs).length) { if(Object.keys(noIdsDialogs).length) {
//setTimeout(() => { // test bad situation //setTimeout(() => { // test bad situation
this.reloadConversation(Object.keys(noIdsDialogs).map(id => +id)).then(() => { this.reloadConversation(Object.keys(noIdsDialogs).map(id => +id)).then(() => {
rootScope.broadcast('dialogs_multiupdate', noIdsDialogs); rootScope.dispatchEvent('dialogs_multiupdate', noIdsDialogs);
for(let peerId in noIdsDialogs) { for(let peerId in noIdsDialogs) {
rootScope.broadcast('dialog_unread', {peerId: +peerId}); rootScope.dispatchEvent('dialog_unread', {peerId: +peerId});
} }
}); });
//}, 10e3); //}, 10e3);
@ -1736,7 +1736,7 @@ export class AppMessagesManager {
if(hasPrepend) { if(hasPrepend) {
this.scheduleHandleNewDialogs(); this.scheduleHandleNewDialogs();
} else { } else {
rootScope.broadcast('dialogs_multiupdate', {}); rootScope.dispatchEvent('dialogs_multiupdate', {});
} }
return dialogsResult; return dialogsResult;
@ -1975,11 +1975,11 @@ export class AppMessagesManager {
delete this.messagesStorageByPeerId[peerId]; delete this.messagesStorageByPeerId[peerId];
if(justClear) { if(justClear) {
rootScope.broadcast('dialog_flush', {peerId}); rootScope.dispatchEvent('dialog_flush', {peerId});
} else { } else {
this.dialogsStorage.dropDialog(peerId); this.dialogsStorage.dropDialog(peerId);
rootScope.broadcast('dialog_drop', {peerId}); rootScope.dispatchEvent('dialog_drop', {peerId});
} }
}); });
} }
@ -1991,7 +1991,7 @@ export class AppMessagesManager {
]) ])
.then(([state, pinned]) => { .then(([state, pinned]) => {
state.hiddenPinnedMessages[peerId] = pinned.maxId; state.hiddenPinnedMessages[peerId] = pinned.maxId;
rootScope.broadcast('peer_pinned_hidden', {peerId, maxId: pinned.maxId}); rootScope.dispatchEvent('peer_pinned_hidden', {peerId, maxId: pinned.maxId});
}); });
} }
@ -2049,7 +2049,7 @@ export class AppMessagesManager {
} }
} }
rootScope.broadcast('peer_pinned_messages', {peerId, unpinAll: true}); rootScope.dispatchEvent('peer_pinned_messages', {peerId, unpinAll: true});
delete this.pinnedMessages[peerId]; delete this.pinnedMessages[peerId];
return true; return true;
@ -2825,11 +2825,11 @@ export class AppMessagesManager {
this.migratedToFrom[migrateTo] = migrateFrom; this.migratedToFrom[migrateTo] = migrateFrom;
//setTimeout(() => { //setTimeout(() => {
rootScope.broadcast('dialog_migrate', {migrateFrom, migrateTo}); rootScope.dispatchEvent('dialog_migrate', {migrateFrom, migrateTo});
const dropped = this.dialogsStorage.dropDialog(migrateFrom); const dropped = this.dialogsStorage.dropDialog(migrateFrom);
if(dropped.length) { if(dropped.length) {
rootScope.broadcast('dialog_drop', {peerId: migrateFrom, dialog: dropped[0]}); rootScope.dispatchEvent('dialog_drop', {peerId: migrateFrom, dialog: dropped[0]});
} }
//}, 100); //}, 100);
} }
@ -3338,7 +3338,7 @@ export class AppMessagesManager {
clearTimeout(this.newMessagesHandleTimeout); clearTimeout(this.newMessagesHandleTimeout);
this.newMessagesHandleTimeout = 0; this.newMessagesHandleTimeout = 0;
rootScope.broadcast('history_multiappend', this.newMessagesToHandle); rootScope.dispatchEvent('history_multiappend', this.newMessagesToHandle);
this.newMessagesToHandle = {}; this.newMessagesToHandle = {};
}; };
@ -3364,7 +3364,7 @@ export class AppMessagesManager {
this.incrementMaxSeenId(newMaxSeenId); this.incrementMaxSeenId(newMaxSeenId);
} }
rootScope.broadcast('dialogs_multiupdate', obj); rootScope.dispatchEvent('dialogs_multiupdate', obj);
this.newDialogsToHandle = {}; this.newDialogsToHandle = {};
}; };
@ -3743,7 +3743,7 @@ export class AppMessagesManager {
} }
if(this.mergeReplyKeyboard(historyStorage, message)) { if(this.mergeReplyKeyboard(historyStorage, message)) {
rootScope.broadcast('history_reply_markup', {peerId}); rootScope.dispatchEvent('history_reply_markup', {peerId});
} }
if(message.fromId > 0 && !message.pFlags.out && message.from_id) { if(message.fromId > 0 && !message.pFlags.out && message.from_id) {
@ -3807,7 +3807,7 @@ export class AppMessagesManager {
dialog.pFlags.unread_mark = true; dialog.pFlags.unread_mark = true;
} }
rootScope.broadcast('dialogs_multiupdate', {[peerId]: dialog}); rootScope.dispatchEvent('dialogs_multiupdate', {[peerId]: dialog});
this.dialogsStorage.setDialogToState(dialog); this.dialogsStorage.setDialogToState(dialog);
} }
}; };
@ -3834,10 +3834,10 @@ export class AppMessagesManager {
// @ts-ignore // @ts-ignore
if(message.clear_history) { // that's will never happen if(message.clear_history) { // that's will never happen
if(isTopMessage) { if(isTopMessage) {
rootScope.broadcast('dialog_flush', {peerId}); rootScope.dispatchEvent('dialog_flush', {peerId});
} }
} else { } else {
rootScope.broadcast('message_edit', { rootScope.dispatchEvent('message_edit', {
storage, storage,
peerId, peerId,
mid mid
@ -3846,7 +3846,7 @@ export class AppMessagesManager {
if(isTopMessage || (message as Message.message).grouped_id) { if(isTopMessage || (message as Message.message).grouped_id) {
const updatedDialogs: {[peerId: number]: Dialog} = {}; const updatedDialogs: {[peerId: number]: Dialog} = {};
updatedDialogs[peerId] = dialog; updatedDialogs[peerId] = dialog;
rootScope.broadcast('dialogs_multiupdate', updatedDialogs); rootScope.dispatchEvent('dialogs_multiupdate', updatedDialogs);
this.dialogsStorage.setDialogToState(dialog); this.dialogsStorage.setDialogToState(dialog);
} }
} }
@ -3938,12 +3938,12 @@ export class AppMessagesManager {
} }
} }
rootScope.broadcast('dialog_unread', {peerId}); rootScope.dispatchEvent('dialog_unread', {peerId});
this.dialogsStorage.setDialogToState(foundDialog); this.dialogsStorage.setDialogToState(foundDialog);
} }
if(foundAffected) { if(foundAffected) {
rootScope.broadcast('messages_read'); rootScope.dispatchEvent('messages_read');
} }
if(!threadId && channelId) { if(!threadId && channelId) {
@ -3951,7 +3951,7 @@ export class AppMessagesManager {
for(const threadKey in this.threadsToReplies) { for(const threadKey in this.threadsToReplies) {
if(threadKey.indexOf(threadKeyPart) === 0) { if(threadKey.indexOf(threadKeyPart) === 0) {
const [peerId, mid] = this.threadsToReplies[threadKey].split('_').map(n => +n); const [peerId, mid] = this.threadsToReplies[threadKey].split('_').map(n => +n);
rootScope.broadcast('replies_updated', this.getMessageByPeer(peerId, mid)); rootScope.dispatchEvent('replies_updated', this.getMessageByPeer(peerId, mid));
} }
} }
} }
@ -3969,7 +3969,7 @@ export class AppMessagesManager {
} }
} }
rootScope.broadcast('messages_media_read', {peerId, mids}); rootScope.dispatchEvent('messages_media_read', {peerId, mids});
}; };
private onUpdateChannelAvailableMessages = (update: Update.updateChannelAvailableMessages) => { private onUpdateChannelAvailableMessages = (update: Update.updateChannelAvailableMessages) => {
@ -4033,14 +4033,14 @@ export class AppMessagesManager {
} }
}); });
rootScope.broadcast('history_delete', {peerId, msgs: historyUpdated.msgs}); rootScope.dispatchEvent('history_delete', {peerId, msgs: historyUpdated.msgs});
const foundDialog = this.getDialogOnly(peerId); const foundDialog = this.getDialogOnly(peerId);
if(foundDialog) { if(foundDialog) {
if(historyUpdated.unread) { if(historyUpdated.unread) {
foundDialog.unread_count -= historyUpdated.unread; foundDialog.unread_count -= historyUpdated.unread;
rootScope.broadcast('dialog_unread', {peerId}); rootScope.dispatchEvent('dialog_unread', {peerId});
} }
if(historyUpdated.msgs[foundDialog.top_message]) { if(historyUpdated.msgs[foundDialog.top_message]) {
@ -4061,7 +4061,7 @@ export class AppMessagesManager {
if(canViewHistory !== hasHistory) { if(canViewHistory !== hasHistory) {
delete this.historiesStorage[peerId]; delete this.historiesStorage[peerId];
rootScope.broadcast('history_forbidden', peerId); rootScope.dispatchEvent('history_forbidden', peerId);
} }
const dialog = this.getDialogOnly(peerId); const dialog = this.getDialogOnly(peerId);
@ -4071,7 +4071,7 @@ export class AppMessagesManager {
} else { } else {
if(dialog) { if(dialog) {
this.dialogsStorage.dropDialog(peerId); this.dialogsStorage.dropDialog(peerId);
rootScope.broadcast('dialog_drop', {peerId, dialog}); rootScope.dispatchEvent('dialog_drop', {peerId, dialog});
} }
} }
} }
@ -4086,7 +4086,7 @@ export class AppMessagesManager {
delete this.historiesStorage[peerId]; delete this.historiesStorage[peerId];
this.reloadConversation(-channelId).then(() => { this.reloadConversation(-channelId).then(() => {
rootScope.broadcast('history_reload', peerId); rootScope.dispatchEvent('history_reload', peerId);
}); });
}; };
@ -4097,7 +4097,7 @@ export class AppMessagesManager {
const message = this.getMessageByPeer(-update.channel_id, mid); const message = this.getMessageByPeer(-update.channel_id, mid);
if(!message.deleted && message.views && message.views < views) { if(!message.deleted && message.views && message.views < views) {
message.views = views; message.views = views;
rootScope.broadcast('message_views', {mid, views}); rootScope.dispatchEvent('message_views', {mid, views});
} }
}; };
@ -4188,7 +4188,7 @@ export class AppMessagesManager {
delete this.pinnedMessages[peerId]; delete this.pinnedMessages[peerId];
appStateManager.getState().then(state => { appStateManager.getState().then(state => {
delete state.hiddenPinnedMessages[peerId]; delete state.hiddenPinnedMessages[peerId];
rootScope.broadcast('peer_pinned_messages', {peerId, mids: messages, pinned: werePinned}); rootScope.dispatchEvent('peer_pinned_messages', {peerId, mids: messages, pinned: werePinned});
}); });
}); });
}; };
@ -4201,7 +4201,7 @@ export class AppMessagesManager {
const dialog = this.getDialogOnly(peerId); const dialog = this.getDialogOnly(peerId);
if(dialog) { if(dialog) {
dialog.notify_settings = notify_settings; dialog.notify_settings = notify_settings;
rootScope.broadcast('dialog_notify_settings', dialog); rootScope.dispatchEvent('dialog_notify_settings', dialog);
this.dialogsStorage.setDialogToState(dialog); this.dialogsStorage.setDialogToState(dialog);
} }
} }
@ -4221,11 +4221,11 @@ export class AppMessagesManager {
if(!oldMessage.deleted) { if(!oldMessage.deleted) {
this.handleEditedMessage(oldMessage, newMessage); this.handleEditedMessage(oldMessage, newMessage);
rootScope.broadcast('message_edit', {storage, peerId, mid: message.mid}); rootScope.dispatchEvent('message_edit', {storage, peerId, mid: message.mid});
} else { } else {
const pendingMessage = this.checkPendingMessage(message); const pendingMessage = this.checkPendingMessage(message);
if(!pendingMessage) { if(!pendingMessage) {
rootScope.broadcast('scheduled_new', {peerId, mid: message.mid}); rootScope.dispatchEvent('scheduled_new', {peerId, mid: message.mid});
} }
} }
} }
@ -4239,7 +4239,7 @@ export class AppMessagesManager {
const mids = update.messages.map(id => this.generateMessageId(id)); const mids = update.messages.map(id => this.generateMessageId(id));
this.handleDeletedMessages(peerId, storage, mids); this.handleDeletedMessages(peerId, storage, mids);
rootScope.broadcast('scheduled_delete', {peerId, mids}); rootScope.dispatchEvent('scheduled_delete', {peerId, mids});
} }
}; };
@ -4281,7 +4281,7 @@ export class AppMessagesManager {
const message = this.getMessageByPeer(peerId, mid); const message = this.getMessageByPeer(peerId, mid);
if(broadcastEventName) { if(broadcastEventName) {
rootScope.broadcast(broadcastEventName, message); rootScope.dispatchEvent(broadcastEventName, message);
} }
return message; return message;
@ -4296,7 +4296,7 @@ export class AppMessagesManager {
if(randomId) { if(randomId) {
const pendingData = this.pendingByRandomId[randomId]; const pendingData = this.pendingByRandomId[randomId];
if(pendingMessage = this.finalizePendingMessage(randomId, message)) { if(pendingMessage = this.finalizePendingMessage(randomId, message)) {
rootScope.broadcast('history_update', {storage: pendingData.storage, peerId: message.peerId, mid: message.mid}); rootScope.dispatchEvent('history_update', {storage: pendingData.storage, peerId: message.peerId, mid: message.mid});
} }
delete this.pendingByMessageId[message.mid]; delete this.pendingByMessageId[message.mid];
@ -4355,7 +4355,7 @@ export class AppMessagesManager {
delete message.random_id; delete message.random_id;
delete message.send; delete message.send;
rootScope.broadcast('messages_pending'); rootScope.dispatchEvent('messages_pending');
} }
delete this.pendingByRandomId[randomId]; delete this.pendingByRandomId[randomId];
@ -4421,7 +4421,7 @@ export class AppMessagesManager {
const tempMessage = this.getMessageFromStorage(storage, tempId); const tempMessage = this.getMessageFromStorage(storage, tempId);
delete storage[tempId]; delete storage[tempId];
rootScope.broadcast('message_sent', {storage, tempId, tempMessage, mid}); rootScope.dispatchEvent('message_sent', {storage, tempId, tempMessage, mid});
} }
public incrementMaxSeenId(maxId: number) { public incrementMaxSeenId(maxId: number) {
@ -4466,7 +4466,7 @@ export class AppMessagesManager {
notification.title = RichTextProcessor.wrapPlainText(notification.title); notification.title = RichTextProcessor.wrapPlainText(notification.title);
notification.onclick = () => { notification.onclick = () => {
rootScope.broadcast('history_focus', {peerId, mid: message.mid}); rootScope.dispatchEvent('history_focus', {peerId, mid: message.mid});
}; };
notification.message = notificationMessage; notification.message = notificationMessage;
@ -4675,7 +4675,7 @@ export class AppMessagesManager {
const mids = messages.map((message) => { const mids = messages.map((message) => {
if(this.mergeReplyKeyboard(historyStorage, message)) { if(this.mergeReplyKeyboard(historyStorage, message)) {
rootScope.broadcast('history_reply_markup', {peerId}); rootScope.dispatchEvent('history_reply_markup', {peerId});
} }
return (message as MyMessage).mid; return (message as MyMessage).mid;
@ -4860,7 +4860,7 @@ export class AppMessagesManager {
this.saveMessages(getMessagesResult.messages); this.saveMessages(getMessagesResult.messages);
} }
rootScope.broadcast('messages_downloaded', {peerId: +peerId, mids}); rootScope.dispatchEvent('messages_downloaded', {peerId: +peerId, mids});
})); }));
} }
@ -4875,7 +4875,7 @@ export class AppMessagesManager {
public wrapSingleMessage(peerId: number, msgId: number, overwrite = false): Promise<void> { public wrapSingleMessage(peerId: number, msgId: number, overwrite = false): Promise<void> {
if(!this.getMessageByPeer(peerId, msgId).deleted && !overwrite) { if(!this.getMessageByPeer(peerId, msgId).deleted && !overwrite) {
rootScope.broadcast('messages_downloaded', {peerId, mids: [msgId]}); rootScope.dispatchEvent('messages_downloaded', {peerId, mids: [msgId]});
return Promise.resolve(); return Promise.resolve();
} else if(!this.needSingleMessages[peerId] || this.needSingleMessages[peerId].indexOf(msgId) === -1) { } else if(!this.needSingleMessages[peerId] || this.needSingleMessages[peerId].indexOf(msgId) === -1) {
(this.needSingleMessages[peerId] ?? (this.needSingleMessages[peerId] = [])).push(msgId); (this.needSingleMessages[peerId] ?? (this.needSingleMessages[peerId] = [])).push(msgId);
@ -4980,7 +4980,7 @@ export class AppMessagesManager {
if(history.albums) { if(history.albums) {
for(const groupId in history.albums) { for(const groupId in history.albums) {
rootScope.broadcast('album_edit', {peerId, groupId, deletedMids: [...history.albums[groupId]]}); rootScope.dispatchEvent('album_edit', {peerId, groupId, deletedMids: [...history.albums[groupId]]});
/* const mids = this.getMidsByAlbum(groupId); /* const mids = this.getMidsByAlbum(groupId);
if(mids.length) { if(mids.length) {
const mid = Math.max(...mids); const mid = Math.max(...mids);

8
src/lib/appManagers/appNotificationsManager.ts

@ -102,7 +102,7 @@ export class AppNotificationsManager {
} }
});*/ });*/
rootScope.on('idle', (newVal) => { rootScope.addEventListener('idle', (newVal) => {
if(this.stopped) { if(this.stopped) {
return; return;
} }
@ -117,7 +117,7 @@ export class AppNotificationsManager {
rootScope.addMultipleEventsListeners({ rootScope.addMultipleEventsListeners({
updateNotifySettings: (update) => { updateNotifySettings: (update) => {
this.savePeerSettings(update.peer._ === 'notifyPeer' ? appPeersManager.getPeerId(update.peer.peer) : update.peer._, update.notify_settings); this.savePeerSettings(update.peer._ === 'notifyPeer' ? appPeersManager.getPeerId(update.peer.peer) : update.peer._, update.notify_settings);
rootScope.broadcast('notify_settings', update); rootScope.dispatchEvent('notify_settings', update);
} }
}); });
@ -401,7 +401,7 @@ export class AppNotificationsManager {
(obj || this.peerSettings)[key] = settings; (obj || this.peerSettings)[key] = settings;
if(typeof(key) !== 'number') { if(typeof(key) !== 'number') {
rootScope.broadcast('notify_peer_type_settings', {key, settings}); rootScope.dispatchEvent('notify_peer_type_settings', {key, settings});
} }
//rootScope.broadcast('notify_settings', {peerId: peerId}); //rootScope.broadcast('notify_settings', {peerId: peerId});
@ -456,7 +456,7 @@ export class AppNotificationsManager {
public start() { public start() {
this.updateLocalSettings(); this.updateLocalSettings();
rootScope.on('settings_updated', this.updateLocalSettings); rootScope.addEventListener('settings_updated', this.updateLocalSettings);
//WebPushApiManager.start(); //WebPushApiManager.start();
if(!this.notificationsUiSupport) { if(!this.notificationsUiSupport) {

2
src/lib/appManagers/appPeersManager.ts

@ -40,7 +40,7 @@ export class AppPeersManager {
constructor() { constructor() {
rootScope.addMultipleEventsListeners({ rootScope.addMultipleEventsListeners({
updatePeerBlocked: (update) => { updatePeerBlocked: (update) => {
rootScope.broadcast('peer_block', {peerId: this.getPeerId(update.peer_id), blocked: update.blocked}); rootScope.dispatchEvent('peer_block', {peerId: this.getPeerId(update.peer_id), blocked: update.blocked});
} }
}); });
} }

2
src/lib/appManagers/appPollsManager.ts

@ -93,7 +93,7 @@ export class AppPollsManager {
} }
poll = this.savePoll(poll, update.results as any); poll = this.savePoll(poll, update.results as any);
rootScope.broadcast('poll_update', {poll, results: update.results as any}); rootScope.dispatchEvent('poll_update', {poll, results: update.results as any});
} }
}); });
} }

2
src/lib/appManagers/appPrivacyManager.ts

@ -29,7 +29,7 @@ export class AppPrivacyManager {
updatePrivacy: (update) => { updatePrivacy: (update) => {
const key = update.key._; const key = update.key._;
this.privacy[key] = update.rules; this.privacy[key] = update.rules;
rootScope.broadcast('privacy_update', update); rootScope.dispatchEvent('privacy_update', update);
} }
}); });
} }

18
src/lib/appManagers/appProfileManager.ts

@ -51,7 +51,7 @@ export class AppProfileManager {
const chatFull = this.chatsFull[chatId] as ChatFull.chatFull; const chatFull = this.chatsFull[chatId] as ChatFull.chatFull;
if(chatFull !== undefined) { if(chatFull !== undefined) {
chatFull.participants = participants; chatFull.participants = participants;
rootScope.broadcast('chat_full_update', chatId); rootScope.dispatchEvent('chat_full_update', chatId);
} }
} }
}, },
@ -75,7 +75,7 @@ export class AppProfileManager {
}); });
_participants.version = update.version; _participants.version = update.version;
rootScope.broadcast('chat_full_update', update.chat_id); rootScope.dispatchEvent('chat_full_update', update.chat_id);
} }
}, },
@ -88,7 +88,7 @@ export class AppProfileManager {
if(participants[i].user_id === update.user_id) { if(participants[i].user_id === update.user_id) {
participants.splice(i, 1); participants.splice(i, 1);
_participants.version = update.version; _participants.version = update.version;
rootScope.broadcast('chat_full_update', update.chat_id); rootScope.dispatchEvent('chat_full_update', update.chat_id);
return; return;
} }
} }
@ -96,7 +96,7 @@ export class AppProfileManager {
} }
}); });
rootScope.on('chat_update', (chatId) => { rootScope.addEventListener('chat_update', (chatId) => {
const fullChat = this.chatsFull[chatId]; const fullChat = this.chatsFull[chatId];
const chat: Chat.chat = appChatsManager.getChat(chatId); const chat: Chat.chat = appChatsManager.getChat(chatId);
if(!chat.photo || !fullChat) { if(!chat.photo || !fullChat) {
@ -107,7 +107,7 @@ export class AppProfileManager {
//////console.log('chat_update:', fullChat); //////console.log('chat_update:', fullChat);
if(fullChat.chat_photo && emptyPhoto !== (fullChat.chat_photo._ === 'photoEmpty')) { if(fullChat.chat_photo && emptyPhoto !== (fullChat.chat_photo._ === 'photoEmpty')) {
delete this.chatsFull[chatId]; delete this.chatsFull[chatId];
rootScope.broadcast('chat_full_update', chatId); rootScope.dispatchEvent('chat_full_update', chatId);
return; return;
} }
if(emptyPhoto) { if(emptyPhoto) {
@ -118,7 +118,7 @@ export class AppProfileManager {
const chatFullPhotoId = fullChat.chat_photo?.id; const chatFullPhotoId = fullChat.chat_photo?.id;
if(chatFullPhotoId !== photoId) { if(chatFullPhotoId !== photoId) {
delete this.chatsFull[chatId]; delete this.chatsFull[chatId];
rootScope.broadcast('chat_full_update', chatId); rootScope.dispatchEvent('chat_full_update', chatId);
} }
}); });
} }
@ -255,7 +255,7 @@ export class AppProfileManager {
appNotificationsManager.savePeerSettings(peerId, fullChat.notify_settings); appNotificationsManager.savePeerSettings(peerId, fullChat.notify_settings);
delete this.fullPromises[peerId]; delete this.fullPromises[peerId];
this.chatsFull[id] = fullChat; this.chatsFull[id] = fullChat;
rootScope.broadcast('chat_full_update', id); rootScope.dispatchEvent('chat_full_update', id);
return fullChat; return fullChat;
}) as any; }) as any;
@ -364,7 +364,7 @@ export class AppProfileManager {
delete this.fullPromises[peerId]; delete this.fullPromises[peerId];
this.chatsFull[id] = fullChannel; this.chatsFull[id] = fullChannel;
rootScope.broadcast('chat_full_update', id); rootScope.dispatchEvent('chat_full_update', id);
return fullChannel; return fullChannel;
}, (error) => { }, (error) => {
@ -417,7 +417,7 @@ export class AppProfileManager {
delete this.chatsFull[id]; delete this.chatsFull[id];
delete this.fullPromises[-id]; delete this.fullPromises[-id];
apiManager.clearCache('channels.getParticipants', (params) => (params.channel as InputChannel.inputChannel).channel_id === id); apiManager.clearCache('channels.getParticipants', (params) => (params.channel as InputChannel.inputChannel).channel_id === id);
rootScope.broadcast('chat_full_update', id); rootScope.dispatchEvent('chat_full_update', id);
} }
public updateProfile(first_name: string, last_name: string, about: string) { public updateProfile(first_name: string, last_name: string, about: string) {

4
src/lib/appManagers/appStateManager.ts

@ -300,7 +300,7 @@ export class AppStateManager extends EventListenerBase<{
if(auth) { if(auth) {
// ! Warning ! DON'T delete this // ! Warning ! DON'T delete this
state.authState = {_: 'authStateSignedIn'}; state.authState = {_: 'authStateSignedIn'};
rootScope.broadcast('user_auth', typeof(auth) === 'number' ? {dcID: 0, id: auth} : auth); // * support old version rootScope.dispatchEvent('user_auth', typeof(auth) === 'number' ? {dcID: 0, id: auth} : auth); // * support old version
} }
// * Read storages // * Read storages
@ -389,7 +389,7 @@ export class AppStateManager extends EventListenerBase<{
public setByKey(key: string, value: any) { public setByKey(key: string, value: any) {
setDeepProperty(this.state, key, value); setDeepProperty(this.state, key, value);
rootScope.broadcast('settings_updated', {key, value}); rootScope.dispatchEvent('settings_updated', {key, value});
const first = key.split('.')[0]; const first = key.split('.')[0];
// @ts-ignore // @ts-ignore

6
src/lib/appManagers/appStickersManager.ts

@ -28,7 +28,7 @@ export class AppStickersManager {
rootScope.addMultipleEventsListeners({ rootScope.addMultipleEventsListeners({
updateNewStickerSet: (update) => { updateNewStickerSet: (update) => {
this.saveStickerSet(update.stickerset, update.stickerset.set.id); this.saveStickerSet(update.stickerset, update.stickerset.set.id);
rootScope.broadcast('stickers_installed', update.stickerset.set); rootScope.dispatchEvent('stickers_installed', update.stickerset.set);
} }
}); });
} }
@ -185,7 +185,7 @@ export class AppStickersManager {
if(res) { if(res) {
delete set.installed_date; delete set.installed_date;
rootScope.broadcast('stickers_deleted', set); rootScope.dispatchEvent('stickers_deleted', set);
this.storage.delete(set.id, true); this.storage.delete(set.id, true);
return true; return true;
} }
@ -197,7 +197,7 @@ export class AppStickersManager {
if(res) { if(res) {
set.installed_date = Date.now() / 1000 | 0; set.installed_date = Date.now() / 1000 | 0;
rootScope.broadcast('stickers_installed', set); rootScope.dispatchEvent('stickers_installed', set);
return true; return true;
} }
} }

22
src/lib/appManagers/appUsersManager.ts

@ -48,7 +48,7 @@ export class AppUsersManager {
constructor() { constructor() {
setInterval(this.updateUsersStatuses, 60000); setInterval(this.updateUsersStatuses, 60000);
rootScope.on('state_synchronized', this.updateUsersStatuses); rootScope.addEventListener('state_synchronized', this.updateUsersStatuses);
rootScope.addMultipleEventsListeners({ rootScope.addMultipleEventsListeners({
updateUserStatus: (update) => { updateUserStatus: (update) => {
@ -67,7 +67,7 @@ export class AppUsersManager {
} }
//user.sortStatus = this.getUserStatusForSort(user.status); //user.sortStatus = this.getUserStatusForSort(user.status);
rootScope.broadcast('user_update', userId); rootScope.dispatchEvent('user_update', userId);
this.setUserToStateIfNeeded(user); this.setUserToStateIfNeeded(user);
} //////else console.warn('No user by id:', userId); } //////else console.warn('No user by id:', userId);
}, },
@ -86,8 +86,8 @@ export class AppUsersManager {
this.setUserToStateIfNeeded(user); this.setUserToStateIfNeeded(user);
rootScope.broadcast('user_update', userId); rootScope.dispatchEvent('user_update', userId);
rootScope.broadcast('avatar_update', userId); rootScope.dispatchEvent('avatar_update', userId);
} else console.warn('No user by id:', userId); } else console.warn('No user by id:', userId);
}, },
@ -110,7 +110,7 @@ export class AppUsersManager {
this.onContactUpdated(update.user_id, update.my_link._ === 'contactLinkContact'); this.onContactUpdated(update.user_id, update.my_link._ === 'contactLinkContact');
break; */ break; */
rootScope.on('language_change', (e) => { rootScope.addEventListener('language_change', (e) => {
const userId = this.getSelf().id; const userId = this.getSelf().id;
this.contactsIndex.indexObject(userId, this.getUserSearchText(userId)); this.contactsIndex.indexObject(userId, this.getUserSearchText(userId));
}); });
@ -357,11 +357,11 @@ export class AppUsersManager {
} */ } */
safeReplaceObject(oldUser, user); safeReplaceObject(oldUser, user);
rootScope.broadcast('user_update', userId); rootScope.dispatchEvent('user_update', userId);
} }
if(changedTitle) { if(changedTitle) {
rootScope.broadcast('peer_title_edit', user.id); rootScope.dispatchEvent('peer_title_edit', user.id);
} }
this.setUserToStateIfNeeded(user); this.setUserToStateIfNeeded(user);
@ -573,7 +573,7 @@ export class AppUsersManager {
user.status.expires < timestampNow) { user.status.expires < timestampNow) {
user.status = {_: 'userStatusOffline', was_online: user.status.expires}; user.status = {_: 'userStatusOffline', was_online: user.status.expires};
rootScope.broadcast('user_update', user.id); rootScope.dispatchEvent('user_update', user.id);
this.setUserToStateIfNeeded(user); this.setUserToStateIfNeeded(user);
} }
@ -609,7 +609,7 @@ export class AppUsersManager {
}; };
//user.sortStatus = this.getUserStatusForSort(user.status); //user.sortStatus = this.getUserStatusForSort(user.status);
rootScope.broadcast('user_update', id); rootScope.dispatchEvent('user_update', id);
this.setUserToStateIfNeeded(user); this.setUserToStateIfNeeded(user);
} }
@ -785,7 +785,7 @@ export class AppUsersManager {
this.onContactsModified(); this.onContactsModified();
rootScope.broadcast('contacts_update', userId); rootScope.dispatchEvent('contacts_update', userId);
} }
} }
@ -814,7 +814,7 @@ export class AppUsersManager {
user.status = status; user.status = status;
//user.sortStatus = this.getUserStatusForSort(user.status); //user.sortStatus = this.getUserStatusForSort(user.status);
rootScope.broadcast('user_update', userId); rootScope.dispatchEvent('user_update', userId);
} }
} }

2
src/lib/appManagers/appWebPagesManager.ts

@ -104,7 +104,7 @@ export class AppWebPagesManager {
msgs.push(+msgId); msgs.push(+msgId);
} }
rootScope.broadcast('webpage_updated', { rootScope.dispatchEvent('webpage_updated', {
id: apiWebPage.id, id: apiWebPage.id,
msgs msgs
}); });

2
src/lib/langPack.ts

@ -206,7 +206,7 @@ namespace I18n {
strings.set(string.key as LangPackKey, string); strings.set(string.key as LangPackKey, string);
} }
rootScope.broadcast('language_change'); rootScope.dispatchEvent('language_change');
const elements = Array.from(document.querySelectorAll(`.i18n`)) as HTMLElement[]; const elements = Array.from(document.querySelectorAll(`.i18n`)) as HTMLElement[];
elements.forEach(element => { elements.forEach(element => {

2
src/lib/mtproto/apiManager.ts

@ -136,7 +136,7 @@ export class ApiManager {
//this.telegramMeNotify(true); //this.telegramMeNotify(true);
/// #if !MTPROTO_WORKER /// #if !MTPROTO_WORKER
rootScope.broadcast('user_auth', userAuth); rootScope.dispatchEvent('user_auth', userAuth);
/// #endif /// #endif
} }

6
src/lib/mtproto/mtprotoworker.ts

@ -101,7 +101,7 @@ export class ApiManagerProxy extends CryptoWorkerMethods {
}); });
this.addTaskListener('connectionStatusChange', (task: any) => { this.addTaskListener('connectionStatusChange', (task: any) => {
rootScope.broadcast('connection_status_change', task.payload); rootScope.dispatchEvent('connection_status_change', task.payload);
}); });
this.addTaskListener('convertWebp', (task) => { this.addTaskListener('convertWebp', (task) => {
@ -280,7 +280,7 @@ export class ApiManagerProxy extends CryptoWorkerMethods {
this.updatesProcessor(task.update); this.updatesProcessor(task.update);
} }
} else if(task.progress) { } else if(task.progress) {
rootScope.broadcast('download_progress', task.progress); rootScope.dispatchEvent('download_progress', task.progress);
} else if(task.hasOwnProperty('result') || task.hasOwnProperty('error')) { } else if(task.hasOwnProperty('result') || task.hasOwnProperty('error')) {
this.finalizeTask(task.taskId, task.result, task.error); this.finalizeTask(task.taskId, task.result, task.error);
} }
@ -479,7 +479,7 @@ export class ApiManagerProxy extends CryptoWorkerMethods {
userAuth = {dcID: 0, id: userAuth}; userAuth = {dcID: 0, id: userAuth};
} }
rootScope.broadcast('user_auth', userAuth); rootScope.dispatchEvent('user_auth', userAuth);
return this.performTaskWorker('setUserAuth', userAuth); return this.performTaskWorker('setUserAuth', userAuth);
} }

37
src/lib/rootScope.ts

@ -75,8 +75,9 @@ export type BroadcastEvents = {
'audio_play': {doc: MyDocument, mid: number, peerId: number}, 'audio_play': {doc: MyDocument, mid: number, peerId: number},
'audio_pause': void, 'audio_pause': void,
'state_cleared': void,
'state_synchronized': number, 'state_synchronized': number,
'state_synchronizing': number, 'state_synchronizing': number | void,
'contacts_update': number, 'contacts_update': number,
'avatar_update': number, 'avatar_update': number,
@ -136,20 +137,20 @@ export class RootScope extends EventListenerBase<{
constructor() { constructor() {
super(); super();
this.on('peer_changed', (peerId) => { this.addEventListener('peer_changed', (peerId) => {
this.peerId = peerId; this.peerId = peerId;
}); });
this.on('user_auth', (e) => { this.addEventListener('user_auth', (e) => {
this.myId = e.id; this.myId = e.id;
}); });
this.on('connection_status_change', (e) => { this.addEventListener('connection_status_change', (e) => {
const status = e; const status = e;
this.connectionStatus[e.name] = status; this.connectionStatus[e.name] = status;
}); });
this.on('idle', (isIDLE) => { this.addEventListener('idle', (isIDLE) => {
if(isIDLE) { if(isIDLE) {
this.idle.focusPromise = new Promise((resolve) => { this.idle.focusPromise = new Promise((resolve) => {
this.idle.focusResolve = resolve; this.idle.focusResolve = resolve;
@ -169,7 +170,7 @@ export class RootScope extends EventListenerBase<{
//const newTheme = this.getTheme(); //const newTheme = this.getTheme();
if(this.myId) { if(this.myId) {
this.broadcast('theme_change'); this.dispatchEvent('theme_change');
} else { } else {
this.setTheme(); this.setTheme();
} }
@ -203,34 +204,12 @@ export class RootScope extends EventListenerBase<{
set overlayIsActive(value: boolean) { set overlayIsActive(value: boolean) {
this._overlayIsActive = value; this._overlayIsActive = value;
this.broadcast('overlay_toggle', value); this.dispatchEvent('overlay_toggle', value);
} }
public getTheme(name: Theme['name'] = this.settings.theme === 'system' ? this.systemTheme : this.settings.theme) { public getTheme(name: Theme['name'] = this.settings.theme === 'system' ? this.systemTheme : this.settings.theme) {
return this.settings.themes.find(t => t.name === name); return this.settings.themes.find(t => t.name === name);
} }
public broadcast = <T extends keyof BroadcastEvents>(name: T, detail?: BroadcastEvents[T]) => {
/* //if(DEBUG) {
if(name !== 'user_update') {
console.debug('Broadcasting ' + name + ' event, with args:', detail);
}
//} */
this.dispatchEvent(name, detail);
};
public on = <T extends keyof BroadcastEvents>(name: T, callback: (e: BroadcastEvents[T]) => any, once?: true) => {
super.addEventListener(name, callback, once);
};
public addEventListener = this.on;
public off = <T extends keyof BroadcastEvents>(name: T, callback: (e: BroadcastEvents[T]) => any) => {
super.removeEventListener(name, callback);
};
public removeEventListener = this.off;
} }
const rootScope = new RootScope(); const rootScope = new RootScope();

6
src/lib/storages/dialogs.ts

@ -66,7 +66,7 @@ export default class DialogsStorage {
this.reset(); this.reset();
rootScope.on('language_change', (e) => { rootScope.addEventListener('language_change', (e) => {
const peerId = appUsersManager.getSelf().id; const peerId = appUsersManager.getSelf().id;
const dialog = this.getDialogOnly(peerId); const dialog = this.getDialogOnly(peerId);
if(dialog) { if(dialog) {
@ -396,7 +396,7 @@ export default class DialogsStorage {
} else { } else {
const dropped = this.dropDialog(peerId); const dropped = this.dropDialog(peerId);
if(dropped.length) { if(dropped.length) {
rootScope.broadcast('dialog_drop', {peerId, dialog: dropped[0]}); rootScope.dispatchEvent('dialog_drop', {peerId, dialog: dropped[0]});
} }
} }
@ -411,7 +411,7 @@ export default class DialogsStorage {
}); });
if(Object.keys(updatedDialogs).length) { if(Object.keys(updatedDialogs).length) {
rootScope.broadcast('dialogs_multiupdate', updatedDialogs); rootScope.dispatchEvent('dialogs_multiupdate', updatedDialogs);
} }
} }

6
src/lib/storages/filters.ts

@ -81,7 +81,7 @@ export default class FiltersStorage {
this.saveDialogFilter(update.filter as any); this.saveDialogFilter(update.filter as any);
} else if(this.filters[update.id]) { // Папка удалена } else if(this.filters[update.id]) { // Папка удалена
//this.getDialogFilters(true); //this.getDialogFilters(true);
this.rootScope.broadcast('filter_delete', this.filters[update.id]); this.rootScope.dispatchEvent('filter_delete', this.filters[update.id]);
delete this.filters[update.id]; delete this.filters[update.id];
} }
@ -98,7 +98,7 @@ export default class FiltersStorage {
this.setOrderIndex(filter); this.setOrderIndex(filter);
}); });
this.rootScope.broadcast('filter_order', update.order); this.rootScope.dispatchEvent('filter_order', update.order);
this.appStateManager.pushToState('filters', this.filters); this.appStateManager.pushToState('filters', this.filters);
}; };
@ -269,7 +269,7 @@ export default class FiltersStorage {
this.setOrderIndex(filter); this.setOrderIndex(filter);
if(update) { if(update) {
this.rootScope.broadcast('filter_update', filter); this.rootScope.dispatchEvent('filter_update', filter);
} }
} }

2
src/pages/pageIm.ts

@ -18,7 +18,7 @@ let onFirstMount = () => {
/* appStateManager.saveState(); */ /* appStateManager.saveState(); */
import('../lib/rootScope').then(m => { import('../lib/rootScope').then(m => {
m.default.broadcast('im_mount'); m.default.dispatchEvent('im_mount');
}); });
if(!I18n.requestedServerLanguage) { if(!I18n.requestedServerLanguage) {

Loading…
Cancel
Save