mirror of
https://github.com/open-webui/open-webui.git
synced 2026-11-26 07:11:00 -05:00
609 lines
15 KiB
Svelte
609 lines
15 KiB
Svelte
<script lang="ts">
|
|
import { getPageContext } from '$lib/utils/page';
|
|
const { goto, url: pageUrl, tab: pageTab, active } = getPageContext();
|
|
|
|
import { toast } from 'svelte-sonner';
|
|
|
|
import { onDestroy, onMount, tick } from 'svelte';
|
|
import { onNavigate } from '$app/navigation';
|
|
import { v4 as uuidv4 } from 'uuid';
|
|
import type { Socket } from 'socket.io-client';
|
|
|
|
import {
|
|
config,
|
|
channels,
|
|
channelId as _channelId,
|
|
showSidebar,
|
|
socket,
|
|
user
|
|
} from '$lib/stores';
|
|
import { getChannelById, getChannelMessages, sendMessage } from '$lib/apis/channels';
|
|
|
|
import Messages from './Messages.svelte';
|
|
import MessageInput from './MessageInput.svelte';
|
|
import Navbar from './Navbar.svelte';
|
|
import { canUseEncryption, connected, enter, request } from '$lib/encryption/client';
|
|
import ResizableSidePanel from '../common/ResizableSidePanel.svelte';
|
|
import EllipsisVertical from '../icons/EllipsisVertical.svelte';
|
|
import Thread from './Thread.svelte';
|
|
import i18n from '$lib/i18n';
|
|
import Spinner from '../common/Spinner.svelte';
|
|
|
|
export let id = '';
|
|
|
|
let mounted = false;
|
|
$: if (mounted && $active && id) {
|
|
_channelId.set(id);
|
|
updateLastReadAt(id);
|
|
}
|
|
$: if (mounted && !$active && $_channelId === id) _channelId.set(null);
|
|
let invitationSession: string | null = null;
|
|
let stopInvitation = () => {};
|
|
$: watchInvitation(
|
|
$socket,
|
|
channel?.id === id ? id : null,
|
|
mounted && canUseEncryption($user, $config?.features)
|
|
);
|
|
|
|
function watchInvitation(
|
|
connection: Socket | null,
|
|
channelId: string | null,
|
|
enabled: boolean | undefined
|
|
) {
|
|
stopInvitation();
|
|
stopInvitation = () => {};
|
|
invitationSession = null;
|
|
if (!enabled || !connection || !channelId) return;
|
|
let alive = true;
|
|
let revision = 0;
|
|
const receive = (event: {
|
|
data?: { type?: string; data?: { channel: string; session: string | null } };
|
|
}) => {
|
|
if (event?.data?.type !== 'encryption:available') return;
|
|
const data = event.data.data;
|
|
if (data?.channel === channelId) {
|
|
revision++;
|
|
invitationSession = data.session;
|
|
}
|
|
};
|
|
const clear = () => {
|
|
revision++;
|
|
invitationSession = null;
|
|
};
|
|
const query = () => {
|
|
if (!connected(connection)) return;
|
|
const issued = revision;
|
|
void request(connection, 'status', { channel: channelId })
|
|
.then((result) => {
|
|
if (alive && revision === issued)
|
|
invitationSession = result.available ? result.session : null;
|
|
})
|
|
.catch(() => {});
|
|
};
|
|
connection.on('events', receive);
|
|
connection.on('disconnect', clear);
|
|
connection.on('connect', query);
|
|
query();
|
|
stopInvitation = () => {
|
|
alive = false;
|
|
connection.off('events', receive);
|
|
connection.off('disconnect', clear);
|
|
connection.off('connect', query);
|
|
};
|
|
}
|
|
|
|
let currentId = null;
|
|
|
|
let scrollEnd = true;
|
|
let messagesContainerElement = null;
|
|
let chatInputElement: { focus: () => void } | null = null;
|
|
let threadChatInputElement = null;
|
|
|
|
let top = false;
|
|
|
|
let channel: any = null;
|
|
let messages = null;
|
|
|
|
let replyToMessage = null;
|
|
let threadId: any = null;
|
|
|
|
onNavigate(({ from, to }) => {
|
|
if (from?.url.pathname !== to.url.pathname) {
|
|
threadId = null;
|
|
return tick();
|
|
}
|
|
});
|
|
|
|
let typingUsers = [];
|
|
let typingUsersTimeout = {};
|
|
|
|
$: if (id) {
|
|
initHandler();
|
|
}
|
|
|
|
$: if (channel && $pageUrl.searchParams.get('thread')) {
|
|
threadId = $pageUrl.searchParams.get('thread');
|
|
}
|
|
|
|
const scrollToBottom = () => {
|
|
if (messagesContainerElement) {
|
|
// The channel uses flex-col-reverse, whose bottom is scrollTop = 0.
|
|
messagesContainerElement.scrollTop = 0;
|
|
}
|
|
};
|
|
|
|
const updateLastReadAt = async (channelId) => {
|
|
$socket?.emit('events:channel', {
|
|
channel_id: channelId,
|
|
message_id: null,
|
|
data: {
|
|
type: 'last_read_at'
|
|
}
|
|
});
|
|
|
|
channels.set(
|
|
$channels.map((channel) => {
|
|
if (channel.id === channelId) {
|
|
return {
|
|
...channel,
|
|
unread_count: 0
|
|
};
|
|
}
|
|
return channel;
|
|
})
|
|
);
|
|
};
|
|
|
|
let threadTrigger: HTMLButtonElement | null = null;
|
|
const closeThread = async () => {
|
|
const trigger = threadTrigger;
|
|
threadTrigger = null;
|
|
threadId = null;
|
|
await tick();
|
|
if (document.activeElement === document.body) {
|
|
(trigger?.isConnected ? trigger : chatInputElement)?.focus();
|
|
}
|
|
};
|
|
|
|
const pinHandler = (
|
|
messageId: string,
|
|
pinned: boolean,
|
|
pinnedBy: string | null = pinned ? ($user?.id ?? null) : null,
|
|
pinnedAt: number | null = pinned ? Date.now() * 1000000 : null
|
|
) => {
|
|
if (messages) {
|
|
messages = messages.map((message) => {
|
|
if (message.id === messageId) {
|
|
return {
|
|
...message,
|
|
is_pinned: pinned,
|
|
pinned_by: pinnedBy,
|
|
pinned_at: pinnedAt
|
|
};
|
|
}
|
|
return message;
|
|
});
|
|
}
|
|
};
|
|
|
|
const initHandler = async () => {
|
|
if (currentId && $active) {
|
|
updateLastReadAt(currentId);
|
|
}
|
|
|
|
currentId = id;
|
|
if ($active) updateLastReadAt(id);
|
|
|
|
top = false;
|
|
messages = null;
|
|
channel = null;
|
|
threadId = null;
|
|
replyToMessage = null;
|
|
|
|
typingUsers = [];
|
|
typingUsersTimeout = {};
|
|
|
|
const messagesRequest = getChannelMessages(localStorage.token, id, 0).catch(() => null);
|
|
|
|
channel = await getChannelById(localStorage.token, id).catch((error) => {
|
|
return null;
|
|
});
|
|
|
|
if (channel) {
|
|
messages = await messagesRequest;
|
|
|
|
if (messages) {
|
|
scrollToBottom();
|
|
|
|
if (messages.length < 50) {
|
|
top = true;
|
|
}
|
|
}
|
|
} else {
|
|
goto('/');
|
|
}
|
|
};
|
|
|
|
const channelEventHandler = async (event) => {
|
|
if (event.channel_id === id) {
|
|
const type = event?.data?.type ?? null;
|
|
const data = event?.data?.data ?? null;
|
|
|
|
if (type === 'message') {
|
|
if ($active && document.visibilityState === 'visible') {
|
|
updateLastReadAt(id);
|
|
}
|
|
|
|
if ((data?.parent_id ?? null) === null) {
|
|
const idx = (messages ?? []).findIndex(
|
|
(message) =>
|
|
message.id === data.id || (data.temp_id && message.temp_id === data.temp_id)
|
|
);
|
|
if (idx === -1) {
|
|
messages = [{ ...data, temp_id: null }, ...(messages ?? [])];
|
|
} else {
|
|
// Confirm the existing row without changing its position or render key.
|
|
const previous = messages[idx];
|
|
messages[idx] = {
|
|
...previous,
|
|
...data,
|
|
temp_id: null,
|
|
client_id: previous.client_id ?? previous.id
|
|
};
|
|
}
|
|
|
|
if (typingUsers.find((user) => user.id === event.user.id)) {
|
|
typingUsers = typingUsers.filter((user) => user.id !== event.user.id);
|
|
}
|
|
|
|
await tick();
|
|
if (idx === -1 && scrollEnd) {
|
|
scrollToBottom();
|
|
}
|
|
}
|
|
} else if (type === 'message:update') {
|
|
const idx = messages.findIndex((message) => message.id === data.id);
|
|
|
|
if (idx !== -1) {
|
|
messages[idx] = { ...messages[idx], ...data };
|
|
}
|
|
} else if (type === 'message:delete') {
|
|
messages = messages
|
|
.filter((message) => message.id !== data.id)
|
|
.map((message) =>
|
|
message?.reply_to_message?.id === data.id
|
|
? { ...message, reply_to_message: null }
|
|
: message
|
|
);
|
|
|
|
if (replyToMessage?.id === data.id) {
|
|
replyToMessage = null;
|
|
}
|
|
|
|
if (threadId === data.id) {
|
|
threadId = null;
|
|
}
|
|
} else if (type === 'message:reply') {
|
|
const idx = messages.findIndex((message) => message.id === data.id);
|
|
|
|
if (idx !== -1) {
|
|
messages[idx] = { ...messages[idx], ...data };
|
|
}
|
|
} else if (type.includes('message:reaction')) {
|
|
const idx = messages.findIndex((message) => message.id === data.id);
|
|
if (idx !== -1) {
|
|
messages[idx] = { ...messages[idx], ...data };
|
|
}
|
|
} else if (type === 'typing' && event.message_id === null) {
|
|
if (event.user.id === $user?.id) {
|
|
return;
|
|
}
|
|
|
|
typingUsers = data.typing
|
|
? [
|
|
...typingUsers,
|
|
...(typingUsers.find((user) => user.id === event.user.id)
|
|
? []
|
|
: [
|
|
{
|
|
id: event.user.id,
|
|
name: event.user.name
|
|
}
|
|
])
|
|
]
|
|
: typingUsers.filter((user) => user.id !== event.user.id);
|
|
|
|
if (typingUsersTimeout[event.user.id]) {
|
|
clearTimeout(typingUsersTimeout[event.user.id]);
|
|
}
|
|
|
|
typingUsersTimeout[event.user.id] = setTimeout(() => {
|
|
typingUsers = typingUsers.filter((user) => user.id !== event.user.id);
|
|
}, 5000);
|
|
}
|
|
}
|
|
};
|
|
|
|
const submitHandler = async ({
|
|
content,
|
|
data,
|
|
channel_id,
|
|
reply_to_message
|
|
}: {
|
|
content: string;
|
|
data: any;
|
|
channel_id: string;
|
|
reply_to_message: any;
|
|
}) => {
|
|
if (!content && (data?.files ?? []).length === 0) {
|
|
return;
|
|
}
|
|
|
|
const tempId = uuidv4();
|
|
|
|
const message = {
|
|
temp_id: tempId,
|
|
content: content,
|
|
data: data,
|
|
reply_to_id: reply_to_message?.id ?? null
|
|
};
|
|
|
|
const ts = Date.now() * 1000000; // nanoseconds
|
|
messages = [
|
|
{
|
|
...message,
|
|
id: tempId,
|
|
client_id: tempId,
|
|
user_id: $user?.id,
|
|
user: $user,
|
|
reply_to_message: reply_to_message ?? null,
|
|
created_at: ts,
|
|
updated_at: ts
|
|
},
|
|
...messages
|
|
];
|
|
|
|
await tick();
|
|
if (id === channel_id) scrollToBottom();
|
|
|
|
const res = await sendMessage(localStorage.token, channel_id, message).catch((error) => {
|
|
toast.error(`${error}`);
|
|
return null;
|
|
});
|
|
|
|
const idx = (messages ?? []).findIndex((message) => message.temp_id === tempId);
|
|
if (idx !== -1) {
|
|
if (res) {
|
|
messages[idx] = { ...messages[idx], ...res, temp_id: null };
|
|
} else {
|
|
messages = messages.filter((message) => message.temp_id !== tempId);
|
|
}
|
|
}
|
|
|
|
return res;
|
|
};
|
|
|
|
const onChange = async () => {
|
|
$socket?.emit('events:channel', {
|
|
channel_id: id,
|
|
message_id: null,
|
|
data: {
|
|
type: 'typing',
|
|
data: {
|
|
typing: true
|
|
}
|
|
}
|
|
});
|
|
|
|
updateLastReadAt(id);
|
|
};
|
|
|
|
const MIN_MESSAGES_WIDTH = 360;
|
|
const MIN_THREAD_WIDTH = 320;
|
|
let contentWidth = 0;
|
|
let threadPanelWidth = 420;
|
|
|
|
// The thread takes the whole width when it does not fit beside the messages.
|
|
$: threadFills = contentWidth < MIN_MESSAGES_WIDTH + MIN_THREAD_WIDTH;
|
|
$: if (contentWidth && !threadFills) {
|
|
threadPanelWidth = Math.min(threadPanelWidth, contentWidth - MIN_MESSAGES_WIDTH);
|
|
}
|
|
|
|
onMount(() => {
|
|
mounted = true;
|
|
|
|
$socket?.on('events:channel', channelEventHandler);
|
|
});
|
|
|
|
onDestroy(() => {
|
|
stopInvitation();
|
|
// last read at
|
|
if ($active) updateLastReadAt(id);
|
|
if ($_channelId === id) _channelId.set(null);
|
|
$socket?.off('events:channel', channelEventHandler);
|
|
});
|
|
import PageTitle from '$lib/components/common/PageTitle.svelte';
|
|
</script>
|
|
|
|
<svelte:document
|
|
on:visibilitychange={() => {
|
|
if (mounted && $active && id && document.visibilityState === 'visible') updateLastReadAt(id);
|
|
}}
|
|
/>
|
|
|
|
<!-- LICENSE covers this Open WebUI browser-title identifier.
|
|
Do not alter, remove, obscure, or replace it except as LICENSE permits:
|
|
https://docs.openwebui.com/license. -->
|
|
{#if channel?.type === 'dm'}
|
|
<PageTitle
|
|
title={(channel?.name.trim() ||
|
|
channel?.users.reduce((a, e, i, arr) => {
|
|
if (e.id === $user?.id) {
|
|
return a;
|
|
}
|
|
|
|
if (a) {
|
|
return `${a}, ${e.name}`;
|
|
} else {
|
|
return e.name;
|
|
}
|
|
}, '')) + ' / Open WebUI'}
|
|
/>
|
|
{:else}
|
|
<PageTitle title={(channel?.name ?? 'Channel') + ' / Open WebUI'} />
|
|
{/if}
|
|
|
|
{#if !channel || messages === null}
|
|
<div class="flex h-full items-center justify-center"><Spinner className="size-5" /></div>
|
|
{:else}
|
|
<div
|
|
class="h-full max-h-full transition-width duration-200 ease-in-out {$showSidebar && !pageTab
|
|
? 'md:max-w-[calc(100%-var(--sidebar-width))]'
|
|
: ''} w-full max-w-full min-w-0 flex flex-col"
|
|
id="channel-container"
|
|
>
|
|
<Navbar
|
|
{channel}
|
|
onPin={pinHandler}
|
|
onUpdate={async () => {
|
|
channel = await getChannelById(localStorage.token, id).catch((error) => {
|
|
return null;
|
|
});
|
|
}}
|
|
>
|
|
<svelte:fragment slot="subtitle">
|
|
{#if invitationSession}
|
|
<div
|
|
class="flex flex-wrap items-center gap-x-1.5 text-[0.6875rem] font-normal text-base-500 dark:text-base-400"
|
|
>
|
|
<span>{$i18n.t('Encrypted chat in progress')}</span>
|
|
<span aria-hidden="true">·</span>
|
|
<button
|
|
type="button"
|
|
aria-label={$i18n.t('Join encrypted chat')}
|
|
class="text-[0.6875rem] font-normal text-base-700 underline-offset-2 hover:underline dark:text-base-200"
|
|
on:click={() => {
|
|
if (!invitationSession || !canUseEncryption($user, $config?.features)) return;
|
|
enter(id, { action: 'join', session: invitationSession });
|
|
void goto(`/channels/${encodeURIComponent(id)}/encrypted`);
|
|
}}
|
|
>
|
|
{$i18n.t('Join')}
|
|
</button>
|
|
</div>
|
|
{/if}
|
|
</svelte:fragment>
|
|
</Navbar>
|
|
|
|
<div class="relative w-full flex-1 min-h-0 flex" bind:clientWidth={contentWidth}>
|
|
<!-- Invisible rather than hidden, to keep the scroll position. -->
|
|
<div
|
|
class="h-full flex flex-col min-w-0 flex-1 relative"
|
|
class:invisible={threadId !== null && threadFills}
|
|
>
|
|
{#if channel && messages !== null}
|
|
<div class="flex-1 overflow-y-auto">
|
|
<div
|
|
class=" pb-2.5 max-w-full z-10 scrollbar-hidden w-full h-full flex-1 flex flex-col-reverse overflow-auto"
|
|
id="messages-container"
|
|
bind:this={messagesContainerElement}
|
|
on:scroll={(e) => {
|
|
scrollEnd = Math.abs(messagesContainerElement.scrollTop) <= 50;
|
|
}}
|
|
>
|
|
{#key id}
|
|
<Messages
|
|
{channel}
|
|
{top}
|
|
bind:messages
|
|
{replyToMessage}
|
|
onReply={async (message) => {
|
|
replyToMessage = message;
|
|
await tick();
|
|
chatInputElement?.focus();
|
|
}}
|
|
onThread={async (id: string, trigger: HTMLButtonElement) => {
|
|
threadTrigger = trigger;
|
|
threadId = id;
|
|
await tick();
|
|
threadChatInputElement?.focus();
|
|
}}
|
|
onPin={pinHandler}
|
|
onLoad={async () => {
|
|
const newMessages = await getChannelMessages(
|
|
localStorage.token,
|
|
id,
|
|
messages.length
|
|
);
|
|
|
|
messages = [...messages, ...newMessages];
|
|
|
|
if (newMessages.length < 50) {
|
|
top = true;
|
|
return;
|
|
}
|
|
}}
|
|
/>
|
|
{/key}
|
|
</div>
|
|
</div>
|
|
|
|
<div class=" pb-3 px-3">
|
|
<MessageInput
|
|
id="root"
|
|
{messages}
|
|
bind:chatInputElement
|
|
bind:replyToMessage
|
|
{typingUsers}
|
|
{channel}
|
|
userSuggestions={true}
|
|
channelSuggestions={true}
|
|
disabled={!channel?.write_access}
|
|
placeholder={!channel?.write_access
|
|
? $i18n.t('You do not have permission to send messages in this channel.')
|
|
: $i18n.t('Type here...')}
|
|
{onChange}
|
|
onSubmit={submitHandler}
|
|
{scrollToBottom}
|
|
{scrollEnd}
|
|
/>
|
|
</div>
|
|
{:else}
|
|
<div class=" flex items-center justify-center h-full w-full">
|
|
<div class="m-auto">
|
|
<Spinner className="size-5" />
|
|
</div>
|
|
</div>
|
|
{/if}
|
|
</div>
|
|
|
|
{#if threadId !== null && contentWidth}
|
|
<ResizableSidePanel
|
|
open={true}
|
|
bind:width={threadPanelWidth}
|
|
minWidth={MIN_THREAD_WIDTH}
|
|
maxWidth={640}
|
|
minSiblingWidth={MIN_MESSAGES_WIDTH}
|
|
subtleDivider
|
|
fill={threadFills}
|
|
className={threadFills ? 'absolute inset-0 z-20' : 'h-full px-2 pt-1 pb-2'}
|
|
>
|
|
<div
|
|
class="h-full w-full {threadFills
|
|
? ''
|
|
: 'rounded-3xl border border-base-200/60 dark:border-base-800/50 shadow-[0_6px_24px_-4px_rgba(0,0,0,0.1)]'}"
|
|
>
|
|
<Thread
|
|
{threadId}
|
|
{channel}
|
|
bind:chatInputElement={threadChatInputElement}
|
|
onPin={pinHandler}
|
|
onClose={closeThread}
|
|
/>
|
|
</div>
|
|
</ResizableSidePanel>
|
|
{/if}
|
|
</div>
|
|
</div>
|
|
{/if}
|