From 90ef1f6b0d2f192bac3501f6cfc654243d9c2e9c Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Thu, 26 Nov 2026 00:59:00 +0400 Subject: [PATCH] refac --- src/lib/components/channel/Channel.svelte | 75 +++++++++-------- src/lib/components/channel/Messages.svelte | 13 +++ src/lib/components/channel/Thread.svelte | 5 +- .../components/chat/Messages/Message.svelte | 30 ++++++- src/lib/components/chat/Tabs/Desktop.svelte | 2 +- .../components/chat/Tabs/FrameCanvas.svelte | 83 +++++++++++++++++-- .../components/chat/Tabs/NativeDesktop.svelte | 1 + .../components/common/DateSeparator.svelte | 32 +++++++ src/lib/utils/index.ts | 11 +++ 9 files changed, 207 insertions(+), 45 deletions(-) create mode 100644 src/lib/components/common/DateSeparator.svelte diff --git a/src/lib/components/channel/Channel.svelte b/src/lib/components/channel/Channel.svelte index d4797c84f9..8680c0f3e9 100644 --- a/src/lib/components/channel/Channel.svelte +++ b/src/lib/components/channel/Channel.svelte @@ -466,41 +466,41 @@ : ''} w-full max-w-full min-w-0 flex flex-col" id="channel-container" > -
-
- { - channel = await getChannelById(localStorage.token, id).catch((error) => { - return null; - }); - }} - > - - {#if invitationSession} -
- {$i18n.t('Encrypted chat in progress')} - - -
- {/if} -
-
+ { + channel = await getChannelById(localStorage.token, id).catch((error) => { + return null; + }); + }} + > + + {#if invitationSession} +
+ {$i18n.t('Encrypted chat in progress')} + + +
+ {/if} +
+
+
+
{#if channel && messages !== null}
-
+
('i18n'); @@ -155,6 +157,16 @@ {/if} {#each messageList as message, messageIdx (id ? `${id}-${message.client_id ?? message.id}` : (message.client_id ?? message.id))} + {@const dateSeparator = + messageIdx === 0 + ? top + : needsDateSeparator( + message.created_at / 1000000, + messageList[messageIdx - 1].created_at / 1000000 + )} + {#if dateSeparator} + + {/if} receiveAppChannelReply({ ...event.detail, parent_id: thread ? id : null })} @@ -166,6 +178,7 @@ disabled={!channel?.write_access || message?.temp_id} pending={!!message?.temp_id} showUserProfile={messageIdx === 0 || + dateSeparator || Object.values(appReplies).some( (event) => event.message_id === messageList.at(messageIdx - 1)?.id ) || diff --git a/src/lib/components/channel/Thread.svelte b/src/lib/components/channel/Thread.svelte index b809b3c42d..3effd8b570 100644 --- a/src/lib/components/channel/Thread.svelte +++ b/src/lib/components/channel/Thread.svelte @@ -235,7 +235,10 @@ {#if channel} -
+
{$i18n.t('Thread')}
diff --git a/src/lib/components/chat/Messages/Message.svelte b/src/lib/components/chat/Messages/Message.svelte index d9a60d2cde..196c7d1949 100644 --- a/src/lib/components/chat/Messages/Message.svelte +++ b/src/lib/components/chat/Messages/Message.svelte @@ -6,8 +6,9 @@ const i18n = getContext('i18n'); import { settings } from '$lib/stores'; - import { copyToClipboard, isInternalMessage } from '$lib/utils'; + import { copyToClipboard, isInternalMessage, needsDateSeparator } from '$lib/utils'; + import DateSeparator from '$lib/components/common/DateSeparator.svelte'; import MultiResponseMessages from './MultiResponseMessages.svelte'; import ResponseMessage from './ResponseMessage.svelte'; import UserMessage from './UserMessage.svelte'; @@ -57,6 +58,29 @@ isInternalMessage(history.messages[messageId]) && history.messages[messageId].childrenIds?.length > 0; + // Compare against the parent in history, as older messages may not be rendered yet. + const showsDateSeparator = (history: any, messageId: string) => { + const message = history.messages[messageId]; + if (!message?.timestamp || isInternalMessage(message)) return false; + + const visited = new Set([messageId]); + let previous = history.messages[message.parentId]; + while (previous && (!previous.timestamp || isInternalMessage(previous))) { + if (visited.has(previous.id)) return false; + visited.add(previous.id); + previous = history.messages[previous.parentId]; + } + + if (!previous) return true; + return needsDateSeparator( + message.timestamp * 1000, + previous.timestamp * 1000, + (previous.meta?.response_ended_at ?? previous.timestamp) * 1000 + ); + }; + + $: dateSeparator = !compactPreview && showsDateSeparator(history, messageId); + // Keep the latest turn's real height when assigning a chat ID remounts the message list, and once // it is no longer the latest: virtualizing it on screen blanks it before it is drawn again. let wasCurrentTurn = false; @@ -86,6 +110,10 @@ class:message-virtualized={!isWebKit && !isFirefox && !wasCurrentTurn} > {#if history.messages[messageId]} + {#if dateSeparator} + + {/if} + {#if history.messages[messageId].role === 'user'} + import { onDestroy } from 'svelte'; let canvas: HTMLCanvasElement; + // Browsers only offer WebCodecs over HTTPS or localhost; the server sends JPEG otherwise. + let h264 = typeof VideoDecoder !== 'undefined'; + let decoder: VideoDecoder | null = null; + let decoded = (frame: VideoFrame | null) => frame?.close(); + export const supportsH264 = () => h264; + + const stopVideo = () => { + if (decoder && decoder.state !== 'closed') decoder.close(); + decoder = null; + }; + onDestroy(stopVideo); + + // Resolves with the frame, or null when this browser cannot decode the stream. + const decode = (packet: ArrayBuffer, configLength: number) => + new Promise((resolve) => { + const timeout = setTimeout(() => decoded(null), 3000); + decoded = (frame) => { + clearTimeout(timeout); + decoded = (late) => late?.close(); + resolve(frame); + }; + try { + if (configLength) { + stopVideo(); + const description = new Uint8Array(packet, 14, configLength); + const profile = Array.from(description.subarray(1, 4), (byte) => + byte.toString(16).padStart(2, '0') + ).join(''); + decoder = new VideoDecoder({ + output: (frame) => decoded(frame), + error: () => decoded(null) + }); + decoder.configure({ + codec: `avc1.${profile}`, + description, + optimizeForLatency: true + }); + } + if (!decoder) throw new Error('Video started without a configuration'); + decoder.decode( + new EncodedVideoChunk({ + type: configLength ? 'key' : 'delta', + timestamp: performance.now() * 1000, + data: new Uint8Array(packet, 14 + configLength) + }) + ); + } catch { + decoded(null); + } + }); + + const paint = (image: CanvasImageSource, width: number, height: number, x: number, y: number) => { + if (!canvas) return; + if (canvas.width !== width || canvas.height !== height) { + canvas.width = width; + canvas.height = height; + } + canvas.getContext('2d', { alpha: false })?.drawImage(image, x, y); + }; export const draw = async (packet: ArrayBuffer) => { if (packet.byteLength < 13) throw new Error('Invalid screen update'); const header = new DataView(packet); @@ -8,16 +68,27 @@ ); if (!width || !height || width > 8192 || height > 8192 || x + w > width || y + h > height) throw new Error('Invalid screen dimensions'); + if (!w && !h) { + if (!h264) return; + const frame = await decode(packet, header.getUint16(12)); + if (!frame) { + // The next acknowledgment asks the server for JPEG and a full picture. + h264 = false; + stopVideo(); + return; + } + try { + paint(frame, width, height, 0, 0); + } finally { + frame.close(); + } + return; + } const image = await createImageBitmap( new Blob([new Uint8Array(packet, 12)], { type: 'image/jpeg' }) ); try { - if (!canvas) return; - if (canvas.width !== width || canvas.height !== height) { - canvas.width = width; - canvas.height = height; - } - canvas.getContext('2d', { alpha: false })?.drawImage(image, x, y, w, h); + paint(image, width, height, x, y); } finally { image.close(); } diff --git a/src/lib/components/chat/Tabs/NativeDesktop.svelte b/src/lib/components/chat/Tabs/NativeDesktop.svelte index 8102449df0..718d8f3a56 100644 --- a/src/lib/components/chat/Tabs/NativeDesktop.svelte +++ b/src/lib/components/chat/Tabs/NativeDesktop.svelte @@ -7,6 +7,7 @@ let pending: Record | null = null; let frame = 0; export const draw = (packet: ArrayBuffer) => frames.draw(packet); + export const supportsH264 = () => frames.supportsH264(); const flush = () => { cancelAnimationFrame(frame); if (pending) send(pending); diff --git a/src/lib/components/common/DateSeparator.svelte b/src/lib/components/common/DateSeparator.svelte new file mode 100644 index 0000000000..c31917ed42 --- /dev/null +++ b/src/lib/components/common/DateSeparator.svelte @@ -0,0 +1,32 @@ + + +
+ + + +
diff --git a/src/lib/utils/index.ts b/src/lib/utils/index.ts index 39d80b8fd0..fab228187c 100644 --- a/src/lib/utils/index.ts +++ b/src/lib/utils/index.ts @@ -557,6 +557,17 @@ export const formatDate = (inputDate) => { } }; +// Whether a message needs a date line above it: the first one, a new day, or an hour after +// the previous message finished. All times are in milliseconds. +export const needsDateSeparator = ( + sentAt: number, + previousSentAt?: number | null, + previousEndedAt = previousSentAt +) => + !previousSentAt || + !dayjs(sentAt).isSame(previousSentAt, 'day') || + sentAt - (previousEndedAt ?? previousSentAt) > 60 * 60 * 1000; + const messageTimestampDate = (inputDate) => { const date = new Date(inputDate < 1_000_000_000_000 ? inputDate * 1000 : inputDate); return Number.isNaN(date.getTime()) ? null : date;