Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

Messages.svelte

99 lines3.3 KB

1<script lang="ts">
2 import { onMount, tick } from 'svelte'
3 import { marked } from 'marked'
4 import { markedHighlight } from 'marked-highlight'
5 import hljs from 'highlight.js'
6 import type { UIMessage } from '@tanstack/ai-svelte'
7 import GuitarRecommendation from './GuitarRecommendation.svelte'
8 import ThinkingPart from './ThinkingPart.svelte'
9​
10 interface Props {
11 messages: ReadonlyArray<UIMessage>
12 }
13​
14 let { messages }: Props = $props()
15​
16 let messagesContainer: HTMLDivElement | undefined = $state()
17​
18 // Configure marked with syntax highlighting
19 marked.use(
20 markedHighlight({
21 langPrefix: 'hljs language-',
22 highlight(code, lang) {
23 const language = hljs.getLanguage(lang) ? lang : 'plaintext'
24 return hljs.highlight(code, { language }).value
25 },
26 }),
27 )
28​
29 // Auto-scroll when messages change
30 $effect(() => {
31 if (messagesContainer && messages.length > 0) {
32 tick().then(() => {
33 if (messagesContainer) {
34 messagesContainer.scrollTop = messagesContainer.scrollHeight
35 }
36 })
37 }
38 })
39​
40 function renderMarkdown(content: string): string {
41 return marked.parse(content, { async: false }) as string
42 }
43</script>
44​
45{#if messages.length > 0}
46 <div bind:this={messagesContainer} class="flex-1 overflow-y-auto px-4 py-4">
47 {#each messages as message (message.id)}
48 <div
49 class={`p-4 rounded-lg mb-2 ${
50 message.role === 'assistant'
51 ? 'bg-linear-to-r from-orange-500/5 to-red-600/5'
52 : 'bg-transparent'
53 }`}
54 >
55 <div class="flex items-start gap-4">
56 {#if message.role === 'assistant'}
57 <div
58 class="w-8 h-8 rounded-lg bg-linear-to-r from-orange-500 to-red-600 flex items-center justify-center text-sm font-medium text-white shrink-0"
59 >
60 AI
61 </div>
62 {:else}
63 <div
64 class="w-8 h-8 rounded-lg bg-gray-700 flex items-center justify-center text-sm font-medium text-white shrink-0"
65 >
66 U
67 </div>
68 {/if}
69 <div class="flex-1 min-w-0">
70 <!-- Render parts in order -->
71 {#each message.parts as part, index}
72 {#if part.type === 'thinking'}
73 <!-- Check if thinking is complete (if there's a text part after) -->
74 {@const isComplete = message.parts
75 .slice(index + 1)
76 .some((p) => p.type === 'text')}
77 <div class="mt-2 mb-2">
78 <ThinkingPart
79 content={part.content}
80 {isComplete}
81 class="p-4 bg-gray-800/50 border border-gray-700/50 rounded-lg"
82 />
83 </div>
84 {:else if part.type === 'text' && part.content}
85 <div class="text-white prose dark:prose-invert max-w-none">
86 {@html renderMarkdown(part.content)}
87 </div>
88 {:else if part.type === 'tool-call' && part.name === 'recommendGuitar' && part.output}
89 <div class="mt-2">
90 <GuitarRecommendation id={part.output?.id} />
91 </div>
92 {/if}
93 {/each}
94 </div>
95 </div>
96 </div>
97 {/each}
98 </div>
99{/if}