Skip to content

Commit

Permalink
Fix autoscroll on new messages (#1382)
Browse files Browse the repository at this point in the history
Co-authored-by: Franco <[email protected]>
Co-authored-by: Sindre Sorhus <[email protected]>
Co-authored-by: Dušan Simić <[email protected]>
  • Loading branch information
3 people authored Jun 27, 2020
1 parent 157e93d commit e94f36e
Showing 1 changed file with 55 additions and 0 deletions.
55 changes: 55 additions & 0 deletions source/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -542,6 +542,58 @@ function insertionListener(event: AnimationEvent): void {
}
}

async function observeAutoscroll(): Promise<void> {
const mainElement = await elementReady<HTMLElement>('._4sp8', {stopOnDomReady: false});
if (!mainElement) {
return;
}

const scrollToBottom = (): void => {
const scrollableElement: HTMLElement | null = document.querySelector('[role=presentation] .scrollable');
if (scrollableElement) {
scrollableElement.scroll({
top: Number.MAX_SAFE_INTEGER,
behavior: 'smooth'
});
}
}

const hookMessageObserver = async (): Promise<void> => {
const chatElement = await elementReady<HTMLElement>(
'[role=presentation] .scrollable [role = region] > div[id ^= "js_"]', {stopOnDomReady: false}
);

if (chatElement) {
// Scroll to the bottom when opening different conversation
scrollToBottom();

const messageObserver = new MutationObserver((record: MutationRecord[]) => {
const newMessages: MutationRecord[] = record.filter(record => {
// The mutation is an addition
return record.addedNodes.length > 0 &&
// ... of a div (skip the "seen" status change)
(record.addedNodes[0] as HTMLElement).tagName === 'DIV' &&
// ... on the last child (skip previous messages added when scrolling up)
chatElement.lastChild!.contains(record.target);
});

if (newMessages.length > 0) {
// Scroll to the bottom when there are new messages
scrollToBottom();
}
});

messageObserver.observe(chatElement, {childList: true, subtree: true});
}
};

hookMessageObserver();

// Hook it again if conversation changes
const conversationObserver = new MutationObserver(hookMessageObserver);
conversationObserver.observe(mainElement, {childList: true});
}

// Listen for emoji element dom insertion
document.addEventListener('animationstart', insertionListener, false);

Expand Down Expand Up @@ -580,6 +632,9 @@ document.addEventListener('DOMContentLoaded', async () => {

// Disable autoplay if set in settings
toggleVideoAutoplay();

// Hook auto-scroll observer
observeAutoscroll();
});

// Handle title bar double-click.
Expand Down

0 comments on commit e94f36e

Please sign in to comment.