Bot description bubble

This commit is contained in:
Eduard Kuzmenko 2021-07-08 02:32:10 +03:00
parent 8e3065a652
commit 368254af95
9 changed files with 211 additions and 135 deletions

View File

@ -10,9 +10,9 @@ import type { AppStickersManager } from "../../lib/appManagers/appStickersManage
import type { AppUsersManager } from "../../lib/appManagers/appUsersManager";
import type { AppInlineBotsManager } from "../../lib/appManagers/appInlineBotsManager";
import type { AppPhotosManager } from "../../lib/appManagers/appPhotosManager";
import type { AppDocsManager, MyDocument } from "../../lib/appManagers/appDocsManager";
import type { MyDocument } from "../../lib/appManagers/appDocsManager";
import type { AppPeersManager } from "../../lib/appManagers/appPeersManager";
import type stateStorage from '../../lib/stateStorage';
import type { AppProfileManager } from "../../lib/appManagers/appProfileManager";
import type Chat from "./chat";
import { CHAT_ANIMATION_GROUP } from "../../lib/appManagers/appImManager";
import { getObjectKeysAndSort } from "../../helpers/object";
@ -38,7 +38,6 @@ import { ripple } from "../ripple";
import { wrapAlbum, wrapPhoto, wrapVideo, wrapDocument, wrapSticker, wrapPoll, wrapGroupedDocuments } from "../wrappers";
import { MessageRender } from "./messageRender";
import LazyLoadQueue from "../lazyLoadQueue";
import { AppChatsManager } from "../../lib/appManagers/appChatsManager";
import ListenerSetter from "../../helpers/listenerSetter";
import PollElement from "../poll";
import AudioElement from "../audio";
@ -147,13 +146,16 @@ export default class ChatBubbles {
[_ in MessageEntity['_']]: boolean
}> = {};
private onAnimateLadder: () => void;
constructor(private chat: Chat,
private appMessagesManager: AppMessagesManager,
private appStickersManager: AppStickersManager,
private appUsersManager: AppUsersManager,
private appInlineBotsManager: AppInlineBotsManager,
private appPhotosManager: AppPhotosManager,
private appPeersManager: AppPeersManager
private appPeersManager: AppPeersManager,
private appProfileManager: AppProfileManager
) {
//this.chat.log.error('Bubbles construction');
@ -429,7 +431,7 @@ export default class ChatBubbles {
}
const bubble = (e.target as HTMLElement).classList.contains('bubble') ? e.target as HTMLElement : null;
if(bubble) {
if(bubble && !bubble.classList.contains('bubble-first')) {
const mid = +bubble.dataset.mid
this.chat.input.initMessageReply(mid);
}
@ -2825,8 +2827,12 @@ export default class ChatBubbles {
}
while(history.length) {
let message = this.chat.getMessage(method());
const message = this.chat.getMessage(method());
if(message.id > 0) {
this.renderMessage(message, reverse, true);
} else {
this.processLocalMessageRender(message);
}
}
(this.messagesQueuePromise || Promise.resolve())
@ -2918,173 +2924,15 @@ export default class ChatBubbles {
}
}
/**
* Load and render history
* @param maxId max message id
* @param reverse 'true' means up
* @param isBackLimit is search
* @param additionMsgId for the last message
* @param justLoad do not render
*/
public getHistory(maxId = 0, reverse = false, isBackLimit = false, additionMsgId = 0, justLoad = false): {cached: boolean, promise: Promise<boolean>} {
const peerId = this.peerId;
//console.time('appImManager call getHistory');
const pageCount = Math.min(30, this.appPhotosManager.windowH / 38/* * 1.25 */ | 0);
//const loadCount = Object.keys(this.bubbles).length > 0 ? 50 : pageCount;
const realLoadCount = Object.keys(this.bubbles).length > 0/* || additionMsgId */ ? Math.max(40, pageCount) : pageCount;//const realLoadCount = 50;
//const realLoadCount = pageCount;//const realLoadCount = 50;
let loadCount = realLoadCount;
/* if(TEST_SCROLL) {
//loadCount = 1;
if(Object.keys(this.bubbles).length > 0)
return {cached: false, promise: Promise.resolve(true)};
} */
if(TEST_SCROLL !== undefined) {
if(TEST_SCROLL) {
if(Object.keys(this.bubbles).length > 0) {
--TEST_SCROLL;
}
} else {
return {cached: false, promise: Promise.resolve(true)};
}
}
////console.time('render history total');
let backLimit = 0;
if(isBackLimit) {
backLimit = loadCount;
if(!reverse) { // if not jump
loadCount = 0;
//maxId = this.appMessagesManager.incrementMessageId(maxId, 1);
}
}
let additionMsgIds: number[];
if(additionMsgId && !isBackLimit) {
if(this.chat.type === 'pinned') {
additionMsgIds = [additionMsgId];
} else {
const historyStorage = this.appMessagesManager.getHistoryStorage(peerId, this.chat.threadId);
const slice = historyStorage.history.slice;
if(slice.length < loadCount && !slice.isEnd(SliceEnd.Both)) {
additionMsgIds = slice.slice();
// * filter last album, because we don't know is it the last item
for(let i = additionMsgIds.length - 1; i >= 0; --i) {
const message = this.chat.getMessage(additionMsgIds[i]);
if(message.grouped_id) additionMsgIds.splice(i, 1);
else break;
}
maxId = additionMsgIds[additionMsgIds.length - 1] || maxId;
}
}
}
/* const result = additionMsgID ?
{history: [additionMsgID]} :
appMessagesManager.getHistory(this.peerId, maxId, loadCount, backLimit); */
let result: ReturnType<AppMessagesManager['getHistory']> | {history: number[]} = this.requestHistory(maxId, loadCount, backLimit) as any;
let resultPromise: Promise<any>;
//const isFirstMessageRender = !!additionMsgID && result instanceof Promise && !appMessagesManager.getMessage(additionMsgID).grouped_id;
const isAdditionRender = additionMsgIds?.length && result instanceof Promise;
const isFirstMessageRender = (this.isFirstLoad && backLimit && result instanceof Promise) || isAdditionRender;
if(isAdditionRender) {
resultPromise = result as Promise<any>;
result = {history: additionMsgIds};
//additionMsgID = 0;
}
this.isFirstLoad = false;
const processResult = (historyResult: typeof result) => {
if(this.chat.type === 'discussion' && 'offsetIdOffset' in historyResult) {
//this.log('discussion got history', loadCount, backLimit, historyResult, isTopEnd);
// * inject discussion start
if(historyResult.history.isEnd(SliceEnd.Top)) {
const serviceStartMessageId = this.appMessagesManager.threadsServiceMessagesIdsStorage[this.peerId + '_' + this.chat.threadId];
if(serviceStartMessageId) historyResult.history.push(serviceStartMessageId);
historyResult.history.push(...this.chat.getMidsByMid(this.chat.threadId).reverse());
this.scrollable.loadedAll.top = true;
}
}
};
const sup = (result: HistoryResult) => {
/* if(maxId && result.history?.length) {
if(this.bubbles[maxId]) {
result.history.findAndSplice(mid => mid === maxId);
}
} */
processResult(result);
////console.timeEnd('render history total');
return getHeavyAnimationPromise().then(() => {
return this.performHistoryResult(result.history || [], reverse, isBackLimit, !isAdditionRender && additionMsgId);
});
};
const processPromise = (result: Promise<HistoryResult>) => {
const promise = result.then((result) => {
//this.log('getHistory not cached result by maxId:', maxId, reverse, isBackLimit, result, peerId, justLoad);
if(reverse ? this.getHistoryTopPromise !== promise : this.getHistoryBottomPromise !== promise) {
this.log.warn('getHistory: peer changed');
////console.timeEnd('render history total');
return Promise.reject();
}
if(justLoad) {
this.scrollable.onScroll(); // нужно делать из-за ранней прогрузки
return true;
}
//console.timeEnd('appImManager call getHistory');
return sup(result);
}, (err) => {
this.log.error('getHistory error:', err);
throw err;
});
return promise;
};
let promise: Promise<boolean>, cached: boolean;
if(result instanceof Promise) {
cached = false;
promise = processPromise(result);
} else if(justLoad) {
return null;
} else {
cached = true;
//this.log('getHistory cached result by maxId:', maxId, reverse, isBackLimit, result, peerId, justLoad);
promise = sup(result as HistoryResult);
//return (reverse ? this.getHistoryTopPromise = promise : this.getHistoryBottomPromise = promise);
//return this.performHistoryResult(result.history || [], reverse, isBackLimit, additionMsgID, true);
}
const waitPromise = isAdditionRender ? processPromise(resultPromise) : promise;
if(isFirstMessageRender && rootScope.settings.animationsEnabled/* && false */) {
let times = isAdditionRender ? 2 : 1;
this.messagesQueueOnRenderAdditional = () => {
this.log('ship went past rocks of magnets');
if(--times) return;
this.messagesQueueOnRenderAdditional = undefined;
private animateAsLadder(additionMsgId: number, additionMsgIds: number[], isAdditionRender: boolean, backLimit: number, maxId: number) {
if(!Object.keys(this.bubbles).length) {
return;
}
if(this.onAnimateLadder) {
this.onAnimateLadder();
}
let sortedMids = getObjectKeysAndSort(this.bubbles, 'desc');
if(isAdditionRender && additionMsgIds.length) {
@ -3194,6 +3042,216 @@ export default class ChatBubbles {
});
}
return promise;
}
private processLocalMessageRender(message: any) {
const bubble = this.renderMessage(message, false, false, undefined, false);
bubble.classList.add('bubble-first', 'is-group-last', 'is-group-first');
bubble.classList.remove('can-have-tail', 'is-in');
const messageDiv = bubble.querySelector('.message');
const b = document.createElement('b');
b.append(i18n('BotInfoTitle'));
messageDiv.prepend(b, '\n\n');
if(this.messagesQueueOnRenderAdditional) {
this.onAnimateLadder = () => {
this.chatInner.prepend(bubble);
this.onAnimateLadder = undefined;
};
} else {
this.chatInner.prepend(bubble);
}
}
/**
* Load and render history
* @param maxId max message id
* @param reverse 'true' means up
* @param isBackLimit is search
* @param additionMsgId for the last message
* @param justLoad do not render
*/
public getHistory(maxId = 0, reverse = false, isBackLimit = false, additionMsgId = 0, justLoad = false): {cached: boolean, promise: Promise<boolean>} {
const peerId = this.peerId;
//console.time('appImManager call getHistory');
const pageCount = Math.min(30, this.appPhotosManager.windowH / 38/* * 1.25 */ | 0);
//const loadCount = Object.keys(this.bubbles).length > 0 ? 50 : pageCount;
const realLoadCount = Object.keys(this.bubbles).length > 0/* || additionMsgId */ ? Math.max(40, pageCount) : pageCount;//const realLoadCount = 50;
//const realLoadCount = pageCount;//const realLoadCount = 50;
let loadCount = realLoadCount;
/* if(TEST_SCROLL) {
//loadCount = 1;
if(Object.keys(this.bubbles).length > 0)
return {cached: false, promise: Promise.resolve(true)};
} */
if(TEST_SCROLL !== undefined) {
if(TEST_SCROLL) {
if(Object.keys(this.bubbles).length > 0) {
--TEST_SCROLL;
}
} else {
return {cached: false, promise: Promise.resolve(true)};
}
}
////console.time('render history total');
let backLimit = 0;
if(isBackLimit) {
backLimit = loadCount;
if(!reverse) { // if not jump
loadCount = 0;
//maxId = this.appMessagesManager.incrementMessageId(maxId, 1);
}
}
let additionMsgIds: number[];
if(additionMsgId && !isBackLimit) {
if(this.chat.type === 'pinned') {
additionMsgIds = [additionMsgId];
} else {
const historyStorage = this.appMessagesManager.getHistoryStorage(peerId, this.chat.threadId);
const slice = historyStorage.history.slice;
if(slice.length < loadCount && !slice.isEnd(SliceEnd.Both)) {
additionMsgIds = slice.slice();
// * filter last album, because we don't know is it the last item
for(let i = additionMsgIds.length - 1; i >= 0; --i) {
const message = this.chat.getMessage(additionMsgIds[i]);
if(message.grouped_id) additionMsgIds.splice(i, 1);
else break;
}
maxId = additionMsgIds[additionMsgIds.length - 1] || maxId;
}
}
}
/* const result = additionMsgID ?
{history: [additionMsgID]} :
appMessagesManager.getHistory(this.peerId, maxId, loadCount, backLimit); */
let result: ReturnType<AppMessagesManager['getHistory']> | {history: number[]} = this.requestHistory(maxId, loadCount, backLimit) as any;
let resultPromise: Promise<any>;
//const isFirstMessageRender = !!additionMsgID && result instanceof Promise && !appMessagesManager.getMessage(additionMsgID).grouped_id;
const isAdditionRender = additionMsgIds?.length && result instanceof Promise;
const isFirstMessageRender = (this.isFirstLoad && backLimit && result instanceof Promise) || isAdditionRender;
if(isAdditionRender) {
resultPromise = result as Promise<any>;
result = {history: additionMsgIds};
//additionMsgID = 0;
}
this.isFirstLoad = false;
const processResult = async(historyResult: typeof result) => {
if('offsetIdOffset' in historyResult && historyResult.history.isEnd(SliceEnd.Top)) {
if(this.chat.type === 'discussion') { // * inject discussion start
//this.log('discussion got history', loadCount, backLimit, historyResult, isTopEnd);
const serviceStartMessageId = this.appMessagesManager.threadsServiceMessagesIdsStorage[this.peerId + '_' + this.chat.threadId];
if(serviceStartMessageId) historyResult.history.push(serviceStartMessageId);
historyResult.history.push(...this.chat.getMidsByMid(this.chat.threadId).reverse());
} else if(this.appUsersManager.isBot(this.peerId)) {
this.log('inject bot description');
await this.appProfileManager.getProfile(this.peerId).then(userFull => {
if(!userFull.bot_info?.description) {
return;
}
const offset = this.appMessagesManager.generateMessageId(0);
const message: Message.message = {
_: 'message',
date: 0,
id: -(this.peerId + offset),
message: userFull.bot_info.description,
peer_id: this.appPeersManager.getOutputPeer(this.peerId),
pFlags: {
bot_description: true
}
};
this.appMessagesManager.saveMessages([message]);
this.processLocalMessageRender(message);
});
}
this.scrollable.loadedAll.top = true;
}
};
const sup = async(result: HistoryResult) => {
/* if(maxId && result.history?.length) {
if(this.bubbles[maxId]) {
result.history.findAndSplice(mid => mid === maxId);
}
} */
await processResult(result);
////console.timeEnd('render history total');
return getHeavyAnimationPromise().then(() => {
return this.performHistoryResult(result.history || [], reverse, isBackLimit, !isAdditionRender && additionMsgId);
});
};
const processPromise = (result: Promise<HistoryResult>) => {
const promise = result.then((result) => {
//this.log('getHistory not cached result by maxId:', maxId, reverse, isBackLimit, result, peerId, justLoad);
if(reverse ? this.getHistoryTopPromise !== promise : this.getHistoryBottomPromise !== promise) {
this.log.warn('getHistory: peer changed');
////console.timeEnd('render history total');
return Promise.reject();
}
if(justLoad) {
this.scrollable.onScroll(); // нужно делать из-за ранней прогрузки
return true;
}
//console.timeEnd('appImManager call getHistory');
return sup(result);
}, (err) => {
this.log.error('getHistory error:', err);
throw err;
});
return promise;
};
let promise: Promise<boolean>, cached: boolean;
if(result instanceof Promise) {
cached = false;
promise = processPromise(result);
} else if(justLoad) {
return null;
} else {
cached = true;
//this.log('getHistory cached result by maxId:', maxId, reverse, isBackLimit, result, peerId, justLoad);
promise = sup(result as HistoryResult);
//return (reverse ? this.getHistoryTopPromise = promise : this.getHistoryBottomPromise = promise);
//return this.performHistoryResult(result.history || [], reverse, isBackLimit, additionMsgID, true);
}
const waitPromise = isAdditionRender ? processPromise(resultPromise) : promise;
if(isFirstMessageRender && rootScope.settings.animationsEnabled/* && false */) {
let times = isAdditionRender ? 2 : 1;
this.messagesQueueOnRenderAdditional = () => {
this.log('ship went past rocks of magnets');
if(--times) return;
this.messagesQueueOnRenderAdditional = undefined;
const promise = this.animateAsLadder(additionMsgId, additionMsgIds, isAdditionRender, backLimit, maxId);
(promise || Promise.resolve()).then(() => {
setTimeout(() => { // preload messages
this.loadMoreHistory(reverse, true);

View File

@ -170,7 +170,7 @@ export default class Chat extends EventListenerBase<{
this.initPeerId = peerId;
this.topbar = new ChatTopbar(this, appSidebarRight, this.appMessagesManager, this.appPeersManager, this.appChatsManager, this.appNotificationsManager);
this.bubbles = new ChatBubbles(this, this.appMessagesManager, this.appStickersManager, this.appUsersManager, this.appInlineBotsManager, this.appPhotosManager, this.appPeersManager);
this.bubbles = new ChatBubbles(this, this.appMessagesManager, this.appStickersManager, this.appUsersManager, this.appInlineBotsManager, this.appPhotosManager, this.appPeersManager, this.appProfileManager);
this.input = new ChatInput(this, this.appMessagesManager, this.appDocsManager, this.appChatsManager, this.appPeersManager, this.appWebPagesManager, this.appImManager, this.appDraftsManager, this.serverTimeManager, this.appNotificationsManager, this.appEmojiManager);
this.selection = new ChatSelection(this, this.bubbles, this.input, this.appMessagesManager);
this.contextMenu = new ChatContextMenu(this.bubbles.bubblesContainer, this, this.appMessagesManager, this.appPeersManager, this.appPollsManager, this.appDocsManager);

View File

@ -61,7 +61,7 @@ export default class ChatContextMenu {
} catch(e) {}
// ! context menu click by date bubble (there is no pointer-events)
if(!bubble) return;
if(!bubble || bubble.classList.contains('bubble-first')) return;
if(e instanceof MouseEvent || e.hasOwnProperty('preventDefault')) (e as any).preventDefault();
if(this.element.classList.contains('active')) {

View File

@ -523,6 +523,6 @@ export default class ChatSelection {
}
public canSelectBubble(bubble: HTMLElement) {
return !bubble.classList.contains('service') && !bubble.classList.contains('is-sending');
return !bubble.classList.contains('service') && !bubble.classList.contains('is-sending') && !bubble.classList.contains('bubble-first');
}
}

View File

@ -493,6 +493,7 @@ const lang = {
"PrivacyDeleteCloudDrafts": "Delete All Cloud Drafts",
"AreYouSureClearDraftsTitle": "Delete cloud drafts",
"AreYouSureClearDrafts": "Are you sure you want to delete all cloud drafts?",
"BotInfoTitle": "What can this bot do?",
// * macos
"AccountSettings.Filters": "Chat Folders",

1
src/layer.d.ts vendored
View File

@ -833,6 +833,7 @@ export namespace Message {
pinned?: true,
unread?: true,
is_outgoing?: true,
bot_description?: true,
}>,
id: number,
from_id?: Peer,

View File

@ -438,14 +438,15 @@ export class AppImManager {
//const bubble = chat.bubbles.getBubbleByPoint('top');
//if(bubble) {
//const top = bubble.getBoundingClientRect().top;
const top = chat.bubbles.scrollable.scrollTop;
const chatBubbles = chat.bubbles;
const top = chatBubbles.scrollable.scrollTop;
const key = chat.peerId + (chat.threadId ? '_' + chat.threadId : '');
const chatPositions = stateStorage.getFromCache('chatPositions');
if(!(chat.bubbles.scrollable.getDistanceToEnd() <= 16 && chat.bubbles.scrollable.loadedAll.bottom) && Object.keys(chat.bubbles.bubbles).length) {
if(!(chatBubbles.scrollable.getDistanceToEnd() <= 16 && chatBubbles.scrollable.loadedAll.bottom) && Object.keys(chatBubbles.bubbles).length) {
const position = {
mids: getObjectKeysAndSort(chat.bubbles.bubbles, 'desc'),
mids: getObjectKeysAndSort(chatBubbles.bubbles, 'desc'),
top
};

View File

@ -51,7 +51,8 @@
{"name": "unread", "type": "true"},
{"name": "is_outgoing", "type": "true"},
{"name": "rReply", "type": "string"},
{"name": "viaBotId", "type": "number"}
{"name": "viaBotId", "type": "number"},
{"name": "bot_description", "type": "true"}
]
}, {
"predicate": "messageService",

View File

@ -721,6 +721,20 @@ $bubble-margin: .25rem;
}
}
&-first {
order: -1;
margin-top: .5rem;
justify-content: center;
.time {
display: none !important;
}
&:before, &:after {
display: none;
}
}
.web {
padding-top: 1px;
margin: 4px 0 -5px 1px;