Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 156 additions & 0 deletions src/lib/components/ReverseScroll.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
<script lang="ts" generics="T">
import { tick } from "svelte";
import type { Snippet } from "svelte";
import { fly } from "svelte/transition";
import { VList } from "virtua/svelte";

import ArrowDown from "~icons/ph/arrow-down";

import { settings } from "#lib/settings/index.js";

interface Props {
class?: string;
data: T[];
showJumpButton?: boolean;

/**
* Whether older items should be loaded with {@linkcode onloadmore} when
* scrolled near the top.
*/
lazy?: boolean;
getKey: (item: T, index: number) => string | number;
onloadmore?: () => Promise<unknown>;
children: Snippet<[item: T, index: number]>;
}

// Arbitrary; corresponds to how much of the bottom of the list needs to be
// visible (smaller = more, larger = less).
const TOLERANCE = 15;

// Distance from the top of the list at which older items start loading.
const LOAD_THRESHOLD = 200;

const {
class: className,
data,
showJumpButton = true,
lazy = false,
getKey,
onloadmore,
children,
}: Props = $props();

let list = $state<VList<T>>();
let scrollingPaused = $state(false);
let lastSeen = $state.raw<T>();
let countSnapshot = $state(0);
let shifting = $state(false);

let loading = false;

const observer = new ResizeObserver(() => {
if (!scrollingPaused) scrollToEnd();
});

const newCount = $derived.by(() => {
if (!scrollingPaused) return 0;

// Counted from the last item seen when older items can be loaded so
// that they aren't counted as new. Otherwise, the length is compared
// so that items moved to the end aren't miscounted.
return onloadmore
? data.length - 1 - data.lastIndexOf(lastSeen!)
: data.length - countSnapshot;
});

const hasNew = $derived(newCount > 0);

$effect(() => {
if (data.length && !scrollingPaused) {
scrollToEnd();
}
});

function scrollToEnd() {
list?.scrollToIndex(data.length - 1, { align: "end" });
}

function handleScroll(offset: number) {
if (!list) return;

const atBottom = offset >= list.getScrollSize() - list.getViewportSize() - TOLERANCE;

if (!atBottom && !scrollingPaused) {
lastSeen = data.at(-1);
countSnapshot = data.length;
}

scrollingPaused = !atBottom;

if (lazy && offset < LOAD_THRESHOLD) {
void loadMore();
}
}

async function loadMore() {
if (loading || !onloadmore) return;

loading = true;
shifting = true;

try {
await onloadmore();

// Keep the current items in place as older ones are prepended.
await tick();
} finally {
shifting = false;
loading = false;
}
}
</script>

<div
class="reverse-scroll group/scroll relative h-full"
data-scrollbar={!settings.state["chat.hideScrollbar"]}
{@attach (element) => {
observer.observe(element);

return () => observer.disconnect();
}}
>
{#if showJumpButton && scrollingPaused}
<div class="absolute inset-x-0 bottom-4 z-10 flex justify-center">
<button
class={[
"flex items-center rounded-full border bg-orange-500/40 p-1.5 text-xs font-medium shadow-sm backdrop-blur-lg transition-[background-color,padding] duration-200 ease-out hover:bg-orange-500/60",
hasNew && "pr-3",
]}
type="button"
onclick={scrollToEnd}
transition:fly={{ y: 16, duration: 200 }}
>
<ArrowDown class="size-4 shrink-0" />

<span
class="grid overflow-hidden transition-[grid-template-columns] duration-200 ease-out"
style:grid-template-columns={hasNew ? "minmax(0, 1fr)" : "minmax(0, 0fr)"}
>
<span class="overflow-hidden pl-1.5 whitespace-nowrap">
{newCount} new {newCount === 1 ? "message" : "messages"}
</span>
</span>
</button>
</div>
{/if}

<VList
class="{className} scroll-fade overflow-y-auto group-data-[scrollbar=false]/scroll:[&::-webkit-scrollbar]:hidden"
{data}
shift={shifting}
{getKey}
{children}
onscroll={handleScroll}
bind:this={list}
/>
</div>
191 changes: 38 additions & 153 deletions src/lib/components/chat/Chat.svelte
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
<script lang="ts">
import { fly } from "svelte/transition";
import { VList } from "virtua/svelte";

import ArrowDown from "~icons/ph/arrow-down";

import type { Message } from "#lib/models/message/message.js";

import { Chat } from "#lib/models/chat.svelte.js";
Expand All @@ -13,52 +8,17 @@
import Event from "../message/Event.svelte";
import Notification from "../message/Notification.svelte";
import UserMessage from "../message/UserMessage.svelte";
import ReverseScroll from "../ReverseScroll.svelte";
import ChatSeparator from "./ChatSeparator.svelte";

interface Props {
class?: string;
chat: Chat;
}

// Arbitrary; corresponds to how much of the bottom of the chat needs to be
// visible (smaller = more, larger = less).
const TOLERANCE = 15;

const { class: className, chat }: Props = $props();

let list = $state<VList<Message>>();
let scrollingPaused = $state(false);
let countSnapshot = $state(0);
let lastRead = $state<Message | null>(null);

const observer = new ResizeObserver(() => {
if (!scrollingPaused) scrollToEnd();
});

const newMessageCount = $derived(chat.messages.length - countSnapshot);
const hasNew = $derived(newMessageCount > 0);

$effect(() => {
if (chat.messages.length && !scrollingPaused) {
scrollToEnd();
}
});

function scrollToEnd() {
list?.scrollToIndex(chat.messages.length - 1, { align: "end" });
}

function handleScroll(offset: number) {
if (!list) return;

const atBottom = offset >= list.getScrollSize() - list.getViewportSize() - TOLERANCE;

if (!atBottom && !scrollingPaused) {
countSnapshot = chat.messages.length;
}

scrollingPaused = !atBottom;
}
</script>

<svelte:window
Expand All @@ -72,121 +32,46 @@
}}
/>

