Skip to content
Draft
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
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import { MessageType } from '#lib/enums/index.ts';
import { chatStore } from '#lib/stores/index.ts';
import type { ChatMessageActions } from '#lib/types/index.ts';
import { MESSAGE_ROW_ATTRIBUTE } from '#lib/utils/index.ts';

interface Props {
chatActions: ChatMessageActions;
Expand Down Expand Up @@ -78,6 +79,7 @@

<div
bind:this={wrapperEl}
{...{ [MESSAGE_ROW_ATTRIBUTE]: message.id }}
class={[
'chat-message',
eager && 'chat-message--eager',
Expand Down Expand Up @@ -108,6 +110,14 @@
--chat-message-intrinsic-size: 500px;
content-visibility: auto;
contain-intrinsic-size: auto var(--chat-message-intrinsic-size);
/* a jump to the row lands it below the tabs, or on a phone below the corner controls */
scroll-margin-top: calc(var(--chat-tabs-offset, 0px) + 1rem);
}

@media (width < 48rem) {
.chat-message {
scroll-margin-top: var(--page-top);
}
}

/*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
uiStore
} from '#lib/stores/index.ts';
import { parseFilesToMessageExtras } from '#lib/utils/browser-only.ts';
import { findMessageRowId, messageRow, scrollToMessageRow } from '#lib/utils/index.ts';
import { disableScrollHandling, onNavigate } from '$app/navigation';
import { page } from '$app/state';
import { tick, untrack } from 'svelte';
Expand Down Expand Up @@ -181,10 +182,57 @@
if (!id || id === lastScrolledConversationId) return;

lastScrolledConversationId = id;

// taken by the first conversation that opens: one meant for another conversation
// (deleted since, say) is dropped, not kept for a later one
const target = chatStore.scrollTarget;

chatStore.scrollTarget = null;

if (target && target.convId === id) {
await landOnMessage(id, target.messageId);

return;
}

await tick();
stick.scrollToBottom();
}

/**
* Lands on one message in place of the bottom, e.g. the one that holds a file picked in
* the Library. A message of another branch switches the conversation to that branch
* first. A message that is gone lands at the bottom after all.
*/
async function landOnMessage(convId: string, messageId: string) {
if (!conversationsStore.activeMessages.some((message) => message.id === messageId)) {
const all = await conversationsStore.getConversationMessages(convId);

// only a message the conversation still holds names a branch to switch to
if (all.some((message) => message.id === messageId)) {
await conversationsStore.navigateToSibling(messageId);
}
}

await tick();

const rowId = findMessageRowId(
conversationsStore.activeMessages,
messageId,
(id) => messageRow(id) !== null
);
const row = rowId ? messageRow(rowId) : null;

if (!row) {
stick.scrollToBottom();

return;
}

stick.release();
scrollToMessageRow(row);
}

/**
* Moves the form between its centered and bottom positions: it fades out
* where it is, drifting toward where it goes, and fades
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
<script lang="ts">
import { ClipboardCopy, Download, MessageSquareShare, MoreHorizontal } from '@lucide/svelte';
import { ContextMenuActions, DropdownMenuActions } from '#lib/components/app/index.ts';
import {
DEFAULT_FILE_ICON,
LIBRARY_ATTACHMENT_ICONS,
LIBRARY_TEXT_PREVIEW_CHARS
} from '#lib/constants/index.ts';
import type { MenuAction } from '#lib/types/index.ts';
import {
attachmentImage,
attachmentText,
copyToClipboard,
downloadAttachment,
type LibraryAttachment
} from '#lib/utils/index.ts';

interface Props {
item: LibraryAttachment;
/** The name of the conversation the file was sent in, when it is known. */
conversationName?: string;
/** Open that conversation at the message that holds the file. */
onGoToConversation: (item: LibraryAttachment) => void;
/** Open the file in the preview. */
onOpen: (item: LibraryAttachment) => void;
}

let { conversationName, item, onGoToConversation, onOpen }: Props = $props();

let contextMenuOpen = $state(false);

const image = $derived(attachmentImage(item.attachment));
const text = $derived(attachmentText(item.attachment));
const Icon = $derived(LIBRARY_ATTACHMENT_ICONS[item.attachment.type] ?? DEFAULT_FILE_ICON);

// the "more actions" dropdown and the right-click menu offer the same actions
const actions = $derived<MenuAction[]>([
{
icon: MessageSquareShare,
label: 'Go to conversation',
onclick: () => onGoToConversation(item)
},
{ icon: Download, label: 'Download', onclick: () => downloadAttachment(item.attachment) },
...(text === undefined
? []
: [
{
icon: ClipboardCopy,
label: 'Copy text',
onclick: () => void copyToClipboard(text, 'Copied to clipboard')
}
])
]);
</script>

<ContextMenuActions bind:open={contextMenuOpen} {actions}>
<figure class="group relative flex flex-col gap-1.5">
<button
aria-label="Open {item.attachment.name}"
class="block w-full cursor-pointer overflow-hidden rounded-xl border border-border/40 bg-muted/40 text-left transition-colors hover:bg-muted focus-visible:ring-3 focus-visible:ring-ring/50 focus-visible:outline-none {contextMenuOpen
? 'bg-muted'
: ''}"
onclick={() => onOpen(item)}
type="button"
>
{#if image}
<img alt="" class="block w-full" decoding="async" loading="lazy" src={image} />
{:else if text}
<!-- the file's own first lines: a text is known by how it starts -->
<p
class="max-h-48 overflow-hidden p-3 font-mono text-caption-sm break-words whitespace-pre-wrap text-muted-foreground"
>
{text.slice(0, LIBRARY_TEXT_PREVIEW_CHARS)}
</p>
{:else}
<span class="flex aspect-4/3 items-center justify-center text-muted-foreground">
<Icon class="size-8 opacity-60" />
</span>
{/if}
</button>

<div
class="absolute top-2 right-2 rounded-md bg-background/80 opacity-0 backdrop-blur transition-opacity group-focus-within:opacity-100 group-hover:opacity-100 max-md:opacity-100"
>
<DropdownMenuActions
{actions}
triggerIcon={MoreHorizontal}
triggerTooltip="Attachment actions"
/>
</div>

<figcaption class="flex min-w-0 flex-col px-0.5">
<span class="truncate text-caption">{item.attachment.name}</span>

{#if conversationName}
<span class="truncate text-caption text-muted-foreground">{conversationName}</span>
{/if}
</figcaption>
</figure>
</ContextMenuActions>
169 changes: 169 additions & 0 deletions ui/apps/chat/src/lib/components/app/library/LibraryAttachments.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
<script lang="ts">
import LibraryAttachmentTile from './LibraryAttachmentTile.svelte';
import * as Empty from '@ggml-org/llama-ui/ui/empty';
import { Skeleton } from '@ggml-org/llama-ui/ui/skeleton';
import { Paperclip, SearchX } from '@lucide/svelte';
import { DialogChatAttachmentsPreview } from '#lib/components/app/index.ts';
import {
LIBRARY_ATTACHMENTS_COLUMN_MIN_WIDTH_PX,
LIBRARY_ATTACHMENTS_MIN_COLUMNS,
LIBRARY_ATTACHMENTS_SEARCH_DEBOUNCE_MS,
LIBRARY_LOAD_MORE_MARGIN
} from '#lib/constants/index.ts';
import { RouterService } from '#lib/services/router.service.ts';
import { chatStore, conversationsStore, libraryAttachmentsStore } from '#lib/stores/index.ts';
import { debounce, type LibraryAttachment } from '#lib/utils/index.ts';
import { goto } from '$app/navigation';
import { onDestroy, untrack } from 'svelte';

interface Props {
query?: string;
}

let { query = '' }: Props = $props();

/** Placeholder tiles while the first page is read, of unlike heights as files are. */
const SKELETON_HEIGHT_CLASSES = ['h-40', 'h-56', 'h-32', 'h-48'];

let gridWidth = $state(0);
let sentinel: HTMLDivElement | undefined = $state();
let previewOpen = $state(false);
let previewIndex = $state(0);

const items = $derived(libraryAttachmentsStore.items);
const columnCount = $derived(
Math.max(
LIBRARY_ATTACHMENTS_MIN_COLUMNS,
Math.floor(gridWidth / LIBRARY_ATTACHMENTS_COLUMN_MIN_WIDTH_PX)
)
);
// Dealt out in turn, so the newest files stay across the top and a page that loads later
// lands under the files already shown without moving them
const columns = $derived(
Array.from({ length: columnCount }, (_, column) =>
items.filter((_, index) => index % columnCount === column)
)
);
const conversationNames = $derived(
new Map(
conversationsStore.conversations.map((conversation) => [conversation.id, conversation.name])
)
);
// the preview lists a message's newest file first, so it gets the files in reverse to
// show them in the grid's order
const previewAttachments = $derived(items.map((item) => item.attachment).reverse());

const search = debounce(
(text: string) => void libraryAttachmentsStore.search(text),
LIBRARY_ATTACHMENTS_SEARCH_DEBOUNCE_MS
);

// showing the tab is the need for the files: the first page loads at once, a search once typing rests
let isFirstLoad = true;

$effect(() => {
const text = query;

untrack(() => {
if (isFirstLoad) void libraryAttachmentsStore.search(text);
else search(text);

isFirstLoad = false;
});
});

// the next page loads as the end of the grid comes near
$effect(() => {
if (!sentinel) return;

const observer = new IntersectionObserver(
(entries) => {
if (entries.some((entry) => entry.isIntersecting)) void libraryAttachmentsStore.loadMore();
},
{ rootMargin: LIBRARY_LOAD_MORE_MARGIN }
);

observer.observe(sentinel);

return () => observer.disconnect();
});

onDestroy(() => libraryAttachmentsStore.clear());

function open(item: LibraryAttachment) {
previewIndex = items.indexOf(item);
previewOpen = true;
}

/** Opens the file's conversation at the message that holds it. */
async function goToConversation(item: LibraryAttachment) {
chatStore.scrollTarget = { convId: item.convId, messageId: item.messageId };

await goto(RouterService.chat(item.convId));
}
</script>

<div bind:clientWidth={gridWidth}>
{#if items.length === 0 && libraryAttachmentsStore.isLoading}
<div class="flex gap-4">
{#each { length: columnCount } as _, column (column)}
<div class="flex min-w-0 flex-1 flex-col gap-4">
{#each SKELETON_HEIGHT_CLASSES as _, row (row)}
<Skeleton
class="{SKELETON_HEIGHT_CLASSES[
(row + column) % SKELETON_HEIGHT_CLASSES.length
]} rounded-xl"
/>
{/each}
</div>
{/each}
</div>
{:else if items.length === 0}
<Empty.Root class="border py-16">
<Empty.Header>
<Empty.Media variant="icon">
{#if query.trim()}
<SearchX />
{:else}
<Paperclip />
{/if}
</Empty.Media>

<Empty.Title>{query.trim() ? 'No attachments match' : 'No attachments yet'}</Empty.Title>

<Empty.Description>
{query.trim()
? 'Try another search.'
: 'The files you send in your chats show here: images, audio, video, PDFs and text.'}
</Empty.Description>
</Empty.Header>
</Empty.Root>
{:else}
<div class="flex items-start gap-4">
{#each columns as column, index (index)}
<ul class="flex min-w-0 flex-1 flex-col gap-4">
{#each column as item (item.id)}
<li>
<LibraryAttachmentTile
conversationName={conversationNames.get(item.convId)}
{item}
onGoToConversation={(target) => void goToConversation(target)}
onOpen={open}
/>
</li>
{/each}
</ul>
{/each}
</div>
{/if}

{#if libraryAttachmentsStore.hasMore}
<div bind:this={sentinel} aria-hidden="true" class="h-px"></div>
{/if}
</div>

<DialogChatAttachmentsPreview
bind:open={previewOpen}
attachments={previewAttachments}
previewFocusIndex={previewIndex}
/>
7 changes: 5 additions & 2 deletions ui/apps/chat/src/lib/components/app/library/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
/**
* LIBRARY
*
* The Library page: the prompts kept in the app, as cards that are sent in a
* chat or used as its system message.
* The Library page, in tabs: the prompts kept in the app, as cards that are sent
* in a chat or used as its system message, and the files of every conversation
* in a grid, each leading back to the message it was sent in.
*/

export { default as LibraryAttachments } from './LibraryAttachments.svelte';
export { default as LibraryAttachmentTile } from './LibraryAttachmentTile.svelte';
export { default as LibraryPromptCard } from './LibraryPromptCard.svelte';
export { default as LibraryPrompts } from './LibraryPrompts.svelte';
Loading
Loading