waffle/frontend/src/components/Messages.svelte

80 lines
2.7 KiB
Svelte
Raw Normal View History

<script>
import { afterUpdate, beforeUpdate, onMount } from "svelte";
import { messagesStoreProvider, showSidebar } from "../stores.js";
import Message from "./Message.svelte";
export let channelId;
2022-04-20 17:49:31 +03:00
let scrollTarget;
let scrollAnchor;
let shouldAutoscroll = true;
let lastScrollHeight = null;
let isScrolledToBottom = true;
$: messages = messagesStoreProvider.getStore(channelId);
2022-04-20 17:49:31 +03:00
afterUpdate(() => {
// hacky way to preserve scroll position when messages are pushed back
if (lastScrollHeight) {
scrollTarget.scrollTop = scrollTarget.scrollHeight - lastScrollHeight;
lastScrollHeight = null;
return;
}
if (shouldAutoscroll && scrollAnchor) {
scrollAnchor.scrollIntoView(false);
2022-04-20 17:49:31 +03:00
}
});
const onScroll = (e) => {
const { scrollTop, offsetHeight, scrollHeight } = e.target;
if ((scrollTop + offsetHeight) >= scrollHeight) { // user scrolled to bottom
messages.setIsCollectingOldMessages(true);
shouldAutoscroll = true;
isScrolledToBottom = true;
} else {
shouldAutoscroll = false;
isScrolledToBottom = false;
if (scrollTop === 0) {
// load older messages if the user scrolls to the top.
// save the current scroll height if the server returned any messages,
// before commiting them to the store. this is to provide the jank scroll height
// preservation
messages.loadOlderMessages(() => {
if (scrollTarget)
lastScrollHeight = scrollTarget.scrollHeight;
});
}
messages.setIsCollectingOldMessages(false);
}
};
const windowDidResize = () => {
// TODO: hack
// showSidebar is false on small viewports
// scrolling to bottom when the virtual keyboard pops up does not work on chromium purely based on isScrolledToBottom for some reason
const isSmallViewport = !$showSidebar;
if (isScrolledToBottom || isSmallViewport) {
scrollAnchor.scrollIntoView(false);
}
};
</script>
<svelte:window on:resize={ windowDidResize } />
<style>
.messages-container {
height: 100%;
width: 100%;
flex-grow: 0;
overflow-y: auto;
2022-04-22 23:01:44 +03:00
overflow-x: hidden;
background-color: var(--background-color-1);
}
</style>
<div class="messages-container" on:scroll={ onScroll } bind:this={ scrollTarget }>
{#each $messages as message (message.id)}
<Message message={message} />
{/each}
<div bind:this={ scrollAnchor } />
</div>