<div
class="chat group/chat relative h-full"
data-scrollbar={!settings.state["chat.hideScrollbar"]}
{@attach (element) => {
observer.observe(element);

return () => observer.disconnect();
}}
>
{#if scrollingPaused}
<div class="absolute inset-x-0 bottom-4 z-10 flex justify-center">
<button
class={[
"flex items-center rounded-full border bg-orange-500/40 p-1.5 text-xs font-medium shadow-sm backdrop-blur-lg transition-[background-color,padding] duration-200 ease-out hover:bg-orange-500/60",
hasNew && "pr-3",
]}
type="button"
onclick={scrollToEnd}
transition:fly={{ y: 16, duration: 200 }}
>
<ArrowDown class="size-4 shrink-0" />

<span
class="grid overflow-hidden transition-[grid-template-columns] duration-200 ease-out"
style:grid-template-columns={hasNew ? "minmax(0, 1fr)" : "minmax(0, 0fr)"}
>
<span class="overflow-hidden pl-1.5 whitespace-nowrap">
{newMessageCount} new {newMessageCount === 1 ? "message" : "messages"}
</span>
</span>
</button>
</div>
{/if}

<VList
class="{className} chat-viewport overflow-y-auto text-sm group-data-[scrollbar=false]/chat:[&::-webkit-scrollbar]:hidden"
data={chat.messages}
getKey={(message) => message.id}
onscroll={handleScroll}
bind:this={list}
>
{#snippet children(message, i)}
{#if message.isEvent() || message.isUser()}
{@const prev = chat.messages[i - 1]}
{@const isNewDay = prev && prev.timestamp.getDate() !== message.timestamp.getDate()}

{#if isNewDay}
<ChatSeparator>
<time datetime={message.timestamp.toISOString()}>
{message.timestamp.toLocaleDateString(navigator.languages, {
dateStyle: "long",
})}
</time>
</ChatSeparator>
{/if}

{#if message.isEvent()}
<Event {message} />
{:else if message.isUser()}
{#if message.event}
<Notification {message} />
{:else if message.autoMod}
<AutoMod {message} metadata={message.autoMod} />
{:else}
<UserMessage {message} />
{/if}
{/if}

{@const next = chat.messages.at(i + 1)}
{@const nextRecent = next && (next.isEvent() || next.isUser()) && next.recent}

{#if message === lastRead && next && settings.state["chat.newSeparator"]}
<ChatSeparator class="text-twitch-400">New messages</ChatSeparator>
{/if}
<ReverseScroll class="{className} text-sm" data={chat.messages} getKey={(message) => message.id}>
{#snippet children(message, i)}
{#if message.isEvent() || message.isUser()}
{@const prev = chat.messages[i - 1]}
{@const isNewDay = prev && prev.timestamp.getDate() !== message.timestamp.getDate()}

{#if isNewDay}
<ChatSeparator>
<time datetime={message.timestamp.toISOString()}>
{message.timestamp.toLocaleDateString(navigator.languages, {
dateStyle: "long",
})}
</time>
</ChatSeparator>
{/if}

{#if message.recent && !nextRecent && settings.state["chat.messages.history.separator"]}
<ChatSeparator class="text-red-400">Live messages</ChatSeparator>
{#if message.isEvent()}
<Event {message} />
{:else if message.isUser()}
{#if message.event}
<Notification {message} />
{:else if message.autoMod}
<AutoMod {message} metadata={message.autoMod} />
{:else}
<UserMessage {message} />
{/if}
{:else if message.isComponent()}
<message.component {...message.props} />
{/if}
{/snippet}
</VList>
</div>

<style>
@property --scroll-fade {
syntax: "<length-percentage>";
inherits: false;
initial-value: 0;
}

.chat :global(.chat-viewport) {
--scroll-fade: 0;
{@const next = chat.messages.at(i + 1)}
{@const nextRecent = next && (next.isEvent() || next.isUser()) && next.recent}

mask-image: linear-gradient(
to bottom,
#000 0,
#000 calc(100% - var(--scroll-fade)),
transparent 100%
);
mask-composite: intersect;
mask-repeat: no-repeat;
animation: 1ms ease-in-out scroll-fade both;
animation-timeline: scroll(self y);
animation-range: calc(100% - calc(var(--spacing) * 24));
}

@keyframes scroll-fade {
from {
--scroll-fade: min(12%, calc(var(--spacing) * 10));
}
{#if message === lastRead && next && settings.state["chat.newSeparator"]}
<ChatSeparator class="text-twitch-400">New messages</ChatSeparator>
{/if}

to {
--scroll-fade: 0;
}
}
</style>
{#if message.recent && !nextRecent && settings.state["chat.messages.history.separator"]}
<ChatSeparator class="text-red-400">Live messages</ChatSeparator>
{/if}
{:else if message.isComponent()}
<message.component {...message.props} />
{/if}
{/snippet}
</ReverseScroll>
Loading
Loading